@brickkit/cli 0.0.0-stage → 0.2.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":"build.js","names":["resolve"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/runner.ts","../src/build.ts"],"sourcesContent":["import { Elysia, type Context } from \"elysia\";\n\nexport interface RequestLoggingOptions {\n enabled?: boolean;\n logger?: (msg: string) => void;\n}\n\nfunction formatLog(\n method: string,\n path: string,\n status: string | number,\n elapsedMs: number,\n): string {\n return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;\n}\n\n/**\n * Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError\n * while `set.status` may still hold the 200 default when onError runs).\n */\nfunction thrownStatus(error: unknown): number | undefined {\n if (typeof error === \"object\" && error !== null && \"status\" in error) {\n const status: unknown = error.status;\n if (typeof status === \"number\") return status;\n }\n return undefined;\n}\n\n/**\n * Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.\n * Timing is tracked per-Request via a WeakMap. The onError hook only logs and\n * returns undefined so existing error mapping is preserved. Logging only —\n * no CORS headers are set here.\n *\n * Hooks are registered with `{ as: \"global\" }` so they propagate to the\n * parent app when mounted via `app.use(...)` — Elysia scopes plain instance\n * hooks to the plugin's own routes. Timing is captured in onBeforeHandle\n * because onRequest offers no `as` option and is never propagated from a\n * used instance. Unmatched routes (no beforeHandle) fall back to Date.now().\n */\nexport function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia {\n const plugin = new Elysia();\n const enabled = opts.enabled ?? true;\n if (!enabled) return plugin;\n const logger = opts.logger ?? console.log;\n const startedAt = new WeakMap<object, number>();\n\n const markStarted = ({ request }: Pick<Context, \"request\">): void => {\n startedAt.set(request, Date.now());\n };\n\n const logSuccess = ({\n request,\n set,\n }: Pick<Context, \"request\" | \"set\">): void => {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n logger(\n formatLog(request.method, path, set.status ?? 200, Date.now() - start),\n );\n };\n\n const logError = ({\n request,\n set,\n error,\n }: Pick<Context, \"request\" | \"set\"> & { error?: unknown }): undefined => {\n if (request) {\n const start = startedAt.get(request) ?? Date.now();\n const path = new URL(request.url).pathname;\n const status = thrownStatus(error) ?? set.status ?? 500;\n logger(formatLog(request.method, path, status, Date.now() - start));\n }\n return undefined;\n };\n\n plugin.onBeforeHandle({ as: \"global\" }, markStarted);\n plugin.onAfterHandle({ as: \"global\" }, logSuccess);\n plugin.onError({ as: \"global\" }, logError);\n\n return plugin;\n}\n","import { Elysia, type Context } from \"elysia\";\n\nexport interface ReferenceOptions {\n path?: string;\n title?: string;\n specUrl?: string;\n}\n\n/** Renders the Scalar API reference page for the given OpenAPI URL. */\nexport function scalarDocsHTML(specUrl: string, title: string): string {\n return `<!doctype html>\n<html>\n <head>\n <title>${title} — API Reference</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"https://scalar.com/favicon.svg\" />\n <style>\n body { margin: 0; padding: 0; height: 100vh; }\n </style>\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"${specUrl}\"\n data-configuration='{\"theme\": \"purple\", \"layout\": \"modern\"}'\n src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\">\n </script>\n </body>\n</html>`;\n}\n\n/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */\nexport function referencePlugin(opts: ReferenceOptions = {}): Elysia {\n const path = opts.path ?? \"/reference\";\n const title = opts.title ?? \"Brick-TS API Mesh\";\n const specUrl = opts.specUrl ?? \"/openapi.json\";\n const plugin = new Elysia();\n plugin.get(path, ({ set }: Context) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(specUrl, title);\n });\n return plugin;\n}\n\n/** Mounts the Scalar reference route onto an existing app. */\nexport function registerReferenceRoute(\n app: Elysia,\n opts: ReferenceOptions = {},\n): Elysia {\n return app.use(referencePlugin(opts)) as Elysia;\n}\n\n/** Renders the Swagger UI page. */\nexport function swaggerDocsHTML(specUrl: string, title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>${title} — Swagger UI</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css\" />\n <style>\n html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }\n *, *:before, *:after { box-sizing: inherit; }\n body { margin:0; background: #fafafa; }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js\" charset=\"UTF-8\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: \"${specUrl}\",\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\"\n });\n };\n </script>\n </body>\n</html>`;\n}\n","import type { Elysia } from \"elysia\";\nimport type { Service, DatabaseHandle } from \"@brickkit/core\";\nimport { ActionExecutionError, ValidationError } from \"@brickkit/core\";\n\nexport type EndpointMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Logger subset handed to endpoint handlers (mirrors action context loggers). */\nexport interface EndpointLogger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/** Context for raw endpoint handlers: Elysia route fields + Brick extras. */\nexport interface EndpointContext {\n params: Record<string, string>;\n query: Record<string, string | undefined>;\n body: unknown;\n headers: Record<string, string>;\n request: Request;\n /** Elysia response setter (status/headers). Mutate like in `app.get`. */\n set: { status?: number; headers: Record<string, string> };\n /** Drizzle db from `service` (or first service with one); `undefined` when none. */\n db: any;\n logger: EndpointLogger;\n traceId: string;\n requestId: string;\n}\n\nexport interface EndpointDefinition {\n method: EndpointMethod;\n /** Elysia-style path, e.g. `/p/:slug`. */\n path: string;\n handler: (ctx: EndpointContext) => unknown | Promise<unknown>;\n /** Db source: instance or registered service name. Defaults to first service with a db. */\n service?: Service<any, any> | string;\n /** Explicit database handle, independent of a service. */\n database?: DatabaseHandle<unknown>;\n summary?: string;\n description?: string;\n tags?: string[];\n}\n\n/** Resolve the db for an endpoint: explicit service first, else first service holding one. */\nexport function resolveEndpointDb(\n service: Service<any, any> | string | undefined,\n services: Service<any, any>[],\n): any {\n if (service) {\n const svc =\n typeof service === \"string\"\n ? services.find((s) => s.name === service)\n : (service as Service<any, any>);\n return svc?.getDb() ?? undefined;\n }\n for (const svc of services) {\n const db = svc.getDb();\n if (db) return db;\n }\n return undefined;\n}\n\n/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */\nexport function createEndpointHandler(\n def: EndpointDefinition,\n services: Service<any, any>[],\n): (elysiaCtx: any) => Promise<unknown> {\n return async ({ params, body, query, headers, request, set }: any) => {\n const traceId =\n headers?.[\"x-trace-id\"] ||\n `tr_${Math.random().toString(36).substring(2, 10)}`;\n const requestId =\n headers?.[\"x-request-id\"] ||\n `req_${Math.random().toString(36).substring(2, 10)}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n const tag = `endpoint:${def.method} ${def.path}`;\n const ctx: EndpointContext = {\n body,\n db: def.database\n ? def.database.getDb()\n : resolveEndpointDb(def.service, services),\n headers: headers ?? {},\n logger: {\n info: (...args) => console.log(`[${tag}]`, ...args),\n warn: (...args) => console.warn(`[${tag}]`, ...args),\n error: (...args) => console.error(`[${tag}]`, ...args),\n debug: (...args) => console.debug(`[${tag}]`, ...args),\n },\n params: params ?? {},\n query: query ?? {},\n request:\n request instanceof Request\n ? request\n : new Request(`http://localhost${def.path}`, {\n headers: new Headers((headers as Record<string, string>) ?? {}),\n method: def.method,\n }),\n requestId,\n set,\n traceId,\n };\n\n try {\n return await def.handler(ctx);\n } catch (err: any) {\n if (err instanceof ValidationError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n if (typeof err?.status === \"number\") {\n set.status = err.status;\n return { message: err.message || \"Endpoint error\", status: err.status };\n }\n set.status = 500;\n return {\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n };\n}\n\n/** `/p/:slug` → `/p/{slug}` for OpenAPI. */\nexport function toOpenApiPath(elysiaPath: string): string {\n return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\n/** Parameter names (`:slug`) extracted for the OpenAPI path item. */\nfunction pathParamNames(elysiaPath: string): string[] {\n return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);\n}\n\n/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */\nexport function endpointPaths(defs: EndpointDefinition[]): Record<string, any> {\n const paths: Record<string, any> = {};\n for (const def of defs) {\n const openApiPath = toOpenApiPath(def.path);\n if (!paths[openApiPath]) paths[openApiPath] = {};\n const params = pathParamNames(def.path).map((name) => ({\n in: \"path\",\n name,\n required: true,\n schema: { type: \"string\" },\n }));\n paths[openApiPath][def.method.toLowerCase()] = {\n ...(def.summary ? { summary: def.summary } : {}),\n ...(def.description ? { description: def.description } : {}),\n ...(def.tags ? { tags: def.tags } : {}),\n ...(params.length > 0 ? { parameters: params } : {}),\n responses: { 200: { description: \"Successful response\" } },\n };\n }\n return paths;\n}\n\n/** The app object returned by `brick`: Elysia plus `endpoint()`. */\nexport type BrickApp = Elysia<any, any, any, any, any, any, any> & {\n /** Register a raw endpoint (outside the JSON action mesh). */\n endpoint(def: EndpointDefinition): void;\n /** All endpoints registered via `endpoint()` (declaration order). */\n listEndpoints(): EndpointDefinition[];\n};\n","import { Elysia } from \"elysia\";\nimport { compileBrickApplication, type CompiledApplication } from \"./compiler\";\nimport {\n type Service,\n getGlobalRegistry,\n generateOpenApiSpec,\n resolveSecrets,\n type SecretSource,\n} from \"@brickkit/core\";\nimport {\n requestLoggingPlugin,\n type RequestLoggingOptions,\n} from \"./request-logger\";\nimport {\n scalarDocsHTML,\n swaggerDocsHTML,\n registerReferenceRoute,\n type ReferenceOptions,\n} from \"./docs\";\nimport {\n createEndpointHandler,\n endpointPaths,\n type BrickApp,\n type EndpointDefinition,\n} from \"./endpoints\";\n\nexport interface CreateServerOptions {\n port?: number;\n /** Generate specialized handlers once at startup (default true). */\n compiler?: boolean;\n /** Ahead-of-time handlers already bound to the supplied services. */\n compilation?: CompiledApplication;\n services?: Service<any, any>[];\n prefix?: string;\n title?: string;\n version?: string;\n description?: string;\n docs?: boolean;\n openApiPath?: string;\n docsPath?: string;\n swaggerPath?: string;\n requestLogging?: boolean | RequestLoggingOptions; // default true\n reference?: boolean | ReferenceOptions; // default false, path \"/reference\"\n secrets?: { source?: SecretSource; validate?: boolean };\n /** Raw endpoints (outside the JSON action mesh), mounted at startup. */\n endpoints?: EndpointDefinition[];\n}\n\nexport {\n compileRoutePlan,\n executeCompiledRoute,\n createActionHandler,\n} from \"./action-handler\";\n\nexport function brick(options: CreateServerOptions = {}): BrickApp {\n const prefix = options.prefix ?? options.compilation?.ir.prefix ?? \"/api\";\n const title = options.title ?? \"Brick-TS API Mesh\";\n const version = options.version ?? \"1.0.0\";\n const compiled = options.compiler !== false;\n const enableDocs = options.docs ?? true;\n const openApiPath = options.openApiPath ?? \"/openapi.json\";\n const docsPath = options.docsPath ?? \"/docs\";\n const swaggerPath = options.swaggerPath ?? \"/swagger\";\n\n const app = new Elysia();\n\n // Fail fast on missing required secrets before serving anything.\n // No-op when no secrets are registered.\n if (options.secrets?.validate !== false) {\n resolveSecrets({ source: options.secrets?.source });\n }\n\n // Diagnostics & health\n app.get(\"/_health\", () => ({\n status: \"ok\",\n uptime: process.uptime(),\n timestamp: Date.now(),\n }));\n\n // Serialize stable metadata once; registry changes invalidate the snapshot.\n app.get(\n \"/_brick/services\",\n compiled\n ? cachedJsonRoute(\n () => getGlobalRegistry().exportArchitecture(),\n () => {\n const registry = getGlobalRegistry();\n return [registry, registry.revision] as const;\n },\n )\n : () => getGlobalRegistry().exportArchitecture(),\n );\n\n // Request logging first so every route below is timed.\n const requestLogging = options.requestLogging ?? true;\n if (requestLogging !== false) {\n const pluginOpts = requestLogging === true ? {} : requestLogging;\n if (pluginOpts.enabled !== false) {\n app.use(requestLoggingPlugin(pluginOpts));\n }\n }\n\n // Scalar API reference (opt-in). Defaults to openApiPath for the spec URL.\n const reference = options.reference ?? false;\n if (reference !== false) {\n const refOpts = reference === true ? {} : reference;\n const settings = {\n path: refOpts.path ?? \"/reference\",\n title: refOpts.title ?? title,\n specUrl: refOpts.specUrl ?? openApiPath,\n };\n if (compiled)\n app.get(\n settings.path,\n htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)),\n );\n else registerReferenceRoute(app, settings);\n }\n\n const services = options.services ?? getGlobalRegistry().list();\n\n // Precompute plans and freeze immutable plans across all services\n for (const service of services) {\n if (typeof (service as any).build === \"function\") {\n (service as any).build();\n }\n }\n\n // Raw endpoints declared via options or app.endpoint() (declaration order).\n const endpointDefs: EndpointDefinition[] = [];\n let endpointRevision = 0;\n\n // OpenAPI 3.1 & Interactive Documentation Endpoints\n if (enableDocs) {\n const buildSpec = () => {\n const spec = generateOpenApiSpec({\n title,\n version,\n description: options.description,\n prefix,\n services,\n });\n // Raw endpoints show up in the spec alongside the action mesh.\n return {\n ...spec,\n paths: { ...spec.paths, ...endpointPaths(endpointDefs) },\n };\n };\n app.get(\n openApiPath,\n compiled\n ? cachedJsonRoute(\n buildSpec,\n () =>\n [\n getGlobalRegistry(),\n getGlobalRegistry().revision + endpointRevision,\n ] as const,\n )\n : buildSpec,\n );\n\n if (compiled) {\n app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));\n app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));\n } else {\n app.get(docsPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return scalarDocsHTML(openApiPath, title);\n });\n\n app.get(swaggerPath, ({ set }) => {\n set.headers[\"content-type\"] = \"text/html; charset=utf-8\";\n return swaggerDocsHTML(openApiPath, title);\n });\n }\n }\n\n // Dedicated Route Registry\n const registeredRoutes = new Set<string>();\n\n const mountRoute = (\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n handler: any,\n ) => {\n const routeKey = `${method} ${path}`;\n if (registeredRoutes.has(routeKey)) {\n return;\n }\n registeredRoutes.add(routeKey);\n\n switch (method) {\n case \"GET\":\n app.get(path, handler);\n break;\n case \"POST\":\n app.post(path, handler);\n break;\n case \"PUT\":\n app.put(path, handler);\n break;\n case \"PATCH\":\n app.patch(path, handler);\n break;\n case \"DELETE\":\n app.delete(path, handler);\n break;\n }\n };\n\n // Raw endpoints (outside the JSON action mesh).\n const mountEndpoint = (def: EndpointDefinition) => {\n endpointDefs.push(def);\n endpointRevision++;\n mountRoute(def.method, def.path, createEndpointHandler(def, services));\n };\n\n for (const def of options.endpoints ?? []) {\n mountEndpoint(def);\n }\n\n const brickApp = app as unknown as BrickApp;\n brickApp.endpoint = (def: EndpointDefinition) => {\n mountEndpoint(def);\n };\n brickApp.listEndpoints = () => [...endpointDefs];\n\n const compilation =\n options.compilation ??\n compileBrickApplication({\n services,\n prefix,\n mode: options.compiler === false ? \"generic\" : \"specialized\",\n });\n if (\n compilation.ir.prefix !== prefix ||\n JSON.stringify(compilation.ir.services) !==\n JSON.stringify(services.map((service) => service.name))\n ) {\n throw new Error(\n \"Brick compiler: server services/prefix differ from the bound compilation\",\n );\n }\n for (const route of compilation.routes)\n mountRoute(route.ir.method, route.ir.path, route.handler);\n\n return brickApp;\n}\n\nfunction htmlResponse(html: string): Response {\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Reuse serialized JSON, without sharing a mutable response body between requests. */\nfunction cachedJsonRoute(\n build: () => unknown,\n revision: () => readonly [unknown, number],\n) {\n let [owner, version] = revision();\n let json = JSON.stringify(build());\n return ({ set }: { set: { headers: Record<string, unknown> } }) => {\n const [currentOwner, currentVersion] = revision();\n if (currentOwner !== owner || currentVersion !== version) {\n json = JSON.stringify(build());\n owner = currentOwner;\n version = currentVersion;\n }\n set.headers[\"content-type\"] = \"application/json;charset=utf-8\";\n return json;\n };\n}\n","import { existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { brick } from \"./server\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const port = options.port ?? (Number(process.env.PORT) || 4000);\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (existsSync(resolvedEntry)) {\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n } else {\n console.warn(`[Brick-TS] Specified entry not found: ${resolvedEntry}`);\n }\n }\n\n const registry = getGlobalRegistry();\n const services = registry.list();\n\n console.log(`\\n🧱 Brick-TS Development Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n console.log(` • ${svc.name} (${svc.listActions().length} actions)`);\n if (typeof (svc as any).listResources === \"function\") {\n for (const res of (svc as any).listResources()) {\n console.log(\n ` -> Resource: /api/${res.name} (REST: GET, POST, /:id: GET, PATCH, DELETE)`,\n );\n }\n }\n for (const act of svc.listActions()) {\n console.log(` -> Action: /api/${svc.name}/${act.name}`);\n }\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\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","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { compileBrickApplication, emitCompiledApplication } from \"./compiler\";\n\nexport interface BuildApplicationOptions {\n /** A module that registers services, without starting a server. */\n entry: string;\n outdir?: string;\n prefix?: string;\n port?: number;\n requestLogging?: boolean;\n}\n\n/** Analyze definitions and bundle the emitted handlers with the user's callbacks. */\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 < 0 || port > 65535)\n throw new Error(\n \"Brick compiler: port must be an integer between 0 and 65535\",\n );\n await import(pathToFileURL(entry).href);\n const services = getGlobalRegistry().list();\n if (!services.length)\n throw new Error(\n \"Brick compiler: entry registered no services; use a definitions module\",\n );\n const compilation = compileBrickApplication({\n services,\n prefix: options.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 ${JSON.stringify(entry)};\nimport { brick } from \"@brickkit/cli\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { bind } from \"./routes.js\";\nconst services = getGlobalRegistry().list();\nexport const app = brick({ services, compilation: bind(services), requestLogging: ${options.requestLogging ?? true} });\nif (import.meta.main) {\n const port = Number(process.env.PORT ?? ${port});\n if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(\"Invalid PORT\");\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 });\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":";;;;;;;;;AAOA,SAAS,UACP,QACA,MACA,QACA,WACQ;CACR,OAAO,GAAG,OAAO,GAAG,KAAK,KAAK,OAAO,MAAM,EAAE,IAAI,UAAU;AAC7D;;;;;AAMA,SAAS,aAAa,OAAoC;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,OAAO;EACpE,MAAM,SAAkB,MAAM;EAC9B,IAAI,OAAO,WAAW,UAAU,OAAO;CACzC;AAEF;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,OAA8B,CAAC,GAAW;CAC7E,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,EADY,KAAK,WAAW,OAClB,OAAO;CACrB,MAAM,SAAS,KAAK,UAAU,QAAQ;CACtC,MAAM,4BAAY,IAAI,QAAwB;CAE9C,MAAM,eAAe,EAAE,cAA8C;EACnE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Ae,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,91 @@
1
+ import { CompiledRoutePlan, ResourceReadQueries, Service } from "@brickkit/core";
2
+ //#region src/compiler/ir.d.ts
3
+ type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
4
+ interface RouteIR {
5
+ readonly method: RouteMethod;
6
+ readonly path: string;
7
+ readonly service: string;
8
+ readonly action: string;
9
+ readonly kind: "action" | "resource";
10
+ readonly input: boolean;
11
+ readonly output: boolean;
12
+ readonly context: boolean;
13
+ readonly authorize: boolean;
14
+ readonly inputPrecedence: readonly ("query" | "params" | "body")[];
15
+ readonly coercions: readonly {
16
+ readonly key: string;
17
+ readonly type: "number" | "boolean";
18
+ }[];
19
+ /** JSON projection for inspection and stale-artifact detection, not runtime validation. */
20
+ readonly inputSchema?: unknown;
21
+ readonly outputSchema?: unknown;
22
+ }
23
+ interface BrickIR {
24
+ readonly version: 1;
25
+ readonly target: "bun-elysia";
26
+ readonly prefix: string;
27
+ readonly services: readonly string[];
28
+ readonly routes: readonly RouteIR[];
29
+ readonly reads: readonly ResourceReadQueries[];
30
+ readonly diagnostics: readonly string[];
31
+ }
32
+ //#endregion
33
+ //#region src/compiler/runtime.d.ts
34
+ type CompiledHandler = (context: any) => unknown | Promise<unknown>;
35
+ type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;
36
+ /** Retains Brick's existing source precedence and treatment of empty bodies. */
37
+ declare function mergeInput(first: any, second: any, third: any): any;
38
+ declare function validate(check: NonNullable<CompiledRoutePlan["inputChecker"]>, value: unknown, action: string, stage: "input" | "output"): void;
39
+ declare function mapError(err: any, set: any): {
40
+ name: string;
41
+ code: string;
42
+ message: string;
43
+ status: number;
44
+ details: unknown;
45
+ } | {
46
+ name: string;
47
+ message: string;
48
+ status: number;
49
+ errors: import("@brickkit/core").ValidationErrorItem[];
50
+ } | {
51
+ name: string;
52
+ message: any;
53
+ status: number;
54
+ };
55
+ declare const compilerRuntime: Readonly<{
56
+ emptyServices: Readonly<{}>;
57
+ defaultRequest: Request;
58
+ nextSequence: () => string;
59
+ mergeInput: typeof mergeInput;
60
+ validate: typeof validate;
61
+ mapError: typeof mapError;
62
+ isThenable: (value: any) => boolean;
63
+ deny: (action: string) => never;
64
+ }>;
65
+ //#endregion
66
+ //#region src/compiler/emit.d.ts
67
+ /** Emits framework code only. User callbacks remain closures bound separately. */
68
+ declare function emitHandlerFactory(route: RouteIR): string;
69
+ /** An ES module of real JS functions; it never stringifies application callbacks. */
70
+ declare function emitCompiledApplication(ir: BrickIR, runtimeImport?: string): string;
71
+ //#endregion
72
+ //#region src/compiler.d.ts
73
+ interface CompiledRoute {
74
+ readonly ir: RouteIR;
75
+ readonly handler: CompiledHandler;
76
+ }
77
+ interface CompiledApplication {
78
+ readonly ir: BrickIR;
79
+ readonly routes: readonly CompiledRoute[];
80
+ }
81
+ /** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
82
+ declare function compileBrickApplication(options: {
83
+ services: Service<any, any>[];
84
+ prefix?: string;
85
+ mode?: "specialized" | "generic";
86
+ }): CompiledApplication;
87
+ /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
88
+ declare function bindCompiledApplication(ir: BrickIR, services: Service<any, any>[], factories: readonly HandlerFactory[]): CompiledApplication;
89
+ //#endregion
90
+ export { emitCompiledApplication as a, HandlerFactory as c, RouteMethod as d, compileBrickApplication as i, BrickIR as l, CompiledRoute as n, emitHandlerFactory as o, bindCompiledApplication as r, CompiledHandler as s, CompiledApplication as t, RouteIR as u };
91
+ //# sourceMappingURL=compiler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler.d.ts","names":[],"sources":["../src/compiler/ir.ts","../src/compiler/runtime.ts","../src/compiler/emit.ts","../src/compiler.ts"],"mappings":";;KAOY;UACK;WACN,QAAQ;WACR;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;aACE;aACA;;;WAGF;WACA;;UAEM;WACN;WACA;WACA;WACA;WACA,iBAAiB;WACjB,gBAAgB;WAChB;;;;KC5BC,mBAAmB,2BAA2B;KAC9C,kBACV,SAAS,mBACT,gBAAgB,oBACb;;iBAaI,WAAW,YAAY,aAAa;iBAWpC,SACP,OAAO,YAAY,oCACnB,gBACA,gBACA;iBAeO,SAAS,UAAU;;;;;;;;;;;;;;;;cAaf,iBAAe;;;;;;;EAON,aAAA;EAEL,OAAA;;;;;iBCxED,mBAAmB,OAAO;;iBA0E1B,wBACd,IAAI,SACJ;;;UCzDe;WACN,IAAI;WACJ,SAAS;;UAEH;WACN,IAAI;WACJ,iBAAiB;;;iBAsBZ,wBAAwB;EACtC,UAAU;EACV;EACA;IACE;;iBAsBY,wBACd,IAAI,SACJ,UAAU,qBACV,oBAAoB,mBACnB"}
@@ -0,0 +1,2 @@
1
+ import { i as emitHandlerFactory, n as compileBrickApplication, r as emitCompiledApplication, t as bindCompiledApplication } from "./compiler2.js";
2
+ export { bindCompiledApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory };
@@ -0,0 +1,2 @@
1
+ import { a as emitCompiledApplication, c as HandlerFactory, d as RouteMethod, i as compileBrickApplication, l as BrickIR, n as CompiledRoute, o as emitHandlerFactory, r as bindCompiledApplication, s as CompiledHandler, t as CompiledApplication, u as RouteIR } from "./compiler.js";
2
+ export { type BrickIR, CompiledApplication, type CompiledHandler, CompiledRoute, type HandlerFactory, type RouteIR, type RouteMethod, bindCompiledApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory };
@@ -0,0 +1,473 @@
1
+ import { ActionExecutionError, ValidationError, buildErrorHelpers, describeResourceReads, getCompiledCheck, prepareResourceReads, prepareResourceWrites } from "@brickkit/core";
2
+ //#region src/action-handler.ts
3
+ let _srvSeq = 0;
4
+ const EMPTY_SERVICES$1 = Object.freeze({});
5
+ const DEFAULT_REQUEST$1 = new Request("http://localhost");
6
+ function isNonEmpty$1(obj) {
7
+ if (obj == null) return false;
8
+ for (const _ in obj) return true;
9
+ return false;
10
+ }
11
+ function compileRoutePlan(service, action, routePath, method) {
12
+ const actionName = action.name;
13
+ const serviceName = service.name;
14
+ const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
15
+ const inputSchema = action.config?.input;
16
+ const outputSchema = action.config?.output;
17
+ const hasInput = Boolean(inputSchema);
18
+ const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
19
+ const outputChecker = outputSchema ? getCompiledCheck(outputSchema) : void 0;
20
+ let coercions;
21
+ if (inputSchema && typeof inputSchema.properties === "object") {
22
+ const list = [];
23
+ for (const [key, prop] of Object.entries(inputSchema.properties)) {
24
+ const type = prop?.type;
25
+ if (type === "number" || type === "integer") list.push({
26
+ key,
27
+ isNumber: true,
28
+ isBoolean: false
29
+ });
30
+ else if (type === "boolean") list.push({
31
+ key,
32
+ isNumber: false,
33
+ isBoolean: true
34
+ });
35
+ }
36
+ if (list.length > 0) coercions = list;
37
+ }
38
+ const contextHook = service.options?.context;
39
+ const hasContextHook = typeof contextHook === "function";
40
+ const authorize = action.config?.authorize;
41
+ const hasAuthorize = typeof authorize === "function";
42
+ const execute = action.config?.execute;
43
+ const tag = `[${serviceName}:${actionName}]`;
44
+ const logger = {
45
+ info: (...args) => console.log(tag, ...args),
46
+ warn: (...args) => console.warn(tag, ...args),
47
+ error: (...args) => console.error(tag, ...args),
48
+ debug: (...args) => console.debug(tag, ...args)
49
+ };
50
+ const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
51
+ const cachedDb = service.getDb();
52
+ return {
53
+ service,
54
+ action,
55
+ actionName,
56
+ serviceName,
57
+ routePath,
58
+ method,
59
+ isGetLike,
60
+ hasInput,
61
+ hasContextHook,
62
+ contextHook,
63
+ hasAuthorize,
64
+ authorize,
65
+ execute,
66
+ inputChecker,
67
+ outputChecker,
68
+ coercions,
69
+ logger,
70
+ errorBuilder,
71
+ cachedDb
72
+ };
73
+ }
74
+ async function executeCompiledRoute(plan, elysiaCtx) {
75
+ const { params, body, query, headers, request, set } = elysiaCtx;
76
+ const seq = (++_srvSeq).toString(36);
77
+ const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
78
+ const requestId = headers && headers["x-request-id"] || `req_${seq}`;
79
+ if (set?.headers) {
80
+ set.headers["x-trace-id"] = traceId;
81
+ set.headers["x-request-id"] = requestId;
82
+ }
83
+ let input;
84
+ if (plan.hasInput) {
85
+ let coercedQuery = query;
86
+ if (query && plan.coercions && plan.coercions.length > 0) {
87
+ coercedQuery = { ...query };
88
+ for (let i = 0; i < plan.coercions.length; i++) {
89
+ const c = plan.coercions[i];
90
+ const val = query[c.key];
91
+ if (val !== void 0) {
92
+ if (c.isNumber) {
93
+ const num = Number(val);
94
+ if (!isNaN(num)) coercedQuery[c.key] = num;
95
+ } else if (c.isBoolean) {
96
+ if (val === "true" || val === "1") coercedQuery[c.key] = true;
97
+ else if (val === "false" || val === "0") coercedQuery[c.key] = false;
98
+ }
99
+ }
100
+ }
101
+ }
102
+ const hasP = isNonEmpty$1(params);
103
+ const hasB = isNonEmpty$1(body);
104
+ const hasQ = isNonEmpty$1(coercedQuery);
105
+ if (plan.isGetLike) {
106
+ if (hasQ && !hasP && !hasB) input = coercedQuery;
107
+ else if (hasP && !hasQ && !hasB) input = params;
108
+ else if (hasB && !hasP && !hasQ) input = body;
109
+ else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
110
+ } else if (hasB && !hasP && !hasQ) input = body;
111
+ else if (hasP && !hasB && !hasQ) input = params;
112
+ else if (hasQ && !hasP && !hasB) input = coercedQuery;
113
+ else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
114
+ }
115
+ const ctx = {
116
+ request: request instanceof Request ? request : DEFAULT_REQUEST$1,
117
+ traceId,
118
+ requestId,
119
+ db: plan.cachedDb ?? plan.service.getDb(),
120
+ logger: plan.logger,
121
+ services: EMPTY_SERVICES$1,
122
+ metadata: { headers },
123
+ _resolved: true
124
+ };
125
+ try {
126
+ if (plan.hasContextHook) {
127
+ const extra = plan.contextHook(ctx);
128
+ const resolved = extra instanceof Promise ? await extra : extra;
129
+ if (resolved) Object.assign(ctx, resolved);
130
+ }
131
+ if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
132
+ if (plan.hasInput && plan.inputChecker) {
133
+ if (!plan.inputChecker.Check(input)) {
134
+ const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
135
+ path: err.path,
136
+ message: err.message,
137
+ value: err.value
138
+ }));
139
+ throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
140
+ }
141
+ }
142
+ if (plan.hasAuthorize) {
143
+ const authRes = plan.authorize({
144
+ ctx,
145
+ input,
146
+ user: ctx.user
147
+ });
148
+ if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${plan.actionName}'`, 403);
149
+ }
150
+ const execRes = plan.execute({
151
+ input,
152
+ ctx,
153
+ error: plan.errorBuilder
154
+ });
155
+ const result = execRes instanceof Promise ? await execRes : execRes;
156
+ if (plan.outputChecker) {
157
+ if (!plan.outputChecker.Check(result)) {
158
+ const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
159
+ path: err.path,
160
+ message: err.message,
161
+ value: err.value
162
+ }));
163
+ throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
164
+ }
165
+ }
166
+ return result;
167
+ } catch (err) {
168
+ if (err instanceof ValidationError || err instanceof ActionExecutionError) {
169
+ set.status = err.status || 400;
170
+ return err.toJSON();
171
+ }
172
+ set.status = 500;
173
+ return {
174
+ name: "InternalServerError",
175
+ message: err.message || "An unexpected error occurred",
176
+ status: 500
177
+ };
178
+ }
179
+ }
180
+ //#endregion
181
+ //#region src/compiler/ir.ts
182
+ function freezeIR(value) {
183
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
184
+ for (const child of Object.values(value)) freezeIR(child);
185
+ Object.freeze(value);
186
+ }
187
+ return value;
188
+ }
189
+ function schemaSnapshot(schema) {
190
+ return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
191
+ }
192
+ function analyzeApplication(services, prefix = "/api") {
193
+ if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
194
+ const names = /* @__PURE__ */ new Set();
195
+ for (const service of services) {
196
+ if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
197
+ names.add(service.name);
198
+ service.build();
199
+ }
200
+ const routes = [];
201
+ const bindings = [];
202
+ const registered = /* @__PURE__ */ new Map();
203
+ const diagnostics = [];
204
+ const add = (service, action, method, path, kind) => {
205
+ if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
206
+ const key = `${method} ${path}`;
207
+ const previous = registered.get(key);
208
+ if (previous) {
209
+ diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`);
210
+ return;
211
+ }
212
+ if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
213
+ registered.set(key, `${service.name}.${action.name}`);
214
+ const readLike = method === "GET" || action.name.startsWith("get") || action.name.endsWith(".get") || action.name.startsWith("list") || action.name.endsWith(".list") || action.name.startsWith("find") || action.name.startsWith("read");
215
+ const coercions = [];
216
+ for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
217
+ key,
218
+ type: "number"
219
+ });
220
+ else if (prop.type === "boolean") coercions.push({
221
+ key,
222
+ type: "boolean"
223
+ });
224
+ routes.push({
225
+ method,
226
+ path,
227
+ service: service.name,
228
+ action: action.name,
229
+ kind,
230
+ input: Boolean(action.config.input),
231
+ output: Boolean(action.config.output),
232
+ context: typeof service.options.context === "function",
233
+ authorize: typeof action.config.authorize === "function",
234
+ inputPrecedence: readLike ? [
235
+ "query",
236
+ "params",
237
+ "body"
238
+ ] : [
239
+ "params",
240
+ "body",
241
+ "query"
242
+ ],
243
+ coercions,
244
+ inputSchema: schemaSnapshot(action.config.input),
245
+ outputSchema: schemaSnapshot(action.config.output)
246
+ });
247
+ bindings.push({
248
+ service,
249
+ action
250
+ });
251
+ };
252
+ for (const service of services) {
253
+ for (const resource of service.listResources()) {
254
+ const collection = `${prefix}/${resource.name}`;
255
+ const item = `${collection}/:id`;
256
+ for (const [operation, method, path] of [
257
+ [
258
+ "list",
259
+ "GET",
260
+ collection
261
+ ],
262
+ [
263
+ "create",
264
+ "POST",
265
+ collection
266
+ ],
267
+ [
268
+ "get",
269
+ "GET",
270
+ item
271
+ ],
272
+ [
273
+ "update",
274
+ "PATCH",
275
+ item
276
+ ],
277
+ [
278
+ "update",
279
+ "PUT",
280
+ item
281
+ ],
282
+ [
283
+ "delete",
284
+ "DELETE",
285
+ item
286
+ ]
287
+ ]) {
288
+ const action = resource.actions[operation];
289
+ if (action) add(service, action, method, path, "resource");
290
+ }
291
+ }
292
+ for (const action of service.listActions()) {
293
+ const path = `${prefix}/${service.name}/${action.name}`;
294
+ add(service, action, "POST", path, "action");
295
+ if (/^(get|list|find|read)/.test(action.name)) add(service, action, "GET", path, "action");
296
+ if (action.config.path) {
297
+ if (action.config.method) add(service, action, action.config.method, action.config.path, "action");
298
+ else {
299
+ add(service, action, "GET", action.config.path, "action");
300
+ add(service, action, "POST", action.config.path, "action");
301
+ }
302
+ }
303
+ }
304
+ }
305
+ const reads = services.flatMap((service) => service.listResources().flatMap((resource) => {
306
+ const queries = describeResourceReads(service, resource);
307
+ return queries ? [queries] : [];
308
+ }));
309
+ return {
310
+ ir: freezeIR({
311
+ version: 1,
312
+ target: "bun-elysia",
313
+ prefix,
314
+ services: [...names],
315
+ routes,
316
+ reads,
317
+ diagnostics
318
+ }),
319
+ bindings
320
+ };
321
+ }
322
+ //#endregion
323
+ //#region src/compiler/emit.ts
324
+ /** Emits framework code only. User callbacks remain closures bound separately. */
325
+ function emitHandlerFactory(route) {
326
+ const name = JSON.stringify(route.action);
327
+ const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
328
+ const input = ["let input;"];
329
+ if (route.input) {
330
+ input.push("let coercedQuery = query;");
331
+ if (route.coercions.length) {
332
+ input.push("if (query) {", "coercedQuery = { ...query };");
333
+ for (const [index, coercion] of route.coercions.entries()) {
334
+ const key = JSON.stringify(coercion.key);
335
+ input.push(`const v${index} = query[${key}];`);
336
+ if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
337
+ else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
338
+ }
339
+ input.push("}");
340
+ }
341
+ input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
342
+ if (route.inputSchema?.type === "object") input.push("input ??= {};");
343
+ }
344
+ const asyncStages = route.context || route.authorize;
345
+ const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
346
+ const validation = route.input ? `validate(inputChecker, input, ${name}, "input");` : "";
347
+ const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
348
+ const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
349
+ const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
350
+ if (isThenable(result)) return Promise.resolve(result).then(value => {
351
+ ${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
352
+ return value;
353
+ }).catch(err => mapError(err, set));
354
+ ${output}
355
+ return result;`;
356
+ return `function bindAction(binding, runtime) {
357
+ const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
358
+ const { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;
359
+ return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
360
+ const seq = nextSequence();
361
+ const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
362
+ const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
363
+ if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
364
+ ${input.join("\n")}
365
+ const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
366
+ db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
367
+ try {
368
+ ${context}
369
+ ${validation}
370
+ ${authorization}
371
+ ${execute}
372
+ } catch (err) { return mapError(err, set); }
373
+ };
374
+ }`;
375
+ }
376
+ /** An ES module of real JS functions; it never stringifies application callbacks. */
377
+ function emitCompiledApplication(ir, runtimeImport = "@brickkit/cli/compiler") {
378
+ return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\nconst factories = [\n${ir.routes.map(emitHandlerFactory).join(",\n")}\n];\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\n`;
379
+ }
380
+ //#endregion
381
+ //#region src/compiler/runtime.ts
382
+ const EMPTY_SERVICES = Object.freeze({});
383
+ const DEFAULT_REQUEST = new Request("http://localhost");
384
+ let sequence = 0;
385
+ function isNonEmpty(value) {
386
+ if (value == null) return false;
387
+ for (const _ in value) return true;
388
+ return false;
389
+ }
390
+ /** Retains Brick's existing source precedence and treatment of empty bodies. */
391
+ function mergeInput(first, second, third) {
392
+ const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
393
+ if (a && !b && !c) return first;
394
+ if (b && !a && !c) return second;
395
+ if (c && !a && !b) return third;
396
+ if (a || b || c) return Object.assign({}, first, second, third);
397
+ }
398
+ function validate(check, value, action, stage) {
399
+ if (check.Check(value)) return;
400
+ const errors = Array.from(check.Errors(value)).map((err) => ({
401
+ path: err.path,
402
+ message: err.message,
403
+ value: err.value
404
+ }));
405
+ throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
406
+ }
407
+ function mapError(err, set) {
408
+ if (err instanceof ValidationError || err instanceof ActionExecutionError) {
409
+ set.status = err.status || 400;
410
+ return err.toJSON();
411
+ }
412
+ set.status = 500;
413
+ return {
414
+ name: "InternalServerError",
415
+ message: err?.message || "An unexpected error occurred",
416
+ status: 500
417
+ };
418
+ }
419
+ const compilerRuntime = Object.freeze({
420
+ emptyServices: EMPTY_SERVICES,
421
+ defaultRequest: DEFAULT_REQUEST,
422
+ nextSequence: () => (++sequence).toString(36),
423
+ mergeInput,
424
+ validate,
425
+ mapError,
426
+ isThenable: (value) => value != null && typeof value.then === "function",
427
+ deny: (action) => {
428
+ throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
429
+ }
430
+ });
431
+ //#endregion
432
+ //#region src/compiler.ts
433
+ function bindAnalyzed(ir, bindings, factories) {
434
+ if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
435
+ const routes = ir.routes.map((route, index) => {
436
+ const { service, action } = bindings[index];
437
+ const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
438
+ const handler = factories[index](plan, compilerRuntime);
439
+ return Object.freeze({
440
+ ir: route,
441
+ handler
442
+ });
443
+ });
444
+ return Object.freeze({
445
+ ir: freezeIR(ir),
446
+ routes: Object.freeze(routes)
447
+ });
448
+ }
449
+ /** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
450
+ function compileBrickApplication(options) {
451
+ const { ir, bindings } = analyzeApplication(options.services, options.prefix);
452
+ const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
453
+ if (options.mode !== "generic") for (const service of options.services) {
454
+ prepareResourceReads(service);
455
+ prepareResourceWrites(service);
456
+ }
457
+ return bindAnalyzed(ir, bindings, factories);
458
+ }
459
+ /** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
460
+ function bindCompiledApplication(ir, services, factories) {
461
+ if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
462
+ const analyzed = analyzeApplication(services, ir.prefix);
463
+ if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
464
+ for (const service of services) {
465
+ prepareResourceReads(service);
466
+ prepareResourceWrites(service);
467
+ }
468
+ return bindAnalyzed(ir, analyzed.bindings, factories);
469
+ }
470
+ //#endregion
471
+ export { emitHandlerFactory as i, compileBrickApplication as n, emitCompiledApplication as r, bindCompiledApplication as t };
472
+
473
+ //# sourceMappingURL=compiler2.js.map