import { execFileSync } from 'node:child_process'; import { cp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import { join, resolve } from 'node:path'; const root=resolve(fileURLToPath(new URL('..',import.meta.url))),output=join(root,'.headless-dist'); await rm(output,{recursive:true,force:true}); execFileSync(process.execPath,[join(root,'node_modules/typescript/bin/tsc'),'-p',join(root,'tsconfig.headless.json')],{cwd:root,stdio:'inherit'}); async function declarations(directory){ for(const entry of await readdir(directory,{withFileTypes:true})){ const path=join(directory,entry.name); if(entry.isDirectory())await declarations(path); else if(entry.name.endsWith('.d.ts')){ const source=await readFile(path,'utf8'); // Native TS rewrites runtime imports, but leaves source suffixes in declarations. // Only module specifiers change; data/schema string literals remain intact. const next=source.replace(/((?:from\s+|import\s*\()\s*['"])(\.\.?\/[^'"]+)\.ts(['"])/g,'$1$2.js$3'); await writeFile(path,next); } } } await declarations(join(output,'modules')); for(const [module,worker]of [['browser-digests','digest.worker'],['browser-images','image.worker']]){ const path=join(output,'modules/canvas-runtime',`${module}.js`),source=await readFile(path,'utf8'),before=`./${worker}.ts`; if(source.split(before).length!==2)throw Error(`Unexpected Worker URL in ${module}`); await readFile(join(output,'modules/canvas-runtime',`${worker}.js`)); await writeFile(path,source.replace(before,`./${worker}.js`)); } for(const name of ['package.json','consumer.mjs','README.md','STEP4_ACCEPTANCE.md','SERVICE_ACCEPTANCE.md'])await cp(join(root,'headless',name),join(output,name)); console.log('Built .headless-dist: ESM, declarations, browser adapters and Worker modules');