All files / building third-party-licenses.cjs

99.56% Statements 228/229
95.03% Branches 134/141
100% Functions 37/37
100% Lines 192/192

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385                                          18x 18x 18x 18x   18x     18x           18x   18x   48x                   26x 26x 26x 26x 13x 13x 13x 11x   13x 13x 13x 11x                 41x 37x 37x 37x 43x 41x 8x 8x 7x   40x   37x 51x 48x 5x 5x 5x   48x   37x 56x 56x 6x 6x 4x   50x 49x 49x   37x 37x 34x   3x                   22x 20x 8x 6x 6x   3x                 12x 12x                     19x 23x 19x 8x 8x                       18x 18x 18x 18x 40x   10x 18x 18x   5x 5x   18x 7x 7x   6x 6x       18x 18x 10x 10x   18x 18x                     18x 18x 18x 18x         18x 18x 14x 14x   18x 2x 2x 4x 4x 19x 19x 19x 19x 5x 4x 4x   19x       18x 7x 7x 9x     18x 3x   18x     18x               8x               16x       6x 6x     6x 4x     4x 4x 4x 1x   1x                 6x 6x 3x 3x   6x 6x   6x 3x 2x 2x     2x 2x 5x 4x 4x   2x                 13x 13x 21x 4x 2x   19x     19x   13x 19x   13x       12x 12x 12x 12x 12x 12x 12x 6x 6x 6x   6x 18x 6x 16x 6x     12x 12x 12x 5x 1x 1x   4x 4x 4x     12x 5x 5x   12x 12x   36x       12x       18x 18x 18x 18x 18x 18x 18x 18x 18x 18x  
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
// @ts-check
// Webpack-плагин: файл лицензий сторонних пакетов, вошедших в бандл фронта (ERA-3561).
// Файл пишется вне dist (по HTTP не раздаётся) и не является ассетом webpack.
// webpack не подключается через require: API берётся из compiler.webpack
// (tests/building/vue-config.test.js мокает модуль webpack целиком).
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { IN_TREE_VENDORED, LICENSE_TEXTS, PACKAGE_OVERRIDES } = require('./third-party-licenses.static.cjs');
 
const PLUGIN_NAME = 'ThirdPartyLicensesPlugin';
 
// Лицензии, которые не требуют решения ИТ-лида (остальные дают предупреждение сборки)
const ALLOWED_LICENSES = new Set([
    'MIT', 'ISC', 'BSD-2-Clause', 'BSD-3-Clause', 'Apache-2.0', '0BSD', 'CC0-1.0', 'Unlicense',
    'Python-2.0', 'BlueOak-1.0.0', 'MIT-0', 'Zlib', 'OFL-1.1'
]);
 
// Плагины под MIT (LICENSE в каталоге плагина, см. NOTICE)
const MIT_PLUGINS = ['plugins/html/', 'plugins/svg/', 'plugins/drawio/', 'plugins/devtool/'];
 
const LICENSE_FILE = /^(licen[cs]e|copying|notice|thirdpartynotices)([.\-_].*)?$/i;
 
const toPosix = (value) => value.split(path.sep).join('/');
 
/**
 * Корень пакета для файла модуля: node_modules (с учётом @scope и вложенных node_modules) или libs/<имя>.
 * Свой код (src, plugins вне node_modules, smartants.cjs) — null.
 * @param {string} resource абсолютный путь файла модуля
 * @param {string} rootDir корень репозитория
 * @returns {string | null}
 */
function packageRootOf(resource, rootDir) {
    const file = toPosix(resource.split('?')[0]);
    const marker = '/node_modules/';
    const index = file.lastIndexOf(marker);
    if (index >= 0) {
        const segments = file.slice(index + marker.length).split('/');
        const depth = segments[0].startsWith('@') ? 2 : 1;
        if (segments.length <= depth) return null;
        return file.slice(0, index + marker.length) + segments.slice(0, depth).join('/');
    }
    const relative = toPosix(path.relative(rootDir, file));
    const libs = /^libs\/([^/]+)\//.exec(relative);
    if (libs) return toPosix(path.join(rootDir, 'libs', libs[1]));
    return null;
}
 
/**
 * Разбор SPDX-выражения: OR — достаточно одной разрешённой части, AND — нужны все, скобки учитываются.
 * @param {string | undefined} expression
 * @returns {boolean}
 */
function isAllowed(expression) {
    if (!expression || typeof expression !== 'string') return false;
    const tokens = expression.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').trim().split(/\s+/);
    let position = 0;
    const parseOr = () => {
        let value = parseAnd();
        while (tokens[position] === 'OR') {
            position++;
            const right = parseAnd();
            value = value || right;
        }
        return value;
    };
    const parseAnd = () => {
        let value = parseAtom();
        while (tokens[position] === 'AND') {
            position++;
            const right = parseAtom();
            value = value && right;
        }
        return value;
    };
    const parseAtom = () => {
        const token = tokens[position++];
        if (token === '(') {
            const value = parseOr();
            if (tokens[position++] !== ')') throw new Error('unbalanced');
            return value;
        }
        if (!token || token === ')') throw new Error('unexpected end');
        if (tokens[position] === 'WITH') position += 2;
        return ALLOWED_LICENSES.has(token.replace(/\+$/, ''));
    };
    try {
        const value = parseOr();
        return position === tokens.length && value;
    } catch {
        return false;
    }
}
 
/**
 * Лицензия из package.json: строка, {type} или устаревший licenses[].
 * @param {any} pkg
 * @returns {string}
 */
function licenseOf(pkg) {
    const one = (value) => (typeof value === 'string' ? value : value && typeof value.type === 'string' ? value.type : '');
    if (pkg.license) return one(pkg.license) || 'UNKNOWN';
    if (Array.isArray(pkg.licenses) && pkg.licenses.length) {
        const list = pkg.licenses.map(one).filter(Boolean);
        if (list.length) return list.length > 1 ? `(${list.join(' OR ')})` : list[0];
    }
    return 'UNKNOWN';
}
 
/**
 * Имя автора без email и URL.
 * @param {any} author
 * @returns {string}
 */
function authorName(author) {
    const raw = typeof author === 'string' ? author : author && typeof author.name === 'string' ? author.name : '';
    return raw.replace(/<[^>]*>/g, '').replace(/\([^)]*\)/g, '').trim();
}
 
/**
 * Стандартный текст лицензии для пакета без файла лицензии (MIT, ISC, 0BSD).
 * @param {string} license
 * @param {string} copyrightHolder
 * @returns {string | null}
 */
function standardLicenseText(license, copyrightHolder) {
    // Для выражения из одних OR берётся первая лицензия, у которой есть стандартный текст
    const parts = /\sAND\s/.test(license) ? [license] : license.replace(/[()]/g, '').split(/\s+OR\s+/);
    const spdx = parts.map((part) => part.trim()).find((part) => LICENSE_TEXTS[part]);
    if (!spdx) return null;
    const copyright = copyrightHolder ? `Copyright (c) ${copyrightHolder}\n\n` : '';
    return `(standard ${spdx} text; the package contains no license file)\n\n${copyright}${LICENSE_TEXTS[spdx]}`;
}
 
/**
 * Сведения о пакете из его корня.
 * @param {string} root
 * @param {Iterable<string>} files файлы модулей пакета, попавшие в бандл
 * @param {Record<string, { license: string, note: string, text?: string, copyrightHolder?: string }>} [overrides]
 *   решения по пакетам (name@version), по умолчанию — PACKAGE_OVERRIDES
 * @returns {{ name: string, version: string, license: string, texts: string[], missingText: boolean }}
 */
function readPackage(root, files, overrides = PACKAGE_OVERRIDES) {
    const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
    const override = overrides[`${pkg.name}@${pkg.version}`];
    const license = override ? override.license : licenseOf(pkg);
    const texts = fs.readdirSync(root)
        .filter((name) => LICENSE_FILE.test(name) && fs.statSync(path.join(root, name)).isFile())
        .sort()
        .map((name) => fs.readFileSync(path.join(root, name), 'utf8').trim());
    let missingText = false;
    if (!texts.length && override) {
        // Решение ИТ-лида: текст из upstream или стандартный текст с указанным правообладателем
        const text = override.text || standardLicenseText(license, override.copyrightHolder || '');
        if (text) texts.push(`(${override.note})\n\n${text.trim()}`);
    }
    if (!texts.length) {
        const standard = standardLicenseText(license, authorName(pkg.author));
        if (standard) texts.push(standard);
        else {
            texts.push('License text is not included in the package.');
            missingText = true;
        }
    }
    // Уведомления, которые webpack/terser вынес из бандла пакета в <файл>.LICENSE.txt
    const sidecars = new Set();
    for (const file of files) {
        const sidecar = `${file}.LICENSE.txt`;
        if (fs.existsSync(sidecar)) sidecars.add(sidecar);
    }
    for (const sidecar of [...sidecars].sort()) texts.push(fs.readFileSync(sidecar, 'utf8').trim());
    return { name: pkg.name || path.basename(root), version: pkg.version || '', license, texts, missingText };
}
 
/**
 * Текст файла лицензий. Детерминированный: без дат и абсолютных путей, пакеты отсортированы.
 * @param {{ packages: Array<{ name: string, version: string, license: string, texts: string[] }>,
 *   inTree: Array<{ title: string, components: Array<{ name: string, version: string, license: string, copyright: string[] }> }>,
 *   mitPlugins: Array<{ path: string, text: string }>, apacheText: string }} data
 * @returns {string}
 */
function renderLicenses({ packages, inTree, mitPlugins, apacheText }) {
    const unique = new Map();
    for (const item of packages) unique.set(`${item.name}@${item.version}`, item);
    const sorted = [...unique.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
    const out = [
        'Third-party software included in the SEAF.ArchTool frontend bundle.',
        'Generated at build time. See also LICENSE and NOTICE.',
        ''
    ];
    let needsApache = false;
    for (const [id, item] of sorted) {
        out.push(`==== ${id} ====`, `License: ${item.license}`, '', ...item.texts.flatMap((text) => [text, '']));
        if (/Apache-2\.0/.test(item.license)) needsApache = true;
    }
    if (inTree.length) {
        out.push('==== Third-party code included in the repository ====', '');
        for (const entry of inTree) {
            out.push(`---- ${entry.title} ----`, '');
            for (const component of entry.components) {
                const id = component.version ? `${component.name}@${component.version}` : component.name;
                out.push(`${id}`, `License: ${component.license}`, ...component.copyright);
                const text = LICENSE_TEXTS[component.license];
                if (text) out.push('', text);
                else if (component.license === 'Apache-2.0') {
                    needsApache = true;
                    out.push('(Apache License 2.0 text: see the end of this file)');
                }
                out.push('');
            }
        }
    }
    if (mitPlugins.length) {
        out.push('==== MIT plugins ====', '');
        for (const plugin of [...mitPlugins].sort((a, b) => (a.path < b.path ? -1 : 1))) {
            out.push(`---- ${plugin.path} ----`, '', plugin.text.trim(), '');
        }
    }
    if (needsApache && apacheText) {
        out.push('==== Apache License 2.0 text ====', '', apacheText.trim(), '');
    }
    return out.join('\n');
}
 
const sha256 = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex');
 
/**
 * Файл штампа сборки рядом с файлом лицензий: third-party-licenses.txt → third-party-licenses.build.json
 * @param {string} outputFile
 * @returns {string}
 */
function buildStampFile(outputFile) {
    return outputFile.replace(/(\.txt)?$/, '.build.json');
}
 
class ThirdPartyLicensesPlugin {
    /**
     * @param {{ rootDir: string, outputFile: string }} options
     */
    constructor(options) {
        this.options = options;
    }
 
    apply(compiler) {
        const { Compilation, WebpackError } = compiler.webpack;
        let content = null;
 
        // thisCompilation — без дочерних компиляций (html-webpack-plugin, воркеры)
        compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
            compilation.hooks.processAssets.tap(
                { name: PLUGIN_NAME, stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL },
                () => {
                    const { text, warnings } = this.collect(compilation);
                    content = text;
                    if (warnings.length) {
                        compilation.warnings.push(new WebpackError(
                            `${PLUGIN_NAME}: лицензии требуют проверки (нет текста или не из разрешённого списка):\n`
                            + warnings.map((line) => `  - ${line}`).join('\n')
                        ));
                    }
                }
            );
        });
 
        // Файл прошлой сборки удаляется до начала новой: если сборка упадёт, устаревший файл не
        // попадёт в образ или пакет. Сборку без плагина (не production) ловит plugin-publish.mjs по штампу
        const stampFile = buildStampFile(this.options.outputFile);
        const removeStale = () => {
            fs.rmSync(this.options.outputFile, { force: true });
            fs.rmSync(stampFile, { force: true });
        };
        compiler.hooks.beforeRun.tap(PLUGIN_NAME, removeStale);
        compiler.hooks.watchRun.tap(PLUGIN_NAME, removeStale);
 
        compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation) => {
            if (content === null) return;
            fs.mkdirSync(path.dirname(this.options.outputFile), { recursive: true });
            fs.writeFileSync(this.options.outputFile, content, 'utf8');
            // Штамп сборки: sha256 выданных html (plugin.html, index.html). plugin-publish.mjs сверяет
            // его с dist, чтобы не опубликовать файл лицензий от другой сборки; от mtime не зависит
            const html = {};
            const outputPath = compilation.outputOptions.path;
            for (const name of compilation.getAssets().map((asset) => asset.name).filter((n) => n.endsWith('.html')).sort()) {
                const file = path.join(outputPath, name);
                if (fs.existsSync(file)) html[name] = sha256(fs.readFileSync(file));
            }
            fs.writeFileSync(stampFile, `${JSON.stringify({ html }, null, 2)}\n`, 'utf8');
        });
    }
 
    /**
     * Файлы модулей, попавших в чанки (с раскрытием ConcatenatedModule). У CSS, извлечённого
     * mini-css-extract-plugin, в чанках лежит CssModule без resource: файл берётся из nameForCondition().
     */
    resources(compilation) {
        const result = new Set();
        const add = (module) => {
            if (module.modules) {
                for (const inner of module.modules) add(inner);
                return;
            }
            const resource = typeof module.resource === 'string'
                ? module.resource
                : typeof module.nameForCondition === 'function' ? module.nameForCondition() : null;
            if (typeof resource === 'string' && path.isAbsolute(resource)) result.add(resource.split('?')[0]);
        };
        for (const module of compilation.modules) {
            if (compilation.chunkGraph.getNumberOfModuleChunks(module) > 0) add(module);
        }
        return result;
    }
 
    collect(compilation) {
        const { rootDir } = this.options;
        const packageFiles = new Map();
        const inTree = new Set();
        const mitPlugins = new Set();
        for (const resource of this.resources(compilation)) {
            const root = packageRootOf(resource, rootDir);
            if (root) {
                if (!packageFiles.has(root)) packageFiles.set(root, new Set());
                packageFiles.get(root).add(resource);
                continue;
            }
            const relative = toPosix(path.relative(rootDir, resource));
            const vendored = IN_TREE_VENDORED.find((entry) => relative.startsWith(entry.path));
            Iif (vendored) inTree.add(vendored);
            const plugin = MIT_PLUGINS.find((prefix) => relative.startsWith(prefix));
            if (plugin) mitPlugins.add(plugin);
        }
 
        const warnings = [];
        const packages = [];
        for (const [root, files] of packageFiles) {
            if (!fs.existsSync(path.join(root, 'package.json'))) {
                warnings.push(`${toPosix(path.relative(rootDir, root))}: нет package.json, лицензия не определена`);
                continue;
            }
            const item = readPackage(root, files);
            packages.push(item);
            if (item.missingText || !isAllowed(item.license)) warnings.push(`${item.name}@${item.version}: ${item.license}`);
        }
 
        const pluginTexts = [...mitPlugins].map((prefix) => {
            const file = path.join(rootDir, prefix, 'LICENSE');
            return { path: prefix.replace(/\/$/, ''), text: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : 'MIT' };
        });
        const apacheFile = path.join(rootDir, 'LICENSE');
        const text = renderLicenses({
            packages,
            inTree: IN_TREE_VENDORED.filter((entry) => inTree.has(entry)),
            mitPlugins: pluginTexts,
            apacheText: fs.existsSync(apacheFile) ? fs.readFileSync(apacheFile, 'utf8') : ''
        });
        return { text, warnings: [...new Set(warnings)].sort() };
    }
}
 
module.exports = ThirdPartyLicensesPlugin;
module.exports.ThirdPartyLicensesPlugin = ThirdPartyLicensesPlugin;
module.exports.packageRootOf = packageRootOf;
module.exports.isAllowed = isAllowed;
module.exports.licenseOf = licenseOf;
module.exports.authorName = authorName;
module.exports.standardLicenseText = standardLicenseText;
module.exports.readPackage = readPackage;
module.exports.renderLicenses = renderLicenses;
module.exports.buildStampFile = buildStampFile;