// Keeps the operator's server-side services out of the web bundle. // // node scripts/ci/web-bundle.mjs [assets] [sources] // // Reads the service keys that `sources` declares and fails when a JavaScript file in `assets` // contains one. Defaults to the built `apps/web/dist/assets` and to // `packages/orchestrator/src/operator`, so run it after `pnpm build`. import { existsSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; const serviceKey = /Context\.Service<[^]*?>\(\)\(\s*"(@usine\/[^"]+)"/gu; const escape = (text) => text.replaceAll(/[.*+?^${}()|[\]\\/]/gu, "\\$&"); const files = (directory, extension) => existsSync(directory) ? readdirSync(directory, { recursive: true, withFileTypes: true }) .filter((entry) => entry.isFile() && entry.name.endsWith(extension)) .map((entry) => join(entry.parentPath, entry.name)) : []; /** * Returns the keys of the `Context.Service` classes that the TypeScript files under `sources` * declare. Throws when there is none, so a changed key format can't pass the check unread. */ export const serviceKeys = (sources) => { const keys = new Set(); for (const file of files(sources, ".ts")) { for (const [, key] of readFileSync(file, "utf8").matchAll(serviceKey)) keys.add(key); } if (keys.size === 0) throw new Error(`No service key in ${sources}`); return [...keys].sort(); }; /** * Returns each JavaScript file under `assets` with the `keys` it contains as string literals. * Throws when `assets` holds no JavaScript, which means the web app isn't built. */ export const leakedServices = (assets, keys) => { const scripts = files(assets, ".js"); if (scripts.length === 0) throw new Error(`No JavaScript in ${assets}; run pnpm build first`); const literals = keys.map((key) => ({ key, literal: new RegExp(`[\`"']${escape(key)}[\`"']`, "u"), })); return scripts.flatMap((file) => { const source = readFileSync(file, "utf8"); const found = literals.filter(({ literal }) => literal.test(source)).map(({ key }) => key); return found.length === 0 ? [] : [{ file, keys: found }]; }); }; if (process.argv[1] === fileURLToPath(import.meta.url)) { const root = fileURLToPath(new URL("../../", import.meta.url)); const assets = process.argv[2] ?? join(root, "apps/web/dist/assets"); const sources = process.argv[3] ?? join(root, "packages/orchestrator/src/operator"); const keys = serviceKeys(sources); const leaks = leakedServices(assets, keys); for (const { file, keys: found } of leaks) { console.error(`${file}: bundles operator services ${found.join(", ")}`); } if (leaks.length > 0) { console.error("Import the view file, not its service file, from code that the web UI reaches."); process.exitCode = 1; } else { console.log(`The web bundle contains none of the ${keys.length} operator services.`); } }