import { createHash } from 'node:crypto' import { mkdir, readFile, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { build } from 'esbuild' const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') const entry = resolve(root, 'scripts/code-editor-entry.ts') const target = resolve(root, 'src/editor/codeEditorAssets.ts') const check = process.argv.includes('--check') const buildResult = await build({ entryPoints: [entry], bundle: true, write: false, format: 'iife', platform: 'browser', target: ['safari16.4'], minify: true, charset: 'utf8', legalComments: 'eof', sourcemap: false, logLevel: 'silent', }) const output = buildResult.outputFiles?.[0] if (!output) throw new Error('The CodeMirror bundle did not produce JavaScript output.') const script = output.text.replace(/<\/script/gi, '<\\/script') const scriptHash = createHash('sha256').update(script).digest() const scriptHashHex = scriptHash.toString('hex') const scriptHashCsp = scriptHash.toString('base64') const csp = [ "default-src 'none'", `script-src 'sha256-${scriptHashCsp}'`, "style-src 'unsafe-inline'", "connect-src 'none'", "img-src 'none'", "media-src 'none'", "font-src 'none'", "object-src 'none'", "frame-src 'none'", "worker-src 'none'", "base-uri 'none'", "form-action 'none'", ].join('; ') const htmlPrefix = [ '', '', '
', '', '', ``, '', '', '', '', '' const generated = [ '// Generated by scripts/embed-code-editor.mjs. Do not edit by hand.', `export const CODE_EDITOR_ASSET_SHA256 = ${JSON.stringify(scriptHashHex)}`, // Emit one literal. Metro constant-folds the previous SCRIPT + HTML form and // stores the CodeMirror program twice in Hermes bytecode. `export const CODE_EDITOR_HTML = ${JSON.stringify(`${htmlPrefix}${script}${htmlSuffix}`)}`, '', ].join('\n') const existing = await readFile(target, 'utf8').catch(() => null) if (check) { if (existing !== generated) { console.error('Generated CodeMirror assets are stale. Run: node scripts/embed-code-editor.mjs') process.exitCode = 1 } } else if (existing !== generated) { await mkdir(dirname(target), { recursive: true }) await writeFile(target, generated) }