gemi 0.194.0 → 0.195.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/{chunk-svtjfmkc.js → chunk-0y7jqe6m.js} +2 -2
  4. package/dist/{chunk-svtjfmkc.js.map → chunk-0y7jqe6m.js.map} +1 -1
  5. package/dist/{chunk-mc8fdh65.js → chunk-39w89wss.js} +2 -2
  6. package/dist/{chunk-mc8fdh65.js.map → chunk-39w89wss.js.map} +1 -1
  7. package/dist/{chunk-1yhvqthv.js → chunk-3qmvtfw2.js} +2 -2
  8. package/dist/{chunk-1yhvqthv.js.map → chunk-3qmvtfw2.js.map} +1 -1
  9. package/dist/{chunk-1m7kqf2t.js → chunk-5qcqwcp7.js} +3 -3
  10. package/dist/{chunk-1m7kqf2t.js.map → chunk-5qcqwcp7.js.map} +1 -1
  11. package/dist/{chunk-3svm89z4.js → chunk-652a9mr0.js} +2 -2
  12. package/dist/{chunk-3svm89z4.js.map → chunk-652a9mr0.js.map} +1 -1
  13. package/dist/{chunk-63dh2zt4.js → chunk-6efjnt6r.js} +2 -2
  14. package/dist/{chunk-63dh2zt4.js.map → chunk-6efjnt6r.js.map} +1 -1
  15. package/dist/{chunk-h9taahxv.js → chunk-7zf8rnsb.js} +3 -3
  16. package/dist/{chunk-h9taahxv.js.map → chunk-7zf8rnsb.js.map} +1 -1
  17. package/dist/chunk-afs0geyy.js +10 -0
  18. package/dist/{chunk-c6khfprk.js.map → chunk-afs0geyy.js.map} +3 -4
  19. package/dist/{chunk-jq1vwj5g.js → chunk-ahx3g8tq.js} +1 -1
  20. package/dist/chunk-ggbf1web.js +5 -0
  21. package/dist/{chunk-gn90agsv.js.map → chunk-ggbf1web.js.map} +1 -1
  22. package/dist/{chunk-scmjmsps.js → chunk-j56zk5a0.js} +3 -3
  23. package/dist/{chunk-scmjmsps.js.map → chunk-j56zk5a0.js.map} +1 -1
  24. package/dist/{chunk-495k9h6p.js → chunk-mndcq5z1.js} +2 -2
  25. package/dist/{chunk-495k9h6p.js.map → chunk-mndcq5z1.js.map} +1 -1
  26. package/dist/{chunk-v20fe53s.js → chunk-nphb176s.js} +9 -9
  27. package/dist/{chunk-v20fe53s.js.map → chunk-nphb176s.js.map} +5 -4
  28. package/dist/{chunk-geqdq8hp.js → chunk-p4eger3g.js} +2 -2
  29. package/dist/{chunk-geqdq8hp.js.map → chunk-p4eger3g.js.map} +1 -1
  30. package/dist/{chunk-xpkpz4g6.js → chunk-vqq0z746.js} +2 -2
  31. package/dist/{chunk-xpkpz4g6.js.map → chunk-vqq0z746.js.map} +1 -1
  32. package/dist/{chunk-5nkg3rmw.js → chunk-xjb8frdx.js} +3 -3
  33. package/dist/{chunk-5nkg3rmw.js.map → chunk-xjb8frdx.js.map} +1 -1
  34. package/dist/console/run.js +2 -2
  35. package/dist/console/run.js.map +1 -1
  36. package/dist/database/index.js +1 -1
  37. package/dist/facades/index.js +2 -2
  38. package/dist/facades/index.js.map +1 -1
  39. package/dist/http/index.js +2 -2
  40. package/dist/http/index.js.map +1 -1
  41. package/dist/i18n/index.js +2 -2
  42. package/dist/i18n/index.js.map +1 -1
  43. package/dist/kernel/index.js +2 -2
  44. package/dist/kernel/index.js.map +1 -1
  45. package/dist/orm/index.js +2 -2
  46. package/dist/orm/index.js.map +1 -1
  47. package/dist/server/index.js +1 -1
  48. package/dist/services/index.d.ts +1 -1
  49. package/dist/services/index.d.ts.map +1 -1
  50. package/dist/services/index.js +3 -3
  51. package/dist/services/index.js.map +1 -1
  52. package/dist/services/logging/LogManager.d.ts +10 -1
  53. package/dist/services/logging/LogManager.d.ts.map +1 -1
  54. package/dist/services/logging/config.d.ts +29 -0
  55. package/dist/services/logging/config.d.ts.map +1 -1
  56. package/dist/services/queue/work.js +2 -2
  57. package/dist/services/queue/work.js.map +1 -1
  58. package/dist/support/index.js +2 -2
  59. package/dist/support/index.js.map +1 -1
  60. package/package.json +1 -1
  61. package/dist/chunk-c6khfprk.js +0 -10
  62. package/dist/chunk-gn90agsv.js +0 -5
  63. /package/dist/{chunk-jq1vwj5g.js.map → chunk-ahx3g8tq.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{W as P,Y as c,Z as f,_ as l}from"./chunk-1yhvqthv.js";import{na as u,oa as m}from"./chunk-7t60d5qy.js";import"./chunk-bwg7genv.js";import"./chunk-mvd4mc8p.js";import"./chunk-7txst143.js";import"./chunk-08m9egzx.js";import"./chunk-s0z61m9j.js";import"./chunk-b6zqjyn1.js";import{gj as S}from"./chunk-228w21t6.js";import{yl as T}from"./chunk-j49vh5bs.js";import{Ol as y}from"./chunk-2g2fsr71.js";import"./chunk-vgxkt9vd.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{W as P,Y as c,Z as f,_ as l}from"./chunk-3qmvtfw2.js";import{na as u,oa as m}from"./chunk-7t60d5qy.js";import"./chunk-bwg7genv.js";import"./chunk-mvd4mc8p.js";import"./chunk-7txst143.js";import"./chunk-08m9egzx.js";import"./chunk-s0z61m9j.js";import"./chunk-b6zqjyn1.js";import{gj as S}from"./chunk-228w21t6.js";import{yl as T}from"./chunk-j49vh5bs.js";import{Ol as y}from"./chunk-2g2fsr71.js";import"./chunk-vgxkt9vd.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
3
  `).split(`
4
4
  `).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
5
5
  `).trim()}function N(J){return`
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{ke as o}from"./chunk-652a9mr0.js";import{le as i}from"./chunk-vqq0z746.js";import{pk as t}from"./chunk-beckfwe9.js";import{pl as r}from"./chunk-8e17k7ht.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
3
+ export{n as bb};
4
+
5
+ //# debugId=BDE7A4D4B6CA957C64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { ServiceProvider } from \"../support/ServiceProvider\";\nimport { withDefaults } from \"../support/withDefaults\";\nimport { Translator } from \"./Translator\";\nimport { translationConfigDefaults, type TranslationConfig } from \"./config\";\n\nexport class TranslationServiceProvider extends ServiceProvider {\n register() {\n this.app.singleton(\n Translator,\n () =>\n new Translator(\n withDefaults(\n translationConfigDefaults(),\n this.app.config.get<TranslationConfig>(\"translation\", {}),\n ),\n ),\n );\n }\n}\n"
6
6
  ],
7
7
  "mappings": ";sLAKO,AAAM,IAAmC,LAAgB,CAC9D,QAAQ,EAAG,CACT,KAAK,IAAI,UACP,EACA,IACE,IAAI,EACF,EACE,EAA0B,EAC1B,KAAK,IAAI,OAAO,IAAuB,cAAe,CAAC,CAAC,CAC1D,CACF,CACJ,EAEJ",
8
- "debugId": "24D2145F126B46BD64756E2164756E21",
8
+ "debugId": "BDE7A4D4B6CA957C64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ah as R,Bh as Y,Ch as M,Dh as Q,Eh as O,Fh as y,Lh as U,yh as K,zh as L}from"./chunk-geqdq8hp.js";import{Nj as G,Oj as W}from"./chunk-1705yamg.js";var S=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,I=/^\s*as\s+(jsonb|json)\s*\)/i,P=/\bcast\s*\(\s*$/i,T=new Set;function _(k,B){if(!B.typesParametersFromStatement)return{fragment:k,jsonParameters:T};let q=Y(k),z=new Set,D;for(let H=0;H<q.length-1;H++){let X=q[H+1],$=S.exec(X);if($){D??=[...q],D[H+1]=`::text::${$[1]}${X.slice($[0].length)}`,z.add(H);continue}let J=I.exec(X);if(J&&P.test((D??q)[H]))D??=[...q],D[H+1]=` as text)::${J[1]}${X.slice(J[0].length)}`,z.add(H)}if(!D)return{fragment:k,jsonParameters:z};return{fragment:M(D,k.binders),jsonParameters:z}}function C(k,B){if(k===null||k===void 0)return null;let q=U(k);if(q==="db")return null;if(q==="json")return"null";if(q==="any")throw new W(B,"DB",B,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof k==="string")return k;let z;try{z=JSON.stringify(k)}catch(D){throw new W(B,"DB",B,`A parameter cast to json could not be serialised: ${D instanceof Error?D.message:String(D)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(z===void 0)throw new W(B,"DB",B,`A ${typeof k} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return z}var N=new WeakSet;function Z(k){return N.add(k),k}function V(k){return typeof k==="object"&&k!==null&&N.has(k)}function g(k,...B){if(!Array.isArray(k)||!("raw"in k))throw new G("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let q=[];for(let z=0;z<k.length;z++)if(q.push(L(k[z])),z<B.length)q.push(F(B[z]));return Z(Q(...q))}function m(k,B=", "){if(!Array.isArray(k))throw new W("join","DB","sql",`Expected an array of fragments or values, got ${typeof k}.`);if(k.length===0)return b;let q=k.map(F);if(V(B)){let z=[];for(let D=0;D<q.length;D++){if(D>0)z.push(B);z.push(q[D])}return Z(Q(...z))}return j(B),Z(O(q,B))}var h=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function j(k){if(typeof k==="string"&&h.test(k))return;throw new W("join","DB","sql",typeof k==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(k)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${k===null?"null":typeof k}.`)}var b=Z(Object.freeze({text:"",binders:Object.freeze([])}));function v(k){if(typeof k!=="string")throw new W("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(k)?"an array":typeof k}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return Z(L(k))}function p(k,B,q="query"){if(!V(k))throw new W(q,"DB",q,`Expected a fragment built with 'sql', got ${k===null?"null":typeof k}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let z=_(k,B),D=y(z.fragment,B,{model:"DB",operation:q});return{text:D.text,values:K(D.binders)(void 0).map((H,X)=>z.jsonParameters.has(X)?C(H,q):H===null||H===void 0?H??null:B.encodeUntyped(H))}}function F(k){if(V(k))return k;return R(()=>k)}
3
- export{g as sh,m as th,b as uh,v as vh,p as wh};
2
+ import{Ah as M,Bh as Q,Ch as O,Dh as y,Jh as U,wh as K,xh as L,yh as R,zh as Y}from"./chunk-p4eger3g.js";import{Nj as G,Oj as W}from"./chunk-1705yamg.js";var S=/^\s*::\s*(?:text\s*::\s*)?(jsonb|json)\b(?!\s*\[)/i,I=/^\s*as\s+(jsonb|json)\s*\)/i,P=/\bcast\s*\(\s*$/i,T=new Set;function _(k,B){if(!B.typesParametersFromStatement)return{fragment:k,jsonParameters:T};let q=Y(k),z=new Set,D;for(let H=0;H<q.length-1;H++){let X=q[H+1],$=S.exec(X);if($){D??=[...q],D[H+1]=`::text::${$[1]}${X.slice($[0].length)}`,z.add(H);continue}let J=I.exec(X);if(J&&P.test((D??q)[H]))D??=[...q],D[H+1]=` as text)::${J[1]}${X.slice(J[0].length)}`,z.add(H)}if(!D)return{fragment:k,jsonParameters:z};return{fragment:M(D,k.binders),jsonParameters:z}}function C(k,B){if(k===null||k===void 0)return null;let q=U(k);if(q==="db")return null;if(q==="json")return"null";if(q==="any")throw new W(B,"DB",B,"Prisma.AnyNull is a filter operand \u2014 it asks for a SQL NULL *or* a JSON "+"null \u2014 so it has no single value to bind. Write the one you mean: "+"Prisma.DbNull for the column being NULL, Prisma.JsonNull for the JSON value.");if(typeof k==="string")return k;let z;try{z=JSON.stringify(k)}catch(D){throw new W(B,"DB",B,`A parameter cast to json could not be serialised: ${D instanceof Error?D.message:String(D)}. `+"Bind text you have serialised yourself if the value is not JSON \u2014 a "+"bigint has no JSON form, and neither does a cycle.")}if(z===void 0)throw new W(B,"DB",B,`A ${typeof k} was bound to a parameter cast to json, and has no JSON form. Bind the value it stands for.`);return z}var N=new WeakSet;function Z(k){return N.add(k),k}function V(k){return typeof k==="object"&&k!==null&&N.has(k)}function g(k,...B){if(!Array.isArray(k)||!("raw"in k))throw new G("sql","DB","sql","'sql' is a tagged template \u2014 write sql`select 1`, not sql(\"select 1\"). "+"To put text that is not a value into a statement, use 'unsafeSql', and read what it says first.");let q=[];for(let z=0;z<k.length;z++)if(q.push(L(k[z])),z<B.length)q.push(F(B[z]));return Z(Q(...q))}function m(k,B=", "){if(!Array.isArray(k))throw new W("join","DB","sql",`Expected an array of fragments or values, got ${typeof k}.`);if(k.length===0)return b;let q=k.map(F);if(V(B)){let z=[];for(let D=0;D<q.length;D++){if(D>0)z.push(B);z.push(q[D])}return Z(Q(...z))}return j(B),Z(O(q,B))}var h=/^[\s,]*$|^\s*(?:and|or)\s*$/i;function j(k){if(typeof k==="string"&&h.test(k))return;throw new W("join","DB","sql",typeof k==="string"?`A separator is written into the SQL text, so it may only be glue: whitespace, commas, or 'and' / 'or'. Got ${JSON.stringify(k)}. If that is deliberate, say so with `+"unsafeSql(...) \u2014 and never build one from anything that came from "+"outside the program.":`Expected a separator string or a fragment, got ${k===null?"null":typeof k}.`)}var b=Z(Object.freeze({text:"",binders:Object.freeze([])}));function v(k){if(typeof k!=="string")throw new W("unsafeSql","DB","sql",`Expected a string literal, got ${Array.isArray(k)?"an array":typeof k}. 'unsafeSql' is a plain call, not a tagged template \u2014 a template would `+"interpolate values into the SQL text, which is the one thing it must never do.");return Z(L(k))}function p(k,B,q="query"){if(!V(k))throw new W(q,"DB",q,`Expected a fragment built with 'sql', got ${k===null?"null":typeof k}. A plain string is not accepted here on purpose \u2014 it would be the one `+"path into the SQL text that nobody had to think about.");let z=_(k,B),D=y(z.fragment,B,{model:"DB",operation:q});return{text:D.text,values:K(D.binders)(void 0).map((H,X)=>z.jsonParameters.has(X)?C(H,q):H===null||H===void 0?H??null:B.encodeUntyped(H))}}function F(k){if(V(k))return k;return R(()=>k)}
3
+ export{g as qh,m as rh,b as sh,v as th,p as uh};
4
4
 
5
- //# debugId=858BEB33CA7DA11664756E2164756E21
5
+ //# debugId=30C5CDE00EB7E23E64756E2164756E21
@@ -6,6 +6,6 @@
6
6
  "import type { SqlDialect } from \"./dialect\";\nimport {\n InvalidArgumentError,\n UnsupportedQueryError,\n} from \"./errors\";\nimport {\n type Fragment,\n bindValues,\n concat,\n joinFragments,\n param,\n render,\n sql as text,\n} from \"./compile/fragment\";\nimport { jsonTextParameter, retypeJsonParameters } from \"./json-param\";\n\n/**\n * SQL fragments as first-class values: `sql`, `join`, `empty`, and one door out.\n *\n * The ORM deliberately does not implement every SQL shape — `distinct`, cursor\n * pagination, window functions, recursive CTEs. That is the right call, but it\n * is only half a decision: the shapes it declines have to have somewhere to go,\n * and \"drop to raw SQL\" is not an answer if raw SQL cannot be *composed*.\n *\n * `DB.sql` — Bun's tagged template — covers a single self-contained statement,\n * and that is genuinely all it covers. The shape it cannot express is the common\n * one: a predicate list built conditionally, passed around as a value, and\n * interpolated into a larger statement.\n *\n * ```ts\n * const filters = []\n * if (q) filters.push(sql`name ilike ${`%${q}%`}`)\n * if (organizationId) filters.push(sql`\"organizationId\" = ${organizationId}`)\n *\n * const where = filters.length ? sql`where ${join(filters, \" and \")}` : empty\n * const rows = await DB.query(sql`select * from \"Product\" ${where} limit ${20}`)\n * ```\n *\n * ## This is the compiler's own `Fragment`, made public\n *\n * Not a parallel mechanism. `compile/fragment.ts` has held exactly this shape\n * since iteration 1 — text plus positional binders, composable, never\n * concatenating a value into the text — because that is what invariant 2 needs\n * internally. Reusing it means a public fragment binds by the same rule the\n * compiler's own SQL does, and it means the parameter ceiling, the placeholder\n * numbering and the dialect split are all already handled rather than\n * reimplemented one door down.\n *\n * **Placeholders are assigned at assembly, not at authoring.** SQLite writes\n * `?` and Postgres writes `$1`, `$2`, and a fragment does not know where in the\n * final statement it will land — so `sql` records a *position* and `render`\n * turns it into a placeholder once the whole statement exists. That is what lets\n * the same fragment be nested, reused twice in one statement, or built before\n * the dialect is even known.\n */\n\n/**\n * A composable piece of SQL. Its values are bound parameters, never text.\n *\n * Opaque on purpose: an application builds one with `sql`, combines it with\n * `join`, and hands it to `DB.query` / `DB.execute`. Reading `.text` off it is\n * not part of the contract — it holds parameter *markers* rather than the\n * dialect's placeholders, so it is not the statement that runs.\n */\nexport type SqlFragment = Fragment;\n\n/**\n * Every fragment this module has produced.\n *\n * **Identity, not shape, and the difference is a SQL injection.** `interpolate`\n * splices a fragment as text and binds everything else, so \"is this a fragment\"\n * decides whether a value reaches the statement or a parameter. Asking the\n * *shape* — a `text` string and a `binders` array — makes that decision\n * answerable by anything that can name two properties, and `{\"text\": \"…\",\n * \"binders\": []}` is two lines of JSON:\n *\n * ```ts\n * const body = await request.json()\n * await DB.query(sql`select \"email\" from \"User\" where \"email\" = ${body.email}`)\n * // body.email = { text: `'' union select \"password\" from \"User\"`, binders: [] }\n * // -> select \"email\" from \"User\" where \"email\" = '' union select \"password\" from \"User\"\n * ```\n *\n * That is the intended call site with the intended safe value, and it returned\n * the password column out of a statement selecting only `email`. The internal\n * `Fragment` never had the problem because nothing outside `compile/` could\n * construct one; making the type public is what turned \"text plus binders\" from\n * an implementation detail into a shape an attacker can name. `unsafeSql` is\n * built so that reaching for the escape hatch is a decision — a structural check\n * is a second, unmarked door beside it.\n *\n * A `WeakSet` the module owns cannot be forged: membership is granted only by\n * the constructors below. It registers the *returned* object rather than\n * stamping a property, because `concat` and `joinFragments` return fresh objects\n * — a marker property on the inputs would not survive them, and the version that\n * cannot drift is the one that brands what actually comes out.\n */\nconst FRAGMENTS = new WeakSet<object>();\n\nfunction brand(fragment: Fragment): SqlFragment {\n FRAGMENTS.add(fragment);\n return fragment;\n}\n\n/** Whether a value is a fragment *this module made*, so it splices rather than binds. */\nfunction isFragment(value: unknown): value is Fragment {\n return typeof value === \"object\" && value !== null && FRAGMENTS.has(value);\n}\n\n/**\n * A SQL fragment. Every `${value}` is bound as a parameter; a `${fragment}` is\n * spliced in, carrying its own parameters with it.\n *\n * ```ts\n * sql`where \"id\" = ${id}` // \"id\" = $1, with id bound\n * sql`where ${sql`\"a\" = ${1}`} and ${sql`\"b\" = ${2}`}` // nests to any depth\n * ```\n *\n * An interpolated **array** is bound as one value, not expanded — that is what\n * Postgres's `= any($1)` wants, and it is the only reading that does not depend\n * on the dialect. For a comma-separated list of placeholders, say so with\n * `join`.\n *\n * A value at a `::jsonb` cast the caller wrote is the one parameter with a type\n * behind it, and it is bound as **JSON text** so that the statement means what\n * the same statement meant under Prisma's `$executeRaw`:\n *\n * ```ts\n * sql`… set payload = payload || ${JSON.stringify(patch)}::jsonb` // merges\n * ```\n *\n * Without that the driver would JSON-encode the string and the column would\n * hold the document as a jsonb *string* — which `||` appends as an array\n * element rather than merging. `json-param.ts` has the measurements.\n */\nexport function sql(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): SqlFragment {\n // A defensive check rather than a type error, because the interesting misuse\n // is `sql(userInput)` — a plain call with a string, which would otherwise\n // reach `strings.raw` as `undefined` and produce a fragment of `undefined`\n // text rather than an error. It is also the shape somebody reaches for when\n // they want the escape hatch and have not found `unsafeSql`.\n if (!Array.isArray(strings) || !(\"raw\" in (strings as object))) {\n throw new UnsupportedQueryError(\n \"sql\",\n \"DB\",\n \"sql\",\n `'sql' is a tagged template — write sql\\`select 1\\`, not sql(\"select 1\"). ` +\n `To put text that is not a value into a statement, use 'unsafeSql', ` +\n `and read what it says first.`,\n );\n }\n\n const parts: Fragment[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n parts.push(text(strings[i]));\n if (i < values.length) parts.push(interpolate(values[i]));\n }\n\n return brand(concat(...parts));\n}\n\n/**\n * Fragments — or values — joined by a separator, the way `Array.join` reads.\n *\n * ```ts\n * join(filters, \" and \") // a and b and c\n * join([sql`\"a\" asc`, sql`\"b\" desc`]) // \"a\" asc, \"b\" desc\n * join(ids) // $1, $2, $3 — each bound\n * ```\n *\n * An **empty list produces `empty`**, not a separator and not a syntax error, so\n * `join` composes with a list that turned out to have nothing in it. That is the\n * case a caller forgets, and it is the one that would otherwise emit `where ` and\n * fail at the database rather than here.\n *\n * ## The separator is text, so it is not a free string\n *\n * It goes between the fragments *in the statement*, which makes it the one other\n * place a string could reach the SQL — and this module's whole claim is that\n * `unsafeSql` is **the** door. So a plain-string separator has to be glue and\n * nothing else: whitespace, commas, or a boolean connective. Anything more\n * expressive is legitimate and has to say so:\n *\n * ```ts\n * join(filters, \" and \") // fine\n * join(parts, unsafeSql(\") and (\")) // fine, and visibly a decision\n * join(ids, request.query.sep) // refused\n * ```\n *\n * A **blocklist would not do**, which is why this is an allowlist. The obvious\n * one — reject quotes, semicolons and comment markers — lets this through:\n *\n * join([1, 2], \") or 1=1 union select password from Users where 1=(1\")\n *\n * No quote, no `--`, still an injection. There is no sound way to say \"this\n * arbitrary text is safe glue\", so the rule is that glue is a small closed set\n * and everything else is a fragment somebody built on purpose.\n */\nexport function join(\n values: readonly unknown[],\n separator: string | SqlFragment = \", \",\n): SqlFragment {\n if (!Array.isArray(values)) {\n throw new InvalidArgumentError(\n \"join\",\n \"DB\",\n \"sql\",\n `Expected an array of fragments or values, got ${typeof values}.`,\n );\n }\n if (values.length === 0) return empty;\n\n const parts = values.map(interpolate);\n\n if (isFragment(separator)) {\n const woven: Fragment[] = [];\n for (let i = 0; i < parts.length; i++) {\n if (i > 0) woven.push(separator);\n woven.push(parts[i]);\n }\n return brand(concat(...woven));\n }\n\n assertGlue(separator);\n return brand(joinFragments(parts, separator));\n}\n\n/**\n * Whitespace and commas, or a boolean connective surrounded by whitespace.\n *\n * Deliberately small. Every separator a composed statement actually needs is in\n * here — `\", \"`, `\" and \"`, `\" or \"`, `\" \"` — and everything outside it is\n * expressive enough to change what the statement *does*, which is the property\n * that makes it a `unsafeSql` decision rather than a string argument.\n */\nconst GLUE = /^[\\s,]*$|^\\s*(?:and|or)\\s*$/i;\n\nfunction assertGlue(separator: unknown): void {\n if (typeof separator === \"string\" && GLUE.test(separator)) return;\n\n throw new InvalidArgumentError(\n \"join\",\n \"DB\",\n \"sql\",\n typeof separator === \"string\"\n ? `A separator is written into the SQL text, so it may only be glue: ` +\n `whitespace, commas, or 'and' / 'or'. Got ` +\n `${JSON.stringify(separator)}. If that is deliberate, say so with ` +\n `unsafeSql(...) — and never build one from anything that came from ` +\n `outside the program.`\n : `Expected a separator string or a fragment, got ${\n separator === null ? \"null\" : typeof separator\n }.`,\n );\n}\n\n/**\n * The fragment that contributes nothing.\n *\n * The point of it is that `where ${empty}` and `where ${filter}` are the same\n * expression — a conditional predicate is a value, not a branch around the\n * statement. Frozen, because it is shared by every caller and a fragment is read\n * as immutable everywhere else.\n */\nexport const empty: SqlFragment = brand(\n Object.freeze({ text: \"\", binders: Object.freeze([]) as [] }),\n);\n\n/**\n * **Text straight into the SQL, with no parameter around it.** The one door in\n * this ORM through which a value reaches the statement text.\n *\n * Everything else in the compiler exists to make this impossible — identifiers\n * come from the generated schema, values are bound — so reaching for it should\n * feel like reaching for it. **Never give it a value that came from a request, a\n * form, a URL, a header, a queue payload or a database row.** There is no\n * escaping here and there will not be: escaping that is \"usually right\" is worse\n * than none, because it survives review.\n *\n * ## Why it exists at all, since that is the fair question\n *\n * Plan quality can depend on *not* parameterising. A partial index declared as\n *\n * ```sql\n * create index … on \"Job\" (…) where \"name\" is distinct from 'reaper'\n * ```\n *\n * is only usable if the planner can prove the query's predicate matches the\n * index's. A bound parameter is opaque at plan time, so `where \"name\" is\n * distinct from $1` does not match — and the query falls back to a sequential\n * scan over the whole table. The constant has to be *in the text*:\n *\n * ```ts\n * const REAPER = unsafeSql(`'reaper'`) // a literal in this file, never input\n * await DB.query(sql`\n * select … from \"Job\" where \"name\" is distinct from ${REAPER} …\n * `)\n * ```\n *\n * A builder with no escape hatch cannot express that at any price, and the\n * workaround — hand-writing the whole statement — loses composition for every\n * other part of it.\n *\n * The same applies to the other things that cannot be parameters in SQL:\n * identifiers, a sort direction, a table name chosen from a fixed set in code.\n * All of them share the rule above — the value is written in the source file, or\n * chosen from a set written in the source file, never passed in.\n */\nexport function unsafeSql(literal: string): SqlFragment {\n if (typeof literal !== \"string\") {\n throw new InvalidArgumentError(\n \"unsafeSql\",\n \"DB\",\n \"sql\",\n `Expected a string literal, got ${\n Array.isArray(literal) ? \"an array\" : typeof literal\n }. 'unsafeSql' is a plain call, not a tagged template — a template would ` +\n `interpolate values into the SQL text, which is the one thing it must ` +\n `never do.`,\n );\n }\n return brand(text(literal));\n}\n\n/**\n * A fragment as the statement a driver can run: the dialect's placeholders in\n * the text, and the values in the order they appear.\n *\n * Separate from the executing, and exported, because it is the half that is a\n * pure function of `(fragment, dialect)` — so a test can assert what a\n * composition emits on both dialects without a database anywhere near it, which\n * is exactly how the rest of the compiler is tested.\n *\n * `render` also applies the parameter ceiling here, which matters more for a\n * hand-built fragment than for a compiled plan: `join(ids)` over a\n * request-derived list is one placeholder per element on SQLite, and 40 000 of\n * them is a driver error rather than a clear one.\n */\nexport function renderFragment(\n fragment: SqlFragment,\n dialect: SqlDialect,\n operation = \"query\",\n): { text: string; values: unknown[] } {\n if (!isFragment(fragment)) {\n throw new InvalidArgumentError(\n operation,\n \"DB\",\n operation,\n `Expected a fragment built with 'sql', got ${\n fragment === null ? \"null\" : typeof fragment\n }. A plain string is not accepted here on purpose — it would be the one ` +\n `path into the SQL text that nobody had to think about.`,\n );\n }\n\n // The one thing a raw parameter can be *told* about its type: a `::jsonb` the\n // caller wrote onto their own placeholder. Where there is one, the parameter\n // is retyped through `text` and its value serialised, because Bun otherwise\n // JSON-encodes a string bound to a `jsonb` parameter and stores the document\n // as a jsonb *string* where Prisma stored the object. See `json-param.ts` —\n // the mechanism, the measurements, and why a string is not serialised here\n // while `fieldParam` serialises one.\n //\n // The dialect is passed because this is not universal, and the reason is\n // narrower than it looks: `::` is Postgres-only syntax, but `cast(? as json)`\n // *parses and runs* on SQLite, where it means NUMERIC affinity — so retyping\n // it would rewrite a working statement into `cast(? as text)::json`, which\n // SQLite cannot parse. `typesParametersFromStatement` is false there.\n const json = retypeJsonParameters(fragment, dialect);\n\n const rendered = render(json.fragment, dialect, { model: \"DB\", operation });\n return {\n text: rendered.text,\n // `encodeUntyped` and not `encode`: there is no field here to ask, which is\n // the whole difference between a fragment's parameters and a compiled\n // plan's. It normalises the two JavaScript types whose SQL form the ORM has\n // already decided — a `Date` and a boolean — so a raw statement compares\n // against ORM-written rows on both dialects rather than only on Postgres.\n values: bindValues(rendered.binders)(undefined).map((value, index) =>\n json.jsonParameters.has(index)\n ? jsonTextParameter(value, operation)\n : value === null || value === undefined\n ? (value ?? null)\n : dialect.encodeUntyped(value),\n ),\n };\n}\n\n/**\n * One interpolated slot: a fragment splices, anything else binds.\n *\n * The binder ignores both its arguments. A compiled plan's binders read the\n * *call's* argument tree, because one plan serves many calls; a fragment is\n * built per call and closes over the value it was given, which is the whole\n * difference between the compiler's fragments and these.\n */\nfunction interpolate(value: unknown): Fragment {\n if (isFragment(value)) return value;\n return param(() => value);\n}\n"
7
7
  ],
8
8
  "mappings": ";gKA0IA,FAAM,EAAgB,qDAehB,EAAgB,8BAQhB,EAAY,mBAGZ,EAA6B,IAAI,IAYhC,SAAS,CAAoB,CAClC,EACA,EAIA,CACA,GAAI,CAAC,EAAQ,6BACX,MAAO,CAAE,WAAU,eAAgB,CAAM,EAG3C,IAAM,EAAW,EAAc,CAAQ,EACjC,EAAiB,IAAI,IACvB,EAKJ,QAAS,EAAQ,EAAG,EAAQ,EAAS,OAAS,EAAG,IAAS,CACxD,IAAM,EAAQ,EAAS,EAAQ,GAEzB,EAAW,EAAc,KAAK,CAAK,EACzC,GAAI,EAAU,CACZ,IAAc,CAAC,GAAG,CAAQ,EAC1B,EAAU,EAAQ,GAChB,WAAW,EAAS,KAAK,EAAM,MAAM,EAAS,GAAG,MAAM,IACzD,EAAe,IAAI,CAAK,EACxB,SAGF,IAAM,EAAK,EAAc,KAAK,CAAK,EAKnC,GAAI,GAAM,EAAU,MAAM,GAAa,GAAU,EAAM,EACrD,IAAc,CAAC,GAAG,CAAQ,EAC1B,EAAU,EAAQ,GAAK,cAAc,EAAG,KAAK,EAAM,MAAM,EAAG,GAAG,MAAM,IACrE,EAAe,IAAI,CAAK,EAI5B,GAAI,CAAC,EAAW,MAAO,CAAE,WAAU,gBAAe,EAClD,MAAO,CACL,SAAU,EAAkB,EAAW,EAAS,OAAO,EACvD,gBACF,EAYK,SAAS,CAAiB,CAAC,EAAgB,EAA4B,CAO5E,GAAI,IAAU,MAAQ,IAAU,OAAW,OAAO,KAKlD,IAAM,EAAW,EAAa,CAAK,EACnC,GAAI,IAAa,KAAM,OAAO,KAC9B,GAAI,IAAa,OAAQ,MAAO,OAChC,GAAI,IAAa,MACf,MAAM,IAAI,EACR,EACA,KACA,EACA,gFACE,0EACA,8EAEJ,EAMF,GAAI,OAAO,IAAU,SAAU,OAAO,EAEtC,IAAI,EACJ,GAAI,CACF,EAAO,KAAK,UAAU,CAAK,EAC3B,MAAO,EAAO,CAId,MAAM,IAAI,EACR,EACA,KACA,EACA,qDACK,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,MACxD,4EACA,oDACJ,EAMF,GAAI,IAAS,OACX,MAAM,IAAI,EACR,EACA,KACA,EACA,KAAK,OAAO,8FAEd,EAGF,OAAO,ECxMT,IAAM,EAAY,IAAI,QAEtB,SAAS,CAAK,CAAC,EAAiC,CAE9C,OADA,EAAU,IAAI,CAAQ,EACf,EAIT,SAAS,CAAU,CAAC,EAAmC,CACrD,OAAO,OAAO,IAAU,UAAY,IAAU,MAAQ,EAAU,IAAI,CAAK,EA6BpE,SAAS,CAAG,CACjB,KACG,EACU,CAMb,GAAI,CAAC,MAAM,QAAQ,CAAO,GAAK,EAAE,QAAU,GACzC,MAAM,IAAI,EACR,MACA,KACA,MACA,iFACE,iGAEJ,EAGF,IAAM,EAAoB,CAAC,EAE3B,QAAS,EAAI,EAAG,EAAI,EAAQ,OAAQ,IAElC,GADA,EAAM,KAAK,EAAK,EAAQ,EAAE,CAAC,EACvB,EAAI,EAAO,OAAQ,EAAM,KAAK,EAAY,EAAO,EAAE,CAAC,EAG1D,OAAO,EAAM,EAAO,GAAG,CAAK,CAAC,EAwCxB,SAAS,CAAI,CAClB,EACA,EAAkC,KACrB,CACb,GAAI,CAAC,MAAM,QAAQ,CAAM,EACvB,MAAM,IAAI,EACR,OACA,KACA,MACA,iDAAiD,OAAO,IAC1D,EAEF,GAAI,EAAO,SAAW,EAAG,OAAO,EAEhC,IAAM,EAAQ,EAAO,IAAI,CAAW,EAEpC,GAAI,EAAW,CAAS,EAAG,CACzB,IAAM,EAAoB,CAAC,EAC3B,QAAS,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACrC,GAAI,EAAI,EAAG,EAAM,KAAK,CAAS,EAC/B,EAAM,KAAK,EAAM,EAAE,EAErB,OAAO,EAAM,EAAO,GAAG,CAAK,CAAC,EAI/B,OADA,EAAW,CAAS,EACb,EAAM,EAAc,EAAO,CAAS,CAAC,EAW9C,IAAM,EAAO,+BAEb,SAAS,CAAU,CAAC,EAA0B,CAC5C,GAAI,OAAO,IAAc,UAAY,EAAK,KAAK,CAAS,EAAG,OAE3D,MAAM,IAAI,EACR,OACA,KACA,MACA,OAAO,IAAc,SACjB,8GAEG,KAAK,UAAU,CAAS,yCAC3B,0EACA,uBACA,kDACE,IAAc,KAAO,OAAS,OAAO,IAE7C,EAWK,IAAM,EAAqB,EAChC,OAAO,OAAO,CAAE,KAAM,GAAI,QAAS,OAAO,OAAO,CAAC,CAAC,CAAQ,CAAC,CAC9D,EA0CO,SAAS,CAAS,CAAC,EAA8B,CACtD,GAAI,OAAO,IAAY,SACrB,MAAM,IAAI,EACR,YACA,KACA,MACA,kCACE,MAAM,QAAQ,CAAO,EAAI,WAAa,OAAO,iFAE7C,gFAEJ,EAEF,OAAO,EAAM,EAAK,CAAO,CAAC,EAiBrB,SAAS,CAAc,CAC5B,EACA,EACA,EAAY,QACyB,CACrC,GAAI,CAAC,EAAW,CAAQ,EACtB,MAAM,IAAI,EACR,EACA,KACA,EACA,6CACE,IAAa,KAAO,OAAS,OAAO,gFAEpC,wDACJ,EAgBF,IAAM,EAAO,EAAqB,EAAU,CAAO,EAE7C,EAAW,EAAO,EAAK,SAAU,EAAS,CAAE,MAAO,KAAM,WAAU,CAAC,EAC1E,MAAO,CACL,KAAM,EAAS,KAMf,OAAQ,EAAW,EAAS,OAAO,EAAE,MAAS,EAAE,IAAI,CAAC,EAAO,IAC1D,EAAK,eAAe,IAAI,CAAK,EACzB,EAAkB,EAAO,CAAS,EAClC,IAAU,MAAQ,IAAU,OACzB,GAAS,KACV,EAAQ,cAAc,CAAK,CACnC,CACF,EAWF,SAAS,CAAW,CAAC,EAA0B,CAC7C,GAAI,EAAW,CAAK,EAAG,OAAO,EAC9B,OAAO,EAAM,IAAM,CAAK",
9
- "debugId": "858BEB33CA7DA11664756E2164756E21",
9
+ "debugId": "30C5CDE00EB7E23E64756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  class m{name;cron;withoutOverlapping=!1;onOneServer=!1;shouldRun(){return!0}callback(f){}onTick(){}onComplete(){}static exp(f){return f}}
3
- export{m as Rd};
3
+ export{m as Pd};
4
4
 
5
- //# debugId=269EE810896CDB8E64756E2164756E21
5
+ //# debugId=1042DD191854A08764756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "// A cron expression accepted by `Bun.cron`: a 5-field expression\n// (`minute hour day-of-month month day-of-week`, interpreted in UTC) or one of\n// the nicknames below. The `string & {}` member keeps arbitrary expressions\n// assignable while still surfacing the nicknames in editor autocomplete.\nexport type CronExpression =\n | \"@yearly\"\n | \"@annually\"\n | \"@monthly\"\n | \"@weekly\"\n | \"@daily\"\n | \"@midnight\"\n | \"@hourly\"\n | (string & {});\n\nimport type { HeldLock } from \"../lock/LockManager\";\n\nexport type WithoutOverlapping =\n | boolean\n | {\n /**\n * The lock's lease, in milliseconds: how long it outlives an instance\n * that died holding it. Renewed every third of this while the tick\n * runs, so it does not limit how long a tick may take. Default five\n * minutes.\n */\n expiresAfter?: number;\n };\n\nexport class CronJob {\n name: string;\n cron: CronExpression;\n\n /**\n * Skips a tick while an earlier tick of this job is still running, on this\n * instance or any other sharing the queue's storage. With the database\n * queue driver that is a lock row in `gemi_locks`; with the memory driver\n * it only covers this process.\n *\n * The lock is held across `onTick`, `callback` and `onComplete`, and handed\n * to `callback` as its argument. If its lease is lost while the tick runs\n * (the instance stalled past `expiresAfter`), `lock.lost` aborts and the\n * scheduler logs it. Writes that must not land after that go through\n * `lock.fence(...)`.\n *\n * It does not stop a second instance from running the same tick after the\n * first one finished; `onOneServer` does.\n */\n withoutOverlapping: WithoutOverlapping = false;\n\n /**\n * Runs each tick on one instance only, across every instance sharing the\n * queue's storage: the first to claim the tick's minute runs it, the others\n * skip it. Assumes the instances' clocks agree to well within a minute.\n */\n onOneServer = false;\n\n /**\n * Decides whether this tick happens at all. Evaluated once per tick, before\n * anything else; returning `false` skips `onTick`, `callback` and\n * `onComplete` alike.\n *\n * ### Why this is a member and not a line the job writes for itself\n *\n * A job that reports outward — mails a digest, opens a Sentry issue, pings a\n * channel — must not fire from a laptop, and the guard for that has to cover\n * the whole tick. There was nowhere to write it. gemi calls `onTick` and\n * `onComplete` *outside* `callback`, so a guard placed in a lifecycle hook\n * only stops the hook it lives in: an early `return` at the top of `callback`\n * leaves the job still announcing that it started and still announcing that\n * it finished, which for an outward-reporting job is most of the damage.\n *\n * The only construct that covered every hook was an abstract base class that\n * shadowed `callback` with the guard and renamed the real body to `run()` —\n * and that costs the app the framework's own vocabulary. A job then reads\n * `async run()` while every page of the documentation reads `async\n * callback()`, so the next person to follow the docs writes a `callback` the\n * base class never calls: no error, no output, a job that silently does\n * nothing. Forgetting *this* member fails the other way round — the job runs,\n * which is what it did before anyone asked for a gate.\n *\n * ### What it gates\n *\n * Work, not registration. A job whose gate returns `false` is still\n * scheduled, still holds its `Bun.cron` handle, and still appears in\n * `app(Scheduler).jobs` — \"is it scheduled\" and \"will it do anything\" are\n * different questions and the second one is answered per tick. That is also\n * why this is a method: a field would be read once, when the scheduler\n * constructs the job at boot, and would freeze whatever it saw then.\n *\n * A gate that throws is logged and treated as `false`. Cron work recurs, so\n * a skipped tick is recovered by the next one, while an email sent from the\n * wrong machine is not recovered at all.\n *\n * ### Composing with a base class\n *\n * Nothing here calls `super` for you. A subclass that overrides `shouldRun`\n * for its own reason silently replaces whatever its base was gating on, so\n * narrow rather than redefine:\n *\n * ```typescript\n * async shouldRun() {\n * return (await super.shouldRun()) && this.hasSubscribers();\n * }\n * ```\n *\n * A shared base should annotate its return type as written here rather than\n * let it be inferred: a base returning a plain `boolean` narrows the\n * signature its subclasses inherit, and the `await super` above then does not\n * typecheck against it.\n */\n shouldRun(): Promise<boolean> | boolean {\n return true;\n }\n\n /**\n * The tick's work. `lock` is the `withoutOverlapping` lock when the job\n * declares one.\n */\n callback(_lock?: HeldLock): Promise<void> | void {}\n onTick(): Promise<void> | void {}\n onComplete(): Promise<void> | void {}\n\n static exp(expression: CronExpression) {\n return expression;\n }\n}\n"
6
6
  ],
7
7
  "mappings": ";AA4BO,MAAM,CAAQ,CACnB,KACA,KAiBA,mBAAyC,GAOzC,YAAc,GAwDd,SAAS,EAA+B,CACtC,MAAO,GAOT,QAAQ,CAAC,EAAwC,EACjD,MAAM,EAAyB,EAC/B,UAAU,EAAyB,QAE5B,IAAG,CAAC,EAA4B,CACrC,OAAO,EAEX",
8
- "debugId": "269EE810896CDB8E64756E2164756E21",
8
+ "debugId": "1042DD191854A08764756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,15 +1,15 @@
1
1
  // @bun
2
- import{ej as F,fj as _1,gj as O1}from"./chunk-228w21t6.js";import{lj as g1,oj as b}from"./chunk-dfmxvp8p.js";import{pl as R0}from"./chunk-8e17k7ht.js";import{tl as C1}from"./chunk-ermvtpy9.js";import{Ml as H1}from"./chunk-aycfrzh1.js";import{Ul as aQ}from"./chunk-vgxkt9vd.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:
2
+ import{ej as q,fj as O1,gj as _1}from"./chunk-228w21t6.js";import{lj as g1,oj as b}from"./chunk-dfmxvp8p.js";import{pl as R0}from"./chunk-8e17k7ht.js";import{tl as C1}from"./chunk-ermvtpy9.js";import{Ml as H1}from"./chunk-aycfrzh1.js";import{Ul as rQ}from"./chunk-vgxkt9vd.js";class s1{static kind="controller";constructor(){}}class p0 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 RZ(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((z)=>z.trim()).filter((z)=>z!=="");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 z=u(J);if(z===null)return null;return{kind:"suffix",suffixLength:z}}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 LZ(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function CZ(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 OZ(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function e1(Q){return`bytes */${Q}`}class a extends q{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 u0(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 d0(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 l0=["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=d0(X);return(Y)=>Y instanceof Blob&&Y.type.startsWith(G)}case"fileSize":{let G=u0(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: ${l0.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=t0(o0(Q.node,Z),$),G=[Q.description,i0(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function i0(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 o0(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 t0(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 s0(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function a0(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 s0(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 r0(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function e0(Q){let Z=r0(Q);return Z?`${Z}: `:""}function E1(Q){return`${e0(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:QQ(Q,Z,$,X)}}function QQ(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 ${a0(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 $Q(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,z)=>{let B=h(G.item,W,[...$,z],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 z=h(W,K[H],[...$,H],X);if(!z.drop)J[H]=z.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 z=M1(J,Z);if(!K||z>K.score)K={issues:H,score:z}}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 ZQ(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=ZQ(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 $Q(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
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}
4
+ `)}`);this.name="JSONSchemaError",this.problems=Q}}var XQ=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=(V,U=$)=>{X.push(U?`${U}: ${V}`:V);return},Y=(V)=>$?`${$}.${V}`:V;if(!D1(Q))return G("expected a schema object");let K=new Set(Z.ignoreKeywords??[]),J=(V)=>XQ.has(V)||V.startsWith("x-")||K.has(V),H=!1,W=Q.type;if(Array.isArray(W)){let V=W.filter((U)=>U!=="null");if(V.length!==1)return G(`type ${JSON.stringify(W)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,Y("type"));H=V.length<W.length,W=V[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 z=new Set(["type","description","enum","const","anyOf",...W?r[W]:[]]),B=!1;for(let V of Object.keys(Q)){if(z.has(V)||J(V))continue;B=!0;let U=Object.entries(r).find(([,P])=>P.includes(V));G(U&&U[0]!==W?`"${V}" applies to type ${U[0]}, and this schema is ${W?`type ${W}`:"untyped"}`:`"${V}" is not supported by s.fromJSONSchema`,Y(V))}if(B)return;if(Q.description!==void 0&&typeof Q.description!=="string")return G("expected a string",Y("description"));let L=Q.description,D=(V)=>({node:V,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 V=[],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)V.push(A);else U=!0}),U)return;if(V.length===0)return G("anyOf has only null in it",Y("anyOf"));if(V.length===1){let P=V[0];return{...P,nullable:P.nullable||H,...L?{description:L}:{}}}return D({kind:"union",members:V})}if(Q.const!==void 0){let V=Q.const;if(typeof V!=="string"&&typeof V!=="number"&&typeof V!=="boolean")return G("only a string, number or boolean const is supported",Y("const"));if(W!==void 0&&typeof V!==(W==="integer"?"number":W))return G(`const ${JSON.stringify(V)} is not of type ${W}`,Y("const"));return D({kind:"literal",value:V})}let M;if(W==="string"){if(M=GQ(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 V=Q.enum.filter((R)=>R!==null);if(V.length<Q.enum.length)H=!0;let U=V.find((R)=>!(typeof R==="string"||typeof R==="number"||typeof R==="boolean")||W!==void 0&&typeof R!==(W==="integer"?"number":W));if(U!==void 0||V.length===0)return G(W?`every value must be of type ${W}${V.length===0?", and there must be one":`; ${JSON.stringify(U)} is not`}`:"only strings, numbers and booleans are supported",Y("enum"));if(V.every((R)=>typeof R==="string"))return D({kind:"enum",values:[...new Set(V)],...M?{checks:M}:{}});let P=[...new Set(V)];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 V=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}V[P]=R}if(U)return;return D({kind:"number",...Object.keys(V).length>0?{checks:V}:{}})}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 V={},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}V[R]=A}let P=j1(Q.items,Z,Y("items"),X);if(!P||U)return;return D({kind:"array",item:P,...Object.keys(V).length>0?{checks:V}:{}})}case"object":{let V=Q.properties??{};if(!D1(V))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((N)=>typeof N==="string"))return G("expected an array of property names",Y("required"));let P=U.filter((N)=>!Object.hasOwn(V,N));if(P.length>0)return G(`lists properties the schema doesn't have: ${P.join(", ")}`,Y("required"));let R={},A=!1;for(let[N,_]of Object.entries(V)){let C=j1(_,Z,Y(`properties.${N}`),X);if(!C){A=!0;continue}R[N]=U.includes(N)?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 GQ(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:YQ(J)}}if(Y)return null;return Object.keys(G).length>0?G:void 0}function YQ(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var FZ={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:HQ,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 qZ(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 KQ=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function HQ(Q,Z){if(typeof Q!=="string"||!KQ.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 SZ(Q,Z,$,X){X1.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function V0(Q){return X1.get(Q)?.progress}function z0(Q){return X1.get(Q)?.grant}function B0(Q){return X1.has(Q)}function EZ(Q){return X1.get(Q)?.clientAddress}var P0=new WeakMap;function kZ(Q,Z){P0.set(Q,Z)}function D0(Q){return P0.get(Q)??null}var k1=new WeakMap;function gZ(Q,Z){let $=k1.get(Q)??[];if(!$.includes(Z))k1.set(Q,[...$,Z])}function yZ(Q){return k1.get(Q)??[]}class l{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 JQ(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 WQ{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 z=K.get(H);if(Array.isArray(z))z.push(W),K.set(H,z);else K.set(H,[z,W])}else K.set(H,W);let J=Object.fromEntries(K.entries());this.search=new l(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 z0(this.rawRequest)??null}reportProgress(Q){let Z=V0(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 l(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 q)throw X;throw new q("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 l(Object.fromEntries($.entries()))}return new l({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch($){if($ instanceof q)throw $;throw new q("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new q("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new q("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 JQ(Z,G)){let H=this.checkField(J,Y);if(H.length>0){let W=$[M0(K)]??=[];for(let z of H)if(!W.includes(z))W.push(z)}}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 l(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 VQ extends q{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:_1("authorization",this.error,401)}},view:{}}}}class y1 extends q{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:y1.apiStatus,data:{error:_1("permission",this.error,y1.apiStatus)}},view:{status:403}}}}class b1 extends q{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:O1("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":e1(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class zQ extends q{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:O1("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class m extends q{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:O1("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class BQ extends q{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:_1("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 PQ}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:PQ.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 DQ,open as UQ,readdir as f1,rename as MQ,rmdir as RQ,stat as jQ,unlink as C0}from"fs/promises";import{dirname as LQ,isAbsolute as v1,relative as K1,resolve as n,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=n(this.folderPath),K=n(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 DQ(LQ(K),{recursive:!0}),G=`${K}.${Bun.randomUUIDv7()}.partial`;let H=await UQ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:W,value:z}=await X.read();if(W)break;for(let B=0;B<z.byteLength;){let{bytesWritten:L}=await H.write(z,B);B+=L}}}finally{await H.close()}return $?.throwIfAborted(),await MQ(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 $=n(this.folderPath),X=n($,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=n(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),Y=n(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 z=`${J}${f}${W.name}`,B=K1($,z).split(f).join("/");if(W.isDirectory()){if(`${B}/`.startsWith(G)||G.startsWith(`${B}/`))await K(z)}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 jQ(`${$}/${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 RQ(G)}catch{}}async list(){return await f1(this.folderPath)}}var v=30000;function R8(Q){return Q}function O0(){return{driver:new h1,fetchTimeoutMs:v,fetchIdleTimeoutMs:v}}class m1{static token="filesystem";driver;fetchTimeoutMs;fetchIdleTimeoutMs;constructor(Q={}){this.driver=Q.driver??O0().driver,this.fetchTimeoutMs=Q.fetchTimeoutMs??v,this.fetchIdleTimeoutMs=Q.fetchIdleTimeoutMs??v}}class _0 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 _0(J,L,D,H);return K.abort(M),M},z=Promise.resolve(Q.fetch(Z,{...$,signal:K.signal})),B;if(G){let L,D=new Promise((M,V)=>{L=setTimeout(()=>V(W("fetchTimeoutMs",G)),G)});try{B=await Promise.race([z,D])}catch(M){if(K.signal.aborted)throw z.then((V)=>V.body?.cancel(K.signal.reason).catch(()=>{}),()=>{}),K.signal.reason;throw M}finally{clearTimeout(L)}}else B=await z;if(!Y||!B.body)return B;return new Response(CQ(B.body,Y,()=>W("fetchIdleTimeoutMs",Y)),{status:B.status,statusText:B.statusText,headers:B.headers})}function CQ(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 N1 extends T{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class F1 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 q1 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 OQ(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,z)=>{if(W==="")return[];let B=[],L=W.split(":");for(let D=0;D<L.length;D++){let M=L[D];if(z&&D===L.length-1&&M.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(M))return null;let V=M.split(".").map(Number);if(V.some((U)=>U>255))return null;B.push(V[0]<<8|V[1],V[2]<<8|V[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,z)=>{H[z*2]=W>>8,H[z*2+1]=W&255}),H}function W1(Q){let Z=I0(Q);if(Z)return{family:6,bytes:Z};let $=OQ(Q);if($)return{family:4,bytes:$};return null}function p(Q){if(Q.family===6&&AQ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function AQ(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function V1(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($)?IQ($):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 IQ(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 O=(Q,Z)=>({cidr:t(Q),kind:Z,text:Q}),NQ=[O("0.0.0.0/8","unspecified"),O("10.0.0.0/8","private"),O("100.64.0.0/10","shared"),O("127.0.0.0/8","loopback"),O("169.254.169.254/32","metadata"),O("169.254.0.0/16","link-local"),O("168.63.129.16/32","metadata"),O("172.16.0.0/12","private"),O("192.0.0.0/24","reserved"),O("192.0.2.0/24","documentation"),O("192.88.99.0/24","reserved"),O("192.168.0.0/16","private"),O("198.18.0.0/15","benchmarking"),O("198.51.100.0/24","documentation"),O("203.0.113.0/24","documentation"),O("224.0.0.0/4","multicast"),O("255.255.255.255/32","broadcast"),O("240.0.0.0/4","reserved")],FQ=[O("::/128","unspecified"),O("::1/128","loopback"),O("64:ff9b:1::/48","private"),O("::/8","reserved"),O("100::/64","reserved"),O("2001:db8::/32","documentation"),O("2001::/23","reserved"),O("3fff::/20","documentation"),O("fd00:ec2::254/128","metadata"),O("fc00::/7","unique-local"),O("fe80::/10","link-local"),O("fec0::/10","private"),O("ff00::/8","multicast")],qQ=t("64:ff9b::/96"),TQ=t("2002::/16"),wQ=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=NQ.find((Y)=>g($,Y.cidr));return G?{kind:G.kind,range:G.text}:null}if(g($,qQ))return T1({family:4,bytes:$.bytes.slice(12)});if(g($,TQ))return T1({family:4,bytes:$.bytes.slice(2,6)});let X=FQ.find((G)=>g($,G.cidr));if(X)return{kind:X.kind,range:X.text};return g($,wQ)?null:{kind:"reserved",range:"outside 2000::/3"}}function N0(Q,Z){let $=p(Q),X=p(Z);return $.family===X.family&&$.bytes.every((G,Y)=>G===X.bytes[Y])}import{lookup as SQ}from"dns/promises";import*as EQ from"http";import*as xQ 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 z1={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},kQ=new Set([301,302,303,307,308]),gQ=new Set([101,103,204,205,304]),yQ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],bQ=["authorization","cookie","proxy-authorization"];async function T0(Q,Z={}){let $=fQ(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 F1(K,"total",$.timeout)),$.timeout),W=()=>J(X.reason);X?.addEventListener("abort",W,{once:!0});let z=()=>{clearTimeout(H),X?.removeEventListener("abort",W)};try{let B=q0(K,$),L=(Z.method??"GET").toUpperCase(),D=new Headers(Z.headers);for(let V of yQ)D.delete(V);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 cQ(L,Z.body,D);for(let V=0;;V++){K=B.href;let{request:U,response:P,address:R}=await pQ(B,L,D,M,$,Y),A=P.statusCode??0,I=P.headers.location;if(kQ.has(A)&&I&&Z.redirect!=="manual"){if(U.destroy(),V>=$.maxRedirects)throw new c1(B.href,$.maxRedirects);let N;try{N=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 _=[];D.forEach((C,j)=>{if(j.startsWith("content-"))_.push(j)});for(let C of _)D.delete(C)}if(N.origin!==B.origin)for(let _ of bQ)D.delete(_);B=q0(N.href,$);continue}return uQ({url:B,hop:V,method:L,request:U,response:P,address:R,policy:$,signal:Y,release:z})}}catch(B){throw z(),Y.aborted?Y.reason:B}}function fQ(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??z1.timeout,connectTimeout:Q.connectTimeout??z1.connectTimeout,maxSize:Q.maxSize??z1.maxSize,maxRedirects:Q.maxRedirects??z1.maxRedirects,ports:Q.ports??z1.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??vQ}}async function vQ(Q){return(await SQ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function w0(Q){return Q.toLowerCase().replace(/\.$/,"")}function F0(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function q0(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 hQ(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&&F0(X,Z.deny.hosts))throw new I1(Q.href,X,"denied");let K=!Y&&Z.allow!==null&&F0(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 mQ(Z.resolve(X),$)}catch(W){if($.aborted)throw $.reason;throw new N1(Q.href,X,W)}if(J=H.map((W)=>W1(W)).filter((W)=>W!==null),J.length===0)throw new N1(Q.href,X)}for(let H of J){let W=V1(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 z=T1(H);if(z&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((B)=>g(H,B)))throw new i(Q.href,X,W,z.kind)}return{host:X,addresses:J,isLiteral:Y}}function mQ(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 cQ(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 pQ(Q,Z,$,X,G,Y){let K=new AbortController,J=setTimeout(()=>K.abort(new F1(Q.href,"connect",G.connectTimeout)),G.connectTimeout),H=AbortSignal.any([Y,K.signal]);try{let{host:W,addresses:z,isLiteral:B}=await hQ(Q,G,H),L=Q.protocol==="https:",D={};if($.forEach((M,V)=>{D[V]=M}),X)D["content-length"]=String(X.byteLength);return await new Promise((M,V)=>{let U={method:Z,host:W,port:S0(Q),path:`${Q.pathname}${Q.search}`,headers:D,agent:!1,lookup:(_,C,j)=>{let w=C?.family,F=z.filter((B1)=>!w||B1.family===w);if(F.length===0)j(Object.assign(Error(`No IPv${w} address for ${W}`),{code:"ENOTFOUND"}));else if(C?.all)j(null,F.map((B1)=>({address:V1(B1),family:B1.family})));else j(null,V1(F[0]),F[0].family)}};if(L&&!B)U.servername=W;let P=(L?xQ:EQ).request(U),R=null,A=(_)=>{H.removeEventListener("abort",I),P.destroy(),V(_)},I=()=>A(H.aborted?H.reason:Y.reason);H.addEventListener("abort",I,{once:!0});let N=(_)=>{let C=_?.remoteAddress;if(!C||R!==null)return!0;let j=W1(C);if(!j||!z.some((w)=>N0(w,j)))return A(new i(Q.href,W,C,"not-allowed")),!1;return R=V1(p(j)),!0};P.once("socket",(_)=>{let C=()=>{if(N(_)&&!L)clearTimeout(J)};if(_.connecting)_.once("connect",C);else C();if(L)_.once("secureConnect",()=>clearTimeout(J))}),P.once("response",(_)=>{if(clearTimeout(J),_.on("error",()=>{}),!N(_.socket))return;H.removeEventListener("abort",I),M({request:P,response:_,address:R})}),P.on("error",(_)=>{if(H.aborted)return A(H.reason);A(_ instanceof T?_:new o(Q.href,_))}),P.end(X??void 0)})}finally{clearTimeout(J)}}function uQ({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 z=new Headers,B=G.rawHeaders;for(let C=0;C<B.length;C+=2)z.append(B[C],B[C+1]);if(K.contentTypes){let C=z.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!C||!K.contentTypes.some((j)=>dQ(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:z};if($==="HEAD"||gQ.has(W))return X.destroy(),H(),new u1(null,D,L);let M=z.get("content-encoding")?.trim().toLowerCase(),V=M==="gzip"||M==="x-gzip"?s.createGunzip():M==="deflate"?s.createInflate():M==="br"?s.createBrotliDecompress():null,U=Number(z.get("content-length"));if(!V&&Number.isFinite(U)&&U>K.maxSize)throw X.destroy(),new q1(Q.href,K.maxSize);if(V)z.delete("content-encoding"),z.delete("content-length");let P=V?G.pipe(V):G,R=0,A=!1,I=()=>{},N=()=>{A=!0,J.removeEventListener("abort",I),H()},_=new ReadableStream({start(C){let j=(F)=>{if(A)return;if(N(),F===void 0)C.close();else X.destroy(),V?.destroy(),C.error(F)};if(I=()=>j(J.reason),J.addEventListener("abort",I,{once:!0}),J.aborted)return I();P.on("data",(F)=>{if(A)return;if(R+=F.byteLength,R>K.maxSize)return j(new q1(Q.href,K.maxSize));if(C.enqueue(new Uint8Array(F)),(C.desiredSize??1)<=0)P.pause()}),P.once("end",()=>j());let w=(F)=>j(F instanceof T?F:new o(Q.href,F));if(P.on("error",w),V)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;N(),X.destroy(),V?.destroy()}});return new u1(_,D,L)}function dQ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function x0(Q){return iQ(Q)??tQ(Q)??sQ(Q)}var d1=4096,lQ={"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 lQ[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 iQ(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 oQ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function tQ(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 oQ){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 sQ(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 aQ=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 aQ.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 QZ}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 z=await T0(Z,{...$.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:W,timeout:J,maxSize:K});if(!z.ok)throw await z.body?.cancel().catch(()=>{}),new p1(z.url,z.status);let B=(z.body??new Response(new Uint8Array).body).getReader(),L=async(j)=>{throw await B.cancel(j).catch(()=>{}),j},D=[],M=0,V=!1;while(M<d1){let{done:j,value:w}=await B.read();if(j){V=!0;break}D.push(w),M+=w.byteLength}let U=eQ(D,M),P=x0(U.subarray(0,Math.min(M,d1))),R=H?.length?H:["*/*"];if(!g0(P,R))await L(new J1(z.url,P,R));let A=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${k0(P)}`].filter(Boolean).join("/"),I=M,N=new ReadableStream({start(j){if(M>0)j.enqueue(U);if(V)j.close()},async pull(j){let{done:w,value:F}=await B.read();if(w){j.close();return}I+=F.byteLength,j.enqueue(F)},cancel(j){return B.cancel(j)}}),_={name:A,bucket:Y,body:N,contentType:P},C;try{C=Q.putStream?await Q.putStream(_,{signal:W}):await Y1.prototype.putStream.call(Q,_,{signal:W})}catch(j){throw await L(j),j}return{name:C,contentType:P,size:I,url:z.url}}function eQ(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 ZZ 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=QZ.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)}}var f0=["cookie","set-cookie","authorization","proxy-authorization","x-api-key"];function d8(Q){return Q}function l8(){let Q=Bun.env.NODE_ENV==="development";return{maxFileSize:10485760,console:Q,consoleFormat:Q?"text":"json",requestFields:[],redactHeaders:[],onLogFileClosed:()=>{},onLogCreated:()=>{}}}import{mkdir as n1,readdir as YZ,access as KZ}from"fs/promises";var l1=["debug","info","notice","warning","error","critical","alert","emergency"],$Z=l1.indexOf("warning");function h0(Q){if(!Q)return-1;if(Q===!0)return 0;let Z=l1.indexOf(Q);return Z===-1?0:Z}function XZ(){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 v0(Q){try{return JSON.stringify(Q,XZ())}catch{return'"[Unserializable]"'}}function GZ(Q,Z){if(Z==="json")return v0({...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}${$?` ${v0(Q.metadata)}`:""}`}function m0(Q,Z){let $=l1.indexOf(Q.level);if(Z.threshold===-1||$<Z.threshold)return;try{let X=GZ(Q,Z.format)+`
5
+ `;if($>=$Z)process.stderr.write(X);else process.stdout.write(X)}catch{}}async function i1(Q){try{return await KZ(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;redactedHeaders;constructor(Q){this.config=Q;this.consoleThreshold=h0(Q.console),this.redactedHeaders=new Set([...f0,...Q.redactHeaders??[]].map((Z)=>Z.toLowerCase()))}requestMetadata(Q){let Z=new URL(Q.url),$={method:Q.method,path:Z.pathname,userAgent:Q.headers.get("user-agent")??void 0},X=Q.headers.get("x-request-id");if(X)$.requestId=X;let G=this.config.requestFields??[];if(G.includes("url"))$.url=Q.url;if(G.includes("headers")){let Y={};Q.headers.forEach((K,J)=>{Y[J]=this.redactedHeaders.has(J)?"[redacted]":K}),$.headers=Y}return $}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 n1(Q);if(!await i1(this.logsDirPath))await n1(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await i1(this.logsDirPath))await n1(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 YZ(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=this.requestMetadata(X.req.rawRequest);let K={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:Q,message:Z,metadata:{...G,...$}};if(this.consoleThreshold!==-1)m0({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 HZ 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 JZ{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(WZ())(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 WZ(){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 c0(Q){return`id: ${Q.seq}
8
8
  data: ${JSON.stringify(Q.event)}
9
9
 
10
- `}var WZ=5000,zZ=`: keepalive
10
+ `}var VZ=5000,zZ=`: keepalive
11
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 Rh,c0 as Sh,MZ as Th,J0 as Uh,wZ as Vh,V0 as Wh,SZ as Xh,a1 as Yh,r1 as Zh,jZ as _h,LZ as $h,CZ as ai,e1 as bi,xZ as ci,D0 as di,kZ as ei,gZ as fi,a as gi,k as hi,G0 as ii,H0 as ji,qZ as ki,NZ as li,JQ as mi,j0 as ni,WQ as oi,y1 as pi,b1 as qi,zQ as ri,m as si,VQ as ti,G1 as ui,y0 as vi,A1 as wi,Y1 as xi,L0 as yi,h1 as zi,M8 as Ai,_0 as Bi,m1 as Ci,O0 as Di,T as Ei,c as Fi,I1 as Gi,i as Hi,q1 as Ii,N1 as Ji,F1 as Ki,J1 as Li,c1 as Mi,o as Ni,p1 as Oi,W1 as Pi,T1 as Qi,u1 as Ri,T0 as Si,x0 as Ti,E0 as Ui,QZ as Vi,o1 as Wi,KZ as Xi,HZ as Yi,m0 as Zi,zZ as _i,VZ as $i,BZ as aj,e8 as bj};
12
+ `;function BZ(Q,Z=VZ){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 PZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function G$(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,Y=new ReadableStream({start(K){G=BZ(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(c0(J.value))),G.touch()}catch(J){let H={type:"error",error:UZ(J)};G.stop(),K.enqueue(t1.encode(c0({seq:X+1,event:H}))),K.close()}},cancel(K){G.stop(),$.return?.(K)}});return new Response(Y,{status:Z,headers:PZ()})}var DZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function UZ(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&DZ.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 Ph,p0 as Qh,RZ as Rh,J0 as Sh,SZ as Th,z0 as Uh,EZ as Vh,a1 as Wh,r1 as Xh,LZ as Yh,CZ as Zh,OZ as _h,e1 as $h,kZ as ai,D0 as bi,gZ as ci,yZ as di,a as ei,k as fi,G0 as gi,H0 as hi,FZ as ii,qZ as ji,WQ as ki,j0 as li,VQ as mi,y1 as ni,b1 as oi,zQ as pi,m as qi,BQ as ri,G1 as si,y0 as ti,A1 as ui,Y1 as vi,L0 as wi,h1 as xi,R8 as yi,O0 as zi,m1 as Ai,_0 as Bi,T as Ci,c as Di,I1 as Ei,i as Fi,N1 as Gi,F1 as Hi,q1 as Ii,J1 as Ji,c1 as Ki,o as Li,p1 as Mi,W1 as Ni,T1 as Oi,u1 as Pi,T0 as Qi,x0 as Ri,E0 as Si,ZZ as Ti,d8 as Ui,l8 as Vi,o1 as Wi,HZ as Xi,JZ as Yi,c0 as Zi,zZ as _i,BZ as $i,PZ as aj,G$ as bj};
14
14
 
15
- //# debugId=28C46967FF8EC07064756E2164756E21
15
+ //# debugId=C42D8D547A2FAD9864756E2164756E21