// 生成 src/source-bundle.ts:部署出去的这份 Worker 的全部源代码(按 AGPL-3.0 第 13 条,经 /source 提供给用户)。 // // 收:src/**(不含 source-bundle.ts 自己)、scripts/**、package.json、package-lock.json、wrangler.jsonc、tsconfig*.json、LICENSE。 // 键是相对 eval/ 的路径,按字母排。npm run build / test / deploy 之前都会先跑它;test/source.test.mjs 核对生成的和磁盘上的一致。 // // 用法:node scripts/gen-source.mjs 写文件 // node scripts/gen-source.mjs --check 只核对,不一致就退出 1 import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join, relative, sep } from "node:path"; import { fileURLToPath } from "node:url"; const ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const OUT = join(ROOT, "src", "source-bundle.ts"); function walk(dir) { const out = []; for (const name of readdirSync(dir)) { const p = join(dir, name); if (statSync(p).isDirectory()) out.push(...walk(p)); else out.push(p); } return out; } export function collect() { const files = [ ...walk(join(ROOT, "src")).filter((p) => p !== OUT), ...walk(join(ROOT, "scripts")), ...["package.json", "package-lock.json", "wrangler.jsonc", "tsconfig.json", "tsconfig.build.json", "LICENSE"].map((f) => join(ROOT, f), ), ]; const bundle = {}; for (const p of files.sort()) bundle[relative(ROOT, p).split(sep).join("/")] = readFileSync(p, "utf8"); return Object.fromEntries(Object.entries(bundle).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); } export function render(bundle) { return ( "// 生成的文件,别手改:node scripts/gen-source.mjs(npm run build / test / deploy 会先跑它)。\n" + "// 部署出去的源代码全文,/source 按 AGPL-3.0 第 13 条提供。\n" + "export const SOURCE_FILES: Record = " + JSON.stringify(bundle, null, 1) + ";\n" ); } if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { const text = render(collect()); if (process.argv.includes("--check")) { let cur = ""; try { cur = readFileSync(OUT, "utf8"); } catch {} if (cur !== text) { console.error("src/source-bundle.ts 过期了:跑 node scripts/gen-source.mjs"); process.exit(1); } } else { writeFileSync(OUT, text); console.log(`source-bundle: ${Object.keys(collect()).length} 个文件`); } }