gemi 0.187.0 → 0.188.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/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-wd3eyjbj.js → chunk-07mvnzgx.js} +3 -3
- package/dist/{chunk-wd3eyjbj.js.map → chunk-07mvnzgx.js.map} +1 -1
- package/dist/{chunk-jg1n0b5e.js → chunk-0sjz2g5b.js} +2 -2
- package/dist/{chunk-jg1n0b5e.js.map → chunk-0sjz2g5b.js.map} +1 -1
- package/dist/{chunk-pcc8v9jc.js → chunk-0t5mex63.js} +2 -2
- package/dist/{chunk-pcc8v9jc.js.map → chunk-0t5mex63.js.map} +1 -1
- package/dist/{chunk-n2vx8eqm.js → chunk-1mg3x0j0.js} +2 -2
- package/dist/{chunk-n2vx8eqm.js.map → chunk-1mg3x0j0.js.map} +1 -1
- package/dist/{chunk-8nxrgzxp.js → chunk-1p7p76er.js} +2 -2
- package/dist/{chunk-8nxrgzxp.js.map → chunk-1p7p76er.js.map} +1 -1
- package/dist/{chunk-5yj3k754.js → chunk-24vv42t6.js} +3 -3
- package/dist/{chunk-5yj3k754.js.map → chunk-24vv42t6.js.map} +1 -1
- package/dist/{chunk-nd2vajx0.js → chunk-2tfafjmk.js} +2 -2
- package/dist/{chunk-nd2vajx0.js.map → chunk-2tfafjmk.js.map} +1 -1
- package/dist/{chunk-x0vrrfp7.js → chunk-3kd3w33a.js} +2 -2
- package/dist/{chunk-x0vrrfp7.js.map → chunk-3kd3w33a.js.map} +1 -1
- package/dist/{chunk-nchyjgpr.js → chunk-4x22y92r.js} +2 -2
- package/dist/{chunk-nchyjgpr.js.map → chunk-4x22y92r.js.map} +1 -1
- package/dist/chunk-4xpcx3ws.js +15 -0
- package/dist/{chunk-9caq1znh.js.map → chunk-4xpcx3ws.js.map} +7 -6
- package/dist/{chunk-s5p7pd7v.js → chunk-4xtefwwa.js} +2 -2
- package/dist/{chunk-s5p7pd7v.js.map → chunk-4xtefwwa.js.map} +1 -1
- package/dist/{chunk-ttcmvam5.js → chunk-4zwnmk3c.js} +2 -2
- package/dist/{chunk-ttcmvam5.js.map → chunk-4zwnmk3c.js.map} +1 -1
- package/dist/{chunk-1x1je71f.js → chunk-5zgkh1xp.js} +2 -2
- package/dist/{chunk-1x1je71f.js.map → chunk-5zgkh1xp.js.map} +1 -1
- package/dist/{chunk-6cq83t7e.js → chunk-6dtq4h9p.js} +2 -2
- package/dist/{chunk-6cq83t7e.js.map → chunk-6dtq4h9p.js.map} +1 -1
- package/dist/{chunk-1ecvjvbg.js → chunk-6s6cek6k.js} +2 -2
- package/dist/{chunk-1ecvjvbg.js.map → chunk-6s6cek6k.js.map} +1 -1
- package/dist/{chunk-9sv8skzh.js → chunk-74n9paen.js} +2 -2
- package/dist/{chunk-9sv8skzh.js.map → chunk-74n9paen.js.map} +1 -1
- package/dist/{chunk-epmtvd6j.js → chunk-7s6gdgwx.js} +2 -2
- package/dist/{chunk-epmtvd6j.js.map → chunk-7s6gdgwx.js.map} +1 -1
- package/dist/{chunk-cgxk8pn8.js → chunk-80cwastb.js} +3 -3
- package/dist/{chunk-cgxk8pn8.js.map → chunk-80cwastb.js.map} +1 -1
- package/dist/{chunk-0jbwxas3.js → chunk-88508q02.js} +2 -2
- package/dist/{chunk-0jbwxas3.js.map → chunk-88508q02.js.map} +1 -1
- package/dist/{chunk-2pj5e233.js → chunk-8a72czrb.js} +3 -3
- package/dist/{chunk-2pj5e233.js.map → chunk-8a72czrb.js.map} +1 -1
- package/dist/{chunk-n7nx6hby.js → chunk-8bp5s118.js} +4 -4
- package/dist/{chunk-n7nx6hby.js.map → chunk-8bp5s118.js.map} +1 -1
- package/dist/{chunk-xa2k8dm0.js → chunk-9ep490s9.js} +2 -2
- package/dist/{chunk-xa2k8dm0.js.map → chunk-9ep490s9.js.map} +1 -1
- package/dist/{chunk-gap8ta5q.js → chunk-attv9byj.js} +2 -2
- package/dist/{chunk-gap8ta5q.js.map → chunk-attv9byj.js.map} +1 -1
- package/dist/{chunk-2757n2e2.js → chunk-babcg0fq.js} +2 -2
- package/dist/{chunk-2757n2e2.js.map → chunk-babcg0fq.js.map} +1 -1
- package/dist/{chunk-gpsqtjx5.js → chunk-bmckdsec.js} +1 -1
- package/dist/{chunk-3cmm9atm.js → chunk-bwh1n2cj.js} +2 -2
- package/dist/{chunk-3cmm9atm.js.map → chunk-bwh1n2cj.js.map} +1 -1
- package/dist/{chunk-y4yv9e31.js → chunk-cbjjg80m.js} +1 -1
- package/dist/{chunk-s52ecbdd.js → chunk-cbp8xrsn.js} +2 -2
- package/dist/{chunk-s52ecbdd.js.map → chunk-cbp8xrsn.js.map} +1 -1
- package/dist/{chunk-nwafkabk.js → chunk-cr37wx3s.js} +2 -2
- package/dist/{chunk-nwafkabk.js.map → chunk-cr37wx3s.js.map} +1 -1
- package/dist/{chunk-d19x7t1z.js → chunk-cr9rd0v4.js} +2 -2
- package/dist/{chunk-d19x7t1z.js.map → chunk-cr9rd0v4.js.map} +1 -1
- package/dist/{chunk-sg8fcsvn.js → chunk-czw7kqtp.js} +2 -2
- package/dist/{chunk-sg8fcsvn.js.map → chunk-czw7kqtp.js.map} +1 -1
- package/dist/{chunk-kgsmh0v0.js → chunk-dm61gz7e.js} +2 -2
- package/dist/{chunk-kgsmh0v0.js.map → chunk-dm61gz7e.js.map} +1 -1
- package/dist/{chunk-5q2v29ma.js → chunk-e6k0024c.js} +1 -1
- package/dist/{chunk-znnt70rn.js → chunk-edj701p0.js} +3 -3
- package/dist/{chunk-znnt70rn.js.map → chunk-edj701p0.js.map} +1 -1
- package/dist/{chunk-aezj1erg.js → chunk-fg1mpyp9.js} +2 -2
- package/dist/{chunk-aezj1erg.js.map → chunk-fg1mpyp9.js.map} +1 -1
- package/dist/{chunk-hc58rnwq.js → chunk-gcjjwgnt.js} +2 -2
- package/dist/{chunk-hc58rnwq.js.map → chunk-gcjjwgnt.js.map} +1 -1
- package/dist/{chunk-yn2v5axb.js → chunk-gtbjdx8d.js} +2 -2
- package/dist/{chunk-yn2v5axb.js.map → chunk-gtbjdx8d.js.map} +1 -1
- package/dist/chunk-h3jxnd65.js +5 -0
- package/dist/{chunk-ghf4kgs6.js.map → chunk-h3jxnd65.js.map} +1 -1
- package/dist/{chunk-q7nz3b4q.js → chunk-jmgjhfya.js} +2 -2
- package/dist/{chunk-q7nz3b4q.js.map → chunk-jmgjhfya.js.map} +1 -1
- package/dist/{chunk-m62jshaz.js → chunk-jsbq8qq0.js} +3 -3
- package/dist/{chunk-m62jshaz.js.map → chunk-jsbq8qq0.js.map} +1 -1
- package/dist/{chunk-ascbx2kb.js → chunk-k4c0q1za.js} +1 -1
- package/dist/{chunk-gw9sy16b.js → chunk-kcgbb7cd.js} +2 -2
- package/dist/{chunk-gw9sy16b.js.map → chunk-kcgbb7cd.js.map} +1 -1
- package/dist/{chunk-9by5yphc.js → chunk-kjtq7vk3.js} +1 -1
- package/dist/{chunk-5sc7j1g0.js → chunk-kkymwxt2.js} +2 -2
- package/dist/{chunk-5sc7j1g0.js.map → chunk-kkymwxt2.js.map} +1 -1
- package/dist/{chunk-v7e5gv6w.js → chunk-ktgmrjj3.js} +2 -2
- package/dist/{chunk-v7e5gv6w.js.map → chunk-ktgmrjj3.js.map} +1 -1
- package/dist/{chunk-3yzmzcxn.js → chunk-kzny5cj2.js} +2 -2
- package/dist/{chunk-3yzmzcxn.js.map → chunk-kzny5cj2.js.map} +1 -1
- package/dist/{chunk-kqwenh9b.js → chunk-m8y3y6sw.js} +2 -2
- package/dist/{chunk-kqwenh9b.js.map → chunk-m8y3y6sw.js.map} +1 -1
- package/dist/{chunk-4e99zzkt.js → chunk-ma2sders.js} +2 -2
- package/dist/{chunk-4e99zzkt.js.map → chunk-ma2sders.js.map} +1 -1
- package/dist/{chunk-tns989kw.js → chunk-mx4z8c6r.js} +2 -2
- package/dist/{chunk-tns989kw.js.map → chunk-mx4z8c6r.js.map} +1 -1
- package/dist/{chunk-xf515fp7.js → chunk-n0mjy9ep.js} +2 -2
- package/dist/{chunk-xf515fp7.js.map → chunk-n0mjy9ep.js.map} +1 -1
- package/dist/{chunk-jqdqpdss.js → chunk-n1b6r6s9.js} +2 -2
- package/dist/{chunk-jqdqpdss.js.map → chunk-n1b6r6s9.js.map} +1 -1
- package/dist/{chunk-rztf3yam.js → chunk-n28c9xjp.js} +2 -2
- package/dist/{chunk-rztf3yam.js.map → chunk-n28c9xjp.js.map} +1 -1
- package/dist/{chunk-y8c704wp.js → chunk-nbfzyvav.js} +2 -2
- package/dist/{chunk-y8c704wp.js.map → chunk-nbfzyvav.js.map} +1 -1
- package/dist/{chunk-2ys56r3z.js → chunk-p9rf0e8r.js} +2 -2
- package/dist/{chunk-2ys56r3z.js.map → chunk-p9rf0e8r.js.map} +1 -1
- package/dist/{chunk-28xqs354.js → chunk-pchb1awj.js} +2 -2
- package/dist/{chunk-28xqs354.js.map → chunk-pchb1awj.js.map} +1 -1
- package/dist/{chunk-bf88yh7q.js → chunk-ph793v5g.js} +2 -2
- package/dist/{chunk-bf88yh7q.js.map → chunk-ph793v5g.js.map} +1 -1
- package/dist/{chunk-2a4q9t8c.js → chunk-q8zhfe2s.js} +2 -2
- package/dist/{chunk-2a4q9t8c.js.map → chunk-q8zhfe2s.js.map} +1 -1
- package/dist/{chunk-jx8n3w5j.js → chunk-q9b0ndf0.js} +3 -3
- package/dist/{chunk-jx8n3w5j.js.map → chunk-q9b0ndf0.js.map} +1 -1
- package/dist/{chunk-qj138p8j.js → chunk-r5cddkyc.js} +2 -2
- package/dist/{chunk-qj138p8j.js.map → chunk-r5cddkyc.js.map} +1 -1
- package/dist/{chunk-x0983cez.js → chunk-sbhpdhwc.js} +2 -2
- package/dist/{chunk-x0983cez.js.map → chunk-sbhpdhwc.js.map} +1 -1
- package/dist/{chunk-3t37a4e5.js → chunk-scscdtd6.js} +2 -2
- package/dist/{chunk-3t37a4e5.js.map → chunk-scscdtd6.js.map} +1 -1
- package/dist/{chunk-bw2ptzxr.js → chunk-t201nja2.js} +2 -2
- package/dist/{chunk-bw2ptzxr.js.map → chunk-t201nja2.js.map} +1 -1
- package/dist/{chunk-b3e27j6t.js → chunk-tfvdrvbn.js} +2 -2
- package/dist/{chunk-b3e27j6t.js.map → chunk-tfvdrvbn.js.map} +1 -1
- package/dist/{chunk-7pes8axs.js → chunk-v6ewt7tc.js} +2 -2
- package/dist/{chunk-7pes8axs.js.map → chunk-v6ewt7tc.js.map} +1 -1
- package/dist/{chunk-tnqvxzbw.js → chunk-vmax8gjr.js} +2 -2
- package/dist/{chunk-tnqvxzbw.js.map → chunk-vmax8gjr.js.map} +1 -1
- package/dist/{chunk-0bzcxgks.js → chunk-vpms0v5m.js} +3 -3
- package/dist/{chunk-0bzcxgks.js.map → chunk-vpms0v5m.js.map} +1 -1
- package/dist/{chunk-twn4yxsd.js → chunk-vqrqzfyw.js} +2 -2
- package/dist/{chunk-twn4yxsd.js.map → chunk-vqrqzfyw.js.map} +1 -1
- package/dist/{chunk-c3rn99hm.js → chunk-vyqk7de0.js} +1 -1
- package/dist/{chunk-zdwgcyjh.js → chunk-wk84z25h.js} +2 -2
- package/dist/{chunk-zdwgcyjh.js.map → chunk-wk84z25h.js.map} +1 -1
- package/dist/{chunk-dwt3p2aw.js → chunk-yp4rbknt.js} +2 -2
- package/dist/{chunk-dwt3p2aw.js.map → chunk-yp4rbknt.js.map} +1 -1
- package/dist/{chunk-rsnm21vr.js → chunk-yqf1k3kb.js} +3 -3
- package/dist/{chunk-rsnm21vr.js.map → chunk-yqf1k3kb.js.map} +1 -1
- package/dist/{chunk-kj6wqkjc.js → chunk-zck41hz4.js} +4 -4
- package/dist/{chunk-kj6wqkjc.js.map → chunk-zck41hz4.js.map} +1 -1
- package/dist/{chunk-6m5rt6xg.js → chunk-zjr8kgbg.js} +2 -2
- package/dist/{chunk-6m5rt6xg.js.map → chunk-zjr8kgbg.js.map} +1 -1
- package/dist/{chunk-10sbvn36.js → chunk-zqcaqwey.js} +2 -2
- package/dist/{chunk-10sbvn36.js.map → chunk-zqcaqwey.js.map} +1 -1
- package/dist/{chunk-eeqfp05r.js → chunk-zrndnz4n.js} +2 -2
- package/dist/{chunk-eeqfp05r.js.map → chunk-zrndnz4n.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/Storage.d.ts +6 -0
- package/dist/facades/Storage.d.ts.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/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/file-storage/FilesystemManager.d.ts +4 -0
- package/dist/services/file-storage/FilesystemManager.d.ts.map +1 -1
- package/dist/services/file-storage/config.d.ts +16 -0
- package/dist/services/file-storage/config.d.ts.map +1 -1
- package/dist/services/file-storage/fetchTimeouts.d.ts +41 -0
- package/dist/services/file-storage/fetchTimeouts.d.ts.map +1 -0
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.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-9caq1znh.js +0 -15
- package/dist/chunk-ghf4kgs6.js +0 -5
- /package/dist/{chunk-gpsqtjx5.js.map → chunk-bmckdsec.js.map} +0 -0
- /package/dist/{chunk-y4yv9e31.js.map → chunk-cbjjg80m.js.map} +0 -0
- /package/dist/{chunk-5q2v29ma.js.map → chunk-e6k0024c.js.map} +0 -0
- /package/dist/{chunk-ascbx2kb.js.map → chunk-k4c0q1za.js.map} +0 -0
- /package/dist/{chunk-9by5yphc.js.map → chunk-kjtq7vk3.js.map} +0 -0
- /package/dist/{chunk-c3rn99hm.js.map → chunk-vyqk7de0.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Od as R}from"./chunk-bm3pyh9m.js";import{Vd as Q,ce as S,he as E}from"./chunk-
|
|
2
|
+
import{Od as R}from"./chunk-bm3pyh9m.js";import{Vd as Q,ce as S,he as E}from"./chunk-attv9byj.js";import{ml as K}from"./chunk-edj701p0.js";import{Dl as A,El as $,Fl as D}from"./chunk-mx4z8c6r.js";class j extends Error{code;constructor(q,z=1){super(q);this.code=z;this.name="CommandFailed"}}class J{static commandName="unset";static description="";static args=[];static options=[];run(q){}}function p(q){return q}function C(){return{commands:[],commandsDir:"app/commands"}}var I=Symbol.for("gemi.console.builder");function k(q){if(q.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(q)||/\s/.test(q))throw Error(`Invalid command name ${JSON.stringify(q)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
|
|
3
3
|
|
|
4
4
|
defineCommand("mail:send")
|
|
5
5
|
.arg("user", { required: true })
|
|
@@ -16,4 +16,4 @@ import{Od as R}from"./chunk-bm3pyh9m.js";import{Vd as Q,ce as S,he as E}from"./c
|
|
|
16
16
|
If this is an abstract base its subclasses extend, move it out of the `+"listeners directory \u2014 the walk excludes gemi's `Listener` and "+"nothing else, so a base sitting beside its subclasses is registered and run like one of them.")}function v(q){for(let z of q){if(Object.getOwnPropertyDescriptor(z,"name")?.writable)continue;console.warn(`Event listener ${z.name} does not declare \`static name\`, so it is registered under its class name, which a production build renames. Nothing reads that name across a build boundary while the `+"listener is sync, which is why this is a warning \u2014 but adding "+`\`queued = true\` to it is refused at boot for the same reason, because the queue's key is that string. Add: static name = "${z.name}";`)}}function u(q){let z=new Set;for(let{event:F}of q){if(z.has(F))continue;if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;z.add(F),console.warn(`Event ${F.name} does not declare \`static name\`, so it is dispatched under its class name. A production build minifies the code that dispatches it and renames the class, while discovery reads `+"the listener's copy from source and does not \u2014 so the dispatch would "+`reach no listener in production and nowhere else. Add: static name = "${F.name}";`)}}
|
|
17
17
|
export{j as yd,J as zd,p as Ad,C as Bd,c as Cd,o as Dd,T as Ed,i as Fd,B as Gd,U as Hd,W as Id,Sq as Jd,Zq as Kd,_q as Ld,Iq as Md,Uq as Nd};
|
|
18
18
|
|
|
19
|
-
//# debugId=
|
|
19
|
+
//# debugId=124C491D13F36AA864756E2164756E21
|
|
@@ -12,6 +12,6 @@
|
|
|
12
12
|
"import { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nimport {\n discoverClasses,\n DiscoveryError,\n projectRoot,\n} from \"../support/discover\";\nimport { Command, type CommandClass } from \"../console/Command\";\nimport { commandConfigDefaults } from \"../console/config\";\nimport { isUnfinishedBuilder } from \"../console/builder\";\nimport { CronJob } from \"./cron/CronJob\";\nimport { scheduleConfigDefaults } from \"./cron/config\";\nimport { eventConfigDefaults } from \"./events/config\";\nimport type { EventClass } from \"./events/Event\";\nimport { Listener, type ListenerClass } from \"./events/Listener\";\nimport { Job } from \"./queue/Job\";\nimport { queueConfigDefaults } from \"./queue/config\";\nimport { Workflow, type WorkflowClass } from \"./queue/workflow/Workflow\";\n\n/**\n * Reading an application's jobs off the filesystem, for the two subsystems that\n * were asking every app to write its job list twice.\n *\n * Both functions here are the same call to `discoverClasses` with a different\n * base class, which is deliberate: one walk, one set of skip rules, one answer\n * to \"what does this app have\". They are exported from `gemi/services` rather\n * than kept private to the providers because the list stopped being something\n * an app could import — a test that used to walk the exported `jobs` array\n * needs somewhere to ask the same question, and so does a script.\n *\n * What the providers add on top of these is the decision of *whether* to ask,\n * which is the config's to make and not this file's.\n */\n\n/**\n * A directory the app named, resolved the way the app meant it.\n *\n * Relative paths hang off the project root rather than `process.cwd()` at the\n * moment of the call, because a config slice saying `app/jobs` means the app's\n * `app/jobs` and not whatever directory somebody happened to launch a script\n * from. Absolute paths are taken as given, which is what makes these callable\n * from a test that has no project around it.\n */\nfunction resolveDir(dir: string): string {\n return isAbsolute(dir) ? dir : join(projectRoot(), dir);\n}\n\n/**\n * Says something when the directory is missing *and so is the tree it lives in*.\n *\n * A missing directory has two readings and they want opposite responses. An app\n * that has never written a cron job has no `app/cron`, and warning about that on\n * every boot for the rest of its life is noise — the answer \"you have no cron\n * jobs\" is correct and uninteresting. But a deploy that ships `dist/` and\n * `node_modules/` without the source has no `app/cron` *and no `app/`*, and\n * there discovery quietly returns nothing while the app very much does have\n * jobs: the exact silence #322 and #323 exist to remove, reintroduced one layer\n * down and in production only.\n *\n * The parent directory is what tells them apart. If neither the directory nor\n * the one above it is there, the tree this was pointed into is not there\n * either, and that is worth a sentence.\n */\nfunction warnIfSourceIsMissing(\n resolved: string,\n subject: string,\n slice: string,\n) {\n if (existsSync(resolved) || existsSync(dirname(resolved))) return;\n\n console.warn(\n `No ${subject} were discovered: neither ${resolved} nor the directory ` +\n `above it exists, so this process cannot see the application's source. ` +\n `If this is a deploy that ships only the build output, list the classes ` +\n `explicitly in app/config/${slice}.ts so they travel with it.`,\n );\n}\n\n/**\n * The `Job` subclasses under `dir`, defaulting to the config slice's `app/jobs`.\n *\n * This is what a `queue` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array:\n * every job this application would register, in the order it would register\n * them.\n *\n * Every file underneath is imported, so calling this runs the app's job modules\n * — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverJobs(\n dir: string = queueConfigDefaults().jobsDir,\n): Promise<Array<new () => Job>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"queue jobs\", \"queue\");\n const jobs = await discoverClasses(resolved, Job);\n warnIfNameWillNotSurviveTheBuild(jobs);\n return jobs;\n}\n\n/**\n * The `Workflow` subclasses under `dir`, defaulting to the queue slice's\n * `app/workflows`: what a `queue` slice with no `workflows` key resolves to.\n * A missing directory is no workflows, said nothing about unless the tree\n * above it is missing too.\n */\nexport async function discoverWorkflows(\n dir: string = queueConfigDefaults().workflowsDir,\n): Promise<WorkflowClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"workflows\", \"queue\");\n const workflows = (await discoverClasses(resolved, Workflow)) as WorkflowClass[];\n for (const workflow of workflows) {\n if (Object.getOwnPropertyDescriptor(workflow, \"name\")?.writable) continue;\n console.warn(\n `Workflow ${workflow.name} does not declare \\`static name\\`. A workflow ` +\n `is stored under its name, and a production build renames the class. ` +\n `Add: static name = \"${workflow.name}\";`,\n );\n }\n return workflows;\n}\n\n/**\n * Says something about a discovered job that never declared `static name`.\n *\n * This is the one hazard discovery introduces rather than removes, and it is\n * production-only. `gemi build` minifies the server entry, and app code\n * reachable from it — a controller, and every job class that controller\n * imports to dispatch — is bundled and minified with it. Minification renames\n * the class binding, and a class's implicit `.name` is that binding: a\n * `TestJob` in the bundle reports `\"D\"`. Discovery, meanwhile, imports\n * `app/jobs/TestJob.ts` from source at runtime, where it is still `\"TestJob\"`.\n * The queue is keyed by that name, so the two halves stop agreeing and the\n * dispatch is dropped — in production, and only there.\n *\n * A declared `static name = \"TestJob\"` is a string literal, which survives\n * minification intact, and the two halves agree again. `docs/jobs-and-queues.md`\n * has always called it required; before discovery an app could get away without\n * it, because the explicit `jobs` array was bundled too and both sides were\n * wrong in the same way.\n *\n * The check is exact rather than a guess: a `static name = \"...\"` class field\n * defines a *writable* own property, while the implicit class name is\n * non-writable. Cron is unaffected — `CronJob.name` is an instance field\n * holding a string literal, not the class binding.\n */\nfunction warnIfNameWillNotSurviveTheBuild(jobs: Array<new () => Job>) {\n for (const job of jobs) {\n if (Object.getOwnPropertyDescriptor(job, \"name\")?.writable) continue;\n\n console.warn(\n `Queued job ${job.name} does not declare \\`static name\\`, so it is ` +\n `registered under its class name. A production build minifies the ` +\n `class that dispatches it and renames it, while discovery reads this ` +\n `file from source and does not — so the dispatch would be dropped in ` +\n `production and nowhere else. Add: static name = \"${job.name}\";`,\n );\n }\n}\n\n/**\n * The `CronJob` subclasses under `dir`, defaulting to the config slice's\n * `app/cron`.\n *\n * This is what a `schedule` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array —\n * though after boot `app(Scheduler).jobs` is the better one, because it is what\n * the scheduler actually took rather than what this would find if asked again.\n *\n * Every file underneath is imported, so calling this runs the app's cron\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCronJobs(\n dir: string = scheduleConfigDefaults().jobsDir,\n): Promise<Array<new () => CronJob>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"cron jobs\", \"schedule\");\n return await discoverClasses(resolved, CronJob);\n}\n\n/**\n * The `Command` subclasses under `dir`, defaulting to the config slice's\n * `app/commands`.\n *\n * This is what a `commands`-less `command` slice resolves to, and what\n * `gemi run` lists. Unlike the two above it is not called during boot — a\n * command registry has one consumer, and importing every file under\n * `app/commands` into every server process would be a cost paid on every start\n * for code no request reaches.\n *\n * Every file underneath is imported, so calling this runs the app's command\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCommands(\n dir: string = commandConfigDefaults().commandsDir,\n): Promise<CommandClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"commands\", \"command\");\n\n const unfinished: string[] = [];\n\n const commands = await discoverClasses(\n resolved,\n Command,\n [],\n (value, file) => {\n if (isUnfinishedBuilder(value)) unfinished.push(file);\n },\n );\n\n refuseUnfinishedBuilders(unfinished);\n\n return commands as CommandClass[];\n}\n\n/**\n * Stops the walk for a builder chain that was never finished.\n *\n * This is the one silence the builder introduces, and it is the exact shape\n * #322 and #323 exist to remove. `defineCommand(...).arg(...)` without a\n * trailing `.handle(...)` is a plain object rather than a class, so\n * `discoverClasses` discards it along with every constant and helper a command\n * file happens to export — and the command disappears from `gemi run` with\n * nothing raised. The author sees a listing containing every command except the\n * one they just wrote.\n *\n * A throw rather than a warning, because there is no reading of an unfinished\n * builder under which the author meant it: the chain builds a description of a\n * command and then discards it.\n *\n * \"Unfinished\" is decided by `.handle()` clearing the brand, not by the export\n * still being a builder object. Those differ for the natural way to share\n * declarations —\n *\n * export const base = defineCommand(\"reindex\").option(\"verbose\", …);\n * export default base.handle(async () => {});\n *\n * — where `base` is a builder that *did* produce a command. Keying off the shape\n * alone made that file abort the whole of `gemi run`, taking every other command\n * in the project down with it, under a message that was untrue for it.\n */\nfunction refuseUnfinishedBuilders(files: string[]): void {\n if (files.length === 0) return;\n\n const subject =\n files.length === 1\n ? `${files[0]} exports a command builder that never called \\`.handle()\\``\n : `${files.length} files export a command builder that never called ` +\n `\\`.handle()\\`:\\n ${files.join(\"\\n \")}`;\n\n throw new DiscoveryError(\n `${subject}, so there is no command to run. \\`.handle()\\` is what turns ` +\n `the chain into a command — finish it:\\n\\n` +\n ` export default defineCommand(\"my-command\")\\n` +\n ` .handle(async ({ line }) => { line(\"hello\") })`,\n );\n}\n\n/**\n * The `Listener` subclasses under `dir`, defaulting to the config slice's\n * `app/listeners`.\n *\n * This is what an `events` config slice with no `listeners` key resolves to.\n * Call it directly to ask what an application would register: every listener,\n * in the order it would register them.\n *\n * Only listeners are walked. Event classes are never discovered — each is\n * imported by the listener that binds to it and by the code that dispatches it,\n * so there is nothing a walk over them would find that is not already in the\n * module graph.\n *\n * **Known residual, matching jobs and cron.** `discoverClasses` excludes the\n * `base` it is handed and not intermediates, so an abstract listener base\n * written in `listenersDir` and extended by its siblings is discovered and\n * registered alongside them — constructed, with its `handle` called, on every\n * dispatch of whatever event it declares. Keep shared bases outside the\n * directory.\n *\n * Every file underneath is imported, so calling this runs the app's listener\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n *\n * @throws DiscoveryError if a discovered listener declares no `static event`.\n */\nexport async function discoverListeners(\n dir: string = eventConfigDefaults().listenersDir,\n): Promise<ListenerClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"event listeners\", \"events\");\n\n const listeners = (await discoverClasses(\n resolved,\n Listener,\n )) as ListenerClass[];\n\n refuseListenersWithNoEvent(listeners);\n warnIfListenerNameWillNotSurviveTheBuild(listeners);\n warnIfEventNameWillNotSurviveTheBuild(listeners);\n\n return listeners;\n}\n\n/**\n * Stops the walk for a listener that binds to nothing.\n *\n * `static event` is declared as required on the base and the compiler still\n * cannot see it missing: every subclass inherits the declaration whether or not\n * it assigns to one, so `typeof SomeListener` type-checks either way. What the\n * author gets instead is a file that is imported, registered under no name, and\n * never called — the silence this whole module is arranged against.\n *\n * A throw rather than a warning, because there is no reading of a listener with\n * no event under which the author meant it. The usual cause is the residual\n * above: an abstract base sharing a gate between two listeners, sitting in\n * `listenersDir` where the walk finds it. Moving it out is the fix, and the\n * message says so — the alternative, excluding it by some guess about\n * abstractness, is how a discovery pass ends up quietly covering less than the\n * directory holds.\n */\nfunction refuseListenersWithNoEvent(listeners: ListenerClass[]): void {\n const orphans = listeners.filter((listener) => !listener.event);\n if (orphans.length === 0) return;\n\n throw new DiscoveryError(\n `${orphans\n .map((listener) => listener.name)\n .join(\", \")} declare no \\`static event\\`, so there is no event name to ` +\n `register them under and their \\`handle\\` would never run. Every ` +\n `listener binds to exactly one event:\\n\\n` +\n ` static event = UserRegistered;\\n\\n` +\n `If this is an abstract base its subclasses extend, move it out of the ` +\n `listeners directory — the walk excludes gemi's \\`Listener\\` and ` +\n `nothing else, so a base sitting beside its subclasses is registered ` +\n `and run like one of them.`,\n );\n}\n\n/**\n * Says something about a discovered listener that never declared `static name`.\n *\n * The hazard is `warnIfNameWillNotSurviveTheBuild`'s, one subsystem over: a\n * `static name = \"...\"` class field defines a *writable* own property while the\n * implicit class binding does not, and a minifier renames the binding while\n * leaving the string literal alone. The two spellings are indistinguishable by\n * value — both read `\"SendWelcomeEmail\"` in development — so the descriptor is\n * the only thing that tells them apart, and the difference only becomes visible\n * in a production build.\n *\n * A warning rather than a refusal, because a *sync* listener's name has no\n * second half to disagree with: every reader of it comes from this same\n * source-side walk, so a minified build and this walk cannot produce two\n * different strings for it. A **queued** listener does have one — the name is\n * the queue's key and it crosses a JSON boundary — and that case is refused\n * outright, by `jobForListener`, at the point the listener is registered with\n * the queue rather than here. This walk cannot tell the two apart without\n * constructing every listener it found; the registry constructs them anyway.\n */\nfunction warnIfListenerNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n for (const listener of listeners) {\n if (Object.getOwnPropertyDescriptor(listener, \"name\")?.writable) continue;\n\n console.warn(\n `Event listener ${listener.name} does not declare \\`static name\\`, so ` +\n `it is registered under its class name, which a production build ` +\n `renames. Nothing reads that name across a build boundary while the ` +\n `listener is sync, which is why this is a warning — but adding ` +\n `\\`queued = true\\` to it is refused at boot for the same reason, ` +\n `because the queue's key is that string. Add: static name = ` +\n `\"${listener.name}\";`,\n );\n }\n}\n\n/**\n * Says something about the *event* a discovered listener binds to, when that\n * event's name is the implicit class binding.\n *\n * This is the check that matters from the first dispatch, and it is the reason\n * `discoverListeners` reads `static event` at all. The registry is keyed by the\n * event's name; the dispatcher supplies that name from the class it constructs.\n * A production build minifies the server entry and the app code reachable from\n * it — the controller, and the event class it imports in order to dispatch —\n * while discovery imports `app/listeners/*.ts` from source, and those files\n * import `app/events/*.ts` from source too. Two module graphs, two class\n * objects, and an implicit `.name` that reads `\"UserRegistered\"` on one side\n * and `\"D\"` on the other. The dispatch then finds no listeners, which is legal,\n * normal, and completely silent.\n *\n * A declared `static name` is a string literal, which survives minification\n * intact, and the two halves agree again.\n *\n * Checked through the descriptor rather than the string, and not by comparing\n * `event.name` to anything: in development the two spellings produce the same\n * value, so a check on the string would be a tautology that passes forever.\n */\nfunction warnIfEventNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n const warned = new Set<EventClass>();\n\n for (const { event } of listeners) {\n if (warned.has(event)) continue;\n if (Object.getOwnPropertyDescriptor(event, \"name\")?.writable) continue;\n warned.add(event);\n\n console.warn(\n `Event ${event.name} does not declare \\`static name\\`, so it is ` +\n `dispatched under its class name. A production build minifies the ` +\n `code that dispatches it and renames the class, while discovery reads ` +\n `the listener's copy from source and does not — so the dispatch would ` +\n `reach no listener in production and nowhere else. Add: ` +\n `static name = \"${event.name}\";`,\n );\n }\n}\n"
|
|
13
13
|
],
|
|
14
14
|
"mappings": "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",
|
|
15
|
-
"debugId": "
|
|
15
|
+
"debugId": "124C491D13F36AA864756E2164756E21",
|
|
16
16
|
"names": []
|
|
17
17
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T as J}from"./chunk-
|
|
2
|
+
import{T as J}from"./chunk-bwh1n2cj.js";import{Kl as I}from"./chunk-jmgjhfya.js";var Z=I((Q)=>{var K=J(),L=(b)=>{return{setHttpHandler(j){b.httpHandler=j},httpHandler(){return b.httpHandler},updateHttpClientConfig(j,w){b.httpHandler?.updateHttpClientConfig(j,w)},httpHandlerConfigs(){return b.httpHandler.httpHandlerConfigs()}}},M=(b)=>{return{httpHandler:b.httpHandler()}};class B{name;kind;values;constructor({name:b,kind:j=K.FieldPosition.HEADER,values:w=[]}){this.name=b,this.kind=j,this.values=w}add(b){this.values.push(b)}set(b){this.values=b}remove(b){this.values=this.values.filter((j)=>j!==b)}toString(){return this.values.map((b)=>b.includes(",")||b.includes(" ")?`"${b}"`:b).join(", ")}get(){return this.values}}class D{entries={};encoding;constructor({fields:b=[],encoding:j="utf-8"}){b.forEach(this.setField.bind(this)),this.encoding=j}setField(b){this.entries[b.name.toLowerCase()]=b}getField(b){return this.entries[b.toLowerCase()]}removeField(b){delete this.entries[b.toLowerCase()]}getByType(b){return Object.values(this.entries).filter((j)=>j.kind===b)}}class z{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(b){this.method=b.method||"GET",this.hostname=b.hostname||"localhost",this.port=b.port,this.query=b.query||{},this.headers=b.headers||{},this.body=b.body,this.protocol=b.protocol?b.protocol.slice(-1)!==":"?`${b.protocol}:`:b.protocol:"https:",this.path=b.path?b.path.charAt(0)!=="/"?`/${b.path}`:b.path:"/",this.username=b.username,this.password=b.password,this.fragment=b.fragment}static clone(b){let j=new z({...b,headers:{...b.headers}});if(j.query)j.query=O(j.query);return j}static isInstance(b){if(!b)return!1;let j=b;return"method"in j&&"protocol"in j&&"hostname"in j&&"path"in j&&typeof j.query==="object"&&typeof j.headers==="object"}clone(){return z.clone(this)}}function O(b){return Object.keys(b).reduce((j,w)=>{let A=b[w];return{...j,[w]:Array.isArray(A)?[...A]:A}},{})}class G{statusCode;reason;headers;body;constructor(b){this.statusCode=b.statusCode,this.reason=b.reason,this.headers=b.headers||{},this.body=b.body}static isInstance(b){if(!b)return!1;let j=b;return typeof j.statusCode==="number"&&typeof j.headers==="object"}}function P(b){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(b)}Q.Field=B;Q.Fields=D;Q.HttpRequest=z;Q.HttpResponse=G;Q.getHttpHandlerExtensionConfiguration=L;Q.isValidHostname=P;Q.resolveHttpHandlerRuntimeConfig=M});
|
|
3
3
|
export{Z as Q};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=54EC3B341BC097AB64756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"'use strict';\n\nvar types = require('@smithy/types');\n\nconst getHttpHandlerExtensionConfiguration = (runtimeConfig) => {\n return {\n setHttpHandler(handler) {\n runtimeConfig.httpHandler = handler;\n },\n httpHandler() {\n return runtimeConfig.httpHandler;\n },\n updateHttpClientConfig(key, value) {\n runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);\n },\n httpHandlerConfigs() {\n return runtimeConfig.httpHandler.httpHandlerConfigs();\n },\n };\n};\nconst resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {\n return {\n httpHandler: httpHandlerExtensionConfiguration.httpHandler(),\n };\n};\n\nclass Field {\n name;\n kind;\n values;\n constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) {\n this.name = name;\n this.kind = kind;\n this.values = values;\n }\n add(value) {\n this.values.push(value);\n }\n set(values) {\n this.values = values;\n }\n remove(value) {\n this.values = this.values.filter((v) => v !== value);\n }\n toString() {\n return this.values.map((v) => (v.includes(\",\") || v.includes(\" \") ? `\"${v}\"` : v)).join(\", \");\n }\n get() {\n return this.values;\n }\n}\n\nclass Fields {\n entries = {};\n encoding;\n constructor({ fields = [], encoding = \"utf-8\" }) {\n fields.forEach(this.setField.bind(this));\n this.encoding = encoding;\n }\n setField(field) {\n this.entries[field.name.toLowerCase()] = field;\n }\n getField(name) {\n return this.entries[name.toLowerCase()];\n }\n removeField(name) {\n delete this.entries[name.toLowerCase()];\n }\n getByType(kind) {\n return Object.values(this.entries).filter((field) => field.kind === kind);\n }\n}\n\nclass HttpRequest {\n method;\n protocol;\n hostname;\n port;\n path;\n query;\n headers;\n username;\n password;\n fragment;\n body;\n constructor(options) {\n this.method = options.method || \"GET\";\n this.hostname = options.hostname || \"localhost\";\n this.port = options.port;\n this.query = options.query || {};\n this.headers = options.headers || {};\n this.body = options.body;\n this.protocol = options.protocol\n ? options.protocol.slice(-1) !== \":\"\n ? `${options.protocol}:`\n : options.protocol\n : \"https:\";\n this.path = options.path ? (options.path.charAt(0) !== \"/\" ? `/${options.path}` : options.path) : \"/\";\n this.username = options.username;\n this.password = options.password;\n this.fragment = options.fragment;\n }\n static clone(request) {\n const cloned = new HttpRequest({\n ...request,\n headers: { ...request.headers },\n });\n if (cloned.query) {\n cloned.query = cloneQuery(cloned.query);\n }\n return cloned;\n }\n static isInstance(request) {\n if (!request) {\n return false;\n }\n const req = request;\n return (\"method\" in req &&\n \"protocol\" in req &&\n \"hostname\" in req &&\n \"path\" in req &&\n typeof req[\"query\"] === \"object\" &&\n typeof req[\"headers\"] === \"object\");\n }\n clone() {\n return HttpRequest.clone(this);\n }\n}\nfunction cloneQuery(query) {\n return Object.keys(query).reduce((carry, paramName) => {\n const param = query[paramName];\n return {\n ...carry,\n [paramName]: Array.isArray(param) ? [...param] : param,\n };\n }, {});\n}\n\nclass HttpResponse {\n statusCode;\n reason;\n headers;\n body;\n constructor(options) {\n this.statusCode = options.statusCode;\n this.reason = options.reason;\n this.headers = options.headers || {};\n this.body = options.body;\n }\n static isInstance(response) {\n if (!response)\n return false;\n const resp = response;\n return typeof resp.statusCode === \"number\" && typeof resp.headers === \"object\";\n }\n}\n\nfunction isValidHostname(hostname) {\n const hostPattern = /^[a-z0-9][a-z0-9\\.\\-]*[a-z0-9]$/;\n return hostPattern.test(hostname);\n}\n\nexports.Field = Field;\nexports.Fields = Fields;\nexports.HttpRequest = HttpRequest;\nexports.HttpResponse = HttpResponse;\nexports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;\nexports.isValidHostname = isValidHostname;\nexports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": "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",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "54EC3B341BC097AB64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$i as O1,Zi as F,_i as _1}from"./chunk-6s6cek6k.js";import{ej as g1,hj as b}from"./chunk-2tfafjmk.js";import{il as R0}from"./chunk-4zwnmk3c.js";import{ml as C1}from"./chunk-edj701p0.js";import{Fl as H1}from"./chunk-mx4z8c6r.js";import{Nl as aQ}from"./chunk-jmgjhfya.js";class s1{static kind="controller";constructor(){}}class c0 extends s1{}function w1(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 MZ(Q){return w1(Q.headers.get("cookie"))}function u(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function a1(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let X=Z.slice(6).split(",").map((V)=>V.trim()).filter((V)=>V!=="");if(X.length!==1)return null;let G=X[0],Y=G.indexOf("-");if(Y===-1)return null;let K=G.slice(0,Y),J=G.slice(Y+1);if(K===""){let V=u(J);if(V===null)return null;return{kind:"suffix",suffixLength:V}}let H=u(K);if(H===null)return null;if(J==="")return{kind:"offset",start:H,end:null};let W=u(J);if(W===null||W<H)return null;return{kind:"offset",start:H,end:W}}function r1(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 jZ(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function LZ(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let $=u(Z[1]),X=u(Z[2]),G=u(Z[3]);if($===null||X===null||G===null||X<$)return null;return{start:$,end:X,total:G}}function CZ(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function e1(Q){return`bytes */${Q}`}class a extends F{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 p0(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 u0(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 Q0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function S1(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var d0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function P1(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 Z0(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)=>S1(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=P1($,X);return(Y)=>{let K=Q0(Y);return K!==void 0&&K>=G}}case"max":{let G=P1($,X);return(Y)=>{let K=Q0(Y);return K!==void 0&&K<=G}}case"gte":{let G=P1($,X);return(Y)=>S1(Y)&&Y>=G}case"lte":{let G=P1($,X);return(Y)=>S1(Y)&&Y<=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=u0(X);return(Y)=>Y instanceof Blob&&Y.type.startsWith(G)}case"fileSize":{let G=p0(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(Y)=>Y instanceof Blob&&Y.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((Y)=>Y!=="");if(G.length===0)throw new k('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(Y)=>typeof Y==="string"&&G.includes(Y)}default:throw new k(`Unknown validation rule "${Q}". Known rules: ${d0.join(", ")}`)}}function d(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 L1=new WeakMap;function G0(Q){return typeof Q==="object"&&Q!==null&&L1.has(Q)}function U1(Q){let Z=L1.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function n0(Q){let Z={defs:{},cells:new Map},$=Q;if(Q.node.kind==="ref"){let G=d(Q.node.cell);$={...G,...Q.description?{description:Q.description}:{},optional:Q.optional,nullable:Q.nullable||G.nullable}}let X=e($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function e(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=o0(i0(Q.node,Z),$),G=[Q.description,l0(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function l0(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 i0(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:e(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,e(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>e($,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]=e(d($),Z);return{$ref:`#/$defs/${$.name}`}}}}function o0(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 t0(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function s0(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 t0(Z)}function Y0(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 Y0({...d(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function a0(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function r0(Q){let Z=a0(Q);return Z?`${Z}: `:""}function E1(Q){return`${r0(Q.path)}${Q.message}`}function M1(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[Y,K]of Object.entries($.shape))G+=M1(K,X[Y]);return G}case"union":return $.members.reduce((X,G)=>Math.max(X,M1(G,Z)),0);case"json":return 1;case"ref":return K0($.cell,Z,()=>1,()=>M1(d($.cell),Z))}}function K0(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 h(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:e0(Q,Z,$,X)}}function e0(Q,Z,$,X){let G=Q.node,Y=()=>{let K=Z===void 0?"required":G.kind==="literal"?"const":G.kind==="enum"&&typeof Z==="string"?"enum":"type",J=K==="const"?{allowedValue:G.value}:K==="enum"?{allowedValues:G.values}:{};X.push({path:$,code:K,message:`expected ${Y0(Q)}, got ${s0(G,Z)}`,params:J});return};switch(G.kind){case"string":if(typeof Z!=="string")return Y();return $0(G.checks,Z,$,X),Z;case"number":if(typeof Z!=="number"||!Number.isFinite(Z))return Y();if(G.checks?.integer&&!Number.isInteger(Z))return Y();return ZQ(G.checks,Z,$,X),Z;case"boolean":return typeof Z==="boolean"?Z:Y();case"literal":return Z===G.value?Z:Y();case"enum":if(typeof Z!=="string"||!G.values.includes(Z))return Y();return $0(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return Y();let K=Z.map((W,V)=>{let B=h(G.item,W,[...$,V],X);return B.drop?void 0:B.value}),{minItems:J,maxItems:H}=G.checks??{};if(J!==void 0&&Z.length<J)X.push({path:$,code:"minItems",message:`expected at least ${J} items, got ${Z.length}`,params:{limit:J}});if(H!==void 0&&Z.length>H)X.push({path:$,code:"maxItems",message:`expected at most ${H} items, got ${Z.length}`,params:{limit:H}});return K}case"object":{if(typeof Z!=="object"||Z===null||Array.isArray(Z))return Y();let K=Z,J={};for(let[H,W]of Object.entries(G.shape)){let V=h(W,K[H],[...$,H],X);if(!V.drop)J[H]=V.value}if(G.unknownKeys)for(let H of Object.keys(K)){if(Object.hasOwn(G.shape,H)||K[H]===void 0)continue;if(G.unknownKeys==="error"){X.push({path:[...$,H],code:"additionalProperties",message:"unknown key",params:{additionalProperty:H}});continue}$1(K[H],[...$,H],X,new Set),Object.defineProperty(J,H,{value:K[H],enumerable:!0,writable:!0,configurable:!0})}return J}case"union":{let K;for(let J of G.members){let H=[],W=h(J,Z,$,H);if(H.length===0)return W.drop?void 0:W.value;let V=M1(J,Z);if(!K||V>K.score)K={issues:H,score:V}}X.push({path:$,code:"anyOf",message:`no matching variant; closest: ${K.issues.map(E1).join("; ")}`,params:{closest:K.issues}});return}case"json":if(Z===void 0)return Y();return $1(Z,$,X,new Set),Z;case"ref":return K0(G.cell,Z,()=>{X.push({path:$,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>h(d(G.cell),Z,$,X).value)}}function QQ(Q){let Z=0;for(let $ of Q)Z++;return Z}function $0(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:Y,format:K}=Q;if(G!==void 0||Y!==void 0){let J=QQ(Z);if(G!==void 0&&J<G)X.push({path:$,code:"minLength",message:`expected at least ${G} characters, got ${J}`,params:{limit:G}});if(Y!==void 0&&J>Y)X.push({path:$,code:"maxLength",message:`expected at most ${Y} characters, got ${J}`,params:{limit:Y}})}if(K){let J=!1;try{J=K.test(Z)===!0}catch{}if(!J)X.push({path:$,code:"format",message:`expected a string in format "${K.name}"`,params:{format:K.name}})}}function ZQ(Q,Z,$,X){if(!Q)return;let G=(Y,K,J,H)=>{if(K===void 0||J(K))return;X.push({path:$,code:Y,message:`expected ${H} ${K}, got ${Z}`,params:{limit:K}})};G("minimum",Q.minimum,(Y)=>Z>=Y,"at least"),G("exclusiveMinimum",Q.exclusiveMinimum,(Y)=>Z>Y,"more than"),G("maximum",Q.maximum,(Y)=>Z<=Y,"at most"),G("exclusiveMaximum",Q.exclusiveMaximum,(Y)=>Z<Y,"less than")}function $1(Q,Z,$,X,G=!0){let Y=(J)=>{$.push({path:Z,code:"type",message:`expected a JSON value, got ${J}`,params:{}})};switch(typeof Q){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(Q))Y(String(Q));return;case"bigint":return Y("a bigint");case"function":return Y("a function");case"symbol":return Y("a symbol")}if(Q===null)return;let K=Q;if(X.has(K))return Y("a circular reference");X.add(K);try{let J=G?K.toJSON:void 0;if(typeof J==="function"){let H;try{H=J.call(K)}catch{return Y("a toJSON that threw")}if(H===void 0)return Y("a toJSON that returns undefined");return $1(H,Z,$,X,!1)}if(Array.isArray(Q))Q.forEach((H,W)=>$1(H,[...Z,W],$,X));else for(let[H,W]of Object.entries(K))$1(W,[...Z,H],$,X)}finally{X.delete(K)}}function S(Q){return R1(Q)}function R1(Q){let Z={toJSONSchema:()=>n0(Q),parse($){let X=[],G=h(Q,$,[],X);if(X.length>0)throw Error(X.map(E1).join("; "));return G.drop?void 0:G.value},safeParse($){let X=[],G=h(Q,$,[],X);if(X.length>0)return{ok:!1,errors:X.map(E1)};return{ok:!0,value:G.drop?void 0:G.value}},validate($){let X=[],G=h(Q,$,[],X);if(X.length>0)return{ok:!1,issues:X};return{ok:!0,value:G.drop?void 0:G.value}},describe:($)=>R1({...Q,description:$}),optional:()=>R1({...Q,optional:!0}),nullable:()=>R1({...Q,nullable:!0,optional:!1})};return L1.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var X0=["strip","error","passthrough"];class H0 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 $Q=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 D1(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function j1(Q,Z,$,X){let G=(z,U=$)=>{X.push(U?`${U}: ${z}`:z);return},Y=(z)=>$?`${$}.${z}`:z;if(!D1(Q))return G("expected a schema object");let K=new Set(Z.ignoreKeywords??[]),J=(z)=>$Q.has(z)||z.startsWith("x-")||K.has(z),H=!1,W=Q.type;if(Array.isArray(W)){let z=W.filter((U)=>U!=="null");if(z.length!==1)return G(`type ${JSON.stringify(W)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,Y("type"));H=z.length<W.length,W=z[0]}if(W!==void 0&&(typeof W!=="string"||!(W in r)))return G(`type ${JSON.stringify(W)} is not supported; expected one of ${Object.keys(r).join(", ")}`,Y("type"));let V=new Set(["type","description","enum","const","anyOf",...W?r[W]:[]]),B=!1;for(let z of Object.keys(Q)){if(V.has(z)||J(z))continue;B=!0;let U=Object.entries(r).find(([,P])=>P.includes(z));G(U&&U[0]!==W?`"${z}" applies to type ${U[0]}, and this schema is ${W?`type ${W}`:"untyped"}`:`"${z}" is not supported by s.fromJSONSchema`,Y(z))}if(B)return;if(Q.description!==void 0&&typeof Q.description!=="string")return G("expected a string",Y("description"));let L=Q.description,D=(z)=>({node:z,optional:!1,nullable:H,...L?{description:L}:{}});if(Q.anyOf!==void 0){if(W!==void 0||Q.enum!==void 0||Q.const!==void 0)return G("anyOf cannot be combined with type, enum or const here",Y("anyOf"));if(!Array.isArray(Q.anyOf)||Q.anyOf.length===0)return G("expected a non-empty array",Y("anyOf"));let z=[],U=!1;if(Q.anyOf.forEach((P,R)=>{if(D1(P)&&P.type==="null"&&Object.keys(P).length===1){H=!0;return}let A=j1(P,Z,Y(`anyOf[${R}]`),X);if(A)z.push(A);else U=!0}),U)return;if(z.length===0)return G("anyOf has only null in it",Y("anyOf"));if(z.length===1){let P=z[0];return{...P,nullable:P.nullable||H,...L?{description:L}:{}}}return D({kind:"union",members:z})}if(Q.const!==void 0){let z=Q.const;if(typeof z!=="string"&&typeof z!=="number"&&typeof z!=="boolean")return G("only a string, number or boolean const is supported",Y("const"));if(W!==void 0&&typeof z!==(W==="integer"?"number":W))return G(`const ${JSON.stringify(z)} is not of type ${W}`,Y("const"));return D({kind:"literal",value:z})}let M;if(W==="string"){if(M=XQ(Q,Z,Y,X),M===null)return}if(Q.enum!==void 0){if(!Array.isArray(Q.enum)||Q.enum.length===0)return G("expected a non-empty array",Y("enum"));let z=Q.enum.filter((R)=>R!==null);if(z.length<Q.enum.length)H=!0;let U=z.find((R)=>!(typeof R==="string"||typeof R==="number"||typeof R==="boolean")||W!==void 0&&typeof R!==(W==="integer"?"number":W));if(U!==void 0||z.length===0)return G(W?`every value must be of type ${W}${z.length===0?", and there must be one":`; ${JSON.stringify(U)} is not`}`:"only strings, numbers and booleans are supported",Y("enum"));if(z.every((R)=>typeof R==="string"))return D({kind:"enum",values:[...new Set(z)],...M?{checks:M}:{}});let P=[...new Set(z)];if(P.length===1)return D({kind:"literal",value:P[0]});return D({kind:"union",members:P.map((R)=>x({kind:"literal",value:R}))})}switch(W){case void 0:return G("a schema needs a type, an enum, a const or an anyOf");case"string":return D({kind:"string",...M?{checks:M}:{}});case"number":case"integer":{let z=W==="integer"?{integer:!0}:{},U=!1;for(let P of r.number){let R=Q[P];if(R===void 0)continue;if(typeof R!=="number"||!Number.isFinite(R)){G("expected a number",Y(P)),U=!0;continue}z[P]=R}if(U)return;return D({kind:"number",...Object.keys(z).length>0?{checks:z}:{}})}case"boolean":return D({kind:"boolean"});case"array":{if(!D1(Q.items))return G('an array needs "items" to be one schema (tuples are not supported)',Y("items"));let z={},U=!1;for(let R of["minItems","maxItems"]){let A=Q[R];if(A===void 0)continue;if(typeof A!=="number"||!Number.isInteger(A)||A<0){G("expected a non-negative integer",Y(R)),U=!0;continue}z[R]=A}let P=j1(Q.items,Z,Y("items"),X);if(!P||U)return;return D({kind:"array",item:P,...Object.keys(z).length>0?{checks:z}:{}})}case"object":{let z=Q.properties??{};if(!D1(z))return G("expected an object",Y("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())",Y("additionalProperties"));let U=Q.required??[];if(!Array.isArray(U)||!U.every((q)=>typeof q==="string"))return G("expected an array of property names",Y("required"));let P=U.filter((q)=>!Object.hasOwn(z,q));if(P.length>0)return G(`lists properties the schema doesn't have: ${P.join(", ")}`,Y("required"));let R={},A=!1;for(let[q,O]of Object.entries(z)){let C=j1(O,Z,Y(`properties.${q}`),X);if(!C){A=!0;continue}R[q]=U.includes(q)?C:{...C,optional:!0}}if(A)return;let I=Z.unknownKeys;return D({kind:"object",shape:R,...I==="error"||I==="passthrough"?{unknownKeys:I}:{}})}}return}function XQ(Q,Z,$,X){let G={},Y=!1;for(let K of["minLength","maxLength"]){let J=Q[K];if(J===void 0)continue;if(typeof J!=="number"||!Number.isInteger(J)||J<0){X.push(`${$(K)}: expected a non-negative integer`),Y=!0;continue}G[K]=J}if(Q.format!==void 0){let K=Q.format,J=typeof K==="string"?Z.formats?.[K]:void 0;if(typeof K!=="string")X.push(`${$("format")}: expected a string`),Y=!0;else if(!J||!Object.hasOwn(Z.formats,K))X.push(`${$("format")}: unknown format ${JSON.stringify(K)}; pass a check for it in the formats option`),Y=!0;else G.format={name:K,test:GQ(J)}}if(Y)return null;return Object.keys(G).length>0?G:void 0}function GQ(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var qZ={string:()=>S(x({kind:"string"})),number:()=>S(x({kind:"number"})),boolean:()=>S(x({kind:"boolean"})),literal:(Q)=>S(x({kind:"literal",value:Q})),enum:(Q)=>S(x({kind:"enum",values:Q})),object:(Q)=>S(x({kind:"object",shape:Object.fromEntries(Object.entries(Q).map(([Z,$])=>[Z,U1($)]))})),array:(Q)=>S(x({kind:"array",item:U1(Q)})),union:(Q)=>S(x({kind:"union",members:Q.map(U1)})),json:()=>S(x({kind:"json"})),recursive:KQ,fromJSONSchema:(Q,Z={})=>{let $=[];if(Z.unknownKeys!==void 0&&!X0.includes(Z.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${X0.map((G)=>JSON.stringify(G)).join(", ")}, got ${JSON.stringify(Z.unknownKeys)}`);let X=j1(Q,Z,"",$);if(!X||$.length>0)throw new H0($.length>0?$:["unreadable schema"]);return S(X)}};function NZ(Q){let Z=L1.get(Q);if(Z)return Z1(Z.node);return Q1(Q.toJSONSchema())}function Q1(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(!Q1($))return!1;if(Q.items&&!Q1(Q.items))return!1;for(let $ of Q.anyOf??[])if(!Q1($))return!1;for(let $ of Object.values(Q.$defs??{}))if(!Q1($))return!1;return!0}function Z1(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(($)=>Z1($.node,Z));case"array":return Z1(Q.item.node,Z);case"union":return Q.members.every(($)=>Z1($.node,Z));case"json":return!1;case"ref":if(Z.has(Q.cell))return!0;return Z.add(Q.cell),Z1(d(Q.cell).node,Z)}}function x1(Q,Z,$=new Set){let X=Q.node;if(X.kind==="union")return X.members.some((G)=>x1(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),x1(X.cell.definition,Z,$)}var YQ=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function KQ(Q,Z){if(typeof Q!=="string"||!YQ.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=U1(Z(S(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(x1(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,S(X())}function J0(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),$=Z.trim().toLowerCase();return $===""?null:$}function W0(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 X1=new WeakMap;function wZ(Q,Z,$,X){X1.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function z0(Q){return X1.get(Q)?.progress}function V0(Q){return X1.get(Q)?.grant}function B0(Q){return X1.has(Q)}function SZ(Q){return X1.get(Q)?.clientAddress}var P0=new WeakMap;function xZ(Q,Z){P0.set(Q,Z)}function D0(Q){return P0.get(Q)??null}var k1=new WeakMap;function kZ(Q,Z){let $=k1.get(Q)??[];if(!$.includes(Z))k1.set(Q,[...$,Z])}function gZ(Q){return k1.get(Q)??[]}class n{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 U0(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function HQ(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:Y,value:K}of $){if(X==="*"){if(Array.isArray(K))K.forEach((J,H)=>G.push({path:[...Y,H],value:J}));else if(U0(K))for(let[J,H]of Object.entries(K))G.push({path:[...Y,J],value:H});continue}if(Array.isArray(K)&&/^\d+$/.test(X)){G.push({path:[...Y,Number(X)],value:K[Number(X)]});continue}G.push({path:[...Y,X],value:U0(K)&&Object.hasOwn(K,X)?K[X]:void 0})}$=G}return $}function M0(Q){return Q.join(".")}class JQ{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(Q,Z,$,X){if(!Q){let H=b.getStore().req;this.params=H.params,this.rawRequest=H.rawRequest,this.kind=H.kind,this.routePath=H.routePath,this.domain=H.domain??null,this.state=H.state??new g1}else this.params=Z,this.rawRequest=Q,this.routePath=X,this.kind=$??"api",this.domain=D0(Q),this.state=new g1;this.headers=this.rawRequest.headers;let G=w1(this.rawRequest.headers.get("Cookie")),Y=new URL(this.rawRequest.url),K=new Map;for(let[H,W]of Y.searchParams)if(K.has(H)){let V=K.get(H);if(Array.isArray(V))V.push(W),K.set(H,V);else K.set(H,[V,W])}else K.set(H,W);let J=Object.fromEntries(K.entries());this.search=new n(J),this.cookies=G}locale(){let Q=b.getStore();if(Q.locale)return Q.locale;let Z=C1(R0);return Z.isLocaleAware?Z.detectLocale(Q.req):Q.locale}ctx(){return b.getStore()}isModelOriginated(){return B0(this.rawRequest)}mcpGrant(){return V0(this.rawRequest)??null}reportProgress(Q){let Z=z0(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return a1(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=J0(this.rawRequest.headers.get("Content-Type"));if(W0(Q))return new n(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 F)throw X;throw new F("The request body could not be read as a form.")}let $=new Map;for(let[X,G]of Z.entries())if($.has(X)){let Y=$.get(X);if(Array.isArray(Y))Y.push(G);else $.set(X,[Y,G])}else $.set(X,G);return new n(Object.fromEntries($.entries()))}return new n({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch($){if($ instanceof F)throw $;throw new F("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new F("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new F("The request body must be a JSON object.");return Z}validateInput(Q){if(G0(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},$={},X=Object.entries(this.schema).map(([G,Y])=>({key:G,rules:Object.entries(Y).map(([K,J])=>({rule:K,message:J,check:typeof J==="function"?null:this.ruleFor(G,K)}))}));for(let{key:G,rules:Y}of X)for(let{path:K,value:J}of HQ(Z,G)){let H=this.checkField(J,Y);if(H.length>0){let W=$[M0(K)]??=[];for(let V of H)if(!W.includes(V))W.push(V)}}if(this.addRefinements($,Z),Object.keys($).length>0)throw new a($);return Q}checkField(Q,Z){let $=Z.some(({rule:Y})=>Y==="required"),X=Q===void 0||Q===null||Q==="",G=[];for(let{rule:Y,message:K,check:J}of Z){let H=K,W=!1;if(typeof K==="function")H=K(Q),W=typeof H>"u";else W=J(Q);if(W)continue;if(X&&!$)continue;if(Y==="required")return[String(H)];if(!G.includes(String(H)))G.push(String(H))}return G}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),$={};if("issues"in Z)for(let G of Z.issues){let Y=M0(G.path),K=$[Y]??=[];if(!K.includes(G.message))K.push(G.message)}let X="value"in Z?new n(Z.value):Q;if(this.addRefinements($,X.toJSON()),Object.keys($).length>0)throw new a($);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 Z0(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 a))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}var j0="x-gemi-sign-in";class WQ extends F{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:O1("authorization",this.error,401)}},view:{}}}}class y1 extends F{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:y1.apiStatus,data:{error:O1("permission",this.error,y1.apiStatus)}},view:{status:403}}}}class b1 extends F{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:_1("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":e1(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class zQ extends F{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:_1("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class m extends F{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:_1("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class VQ extends F{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:O1("authentication","Authentication error",401)},headers:{[j0]:Z}},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 G1{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return C1(this.getFacadeAccessor())}}import{Buffer as BQ}from"buffer";function A1(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 Y1{async putStream({body:Q,...Z},$={}){$.signal?.throwIfAborted();let X=[],G=Q.getReader();try{for(;;){$.signal?.throwIfAborted();let{done:Y,value:K}=await G.read();if(Y)break;X.push(K)}}catch(Y){throw await G.cancel(Y).catch(()=>{}),Y}return this.put({...Z,body:BQ.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={}){A1(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 m(Z.name);let X=$.headers.get("Content-Type")??"application/octet-stream",G=$.headers.get("ETag")??void 0,Y=$.headers.get("Last-Modified"),K=Y?new Date(Y):void 0;if(Z.range){let W=await $.blob();return{body:W,start:0,end:W.size-1,total:W.size,partial:!1,type:X,etag:G,lastModified:K,name:Z.name}}let J=Number($.headers.get("Content-Length")),H=Number.isFinite(J)?J:0;return{body:$.body,start:0,end:H-1,total:H,partial:!1,type:X,etag:G,lastModified:K,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 m(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 L0(Q,Z){if(!Z)return Q;let $=Q.getReader(),X=!1,G,Y=()=>{if(X=!0,G)Z.removeEventListener("abort",G)};return new ReadableStream({start(K){if(G=()=>{if(X)return;Y(),K.error(Z.reason),$.cancel(Z.reason).catch(()=>{})},Z.aborted)G();else Z.addEventListener("abort",G,{once:!0})},async pull(K){let J;try{J=await $.read()}catch(H){if(X)return;Y(),K.error(H);return}if(X)return;if(J.done){Y(),K.close();return}K.enqueue(J.value)},cancel(K){return Y(),$.cancel(K)}},{highWaterMark:0})}import{mkdir as PQ,open as DQ,readdir as f1,rename as UQ,rmdir as MQ,stat as RQ,unlink as C0}from"fs/promises";import{dirname as jQ,isAbsolute as v1,relative as K1,resolve as l,sep as f}from"path";class h1 extends Y1{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${H1()}/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()):"",Y=`${this.folderPath}/${X}`;return Z?.throwIfAborted(),await Bun.write(Y,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 Y=l(this.folderPath),K=l(Y,Q),J=K1(Y,K);if(!J||J===".."||J.startsWith(`..${f}`)||v1(J))throw Error(`Refusing to write "${Q}": it is outside the storage folder`);await PQ(jQ(K),{recursive:!0}),G=`${K}.${Bun.randomUUIDv7()}.partial`;let H=await DQ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:W,value:V}=await X.read();if(W)break;for(let B=0;B<V.byteLength;){let{bytesWritten:L}=await H.write(V,B);B+=L}}}finally{await H.close()}return $?.throwIfAborted(),await UQ(G,K),Q}catch(Y){if(await X.cancel(Y).catch(()=>{}),G)await C0(G).catch(()=>{});throw Y}}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}`,Y=Bun.file(G),K=L0(Bun.file(G).stream(),Z),J=new Date(Y.lastModified).toUTCString();return new Response(K,{headers:{"Content-Type":Y.type,"Content-Length":String(Y.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J}})}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 m($);let Y=G.size,K=X?r1(X,Y):null;if(X&&!K)throw new b1(Y);let J=K?.start??0,H=K?K.end:Y-1;return{body:K?G.slice(J,H+1):G,start:J,end:H,total:Y,partial:Boolean(K),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 m(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=K1($,X);if(!G||G===".."||G.startsWith(`..${f}`)||v1(G))throw Error(`Refusing to delete "${Z}": it is outside the storage folder`);try{await C0(X)}catch(Y){if(Y?.code==="ENOENT")return;throw Y}}resolvePrefix(Q){let Z=l(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),Y=l(Z,X),K=K1(Z,Y);if(K===".."||K.startsWith(`..${f}`)||v1(K))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let J=K.split(f).join("/");return{root:Z,dir:Y,match:J?`${J}/${G}`:G}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:$,dir:X,match:G}=this.resolvePrefix(Q),Y=[],K=async(J)=>{let H;try{H=await f1(J,{withFileTypes:!0})}catch(W){if(W?.code==="ENOENT"||W?.code==="ENOTDIR")return;throw W}for(let W of H){let V=`${J}${f}${W.name}`,B=K1($,V).split(f).join("/");if(W.isDirectory()){if(`${B}/`.startsWith(G)||G.startsWith(`${B}/`))await K(V)}else if(W.isFile()&&B.startsWith(G))Y.push(B)}};await K(X),Y.sort();for(let J of Y){Z?.throwIfAborted();let H;try{H=await RQ(`${$}/${J}`)}catch(W){if(W?.code==="ENOENT")continue;throw W}yield{name:J,size:H.size,lastModified:H.mtime}}}async deletePrefix(Q,Z={}){A1(Q);let{root:$,match:X}=this.resolvePrefix(Q);A1(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 Y;try{Y=await f1(G,{withFileTypes:!0})}catch{return}for(let K of Y){if(!K.isDirectory())continue;let J=`${G}${f}${K.name}`,H=K1(Q,J).split(f).join("/");if(`${H}/`.startsWith(Z)||Z.startsWith(`${H}/`)){if(await X(J),`${H}/`.startsWith(Z))$.push(J)}}};await X(Q);for(let G of $)try{await MQ(G)}catch{}}async list(){return await f1(this.folderPath)}}var v=30000;function M8(Q){return Q}function _0(){return{driver:new h1,fetchTimeoutMs:v,fetchIdleTimeoutMs:v}}class m1{static token="filesystem";driver;fetchTimeoutMs;fetchIdleTimeoutMs;constructor(Q={}){this.driver=Q.driver??_0().driver,this.fetchTimeoutMs=Q.fetchTimeoutMs??v,this.fetchIdleTimeoutMs=Q.fetchIdleTimeoutMs??v}}class O0 extends Error{driver;limit;timeoutMs;object;code="storage-fetch-timeout";constructor(Q,Z,$,X){super(Z==="fetchTimeoutMs"?`${Q}: no response for "${X}" within ${$}ms (fetchTimeoutMs)`:`${Q}: the body of "${X}" sent nothing for ${$}ms (fetchIdleTimeoutMs)`);this.driver=Q;this.limit=Z;this.timeoutMs=$;this.object=X;this.name="StorageFetchTimeoutError"}}async function A0(Q,Z,$,X){let{fetchTimeoutMs:G,fetchIdleTimeoutMs:Y}=X;if($.signal||!G&&!Y)return Q.fetch(Z,$);let K=new AbortController,J=Q.constructor?.name||"FileStorageDriver",H=typeof Z==="string"?Z:Z.name,W=(L,D)=>{let M=new O0(J,L,D,H);return K.abort(M),M},V=Promise.resolve(Q.fetch(Z,{...$,signal:K.signal})),B;if(G){let L,D=new Promise((M,z)=>{L=setTimeout(()=>z(W("fetchTimeoutMs",G)),G)});try{B=await Promise.race([V,D])}catch(M){if(K.signal.aborted)throw V.then((z)=>z.body?.cancel(K.signal.reason).catch(()=>{}),()=>{}),K.signal.reason;throw M}finally{clearTimeout(L)}}else B=await V;if(!Y||!B.body)return B;return new Response(LQ(B.body,Y,()=>W("fetchIdleTimeoutMs",Y)),{status:B.status,statusText:B.statusText,headers:B.headers})}function LQ(Q,Z,$){let X=Q.getReader();return new ReadableStream({async pull(G){let Y,K,J=new Promise((H,W)=>{Y=setTimeout(()=>{K=$(),W(K)},Z)});try{let H=await Promise.race([X.read(),J]);if(H.done)G.close();else G.enqueue(H.value)}catch(H){let W=K??H;G.error(W),X.cancel(W).catch(()=>{})}finally{clearTimeout(Y)}},cancel(G){return X.cancel(G)}},{highWaterMark:0})}class T extends Error{code="safe-fetch";url;constructor(Q,Z,$){super(Q,$);this.name=new.target.name,this.url=Z}}class c extends T{reason;code="invalid-url";constructor(Q,Z,$){super($,Q);this.reason=Z}}class I1 extends T{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 T{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 q1 extends T{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class N1 extends T{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 F1 extends T{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class J1 extends T{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 c1 extends T{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class o extends T{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class p1 extends T{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function CQ(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 Y of Z){let K=_Q(Y);if(K===null)return null;$.push(K)}let X=$.pop();for(let Y of $)if(Y>255)return null;if(X>=256**(4-$.length))return null;let G=X;return $.forEach((Y,K)=>{G+=Y*256**(3-K)}),new Uint8Array([Math.floor(G/16777216)&255,Math.floor(G/65536)&255,Math.floor(G/256)&255,G&255])}function _Q(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 I0(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=(W,V)=>{if(W==="")return[];let B=[],L=W.split(":");for(let D=0;D<L.length;D++){let M=L[D];if(V&&D===L.length-1&&M.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(M))return null;let z=M.split(".").map(Number);if(z.some((U)=>U>255))return null;B.push(z[0]<<8|z[1],z[2]<<8|z[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(M))return null;B.push(parseInt(M,16))}return B},Y=G(X[0],X.length===1),K=X.length===2?G(X[1],!0):[];if(!Y||!K)return null;let J;if(X.length===2){let W=8-Y.length-K.length;if(W<1)return null;J=[...Y,...Array.from({length:W},()=>0),...K]}else J=Y;if(J.length!==8)return null;let H=new Uint8Array(16);return J.forEach((W,V)=>{H[V*2]=W>>8,H[V*2+1]=W&255}),H}function W1(Q){let Z=I0(Q);if(Z)return{family:6,bytes:Z};let $=CQ(Q);if($)return{family:4,bytes:$};return null}function p(Q){if(Q.family===6&&OQ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function OQ(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function z1(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 t(Q){let Z=Q.lastIndexOf("/"),$=Z===-1?Q:Q.slice(0,Z),X=/^[0-9.]+$/.test($)?AQ($):I0($);if(!X)return null;let G=p(X.length===4?{family:4,bytes:X}:{family:6,bytes:X}),Y=G.family===4?32:128,K=Y;if(Z!==-1){let J=Q.slice(Z+1);if(!/^\d{1,3}$/.test(J))return null;if(K=Number(J),X.length===16&&G.family===4)K-=96;if(K<0||K>Y)return null}return{family:G.family,bytes:G.bytes,prefix:K}}function AQ(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 $=p(Q);if($.family!==Z.family)return!1;let X=Z.prefix;for(let G=0;X>0;G++){let Y=Math.min(8,X),K=255<<8-Y&255;if(($.bytes[G]&K)!==(Z.bytes[G]&K))return!1;X-=Y}return!0}var _=(Q,Z)=>({cidr:t(Q),kind:Z,text:Q}),IQ=[_("0.0.0.0/8","unspecified"),_("10.0.0.0/8","private"),_("100.64.0.0/10","shared"),_("127.0.0.0/8","loopback"),_("169.254.169.254/32","metadata"),_("169.254.0.0/16","link-local"),_("168.63.129.16/32","metadata"),_("172.16.0.0/12","private"),_("192.0.0.0/24","reserved"),_("192.0.2.0/24","documentation"),_("192.88.99.0/24","reserved"),_("192.168.0.0/16","private"),_("198.18.0.0/15","benchmarking"),_("198.51.100.0/24","documentation"),_("203.0.113.0/24","documentation"),_("224.0.0.0/4","multicast"),_("255.255.255.255/32","broadcast"),_("240.0.0.0/4","reserved")],qQ=[_("::/128","unspecified"),_("::1/128","loopback"),_("64:ff9b:1::/48","private"),_("::/8","reserved"),_("100::/64","reserved"),_("2001:db8::/32","documentation"),_("2001::/23","reserved"),_("3fff::/20","documentation"),_("fd00:ec2::254/128","metadata"),_("fc00::/7","unique-local"),_("fe80::/10","link-local"),_("fec0::/10","private"),_("ff00::/8","multicast")],NQ=t("64:ff9b::/96"),FQ=t("2002::/16"),TQ=t("2000::/3");function T1(Q){let Z=typeof Q==="string"?W1(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let $=p(Z);if($.family===4){let G=IQ.find((Y)=>g($,Y.cidr));return G?{kind:G.kind,range:G.text}:null}if(g($,NQ))return T1({family:4,bytes:$.bytes.slice(12)});if(g($,FQ))return T1({family:4,bytes:$.bytes.slice(2,6)});let X=qQ.find((G)=>g($,G.cidr));if(X)return{kind:X.kind,range:X.text};return g($,TQ)?null:{kind:"reserved",range:"outside 2000::/3"}}function q0(Q,Z){let $=p(Q),X=p(Z);return $.family===X.family&&$.bytes.every((G,Y)=>G===X.bytes[Y])}import{lookup as wQ}from"dns/promises";import*as SQ from"http";import*as EQ from"https";import*as s from"zlib";class u1 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 V1={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},xQ=new Set([301,302,303,307,308]),kQ=new Set([101,103,204,205,304]),gQ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],yQ=["authorization","cookie","proxy-authorization"];async function T0(Q,Z={}){let $=bQ(Z),X=Z.signal;X?.throwIfAborted();let G=new AbortController,Y=G.signal,K=String(Q),J=(B)=>{if(!Y.aborted)G.abort(B)},H=setTimeout(()=>J(new N1(K,"total",$.timeout)),$.timeout),W=()=>J(X.reason);X?.addEventListener("abort",W,{once:!0});let V=()=>{clearTimeout(H),X?.removeEventListener("abort",W)};try{let B=F0(K,$),L=(Z.method??"GET").toUpperCase(),D=new Headers(Z.headers);for(let z of gQ)D.delete(z);if(!D.has("accept"))D.set("accept","*/*");if(!D.has("user-agent"))D.set("user-agent","gemi");if(!D.has("accept-encoding"))D.set("accept-encoding","gzip, deflate, br");let M=await mQ(L,Z.body,D);for(let z=0;;z++){K=B.href;let{request:U,response:P,address:R}=await cQ(B,L,D,M,$,Y),A=P.statusCode??0,I=P.headers.location;if(xQ.has(A)&&I&&Z.redirect!=="manual"){if(U.destroy(),z>=$.maxRedirects)throw new c1(B.href,$.maxRedirects);let q;try{q=new URL(I,B)}catch{throw new c(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(A===303?L!=="HEAD":(A===301||A===302)&&L==="POST"){L="GET",M=null;let O=[];D.forEach((C,j)=>{if(j.startsWith("content-"))O.push(j)});for(let C of O)D.delete(C)}if(q.origin!==B.origin)for(let O of yQ)D.delete(O);B=F0(q.href,$);continue}return pQ({url:B,hop:z,method:L,request:U,response:P,address:R,policy:$,signal:Y,release:V})}}catch(B){throw V(),Y.aborted?Y.reason:B}}function bQ(Q){let Z=(X,G)=>{let Y={hosts:[],ranges:[]};for(let K of X){let J=K.includes("/")||K.includes(":")||/^[\d.]+$/.test(K),H=J?t(K):null;if(H)Y.ranges.push(H);else if(!J&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(K))Y.hosts.push(w0(K));else throw TypeError(`safeFetch: "${K}" in ${G} is not a host name or an IP range.`)}return Y},$=Q.allowPrivate;return{timeout:Q.timeout??V1.timeout,connectTimeout:Q.connectTimeout??V1.connectTimeout,maxSize:Q.maxSize??V1.maxSize,maxRedirects:Q.maxRedirects??V1.maxRedirects,ports:Q.ports??V1.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??fQ}}async function fQ(Q){return(await wQ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function w0(Q){return Q.toLowerCase().replace(/\.$/,"")}function N0(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function F0(Q,Z){let $;try{$=new URL(Q)}catch{throw new c(Q,"malformed",`"${Q}" is not a URL.`)}if($.protocol!=="http:"&&$.protocol!=="https:")throw new c($.href,"scheme",`Only http and https URLs can be fetched, not ${$.protocol.slice(0,-1)}.`);if($.username||$.password)throw new c($.href,"credentials","The URL has a username or password in it.");let X=S0($);if(Z.ports!=="any"&&!Z.ports.includes(X))throw new c($.href,"port",`Port ${X} is not allowed.`);return $}function S0(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function vQ(Q,Z,$){let X=w0(Q.hostname.replace(/^\[(.*)\]$/,"$1")),G=W1(X),Y=G!==null&&(X.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(X));if(!Y&&N0(X,Z.deny.hosts))throw new I1(Q.href,X,"denied");let K=!Y&&Z.allow!==null&&N0(X,Z.allow.hosts);if(Z.allow&&!K&&Z.allow.ranges.length===0)throw new I1(Q.href,X,"not-allowed");let J;if(Y)J=[G];else{let H;try{H=await hQ(Z.resolve(X),$)}catch(W){if($.aborted)throw $.reason;throw new q1(Q.href,X,W)}if(J=H.map((W)=>W1(W)).filter((W)=>W!==null),J.length===0)throw new q1(Q.href,X)}for(let H of J){let W=z1(H);if(Z.deny.ranges.some((B)=>g(H,B)))throw new i(Q.href,X,W,"denied");if(Z.allow&&!K&&!Z.allow.ranges.some((B)=>g(H,B)))throw new i(Q.href,X,W,"not-allowed");let V=T1(H);if(V&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((B)=>g(H,B)))throw new i(Q.href,X,W,V.kind)}return{host:X,addresses:J,isLiteral:Y}}function hQ(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((Y)=>{Z.removeEventListener("abort",G),$(Y)},(Y)=>{Z.removeEventListener("abort",G),X(Y)})})}async function mQ(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 cQ(Q,Z,$,X,G,Y){let K=new AbortController,J=setTimeout(()=>K.abort(new N1(Q.href,"connect",G.connectTimeout)),G.connectTimeout),H=AbortSignal.any([Y,K.signal]);try{let{host:W,addresses:V,isLiteral:B}=await vQ(Q,G,H),L=Q.protocol==="https:",D={};if($.forEach((M,z)=>{D[z]=M}),X)D["content-length"]=String(X.byteLength);return await new Promise((M,z)=>{let U={method:Z,host:W,port:S0(Q),path:`${Q.pathname}${Q.search}`,headers:D,agent:!1,lookup:(O,C,j)=>{let w=C?.family,N=V.filter((B1)=>!w||B1.family===w);if(N.length===0)j(Object.assign(Error(`No IPv${w} address for ${W}`),{code:"ENOTFOUND"}));else if(C?.all)j(null,N.map((B1)=>({address:z1(B1),family:B1.family})));else j(null,z1(N[0]),N[0].family)}};if(L&&!B)U.servername=W;let P=(L?EQ:SQ).request(U),R=null,A=(O)=>{H.removeEventListener("abort",I),P.destroy(),z(O)},I=()=>A(H.aborted?H.reason:Y.reason);H.addEventListener("abort",I,{once:!0});let q=(O)=>{let C=O?.remoteAddress;if(!C||R!==null)return!0;let j=W1(C);if(!j||!V.some((w)=>q0(w,j)))return A(new i(Q.href,W,C,"not-allowed")),!1;return R=z1(p(j)),!0};P.once("socket",(O)=>{let C=()=>{if(q(O)&&!L)clearTimeout(J)};if(O.connecting)O.once("connect",C);else C();if(L)O.once("secureConnect",()=>clearTimeout(J))}),P.once("response",(O)=>{if(clearTimeout(J),O.on("error",()=>{}),!q(O.socket))return;H.removeEventListener("abort",I),M({request:P,response:O,address:R})}),P.on("error",(O)=>{if(H.aborted)return A(H.reason);A(O instanceof T?O:new o(Q.href,O))}),P.end(X??void 0)})}finally{clearTimeout(J)}}function pQ({url:Q,hop:Z,method:$,request:X,response:G,address:Y,policy:K,signal:J,release:H}){let W=G.statusCode??0;if(W<200||W>599)throw X.destroy(),new o(Q.href,Error(`Unexpected status ${W}`));let V=new Headers,B=G.rawHeaders;for(let C=0;C<B.length;C+=2)V.append(B[C],B[C+1]);if(K.contentTypes){let C=V.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!C||!K.contentTypes.some((j)=>uQ(C,j)))throw X.destroy(),new J1(Q.href,C,K.contentTypes)}let L={url:Q.href,redirected:Z>0,address:Y},D={status:W,statusText:G.statusMessage??"",headers:V};if($==="HEAD"||kQ.has(W))return X.destroy(),H(),new u1(null,D,L);let M=V.get("content-encoding")?.trim().toLowerCase(),z=M==="gzip"||M==="x-gzip"?s.createGunzip():M==="deflate"?s.createInflate():M==="br"?s.createBrotliDecompress():null,U=Number(V.get("content-length"));if(!z&&Number.isFinite(U)&&U>K.maxSize)throw X.destroy(),new F1(Q.href,K.maxSize);if(z)V.delete("content-encoding"),V.delete("content-length");let P=z?G.pipe(z):G,R=0,A=!1,I=()=>{},q=()=>{A=!0,J.removeEventListener("abort",I),H()},O=new ReadableStream({start(C){let j=(N)=>{if(A)return;if(q(),N===void 0)C.close();else X.destroy(),z?.destroy(),C.error(N)};if(I=()=>j(J.reason),J.addEventListener("abort",I,{once:!0}),J.aborted)return I();P.on("data",(N)=>{if(A)return;if(R+=N.byteLength,R>K.maxSize)return j(new F1(Q.href,K.maxSize));if(C.enqueue(new Uint8Array(N)),(C.desiredSize??1)<=0)P.pause()}),P.once("end",()=>j());let w=(N)=>j(N instanceof T?N:new o(Q.href,N));if(P.on("error",w),z)G.on("error",w);G.once("aborted",()=>j(new o(Q.href,Error("The response was cut off."))))},pull(){P.resume()},cancel(){if(A)return;q(),X.destroy(),z?.destroy()}});return new u1(O,D,L)}function uQ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function x0(Q){return lQ(Q)??oQ(Q)??tQ(Q)}var d1=4096,dQ={"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 k0(Q){return dQ[Q]??"bin"}function E(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 nQ={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 lQ(Q){if(E(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(E(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 nQ[Z]??"video/mp4"}if(E(Q,[73,73,42,0])||E(Q,[77,77,0,42]))return"image/tiff";if(E(Q,[66,77])&&E(Q,[0,0,0,0],6))return"image/bmp";if(E(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(E(Q,[37,80,68,70,45]))return"application/pdf";if(E(Q,[80,75,3,4]))return"application/zip";if(E(Q,[31,139]))return"application/gzip";if(E(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(E(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 iQ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function oQ(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 iQ){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 tQ(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 sQ=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function E0(Q){let Z=Q.split(";")[0].trim().toLowerCase();return sQ.has(Z)||Z.endsWith("+xml")}function g0(Q,Z){let $=Q.split(";")[0].trim().toLowerCase();return Z.some((X)=>{let G=X.split(";")[0].trim().toLowerCase();if(G==="*/*"||G==="*")return!E0($);if(G.endsWith("/*"))return $.startsWith(G.slice(0,-1))&&!E0($);return $===G})}import{Buffer as eQ}from"buffer";async function y0(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 b0(Q,Z,$={}){let{name:X,directory:G,bucket:Y,maxSize:K,timeout:J,contentTypes:H,signal:W}=$;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 V=await T0(Z,{...$.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:W,timeout:J,maxSize:K});if(!V.ok)throw await V.body?.cancel().catch(()=>{}),new p1(V.url,V.status);let B=(V.body??new Response(new Uint8Array).body).getReader(),L=async(j)=>{throw await B.cancel(j).catch(()=>{}),j},D=[],M=0,z=!1;while(M<d1){let{done:j,value:w}=await B.read();if(j){z=!0;break}D.push(w),M+=w.byteLength}let U=rQ(D,M),P=x0(U.subarray(0,Math.min(M,d1))),R=H?.length?H:["*/*"];if(!g0(P,R))await L(new J1(V.url,P,R));let A=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${k0(P)}`].filter(Boolean).join("/"),I=M,q=new ReadableStream({start(j){if(M>0)j.enqueue(U);if(z)j.close()},async pull(j){let{done:w,value:N}=await B.read();if(w){j.close();return}I+=N.byteLength,j.enqueue(N)},cancel(j){return B.cancel(j)}}),O={name:A,bucket:Y,body:q,contentType:P},C;try{C=Q.putStream?await Q.putStream(O,{signal:W}):await Y1.prototype.putStream.call(Q,O,{signal:W})}catch(j){throw await L(j),j}return{name:C,contentType:P,size:I,url:V.url}}function rQ(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 QZ extends G1{static getFacadeAccessor(){return m1}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return b0(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=eQ.from(await Q.arrayBuffer()),$=await y0("Storage.metadata()");try{return await $(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){Z.signal?.throwIfAborted();let $=this.getFacadeRoot();return A0($.driver,Q,Z,{fetchTimeoutMs:$.fetchTimeoutMs??v,fetchIdleTimeoutMs:$.fetchIdleTimeoutMs??v})}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 l1,readdir as GZ,access as YZ}from"fs/promises";var n1=["debug","info","notice","warning","error","critical","alert","emergency"],ZZ=n1.indexOf("warning");function v0(Q){if(!Q)return-1;if(Q===!0)return 0;let Z=n1.indexOf(Q);return Z===-1?0:Z}function $Z(){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 f0(Q){try{return JSON.stringify(Q,$Z())}catch{return'"[Unserializable]"'}}function XZ(Q,Z){if(Z==="json")return f0({...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}${$?` ${f0(Q.metadata)}`:""}`}function h0(Q,Z){let $=n1.indexOf(Q.level);if(Z.threshold===-1||$<Z.threshold)return;try{let X=XZ(Q,Z.format)+`
|
|
5
|
+
`;if($>=ZZ)process.stderr.write(X);else process.stdout.write(X)}catch{}}async function i1(Q){try{return await YZ(Q),!0}catch{return!1}}class o1{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${H1()}/storage/logs`}consoleThreshold;constructor(Q){this.config=Q;this.consoleThreshold=v0(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=`${H1()}/storage`;if(!await i1(Q))await l1(Q);if(!await i1(this.logsDirPath))await l1(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await i1(this.logsDirPath))await l1(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 GZ(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={},Y={};if(X)Y={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 K={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:Q,message:Z,metadata:{...G,...$}};if(this.consoleThreshold!==-1)h0({timestamp:K.timestamp,level:Q,message:Z,metadata:{...Y,...$}},{threshold:this.consoleThreshold,format:this.config.consoleFormat});let J="";try{J=JSON.stringify(K)}catch(H){console.log("Error parsing log object",H)}try{let H=this.config.onLogCreated(K);if(H instanceof Promise)H.catch((W)=>console.error("Error in onLogCreated",W))}catch(H){console.error("Error in onLogCreated",H)}if(!this.writer)return;this.writerSize+=J.length,this.fileSize+=J.length;try{this.writer.write(J),this.writer.write(`
|
|
7
|
+
`),this.tryFlush()}catch(H){console.error("Error writing log",H)}}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 KZ extends G1{static getFacadeAccessor(){return o1}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 HZ{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(JZ())(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 JZ(){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 t1=new TextEncoder;function m0(Q){return`id: ${Q.seq}
|
|
8
|
+
data: ${JSON.stringify(Q.event)}
|
|
9
|
+
|
|
10
|
+
`}var WZ=5000,zZ=`: keepalive
|
|
11
|
+
|
|
12
|
+
`;function VZ(Q,Z=WZ){let $=null,X=!1,G=()=>{if(X)return;if($!==null)clearTimeout($);$=setTimeout(()=>{if($=null,X)return;try{Q.enqueue(t1.encode(zZ))}catch{Y();return}G()},Z)},Y=()=>{if(X=!0,$!==null)clearTimeout($);$=null};return G(),{touch:G,stop:Y}}function BZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function e8(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,Y=new ReadableStream({start(K){G=VZ(K)},async pull(K){try{let J=await $.next();if(J.done){G.stop(),K.close();return}X=J.value.seq,K.enqueue(t1.encode(m0(J.value))),G.touch()}catch(J){let H={type:"error",error:DZ(J)};G.stop(),K.enqueue(t1.encode(m0({seq:X+1,event:H}))),K.close()}},cancel(K){G.stop(),$.return?.(K)}});return new Response(Y,{status:Z,headers:BZ()})}var PZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function DZ(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&PZ.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{s1 as Lh,c0 as Mh,MZ as Nh,J0 as Oh,wZ as Ph,V0 as Qh,SZ as Rh,a1 as Sh,r1 as Th,jZ as Uh,LZ as Vh,CZ as Wh,e1 as Xh,xZ as Yh,D0 as Zh,kZ as _h,gZ as $h,a as ai,k as bi,G0 as ci,H0 as di,qZ as ei,NZ as fi,JQ as gi,j0 as hi,WQ as ii,y1 as ji,b1 as ki,zQ as li,m as mi,VQ as ni,G1 as oi,y0 as pi,A1 as qi,Y1 as ri,L0 as si,h1 as ti,M8 as ui,_0 as vi,m1 as wi,O0 as xi,T as yi,c as zi,I1 as Ai,i as Bi,q1 as Ci,N1 as Di,F1 as Ei,J1 as Fi,c1 as Gi,o as Hi,p1 as Ii,W1 as Ji,T1 as Ki,u1 as Li,T0 as Mi,x0 as Ni,E0 as Oi,QZ as Pi,o1 as Qi,KZ as Ri,HZ as Si,zZ as Ti,VZ as Ui,BZ as Vi,e8 as Wi};
|
|
14
|
+
|
|
15
|
+
//# debugId=1FF80412A3AA92A964756E2164756E21
|