import assert from 'node:assert/strict';
import { readFile, readdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
const accepted = new Set(['MIT', 'ISC', 'BSD-2-Clause', 'BSD-3-Clause', 'Apache-2.0', '(MIT AND Zlib)', '(MPL-2.0 OR Apache-2.0)', '(MIT OR CC0-1.0)', 'CC0-1.0', '0BSD', 'Unlicense', 'BlueOak-1.0.0']);
export async function notices(root) {
const lock = JSON.parse(await readFile(join(root, 'package-lock.json'), 'utf8'));
const records = []; let text = '蓝色精英图片工具 · 第三方软件许可\n依赖版本与来源见 package-lock.json。以下保留安装包随附的许可文本;包含构建和验收依赖。\n';
for (const [path, record] of Object.entries(lock.packages).sort()) {
if (!path) continue;
assert(accepted.has(record.license) || (path === 'node_modules/clipper-lib' && record.license === 'BSL') || (record.dev && ['MPL-2.0', '(Unlicense OR Apache-2.0)'].includes(record.license)), `License review required: ${path}: ${record.license}`);
let files;
try { files = await readdir(join(root, path)); } catch { if (record.optional) continue; throw new Error(`Missing ${path}`); }
let licenseRoot = join(root, path);
let licenses = files.filter((file) => /^(licen[sc]e|copying|notice|third-party-license|mit-license)(\.|$|-)/i.test(file));
if (['node_modules/clipper-lib', 'node_modules/boolbase'].includes(path)) { licenseRoot = join(root, 'licenses'); licenses = [path.slice('node_modules/'.length) + '.txt']; }
if (!licenses.length && path.startsWith('node_modules/@rolldown/binding-')) {
licenseRoot = join(root, 'node_modules/rolldown'); licenses = ['LICENSE', 'THIRD-PARTY-LICENSE'];
}
assert(licenses.length, `Missing license text: ${path}`);
records.push({ name: path.split('node_modules/').at(-1), version: record.version, license: record.license, selectedLicense: record.license === '(MPL-2.0 OR Apache-2.0)' ? 'Apache-2.0' : record.license, integrity: record.integrity, dev: Boolean(record.dev), files: licenses });
text += `\n\n${path} @ ${record.version} (${record.license})\n${record.resolved}\n`;
for (const file of licenses) text += `\n--- ${file} ---\n${await readFile(join(licenseRoot, file), 'utf8')}\n`;
if (path === 'node_modules/pako') {
const zlib = await readFile(join(root, path, 'lib/zlib/deflate.js'), 'utf8');
const header = zlib.slice(zlib.indexOf('// (C)'), zlib.indexOf('\nvar utils'));
assert(header.includes('This notice may not be removed'));
text += `\n--- Zlib notice from lib/zlib/deflate.js ---\n${header}\n`;
}
}
await writeFile(join(root, 'THIRD-PARTY-NOTICES.txt'), text, 'utf8');
await writeFile(join(root, 'DEPENDENCIES.json'), JSON.stringify(records, null, 2) + '\n', 'utf8');
}