gemi 0.201.0 → 0.202.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +18 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-6xa5yqrw.js → chunk-07qjfj2c.js} +2 -2
- package/dist/{chunk-6xa5yqrw.js.map → chunk-07qjfj2c.js.map} +1 -1
- package/dist/{chunk-zpqcawmq.js → chunk-0a5png2z.js} +2 -2
- package/dist/{chunk-xb0k1br9.js.map → chunk-0a5png2z.js.map} +1 -1
- package/dist/{chunk-s9z0xxth.js → chunk-2816nz5e.js} +2 -2
- package/dist/{chunk-s9z0xxth.js.map → chunk-2816nz5e.js.map} +1 -1
- package/dist/{chunk-e7bb26fb.js → chunk-2n98hczh.js} +2 -2
- package/dist/{chunk-e7bb26fb.js.map → chunk-2n98hczh.js.map} +1 -1
- package/dist/{chunk-yw9mn5w7.js → chunk-3cd30c7k.js} +2 -2
- package/dist/{chunk-yw9mn5w7.js.map → chunk-3cd30c7k.js.map} +1 -1
- package/dist/{chunk-v2pt8h42.js → chunk-4jbrazr4.js} +2 -2
- package/dist/{chunk-v2pt8h42.js.map → chunk-4jbrazr4.js.map} +1 -1
- package/dist/{chunk-ty7tv5ab.js → chunk-5msb5ev6.js} +2 -2
- package/dist/{chunk-ty7tv5ab.js.map → chunk-5msb5ev6.js.map} +1 -1
- package/dist/{chunk-ahss6dcp.js → chunk-65r1ne8r.js} +2 -2
- package/dist/{chunk-ahss6dcp.js.map → chunk-65r1ne8r.js.map} +1 -1
- package/dist/{chunk-w84ke0bp.js → chunk-6a7kp98d.js} +2 -2
- package/dist/{chunk-w84ke0bp.js.map → chunk-6a7kp98d.js.map} +1 -1
- package/dist/{chunk-rh84xq17.js → chunk-6eywgbfz.js} +2 -2
- package/dist/{chunk-rh84xq17.js.map → chunk-6eywgbfz.js.map} +1 -1
- package/dist/{chunk-97g2qc7j.js → chunk-781k79x8.js} +1 -1
- package/dist/{chunk-rcnpjwp4.js → chunk-7881fdej.js} +2 -2
- package/dist/{chunk-rcnpjwp4.js.map → chunk-7881fdej.js.map} +1 -1
- package/dist/{chunk-2cyd3h4h.js → chunk-7gmkcgq0.js} +2 -2
- package/dist/{chunk-2cyd3h4h.js.map → chunk-7gmkcgq0.js.map} +1 -1
- package/dist/{chunk-n9k29mrs.js → chunk-7xwr52d8.js} +2 -2
- package/dist/{chunk-n9k29mrs.js.map → chunk-7xwr52d8.js.map} +1 -1
- package/dist/{chunk-wxb2pqqz.js → chunk-87f4gan9.js} +2 -2
- package/dist/{chunk-wxb2pqqz.js.map → chunk-87f4gan9.js.map} +1 -1
- package/dist/{chunk-206n0q1f.js → chunk-9k3axdsb.js} +2 -2
- package/dist/{chunk-206n0q1f.js.map → chunk-9k3axdsb.js.map} +1 -1
- package/dist/{chunk-tyvc46ns.js → chunk-9kmh038f.js} +2 -2
- package/dist/{chunk-tyvc46ns.js.map → chunk-9kmh038f.js.map} +1 -1
- package/dist/{chunk-zwbpcch0.js → chunk-a2ybf4jf.js} +1 -1
- package/dist/{chunk-42b6zzg2.js → chunk-a5fvqc4k.js} +2 -2
- package/dist/{chunk-42b6zzg2.js.map → chunk-a5fvqc4k.js.map} +1 -1
- package/dist/{chunk-xxep62yg.js → chunk-a6hac7pd.js} +1 -1
- package/dist/{chunk-w09wtxr6.js → chunk-a9cztxee.js} +3 -3
- package/dist/{chunk-w09wtxr6.js.map → chunk-a9cztxee.js.map} +1 -1
- package/dist/{chunk-ct1vh28z.js → chunk-bs6nxaqa.js} +2 -2
- package/dist/{chunk-ct1vh28z.js.map → chunk-bs6nxaqa.js.map} +1 -1
- package/dist/{chunk-tjsv6e3a.js → chunk-bz3527wx.js} +2 -2
- package/dist/{chunk-tjsv6e3a.js.map → chunk-bz3527wx.js.map} +1 -1
- package/dist/{chunk-6ftdsrkq.js → chunk-c8041bgj.js} +2 -2
- package/dist/{chunk-6ftdsrkq.js.map → chunk-c8041bgj.js.map} +1 -1
- package/dist/{chunk-xb0k1br9.js → chunk-cwxjqfkx.js} +2 -2
- package/dist/{chunk-zpqcawmq.js.map → chunk-cwxjqfkx.js.map} +1 -1
- package/dist/{chunk-q2dypdf5.js → chunk-dh8jqx0k.js} +2 -2
- package/dist/{chunk-q2dypdf5.js.map → chunk-dh8jqx0k.js.map} +1 -1
- package/dist/{chunk-ff22412e.js → chunk-e3bwytc2.js} +4 -4
- package/dist/{chunk-ff22412e.js.map → chunk-e3bwytc2.js.map} +1 -1
- package/dist/{chunk-dp2r3vkj.js → chunk-e9w2yzd2.js} +2 -2
- package/dist/{chunk-dp2r3vkj.js.map → chunk-e9w2yzd2.js.map} +1 -1
- package/dist/{chunk-50nex9wg.js → chunk-evaeb75q.js} +3 -3
- package/dist/{chunk-50nex9wg.js.map → chunk-evaeb75q.js.map} +1 -1
- package/dist/{chunk-nnaz5djg.js → chunk-fdcay8np.js} +2 -2
- package/dist/{chunk-nnaz5djg.js.map → chunk-fdcay8np.js.map} +1 -1
- package/dist/{chunk-gx2fhmnx.js → chunk-h1fqgz82.js} +3 -3
- package/dist/{chunk-gx2fhmnx.js.map → chunk-h1fqgz82.js.map} +1 -1
- package/dist/{chunk-93j09zw7.js → chunk-h2ysbsax.js} +1 -1
- package/dist/{chunk-drb6gpgv.js → chunk-h7h8ra65.js} +1 -1
- package/dist/{chunk-1qw9qz03.js → chunk-hd8gymeg.js} +2 -2
- package/dist/{chunk-1qw9qz03.js.map → chunk-hd8gymeg.js.map} +1 -1
- package/dist/{chunk-n3p16jpb.js → chunk-hra8evrw.js} +3 -3
- package/dist/{chunk-n3p16jpb.js.map → chunk-hra8evrw.js.map} +1 -1
- package/dist/{chunk-dqgn4wgf.js → chunk-j43hftgw.js} +2 -2
- package/dist/{chunk-dqgn4wgf.js.map → chunk-j43hftgw.js.map} +1 -1
- package/dist/{chunk-txbram9h.js → chunk-m3nhdg9v.js} +2 -2
- package/dist/{chunk-txbram9h.js.map → chunk-m3nhdg9v.js.map} +1 -1
- package/dist/{chunk-bdbg2dt6.js → chunk-mq82r0qp.js} +2 -2
- package/dist/{chunk-bdbg2dt6.js.map → chunk-mq82r0qp.js.map} +1 -1
- package/dist/{chunk-pab6ye4d.js → chunk-n7bz2283.js} +2 -2
- package/dist/{chunk-pab6ye4d.js.map → chunk-n7bz2283.js.map} +1 -1
- package/dist/{chunk-e603nm1c.js → chunk-p96z3yb6.js} +2 -2
- package/dist/{chunk-e603nm1c.js.map → chunk-p96z3yb6.js.map} +1 -1
- package/dist/{chunk-0kfrwbhg.js → chunk-phszs9ea.js} +4 -4
- package/dist/{chunk-0kfrwbhg.js.map → chunk-phszs9ea.js.map} +1 -1
- package/dist/{chunk-503ce1t9.js → chunk-ptbrbp80.js} +2 -2
- package/dist/{chunk-503ce1t9.js.map → chunk-ptbrbp80.js.map} +1 -1
- package/dist/{chunk-8fzcs8dv.js → chunk-qz7v6271.js} +2 -2
- package/dist/{chunk-8fzcs8dv.js.map → chunk-qz7v6271.js.map} +1 -1
- package/dist/{chunk-kz15j07h.js → chunk-sw7c95nh.js} +2 -2
- package/dist/{chunk-kz15j07h.js.map → chunk-sw7c95nh.js.map} +1 -1
- package/dist/{chunk-61mcmhjp.js → chunk-tbt2j0rf.js} +1 -1
- package/dist/{chunk-6nr97atn.js → chunk-wn9e8bjn.js} +2 -2
- package/dist/{chunk-6nr97atn.js.map → chunk-wn9e8bjn.js.map} +1 -1
- package/dist/chunk-wxcbfqkd.js +5 -0
- package/dist/chunk-wxcbfqkd.js.map +13 -0
- package/dist/{chunk-952ek0kg.js → chunk-x2zw82xg.js} +17 -17
- package/dist/{chunk-952ek0kg.js.map → chunk-x2zw82xg.js.map} +3 -3
- package/dist/{chunk-q1zj3a0e.js → chunk-x41vw44z.js} +2 -2
- package/dist/{chunk-q1zj3a0e.js.map → chunk-x41vw44z.js.map} +1 -1
- package/dist/chunk-xhky6kyf.js +5 -0
- package/dist/chunk-xhky6kyf.js.map +10 -0
- package/dist/{chunk-y167pt0p.js → chunk-y0gaw9ez.js} +2 -2
- package/dist/{chunk-y167pt0p.js.map → chunk-y0gaw9ez.js.map} +1 -1
- package/dist/{chunk-84stff4t.js → chunk-y9ktwyrx.js} +1 -1
- package/dist/{chunk-6brwvyrz.js → chunk-zgg2xsxp.js} +2 -2
- package/dist/{chunk-6brwvyrz.js.map → chunk-zgg2xsxp.js.map} +1 -1
- package/dist/{chunk-4reyxar1.js → chunk-zhmc2jm4.js} +1 -1
- package/dist/{chunk-xhc16pv1.js → chunk-zmj4fj4n.js} +1 -1
- package/dist/chunks/{RealtimeClient-DmBC8zxt.js → RealtimeClient-BnNSz8AK.js} +2 -2
- package/dist/chunks/{RealtimeClient-DmBC8zxt.js.map → RealtimeClient-BnNSz8AK.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-BTVQYl5O.js → ThemeProvider-CoQ-vnvy.js} +9 -6
- package/dist/chunks/{ThemeProvider-BTVQYl5O.js.map → ThemeProvider-CoQ-vnvy.js.map} +1 -1
- package/dist/chunks/{fetchFileRequest-BHCSZqKL.js → fetchFileRequest-Bhp0oJ0T.js} +2 -2
- package/dist/chunks/{fetchFileRequest-BHCSZqKL.js.map → fetchFileRequest-Bhp0oJ0T.js.map} +1 -1
- package/dist/chunks/{live-DIj7rF0t.js → live-Dt8sq9W4.js} +3 -3
- package/dist/chunks/{live-DIj7rF0t.js.map → live-Dt8sq9W4.js.map} +1 -1
- package/dist/chunks/{mutationExtras-BRFfb6-L.js → mutationExtras-ChOGPZlY.js} +2 -2
- package/dist/chunks/{mutationExtras-BRFfb6-L.js.map → mutationExtras-ChOGPZlY.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-CRRgUXJp.js → subscriptionStream-DDl_H-QM.js} +2 -2
- package/dist/chunks/{subscriptionStream-CRRgUXJp.js.map → subscriptionStream-DDl_H-QM.js.map} +1 -1
- package/dist/client/index.js +4 -4
- package/dist/client/scrollRestoration.d.ts +5 -2
- package/dist/client/scrollRestoration.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +1 -1
- package/dist/database/index.js +1 -1
- package/dist/email/index.js +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/foundation/Application.d.ts +23 -3
- package/dist/foundation/Application.d.ts.map +1 -1
- package/dist/foundation/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/dictionaryRuntime.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/Kernel.d.ts.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +3 -3
- package/dist/orm/index.js +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +2 -2
- package/dist/server/shutdown.d.ts +35 -0
- package/dist/server/shutdown.d.ts.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/WorkerProcess.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +3 -3
- package/dist/stats/route-table.js +1 -1
- package/dist/support/Service.d.ts +21 -0
- package/dist/support/Service.d.ts.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +3 -3
- package/dist/testing/index.js +2 -2
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-1yq2b55s.js +0 -5
- package/dist/chunk-1yq2b55s.js.map +0 -10
- package/dist/chunk-jkf5kjaz.js +0 -5
- package/dist/chunk-jkf5kjaz.js.map +0 -13
- /package/dist/{chunk-97g2qc7j.js.map → chunk-781k79x8.js.map} +0 -0
- /package/dist/{chunk-zwbpcch0.js.map → chunk-a2ybf4jf.js.map} +0 -0
- /package/dist/{chunk-xxep62yg.js.map → chunk-a6hac7pd.js.map} +0 -0
- /package/dist/{chunk-93j09zw7.js.map → chunk-h2ysbsax.js.map} +0 -0
- /package/dist/{chunk-drb6gpgv.js.map → chunk-h7h8ra65.js.map} +0 -0
- /package/dist/{chunk-61mcmhjp.js.map → chunk-tbt2j0rf.js.map} +0 -0
- /package/dist/{chunk-84stff4t.js.map → chunk-y9ktwyrx.js.map} +0 -0
- /package/dist/{chunk-4reyxar1.js.map → chunk-zhmc2jm4.js.map} +0 -0
- /package/dist/{chunk-xhc16pv1.js.map → chunk-zmj4fj4n.js.map} +0 -0
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * The entry point `gemi queue:work` spawns.\n *\n * Exposed as `gemi/queue/work` and resolved by the CLI out of the\n * *application's* `node_modules`, for the reason `gemi/console/run` is: the\n * application's kernel, providers and jobs are built from its copy of gemi,\n * and the worker that drives them should be the same copy, not one bundled\n * into the CLI.\n *\n * Everything worth testing is in `QueueWorker`; this file is the order the\n * process does things in.\n */\nimport path from \"node:path\";\n\nimport { installShutdownSignals } from \"../../server/shutdown\";\nimport { projectRoot } from \"../../support/discover\";\nimport { markQueueWorker } from \"./QueueManager\";\nimport { QueueWorker, QueueWorkerRefused, type WorkerKernel } from \"./WorkerProcess\";\n\nasync function main(): Promise<number | undefined> {\n const rootDir = projectRoot();\n // What `Server.start` and `httpProd` set, and for the same readers: a\n // `worker = true` job's thread finds the application through them, and the\n // log provider resolves its paths from `ROOT_DIR`.\n process.env.ROOT_DIR = rootDir;\n process.env.APP_DIR = path.join(rootDir, \"app\");\n // Before the kernel is imported, so no claim rule can be asked first.\n markQueueWorker();\n\n const kernelPath = path.join(rootDir, \"app/kernel/Kernel.ts\");\n const { default: Kernel } = (await import(kernelPath)) as {\n default?: new () => WorkerKernel & { boot(): void };\n };\n if (typeof Kernel !== \"function\") {\n console.error(`[gemi] ${kernelPath} has no default export to boot the worker from.`);\n return 1;\n }\n const kernel = new Kernel();\n kernel.boot();\n\n const worker = new QueueWorker(kernel);\n // Before the boot, as `Server.start` does in production: the boot is the\n // slow part, and a signal that lands in it would otherwise kill the process\n // on the spot. In development too, unlike a server — no `bun --hot` re-runs\n // this, and a Ctrl+C that lets the jobs finish is what a worker is for.\n installShutdownSignals(() => worker.stop());\n\n try {\n await worker.start();\n } catch (error) {\n if (!(error instanceof QueueWorkerRefused)) throw error;\n console.error(error.message);\n return 1;\n }\n // Running: the signal handler exits the process once it has drained.\n return undefined;\n}\n\nmain().then(\n (code) => {\n if (code !== undefined) process.exit(code);\n },\n (error) => {\n console.error(\"[gemi] The queue worker failed to start:\", error);\n process.exit(1);\n },\n);\n",
|
|
6
6
|
"import type { Application } from \"../../foundation/Application\";\nimport type { BroadcastConfig } from \"./config\";\nimport { MemoryBroadcastDriver } from \"./MemoryBroadcastDriver\";\n\n/**\n * What `gemi queue:work` warns at boot when the app declares channels but\n * broadcasts with the memory driver, or `null`. A worker has no sockets, so\n * with the memory driver its jobs' emits reach no one, with nothing else to\n * say so. A warning, not a refusal as for a memory queue: the worker still\n * runs its jobs, only their broadcasts are lost.\n */\nexport function memoryBroadcastInWorker(application: Application): string | null {\n if (!application.config.get(\"route.channels\")) return null;\n const driver = application.config.get<BroadcastConfig>(\"broadcast\", {}).driver;\n const memory =\n driver === undefined || driver === \"memory\" || driver instanceof MemoryBroadcastDriver;\n if (!memory) return null;\n return (\n \"[gemi] Broadcasts from this worker reach no one: the broadcast driver is \" +\n '\"memory\", which delivers to the sockets of the process that emits, and a ' +\n 'worker has none. Set `driver: \"redis\"` in app/config/broadcast.ts.'\n );\n}\n",
|
|
7
|
-
"import type { Application, ShutdownReport } from \"../../foundation/Application\";\nimport {
|
|
7
|
+
"import type { Application, ShutdownReport } from \"../../foundation/Application\";\nimport {\n heldWork,\n heldWorkSettled,\n markShuttingDown,\n shutdownSettings,\n type ShutdownSettings,\n} from \"../../server/shutdown\";\nimport { memoryBroadcastInWorker } from \"../broadcast/workerWarning\";\nimport { QueueManager } from \"./QueueManager\";\n\n/** The part of a `Kernel` a worker drives. */\nexport type WorkerKernel = {\n readonly app: Application;\n waitForBoot(): Promise<void>;\n shutdown(options?: { timeoutMs?: number }): Promise<ShutdownReport>;\n};\n\n/**\n * A worker that was told to start in an application it cannot claim for. The\n * message is written for the operator reading the deploy's logs.\n */\nexport class QueueWorkerRefused extends Error {\n name = \"QueueWorkerRefused\";\n}\n\n/**\n * The process `gemi queue:work` runs: the application booted as a server boots\n * it, claiming from the queue, and no `Bun.serve`. It exists so job capacity\n * can be scaled apart from request traffic, which needs a driver both kinds of\n * process can reach; see `start` for why the memory driver is refused.\n *\n * The caller marks the process as a worker (`markQueueWorker`) before the\n * kernel registers, so every claim rule that asks `claimsInThisProcess` sees a\n * process that claims, whatever `GEMI_QUEUE_CLAIM` says.\n */\nexport class QueueWorker {\n private stopping: Promise<number> | undefined;\n private keepAlive: ReturnType<typeof setInterval> | undefined;\n private readonly settings: ShutdownSettings;\n\n /**\n * `settings` default to the `GEMI_SHUTDOWN_*` variables, read here rather\n * than at the signal so a bad value is warned about while the deploy is\n * being watched, as `Server.start` does.\n */\n constructor(\n private readonly kernel: WorkerKernel,\n settings: Partial<ShutdownSettings> = {},\n ) {\n this.settings = { ...shutdownSettings(), ...settings };\n }\n\n /**\n * Boots the application and starts claiming. Rejects with\n * `QueueWorkerRefused` when the application has no queue, or its queue uses\n * the memory driver.\n *\n * Refused rather than warned about, because a memory worker can never do\n * anything: its jobs live in a `Map` in the process that dispatched them,\n * so a worker's is always empty. Left running, it looks like a healthy\n * deploy — a process up, no errors — that runs nothing, and scaling it out\n * adds no capacity. An exit the platform reports as a crash loop is a form\n * of the mistake someone will see.\n */\n async start(): Promise<void> {\n await this.kernel.waitForBoot();\n // A signal during the boot has already drained and cleared the handle\n // below. Going on would start the loop again and arm a handle nothing\n // clears, holding open a worker that has finished shutting down.\n if (this.stopping) return;\n\n const application = this.kernel.app;\n // `bound`, not `make` in a try: an application built without the queue\n // provider is a configuration to name, not an unbound-token stack trace.\n if (!application.bound(QueueManager)) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` has no queue to claim from: this application \" +\n \"does not register QueueServiceProvider.\",\n );\n }\n const queue = application.make(QueueManager);\n if (!queue.durable) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` refuses to start: the queue uses the memory \" +\n \"driver, which keeps each job in the process that dispatched it, so \" +\n 'a worker never sees one. Set `driver: \"database\"` (or another driver ' +\n \"every process can reach) in app/config/queue.ts, or run jobs in the \" +\n \"server and drop the worker.\",\n );\n }\n\n // Idempotent: a production boot with a durable driver has already started\n // it (`startClaimingIfServing`). Development has not, and a worker claims\n // in either.\n queue.start();\n // The queue's poll timer is unref'd, so that a script's queue does not\n // hold it open; here the queue is the process, and without a handle of its\n // own an idle worker would exit 0 as soon as it booted.\n this.keepAlive = setInterval(() => {}, 1 << 30);\n console.log(\n `[gemi] Queue worker started: claiming up to ${queue.config.concurrency} job(s) at a time.`,\n );\n const broadcastWarning = memoryBroadcastInWorker(application);\n if (broadcastWarning) console.warn(broadcastWarning);\n }\n\n /**\n * Stops claiming, waits for the running jobs, runs every provider's\n * `shutdown()`, and resolves with the exit code: 0 when no job was left\n * running and every provider finished in time, 1 otherwise. Idempotent.\n *\n * `gemi start`'s drain, with the jobs where the requests were:\n * `isShuttingDown()` turns true, which stops a durable queue claiming;\n * running jobs get `timeoutMs` (`GEMI_SHUTDOWN_TIMEOUT`), which a server\n * spends on requests; then `Application.shutdown` gets `providerTimeoutMs`,\n * and in it the queue provider waits for whatever is still running and\n * names it. The two budgets add up as they do for a server, so a worker\n * fits the same grace period. `delayMs` is not waited: it is for a load\n * balancer, and nothing routes to a worker.\n */\n stop(settings: Partial<ShutdownSettings> = {}): Promise<number> {\n this.stopping ??= this.drain({ ...this.settings, ...settings });\n return this.stopping;\n }\n\n private async drain(settings: ShutdownSettings): Promise<number> {\n const deadline = Date.now() + settings.timeoutMs;\n markShuttingDown();\n const application = this.kernel.app;\n // Resolving the manager now would build a driver only to stop it, which\n // is what a signal during the boot, before the provider resolved it, finds.\n const queue = application.resolved(QueueManager) ? application.make(QueueManager) : undefined;\n if (queue) {\n console.log(\n `[gemi] Shutting down: waiting for ${queue.running} running job(s) ` +\n `(up to ${settings.timeoutMs / 1000}s).`,\n );\n await queue.drain(settings.timeoutMs);\n }\n // Work held with `holdShutdown` (#1210) gets what is left of the same budget.\n let held = heldWork() === 0;\n if (!held) {\n const remaining = deadline - Date.now();\n held =\n remaining > 0 &&\n (await Promise.race([\n heldWorkSettled().then(() => true),\n new Promise<false>((resolve) => setTimeout(() => resolve(false), remaining)),\n ]));\n if (!held) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${heldWork()} held background task(s) still running; abandoning them.`,\n );\n }\n }\n\n const report = await this.kernel.shutdown({ timeoutMs: settings.providerTimeoutMs });\n clearInterval(this.keepAlive);\n const clean =\n held && (queue?.running ?? 0) === 0 && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n }\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": ";
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": ";gdAYA,kBCDO,OAAS,DAAuB,DAAC,AAAyC,DAC/E,CAAI,DAAC,AAAY,KAAO,IAAI,gBAAgB,EAAG,OAAO,KACtD,IAAM,EAAS,EAAY,OAAO,IAAqB,YAAa,CAAC,CAAC,EAAE,OAGxE,GAAI,EADF,IAAW,QAAa,IAAW,UAAY,aAAkB,GACtD,OAAO,KACpB,MACE,uNCIG,MAAM,UAA2B,KAAM,CAC5C,KAAO,oBACT,CAYO,MAAM,CAAY,CAWJ,OAVX,SACA,UACS,SAOjB,WAAW,CACQ,EACjB,EAAsC,CAAC,EACv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AAM,KAAK,OAAO,SAAS,CAAE,UAAW,EAAS,iBAAkB,CAAC,EACnF,cAAc,KAAK,SAAS,EAC5B,IAAM,EACJ,IAAS,GAAO,SAAW,KAAO,GAAK,EAAO,OAAO,SAAW,GAAK,EAAO,SAAS,SAAW,EAElG,OADA,QAAQ,IAAI,mBAAmB,EAAQ,WAAa,yBAAyB,EACtE,EAAQ,EAAI,EAEvB,CFjJA,eAAe,CAAI,EAAgC,CACjD,IAAM,EAAU,EAAY,EAI5B,QAAQ,IAAI,SAAW,EACvB,QAAQ,IAAI,QAAU,EAAK,KAAK,EAAS,KAAK,EAE9C,EAAgB,EAEhB,IAAM,EAAa,EAAK,KAAK,EAAS,sBAAsB,GACpD,QAAS,GAAY,MAAa,UAG1C,GAAI,OAAO,IAAW,WAEpB,OADA,QAAQ,MAAM,UAAU,kDAA2D,EAC5E,EAET,IAAM,EAAS,IAAI,EACnB,EAAO,KAAK,EAEZ,IAAM,EAAS,IAAI,EAAY,CAAM,EAKrC,EAAuB,IAAM,EAAO,KAAK,CAAC,EAE1C,GAAI,CACF,MAAM,EAAO,MAAM,EACnB,MAAO,EAAO,CACd,GAAI,EAAE,aAAiB,GAAqB,MAAM,EAElD,OADA,QAAQ,MAAM,EAAM,OAAO,EACpB,EAGT,OAGF,EAAK,EAAE,KACL,CAAC,IAAS,CACR,GAAI,IAAS,OAAW,QAAQ,KAAK,CAAI,GAE3C,CAAC,IAAU,CACT,QAAQ,MAAM,2CAA4C,CAAK,EAC/D,QAAQ,KAAK,CAAC,EAElB",
|
|
10
|
+
"debugId": "427A66C78129C4D964756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"../chunk-
|
|
2
|
+
import"../chunk-0a5png2z.js";import M from"path";import{writeFileSync as Q}from"fs";var L=new Set(["FILE","REDIRECT"]);function H(j){return j.run(()=>{let x=[];for(let{group:z,view:D}of j.domains().viewGroups())for(let[G,B]of Object.entries(D.flatViewRoutes)){let C=D.routeManifest[G]??B.segments.map((K)=>K.viewPath);if(C.length===0||L.has(C.at(-1)))continue;x.push({path:G,group:z,views:C,...B.static?{static:{...B.static.layout?{layout:B.static.layout}:{},...B.static.navigation?{navigation:!0}:{}}}:{}})}return x})}var J=process.argv[2];async function U(){if(!J)throw Error("usage: route-table <out.json>");let j=M.resolve(process.cwd(),"app/kernel/Kernel.ts"),x=await import(j);if(typeof x.default!=="function")throw Error(`${j} has no default export (the Kernel subclass).`);let z=new x.default;z.boot();try{Q(J,JSON.stringify(H(z)))}finally{z.destroy()}}U().then(()=>process.exit(0),(j)=>{console.error(j?.stack??String(j)),process.exit(1)});
|
|
3
3
|
|
|
4
4
|
//# debugId=05EB0087C5A2060D64756E2164756E21
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ProviderShutdownResult } from "./ServiceProvider";
|
|
1
2
|
/**
|
|
2
3
|
* Base for the application's own long-lived singletons — an API client, a
|
|
3
4
|
* billing gateway, a search index. A subclass declares a `static token`, holds
|
|
@@ -40,6 +41,26 @@ export declare abstract class Service {
|
|
|
40
41
|
* `boot()` needs another service must be listed after it.
|
|
41
42
|
*/
|
|
42
43
|
boot(): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Runs once when a production server (or a `gemi queue:work` worker) is
|
|
46
|
+
* told to stop, after the requests and the work held with `holdShutdown`
|
|
47
|
+
* (from `gemi/server`) have drained (#1210). Services shut down in reverse
|
|
48
|
+
* `services` order, before every provider, so a service may still use the
|
|
49
|
+
* database, the cache and the facades here. Under `gemi dev` it also runs
|
|
50
|
+
* for the application a `bun --hot` reload replaced.
|
|
51
|
+
*
|
|
52
|
+
* It shares the providers' deadline (`GEMI_SHUTDOWN_PROVIDER_TIMEOUT`):
|
|
53
|
+
* `timeoutMs` is what is left of it. Resolve `{ abandoned: true }` when it
|
|
54
|
+
* gave up on work at the deadline, as a provider would; one that throws is
|
|
55
|
+
* logged and the rest still run. See `ServiceProvider.shutdown`.
|
|
56
|
+
*
|
|
57
|
+
* Named `onShutdown` rather than `shutdown` so that a service which already
|
|
58
|
+
* has a `shutdown()` method of its own (called from a provider, with its own
|
|
59
|
+
* arguments) is not called a second time, with an argument it doesn't take.
|
|
60
|
+
*/
|
|
61
|
+
onShutdown(_options: {
|
|
62
|
+
timeoutMs: number;
|
|
63
|
+
}): ProviderShutdownResult | Promise<ProviderShutdownResult>;
|
|
43
64
|
/**
|
|
44
65
|
* The booted singleton for the current application.
|
|
45
66
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Service.d.ts","sourceRoot":"","sources":["../../support/Service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Service.d.ts","sourceRoot":"","sources":["../../support/Service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAGhE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,8BAAsB,OAAO;IAC3B;;;;;OAKG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAE3B;;;;;;;;;;;;;;;;OAgBG;IACH,UAAU,CAAC,QAAQ,EAAE;QACnB,SAAS,EAAE,MAAM,CAAC;KACnB,GAAG,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAE5D;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,MAAM,CAAC,CAAC,EACb,IAAI,EAAE,CAAC,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC,GAAG;QAC3C,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;KACd,GACA,CAAC;IAoBJ;;;;;;;;;;;;;;;OAeG;IACH,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;CAO5E;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAAC,UAAU,OAAO,CAAC,GAAG;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd,CAAC"}
|
package/dist/support/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{le as Y}from"../chunk-vqq0z746.js";import{xk as M}from"../chunk-bcfcwbp4.js";import{Bl as R,zl as P}from"../chunk-
|
|
2
|
+
import{le as Y}from"../chunk-vqq0z746.js";import{xk as M}from"../chunk-bcfcwbp4.js";import{Bl as R,zl as P}from"../chunk-wxcbfqkd.js";import"../chunk-ha4er085.js";import{Vl as Q,Wl as U,Xl as V,Yl as W}from"../chunk-65r1ne8r.js";import"../chunk-0a5png2z.js";class S{static token;async boot(){}onShutdown(x){}static inject(){if(!this.token)throw Error(`Service [${this.name}] does not declare a \`static token\`, so the container has no key to resolve it by.`);try{return R(this)}catch(x){throw Error(`Could not inject [${this.name}]. Services are constructed when the kernel boots, so `+"inject() only works from code that runs after that \u2014 a constructor default or a method "+`body, never module top level. Check that [${this.name}] is listed in \`services\` on your Kernel.`,{cause:x})}}static with(x){let f=new this;for(let[C,g]of Object.entries(x))if(g!==void 0)f[C]=g;return f}}import{readdir as z}from"fs/promises";import{join as B,parse as j}from"path";var H=[".ts",".tsx",".js",".mjs",".jsx"];function J(x={}){let f={};for(let[C,g]of Object.entries(x))f[C]=q(g);return new P(f)}async function L(x,f=new P){let C=[];try{C=await z(x)}catch(D){return f}let g=C.filter((D)=>{let{ext:v,name:F}=j(D);return H.includes(v)&&!F.startsWith(".")}).sort();for(let D of g){let{name:v}=j(D),F=await import(B(x,D));f.set(v,q(F))}return f}function q(x){if(x&&typeof x==="object"&&"default"in x)return x.default;return x}export{M as withDefaults,Q as sourceFiles,W as projectRoot,L as loadConfigFrom,V as discoverClasses,J as createConfigRepository,Y as ServiceProvider,S as Service,P as Repository,U as DiscoveryError};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=F697CA21F59DFAE164756E2164756E21
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../support/Service.ts", "../support/loadConfig.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { ServiceToken } from \"../container/Container\";\nimport { app } from \"../foundation/app\";\n\n/**\n * Base for the application's own long-lived singletons — an API client, a\n * billing gateway, a search index. A subclass declares a `static token`, holds\n * its settings as ordinary fields, and is listed in `services` on the Kernel;\n * the kernel constructs it once and awaits its `boot()` before the first\n * request is served.\n *\n * ### Why the settings are fields and not a config slice\n *\n * `app/config/*.ts` exists because you do not own the class. `MailManager` and\n * `AuthManager` ship with the framework, so a config slice is the only place\n * you can reach in and change them. You *do* own a `Service` subclass, so there\n * is nothing to reach in from the outside for — a field is a real declaration\n * the compiler checks, where a config slice is a string key and a cast over\n * `Repository.get`, which returns `any`. Use `.with()` to override at the\n * wiring site or in a test.\n *\n * ### Why `boot()` is async and the constructor is not\n *\n * `Container.make` is synchronous, so a lazily-constructed service could never\n * await anything. Construction therefore does no I/O — it runs during the\n * kernel's synchronous phase, which is what makes an instance available to a\n * provider's `boot()` — and everything that needs to await happens in `boot()`,\n * during the asynchronous phase. The cost is that every listed service is\n * constructed and booted on every application boot, including in a worker\n * thread and in every test that boots a kernel. Keep `boot()` cheap: validate\n * settings there, and open connections lazily inside the methods that need\n * them.\n */\nexport abstract class Service {\n /**\n * The container key. Required, and a string literal rather than the class's\n * implicit `.name`, for the same reason every other service in the framework\n * carries one — see the note on `ServiceToken`. Minification renames the\n * class; it cannot rename a string.\n */\n static token: string;\n\n /**\n * Awaited once during kernel boot, in `services` order. A service whose\n * `boot()` needs another service must be listed after it.\n */\n async boot(): Promise<void> {}\n\n /**\n * The booted singleton for the current application.\n *\n * Written as a constructor default so a controller reads as an ordinary\n * class and stays constructible by hand:\n *\n * class FooController extends Controller {\n * constructor(private billing = Billing.inject()) {\n * super();\n * }\n * }\n *\n * The default is evaluated when the controller is constructed — per request,\n * inside the kernel's async context — so this resolves against the\n * Application handling that request, and a test that passes its own instance\n * never evaluates it at all.\n */\n static inject<T>(\n this: (abstract new (...args: any[]) => T) & {\n token: string;\n name: string;\n },\n ): T {\n if (!this.token) {\n throw new Error(\n `Service [${this.name}] does not declare a \\`static token\\`, so the container has no key to resolve it by.`,\n );\n }\n\n try {\n return app(this as ServiceToken<T>);\n } catch (cause) {\n throw new Error(\n `Could not inject [${this.name}]. Services are constructed when the kernel boots, so ` +\n `inject() only works from code that runs after that — a constructor default or a method ` +\n `body, never module top level. Check that [${this.name}] is listed in \\`services\\` on ` +\n `your Kernel.`,\n { cause },\n );\n }\n }\n\n /**\n * A configured instance: constructs the service and assigns over its fields.\n * Typed against the subclass, which a constructor parameter on this base\n * class could not be — there is no `Partial<this>` in a constructor\n * signature.\n *\n * services = [Billing.with({ apiKey: process.env.STAGING_KEY })];\n * const billing = Billing.with({ apiKey: \"test\" }); // in a test\n *\n * A key whose value is `undefined` is skipped rather than assigned. The first\n * line above is the reason: `process.env.STAGING_KEY` is `undefined` in every\n * environment that does not set it, and `Object.assign` would copy that over\n * the field's declared default — so the service would boot holding\n * `undefined` where it had a perfectly good fallback. An absent value is not\n * an override; write `null` if you mean to clear a field.\n */\n static with<T extends Service>(this: new () => T, overrides: Partial<T>): T {\n const instance = new this();\n for (const [key, value] of Object.entries(overrides)) {\n if (value !== undefined) instance[key] = value;\n }\n return instance;\n }\n}\n\n/**\n * A `Service` subclass, as the Kernel's `services` array accepts it. The array\n * also takes instances, which is what `.with()` returns.\n */\nexport type ServiceConstructor = (new () => Service) & {\n token: string;\n name: string;\n};\n",
|
|
5
|
+
"import type { ServiceToken } from \"../container/Container\";\nimport type { ProviderShutdownResult } from \"./ServiceProvider\";\nimport { app } from \"../foundation/app\";\n\n/**\n * Base for the application's own long-lived singletons — an API client, a\n * billing gateway, a search index. A subclass declares a `static token`, holds\n * its settings as ordinary fields, and is listed in `services` on the Kernel;\n * the kernel constructs it once and awaits its `boot()` before the first\n * request is served.\n *\n * ### Why the settings are fields and not a config slice\n *\n * `app/config/*.ts` exists because you do not own the class. `MailManager` and\n * `AuthManager` ship with the framework, so a config slice is the only place\n * you can reach in and change them. You *do* own a `Service` subclass, so there\n * is nothing to reach in from the outside for — a field is a real declaration\n * the compiler checks, where a config slice is a string key and a cast over\n * `Repository.get`, which returns `any`. Use `.with()` to override at the\n * wiring site or in a test.\n *\n * ### Why `boot()` is async and the constructor is not\n *\n * `Container.make` is synchronous, so a lazily-constructed service could never\n * await anything. Construction therefore does no I/O — it runs during the\n * kernel's synchronous phase, which is what makes an instance available to a\n * provider's `boot()` — and everything that needs to await happens in `boot()`,\n * during the asynchronous phase. The cost is that every listed service is\n * constructed and booted on every application boot, including in a worker\n * thread and in every test that boots a kernel. Keep `boot()` cheap: validate\n * settings there, and open connections lazily inside the methods that need\n * them.\n */\nexport abstract class Service {\n /**\n * The container key. Required, and a string literal rather than the class's\n * implicit `.name`, for the same reason every other service in the framework\n * carries one — see the note on `ServiceToken`. Minification renames the\n * class; it cannot rename a string.\n */\n static token: string;\n\n /**\n * Awaited once during kernel boot, in `services` order. A service whose\n * `boot()` needs another service must be listed after it.\n */\n async boot(): Promise<void> {}\n\n /**\n * Runs once when a production server (or a `gemi queue:work` worker) is\n * told to stop, after the requests and the work held with `holdShutdown`\n * (from `gemi/server`) have drained (#1210). Services shut down in reverse\n * `services` order, before every provider, so a service may still use the\n * database, the cache and the facades here. Under `gemi dev` it also runs\n * for the application a `bun --hot` reload replaced.\n *\n * It shares the providers' deadline (`GEMI_SHUTDOWN_PROVIDER_TIMEOUT`):\n * `timeoutMs` is what is left of it. Resolve `{ abandoned: true }` when it\n * gave up on work at the deadline, as a provider would; one that throws is\n * logged and the rest still run. See `ServiceProvider.shutdown`.\n *\n * Named `onShutdown` rather than `shutdown` so that a service which already\n * has a `shutdown()` method of its own (called from a provider, with its own\n * arguments) is not called a second time, with an argument it doesn't take.\n */\n onShutdown(_options: {\n timeoutMs: number;\n }): ProviderShutdownResult | Promise<ProviderShutdownResult> {}\n\n /**\n * The booted singleton for the current application.\n *\n * Written as a constructor default so a controller reads as an ordinary\n * class and stays constructible by hand:\n *\n * class FooController extends Controller {\n * constructor(private billing = Billing.inject()) {\n * super();\n * }\n * }\n *\n * The default is evaluated when the controller is constructed — per request,\n * inside the kernel's async context — so this resolves against the\n * Application handling that request, and a test that passes its own instance\n * never evaluates it at all.\n */\n static inject<T>(\n this: (abstract new (...args: any[]) => T) & {\n token: string;\n name: string;\n },\n ): T {\n if (!this.token) {\n throw new Error(\n `Service [${this.name}] does not declare a \\`static token\\`, so the container has no key to resolve it by.`,\n );\n }\n\n try {\n return app(this as ServiceToken<T>);\n } catch (cause) {\n throw new Error(\n `Could not inject [${this.name}]. Services are constructed when the kernel boots, so ` +\n `inject() only works from code that runs after that — a constructor default or a method ` +\n `body, never module top level. Check that [${this.name}] is listed in \\`services\\` on ` +\n `your Kernel.`,\n { cause },\n );\n }\n }\n\n /**\n * A configured instance: constructs the service and assigns over its fields.\n * Typed against the subclass, which a constructor parameter on this base\n * class could not be — there is no `Partial<this>` in a constructor\n * signature.\n *\n * services = [Billing.with({ apiKey: process.env.STAGING_KEY })];\n * const billing = Billing.with({ apiKey: \"test\" }); // in a test\n *\n * A key whose value is `undefined` is skipped rather than assigned. The first\n * line above is the reason: `process.env.STAGING_KEY` is `undefined` in every\n * environment that does not set it, and `Object.assign` would copy that over\n * the field's declared default — so the service would boot holding\n * `undefined` where it had a perfectly good fallback. An absent value is not\n * an override; write `null` if you mean to clear a field.\n */\n static with<T extends Service>(this: new () => T, overrides: Partial<T>): T {\n const instance = new this();\n for (const [key, value] of Object.entries(overrides)) {\n if (value !== undefined) instance[key] = value;\n }\n return instance;\n }\n}\n\n/**\n * A `Service` subclass, as the Kernel's `services` array accepts it. The array\n * also takes instances, which is what `.with()` returns.\n */\nexport type ServiceConstructor = (new () => Service) & {\n token: string;\n name: string;\n};\n",
|
|
6
6
|
"import { readdir } from \"node:fs/promises\";\nimport { join, parse } from \"node:path\";\n\nimport { Repository } from \"./Repository\";\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".mjs\", \".jsx\"];\n\n// Builds a Repository from an already-imported map of config modules. The map\n// key becomes the top-level config key, so `{ mail: mailModule }` is readable\n// as `config.get(\"mail.driver\")`. Each entry may be either the module namespace\n// (its `default` export is unwrapped) or the config object itself.\nexport function createConfigRepository(\n modules: Record<string, any> = {},\n): Repository {\n const items: Record<string, any> = {};\n\n for (const [key, mod] of Object.entries(modules)) {\n items[key] = unwrap(mod);\n }\n\n return new Repository(items);\n}\n\n// Reads every config module in an app's `app/config` directory into a\n// Repository. The file's basename is the top-level key: `app/config/mail.ts`\n// populates `mail.*`. A missing directory yields an empty Repository so apps\n// that declare no config still boot.\nexport async function loadConfigFrom(\n directory: string,\n repository = new Repository(),\n): Promise<Repository> {\n let entries: string[] = [];\n\n try {\n entries = await readdir(directory);\n } catch (err) {\n return repository;\n }\n\n const files = entries\n .filter((entry) => {\n const { ext, name } = parse(entry);\n return CONFIG_EXTENSIONS.includes(ext) && !name.startsWith(\".\");\n })\n .sort();\n\n for (const file of files) {\n const { name } = parse(file);\n const mod = await import(join(directory, file));\n repository.set(name, unwrap(mod));\n }\n\n return repository;\n}\n\nfunction unwrap(mod: any) {\n if (mod && typeof mod === \"object\" && \"default\" in mod) {\n return mod.default;\n }\n return mod;\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": ";2RAiCO,CAAe,JAAQ,EAOrB,OAMD,AAAI,EAAkB,EAmB5B,UAAU,CAAC,EAEkD,QAmBtD,OAAS,EAKX,CACH,GAAI,CAAC,KAAK,MACR,MAAU,MACR,YAAY,KAAK,0FACnB,EAGF,GAAI,CACF,O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|
-
import { t as followLive } from "../chunks/live-
|
|
2
|
-
import { $ as toVariantKey, B as Action, G as RealtimeContext, J as liveModule, N as I18nProvider, P as ServerDataContext, V as createMemoryHistory, c as ClientRouterContext, et as applyParams, i as RouteTransitionProvider, nt as QueryManagerContext, r as m, rt as QueryManagerProvider, t as ThemeProvider, xt as Subject, z as ProgressManager } from "../chunks/ThemeProvider-
|
|
1
|
+
import { t as followLive } from "../chunks/live-Dt8sq9W4.js";
|
|
2
|
+
import { $ as toVariantKey, B as Action, G as RealtimeContext, J as liveModule, N as I18nProvider, P as ServerDataContext, V as createMemoryHistory, c as ClientRouterContext, et as applyParams, i as RouteTransitionProvider, nt as QueryManagerContext, r as m, rt as QueryManagerProvider, t as ThemeProvider, xt as Subject, z as ProgressManager } from "../chunks/ThemeProvider-CoQ-vnvy.js";
|
|
3
3
|
import { r as RouteStateProvider } from "../chunks/useParams-BN3XXfmG.js";
|
|
4
4
|
import { t as channelKey } from "../chunks/channelKey-CIhHpX6x.js";
|
|
5
5
|
import { Suspense, createElement, useContext, useMemo, useRef, useState } from "react";
|
package/dist/vitest/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ga as B,ha as D}from"../chunk-
|
|
2
|
+
import{ga as B,ha as D}from"../chunk-hra8evrw.js";import"../chunk-9k3axdsb.js";import"../chunk-bs6nxaqa.js";import{Ba as J}from"../chunk-5zjw41cv.js";import"../chunk-by0afyps.js";import"../chunk-0a5png2z.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
|
|
3
3
|
|
|
4
4
|
//# debugId=CE19A4044ADA908764756E2164756E21
|
package/package.json
CHANGED
package/dist/chunk-1yq2b55s.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{constants as M}from"os";var Y=Symbol.for("gemi.server.shutdown");function Q(){let j=globalThis;return j[Y]??={shuttingDown:!1,drained:!1},j[Y]}function R(){return Q().shuttingDown}function f(){Q().shuttingDown=!0}function x(){Q().drained=!0}function W(j=process.env){let z={timeoutMs:U(j.GEMI_SHUTDOWN_TIMEOUT,20),delayMs:U(j.GEMI_SHUTDOWN_DELAY,0),providerTimeoutMs:U(j.GEMI_SHUTDOWN_PROVIDER_TIMEOUT,5)};if(z.delayMs>0&&z.delayMs>=z.timeoutMs)console.warn(`[gemi] GEMI_SHUTDOWN_DELAY (${z.delayMs/1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${z.timeoutMs/1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`);return z}function U(j,z){let B=j===void 0||j.trim()===""?NaN:Number(j);if(Number.isFinite(B)&&B>=0)return B*1000;if(j!==void 0)console.warn(`[gemi] Ignoring shutdown setting "${j}": expected a number of seconds.`);return z*1000}async function E(j){let{server:z,settings:B}=j,J=Date.now()+B.timeoutMs;f(),console.log(`[gemi] Shutting down: draining in-flight requests (up to ${B.timeoutMs/1000}s).`);let H=!0;if(z){if(B.delayMs>0)await _(Math.min(B.delayMs,J-Date.now()));let O=z.stop(),V=Promise.resolve();try{V=Promise.resolve(j.closeSockets?.()).catch(()=>{})}catch(F){console.error("[gemi] Closing the broadcast sockets failed:",F)}let X=J-Date.now(),$=j.closeSockets?Promise.race([O,Promise.all([V,y(z)])]):O;if(H=X>0?await G($,X):z.pendingRequests===0,!H)console.error(`[gemi] Shutdown grace period elapsed with ${z.pendingRequests} request(s) still in flight; abandoning them.`),z.stop(!0).catch(()=>{})}x();let P=await j.shutdownProviders({timeoutMs:B.providerTimeoutMs}),K=H&&P.failed.length===0&&P.timedOut.length===0;return console.log(`[gemi] Shutdown ${K?"complete":"finished with errors"}.`),K?0:1}function y(j){return new Promise((z)=>{let B=()=>{if(j.pendingRequests===0){z();return}setTimeout(B,50).unref?.()};B()})}async function G(j,z){if(z<=0)return!1;let B,J=await Promise.race([j.then(()=>!0,()=>!0),new Promise((H)=>{B=setTimeout(()=>H(!1),z)})]);return clearTimeout(B),J}function _(j){return new Promise((z)=>setTimeout(z,Math.max(0,j)))}function q(j){if(!R())return j;try{return j.headers.set("Connection","close"),j}catch{let z=new Response(j.body,j);return z.headers.set("Connection","close"),z}}function N(j){return async(z,B)=>{if(Q().drained)return new Response("Service Unavailable",{status:503,headers:{Connection:"close"}});return q(await j(z,B))}}var Z=Symbol.for("gemi.server.signalsInstalled"),w=1000;function D(j,z={}){let B=globalThis;if(B[Z])return;B[Z]=!0;let J=z.repeatWindowMs??w,H,P=(K)=>{if(H!==void 0){if(Date.now()-H<J)return;console.error(`[gemi] ${K} received again; exiting without waiting for the drain.`),process.exit(128+M.signals[K])}H=Date.now(),console.log(`[gemi] ${K} received.`),j().then((O)=>process.exit(O),(O)=>{console.error("[gemi] Shutdown failed:",O),process.exit(1)})};process.on("SIGTERM",P),process.on("SIGINT",P)}
|
|
3
|
-
export{R as Kl,f as Ll,W as Ml,E as Nl,q as Ol,N as Pl,D as Ql};
|
|
4
|
-
|
|
5
|
-
//# debugId=05FAF485CABCC91864756E2164756E21
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../server/shutdown.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import { constants } from \"node:os\";\nimport type { ShutdownReport } from \"../foundation/Application\";\nimport type { Instrumentation } from \"./types\";\n\n// On `globalThis` under a registry symbol rather than in a module variable, so\n// the flag an app's health route reads is the one the server set even when two\n// copies of this module are loaded — the built CLI bundles its own gemi (see\n// `app/App.ts`), and `bun --hot` re-evaluates every module on a reload.\nconst STATE = Symbol.for(\"gemi.server.shutdown\");\n\ntype ShutdownState = { shuttingDown: boolean; drained: boolean };\n\nfunction state(): ShutdownState {\n const global = globalThis as { [STATE]?: ShutdownState };\n global[STATE] ??= { shuttingDown: false, drained: false };\n return global[STATE];\n}\n\n/**\n * True from the moment this server process has been told to stop — before it\n * stops accepting connections — until it exits.\n *\n * gemi's built-in health route (`./health`) answers `503` while this is true,\n * and so should an app's own health route, so the platform's probe pulls the\n * instance while the in-flight requests are still draining. Every response sent in that window also carries\n * `Connection: close`, so a client that honours it opens its next request on a\n * new connection — one the load balancer can route elsewhere — instead of\n * reusing this one.\n */\nexport function isShuttingDown(): boolean {\n return state().shuttingDown;\n}\n\nexport function markShuttingDown() {\n state().shuttingDown = true;\n}\n\n/**\n * The request drain is over and the providers' `shutdown()` may be running:\n * from here on a request must not reach the app. See `serveForShutdown`.\n */\nexport function markDrained() {\n state().drained = true;\n}\n\n/** Test seam: a fresh process starts false, and so should each test. */\nexport function resetShuttingDown() {\n state().shuttingDown = false;\n state().drained = false;\n}\n\nexport type ShutdownSettings = {\n /**\n * From the signal to the end of the request drain, in milliseconds — the\n * delay below included. Requests still in flight when it runs out are\n * abandoned. `GEMI_SHUTDOWN_TIMEOUT`, in seconds; default 20. `0` means\n * \"close the listener and do not wait\": a shutdown with nothing in flight is\n * still a clean one.\n */\n timeoutMs: number;\n /**\n * How long to keep accepting new requests after `isShuttingDown()` turns\n * true, in milliseconds, so a health probe can see the `503` and the load\n * balancer stop routing here before the listener closes.\n * `GEMI_SHUTDOWN_DELAY`, in seconds; default 0.\n */\n delayMs: number;\n /**\n * The shared deadline for every provider's `shutdown()`, in milliseconds,\n * after the drain. `GEMI_SHUTDOWN_PROVIDER_TIMEOUT`, in seconds; default 5.\n * `0` skips the hooks — deliberately, so it is not reported as a failure.\n */\n providerTimeoutMs: number;\n};\n\n/**\n * 20s to drain plus 5s for providers is 25s: under the 30s that Kubernetes,\n * Azure Container Apps and ECS give by default between `SIGTERM` and `SIGKILL`,\n * with 5s left for the `gemi start` relay, the process exit and clock skew\n * between the platform's timer and ours. A platform with a shorter window\n * (Cloud Run's 10s, Fly's 5s) needs these lowered, not the other way round —\n * a drain that outlives the grace period ends in the same `SIGKILL` as no drain.\n *\n * The delay defaults to 0 because it only helps where a probe is watching, and\n * otherwise every shutdown would pay it for nothing.\n */\nexport function shutdownSettings(\n env: Record<string, string | undefined> = process.env,\n): ShutdownSettings {\n const settings = {\n timeoutMs: seconds(env.GEMI_SHUTDOWN_TIMEOUT, 20),\n delayMs: seconds(env.GEMI_SHUTDOWN_DELAY, 0),\n providerTimeoutMs: seconds(env.GEMI_SHUTDOWN_PROVIDER_TIMEOUT, 5),\n };\n // Warned, not clamped: the delay is sized to a probe, the timeout to the\n // platform's grace period, and which one is wrong only the operator knows.\n // Left alone, every shutdown spends the whole timeout in the delay and then\n // abandons whatever is in flight without draining it.\n if (settings.delayMs > 0 && settings.delayMs >= settings.timeoutMs) {\n console.warn(\n `[gemi] GEMI_SHUTDOWN_DELAY (${settings.delayMs / 1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${settings.timeoutMs / 1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`,\n );\n }\n return settings;\n}\n\nfunction seconds(value: string | undefined, fallback: number): number {\n const parsed = value === undefined || value.trim() === \"\" ? NaN : Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1000;\n if (value !== undefined) {\n console.warn(`[gemi] Ignoring shutdown setting \"${value}\": expected a number of seconds.`);\n }\n return fallback * 1000;\n}\n\n/** The part of `Bun.Server` a drain needs. */\nexport type Stoppable = {\n stop(closeActiveConnections?: boolean): Promise<void>;\n readonly pendingRequests: number;\n};\n\n/**\n * The shutdown sequence, in its order:\n *\n * 1. `isShuttingDown()` turns true — first, so the health route answers `503`\n * and responses carry `Connection: close` while the listener is still open.\n * 2. After `delayMs`, the listener closes (`server.stop()` without force):\n * new connections are refused, while every request in flight — a streamed\n * response included, to its last chunk — runs to completion.\n * Broadcast sockets are told `bye` and closed (`closeSockets`): a graceful\n * stop waits for open WebSockets, which never close on their own.\n * 3. That completion is awaited until `timeoutMs` from the start.\n * 4. From here a request is refused with a `503` before it reaches the app\n * (`serveForShutdown`), and every provider's `shutdown()` runs, reverse\n * order, `providerTimeoutMs`.\n *\n * Resolves with the exit code: 0 when every step finished in time, 1 when the\n * drain was cut short or a provider failed or overran.\n *\n * Two things `stop()` does not do, both measured on Bun 1.3.14, and both why\n * the process exit that follows is what actually ends the server:\n *\n * - It does not close a kept-alive connection. One that is idle when the\n * listener closes stays open, and a request sent down it afterwards is\n * served. That is what the `Connection: close` on every response in the\n * window is for: a client (or a proxy in front) that honours it opens its\n * next request on a new connection, which the closed listener refuses. A\n * client that does not honour it is what step 4's `503` is for — Bun does\n * not close the socket after a `Connection: close` response either (#566).\n * - `stop(true)` issued after a graceful `stop()` does not cut the remaining\n * requests off; it waits for the same ones. It is still called when the\n * drain times out, for a Bun that does, but nothing here depends on it. Nor\n * does it close an idle kept-alive connection. Only a `stop(true)` issued\n * *first* does that, and it cuts off the requests in flight with it, which\n * is the drain given up — so the idle ones are refused, not closed.\n */\nexport async function drain(params: {\n server: Stoppable | undefined;\n /**\n * Says `bye` to the broadcast sockets and closes them, right after the\n * listener closes, and resolves once they are closed or cut. A graceful\n * `stop()` waits for open WebSockets, which otherwise never close on their\n * own.\n */\n closeSockets?: () => void | Promise<void>;\n shutdownProviders: (options: { timeoutMs: number }) => Promise<ShutdownReport>;\n settings: ShutdownSettings;\n}): Promise<number> {\n const { server, settings } = params;\n const deadline = Date.now() + settings.timeoutMs;\n\n markShuttingDown();\n console.log(\n `[gemi] Shutting down: draining in-flight requests (up to ${settings.timeoutMs / 1000}s).`,\n );\n\n let drained = true;\n if (server) {\n if (settings.delayMs > 0) {\n await sleep(Math.min(settings.delayMs, deadline - Date.now()));\n }\n const stopped = server.stop();\n let socketsClosed: Promise<unknown> = Promise.resolve();\n try {\n socketsClosed = Promise.resolve(params.closeSockets?.()).catch(() => {});\n } catch (error) {\n console.error(\"[gemi] Closing the broadcast sockets failed:\", error);\n }\n // No time left to wait — a `GEMI_SHUTDOWN_TIMEOUT` of 0, or a delay that\n // spent all of it — is \"do not wait for what is in flight\", and that is\n // only a failure when something *is* in flight. Reading it as one made\n // every clean shutdown log an abandonment and exit 1 for the operator who\n // zeroed the budget to fit a 5s grace period, with nothing to abandon.\n const remaining = deadline - Date.now();\n // With broadcast sockets, the stop's own promise has been seen to stay\n // pending for good after every request finished and every socket was\n // closed or terminated (Bun 1.4.2 on a loaded Linux CI runner, with its\n // `pendingWebSockets` stuck above 0). So the drain also ends on its real\n // condition: no request in flight, and the hub's sockets closed or cut.\n const done = params.closeSockets\n ? Promise.race([stopped, Promise.all([socketsClosed, noRequestInFlight(server)])])\n : stopped;\n drained =\n remaining > 0 ? await settlesWithin(done, remaining) : server.pendingRequests === 0;\n if (!drained) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${server.pendingRequests} request(s) still in flight; abandoning them.`,\n );\n void server.stop(true).catch(() => {});\n }\n }\n\n // Whether or not the drain finished: a request that arrives now, down a\n // kept-alive connection the listener's close left open, would run against\n // providers that are being shut down underneath it.\n markDrained();\n const report = await params.shutdownProviders({ timeoutMs: settings.providerTimeoutMs });\n const clean = drained && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n}\n\n/**\n * Resolves once `server` has no request in flight. A streamed response counts\n * until its last chunk (measured on Bun 1.4, macOS and Linux).\n */\nfunction noRequestInFlight(server: Stoppable): Promise<void> {\n return new Promise((resolve) => {\n const check = () => {\n if (server.pendingRequests === 0) {\n resolve();\n return;\n }\n const timer = setTimeout(check, 50);\n (timer as { unref?: () => void }).unref?.();\n };\n check();\n });\n}\n\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n // `drain` decides for itself what a budget that is already spent means, so\n // this is only a guard: a race against `setTimeout(0)` is a coin toss, and\n // \"did not settle within no time at all\" is the honest answer to it.\n if (ms <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n promise.then(\n () => true,\n () => true,\n ),\n new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n }),\n ]);\n clearTimeout(timer);\n return result;\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\n/**\n * `Connection: close` on a response sent while shutting down, so the client's\n * next request opens a connection — which the load balancer can send elsewhere\n * — instead of reusing this one.\n *\n * The spec makes some responses' headers immutable (a `Response.redirect`, a\n * proxied `fetch`), and setting one throws. Bun 1.3.14 lets both be set, so\n * the copy is for a Bun that follows the spec — a throw here would turn every\n * such response in the drain window into a 500.\n */\nexport function closeConnectionWhileShuttingDown(res: Response): Response {\n if (!isShuttingDown()) return res;\n try {\n res.headers.set(\"Connection\", \"close\");\n return res;\n } catch {\n const copy = new Response(res.body, res);\n copy.headers.set(\"Connection\", \"close\");\n return copy;\n }\n}\n\n/**\n * What every response goes through while this process serves: the app's\n * instrumentation, with the two changes a shutdown makes to it.\n *\n * - While the requests in flight drain, a response carries `Connection: close`\n * (`closeConnectionWhileShuttingDown`).\n * - Once they have drained, a request is answered `503` with\n * `Connection: close` and reaches neither the app nor its instrumentation.\n * The listener is closed by then, so only a kept-alive connection can still\n * deliver one, and `server.stop()` leaves those open. Serving it would run a\n * handler against providers whose `shutdown()` is closing the pool, the\n * queue or the cache it uses — until the process exits. The instrumentation\n * is skipped too because it is app code, and a tracer or error reporter is\n * exactly what a provider flushes and closes at this point.\n */\nexport function serveForShutdown(instrumentation: Instrumentation): Instrumentation {\n return async (req, next) => {\n if (state().drained) {\n return new Response(\"Service Unavailable\", {\n status: 503,\n headers: { Connection: \"close\" },\n });\n }\n return closeConnectionWhileShuttingDown(await instrumentation(req, next));\n };\n}\n\n// Installed once per process, not once per `Server`: a listener per instance\n// would each start a shutdown of its own, and read the other's signal as the\n// second one.\nconst SIGNALS_INSTALLED = Symbol.for(\"gemi.server.signalsInstalled\");\n\n/**\n * A repeat of the first signal inside this window is the same shutdown\n * delivered twice, not an operator asking to skip the drain. One shutdown\n * routinely arrives more than once, milliseconds apart: Ctrl+C on\n * `bun run start` reaches the server directly (the whole foreground group is\n * signalled), and again through `gemi start`'s relay — twice over, since\n * `bun run` forwards it to `gemi start` too. systemd's default\n * `KillMode=control-group` and `tini -g` do the same to every process in the\n * group. A person pressing Ctrl+C again is well outside a second.\n */\nconst REPEAT_WINDOW_MS = 1000;\n\n/**\n * `SIGTERM` or `SIGINT` runs `stop` and exits with the code it resolves with.\n * Another signal of either kind, more than `repeatWindowMs` after the first,\n * exits at once with `128 + n` — an operator pressing Ctrl+C again does not\n * want to wait out the grace period. Without a listener the first signal would\n * do that too: the default action for both is to terminate the process on the\n * spot.\n */\nexport function installShutdownSignals(\n stop: () => Promise<number>,\n options: { repeatWindowMs?: number } = {},\n) {\n const global = globalThis as { [SIGNALS_INSTALLED]?: boolean };\n if (global[SIGNALS_INSTALLED]) return;\n global[SIGNALS_INSTALLED] = true;\n\n const repeatWindowMs = options.repeatWindowMs ?? REPEAT_WINDOW_MS;\n let receivedAt: number | undefined;\n const onSignal = (signal: \"SIGTERM\" | \"SIGINT\") => {\n if (receivedAt !== undefined) {\n if (Date.now() - receivedAt < repeatWindowMs) return;\n console.error(`[gemi] ${signal} received again; exiting without waiting for the drain.`);\n process.exit(128 + constants.signals[signal]);\n }\n receivedAt = Date.now();\n console.log(`[gemi] ${signal} received.`);\n stop().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"[gemi] Shutdown failed:\", error);\n process.exit(1);\n },\n );\n };\n process.on(\"SIGTERM\", onSignal);\n process.on(\"SIGINT\", onSignal);\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";AAAA,oBAAS,WAQT,IAAM,EAAQ,OAAO,IAAI,sBAAsB,EAI/C,SAAS,CAAK,EAAkB,CAC9B,IAAM,EAAS,WAEf,OADA,EAAO,KAAW,CAAE,aAAc,GAAO,QAAS,EAAM,EACjD,EAAO,GAcT,SAAS,CAAc,EAAY,CACxC,OAAO,EAAM,EAAE,aAGV,SAAS,CAAgB,EAAG,C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EAAK,QAAQ,IAAI,aAAc,OAAO,EAC/B,GAmBJ,SAAS,CAAgB,CAAC,EAAmD,CAClF,MAAO,OAAO,EAAK,IAAS,CAC1B,GAAI,EAAM,EAAE,QACV,OAAO,IAAI,SAAS,sBAAuB,CACzC,OAAQ,IACR,QAAS,CAAE,WAAY,OAAQ,CACjC,CAAC,EAEH,OAAO,EAAiC,MAAM,EAAgB,EAAK,CAAI,CAAC,GAO5E,IAAM,EAAoB,OAAO,IAAI,8BAA8B,EAY7D,EAAmB,KAUlB,SAAS,CAAsB,CACpC,EACA,EAAuC,CAAC,EACxC,CACA,IAAM,EAAS,WACf,GAAI,EAAO,GAAoB,OAC/B,EAAO,GAAqB,GAE5B,IAAM,EAAiB,EAAQ,gBAAkB,EAC7C,EACE,EAAW,CAAC,IAAiC,CACjD,GAAI,IAAe,OAAW,CAC5B,GAAI,KAAK,IAAI,EAAI,EAAa,EAAgB,OAC9C,QAAQ,MAAM,UAAU,0DAA+D,EACvF,QAAQ,KAAK,IAAM,EAAU,QAAQ,EAAO,EAE9C,EAAa,KAAK,IAAI,EACtB,QAAQ,IAAI,UAAU,aAAkB,EACxC,EAAK,EAAE,KACL,CAAC,IAAS,QAAQ,KAAK,CAAI,EAC3B,CAAC,IAAU,CACT,QAAQ,MAAM,0BAA2B,CAAK,EAC9C,QAAQ,KAAK,CAAC,EAElB,GAEF,QAAQ,GAAG,UAAW,CAAQ,EAC9B,QAAQ,GAAG,SAAU,CAAQ",
|
|
8
|
-
"debugId": "05FAF485CABCC91864756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
package/dist/chunk-jkf5kjaz.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Dl as B}from"./chunk-ha4er085.js";function $(z){return z.split(".")}class Y{static token="config";items;constructor(z={}){this.items=z}has(z){let F=this.items;for(let E of $(z)){if(F===null||typeof F!=="object"||!(E in F))return!1;F=F[E]}return!0}get(z,F){let E=this.items;for(let G of $(z)){if(E===null||typeof E!=="object"||!(G in E))return F;E=E[G]}return E===void 0?F:E}getMany(z){let F=Array.isArray(z)?z.map((G)=>[G,void 0]):Object.entries(z),E={};for(let[G,H]of F)E[G]=this.get(G,H);return E}set(z,F){let E=typeof z==="string"?[[z,F]]:Object.entries(z);for(let[G,H]of E){let U=$(G),Z=U.pop(),J=this.items;for(let Q of U){let W=J[Q];if(W===null||typeof W!=="object")J[Q]={};J=J[Q]}J[Z]=H}}prepend(z,F){let E=this.get(z,[]);E.unshift(F),this.set(z,E)}push(z,F){let E=this.get(z,[]);E.push(F),this.set(z,E)}merge(z){for(let[F,E]of Object.entries(z)){let G=this.items[F];if(G!==null&&typeof G==="object"&&!Array.isArray(G)&&E!==null&&typeof E==="object"&&!Array.isArray(E))this.items[F]={...G,...E};else this.items[F]=E}}all(){return this.items}}var j=Symbol.for("gemi.foundation.Application");class X extends B{[j]=!0;static isApplication(z){return typeof z==="object"&&z!==null&&j in z}config;providers=[];booted=!1;constructor(z=new Y){super();this.config=z,this.instance(Y,z)}static currentInstance;static getInstance(){return X.currentInstance}static setInstance(z){return X.currentInstance=z,z}register(z){let F=this.providers.find((G)=>G instanceof z);if(F)return F;let E=new z(this);return E.register(),this.providers.push(E),E}registerMany(z){for(let F of z)this.register(F)}getProviders(){return[...this.providers]}isBooted(){return this.booted}async boot(){if(this.booted)return;for(let z of this.providers)await z.boot();this.booted=!0}shutdown(z={}){return this.shutdownPromise??=this.shutdownProviders(z.timeoutMs??5000),this.shutdownPromise}shutdownPromise;async shutdownProviders(z){let F={failed:[],timedOut:[]};if(z<=0){if(this.providers.length>0)console.log(`[gemi] Skipping ${this.providers.length} provider shutdown hook(s): no time is budgeted for them.`);return F}let E=Date.now()+z;for(let G of[...this.providers].reverse()){let H=G.constructor.name,U=E-Date.now();if(U<=0){console.error(`[gemi] ${H}.shutdown() skipped: the provider shutdown deadline had passed.`),F.timedOut.push(H);continue}let Z,J=await Promise.race([Promise.resolve().then(()=>G.shutdown({timeoutMs:U})).then((Q)=>Q?.abandoned?"abandoned":"done",(Q)=>{return console.error(`[gemi] ${H}.shutdown() failed:`,Q),"failed"}),new Promise((Q)=>{Z=setTimeout(()=>Q("timeout"),U)})]);if(clearTimeout(Z),J==="failed")F.failed.push(H);if(J==="abandoned")F.timedOut.push(H);if(J==="timeout")console.error(`[gemi] ${H}.shutdown() did not finish within the provider shutdown deadline; moving on.`),F.timedOut.push(H)}return F}flush(){super.flush(),this.instance(Y,this.config),this.providers=[],this.booted=!1,this.shutdownPromise=void 0}}import{AsyncLocalStorage as K}from"async_hooks";var D=new K;function I(z){let F=D.getStore(),E=X.isApplication(F)?F:X.getInstance();if(!E)throw Error("No Application instance is available. Boot a Kernel before resolving services.");return z?E.make(z):E}
|
|
3
|
-
export{D as yl,Y as zl,X as Al,I as Bl};
|
|
4
|
-
|
|
5
|
-
//# debugId=4F8126780155F4F164756E2164756E21
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../support/Repository.ts", "../foundation/Application.ts", "../kernel/context.ts", "../foundation/app.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"// Runtime configuration store, modeled on `Illuminate\\Config\\Repository`.\n// Keys are dot paths (\"mail.driver\", \"route.view.rootRouter\") resolved against\n// a plain nested object. This is the RUNTIME config; `gemi/config` is the\n// BUILD config (gemi.config.ts) and is unrelated.\n\nexport type ConfigItems = Record<string, any>;\n\nfunction segments(key: string): string[] {\n return key.split(\".\");\n}\n\nexport class Repository {\n // Container token. The Kernel binds its Repository under `config`, so any\n // provider can `app.make(Repository)` — though `this.app.config` is shorter.\n static token = \"config\";\n\n private items: ConfigItems;\n\n constructor(items: ConfigItems = {}) {\n this.items = items;\n }\n\n has(key: string): boolean {\n let target: any = this.items;\n for (const segment of segments(key)) {\n if (target === null || typeof target !== \"object\" || !(segment in target)) {\n return false;\n }\n target = target[segment];\n }\n return true;\n }\n\n get<T = any>(key: string, defaultValue?: T): T {\n let target: any = this.items;\n for (const segment of segments(key)) {\n if (target === null || typeof target !== \"object\" || !(segment in target)) {\n return defaultValue as T;\n }\n target = target[segment];\n }\n return target === undefined ? (defaultValue as T) : (target as T);\n }\n\n // Reads many keys at once. Accepts either a list of keys or a\n // `{ key: defaultValue }` map, mirroring `Repository::getMany`.\n getMany(keys: string[] | Record<string, any>): Record<string, any> {\n const entries: Array<[string, any]> = Array.isArray(keys)\n ? keys.map((key): [string, any] => [key, undefined])\n : Object.entries(keys);\n\n const result: Record<string, any> = {};\n for (const [key, defaultValue] of entries) {\n result[key] = this.get(key, defaultValue);\n }\n return result;\n }\n\n set(key: string | Record<string, any>, value?: any): void {\n const entries: Array<[string, any]> =\n typeof key === \"string\" ? [[key, value]] : Object.entries(key);\n\n for (const [path, item] of entries) {\n const parts = segments(path);\n const last = parts.pop() as string;\n\n let target: any = this.items;\n for (const segment of parts) {\n const next = target[segment];\n if (next === null || typeof next !== \"object\") {\n target[segment] = {};\n }\n target = target[segment];\n }\n\n target[last] = item;\n }\n }\n\n // Adds `value` to the front of the array stored at `key`.\n prepend(key: string, value: any): void {\n const array = this.get<any[]>(key, []);\n array.unshift(value);\n this.set(key, array);\n }\n\n // Adds `value` to the end of the array stored at `key`.\n push(key: string, value: any): void {\n const array = this.get<any[]>(key, []);\n array.push(value);\n this.set(key, array);\n }\n\n // Shallow-merges a `{ topLevelKey: config }` map into the store. Existing\n // top-level keys are merged one level deep so partial overrides compose.\n merge(items: ConfigItems): void {\n for (const [key, value] of Object.entries(items)) {\n const current = this.items[key];\n if (\n current !== null &&\n typeof current === \"object\" &&\n !Array.isArray(current) &&\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n this.items[key] = { ...current, ...value };\n } else {\n this.items[key] = value;\n }\n }\n }\n\n all(): ConfigItems {\n return this.items;\n }\n}\n",
|
|
6
|
-
"import { Container } from \"../container/Container\";\nimport { Repository } from \"../support/Repository\";\nimport type { ServiceProvider } from \"../support/ServiceProvider\";\n\nexport type ServiceProviderConstructor = new (\n app: Application,\n) => ServiceProvider;\n\n/**\n * What `Application.shutdown()` could not finish, by provider class name. Both\n * empty means every provider's `shutdown()` resolved in time and abandoned\n * nothing. `timedOut` holds the providers that overran the deadline and the\n * ones that resolved `{ abandoned: true }`.\n */\nexport type ShutdownReport = { failed: string[]; timedOut: string[] };\n\n/**\n * Cross-copy brand. `dist/bin/gemi.js` bundles its own gemi while the app\n * resolves `gemi/*` to source, so `instanceof Application` is false for an\n * Application built by the other copy. `Symbol.for` is registry-global and\n * survives that boundary — the same reason services key off a `static token`\n * string rather than the constructor object.\n */\nconst APPLICATION_BRAND = Symbol.for(\"gemi.foundation.Application\");\n\nexport class Application extends Container {\n readonly [APPLICATION_BRAND] = true;\n\n static isApplication(value: unknown): value is Application {\n return (\n typeof value === \"object\" && value !== null && APPLICATION_BRAND in value\n );\n }\n\n /**\n * Runtime configuration (`app/config/*.ts`). Also bound in the container, so\n * `app.make(Repository)` and `app.config` are the same object.\n */\n readonly config: Repository;\n\n private providers: ServiceProvider[] = [];\n private booted = false;\n\n constructor(config: Repository = new Repository()) {\n super();\n this.config = config;\n this.instance(Repository, config);\n }\n\n private static currentInstance: Application | undefined;\n\n static getInstance(): Application | undefined {\n return Application.currentInstance;\n }\n\n static setInstance(app: Application | undefined) {\n Application.currentInstance = app;\n return app;\n }\n\n /**\n * Instantiates the provider and runs its `register()` immediately, exactly as\n * Laravel does. Registration is therefore synchronous — only `boot()` is\n * async, which is what lets `new App({ kernel })` stay a sync constructor.\n */\n register(Provider: ServiceProviderConstructor): ServiceProvider {\n const existing = this.providers.find((p) => p instanceof Provider);\n if (existing) {\n return existing;\n }\n\n const provider = new Provider(this);\n provider.register();\n this.providers.push(provider);\n return provider;\n }\n\n registerMany(providers: ServiceProviderConstructor[]) {\n for (const Provider of providers) {\n this.register(Provider);\n }\n }\n\n getProviders(): ServiceProvider[] {\n return [...this.providers];\n }\n\n isBooted(): boolean {\n return this.booted;\n }\n\n /**\n * Phase two. Every provider has already registered by the time any of these\n * run, so a provider's `boot()` may resolve services owned by any other.\n */\n async boot(): Promise<void> {\n if (this.booted) {\n return;\n }\n for (const provider of this.providers) {\n await provider.boot();\n }\n this.booted = true;\n }\n\n /**\n * Runs every provider's `shutdown()`, in reverse registration order, and\n * resolves with what did not finish cleanly. Never rejects: this runs on the\n * way out of a process, and a throw here would skip the providers after the\n * one that threw — the database pool closing is exactly the kind of thing\n * that must not depend on the mail provider behaving.\n *\n * Reverse order because registration order is dependency order: a provider\n * registered later may use an earlier one in its own `shutdown()` (the\n * queue finishing its jobs against a database that is still open).\n *\n * The providers share one deadline rather than each getting `timeoutMs`,\n * because the caller's budget is a platform's grace period, which bounds the\n * whole exit — seventeen providers each allowed five seconds would add up to\n * a `SIGKILL`. A provider that overruns is abandoned (its promise keeps\n * running; the process is about to exit) and reported in `timedOut`; one\n * reached after the deadline has passed is not called at all and reported\n * the same way. So is one that resolves `{ abandoned: true }`: it bounded\n * its own wait and gave up on work (a queued job, a cron tick), which is the\n * same unclean stop. A `timeoutMs` of 0 is different in kind: nothing is\n * called, nothing is reported, and the shutdown stays clean — the caller has said\n * there is no time for this phase, which is a decision, not a fault.\n *\n * Idempotent: a second call returns the first call's result.\n */\n shutdown(options: { timeoutMs?: number } = {}): Promise<ShutdownReport> {\n this.shutdownPromise ??= this.shutdownProviders(options.timeoutMs ?? 5_000);\n return this.shutdownPromise;\n }\n\n private shutdownPromise: Promise<ShutdownReport> | undefined;\n\n private async shutdownProviders(timeoutMs: number): Promise<ShutdownReport> {\n const report: ShutdownReport = { failed: [], timedOut: [] };\n\n // A budget of zero is \"skip this phase\", not \"every provider failed\". An\n // operator fitting the shutdown into a five-second grace period says so by\n // setting `GEMI_SHUTDOWN_PROVIDER_TIMEOUT=0`, and reading it as a deadline\n // that had already passed reported their own configuration back to them as\n // a fault: a `console.error` per provider, every provider in `timedOut`,\n // and a non-zero exit on every otherwise clean shutdown. One line saying\n // what was skipped is the whole of it.\n if (timeoutMs <= 0) {\n if (this.providers.length > 0) {\n console.log(\n `[gemi] Skipping ${this.providers.length} provider shutdown hook(s): no time is budgeted for them.`,\n );\n }\n return report;\n }\n\n const deadline = Date.now() + timeoutMs;\n\n for (const provider of [...this.providers].reverse()) {\n const name = provider.constructor.name;\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n console.error(\n `[gemi] ${name}.shutdown() skipped: the provider shutdown deadline had passed.`,\n );\n report.timedOut.push(name);\n continue;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const outcome = await Promise.race([\n // `.then` rather than a direct call, so a synchronous throw lands in\n // the same `catch` as a rejection.\n Promise.resolve()\n // With what is left of the shared deadline, so a provider that waits\n // on something can bound its own wait and report what it abandoned\n // rather than being cut off mid-wait by the race below.\n .then(() => provider.shutdown({ timeoutMs: remaining }))\n .then(\n (result) =>\n (result as { abandoned?: boolean } | undefined)?.abandoned\n ? (\"abandoned\" as const)\n : (\"done\" as const),\n (error: unknown) => {\n console.error(`[gemi] ${name}.shutdown() failed:`, error);\n return \"failed\" as const;\n },\n ),\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), remaining);\n }),\n ]);\n clearTimeout(timer);\n\n if (outcome === \"failed\") report.failed.push(name);\n // The provider gave up on work at the deadline and has already named it\n // in its own log line; it counts as timed out so the exit code says so.\n if (outcome === \"abandoned\") report.timedOut.push(name);\n if (outcome === \"timeout\") {\n console.error(\n `[gemi] ${name}.shutdown() did not finish within the provider shutdown deadline; moving on.`,\n );\n report.timedOut.push(name);\n }\n }\n\n return report;\n }\n\n flush() {\n super.flush();\n this.instance(Repository, this.config);\n this.providers = [];\n this.booted = false;\n this.shutdownPromise = undefined;\n }\n}\n",
|
|
7
|
-
"import { AsyncLocalStorage } from \"async_hooks\";\n\n/**\n * The kernel's AsyncLocalStorage. It holds the Application, and nothing else —\n * `Kernel.run()` enters it once per request or cron tick,\n * and `foundation/app.ts` reads it to resolve services.\n *\n * \"The framework's only AsyncLocalStorage\" is a claim that used to sit here. It\n * was already not true — the *kernel's* is the only one, but `http/` and now\n * the ORM each keep their own. Three in the shipped framework (a fourth\n * sits in `rfc/workflow.ts`, an unreferenced design sketch that is outside\n * `package.json`'s exports and that nothing imports):\n *\n * kernel kernel/context.ts the Application\n * request http/requestContext.ts req, user, cookies, locale\n * orm orm/context.ts an open transaction\n *\n * The pattern is one store per scope with one owner, entered by that owner and\n * read through its own accessor — `app()`, `RequestContext.getStore()`,\n * `currentTransaction()`. What matters is that this one holds the Application\n * and nothing else, because `foundation/app.ts` reads it unconditionally.\n *\n * The ORM's, added in iteration 5, holds an open transaction handle and its\n * nesting depth. It is deliberately separate rather than merged into this one:\n *\n * - A transaction scope nests *inside* an Application scope without replacing\n * it. Re-entering this store with a `{ app, tx }` wrapper would mean every\n * reader of it — `app()` above all — has to handle two shapes forever, and a\n * miss there is not a transaction bug, it is a service resolving off the\n * wrong Application.\n * - The alternative of hanging the handle off the Application is worse than a\n * style question: one Application serves every concurrent request, so two\n * overlapping transactions would overwrite each other's handle and statements\n * would land in the wrong one. That is silent data corruption.\n *\n * The cost is honest: one more store on the hot path of every query. The ORM's\n * is shallow — one small object, entered only inside `Model.transaction` or\n * `DB.transaction`, never per request — so a query outside a transaction pays\n * one `getStore()` returning undefined.\n *\n * If another is ever proposed, this is the note to read first: the bar is that\n * the state is genuinely per-async-scope *and* cannot live in an existing store\n * without making that store's readers ambiguous.\n */\nexport const kernelContext = new AsyncLocalStorage();\n",
|
|
8
|
-
"import type { ServiceToken } from \"../container/Container\";\nimport { kernelContext } from \"../kernel/context\";\nimport { Application } from \"./Application\";\n\n/**\n * Resolves the Application for the current async context. Reads the kernel\n * AsyncLocalStorage — there is exactly one ALS in the framework, and\n * `Kernel.run()` stores the Application in it, so this is the primary path for\n * anything running inside a request or a cron tick.\n *\n * The static instance (Laravel's `Container::setInstance`, set by\n * `Kernel.boot()`) is the fallback for code that runs outside any `run()`\n * scope — build-time tooling, module top level, a stray `setTimeout`.\n */\nexport function app(): Application;\nexport function app<T>(token: ServiceToken<T>): T;\nexport function app<T>(token?: ServiceToken<T>): Application | T {\n const store = kernelContext.getStore();\n const instance = Application.isApplication(store)\n ? store\n : Application.getInstance();\n\n if (!instance) {\n throw new Error(\n \"No Application instance is available. Boot a Kernel before resolving services.\",\n );\n }\n\n return token ? instance.make(token) : instance;\n}\n"
|
|
9
|
-
],
|
|
10
|
-
"mappings": ";yCAOA,SAAS,CAAQ,CAAC,EAAuB,CACvC,OAAO,EAAI,MAAM,GAAG,EAGf,MAAM,CAAW,OAGf,OAAQ,SAEP,MAER,WAAW,CAAC,EAAqB,CAAC,EAAG,CACnC,KAAK,MAAQ,EAGf,GAAG,CAAC,EAAsB,CACxB,IAAI,EAAc,KAAK,MACvB,QAAW,KAAW,EAAS,CAAG,EAAG,CACnC,GAAI,IAAW,MAAQ,OAAO,IAAW,UAAY,EAAE,KAAW,GAChE,MAAO,GAET,EAAS,EAAO,GAElB,MAAO,GAGT,GAAY,CAAC,EAAa,EAAqB,CAC7C,IAAI,EAAc,KAAK,MACvB,QAAW,KAAW,EAAS,CAAG,EAAG,CACnC,GAAI,IAAW,MAAQ,OAAO,IAAW,UAAY,EAAE,KAAW,GAChE,OAAO,EAET,EAAS,EAAO,GAElB,OAAO,IAAW,OAAa,EAAsB,EAKvD,OAAO,CAAC,EAA2D,CACjE,IAAM,EAAgC,MAAM,QAAQ,CAAI,EACpD,EAAK,IAAI,CAAC,IAAuB,CAAC,EAAK,MAAS,CAAC,EACjD,OAAO,QAAQ,CAAI,EAEjB,EAA8B,CAAC,EACrC,QAAY,EAAK,KAAiB,EAChC,EAAO,GAAO,KAAK,IAAI,EAAK,CAAY,EAE1C,OAAO,EAGT,GAAG,CAAC,EAAmC,EAAmB,CACxD,IAAM,EACJ,OAAO,IAAQ,SAAW,CAAC,CAAC,EAAK,CAAK,CAAC,EAAI,OAAO,QAAQ,CAAG,EAE/D,QAAY,EAAM,KAAS,EAAS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5C,YACA,OACP,CAAC,IAAmB,CAElB,OADA,QAAQ,MAAM,UAAU,uBAA2B,CAAK,EACjD,SAEX,EACF,IAAI,QAAmB,CAAC,IAAY,CAClC,EAAQ,WAAW,IAAM,EAAQ,SAAS,EAAG,CAAS,EACvD,CACH,CAAC,EAGD,GAFA,aAAa,CAAK,EAEd,IAAY,SAAU,EAAO,OAAO,KAAK,CAAI,EAGjD,GAAI,IAAY,YAAa,EAAO,SAAS,KAAK,CAAI,EACtD,GAAI,IAAY,UACd,QAAQ,MACN,UAAU,+EACZ,EACA,EAAO,SAAS,KAAK,CAAI,EAI7B,OAAO,EAGT,KAAK,EAAG,CACN,MAAM,MAAM,EACZ,KAAK,SAAS,EAAY,KAAK,MAAM,EACrC,KAAK,UAAY,CAAC,EAClB,KAAK,OAAS,GACd,KAAK,gBAAkB,OAE3B,CCxNA,4BAAS,oBA4CF,IAAM,EAAgB,IAAI,EC5B1B,SAAS,CAAM,CAAC,EAA0C,CAC/D,IAAM,EAAQ,EAAc,SAAS,EAC/B,EAAW,EAAY,cAAc,CAAK,EAC5C,EACA,EAAY,YAAY,EAE5B,GAAI,CAAC,EACH,MAAU,MACR,gFACF,EAGF,OAAO,EAAQ,EAAS,KAAK,CAAK,EAAI",
|
|
11
|
-
"debugId": "4F8126780155F4F164756E2164756E21",
|
|
12
|
-
"names": []
|
|
13
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|