gemi 0.166.1 → 0.168.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 +3 -5
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +16 -2
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/Prompt.d.ts +15 -1
- package/dist/ai/Prompt.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 +32 -32
- package/dist/ai/index.js.map +4 -4
- package/dist/app/index.js +1 -1
- package/dist/bin/gemi.js +405 -376
- package/dist/bin/gemi.js.map +5 -4
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-eyv6hss6.js → chunk-0q65jzhv.js} +2 -2
- package/dist/{chunk-eyv6hss6.js.map → chunk-0q65jzhv.js.map} +1 -1
- package/dist/{chunk-p3qbym3v.js → chunk-0wet87jm.js} +2 -2
- package/dist/{chunk-p3qbym3v.js.map → chunk-0wet87jm.js.map} +1 -1
- package/dist/{chunk-4fzevafk.js → chunk-0wk992a5.js} +2 -2
- package/dist/{chunk-4fzevafk.js.map → chunk-0wk992a5.js.map} +1 -1
- package/dist/{chunk-q4vtjdea.js → chunk-17272ccy.js} +3 -3
- package/dist/{chunk-q4vtjdea.js.map → chunk-17272ccy.js.map} +1 -1
- package/dist/{chunk-w4at2d5d.js → chunk-1h6g1hkg.js} +2 -2
- package/dist/{chunk-w4at2d5d.js.map → chunk-1h6g1hkg.js.map} +1 -1
- package/dist/{chunk-hdt8cwsv.js → chunk-21hppqtb.js} +2 -2
- package/dist/{chunk-hdt8cwsv.js.map → chunk-21hppqtb.js.map} +1 -1
- package/dist/{chunk-qec3g4w3.js → chunk-2v7wq01w.js} +2 -2
- package/dist/{chunk-qec3g4w3.js.map → chunk-2v7wq01w.js.map} +1 -1
- package/dist/{chunk-qeayzybn.js → chunk-2xtkh8bh.js} +19 -19
- package/dist/{chunk-qeayzybn.js.map → chunk-2xtkh8bh.js.map} +3 -3
- package/dist/{chunk-0hfvwzd1.js → chunk-31np60bx.js} +2 -2
- package/dist/{chunk-0hfvwzd1.js.map → chunk-31np60bx.js.map} +1 -1
- package/dist/{chunk-mbkje42z.js → chunk-3682hkq0.js} +2 -2
- package/dist/{chunk-mbkje42z.js.map → chunk-3682hkq0.js.map} +1 -1
- package/dist/{chunk-fnj2hc5v.js → chunk-3rp908gn.js} +1 -1
- package/dist/{chunk-3xj1e3ns.js → chunk-44y62yav.js} +3 -3
- package/dist/{chunk-3xj1e3ns.js.map → chunk-44y62yav.js.map} +1 -1
- package/dist/{chunk-c3cdj9y7.js → chunk-4mtqbcc5.js} +2 -2
- package/dist/{chunk-c3cdj9y7.js.map → chunk-4mtqbcc5.js.map} +1 -1
- package/dist/{chunk-80703vks.js → chunk-4qpyz627.js} +2 -2
- package/dist/{chunk-80703vks.js.map → chunk-4qpyz627.js.map} +1 -1
- package/dist/{chunk-4rnpvajg.js → chunk-4tt14jnx.js} +2 -2
- package/dist/{chunk-4rnpvajg.js.map → chunk-4tt14jnx.js.map} +1 -1
- package/dist/{chunk-efjk5aq7.js → chunk-5n21z4n8.js} +2 -2
- package/dist/{chunk-efjk5aq7.js.map → chunk-5n21z4n8.js.map} +1 -1
- package/dist/{chunk-pk4drzc9.js → chunk-5nz46dyw.js} +2 -2
- package/dist/{chunk-pk4drzc9.js.map → chunk-5nz46dyw.js.map} +1 -1
- package/dist/{chunk-6tbs7yc1.js → chunk-6t1t7h05.js} +2 -2
- package/dist/{chunk-6tbs7yc1.js.map → chunk-6t1t7h05.js.map} +1 -1
- package/dist/{chunk-tms2g9at.js → chunk-777v6242.js} +1 -1
- package/dist/{chunk-kcgnjzqr.js → chunk-8b9ks729.js} +3 -3
- package/dist/{chunk-kcgnjzqr.js.map → chunk-8b9ks729.js.map} +1 -1
- package/dist/{chunk-8f4jkpv7.js → chunk-8hfyscnn.js} +1 -1
- package/dist/{chunk-4587ab6m.js → chunk-978pc27j.js} +2 -2
- package/dist/{chunk-4587ab6m.js.map → chunk-978pc27j.js.map} +1 -1
- package/dist/{chunk-y1ks8ahw.js → chunk-9aj6eavs.js} +2 -2
- package/dist/{chunk-y1ks8ahw.js.map → chunk-9aj6eavs.js.map} +1 -1
- package/dist/{chunk-xw5d66ec.js → chunk-9akefv1y.js} +2 -2
- package/dist/{chunk-xw5d66ec.js.map → chunk-9akefv1y.js.map} +1 -1
- package/dist/{chunk-y6x52vkb.js → chunk-9ft0ayhf.js} +2 -2
- package/dist/{chunk-y6x52vkb.js.map → chunk-9ft0ayhf.js.map} +1 -1
- package/dist/{chunk-m5hd632w.js → chunk-9wcv7e1a.js} +2 -2
- package/dist/{chunk-h5whhrds.js.map → chunk-9wcv7e1a.js.map} +1 -1
- package/dist/{chunk-8rnvw8xr.js → chunk-a053eza0.js} +2 -2
- package/dist/{chunk-8rnvw8xr.js.map → chunk-a053eza0.js.map} +1 -1
- package/dist/{chunk-c0dvdfm0.js → chunk-a9frf7ym.js} +2 -2
- package/dist/{chunk-c0dvdfm0.js.map → chunk-a9frf7ym.js.map} +1 -1
- package/dist/{chunk-2jk0f4sj.js → chunk-aj1jrwwh.js} +2 -2
- package/dist/{chunk-2jk0f4sj.js.map → chunk-aj1jrwwh.js.map} +1 -1
- package/dist/{chunk-h11r8h31.js → chunk-bb3fdgwt.js} +11 -11
- package/dist/{chunk-h11r8h31.js.map → chunk-bb3fdgwt.js.map} +3 -3
- package/dist/{chunk-36yp8364.js → chunk-c46vhvk4.js} +2 -2
- package/dist/{chunk-36yp8364.js.map → chunk-c46vhvk4.js.map} +1 -1
- package/dist/{chunk-5x9b1ema.js → chunk-df2zeevj.js} +2 -2
- package/dist/{chunk-5x9b1ema.js.map → chunk-df2zeevj.js.map} +1 -1
- package/dist/{chunk-ndyafsv6.js → chunk-drwjwtmj.js} +2 -2
- package/dist/{chunk-ndyafsv6.js.map → chunk-drwjwtmj.js.map} +1 -1
- package/dist/{chunk-wypncj52.js → chunk-ecdjbd2w.js} +3 -3
- package/dist/{chunk-wypncj52.js.map → chunk-ecdjbd2w.js.map} +1 -1
- package/dist/{chunk-6cw6tn57.js → chunk-embwksec.js} +2 -2
- package/dist/{chunk-6cw6tn57.js.map → chunk-embwksec.js.map} +1 -1
- package/dist/{chunk-fdfy25mv.js → chunk-esjt9q54.js} +2 -2
- package/dist/{chunk-fdfy25mv.js.map → chunk-esjt9q54.js.map} +1 -1
- package/dist/chunk-f4nanvkm.js +5 -0
- package/dist/{chunk-8v6y52et.js.map → chunk-f4nanvkm.js.map} +1 -1
- package/dist/{chunk-b8qfypzq.js → chunk-fb77hwk0.js} +3 -3
- package/dist/{chunk-b8qfypzq.js.map → chunk-fb77hwk0.js.map} +1 -1
- package/dist/{chunk-fva651jp.js → chunk-fcbgshf5.js} +2 -2
- package/dist/{chunk-fva651jp.js.map → chunk-fcbgshf5.js.map} +1 -1
- package/dist/{chunk-f6mwnw81.js → chunk-g1jfc50d.js} +3 -3
- package/dist/{chunk-f6mwnw81.js.map → chunk-g1jfc50d.js.map} +1 -1
- package/dist/{chunk-0psf0chk.js → chunk-g548q257.js} +2 -2
- package/dist/{chunk-0psf0chk.js.map → chunk-g548q257.js.map} +1 -1
- package/dist/{chunk-wjff0d08.js → chunk-gjwf07hy.js} +3 -3
- package/dist/{chunk-wjff0d08.js.map → chunk-gjwf07hy.js.map} +1 -1
- package/dist/{chunk-2ewe42dq.js → chunk-gwphn604.js} +3 -3
- package/dist/{chunk-2ewe42dq.js.map → chunk-gwphn604.js.map} +1 -1
- package/dist/{chunk-xed7yf6h.js → chunk-hgpvfhtp.js} +1 -1
- package/dist/{chunk-h5whhrds.js → chunk-hwpp9b7f.js} +2 -2
- package/dist/{chunk-m5hd632w.js.map → chunk-hwpp9b7f.js.map} +1 -1
- package/dist/{chunk-vqf4s99d.js → chunk-jd079awh.js} +2 -2
- package/dist/{chunk-vqf4s99d.js.map → chunk-jd079awh.js.map} +1 -1
- package/dist/{chunk-1ap3vcrr.js → chunk-jxx9mctk.js} +2 -2
- package/dist/{chunk-1ap3vcrr.js.map → chunk-jxx9mctk.js.map} +1 -1
- package/dist/{chunk-mj429x94.js → chunk-k87tqe29.js} +2 -2
- package/dist/{chunk-mj429x94.js.map → chunk-k87tqe29.js.map} +1 -1
- package/dist/{chunk-1k4rvfza.js → chunk-kbw6y0ag.js} +2 -2
- package/dist/{chunk-1k4rvfza.js.map → chunk-kbw6y0ag.js.map} +1 -1
- package/dist/{chunk-pr2enaz5.js → chunk-krdq5s4y.js} +2 -2
- package/dist/{chunk-pr2enaz5.js.map → chunk-krdq5s4y.js.map} +1 -1
- package/dist/{chunk-7ysw97gp.js → chunk-m6sj1q1q.js} +2 -2
- package/dist/{chunk-7ysw97gp.js.map → chunk-m6sj1q1q.js.map} +1 -1
- package/dist/{chunk-hgvt5084.js → chunk-m950vw4c.js} +2 -2
- package/dist/{chunk-hgvt5084.js.map → chunk-m950vw4c.js.map} +1 -1
- package/dist/{chunk-873k84dt.js → chunk-mm45shzv.js} +2 -2
- package/dist/{chunk-873k84dt.js.map → chunk-mm45shzv.js.map} +1 -1
- package/dist/{chunk-6q15sx3h.js → chunk-p56zntmt.js} +3 -3
- package/dist/{chunk-6q15sx3h.js.map → chunk-p56zntmt.js.map} +1 -1
- package/dist/{chunk-8yxjrjef.js → chunk-q01p8ta3.js} +2 -2
- package/dist/{chunk-8yxjrjef.js.map → chunk-q01p8ta3.js.map} +1 -1
- package/dist/{chunk-p97w2388.js → chunk-q3511sb5.js} +2 -2
- package/dist/{chunk-p97w2388.js.map → chunk-q3511sb5.js.map} +1 -1
- package/dist/{chunk-kfdy4vv1.js → chunk-q788x8pm.js} +2 -2
- package/dist/{chunk-kfdy4vv1.js.map → chunk-q788x8pm.js.map} +1 -1
- package/dist/{chunk-23670kw5.js → chunk-rpdekb8t.js} +2 -2
- package/dist/{chunk-23670kw5.js.map → chunk-rpdekb8t.js.map} +1 -1
- package/dist/{chunk-j7k0nzqz.js → chunk-s4fb4njt.js} +2 -2
- package/dist/{chunk-j7k0nzqz.js.map → chunk-s4fb4njt.js.map} +1 -1
- package/dist/{chunk-7yh908jj.js → chunk-s71e6k9m.js} +3 -3
- package/dist/{chunk-7yh908jj.js.map → chunk-s71e6k9m.js.map} +1 -1
- package/dist/{chunk-6eb6jgdv.js → chunk-sdn3dmpp.js} +4 -4
- package/dist/{chunk-6eb6jgdv.js.map → chunk-sdn3dmpp.js.map} +1 -1
- package/dist/{chunk-fxd7pqk3.js → chunk-sp77zwpn.js} +2 -2
- package/dist/{chunk-fxd7pqk3.js.map → chunk-sp77zwpn.js.map} +1 -1
- package/dist/{chunk-82jhqxx7.js → chunk-sv86v56c.js} +3 -3
- package/dist/{chunk-82jhqxx7.js.map → chunk-sv86v56c.js.map} +1 -1
- package/dist/{chunk-bym06a64.js → chunk-sxf94q13.js} +2 -2
- package/dist/{chunk-bym06a64.js.map → chunk-sxf94q13.js.map} +1 -1
- package/dist/{chunk-pd3qbf8r.js → chunk-ta2wsjz6.js} +2 -2
- package/dist/{chunk-pd3qbf8r.js.map → chunk-ta2wsjz6.js.map} +1 -1
- package/dist/{chunk-58k1zstz.js → chunk-thbs63gy.js} +1 -1
- package/dist/{chunk-71prz4rp.js → chunk-vfvjfw5k.js} +2 -2
- package/dist/{chunk-71prz4rp.js.map → chunk-vfvjfw5k.js.map} +1 -1
- package/dist/{chunk-sca3tpce.js → chunk-vnk4vaer.js} +3 -3
- package/dist/{chunk-sca3tpce.js.map → chunk-vnk4vaer.js.map} +1 -1
- package/dist/{chunk-f9nmn8x7.js → chunk-wc2sg9ny.js} +2 -2
- package/dist/{chunk-f9nmn8x7.js.map → chunk-wc2sg9ny.js.map} +1 -1
- package/dist/{chunk-rzqxkm9r.js → chunk-wp9hw3we.js} +2 -2
- package/dist/{chunk-rzqxkm9r.js.map → chunk-wp9hw3we.js.map} +1 -1
- package/dist/{chunk-4w9gbe11.js → chunk-wt1yzzbw.js} +1 -1
- package/dist/{chunk-d29dcs3e.js → chunk-xkas0yp8.js} +3 -3
- package/dist/{chunk-d29dcs3e.js.map → chunk-xkas0yp8.js.map} +1 -1
- package/dist/{chunk-j1yhtwsk.js → chunk-y3s05q6b.js} +2 -2
- package/dist/{chunk-j1yhtwsk.js.map → chunk-y3s05q6b.js.map} +1 -1
- package/dist/chunk-ys8nk9ga.js +15 -0
- package/dist/{chunk-ty9s0z7q.js.map → chunk-ys8nk9ga.js.map} +3 -3
- package/dist/{chunk-0gzqhjyg.js → chunk-z4dhd5pk.js} +2 -2
- package/dist/{chunk-0gzqhjyg.js.map → chunk-z4dhd5pk.js.map} +1 -1
- package/dist/{chunk-xxbkp90v.js → chunk-z5g56ds0.js} +3 -3
- package/dist/{chunk-xxbkp90v.js.map → chunk-z5g56ds0.js.map} +1 -1
- package/dist/{chunk-bzrhc7q3.js → chunk-zqptpk90.js} +2 -2
- package/dist/{chunk-bzrhc7q3.js.map → chunk-zqptpk90.js.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 +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +6 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/serverQueryFetcher.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-8v6y52et.js +0 -5
- package/dist/chunk-ty9s0z7q.js +0 -15
- /package/dist/{chunk-fnj2hc5v.js.map → chunk-3rp908gn.js.map} +0 -0
- /package/dist/{chunk-tms2g9at.js.map → chunk-777v6242.js.map} +0 -0
- /package/dist/{chunk-8f4jkpv7.js.map → chunk-8hfyscnn.js.map} +0 -0
- /package/dist/{chunk-xed7yf6h.js.map → chunk-hgpvfhtp.js.map} +0 -0
- /package/dist/{chunk-58k1zstz.js.map → chunk-thbs63gy.js.map} +0 -0
- /package/dist/{chunk-4w9gbe11.js.map → chunk-wt1yzzbw.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{$d as H,ce as _}from"../../chunk-gjwf07hy.js";import{Xj as O}from"../../chunk-s4fb4njt.js";import"../../chunk-6t1t7h05.js";import"../../chunk-a9frf7ym.js";import"../../chunk-gwphn604.js";import"../../chunk-m950vw4c.js";import"../../chunk-8b9ks729.js";import"../../chunk-0q65jzhv.js";import{ol as U,pl as V,tl as Z}from"../../chunk-9akefv1y.js";import{xl as Y}from"../../chunk-rpdekb8t.js";import"../../chunk-9wcv7e1a.js";import X from"path";function T(z){if(!z.config.get("route.channels"))return null;let C=z.config.get("broadcast",{}).driver;if(!(C===void 0||C==="memory"||C instanceof O))return null;return'[gemi] Broadcasts from this worker reach no one: the broadcast driver is "memory", which delivers to the sockets of the process that emits, and a worker has none. Set `driver: "redis"` in app/config/broadcast.ts.'}class J extends Error{name="QueueWorkerRefused"}class N{kernel;stopping;keepAlive;settings;constructor(z,C={}){this.kernel=z;this.settings={...V(),...C}}async start(){if(await this.kernel.waitForBoot(),this.stopping)return;let z=this.kernel.app;if(!z.bound(H))throw new J("[gemi] `gemi queue:work` has no queue to claim from: this application does not register QueueServiceProvider.");let C=z.make(H);if(!C.durable)throw new J('[gemi] `gemi queue:work` refuses to start: the queue uses the memory driver, which keeps each job in the process that dispatched it, so a worker never sees one. Set `driver: "database"` (or another driver every process can reach) in app/config/queue.ts, or run jobs in the server and drop the worker.');C.start(),this.keepAlive=setInterval(()=>{},1073741824),console.log(`[gemi] Queue worker started: claiming up to ${C.config.concurrency} job(s) at a time.`);let E=T(z);if(E)console.warn(E)}stop(z={}){return this.stopping??=this.drain({...this.settings,...z}),this.stopping}async drain(z){U();let C=this.kernel.app,E=C.resolved(H)?C.make(H):void 0;if(E)console.log(`[gemi] Shutting down: waiting for ${E.running} running job(s) (up to ${z.timeoutMs/1000}s).`),await E.drain(z.timeoutMs);let F=await this.kernel.shutdown({timeoutMs:z.providerTimeoutMs});clearInterval(this.keepAlive);let G=(E?.running??0)===0&&F.failed.length===0&&F.timedOut.length===0;return console.log(`[gemi] Shutdown ${G?"complete":"finished with errors"}.`),G?0:1}}async function $(){let z=Y();process.env.ROOT_DIR=z,process.env.APP_DIR=X.join(z,"app"),_();let C=X.join(z,"app/kernel/Kernel.ts"),{default:E}=await import(C);if(typeof E!=="function")return console.error(`[gemi] ${C} has no default export to boot the worker from.`),1;let F=new E;F.boot();let G=new N(F);Z(()=>G.stop());try{await G.start()}catch(L){if(!(L instanceof J))throw L;return console.error(L.message),1}return}$().then((z)=>{if(z!==void 0)process.exit(z)},(z)=>{console.error("[gemi] The queue worker failed to start:",z),process.exit(1)});
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=984A78AFB2512BEF64756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import type { Application, ShutdownReport } from \"../../foundation/Application\";\nimport { markShuttingDown, shutdownSettings, type ShutdownSettings } 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 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\n const report = await this.kernel.shutdown({ timeoutMs: settings.providerTimeoutMs });\n clearInterval(this.keepAlive);\n const clean =\n (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
9
|
"mappings": ";gcAYA,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,uNCFG,MAAM,UAA2B,KAAM,CAC5C,KAAO,oBACT,CAYO,MAAM,CAAY,CAWJ,OAVX,SACA,UACS,SAOjB,WAAW,CACQ,EACjB,EAAsC,CAAC,EACvC,CAFiB,cAGjB,KAAK,SAAW,IAAK,EAAiB,KAAM,CAAS,OAejD,MAAK,EAAkB,CAK3B,GAJA,MAAM,KAAK,OAAO,YAAY,EAI1B,KAAK,SAAU,OAEnB,IAAM,EAAc,KAAK,OAAO,IAGhC,GAAI,CAAC,EAAY,MAAM,CAAY,EACjC,MAAM,IAAI,EACR,+GAEF,EAEF,IAAM,EAAQ,EAAY,KAAK,CAAY,EAC3C,GAAI,CAAC,EAAM,QACT,MAAM,IAAI,EACR,8SAKF,EAMF,EAAM,MAAM,EAIZ,KAAK,UAAY,YAAY,IAAM,GAAI,UAAO,EAC9C,QAAQ,IACN,+CAA+C,EAAM,OAAO,+BAC9D,EACA,IAAM,EAAmB,EAAwB,CAAW,EAC5D,GAAI,EAAkB,QAAQ,KAAK,CAAgB,EAiBrD,IAAI,CAAC,EAAsC,CAAC,EAAoB,CAE9D,OADA,KAAK,WAAa,KAAK,MAAM,IAAK,KAAK,YAAa,CAAS,CAAC,EACvD,KAAK,cAGA,MAAK,CAAC,EAA6C,CAC/D,EAAiB,EACjB,IAAM,EAAc,KAAK,OAAO,IAG1B,EAAQ,EAAY,SAAS,CAAY,EAAI,EAAY,KAAK,CAAY,EAAI,OACpF,GAAI,EACF,QAAQ,IACN,qCAAqC,EAAM,iCAC/B,EAAS,UAAY,SACnC,EACA,MAAM,EAAM,MAAM,EAAS,SAAS,EAGtC,IAAM,EAAS,MAAM,KAAK,OAAO,SAAS,CAAE,UAAW,EAAS,iBAAkB,CAAC,EACnF,cAAc,KAAK,SAAS,EAC5B,IAAM,GACH,GAAO,SAAW,KAAO,GAAK,EAAO,OAAO,SAAW,GAAK,EAAO,SAAS,SAAW,EAE1F,OADA,QAAQ,IAAI,mBAAmB,EAAQ,WAAa,yBAAyB,EACtE,EAAQ,EAAI,EAEvB,CF1HA,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": "
|
|
10
|
+
"debugId": "984A78AFB2512BEF64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serverQueryFetcher.d.ts","sourceRoot":"","sources":["../../../services/router/serverQueryFetcher.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"serverQueryFetcher.d.ts","sourceRoot":"","sources":["../../../services/router/serverQueryFetcher.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,OAAO,GAAG,kBAAkB,CAsGzE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"../chunk-
|
|
2
|
+
import"../chunk-9wcv7e1a.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
|
package/dist/support/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{he as Y}from"../chunk-zqptpk90.js";import{ak as M}from"../chunk-a9frf7ym.js";import{cl as P,el as R}from"../chunk-8b9ks729.js";import"../chunk-0q65jzhv.js";import{ul as Q,vl as U,wl as V,xl as W}from"../chunk-rpdekb8t.js";import"../chunk-9wcv7e1a.js";class S{static token;async boot(){}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=9719323EC3945ADE64756E2164756E21
|
|
@@ -6,6 +6,6 @@
|
|
|
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
8
|
"mappings": ";2RAgCO,CAAe,JAAQ,EAOrB,OAMD,AAAI,EAAkB,QAmBrB,OAAS,EAKX,CACH,GAAI,CAAC,KAAK,MACR,MAAU,MACR,YAAY,KAAK,0FACnB,EAGF,GAAI,CACF,OAAO,EAAI,IAAuB,EAClC,MAAO,EAAO,CACd,MAAU,MACR,qBAAqB,KAAK,6DACxB,+FACA,6CAA6C,KAAK,kDAEpD,CAAE,OAAM,CACV,SAoBG,KAAuB,CAAoB,EAA0B,CAC1E,IAAM,EAAW,IAAI,KACrB,QAAY,EAAK,KAAU,OAAO,QAAQ,CAAS,EACjD,GAAI,IAAU,OAAW,EAAS,GAAO,EAE3C,OAAO,EAEX,CChHA,kBAAS,oBACT,eAAS,WAAM,aAIf,IAAM,EAAoB,CAAC,MAAO,OAAQ,MAAO,OAAQ,MAAM,EAMxD,SAAS,CAAsB,CACpC,EAA+B,CAAC,EACpB,CACZ,IAAM,EAA6B,CAAC,EAEpC,QAAY,EAAK,KAAQ,OAAO,QAAQ,CAAO,EAC7C,EAAM,GAAO,EAAO,CAAG,EAGzB,OAAO,IAAI,EAAW,CAAK,EAO7B,eAAsB,CAAc,CAClC,EACA,EAAa,IAAI,EACI,CACrB,IAAI,EAAoB,CAAC,EAEzB,GAAI,CACF,EAAU,MAAM,EAAQ,CAAS,EACjC,MAAO,EAAK,CACZ,OAAO,EAGT,IAAM,EAAQ,EACX,OAAO,CAAC,IAAU,CACjB,IAAQ,MAAK,QAAS,EAAM,CAAK,EACjC,OAAO,EAAkB,SAAS,CAAG,GAAK,CAAC,EAAK,WAAW,GAAG,EAC/D,EACA,KAAK,EAER,QAAW,KAAQ,EAAO,CACxB,IAAQ,QAAS,EAAM,CAAI,EACrB,EAAM,MAAa,SAAK,EAAW,CAAI,GAC7C,EAAW,IAAI,EAAM,EAAO,CAAG,CAAC,EAGlC,OAAO,EAGT,SAAS,CAAM,CAAC,EAAU,CACxB,GAAI,GAAO,OAAO,IAAQ,UAAY,YAAa,EACjD,OAAO,EAAI,QAEb,OAAO",
|
|
9
|
-
"debugId": "
|
|
9
|
+
"debugId": "9719323EC3945ADE64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
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-p56zntmt.js";import"../chunk-5nz46dyw.js";import"../chunk-wp9hw3we.js";import{Ba as J}from"../chunk-9ft0ayhf.js";import"../chunk-sp77zwpn.js";import"../chunk-9wcv7e1a.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-8v6y52et.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{fe as o}from"./chunk-f6mwnw81.js";import{ge as i}from"./chunk-bzrhc7q3.js";import{$j as t}from"./chunk-c0dvdfm0.js";import{$k as r}from"./chunk-71prz4rp.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
|
|
3
|
-
export{n as bb};
|
|
4
|
-
|
|
5
|
-
//# debugId=D93400955383164464756E2164756E21
|
package/dist/chunk-ty9s0z7q.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Qi as N,Ri as _0,Si as C0}from"./chunk-efjk5aq7.js";import{Xi as x0,_i as b}from"./chunk-w4at2d5d.js";import{dl as BQ}from"./chunk-kcgnjzqr.js";import{wl as Y0}from"./chunk-23670kw5.js";import{El as lZ}from"./chunk-m5hd632w.js";class o0{static kind="controller";constructor(){}}class bQ extends o0{}function N0(Q){let Z=new Map;if(!Q)return Z;for(let $ of Q.split(";")){let X=$.indexOf("=");if(X===-1)continue;let G=$.slice(0,X).trim();if(!G)continue;Z.set(G,$.slice(X+1).trim())}return Z}function W1(Q){return N0(Q.headers.get("cookie"))}function p(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function t0(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let X=Z.slice(6).split(",").map((D)=>D.trim()).filter((D)=>D!=="");if(X.length!==1)return null;let G=X[0],H=G.indexOf("-");if(H===-1)return null;let Y=G.slice(0,H),M=G.slice(H+1);if(Y===""){let D=p(M);if(D===null)return null;return{kind:"suffix",suffixLength:D}}let K=p(Y);if(K===null)return null;if(M==="")return{kind:"offset",start:K,end:null};let J=p(M);if(J===null||J<K)return null;return{kind:"offset",start:K,end:J}}function s0(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let $,X;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;$=Math.max(0,Z-Q.suffixLength),X=Z-1}else{if(Q.start>=Z)return null;if($=Q.start,X=Q.end===null?Z-1:Math.min(Q.end,Z-1),X<$)return null}return{start:$,end:X,length:X-$+1}}function z1(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function U1(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let $=p(Z[1]),X=p(Z[2]),G=p(Z[3]);if($===null||X===null||G===null||X<$)return null;return{start:$,end:X,total:G}}function V1(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function r0(Q){return`bytes */${Q}`}class s extends N{errors={};constructor(Q){super("Validation error");this.name="ValidationError",this.errors=Q,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:Q,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function fQ(Q){let[Z,$]=Q.match(/\d+|\D+/g)??[];if(!Z||!$)return 0;let X=Number.parseInt(Z);switch($){case"B":return X;case"KB":return X*1024;case"MB":return X*1024*1024;case"GB":return X*1024*1024*1024;case"TB":return X*1024*1024*1024*1024;default:return 0}}function vQ(Q){switch(Q){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return Q}}function a0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function q0(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var hQ=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function z0(Q,Z){let $=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN($))throw new k(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return $}function e0(Q){let Z=Q.indexOf(":"),$=Z===-1?Q:Q.slice(0,Z),X=Z===-1?void 0:Q.slice(Z+1);switch($){case"required":return(G)=>{if(G instanceof Blob)return G.size>0;if(G===null||G===void 0)return!1;if(typeof G==="string"||Array.isArray(G))return G.length>0;return!0};case"string":return(G)=>typeof G==="string";case"boolean":return(G)=>typeof G==="boolean";case"number":return(G)=>q0(G);case"password":return(G)=>{return typeof G==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(G)};case"min":{let G=z0($,X);return(H)=>{let Y=a0(H);return Y!==void 0&&Y>=G}}case"max":{let G=z0($,X);return(H)=>{let Y=a0(H);return Y!==void 0&&Y<=G}}case"gte":{let G=z0($,X);return(H)=>q0(H)&&H>=G}case"lte":{let G=z0($,X);return(H)=>q0(H)&&H<=G}case"email":return(G)=>{return typeof G==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)};case"file":return(G)=>{return G instanceof Blob};case"fileType":{if(!X)throw new k('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let G=vQ(X);return(H)=>H instanceof Blob&&H.type.startsWith(G)}case"fileSize":{let G=fQ(X??"");if(G===0&&!/^0+(B|KB|MB|GB|TB)$/.test(X??""))throw new k(`Validation rule "fileSize:${X??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(H)=>H instanceof Blob&&H.size<=G}case"array":return(G)=>Array.isArray(G);case"object":return(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G)&&!(G instanceof Blob);case"in":{let G=(X??"").split(",").filter((H)=>H!=="");if(G.length===0)throw new k('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(H)=>typeof H==="string"&&G.includes(H)}default:throw new k(`Unknown validation rule "${Q}". Known rules: ${hQ.join(", ")}`)}}function u(Q){if(!Q.definition)throw Error(`gemi/ai: the recursive schema "${Q.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return Q.definition}var R0=new WeakMap;function $Q(Q){return typeof Q==="object"&&Q!==null&&R0.has(Q)}function V0(Q){let Z=R0.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function mQ(Q){let Z={defs:{},cells:new Map},$=Q;if(Q.node.kind==="ref"){let G=u(Q.node.cell);$={...G,...Q.description?{description:Q.description}:{},optional:Q.optional,nullable:Q.nullable||G.nullable}}let X=a($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function a(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=uQ(pQ(Q.node,Z),$),G=[Q.description,cQ(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function cQ(Q){let Z=[];if(Q.kind==="string"||Q.kind==="enum"){let $=Q.checks;if($?.format)Z.push(`Format: ${$.format.name}.`);if($?.minLength!==void 0)Z.push(`At least ${$.minLength} characters.`);if($?.maxLength!==void 0)Z.push(`At most ${$.maxLength} characters.`)}else if(Q.kind==="number"){let $=Q.checks;if($?.minimum!==void 0)Z.push(`Minimum ${$.minimum}.`);if($?.exclusiveMinimum!==void 0)Z.push(`Greater than ${$.exclusiveMinimum}.`);if($?.maximum!==void 0)Z.push(`Maximum ${$.maximum}.`);if($?.exclusiveMaximum!==void 0)Z.push(`Less than ${$.exclusiveMaximum}.`)}else if(Q.kind==="array"){let $=Q.checks;if($?.minItems!==void 0)Z.push(`At least ${$.minItems} items.`);if($?.maxItems!==void 0)Z.push(`At most ${$.maxItems} items.`)}return Z.join(" ")}function pQ(Q,Z){switch(Q.kind){case"string":return{type:"string"};case"number":return{type:Q.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof Q.value,const:Q.value};case"enum":return{type:"string",enum:Q.values};case"array":return{type:"array",items:a(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,a(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>a($,Z))};case"json":return{};case"ref":{let{cell:$}=Q,X=Z.cells.get($.name);if(X&&X!==$)throw Error(`gemi/ai: two different recursive schemas are named "${$.name}" in one schema; give each s.recursive(...) its own name`);if(!X)Z.cells.set($.name,$),Z.defs[$.name]={},Z.defs[$.name]=a(u($),Z);return{$ref:`#/$defs/${$.name}`}}}}function uQ(Q,Z){if(!Z)return Q;if(Q.anyOf)return{...Q,anyOf:[...Q.anyOf,{type:"null"}]};if(Q.enum||Q.const!==void 0)return{anyOf:[Q,{type:"null"}]};if(typeof Q.type==="string")return{...Q,type:[Q.type,"null"]};return{anyOf:[Q,{type:"null"}]}}function dQ(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function lQ(Q,Z){if(typeof Z==="number"&&!Number.isFinite(Z))return String(Z);if(Q.kind==="literal"||Q.kind==="enum"){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return JSON.stringify(Z)}return dQ(Z)}function XQ(Q){let Z=Q.node,$=(()=>{switch(Z.kind){case"number":return Z.checks?.integer?"integer":"number";case"string":case"boolean":return Z.kind;case"literal":return JSON.stringify(Z.value);case"enum":return`one of ${Z.values.map((X)=>JSON.stringify(X)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return XQ({...u(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function iQ(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function nQ(Q){let Z=iQ(Q);return Z?`${Z}: `:""}function w0(Q){return`${nQ(Q.path)}${Q.message}`}function B0(Q,Z){if(Z===null||Z===void 0)return Q.optional||Q.nullable?1:0;let $=Q.node;switch($.kind){case"string":return typeof Z==="string"?1:0;case"number":return typeof Z==="number"?1:0;case"boolean":return typeof Z==="boolean"?1:0;case"literal":return Z===$.value?10:0;case"enum":return typeof Z==="string"&&$.values.includes(Z)?10:0;case"array":return Array.isArray(Z)?1:0;case"object":{if(typeof Z!=="object"||Array.isArray(Z))return 0;let X=Z,G=1;for(let[H,Y]of Object.entries($.shape))G+=B0(Y,X[H]);return G}case"union":return $.members.reduce((X,G)=>Math.max(X,B0(G,Z)),0);case"json":return 1;case"ref":return GQ($.cell,Z,()=>1,()=>B0(u($.cell),Z))}}function GQ(Q,Z,$,X){if(typeof Z!=="object"||Z===null)return X();if(Q.active.has(Z))return $();Q.active.add(Z);try{return X()}finally{Q.active.delete(Z)}}function v(Q,Z,$,X){if(Q.optional&&(Z===null||Z===void 0))return{drop:!0,value:void 0};if(Q.nullable&&Z===null)return{drop:!1,value:null};return{drop:!1,value:oQ(Q,Z,$,X)}}function oQ(Q,Z,$,X){let G=Q.node,H=()=>{let Y=Z===void 0?"required":G.kind==="literal"?"const":G.kind==="enum"&&typeof Z==="string"?"enum":"type",M=Y==="const"?{allowedValue:G.value}:Y==="enum"?{allowedValues:G.values}:{};X.push({path:$,code:Y,message:`expected ${XQ(Q)}, got ${lQ(G,Z)}`,params:M});return};switch(G.kind){case"string":if(typeof Z!=="string")return H();return QQ(G.checks,Z,$,X),Z;case"number":if(typeof Z!=="number"||!Number.isFinite(Z))return H();if(G.checks?.integer&&!Number.isInteger(Z))return H();return sQ(G.checks,Z,$,X),Z;case"boolean":return typeof Z==="boolean"?Z:H();case"literal":return Z===G.value?Z:H();case"enum":if(typeof Z!=="string"||!G.values.includes(Z))return H();return QQ(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return H();let Y=Z.map((J,D)=>{let z=v(G.item,J,[...$,D],X);return z.drop?void 0:z.value}),{minItems:M,maxItems:K}=G.checks??{};if(M!==void 0&&Z.length<M)X.push({path:$,code:"minItems",message:`expected at least ${M} items, got ${Z.length}`,params:{limit:M}});if(K!==void 0&&Z.length>K)X.push({path:$,code:"maxItems",message:`expected at most ${K} items, got ${Z.length}`,params:{limit:K}});return Y}case"object":{if(typeof Z!=="object"||Z===null||Array.isArray(Z))return H();let Y=Z,M={};for(let[K,J]of Object.entries(G.shape)){let D=v(J,Y[K],[...$,K],X);if(!D.drop)M[K]=D.value}if(G.unknownKeys)for(let K of Object.keys(Y)){if(Object.hasOwn(G.shape,K)||Y[K]===void 0)continue;if(G.unknownKeys==="error"){X.push({path:[...$,K],code:"additionalProperties",message:"unknown key",params:{additionalProperty:K}});continue}Z0(Y[K],[...$,K],X,new Set),Object.defineProperty(M,K,{value:Y[K],enumerable:!0,writable:!0,configurable:!0})}return M}case"union":{let Y;for(let M of G.members){let K=[],J=v(M,Z,$,K);if(K.length===0)return J.drop?void 0:J.value;let D=B0(M,Z);if(!Y||D>Y.score)Y={issues:K,score:D}}X.push({path:$,code:"anyOf",message:`no matching variant; closest: ${Y.issues.map(w0).join("; ")}`,params:{closest:Y.issues}});return}case"json":if(Z===void 0)return H();return Z0(Z,$,X,new Set),Z;case"ref":return GQ(G.cell,Z,()=>{X.push({path:$,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>v(u(G.cell),Z,$,X).value)}}function tQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function QQ(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:H,format:Y}=Q;if(G!==void 0||H!==void 0){let M=tQ(Z);if(G!==void 0&&M<G)X.push({path:$,code:"minLength",message:`expected at least ${G} characters, got ${M}`,params:{limit:G}});if(H!==void 0&&M>H)X.push({path:$,code:"maxLength",message:`expected at most ${H} characters, got ${M}`,params:{limit:H}})}if(Y){let M=!1;try{M=Y.test(Z)===!0}catch{}if(!M)X.push({path:$,code:"format",message:`expected a string in format "${Y.name}"`,params:{format:Y.name}})}}function sQ(Q,Z,$,X){if(!Q)return;let G=(H,Y,M,K)=>{if(Y===void 0||M(Y))return;X.push({path:$,code:H,message:`expected ${K} ${Y}, got ${Z}`,params:{limit:Y}})};G("minimum",Q.minimum,(H)=>Z>=H,"at least"),G("exclusiveMinimum",Q.exclusiveMinimum,(H)=>Z>H,"more than"),G("maximum",Q.maximum,(H)=>Z<=H,"at most"),G("exclusiveMaximum",Q.exclusiveMaximum,(H)=>Z<H,"less than")}function Z0(Q,Z,$,X,G=!0){let H=(M)=>{$.push({path:Z,code:"type",message:`expected a JSON value, got ${M}`,params:{}})};switch(typeof Q){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(Q))H(String(Q));return;case"bigint":return H("a bigint");case"function":return H("a function");case"symbol":return H("a symbol")}if(Q===null)return;let Y=Q;if(X.has(Y))return H("a circular reference");X.add(Y);try{let M=G?Y.toJSON:void 0;if(typeof M==="function"){let K;try{K=M.call(Y)}catch{return H("a toJSON that threw")}if(K===void 0)return H("a toJSON that returns undefined");return Z0(K,Z,$,X,!1)}if(Array.isArray(Q))Q.forEach((K,J)=>Z0(K,[...Z,J],$,X));else for(let[K,J]of Object.entries(Y))Z0(J,[...Z,K],$,X)}finally{X.delete(Y)}}function E(Q){return P0(Q)}function P0(Q){let Z={toJSONSchema:()=>mQ(Q),parse($){let X=[],G=v(Q,$,[],X);if(X.length>0)throw Error(X.map(w0).join("; "));return G.drop?void 0:G.value},safeParse($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,errors:X.map(w0)};return{ok:!0,value:G.drop?void 0:G.value}},validate($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,issues:X};return{ok:!0,value:G.drop?void 0:G.value}},describe:($)=>P0({...Q,description:$}),optional:()=>P0({...Q,optional:!0}),nullable:()=>P0({...Q,nullable:!0,optional:!1})};return R0.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var ZQ=["strip","error","passthrough"];class HQ extends Error{problems;constructor(Q){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
3
|
-
${Q.map((Z)=>`- ${Z}`).join(`
|
|
4
|
-
`)}`);this.name="JSONSchemaError",this.problems=Q}}var rQ=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),r={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function U0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function j0(Q,Z,$,X){let G=(W,V=$)=>{X.push(V?`${V}: ${W}`:W);return},H=(W)=>$?`${$}.${W}`:W;if(!U0(Q))return G("expected a schema object");let Y=new Set(Z.ignoreKeywords??[]),M=(W)=>rQ.has(W)||W.startsWith("x-")||Y.has(W),K=!1,J=Q.type;if(Array.isArray(J)){let W=J.filter((V)=>V!=="null");if(W.length!==1)return G(`type ${JSON.stringify(J)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,H("type"));K=W.length<J.length,J=W[0]}if(J!==void 0&&(typeof J!=="string"||!(J in r)))return G(`type ${JSON.stringify(J)} is not supported; expected one of ${Object.keys(r).join(", ")}`,H("type"));let D=new Set(["type","description","enum","const","anyOf",...J?r[J]:[]]),z=!1;for(let W of Object.keys(Q)){if(D.has(W)||M(W))continue;z=!0;let V=Object.entries(r).find(([,U])=>U.includes(W));G(V&&V[0]!==J?`"${W}" applies to type ${V[0]}, and this schema is ${J?`type ${J}`:"untyped"}`:`"${W}" is not supported by s.fromJSONSchema`,H(W))}if(z)return;if(Q.description!==void 0&&typeof Q.description!=="string")return G("expected a string",H("description"));let O=Q.description,B=(W)=>({node:W,optional:!1,nullable:K,...O?{description:O}:{}});if(Q.anyOf!==void 0){if(J!==void 0||Q.enum!==void 0||Q.const!==void 0)return G("anyOf cannot be combined with type, enum or const here",H("anyOf"));if(!Array.isArray(Q.anyOf)||Q.anyOf.length===0)return G("expected a non-empty array",H("anyOf"));let W=[],V=!1;if(Q.anyOf.forEach((U,P)=>{if(U0(U)&&U.type==="null"&&Object.keys(U).length===1){K=!0;return}let F=j0(U,Z,H(`anyOf[${P}]`),X);if(F)W.push(F);else V=!0}),V)return;if(W.length===0)return G("anyOf has only null in it",H("anyOf"));if(W.length===1){let U=W[0];return{...U,nullable:U.nullable||K,...O?{description:O}:{}}}return B({kind:"union",members:W})}if(Q.const!==void 0){let W=Q.const;if(typeof W!=="string"&&typeof W!=="number"&&typeof W!=="boolean")return G("only a string, number or boolean const is supported",H("const"));if(J!==void 0&&typeof W!==(J==="integer"?"number":J))return G(`const ${JSON.stringify(W)} is not of type ${J}`,H("const"));return B({kind:"literal",value:W})}let _;if(J==="string"){if(_=aQ(Q,Z,H,X),_===null)return}if(Q.enum!==void 0){if(!Array.isArray(Q.enum)||Q.enum.length===0)return G("expected a non-empty array",H("enum"));let W=Q.enum.filter((P)=>P!==null);if(W.length<Q.enum.length)K=!0;let V=W.find((P)=>!(typeof P==="string"||typeof P==="number"||typeof P==="boolean")||J!==void 0&&typeof P!==(J==="integer"?"number":J));if(V!==void 0||W.length===0)return G(J?`every value must be of type ${J}${W.length===0?", and there must be one":`; ${JSON.stringify(V)} is not`}`:"only strings, numbers and booleans are supported",H("enum"));if(W.every((P)=>typeof P==="string"))return B({kind:"enum",values:[...new Set(W)],..._?{checks:_}:{}});let U=[...new Set(W)];if(U.length===1)return B({kind:"literal",value:U[0]});return B({kind:"union",members:U.map((P)=>x({kind:"literal",value:P}))})}switch(J){case void 0:return G("a schema needs a type, an enum, a const or an anyOf");case"string":return B({kind:"string",..._?{checks:_}:{}});case"number":case"integer":{let W=J==="integer"?{integer:!0}:{},V=!1;for(let U of r.number){let P=Q[U];if(P===void 0)continue;if(typeof P!=="number"||!Number.isFinite(P)){G("expected a number",H(U)),V=!0;continue}W[U]=P}if(V)return;return B({kind:"number",...Object.keys(W).length>0?{checks:W}:{}})}case"boolean":return B({kind:"boolean"});case"array":{if(!U0(Q.items))return G('an array needs "items" to be one schema (tuples are not supported)',H("items"));let W={},V=!1;for(let P of["minItems","maxItems"]){let F=Q[P];if(F===void 0)continue;if(typeof F!=="number"||!Number.isInteger(F)||F<0){G("expected a non-negative integer",H(P)),V=!0;continue}W[P]=F}let U=j0(Q.items,Z,H("items"),X);if(!U||V)return;return B({kind:"array",item:U,...Object.keys(W).length>0?{checks:W}:{}})}case"object":{let W=Q.properties??{};if(!U0(W))return G("expected an object",H("properties"));if(Q.additionalProperties!==void 0&&Q.additionalProperties!==!1)return G("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",H("additionalProperties"));let V=Q.required??[];if(!Array.isArray(V)||!V.every((T)=>typeof T==="string"))return G("expected an array of property names",H("required"));let U=V.filter((T)=>!Object.hasOwn(W,T));if(U.length>0)return G(`lists properties the schema doesn't have: ${U.join(", ")}`,H("required"));let P={},F=!1;for(let[T,L]of Object.entries(W)){let R=j0(L,Z,H(`properties.${T}`),X);if(!R){F=!0;continue}P[T]=V.includes(T)?R:{...R,optional:!0}}if(F)return;let I=Z.unknownKeys;return B({kind:"object",shape:P,...I==="error"||I==="passthrough"?{unknownKeys:I}:{}})}}return}function aQ(Q,Z,$,X){let G={},H=!1;for(let Y of["minLength","maxLength"]){let M=Q[Y];if(M===void 0)continue;if(typeof M!=="number"||!Number.isInteger(M)||M<0){X.push(`${$(Y)}: expected a non-negative integer`),H=!0;continue}G[Y]=M}if(Q.format!==void 0){let Y=Q.format,M=typeof Y==="string"?Z.formats?.[Y]:void 0;if(typeof Y!=="string")X.push(`${$("format")}: expected a string`),H=!0;else if(!M||!Object.hasOwn(Z.formats,Y))X.push(`${$("format")}: unknown format ${JSON.stringify(Y)}; pass a check for it in the formats option`),H=!0;else G.format={name:Y,test:eQ(M)}}if(H)return null;return Object.keys(G).length>0?G:void 0}function eQ(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var _1={string:()=>E(x({kind:"string"})),number:()=>E(x({kind:"number"})),boolean:()=>E(x({kind:"boolean"})),literal:(Q)=>E(x({kind:"literal",value:Q})),enum:(Q)=>E(x({kind:"enum",values:Q})),object:(Q)=>E(x({kind:"object",shape:Object.fromEntries(Object.entries(Q).map(([Z,$])=>[Z,V0($)]))})),array:(Q)=>E(x({kind:"array",item:V0(Q)})),union:(Q)=>E(x({kind:"union",members:Q.map(V0)})),json:()=>E(x({kind:"json"})),recursive:ZZ,fromJSONSchema:(Q,Z={})=>{let $=[];if(Z.unknownKeys!==void 0&&!ZQ.includes(Z.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${ZQ.map((G)=>JSON.stringify(G)).join(", ")}, got ${JSON.stringify(Z.unknownKeys)}`);let X=j0(Q,Z,"",$);if(!X||$.length>0)throw new HQ($.length>0?$:["unreadable schema"]);return E(X)}};function C1(Q){let Z=R0.get(Q);if(Z)return Q0(Z.node);return e(Q.toJSONSchema())}function e(Q){if(!(Q.$ref!==void 0||Q.type!==void 0||Q.enum!==void 0||Q.const!==void 0||Q.anyOf!==void 0||Q.properties!==void 0||Q.items!==void 0))return!1;for(let $ of Object.values(Q.properties??{}))if(!e($))return!1;if(Q.items&&!e(Q.items))return!1;for(let $ of Q.anyOf??[])if(!e($))return!1;for(let $ of Object.values(Q.$defs??{}))if(!e($))return!1;return!0}function Q0(Q,Z=new Set){switch(Q.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(Q.shape).every(($)=>Q0($.node,Z));case"array":return Q0(Q.item.node,Z);case"union":return Q.members.every(($)=>Q0($.node,Z));case"json":return!1;case"ref":if(Z.has(Q.cell))return!0;return Z.add(Q.cell),Q0(u(Q.cell).node,Z)}}function E0(Q,Z,$=new Set){let X=Q.node;if(X.kind==="union")return X.members.some((G)=>E0(G,Z,$));if(X.kind!=="ref")return!1;if(X.cell===Z)return!0;if($.has(X.cell)||!X.cell.definition)return!1;return $.add(X.cell),E0(X.cell.definition,Z,$)}var QZ=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function ZZ(Q,Z){if(typeof Q!=="string"||!QZ.test(Q))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(Q)}`);let $={name:Q,active:new Set},X=()=>x({kind:"ref",cell:$}),G=V0(Z(E(X())));if(G.optional)throw Error(`gemi/ai: the recursive schema "${Q}" is optional() as a whole; mark the places that use it optional instead`);if(E0(G,$))throw Error(`gemi/ai: the recursive schema "${Q}" refers to itself outside any object or array, so it describes no finite value; nest \`self\` in an s.object(...) field or an s.array(...)`);return $.definition=G,E(X())}function YQ(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),$=Z.trim().toLowerCase();return $===""?null:$}function KQ(Q){if(Q===null)return!1;if(Q==="application/json")return!0;let Z=Q.indexOf("/");return Z>0&&Q.endsWith("+json")&&Q.length>Z+1+5}var $0=new WeakMap;function F1(Q,Z,$,X){$0.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function MQ(Q){return $0.get(Q)?.progress}function JQ(Q){return $0.get(Q)?.grant}function WQ(Q){return $0.has(Q)}function I1(Q){return $0.get(Q)?.clientAddress}var DQ=new WeakMap;function A1(Q,Z){DQ.set(Q,Z)}function zQ(Q){return DQ.get(Q)??null}var S0=new WeakMap;function N1(Q,Z){let $=S0.get(Q)??[];if(!$.includes(Z))S0.set(Q,[...$,Z])}function q1(Q){return S0.get(Q)??[]}class d{data;constructor(Q){this.data=Q}get(Q){return this.data[Q]}has(Q){return this.data[Q]!==void 0}toJSON(){return this.data}}function UQ(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function $Z(Q,Z){if(!Z.includes(".")||Object.hasOwn(Q,Z))return[{path:[Z],value:Q[Z]}];let $=[{path:[],value:Q}];for(let X of Z.split(".")){let G=[];for(let{path:H,value:Y}of $){if(X==="*"){if(Array.isArray(Y))Y.forEach((M,K)=>G.push({path:[...H,K],value:M}));else if(UQ(Y))for(let[M,K]of Object.entries(Y))G.push({path:[...H,M],value:K});continue}if(Array.isArray(Y)&&/^\d+$/.test(X)){G.push({path:[...H,Number(X)],value:Y[Number(X)]});continue}G.push({path:[...H,X],value:UQ(Y)&&Object.hasOwn(Y,X)?Y[X]:void 0})}$=G}return $}function VQ(Q){return Q.join(".")}class XZ{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(Q,Z,$,X){if(!Q){let K=b.getStore().req;this.params=K.params,this.rawRequest=K.rawRequest,this.kind=K.kind,this.routePath=K.routePath,this.domain=K.domain??null,this.state=K.state??new x0}else this.params=Z,this.rawRequest=Q,this.routePath=X,this.kind=$??"api",this.domain=zQ(Q),this.state=new x0;this.headers=this.rawRequest.headers;let G=N0(this.rawRequest.headers.get("Cookie")),H=new URL(this.rawRequest.url),Y=new Map;for(let[K,J]of H.searchParams)if(Y.has(K)){let D=Y.get(K);if(Array.isArray(D))D.push(J),Y.set(K,D);else Y.set(K,[D,J])}else Y.set(K,J);let M=Object.fromEntries(Y.entries());this.search=new d(M),this.cookies=G}locale(){return b.getStore().locale}ctx(){return b.getStore()}isModelOriginated(){return WQ(this.rawRequest)}mcpGrant(){return JQ(this.rawRequest)??null}reportProgress(Q){let Z=MQ(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return t0(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=YQ(this.rawRequest.headers.get("Content-Type"));if(KQ(Q))return new d(await this.parseJsonBody());if(Q==="application/x-www-form-urlencoded"||Q==="multipart/form-data"){let Z;try{Z=await this.rawRequest.formData()}catch(X){if(X instanceof N)throw X;throw new N("The request body could not be read as a form.")}let $=new Map;for(let[X,G]of Z.entries())if($.has(X)){let H=$.get(X);if(Array.isArray(H))H.push(G);else $.set(X,[H,G])}else $.set(X,G);return new d(Object.fromEntries($.entries()))}return new d({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch($){if($ instanceof N)throw $;throw new N("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new N("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new N("The request body must be a JSON object.");return Z}validateInput(Q){if($Q(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},$={},X=Object.entries(this.schema).map(([G,H])=>({key:G,rules:Object.entries(H).map(([Y,M])=>({rule:Y,message:M,check:typeof M==="function"?null:this.ruleFor(G,Y)}))}));for(let{key:G,rules:H}of X)for(let{path:Y,value:M}of $Z(Z,G)){let K=this.checkField(M,H);if(K.length>0){let J=$[VQ(Y)]??=[];for(let D of K)if(!J.includes(D))J.push(D)}}if(this.addRefinements($,Z),Object.keys($).length>0)throw new s($);return Q}checkField(Q,Z){let $=Z.some(({rule:H})=>H==="required"),X=Q===void 0||Q===null||Q==="",G=[];for(let{rule:H,message:Y,check:M}of Z){let K=Y,J=!1;if(typeof Y==="function")K=Y(Q),J=typeof K>"u";else J=M(Q);if(J)continue;if(X&&!$)continue;if(H==="required")return[String(K)];if(!G.includes(String(K)))G.push(String(K))}return G}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),$={};if("issues"in Z)for(let G of Z.issues){let H=VQ(G.path),Y=$[H]??=[];if(!Y.includes(G.message))Y.push(G.message)}let X="value"in Z?new d(Z.value):Q;if(this.addRefinements($,X.toJSON()),Object.keys($).length>0)throw new s($);return X}addRefinements(Q,Z){for(let[$,X]of Object.entries(this.refine(Z)??{})){let G=Q[$]??[];Q[$]=G.includes(X)?G:[...G,X]}}ruleFor(Q,Z){try{return e0(Z)}catch($){if($ instanceof k)throw new k(`${this.constructor.name}.schema.${Q}: ${$.message}`);throw $}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let Q=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(Q)}}catch(Z){if(!(Z instanceof s))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}class GZ extends N{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:C0("authorization",this.error,401)}},view:{}}}}class k0 extends N{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:k0.apiStatus,data:{error:C0("permission",this.error,k0.apiStatus)}},view:{status:403}}}}class g0 extends N{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:_0("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":r0(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class HZ extends N{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:_0("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class h extends N{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:_0("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class YZ extends N{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:C0("authentication","Authentication error",401)}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Z}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Z}}}}}class X0{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return BQ(this.getFacadeAccessor())}}import{Buffer as KZ}from"buffer";function L0(Q){if(typeof Q!=="string"||/^[\s/.]*$/.test(Q))throw Error(`Refusing to delete by prefix ${JSON.stringify(Q)}: it would match the whole store`)}class G0{async putStream({body:Q,...Z},$={}){$.signal?.throwIfAborted();let X=[],G=Q.getReader();try{for(;;){$.signal?.throwIfAborted();let{done:H,value:Y}=await G.read();if(H)break;X.push(Y)}}catch(H){throw await G.cancel(H).catch(()=>{}),H}return this.put({...Z,body:KZ.concat(X)},$)}async*objects(Q,Z={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(Q,Z={}){L0(Q);let $=[];for await(let X of this.objects(Q,Z))$.push(X.name);for(let X of $)Z.signal?.throwIfAborted(),await this.delete({name:X,bucket:Z.bucket});return $.length}async delete(Q){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,$=await this.fetch({name:Z.name,bucket:Z.bucket});if(!$.ok)throw new h(Z.name);let X=$.headers.get("Content-Type")??"application/octet-stream",G=$.headers.get("ETag")??void 0,H=$.headers.get("Last-Modified"),Y=H?new Date(H):void 0;if(Z.range){let J=await $.blob();return{body:J,start:0,end:J.size-1,total:J.size,partial:!1,type:X,etag:G,lastModified:Y,name:Z.name}}let M=Number($.headers.get("Content-Length")),K=Number.isFinite(M)?M:0;return{body:$.body,start:0,end:K-1,total:K,partial:!1,type:X,etag:G,lastModified:Y,name:Z.name}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=typeof Q==="string"?void 0:Q.bucket,X=await this.fetch({name:Z,bucket:$});if(!X.ok)throw new h(Z);let G=Number(X.headers.get("Content-Length"));if(Number.isFinite(G))return await X.body?.cancel(),G;return(await X.blob()).size}}function PQ(Q,Z){if(!Z)return Q;let $=Q.getReader(),X=!1,G,H=()=>{if(X=!0,G)Z.removeEventListener("abort",G)};return new ReadableStream({start(Y){if(G=()=>{if(X)return;H(),Y.error(Z.reason),$.cancel(Z.reason).catch(()=>{})},Z.aborted)G();else Z.addEventListener("abort",G,{once:!0})},async pull(Y){let M;try{M=await $.read()}catch(K){if(X)return;H(),Y.error(K);return}if(X)return;if(M.done){H(),Y.close();return}Y.enqueue(M.value)},cancel(Y){return H(),$.cancel(Y)}},{highWaterMark:0})}import{mkdir as MZ,open as JZ,readdir as y0,rename as WZ,rmdir as DZ,stat as zZ,unlink as jQ}from"fs/promises";import{dirname as UZ,isAbsolute as b0,relative as H0,resolve as l,sep as f}from"path";class f0 extends G0{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${Y0()}/storage`}async put(Q,{signal:Z}={}){Z?.throwIfAborted();let $,X;if(Q instanceof Blob)$=Q,X=`${Bun.randomUUIDv7()}.${Q.type.split("/")[1].split(";")[0]}`;else $=Q.body,X=Q.name;let G=$ instanceof Buffer?$:$ instanceof Blob||$ instanceof File?Buffer.from(await $.arrayBuffer()):"",H=`${this.folderPath}/${X}`;return Z?.throwIfAborted(),await Bun.write(H,G),X}async putStream({name:Q,body:Z},{signal:$}={}){let X=Z.getReader(),G=null;try{if($?.throwIfAborted(),!Q)throw Error("Object name has to be specified");let H=l(this.folderPath),Y=l(H,Q),M=H0(H,Y);if(!M||M===".."||M.startsWith(`..${f}`)||b0(M))throw Error(`Refusing to write "${Q}": it is outside the storage folder`);await MZ(UZ(Y),{recursive:!0}),G=`${Y}.${Bun.randomUUIDv7()}.partial`;let K=await JZ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:J,value:D}=await X.read();if(J)break;for(let z=0;z<D.byteLength;){let{bytesWritten:O}=await K.write(D,z);z+=O}}}finally{await K.close()}return $?.throwIfAborted(),await WZ(G,Y),Q}catch(H){if(await X.cancel(H).catch(()=>{}),G)await jQ(G).catch(()=>{});throw H}}async fetch(Q,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,X;if(typeof Q==="string")X=Q;else $=Q.bucket??$,X=Q.name;if(!X)throw Error("Object name has to be specified");let G=`${this.folderPath}/${X}`,H=Bun.file(G),Y=PQ(Bun.file(G).stream(),Z),M=new Date(H.lastModified).toUTCString();return new Response(Y,{headers:{"Content-Type":H.type,"Content-Length":String(H.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":M}})}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,{name:$,range:X=null}=Z;if(!$)throw Error("Object name has to be specified");let G=Bun.file(`${this.folderPath}/${$}`);if(!await G.exists())throw new h($);let H=G.size,Y=X?s0(X,H):null;if(X&&!Y)throw new g0(H);let M=Y?.start??0,K=Y?Y.end:H-1;return{body:Y?G.slice(M,K+1):G,start:M,end:K,total:H,partial:Boolean(Y),type:G.type||"application/octet-stream",lastModified:new Date(G.lastModified),name:$}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=Bun.file(`${this.folderPath}/${Z}`);if(!await $.exists())throw new h(Z);return $.size}async delete(Q){let Z=typeof Q==="string"?Q:Q.name;if(!Z)throw Error("Object name has to be specified");let $=l(this.folderPath),X=l($,Z),G=H0($,X);if(!G||G===".."||G.startsWith(`..${f}`)||b0(G))throw Error(`Refusing to delete "${Z}": it is outside the storage folder`);try{await jQ(X)}catch(H){if(H?.code==="ENOENT")return;throw H}}resolvePrefix(Q){let Z=l(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),H=l(Z,X),Y=H0(Z,H);if(Y===".."||Y.startsWith(`..${f}`)||b0(Y))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let M=Y.split(f).join("/");return{root:Z,dir:H,match:M?`${M}/${G}`:G}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:$,dir:X,match:G}=this.resolvePrefix(Q),H=[],Y=async(M)=>{let K;try{K=await y0(M,{withFileTypes:!0})}catch(J){if(J?.code==="ENOENT"||J?.code==="ENOTDIR")return;throw J}for(let J of K){let D=`${M}${f}${J.name}`,z=H0($,D).split(f).join("/");if(J.isDirectory()){if(`${z}/`.startsWith(G)||G.startsWith(`${z}/`))await Y(D)}else if(J.isFile()&&z.startsWith(G))H.push(z)}};await Y(X),H.sort();for(let M of H){Z?.throwIfAborted();let K;try{K=await zZ(`${$}/${M}`)}catch(J){if(J?.code==="ENOENT")continue;throw J}yield{name:M,size:K.size,lastModified:K.mtime}}}async deletePrefix(Q,Z={}){L0(Q);let{root:$,match:X}=this.resolvePrefix(Q);L0(X);let G=await super.deletePrefix(Q,Z);if(G>0)await this.pruneEmptyDirs($,X);return G}async pruneEmptyDirs(Q,Z){let $=[],X=async(G)=>{let H;try{H=await y0(G,{withFileTypes:!0})}catch{return}for(let Y of H){if(!Y.isDirectory())continue;let M=`${G}${f}${Y.name}`,K=H0(Q,M).split(f).join("/");if(`${K}/`.startsWith(Z)||Z.startsWith(`${K}/`)){if(await X(M),`${K}/`.startsWith(Z))$.push(M)}}};await X(Q);for(let G of $)try{await DZ(G)}catch{}}async list(){return await y0(this.folderPath)}}function Y8(Q){return Q}function RQ(){return{driver:new f0}}class v0{static token="filesystem";driver;constructor(Q={}){this.driver=Q.driver??RQ().driver}}class q extends Error{code="safe-fetch";url;constructor(Q,Z,$){super(Q,$);this.name=new.target.name,this.url=Z}}class m extends q{reason;code="invalid-url";constructor(Q,Z,$){super($,Q);this.reason=Z}}class O0 extends q{host;reason;code="blocked-host";constructor(Q,Z,$){super($==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,Q);this.host=Z;this.reason=$}}class i extends q{host;address;range;code="blocked-address";constructor(Q,Z,$,X){super(Z===$?`${$} is not a public address (${X}).`:`${Z} resolves to ${$}, which is not a public address (${X}).`,Q);this.host=Z;this.address=$;this.range=X}}class F0 extends q{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class I0 extends q{phase;ms;code="timeout";constructor(Q,Z,$){super(Z==="connect"?`Couldn't connect within ${$} ms.`:`The request didn't finish within ${$} ms.`,Q);this.phase=Z;this.ms=$}}class T0 extends q{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class K0 extends q{contentType;allowed;code="content-type";constructor(Q,Z,$){super(`The response is ${Z??"of no content type"}, not ${$.join(" or ")}.`,Q);this.contentType=Z;this.allowed=$}}class h0 extends q{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class n extends q{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class m0 extends q{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function VZ(Q){if(Q==="")return null;let Z=Q.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let $=[];for(let H of Z){let Y=BZ(H);if(Y===null)return null;$.push(Y)}let X=$.pop();for(let H of $)if(H>255)return null;if(X>=256**(4-$.length))return null;let G=X;return $.forEach((H,Y)=>{G+=H*256**(3-Y)}),new Uint8Array([Math.floor(G/16777216)&255,Math.floor(G/65536)&255,Math.floor(G/256)&255,G&255])}function BZ(Q){if(Q==="")return null;let Z=Q,$=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),$=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),$=8;if(!($===16?/^[0-9a-f]+$/i:$===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let G=parseInt(Z,$);return Number.isSafeInteger(G)?G:null}function _Q(Q){let Z=Q;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let $=Z.indexOf("%");if($!==-1)Z=Z.slice(0,$);if(!Z.includes(":"))return null;let X=Z.split("::");if(X.length>2)return null;let G=(J,D)=>{if(J==="")return[];let z=[],O=J.split(":");for(let B=0;B<O.length;B++){let _=O[B];if(D&&B===O.length-1&&_.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(_))return null;let W=_.split(".").map(Number);if(W.some((V)=>V>255))return null;z.push(W[0]<<8|W[1],W[2]<<8|W[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(_))return null;z.push(parseInt(_,16))}return z},H=G(X[0],X.length===1),Y=X.length===2?G(X[1],!0):[];if(!H||!Y)return null;let M;if(X.length===2){let J=8-H.length-Y.length;if(J<1)return null;M=[...H,...Array.from({length:J},()=>0),...Y]}else M=H;if(M.length!==8)return null;let K=new Uint8Array(16);return M.forEach((J,D)=>{K[D*2]=J>>8,K[D*2+1]=J&255}),K}function M0(Q){let Z=_Q(Q);if(Z)return{family:6,bytes:Z};let $=VZ(Q);if($)return{family:4,bytes:$};return null}function c(Q){if(Q.family===6&&PZ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function PZ(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function J0(Q){if(Q.family===4)return Array.from(Q.bytes).join(".");let Z=[];for(let $=0;$<16;$+=2)Z.push((Q.bytes[$]<<8|Q.bytes[$+1]).toString(16));return Z.join(":")}function o(Q){let Z=Q.lastIndexOf("/"),$=Z===-1?Q:Q.slice(0,Z),X=/^[0-9.]+$/.test($)?jZ($):_Q($);if(!X)return null;let G=c(X.length===4?{family:4,bytes:X}:{family:6,bytes:X}),H=G.family===4?32:128,Y=H;if(Z!==-1){let M=Q.slice(Z+1);if(!/^\d{1,3}$/.test(M))return null;if(Y=Number(M),X.length===16&&G.family===4)Y-=96;if(Y<0||Y>H)return null}return{family:G.family,bytes:G.bytes,prefix:Y}}function jZ(Q){return/^\d{1,3}(\.\d{1,3}){3}$/.test(Q)&&Q.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array(Q.split(".").map(Number)):null}function g(Q,Z){let $=c(Q);if($.family!==Z.family)return!1;let X=Z.prefix;for(let G=0;X>0;G++){let H=Math.min(8,X),Y=255<<8-H&255;if(($.bytes[G]&Y)!==(Z.bytes[G]&Y))return!1;X-=H}return!0}var C=(Q,Z)=>({cidr:o(Q),kind:Z,text:Q}),RZ=[C("0.0.0.0/8","unspecified"),C("10.0.0.0/8","private"),C("100.64.0.0/10","shared"),C("127.0.0.0/8","loopback"),C("169.254.169.254/32","metadata"),C("169.254.0.0/16","link-local"),C("168.63.129.16/32","metadata"),C("172.16.0.0/12","private"),C("192.0.0.0/24","reserved"),C("192.0.2.0/24","documentation"),C("192.88.99.0/24","reserved"),C("192.168.0.0/16","private"),C("198.18.0.0/15","benchmarking"),C("198.51.100.0/24","documentation"),C("203.0.113.0/24","documentation"),C("224.0.0.0/4","multicast"),C("255.255.255.255/32","broadcast"),C("240.0.0.0/4","reserved")],_Z=[C("::/128","unspecified"),C("::1/128","loopback"),C("64:ff9b:1::/48","private"),C("::/8","reserved"),C("100::/64","reserved"),C("2001:db8::/32","documentation"),C("2001::/23","reserved"),C("3fff::/20","documentation"),C("fd00:ec2::254/128","metadata"),C("fc00::/7","unique-local"),C("fe80::/10","link-local"),C("fec0::/10","private"),C("ff00::/8","multicast")],CZ=o("64:ff9b::/96"),LZ=o("2002::/16"),OZ=o("2000::/3");function A0(Q){let Z=typeof Q==="string"?M0(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let $=c(Z);if($.family===4){let G=RZ.find((H)=>g($,H.cidr));return G?{kind:G.kind,range:G.text}:null}if(g($,CZ))return A0({family:4,bytes:$.bytes.slice(12)});if(g($,LZ))return A0({family:4,bytes:$.bytes.slice(2,6)});let X=_Z.find((G)=>g($,G.cidr));if(X)return{kind:X.kind,range:X.text};return g($,OZ)?null:{kind:"reserved",range:"outside 2000::/3"}}function CQ(Q,Z){let $=c(Q),X=c(Z);return $.family===X.family&&$.bytes.every((G,H)=>G===X.bytes[H])}import{lookup as FZ}from"dns/promises";import*as IZ from"http";import*as TZ from"https";import*as t from"zlib";class c0 extends Response{#Q;#Z;address;constructor(Q,Z,$){super(Q,Z);this.#Q=$.url,this.#Z=$.redirected,this.address=$.address}get url(){return this.#Q}get redirected(){return this.#Z}}var W0={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},AZ=new Set([301,302,303,307,308]),NZ=new Set([101,103,204,205,304]),qZ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],wZ=["authorization","cookie","proxy-authorization"];async function FQ(Q,Z={}){let $=EZ(Z),X=Z.signal;X?.throwIfAborted();let G=new AbortController,H=G.signal,Y=String(Q),M=(z)=>{if(!H.aborted)G.abort(z)},K=setTimeout(()=>M(new I0(Y,"total",$.timeout)),$.timeout),J=()=>M(X.reason);X?.addEventListener("abort",J,{once:!0});let D=()=>{clearTimeout(K),X?.removeEventListener("abort",J)};try{let z=OQ(Y,$),O=(Z.method??"GET").toUpperCase(),B=new Headers(Z.headers);for(let W of qZ)B.delete(W);if(!B.has("accept"))B.set("accept","*/*");if(!B.has("user-agent"))B.set("user-agent","gemi");if(!B.has("accept-encoding"))B.set("accept-encoding","gzip, deflate, br");let _=await gZ(O,Z.body,B);for(let W=0;;W++){Y=z.href;let{request:V,response:U,address:P}=await yZ(z,O,B,_,$,H),F=U.statusCode??0,I=U.headers.location;if(AZ.has(F)&&I&&Z.redirect!=="manual"){if(V.destroy(),W>=$.maxRedirects)throw new h0(z.href,$.maxRedirects);let T;try{T=new URL(I,z)}catch{throw new m(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(F===303?O!=="HEAD":(F===301||F===302)&&O==="POST"){O="GET",_=null;let L=[];B.forEach((R,j)=>{if(j.startsWith("content-"))L.push(j)});for(let R of L)B.delete(R)}if(T.origin!==z.origin)for(let L of wZ)B.delete(L);z=OQ(T.href,$);continue}return bZ({url:z,hop:W,method:O,request:V,response:U,address:P,policy:$,signal:H,release:D})}}catch(z){throw D(),H.aborted?H.reason:z}}function EZ(Q){let Z=(X,G)=>{let H={hosts:[],ranges:[]};for(let Y of X){let M=Y.includes("/")||Y.includes(":")||/^[\d.]+$/.test(Y),K=M?o(Y):null;if(K)H.ranges.push(K);else if(!M&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(Y))H.hosts.push(IQ(Y));else throw TypeError(`safeFetch: "${Y}" in ${G} is not a host name or an IP range.`)}return H},$=Q.allowPrivate;return{timeout:Q.timeout??W0.timeout,connectTimeout:Q.connectTimeout??W0.connectTimeout,maxSize:Q.maxSize??W0.maxSize,maxRedirects:Q.maxRedirects??W0.maxRedirects,ports:Q.ports??W0.ports,allow:Q.allow&&Q.allow.length>0?Z(Q.allow,"allow"):null,deny:Z(Q.deny??[],"deny"),allowPrivate:$===!0?!0:Z($||[],"allowPrivate").ranges,contentTypes:Q.contentTypes?.length?Q.contentTypes:null,resolve:Q.resolve??SZ}}async function SZ(Q){return(await FZ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function IQ(Q){return Q.toLowerCase().replace(/\.$/,"")}function LQ(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function OQ(Q,Z){let $;try{$=new URL(Q)}catch{throw new m(Q,"malformed",`"${Q}" is not a URL.`)}if($.protocol!=="http:"&&$.protocol!=="https:")throw new m($.href,"scheme",`Only http and https URLs can be fetched, not ${$.protocol.slice(0,-1)}.`);if($.username||$.password)throw new m($.href,"credentials","The URL has a username or password in it.");let X=TQ($);if(Z.ports!=="any"&&!Z.ports.includes(X))throw new m($.href,"port",`Port ${X} is not allowed.`);return $}function TQ(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function xZ(Q,Z,$){let X=IQ(Q.hostname.replace(/^\[(.*)\]$/,"$1")),G=M0(X),H=G!==null&&(X.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(X));if(!H&&LQ(X,Z.deny.hosts))throw new O0(Q.href,X,"denied");let Y=!H&&Z.allow!==null&&LQ(X,Z.allow.hosts);if(Z.allow&&!Y&&Z.allow.ranges.length===0)throw new O0(Q.href,X,"not-allowed");let M;if(H)M=[G];else{let K;try{K=await kZ(Z.resolve(X),$)}catch(J){if($.aborted)throw $.reason;throw new F0(Q.href,X,J)}if(M=K.map((J)=>M0(J)).filter((J)=>J!==null),M.length===0)throw new F0(Q.href,X)}for(let K of M){let J=J0(K);if(Z.deny.ranges.some((z)=>g(K,z)))throw new i(Q.href,X,J,"denied");if(Z.allow&&!Y&&!Z.allow.ranges.some((z)=>g(K,z)))throw new i(Q.href,X,J,"not-allowed");let D=A0(K);if(D&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((z)=>g(K,z)))throw new i(Q.href,X,J,D.kind)}return{host:X,addresses:M,isLiteral:H}}function kZ(Q,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise(($,X)=>{let G=()=>X(Z.reason);Z.addEventListener("abort",G,{once:!0}),Q.then((H)=>{Z.removeEventListener("abort",G),$(H)},(H)=>{Z.removeEventListener("abort",G),X(H)})})}async function gZ(Q,Z,$){if(Z===void 0||Z===null)return null;if(Q==="GET"||Q==="HEAD")throw TypeError(`safeFetch: a ${Q} request can't have a body.`);let X=new Request("http://body.invalid/",{method:"POST",body:Z}),G=X.headers.get("content-type");if(G&&!$.has("content-type"))$.set("content-type",G);return new Uint8Array(await X.arrayBuffer())}async function yZ(Q,Z,$,X,G,H){let Y=new AbortController,M=setTimeout(()=>Y.abort(new I0(Q.href,"connect",G.connectTimeout)),G.connectTimeout),K=AbortSignal.any([H,Y.signal]);try{let{host:J,addresses:D,isLiteral:z}=await xZ(Q,G,K),O=Q.protocol==="https:",B={};if($.forEach((_,W)=>{B[W]=_}),X)B["content-length"]=String(X.byteLength);return await new Promise((_,W)=>{let V={method:Z,host:J,port:TQ(Q),path:`${Q.pathname}${Q.search}`,headers:B,agent:!1,lookup:(L,R,j)=>{let w=R?.family,A=D.filter((D0)=>!w||D0.family===w);if(A.length===0)j(Object.assign(Error(`No IPv${w} address for ${J}`),{code:"ENOTFOUND"}));else if(R?.all)j(null,A.map((D0)=>({address:J0(D0),family:D0.family})));else j(null,J0(A[0]),A[0].family)}};if(O&&!z)V.servername=J;let U=(O?TZ:IZ).request(V),P=null,F=(L)=>{K.removeEventListener("abort",I),U.destroy(),W(L)},I=()=>F(K.aborted?K.reason:H.reason);K.addEventListener("abort",I,{once:!0});let T=(L)=>{let R=L?.remoteAddress;if(!R||P!==null)return!0;let j=M0(R);if(!j||!D.some((w)=>CQ(w,j)))return F(new i(Q.href,J,R,"not-allowed")),!1;return P=J0(c(j)),!0};U.once("socket",(L)=>{let R=()=>{if(T(L)&&!O)clearTimeout(M)};if(L.connecting)L.once("connect",R);else R();if(O)L.once("secureConnect",()=>clearTimeout(M))}),U.once("response",(L)=>{if(clearTimeout(M),L.on("error",()=>{}),!T(L.socket))return;K.removeEventListener("abort",I),_({request:U,response:L,address:P})}),U.on("error",(L)=>{if(K.aborted)return F(K.reason);F(L instanceof q?L:new n(Q.href,L))}),U.end(X??void 0)})}finally{clearTimeout(M)}}function bZ({url:Q,hop:Z,method:$,request:X,response:G,address:H,policy:Y,signal:M,release:K}){let J=G.statusCode??0;if(J<200||J>599)throw X.destroy(),new n(Q.href,Error(`Unexpected status ${J}`));let D=new Headers,z=G.rawHeaders;for(let R=0;R<z.length;R+=2)D.append(z[R],z[R+1]);if(Y.contentTypes){let R=D.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!R||!Y.contentTypes.some((j)=>fZ(R,j)))throw X.destroy(),new K0(Q.href,R,Y.contentTypes)}let O={url:Q.href,redirected:Z>0,address:H},B={status:J,statusText:G.statusMessage??"",headers:D};if($==="HEAD"||NZ.has(J))return X.destroy(),K(),new c0(null,B,O);let _=D.get("content-encoding")?.trim().toLowerCase(),W=_==="gzip"||_==="x-gzip"?t.createGunzip():_==="deflate"?t.createInflate():_==="br"?t.createBrotliDecompress():null,V=Number(D.get("content-length"));if(!W&&Number.isFinite(V)&&V>Y.maxSize)throw X.destroy(),new T0(Q.href,Y.maxSize);if(W)D.delete("content-encoding"),D.delete("content-length");let U=W?G.pipe(W):G,P=0,F=!1,I=()=>{},T=()=>{F=!0,M.removeEventListener("abort",I),K()},L=new ReadableStream({start(R){let j=(A)=>{if(F)return;if(T(),A===void 0)R.close();else X.destroy(),W?.destroy(),R.error(A)};if(I=()=>j(M.reason),M.addEventListener("abort",I,{once:!0}),M.aborted)return I();U.on("data",(A)=>{if(F)return;if(P+=A.byteLength,P>Y.maxSize)return j(new T0(Q.href,Y.maxSize));if(R.enqueue(new Uint8Array(A)),(R.desiredSize??1)<=0)U.pause()}),U.once("end",()=>j());let w=(A)=>j(A instanceof q?A:new n(Q.href,A));if(U.on("error",w),W)G.on("error",w);G.once("aborted",()=>j(new n(Q.href,Error("The response was cut off."))))},pull(){U.resume()},cancel(){if(F)return;T(),X.destroy(),W?.destroy()}});return new c0(L,B,O)}function fZ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function NQ(Q){return mZ(Q)??pZ(Q)??uZ(Q)}var p0=4096,vZ={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/heic":"heic","image/heif":"heif","image/bmp":"bmp","image/tiff":"tiff","image/x-icon":"ico","image/svg+xml":"svg","audio/mpeg":"mp3","audio/aac":"aac","audio/mp4":"m4a","audio/ogg":"ogg","audio/flac":"flac","audio/wav":"wav","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm","video/x-matroska":"mkv","video/x-msvideo":"avi","font/woff":"woff","font/woff2":"woff2","font/ttf":"ttf","font/otf":"otf","application/pdf":"pdf","application/zip":"zip","application/gzip":"gz","application/xml":"xml","text/html":"html","text/plain":"txt","application/octet-stream":"bin"};function qQ(Q){return vZ[Q]??"bin"}function S(Q,Z,$=0){if(Q.length<$+Z.length)return!1;return Z.every((X,G)=>Q[$+G]===X)}function y(Q,Z,$){return String.fromCharCode(...Q.subarray(Z,$))}var hZ={avif:"image/avif",avis:"image/avif",heic:"image/heic",heix:"image/heic",hevc:"image/heic",hevx:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif","qt ":"video/quicktime","M4A ":"audio/mp4","M4B ":"audio/mp4"};function mZ(Q){if(S(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(S(Q,[255,216,255]))return"image/jpeg";if(Q.length>=6&&(y(Q,0,6)==="GIF87a"||y(Q,0,6)==="GIF89a"))return"image/gif";if(Q.length>=12&&y(Q,0,4)==="RIFF"){let Z=y(Q,8,12);if(Z==="WEBP")return"image/webp";if(Z==="WAVE")return"audio/wav";if(Z==="AVI ")return"video/x-msvideo"}if(Q.length>=12&&y(Q,4,8)==="ftyp"){let Z=y(Q,8,12);return hZ[Z]??"video/mp4"}if(S(Q,[73,73,42,0])||S(Q,[77,77,0,42]))return"image/tiff";if(S(Q,[66,77])&&S(Q,[0,0,0,0],6))return"image/bmp";if(S(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(S(Q,[37,80,68,70,45]))return"application/pdf";if(S(Q,[80,75,3,4]))return"application/zip";if(S(Q,[31,139]))return"application/gzip";if(S(Q,[26,69,223,163]))return y(Q,0,Math.min(Q.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(Q.length>=4){let Z=y(Q,0,4);if(Z==="OggS")return"audio/ogg";if(Z==="fLaC")return"audio/flac";if(Z==="wOFF")return"font/woff";if(Z==="wOF2")return"font/woff2";if(Z==="OTTO")return"font/otf"}if(S(Q,[0,1,0,0,0]))return"font/ttf";if(Q.length>=3&&y(Q,0,3)==="ID3")return"audio/mpeg";if(Q.length>=2&&Q[0]===255){if((Q[1]&246)===240)return"audio/aac";if((Q[1]&224)===224&&(Q[1]&6)!==0)return"audio/mpeg"}return null}var cZ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function pZ(Q){let Z=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(Z.charCodeAt(0)===65279)Z=Z.slice(1);if(Z=Z.trimStart(),!Z.startsWith("<"))return null;let $=Z.toLowerCase(),X=$;for(;;){X=X.trimStart();let G=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(X);if(!G)break;X=X.slice(G[0].length)}if(/^<svg[\s>/]/.test(X))return"image/svg+xml";for(let G of cZ){if(!$.startsWith(`<${G}`))continue;if(/^[\s>]/.test($.charAt(G.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(X))return"text/html";if($.startsWith("<?xml"))return"application/xml";return null}function uZ(Q){if(Q.length===0)return"application/octet-stream";for(let Z of Q)if(Z<32&&Z!==9&&Z!==10&&Z!==12&&Z!==13&&Z!==27)return"application/octet-stream";try{return new TextDecoder("utf-8",{fatal:!0}).decode(Q,{stream:!0}),"text/plain"}catch{return"application/octet-stream"}}var dZ=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function AQ(Q){let Z=Q.split(";")[0].trim().toLowerCase();return dZ.has(Z)||Z.endsWith("+xml")}function wQ(Q,Z){let $=Q.split(";")[0].trim().toLowerCase();return Z.some((X)=>{let G=X.split(";")[0].trim().toLowerCase();if(G==="*/*"||G==="*")return!AQ($);if(G.endsWith("/*"))return $.startsWith(G.slice(0,-1))&&!AQ($);return $===G})}import{Buffer as nZ}from"buffer";async function EQ(Q){try{return(await import("sharp")).default}catch(Z){throw Error(`${Q} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Z})}}async function SQ(Q,Z,$={}){let{name:X,directory:G,bucket:H,maxSize:Y,timeout:M,contentTypes:K,signal:J}=$;if(X!==void 0&&G!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(X!==void 0&&!X)throw TypeError("Storage.putFromUrl(): `name` is empty.");let D=await FQ(Z,{...$.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:J,timeout:M,maxSize:Y});if(!D.ok)throw await D.body?.cancel().catch(()=>{}),new m0(D.url,D.status);let z=(D.body??new Response(new Uint8Array).body).getReader(),O=async(j)=>{throw await z.cancel(j).catch(()=>{}),j},B=[],_=0,W=!1;while(_<p0){let{done:j,value:w}=await z.read();if(j){W=!0;break}B.push(w),_+=w.byteLength}let V=iZ(B,_),U=NQ(V.subarray(0,Math.min(_,p0))),P=K?.length?K:["*/*"];if(!wQ(U,P))await O(new K0(D.url,U,P));let F=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${qQ(U)}`].filter(Boolean).join("/"),I=_,T=new ReadableStream({start(j){if(_>0)j.enqueue(V);if(W)j.close()},async pull(j){let{done:w,value:A}=await z.read();if(w){j.close();return}I+=A.byteLength,j.enqueue(A)},cancel(j){return z.cancel(j)}}),L={name:F,bucket:H,body:T,contentType:U},R;try{R=Q.putStream?await Q.putStream(L,{signal:J}):await G0.prototype.putStream.call(Q,L,{signal:J})}catch(j){throw await O(j),j}return{name:R,contentType:U,size:I,url:D.url}}function iZ(Q,Z){if(Q.length===1)return Q[0];let $=new Uint8Array(Z),X=0;for(let G of Q)$.set(G,X),X+=G.byteLength;return $}class oZ extends X0{static getFacadeAccessor(){return v0}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return SQ(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=nZ.from(await Q.arrayBuffer()),$=await EQ("Storage.metadata()");try{return await $(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){return Z.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(Q,Z)}static async read(Q,Z={}){let $=typeof Q==="string"?{name:Q}:{...Q},X="range"in Z?Z.range??null:$.range!==void 0?$.range:b.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...$,range:X})}static list(Q){return this.getFacadeRoot().driver.list(Q)}static objects(Q,Z={}){return this.getFacadeRoot().driver.objects(Q,Z)}static async deletePrefix(Q,Z={}){return this.getFacadeRoot().driver.deletePrefix(Q,Z)}static async delete(Q){return this.getFacadeRoot().driver.delete(Q)}}import{mkdir as d0,readdir as aZ,access as eZ}from"fs/promises";var u0=["debug","info","notice","warning","error","critical","alert","emergency"],tZ=u0.indexOf("warning");function kQ(Q){if(!Q)return-1;if(Q===!0)return 0;let Z=u0.indexOf(Q);return Z===-1?0:Z}function sZ(){let Q=new WeakSet;return function(Z,$){if(typeof $==="bigint")return $.toString();if($ instanceof Error){let X={name:$.name,message:$.message,stack:$.stack};for(let G of Object.keys($))X[G]=$[G];if($.cause!==void 0)X.cause=$.cause;return X}if($!==null&&typeof $==="object"){if(Q.has($))return"[Circular]";Q.add($)}return $}}function xQ(Q){try{return JSON.stringify(Q,sZ())}catch{return'"[Unserializable]"'}}function rZ(Q,Z){if(Z==="json")return xQ({...Q.metadata,timestamp:Q.timestamp,level:Q.level,message:Q.message});let $=Object.keys(Q.metadata).length>0;return`${Q.timestamp} ${Q.level.toUpperCase()} ${Q.message}${$?` ${xQ(Q.metadata)}`:""}`}function gQ(Q,Z){let $=u0.indexOf(Q.level);if(Z.threshold===-1||$<Z.threshold)return;try{let X=rZ(Q,Z.format)+`
|
|
5
|
-
`;if($>=tZ)process.stderr.write(X);else process.stdout.write(X)}catch{}}async function l0(Q){try{return await eZ(Q),!0}catch{return!1}}class i0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${Y0()}/storage/logs`}consoleThreshold;constructor(Q){this.config=Q;this.consoleThreshold=kQ(Q.console)}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((Q)=>{console.error("Log storage unavailable, file logging disabled",Q)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let Q=`${Y0()}/storage`;if(!await l0(Q))await d0(Q);if(!await l0(this.logsDirPath))await d0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await l0(this.logsDirPath))await d0(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let $=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed($),this.fileSize=0,this.writerSize=0}let Z=(await aZ(this.logsDirPath)).sort().reverse()[0];if(Z){let $=Bun.file(`${this.logsDirPath}/${Z}`);if($.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Z}`,this.writer=$.writer(),this.writer.write(await $.text()),this.writer.write(`
|
|
6
|
-
`),this.writer.flush(),this.fileSize=$.size}if(!this.writer){let $=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${$}`;let X=Bun.file(`${this.logsDirPath}/${$}`);this.writer=X.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(Q,Z,$={}){if(!this.isReady)await this.boot();let X=b.getStore(),G={},H={};if(X)H={method:X.req.rawRequest.method,path:new URL(X.req.rawRequest.url).pathname},G={url:X.req.rawRequest.url,method:X.req.rawRequest.method,headers:X.req.rawRequest.headers,body:X.req.rawRequest.body};let Y={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:Q,message:Z,metadata:{...G,...$}};if(this.consoleThreshold!==-1)gQ({timestamp:Y.timestamp,level:Q,message:Z,metadata:{...H,...$}},{threshold:this.consoleThreshold,format:this.config.consoleFormat});let M="";try{M=JSON.stringify(Y)}catch(K){console.log("Error parsing log object",K)}try{let K=this.config.onLogCreated(Y);if(K instanceof Promise)K.catch((J)=>console.error("Error in onLogCreated",J))}catch(K){console.error("Error in onLogCreated",K)}if(!this.writer)return;this.writerSize+=M.length,this.fileSize+=M.length;try{this.writer.write(M),this.writer.write(`
|
|
7
|
-
`),this.tryFlush()}catch(K){console.error("Error writing log",K)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class Q1 extends X0{static getFacadeAccessor(){return i0}static debug(Q,Z){this.getFacadeRoot().log("debug",Q,Z)}static info(Q,Z){this.getFacadeRoot().log("info",Q,Z)}static notice(Q,Z){this.getFacadeRoot().log("notice",Q,Z)}static warning(Q,Z){this.getFacadeRoot().log("warning",Q,Z)}static error(Q,Z){this.getFacadeRoot().log("error",Q,Z)}static critical(Q,Z){this.getFacadeRoot().log("critical",Q,Z)}static alert(Q,Z){this.getFacadeRoot().log("alert",Q,Z)}static emergency(Q,Z){this.getFacadeRoot().log("emergency",Q,Z)}}class Z1{config;static token="redis";instance=null;connectingSince=null;downSince=null;replaceDelay=500;constructor(Q={}){this.config=Q}get client(){if(this.instance===null)return this.build();let Q=this.instance;if(this.isDown(Q,Date.now())){this.instance=null;try{Q.close()}catch{}return this.build()}return Q}set client(Q){this.instance=Q,this.connectingSince=null,this.downSince=null,this.replaceDelay=500}close(){let Q=this.instance;this.instance=null,this.connectingSince=null,this.downSince=null,this.replaceDelay=500,Q?.close()}build(){let Q=new($1())(this.config.url,this.config.options);if(this.instance=Q,this.downSince=null,this.connectingSince=null,typeof Q.connect==="function"){this.connectingSince=Date.now();let Z;try{Z=Promise.resolve(Q.connect())}catch($){Z=Promise.reject($)}Z.then(()=>{if(this.instance!==Q)return;this.connectingSince=null,this.replaceDelay=500},()=>{if(this.instance!==Q)return;this.connectingSince=null})}return Q}isDown(Q,Z){if(Q.connected!==!1||typeof Q.connect!=="function")return this.downSince=null,!1;if(this.connectingSince!==null){let $=(this.config.options?.connectionTimeout??1e4)+5000;if(Z-this.connectingSince<$)return!1;this.connectingSince=null}if(this.downSince??=Z,Z-this.downSince<this.replaceDelay)return!1;return this.replaceDelay=Math.min(this.replaceDelay*2,1e4),!0}}function $1(){let Q=globalThis.Bun?.RedisClient;if(typeof Q!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return Q}var n0=new TextEncoder;function yQ(Q){return`id: ${Q.seq}
|
|
8
|
-
data: ${JSON.stringify(Q.event)}
|
|
9
|
-
|
|
10
|
-
`}var X1=5000,G1=`: keepalive
|
|
11
|
-
|
|
12
|
-
`;function H1(Q,Z=X1){let $=null,X=!1,G=()=>{if(X)return;if($!==null)clearTimeout($);$=setTimeout(()=>{if($=null,X)return;try{Q.enqueue(n0.encode(G1))}catch{H();return}G()},Z)},H=()=>{if(X=!0,$!==null)clearTimeout($);$=null};return G(),{touch:G,stop:H}}function Y1(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function m8(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,H=new ReadableStream({start(Y){G=H1(Y)},async pull(Y){try{let M=await $.next();if(M.done){G.stop(),Y.close();return}X=M.value.seq,Y.enqueue(n0.encode(yQ(M.value))),G.touch()}catch(M){let K={type:"error",error:M1(M)};G.stop(),Y.enqueue(n0.encode(yQ({seq:X+1,event:K}))),Y.close()}},cancel(Y){G.stop(),$.return?.(Y)}});return new Response(H,{status:Z,headers:Y1()})}var K1=new Set(["frame_cursor_evicted","live_run_not_found"]);function M1(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&K1.has(Z))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}
|
|
13
|
-
export{o0 as Fh,bQ as Gh,W1 as Hh,YQ as Ih,F1 as Jh,JQ as Kh,I1 as Lh,t0 as Mh,s0 as Nh,z1 as Oh,U1 as Ph,V1 as Qh,r0 as Rh,A1 as Sh,zQ as Th,N1 as Uh,q1 as Vh,s as Wh,k as Xh,$Q as Yh,HQ as Zh,_1 as _h,C1 as $h,XZ as ai,GZ as bi,k0 as ci,g0 as di,HZ as ei,h as fi,YZ as gi,X0 as hi,EQ as ii,L0 as ji,G0 as ki,PQ as li,f0 as mi,Y8 as ni,RQ as oi,v0 as pi,q as qi,m as ri,O0 as si,i as ti,F0 as ui,I0 as vi,T0 as wi,K0 as xi,h0 as yi,n as zi,m0 as Ai,A0 as Bi,c0 as Ci,FQ as Di,NQ as Ei,AQ as Fi,oZ as Gi,i0 as Hi,Q1 as Ii,Z1 as Ji,G1 as Ki,H1 as Li,Y1 as Mi,m8 as Ni};
|
|
14
|
-
|
|
15
|
-
//# debugId=46597C20CE18EC4964756E2164756E21
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|