@brickkit/cli 0.4.2 → 0.6.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-contract-file.js","names":[],"sources":["../src/native-build.ts","../src/build.ts","../src/client-contract-file.ts"],"sourcesContent":["import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { NativeBrickApp } from \"@brickkit/core\";\n\nexport async function buildNativeApplication(\n options: { entry: string; outdir?: string; port: number },\n app: NativeBrickApp,\n) {\n const entry = resolve(options.entry);\n const outdir = resolve(options.outdir ?? \"dist/brick\");\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-native-build-\"));\n try {\n await Bun.write(\n join(staging, \"entry.ts\"),\n `import app from ${JSON.stringify(entry)};\nexport { app };\nif (import.meta.main) {\n const port = Number(process.env.PORT ?? ${options.port});\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(\"Invalid PORT: must be between 1 and 65535\");\n let server;\n try {\n await app.ready();\n server = Bun.serve({ port, fetch: request => app.fetch(request) });\n } catch (error) {\n await app.dispose();\n throw error;\n }\n let closing;\n const stop = () => closing ??= (async () => {\n try { await server.stop(true); } finally { await app.dispose(); }\n })();\n const onSignal = () => void stop().then(() => process.exit(0), error => {\n console.error(error);\n process.exit(1);\n });\n process.once(\"SIGINT\", onSignal);\n process.once(\"SIGTERM\", onSignal);\n console.log(\"Brick server listening on http://localhost:\" + server.port);\n}\n`,\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 });\n if (!result.success)\n throw new AggregateError(\n result.logs,\n \"Brick: native application bundling failed\",\n );\n const services = app.services.map((service) => ({\n name: service.name,\n actions: Object.values(service.actions).map((action) => ({\n name: action.endpoint.identifier,\n method: action.method,\n path: action.path,\n })),\n }));\n const ir = {\n version: 2 as const,\n target: \"effect-http-api\" as const,\n services,\n routes: services.flatMap((service) =>\n service.actions.map((action) => ({ service: service.name, ...action })),\n ),\n diagnostics: [],\n };\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of [\"brick-ir.json\", \"server.js.map\", \"server.js\"])\n await rename(join(staging, name), join(outdir, name));\n return { outdir, entry: join(outdir, \"server.js\"), ir };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n","import { join, resolve } from \"node:path\";\nimport { loadApplication } from \"./app-entry\";\nimport { buildNativeApplication } from \"./native-build\";\n\nexport interface BuildApplicationOptions {\n /** Module whose default export is a Brick.app(), without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n}\n\n/** Bundle the application and its scoped Effect dependencies into a Bun server. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? \"dist/brick\");\n if (entry === join(outdir, \"server.js\"))\n throw new Error(\"Brick: output would overwrite the application entry\");\n const port = options.port ?? 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535)\n throw new Error(\"Brick: port must be an integer between 1 and 65535\");\n const app = await loadApplication(entry);\n try {\n return await buildNativeApplication({ entry, outdir, port }, app);\n } finally {\n await app.dispose();\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 { loadApplication } from \"./app-entry\";\nimport { generateNativeClientContract } from \"./native-client-contract\";\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 loadApplication(entry);\n const source = await generateNativeClientContract(app, {\n entry,\n output,\n }).finally(() => app.dispose());\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"],"mappings":";;;;;;AAIA,eAAsB,uBACpB,SACA,KACA;CACA,MAAM,QAAQ,QAAQ,QAAQ,KAAK;CACnC,MAAM,SAAS,QAAQ,QAAQ,UAAU,YAAY;CACrD,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CAChD,MAAM,UAAU,MAAM,QAAQ,KAAK,QAAQ,MAAM,GAAG,sBAAsB,CAAC;CAC3E,IAAI;EACF,MAAM,IAAI,MACR,KAAK,SAAS,UAAU,GACxB,mBAAmB,KAAK,UAAU,KAAK,EAAE;;;4CAGH,QAAQ,KAAK;;;;;;;;;;;;;;;;;;;;;;CAuBrD;EACA,MAAM,SAAS,MAAM,IAAI,MAAM;GAC7B,aAAa,CAAC,KAAK,SAAS,UAAU,CAAC;GACvC,QAAQ;GACR,QAAQ;GACR,QAAQ;GACR,QAAQ;GACR,WAAW;EACb,CAAC;EACD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,eACR,OAAO,MACP,2CACF;EACF,MAAM,WAAW,IAAI,SAAS,KAAK,aAAa;GAC9C,MAAM,QAAQ;GACd,SAAS,OAAO,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,YAAY;IACvD,MAAM,OAAO,SAAS;IACtB,QAAQ,OAAO;IACf,MAAM,OAAO;GACf,EAAE;EACJ,EAAE;EACF,MAAM,KAAK;GACT,SAAS;GACT,QAAQ;GACR;GACA,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AM,IAAI,MAAM,0DAA0D;CAC5E,MAAM,MAAM,MAAM,gBAAgB,KAAK;CACvC,MAAM,SAAS,MAAM,6BAA6B,KAAK;EACrD;EACA;CACF,CAAC,CAAC,CAAC,cAAc,IAAI,QAAQ,CAAC;CAK9B,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;CACA,OAAO;AACT"}
@@ -1,10 +1,8 @@
1
- import { t as startDevApplication } from "./runner.js";
2
- import { t as parsePort } from "./port-utils.js";
1
+ import { i as parsePort, t as startDevApplication } from "./runner.js";
3
2
  //#region src/dev-worker.ts
4
3
  await startDevApplication({
5
4
  entry: process.argv[2],
6
- port: parsePort(process.argv[3] || void 0, process.env.PORT),
7
- prefix: process.argv[4] || void 0
5
+ port: parsePort(process.argv[3] || void 0, process.env.PORT)
8
6
  });
9
7
  //#endregion
10
8
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { startDevApplication } from \"./runner\";\nimport { parsePort } from \"./port-utils\";\n\nawait startDevApplication({\n entry: process.argv[2],\n port: parsePort(process.argv[3] || undefined, process.env.PORT),\n prefix: process.argv[4] || undefined,\n});\n"],"mappings":";;;AAGA,MAAM,oBAAoB;CACxB,OAAO,QAAQ,KAAK;CACpB,MAAM,UAAU,QAAQ,KAAK,MAAM,KAAA,GAAW,QAAQ,IAAI,IAAI;CAC9D,QAAQ,QAAQ,KAAK,MAAM,KAAA;AAC7B,CAAC"}
1
+ {"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { startDevApplication } from \"./runner\";\nimport { parsePort } from \"./port-utils\";\n\nawait startDevApplication({\n entry: process.argv[2],\n port: parsePort(process.argv[3] || undefined, process.env.PORT),\n});\n"],"mappings":";;AAGA,MAAM,oBAAoB;CACxB,OAAO,QAAQ,KAAK;CACpB,MAAM,UAAU,QAAQ,KAAK,MAAM,KAAA,GAAW,QAAQ,IAAI,IAAI;AAChE,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,34 +1,64 @@
1
- import { n as emitHandlerFactory, t as emitCompiledApplication } from "./emit.js";
2
- import { BrickApp, BrickApp as BrickApp$1, BrickApp as BrickApp$2, BrickIR, CompiledApplication, CompiledHandler, CompiledRoute, CreateServerOptions, EndpointContext, EndpointDefinition, EndpointLogger, EndpointMethod, HandlerFactory, ReferenceOptions, RequestLoggingOptions, RouteIR, RouteMethod, bindCompiledApplication, brick, compileBrickApplication, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML } from "@brickkit/core";
1
+ import { NativeBrickApp } from "@brickkit/core";
2
+ //#region src/native-server.d.ts
3
+ interface NativeServer {
4
+ readonly app: NativeBrickApp;
5
+ readonly server: Bun.Server<undefined>;
6
+ stop(): Promise<void>;
7
+ }
8
+ //#endregion
3
9
  //#region src/runner.d.ts
4
10
  interface DevServerOptions {
5
11
  port?: number;
6
12
  entry?: string;
7
- prefix?: string;
8
13
  }
9
- export declare function startDevServer(options?: DevServerOptions): Promise<BrickApp$1 | {
14
+ export declare function startDevApplication(options: DevServerOptions): Promise<NativeServer>;
15
+ export declare const startProdServer: typeof startDevApplication;
16
+ export declare function startDevServer(options?: DevServerOptions): Promise<{
10
17
  stop: () => void;
11
18
  }>;
12
19
  //#endregion
13
20
  //#region src/build.d.ts
14
21
  interface BuildApplicationOptions {
15
- /** A module whose default export is a BrickApp, without starting a server. */
22
+ /** Module whose default export is a Brick.app(), without starting a server. */
16
23
  entry: string;
17
24
  outdir?: string;
18
25
  port?: number;
19
- /** Precompile Elysia's HTTP handlers at build time (default true). */
20
- aot?: boolean;
21
26
  }
22
- /** Bundle an exported BrickApp with generated handlers and its original configuration. */
27
+ /** Bundle the application and its scoped Effect dependencies into a Bun server. */
23
28
  export declare function buildApplication(options: BuildApplicationOptions): Promise<{
24
29
  outdir: string;
25
30
  entry: string;
26
- ir: import("@brickkit/core").BrickIR;
31
+ ir: {
32
+ version: 2;
33
+ target: "effect-http-api";
34
+ services: {
35
+ name: string;
36
+ actions: {
37
+ name: string;
38
+ method: string;
39
+ path: `/${string}`;
40
+ }[];
41
+ }[];
42
+ routes: {
43
+ name: string;
44
+ method: string;
45
+ path: `/${string}`;
46
+ service: string;
47
+ }[];
48
+ diagnostics: never[];
49
+ };
27
50
  }>;
28
51
  //#endregion
29
- //#region src/client-contract.d.ts
30
- /** Generate browser metadata and transport types from the app's selected services. */
31
- export declare function generateClientContract(app: BrickApp$2): string;
52
+ //#region src/client-contract-file.d.ts
53
+ /** Generate a client contract without loading Vite or starting a server. */
54
+ export declare function writeClientContract(entryPath: string, outputPath?: string): Promise<string>;
55
+ //#endregion
56
+ //#region src/native-client-contract.d.ts
57
+ export declare function generateNativeClientContract(app: NativeBrickApp, options: {
58
+ entry: string;
59
+ output: string;
60
+ load?: (path: string) => Promise<Record<string, unknown>>;
61
+ }): Promise<string>;
32
62
  //#endregion
33
- export { type BrickApp, type BrickIR, type BuildApplicationOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, type CreateServerOptions, type DevServerOptions, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, type HandlerFactory, type ReferenceOptions, type RequestLoggingOptions, type RouteIR, type RouteMethod, bindCompiledApplication, brick, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML };
63
+ export type { BuildApplicationOptions, DevServerOptions };
34
64
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["BrickApp","BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UAWiB;EACf;EACA;EACA;;wBA2IoB,eAAe,UAAS,mBAAqB,QAAAA;;;;;UCnJlD;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;wBCVvD,uBAAuB,KAAKC"}
1
+ {"version":3,"file":"index.d.ts","names":["_$__native_server0.NativeServer"],"sources":["../src/native-server.ts","../src/runner.ts","../src/build.ts","../src/client-contract-file.ts","../src/native-client-contract.ts"],"mappings":";;UAGiB;WACN,KAAK;WACL,QAAQ,IAAI;EACrB,QAAQ;;;;UCAO;EACf;EACA;;wBAGoB,oBAAoB,SAAS,mBAAgB,QAAhBA;qBAMtC,wBAAe;wBAEN,eAAe,UAAS,mBAAqB;;;;;UCflD;;EAEf;EACA;EACA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;wBCLjD,oBACpB,mBACA,sBAAmB;;;wBCFC,6BACpB,KAAK,gBACL;EACE;EACA;EACA,QAAQ,iBAAiB,QAAQ;IAClC"}
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
- import { n as startDevServer } from "./runner.js";
2
- import { a as emitHandlerFactory, i as emitCompiledApplication } from "./compiler2.js";
3
- import { t as buildApplication } from "./build.js";
4
- import { t as generateClientContract } from "./client-contract.js";
5
- import { bindCompiledApplication, brick, compileBrickApplication, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML } from "@brickkit/core";
6
- export { bindCompiledApplication, brick, buildApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, generateClientContract, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
1
+ import { n as startDevServer, r as startProdServer, t as startDevApplication } from "./runner.js";
2
+ import { n as buildApplication, t as writeClientContract } from "./client-contract-file.js";
3
+ import { t as generateNativeClientContract } from "./native-client-contract.js";
4
+ export { buildApplication, generateNativeClientContract, startDevApplication, startDevServer, startProdServer, writeClientContract };
@@ -0,0 +1,46 @@
1
+ import { dirname, relative, resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { stat } from "node:fs/promises";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { HttpApi, OpenApi } from "effect/http-api";
6
+ //#region src/native-client-contract.ts
7
+ async function generateNativeClientContract(app, options) {
8
+ if (!app.client) throw new Error("Brick: configure client.module in Brick.app() with a browser-safe HttpApi export.");
9
+ const base = resolve(dirname(options.entry), app.client.module);
10
+ let modulePath;
11
+ for (const candidate of [
12
+ base,
13
+ base + ".ts",
14
+ base + ".tsx",
15
+ base + ".js",
16
+ base + ".mjs",
17
+ resolve(base, "index.ts")
18
+ ]) if (await stat(candidate).then((value) => value.isFile(), (error) => {
19
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
20
+ throw error;
21
+ })) {
22
+ modulePath = candidate;
23
+ break;
24
+ }
25
+ if (!modulePath) throw new Error(`Brick: cannot find client contract module '${app.client.module}'.`);
26
+ if (resolve(modulePath) === resolve(options.entry) || resolve(modulePath) === resolve(options.output)) throw new Error("Brick: the client contract must be a separate schema module.");
27
+ const name = app.client.exportName ?? "Api";
28
+ const api = (await (options.load ? options.load(modulePath) : import(pathToFileURL(modulePath).href)))[name];
29
+ if (!HttpApi.isHttpApi(api)) throw new Error(`Brick: ${app.client.module} must export a HttpApi named '${name}'.`);
30
+ const expected = app.openApi();
31
+ const actual = OpenApi.fromApi(api);
32
+ if (!isDeepStrictEqual(expected.paths, actual.paths) || !isDeepStrictEqual(expected.components, actual.components)) throw new Error("Brick: the browser contract differs from the application's routes or schemas.");
33
+ let specifier = relative(dirname(options.output), modulePath).replaceAll("\\", "/").replace(/\.(?:[cm]?ts|tsx)$/, "");
34
+ if (!specifier.startsWith(".")) specifier = "./" + specifier;
35
+ return `// Generated by Brick. Do not edit.
36
+ import { ${JSON.stringify(name)} as api } from ${JSON.stringify(specifier)};
37
+ import type { HttpApiClient } from "effect/http-api";
38
+ export { api };
39
+ export { createClient, createEffectClient } from "@brickkit/client";
40
+ export type AppClient = HttpApiClient.ForApi<typeof api>;
41
+ `;
42
+ }
43
+ //#endregion
44
+ export { generateNativeClientContract as t };
45
+
46
+ //# sourceMappingURL=native-client-contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-client-contract.js","names":[],"sources":["../src/native-client-contract.ts"],"sourcesContent":["import { dirname, relative, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { stat } from \"node:fs/promises\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { HttpApi, OpenApi } from \"effect/http-api\";\nimport type { NativeBrickApp } from \"@brickkit/core\";\n\nexport async function generateNativeClientContract(\n app: NativeBrickApp,\n options: {\n entry: string;\n output: string;\n load?: (path: string) => Promise<Record<string, unknown>>;\n },\n) {\n if (!app.client)\n throw new Error(\n \"Brick: configure client.module in Brick.app() with a browser-safe HttpApi export.\",\n );\n const base = resolve(dirname(options.entry), app.client.module);\n let modulePath: string | undefined;\n for (const candidate of [\n base,\n base + \".ts\",\n base + \".tsx\",\n base + \".js\",\n base + \".mjs\",\n resolve(base, \"index.ts\"),\n ]) {\n if (\n await stat(candidate).then(\n (value) => value.isFile(),\n (error) => {\n if (error.code === \"ENOENT\" || error.code === \"ENOTDIR\") return false;\n throw error;\n },\n )\n ) {\n modulePath = candidate;\n break;\n }\n }\n if (!modulePath)\n throw new Error(\n `Brick: cannot find client contract module '${app.client.module}'.`,\n );\n if (\n resolve(modulePath) === resolve(options.entry) ||\n resolve(modulePath) === resolve(options.output)\n ) {\n throw new Error(\n \"Brick: the client contract must be a separate schema module.\",\n );\n }\n const name = app.client.exportName ?? \"Api\";\n const module = await (options.load\n ? options.load(modulePath)\n : import(pathToFileURL(modulePath).href));\n const api: unknown = module[name];\n if (!HttpApi.isHttpApi(api))\n throw new Error(\n `Brick: ${app.client.module} must export a HttpApi named '${name}'.`,\n );\n const expected = app.openApi();\n const actual = OpenApi.fromApi(api);\n if (\n !isDeepStrictEqual(expected.paths, actual.paths) ||\n !isDeepStrictEqual(expected.components, actual.components)\n ) {\n throw new Error(\n \"Brick: the browser contract differs from the application's routes or schemas.\",\n );\n }\n let specifier = relative(dirname(options.output), modulePath)\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\.(?:[cm]?ts|tsx)$/, \"\");\n if (!specifier.startsWith(\".\")) specifier = \"./\" + specifier;\n return `// Generated by Brick. Do not edit.\nimport { ${JSON.stringify(name)} as api } from ${JSON.stringify(specifier)};\nimport type { HttpApiClient } from \"effect/http-api\";\nexport { api };\nexport { createClient, createEffectClient } from \"@brickkit/client\";\nexport type AppClient = HttpApiClient.ForApi<typeof api>;\n`;\n}\n"],"mappings":";;;;;;AAOA,eAAsB,6BACpB,KACA,SAKA;CACA,IAAI,CAAC,IAAI,QACP,MAAM,IAAI,MACR,mFACF;CACF,MAAM,OAAO,QAAQ,QAAQ,QAAQ,KAAK,GAAG,IAAI,OAAO,MAAM;CAC9D,IAAI;CACJ,KAAK,MAAM,aAAa;EACtB;EACA,OAAO;EACP,OAAO;EACP,OAAO;EACP,OAAO;EACP,QAAQ,MAAM,UAAU;CAC1B,GACE,IACE,MAAM,KAAK,SAAS,CAAC,CAAC,MACnB,UAAU,MAAM,OAAO,IACvB,UAAU;EACT,IAAI,MAAM,SAAS,YAAY,MAAM,SAAS,WAAW,OAAO;EAChE,MAAM;CACR,CACF,GACA;EACA,aAAa;EACb;CACF;CAEF,IAAI,CAAC,YACH,MAAM,IAAI,MACR,8CAA8C,IAAI,OAAO,OAAO,GAClE;CACF,IACE,QAAQ,UAAU,MAAM,QAAQ,QAAQ,KAAK,KAC7C,QAAQ,UAAU,MAAM,QAAQ,QAAQ,MAAM,GAE9C,MAAM,IAAI,MACR,8DACF;CAEF,MAAM,OAAO,IAAI,OAAO,cAAc;CAItC,MAAM,OAAe,OAHC,QAAQ,OAC1B,QAAQ,KAAK,UAAU,IACvB,OAAO,cAAc,UAAU,CAAC,CAAC,OAAA,CACT;CAC5B,IAAI,CAAC,QAAQ,UAAU,GAAG,GACxB,MAAM,IAAI,MACR,UAAU,IAAI,OAAO,OAAO,gCAAgC,KAAK,GACnE;CACF,MAAM,WAAW,IAAI,QAAQ;CAC7B,MAAM,SAAS,QAAQ,QAAQ,GAAG;CAClC,IACE,CAAC,kBAAkB,SAAS,OAAO,OAAO,KAAK,KAC/C,CAAC,kBAAkB,SAAS,YAAY,OAAO,UAAU,GAEzD,MAAM,IAAI,MACR,+EACF;CAEF,IAAI,YAAY,SAAS,QAAQ,QAAQ,MAAM,GAAG,UAAU,CAAC,CAC1D,WAAW,MAAM,GAAG,CAAC,CACrB,QAAQ,sBAAsB,EAAE;CACnC,IAAI,CAAC,UAAU,WAAW,GAAG,GAAG,YAAY,OAAO;CACnD,OAAO;WACE,KAAK,UAAU,IAAI,EAAE,iBAAiB,KAAK,UAAU,SAAS,EAAE;;;;;;AAM3E"}
package/dist/runner.js CHANGED
@@ -1,90 +1,77 @@
1
- import { brick, getPluginActionRoute, isBrickApp } from "@brickkit/core";
2
- import { existsSync, watch } from "fs";
3
- import { resolve } from "path";
4
- import { fileURLToPath } from "node:url";
5
- //#region src/runner.ts
6
- async function createServer(options, label, application) {
1
+ import { existsSync, watch } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { isNativeBrickApp } from "@brickkit/core";
5
+ //#region src/app-entry.ts
6
+ async function loadApplication(entry) {
7
+ const module = await import(pathToFileURL(resolve(entry)).href);
8
+ if (!isNativeBrickApp(module.default)) throw new Error("Brick: the entry module must default-export a BrickApp created by Brick.app().");
9
+ return module.default;
10
+ }
11
+ //#endregion
12
+ //#region src/port-utils.ts
13
+ function parsePort(portStr, envPort) {
7
14
  let port;
8
- if (options.port !== void 0) port = options.port;
9
- else if (process.env.PORT !== void 0 && process.env.PORT !== "") port = Number(process.env.PORT);
15
+ if (portStr !== void 0) port = Number(portStr);
16
+ else if (envPort !== void 0 && envPort !== "") port = Number(envPort);
10
17
  else port = 4e3;
11
18
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port: ${port}. Port must be an integer between 1 and 65535`);
12
- const app = application ?? brick({
13
- port,
14
- prefix: options.prefix
15
- });
16
- await app.listen({ port });
17
- const prefix = app.definition.prefix;
18
- const services = app.definition.services;
19
- console.log(`\n🧱 Brick-TS ${label} Server`);
20
- console.log(` Registered Services: ${services.length}`);
21
- for (const svc of services) {
22
- const actions = svc.listActions();
23
- console.log(` • ${svc.name} (${actions.length} actions)`);
24
- for (const act of actions) {
25
- const pluginRoute = getPluginActionRoute(act, prefix);
26
- if (pluginRoute === false) continue;
27
- const method = pluginRoute?.method ?? act.config.method ?? "POST";
28
- const path = pluginRoute?.path ?? act.config.path ?? `${prefix}/${svc.name}/${act.name}`;
29
- console.log(` -> ${method.padEnd(6)} ${path}`);
30
- }
31
- }
32
- console.log(`\n⚡ API Gateway running on: http://localhost:${port}`);
33
- console.log(`🩺 Health check: http://localhost:${port}/_health`);
34
- console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
35
- return app;
19
+ return port;
36
20
  }
37
- async function startProdServer(options = {}) {
38
- const entry = options.entry;
39
- if (entry) {
40
- const resolvedEntry = resolve(process.cwd(), entry);
41
- if (!existsSync(resolvedEntry)) {
42
- console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);
43
- process.exit(1);
44
- }
45
- console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
46
- await import(resolvedEntry);
21
+ //#endregion
22
+ //#region src/native-server.ts
23
+ async function startNativeServer(app, options = {}) {
24
+ let server;
25
+ try {
26
+ const port = parsePort(options.port === void 0 ? void 0 : String(options.port), process.env.PORT);
27
+ await app.ready();
28
+ server = Bun.serve({
29
+ port,
30
+ fetch: (request) => app.fetch(request)
31
+ });
32
+ } catch (error) {
33
+ await app.dispose();
34
+ throw error;
47
35
  }
48
- const port = options.port !== void 0 ? options.port : process.env.PORT !== void 0 && process.env.PORT !== "" ? Number(process.env.PORT) : 4e3;
49
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port: ${port}. Port must be an integer between 1 and 65535`);
50
- const app = brick({
51
- port,
52
- prefix: options.prefix
53
- });
54
- const prefix = app.definition.prefix;
55
- const services = app.definition.services;
56
- console.log(`\n🧱 Brick-TS Production Server`);
57
- console.log(` Registered Services: ${services.length}`);
58
- for (const svc of services) {
59
- const actions = svc.listActions();
60
- console.log(` • ${svc.name} (${actions.length} actions)`);
61
- for (const act of actions) {
62
- const pluginRoute = getPluginActionRoute(act, prefix);
63
- if (pluginRoute === false) continue;
64
- const method = pluginRoute?.method ?? act.config.method ?? "POST";
65
- const path = pluginRoute?.path ?? act.config.path ?? `${prefix}/${svc.name}/${act.name}`;
66
- console.log(` -> ${method.padEnd(6)} ${path}`);
36
+ let closing;
37
+ const stop = () => closing ??= (async () => {
38
+ process.off("SIGINT", onSignal);
39
+ process.off("SIGTERM", onSignal);
40
+ try {
41
+ await server.stop(true);
42
+ } finally {
43
+ await app.dispose();
67
44
  }
68
- }
69
- app.listen(port);
70
- console.log(`\n⚡ API Gateway running on: http://localhost:${port}`);
71
- console.log(`🩺 Health check: http://localhost:${port}/_health`);
72
- console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
73
- return app;
45
+ })();
46
+ const onSignal = () => {
47
+ stop().then(() => process.exit(0), (error) => {
48
+ console.error(error);
49
+ process.exit(1);
50
+ });
51
+ };
52
+ process.once("SIGINT", onSignal);
53
+ process.once("SIGTERM", onSignal);
54
+ console.log(`\n⚡ API Gateway running on: http://localhost:${server.port}`);
55
+ console.log(`🩺 Health check: http://localhost:${server.port}/_health`);
56
+ console.log(`🗺️ Architecture graph: http://localhost:${server.port}/_brick/services\n`);
57
+ return {
58
+ app,
59
+ server,
60
+ stop
61
+ };
74
62
  }
63
+ //#endregion
64
+ //#region src/runner.ts
75
65
  async function startDevApplication(options) {
76
- const module = options.entry ? await import(resolve(options.entry)) : void 0;
77
- if (isBrickApp(module?.default) && options.prefix !== void 0) console.warn(`[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`);
78
- return createServer(options, "Development", isBrickApp(module?.default) ? module.default : void 0);
66
+ if (!options.entry) throw new Error("Brick: an application entry is required.");
67
+ return startNativeServer(await loadApplication(options.entry), options);
79
68
  }
69
+ const startProdServer = startDevApplication;
80
70
  async function startDevServer(options = {}) {
81
71
  const entry = options.entry;
82
- if (!entry) return createServer(options, "Development");
72
+ if (!entry) throw new Error("Brick: an application entry is required.");
83
73
  const resolvedEntry = resolve(entry);
84
- if (!existsSync(resolvedEntry)) {
85
- console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);
86
- process.exit(1);
87
- }
74
+ if (!existsSync(resolvedEntry)) throw new Error(`Brick: entry not found: ${resolvedEntry}`);
88
75
  const worker = new URL(import.meta.url.endsWith(".ts") ? "./dev-worker.ts" : "./dev-worker.js", import.meta.url);
89
76
  let stopped = false;
90
77
  const intentionalExits = /* @__PURE__ */ new WeakSet();
@@ -93,8 +80,7 @@ async function startDevServer(options = {}) {
93
80
  process.execPath,
94
81
  fileURLToPath(worker),
95
82
  resolvedEntry,
96
- String(options.port ?? ""),
97
- options.prefix ?? ""
83
+ String(options.port ?? "")
98
84
  ], {
99
85
  cwd: process.cwd(),
100
86
  stdout: "inherit",
@@ -158,6 +144,6 @@ async function startDevServer(options = {}) {
158
144
  return { stop };
159
145
  }
160
146
  //#endregion
161
- export { startDevServer as n, startProdServer as r, startDevApplication as t };
147
+ export { loadApplication as a, parsePort as i, startDevServer as n, startProdServer as r, startDevApplication as t };
162
148
 
163
149
  //# sourceMappingURL=runner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","names":[],"sources":["../src/runner.ts"],"sourcesContent":["import { existsSync } from \"fs\";\nimport { watch } from \"fs\";\nimport { resolve } from \"path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n brick,\n getPluginActionRoute,\n isBrickApp,\n type BrickApp,\n} from \"@brickkit/core\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nasync function createServer(\n options: DevServerOptions,\n label: string,\n application?: BrickApp,\n) {\n let port: number;\n if (options.port !== undefined) {\n port = options.port;\n } else if (process.env.PORT !== undefined && process.env.PORT !== \"\") {\n port = Number(process.env.PORT);\n } else {\n port = 4000;\n }\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n application ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n await app.listen({ port });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS ${label} Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startProdServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n }\n\n const port =\n options.port !== undefined\n ? options.port\n : process.env.PORT !== undefined && process.env.PORT !== \"\"\n ? Number(process.env.PORT)\n : 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS Production Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startDevApplication(options: DevServerOptions) {\n const module = options.entry\n ? await import(resolve(options.entry))\n : undefined;\n if (isBrickApp(module?.default) && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`,\n );\n }\n return createServer(\n options,\n \"Development\",\n isBrickApp(module?.default) ? module.default : undefined,\n );\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry) return createServer(options, \"Development\");\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n\n const worker = new URL(\n import.meta.url.endsWith(\".ts\") ? \"./dev-worker.ts\" : \"./dev-worker.js\",\n import.meta.url,\n );\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const launch = () => {\n const application = Bun.spawn(\n [\n process.execPath,\n fileURLToPath(worker),\n resolvedEntry,\n String(options.port ?? \"\"),\n options.prefix ?? \"\",\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n void application.exited.then((code) => {\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 }\n });\n return application;\n };\n let child = launch();\n const watchDirs = [\n ...new Set([resolve(\"src\"), resolve(\"app\"), resolve(resolvedEntry, \"..\")]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart() {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\"\\n📝 Changes detected. Restarting server...\");\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 const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }),\n );\n const stop = () => {\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = () => {\n stop();\n 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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AC,OAAO,UAAU;CACnB,IAAI;CACJ,IAAI,aAAa;CACjB,IAAI,QAAQ;CAEZ,eAAe,UAAU;EACvB,QAAQ;EACR,IAAI,cAAc,SAAS;EAC3B,aAAa;EACb,IAAI;GACF,OAAO,SAAS,CAAC,SAAS;IACxB,QAAQ;IACR,QAAQ,IAAI,6CAA6C;IACzD,iBAAiB,IAAI,KAAK;IAC1B,MAAM,KAAK;IACX,MAAM,MAAM;IACZ,IAAI,CAAC,SAAS,QAAQ,OAAO;GAC/B;EACF,UAAU;GACR,aAAa;EACf;CACF;CAEA,MAAM,WAAW,UAAU,KAAK,QAC9B,MAAM,KAAK,EAAE,WAAW,KAAK,IAAI,QAAQ,aAAa;EACpD,IAAI,CAAC,YAAY,SAAS,MAAM,OAAO,CAAC,CAAC,SAAS,cAAc,GAAG;EACnE,aAAa,OAAO;EACpB,UAAU,iBAAiB;GACzB,QAAa;EACf,GAAG,GAAG;CACR,CAAC,CACH;CACA,MAAM,aAAa;EACjB,UAAU;EACV,aAAa,OAAO;EACpB,KAAK,MAAM,WAAW,UAAU,QAAQ,MAAM;EAC9C,MAAM,KAAK;EACX,QAAQ,IAAI,UAAU,QAAQ;EAC9B,QAAQ,IAAI,WAAW,QAAQ;EAC/B,QAAQ,IAAI,QAAQ,IAAI;CAC1B;CACA,MAAM,iBAAiB;EACrB,KAAK;EACL,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,UAAU,QAAQ;CAC7B,QAAQ,GAAG,WAAW,QAAQ;CAC9B,QAAQ,GAAG,QAAQ,IAAI;CACvB,QAAQ,IAAI,iCAAiC,UAAU,KAAK,IAAI,GAAG;CACnE,OAAO,EAAE,KAAK;AAChB"}
1
+ {"version":3,"file":"runner.js","names":[],"sources":["../src/app-entry.ts","../src/port-utils.ts","../src/native-server.ts","../src/runner.ts"],"sourcesContent":["import { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { isNativeBrickApp, type NativeBrickApp } from \"@brickkit/core\";\n\nexport async function loadApplication(entry: string): Promise<NativeBrickApp> {\n const module = await import(pathToFileURL(resolve(entry)).href);\n if (!isNativeBrickApp(module.default))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by Brick.app().\",\n );\n return module.default;\n}\n","export function parsePort(\n portStr: string | undefined,\n envPort?: string | undefined,\n): number {\n let port: number | undefined;\n if (portStr !== undefined) {\n port = Number(portStr);\n } else if (envPort !== undefined && envPort !== \"\") {\n port = Number(envPort);\n } else {\n port = 4000;\n }\n\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n return port;\n}\n","import type { NativeBrickApp } from \"@brickkit/core\";\nimport { parsePort } from \"./port-utils\";\n\nexport interface NativeServer {\n readonly app: NativeBrickApp;\n readonly server: Bun.Server<undefined>;\n stop(): Promise<void>;\n}\n\nexport async function startNativeServer(\n app: NativeBrickApp,\n options: { port?: number } = {},\n): Promise<NativeServer> {\n let server: Bun.Server<undefined>;\n try {\n const port = parsePort(\n options.port === undefined ? undefined : String(options.port),\n process.env.PORT,\n );\n await app.ready();\n server = Bun.serve({ port, fetch: (request) => app.fetch(request) });\n } catch (error) {\n await app.dispose();\n throw error;\n }\n let closing: Promise<void> | undefined;\n const stop = () =>\n (closing ??= (async () => {\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n try {\n await server.stop(true);\n } finally {\n await app.dispose();\n }\n })());\n const onSignal = () => {\n void stop().then(\n () => process.exit(0),\n (error) => {\n console.error(error);\n process.exit(1);\n },\n );\n };\n process.once(\"SIGINT\", onSignal);\n process.once(\"SIGTERM\", onSignal);\n console.log(`\\n⚡ API Gateway running on: http://localhost:${server.port}`);\n console.log(\n `🩺 Health check: http://localhost:${server.port}/_health`,\n );\n console.log(\n `🗺️ Architecture graph: http://localhost:${server.port}/_brick/services\\n`,\n );\n return { app, server, stop };\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadApplication } from \"./app-entry\";\nimport { startNativeServer } from \"./native-server\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n}\n\nexport async function startDevApplication(options: DevServerOptions) {\n if (!options.entry)\n throw new Error(\"Brick: an application entry is required.\");\n return startNativeServer(await loadApplication(options.entry), options);\n}\n\nexport const startProdServer = startDevApplication;\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry) throw new Error(\"Brick: an application entry is required.\");\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry)) {\n throw new Error(`Brick: entry not found: ${resolvedEntry}`);\n }\n\n const worker = new URL(\n import.meta.url.endsWith(\".ts\") ? \"./dev-worker.ts\" : \"./dev-worker.js\",\n import.meta.url,\n );\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const launch = () => {\n const application = Bun.spawn(\n [\n process.execPath,\n fileURLToPath(worker),\n resolvedEntry,\n String(options.port ?? \"\"),\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n void application.exited.then((code) => {\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 }\n });\n return application;\n };\n let child = launch();\n const watchDirs = [\n ...new Set([resolve(\"src\"), resolve(\"app\"), resolve(resolvedEntry, \"..\")]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart() {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\"\\n📝 Changes detected. Restarting server...\");\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 const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }),\n );\n const stop = () => {\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = () => {\n stop();\n 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"],"mappings":";;;;;AAIA,eAAsB,gBAAgB,OAAwC;CAC5E,MAAM,SAAS,MAAM,OAAO,cAAc,QAAQ,KAAK,CAAC,CAAC,CAAC;CAC1D,IAAI,CAAC,iBAAiB,OAAO,OAAO,GAClC,MAAM,IAAI,MACR,gFACF;CACF,OAAO,OAAO;AAChB;;;ACXA,SAAgB,UACd,SACA,SACQ;CACR,IAAI;CACJ,IAAI,YAAY,KAAA,GACd,OAAO,OAAO,OAAO;MAChB,IAAI,YAAY,KAAA,KAAa,YAAY,IAC9C,OAAO,OAAO,OAAO;MAErB,OAAO;CAGT,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MACR,iBAAiB,KAAK,8CACxB;CAEF,OAAO;AACT;;;ACVA,eAAsB,kBACpB,KACA,UAA6B,CAAC,GACP;CACvB,IAAI;CACJ,IAAI;EACF,MAAM,OAAO,UACX,QAAQ,SAAS,KAAA,IAAY,KAAA,IAAY,OAAO,QAAQ,IAAI,GAC5D,QAAQ,IAAI,IACd;EACA,MAAM,IAAI,MAAM;EAChB,SAAS,IAAI,MAAM;GAAE;GAAM,QAAQ,YAAY,IAAI,MAAM,OAAO;EAAE,CAAC;CACrE,SAAS,OAAO;EACd,MAAM,IAAI,QAAQ;EAClB,MAAM;CACR;CACA,IAAI;CACJ,MAAM,aAC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;CACA,QAAQ,GAAG,UAAU,QAAQ;CAC7B,QAAQ,GAAG,WAAW,QAAQ;CAC9B,QAAQ,GAAG,QAAQ,IAAI;CACvB,QAAQ,IAAI,iCAAiC,UAAU,KAAK,IAAI,GAAG;CACnE,OAAO,EAAE,KAAK;AAChB"}
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;iBAciB;;EAEf;;EAEA;;;wBAIc,YAAY,SAAS,2BAA2B"}
1
+ {"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;iBAeiB;;EAEf;;EAEA;;;wBAIc,YAAY,SAAS,2BAA2B"}
package/dist/vite.js CHANGED
@@ -1,6 +1,7 @@
1
- import { t as generateClientContract } from "./client-contract.js";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
1
+ import { t as generateNativeClientContract } from "./native-client-contract.js";
3
2
  import { dirname, resolve } from "node:path";
3
+ import { isNativeBrickApp } from "@brickkit/core";
4
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
4
5
  import { createServer, isRunnableDevEnvironment, normalizePath } from "vite";
5
6
  import { ModuleRunner } from "vite/module-runner";
6
7
  //#region src/vite.ts
@@ -13,17 +14,34 @@ function brickClient(options) {
13
14
  let config;
14
15
  let buildGeneration;
15
16
  let runner;
17
+ let ownedApp;
16
18
  let reload = Promise.resolve();
17
19
  const dependencies = /* @__PURE__ */ new Set();
18
- async function writeContract(value) {
19
- if (!value || typeof value.endpoint !== "function" || !value.definition) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
20
- const source = generateClientContract(value);
20
+ async function writeContract(value, load) {
21
+ if (!isNativeBrickApp(value)) throw new Error("Brick: the entry module must default-export a BrickApp created by Brick.app().");
22
+ const source = await generateNativeClientContract(value, {
23
+ entry,
24
+ output,
25
+ load
26
+ });
21
27
  if (await readFile(output, "utf8").catch((error) => {
22
28
  if (error.code !== "ENOENT") throw error;
23
29
  }) === source) return;
24
30
  await mkdir(dirname(output), { recursive: true });
25
31
  await writeFile(output, source);
26
32
  }
33
+ async function replaceContract(value, load) {
34
+ const candidate = isNativeBrickApp(value) ? value : void 0;
35
+ try {
36
+ await writeContract(value, load);
37
+ } catch (error) {
38
+ if (candidate !== ownedApp) await candidate?.dispose();
39
+ throw error;
40
+ }
41
+ const previous = ownedApp;
42
+ ownedApp = candidate;
43
+ if (previous !== candidate) await previous?.dispose();
44
+ }
27
45
  function collectDependencies(node, seen = /* @__PURE__ */ new Set()) {
28
46
  if (!node || seen.has(node)) return;
29
47
  seen.add(node);
@@ -46,7 +64,12 @@ function brickClient(options) {
46
64
  hmr: false,
47
65
  transport: { invoke: (payload) => environment.hot.handleInvoke(payload) }
48
66
  });
49
- await writeContract((await runner.import(entry)).default);
67
+ try {
68
+ await replaceContract((await runner.import(entry)).default, (path) => runner.import(path));
69
+ } catch (error) {
70
+ await runner.close();
71
+ throw error;
72
+ }
50
73
  dependencies.clear();
51
74
  collectDependencies(environment.moduleGraph.getModuleById(entry));
52
75
  dependencies.add(entry);
@@ -58,7 +81,7 @@ function brickClient(options) {
58
81
  reload = reload.catch(() => {}).then(async () => {
59
82
  for (const module of context.modules) this.environment.moduleGraph.invalidateModule(module);
60
83
  currentRunner.clearCache();
61
- await writeContract((await currentRunner.import(entry)).default);
84
+ await replaceContract((await currentRunner.import(entry)).default, (path) => currentRunner.import(path));
62
85
  dependencies.clear();
63
86
  collectDependencies(this.environment.moduleGraph.getModuleById(entry));
64
87
  dependencies.add(entry);
@@ -66,7 +89,13 @@ function brickClient(options) {
66
89
  await reload;
67
90
  },
68
91
  async closeBundle() {
69
- await runner?.close();
92
+ await reload.catch(() => {});
93
+ try {
94
+ await ownedApp?.dispose();
95
+ } finally {
96
+ ownedApp = void 0;
97
+ await runner?.close();
98
+ }
70
99
  },
71
100
  async buildStart() {
72
101
  if (config.command !== "build") return;
@@ -86,12 +115,19 @@ function brickClient(options) {
86
115
  watch: null
87
116
  }
88
117
  });
118
+ let buildApp;
89
119
  try {
90
120
  const environment = loader.environments.ssr;
91
121
  if (!environment || !isRunnableDevEnvironment(environment)) throw new Error("Brick: missing build-time SSR loader.");
92
- await writeContract((await environment.runner.import(entry)).default);
122
+ const value = (await environment.runner.import(entry)).default;
123
+ if (isNativeBrickApp(value)) buildApp = value;
124
+ await writeContract(value, (path) => environment.runner.import(path));
93
125
  } finally {
94
- await loader.close();
126
+ try {
127
+ await buildApp?.dispose();
128
+ } finally {
129
+ await loader.close();
130
+ }
95
131
  }
96
132
  })();
97
133
  await buildGeneration;
@@ -104,8 +140,8 @@ function brickClient(options) {
104
140
  load(id) {
105
141
  if (id !== resolvedId) return;
106
142
  return `import app from ${JSON.stringify(entry)};
107
- if (!app || typeof app.fetch !== "function" || typeof app.endpoint !== "function") {
108
- throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
143
+ if (!app || typeof app.fetch !== "function" || app.kind !== "brick-native-app") {
144
+ throw new Error("Brick: the entry module must default-export a BrickApp created by Brick.app().");
109
145
  }
110
146
  export default app;
111
147
  `;
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import { resolve, dirname } from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport {\n createServer,\n isRunnableDevEnvironment,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type EnvironmentModuleNode,\n} from \"vite\";\nimport { generateClientContract } from \"./client-contract\";\nimport type { BrickApp } from \"@brickkit/core\";\nimport { ModuleRunner } from \"vite/module-runner\";\n\nexport interface BrickClientPluginOptions {\n /** Any module whose default export is a BrickApp; do not call listen() there. */\n entry: string;\n /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */\n output?: string;\n}\n\n/** Load a BrickApp through Vite's server module graph, including dependency HMR. */\nexport function brickClient(options: BrickClientPluginOptions): Plugin {\n const virtualId = \"virtual:brick-app\";\n const resolvedId = \"\\0\" + virtualId;\n let entry: string;\n let output: string;\n let config: ResolvedConfig;\n let buildGeneration: Promise<void> | undefined;\n let runner: ModuleRunner | undefined;\n let reload = Promise.resolve();\n const dependencies = new Set<string>();\n\n async function writeContract(value: unknown) {\n if (\n !value ||\n typeof (value as BrickApp).endpoint !== \"function\" ||\n !(value as BrickApp).definition\n ) {\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n }\n const source = generateClientContract(value as BrickApp);\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous === source) return;\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, source);\n }\n\n function collectDependencies(\n node: EnvironmentModuleNode | undefined,\n seen = new Set<EnvironmentModuleNode>(),\n ) {\n if (!node || seen.has(node)) return;\n seen.add(node);\n if (node.file) dependencies.add(node.file);\n for (const imported of node.importedModules)\n collectDependencies(imported, seen);\n }\n\n return {\n name: \"brick:client\",\n enforce: \"pre\",\n configResolved(resolved) {\n config = resolved;\n entry = normalizePath(resolve(config.root, options.entry));\n output = normalizePath(\n resolve(config.root, options.output ?? \"_brick/contract.ts\"),\n );\n if (entry === output)\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n },\n async configureServer(server) {\n const environment = server.environments.ssr;\n if (!environment)\n throw new Error(\n \"Brick: client generation requires a Vite SSR environment.\",\n );\n // Frameworks such as Start own their SSR runner. Use an independent runner\n // on the same transform graph to read app metadata without changing theirs.\n runner = new ModuleRunner({\n hmr: false,\n transport: {\n invoke: (payload) => environment.hot.handleInvoke(payload),\n },\n });\n await writeContract((await runner.import(entry)).default);\n dependencies.clear();\n collectDependencies(environment.moduleGraph.getModuleById(entry));\n dependencies.add(entry);\n },\n async hotUpdate(context) {\n if (\n this.environment.name !== \"ssr\" ||\n !dependencies.has(context.file) ||\n context.file === output\n )\n return;\n if (!runner) return;\n const currentRunner = runner;\n reload = reload\n .catch(() => {})\n .then(async () => {\n for (const module of context.modules)\n this.environment.moduleGraph.invalidateModule(module);\n currentRunner.clearCache();\n await writeContract((await currentRunner.import(entry)).default);\n dependencies.clear();\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n dependencies.add(entry);\n });\n await reload;\n },\n async closeBundle() {\n await runner?.close();\n },\n async buildStart() {\n if (config.command !== \"build\") return;\n buildGeneration ??= (async () => {\n // Evaluate the server entry through Vite's TS/alias resolver before client compilation.\n // This loader has no app plugins, so it cannot recursively trigger generation.\n const loader = await createServer({\n configFile: false,\n root: config.root,\n mode: config.mode,\n envDir: config.envDir,\n base: config.base,\n define: config.define,\n logLevel: \"silent\",\n resolve: { alias: config.resolve.alias },\n ssr: config.ssr,\n server: { middlewareMode: true, watch: null },\n });\n try {\n const environment = loader.environments.ssr;\n if (!environment || !isRunnableDevEnvironment(environment))\n throw new Error(\"Brick: missing build-time SSR loader.\");\n await writeContract((await environment.runner.import(entry)).default);\n } finally {\n await loader.close();\n }\n })();\n await buildGeneration;\n },\n resolveId(id) {\n if (id !== virtualId) return;\n if (this.environment.config.consumer === \"client\") {\n throw new Error(\n \"Brick: virtual:brick-app is server-only; never import the backend app in the browser.\",\n );\n }\n return resolvedId;\n },\n load(id) {\n if (id !== resolvedId) return;\n return `import app from ${JSON.stringify(entry)};\nif (!app || typeof app.fetch !== \"function\" || typeof app.endpoint !== \"function\") {\n throw new Error(\"Brick: the entry module must default-export a BrickApp created by brick().\");\n}\nexport default app;\n`;\n },\n };\n}\n"],"mappings":";;;;;;;AAsBA,SAAgB,YAAY,SAA2C;CACrE,MAAM,YAAY;CAClB,MAAM,aAAa,OAAO;CAC1B,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,QAAQ,QAAQ;CAC7B,MAAM,+BAAe,IAAI,IAAY;CAErC,eAAe,cAAc,OAAgB;EAC3C,IACE,CAAC,SACD,OAAQ,MAAmB,aAAa,cACxC,CAAE,MAAmB,YAErB,MAAM,IAAI,MACR,4EACF;EAEF,M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ources":["../src/vite.ts"],"sourcesContent":["import { resolve, dirname } from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport {\n createServer,\n isRunnableDevEnvironment,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type EnvironmentModuleNode,\n} from \"vite\";\nimport type { NativeBrickApp } from \"@brickkit/core\";\nimport { isNativeBrickApp } from \"@brickkit/core\";\nimport { generateNativeClientContract } from \"./native-client-contract\";\nimport { ModuleRunner } from \"vite/module-runner\";\n\nexport interface BrickClientPluginOptions {\n /** Any module whose default export is a BrickApp; do not call listen() there. */\n entry: string;\n /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */\n output?: string;\n}\n\n/** Load a BrickApp through Vite's server module graph, including dependency HMR. */\nexport function brickClient(options: BrickClientPluginOptions): Plugin {\n const virtualId = \"virtual:brick-app\";\n const resolvedId = \"\\0\" + virtualId;\n let entry: string;\n let output: string;\n let config: ResolvedConfig;\n let buildGeneration: Promise<void> | undefined;\n let runner: ModuleRunner | undefined;\n let ownedApp: NativeBrickApp | undefined;\n let reload = Promise.resolve();\n const dependencies = new Set<string>();\n\n async function writeContract(\n value: unknown,\n load?: (path: string) => Promise<Record<string, unknown>>,\n ) {\n if (!isNativeBrickApp(value))\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by Brick.app().\",\n );\n const source = await generateNativeClientContract(value, {\n entry,\n output,\n load,\n });\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous === source) return;\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, source);\n }\n\n async function replaceContract(\n value: unknown,\n load: (path: string) => Promise<Record<string, unknown>>,\n ) {\n const candidate = isNativeBrickApp(value) ? value : undefined;\n try {\n await writeContract(value, load);\n } catch (error) {\n if (candidate !== ownedApp) await candidate?.dispose();\n throw error;\n }\n const previous = ownedApp;\n ownedApp = candidate;\n if (previous !== candidate) await previous?.dispose();\n }\n\n function collectDependencies(\n node: EnvironmentModuleNode | undefined,\n seen = new Set<EnvironmentModuleNode>(),\n ) {\n if (!node || seen.has(node)) return;\n seen.add(node);\n if (node.file) dependencies.add(node.file);\n for (const imported of node.importedModules)\n collectDependencies(imported, seen);\n }\n\n return {\n name: \"brick:client\",\n enforce: \"pre\",\n configResolved(resolved) {\n config = resolved;\n entry = normalizePath(resolve(config.root, options.entry));\n output = normalizePath(\n resolve(config.root, options.output ?? \"_brick/contract.ts\"),\n );\n if (entry === output)\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n },\n async configureServer(server) {\n const environment = server.environments.ssr;\n if (!environment)\n throw new Error(\n \"Brick: client generation requires a Vite SSR environment.\",\n );\n // Frameworks such as Start own their SSR runner. Use an independent runner\n // on the same transform graph to read app metadata without changing theirs.\n runner = new ModuleRunner({\n hmr: false,\n transport: {\n invoke: (payload) => environment.hot.handleInvoke(payload),\n },\n });\n try {\n await replaceContract((await runner.import(entry)).default, (path) =>\n runner!.import(path),\n );\n } catch (error) {\n await runner.close();\n throw error;\n }\n dependencies.clear();\n collectDependencies(environment.moduleGraph.getModuleById(entry));\n dependencies.add(entry);\n },\n async hotUpdate(context) {\n if (\n this.environment.name !== \"ssr\" ||\n !dependencies.has(context.file) ||\n context.file === output\n )\n return;\n if (!runner) return;\n const currentRunner = runner;\n reload = reload\n .catch(() => {})\n .then(async () => {\n for (const module of context.modules)\n this.environment.moduleGraph.invalidateModule(module);\n currentRunner.clearCache();\n await replaceContract(\n (await currentRunner.import(entry)).default,\n (path) => currentRunner.import(path),\n );\n dependencies.clear();\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n dependencies.add(entry);\n });\n await reload;\n },\n async closeBundle() {\n await reload.catch(() => {});\n try {\n await ownedApp?.dispose();\n } finally {\n ownedApp = undefined;\n await runner?.close();\n }\n },\n async buildStart() {\n if (config.command !== \"build\") return;\n buildGeneration ??= (async () => {\n // Evaluate the server entry through Vite's TS/alias resolver before client compilation.\n // This loader has no app plugins, so it cannot recursively trigger generation.\n const loader = await createServer({\n configFile: false,\n root: config.root,\n mode: config.mode,\n envDir: config.envDir,\n base: config.base,\n define: config.define,\n logLevel: \"silent\",\n resolve: { alias: config.resolve.alias },\n ssr: config.ssr,\n server: { middlewareMode: true, watch: null },\n });\n let buildApp: NativeBrickApp | undefined;\n try {\n const environment = loader.environments.ssr;\n if (!environment || !isRunnableDevEnvironment(environment))\n throw new Error(\"Brick: missing build-time SSR loader.\");\n const value: unknown = (await environment.runner.import(entry))\n .default;\n if (isNativeBrickApp(value)) buildApp = value;\n await writeContract(value, (path) => environment.runner.import(path));\n } finally {\n try {\n await buildApp?.dispose();\n } finally {\n await loader.close();\n }\n }\n })();\n await buildGeneration;\n },\n resolveId(id) {\n if (id !== virtualId) return;\n if (this.environment.config.consumer === \"client\") {\n throw new Error(\n \"Brick: virtual:brick-app is server-only; never import the backend app in the browser.\",\n );\n }\n return resolvedId;\n },\n load(id) {\n if (id !== resolvedId) return;\n return `import app from ${JSON.stringify(entry)};\nif (!app || typeof app.fetch !== \"function\" || app.kind !== \"brick-native-app\") {\n throw new Error(\"Brick: the entry module must default-export a BrickApp created by Brick.app().\");\n}\nexport default app;\n`;\n },\n };\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,YAAY,SAA2C;CACrE,MAAM,YAAY;CAClB,MAAM,aAAa,OAAO;CAC1B,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,QAAQ,QAAQ;CAC7B,MAAM,+BAAe,IAAI,IAAY;CAErC,eAAe,cACb,OACA,MACA;EACA,IAAI,CAAC,iBAAiB,KAAK,GACzB,MAAM,IAAI,MACR,gFACF;EACF,MAAM,SAAS,MAAM,6BAA6B,OAAO;GACvD;GACA;GACA;EACF,CAAC;EAKD,IAAI,MAJmB,SAAS,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAU;GAC/D,IAAI,MAAM,SAAS,UAAU,MAAM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AAM,SAAkB,MAAM,YAAY,OAAO,OAAO,KAAK,EAAA,CAC1D;KACH,IAAI,iBAAiB,KAAK,GAAG,WAAW;KACxC,MAAM,cAAc,QAAQ,SAAS,YAAY,OAAO,OAAO,IAAI,CAAC;IACtE,UAAU;KACR,IAAI;MACF,MAAM,UAAU,QAAQ;KAC1B,UAAU;MACR,MAAM,OAAO,MAAM;KACrB;IACF;GACF,EAAA,CAAG;GACH,MAAM;EACR;EACA,UAAU,IAAI;GACZ,IAAI,OAAO,WAAW;GACtB,IAAI,KAAK,YAAY,OAAO,aAAa,UACvC,MAAM,IAAI,MACR,uFACF;GAEF,OAAO;EACT;EACA,KAAK,IAAI;GACP,IAAI,OAAO,YAAY;GACvB,OAAO,mBAAmB,KAAK,UAAU,KAAK,EAAE;;;;;;EAMlD;CACF;AACF"}
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "@brickkit/cli",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "CLI and server engine for Brick-TS",
5
5
  "keywords": [
6
6
  "typescript",
7
7
  "bun",
8
8
  "cli",
9
9
  "dev-server",
10
- "elysia",
11
10
  "openapi-generator",
12
11
  "typed-client",
13
12
  "vite-plugin",
@@ -27,10 +26,6 @@
27
26
  "import": "./dist/index.js",
28
27
  "types": "./dist/index.d.ts"
29
28
  },
30
- "./compiler": {
31
- "import": "./dist/compiler.js",
32
- "types": "./dist/compiler.d.ts"
33
- },
34
29
  "./vite": {
35
30
  "import": "./dist/vite.js",
36
31
  "types": "./dist/vite.d.ts"
@@ -61,10 +56,9 @@
61
56
  "format:check": "oxfmt --check ."
62
57
  },
63
58
  "dependencies": {
64
- "@brickkit/core": "^0.4.2",
65
- "@sinclair/typebox": "^0.34.52",
59
+ "@brickkit/core": "^0.6.0",
66
60
  "commander": "^15.0.0",
67
- "elysia": "2.0.0-beta.29"
61
+ "effect": "4.0.4"
68
62
  },
69
63
  "devDependencies": {
70
64
  "@types/bun": "^1.4.3",