@brickkit/cli 0.7.0 → 0.7.2
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/README.md +30 -0
- package/dist/app-entry.js +1 -0
- package/dist/app-entry2.js +12 -0
- package/dist/app-entry2.js.map +1 -0
- package/dist/bin.js +8 -30
- package/dist/bin.js.map +1 -1
- package/dist/build.js +2 -9
- package/dist/build.js.map +1 -1
- package/dist/client-contract-file.js +1 -0
- package/dist/client-contract-file2.js +34 -0
- package/dist/client-contract-file2.js.map +1 -0
- package/dist/client-contract.js +1 -268
- package/dist/client-contract2.js +268 -0
- package/dist/client-contract2.js.map +1 -0
- package/dist/dev-worker.js +25 -1
- package/dist/dev-worker.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/runner.js +64 -5
- package/dist/runner.js.map +1 -1
- package/dist/vite.js +31 -12
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
- package/dist/client-contract.js.map +0 -1
package/README.md
CHANGED
|
@@ -193,3 +193,33 @@ and rerun after changing backend definitions. You can add a package script:
|
|
|
193
193
|
Import the generated `contract` with `createBrickClient({ baseUrl, contract })`
|
|
194
194
|
as shown above. The command creates parent directories and leaves an unchanged
|
|
195
195
|
contract file untouched. Add the generated output to `.gitignore`.
|
|
196
|
+
|
|
197
|
+
## Coordinate backend and frontend development
|
|
198
|
+
|
|
199
|
+
For a separate frontend tool, generate the contract before its compiler starts:
|
|
200
|
+
|
|
201
|
+
```sh
|
|
202
|
+
brick dev src/app.ts --client frontend/src/contract.ts --frontend 'bun run --cwd frontend dev'
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
The app entry must default-export a BrickApp without calling `.listen()`.
|
|
206
|
+
Brick generates the initial contract, starts the frontend command once, and
|
|
207
|
+
restarts the backend on edits. Imported local dependencies outside the entry's
|
|
208
|
+
directory are watched too. Changes coalesce before restart; every restart evaluates
|
|
209
|
+
the app in a fresh process and generates the contract before starting the server.
|
|
210
|
+
Generation failures preserve the previous contract and print the error. The next
|
|
211
|
+
valid edit retries. Stopping `brick dev` stops its backend and frontend children.
|
|
212
|
+
`--client` also works without `--frontend` if another process owns the frontend.
|
|
213
|
+
|
|
214
|
+
For an embedded Vite app such as Pages, keep using `brickClient` in `vite.config.ts`.
|
|
215
|
+
Vite owns backend loading and frontend startup in that setup. It generates before
|
|
216
|
+
startup and production compilation, reloads the app definition graph, including imported service instances, and reports generation errors through its terminal and browser overlay.
|
|
217
|
+
A valid edit regenerates the contract after an error. Both integrations atomically
|
|
218
|
+
replace changed contracts and preserve unchanged files, so implementation-only
|
|
219
|
+
edits do not trigger frontend contract updates. Generated files are excluded from
|
|
220
|
+
regeneration triggers.
|
|
221
|
+
|
|
222
|
+
For non-Vite production builds and type checks, run `brick gen client` as the first
|
|
223
|
+
command in the build or typecheck script. It uses the same generator and atomic
|
|
224
|
+
writer as development. Keep startup jobs and listeners outside the app definition,
|
|
225
|
+
since all generation paths evaluate the entry.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { n as requireBrickApp } from "./app-entry2.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { requireBrickApp } from "@brickkit/core";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
//#region src/app-entry.ts
|
|
5
|
+
async function loadBrickApp(entry) {
|
|
6
|
+
const module = await import(pathToFileURL(resolve(entry)).href);
|
|
7
|
+
return requireBrickApp(module.default);
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { requireBrickApp as n, loadBrickApp as t };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=app-entry2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-entry2.js","names":[],"sources":["../src/app-entry.ts"],"sourcesContent":["import { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { isBrickApp, requireBrickApp, type BrickApp } from \"@brickkit/core\";\n\nexport { isBrickApp, requireBrickApp, type BrickApp };\n\nexport async function loadBrickApp(entry: string): Promise<BrickApp> {\n const module = await import(pathToFileURL(resolve(entry)).href);\n return requireBrickApp(module.default);\n}\n"],"mappings":";;;;AAMA,eAAsB,aAAa,OAAkC;CACnE,MAAM,SAAS,MAAM,OAAO,cAAc,QAAQ,KAAK,CAAC,CAAC,CAAC;CAC1D,OAAO,gBAAgB,OAAO,OAAO;AACvC"}
|
package/dist/bin.js
CHANGED
|
@@ -1,38 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
import { n as startDevServer, r as startProdServer } from "./runner.js";
|
|
3
|
-
import {
|
|
4
|
-
import { t as
|
|
3
|
+
import { t as loadBrickApp } from "./app-entry2.js";
|
|
4
|
+
import { t as buildApplication } from "./build.js";
|
|
5
|
+
import { t as writeClientContract } from "./client-contract-file2.js";
|
|
5
6
|
import { t as parsePort } from "./port-utils.js";
|
|
6
7
|
import { generateOpenApiSpec, getGlobalRegistry } from "@brickkit/core";
|
|
7
|
-
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
8
|
-
import { dirname, join, resolve } from "node:path";
|
|
9
|
-
import { randomUUID } from "node:crypto";
|
|
10
8
|
import { Command, InvalidArgumentError } from "commander";
|
|
11
|
-
//#region src/client-contract-file.ts
|
|
12
|
-
/** Generate a client contract without loading Vite or starting a server. */
|
|
13
|
-
async function writeClientContract(entryPath, outputPath) {
|
|
14
|
-
const entry = resolve(entryPath);
|
|
15
|
-
const output = resolve(outputPath ?? "_brick/contract.ts");
|
|
16
|
-
if (entry === output) throw new Error("Brick: contract output must not overwrite the app entry.");
|
|
17
|
-
const app = await loadBrickApp(entry);
|
|
18
|
-
const source = generateClientContract(app);
|
|
19
|
-
if (await readFile(output, "utf8").catch((error) => {
|
|
20
|
-
if (error.code !== "ENOENT") throw error;
|
|
21
|
-
}) !== source) {
|
|
22
|
-
await mkdir(dirname(output), { recursive: true });
|
|
23
|
-
const temporary = join(dirname(output), `.brick-contract-${randomUUID()}.tmp`);
|
|
24
|
-
try {
|
|
25
|
-
await writeFile(temporary, source, { flag: "wx" });
|
|
26
|
-
await rename(temporary, output);
|
|
27
|
-
} finally {
|
|
28
|
-
await rm(temporary, { force: true });
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
return output;
|
|
32
|
-
}
|
|
33
9
|
//#endregion
|
|
34
10
|
//#region src/bin.ts
|
|
35
|
-
const CLI_VERSION = "0.7.
|
|
11
|
+
const CLI_VERSION = "0.7.2";
|
|
36
12
|
const PORT_HELP = "Port to listen on (CLI --port overrides PORT env, default 4000)";
|
|
37
13
|
const PORT_RESOLUTION_HELP = `
|
|
38
14
|
Port Resolution (dev/start commands):
|
|
@@ -73,11 +49,13 @@ Usage:
|
|
|
73
49
|
brick gen client <entry> [--output <file>] Generate a typed browser client contract
|
|
74
50
|
brick info <entry> Export architecture JSON schema
|
|
75
51
|
${PORT_RESOLUTION_HELP}`);
|
|
76
|
-
program.command("dev").description("Start development server with live reload").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
|
|
52
|
+
program.command("dev").description("Start development server with live reload").option("--client <file>", "Generate and watch a browser contract before startup").option("--frontend <command>", "Start frontend after contract generation; requires --client").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
|
|
77
53
|
const port = resolveDevPort(opts.port);
|
|
78
54
|
await startDevServer({
|
|
79
55
|
entry,
|
|
80
|
-
port
|
|
56
|
+
port,
|
|
57
|
+
clientOutput: opts.client,
|
|
58
|
+
frontend: opts.frontend
|
|
81
59
|
});
|
|
82
60
|
});
|
|
83
61
|
program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":["cliPkg.version"],"sources":["../src/client-contract-file.ts","../package.json","../src/bin.ts"],"sourcesContent":["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 { loadBrickApp } from \"./app-entry\";\n\n/** Generate a client contract without loading Vite or starting a server. */\nexport async function writeClientContract(\n entryPath: string,\n outputPath?: string,\n) {\n const entry = resolve(entryPath);\n const output = resolve(outputPath ?? \"_brick/contract.ts\");\n if (entry === output)\n throw new Error(\"Brick: contract output must not overwrite the app entry.\");\n const app = await loadBrickApp(entry);\n const source = generateClientContract(app);\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 `.brick-contract-${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 return output;\n}\n","","#!/usr/bin/env bun\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { generateOpenApiSpec, getGlobalRegistry } from \"@brickkit/core\";\nimport { parsePort } from \"./port-utils\";\nimport { loadBrickApp } from \"./app-entry\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP =\n \"Port to listen on (CLI --port overrides PORT env, default 4000)\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Defaults to 4000 if neither is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nfunction parsePortOption(value: string): number {\n try {\n return parsePort(value, undefined);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\nfunction resolveDevPort(cliPort: number | undefined): number {\n if (cliPort !== undefined) return cliPort;\n return parsePort(undefined, process.env.PORT);\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .addHelpText(\n \"after\",\n `\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] [--port <number>] Start production server\n brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server\n brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick gen client <entry> [--output <file>] Generate a typed browser client contract\n brick info <entry> Export architecture JSON schema\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(async (entry: string | undefined, opts: { port?: number }) => {\n const port = resolveDevPort(opts.port);\n await startDevServer({ entry, port });\n });\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(async (entry: string | undefined, opts: { port?: number }) => {\n const port = resolveDevPort(opts.port);\n await startProdServer({ entry, port });\n });\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"<entry>\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entry: string,\n opts: {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n },\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new Error(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const result = await buildApplication({\n entry,\n outdir: opts.outdir,\n port: opts.port,\n aot: opts.aot,\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n console.log(`Run: bun ${result.entry}`);\n },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client)\")\n .action((subcommand: string | undefined) => {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client`,\n );\n process.exit(1);\n });\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"<entry>\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(async (entry: string, opts: { output?: string }) => {\n const app = await loadBrickApp(entry);\n const spec = generateOpenApiSpec({\n services: [...app.definition.services],\n prefix: app.definition.prefix,\n });\n const jsonOutput = JSON.stringify(spec, null, 2);\n if (opts.output) {\n await Bun.write(opts.output, jsonOutput);\n console.log(`✅ OpenAPI 3.1 specification written to ${opts.output}`);\n } else {\n console.log(jsonOutput);\n }\n });\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"<entry>\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(async (entry: string, opts: { output?: string }) => {\n const output = await writeClientContract(entry, opts.output);\n console.log(`Client contract written to ${output}`);\n });\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"<entry>\", \"Application entry file\")\n .action(async (entry: string) => {\n const app = await loadBrickApp(entry);\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n });\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n // Preserve legacy behavior: bare `brick` starts the dev server.\n const userArgs = process.argv.slice(2);\n if (userArgs.length === 0) {\n const port = parsePort(undefined, process.env.PORT);\n await startDevServer({ port });\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AAOA,eAAsB,oBACpB,WACA,YACA;CACA,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,cAAc,oBAAoB;CACzD,IAAI,UAAU,QACZ,MAAM,IAAI,MAAM,0DAA0D;CAC5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AAkB,CAAC,CAAC,mBACvC,IAAI,UACN;EACA,QAAQ,IAAI,KAAK,UAAU,cAAc,MAAM,CAAC,CAAC;CACnD,CAAC;CAEH,OAAO;AACT;AAEA,eAAe,OAAO;CACpB,MAAM,UAAU,cAAc;CAG9B,IADiB,QAAQ,KAAK,MAAM,CACzB,CAAC,CAAC,WAAW,GAAG;EACzB,MAAM,OAAO,UAAU,KAAA,GAAW,QAAQ,IAAI,IAAI;EAClD,MAAM,eAAe,EAAE,KAAK,CAAC;EAC7B;CACF;CACA,MAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAGpB,IAAI,KAAK,aAAa,KAAA,GACpB,QAAQ,KAAK,IAAI,QAAQ;CAE3B,IAAI,KAAK,MAAM,aAAa,YAAY,GACtC,QAAQ,KAAK,CAAC;CAEhB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
1
|
+
{"version":3,"file":"bin.js","names":["cliPkg.version"],"sources":["../package.json","../src/bin.ts"],"sourcesContent":["","#!/usr/bin/env bun\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { generateOpenApiSpec, getGlobalRegistry } from \"@brickkit/core\";\nimport { parsePort } from \"./port-utils\";\nimport { loadBrickApp } from \"./app-entry\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP =\n \"Port to listen on (CLI --port overrides PORT env, default 4000)\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Defaults to 4000 if neither is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nfunction parsePortOption(value: string): number {\n try {\n return parsePort(value, undefined);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\nfunction resolveDevPort(cliPort: number | undefined): number {\n if (cliPort !== undefined) return cliPort;\n return parsePort(undefined, process.env.PORT);\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .addHelpText(\n \"after\",\n `\nUsage:\n brick dev [entry] [--port <number>] Start development server with live reload\n brick start [entry] [--port <number>] Start production server\n brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server\n brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick gen client <entry> [--output <file>] Generate a typed browser client contract\n brick info <entry> Export architecture JSON schema\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .option(\n \"--client <file>\",\n \"Generate and watch a browser contract before startup\",\n )\n .option(\n \"--frontend <command>\",\n \"Start frontend after contract generation; requires --client\",\n )\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entry: string | undefined,\n opts: { port?: number; client?: string; frontend?: string },\n ) => {\n const port = resolveDevPort(opts.port);\n await startDevServer({\n entry,\n port,\n clientOutput: opts.client,\n frontend: opts.frontend,\n });\n },\n );\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(async (entry: string | undefined, opts: { port?: number }) => {\n const port = resolveDevPort(opts.port);\n await startProdServer({ entry, port });\n });\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"<entry>\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entry: string,\n opts: {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n },\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new Error(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const result = await buildApplication({\n entry,\n outdir: opts.outdir,\n port: opts.port,\n aot: opts.aot,\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n console.log(`Run: bun ${result.entry}`);\n },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client)\")\n .action((subcommand: string | undefined) => {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client`,\n );\n process.exit(1);\n });\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"<entry>\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(async (entry: string, opts: { output?: string }) => {\n const app = await loadBrickApp(entry);\n const spec = generateOpenApiSpec({\n services: [...app.definition.services],\n prefix: app.definition.prefix,\n });\n const jsonOutput = JSON.stringify(spec, null, 2);\n if (opts.output) {\n await Bun.write(opts.output, jsonOutput);\n console.log(`✅ OpenAPI 3.1 specification written to ${opts.output}`);\n } else {\n console.log(jsonOutput);\n }\n });\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"<entry>\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(async (entry: string, opts: { output?: string }) => {\n const output = await writeClientContract(entry, opts.output);\n console.log(`Client contract written to ${output}`);\n });\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"<entry>\", \"Application entry file\")\n .action(async (entry: string) => {\n const app = await loadBrickApp(entry);\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n });\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n // Preserve legacy behavior: bare `brick` starts the dev server.\n const userArgs = process.argv.slice(2);\n if (userArgs.length === 0) {\n const port = parsePort(undefined, process.env.PORT);\n await startDevServer({ port });\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;ACWA,MAAM,cAAsBA;AAE5B,MAAM,YACJ;AAEF,MAAM,uBAAuB;;;;;;;;;;;;;AA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YAAY,GACtC,QAAQ,KAAK,CAAC;CAEhB,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/dist/build.js
CHANGED
|
@@ -1,15 +1,8 @@
|
|
|
1
1
|
import { i as emitCompiledApplication, n as compileBrickApplication } from "./compiler2.js";
|
|
2
|
-
import {
|
|
3
|
-
import { pathToFileURL } from "node:url";
|
|
2
|
+
import { t as loadBrickApp } from "./app-entry2.js";
|
|
4
3
|
import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
|
|
5
4
|
import { dirname, join, resolve } from "node:path";
|
|
6
5
|
import { aot } from "elysia/plugin/aot/bun";
|
|
7
|
-
//#region src/app-entry.ts
|
|
8
|
-
async function loadBrickApp(entry) {
|
|
9
|
-
const module = await import(pathToFileURL(resolve(entry)).href);
|
|
10
|
-
return requireBrickApp(module.default);
|
|
11
|
-
}
|
|
12
|
-
//#endregion
|
|
13
6
|
//#region src/build.ts
|
|
14
7
|
/** Bundle an exported BrickApp with generated handlers and its original configuration. */
|
|
15
8
|
async function buildApplication(options) {
|
|
@@ -77,6 +70,6 @@ if (import.meta.main) {
|
|
|
77
70
|
}
|
|
78
71
|
}
|
|
79
72
|
//#endregion
|
|
80
|
-
export {
|
|
73
|
+
export { buildApplication as t };
|
|
81
74
|
|
|
82
75
|
//# sourceMappingURL=build.js.map
|
package/dist/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"build.js","names":[],"sources":["../src/build.ts"],"sourcesContent":["import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\nimport { aot } from \"elysia/plugin/aot/bun\";\nimport { loadBrickApp } from \"./app-entry\";\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\n/** Bundle an exported BrickApp with generated handlers 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 ?? \"dist/brick\");\n if (\n entry === join(outdir, \"server.js\") ||\n entry === join(outdir, \"routes.js\")\n )\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = options.port ?? 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535)\n throw new Error(\n \"Brick compiler: port must be an integer between 1 and 65535\",\n );\n const app = await loadBrickApp(entry);\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 source = `import { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { ir, bind } from \"./routes.js\";\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir, bind);\nif (import.meta.main) {\n const port = Number(process.env.PORT ?? ${port});\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(\"Invalid PORT: must be between 1 and 65535\");\n app.listen(port);\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n const stop = async () => { await app.stop(); process.exit(0); };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\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 plugins:\n options.aot === false\n ? []\n : [aot(join(staging, \"entry.ts\"), { target: \"bun\", strip: true })],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\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 [\n \"routes.js\",\n \"brick-ir.json\",\n \"server.js.map\",\n \"server.js\",\n ])\n await rename(join(staging, name), join(outdir, name));\n return { outdir, entry: join(outdir, \"server.js\"), ir: compilation.ir };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;AAgBA,eAAsB,iBAAiB,SAAkC;CACvE,MAAM,QAAQ,QAAQ,QAAQ,KAAK;CACnC,IAAI,CAAE,MAAM,IAAI,KAAK,KAAK,CAAC,CAAC,OAAO,GACjC,MAAM,IAAI,MAAM,oCAAoC,OAAO;CAC7D,MAAM,SAAS,QAAQ,QAAQ,UAAU,YAAY;CACrD,IACE,UAAU,KAAK,QAAQ,WAAW,KAClC,UAAU,KAAK,QAAQ,WAAW,GAElC,MAAM,IAAI,MACR,8DACF;CACF,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MACR,6DACF;CACF,MAAM,MAAM,MAAM,aAAa,KAAK;CACpC,MAAM,WAAW,CAAC,GAAG,IAAI,WAAW,QAAQ;CAC5C,MAAM,cAAc,wBAAwB;EAC1C;EACA,QAAQ,IAAI,WAAW;CACzB,CAAC;CACD,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CAChD,MAAM,UAAU,MAAM,QAAQ,KAAK,QAAQ,MAAM,GAAG,eAAe,CAAC;CACpE,IAAI;EACF,MAAM,IAAI,MACR,KAAK,SAAS,WAAW,GACzB,wBAAwB,YAAY,EAAE,CACxC;EACA,MAAM,SAAS;;6DAE0C,KAAK,UAAU,KAAK,EAAE;;4CAEvC,KAAK;;;;;;;;;EAS7C,MAAM,IAAI,MAAM,KAAK,SAAS,UAAU,GAAG,MAAM;EACjD,MAAM,SAAS,MAAM,IAAI,MAAM;GAC7B,aAAa,CAAC,KAAK,SAAS,UAAU,CAAC;GACvC,QAAQ;GACR,QAAQ;GACR,QAAQ;GACR,QAAQ;GACR,WAAW;GACX,SACE,QAAQ,QAAQ,QACZ,CAAC,IACD,CAAC,IAAI,KAAK,SAAS,UAAU,GAAG;IAAE,QAAQ;IAAO,OAAO;GAAK,CAAC,CAAC;EACvE,CAAC;EACD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,eAAe,OAAO,MAAM,iCAAiC;EACzE,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;GACjB;GACA;GACA;GACA;EACF,GACE,MAAM,OAAO,KAAK,SAAS,IAAI,GAAG,KAAK,QAAQ,IAAI,CAAC;EACtD,OAAO;GAAE;GAAQ,OAAO,KAAK,QAAQ,WAAW;GAAG,IAAI,YAAY;EAAG;CACxE,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { n as writeContractSource } from "./client-contract-file2.js";
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { t as loadBrickApp } from "./app-entry2.js";
|
|
2
|
+
import { t as generateClientContract } from "./client-contract2.js";
|
|
3
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
//#region src/client-contract-file.ts
|
|
7
|
+
/** Generate a client contract without loading Vite or starting a server. */
|
|
8
|
+
async function writeClientContract(entryPath, outputPath) {
|
|
9
|
+
const entry = resolve(entryPath);
|
|
10
|
+
const output = resolve(outputPath ?? "_brick/contract.ts");
|
|
11
|
+
if (entry === output) throw new Error("Brick: contract output must not overwrite the app entry.");
|
|
12
|
+
const app = await loadBrickApp(entry);
|
|
13
|
+
await writeContractSource(output, generateClientContract(app));
|
|
14
|
+
return output;
|
|
15
|
+
}
|
|
16
|
+
/** Atomically replace changed contracts, preserving timestamps when unchanged. */
|
|
17
|
+
async function writeContractSource(output, source) {
|
|
18
|
+
if (await readFile(output, "utf8").catch((error) => {
|
|
19
|
+
if (error.code !== "ENOENT") throw error;
|
|
20
|
+
}) !== source) {
|
|
21
|
+
await mkdir(dirname(output), { recursive: true });
|
|
22
|
+
const temporary = join(dirname(output), `.brick-contract-${randomUUID()}.tmp`);
|
|
23
|
+
try {
|
|
24
|
+
await writeFile(temporary, source, { flag: "wx" });
|
|
25
|
+
await rename(temporary, output);
|
|
26
|
+
} finally {
|
|
27
|
+
await rm(temporary, { force: true });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { writeContractSource as n, writeClientContract as t };
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=client-contract-file2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-contract-file2.js","names":[],"sources":["../src/client-contract-file.ts"],"sourcesContent":["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 { loadBrickApp } from \"./app-entry\";\n\n/** Generate a client contract without loading Vite or starting a server. */\nexport async function writeClientContract(\n entryPath: string,\n outputPath?: string,\n) {\n const entry = resolve(entryPath);\n const output = resolve(outputPath ?? \"_brick/contract.ts\");\n if (entry === output)\n throw new Error(\"Brick: contract output must not overwrite the app entry.\");\n const app = await loadBrickApp(entry);\n const source = generateClientContract(app);\n await writeContractSource(output, source);\n return output;\n}\n\n/** Atomically replace changed contracts, preserving timestamps when unchanged. */\nexport async function writeContractSource(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 `.brick-contract-${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":";;;;;;;AAOA,eAAsB,oBACpB,WACA,YACA;CACA,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,cAAc,oBAAoB;CACzD,IAAI,UAAU,QACZ,MAAM,IAAI,MAAM,0DAA0D;CAC5E,MAAM,MAAM,MAAM,aAAa,KAAK;CAEpC,MAAM,oBAAoB,QADX,uBAAuB,GACC,CAAC;CACxC,OAAO;AACT;;AAGA,eAAsB,oBAAoB,QAAgB,QAAgB;CAKxE,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,mBAAmB,WAAW,EAAE,KAClC;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/client-contract.js
CHANGED
|
@@ -1,268 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
//#region src/client-contract.ts
|
|
4
|
-
/** Generate browser metadata and transport types from the app's selected services. */
|
|
5
|
-
function generateClientContract(app) {
|
|
6
|
-
const { services, prefix } = app.definition;
|
|
7
|
-
const contract = Object.create(null);
|
|
8
|
-
const types = Object.create(null);
|
|
9
|
-
const schemas = new SchemaTypes();
|
|
10
|
-
for (const service of services) addServiceActions(service, prefix, contract, types, schemas);
|
|
11
|
-
return `// Generated by the Brick Vite plugin. Do not edit.
|
|
12
|
-
import type { BrickClientAction } from "@brickkit/core/client";
|
|
13
|
-
|
|
14
|
-
${schemas.renderContract(namespaceType(types))}
|
|
15
|
-
|
|
16
|
-
export const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});
|
|
17
|
-
`;
|
|
18
|
-
}
|
|
19
|
-
function addServiceActions(service, prefix, contract, types, schemas) {
|
|
20
|
-
const namespace = contract[service.name] ?? Object.create(null);
|
|
21
|
-
const namespaceTypes = types[service.name] ?? Object.create(null);
|
|
22
|
-
contract[service.name] = namespace;
|
|
23
|
-
types[service.name] = namespaceTypes;
|
|
24
|
-
for (const action of service.listActions()) {
|
|
25
|
-
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
26
|
-
if (pluginRoute === false) continue;
|
|
27
|
-
const { input, output, errors, path, method } = action.config;
|
|
28
|
-
let inputType;
|
|
29
|
-
let outputType;
|
|
30
|
-
try {
|
|
31
|
-
inputType = input ? schemas.generate(input) : "unknown";
|
|
32
|
-
outputType = output ? schemas.generate(output) : "unknown";
|
|
33
|
-
} catch (error) {
|
|
34
|
-
throw new Error(`Brick client: cannot generate '${service.name}.${action.name}': ${error.message}`);
|
|
35
|
-
}
|
|
36
|
-
const metadata = {
|
|
37
|
-
kind: "action",
|
|
38
|
-
name: action.name,
|
|
39
|
-
serviceName: service.name,
|
|
40
|
-
...action.plugin ? { plugin: action.plugin } : pluginRoute?.plugin ? { plugin: pluginRoute.plugin } : {},
|
|
41
|
-
...action.resource ? { resource: action.resource } : pluginRoute?.resource ? { resource: pluginRoute.resource } : {},
|
|
42
|
-
config: {
|
|
43
|
-
path: pluginRoute?.path ?? path ?? `${prefix}/${service.name}/${action.name}`,
|
|
44
|
-
method: pluginRoute?.method ?? method ?? "POST"
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
insertAction(pluginRoute?.clientPath ? contract : namespace, pluginRoute?.clientPath ? types : namespaceTypes, metadata, actionType(inputType, outputType, errors), pluginRoute?.clientPath);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
function insertAction(node, typeNode, metadata, type, clientPath) {
|
|
51
|
-
const segments = clientPath ?? metadata.name.split(".");
|
|
52
|
-
for (const segment of segments.slice(0, -1)) {
|
|
53
|
-
if (Object.hasOwn(typeNode, segment) && typeof typeNode[segment] === "string") throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
|
|
54
|
-
node[segment] ??= Object.create(null);
|
|
55
|
-
typeNode[segment] ??= Object.create(null);
|
|
56
|
-
node = node[segment];
|
|
57
|
-
typeNode = typeNode[segment];
|
|
58
|
-
}
|
|
59
|
-
const leaf = segments.at(-1);
|
|
60
|
-
if (Object.hasOwn(node, leaf)) throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
|
|
61
|
-
node[leaf] = metadata;
|
|
62
|
-
typeNode[leaf] = type;
|
|
63
|
-
}
|
|
64
|
-
function actionType(input, output, errors) {
|
|
65
|
-
const codes = Object.keys(errors ?? {});
|
|
66
|
-
return `BrickClientAction<${input}, ${output}, ${codes.length ? `Record<${codes.map((code) => JSON.stringify(code)).join(" | ")}, { message: string; status?: number }>` : "{}"}>`;
|
|
67
|
-
}
|
|
68
|
-
function namespaceType(node) {
|
|
69
|
-
return `{\n${Object.entries(node).map(([key, value]) => ` ${JSON.stringify(key)}: ${typeof value === "string" ? value : namespaceType(value)};`).join("\n")}\n}`;
|
|
70
|
-
}
|
|
71
|
-
var SchemaTypes = class {
|
|
72
|
-
aliases = /* @__PURE__ */ new Map();
|
|
73
|
-
names = /* @__PURE__ */ new Set([
|
|
74
|
-
"AppContract",
|
|
75
|
-
"BrickClientAction",
|
|
76
|
-
"contract"
|
|
77
|
-
]);
|
|
78
|
-
fragments = [];
|
|
79
|
-
fragmentIds = /* @__PURE__ */ new Map();
|
|
80
|
-
fragment(body) {
|
|
81
|
-
let id = this.fragmentIds.get(body);
|
|
82
|
-
if (id === void 0) {
|
|
83
|
-
id = this.fragments.length;
|
|
84
|
-
const size = body.replace(/\0(\d+)\0/g, "").length + [...body.matchAll(/\0(\d+)\0/g)].reduce((total, match) => total + this.fragments[Number(match[1])].size, 0);
|
|
85
|
-
const shape = body.replace(/\0(\d+)\0/g, (_, child) => this.fragments[Number(child)].hash);
|
|
86
|
-
const hash = createHash("sha256").update(shape).digest("hex");
|
|
87
|
-
this.fragments.push({
|
|
88
|
-
body,
|
|
89
|
-
size,
|
|
90
|
-
hash
|
|
91
|
-
});
|
|
92
|
-
this.fragmentIds.set(body, id);
|
|
93
|
-
}
|
|
94
|
-
return `\0${id}\0`;
|
|
95
|
-
}
|
|
96
|
-
renderContract(contract) {
|
|
97
|
-
const uses = this.fragments.map(() => 0);
|
|
98
|
-
const count = (body, multiplier) => {
|
|
99
|
-
for (const match of body.matchAll(/\0(\d+)\0/g)) uses[Number(match[1])] += multiplier;
|
|
100
|
-
};
|
|
101
|
-
count(contract, 1);
|
|
102
|
-
for (const body of this.aliases.values()) count(body, 1);
|
|
103
|
-
const shared = /* @__PURE__ */ new Map();
|
|
104
|
-
for (let id = this.fragments.length - 1; id >= 0; id--) {
|
|
105
|
-
const { body, size, hash } = this.fragments[id];
|
|
106
|
-
const nameBase = `BrickSchema_${hash.slice(0, 12)}`;
|
|
107
|
-
let name = nameBase;
|
|
108
|
-
let suffix = 2;
|
|
109
|
-
while (this.names.has(name)) name = `${nameBase}_${suffix++}`;
|
|
110
|
-
const declarationCost = `export type ${name} = ;\n\n`.length;
|
|
111
|
-
if (uses[id] > 1 && (uses[id] - 1) * size > uses[id] * name.length + declarationCost) {
|
|
112
|
-
this.names.add(name);
|
|
113
|
-
shared.set(id, name);
|
|
114
|
-
}
|
|
115
|
-
count(body, shared.has(id) ? 1 : uses[id]);
|
|
116
|
-
}
|
|
117
|
-
const rendered = [];
|
|
118
|
-
const declarations = [];
|
|
119
|
-
for (let id = 0; id < this.fragments.length; id++) {
|
|
120
|
-
const body = this.fragments[id].body.replace(/\0(\d+)\0/g, (_, child) => rendered[Number(child)]);
|
|
121
|
-
const name = shared.get(id);
|
|
122
|
-
if (name && (uses[id] - 1) * body.length > uses[id] * name.length + `export type ${name} = ;\n\n`.length) {
|
|
123
|
-
declarations.push(`export type ${name} = ${body};\n\n`);
|
|
124
|
-
rendered.push(name);
|
|
125
|
-
} else rendered.push(body);
|
|
126
|
-
}
|
|
127
|
-
const render = (body) => body.replace(/\0(\d+)\0/g, (_, id) => rendered[Number(id)]);
|
|
128
|
-
return declarations.join("") + [...this.aliases].map(([name, type]) => `export type ${name} = ${render(type)};\n\n`).join("") + `export type AppContract = ${render(contract)};`;
|
|
129
|
-
}
|
|
130
|
-
generate(root) {
|
|
131
|
-
const ids = /* @__PURE__ */ new Map();
|
|
132
|
-
const references = [];
|
|
133
|
-
const resources = /* @__PURE__ */ new Map();
|
|
134
|
-
const active = /* @__PURE__ */ new Set();
|
|
135
|
-
const visit = (schema, base) => {
|
|
136
|
-
if (!schema || typeof schema !== "object" || active.has(schema)) return;
|
|
137
|
-
const currentBase = typeof schema.$id === "string" && schema.$id ? schema : base;
|
|
138
|
-
if (!resources.has(schema)) resources.set(schema, currentBase);
|
|
139
|
-
if (typeof schema.$ref === "string") references.push({
|
|
140
|
-
ref: schema.$ref,
|
|
141
|
-
base: currentBase
|
|
142
|
-
});
|
|
143
|
-
active.add(schema);
|
|
144
|
-
try {
|
|
145
|
-
if (typeof schema.$id === "string" && schema.$id) ids.set(schema.$id, schema);
|
|
146
|
-
for (const key of [
|
|
147
|
-
"properties",
|
|
148
|
-
"patternProperties",
|
|
149
|
-
"$defs",
|
|
150
|
-
"definitions"
|
|
151
|
-
]) for (const child of Object.values(schema[key] ?? {})) visit(child, currentBase);
|
|
152
|
-
for (const key of [
|
|
153
|
-
"anyOf",
|
|
154
|
-
"oneOf",
|
|
155
|
-
"allOf",
|
|
156
|
-
"prefixItems"
|
|
157
|
-
]) for (const child of schema[key] ?? []) visit(child, currentBase);
|
|
158
|
-
for (const key of [
|
|
159
|
-
"items",
|
|
160
|
-
"additionalProperties",
|
|
161
|
-
"not"
|
|
162
|
-
]) if (Array.isArray(schema[key])) schema[key].forEach((child) => visit(child, currentBase));
|
|
163
|
-
else visit(schema[key], currentBase);
|
|
164
|
-
} finally {
|
|
165
|
-
active.delete(schema);
|
|
166
|
-
}
|
|
167
|
-
};
|
|
168
|
-
visit(root, root);
|
|
169
|
-
const resolve = (reference, base) => {
|
|
170
|
-
const hashIndex = reference.indexOf("#");
|
|
171
|
-
const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);
|
|
172
|
-
const fragment = hashIndex === -1 ? void 0 : reference.slice(hashIndex + 1);
|
|
173
|
-
let target = id ? ids.get(id) : base;
|
|
174
|
-
if (fragment) {
|
|
175
|
-
if (!fragment.startsWith("/")) return void 0;
|
|
176
|
-
try {
|
|
177
|
-
for (const part of decodeURIComponent(fragment).slice(1).split("/")) {
|
|
178
|
-
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
179
|
-
if (!target || !Object.hasOwn(target, key)) return void 0;
|
|
180
|
-
target = target[key];
|
|
181
|
-
}
|
|
182
|
-
} catch {
|
|
183
|
-
return;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
return typeof target === "boolean" || target && typeof target === "object" ? target : void 0;
|
|
187
|
-
};
|
|
188
|
-
const targets = new Set(references.map(({ ref, base }) => resolve(ref, base)).filter((value) => value !== void 0));
|
|
189
|
-
const names = /* @__PURE__ */ new Map();
|
|
190
|
-
const emit = (schema, inline = false, base = root) => {
|
|
191
|
-
const body = emitInline(schema, inline, base);
|
|
192
|
-
if (schema && !schema.$ref && !Object.hasOwn(schema, "const") && (schema.anyOf || schema.oneOf || schema.allOf || schema.enum?.length > 1 || schema.type === "array" || schema.type === "object")) return this.fragment(body);
|
|
193
|
-
return body;
|
|
194
|
-
};
|
|
195
|
-
const emitInline = (schema, inline, base) => {
|
|
196
|
-
if (schema === void 0 || schema === true) return "unknown";
|
|
197
|
-
if (schema === false || schema.not && !Object.keys(schema.not).length) return "never";
|
|
198
|
-
const currentBase = schema && typeof schema === "object" && typeof schema.$id === "string" && schema.$id ? schema : base;
|
|
199
|
-
if (!inline && targets.has(schema)) {
|
|
200
|
-
const existing = names.get(schema);
|
|
201
|
-
if (existing) return existing;
|
|
202
|
-
const hint = schema.title ?? schema.$id ?? "Schema";
|
|
203
|
-
let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, "_");
|
|
204
|
-
if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;
|
|
205
|
-
nameBase = `Brick${nameBase}`;
|
|
206
|
-
let name = nameBase;
|
|
207
|
-
let suffix = 2;
|
|
208
|
-
while (this.names.has(name)) {
|
|
209
|
-
name = `${nameBase}_${suffix}`;
|
|
210
|
-
suffix += 1;
|
|
211
|
-
}
|
|
212
|
-
this.names.add(name);
|
|
213
|
-
names.set(schema, name);
|
|
214
|
-
this.aliases.set(name, emit(schema, true, currentBase));
|
|
215
|
-
return name;
|
|
216
|
-
}
|
|
217
|
-
if (schema.$ref) {
|
|
218
|
-
const target = resolve(schema.$ref, currentBase);
|
|
219
|
-
if (target === void 0) throw new Error(`unresolved schema reference '${schema.$ref}'`);
|
|
220
|
-
const targetBase = target && typeof target === "object" ? resources.get(target) ?? root : currentBase;
|
|
221
|
-
return emit(target, false, targetBase);
|
|
222
|
-
}
|
|
223
|
-
if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
|
|
224
|
-
if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ") || "never";
|
|
225
|
-
if (schema.anyOf || schema.oneOf) return `(${(schema.anyOf ?? schema.oneOf).map((child) => emit(child, false, currentBase)).join(" | ")})`;
|
|
226
|
-
if (schema.allOf) return `(${schema.allOf.map((child) => emit(child, false, currentBase)).join(" & ")})`;
|
|
227
|
-
switch (schema.type) {
|
|
228
|
-
case "string": return "string";
|
|
229
|
-
case "number":
|
|
230
|
-
case "integer": return "number";
|
|
231
|
-
case "boolean": return "boolean";
|
|
232
|
-
case "null": return "null";
|
|
233
|
-
case "undefined":
|
|
234
|
-
case "void": return "undefined";
|
|
235
|
-
case "array":
|
|
236
|
-
if (Array.isArray(schema.items)) return `[${schema.items.map((child) => emit(child, false, currentBase)).join(", ")}]`;
|
|
237
|
-
return `Array<${emit(schema.items, false, currentBase)}>`;
|
|
238
|
-
case "object": {
|
|
239
|
-
const entries = Object.entries(schema.properties ?? {});
|
|
240
|
-
const properties = entries.map(([key, value]) => `${JSON.stringify(key)}${schema.required?.includes(key) ? "" : "?"}: ${emit(value, false, currentBase)};`);
|
|
241
|
-
const indexParts = Object.values(schema.patternProperties ?? {}).map((child) => emit(child, false, currentBase));
|
|
242
|
-
if (schema.additionalProperties) indexParts.push(emit(schema.additionalProperties, false, currentBase));
|
|
243
|
-
let indexType;
|
|
244
|
-
if (indexParts.length) {
|
|
245
|
-
for (const [, value] of entries) {
|
|
246
|
-
const propType = emit(value, false, currentBase);
|
|
247
|
-
if (!indexParts.includes(propType)) indexParts.push(propType);
|
|
248
|
-
}
|
|
249
|
-
indexType = indexParts.join(" | ");
|
|
250
|
-
}
|
|
251
|
-
const object = `{ ${properties.join(" ")} }`;
|
|
252
|
-
if (indexType) {
|
|
253
|
-
const index = `{ [key: string]: ${indexType} }`;
|
|
254
|
-
return properties.length ? `${object} & ${index}` : index;
|
|
255
|
-
}
|
|
256
|
-
return object;
|
|
257
|
-
}
|
|
258
|
-
case void 0: return "unknown";
|
|
259
|
-
default: throw new Error(`unsupported transport schema type '${schema.type}'`);
|
|
260
|
-
}
|
|
261
|
-
};
|
|
262
|
-
return emit(root);
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
//#endregion
|
|
266
|
-
export { generateClientContract as t };
|
|
267
|
-
|
|
268
|
-
//# sourceMappingURL=client-contract.js.map
|
|
1
|
+
export { t as generateClientContract } from "./client-contract2.js";
|