@brickkit/cli 0.13.3 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dashboard-dist/{api-reference-mT9VNcPb.js → api-reference-BP4ULs5J.js} +4 -4
- package/dashboard-dist/app.js +10 -10
- package/dashboard-dist/{client-CwATkLJa.js → client-CID_ep-s.js} +1 -1
- package/dashboard-dist/{core-BEUWp6B5.js → core-B123mLVe.js} +1 -1
- package/dashboard-dist/{docs-BRrtyxDB.js → docs-B5JrvjJm.js} +2 -2
- package/dashboard-dist/kit.js +1 -1
- package/dashboard-dist/{popover-Bj9x-88h.js → popover-B4rnc_po.js} +1 -1
- package/dist/bin.js +44 -1
- package/dist/bin.js.map +1 -1
- package/dist/build.js +13 -6
- package/dist/build.js.map +1 -1
- package/dist/client-contract-file.js +1 -1
- package/dist/client-contract-file.js.map +1 -1
- package/dist/dashboard-host.js +35 -14
- package/dist/dashboard-host.js.map +1 -1
- package/dist/dashboard-protocol.js +21 -1
- package/dist/dashboard-protocol.js.map +1 -1
- package/dist/dashboard.d.ts +1 -1
- package/dist/definitions.js +1 -0
- package/dist/definitions.js.map +1 -1
- package/dist/dev-protocol.js.map +1 -1
- package/dist/dev-worker.js +51 -12
- package/dist/dev-worker.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/project.js +4 -2
- package/dist/project.js.map +1 -1
- package/dist/vite.js +2 -1
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
package/dist/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","names":[],"sources":["../src/manifest.ts","../src/runner.ts","../src/compiler/aot.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { writeFileIfChanged } from \"./client-contract-file\";\n\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n DEFINITION_KINDS,\n MANIFEST_FILE,\n type DefinitionKind,\n} from \"./definitions\";\n\n/** Services register before the resources that join them; every other kind after. */\nconst FIRST: readonly DefinitionKind[] = [\"service\", \"resource\"];\n\nfunction rank(file: string) {\n const index = FIRST.indexOf(\n DEFINITION_FILE.exec(file)?.[2] as DefinitionKind,\n );\n return index === -1 ? FIRST.length : index;\n}\n\n/** Definition files under `services`: service files first, then resources, then the rest, each by path. */\nexport function scanDefinitionFiles(services: string): string[] {\n if (!existsSync(services)) return [];\n // Built per call: index.ts imports this module (through runner) and still\n // exports defineConfig, so Node may load it (ESLint reading brick.config.ts).\n const glob = new Bun.Glob(\n `**/*.{${DEFINITION_KINDS.join(\",\")}}.{${DEFINITION_EXTENSIONS.join(\",\")}}`,\n );\n const files = [...glob.scanSync({ cwd: services, onlyFiles: true })]\n .map((file) => file.split(sep).join(\"/\"))\n .filter((file) => !file.split(\"/\").includes(\"node_modules\"));\n return files.sort(\n (a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0),\n );\n}\n\n/** The source of `services.gen.ts`, which imports every definition file so each registers itself. */\nexport function renderManifest(services: string, generated: string): string {\n const imports = scanDefinitionFiles(services).map((file) => {\n let specifier = relative(generated, join(services, file))\n .split(sep)\n .join(\"/\")\n .replace(DEFINITION_FILE, \"$1.$2\");\n if (!specifier.startsWith(\".\")) specifier = `./${specifier}`;\n return `import ${JSON.stringify(specifier)};\\n`;\n });\n return `// Generated by Brick. Do not edit.\n// Imports every definition file under the services folder, so each one\n// registers itself on its service. The app entry imports this file.\n${imports.join(\"\")}\nexport {};\n`;\n}\n\n/** Write `<generated>/services.gen.ts`, leaving it untouched when nothing changed. */\nexport async function writeServiceManifest(options: {\n services: string;\n generated: string;\n}): Promise<string> {\n const output = join(options.generated, MANIFEST_FILE);\n await writeFileIfChanged(\n output,\n renderManifest(options.services, options.generated),\n );\n return output;\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport { brick, isBrickApp } from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { TEMPORARY_FILE_PREFIX } from \"./client-contract-file\";\nimport {\n ConfigError,\n CONTRACT_FILE,\n DEFAULT_DASHBOARD_PORT,\n PROJECT_DEFAULTS,\n resolvePort,\n} from \"./config\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ownModule } from \"./own-module\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerMessage, WorkerOptions } from \"./dev-protocol\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { printBanner, serveApp, shutdownOnSignal } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n /**\n * @deprecated Only used without an `entry`; an exported app sets its own\n * prefix in `brick({ prefix })`.\n */\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n /**\n * Local dashboard with live requests, traces, errors, and reloads. Needs an\n * entry. `port` is where it listens and `historyDays` how long finished\n * requests are kept on disk; zero keeps live data only. `extension` and\n * `theme` customise it (see `DashboardExtensionOptions`).\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n /**\n * Keep `<generated>/services.gen.ts` importing every definition file under\n * `services`: written before the app starts and again when files change.\n */\n manifest?: { services: string; generated: string };\n}\n\n/**\n * What `brick start` runs: serve the entry's default-exported app as it built\n * it (else one with the registered services), with the monitoring dashboard\n * it asks for, until SIGINT or SIGTERM.\n */\nexport async function startProdServer(options: {\n entry?: string;\n port?: number;\n /** The production dashboard's extension and theme. */\n dashboard?: DashboardExtensionOptions;\n}) {\n let exported: unknown;\n if (options.entry) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n exported = await importEntry(options.entry, { run: true });\n }\n const port = resolvePort(options.port);\n const app = isBrickApp(exported) ? exported : brick();\n await buildAppWorkflows(app);\n const dashboard = await serveApp(app, {\n port,\n dashboard: options.dashboard,\n });\n shutdownOnSignal(app);\n printBanner(app, { label: \"Production\", port, dashboard });\n return app;\n}\n\n/**\n * What `brick worker` runs: load the app and deliver its events from this\n * process, without serving HTTP. Run it beside API processes that only record\n * events (`events: { dispatch: false }`), or alone for an app with no routes.\n * Workflow listeners run here too: the world starts and the steps of every run\n * in it execute in this process.\n *\n * @param options - `entry`: the app file, which must default-export a `brick()` app.\n * @returns The app.\n * @throws When the entry is missing, has no `events`, or only records events.\n */\nexport async function startWorker(options: { entry: string }) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n const app = await importEntry(options.entry, { run: true });\n if (!isBrickApp(app))\n throw new ConfigError(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new ConfigError(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new ConfigError(\n \"Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.\",\n );\n await buildAppWorkflows(app);\n await app.start();\n app.events.start();\n shutdownOnSignal(app);\n const listeners = app.events.describe().listeners;\n console.log(`\\n🧱 Brick-TS Worker`);\n console.log(\n ` Delivering events to ${listeners.length} ${listeners.length === 1 ? \"listener\" : \"listeners\"}: ${listeners.map((l) => l.name).join(\", \") || \"none\"}\\n`,\n );\n return app;\n}\n\n/**\n * What `brick dev` runs: start the application, restart it when its files\n * change, and serve the dashboard beside it. With an `entry`, the app runs in\n * a worker process that restarts on every change to the entry or the files it\n * imports, and reports its requests to the dashboard; without one, a server\n * with the registered services starts in this process.\n *\n * @param options - `entry`, `port` (else `PORT`, else 4000), `prefix`,\n * `clientOutput` to regenerate the typed client's contract on each start,\n * `frontend` to launch a frontend command once, and `dashboard` (`port` and\n * `historyDays`, or `false`).\n * @returns The application, when started in this process.\n * @throws When `frontend` is given without `clientOutput`, or the dashboard\n * would use the app's port.\n */\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new ConfigError(\n \"Brick: --client and --frontend require an app entry.\",\n );\n if (options.frontend && !options.clientOutput)\n throw new ConfigError(\"Brick: --frontend requires --client <file>.\");\n const port = resolvePort(options.port);\n if (!entry) return startDevApplication({ port, prefix: options.prefix });\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry))\n throw new ConfigError(\n `[Brick-TS] Error: Entry file not found: ${resolvedEntry}`,\n );\n\n if (\n options.dashboard &&\n (options.dashboard.port ?? DEFAULT_DASHBOARD_PORT) === port\n )\n throw new ConfigError(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n const manifest = options.manifest;\n if (manifest) await writeServiceManifest(manifest);\n const contract = resolve(\n options.clientOutput ??\n join(manifest?.generated ?? PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n );\n const workerOptions: WorkerOptions = {\n entry: resolvedEntry,\n port,\n prefix: options.prefix,\n clientOutput: options.clientOutput && contract,\n telemetry: Boolean(options.dashboard),\n };\n // Bind the dashboard before the first worker starts, so the worker's spans\n // have somewhere to go.\n const dashboard = options.dashboard\n ? await openDashboard({\n port: options.dashboard.port,\n directory: process.cwd(),\n historyDays: options.dashboard.historyDays,\n warn: (message) => console.warn(message),\n docs: true,\n dashboard: {\n extension: options.dashboard.extension,\n theme: options.dashboard.theme,\n },\n restart: () => {\n void restart(\"dashboard\");\n },\n portHint: \"Use --dashboard-port <number> or --no-dashboard.\",\n })\n : undefined;\n const telemetry = dashboard?.store;\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const receive = (message: WorkerMessage, generation: number) => {\n switch (message.type) {\n case \"brick:telemetry\":\n telemetry?.ingest(message.records, generation);\n return;\n case \"brick:error\":\n telemetry?.recordWorkerError(message.phase, message.error, generation);\n return;\n case \"brick:contract-ready\":\n if (options.frontend && !frontend && !stopped)\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n telemetry?.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n return;\n case \"brick:architecture\":\n telemetry?.setArchitecture(message.architecture, generation);\n void dashboard?.setPluginExtensions(message.architecture.plugins ?? []);\n return;\n case \"brick:inspector\":\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector({ port: message.port, token: message.token });\n return;\n case \"brick:documentation\":\n void dashboard?.docs?.configure(\n dirname(resolvedEntry),\n message.documentation,\n );\n return;\n case \"brick:api-documents\":\n telemetry?.setApiDocuments(\n message.documents,\n `http://localhost:${port}`,\n );\n return;\n case \"brick:dependencies\":\n for (const file of message.files) {\n if (file === contract) continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n return;\n }\n };\n const launch = () => {\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n const generation = telemetry?.startGeneration() ?? 0;\n const application = Bun.spawn(\n [\n process.execPath,\n ownModule(\"dev-worker\"),\n JSON.stringify(workerOptions),\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc: (message: WorkerMessage) => receive(message, generation),\n },\n );\n void application.exited.then((code) => {\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector(undefined);\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n telemetry?.recordReload({\n kind: \"exited\",\n generation,\n detail: `exit code ${code}`,\n });\n }\n telemetry?.interruptGeneration(generation);\n });\n return application;\n };\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n // The worker reports the other files the entry imports (brick:dependencies).\n const watchDirs = [\n ...new Set([\n dirname(resolvedEntry),\n ...(manifest ? [manifest.services] : []),\n ]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart(trigger: \"changes\" | \"dashboard\" = \"changes\") {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\n trigger === \"changes\"\n ? \"\\n📝 Changes detected. Restarting server...\"\n : \"\\n🔄 Restart requested from the dashboard. Restarting server...\",\n );\n telemetry?.recordReload({\n kind: \"restarting\",\n generation: telemetry.latestGeneration,\n detail:\n trigger === \"changes\" ? \"source changed\" : \"restart from dashboard\",\n });\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const extension = options.dashboard && options.dashboard.extension;\n const extensionDir =\n extension && !watchDirs.includes(dirname(resolve(extension)))\n ? `${dirname(resolve(extension))}${sep}`\n : undefined;\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === contract ||\n basename(file).startsWith(TEMPORARY_FILE_PREFIX) ||\n // The dashboard rebuilds its extension itself; the app restarts only\n // for the files it imports.\n (extensionDir !== undefined &&\n file.startsWith(extensionDir) &&\n !dependencyFiles.has(file))\n )\n return;\n // A definition file was added or removed: refresh the import list first.\n if (manifest && file.startsWith(manifest.services + sep)) {\n void writeServiceManifest(manifest)\n .catch((error: unknown) =>\n console.error(\"[Brick-TS] Could not write services.gen.ts:\", error),\n )\n .finally(scheduleRestart);\n return;\n }\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n dashboard?.stop();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = (signal: NodeJS.Signals) => {\n if (stopped) {\n child.kill(\"SIGKILL\");\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n }\n stop();\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n void child.exited.then(() => process.exit(0));\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n","import { aot } from \"elysia/plugin/aot/bun\";\nimport type { BunPlugin } from \"bun\";\n\n/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */\nexport function brickAot(entry: string, keep: boolean): BunPlugin {\n // `keep`: WS routes still need cookie setup during reconstruction in beta.29,\n // and shipped workflows mount their webhook route only when a world is set at\n // run time. Retain those modules while continuing to precompile HTTP handlers.\n if (keep) return aot(entry, { target: \"bun\", strip: false });\n return {\n name: \"brick-elysia-aot\",\n async setup(build) {\n await aot(entry, { target: \"bun\", strip: true }).setup({\n ...build,\n onLoad(options, callback) {\n return build.onLoad(options, async (args) => {\n const result = await callback(args);\n if (\n !result ||\n !(\"contents\" in result) ||\n typeof result.contents !== \"string\"\n )\n return result;\n let contents = result.contents;\n if (\n /[/\\\\]elysia[/\\\\]dist[/\\\\]ws[/\\\\]route\\.m?js$/.test(args.path) &&\n contents.includes(\n \"[elysia-aot] WebSocket route builder was stripped\",\n )\n ) {\n for (const name of [\"resolveWSOptions\", \"accumulateWSOptions\"]) {\n if (!contents.includes(`export function ${name}`))\n contents += `\\nexport function ${name}() { throw new Error(\"WebSocket support was stripped\"); }\\n`;\n }\n }\n return contents === result.contents\n ? result\n : { ...result, contents };\n });\n },\n });\n },\n };\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, WORKFLOW_BUNDLE } from \"@brickkit/core\";\nimport type { BunPlugin } from \"bun\";\nimport { emitCompiledApplication } from \"./compiler\";\nimport { brickAot } from \"./compiler/aot\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ownModule } from \"./own-module\";\nimport { DEFAULT_OUTDIR, resolvePort } from \"./config\";\nimport { shipWorkflows, workflowTransformPlugin } from \"./workflows\";\nimport {\n themeCss,\n writeDashboardExtension,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n /**\n * The dashboard's extension, built into `<outdir>/dashboard` with those of\n * the app's plugins for the production dashboard to serve; its theme is\n * checked here too.\n */\n dashboard?: DashboardExtensionOptions;\n}\n\n/**\n * The production dashboard stays out of the bundle: it serves files that ship\n * with @brickkit/cli, so a built server whose app asks for it imports it from\n * there at run time. Without a dashboard the bundle needs nothing installed.\n */\nconst productionDashboardAtRunTime: BunPlugin = {\n name: \"brick:production-dashboard\",\n setup(build) {\n build.onResolve({ filter: /^\\.\\/production-dashboard(\\.[jt]s)?$/ }, () => ({\n path: \"@brickkit/cli/production-dashboard\",\n external: true,\n }));\n },\n};\n\n/** The files `brick build` writes to the output folder, `server.js` last. */\nconst OUTPUTS = [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"];\n\n/** Bundle an exported BrickApp with its compiled IR and its original configuration. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? DEFAULT_OUTDIR);\n if (OUTPUTS.some((name) => entry === join(outdir, name)))\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = resolvePort(options.port, undefined, \"\");\n themeCss(options.dashboard?.theme);\n const extension = options.dashboard?.extension\n ? resolve(options.dashboard.extension)\n : undefined;\n if (extension && !(await Bun.file(extension).exists()))\n throw new Error(\n `Brick compiler: dashboard extension not found: ${extension}`,\n );\n const app = await loadBrickApp(entry);\n const root = app.events?.workflows?.root ?? process.cwd();\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const dashboard = (await writeDashboardExtension(\n extension,\n app.definition.plugins ?? [],\n join(staging, \"dashboard\"),\n ))\n ? join(outdir, \"dashboard\")\n : undefined;\n const theme = JSON.stringify(options.dashboard?.theme);\n const source = `import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { resolvePort } from ${JSON.stringify(ownModule(\"config\"))};\nimport { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule(\"serve\"))};\nconst workflows = fileURLToPath(new URL(${JSON.stringify(`./${WORKFLOW_BUNDLE.dir}`)}, import.meta.url));\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), undefined, {\n workflows: existsSync(workflows) ? workflows : undefined,\n});\nexport default app;\nif (import.meta.main) {\n await serveApp(app, {\n port: resolvePort(undefined, ${port}),\n dashboard: { extension: ${dashboard ? 'fileURLToPath(new URL(\"./dashboard\", import.meta.url))' : \"undefined\"}, theme: ${theme} },\n });\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n shutdownOnSignal(app);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n // Whether to ship workflows depends on the files the bundle holds, not on\n // the env: an app may declare its workflow listeners only at run time.\n let directives = false;\n const transform = await workflowTransformPlugin(root, () => {\n directives = true;\n });\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n // AOT first: the workflow plugin loads every project file it sees, so after\n // it the AOT plugin would never get to transform the entry.\n plugins: [\n ...(options.aot === false\n ? []\n : [\n brickAot(\n join(staging, \"entry.ts\"),\n app.definition.sockets.length > 0 || transform !== undefined,\n ),\n ]),\n ...(transform ? [transform] : []),\n productionDashboardAtRunTime,\n ],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n const workflows =\n (directives || Boolean(app.events?.workflows)) &&\n (await shipWorkflows(root, staging, Boolean(app.events?.workflows)));\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of OUTPUTS)\n await rename(join(staging, name), join(outdir, name));\n // Only the bundle is ours: other files under .well-known stay.\n const bundle = join(outdir, WORKFLOW_BUNDLE.dir);\n await rm(bundle, { recursive: true, force: true });\n if (workflows) {\n await mkdir(dirname(bundle), { recursive: true });\n await rename(join(staging, WORKFLOW_BUNDLE.dir), bundle);\n }\n if (dashboard) {\n await rm(dashboard, { recursive: true, force: true });\n await rename(join(staging, \"dashboard\"), dashboard);\n }\n return {\n outdir,\n entry: join(outdir, \"server.js\"),\n ir: compilation.ir,\n dashboard,\n workflows: workflows ?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AAI,IAC5C;EACA,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;EACvC,KAAK,MAAM,QAAQ,SACjB,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,QAAQ,IAAI,CAAC;EAEtD,MAAM,SAAS,KAAK,QAAQ,gBAAgB,GAAG;EAC/C,MAAM,GAAG,QAAQ;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EACjD,IAAI,WAAW;GACb,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;GAChD,MAAM,OAAO,KAAK,SAAS,gBAAgB,GAAG,GAAG,MAAM;EACzD;EACA,IAAI,WAAW;GACb,MAAM,GAAG,WAAW;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACpD,MAAM,OAAO,KAAK,SAAS,WAAW,GAAG,SAAS;EACpD;EACA,OAAO;GACL;GACA,OAAO,KAAK,QAAQ,WAAW;GAC/B,IAAI,YAAY;GAChB;GACA,WAAW,YAAY,KAAK,QAAQ,gBAAgB,GAAG,IAAI,KAAA;EAC7D;CACF,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
|
1
|
+
{"version":3,"file":"build.js","names":[],"sources":["../src/manifest.ts","../src/runner.ts","../src/compiler/aot.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { writeFileIfChanged } from \"./client-contract-file\";\n\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n DEFINITION_KINDS,\n MANIFEST_FILE,\n type DefinitionKind,\n} from \"./definitions\";\n\n/** Services register before the resources that join them; every other kind after. */\nconst FIRST: readonly DefinitionKind[] = [\"service\", \"resource\"];\n\nfunction rank(file: string) {\n const index = FIRST.indexOf(\n DEFINITION_FILE.exec(file)?.[2] as DefinitionKind,\n );\n return index === -1 ? FIRST.length : index;\n}\n\n/** Definition files under `services`: service files first, then resources, then the rest, each by path. */\nexport function scanDefinitionFiles(services: string): string[] {\n if (!existsSync(services)) return [];\n // Built per call: index.ts imports this module (through runner) and still\n // exports defineConfig, so Node may load it (ESLint reading brick.config.ts).\n const glob = new Bun.Glob(\n `**/*.{${DEFINITION_KINDS.join(\",\")}}.{${DEFINITION_EXTENSIONS.join(\",\")}}`,\n );\n const files = [...glob.scanSync({ cwd: services, onlyFiles: true })]\n .map((file) => file.split(sep).join(\"/\"))\n .filter((file) => !file.split(\"/\").includes(\"node_modules\"));\n return files.sort(\n (a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0),\n );\n}\n\n/** The source of `services.gen.ts`, which imports every definition file so each registers itself. */\nexport function renderManifest(services: string, generated: string): string {\n const imports = scanDefinitionFiles(services).map((file) => {\n let specifier = relative(generated, join(services, file))\n .split(sep)\n .join(\"/\")\n .replace(DEFINITION_FILE, \"$1.$2\");\n if (!specifier.startsWith(\".\")) specifier = `./${specifier}`;\n return `import ${JSON.stringify(specifier)};\\n`;\n });\n return `// Generated by Brick. Do not edit.\n// Imports every definition file under the services folder, so each one\n// registers itself on its service. The app entry imports this file.\n${imports.join(\"\")}\nexport {};\n`;\n}\n\n/** Write `<generated>/services.gen.ts`, leaving it untouched when nothing changed. */\nexport async function writeServiceManifest(options: {\n services: string;\n generated: string;\n}): Promise<string> {\n const output = join(options.generated, MANIFEST_FILE);\n await writeFileIfChanged(\n output,\n renderManifest(options.services, options.generated),\n );\n return output;\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport {\n brick,\n dashboardKey,\n DASHBOARD_KEY_ENV,\n isBrickApp,\n} from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { TEMPORARY_FILE_PREFIX } from \"./client-contract-file\";\nimport {\n ConfigError,\n CONTRACT_FILE,\n DEFAULT_DASHBOARD_PORT,\n PROJECT_DEFAULTS,\n resolvePort,\n} from \"./config\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ownModule } from \"./own-module\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerMessage, WorkerOptions } from \"./dev-protocol\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { printBanner, serveApp, shutdownOnSignal } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n /**\n * @deprecated Only used without an `entry`; an exported app sets its own\n * prefix in `brick({ prefix })`.\n */\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n /**\n * Local dashboard with live requests, traces, errors, and reloads. Needs an\n * entry. `port` is where it listens and `historyDays` how long finished\n * requests are kept on disk; zero keeps live data only. `extension` and\n * `theme` customise it (see `DashboardExtensionOptions`).\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n /**\n * Keep `<generated>/services.gen.ts` importing every definition file under\n * `services`: written before the app starts and again when files change.\n */\n manifest?: { services: string; generated: string };\n}\n\n/**\n * What `brick start` runs: serve the entry's default-exported app as it built\n * it (else one with the registered services), with the monitoring dashboard\n * it asks for, until SIGINT or SIGTERM.\n */\nexport async function startProdServer(options: {\n entry?: string;\n port?: number;\n /** The production dashboard's extension and theme. */\n dashboard?: DashboardExtensionOptions;\n}) {\n let exported: unknown;\n if (options.entry) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n exported = await importEntry(options.entry, { run: true });\n }\n const port = resolvePort(options.port);\n const app = isBrickApp(exported) ? exported : brick();\n await buildAppWorkflows(app);\n const dashboard = await serveApp(app, {\n port,\n dashboard: options.dashboard,\n });\n shutdownOnSignal(app);\n printBanner(app, { label: \"Production\", port, dashboard });\n return app;\n}\n\n/**\n * What `brick worker` runs: load the app, deliver its events and run its\n * schedules from this process, without serving HTTP. Run it beside API processes that only record\n * events (`events: { dispatch: false }`), or alone for an app with no routes.\n * Workflow listeners run here too: the world starts and the steps of every run\n * in it execute in this process.\n *\n * @param options - `entry`: the app file, which must default-export a `brick()` app.\n * @returns The app.\n * @throws When the entry is missing, has no `events`, or only records events.\n */\nexport async function startWorker(options: { entry: string }) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n const app = await importEntry(options.entry, { run: true });\n if (!isBrickApp(app))\n throw new ConfigError(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new ConfigError(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new ConfigError(\n \"Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.\",\n );\n await buildAppWorkflows(app);\n await app.start();\n app.events.start();\n shutdownOnSignal(app);\n const { listeners, schedules = [] } = app.events.describe();\n console.log(`\\n🧱 Brick-TS Worker`);\n console.log(\n ` Delivering events to ${listeners.length} ${listeners.length === 1 ? \"listener\" : \"listeners\"}: ${listeners.map((l) => l.name).join(\", \") || \"none\"}`,\n );\n if (schedules.length)\n console.log(\n ` Running ${schedules.length} ${schedules.length === 1 ? \"schedule\" : \"schedules\"}: ${schedules.map((s) => s.name).join(\", \")}`,\n );\n console.log(\"\");\n return app;\n}\n\n/**\n * What `brick dev` runs: start the application, restart it when its files\n * change, and serve the dashboard beside it. With an `entry`, the app runs in\n * a worker process that restarts on every change to the entry or the files it\n * imports, and reports its requests to the dashboard; without one, a server\n * with the registered services starts in this process.\n *\n * @param options - `entry`, `port` (else `PORT`, else 4000), `prefix`,\n * `clientOutput` to regenerate the typed client's contract on each start,\n * `frontend` to launch a frontend command once, and `dashboard` (`port` and\n * `historyDays`, or `false`).\n * @returns The application, when started in this process.\n * @throws When `frontend` is given without `clientOutput`, or the dashboard\n * would use the app's port.\n */\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new ConfigError(\n \"Brick: --client and --frontend require an app entry.\",\n );\n if (options.frontend && !options.clientOutput)\n throw new ConfigError(\"Brick: --frontend requires --client <file>.\");\n const port = resolvePort(options.port);\n if (!entry) return startDevApplication({ port, prefix: options.prefix });\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry))\n throw new ConfigError(\n `[Brick-TS] Error: Entry file not found: ${resolvedEntry}`,\n );\n\n if (\n options.dashboard &&\n (options.dashboard.port ?? DEFAULT_DASHBOARD_PORT) === port\n )\n throw new ConfigError(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n const manifest = options.manifest;\n if (manifest) await writeServiceManifest(manifest);\n const contract = resolve(\n options.clientOutput ??\n join(manifest?.generated ?? PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n );\n const workerOptions: WorkerOptions = {\n entry: resolvedEntry,\n port,\n prefix: options.prefix,\n clientOutput: options.clientOutput && contract,\n telemetry: Boolean(options.dashboard),\n };\n // Bind the dashboard before the first worker starts, so the worker's spans\n // have somewhere to go.\n const dashboard = options.dashboard\n ? await openDashboard({\n port: options.dashboard.port,\n directory: process.cwd(),\n historyDays: options.dashboard.historyDays,\n warn: (message) => console.warn(message),\n docs: true,\n dashboard: {\n extension: options.dashboard.extension,\n theme: options.dashboard.theme,\n },\n restart: () => {\n void restart(\"dashboard\");\n },\n portHint: \"Use --dashboard-port <number> or --no-dashboard.\",\n })\n : undefined;\n const telemetry = dashboard?.store;\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const receive = (message: WorkerMessage, generation: number) => {\n switch (message.type) {\n case \"brick:telemetry\":\n telemetry?.ingest(message.records, generation);\n return;\n case \"brick:error\":\n telemetry?.recordWorkerError(message.phase, message.error, generation);\n return;\n case \"brick:contract-ready\":\n if (options.frontend && !frontend && !stopped)\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n telemetry?.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n return;\n case \"brick:architecture\":\n telemetry?.setArchitecture(message.architecture, generation);\n void dashboard?.setPluginExtensions(message.architecture.plugins ?? []);\n return;\n case \"brick:inspector\":\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector({\n port: message.port,\n token: message.token,\n workflows: message.workflows,\n });\n return;\n case \"brick:documentation\":\n void dashboard?.docs?.configure(\n dirname(resolvedEntry),\n message.documentation,\n );\n return;\n case \"brick:api-documents\":\n telemetry?.setApiDocuments(\n message.documents,\n `http://localhost:${port}`,\n );\n return;\n case \"brick:dependencies\":\n for (const file of message.files) {\n if (file === contract) continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n return;\n }\n };\n const launch = () => {\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n const generation = telemetry?.startGeneration() ?? 0;\n const application = Bun.spawn(\n [\n process.execPath,\n ownModule(\"dev-worker\"),\n JSON.stringify(workerOptions),\n ],\n {\n cwd: process.cwd(),\n env: dashboard\n ? { ...process.env, [DASHBOARD_KEY_ENV]: dashboardKey() }\n : process.env,\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc: (message: WorkerMessage) => receive(message, generation),\n },\n );\n void application.exited.then((code) => {\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector(undefined);\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n telemetry?.recordReload({\n kind: \"exited\",\n generation,\n detail: `exit code ${code}`,\n });\n }\n telemetry?.interruptGeneration(generation);\n });\n return application;\n };\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n // The worker reports the other files the entry imports (brick:dependencies).\n const watchDirs = [\n ...new Set([\n dirname(resolvedEntry),\n ...(manifest ? [manifest.services] : []),\n ]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart(trigger: \"changes\" | \"dashboard\" = \"changes\") {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\n trigger === \"changes\"\n ? \"\\n📝 Changes detected. Restarting server...\"\n : \"\\n🔄 Restart requested from the dashboard. Restarting server...\",\n );\n telemetry?.recordReload({\n kind: \"restarting\",\n generation: telemetry.latestGeneration,\n detail:\n trigger === \"changes\" ? \"source changed\" : \"restart from dashboard\",\n });\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const extension = options.dashboard && options.dashboard.extension;\n const extensionDir =\n extension && !watchDirs.includes(dirname(resolve(extension)))\n ? `${dirname(resolve(extension))}${sep}`\n : undefined;\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === contract ||\n basename(file).startsWith(TEMPORARY_FILE_PREFIX) ||\n // The dashboard rebuilds its extension itself; the app restarts only\n // for the files it imports.\n (extensionDir !== undefined &&\n file.startsWith(extensionDir) &&\n !dependencyFiles.has(file))\n )\n return;\n // A definition file was added or removed: refresh the import list first.\n if (manifest && file.startsWith(manifest.services + sep)) {\n void writeServiceManifest(manifest)\n .catch((error: unknown) =>\n console.error(\"[Brick-TS] Could not write services.gen.ts:\", error),\n )\n .finally(scheduleRestart);\n return;\n }\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n dashboard?.stop();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = (signal: NodeJS.Signals) => {\n if (stopped) {\n child.kill(\"SIGKILL\");\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n }\n stop();\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n void child.exited.then(() => process.exit(0));\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n","import { aot } from \"elysia/plugin/aot/bun\";\nimport type { BunPlugin } from \"bun\";\n\n/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */\nexport function brickAot(entry: string, keep: boolean): BunPlugin {\n // `keep`: WS routes still need cookie setup during reconstruction in beta.29,\n // and shipped workflows mount their webhook route only when a world is set at\n // run time. Retain those modules while continuing to precompile HTTP handlers.\n if (keep) return aot(entry, { target: \"bun\", strip: false });\n return {\n name: \"brick-elysia-aot\",\n async setup(build) {\n await aot(entry, { target: \"bun\", strip: true }).setup({\n ...build,\n onLoad(options, callback) {\n return build.onLoad(options, async (args) => {\n const result = await callback(args);\n if (\n !result ||\n !(\"contents\" in result) ||\n typeof result.contents !== \"string\"\n )\n return result;\n let contents = result.contents;\n if (\n /[/\\\\]elysia[/\\\\]dist[/\\\\]ws[/\\\\]route\\.m?js$/.test(args.path) &&\n contents.includes(\n \"[elysia-aot] WebSocket route builder was stripped\",\n )\n ) {\n for (const name of [\"resolveWSOptions\", \"accumulateWSOptions\"]) {\n if (!contents.includes(`export function ${name}`))\n contents += `\\nexport function ${name}() { throw new Error(\"WebSocket support was stripped\"); }\\n`;\n }\n }\n return contents === result.contents\n ? result\n : { ...result, contents };\n });\n },\n });\n },\n };\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, WORKFLOW_BUNDLE } from \"@brickkit/core\";\nimport type { BunPlugin } from \"bun\";\nimport { emitCompiledApplication } from \"./compiler\";\nimport { brickAot } from \"./compiler/aot\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ownModule } from \"./own-module\";\nimport { DEFAULT_OUTDIR, resolvePort } from \"./config\";\nimport { shipWorkflows, workflowTransformPlugin } from \"./workflows\";\nimport {\n themeCss,\n writeDashboardExtension,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n /**\n * The dashboard's extension, built into `<outdir>/dashboard` with those of\n * the app's plugins for the production dashboard to serve; its theme is\n * checked here too.\n */\n dashboard?: DashboardExtensionOptions;\n}\n\n/**\n * The production dashboard stays out of the bundle: it serves files that ship\n * with @brickkit/cli, so a built server whose app asks for it imports it from\n * there at run time. Without a dashboard the bundle needs nothing installed.\n */\nconst productionDashboardAtRunTime: BunPlugin = {\n name: \"brick:production-dashboard\",\n setup(build) {\n build.onResolve({ filter: /^\\.\\/production-dashboard(\\.[jt]s)?$/ }, () => ({\n path: \"@brickkit/cli/production-dashboard\",\n external: true,\n }));\n },\n};\n\n/** The files `brick build` writes to the output folder, `server.js` last. */\nconst OUTPUTS = [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"];\n\n/** Bundle an exported BrickApp with its compiled IR and its original configuration. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? DEFAULT_OUTDIR);\n if (OUTPUTS.some((name) => entry === join(outdir, name)))\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = resolvePort(options.port, undefined, \"\");\n themeCss(options.dashboard?.theme);\n const extension = options.dashboard?.extension\n ? resolve(options.dashboard.extension)\n : undefined;\n if (extension && !(await Bun.file(extension).exists()))\n throw new Error(\n `Brick compiler: dashboard extension not found: ${extension}`,\n );\n const app = await loadBrickApp(entry);\n const root = app.events?.workflows?.root ?? process.cwd();\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const dashboard = (await writeDashboardExtension(\n extension,\n app.definition.plugins ?? [],\n join(staging, \"dashboard\"),\n ))\n ? join(outdir, \"dashboard\")\n : undefined;\n const theme = JSON.stringify(options.dashboard?.theme);\n const source = `import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { resolvePort } from ${JSON.stringify(ownModule(\"config\"))};\nimport { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule(\"serve\"))};\nconst workflows = fileURLToPath(new URL(${JSON.stringify(`./${WORKFLOW_BUNDLE.dir}`)}, import.meta.url));\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), undefined, {\n workflows: existsSync(workflows) ? workflows : undefined,\n});\nexport default app;\nif (import.meta.main) {\n await serveApp(app, {\n port: resolvePort(undefined, ${port}),\n dashboard: { extension: ${dashboard ? 'fileURLToPath(new URL(\"./dashboard\", import.meta.url))' : \"undefined\"}, theme: ${theme} },\n });\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n shutdownOnSignal(app);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n // Whether to ship workflows depends on the files the bundle holds, not on\n // the env: an app may declare its workflow listeners only at run time.\n let directives = false;\n const transform = await workflowTransformPlugin(root, () => {\n directives = true;\n });\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n // AOT first: the workflow plugin loads every project file it sees, so after\n // it the AOT plugin would never get to transform the entry.\n plugins: [\n ...(options.aot === false\n ? []\n : [\n brickAot(\n join(staging, \"entry.ts\"),\n app.definition.sockets.length > 0 || transform !== undefined,\n ),\n ]),\n ...(transform ? [transform] : []),\n productionDashboardAtRunTime,\n ],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n const workflows =\n (directives || Boolean(app.events?.workflows)) &&\n (await shipWorkflows(root, staging, Boolean(app.events?.workflows)));\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of OUTPUTS)\n await rename(join(staging, name), join(outdir, name));\n // Only the bundle is ours: other files under .well-known stay.\n const bundle = join(outdir, WORKFLOW_BUNDLE.dir);\n await rm(bundle, { recursive: true, force: true });\n if (workflows) {\n await mkdir(dirname(bundle), { recursive: true });\n await rename(join(staging, WORKFLOW_BUNDLE.dir), bundle);\n }\n if (dashboard) {\n await rm(dashboard, { recursive: true, force: true });\n await rename(join(staging, \"dashboard\"), dashboard);\n }\n return {\n outdir,\n entry: join(outdir, \"server.js\"),\n ir: compilation.ir,\n dashboard,\n workflows: workflows ? join(outdir, WORKFLOW_BUNDLE.dir) : undefined,\n };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAM,QAAmC,CAAC,WAAW,UAAU;AAE/D,SAAS,KAAK,MAAc;CAC1B,MAAM,QAAQ,MAAM,QAClB,gBAAgB,KAAK,IAAI,CAAC,GAAG,EAC/B;CACA,OAAO,UAAU,KAAK,MAAM,SAAS;AACvC;;AAGA,SAAgB,oBAAoB,UAA4B;CAC9D,IAAI,CAAC,WAAW,QAAQ,GAAG,OAAO,CAAC;CASnC,OAHc,CAAC,GAAG,IAHD,IAAI,KACnB,SAAS,iBAAiB,KAAK,GAAG,EAAE,KAAK,sBAAsB,KAAK,GAAG,EAAE,EAEtD,CAAC,CAAC,SAAS;EAAE,KAAK;EAAU,WAAW;CAAK,CAAC,CAAC,CAAC,CACjE,KAAK,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CACxC,QAAQ,SAAS,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,cAAc,CACjD,CAAC,CAAC,MACV,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,EAC3D;AACF;;AAGA,SAAgB,eAAe,UAAkB,WAA2B;CAS1E,OAAO;;;EARS,oBAAoB,QAAQ,CAAC,CAAC,KAAK,SAAS;EAC1D,IAAI,YAAY,SAAS,WAAW,KAAK,UAAU,IAAI,CAAC,CAAC,CACtD,MAAM,GAAG,CAAC,CACV,KAAK,GAAG,CAAC,CACT,QAAQ,iBAAiB,OAAO;EACnC,IAAI,CAAC,UAAU,WAAW,GAAG,GAAG,YAAY,KAAK;EACjD,OAAO,UAAU,KAAK,UAAU,SAAS,EAAE;CAC7C,CAIM,CAAC,CAAC,KAAK,EAAE,EAAE;;;AAGnB;;AAGA,eAAsB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AAY,CAAC,SAAS,IAAI,CAAC;IAC/B;GACF;EACF,CAAC;EACD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,eAAe,OAAO,MAAM,iCAAiC;EACzE,MAAM,aACH,cAAc,QAAQ,IAAI,QAAQ,SAAS,MAC3C,MAAM,cAAc,MAAM,SAAS,QAAQ,IAAI,QAAQ,SAAS,CAAC;EACpE,MAAM,IAAI,MACR,KAAK,SAAS,eAAe,GAC7B,KAAK,UAAU,YAAY,IAAI,MAAM,CAAC,IAAI,IAC5C;EACA,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;EACvC,KAAK,MAAM,QAAQ,SACjB,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,QAAQ,IAAI,CAAC;EAEtD,MAAM,SAAS,KAAK,QAAQ,gBAAgB,GAAG;EAC/C,MAAM,GAAG,QAAQ;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EACjD,IAAI,WAAW;GACb,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;GAChD,MAAM,OAAO,KAAK,SAAS,gBAAgB,GAAG,GAAG,MAAM;EACzD;EACA,IAAI,WAAW;GACb,MAAM,GAAG,WAAW;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACpD,MAAM,OAAO,KAAK,SAAS,WAAW,GAAG,SAAS;EACpD;EACA,OAAO;GACL;GACA,OAAO,KAAK,QAAQ,WAAW;GAC/B,IAAI,YAAY;GAChB;GACA,WAAW,YAAY,KAAK,QAAQ,gBAAgB,GAAG,IAAI,KAAA;EAC7D;CACF,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
|
@@ -282,7 +282,7 @@ var SchemaTypes = class {
|
|
|
282
282
|
if (schema.anyOf || schema.oneOf) return `(${(schema.anyOf ?? schema.oneOf).map((child) => emit(child, false, currentBase)).join(" | ")})`;
|
|
283
283
|
if (schema.allOf) return `(${schema.allOf.map((child) => emit(child, false, currentBase)).join(" & ")})`;
|
|
284
284
|
switch (schema.type) {
|
|
285
|
-
case "string": return "string";
|
|
285
|
+
case "string": return schema.format === "binary" ? "Blob" : "string";
|
|
286
286
|
case "number":
|
|
287
287
|
case "integer": return "number";
|
|
288
288
|
case "boolean": return "boolean";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-contract-file.js","names":[],"sources":["../src/app-entry.ts","../src/client-contract.ts","../src/client-contract-file.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { requireBrickApp, type BrickApp } from \"@brickkit/core\";\nimport { ConfigError } from \"./config\";\nimport { registerWorkflowTransform } from \"./workflows\";\n\n/**\n * Import an app entry and return its default export. `run`: the app will run\n * in this process, so workflow files are transformed as they load.\n *\n * @throws When the file does not exist.\n */\nexport async function importEntry(\n entry: string,\n options: { run?: boolean } = {},\n): Promise<unknown> {\n const file = resolve(entry);\n if (!existsSync(file))\n throw new ConfigError(`[Brick-TS] Error: Entry file not found: ${file}`);\n if (options.run) await registerWorkflowTransform();\n return (await import(pathToFileURL(file).href)).default;\n}\n\n/**\n * Import an app entry to inspect it: to build it, or to read its routes. The app\n * is not run, so what creating it opened is released here: a workflow world\n * holds Redis connections that would keep the command from exiting.\n */\nexport async function loadBrickApp(entry: string): Promise<BrickApp> {\n const app = requireBrickApp(await importEntry(entry));\n await app.events?.stop();\n return app;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n actionOwners,\n getActionRoute,\n getPluginActionRoute,\n serializeSocketSchema,\n type Service,\n} from \"@brickkit/core\";\nimport type {\n BrickClientAction,\n BrickClientSocket,\n} from \"@brickkit/core/client\";\nimport type { BrickApp } from \"@brickkit/core\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const schemas = new SchemaTypes();\n for (const service of services) {\n addServiceActions(service, prefix, contract, types, schemas);\n for (const socket of service.listSockets()) {\n const route = app.definition.sockets.find(\n (route) =>\n route.service === service.name && route.name === socket.schema.name,\n );\n if (!route)\n throw new Error(\n `Brick client: missing socket route '${service.name}.${socket.schema.name}'`,\n );\n try {\n const metadata: BrickClientSocket = {\n kind: \"socket\",\n name: socket.schema.name,\n serviceName: service.name,\n config: { path: route.path },\n output: Object.fromEntries(\n Object.entries(socket.output).map(([key, schema]) => [\n key,\n serializeSocketSchema(schema),\n ]),\n ),\n };\n const payloads = (map: typeof socket.input) =>\n `{ ${Object.entries(map)\n .map(\n ([key, schema]) =>\n `${JSON.stringify(key)}: ${schemas.generate(schema)}`,\n )\n .join(\"; \")} }`;\n insertAction(\n contract[service.name],\n types[service.name],\n metadata,\n `BrickClientSocket<${payloads(socket.input)}, ${payloads(socket.output)}, ${errorsType(socket.errors)}>`,\n );\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate socket '${service.name}.${socket.schema.name}': ${String(error)}`,\n );\n }\n }\n }\n return `// Generated by Brick. Do not edit.\nimport type { BrickClientAction${app.definition.sockets.length ? \", BrickClientSocket\" : \"\"} } from \"@brickkit/core/client\";\n\n${schemas.renderContract(namespaceType(types))}\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n\n// Types useService(service) on the server from this contract.\ndeclare module \"@brickkit/core/client\" {\n interface BrickServices extends AppContract {}\n}\n`;\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n schemas: SchemaTypes,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n const pluginRoute = getPluginActionRoute(action, prefix) || undefined;\n const { input, output, errors } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemas.generate(input) : \"unknown\";\n outputType = output ? schemas.generate(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n ...actionOwners(action),\n config: { path: route.path, method: route.method },\n };\n insertAction(\n pluginRoute?.clientPath ? contract : namespace,\n pluginRoute?.clientPath ? types : namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n pluginRoute?.clientPath,\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction | BrickClientSocket,\n type: string,\n clientPath?: readonly string[],\n) {\n const segments = clientPath ?? metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n return `BrickClientAction<${input}, ${output}, ${errorsType(errors)}>`;\n}\n\nfunction errorsType(errors: Record<string, unknown> | undefined): string {\n const codes = Object.keys(errors ?? {});\n return codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nclass SchemaTypes {\n private readonly aliases = new Map<string, string>();\n private readonly names = new Set([\n \"AppContract\",\n \"BrickClientAction\",\n \"BrickClientSocket\",\n \"contract\",\n ]);\n\n // Internal tokens cannot occur in JSON-escaped property names or literals.\n private readonly fragments: { body: string; size: number; hash: string }[] =\n [];\n private readonly fragmentIds = new Map<string, number>();\n\n private fragment(body: string): string {\n let id = this.fragmentIds.get(body);\n if (id === undefined) {\n id = this.fragments.length;\n const size =\n body.replace(/\\0(\\d+)\\0/g, \"\").length +\n [...body.matchAll(/\\0(\\d+)\\0/g)].reduce(\n (total, match) => total + this.fragments[Number(match[1])]!.size,\n 0,\n );\n const shape = body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => this.fragments[Number(child)]!.hash,\n );\n const hash = createHash(\"sha256\").update(shape).digest(\"hex\");\n this.fragments.push({ body, size, hash });\n this.fragmentIds.set(body, id);\n }\n return `\\0${id}\\0`;\n }\n\n renderContract(contract: string): string {\n const uses = this.fragments.map(() => 0);\n const count = (body: string, multiplier: number) => {\n for (const match of body.matchAll(/\\0(\\d+)\\0/g))\n uses[Number(match[1])]! += multiplier;\n };\n count(contract, 1);\n for (const body of this.aliases.values()) count(body, 1);\n // Whether naming a type saves more text than its declaration costs.\n const worthSharing = (id: number, size: number, name: string) =>\n uses[id]! > 1 &&\n (uses[id]! - 1) * size >\n uses[id]! * name.length + `export type ${name} = ;\\n\\n`.length;\n const shared = new Map<number, string>();\n // Parents are interned after their children. Once a parent is shared, its\n // children occur only once in its declaration, avoiding overlapping savings.\n for (let id = this.fragments.length - 1; id >= 0; id--) {\n const { body, size, hash } = this.fragments[id]!;\n const nameBase = `BrickSchema_${hash.slice(0, 12)}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) name = `${nameBase}_${suffix++}`;\n if (worthSharing(id, size, name)) {\n this.names.add(name);\n shared.set(id, name);\n }\n count(body, shared.has(id) ? 1 : uses[id]!);\n }\n const rendered: string[] = [];\n const declarations: string[] = [];\n for (let id = 0; id < this.fragments.length; id++) {\n const body = this.fragments[id]!.body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => rendered[Number(child)]!,\n );\n const name = shared.get(id);\n // Child aliases can make a parent too small to justify sharing it.\n if (name && worthSharing(id, body.length, name)) {\n declarations.push(`export type ${name} = ${body};\\n\\n`);\n rendered.push(name);\n } else rendered.push(body);\n }\n const render = (body: string) =>\n body.replace(/\\0(\\d+)\\0/g, (_, id) => rendered[Number(id)]!);\n return (\n declarations.join(\"\") +\n [...this.aliases]\n .map(([name, type]) => `export type ${name} = ${render(type)};\\n\\n`)\n .join(\"\") +\n `export type AppContract = ${render(contract)};`\n );\n }\n\n generate(root: any): string {\n // IDs belong to this schema document. Separate actions may reuse the same ID.\n const ids = new Map<string, any>();\n const references: { ref: string; base: any }[] = [];\n const resources = new Map<unknown, any>();\n const active = new Set<unknown>();\n const visit = (schema: any, base: any) => {\n if (!schema || typeof schema !== \"object\" || active.has(schema)) return;\n const currentBase =\n typeof schema.$id === \"string\" && schema.$id ? schema : base;\n if (!resources.has(schema)) resources.set(schema, currentBase);\n if (typeof schema.$ref === \"string\")\n references.push({ ref: schema.$ref, base: currentBase });\n active.add(schema);\n try {\n if (typeof schema.$id === \"string\" && schema.$id)\n ids.set(schema.$id, schema);\n for (const key of [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n ]) {\n for (const child of Object.values(schema[key] ?? {}))\n visit(child, currentBase);\n }\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n for (const child of schema[key] ?? []) visit(child, currentBase);\n }\n for (const key of [\"items\", \"additionalProperties\", \"not\"]) {\n if (Array.isArray(schema[key]))\n schema[key].forEach((child: any) => visit(child, currentBase));\n else visit(schema[key], currentBase);\n }\n } finally {\n active.delete(schema);\n }\n };\n visit(root, root);\n\n const resolve = (reference: string, base: any): any => {\n const hashIndex = reference.indexOf(\"#\");\n const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);\n const fragment =\n hashIndex === -1 ? undefined : reference.slice(hashIndex + 1);\n let target = id ? ids.get(id) : base;\n if (fragment) {\n if (!fragment.startsWith(\"/\")) return undefined;\n try {\n for (const part of decodeURIComponent(fragment).slice(1).split(\"/\")) {\n const key = part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (!target || !Object.hasOwn(target, key)) return undefined;\n target = target[key];\n }\n } catch {\n return undefined;\n }\n }\n return typeof target === \"boolean\" ||\n (target && typeof target === \"object\")\n ? target\n : undefined;\n };\n const targets = new Set(\n references\n .map(({ ref, base }) => resolve(ref, base))\n .filter((value) => value !== undefined),\n );\n const names = new Map<any, string>();\n const emit = (schema: any, inline = false, base: any = root): string => {\n const body = emitInline(schema, inline, base);\n // References already have document-scoped aliases; scalars stay inline.\n if (\n schema &&\n !schema.$ref &&\n !Object.hasOwn(schema, \"const\") &&\n (schema.anyOf ||\n schema.oneOf ||\n schema.allOf ||\n schema.enum?.length > 1 ||\n schema.type === \"array\" ||\n schema.type === \"object\")\n )\n return this.fragment(body);\n return body;\n };\n const emitInline = (schema: any, inline: boolean, base: any): string => {\n if (schema === undefined || schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n const currentBase =\n schema &&\n typeof schema === \"object\" &&\n typeof schema.$id === \"string\" &&\n schema.$id\n ? schema\n : base;\n if (!inline && targets.has(schema)) {\n const existing = names.get(schema);\n if (existing) return existing;\n // Titles provide readable names; generated TypeBox IDs remain usable fallbacks.\n const hint = schema.title ?? schema.$id ?? \"Schema\";\n let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, \"_\");\n if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;\n nameBase = `Brick${nameBase}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) {\n name = `${nameBase}_${suffix}`;\n suffix += 1;\n }\n this.names.add(name);\n names.set(schema, name);\n // names is reserved before the body is rendered, so recursive refs terminate.\n this.aliases.set(name, emit(schema, true, currentBase));\n return name;\n }\n if (schema.$ref) {\n const target = resolve(schema.$ref, currentBase);\n if (target === undefined)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n const targetBase =\n target && typeof target === \"object\"\n ? (resources.get(target) ?? root)\n : currentBase;\n return emit(target, false, targetBase);\n }\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \") || \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map((child: any) => emit(child, false, currentBase)).join(\" | \")})`;\n if (schema.allOf)\n return `(${schema.allOf.map((child: any) => emit(child, false, currentBase)).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n if (Array.isArray(schema.items))\n return `[${schema.items.map((child: any) => emit(child, false, currentBase)).join(\", \")}]`;\n return `Array<${emit(schema.items, false, currentBase)}>`;\n case \"object\": {\n const entries = Object.entries(schema.properties ?? {});\n const properties = entries.map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${emit(value, false, currentBase)};`,\n );\n // additionalProperties applies to keys matched by neither properties\n // nor patternProperties, so union it instead of discarding it.\n const indexParts = Object.values(schema.patternProperties ?? {}).map(\n (child) => emit(child, false, currentBase),\n );\n if (schema.additionalProperties) {\n indexParts.push(\n emit(schema.additionalProperties, false, currentBase),\n );\n }\n let indexType: string | undefined;\n if (indexParts.length) {\n // TS index signatures must also cover declared keys, so widen\n // with their types; otherwise the intersection below rejects\n // valid values. Over-approximating is safe: the server validates.\n for (const [, value] of entries) {\n const propType = emit(value, false, currentBase);\n if (!indexParts.includes(propType)) indexParts.push(propType);\n }\n indexType = indexParts.join(\" | \");\n }\n const object = `{ ${properties.join(\" \")} }`;\n if (indexType) {\n const index = `{ [key: string]: ${indexType} }`;\n return properties.length ? `${object} & ${index}` : index;\n }\n return object;\n }\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n };\n return emit(root);\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { generateClientContract } from \"./client-contract\";\nimport { requireBrickApp } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\n\n/** Generate a client contract without loading Vite or starting a server. */\nexport async function writeClientContract(entry: string, output: string) {\n checkContractOutput(entry, output);\n await writeAppContract(await loadBrickApp(entry), entry, output);\n return resolve(output);\n}\n\nfunction checkContractOutput(entry: string, output: string) {\n if (resolve(output) === resolve(entry))\n throw new Error(\"Brick: contract output must not overwrite the app entry.\");\n}\n\n/** Write the browser contract of the entry's `app` to `output`. */\nexport async function writeAppContract(\n app: unknown,\n entry: string,\n output: string,\n) {\n checkContractOutput(entry, output);\n await writeFileIfChanged(\n resolve(output),\n generateClientContract(requireBrickApp(app)),\n );\n}\n\n/** Begins the name of the temporary file `writeFileIfChanged` renames into place; watchers skip it. */\nexport const TEMPORARY_FILE_PREFIX = \".brick-write-\";\n\n/** Atomically replace a generated file whose text changed, leaving it (and its timestamp) alone otherwise. */\nexport async function writeFileIfChanged(output: string, source: string) {\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous !== source) {\n await mkdir(dirname(output), { recursive: true });\n const temporary = join(\n dirname(output),\n `${TEMPORARY_FILE_PREFIX}${randomUUID()}.tmp`,\n );\n try {\n await writeFile(temporary, source, { flag: \"wx\" });\n await rename(tempor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,SACE,MAAM,IAAI,MAAM,sCAAsC,OAAO,KAAK,EAAE;GACxE;EACF;EACA,OAAO,KAAK,IAAI;CAClB;AACF;;;ACxcA,eAAsB,oBAAoB,OAAe,QAAgB;CACvE,oBAAoB,OAAO,MAAM;CACjC,MAAM,iBAAiB,MAAM,aAAa,KAAK,GAAG,OAAO,MAAM;CAC/D,OAAO,QAAQ,MAAM;AACvB;AAEA,SAAS,oBAAoB,OAAe,QAAgB;CAC1D,IAAI,QAAQ,MAAM,MAAM,QAAQ,KAAK,GACnC,MAAM,IAAI,MAAM,0DAA0D;AAC9E;;AAGA,eAAsB,iBACpB,KACA,OACA,QACA;CACA,oBAAoB,OAAO,MAAM;CACjC,MAAM,mBACJ,QAAQ,MAAM,GACd,uBAAuB,gBAAgB,GAAG,CAAC,CAC7C;AACF;;AAGA,MAAa,wBAAwB;;AAGrC,eAAsB,mBAAmB,QAAgB,QAAgB;CAKvE,IAAI,MAJmB,SAAS,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAU;EAC/D,IAAI,MAAM,SAAS,UAAU,MAAM;CAErC,CAAC,MACgB,QAAQ;EACvB,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,MAAM,YAAY,KAChB,QAAQ,MAAM,GACd,GAAG,wBAAwB,WAAW,EAAE,KAC1C;EACA,IAAI;GACF,MAAM,UAAU,WAAW,QAAQ,EAAE,MAAM,KAAK,CAAC;GACjD,MAAM,OAAO,WAAW,MAAM;EAChC,UAAU;GACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;EACrC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"client-contract-file.js","names":[],"sources":["../src/app-entry.ts","../src/client-contract.ts","../src/client-contract-file.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { requireBrickApp, type BrickApp } from \"@brickkit/core\";\nimport { ConfigError } from \"./config\";\nimport { registerWorkflowTransform } from \"./workflows\";\n\n/**\n * Import an app entry and return its default export. `run`: the app will run\n * in this process, so workflow files are transformed as they load.\n *\n * @throws When the file does not exist.\n */\nexport async function importEntry(\n entry: string,\n options: { run?: boolean } = {},\n): Promise<unknown> {\n const file = resolve(entry);\n if (!existsSync(file))\n throw new ConfigError(`[Brick-TS] Error: Entry file not found: ${file}`);\n if (options.run) await registerWorkflowTransform();\n return (await import(pathToFileURL(file).href)).default;\n}\n\n/**\n * Import an app entry to inspect it: to build it, or to read its routes. The app\n * is not run, so what creating it opened is released here: a workflow world\n * holds Redis connections that would keep the command from exiting.\n */\nexport async function loadBrickApp(entry: string): Promise<BrickApp> {\n const app = requireBrickApp(await importEntry(entry));\n await app.events?.stop();\n return app;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n actionOwners,\n getActionRoute,\n getPluginActionRoute,\n serializeSocketSchema,\n type Service,\n} from \"@brickkit/core\";\nimport type {\n BrickClientAction,\n BrickClientSocket,\n} from \"@brickkit/core/client\";\nimport type { BrickApp } from \"@brickkit/core\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const schemas = new SchemaTypes();\n for (const service of services) {\n addServiceActions(service, prefix, contract, types, schemas);\n for (const socket of service.listSockets()) {\n const route = app.definition.sockets.find(\n (route) =>\n route.service === service.name && route.name === socket.schema.name,\n );\n if (!route)\n throw new Error(\n `Brick client: missing socket route '${service.name}.${socket.schema.name}'`,\n );\n try {\n const metadata: BrickClientSocket = {\n kind: \"socket\",\n name: socket.schema.name,\n serviceName: service.name,\n config: { path: route.path },\n output: Object.fromEntries(\n Object.entries(socket.output).map(([key, schema]) => [\n key,\n serializeSocketSchema(schema),\n ]),\n ),\n };\n const payloads = (map: typeof socket.input) =>\n `{ ${Object.entries(map)\n .map(\n ([key, schema]) =>\n `${JSON.stringify(key)}: ${schemas.generate(schema)}`,\n )\n .join(\"; \")} }`;\n insertAction(\n contract[service.name],\n types[service.name],\n metadata,\n `BrickClientSocket<${payloads(socket.input)}, ${payloads(socket.output)}, ${errorsType(socket.errors)}>`,\n );\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate socket '${service.name}.${socket.schema.name}': ${String(error)}`,\n );\n }\n }\n }\n return `// Generated by Brick. Do not edit.\nimport type { BrickClientAction${app.definition.sockets.length ? \", BrickClientSocket\" : \"\"} } from \"@brickkit/core/client\";\n\n${schemas.renderContract(namespaceType(types))}\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n\n// Types useService(service) on the server from this contract.\ndeclare module \"@brickkit/core/client\" {\n interface BrickServices extends AppContract {}\n}\n`;\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n schemas: SchemaTypes,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n const route = getActionRoute(action, prefix);\n if (route === false) continue;\n const pluginRoute = getPluginActionRoute(action, prefix) || undefined;\n const { input, output, errors } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemas.generate(input) : \"unknown\";\n outputType = output ? schemas.generate(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n ...actionOwners(action),\n config: { path: route.path, method: route.method },\n };\n insertAction(\n pluginRoute?.clientPath ? contract : namespace,\n pluginRoute?.clientPath ? types : namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n pluginRoute?.clientPath,\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction | BrickClientSocket,\n type: string,\n clientPath?: readonly string[],\n) {\n const segments = clientPath ?? metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n return `BrickClientAction<${input}, ${output}, ${errorsType(errors)}>`;\n}\n\nfunction errorsType(errors: Record<string, unknown> | undefined): string {\n const codes = Object.keys(errors ?? {});\n return codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nclass SchemaTypes {\n private readonly aliases = new Map<string, string>();\n private readonly names = new Set([\n \"AppContract\",\n \"BrickClientAction\",\n \"BrickClientSocket\",\n \"contract\",\n ]);\n\n // Internal tokens cannot occur in JSON-escaped property names or literals.\n private readonly fragments: { body: string; size: number; hash: string }[] =\n [];\n private readonly fragmentIds = new Map<string, number>();\n\n private fragment(body: string): string {\n let id = this.fragmentIds.get(body);\n if (id === undefined) {\n id = this.fragments.length;\n const size =\n body.replace(/\\0(\\d+)\\0/g, \"\").length +\n [...body.matchAll(/\\0(\\d+)\\0/g)].reduce(\n (total, match) => total + this.fragments[Number(match[1])]!.size,\n 0,\n );\n const shape = body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => this.fragments[Number(child)]!.hash,\n );\n const hash = createHash(\"sha256\").update(shape).digest(\"hex\");\n this.fragments.push({ body, size, hash });\n this.fragmentIds.set(body, id);\n }\n return `\\0${id}\\0`;\n }\n\n renderContract(contract: string): string {\n const uses = this.fragments.map(() => 0);\n const count = (body: string, multiplier: number) => {\n for (const match of body.matchAll(/\\0(\\d+)\\0/g))\n uses[Number(match[1])]! += multiplier;\n };\n count(contract, 1);\n for (const body of this.aliases.values()) count(body, 1);\n // Whether naming a type saves more text than its declaration costs.\n const worthSharing = (id: number, size: number, name: string) =>\n uses[id]! > 1 &&\n (uses[id]! - 1) * size >\n uses[id]! * name.length + `export type ${name} = ;\\n\\n`.length;\n const shared = new Map<number, string>();\n // Parents are interned after their children. Once a parent is shared, its\n // children occur only once in its declaration, avoiding overlapping savings.\n for (let id = this.fragments.length - 1; id >= 0; id--) {\n const { body, size, hash } = this.fragments[id]!;\n const nameBase = `BrickSchema_${hash.slice(0, 12)}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) name = `${nameBase}_${suffix++}`;\n if (worthSharing(id, size, name)) {\n this.names.add(name);\n shared.set(id, name);\n }\n count(body, shared.has(id) ? 1 : uses[id]!);\n }\n const rendered: string[] = [];\n const declarations: string[] = [];\n for (let id = 0; id < this.fragments.length; id++) {\n const body = this.fragments[id]!.body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => rendered[Number(child)]!,\n );\n const name = shared.get(id);\n // Child aliases can make a parent too small to justify sharing it.\n if (name && worthSharing(id, body.length, name)) {\n declarations.push(`export type ${name} = ${body};\\n\\n`);\n rendered.push(name);\n } else rendered.push(body);\n }\n const render = (body: string) =>\n body.replace(/\\0(\\d+)\\0/g, (_, id) => rendered[Number(id)]!);\n return (\n declarations.join(\"\") +\n [...this.aliases]\n .map(([name, type]) => `export type ${name} = ${render(type)};\\n\\n`)\n .join(\"\") +\n `export type AppContract = ${render(contract)};`\n );\n }\n\n generate(root: any): string {\n // IDs belong to this schema document. Separate actions may reuse the same ID.\n const ids = new Map<string, any>();\n const references: { ref: string; base: any }[] = [];\n const resources = new Map<unknown, any>();\n const active = new Set<unknown>();\n const visit = (schema: any, base: any) => {\n if (!schema || typeof schema !== \"object\" || active.has(schema)) return;\n const currentBase =\n typeof schema.$id === \"string\" && schema.$id ? schema : base;\n if (!resources.has(schema)) resources.set(schema, currentBase);\n if (typeof schema.$ref === \"string\")\n references.push({ ref: schema.$ref, base: currentBase });\n active.add(schema);\n try {\n if (typeof schema.$id === \"string\" && schema.$id)\n ids.set(schema.$id, schema);\n for (const key of [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n ]) {\n for (const child of Object.values(schema[key] ?? {}))\n visit(child, currentBase);\n }\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n for (const child of schema[key] ?? []) visit(child, currentBase);\n }\n for (const key of [\"items\", \"additionalProperties\", \"not\"]) {\n if (Array.isArray(schema[key]))\n schema[key].forEach((child: any) => visit(child, currentBase));\n else visit(schema[key], currentBase);\n }\n } finally {\n active.delete(schema);\n }\n };\n visit(root, root);\n\n const resolve = (reference: string, base: any): any => {\n const hashIndex = reference.indexOf(\"#\");\n const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);\n const fragment =\n hashIndex === -1 ? undefined : reference.slice(hashIndex + 1);\n let target = id ? ids.get(id) : base;\n if (fragment) {\n if (!fragment.startsWith(\"/\")) return undefined;\n try {\n for (const part of decodeURIComponent(fragment).slice(1).split(\"/\")) {\n const key = part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (!target || !Object.hasOwn(target, key)) return undefined;\n target = target[key];\n }\n } catch {\n return undefined;\n }\n }\n return typeof target === \"boolean\" ||\n (target && typeof target === \"object\")\n ? target\n : undefined;\n };\n const targets = new Set(\n references\n .map(({ ref, base }) => resolve(ref, base))\n .filter((value) => value !== undefined),\n );\n const names = new Map<any, string>();\n const emit = (schema: any, inline = false, base: any = root): string => {\n const body = emitInline(schema, inline, base);\n // References already have document-scoped aliases; scalars stay inline.\n if (\n schema &&\n !schema.$ref &&\n !Object.hasOwn(schema, \"const\") &&\n (schema.anyOf ||\n schema.oneOf ||\n schema.allOf ||\n schema.enum?.length > 1 ||\n schema.type === \"array\" ||\n schema.type === \"object\")\n )\n return this.fragment(body);\n return body;\n };\n const emitInline = (schema: any, inline: boolean, base: any): string => {\n if (schema === undefined || schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n const currentBase =\n schema &&\n typeof schema === \"object\" &&\n typeof schema.$id === \"string\" &&\n schema.$id\n ? schema\n : base;\n if (!inline && targets.has(schema)) {\n const existing = names.get(schema);\n if (existing) return existing;\n // Titles provide readable names; generated TypeBox IDs remain usable fallbacks.\n const hint = schema.title ?? schema.$id ?? \"Schema\";\n let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, \"_\");\n if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;\n nameBase = `Brick${nameBase}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) {\n name = `${nameBase}_${suffix}`;\n suffix += 1;\n }\n this.names.add(name);\n names.set(schema, name);\n // names is reserved before the body is rendered, so recursive refs terminate.\n this.aliases.set(name, emit(schema, true, currentBase));\n return name;\n }\n if (schema.$ref) {\n const target = resolve(schema.$ref, currentBase);\n if (target === undefined)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n const targetBase =\n target && typeof target === \"object\"\n ? (resources.get(target) ?? root)\n : currentBase;\n return emit(target, false, targetBase);\n }\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \") || \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map((child: any) => emit(child, false, currentBase)).join(\" | \")})`;\n if (schema.allOf)\n return `(${schema.allOf.map((child: any) => emit(child, false, currentBase)).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return schema.format === \"binary\" ? \"Blob\" : \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n if (Array.isArray(schema.items))\n return `[${schema.items.map((child: any) => emit(child, false, currentBase)).join(\", \")}]`;\n return `Array<${emit(schema.items, false, currentBase)}>`;\n case \"object\": {\n const entries = Object.entries(schema.properties ?? {});\n const properties = entries.map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${emit(value, false, currentBase)};`,\n );\n // additionalProperties applies to keys matched by neither properties\n // nor patternProperties, so union it instead of discarding it.\n const indexParts = Object.values(schema.patternProperties ?? {}).map(\n (child) => emit(child, false, currentBase),\n );\n if (schema.additionalProperties) {\n indexParts.push(\n emit(schema.additionalProperties, false, currentBase),\n );\n }\n let indexType: string | undefined;\n if (indexParts.length) {\n // TS index signatures must also cover declared keys, so widen\n // with their types; otherwise the intersection below rejects\n // valid values. Over-approximating is safe: the server validates.\n for (const [, value] of entries) {\n const propType = emit(value, false, currentBase);\n if (!indexParts.includes(propType)) indexParts.push(propType);\n }\n indexType = indexParts.join(\" | \");\n }\n const object = `{ ${properties.join(\" \")} }`;\n if (indexType) {\n const index = `{ [key: string]: ${indexType} }`;\n return properties.length ? `${object} & ${index}` : index;\n }\n return object;\n }\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n };\n return emit(root);\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { generateClientContract } from \"./client-contract\";\nimport { requireBrickApp } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\n\n/** Generate a client contract without loading Vite or starting a server. */\nexport async function writeClientContract(entry: string, output: string) {\n checkContractOutput(entry, output);\n await writeAppContract(await loadBrickApp(entry), entry, output);\n return resolve(output);\n}\n\nfunction checkContractOutput(entry: string, output: string) {\n if (resolve(output) === resolve(entry))\n throw new Error(\"Brick: contract output must not overwrite the app entry.\");\n}\n\n/** Write the browser contract of the entry's `app` to `output`. */\nexport async function writeAppContract(\n app: unknown,\n entry: string,\n output: string,\n) {\n checkContractOutput(entry, output);\n await writeFileIfChanged(\n resolve(output),\n generateClientContract(requireBrickApp(app)),\n );\n}\n\n/** Begins the name of the temporary file `writeFileIfChanged` renames into place; watchers skip it. */\nexport const TEMPORARY_FILE_PREFIX = \".brick-write-\";\n\n/** Atomically replace a generated file whose text changed, leaving it (and its timestamp) alone otherwise. */\nexport async function writeFileIfChanged(output: string, source: string) {\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous !== source) {\n await mkdir(dirname(output), { recursive: true });\n const temporary = join(\n dirname(output),\n `${TEMPORARY_FILE_PREFIX}${randomUUID()}.tmp`,\n );\n try {\n await writeFile(temporary, source, { flag: \"wx\" });\n await rename(temporary, output);\n } finally {\n await rm(temporary, { force: true });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAaA,eAAsB,YACpB,OACA,UAA6B,CAAC,GACZ;CAClB,MAAM,OAAO,QAAQ,KAAK;CAC1B,IAAI,CAAC,WAAW,IAAI,GAClB,MAAM,IAAI,YAAY,2CAA2C,MAAM;CACzE,IAAI,QAAQ,KAAK,MAAM,0BAA0B;CACjD,QAAQ,MAAM,OAAO,cAAc,IAAI,CAAC,CAAC,MAAA,CAAO;AAClD;;;;;;AAOA,eAAsB,aAAa,OAAkC;CACnE,MAAM,MAAM,gBAAgB,MAAM,YAAY,KAAK,CAAC;CACpD,MAAM,IAAI,QAA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QACA;CACA,oBAAoB,OAAO,MAAM;CACjC,MAAM,mBACJ,QAAQ,MAAM,GACd,uBAAuB,gBAAgB,GAAG,CAAC,CAC7C;AACF;;AAGA,MAAa,wBAAwB;;AAGrC,eAAsB,mBAAmB,QAAgB,QAAgB;CAKvE,IAAI,MAJmB,SAAS,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAU;EAC/D,IAAI,MAAM,SAAS,UAAU,MAAM;CAErC,CAAC,MACgB,QAAQ;EACvB,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,MAAM,YAAY,KAChB,QAAQ,MAAM,GACd,GAAG,wBAAwB,WAAW,EAAE,KAC1C;EACA,IAAI;GACF,MAAM,UAAU,WAAW,QAAQ,EAAE,MAAM,KAAK,CAAC;GACjD,MAAM,OAAO,WAAW,MAAM;EAChC,UAAU;GACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;EACrC;CACF;AACF"}
|
package/dist/dashboard-host.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { n as ConfigError, r as DEFAULT_DASHBOARD_PORT } from "./config2.js";
|
|
2
|
-
import { a as INSPECTOR_TOKEN_HEADER, c as SHARED_MODULES, d as assetUrl, f as decode, g as
|
|
2
|
+
import { _ as matchRoute, a as INSPECTOR_TOKEN_HEADER, c as SHARED_MODULES, d as assetUrl, f as decode, g as isExternalHref, h as docsHref, i as DOCS_PATHS, l as SPAN, m as docsFileUrl, n as ATTR, o as LIVE_LIMITS, s as ROUTES, t as ASSETS, u as THEME_STORAGE_KEY } from "./dashboard-protocol.js";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { existsSync, mkdirSync, watch, writeFileSync } from "node:fs";
|
|
5
5
|
import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { DASHBOARD_IDENTITY_HEADER, signDashboardIdentity } from "@brickkit/core";
|
|
6
7
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
8
|
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
8
9
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
@@ -1158,6 +1159,7 @@ function webRequest(request) {
|
|
|
1158
1159
|
headers
|
|
1159
1160
|
});
|
|
1160
1161
|
}
|
|
1162
|
+
const isIdentity = (value) => typeof value === "object" && value !== null && !(value instanceof Response) && typeof value.user?.id === "string";
|
|
1161
1163
|
const refusal = (status, body, headers = {}) => ({
|
|
1162
1164
|
allowed: false,
|
|
1163
1165
|
status,
|
|
@@ -1169,7 +1171,7 @@ const refusal = (status, body, headers = {}) => ({
|
|
|
1169
1171
|
});
|
|
1170
1172
|
/**
|
|
1171
1173
|
* The check for the dashboard's requests. A request passes with a valid token,
|
|
1172
|
-
* or when the app's `authorize` returns `true
|
|
1174
|
+
* or when the app's `authorize` returns `true` or an identity (`{ user }`). Anything else is answered:
|
|
1173
1175
|
* what `authorize` returned if it returned a `Response`, else 401 (with a
|
|
1174
1176
|
* browser sign-in prompt when tokens are in use), and 503 when `authorize`
|
|
1175
1177
|
* threw or ran out of time, since a check that cannot answer must not let
|
|
@@ -1179,7 +1181,10 @@ function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS
|
|
|
1179
1181
|
const tokens = auth.token === void 0 ? [] : typeof auth.token === "string" ? [auth.token] : [...auth.token];
|
|
1180
1182
|
const prompt = tokens.length > 0 ? { "www-authenticate": "Basic realm=\"Brick dashboard\", charset=\"UTF-8\"" } : {};
|
|
1181
1183
|
return async (request) => {
|
|
1182
|
-
if (tokens.length > 0 && isToken(credential(request), tokens)) return {
|
|
1184
|
+
if (tokens.length > 0 && isToken(credential(request), tokens)) return {
|
|
1185
|
+
allowed: true,
|
|
1186
|
+
identity: {}
|
|
1187
|
+
};
|
|
1183
1188
|
if (!auth.authorize) return refusal(401, "Unauthorized", prompt);
|
|
1184
1189
|
let decision;
|
|
1185
1190
|
let timer;
|
|
@@ -1193,7 +1198,17 @@ function createAccess(auth, onError = () => {}, timeoutMs = AUTHORIZE_TIMEOUT_MS
|
|
|
1193
1198
|
} finally {
|
|
1194
1199
|
clearTimeout(timer);
|
|
1195
1200
|
}
|
|
1196
|
-
if (decision === true) return {
|
|
1201
|
+
if (decision === true) return {
|
|
1202
|
+
allowed: true,
|
|
1203
|
+
identity: {}
|
|
1204
|
+
};
|
|
1205
|
+
if (isIdentity(decision)) return {
|
|
1206
|
+
allowed: true,
|
|
1207
|
+
identity: { user: {
|
|
1208
|
+
id: decision.user.id,
|
|
1209
|
+
...typeof decision.user.name === "string" ? { name: decision.user.name } : {}
|
|
1210
|
+
} }
|
|
1211
|
+
};
|
|
1197
1212
|
if (decision instanceof Response) {
|
|
1198
1213
|
const headers = {};
|
|
1199
1214
|
decision.headers.forEach((value, name) => {
|
|
@@ -1289,12 +1304,14 @@ function startDevDashboard(options) {
|
|
|
1289
1304
|
await health(response);
|
|
1290
1305
|
return;
|
|
1291
1306
|
}
|
|
1307
|
+
let identity = {};
|
|
1292
1308
|
if (access) {
|
|
1293
1309
|
const decision = await access(request);
|
|
1294
1310
|
if (!decision.allowed) {
|
|
1295
1311
|
send(response, decision.status, decision.body, decision.headers);
|
|
1296
1312
|
return;
|
|
1297
1313
|
}
|
|
1314
|
+
identity = decision.identity;
|
|
1298
1315
|
}
|
|
1299
1316
|
if (!route || production && !servedInProduction(route)) {
|
|
1300
1317
|
send(response, 404, "Not found");
|
|
@@ -1304,7 +1321,7 @@ function startDevDashboard(options) {
|
|
|
1304
1321
|
send(response, 403, "Forbidden");
|
|
1305
1322
|
return;
|
|
1306
1323
|
}
|
|
1307
|
-
await handlers[route](request, response, url);
|
|
1324
|
+
await handlers[route](request, response, url, identity);
|
|
1308
1325
|
}
|
|
1309
1326
|
function servedInProduction(route) {
|
|
1310
1327
|
const served = ROUTES[route].production;
|
|
@@ -1365,6 +1382,7 @@ function startDevDashboard(options) {
|
|
|
1365
1382
|
frameOnlyHere(response);
|
|
1366
1383
|
return inspector(request, response, url);
|
|
1367
1384
|
},
|
|
1385
|
+
schedules: (request, response, url) => inspector(request, response, url),
|
|
1368
1386
|
ingest,
|
|
1369
1387
|
restart(request, response) {
|
|
1370
1388
|
if (!options.restart) {
|
|
@@ -1460,7 +1478,7 @@ function startDevDashboard(options) {
|
|
|
1460
1478
|
async function inspector(request, response, url) {
|
|
1461
1479
|
const target = options.store.inspectorTarget();
|
|
1462
1480
|
if (!target) {
|
|
1463
|
-
send(response, 503, "The workflow inspector
|
|
1481
|
+
send(response, 503, "The workflow inspector and schedules are not being served. The app may be restarting, or it may have neither workflows nor schedules.", { "content-type": "text/plain; charset=utf-8" });
|
|
1464
1482
|
return;
|
|
1465
1483
|
}
|
|
1466
1484
|
if (!isBodyless(request) && !fromOwnPage(request)) {
|
|
@@ -1472,9 +1490,10 @@ function startDevDashboard(options) {
|
|
|
1472
1490
|
/**
|
|
1473
1491
|
* Pass `/app/*` to the app, so the extension's pages read it from the
|
|
1474
1492
|
* dashboard's own origin. Only the dashboard's page may use it, as with the
|
|
1475
|
-
* API proxy. A credential for the dashboard itself is not passed on
|
|
1493
|
+
* API proxy. A credential for the dashboard itself is not passed on; who the
|
|
1494
|
+
* dashboard let in is, signed, for `ctx.dashboard` and `dashboardUser()`.
|
|
1476
1495
|
*/
|
|
1477
|
-
async function app(request, response, url) {
|
|
1496
|
+
async function app(request, response, url, identity) {
|
|
1478
1497
|
if (!fromOwnPage(request)) {
|
|
1479
1498
|
send(response, 403, "Forbidden");
|
|
1480
1499
|
return;
|
|
@@ -1487,6 +1506,7 @@ function startDevDashboard(options) {
|
|
|
1487
1506
|
frameOnlyHere(response);
|
|
1488
1507
|
await forward(request, response, `${new URL(appUrl).origin}${url.pathname.slice(ROUTES.app.path.length) || "/"}${url.search}`, (headers) => {
|
|
1489
1508
|
if (access) headers.delete("authorization");
|
|
1509
|
+
headers.set(DASHBOARD_IDENTITY_HEADER, signDashboardIdentity(identity));
|
|
1490
1510
|
}, "Could not reach the app.");
|
|
1491
1511
|
}
|
|
1492
1512
|
/**
|
|
@@ -1704,7 +1724,7 @@ function frameOnlyHere(response) {
|
|
|
1704
1724
|
function forwardedHeaders(request) {
|
|
1705
1725
|
const headers = new Headers();
|
|
1706
1726
|
for (const [name, value] of Object.entries(request.headers)) {
|
|
1707
|
-
if (value === void 0 || NOT_FORWARDED.has(name)) continue;
|
|
1727
|
+
if (value === void 0 || NOT_FORWARDED.has(name) || name === DASHBOARD_IDENTITY_HEADER) continue;
|
|
1708
1728
|
if (name.startsWith("sec-")) continue;
|
|
1709
1729
|
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
1710
1730
|
}
|
|
@@ -2194,17 +2214,18 @@ var DevTelemetryStore = class {
|
|
|
2194
2214
|
});
|
|
2195
2215
|
}
|
|
2196
2216
|
/**
|
|
2197
|
-
* Set where the app serves its workflow inspector, or
|
|
2198
|
-
* stops. The address stays here: the snapshot says only
|
|
2217
|
+
* Set where the app serves its workflow inspector and schedules, or
|
|
2218
|
+
* `undefined` when it stops. The address stays here: the snapshot says only
|
|
2219
|
+
* whether there is a workflow inspector.
|
|
2199
2220
|
*/
|
|
2200
2221
|
setInspector(target) {
|
|
2201
2222
|
this.#inspector = target;
|
|
2202
2223
|
this.#emit({
|
|
2203
2224
|
type: "inspector",
|
|
2204
|
-
inspector: Boolean(target)
|
|
2225
|
+
inspector: Boolean(target?.workflows)
|
|
2205
2226
|
});
|
|
2206
2227
|
}
|
|
2207
|
-
/** Where the dashboard proxies the workflow inspector, when the app serves
|
|
2228
|
+
/** Where the dashboard proxies the workflow inspector and schedules, when the app serves them. */
|
|
2208
2229
|
inspectorTarget() {
|
|
2209
2230
|
return this.#inspector;
|
|
2210
2231
|
}
|
|
@@ -2224,7 +2245,7 @@ var DevTelemetryStore = class {
|
|
|
2224
2245
|
architecture: this.#architecture,
|
|
2225
2246
|
api: this.#api,
|
|
2226
2247
|
docs: this.#docs,
|
|
2227
|
-
inspector: Boolean(this.#inspector)
|
|
2248
|
+
inspector: Boolean(this.#inspector?.workflows)
|
|
2228
2249
|
};
|
|
2229
2250
|
}
|
|
2230
2251
|
subscribe(listener) {
|