gemi 0.168.0 → 0.170.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.
Files changed (32) hide show
  1. package/dist/app/App.d.ts +3 -3
  2. package/dist/bin/gemi.js.map +1 -1
  3. package/dist/{chunk-esjt9q54.js → chunk-36515hn6.js} +1 -1
  4. package/dist/{chunk-wc2sg9ny.js → chunk-6xve1mg1.js} +1 -1
  5. package/dist/chunk-g548q257.js.map +1 -1
  6. package/dist/{chunk-a053eza0.js → chunk-mc7pkdav.js} +2 -2
  7. package/dist/{chunk-a053eza0.js.map → chunk-mc7pkdav.js.map} +1 -1
  8. package/dist/chunk-t4hphx4x.js +117 -0
  9. package/dist/{chunk-bb3fdgwt.js.map → chunk-t4hphx4x.js.map} +7 -7
  10. package/dist/{chunk-q01p8ta3.js → chunk-x1p2vmj7.js} +1 -1
  11. package/dist/chunk-ys8nk9ga.js.map +2 -2
  12. package/dist/facades/index.js +1 -1
  13. package/dist/http/index.js +1 -1
  14. package/dist/http/requestDomain.d.ts.map +1 -1
  15. package/dist/i18n/index.js +1 -1
  16. package/dist/kernel/index.js +1 -1
  17. package/dist/server/forwardedFor.d.ts +3 -3
  18. package/dist/server/index.js +1 -1
  19. package/dist/services/index.js +1 -1
  20. package/dist/services/router/DomainResolver.d.ts +20 -9
  21. package/dist/services/router/DomainResolver.d.ts.map +1 -1
  22. package/dist/services/router/DomainRouter.d.ts +2 -1
  23. package/dist/services/router/DomainRouter.d.ts.map +1 -1
  24. package/dist/services/router/ViewRouteDispatcher.d.ts +2 -0
  25. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  26. package/dist/services/router/config.d.ts +59 -4
  27. package/dist/services/router/config.d.ts.map +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-bb3fdgwt.js +0 -117
  30. /package/dist/{chunk-esjt9q54.js.map → chunk-36515hn6.js.map} +0 -0
  31. /package/dist/{chunk-wc2sg9ny.js.map → chunk-6xve1mg1.js.map} +0 -0
  32. /package/dist/{chunk-q01p8ta3.js.map → chunk-x1p2vmj7.js.map} +0 -0
package/dist/app/App.d.ts CHANGED
@@ -31,9 +31,9 @@ export declare class App {
31
31
  */
32
32
  sockets(): SocketTransport | null;
33
33
  /**
34
- * Applies `route.domains.trustProxy.clientIpHeader`, or
35
- * `GEMI_CLIENT_IP_HEADER` for an app without `route.domains`: on a request
36
- * that carries the proxy's secret, the address that header names becomes
34
+ * Applies `route.domains.trustProxy`'s `clientIpHeader` and, failing that,
35
+ * `GEMI_CLIENT_IP_HEADER` (with or without `route.domains`): on a request
36
+ * that carries a proxy's secret, the address its header names becomes
37
37
  * the one in `X-Forwarded-For`. The servers call it right after settling
38
38
  * `X-Forwarded-For` (`GEMI_TRUST_PROXY`) and before anything reads it —
39
39
  * the socket upgrade and the global middleware included. `fetch` calls it
@@ -104,7 +104,7 @@
104
104
  "import { Glob } from \"bun\";\nimport { join } from \"node:path\";\n\n// The entry list for the Vite client + SSR builds (passed through as\n// GEMI_INPUT). Derived straight from the filesystem — the same view set\n// `app/client.tsx` registers via `import.meta.glob` — so the build no longer\n// needs to boot the app kernel to discover views.\n//\n// Keep these patterns in sync with `app/client.tsx`'s `init()` glob:\n// include \"./views/**/*.tsx\"\n// exclude \"./views/**/components/**\", \"./views/**/assets/**\",\n// \"./views/RootLayout.tsx\"\nexport default async function (appDir: string): Promise<string[]> {\n const viewsDir = join(appDir, \"views\");\n const glob = new Glob(\"**/*.tsx\");\n\n // `client.tsx` is always the client entry; RootLayout is bundled into it\n // directly (hence excluded from the view globs below).\n const entries = new Set<string>([\"/app/client.tsx\"]);\n\n for await (const file of glob.scan({ cwd: viewsDir })) {\n // `file` is POSIX-relative to `viewsDir`, e.g. \"Home.tsx\",\n // \"dashboard/Index.tsx\", \"components/ui/sidebar.tsx\".\n const segments = file.split(\"/\");\n if (segments.includes(\"components\")) continue; // **/components/**\n if (segments.includes(\"assets\")) continue; // **/assets/**\n if (file === \"RootLayout.tsx\") continue; // ./views/RootLayout.tsx\n // Test files are not views — keep them out of the build so they never\n // become a Vite entry (and never emit a compiled chunk into `dist`).\n if (/\\.(test|spec)\\.tsx$/.test(file)) continue; // **/*.{test,spec}.tsx\n\n entries.add(`/app/views/${file}`);\n }\n\n return Array.from(entries);\n}\n",
105
105
  "import path from \"node:path\";\nimport { App } from \"../app\";\n\n// Build the app straight from the kernel for build-time / tooling use. The\n// runtime entry (`app/server.ts`) can't be imported for this because it starts\n// a server on import and exports no `app`.\nexport async function loadApp() {\n const { default: Kernel } = await import(\n path.resolve(\"./app/kernel/Kernel.ts\")\n );\n return new App({ kernel: Kernel });\n}\n",
106
106
  "/**\n * The prefix every api route is served under. The browser adds it when it\n * fetches (`/api${path}`) and the server strips it before matching, so an api\n * router's own paths never carry it.\n */\nexport const API_PREFIX = \"/api\";\n\n/**\n * Whether a request pathname is an api request: `/api` itself or anything\n * under `/api/`. A bare `startsWith(\"/api\")` also claims `/apidocs`,\n * `/api-keys` and `/apiary`, so a view route there would never render — the\n * api dispatcher would answer its 404 JSON instead.\n */\nexport function isApiPath(pathname: string): boolean {\n return pathname === API_PREFIX || pathname.startsWith(`${API_PREFIX}/`);\n}\n\n/**\n * The api router path a request pathname addresses: `/api/users/1` is\n * `/users/1`, `/api/` is `/` and `/api` is `\"\"`. Only the leading prefix is\n * stripped — `replace(\"/api\", \"\")` would also strip an `/api` inside the path\n * of a request that did not start with one (`/files/api` becoming `/files`).\n * A pathname outside `/api` comes back unchanged, so the dispatcher can still\n * be handed a request by its route path directly.\n */\nexport function apiPath(pathname: string): string {\n return isApiPath(pathname) ? pathname.slice(API_PREFIX.length) : pathname;\n}\n",
107
- "import type { Kernel } from \"../kernel\";\nimport type { CarriedContext } from \"../http/requestContext\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport type { SocketHub } from \"../services/broadcast/SocketHub\";\n\n/** What the servers use of the broadcast `SocketHub`. */\nexport type SocketTransport = Pick<\n SocketHub,\n \"matches\" | \"upgrade\" | \"websocket\" | \"socketOptions\" | \"start\" | \"shutdown\"\n>;\n\ninterface AppParams {\n kernel: new () => Kernel;\n onException?: (error: Error) => void;\n}\n\nexport class App {\n private kernel: Kernel;\n public onException?: (error: Error) => void;\n\n constructor(params: AppParams) {\n this.kernel = new params.kernel();\n this.kernel.boot.call(this.kernel);\n this.onException =\n params.onException ??\n ((error: Error) => {\n console.error(\"Unhandled exception in App:\", error);\n });\n }\n\n // Every service this class touches is resolved through a `this.kernel.*`\n // accessor rather than by importing the service class and calling `app()`\n // here. That is deliberate: the built bin (`dist/bin/gemi.js`) bundles its own\n // copy of gemi, while the app's Kernel is loaded from source and resolves\n // `gemi/*` to the source modules — so the two copies have *different*\n // `kernelContext` AsyncLocalStorage instances and different `Application`\n // class objects. A method call on the Kernel executes in the app's copy and\n // reads the app's container; a resolution attempted here would not. Service\n // *tokens* still cross the boundary safely (they are plain strings), which is\n // why `kernel.resolve()` works from either side.\n public async waitForBoot() {\n await this.kernel.waitForBoot();\n }\n\n public getComponentTree() {\n return this.kernel.viewRoutes().componentTree;\n }\n\n // Every host group's views, not just the root's: the servers load these\n // modules up front, and a view only an `admin.` group routes to still has\n // to be among them.\n public getFlatComponentTree() {\n const views = new Set<string>();\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n for (const view of dispatcher.flatComponentTree) {\n views.add(view);\n }\n }\n return Array.from(views);\n }\n\n /**\n * The views gemi's own routes need from `app/views`, by name, with the\n * config that requires each (#1040), for the servers' existence check.\n */\n public getRequiredViews(): Record<string, string> {\n const views: Record<string, string> = {};\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n Object.assign(views, dispatcher.requiredViews);\n }\n return views;\n }\n\n /**\n * The hosts the dev server's Vite may answer: the `route.domains` root and\n * its subdomains, or any host when custom domains are on, since those are\n * only known to the app's resolver.\n */\n public devAllowedHosts(): true | string[] {\n const domains = this.kernel.domains();\n if (!domains.resolver) {\n return [];\n }\n return domains.acceptsCustomDomains ? true : [`.${domains.resolver.root}`];\n }\n\n /**\n * The broadcast WebSocket endpoint the servers wire into `Bun.serve`, or\n * `null` when the app has no `route.channels`. Typed structurally: the hub\n * belongs to the app's copy of gemi (see the note above).\n */\n public sockets(): SocketTransport | null {\n return this.kernel.sockets.call(this.kernel);\n }\n\n /**\n * Applies `route.domains.trustProxy.clientIpHeader`, or\n * `GEMI_CLIENT_IP_HEADER` for an app without `route.domains`: on a request\n * that carries the proxy's secret, the address that header names becomes\n * the one in `X-Forwarded-For`. The servers call it right after settling\n * `X-Forwarded-For` (`GEMI_TRUST_PROXY`) and before anything reads it —\n * the socket upgrade and the global middleware included. `fetch` calls it\n * too, for a caller that is not one of the servers. Idempotent.\n */\n public applyTrustedClientIp(req: Request) {\n this.kernel.domains().applyClientIp(req);\n }\n\n public getRouteManifest() {\n return this.kernel.viewRoutes().routeManifest;\n }\n\n // Requests `withGlobalMiddleware` already ran the global middleware for, so\n // `fetch` inside it does not run the list a second time, and can still hand\n // the route what the list carried. Keyed by the Request object: the servers\n // hand `fetch` the same one they gated.\n private globallyGated = new WeakMap<Request, CarriedContext | null>();\n\n /**\n * Runs the `global` middleware list, then `next` — what the servers put in\n * front of everything they serve, so the list covers static files, which\n * never reach `fetch`, as well as routes. A refusal is answered without\n * calling `next`. A global middleware that throws something other than a\n * break is answered by `onError` rather than by `next`, since a gate that\n * failed must not let a static file through.\n */\n public async withGlobalMiddleware(\n req: Request,\n next: (req: Request) => Promise<Response>,\n onError: (err: unknown) => Response | Promise<Response>,\n ): Promise<Response> {\n let outcome: Awaited<ReturnType<Kernel[\"globalMiddleware\"]>>;\n try {\n outcome = await this.kernel.run.call(this.kernel, () => this.kernel.globalMiddleware(req));\n } catch (err) {\n return await onError(err);\n }\n if (outcome.refusal) {\n return outcome.refusal;\n }\n this.globallyGated.set(req, outcome.carried);\n return outcome.apply(await next(req));\n }\n\n public async fetch(req: Request): Promise<Response> {\n const url = new URL(req.url);\n return this.kernel.run.call(this.kernel, async () => {\n // Repeated from the servers, for a caller that is not one of them.\n this.applyTrustedClientIp(req);\n // Run here too for a caller that is not one of the servers, a test or an\n // app's own `Bun.serve`, so the list is not skipped by calling `fetch`.\n const gated = this.globallyGated.has(req);\n const outcome = gated ? null : await this.kernel.globalMiddleware(req);\n const carried = gated ? this.globallyGated.get(req) : outcome.carried;\n if (outcome?.refusal) {\n return outcome.refusal;\n }\n // The MCP endpoint, and its OAuth endpoints, on the host it is\n // configured for. Ahead of routing, so no route can shadow it, and after\n // the global middleware, which covers it as it covers everything.\n const mcp = this.kernel.mcpHttp();\n if (mcp) {\n const answered = await mcp.handle(req);\n if (answered) {\n return outcome ? outcome.apply(answered) : answered;\n }\n }\n const domains = this.kernel.domains();\n const dispatchers = (await domains.ask(req)) ?? (await domains.route(req));\n if (dispatchers instanceof Response) {\n return outcome ? outcome.apply(dispatchers) : dispatchers;\n }\n if (!dispatchers) {\n const unknown = new Response(\"Unknown host\", { status: 404 });\n return outcome ? outcome.apply(unknown) : unknown;\n }\n const result = isApiPath(url.pathname)\n ? await dispatchers.api.handleApiRequest(req, carried)\n : await dispatchers.view.handleViewRequest(req, carried);\n if (!outcome) {\n return result;\n }\n // A document comes back as a render function the server calls with its\n // manifests, and the Response only exists once it has.\n if (typeof result === \"function\") {\n const render = result as (...args: any[]) => Promise<Response>;\n return (async (...args: any[]) => outcome.apply(await render(...args))) as any;\n }\n return outcome.apply(result);\n });\n }\n\n public dispatchJob(jobName: string, args: string) {\n const kernelRun = this.kernel.run.bind(this.kernel);\n return kernelRun(() => {\n return this.kernel.queue().dispatchJob(jobName, args);\n });\n }\n\n /** Every provider's `shutdown()`; see `Kernel.shutdown`. */\n public shutdown(options?: { timeoutMs?: number }) {\n return this.kernel.shutdown(options);\n }\n\n public destroy() {\n this.kernel.destroy();\n }\n\n public clone() {\n return Object.assign(Object.create(Object.getPrototypeOf(this)), this);\n }\n}\n\nexport type FetchHandler = InstanceType<typeof App>[\"fetch\"];\n",
107
+ "import type { Kernel } from \"../kernel\";\nimport type { CarriedContext } from \"../http/requestContext\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport type { SocketHub } from \"../services/broadcast/SocketHub\";\n\n/** What the servers use of the broadcast `SocketHub`. */\nexport type SocketTransport = Pick<\n SocketHub,\n \"matches\" | \"upgrade\" | \"websocket\" | \"socketOptions\" | \"start\" | \"shutdown\"\n>;\n\ninterface AppParams {\n kernel: new () => Kernel;\n onException?: (error: Error) => void;\n}\n\nexport class App {\n private kernel: Kernel;\n public onException?: (error: Error) => void;\n\n constructor(params: AppParams) {\n this.kernel = new params.kernel();\n this.kernel.boot.call(this.kernel);\n this.onException =\n params.onException ??\n ((error: Error) => {\n console.error(\"Unhandled exception in App:\", error);\n });\n }\n\n // Every service this class touches is resolved through a `this.kernel.*`\n // accessor rather than by importing the service class and calling `app()`\n // here. That is deliberate: the built bin (`dist/bin/gemi.js`) bundles its own\n // copy of gemi, while the app's Kernel is loaded from source and resolves\n // `gemi/*` to the source modules — so the two copies have *different*\n // `kernelContext` AsyncLocalStorage instances and different `Application`\n // class objects. A method call on the Kernel executes in the app's copy and\n // reads the app's container; a resolution attempted here would not. Service\n // *tokens* still cross the boundary safely (they are plain strings), which is\n // why `kernel.resolve()` works from either side.\n public async waitForBoot() {\n await this.kernel.waitForBoot();\n }\n\n public getComponentTree() {\n return this.kernel.viewRoutes().componentTree;\n }\n\n // Every host group's views, not just the root's: the servers load these\n // modules up front, and a view only an `admin.` group routes to still has\n // to be among them.\n public getFlatComponentTree() {\n const views = new Set<string>();\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n for (const view of dispatcher.flatComponentTree) {\n views.add(view);\n }\n }\n return Array.from(views);\n }\n\n /**\n * The views gemi's own routes need from `app/views`, by name, with the\n * config that requires each (#1040), for the servers' existence check.\n */\n public getRequiredViews(): Record<string, string> {\n const views: Record<string, string> = {};\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n Object.assign(views, dispatcher.requiredViews);\n }\n return views;\n }\n\n /**\n * The hosts the dev server's Vite may answer: the `route.domains` root and\n * its subdomains, or any host when custom domains are on, since those are\n * only known to the app's resolver.\n */\n public devAllowedHosts(): true | string[] {\n const domains = this.kernel.domains();\n if (!domains.resolver) {\n return [];\n }\n return domains.acceptsCustomDomains ? true : [`.${domains.resolver.root}`];\n }\n\n /**\n * The broadcast WebSocket endpoint the servers wire into `Bun.serve`, or\n * `null` when the app has no `route.channels`. Typed structurally: the hub\n * belongs to the app's copy of gemi (see the note above).\n */\n public sockets(): SocketTransport | null {\n return this.kernel.sockets.call(this.kernel);\n }\n\n /**\n * Applies `route.domains.trustProxy`'s `clientIpHeader` and, failing that,\n * `GEMI_CLIENT_IP_HEADER` (with or without `route.domains`): on a request\n * that carries a proxy's secret, the address its header names becomes\n * the one in `X-Forwarded-For`. The servers call it right after settling\n * `X-Forwarded-For` (`GEMI_TRUST_PROXY`) and before anything reads it —\n * the socket upgrade and the global middleware included. `fetch` calls it\n * too, for a caller that is not one of the servers. Idempotent.\n */\n public applyTrustedClientIp(req: Request) {\n this.kernel.domains().applyClientIp(req);\n }\n\n public getRouteManifest() {\n return this.kernel.viewRoutes().routeManifest;\n }\n\n // Requests `withGlobalMiddleware` already ran the global middleware for, so\n // `fetch` inside it does not run the list a second time, and can still hand\n // the route what the list carried. Keyed by the Request object: the servers\n // hand `fetch` the same one they gated.\n private globallyGated = new WeakMap<Request, CarriedContext | null>();\n\n /**\n * Runs the `global` middleware list, then `next` — what the servers put in\n * front of everything they serve, so the list covers static files, which\n * never reach `fetch`, as well as routes. A refusal is answered without\n * calling `next`. A global middleware that throws something other than a\n * break is answered by `onError` rather than by `next`, since a gate that\n * failed must not let a static file through.\n */\n public async withGlobalMiddleware(\n req: Request,\n next: (req: Request) => Promise<Response>,\n onError: (err: unknown) => Response | Promise<Response>,\n ): Promise<Response> {\n let outcome: Awaited<ReturnType<Kernel[\"globalMiddleware\"]>>;\n try {\n outcome = await this.kernel.run.call(this.kernel, () => this.kernel.globalMiddleware(req));\n } catch (err) {\n return await onError(err);\n }\n if (outcome.refusal) {\n return outcome.refusal;\n }\n this.globallyGated.set(req, outcome.carried);\n return outcome.apply(await next(req));\n }\n\n public async fetch(req: Request): Promise<Response> {\n const url = new URL(req.url);\n return this.kernel.run.call(this.kernel, async () => {\n // Repeated from the servers, for a caller that is not one of them.\n this.applyTrustedClientIp(req);\n // Run here too for a caller that is not one of the servers, a test or an\n // app's own `Bun.serve`, so the list is not skipped by calling `fetch`.\n const gated = this.globallyGated.has(req);\n const outcome = gated ? null : await this.kernel.globalMiddleware(req);\n const carried = gated ? this.globallyGated.get(req) : outcome.carried;\n if (outcome?.refusal) {\n return outcome.refusal;\n }\n // The MCP endpoint, and its OAuth endpoints, on the host it is\n // configured for. Ahead of routing, so no route can shadow it, and after\n // the global middleware, which covers it as it covers everything.\n const mcp = this.kernel.mcpHttp();\n if (mcp) {\n const answered = await mcp.handle(req);\n if (answered) {\n return outcome ? outcome.apply(answered) : answered;\n }\n }\n const domains = this.kernel.domains();\n const dispatchers = (await domains.ask(req)) ?? (await domains.route(req));\n if (dispatchers instanceof Response) {\n return outcome ? outcome.apply(dispatchers) : dispatchers;\n }\n if (!dispatchers) {\n const unknown = new Response(\"Unknown host\", { status: 404 });\n return outcome ? outcome.apply(unknown) : unknown;\n }\n const result = isApiPath(url.pathname)\n ? await dispatchers.api.handleApiRequest(req, carried)\n : await dispatchers.view.handleViewRequest(req, carried);\n if (!outcome) {\n return result;\n }\n // A document comes back as a render function the server calls with its\n // manifests, and the Response only exists once it has.\n if (typeof result === \"function\") {\n const render = result as (...args: any[]) => Promise<Response>;\n return (async (...args: any[]) => outcome.apply(await render(...args))) as any;\n }\n return outcome.apply(result);\n });\n }\n\n public dispatchJob(jobName: string, args: string) {\n const kernelRun = this.kernel.run.bind(this.kernel);\n return kernelRun(() => {\n return this.kernel.queue().dispatchJob(jobName, args);\n });\n }\n\n /** Every provider's `shutdown()`; see `Kernel.shutdown`. */\n public shutdown(options?: { timeoutMs?: number }) {\n return this.kernel.shutdown(options);\n }\n\n public destroy() {\n this.kernel.destroy();\n }\n\n public clone() {\n return Object.assign(Object.create(Object.getPrototypeOf(this)), this);\n }\n}\n\nexport type FetchHandler = InstanceType<typeof App>[\"fetch\"];\n",
108
108
  "import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { projectRoot } from \"../../support/discover\";\n\n/**\n * A static view's document script (#919): `.static({ script: \"site/clicks\" })`\n * inlines `app/views/site/clicks.script.ts`, bundled and minified, once in the\n * document's head.\n *\n * `gemi build` bundles every `app/views/**\\/*.script.{ts,js}` into\n * `dist/server/document-scripts.json` (name → source), which `gemi start`\n * reads. Anywhere else (dev, a test through `app.fetch`) a script is bundled\n * from source on each use, so an edit shows on the next load.\n */\n\n/** The suffix that marks a file under `app/views` as a document script. */\nexport const DOCUMENT_SCRIPT_SUFFIX = \".script\";\nconst EXTENSIONS = [\".ts\", \".js\"];\n/** Under `dist/server`. */\nexport const DOCUMENT_SCRIPTS_MANIFEST = \"document-scripts.json\";\n/** The attribute the inlined `<script>` carries, naming its script. */\nexport const DOCUMENT_SCRIPT_ATTRIBUTE = \"data-gemi-script\";\n\n/** A name as `script` takes it: a path under `app/views`, without the suffix. */\nconst NAME = /^[A-Za-z0-9_-]+(\\/[A-Za-z0-9_-]+)*$/;\n\nfunction assertName(name: string) {\n if (typeof name !== \"string\" || !NAME.test(name)) {\n throw new Error(\n `A static view's \\`script\\` is a path under app/views without the \".script.ts\" suffix, e.g. \"site/clicks\". Got ${JSON.stringify(name)}.`,\n );\n }\n}\n\n/** The source file of `name` under `appDir`, or `null` when there is none. */\nexport function documentScriptFile(appDir: string, name: string): string | null {\n for (const extension of EXTENSIONS) {\n const file = join(appDir, \"views\", `${name}${DOCUMENT_SCRIPT_SUFFIX}${extension}`);\n if (existsSync(file)) return file;\n }\n return null;\n}\n\n/**\n * Bundles one script for the browser: imports inlined, minified, wrapped in an\n * IIFE so nothing leaks into the page's scope. Throws when it does not bundle,\n * or when the output holds `</script` or `<!--`, which would end (or confuse)\n * the inline `<script>` element it is put in.\n */\nexport async function bundleDocumentScript(file: string): Promise<string> {\n const result = await Bun.build({\n entrypoints: [file],\n target: \"browser\",\n format: \"iife\",\n minify: true,\n throw: false,\n });\n if (!result.success || !result.outputs[0]) {\n const logs = result.logs.map((log) => String(log)).join(\"\\n\");\n throw new Error(`The document script ${file} does not bundle.\\n${logs}`);\n }\n const source = (await result.outputs[0].text()).trim();\n if (/<\\/script|<!--/i.test(source)) {\n throw new Error(\n `The document script ${file} contains \"</script\" or \"<!--\", which would end the inline <script> it is put in. Write it \"<\\\\/script\" or build the string from parts.`,\n );\n }\n return source;\n}\n\n/** Every document script under `appDir/views`, bundled: what `gemi build` writes. */\nexport async function bundleDocumentScripts(appDir: string): Promise<Record<string, string>> {\n const views = join(appDir, \"views\");\n const scripts: Record<string, string> = {};\n if (!existsSync(views)) return scripts;\n const glob = new Bun.Glob(`**/*${DOCUMENT_SCRIPT_SUFFIX}.{ts,js}`);\n const files = [...glob.scanSync({ cwd: views })].sort();\n for (const file of files) {\n if (file.split(\"/\").includes(\"node_modules\")) continue;\n const name = file.replace(/\\.script\\.[tj]s$/, \"\");\n if (!NAME.test(name) || name in scripts) continue;\n scripts[name] = await bundleDocumentScript(join(views, file));\n }\n return scripts;\n}\n\n/** `'sha256-…'` of `source`, for a `script-src` directive. */\nexport function cspHashOf(source: string): string {\n return `'sha256-${createHash(\"sha256\").update(source).digest(\"base64\")}'`;\n}\n\n// `gemi start`'s manifest, read once. `undefined`: not read yet; `null`: none.\nlet built: Record<string, string> | null | undefined;\n// Bundled from source in production when the manifest lacks a name: once.\nconst bundledInProduction = new Map<string, Promise<string>>();\n\nfunction builtScripts(): Record<string, string> | null {\n if (built === undefined) {\n const file = join(projectRoot(), \"dist\", \"server\", DOCUMENT_SCRIPTS_MANIFEST);\n built = existsSync(file) ? JSON.parse(readFileSync(file, \"utf8\")) : null;\n }\n return built ?? null;\n}\n\n/** Forgets the manifest read by `documentScriptSource` (tests). @internal */\nexport function resetDocumentScripts() {\n built = undefined;\n bundledInProduction.clear();\n}\n\n/**\n * The inlined text of the document script `name`.\n *\n * In production, from `dist/server/document-scripts.json`. A name the\n * manifest lacks (or no manifest) is bundled from source once. Elsewhere it is\n * bundled from source each time. Throws when there is no such file.\n */\nexport async function documentScriptSource(name: string): Promise<string> {\n assertName(name);\n const production = process.env.NODE_ENV === \"production\";\n if (production) {\n const fromBuild = builtScripts()?.[name];\n if (fromBuild !== undefined) return fromBuild;\n const pending = bundledInProduction.get(name);\n if (pending) return pending;\n }\n const appDir = join(projectRoot(), \"app\");\n const file = documentScriptFile(appDir, name);\n if (!file) {\n throw new Error(\n `The document script \"${name}\" was not found. It is a file at app/views/${name}${DOCUMENT_SCRIPT_SUFFIX}.ts (or .js).`,\n );\n }\n if (!production) return bundleDocumentScript(file);\n const pending = bundleDocumentScript(file);\n bundledInProduction.set(name, pending);\n pending.catch(() => bundledInProduction.delete(name));\n return pending;\n}\n\n/**\n * `'sha256-…'` for the document script `name` exactly as a page inlines it,\n * for a `script-src` directive next to `STATIC_NAVIGATION_CSP_HASH`. In dev\n * it follows the source, so it changes as the file does.\n */\nexport async function documentScriptCspHash(name: string): Promise<string> {\n return cspHashOf(await documentScriptSource(name));\n}\n",
109
109
  "import { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Finding the classes an application declared and never imported — the walk\n * #322 and #323 both end at.\n *\n * ### Why it has to run the files\n *\n * A job that is written and not listed does not fail; it disappears.\n * `QueueManager.run` looks a dispatched name up in the map its config built and\n * drops what is not there, so the dispatch is simply lost. A cron drifts worse:\n * nothing is waiting on a tick, so a job that never fires reports nothing to\n * anyone. What both come down to is that `app/config/queue.ts` naming every\n * `Job` subclass is the *only* thing putting those classes in the module graph —\n * the list and the directory are two spellings of one set, kept in step by hand.\n *\n * The way out of that is to read the directory, and there is no static read that\n * will do: the class does not exist until its module has run. So **every file\n * walked here is imported**, and a file that *does something* when imported does\n * it here — at boot, in production, on every start. `gemi check models` makes\n * the same trade for the same reason and pays it once per CI run; a caller of\n * this pays it once per process.\n *\n * ### What that asks of a caller\n *\n * **Point it at a directory of class declarations, not at `app/`.** The skip\n * rules on `sourceFiles` drop what certainly is not one — tests, benchmarks,\n * `.d.ts`, vendored packages — and nothing else. Widening the guesses is how a\n * discovery pass ends up quietly covering less than the directory holds, which\n * is the same silence in a new place.\n *\n * **Let a broken file stop the boot.** `discoverClasses` rethrows an import\n * failure naming the file rather than dropping it and carrying on, for the same\n * reason: four classes found out of five looks exactly like five out of five.\n *\n * **Leave a way out.** Discovery is what should happen when an app said\n * nothing. An app that lists its classes explicitly must not reach this file at\n * all — that is the escape hatch for a directory holding something this cannot\n * import, and it is the sentence an error from here should point at.\n *\n * ### One more thing worth knowing\n *\n * This imports by absolute path, while the application imports the same files\n * through the `@/app/*` alias. Bun keys its module registry by the *resolved*\n * path, so those two specifiers land on one module: a job already reached from\n * a controller is not evaluated a second time here, and the class object is the\n * same one. `gemi build` leaves that true in production — `packages: \"external\"`\n * keeps the app's own code out of `dist/server/server.mjs` and resolves it from\n * source at runtime, exactly as `gemi dev` does.\n *\n * Nothing here depends on that holding, and deliberately: `QueueManager` and the\n * `Scheduler`'s cross-reload registry are both keyed by name rather than by\n * class identity, so a build that did inline the app's modules would produce a\n * duplicate class object and still register the right job. Worth knowing before\n * writing a registry keyed the other way.\n */\n\n/**\n * The files under `dir` that could declare a class.\n *\n * Everything underneath it, because apps do group classes into folders, minus\n * what cannot be one. Each of these is going to be *imported*, so the exclusions\n * are about what is certainly not source rather than about what is probably not:\n *\n * - **Declaration files.** `.d.ts` has no runtime module behind it.\n * - **Tests, type tests and benchmarks**, by the suffix a runner already\n * recognises.\n * - **Dot-directories and `node_modules`.**\n * - **Any directory holding a `package.json`.** That is a package that happens\n * to live here — a vendored client, a generated SDK — not this app's source,\n * and importing its entry point runs somebody else's module graph. The\n * template has two under `app/models`.\n *\n * `ignore` is the escape hatch for the rest: a path prefix, relative to `dir`,\n * naming a file or a directory of adjacent code that runs something on import.\n * Nothing is ignored by default.\n *\n * The order is the same on every run over the same tree, which matters because\n * the caller is going to import in it: entries are sorted per directory before\n * recursing, and `readdirSync` order is the filesystem's rather than\n * alphabetical — a tree written `A.ts` then `B.ts` reads back `B.ts` first on\n * the machines this was tested on. Sorting per directory rather than sorting the\n * finished list is deliberate: for a tree holding both `a.ts` and `a/b.ts`, this\n * emits `a/b.ts` first, because the directory sorts before the file.\n *\n * A directory that does not exist yields an empty list rather than throwing.\n * \"The app has no jobs yet\" is an ordinary state and not this function's to\n * complain about — but it is indistinguishable from \"the app's source did not\n * ship\", so a caller that boots on the answer owes the reader a word about which\n * one it got.\n */\nexport function sourceFiles(dir: string, ignore: string[] = []): string[] {\n const out: string[] = [];\n\n const ignored = (path: string) => {\n const rel = relative(dir, path).split(\"\\\\\").join(\"/\");\n return ignore.some(\n (pattern) => rel === pattern || rel.startsWith(`${pattern}/`),\n );\n };\n\n const walk = (current: string) => {\n for (const entry of readdirSync(current, { withFileTypes: true }).sort(\n (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n )) {\n const path = join(current, entry.name);\n if (ignored(path)) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\")\n continue;\n if (existsSync(join(path, \"package.json\"))) continue;\n walk(path);\n continue;\n }\n\n if (!entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".tsx\")) continue;\n if (entry.name.endsWith(\".d.ts\")) continue;\n if (/\\.(test|test-d|spec|bench)\\.tsx?$/.test(entry.name)) continue;\n\n out.push(path);\n }\n };\n\n if (!existsSync(dir)) return out;\n\n walk(dir);\n return out;\n}\n\n/**\n * A class, as much of one as this file can name. `abstract` so that a base an\n * app never instantiates directly is a legal argument.\n */\ntype ClassLike = abstract new (...args: never[]) => unknown;\n\n/**\n * A file that would not import, reported with the file that would not import.\n *\n * Separate from a bare rethrow because the stack of a failed dynamic import\n * names the module that failed to *resolve*, several frames deep, and says\n * nothing about the walk that asked for it — so the reader learns that some\n * `?raw` specifier is unresolvable without learning that discovery is what\n * imported it, or that listing the classes explicitly is how they get their boot\n * back.\n */\nexport class DiscoveryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"DiscoveryError\";\n }\n}\n\n/**\n * Every exported class under `dir` whose prototype chain reaches `base`.\n *\n * `base` is a parameter rather than an import so that this file names no\n * service and stays cheap to depend on — `bin/check-models.ts` uses the walker\n * above and is bundled into `dist/bin/gemi.js`, which is not somewhere gemi's\n * service layer should end up. It is also what lets a test hand in a base class\n * of its own instead of standing up a project that can resolve `gemi/services`.\n *\n * `base` itself is never returned. A directory whose files import their base\n * from a sibling — the shape an app reaches for when several jobs share a gate —\n * re-exports it as often as not, and a framework that scheduled the abstract\n * base along with its subclasses would be running a job nobody wrote.\n *\n * A class is returned once no matter how many exports name it. A barrel in the\n * directory re-exporting everything beside it is the ordinary case, and it makes\n * every class reachable twice.\n *\n * The order is the walk's, and within a file the module namespace's, which the\n * language sorts by name. So the answer is the same on every run — worth having\n * where the caller is a scheduler and the alternative is a boot order that\n * depends on the filesystem.\n *\n * `onSkipped` is handed every export that did *not* match, with the file it came\n * from. Discovery's characteristic failure is a thing the author wrote and this\n * walk cannot see, and by the time an export has been discarded here the\n * information about why is gone — the caller is left holding \"four classes\"\n * where the directory holds five. A caller that can recognise its own\n * near-misses, as `discoverCommands` recognises a builder chain that was never\n * finished, uses this to say so by name instead.\n *\n * @throws DiscoveryError if a walked file cannot be imported. Not a skip: a file\n * that will not load is a class the caller was going to be told about and now is\n * not, which is the failure discovery exists to remove.\n */\nexport async function discoverClasses<T extends ClassLike>(\n dir: string,\n base: T,\n ignore: string[] = [],\n onSkipped?: (value: unknown, file: string) => void,\n): Promise<T[]> {\n const found = new Set<T>();\n\n for (const path of sourceFiles(dir, ignore)) {\n let module: Record<string, unknown>;\n\n try {\n module = (await import(path)) as Record<string, unknown>;\n } catch (error) {\n throw new DiscoveryError(\n `${path} could not be imported, so the classes in it could not be ` +\n `discovered:\\n ${(error as Error).message}\\n` +\n `List the classes explicitly in the config slice for this directory ` +\n `to skip the walk.`,\n { cause: error },\n );\n }\n\n for (const value of Object.values(module)) {\n if (\n typeof value === \"function\" &&\n value !== base &&\n Object.prototype.isPrototypeOf.call(base, value)\n ) {\n found.add(value as unknown as T);\n continue;\n }\n\n onSkipped?.(value, path);\n }\n }\n\n return [...found];\n}\n\n/**\n * The directory an app's `app/` sits in, as the running process can know it.\n *\n * `ROOT_DIR` is the obvious answer and is not available: `Server.start` awaits\n * `waitForBoot()` — every provider's `register` and `boot` — and only then\n * imports the http layer that sets it. Anything resolving paths during boot is\n * earlier than the variable it would want.\n *\n * What it can use is the same rule `httpProd` computes `ROOT_DIR` with a moment\n * later, which is why that file now calls this instead of repeating it. `gemi\n * dev` and `gemi start` both spawn the server with no `cwd`, so the process\n * inherits the CLI's, and the CLI takes `process.cwd()` for the project root\n * itself — `bun/preload.ts` reads `gemi.config` from it on the same assumption.\n *\n * `httpDev` computes a bare `process.cwd()`, so it and `httpProd` already\n * disagree whenever `GEMI_PROJECT_DIR` is set. Nothing in this repo sets it and\n * `gemi start` ignores it when locating the built entry point, so the two rules\n * are the same rule for every configuration that runs today; the divergence is\n * older than this function and wants its own fix.\n */\nexport function projectRoot(): string {\n return join(process.cwd(), process.env.GEMI_PROJECT_DIR ?? \"\");\n}\n",
110
110
  "import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { projectRoot } from \"../support/discover\";\n\n/**\n * Browser probes (#1020): code an app runs in a headless browser's page with\n * `page.evaluate`, written as a normal module.\n *\n * `page.evaluate` sends one function's source to the browser, so it may use\n * nothing from outside itself. A probe is a module under `app/` named\n * `*.probe.ts` (or `.js`) whose default export is the function to run; it can\n * import helpers like any module. gemi bundles it into one self-contained,\n * minified IIFE for the browser and hands it to `page.evaluate` as an\n * expression that calls the default export with the given arguments.\n *\n * `gemi build` bundles every probe into `dist/server/probes.json` (name →\n * source), which `gemi start` reads. Anywhere else (dev, tests) a probe is\n * bundled on first use and kept until it, or a file it imports, changes.\n *\n * A probe is named by its path under `app/` without the suffix:\n * `app/utils/layout.probe.ts` is `\"utils/layout\"`.\n */\n\n/** The suffix that marks a file under `app` as a probe. */\nexport const PROBE_SUFFIX = \".probe\";\nconst EXTENSIONS = [\".ts\", \".js\"];\n/** Under `dist/server`. */\nexport const PROBES_MANIFEST = \"probes.json\";\n\n/** The free name the bundled IIFE hands the default export to. */\nconst DEFINE = \"__gemiProbe__\";\n/** The bundle's entry: imports the probe and hands its default export over. */\nconst ENTRY = \"/__gemi_probe_entry__.ts\";\n\n/** A name as `probe` takes it: a path under `app`, without the suffix. */\nconst NAME = /^[A-Za-z0-9_-]+(\\/[A-Za-z0-9_-]+)*$/;\n\nfunction assertName(name: string) {\n if (typeof name !== \"string\" || !NAME.test(name)) {\n throw new Error(\n `A probe is named by its path under app/ without the \".probe.ts\" suffix, e.g. \"utils/layout\". Got ${JSON.stringify(name)}.`,\n );\n }\n}\n\n/** The source file of the probe `name` under `appDir`, or `null` when there is none. */\nexport function probeFile(appDir: string, name: string): string | null {\n for (const extension of EXTENSIONS) {\n const file = join(appDir, `${name}${PROBE_SUFFIX}${extension}`);\n if (existsSync(file)) return file;\n }\n return null;\n}\n\ntype Bundled = {\n /** The IIFE: hands the probe's default export to `__gemiProbe__`. */\n source: string;\n /** Every file the bundle read, absolute, for the dev cache. */\n inputs: string[];\n};\n\n/**\n * Bundles one probe for the browser: imports inlined, minified, wrapped in an\n * IIFE that hands the default export to `__gemiProbe__`. Throws when it does\n * not bundle.\n */\nasync function bundle(file: string): Promise<Bundled> {\n const result = await Bun.build({\n entrypoints: [ENTRY],\n files: {\n [ENTRY]: `import probe from ${JSON.stringify(file)};\\n${DEFINE}(probe);\\n`,\n },\n target: \"browser\",\n format: \"iife\",\n minify: true,\n metafile: true,\n throw: false,\n });\n if (!result.success || !result.outputs[0]) {\n const logs = result.logs.map((log) => String(log)).join(\"\\n\");\n throw new Error(`The probe ${file} does not bundle.\\n${logs}`);\n }\n const inputs = Object.keys(result.metafile?.inputs ?? {})\n .map((input) => resolve(input))\n .filter((input) => input !== ENTRY && existsSync(input));\n return { source: (await result.outputs[0].text()).trim(), inputs };\n}\n\n/** One probe's bundled source (the IIFE). Throws when it does not bundle. */\nexport async function bundleProbe(file: string): Promise<string> {\n return (await bundle(file)).source;\n}\n\n/** Every probe under `appDir`, bundled: what `gemi build` writes. */\nexport async function bundleProbes(appDir: string): Promise<Record<string, string>> {\n const probes: Record<string, string> = {};\n if (!existsSync(appDir)) return probes;\n const glob = new Bun.Glob(`**/*${PROBE_SUFFIX}.{ts,js}`);\n const files = [...glob.scanSync({ cwd: appDir })].sort();\n for (const file of files) {\n if (file.split(\"/\").includes(\"node_modules\")) continue;\n const name = file.replace(/\\.probe\\.[tj]s$/, \"\");\n if (!NAME.test(name) || name in probes) continue;\n probes[name] = await bundleProbe(join(appDir, file));\n }\n return probes;\n}\n\n// `gemi start`'s manifest, read once. `undefined`: not read yet; `null`: none.\nlet built: Record<string, string> | null | undefined;\n// Bundled from source: in production once, elsewhere until an input changes.\ntype Cached = { pending: Promise<Bundled>; stamps: Map<string, number> | null };\nconst cache = new Map<string, Cached>();\n\nfunction builtProbes(): Record<string, string> | null {\n if (built === undefined) {\n const file = join(projectRoot(), \"dist\", \"server\", PROBES_MANIFEST);\n built = existsSync(file) ? JSON.parse(readFileSync(file, \"utf8\")) : null;\n }\n return built ?? null;\n}\n\nfunction mtimeOf(file: string): number {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return -1;\n }\n}\n\nfunction stale(stamps: Map<string, number>): boolean {\n for (const [file, mtime] of stamps) {\n if (mtimeOf(file) !== mtime) return true;\n }\n return false;\n}\n\n/** Forgets the manifest and every bundled probe (tests). @internal */\nexport function resetProbes() {\n built = undefined;\n cache.clear();\n}\n\n/**\n * The bundled source (an IIFE) of the probe `name`.\n *\n * In production, from `dist/server/probes.json`; a name the manifest lacks\n * (or no manifest) is bundled from source once. Elsewhere it is bundled on\n * first use and again only once the probe or a file it imports has changed.\n * Throws when there is no such file or it does not bundle.\n */\nexport async function probeSource(name: string): Promise<string> {\n assertName(name);\n const production = process.env.NODE_ENV === \"production\";\n if (production) {\n const fromBuild = builtProbes()?.[name];\n if (fromBuild !== undefined) return fromBuild;\n }\n const cached = cache.get(name);\n if (cached && (cached.stamps === null || !stale(cached.stamps))) {\n return (await cached.pending).source;\n }\n const file = probeFile(join(projectRoot(), \"app\"), name);\n if (!file) {\n throw new Error(\n `The probe \"${name}\" was not found. It is a file at app/${name}${PROBE_SUFFIX}.ts (or .js).`,\n );\n }\n const startedAt = Date.now();\n const entry: Cached = { pending: bundle(file), stamps: null };\n cache.set(name, entry);\n try {\n const bundled = await entry.pending;\n if (!production) {\n // A file changed while it bundled may not be in the bundle: such a\n // stamp never matches, so the next use bundles again.\n entry.stamps = new Map(\n bundled.inputs.map((input) => {\n const mtime = mtimeOf(input);\n return [input, mtime >= startedAt ? -2 : mtime];\n }),\n );\n }\n return bundled.source;\n } catch (error) {\n if (cache.get(name) === entry) cache.delete(name);\n throw error;\n }\n}\n\n/**\n * A JavaScript expression that runs the bundled probe `source` with `args`\n * and evaluates to what it returns (a promise, for an async probe).\n */\nexport function probeExpression(source: string, args: readonly unknown[]): string {\n const json = JSON.stringify(args);\n if (json === undefined) throw new Error(\"A probe's arguments must be JSON values.\");\n // The local names start with `__gemi` so they shadow none of the page's globals the bundle may use.\n return `(() => { let __gemiProbeFn__; const ${DEFINE} = (fn) => { __gemiProbeFn__ = fn; }; ${source}; return __gemiProbeFn__(...${json}); })()`;\n}\n\n/** Anything that evaluates an expression in a page: a puppeteer or playwright `Page`. */\nexport interface ProbePage {\n evaluate(expression: string): Promise<unknown>;\n}\n\n/** The probe function, from its module's type or its own. */\ntype ProbeFunctionOf<M> = M extends { default: infer F } ? F : M;\ntype AnyFunction = (...args: any[]) => unknown;\ntype ArgsOf<F> = F extends AnyFunction ? Parameters<F> : never;\ntype ResultOf<F> = F extends AnyFunction ? Awaited<ReturnType<F>> : never;\n\nexport class Probe<M = AnyFunction> {\n constructor(readonly name: string) {\n assertName(name);\n }\n\n /** The bundled IIFE. */\n source(): Promise<string> {\n return probeSource(this.name);\n }\n\n /**\n * An expression that runs the probe with `args`, for a driver that takes a\n * script string. The arguments must be JSON values.\n */\n async expression(...args: ArgsOf<ProbeFunctionOf<M>>): Promise<string> {\n return probeExpression(await this.source(), args);\n }\n\n /** Runs the probe in `page` with `args` and returns its (awaited) result. */\n async run(page: ProbePage, ...args: ArgsOf<ProbeFunctionOf<M>>): Promise<ResultOf<ProbeFunctionOf<M>>> {\n return (await page.evaluate(await this.expression(...args))) as ResultOf<ProbeFunctionOf<M>>;\n }\n}\n\n/**\n * The probe at `app/<name>.probe.ts`, typed by its module:\n *\n * ```ts\n * const readLayout = probe<typeof import(\"@/app/utils/layout.probe\")>(\"utils/layout\");\n * const reading = await readLayout.run(page, sections);\n * ```\n */\nexport function probe<M = AnyFunction>(name: string): Probe<M> {\n return new Probe<M>(name);\n}\n",
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{W as T,Y as m,Z as P,_ as u}from"./chunk-a053eza0.js";import{na as h,oa as v}from"./chunk-wt1yzzbw.js";import"./chunk-bwg7genv.js";import"./chunk-mvd4mc8p.js";import"./chunk-7txst143.js";import"./chunk-9ft0ayhf.js";import"./chunk-s0z61m9j.js";import"./chunk-g548q257.js";import{Ti as N}from"./chunk-5n21z4n8.js";import{jl as y}from"./chunk-sp77zwpn.js";import{zl as S}from"./chunk-jd079awh.js";import"./chunk-9wcv7e1a.js";import{join as XJ}from"path";import{createServer as KJ}from"vite";import{join as n}from"path";import{existsSync as i}from"fs";import{IncomingMessage as o,ServerResponse as a}from"http";import{Socket as t}from"net";function p(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{W as T,Y as m,Z as P,_ as u}from"./chunk-mc7pkdav.js";import{na as h,oa as v}from"./chunk-wt1yzzbw.js";import"./chunk-bwg7genv.js";import"./chunk-mvd4mc8p.js";import"./chunk-7txst143.js";import"./chunk-9ft0ayhf.js";import"./chunk-s0z61m9j.js";import"./chunk-g548q257.js";import{Ti as N}from"./chunk-5n21z4n8.js";import{jl as y}from"./chunk-sp77zwpn.js";import{zl as S}from"./chunk-jd079awh.js";import"./chunk-9wcv7e1a.js";import{join as XJ}from"path";import{createServer as KJ}from"vite";import{join as n}from"path";import{existsSync as i}from"fs";import{IncomingMessage as o,ServerResponse as a}from"http";import{Socket as t}from"net";function p(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
3
  `).split(`
4
4
  `).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
5
5
  `).trim()}function C(J){return`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{X as k,Y as FJ,Z as LJ,_ as _J}from"./chunk-a053eza0.js";import{pa as N,ta as _,ua as CJ}from"./chunk-bwg7genv.js";import"./chunk-s0z61m9j.js";import{Gg as zJ,Hg as xJ,Ig as KJ,le as e,xg as YJ,yg as R}from"./chunk-bb3fdgwt.js";import"./chunk-vnk4vaer.js";import"./chunk-xkas0yp8.js";import{Nh as t,Oh as r,Rh as s}from"./chunk-ys8nk9ga.js";import{Ti as VJ}from"./chunk-5n21z4n8.js";import"./chunk-1h6g1hkg.js";import"./chunk-s71e6k9m.js";import"./chunk-fb77hwk0.js";import"./chunk-jxx9mctk.js";import"./chunk-s4fb4njt.js";import"./chunk-6t1t7h05.js";import"./chunk-a9frf7ym.js";import"./chunk-gwphn604.js";import"./chunk-m950vw4c.js";import"./chunk-978pc27j.js";import"./chunk-vfvjfw5k.js";import"./chunk-8b9ks729.js";import"./chunk-0q65jzhv.js";import{jl as XJ}from"./chunk-sp77zwpn.js";import"./chunk-9akefv1y.js";import{xl as UJ}from"./chunk-rpdekb8t.js";import{zl as T}from"./chunk-jd079awh.js";import"./chunk-9wcv7e1a.js";import{createHash as O2}from"crypto";import{join as v,resolve as MJ,sep as IJ}from"path";import{Duplex as EJ}from"stream";import{constants as P,createBrotliCompress as yJ,createGzip as gJ}from"zlib";var fJ=["br","gzip"],mJ=1024,uJ=5,hJ=19,cJ=6;function pJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function dJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...W]=Z.split(";"),j=X.trim().toLowerCase();if(j==="")continue;let G=1;for(let Y of W){let O=Y.indexOf("=");if(O===-1)continue;if(Y.slice(0,O).trim().toLowerCase()==="q"){G=pJ(Y.slice(O+1));break}}$.set(j,G)}return $}function S(J,$=fJ){let Z=dJ(J);if(!Z)return null;let X=Z.get("*"),W=null,j=0;for(let G of $){let Y=Z.get(G)??X??0;if(Y>j)W=G,j=Y}return W}function lJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function oJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(lJ($.headers.get("Cache-Control"),"no-transform"))return!1;let W=$.headers.get("Content-Length");if(W!==null&&Number(W)<mJ)return!1;return!0}function nJ(J){let $=J==="br"?yJ({params:{[P.BROTLI_PARAM_QUALITY]:uJ,[P.BROTLI_PARAM_LGWIN]:hJ},flush:P.BROTLI_OPERATION_FLUSH}):gJ({level:cJ,flush:P.Z_SYNC_FLUSH});return EJ.toWeb($)}function iJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function o(J,$){if(!oJ(J.method,$))return $;let Z=new Headers($.headers);iJ(Z);let X=S(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let W;try{W=nJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(W),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as $2,stat as JJ}from"fs/promises";import{join as Z2}from"path";import{mkdir as _2,readFile as aJ,stat as M2,writeFile as I2}from"fs/promises";import{dirname as P2,join as tJ}from"path";import{promisify as n}from"util";import{brotliCompress as rJ,constants as T2,gzip as sJ}from"zlib";var eJ=".vite/static-assets.json";var i={br:".br",gzip:".gz"},J2=["br","gzip"],D2=n(rJ),q2=n(sJ);async function a(J){let $;try{$=await aJ(tJ(J,eJ),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[W,j]of Object.entries(Z)){if(!Array.isArray(j))continue;X.files[W]=J2.filter((G)=>j.includes(G))}return X}function b(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function $J(J){let $=new Set;async function Z(X,W){let j;try{j=await $2(X,{withFileTypes:!0})}catch{return}for(let G of j){if(G.name.startsWith("."))continue;if(W&&G.name==="assets")continue;let Y=Z2(X,G.name),O=G.isDirectory(),V=G.isFile();if(G.isSymbolicLink())try{let K=await JJ(Y);O=K.isDirectory(),V=K.isFile()}catch{continue}if(V)$.add(Y);else if(O&&!G.isSymbolicLink())await Z(Y,!1)}}return await Z(J,!0),$}var X2="public, max-age=31536000, must-revalidate",Q2="public, max-age=31536000, immutable";async function W2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=S(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let W=$+i[X];try{let j=await JJ(W);return j.isFile()?{encoding:X,path:W,size:j.size}:null}catch{return null}}async function ZJ(J,$,Z={}){let X=Bun.file($),W=Z.encodings??[],j={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?Q2:X2,"Accept-Ranges":"bytes"};if(W.length>0)j.Vary="Accept-Encoding";let G=await W2(J,$,W);if(G){let V=Bun.file(G.path);return new Response(V.stream(),{headers:{...j,"Content-Encoding":G.encoding,"Content-Length":String(G.size),ETag:`${b(V.lastModified)}-${G.encoding}`}})}let Y=X.size;j.ETag=b(X.lastModified);let O=t(J.headers.get("Range"));if(O){let V=r(O,Y);if(!V)return e(Y);return new Response(X.slice(V.start,V.end+1).stream(),{status:206,headers:{...j,"Content-Range":s(V.start,V.end,Y),"Content-Length":String(V.length)}})}return new Response(X.stream(),{headers:{...j,"Content-Length":String(Y)}})}import{stat as V2}from"fs/promises";var A="app/client.tsx";function QJ(J,$=N){let Z=J[A]?.file;if(!Z)return;return{module:_(Z,$),preload:L(J,A,$)}}function L(J,$,Z=N){let X=[],W=new Set,j=(G)=>{if(W.has(G))return;W.add(G);let Y=J[G];if(!Y?.file)return;X.push(_(Y.file,Z));for(let O of Y.imports??[])j(O)};return j($),X}function j2(J,$,Z=N){let X=new Set(L(J,$,Z)),W=[],j=new Set,G=(O)=>{if(j.has(O))return;j.add(O);let V=J[O];if(!V)return;for(let K of V.dynamicImports??[])if(!/(^|\/)node_modules\//.test(K)&&!W.includes(K))W.push(K);for(let K of V.imports??[])G(K)};G($);let Y=[];for(let O of W)for(let V of L(J,O,Z))if(!X.has(V))X.add(V),Y.push(V);return Y}function WJ(J,$){let Z=[],X=new Set,W=new Set,j=(G)=>{if(W.has(G))return;W.add(G);let Y=J[G];if(!Y)return;for(let O of Y.imports??[])j(O);for(let O of Y.css??[])if(!X.has(O))X.add(O),Z.push(O)};return j($),Z}function jJ(J,$=N){let Z=new Map;return(X)=>{if(!Z.has(X)){let W=`${X}${XJ}`,j=J[W]?.file;Z.set(X,j?{src:_(j,$),preload:L(J,W,$),dynamicPreload:j2(J,W,$)}:void 0)}return Z.get(X)}}var GJ="x-gemi-build";function HJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var r=!1;try{var s=window.sessionStorage,u=window.location.href,m=JSON.parse(s.getItem(${Z})||"{}");if(!m||typeof m!=="object")m={};var d=Date.now()-m[u];if(navigator.onLine!==!1&&!(d>=0&&d<${$})){m[u]=Date.now();s.setItem(${Z},JSON.stringify(m));r=!0}}catch(e){}if(r)window.location.reload();else throw new Error(${X});export {}`}var G2=new RegExp(`^${YJ}/.+\\.m?js$`);function H2(J){return G2.test(J)}function OJ(J){if(H2(J))return new Response(HJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(R(J))return new Response("Not found",{status:404});return}var Y2=`<!DOCTYPE html>
2
+ import{X as k,Y as FJ,Z as LJ,_ as _J}from"./chunk-mc7pkdav.js";import{pa as N,ta as _,ua as CJ}from"./chunk-bwg7genv.js";import"./chunk-s0z61m9j.js";import{Gg as zJ,Hg as xJ,Ig as KJ,le as e,xg as YJ,yg as R}from"./chunk-t4hphx4x.js";import"./chunk-vnk4vaer.js";import"./chunk-xkas0yp8.js";import{Nh as t,Oh as r,Rh as s}from"./chunk-ys8nk9ga.js";import{Ti as VJ}from"./chunk-5n21z4n8.js";import"./chunk-1h6g1hkg.js";import"./chunk-s71e6k9m.js";import"./chunk-fb77hwk0.js";import"./chunk-jxx9mctk.js";import"./chunk-s4fb4njt.js";import"./chunk-6t1t7h05.js";import"./chunk-a9frf7ym.js";import"./chunk-gwphn604.js";import"./chunk-m950vw4c.js";import"./chunk-978pc27j.js";import"./chunk-vfvjfw5k.js";import"./chunk-8b9ks729.js";import"./chunk-0q65jzhv.js";import{jl as XJ}from"./chunk-sp77zwpn.js";import"./chunk-9akefv1y.js";import{xl as UJ}from"./chunk-rpdekb8t.js";import{zl as T}from"./chunk-jd079awh.js";import"./chunk-9wcv7e1a.js";import{createHash as O2}from"crypto";import{join as v,resolve as MJ,sep as IJ}from"path";import{Duplex as EJ}from"stream";import{constants as P,createBrotliCompress as yJ,createGzip as gJ}from"zlib";var fJ=["br","gzip"],mJ=1024,uJ=5,hJ=19,cJ=6;function pJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function dJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[X,...W]=Z.split(";"),j=X.trim().toLowerCase();if(j==="")continue;let G=1;for(let Y of W){let O=Y.indexOf("=");if(O===-1)continue;if(Y.slice(0,O).trim().toLowerCase()==="q"){G=pJ(Y.slice(O+1));break}}$.set(j,G)}return $}function S(J,$=fJ){let Z=dJ(J);if(!Z)return null;let X=Z.get("*"),W=null,j=0;for(let G of $){let Y=Z.get(G)??X??0;if(Y>j)W=G,j=Y}return W}function lJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function oJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let X=$.headers.get("Content-Encoding");if(X&&X.trim().toLowerCase()!=="identity")return!1;if(lJ($.headers.get("Cache-Control"),"no-transform"))return!1;let W=$.headers.get("Content-Length");if(W!==null&&Number(W)<mJ)return!1;return!0}function nJ(J){let $=J==="br"?yJ({params:{[P.BROTLI_PARAM_QUALITY]:uJ,[P.BROTLI_PARAM_LGWIN]:hJ},flush:P.BROTLI_OPERATION_FLUSH}):gJ({level:cJ,flush:P.Z_SYNC_FLUSH});return EJ.toWeb($)}function iJ(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((X)=>X.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function o(J,$){if(!oJ(J.method,$))return $;let Z=new Headers($.headers);iJ(Z);let X=S(J.headers.get("Accept-Encoding"));if(!X)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let W;try{W=nJ(X)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",X),Z.delete("Content-Length"),new Response($.body.pipeThrough(W),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as $2,stat as JJ}from"fs/promises";import{join as Z2}from"path";import{mkdir as _2,readFile as aJ,stat as M2,writeFile as I2}from"fs/promises";import{dirname as P2,join as tJ}from"path";import{promisify as n}from"util";import{brotliCompress as rJ,constants as T2,gzip as sJ}from"zlib";var eJ=".vite/static-assets.json";var i={br:".br",gzip:".gz"},J2=["br","gzip"],D2=n(rJ),q2=n(sJ);async function a(J){let $;try{$=await aJ(tJ(J,eJ),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let X={files:{}};for(let[W,j]of Object.entries(Z)){if(!Array.isArray(j))continue;X.files[W]=J2.filter((G)=>j.includes(G))}return X}function b(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function $J(J){let $=new Set;async function Z(X,W){let j;try{j=await $2(X,{withFileTypes:!0})}catch{return}for(let G of j){if(G.name.startsWith("."))continue;if(W&&G.name==="assets")continue;let Y=Z2(X,G.name),O=G.isDirectory(),V=G.isFile();if(G.isSymbolicLink())try{let K=await JJ(Y);O=K.isDirectory(),V=K.isFile()}catch{continue}if(V)$.add(Y);else if(O&&!G.isSymbolicLink())await Z(Y,!1)}}return await Z(J,!0),$}var X2="public, max-age=31536000, must-revalidate",Q2="public, max-age=31536000, immutable";async function W2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let X=S(J.headers.get("Accept-Encoding"),Z);if(!X)return null;let W=$+i[X];try{let j=await JJ(W);return j.isFile()?{encoding:X,path:W,size:j.size}:null}catch{return null}}async function ZJ(J,$,Z={}){let X=Bun.file($),W=Z.encodings??[],j={"Content-Type":X.type||"application/octet-stream","Cache-Control":Z.immutable?Q2:X2,"Accept-Ranges":"bytes"};if(W.length>0)j.Vary="Accept-Encoding";let G=await W2(J,$,W);if(G){let V=Bun.file(G.path);return new Response(V.stream(),{headers:{...j,"Content-Encoding":G.encoding,"Content-Length":String(G.size),ETag:`${b(V.lastModified)}-${G.encoding}`}})}let Y=X.size;j.ETag=b(X.lastModified);let O=t(J.headers.get("Range"));if(O){let V=r(O,Y);if(!V)return e(Y);return new Response(X.slice(V.start,V.end+1).stream(),{status:206,headers:{...j,"Content-Range":s(V.start,V.end,Y),"Content-Length":String(V.length)}})}return new Response(X.stream(),{headers:{...j,"Content-Length":String(Y)}})}import{stat as V2}from"fs/promises";var A="app/client.tsx";function QJ(J,$=N){let Z=J[A]?.file;if(!Z)return;return{module:_(Z,$),preload:L(J,A,$)}}function L(J,$,Z=N){let X=[],W=new Set,j=(G)=>{if(W.has(G))return;W.add(G);let Y=J[G];if(!Y?.file)return;X.push(_(Y.file,Z));for(let O of Y.imports??[])j(O)};return j($),X}function j2(J,$,Z=N){let X=new Set(L(J,$,Z)),W=[],j=new Set,G=(O)=>{if(j.has(O))return;j.add(O);let V=J[O];if(!V)return;for(let K of V.dynamicImports??[])if(!/(^|\/)node_modules\//.test(K)&&!W.includes(K))W.push(K);for(let K of V.imports??[])G(K)};G($);let Y=[];for(let O of W)for(let V of L(J,O,Z))if(!X.has(V))X.add(V),Y.push(V);return Y}function WJ(J,$){let Z=[],X=new Set,W=new Set,j=(G)=>{if(W.has(G))return;W.add(G);let Y=J[G];if(!Y)return;for(let O of Y.imports??[])j(O);for(let O of Y.css??[])if(!X.has(O))X.add(O),Z.push(O)};return j($),Z}function jJ(J,$=N){let Z=new Map;return(X)=>{if(!Z.has(X)){let W=`${X}${XJ}`,j=J[W]?.file;Z.set(X,j?{src:_(j,$),preload:L(J,W,$),dynamicPreload:j2(J,W,$)}:void 0)}return Z.get(X)}}var GJ="x-gemi-build";function HJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),X=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var r=!1;try{var s=window.sessionStorage,u=window.location.href,m=JSON.parse(s.getItem(${Z})||"{}");if(!m||typeof m!=="object")m={};var d=Date.now()-m[u];if(navigator.onLine!==!1&&!(d>=0&&d<${$})){m[u]=Date.now();s.setItem(${Z},JSON.stringify(m));r=!0}}catch(e){}if(r)window.location.reload();else throw new Error(${X});export {}`}var G2=new RegExp(`^${YJ}/.+\\.m?js$`);function H2(J){return G2.test(J)}function OJ(J){if(H2(J))return new Response(HJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(R(J))return new Response("Not found",{status:404});return}var Y2=`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8" />
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../app/App.ts"],
4
4
  "sourcesContent": [
5
- "import type { Kernel } from \"../kernel\";\nimport type { CarriedContext } from \"../http/requestContext\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport type { SocketHub } from \"../services/broadcast/SocketHub\";\n\n/** What the servers use of the broadcast `SocketHub`. */\nexport type SocketTransport = Pick<\n SocketHub,\n \"matches\" | \"upgrade\" | \"websocket\" | \"socketOptions\" | \"start\" | \"shutdown\"\n>;\n\ninterface AppParams {\n kernel: new () => Kernel;\n onException?: (error: Error) => void;\n}\n\nexport class App {\n private kernel: Kernel;\n public onException?: (error: Error) => void;\n\n constructor(params: AppParams) {\n this.kernel = new params.kernel();\n this.kernel.boot.call(this.kernel);\n this.onException =\n params.onException ??\n ((error: Error) => {\n console.error(\"Unhandled exception in App:\", error);\n });\n }\n\n // Every service this class touches is resolved through a `this.kernel.*`\n // accessor rather than by importing the service class and calling `app()`\n // here. That is deliberate: the built bin (`dist/bin/gemi.js`) bundles its own\n // copy of gemi, while the app's Kernel is loaded from source and resolves\n // `gemi/*` to the source modules — so the two copies have *different*\n // `kernelContext` AsyncLocalStorage instances and different `Application`\n // class objects. A method call on the Kernel executes in the app's copy and\n // reads the app's container; a resolution attempted here would not. Service\n // *tokens* still cross the boundary safely (they are plain strings), which is\n // why `kernel.resolve()` works from either side.\n public async waitForBoot() {\n await this.kernel.waitForBoot();\n }\n\n public getComponentTree() {\n return this.kernel.viewRoutes().componentTree;\n }\n\n // Every host group's views, not just the root's: the servers load these\n // modules up front, and a view only an `admin.` group routes to still has\n // to be among them.\n public getFlatComponentTree() {\n const views = new Set<string>();\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n for (const view of dispatcher.flatComponentTree) {\n views.add(view);\n }\n }\n return Array.from(views);\n }\n\n /**\n * The views gemi's own routes need from `app/views`, by name, with the\n * config that requires each (#1040), for the servers' existence check.\n */\n public getRequiredViews(): Record<string, string> {\n const views: Record<string, string> = {};\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n Object.assign(views, dispatcher.requiredViews);\n }\n return views;\n }\n\n /**\n * The hosts the dev server's Vite may answer: the `route.domains` root and\n * its subdomains, or any host when custom domains are on, since those are\n * only known to the app's resolver.\n */\n public devAllowedHosts(): true | string[] {\n const domains = this.kernel.domains();\n if (!domains.resolver) {\n return [];\n }\n return domains.acceptsCustomDomains ? true : [`.${domains.resolver.root}`];\n }\n\n /**\n * The broadcast WebSocket endpoint the servers wire into `Bun.serve`, or\n * `null` when the app has no `route.channels`. Typed structurally: the hub\n * belongs to the app's copy of gemi (see the note above).\n */\n public sockets(): SocketTransport | null {\n return this.kernel.sockets.call(this.kernel);\n }\n\n /**\n * Applies `route.domains.trustProxy.clientIpHeader`, or\n * `GEMI_CLIENT_IP_HEADER` for an app without `route.domains`: on a request\n * that carries the proxy's secret, the address that header names becomes\n * the one in `X-Forwarded-For`. The servers call it right after settling\n * `X-Forwarded-For` (`GEMI_TRUST_PROXY`) and before anything reads it —\n * the socket upgrade and the global middleware included. `fetch` calls it\n * too, for a caller that is not one of the servers. Idempotent.\n */\n public applyTrustedClientIp(req: Request) {\n this.kernel.domains().applyClientIp(req);\n }\n\n public getRouteManifest() {\n return this.kernel.viewRoutes().routeManifest;\n }\n\n // Requests `withGlobalMiddleware` already ran the global middleware for, so\n // `fetch` inside it does not run the list a second time, and can still hand\n // the route what the list carried. Keyed by the Request object: the servers\n // hand `fetch` the same one they gated.\n private globallyGated = new WeakMap<Request, CarriedContext | null>();\n\n /**\n * Runs the `global` middleware list, then `next` — what the servers put in\n * front of everything they serve, so the list covers static files, which\n * never reach `fetch`, as well as routes. A refusal is answered without\n * calling `next`. A global middleware that throws something other than a\n * break is answered by `onError` rather than by `next`, since a gate that\n * failed must not let a static file through.\n */\n public async withGlobalMiddleware(\n req: Request,\n next: (req: Request) => Promise<Response>,\n onError: (err: unknown) => Response | Promise<Response>,\n ): Promise<Response> {\n let outcome: Awaited<ReturnType<Kernel[\"globalMiddleware\"]>>;\n try {\n outcome = await this.kernel.run.call(this.kernel, () => this.kernel.globalMiddleware(req));\n } catch (err) {\n return await onError(err);\n }\n if (outcome.refusal) {\n return outcome.refusal;\n }\n this.globallyGated.set(req, outcome.carried);\n return outcome.apply(await next(req));\n }\n\n public async fetch(req: Request): Promise<Response> {\n const url = new URL(req.url);\n return this.kernel.run.call(this.kernel, async () => {\n // Repeated from the servers, for a caller that is not one of them.\n this.applyTrustedClientIp(req);\n // Run here too for a caller that is not one of the servers, a test or an\n // app's own `Bun.serve`, so the list is not skipped by calling `fetch`.\n const gated = this.globallyGated.has(req);\n const outcome = gated ? null : await this.kernel.globalMiddleware(req);\n const carried = gated ? this.globallyGated.get(req) : outcome.carried;\n if (outcome?.refusal) {\n return outcome.refusal;\n }\n // The MCP endpoint, and its OAuth endpoints, on the host it is\n // configured for. Ahead of routing, so no route can shadow it, and after\n // the global middleware, which covers it as it covers everything.\n const mcp = this.kernel.mcpHttp();\n if (mcp) {\n const answered = await mcp.handle(req);\n if (answered) {\n return outcome ? outcome.apply(answered) : answered;\n }\n }\n const domains = this.kernel.domains();\n const dispatchers = (await domains.ask(req)) ?? (await domains.route(req));\n if (dispatchers instanceof Response) {\n return outcome ? outcome.apply(dispatchers) : dispatchers;\n }\n if (!dispatchers) {\n const unknown = new Response(\"Unknown host\", { status: 404 });\n return outcome ? outcome.apply(unknown) : unknown;\n }\n const result = isApiPath(url.pathname)\n ? await dispatchers.api.handleApiRequest(req, carried)\n : await dispatchers.view.handleViewRequest(req, carried);\n if (!outcome) {\n return result;\n }\n // A document comes back as a render function the server calls with its\n // manifests, and the Response only exists once it has.\n if (typeof result === \"function\") {\n const render = result as (...args: any[]) => Promise<Response>;\n return (async (...args: any[]) => outcome.apply(await render(...args))) as any;\n }\n return outcome.apply(result);\n });\n }\n\n public dispatchJob(jobName: string, args: string) {\n const kernelRun = this.kernel.run.bind(this.kernel);\n return kernelRun(() => {\n return this.kernel.queue().dispatchJob(jobName, args);\n });\n }\n\n /** Every provider's `shutdown()`; see `Kernel.shutdown`. */\n public shutdown(options?: { timeoutMs?: number }) {\n return this.kernel.shutdown(options);\n }\n\n public destroy() {\n this.kernel.destroy();\n }\n\n public clone() {\n return Object.assign(Object.create(Object.getPrototypeOf(this)), this);\n }\n}\n\nexport type FetchHandler = InstanceType<typeof App>[\"fetch\"];\n"
5
+ "import type { Kernel } from \"../kernel\";\nimport type { CarriedContext } from \"../http/requestContext\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport type { SocketHub } from \"../services/broadcast/SocketHub\";\n\n/** What the servers use of the broadcast `SocketHub`. */\nexport type SocketTransport = Pick<\n SocketHub,\n \"matches\" | \"upgrade\" | \"websocket\" | \"socketOptions\" | \"start\" | \"shutdown\"\n>;\n\ninterface AppParams {\n kernel: new () => Kernel;\n onException?: (error: Error) => void;\n}\n\nexport class App {\n private kernel: Kernel;\n public onException?: (error: Error) => void;\n\n constructor(params: AppParams) {\n this.kernel = new params.kernel();\n this.kernel.boot.call(this.kernel);\n this.onException =\n params.onException ??\n ((error: Error) => {\n console.error(\"Unhandled exception in App:\", error);\n });\n }\n\n // Every service this class touches is resolved through a `this.kernel.*`\n // accessor rather than by importing the service class and calling `app()`\n // here. That is deliberate: the built bin (`dist/bin/gemi.js`) bundles its own\n // copy of gemi, while the app's Kernel is loaded from source and resolves\n // `gemi/*` to the source modules — so the two copies have *different*\n // `kernelContext` AsyncLocalStorage instances and different `Application`\n // class objects. A method call on the Kernel executes in the app's copy and\n // reads the app's container; a resolution attempted here would not. Service\n // *tokens* still cross the boundary safely (they are plain strings), which is\n // why `kernel.resolve()` works from either side.\n public async waitForBoot() {\n await this.kernel.waitForBoot();\n }\n\n public getComponentTree() {\n return this.kernel.viewRoutes().componentTree;\n }\n\n // Every host group's views, not just the root's: the servers load these\n // modules up front, and a view only an `admin.` group routes to still has\n // to be among them.\n public getFlatComponentTree() {\n const views = new Set<string>();\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n for (const view of dispatcher.flatComponentTree) {\n views.add(view);\n }\n }\n return Array.from(views);\n }\n\n /**\n * The views gemi's own routes need from `app/views`, by name, with the\n * config that requires each (#1040), for the servers' existence check.\n */\n public getRequiredViews(): Record<string, string> {\n const views: Record<string, string> = {};\n for (const dispatcher of this.kernel.domains().viewDispatchers()) {\n Object.assign(views, dispatcher.requiredViews);\n }\n return views;\n }\n\n /**\n * The hosts the dev server's Vite may answer: the `route.domains` root and\n * its subdomains, or any host when custom domains are on, since those are\n * only known to the app's resolver.\n */\n public devAllowedHosts(): true | string[] {\n const domains = this.kernel.domains();\n if (!domains.resolver) {\n return [];\n }\n return domains.acceptsCustomDomains ? true : [`.${domains.resolver.root}`];\n }\n\n /**\n * The broadcast WebSocket endpoint the servers wire into `Bun.serve`, or\n * `null` when the app has no `route.channels`. Typed structurally: the hub\n * belongs to the app's copy of gemi (see the note above).\n */\n public sockets(): SocketTransport | null {\n return this.kernel.sockets.call(this.kernel);\n }\n\n /**\n * Applies `route.domains.trustProxy`'s `clientIpHeader` and, failing that,\n * `GEMI_CLIENT_IP_HEADER` (with or without `route.domains`): on a request\n * that carries a proxy's secret, the address its header names becomes\n * the one in `X-Forwarded-For`. The servers call it right after settling\n * `X-Forwarded-For` (`GEMI_TRUST_PROXY`) and before anything reads it —\n * the socket upgrade and the global middleware included. `fetch` calls it\n * too, for a caller that is not one of the servers. Idempotent.\n */\n public applyTrustedClientIp(req: Request) {\n this.kernel.domains().applyClientIp(req);\n }\n\n public getRouteManifest() {\n return this.kernel.viewRoutes().routeManifest;\n }\n\n // Requests `withGlobalMiddleware` already ran the global middleware for, so\n // `fetch` inside it does not run the list a second time, and can still hand\n // the route what the list carried. Keyed by the Request object: the servers\n // hand `fetch` the same one they gated.\n private globallyGated = new WeakMap<Request, CarriedContext | null>();\n\n /**\n * Runs the `global` middleware list, then `next` — what the servers put in\n * front of everything they serve, so the list covers static files, which\n * never reach `fetch`, as well as routes. A refusal is answered without\n * calling `next`. A global middleware that throws something other than a\n * break is answered by `onError` rather than by `next`, since a gate that\n * failed must not let a static file through.\n */\n public async withGlobalMiddleware(\n req: Request,\n next: (req: Request) => Promise<Response>,\n onError: (err: unknown) => Response | Promise<Response>,\n ): Promise<Response> {\n let outcome: Awaited<ReturnType<Kernel[\"globalMiddleware\"]>>;\n try {\n outcome = await this.kernel.run.call(this.kernel, () => this.kernel.globalMiddleware(req));\n } catch (err) {\n return await onError(err);\n }\n if (outcome.refusal) {\n return outcome.refusal;\n }\n this.globallyGated.set(req, outcome.carried);\n return outcome.apply(await next(req));\n }\n\n public async fetch(req: Request): Promise<Response> {\n const url = new URL(req.url);\n return this.kernel.run.call(this.kernel, async () => {\n // Repeated from the servers, for a caller that is not one of them.\n this.applyTrustedClientIp(req);\n // Run here too for a caller that is not one of the servers, a test or an\n // app's own `Bun.serve`, so the list is not skipped by calling `fetch`.\n const gated = this.globallyGated.has(req);\n const outcome = gated ? null : await this.kernel.globalMiddleware(req);\n const carried = gated ? this.globallyGated.get(req) : outcome.carried;\n if (outcome?.refusal) {\n return outcome.refusal;\n }\n // The MCP endpoint, and its OAuth endpoints, on the host it is\n // configured for. Ahead of routing, so no route can shadow it, and after\n // the global middleware, which covers it as it covers everything.\n const mcp = this.kernel.mcpHttp();\n if (mcp) {\n const answered = await mcp.handle(req);\n if (answered) {\n return outcome ? outcome.apply(answered) : answered;\n }\n }\n const domains = this.kernel.domains();\n const dispatchers = (await domains.ask(req)) ?? (await domains.route(req));\n if (dispatchers instanceof Response) {\n return outcome ? outcome.apply(dispatchers) : dispatchers;\n }\n if (!dispatchers) {\n const unknown = new Response(\"Unknown host\", { status: 404 });\n return outcome ? outcome.apply(unknown) : unknown;\n }\n const result = isApiPath(url.pathname)\n ? await dispatchers.api.handleApiRequest(req, carried)\n : await dispatchers.view.handleViewRequest(req, carried);\n if (!outcome) {\n return result;\n }\n // A document comes back as a render function the server calls with its\n // manifests, and the Response only exists once it has.\n if (typeof result === \"function\") {\n const render = result as (...args: any[]) => Promise<Response>;\n return (async (...args: any[]) => outcome.apply(await render(...args))) as any;\n }\n return outcome.apply(result);\n });\n }\n\n public dispatchJob(jobName: string, args: string) {\n const kernelRun = this.kernel.run.bind(this.kernel);\n return kernelRun(() => {\n return this.kernel.queue().dispatchJob(jobName, args);\n });\n }\n\n /** Every provider's `shutdown()`; see `Kernel.shutdown`. */\n public shutdown(options?: { timeoutMs?: number }) {\n return this.kernel.shutdown(options);\n }\n\n public destroy() {\n this.kernel.destroy();\n }\n\n public clone() {\n return Object.assign(Object.create(Object.getPrototypeOf(this)), this);\n }\n}\n\nexport type FetchHandler = InstanceType<typeof App>[\"fetch\"];\n"
6
6
  ],
7
7
  "mappings": "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",
8
8
  "debugId": "4B66DF7353D1E99364756E2164756E21",
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Ca as f}from"./chunk-s0z61m9j.js";import{createElement as v}from"react";function q(i,t){let e=Object.keys(t).sort((s,r)=>r.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),p=new RegExp(e.join("|"),"g");return i.replace(p,(s)=>t[s])}async function Y(i,t,e=[],p){let s=[...e.map((n)=>`${i}/views/${n}.tsx`),p?`${i}/views/${p}.tsx`:`${i}/views/RootLayout.tsx`],r=new Set;for(let n of s){let u=t.moduleGraph.getModulesByFile(n);if(u)for(let d of u)r.add(d)}let b=[],l=[],g={};for(let n of r)if(n)for(let u of n.importedModules){if(u.file.includes("module.css"))g[u.file]=u.ssrTransformResult.map.sourcesContent.join("");if(u.file.includes(".css"))l.push(u.file)}for(let n of l){let u=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),j="";if(d)j=q(g[n],u.default);b.push({isDev:!0,id:n,content:d?j:u.code})}return b.map((n,u)=>{return v("style",{key:u,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Z(i=[]){return i.map((t,e)=>{return v("style",{key:e,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as y}from"fs";import{basename as z}from"path";import{networkInterfaces as $}from"os";var a={name:"gemi",version:"0.168.0",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./ai/voice":"./ai/voice/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./probe":"./probe/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/ai/voice dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var h=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],E=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,t)=>E?`\x1B[${i}m${t}\x1B[0m`:t,G=(i)=>c("1",i),x=(i)=>c("2",i),o=(i)=>c("36",i),J=(i)=>c("32",i),N=(i)=>c("35",i);function O(){return a.version??"?"}function Q(i){for(let t of Object.values($()))for(let e of t??[])if((e.family==="IPv4"||e.family===4)&&!e.internal)return`http://${e.address}:${i}`;return null}function W(i){return f(i).filter((t)=>y(t)).map((t)=>z(t))}function F(i){let{port:t,rootDir:e}=i,p=`http://localhost:${t}`,s=Q(t),r=W(e),b=(g,n)=>` ${J("\u279C")} ${G(g.padEnd(9))}${n}`,l=["",...h.map((g)=>N(g)),"",` ${x("gemi")} ${o(`v${O()}`)}`,"",b("Local:",o(p)),b("Network:",s?o(s):x("unavailable")),b("Env:",r.length?r.join(", "):x("none")),""];console.log(l.join(`
2
+ import{Ca as f}from"./chunk-s0z61m9j.js";import{createElement as v}from"react";function q(i,t){let e=Object.keys(t).sort((s,r)=>r.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),p=new RegExp(e.join("|"),"g");return i.replace(p,(s)=>t[s])}async function Y(i,t,e=[],p){let s=[...e.map((n)=>`${i}/views/${n}.tsx`),p?`${i}/views/${p}.tsx`:`${i}/views/RootLayout.tsx`],r=new Set;for(let n of s){let u=t.moduleGraph.getModulesByFile(n);if(u)for(let d of u)r.add(d)}let b=[],l=[],g={};for(let n of r)if(n)for(let u of n.importedModules){if(u.file.includes("module.css"))g[u.file]=u.ssrTransformResult.map.sourcesContent.join("");if(u.file.includes(".css"))l.push(u.file)}for(let n of l){let u=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),j="";if(d)j=q(g[n],u.default);b.push({isDev:!0,id:n,content:d?j:u.code})}return b.map((n,u)=>{return v("style",{key:u,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Z(i=[]){return i.map((t,e)=>{return v("style",{key:e,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as y}from"fs";import{basename as z}from"path";import{networkInterfaces as $}from"os";var a={name:"gemi",version:"0.170.0",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./ai/voice":"./ai/voice/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./probe":"./probe/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/ai/voice dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var h=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],E=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,t)=>E?`\x1B[${i}m${t}\x1B[0m`:t,G=(i)=>c("1",i),x=(i)=>c("2",i),o=(i)=>c("36",i),J=(i)=>c("32",i),N=(i)=>c("35",i);function O(){return a.version??"?"}function Q(i){for(let t of Object.values($()))for(let e of t??[])if((e.family==="IPv4"||e.family===4)&&!e.internal)return`http://${e.address}:${i}`;return null}function W(i){return f(i).filter((t)=>y(t)).map((t)=>z(t))}function F(i){let{port:t,rootDir:e}=i,p=`http://localhost:${t}`,s=Q(t),r=W(e),b=(g,n)=>` ${J("\u279C")} ${G(g.padEnd(9))}${n}`,l=["",...h.map((g)=>N(g)),"",` ${x("gemi")} ${o(`v${O()}`)}`,"",b("Local:",o(p)),b("Network:",s?o(s):x("unavailable")),b("Env:",r.length?r.join(", "):x("none")),""];console.log(l.join(`
3
3
  `))}function V(i,t){return Error(`app/views/${i}.tsx is missing. gemi's auth routes render it because ${t} is on. Add the view, or turn that setting off in app/config/auth.ts.`)}function U(i=process.env.SERVER_IDLE_TIMEOUT){if(i===void 0||i.trim()==="")return 10;let t=Number(i.trim());if(!Number.isInteger(t)||t<0||t>255)throw Error(`SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 (0 disables the timeout), got ${JSON.stringify(i)}.`);return t}
4
4
  export{Y as W,Z as X,F as Y,V as Z,U as _};
5
5
 
6
- //# debugId=DBB23962EBF8D63264756E2164756E21
6
+ //# debugId=714D433C3D53C1F464756E2164756E21
@@ -8,6 +8,6 @@
8
8
  "/**\n * Bun's default, and what both servers use when `SERVER_IDLE_TIMEOUT` is unset.\n */\nexport const DEFAULT_SERVER_IDLE_TIMEOUT = 10;\n\n/**\n * The `idleTimeout` (seconds) both `gemi dev` and `gemi start` pass to\n * `Bun.serve`, from `SERVER_IDLE_TIMEOUT` (#787).\n *\n * One reader for both servers, so a long-poll that works under `gemi start`\n * also works under `gemi dev`. Before this, only `httpProd` read the variable\n * and the dev server always ran at Bun's 10 seconds.\n *\n * It is the time a connection may stay silent, a response that has not started\n * included, before Bun closes it; `0` disables it. It does not apply to an\n * upgraded websocket (the HMR relay included), which has its own\n * `websocket.idleTimeout`.\n *\n * Unset or blank means the default. Anything that is not a whole number from 0\n * to 255 (Bun's own limits) fails the boot with the variable's name, instead\n * of Bun's \"expects idleTimeout to be an integer\", which does not say where the\n * value came from.\n */\nexport function serverIdleTimeout(raw: string | undefined = process.env.SERVER_IDLE_TIMEOUT): number {\n if (raw === undefined || raw.trim() === \"\") return DEFAULT_SERVER_IDLE_TIMEOUT;\n\n const seconds = Number(raw.trim());\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > 255) {\n throw new Error(\n `SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 ` +\n `(0 disables the timeout), got ${JSON.stringify(raw)}.`,\n );\n }\n return seconds;\n}\n"
9
9
  ],
10
10
  "mappings": "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",
11
- "debugId": "DBB23962EBF8D63264756E2164756E21",
11
+ "debugId": "714D433C3D53C1F464756E2164756E21",
12
12
  "names": []
13
13
  }