import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs"; import { dirname, join, relative } from "node:path"; import { pathToFileURL } from "node:url"; import process from "node:process"; import { describe } from "../runtime/describe.ts"; import { merge } from "../runtime/registry.ts"; import type { Plugin, Plugins } from "../runtime/define.ts"; import { schemasFromTypes } from "./input-schema.ts"; import { folders, modules } from "./folders.ts"; function ensureDirectory(dir: string) { mkdirSync(dir, { recursive: true }); if (!lstatSync(dir).isDirectory()) throw new Error(`Expected a directory at ${dir}`); } function update(file: string, body: string, check: boolean) { if (existsSync(file) && readFileSync(file, "utf8") === body) return; if (check) throw new Error(`${file} is stale or missing. Run copilotz gen.`); ensureDirectory(dirname(file)); const temp = file + "." + crypto.randomUUID() + ".tmp"; try { writeFileSync(temp, body, { flag: "wx" }); renameSync(temp, file); } finally { rmSync(temp, { force: true }); } } function reconcile(dir: string, files: Map, check: boolean) { if (!existsSync(dir)) return; if (!lstatSync(dir).isDirectory()) throw new Error(`Expected a directory at ${dir}`); for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name); if (entry.isDirectory()) { reconcile(path, files, check); if (readdirSync(path).length) continue; } else if (files.has(path) && entry.isFile()) continue; if (check) throw new Error(`Unexpected generated path ${path}. Run copilotz gen.`); rmSync(path, { recursive: true, force: true }); } } async function names(root: string, front: string[]) { const app = await import(pathToFileURL(join(root, "app.ts")).href) as { plugins(): Plugins }; const plugins = await app.plugins(); const { actions, collections, views } = merge(plugins); const owners = ((plugins as unknown[]).flat(Infinity) as Plugin[]).flatMap((plugin) => Object.entries(plugin.collections ?? {}).filter(([, def]) => "schema" in def) .map(([name]) => [name, plugin.name] as const) ).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); const registry = await describe({ name: "app", actions, collections, views }); const union = (values: string[]) => [...new Set(values)].sort().map((v) => JSON.stringify(v)).join(" | ") || "never"; return [ "// Generated by copilotz gen. Commit this file with the app.", 'import "copilotz";', 'import type {} from "./app.ts";', "", 'declare module "copilotz" {', " interface AppNames {", ` actions: ${union(registry.actions.map((a) => a.name))};`, ` queries: ${ union(registry.keeps.flatMap((c) => c.queries.map((q) => c.name + "." + q.name))) };`, ` collections: ${union(registry.keeps.map((c) => c.name))};`, " collectionOwners: {", ...owners.map(([name, plugin]) => ` ${JSON.stringify(name)}: ${JSON.stringify(plugin)};`), " };", ` views: ${union([...registry.views.map((v) => v.name), ...front])};`, " }", "}", "", ].join("\n"); } async function schemasFor(root: string, selected: ReturnType) { const files = selected.flatMap((folder) => folder.entries.mod.flatMap(({ file, kind }) => kind === "actions" || kind === "collections" ? [{ file, kind }] : [] ) ); const config = join(root, "tsconfig.json"); const results = await schemasFromTypes(files, { tsconfig: existsSync(config) ? config : undefined, }); const errors = [...results.values()].flatMap((result) => result?.error ? [result.error] : []); if (errors.length) throw new Error(errors.join("\n")); return new Map( [...results].flatMap(([file, result]) => result?.schema !== undefined ? [[file, result.schema] as const] : [] ), ); } /** Assembles an app's plugins and records its merged names. In check mode, reads only. */ export async function generate(root: string, check = false): Promise { const selected = folders(root); await buildApp(root, check, selected, await schemasFor(root, selected)); } async function buildApp( root: string, check: boolean, selected: ReturnType, schemas: Awaited>, ) { const build = join(root, ".copilotz", "build"); const files = new Map(); const front: string[] = []; for (const folder of selected) { for (const [path, body] of modules(folder, join(build, "plugins", folder.name), schemas)) { files.set(path, body); } for (const host of ["web", "terminal"] as const) { front.push(...folder.entries[host].map((e) => e.key)); } } const state = dirname(build); if (existsSync(state) && !lstatSync(state).isDirectory()) { throw new Error(`Expected a directory at ${state}`); } reconcile(build, files, check); for (const [file, body] of files) update(file, body, check); if (existsSync(join(root, "tsx.ts")) && !process.versions.deno && !process.versions.bun) { await import(pathToFileURL(join(root, "tsx.ts")).href); } // Link every assembly through the app's loader. A missing default export in a host // entry or a plugin outside app.ts is a filename error too. for (const file of files.keys()) await import(pathToFileURL(file).href); update(join(root, "copilotz-env.d.ts"), await names(root, front), check); } /** Moves the selected assembly into source control and keeps existing package imports working. */ export async function eject(root: string, name?: string): Promise { const all = folders(root); const selected = all.filter((folder) => !name || folder.name === name); if (name && !selected.length) throw new Error(`No generated plugin named ${name}.`); if (!selected.length) return; const schemas = await schemasFor(root, all); await buildApp(root, false, all, schemas); const file = join(root, "package.json"); const pkg = JSON.parse(readFileSync(file, "utf8")); const files = new Map(); for (const folder of selected) { const key = `#copilotz/plugins/${folder.name}/*`; const target = `./plugins/${folder.name}/*`; pkg.imports ??= {}; if (key in pkg.imports && pkg.imports[key] !== target) { throw new Error(`${file} already maps ${key}`); } pkg.imports[key] = target; for (const [path, body] of modules(folder, folder.source, schemas)) { if (existsSync(path)) throw new Error(`Cannot eject over ${relative(root, path)}`); files.set(path, body); } } for (const [path, body] of files) writeFileSync(path, body, { flag: "wx" }); update(file, JSON.stringify(pkg, null, 2) + "\n", false); }