import { transformCtDirective } from "@commontools/ts-transformers"; import { RuntimeProgram } from "./types.ts"; export function pretransformProgram( program: RuntimeProgram, id: string, ): RuntimeProgram { program = transformInjectHelperModule(program); program = transformProgramWithPrefix(program, id); return program; } // For each source file in the program, replace // a `/// ` directive line with an // internal import statement for use by the AST transformer // to provide access to helpers like `derive`, etc. export function transformInjectHelperModule( program: RuntimeProgram, ): RuntimeProgram { return { main: program.main, files: program.files.map((source) => ({ name: source.name, contents: transformCtDirective(source.contents), })), mainExport: program.mainExport, }; } // Adds `id` as a prefix to all files in the program. // Injects a new entry at root `/index.ts` to re-export // the entry contents because otherwise `typescript` // flattens the output, eliding the common prefix. export function transformProgramWithPrefix( program: RuntimeProgram, id: string, ): RuntimeProgram { const main = program.main; const exportNameds = `export * from "${prefix(main, id)}";`; const exportDefault = `export { default } from "${prefix(main, id)}";`; const hasDefault = !program.mainExport || program.mainExport === "default"; const files = [ ...program.files.map((source) => ({ name: prefix(source.name, id), contents: source.contents, })), { name: `/index.ts`, contents: `${exportNameds}${hasDefault ? `\n${exportDefault}` : ""}`, }, ]; return { main: `/index.ts`, files, }; } function prefix(filename: string, id: string): string { return `/${id}${filename}`; }