gemi 0.115.0 → 0.116.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 (73) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/{chunk-t24p7gc6.js → chunk-1q9kd20m.js} +1 -1
  3. package/dist/{chunk-0z8ejxre.js → chunk-4088szy9.js} +1 -1
  4. package/dist/chunk-49nyyjfe.js +5 -0
  5. package/dist/{chunk-9b4erdy2.js.map → chunk-49nyyjfe.js.map} +3 -3
  6. package/dist/{chunk-0av6xvm6.js → chunk-6cx8ncd4.js} +1 -1
  7. package/dist/{chunk-jafm3613.js → chunk-6d8rvr1v.js} +2 -2
  8. package/dist/{chunk-jafm3613.js.map → chunk-6d8rvr1v.js.map} +1 -1
  9. package/dist/{chunk-wzrt5mac.js → chunk-79xg42e7.js} +1 -1
  10. package/dist/chunk-jmg2zsaf.js +5 -0
  11. package/dist/{chunk-7g9yh5ae.js.map → chunk-jmg2zsaf.js.map} +4 -4
  12. package/dist/chunk-ms9k0rx6.js +46 -0
  13. package/dist/{chunk-d6591xck.js.map → chunk-ms9k0rx6.js.map} +5 -5
  14. package/dist/{chunk-mps6ynbh.js → chunk-p91b8zcn.js} +1 -1
  15. package/dist/{chunk-dexdkh3z.js → chunk-pn8v6fj2.js} +1 -1
  16. package/dist/{chunk-mtbygktb.js → chunk-v1tfdgy1.js} +1 -1
  17. package/dist/{chunk-t4t3hqe0.js → chunk-yf1njzd5.js} +1 -1
  18. package/dist/chunks/{ThemeProvider-BgLyzzOL.js → ThemeProvider-BLI4zpLu.js} +8 -3
  19. package/dist/chunks/ThemeProvider-BLI4zpLu.js.map +1 -0
  20. package/dist/client/ClientRouter.d.ts +3 -5
  21. package/dist/client/ClientRouter.d.ts.map +1 -1
  22. package/dist/client/ClientRouterContext.d.ts.map +1 -1
  23. package/dist/client/Head.d.ts +1 -1
  24. package/dist/client/Head.d.ts.map +1 -1
  25. package/dist/client/ServerDataProvider.d.ts +2 -0
  26. package/dist/client/ServerDataProvider.d.ts.map +1 -1
  27. package/dist/client/createRoot.d.ts +2 -4
  28. package/dist/client/createRoot.d.ts.map +1 -1
  29. package/dist/client/htmlAttributes.d.ts +18 -0
  30. package/dist/client/htmlAttributes.d.ts.map +1 -0
  31. package/dist/client/index.d.ts +1 -0
  32. package/dist/client/index.d.ts.map +1 -1
  33. package/dist/client/index.js +79 -6
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/email/index.js +1 -1
  36. package/dist/facades/Meta.d.ts +11 -1
  37. package/dist/facades/Meta.d.ts.map +1 -1
  38. package/dist/facades/index.js +1 -1
  39. package/dist/http/HttpRequest.d.ts +3 -0
  40. package/dist/http/HttpRequest.d.ts.map +1 -1
  41. package/dist/http/Metadata.d.ts +23 -0
  42. package/dist/http/Metadata.d.ts.map +1 -1
  43. package/dist/http/index.js +1 -1
  44. package/dist/http/requestContext.d.ts +3 -0
  45. package/dist/http/requestContext.d.ts.map +1 -1
  46. package/dist/i18n/index.d.ts +1 -0
  47. package/dist/i18n/index.d.ts.map +1 -1
  48. package/dist/i18n/index.js +2 -2
  49. package/dist/i18n/index.js.map +2 -2
  50. package/dist/kernel/index.js +1 -1
  51. package/dist/orm/index.js +1 -1
  52. package/dist/server/index.js +1 -1
  53. package/dist/services/index.d.ts +1 -1
  54. package/dist/services/index.d.ts.map +1 -1
  55. package/dist/services/index.js +1 -1
  56. package/dist/services/router/ViewRouteDispatcher.d.ts +3 -1
  57. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  58. package/dist/services/router/config.d.ts +19 -0
  59. package/dist/services/router/config.d.ts.map +1 -1
  60. package/dist/testing/index.js +1 -1
  61. package/package.json +1 -1
  62. package/dist/chunk-7g9yh5ae.js +0 -5
  63. package/dist/chunk-9b4erdy2.js +0 -5
  64. package/dist/chunk-d6591xck.js +0 -46
  65. package/dist/chunks/ThemeProvider-BgLyzzOL.js.map +0 -1
  66. /package/dist/{chunk-t24p7gc6.js.map → chunk-1q9kd20m.js.map} +0 -0
  67. /package/dist/{chunk-0z8ejxre.js.map → chunk-4088szy9.js.map} +0 -0
  68. /package/dist/{chunk-0av6xvm6.js.map → chunk-6cx8ncd4.js.map} +0 -0
  69. /package/dist/{chunk-wzrt5mac.js.map → chunk-79xg42e7.js.map} +0 -0
  70. /package/dist/{chunk-mps6ynbh.js.map → chunk-p91b8zcn.js.map} +0 -0
  71. /package/dist/{chunk-dexdkh3z.js.map → chunk-pn8v6fj2.js.map} +0 -0
  72. /package/dist/{chunk-mtbygktb.js.map → chunk-v1tfdgy1.js.map} +0 -0
  73. /package/dist/{chunk-t4t3hqe0.js.map → chunk-yf1njzd5.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R as C,T as h,U as m}from"./chunk-jafm3613.js";import{la as w,ma as q}from"./chunk-6chz1ktz.js";import"./chunk-frerzsxq.js";import"./chunk-yer1r3t3.js";import"./chunk-303mprnv.js";import"./chunk-p1aqq0ga.js";import{Ca as N}from"./chunk-4mfrgd5m.js";import"./chunk-5stgtwqw.js";import"./chunk-tw5kwbx4.js";import{Tg as _}from"./chunk-15c2vgaf.js";import{oi as y}from"./chunk-d9mar37g.js";import"./chunk-vw8849ys.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function v(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{R as C,T as h,U as m}from"./chunk-6d8rvr1v.js";import{la as w,ma as q}from"./chunk-6chz1ktz.js";import"./chunk-frerzsxq.js";import"./chunk-yer1r3t3.js";import"./chunk-303mprnv.js";import"./chunk-p1aqq0ga.js";import{Ca as N}from"./chunk-4mfrgd5m.js";import"./chunk-5stgtwqw.js";import"./chunk-tw5kwbx4.js";import{Tg as _}from"./chunk-15c2vgaf.js";import{oi as y}from"./chunk-d9mar37g.js";import"./chunk-vw8849ys.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function v(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 D(J){return`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Rg as F,Sg as t,Tg as l}from"./chunk-15c2vgaf.js";import{Wg as V}from"./chunk-9b4erdy2.js";import{bi as f0}from"./chunk-t4yh4nf9.js";import{ni as h}from"./chunk-1hr4xht1.js";import{ui as LH}from"./chunk-vw8849ys.js";class A0{static kind="controller";constructor(){}}class u0 extends A0{}function Q0(H){let Q=new Map;if(!H)return Q;for(let X of H.split(";")){let $=X.indexOf("=");if($===-1)continue;let Z=X.slice(0,$).trim();if(!Z)continue;Q.set(Z,X.slice($+1).trim())}return Q}function gH(H){return Q0(H.headers.get("cookie"))}function N(H){if(!/^\d+$/.test(H))return null;let Q=Number(H);return Number.isSafeInteger(Q)?Q:null}function J0(H){if(!H)return null;let Q=H.trim();if(!/^bytes=/i.test(Q))return null;let $=Q.slice(6).split(",").map((U)=>U.trim()).filter((U)=>U!=="");if($.length!==1)return null;let Z=$[0],G=Z.indexOf("-");if(G===-1)return null;let W=Z.slice(0,G),Y=Z.slice(G+1);if(W===""){let U=N(Y);if(U===null)return null;return{kind:"suffix",suffixLength:U}}let T=N(W);if(T===null)return null;if(Y==="")return{kind:"offset",start:T,end:null};let M=N(Y);if(M===null||M<T)return null;return{kind:"offset",start:T,end:M}}function L0(H,Q){if(!Number.isFinite(Q)||Q<=0)return null;let X,$;if(H.kind==="suffix"){if(H.suffixLength<=0)return null;X=Math.max(0,Q-H.suffixLength),$=Q-1}else{if(H.start>=Q)return null;if(X=H.start,$=H.end===null?Q-1:Math.min(H.end,Q-1),$<X)return null}return{start:X,end:$,length:$-X+1}}function kH(H){if(H.kind==="suffix")return`bytes=-${H.suffixLength}`;return H.end===null?`bytes=${H.start}-`:`bytes=${H.start}-${H.end}`}function bH(H){if(!H)return null;let Q=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(H.trim());if(!Q)return null;let X=N(Q[1]),$=N(Q[2]),Z=N(Q[3]);if(X===null||$===null||Z===null||$<X)return null;return{start:X,end:$,total:Z}}function fH(H,Q,X){return`bytes ${H}-${Q}/${X}`}function R0(H){return`bytes */${H}`}class S extends F{errors={};constructor(H){super("Validation error");this.name="ValidationError",this.errors=H,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:H,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function o0(H){let[Q,X]=H.match(/\d+|\D+/g)??[];if(!Q||!X)return 0;let $=Number.parseInt(Q);switch(X){case"B":return $;case"KB":return $*1024;case"MB":return $*1024*1024;case"GB":return $*1024*1024*1024;case"TB":return $*1024*1024*1024*1024;default:return 0}}function n0(H){switch(H){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 H}}function C0(H){if(typeof H==="string"||Array.isArray(H))return H.length;return}function X0(H){return typeof H==="number"&&!Number.isNaN(H)}var i0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class P extends Error{name="InvalidValidationRuleError"}function c(H,Q){let X=Q===void 0||Q.trim()===""?Number.NaN:Number(Q);if(Number.isNaN(X))throw new P(`Validation rule "${H}:${Q??""}" needs a number, e.g. "${H}:3"`);return X}function P0(H){let Q=H.indexOf(":"),X=Q===-1?H:H.slice(0,Q),$=Q===-1?void 0:H.slice(Q+1);switch(X){case"required":return(Z)=>{if(Z instanceof Blob)return Z.size>0;if(Z===null||Z===void 0)return!1;if(typeof Z==="string"||Array.isArray(Z))return Z.length>0;return!0};case"string":return(Z)=>typeof Z==="string";case"boolean":return(Z)=>typeof Z==="boolean";case"number":return(Z)=>X0(Z);case"password":return(Z)=>{return typeof Z==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(Z)};case"min":{let Z=c(X,$);return(G)=>{let W=C0(G);return W!==void 0&&W>=Z}}case"max":{let Z=c(X,$);return(G)=>{let W=C0(G);return W!==void 0&&W<=Z}}case"gte":{let Z=c(X,$);return(G)=>X0(G)&&G>=Z}case"lte":{let Z=c(X,$);return(G)=>X0(G)&&G<=Z}case"email":return(Z)=>{return typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)};case"file":return(Z)=>{return Z instanceof Blob};case"fileType":{if(!$)throw new P('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let Z=n0($);return(G)=>G instanceof Blob&&G.type.startsWith(Z)}case"fileSize":{let Z=o0($??"");if(Z===0&&!/^0+(B|KB|MB|GB|TB)$/.test($??""))throw new P(`Validation rule "fileSize:${$??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(G)=>G instanceof Blob&&G.size<=Z}case"array":return(Z)=>Array.isArray(Z);case"object":return(Z)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&!(Z instanceof Blob);case"in":{let Z=($??"").split(",").filter((G)=>G!=="");if(Z.length===0)throw new P('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(G)=>typeof G==="string"&&Z.includes(G)}default:throw new P(`Unknown validation rule "${H}". Known rules: ${i0.join(", ")}`)}}function w(H){if(!H.definition)throw Error(`gemi/ai: the recursive schema "${H.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return H.definition}var i=new WeakMap;function j0(H){return typeof H==="object"&&H!==null&&i.has(H)}function d(H){let Q=i.get(H);if(!Q)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Q}function t0(H){let Q={defs:{},cells:new Map},X=H;if(H.node.kind==="ref"){let Z=w(H.node.cell);X={...Z,...H.description?{description:H.description}:{},optional:H.optional,nullable:H.nullable||Z.nullable}}let $=g(X,Q);return Object.keys(Q.defs).length>0?{...$,$defs:Q.defs}:$}function g(H,Q){let X=(H.optional||H.nullable)&&H.node.kind!=="json",$=r0(s0(H.node,Q),X),Z=[H.description,l0(H.node)].filter(Boolean).join(" ");if(Z&&$.$ref!==void 0)$={anyOf:[$]};return Z?{description:Z,...$}:$}function l0(H){let Q=[];if(H.kind==="string"||H.kind==="enum"){let X=H.checks;if(X?.format)Q.push(`Format: ${X.format.name}.`);if(X?.minLength!==void 0)Q.push(`At least ${X.minLength} characters.`);if(X?.maxLength!==void 0)Q.push(`At most ${X.maxLength} characters.`)}else if(H.kind==="number"){let X=H.checks;if(X?.minimum!==void 0)Q.push(`Minimum ${X.minimum}.`);if(X?.exclusiveMinimum!==void 0)Q.push(`Greater than ${X.exclusiveMinimum}.`);if(X?.maximum!==void 0)Q.push(`Maximum ${X.maximum}.`);if(X?.exclusiveMaximum!==void 0)Q.push(`Less than ${X.exclusiveMaximum}.`)}else if(H.kind==="array"){let X=H.checks;if(X?.minItems!==void 0)Q.push(`At least ${X.minItems} items.`);if(X?.maxItems!==void 0)Q.push(`At most ${X.maxItems} items.`)}return Q.join(" ")}function s0(H,Q){switch(H.kind){case"string":return{type:"string"};case"number":return{type:H.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof H.value,const:H.value};case"enum":return{type:"string",enum:H.values};case"array":return{type:"array",items:g(H.item,Q)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(H.shape).map(([X,$])=>[X,g($,Q)])),required:Object.keys(H.shape),additionalProperties:!1};case"union":return{anyOf:H.members.map((X)=>g(X,Q))};case"json":return{};case"ref":{let{cell:X}=H,$=Q.cells.get(X.name);if($&&$!==X)throw Error(`gemi/ai: two different recursive schemas are named "${X.name}" in one schema; give each s.recursive(...) its own name`);if(!$)Q.cells.set(X.name,X),Q.defs[X.name]={},Q.defs[X.name]=g(w(X),Q);return{$ref:`#/$defs/${X.name}`}}}}function r0(H,Q){if(!Q)return H;if(H.anyOf)return{...H,anyOf:[...H.anyOf,{type:"null"}]};if(H.enum||H.const!==void 0)return{anyOf:[H,{type:"null"}]};if(typeof H.type==="string")return{...H,type:[H.type,"null"]};return{anyOf:[H,{type:"null"}]}}function a0(H){if(H===null)return"null";if(Array.isArray(H))return"array";return typeof H}function e0(H,Q){if(typeof Q==="number"&&!Number.isFinite(Q))return String(Q);if(H.kind==="literal"||H.kind==="enum"){if(typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean")return JSON.stringify(Q)}return a0(Q)}function O0(H){let Q=H.node,X=(()=>{switch(Q.kind){case"number":return Q.checks?.integer?"integer":"number";case"string":case"boolean":return Q.kind;case"literal":return JSON.stringify(Q.value);case"enum":return`one of ${Q.values.map(($)=>JSON.stringify($)).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 O0({...w(Q.cell),optional:!1,nullable:!1})}})();return H.optional||H.nullable?`${X} or null`:X}function HH(H){let Q="";for(let X of H)Q+=typeof X==="number"?`[${X}]`:Q?`.${X}`:X;return Q}function QH(H){let Q=HH(H);return Q?`${Q}: `:""}function Z0(H){return`${QH(H.path)}${H.message}`}function u(H,Q){if(Q===null||Q===void 0)return H.optional||H.nullable?1:0;let X=H.node;switch(X.kind){case"string":return typeof Q==="string"?1:0;case"number":return typeof Q==="number"?1:0;case"boolean":return typeof Q==="boolean"?1:0;case"literal":return Q===X.value?10:0;case"enum":return typeof Q==="string"&&X.values.includes(Q)?10:0;case"array":return Array.isArray(Q)?1:0;case"object":{if(typeof Q!=="object"||Array.isArray(Q))return 0;let $=Q,Z=1;for(let[G,W]of Object.entries(X.shape))Z+=u(W,$[G]);return Z}case"union":return X.members.reduce(($,Z)=>Math.max($,u(Z,Q)),0);case"json":return 1;case"ref":return I0(X.cell,Q,()=>1,()=>u(w(X.cell),Q))}}function I0(H,Q,X,$){if(typeof Q!=="object"||Q===null)return $();if(H.active.has(Q))return X();H.active.add(Q);try{return $()}finally{H.active.delete(Q)}}function j(H,Q,X,$){if(H.optional&&(Q===null||Q===void 0))return{drop:!0,value:void 0};if(H.nullable&&Q===null)return{drop:!1,value:null};return{drop:!1,value:XH(H,Q,X,$)}}function XH(H,Q,X,$){let Z=H.node,G=()=>{let W=Q===void 0?"required":Z.kind==="literal"?"const":Z.kind==="enum"&&typeof Q==="string"?"enum":"type",Y=W==="const"?{allowedValue:Z.value}:W==="enum"?{allowedValues:Z.values}:{};$.push({path:X,code:W,message:`expected ${O0(H)}, got ${e0(Z,Q)}`,params:Y});return};switch(Z.kind){case"string":if(typeof Q!=="string")return G();return V0(Z.checks,Q,X,$),Q;case"number":if(typeof Q!=="number"||!Number.isFinite(Q))return G();if(Z.checks?.integer&&!Number.isInteger(Q))return G();return $H(Z.checks,Q,X,$),Q;case"boolean":return typeof Q==="boolean"?Q:G();case"literal":return Q===Z.value?Q:G();case"enum":if(typeof Q!=="string"||!Z.values.includes(Q))return G();return V0(Z.checks,Q,X,$),Q;case"array":{if(!Array.isArray(Q))return G();let W=Q.map((M,U)=>{let R=j(Z.item,M,[...X,U],$);return R.drop?void 0:R.value}),{minItems:Y,maxItems:T}=Z.checks??{};if(Y!==void 0&&Q.length<Y)$.push({path:X,code:"minItems",message:`expected at least ${Y} items, got ${Q.length}`,params:{limit:Y}});if(T!==void 0&&Q.length>T)$.push({path:X,code:"maxItems",message:`expected at most ${T} items, got ${Q.length}`,params:{limit:T}});return W}case"object":{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return G();let W=Q,Y={};for(let[T,M]of Object.entries(Z.shape)){let U=j(M,W[T],[...X,T],$);if(!U.drop)Y[T]=U.value}if(Z.unknownKeys)for(let T of Object.keys(W)){if(Object.hasOwn(Z.shape,T)||W[T]===void 0)continue;if(Z.unknownKeys==="error"){$.push({path:[...X,T],code:"additionalProperties",message:"unknown key",params:{additionalProperty:T}});continue}b(W[T],[...X,T],$,new Set),Object.defineProperty(Y,T,{value:W[T],enumerable:!0,writable:!0,configurable:!0})}return Y}case"union":{let W;for(let Y of Z.members){let T=[],M=j(Y,Q,X,T);if(T.length===0)return M.drop?void 0:M.value;let U=u(Y,Q);if(!W||U>W.score)W={issues:T,score:U}}$.push({path:X,code:"anyOf",message:`no matching variant; closest: ${W.issues.map(Z0).join("; ")}`,params:{closest:W.issues}});return}case"json":if(Q===void 0)return G();return b(Q,X,$,new Set),Q;case"ref":return I0(Z.cell,Q,()=>{$.push({path:X,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>j(w(Z.cell),Q,X,$).value)}}function ZH(H){let Q=0;for(let X of H)Q++;return Q}function V0(H,Q,X,$){if(!H)return;let{minLength:Z,maxLength:G,format:W}=H;if(Z!==void 0||G!==void 0){let Y=ZH(Q);if(Z!==void 0&&Y<Z)$.push({path:X,code:"minLength",message:`expected at least ${Z} characters, got ${Y}`,params:{limit:Z}});if(G!==void 0&&Y>G)$.push({path:X,code:"maxLength",message:`expected at most ${G} characters, got ${Y}`,params:{limit:G}})}if(W){let Y=!1;try{Y=W.test(Q)===!0}catch{}if(!Y)$.push({path:X,code:"format",message:`expected a string in format "${W.name}"`,params:{format:W.name}})}}function $H(H,Q,X,$){if(!H)return;let Z=(G,W,Y,T)=>{if(W===void 0||Y(W))return;$.push({path:X,code:G,message:`expected ${T} ${W}, got ${Q}`,params:{limit:W}})};Z("minimum",H.minimum,(G)=>Q>=G,"at least"),Z("exclusiveMinimum",H.exclusiveMinimum,(G)=>Q>G,"more than"),Z("maximum",H.maximum,(G)=>Q<=G,"at most"),Z("exclusiveMaximum",H.exclusiveMaximum,(G)=>Q<G,"less than")}function b(H,Q,X,$,Z=!0){let G=(Y)=>{X.push({path:Q,code:"type",message:`expected a JSON value, got ${Y}`,params:{}})};switch(typeof H){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(H))G(String(H));return;case"bigint":return G("a bigint");case"function":return G("a function");case"symbol":return G("a symbol")}if(H===null)return;let W=H;if($.has(W))return G("a circular reference");$.add(W);try{let Y=Z?W.toJSON:void 0;if(typeof Y==="function"){let T;try{T=Y.call(W)}catch{return G("a toJSON that threw")}if(T===void 0)return G("a toJSON that returns undefined");return b(T,Q,X,$,!1)}if(Array.isArray(H))H.forEach((T,M)=>b(T,[...Q,M],X,$));else for(let[T,M]of Object.entries(W))b(M,[...Q,T],X,$)}finally{$.delete(W)}}function A(H){return o(H)}function o(H){let Q={toJSONSchema:()=>t0(H),parse(X){let $=[],Z=j(H,X,[],$);if($.length>0)throw Error($.map(Z0).join("; "));return Z.drop?void 0:Z.value},safeParse(X){let $=[],Z=j(H,X,[],$);if($.length>0)return{ok:!1,errors:$.map(Z0)};return{ok:!0,value:Z.drop?void 0:Z.value}},validate(X){let $=[],Z=j(H,X,[],$);if($.length>0)return{ok:!1,issues:$};return{ok:!0,value:Z.drop?void 0:Z.value}},describe:(X)=>o({...H,description:X}),optional:()=>o({...H,optional:!0}),nullable:()=>o({...H,nullable:!0,optional:!1})};return i.set(Q,H),Q}function L(H){return{node:H,optional:!1,nullable:!1}}var _0=["strip","error","passthrough"];class q0 extends Error{problems;constructor(H){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
2
+ import{Rg as F,Sg as t,Tg as l}from"./chunk-15c2vgaf.js";import{Wg as V}from"./chunk-49nyyjfe.js";import{bi as f0}from"./chunk-t4yh4nf9.js";import{ni as h}from"./chunk-1hr4xht1.js";import{ui as LH}from"./chunk-vw8849ys.js";class A0{static kind="controller";constructor(){}}class u0 extends A0{}function Q0(H){let Q=new Map;if(!H)return Q;for(let X of H.split(";")){let $=X.indexOf("=");if($===-1)continue;let Z=X.slice(0,$).trim();if(!Z)continue;Q.set(Z,X.slice($+1).trim())}return Q}function gH(H){return Q0(H.headers.get("cookie"))}function N(H){if(!/^\d+$/.test(H))return null;let Q=Number(H);return Number.isSafeInteger(Q)?Q:null}function J0(H){if(!H)return null;let Q=H.trim();if(!/^bytes=/i.test(Q))return null;let $=Q.slice(6).split(",").map((U)=>U.trim()).filter((U)=>U!=="");if($.length!==1)return null;let Z=$[0],G=Z.indexOf("-");if(G===-1)return null;let W=Z.slice(0,G),Y=Z.slice(G+1);if(W===""){let U=N(Y);if(U===null)return null;return{kind:"suffix",suffixLength:U}}let T=N(W);if(T===null)return null;if(Y==="")return{kind:"offset",start:T,end:null};let M=N(Y);if(M===null||M<T)return null;return{kind:"offset",start:T,end:M}}function L0(H,Q){if(!Number.isFinite(Q)||Q<=0)return null;let X,$;if(H.kind==="suffix"){if(H.suffixLength<=0)return null;X=Math.max(0,Q-H.suffixLength),$=Q-1}else{if(H.start>=Q)return null;if(X=H.start,$=H.end===null?Q-1:Math.min(H.end,Q-1),$<X)return null}return{start:X,end:$,length:$-X+1}}function kH(H){if(H.kind==="suffix")return`bytes=-${H.suffixLength}`;return H.end===null?`bytes=${H.start}-`:`bytes=${H.start}-${H.end}`}function bH(H){if(!H)return null;let Q=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(H.trim());if(!Q)return null;let X=N(Q[1]),$=N(Q[2]),Z=N(Q[3]);if(X===null||$===null||Z===null||$<X)return null;return{start:X,end:$,total:Z}}function fH(H,Q,X){return`bytes ${H}-${Q}/${X}`}function R0(H){return`bytes */${H}`}class S extends F{errors={};constructor(H){super("Validation error");this.name="ValidationError",this.errors=H,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:H,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function o0(H){let[Q,X]=H.match(/\d+|\D+/g)??[];if(!Q||!X)return 0;let $=Number.parseInt(Q);switch(X){case"B":return $;case"KB":return $*1024;case"MB":return $*1024*1024;case"GB":return $*1024*1024*1024;case"TB":return $*1024*1024*1024*1024;default:return 0}}function n0(H){switch(H){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 H}}function C0(H){if(typeof H==="string"||Array.isArray(H))return H.length;return}function X0(H){return typeof H==="number"&&!Number.isNaN(H)}var i0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class P extends Error{name="InvalidValidationRuleError"}function c(H,Q){let X=Q===void 0||Q.trim()===""?Number.NaN:Number(Q);if(Number.isNaN(X))throw new P(`Validation rule "${H}:${Q??""}" needs a number, e.g. "${H}:3"`);return X}function P0(H){let Q=H.indexOf(":"),X=Q===-1?H:H.slice(0,Q),$=Q===-1?void 0:H.slice(Q+1);switch(X){case"required":return(Z)=>{if(Z instanceof Blob)return Z.size>0;if(Z===null||Z===void 0)return!1;if(typeof Z==="string"||Array.isArray(Z))return Z.length>0;return!0};case"string":return(Z)=>typeof Z==="string";case"boolean":return(Z)=>typeof Z==="boolean";case"number":return(Z)=>X0(Z);case"password":return(Z)=>{return typeof Z==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(Z)};case"min":{let Z=c(X,$);return(G)=>{let W=C0(G);return W!==void 0&&W>=Z}}case"max":{let Z=c(X,$);return(G)=>{let W=C0(G);return W!==void 0&&W<=Z}}case"gte":{let Z=c(X,$);return(G)=>X0(G)&&G>=Z}case"lte":{let Z=c(X,$);return(G)=>X0(G)&&G<=Z}case"email":return(Z)=>{return typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)};case"file":return(Z)=>{return Z instanceof Blob};case"fileType":{if(!$)throw new P('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let Z=n0($);return(G)=>G instanceof Blob&&G.type.startsWith(Z)}case"fileSize":{let Z=o0($??"");if(Z===0&&!/^0+(B|KB|MB|GB|TB)$/.test($??""))throw new P(`Validation rule "fileSize:${$??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(G)=>G instanceof Blob&&G.size<=Z}case"array":return(Z)=>Array.isArray(Z);case"object":return(Z)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&!(Z instanceof Blob);case"in":{let Z=($??"").split(",").filter((G)=>G!=="");if(Z.length===0)throw new P('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(G)=>typeof G==="string"&&Z.includes(G)}default:throw new P(`Unknown validation rule "${H}". Known rules: ${i0.join(", ")}`)}}function w(H){if(!H.definition)throw Error(`gemi/ai: the recursive schema "${H.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return H.definition}var i=new WeakMap;function j0(H){return typeof H==="object"&&H!==null&&i.has(H)}function d(H){let Q=i.get(H);if(!Q)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Q}function t0(H){let Q={defs:{},cells:new Map},X=H;if(H.node.kind==="ref"){let Z=w(H.node.cell);X={...Z,...H.description?{description:H.description}:{},optional:H.optional,nullable:H.nullable||Z.nullable}}let $=g(X,Q);return Object.keys(Q.defs).length>0?{...$,$defs:Q.defs}:$}function g(H,Q){let X=(H.optional||H.nullable)&&H.node.kind!=="json",$=r0(s0(H.node,Q),X),Z=[H.description,l0(H.node)].filter(Boolean).join(" ");if(Z&&$.$ref!==void 0)$={anyOf:[$]};return Z?{description:Z,...$}:$}function l0(H){let Q=[];if(H.kind==="string"||H.kind==="enum"){let X=H.checks;if(X?.format)Q.push(`Format: ${X.format.name}.`);if(X?.minLength!==void 0)Q.push(`At least ${X.minLength} characters.`);if(X?.maxLength!==void 0)Q.push(`At most ${X.maxLength} characters.`)}else if(H.kind==="number"){let X=H.checks;if(X?.minimum!==void 0)Q.push(`Minimum ${X.minimum}.`);if(X?.exclusiveMinimum!==void 0)Q.push(`Greater than ${X.exclusiveMinimum}.`);if(X?.maximum!==void 0)Q.push(`Maximum ${X.maximum}.`);if(X?.exclusiveMaximum!==void 0)Q.push(`Less than ${X.exclusiveMaximum}.`)}else if(H.kind==="array"){let X=H.checks;if(X?.minItems!==void 0)Q.push(`At least ${X.minItems} items.`);if(X?.maxItems!==void 0)Q.push(`At most ${X.maxItems} items.`)}return Q.join(" ")}function s0(H,Q){switch(H.kind){case"string":return{type:"string"};case"number":return{type:H.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof H.value,const:H.value};case"enum":return{type:"string",enum:H.values};case"array":return{type:"array",items:g(H.item,Q)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(H.shape).map(([X,$])=>[X,g($,Q)])),required:Object.keys(H.shape),additionalProperties:!1};case"union":return{anyOf:H.members.map((X)=>g(X,Q))};case"json":return{};case"ref":{let{cell:X}=H,$=Q.cells.get(X.name);if($&&$!==X)throw Error(`gemi/ai: two different recursive schemas are named "${X.name}" in one schema; give each s.recursive(...) its own name`);if(!$)Q.cells.set(X.name,X),Q.defs[X.name]={},Q.defs[X.name]=g(w(X),Q);return{$ref:`#/$defs/${X.name}`}}}}function r0(H,Q){if(!Q)return H;if(H.anyOf)return{...H,anyOf:[...H.anyOf,{type:"null"}]};if(H.enum||H.const!==void 0)return{anyOf:[H,{type:"null"}]};if(typeof H.type==="string")return{...H,type:[H.type,"null"]};return{anyOf:[H,{type:"null"}]}}function a0(H){if(H===null)return"null";if(Array.isArray(H))return"array";return typeof H}function e0(H,Q){if(typeof Q==="number"&&!Number.isFinite(Q))return String(Q);if(H.kind==="literal"||H.kind==="enum"){if(typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean")return JSON.stringify(Q)}return a0(Q)}function O0(H){let Q=H.node,X=(()=>{switch(Q.kind){case"number":return Q.checks?.integer?"integer":"number";case"string":case"boolean":return Q.kind;case"literal":return JSON.stringify(Q.value);case"enum":return`one of ${Q.values.map(($)=>JSON.stringify($)).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 O0({...w(Q.cell),optional:!1,nullable:!1})}})();return H.optional||H.nullable?`${X} or null`:X}function HH(H){let Q="";for(let X of H)Q+=typeof X==="number"?`[${X}]`:Q?`.${X}`:X;return Q}function QH(H){let Q=HH(H);return Q?`${Q}: `:""}function Z0(H){return`${QH(H.path)}${H.message}`}function u(H,Q){if(Q===null||Q===void 0)return H.optional||H.nullable?1:0;let X=H.node;switch(X.kind){case"string":return typeof Q==="string"?1:0;case"number":return typeof Q==="number"?1:0;case"boolean":return typeof Q==="boolean"?1:0;case"literal":return Q===X.value?10:0;case"enum":return typeof Q==="string"&&X.values.includes(Q)?10:0;case"array":return Array.isArray(Q)?1:0;case"object":{if(typeof Q!=="object"||Array.isArray(Q))return 0;let $=Q,Z=1;for(let[G,W]of Object.entries(X.shape))Z+=u(W,$[G]);return Z}case"union":return X.members.reduce(($,Z)=>Math.max($,u(Z,Q)),0);case"json":return 1;case"ref":return I0(X.cell,Q,()=>1,()=>u(w(X.cell),Q))}}function I0(H,Q,X,$){if(typeof Q!=="object"||Q===null)return $();if(H.active.has(Q))return X();H.active.add(Q);try{return $()}finally{H.active.delete(Q)}}function j(H,Q,X,$){if(H.optional&&(Q===null||Q===void 0))return{drop:!0,value:void 0};if(H.nullable&&Q===null)return{drop:!1,value:null};return{drop:!1,value:XH(H,Q,X,$)}}function XH(H,Q,X,$){let Z=H.node,G=()=>{let W=Q===void 0?"required":Z.kind==="literal"?"const":Z.kind==="enum"&&typeof Q==="string"?"enum":"type",Y=W==="const"?{allowedValue:Z.value}:W==="enum"?{allowedValues:Z.values}:{};$.push({path:X,code:W,message:`expected ${O0(H)}, got ${e0(Z,Q)}`,params:Y});return};switch(Z.kind){case"string":if(typeof Q!=="string")return G();return V0(Z.checks,Q,X,$),Q;case"number":if(typeof Q!=="number"||!Number.isFinite(Q))return G();if(Z.checks?.integer&&!Number.isInteger(Q))return G();return $H(Z.checks,Q,X,$),Q;case"boolean":return typeof Q==="boolean"?Q:G();case"literal":return Q===Z.value?Q:G();case"enum":if(typeof Q!=="string"||!Z.values.includes(Q))return G();return V0(Z.checks,Q,X,$),Q;case"array":{if(!Array.isArray(Q))return G();let W=Q.map((M,U)=>{let R=j(Z.item,M,[...X,U],$);return R.drop?void 0:R.value}),{minItems:Y,maxItems:T}=Z.checks??{};if(Y!==void 0&&Q.length<Y)$.push({path:X,code:"minItems",message:`expected at least ${Y} items, got ${Q.length}`,params:{limit:Y}});if(T!==void 0&&Q.length>T)$.push({path:X,code:"maxItems",message:`expected at most ${T} items, got ${Q.length}`,params:{limit:T}});return W}case"object":{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return G();let W=Q,Y={};for(let[T,M]of Object.entries(Z.shape)){let U=j(M,W[T],[...X,T],$);if(!U.drop)Y[T]=U.value}if(Z.unknownKeys)for(let T of Object.keys(W)){if(Object.hasOwn(Z.shape,T)||W[T]===void 0)continue;if(Z.unknownKeys==="error"){$.push({path:[...X,T],code:"additionalProperties",message:"unknown key",params:{additionalProperty:T}});continue}b(W[T],[...X,T],$,new Set),Object.defineProperty(Y,T,{value:W[T],enumerable:!0,writable:!0,configurable:!0})}return Y}case"union":{let W;for(let Y of Z.members){let T=[],M=j(Y,Q,X,T);if(T.length===0)return M.drop?void 0:M.value;let U=u(Y,Q);if(!W||U>W.score)W={issues:T,score:U}}$.push({path:X,code:"anyOf",message:`no matching variant; closest: ${W.issues.map(Z0).join("; ")}`,params:{closest:W.issues}});return}case"json":if(Q===void 0)return G();return b(Q,X,$,new Set),Q;case"ref":return I0(Z.cell,Q,()=>{$.push({path:X,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>j(w(Z.cell),Q,X,$).value)}}function ZH(H){let Q=0;for(let X of H)Q++;return Q}function V0(H,Q,X,$){if(!H)return;let{minLength:Z,maxLength:G,format:W}=H;if(Z!==void 0||G!==void 0){let Y=ZH(Q);if(Z!==void 0&&Y<Z)$.push({path:X,code:"minLength",message:`expected at least ${Z} characters, got ${Y}`,params:{limit:Z}});if(G!==void 0&&Y>G)$.push({path:X,code:"maxLength",message:`expected at most ${G} characters, got ${Y}`,params:{limit:G}})}if(W){let Y=!1;try{Y=W.test(Q)===!0}catch{}if(!Y)$.push({path:X,code:"format",message:`expected a string in format "${W.name}"`,params:{format:W.name}})}}function $H(H,Q,X,$){if(!H)return;let Z=(G,W,Y,T)=>{if(W===void 0||Y(W))return;$.push({path:X,code:G,message:`expected ${T} ${W}, got ${Q}`,params:{limit:W}})};Z("minimum",H.minimum,(G)=>Q>=G,"at least"),Z("exclusiveMinimum",H.exclusiveMinimum,(G)=>Q>G,"more than"),Z("maximum",H.maximum,(G)=>Q<=G,"at most"),Z("exclusiveMaximum",H.exclusiveMaximum,(G)=>Q<G,"less than")}function b(H,Q,X,$,Z=!0){let G=(Y)=>{X.push({path:Q,code:"type",message:`expected a JSON value, got ${Y}`,params:{}})};switch(typeof H){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(H))G(String(H));return;case"bigint":return G("a bigint");case"function":return G("a function");case"symbol":return G("a symbol")}if(H===null)return;let W=H;if($.has(W))return G("a circular reference");$.add(W);try{let Y=Z?W.toJSON:void 0;if(typeof Y==="function"){let T;try{T=Y.call(W)}catch{return G("a toJSON that threw")}if(T===void 0)return G("a toJSON that returns undefined");return b(T,Q,X,$,!1)}if(Array.isArray(H))H.forEach((T,M)=>b(T,[...Q,M],X,$));else for(let[T,M]of Object.entries(W))b(M,[...Q,T],X,$)}finally{$.delete(W)}}function A(H){return o(H)}function o(H){let Q={toJSONSchema:()=>t0(H),parse(X){let $=[],Z=j(H,X,[],$);if($.length>0)throw Error($.map(Z0).join("; "));return Z.drop?void 0:Z.value},safeParse(X){let $=[],Z=j(H,X,[],$);if($.length>0)return{ok:!1,errors:$.map(Z0)};return{ok:!0,value:Z.drop?void 0:Z.value}},validate(X){let $=[],Z=j(H,X,[],$);if($.length>0)return{ok:!1,issues:$};return{ok:!0,value:Z.drop?void 0:Z.value}},describe:(X)=>o({...H,description:X}),optional:()=>o({...H,optional:!0}),nullable:()=>o({...H,nullable:!0,optional:!1})};return i.set(Q,H),Q}function L(H){return{node:H,optional:!1,nullable:!1}}var _0=["strip","error","passthrough"];class q0 extends Error{problems;constructor(H){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
3
3
  ${H.map((Q)=>`- ${Q}`).join(`
4
4
  `)}`);this.name="JSONSchemaError",this.problems=H}}var GH=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),x={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function m(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}function n(H,Q,X,$){let Z=(D,K=X)=>{$.push(K?`${K}: ${D}`:D);return},G=(D)=>X?`${X}.${D}`:D;if(!m(H))return Z("expected a schema object");let W=new Set(Q.ignoreKeywords??[]),Y=(D)=>GH.has(D)||D.startsWith("x-")||W.has(D),T=!1,M=H.type;if(Array.isArray(M)){let D=M.filter((K)=>K!=="null");if(D.length!==1)return Z(`type ${JSON.stringify(M)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,G("type"));T=D.length<M.length,M=D[0]}if(M!==void 0&&(typeof M!=="string"||!(M in x)))return Z(`type ${JSON.stringify(M)} is not supported; expected one of ${Object.keys(x).join(", ")}`,G("type"));let U=new Set(["type","description","enum","const","anyOf",...M?x[M]:[]]),R=!1;for(let D of Object.keys(H)){if(U.has(D)||Y(D))continue;R=!0;let K=Object.entries(x).find(([,z])=>z.includes(D));Z(K&&K[0]!==M?`"${D}" applies to type ${K[0]}, and this schema is ${M?`type ${M}`:"untyped"}`:`"${D}" is not supported by s.fromJSONSchema`,G(D))}if(R)return;if(H.description!==void 0&&typeof H.description!=="string")return Z("expected a string",G("description"));let p=H.description,C=(D)=>({node:D,optional:!1,nullable:T,...p?{description:p}:{}});if(H.anyOf!==void 0){if(M!==void 0||H.enum!==void 0||H.const!==void 0)return Z("anyOf cannot be combined with type, enum or const here",G("anyOf"));if(!Array.isArray(H.anyOf)||H.anyOf.length===0)return Z("expected a non-empty array",G("anyOf"));let D=[],K=!1;if(H.anyOf.forEach((z,B)=>{if(m(z)&&z.type==="null"&&Object.keys(z).length===1){T=!0;return}let J=n(z,Q,G(`anyOf[${B}]`),$);if(J)D.push(J);else K=!0}),K)return;if(D.length===0)return Z("anyOf has only null in it",G("anyOf"));if(D.length===1){let z=D[0];return{...z,nullable:z.nullable||T,...p?{description:p}:{}}}return C({kind:"union",members:D})}if(H.const!==void 0){let D=H.const;if(typeof D!=="string"&&typeof D!=="number"&&typeof D!=="boolean")return Z("only a string, number or boolean const is supported",G("const"));if(M!==void 0&&typeof D!==(M==="integer"?"number":M))return Z(`const ${JSON.stringify(D)} is not of type ${M}`,G("const"));return C({kind:"literal",value:D})}let q;if(M==="string"){if(q=WH(H,Q,G,$),q===null)return}if(H.enum!==void 0){if(!Array.isArray(H.enum)||H.enum.length===0)return Z("expected a non-empty array",G("enum"));let D=H.enum.filter((B)=>B!==null);if(D.length<H.enum.length)T=!0;let K=D.find((B)=>!(typeof B==="string"||typeof B==="number"||typeof B==="boolean")||M!==void 0&&typeof B!==(M==="integer"?"number":M));if(K!==void 0||D.length===0)return Z(M?`every value must be of type ${M}${D.length===0?", and there must be one":`; ${JSON.stringify(K)} is not`}`:"only strings, numbers and booleans are supported",G("enum"));if(D.every((B)=>typeof B==="string"))return C({kind:"enum",values:[...new Set(D)],...q?{checks:q}:{}});let z=[...new Set(D)];if(z.length===1)return C({kind:"literal",value:z[0]});return C({kind:"union",members:z.map((B)=>L({kind:"literal",value:B}))})}switch(M){case void 0:return Z("a schema needs a type, an enum, a const or an anyOf");case"string":return C({kind:"string",...q?{checks:q}:{}});case"number":case"integer":{let D=M==="integer"?{integer:!0}:{},K=!1;for(let z of x.number){let B=H[z];if(B===void 0)continue;if(typeof B!=="number"||!Number.isFinite(B)){Z("expected a number",G(z)),K=!0;continue}D[z]=B}if(K)return;return C({kind:"number",...Object.keys(D).length>0?{checks:D}:{}})}case"boolean":return C({kind:"boolean"});case"array":{if(!m(H.items))return Z('an array needs "items" to be one schema (tuples are not supported)',G("items"));let D={},K=!1;for(let B of["minItems","maxItems"]){let J=H[B];if(J===void 0)continue;if(typeof J!=="number"||!Number.isInteger(J)||J<0){Z("expected a non-negative integer",G(B)),K=!0;continue}D[B]=J}let z=n(H.items,Q,G("items"),$);if(!z||K)return;return C({kind:"array",item:z,...Object.keys(D).length>0?{checks:D}:{}})}case"object":{let D=H.properties??{};if(!m(D))return Z("expected an object",G("properties"));if(H.additionalProperties!==void 0&&H.additionalProperties!==!1)return Z("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",G("additionalProperties"));let K=H.required??[];if(!Array.isArray(K)||!K.every((_)=>typeof _==="string"))return Z("expected an array of property names",G("required"));let z=K.filter((_)=>!Object.hasOwn(D,_));if(z.length>0)return Z(`lists properties the schema doesn't have: ${z.join(", ")}`,G("required"));let B={},J=!1;for(let[_,d0]of Object.entries(D)){let H0=n(d0,Q,G(`properties.${_}`),$);if(!H0){J=!0;continue}B[_]=K.includes(_)?H0:{...H0,optional:!0}}if(J)return;let e=Q.unknownKeys;return C({kind:"object",shape:B,...e==="error"||e==="passthrough"?{unknownKeys:e}:{}})}}return}function WH(H,Q,X,$){let Z={},G=!1;for(let W of["minLength","maxLength"]){let Y=H[W];if(Y===void 0)continue;if(typeof Y!=="number"||!Number.isInteger(Y)||Y<0){$.push(`${X(W)}: expected a non-negative integer`),G=!0;continue}Z[W]=Y}if(H.format!==void 0){let W=H.format,Y=typeof W==="string"?Q.formats?.[W]:void 0;if(typeof W!=="string")$.push(`${X("format")}: expected a string`),G=!0;else if(!Y||!Object.hasOwn(Q.formats,W))$.push(`${X("format")}: unknown format ${JSON.stringify(W)}; pass a check for it in the formats option`),G=!0;else Z.format={name:W,test:YH(Y)}}if(G)return null;return Object.keys(Z).length>0?Z:void 0}function YH(H){if(H===!0)return()=>!0;if(H instanceof RegExp)return(Q)=>{return H.lastIndex=0,H.test(Q)};return H}var mH={string:()=>A(L({kind:"string"})),number:()=>A(L({kind:"number"})),boolean:()=>A(L({kind:"boolean"})),literal:(H)=>A(L({kind:"literal",value:H})),enum:(H)=>A(L({kind:"enum",values:H})),object:(H)=>A(L({kind:"object",shape:Object.fromEntries(Object.entries(H).map(([Q,X])=>[Q,d(X)]))})),array:(H)=>A(L({kind:"array",item:d(H)})),union:(H)=>A(L({kind:"union",members:H.map(d)})),json:()=>A(L({kind:"json"})),recursive:MH,fromJSONSchema:(H,Q={})=>{let X=[];if(Q.unknownKeys!==void 0&&!_0.includes(Q.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${_0.map((Z)=>JSON.stringify(Z)).join(", ")}, got ${JSON.stringify(Q.unknownKeys)}`);let $=n(H,Q,"",X);if(!$||X.length>0)throw new q0(X.length>0?X:["unreadable schema"]);return A($)}};function dH(H){let Q=i.get(H);if(Q)return k(Q.node);return y(H.toJSONSchema())}function y(H){if(!(H.$ref!==void 0||H.type!==void 0||H.enum!==void 0||H.const!==void 0||H.anyOf!==void 0||H.properties!==void 0||H.items!==void 0))return!1;for(let X of Object.values(H.properties??{}))if(!y(X))return!1;if(H.items&&!y(H.items))return!1;for(let X of H.anyOf??[])if(!y(X))return!1;for(let X of Object.values(H.$defs??{}))if(!y(X))return!1;return!0}function k(H,Q=new Set){switch(H.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(H.shape).every((X)=>k(X.node,Q));case"array":return k(H.item.node,Q);case"union":return H.members.every((X)=>k(X.node,Q));case"json":return!1;case"ref":if(Q.has(H.cell))return!0;return Q.add(H.cell),k(w(H.cell).node,Q)}}function $0(H,Q,X=new Set){let $=H.node;if($.kind==="union")return $.members.some((Z)=>$0(Z,Q,X));if($.kind!=="ref")return!1;if($.cell===Q)return!0;if(X.has($.cell)||!$.cell.definition)return!1;return X.add($.cell),$0($.cell.definition,Q,X)}var TH=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function MH(H,Q){if(typeof H!=="string"||!TH.test(H))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(H)}`);let X={name:H,active:new Set},$=()=>L({kind:"ref",cell:X}),Z=d(Q(A($())));if(Z.optional)throw Error(`gemi/ai: the recursive schema "${H}" is optional() as a whole; mark the places that use it optional instead`);if($0(Z,X))throw Error(`gemi/ai: the recursive schema "${H}" 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 X.definition=Z,A($())}function N0(H){if(typeof H!=="string")return null;let[Q]=H.split(";",1),X=Q.trim().toLowerCase();return X===""?null:X}function w0(H){if(H===null)return!1;if(H==="application/json")return!0;let Q=H.indexOf("/");return Q>0&&H.endsWith("+json")&&H.length>Q+1+5}var f=new WeakMap;function nH(H,Q,X,$){f.set(H,{clientAddress:Q,...X?{grant:Object.freeze({...X,scopes:Object.freeze([...X.scopes])})}:{},...$?{progress:$}:{}})}function E0(H){return f.get(H)?.progress}function S0(H){return f.get(H)?.grant}function x0(H){return f.has(H)}function iH(H){return f.get(H)?.clientAddress}var g0=new WeakMap;function lH(H,Q){g0.set(H,Q)}function y0(H){return g0.get(H)??null}var G0=new WeakMap;function sH(H,Q){let X=G0.get(H)??[];if(!X.includes(Q))G0.set(H,[...X,Q])}function rH(H){return G0.get(H)??[]}class E{data;constructor(H){this.data=H}get(H){return this.data[H]}has(H){return this.data[H]!==void 0}toJSON(){return this.data}}function k0(H){return typeof H==="object"&&H!==null&&!(H instanceof Blob)}function DH(H,Q){if(!Q.includes(".")||Object.hasOwn(H,Q))return[{path:[Q],value:H[Q]}];let X=[{path:[],value:H}];for(let $ of Q.split(".")){let Z=[];for(let{path:G,value:W}of X){if($==="*"){if(Array.isArray(W))W.forEach((Y,T)=>Z.push({path:[...G,T],value:Y}));else if(k0(W))for(let[Y,T]of Object.entries(W))Z.push({path:[...G,Y],value:T});continue}if(Array.isArray(W)&&/^\d+$/.test($)){Z.push({path:[...G,Number($)],value:W[Number($)]});continue}Z.push({path:[...G,$],value:k0(W)&&Object.hasOwn(W,$)?W[$]:void 0})}X=Z}return X}function b0(H){return H.join(".")}class UH{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;constructor(H,Q,X,$){if(!H){let T=V.getStore().req;this.params=T.params,this.rawRequest=T.rawRequest,this.kind=T.kind,this.routePath=T.routePath,this.domain=T.domain??null}else this.params=Q,this.rawRequest=H,this.routePath=$,this.kind=X??"api",this.domain=y0(H);this.headers=this.rawRequest.headers;let Z=Q0(this.rawRequest.headers.get("Cookie")),G=new URL(this.rawRequest.url),W=new Map;for(let[T,M]of G.searchParams)if(W.has(T)){let U=W.get(T);if(Array.isArray(U))U.push(M),W.set(T,U);else W.set(T,[U,M])}else W.set(T,M);let Y=Object.fromEntries(W.entries());this.search=new E(Y),this.cookies=Z}locale(){return V.getStore().locale}ctx(){return V.getStore()}isModelOriginated(){return x0(this.rawRequest)}mcpGrant(){return S0(this.rawRequest)??null}reportProgress(H){let Q=E0(this.rawRequest);if(!Q)return!1;return Q(H),!0}get signal(){return this.rawRequest.signal}range(){return J0(this.rawRequest.headers.get("Range"))}refine(H){return{}}async parseBody(){let H=N0(this.rawRequest.headers.get("Content-Type"));if(w0(H))return new E(await this.parseJsonBody());if(H==="application/x-www-form-urlencoded"||H==="multipart/form-data"){let Q;try{Q=await this.rawRequest.formData()}catch($){if($ instanceof F)throw $;throw new F("The request body could not be read as a form.")}let X=new Map;for(let[$,Z]of Q.entries())if(X.has($)){let G=X.get($);if(Array.isArray(G))G.push(Z);else X.set($,[G,Z])}else X.set($,Z);return new E(Object.fromEntries(X.entries()))}return new E({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let H;try{H=await this.rawRequest.text()}catch(X){if(X instanceof F)throw X;throw new F("The request body could not be read.")}if(H.trim()==="")return{};let Q;try{Q=JSON.parse(H)}catch{throw new F("The request body is not valid JSON.")}if(Q===null||typeof Q!=="object")throw new F("The request body must be a JSON object.");return Q}validateInput(H){if(j0(this.schema))return this.validateWithSchema(H);let Q=H.toJSON()??{},X={},$=Object.entries(this.schema).map(([Z,G])=>({key:Z,rules:Object.entries(G).map(([W,Y])=>({rule:W,message:Y,check:typeof Y==="function"?null:this.ruleFor(Z,W)}))}));for(let{key:Z,rules:G}of $)for(let{path:W,value:Y}of DH(Q,Z)){let T=this.checkField(Y,G);if(T.length>0){let M=X[b0(W)]??=[];for(let U of T)if(!M.includes(U))M.push(U)}}if(this.addRefinements(X,Q),Object.keys(X).length>0)throw new S(X);return H}checkField(H,Q){let X=Q.some(({rule:G})=>G==="required"),$=H===void 0||H===null||H==="",Z=[];for(let{rule:G,message:W,check:Y}of Q){let T=W,M=!1;if(typeof W==="function")T=W(H),M=typeof T>"u";else M=Y(H);if(M)continue;if($&&!X)continue;if(G==="required")return[String(T)];if(!Z.includes(String(T)))Z.push(String(T))}return Z}validateWithSchema(H){let Q=this.schema.validate(H.toJSON()),X={};if("issues"in Q)for(let Z of Q.issues){let G=b0(Z.path),W=X[G]??=[];if(!W.includes(Z.message))W.push(Z.message)}let $="value"in Q?new E(Q.value):H;if(this.addRefinements(X,$.toJSON()),Object.keys(X).length>0)throw new S(X);return $}addRefinements(H,Q){for(let[X,$]of Object.entries(this.refine(Q)??{})){let Z=H[X]??[];H[X]=Z.includes($)?Z:[...Z,$]}}ruleFor(H,Q){try{return P0(Q)}catch(X){if(X instanceof P)throw new P(`${this.constructor.name}.schema.${H}: ${X.message}`);throw X}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let H=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(H)}}catch(Q){if(!(Q instanceof S))throw Q;return{isValid:!1,errors:Q.errors,input:H}}}}class KH extends F{error;constructor(H="Not authorized"){super(H);this.name="AuthorizationError",this.error=H,this.payload={api:{status:401,data:{error:l("authorization",this.error,401)}},view:{}}}}class W0 extends F{static apiStatus=403;error;constructor(H="Insufficient permissions"){super(H);this.name="InsufficientPermissionsError",this.error=H,this.payload={api:{status:W0.apiStatus,data:{error:l("permission",this.error,W0.apiStatus)}},view:{status:403}}}}class Y0 extends F{total;constructor(H){super("Range not satisfiable");this.total=H;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:t("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":R0(H),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class BH extends F{constructor(H="Not found"){super(H);this.name="NotFoundError",this.payload={api:{status:404,data:{error:t("not_found",H,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class O extends F{fileName;constructor(H){super("File not found");this.fileName=H;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:t("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class zH extends F{constructor(H={}){super("Authentication error");this.name="AuthenticationError";let Q=H.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:l("authentication","Authentication error",401)}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Q}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Q}}}}}class v{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return f0(this.getFacadeAccessor())}}function s(H){if(typeof H!=="string"||/^[\s/.]*$/.test(H))throw Error(`Refusing to delete by prefix ${JSON.stringify(H)}: it would match the whole store`)}class T0{async*objects(H,Q={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(H,Q={}){s(H);let X=[];for await(let $ of this.objects(H,Q))X.push($.name);for(let $ of X)Q.signal?.throwIfAborted(),await this.delete({name:$,bucket:Q.bucket});return X.length}async delete(H){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(H){let Q=typeof H==="string"?{name:H}:H,X=await this.fetch({name:Q.name,bucket:Q.bucket});if(!X.ok)throw new O(Q.name);let $=X.headers.get("Content-Type")??"application/octet-stream",Z=X.headers.get("ETag")??void 0,G=X.headers.get("Last-Modified"),W=G?new Date(G):void 0;if(Q.range){let M=await X.blob();return{body:M,start:0,end:M.size-1,total:M.size,partial:!1,type:$,etag:Z,lastModified:W,name:Q.name}}let Y=Number(X.headers.get("Content-Length")),T=Number.isFinite(Y)?Y:0;return{body:X.body,start:0,end:T-1,total:T,partial:!1,type:$,etag:Z,lastModified:W,name:Q.name}}async size(H){let Q=typeof H==="string"?H:H.name,X=typeof H==="string"?void 0:H.bucket,$=await this.fetch({name:Q,bucket:X});if(!$.ok)throw new O(Q);let Z=Number($.headers.get("Content-Length"));if(Number.isFinite(Z))return await $.body?.cancel(),Z;return(await $.blob()).size}}function v0(H,Q){if(!Q)return H;let X=H.getReader(),$=!1,Z,G=()=>{if($=!0,Z)Q.removeEventListener("abort",Z)};return new ReadableStream({start(W){if(Z=()=>{if($)return;G(),W.error(Q.reason),X.cancel(Q.reason).catch(()=>{})},Q.aborted)Z();else Q.addEventListener("abort",Z,{once:!0})},async pull(W){let Y;try{Y=await X.read()}catch(T){if($)return;G(),W.error(T);return}if($)return;if(Y.done){G(),W.close();return}W.enqueue(Y.value)},cancel(W){return G(),X.cancel(W)}},{highWaterMark:0})}import{readdir as M0,rmdir as FH,stat as AH,unlink as JH}from"fs/promises";import{isAbsolute as h0,relative as r,resolve as a,sep as I}from"path";class D0 extends T0{configured;constructor(H){super();this.configured=H}get folderPath(){return this.configured??`${h()}/storage`}async put(H,{signal:Q}={}){Q?.throwIfAborted();let X,$;if(H instanceof Blob)X=H,$=`${Bun.randomUUIDv7()}.${H.type.split("/")[1].split(";")[0]}`;else X=H.body,$=H.name;let Z=X instanceof Buffer?X:X instanceof Blob||X instanceof File?Buffer.from(await X.arrayBuffer()):"",G=`${this.folderPath}/${$}`;return Q?.throwIfAborted(),await Bun.write(G,Z),$}async fetch(H,{signal:Q}={}){Q?.throwIfAborted();let X=process.env.BUCKET_NAME,$;if(typeof H==="string")$=H;else X=H.bucket??X,$=H.name;if(!$)throw Error("Object name has to be specified");let Z=`${this.folderPath}/${$}`,G=Bun.file(Z),W=v0(Bun.file(Z).stream(),Q),Y=new Date(G.lastModified).toUTCString();return new Response(W,{headers:{"Content-Type":G.type,"Content-Length":String(G.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":Y}})}async read(H){let Q=typeof H==="string"?{name:H}:H,{name:X,range:$=null}=Q;if(!X)throw Error("Object name has to be specified");let Z=Bun.file(`${this.folderPath}/${X}`);if(!await Z.exists())throw new O(X);let G=Z.size,W=$?L0($,G):null;if($&&!W)throw new Y0(G);let Y=W?.start??0,T=W?W.end:G-1;return{body:W?Z.slice(Y,T+1):Z,start:Y,end:T,total:G,partial:Boolean(W),type:Z.type||"application/octet-stream",lastModified:new Date(Z.lastModified),name:X}}async size(H){let Q=typeof H==="string"?H:H.name,X=Bun.file(`${this.folderPath}/${Q}`);if(!await X.exists())throw new O(Q);return X.size}async delete(H){let Q=typeof H==="string"?H:H.name;if(!Q)throw Error("Object name has to be specified");let X=a(this.folderPath),$=a(X,Q),Z=r(X,$);if(!Z||Z===".."||Z.startsWith(`..${I}`)||h0(Z))throw Error(`Refusing to delete "${Q}": it is outside the storage folder`);try{await JH($)}catch(G){if(G?.code==="ENOENT")return;throw G}}resolvePrefix(H){let Q=a(this.folderPath),X=H.lastIndexOf("/"),$=X===-1?"":H.slice(0,X),Z=X===-1?H:H.slice(X+1),G=a(Q,$),W=r(Q,G);if(W===".."||W.startsWith(`..${I}`)||h0(W))throw Error(`Refusing to list "${H}": it is outside the storage folder`);let Y=W.split(I).join("/");return{root:Q,dir:G,match:Y?`${Y}/${Z}`:Z}}async*objects(H,{signal:Q}={}){Q?.throwIfAborted();let{root:X,dir:$,match:Z}=this.resolvePrefix(H),G=[],W=async(Y)=>{let T;try{T=await M0(Y,{withFileTypes:!0})}catch(M){if(M?.code==="ENOENT"||M?.code==="ENOTDIR")return;throw M}for(let M of T){let U=`${Y}${I}${M.name}`,R=r(X,U).split(I).join("/");if(M.isDirectory()){if(`${R}/`.startsWith(Z)||Z.startsWith(`${R}/`))await W(U)}else if(M.isFile()&&R.startsWith(Z))G.push(R)}};await W($),G.sort();for(let Y of G){Q?.throwIfAborted();let T;try{T=await AH(`${X}/${Y}`)}catch(M){if(M?.code==="ENOENT")continue;throw M}yield{name:Y,size:T.size,lastModified:T.mtime}}}async deletePrefix(H,Q={}){s(H);let{root:X,match:$}=this.resolvePrefix(H);s($);let Z=await super.deletePrefix(H,Q);if(Z>0)await this.pruneEmptyDirs(X,$);return Z}async pruneEmptyDirs(H,Q){let X=[],$=async(Z)=>{let G;try{G=await M0(Z,{withFileTypes:!0})}catch{return}for(let W of G){if(!W.isDirectory())continue;let Y=`${Z}${I}${W.name}`,T=r(H,Y).split(I).join("/");if(`${T}/`.startsWith(Q)||Q.startsWith(`${T}/`)){if(await $(Y),`${T}/`.startsWith(Q))X.push(Y)}}};await $(H);for(let Z of X)try{await FH(Z)}catch{}}async list(){return await M0(this.folderPath)}}function qQ(H){return H}function p0(){return{driver:new D0}}class U0{static token="filesystem";driver;constructor(H={}){this.driver=H.driver??p0().driver}}import{Buffer as RH}from"buffer";async function c0(H){try{return(await import("sharp")).default}catch(Q){throw Error(`${H} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Q})}}class CH extends v{static getFacadeAccessor(){return U0}static async put(H,Q={}){return this.getFacadeRoot().driver.put(H,Q)}static async metadata(H){let Q=RH.from(await H.arrayBuffer()),X=await c0("Storage.metadata()");try{return await X(Q).metadata()}catch{return{}}}static async fetch(H,Q={}){return Q.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(H,Q)}static async read(H,Q={}){let X=typeof H==="string"?{name:H}:{...H},$="range"in Q?Q.range??null:X.range!==void 0?X.range:V.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...X,range:$})}static list(H){return this.getFacadeRoot().driver.list(H)}static objects(H,Q={}){return this.getFacadeRoot().driver.objects(H,Q)}static async deletePrefix(H,Q={}){return this.getFacadeRoot().driver.deletePrefix(H,Q)}static async delete(H){return this.getFacadeRoot().driver.delete(H)}}import{mkdir as K0,readdir as PH,access as VH}from"fs/promises";async function B0(H){try{return await VH(H),!0}catch{return!1}}class z0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${h()}/storage/logs`}constructor(H){this.config=H}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((H)=>{console.error("Log storage unavailable, file logging disabled",H)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let H=`${h()}/storage`;if(!await B0(H))await K0(H);if(!await B0(this.logsDirPath))await K0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await B0(this.logsDirPath))await K0(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let X=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed(X),this.fileSize=0,this.writerSize=0}let Q=(await PH(this.logsDirPath)).sort().reverse()[0];if(Q){let X=Bun.file(`${this.logsDirPath}/${Q}`);if(X.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Q}`,this.writer=X.writer(),this.writer.write(await X.text()),this.writer.write(`
5
5
  `),this.writer.flush(),this.fileSize=X.size}if(!this.writer){let X=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${X}`;let $=Bun.file(`${this.logsDirPath}/${X}`);this.writer=$.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(H,Q,X={}){if(!this.isReady)await this.boot();let $=V.getStore(),Z={};if($)Z={url:$.req.rawRequest.url,method:$.req.rawRequest.method,headers:$.req.rawRequest.headers,body:$.req.rawRequest.body};let G={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:H,message:Q,metadata:{...Z,...X}},W="";try{W=JSON.stringify(G)}catch(Y){console.log("Error parsing log object",Y)}try{let Y=this.config.onLogCreated(G);if(Y instanceof Promise)Y.catch((T)=>console.error("Error in onLogCreated",T))}catch(Y){console.error("Error in onLogCreated",Y)}if(!this.writer)return;this.writerSize+=W.length,this.fileSize+=W.length;try{this.writer.write(W),this.writer.write(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Wh as x}from"./chunk-7g9yh5ae.js";function B(j){return j}function C(){return{supportedLocales:[],defaultLocale:"en-US",prefetch:{},components:{},detectLocale:()=>null,onLocaleChange:(j)=>{console.log(`Locale changed to ${j}`)},timeZone:x,detectTimeZone:()=>null}}
2
+ import{Wh as x}from"./chunk-jmg2zsaf.js";function B(j){return j}function C(){return{supportedLocales:[],defaultLocale:"en-US",prefetch:{},components:{},detectLocale:()=>null,onLocaleChange:(j)=>{console.log(`Locale changed to ${j}`)},timeZone:x,detectTimeZone:()=>null}}
3
3
  export{B as Jc,C as Kc};
4
4
 
5
5
  //# debugId=71C42E9F646488C164756E2164756E21
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Sb as oZ,Vb as t,Wb as aZ,dc as XZ}from"./chunk-0z8ejxre.js";import{oc as DZ,qc as e,sc as U3,tc as B3,vc as C3}from"./chunk-ktr3k768.js";import{Ac as N3,Cc as z3,Dc as X3,Ec as D,Fc as Y3,Gc as K3,Ic as H3,xc as W3}from"./chunk-7vb4eey2.js";import{Lc as F}from"./chunk-n672d4g8.js";import{Ae as _Z,Jd as p,Td as J3,Ud as LZ,Ve as yZ,Yd as r,ad as D3,ed as v,ge as TZ,hd as sZ,ie as $Z,ld as A3,me as SZ,ue as l,ye as m,ze as WZ}from"./chunk-d6591xck.js";import{Xe as I3,Ye as AZ}from"./chunk-whtzggn6.js";import{Gg as qZ,Ig as ZZ,Jg as a,Kg as i,pg as b,rg as PZ}from"./chunk-dexdkh3z.js";import{Wg as tZ}from"./chunk-9b4erdy2.js";import{Xg as G3,Zg as k}from"./chunk-tn2bryy2.js";import{_g as _}from"./chunk-cbqazg9k.js";import{eh as P3}from"./chunk-1myhm0g3.js";import{Uh as OZ}from"./chunk-qsrcdzan.js";import{_h as V3,bi as g}from"./chunk-t4yh4nf9.js";var T3="mcp",S3=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class L extends XZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}class d extends Error{reason;constructor(Z,$){super(Z);this.reason=$;this.name="McpCallRefusedError"}}var j3=/^[A-Za-z0-9_-]{1,64}$/,M3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,jZ=4000,y=1e5,k3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class f{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;constructor(Z,$,G={}){this.router=Z;this.dispatcher=$;this.files=E3(G.files);for(let[W,z]of Object.entries(Z.routes??{}))this.plans.set(W,this.plan(W,z));this.resolveScopes()}list(Z,$){if(MZ(Z),Z.kind==="local")return this.descriptors($);let G=[];for(let[W,z]of this.plans){if(!z.remote||!this.grants(Z.principal,W))continue;if(kZ(z.remote,$))G.push(z.remote)}return G}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values())if(kZ(G,Z))$.push(G);return $}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([Z,{description:$}])=>({name:Z,description:$}))}scopesFor(Z){return[...this.scopeTools].filter(([,{tools:$}])=>$.has(Z)).map(([$])=>$)}async execute(Z,$,G,W,z={}){MZ(Z);let X=this.plans.get($);if(Z.kind==="remote"){if(!X?.remote||!this.grants(Z.principal,$))throw new d(`There is no tool named "${$}".`,"unknown-tool");if(X.descriptor.requiresApproval&&z.approved!==!0)throw new d(`"${$}" needs the user's approval, and this call does not have it.`,"approval-required");W=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${$}".`);let Y=X,K=Z.kind==="remote"?Y.remote:Y.descriptor,U=K.inputSchema.safeParse(G);if(U.ok===!1)throw new L(`Invalid arguments for "${$}": ${U.errors.join(", ")}`);let H=U.value,Q={caller:Z,req:Z.req,tool:K,input:H,ctx:W},V=await this.fillPath(Y,Q),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(I!==K.url)throw new L(`"${$}" has nothing at ${V}.`,404);let C={};for(let q of Y.jsonKeys)if(H[q]!==void 0)C[q]=H[q];let P,x="";if(Y.fileFields.length>0)P=await this.formData(Y,C,Q);else if(K.method==="GET")x=c3(C);else if(Y.jsonKeys.length>0)P=C;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,w={...j?{credentials:j}:{},...z.signal?{signal:z.signal}:{},...z.progress?{progress:z.progress}:{},...Z.kind==="remote"?{identity:{user:Z.principal.user,grant:{via:Z.principal.via,id:Z.principal.id,scopes:Z.principal.scopes,...Z.principal.clientId?{clientId:Z.principal.clientId}:{}}}}:{}},u;try{let q=x?`${V}?${x}`:V;u=Object.keys(w).length>0?await this.dispatcher.dispatchAs(Z.req,K.method,q,P,w):await this.dispatcher.dispatchAs(Z.req,K.method,q,P)}catch(q){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,q),new L(`"${$}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await bZ($,u);return await this.project(Y,Q,u)}plan(Z,$){if(!j3.test(Z))throw Error(`McpRouter: "${Z}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:W,url:z,meta:X}=$;if(z.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[z]?.[W];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...z.matchAll(M3)].map(([,B,A])=>({name:B,modifier:A})),U=X.params??{};for(let B of K)if(!(B.name in U))throw Error(`${G}: the path param "${B.name}" must be bound or declared "input".`);for(let[B,A]of Object.entries(U)){if(!K.some((M)=>M.name===B))throw Error(`${G}: "${B}" in params is not a param of the url.`);if(EZ(A))v3(G,`params.${B}`,A);else RZ(G,`params.${B}`,A)}let H=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(Q.properties)}let V=Object.entries(X.files??{}).map(([B,A])=>({name:B,binder:A}));for(let B of V)RZ(G,`files.${B.name}`,B.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${G}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${G}: title must be a non-empty string.`);let I=m3(G,W,X.annotations);if(V.length>0&&W==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let C={},P=(B,A)=>{if(B in C)throw Error(`${G}: "${B}" is the input key of two params or files, and the model can only send one.`);C[B]=A},x=new Map,j=new Map;for(let B of K){let A=U[B.name];if(A==="input"){let M=b.string().describe(`The ":${B.name}" segment of the url.`);P(B.name,B.modifier==="?"||B.modifier==="*"?M.optional():M)}else if(EZ(A)){let M=A.as??B.name;P(M,A.input),j.set(B.name,{key:M,param:A})}else x.set(B.name,A)}let w={};for(let B of V)if(B.binder==="input")P(B.name,b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),w[B.name]=this.remoteFileSchema();let u=[...Object.keys(C),...V.map((B)=>B.name)];for(let B of new Set(u))if(H.includes(B))throw Error(`${G}: "${B}" is both an input field and a param or file, and the model can only send one.`);let q=Object.freeze({name:Z,description:X.description,method:W,url:z,inputSchema:wZ(X.input,Q,b.object(C)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),q3=!V.every((B)=>B.binder==="input")?null:V.length===0?q:Object.freeze({...q,inputSchema:wZ(X.input,Q,b.object(u3(C,Object.keys(w))),w)});return{descriptor:q,remote:q3,params:K,paramBinders:x,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:Z,fetch:$}=this.files,G={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${Z} bytes decoded.`}};if($)G.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let W={type:"object",description:$?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:G,required:["name","mimeType"],additionalProperties:!1},z=Object.keys(G),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],U={};for(let H of Object.keys(Y))if(!z.includes(H))K.push(`a file has no field "${H}"`);for(let H of z){let Q=Y[H];if(Q===void 0||Q===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof Q!=="string")K.push(`a file's "${H}" must be a string`);else U[H]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:U}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}async fillPath(Z,$){let{input:G,req:W}=$,z=Z.descriptor.url;for(let X of Z.params){let Y=Z.paramBinders.get(X.name),K=Z.modelParams.get(X.name),U;if(Y||K){if(U=K?await this.bind(Z,`the param "${X.name}"`,()=>K.param.bind(G[K.key],W,$),{refusals:!0}):await this.bind(Z,`the param "${X.name}"`,()=>Y(W,$)),U===void 0||U===null||U==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(U)}.`),new L(`"${Z.descriptor.name}" failed on the server.`,500)}else U=G[X.name];let H=`:${X.name}${X.modifier}`;if(U===void 0||U===null||U===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new L(`"${X.name}" of "${Z.descriptor.name}" must not be empty.`);z=z.replace(`/${H}`,"");continue}z=z.replace(H,d3(Z.descriptor.name,X,String(U)))}return z}async formData(Z,$,G){let{input:W,ctx:z}=G,X=Z.descriptor.name;if(G.caller.kind==="remote"){let K=new FormData;for(let[U,H]of Object.entries($))zZ(K,U,H);for(let U of Z.fileFields)K.append(U.name,await this.remoteFile(X,U.name,W[U.name]));return K}if(!z)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,U]of Object.entries($))zZ(Y,K,U);for(let K of Z.fileFields){let U=K.binder==="input"?W[K.name]:await this.bind(Z,`the file "${K.name}"`,()=>K.binder(z,G));if(typeof U!=="string"||U==="")throw new L(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await z.attachments.file(U))}return Y}async remoteFile(Z,$,G){let W=(Q)=>new L(`"${$}" of "${Z}" ${Q}`,400),z=G,{maxBytes:X,fetch:Y}=this.files;if(!w3(z.name))throw W("needs a name of 1 to 255 characters, without control characters or slashes.");if(!b3.test(z.mimeType))throw W(`has a mimeType that is not a media type: "${z.mimeType.slice(0,100)}".`);let K=typeof z.data==="string",U=typeof z.url==="string";if(K===U)throw W(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=z.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-f3(Q)>X)throw W(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!y3.test(Q))throw W("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],z.name,{type:z.mimeType})}if(!Y)throw W("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(z.url)}catch{throw W("has a url that is not a URL.")}if(H.protocol!=="https:")throw W("can only be fetched from an https URL.");try{let Q=await yZ(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw W(`could not be fetched: ${H.host} answered ${Q.status}.`);let V=await Q.arrayBuffer();return new File([V],z.name,{type:z.mimeType})}catch(Q){if(Q instanceof L)throw Q;throw W(`could not be fetched from ${H.host}: ${Q instanceof Error?Q.message:"failed"}.`)}}grants(Z,$){for(let G of Z.scopes??[])if(this.scopeTools.get(G)?.tools.has($))return!0;return!1}resolveScopes(){let Z=this.router.scopes;if(Z===void 0){this.scopeTools.set(T3,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof Z!=="object"||Z===null)throw Error("McpRouter: scopes must be an object of scope names.");let $=new Set([...this.plans.values()].flatMap(({descriptor:G})=>G.tags));for(let[G,W]of Object.entries(Z)){let z=`McpRouter: scope "${G}"`;if(!S3.test(G))throw Error(`${z} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof W?.description!=="string"||W.description==="")throw Error(`${z} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of W.tags??[]){if(!$.has(Y))throw Error(`${z} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:U}]of this.plans)if(U.tags.includes(Y))X.add(K)}for(let Y of W.names??[]){if(!this.plans.has(Y))throw Error(`${z} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${z} reaches no tool. Give it tags or names.`);this.scopeTools.set(G,{description:W.description,tools:X})}}async project(Z,$,G){let{name:W,outputSchema:z}=Z.descriptor;if(G.status<200||G.status>=300)return await bZ(W,G);let X=(V,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${W}" ${V}`);else console.error(`[gemi/mcp] "${W}" ${V}`,I);return new L(`"${W}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),K=await G.text(),U=null;if(K!=="")try{U=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=U;if(Z.result)try{H=await Z.result(U,$)}catch(V){throw X("failed in its result projection:",V)}if(z){let V=z.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let Q=JSON.stringify(H);if(Q!==void 0&&Q.length>y)return`${Q.slice(0,y)}\u2026 [cut at ${y} of ${Q.length} characters]`;return H}async bind(Z,$,G,W={}){try{return await G()}catch(z){if(W.refusals&&z instanceof XZ)throw z;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,z),new L(`"${Z.descriptor.name}" failed on the server.`,500)}}}function MZ(Z){if(Z?.kind==="local"&&Z.req)return;if(Z?.kind==="remote"&&Z.req&&Z.principal?.user&&typeof Z.principal.id==="string"&&Array.isArray(Z.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function kZ(Z,$){if($?.names&&!$.names.includes(Z.name))return!1;if($?.tags&&!Z.tags.some((G)=>$.tags.includes(G)))return!1;return!0}var R3=10485760;function E3(Z){let $=Z?.maxBytes??R3;if(!Number.isSafeInteger($)||$<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let G=Z?.fetchUrls===!0?{}:typeof Z?.fetchUrls==="object"&&Z.fetchUrls!==null?Z.fetchUrls:null;return{maxBytes:$,fetch:G}}function w3(Z){if(Z.length===0||Z.length>255)return!1;for(let $ of Z){let G=$.codePointAt(0);if(G<32||G===127||$==="/"||$==="\\")return!1}return!0}var b3=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,y3=/^[A-Za-z0-9+/]*={0,2}$/;function f3(Z){return Z.endsWith("==")?2:Z.endsWith("=")?1:0}function RZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function EZ(Z){return Z instanceof Object&&Z.__internal_brand==="McpModelParam"}function v3(Z,$,G){if(G.as!==void 0&&(typeof G.as!=="string"||G.as===""))throw Error(`${Z}: ${$}.as must be a non-empty string.`);let W=G.input;if(typeof W?.safeParse!=="function"||typeof W.toJSONSchema!=="function")throw Error(`${Z}: ${$}.input must be a schema, built with s.`);if(typeof G.bind!=="function")throw Error(`${Z}: ${$}.bind must be a function.`)}var g3=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function h3(Z){switch(Z){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function m3(Z,$,G){if(G!==void 0&&(typeof G!=="object"||G===null))throw Error(`${Z}: annotations must be an object of hints.`);let W=h3($);for(let[z,X]of Object.entries(G??{})){if(!g3.has(z))throw Error(`${Z}: "${z}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${Z}: annotations.${z} must be true or false.`);W[z]=X}if(W.readOnlyHint===!0&&(W.destructiveHint||W.idempotentHint))throw Error(`${Z} is read-only${G?.readOnlyHint?"":` (a ${$})`} and also ${W.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(W)}function wZ(Z,$,G,W={}){let z=G.toJSONSchema(),X=Object.fromEntries(Object.entries(W).map(([U,H])=>[U,H.toJSONSchema()])),Y={...$??{},type:"object",properties:{...$?.properties??{},...z.properties,...X},required:[...$?.required??[],...z.required??[],...Object.keys(W)],additionalProperties:!1},K=(U)=>{if(typeof U!=="object"||U===null||Array.isArray(U))return{ok:!1,errors:["expected an object"]};let H=[],Q={};if(Z){let I=Z.safeParse(U);if(I.ok===!1)H.push(...I.errors);else Q={...I.value}}let V=G.safeParse(U);if(V.ok===!1)H.push(...V.errors);else Q={...Q,...V.value};for(let[I,C]of Object.entries(W)){let P=U[I];if(P===void 0){H.push(`"${I}" is required`);continue}let x=C.safeParse(P);if(x.ok===!1)H.push(...x.errors.map((j)=>`${I}: ${j}`));else Q[I]=x.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(U){let H=K(U);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function u3(Z,$){return Object.fromEntries(Object.entries(Z).filter(([G])=>!$.includes(G)))}function d3(Z,$,G){let W=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(W.some((z)=>z==="."||z===".."))throw new L(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return W.map(encodeURIComponent).join("/")}function zZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let W of G)zZ(Z,$,W);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function c3(Z){let $=new URLSearchParams,G=(W,z)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){for(let X of z)G(W,X);return}$.append(W,typeof z==="object"?JSON.stringify(z):String(z))};for(let[W,z]of Object.entries(Z))G(W,z);return $.toString()}async function bZ(Z,$){if($.status>=200&&$.status<300){let W=$.headers.get("Content-Type");if(W&&!k3.test(W)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${W}, which is not shown.`}let z=await $.text();if(z==="")return null;if(z.length>y)return`${z.slice(0,y)}\u2026 [cut at ${y} of ${z.length} characters]`;try{return JSON.parse(z)}catch{return z}}let G=await $.text();if($.status>=400&&$.status<500){let W=G.length>jZ?`${G.slice(0,jZ)}\u2026`:G;throw new L(`"${Z}" was refused with ${$.status}${W?`: ${W}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new L(`"${Z}" failed on the server.`,$.status)}import{createHash as p3,randomBytes as i3,timingSafeEqual as l3}from"crypto";function YZ(Z){let $=Z.headers.get("authorization");if(!$)return null;let G=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec($.trim());return G?G[1]:null}class n3{options;name="api-key";constructor(Z){this.options=Z;if(typeof Z?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test(Z.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof Z.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate(Z){return`${Z}${i3(32).toString("base64url")}`}static hash(Z){return p3("sha256").update(Z).digest("hex")}static hashesMatch(Z,$){let G=Buffer.from(Z),W=Buffer.from($);return G.length===W.length&&l3(G,W)}async resolve(Z){let $=YZ(Z);if(!$?.startsWith(this.options.prefix))return null;let G=await this.options.verify($,Z);if(!G)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!G.user||typeof G.id!=="string"||G.id===""||!Array.isArray(G.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:G.user,via:this.name,id:G.id,scopes:[...G.scopes]}}}}import{createHash as rZ,randomBytes as hZ}from"crypto";async function KZ(Z,$){let G=t3();if(!G)return null;let W=await G.consume(Z,$);return W.allowed?null:Math.max(1,Math.ceil(W.retryAfter/1000))}function t3(){try{let Z=g();return Z.bound(v)?Z.make(v):null}catch{return null}}var HZ=["2026-07-28"],n=["2025-11-25","2025-06-18","2025-03-26"],UZ=[...HZ,...n],QZ="io.modelcontextprotocol/protocolVersion",VZ="io.modelcontextprotocol/clientCapabilities";var BZ="io.modelcontextprotocol/serverInfo",N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class J extends Error{code;data;status;constructor(Z,$,G,W=200){super($);this.code=Z;this.data=G;this.status=W;this.name="JsonRpcError"}}function T(Z,$){return{jsonrpc:"2.0",id:Z,error:{code:$.code,message:$.message,...$.data!==void 0?{data:$.data}:{}}}}function fZ(Z){if(Array.isArray(Z))throw new J(N.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof Z!=="object"||Z===null||Z.jsonrpc!=="2.0")throw new J(N.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let $=Z,G=$.id,W=typeof G==="string"||typeof G==="number"&&Number.isFinite(G);if(typeof $.method==="string"){if($.params!==void 0&&(typeof $.params!=="object"||$.params===null||Array.isArray($.params)))throw new J(N.InvalidRequest,"params must be an object.",void 0,400);if(G===void 0)return{kind:"notification",message:$};if(!W)throw new J(N.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:$}}if(W&&(("result"in $)||("error"in $)))return{kind:"response",message:$};throw new J(N.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function IZ(Z,$){let G=Z.outputSchema?.toJSONSchema(),W={...Z.annotations,...Z.title&&!$?{title:Z.title}:{}};return{name:Z.name,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:Z.inputSchema.toJSONSchema(),...G&&($||G.type==="object")?{outputSchema:G}:{},...Object.keys(W).length>0?{annotations:W}:{}}}function O(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function vZ(Z){let $=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec(Z);if(!$)return Z;try{let G=Buffer.from($[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(G)}catch{return null}}import{createHmac as s3,timingSafeEqual as o3}from"crypto";function JZ(Z,$,G){let W=Buffer.from(JSON.stringify(G)).toString("base64url");return`${$}.${W}.${gZ(Z,$,W).toString("base64url")}`}function FZ(Z,$,G,W=Date.now()){if(typeof G!=="string"||G.length>8192)return null;let z=G.split(".");if(z.length!==3||z[0]!==$)return null;let[,X,Y]=z,K=Buffer.from(Y,"base64url"),U=gZ(Z,$,X);if(K.length!==U.length||!o3(K,U))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=W)return null;return H}function gZ(Z,$,G){return s3("sha256",t(Z)).update(`${$}.${G}`).digest()}var NZ="gemi.mcp.request-state.v1",mZ="gemi.mcp.session.v1",a3=86400000,uZ=600000,dZ="gemi_approval",xZ=2000,r3={limit:600,window:60},e3={limit:30,window:60};class c{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;pending=new Map;inflight=new Map;constructor(Z,$){this.registry=Z;if(typeof $.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=G8($.url);let G=$.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,t(NZ),this.context={resource:this.resource,registry:Z},this.allowedOrigins=new Set(($.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=$.rateLimit===!1?!1:$.rateLimit??r3,this.maxBodyBytes=$.maxBodyBytes??Math.ceil(Z.maxFileBytes*1.4)+1048576,this.serverInfo={name:$.server?.name??"gemi",version:$.server?.version??"1.0.0"},this.instructions=$.server?.instructions,this.nonces=$.nonces??new oZ,this.approvalTimeoutMs=$.approvalTimeoutMs??uZ;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle(Z){let $=new URL(Z.url);if($.host!==this.endpoint.host)return null;for(let z of this.resolvers){let X=await z.handle?.(Z,this.context);if(X)return X}if($.pathname!==this.endpoint.pathname)return null;let G=Z.headers.get("origin");if(G!==null&&!this.allowedOrigins.has(G))return S(T(null,new J(N.InvalidRequest,"Origin not allowed.")),403);let W=G?$8(G):{};if(Z.method==="OPTIONS")return new Response(null,{status:204,headers:{...W,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if(Z.method!=="POST")return cZ(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),W);return cZ(await this.post(Z),W)}async post(Z){let $=null;for(let Y of this.resolvers){let K=await Y.resolve(Z,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt(Z)??this.unauthorized(K.description);$={...K.principal,via:Y.name};break}if(!$)return(YZ(Z)!==null?await this.failedAttempt(Z):null)??this.unauthorized();let G=await this.spend($);if(G)return G;let W=Z.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(W))return new Response("Content-Type must be application/json.",{status:415});let z;try{z=JSON.parse(await Z8(Z,this.maxBodyBytes))}catch(Y){if(Y instanceof o)return S(T(null,new J(N.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return S(T(null,new J(N.ParseError,"Parse error.")),400)}let X=new PZ(Z,{},"api",this.endpoint.pathname);return await tZ.run(X,async()=>{try{return await this.dispatch(Z,X,$,z)}catch(Y){if(Y instanceof J){let K=O(z)&&(typeof z.id==="string"||typeof z.id==="number")?z.id:null;return S(T(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),S(T(null,new J(N.InternalError,"Internal error.")),500)}},{user:$.user})}async dispatch(Z,$,G,W){let z=fZ(W),X={kind:"remote",req:$,principal:G};if(z.kind==="response"){let P=this.session(Z,G),x=this.pending.get(String(z.message.id));if(x&&x.session===P.id)this.pending.delete(String(z.message.id)),x.resolve(z.message);return new Response(null,{status:202})}let{message:Y}=z,K=Y.params??{},U=O(K._meta)?K._meta:{};if(typeof U[QZ]==="string"){if(this.checkModernHeaders(Z,Y,U[QZ]),z.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,x)=>this.modern({principal:G,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:x}),iZ(K),Z.signal)}if(Y.method==="initialize"){if(z.kind!=="request")throw new J(N.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(z.message,K,G)}let H=this.session(Z,G),Q=Z.headers.get("mcp-protocol-version");if(Q!==null&&Q!==H.state.v)throw new J(N.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${H.state.v}.`,void 0,400);if(z.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(V,I);let C=AbortSignal.any([I.signal,Z.signal]);try{return await this.respond(Y,async(P,x)=>this.legacy({principal:G,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:x}),iZ(K)||z8(this.registry,Y,H.state),C,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern(Z){switch(Z.message.method){case"server/discover":return this.complete({supportedVersions:UZ,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:this.registry.list(Z.caller).map(($)=>IZ($,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`,void 0,404)}}async legacy(Z){switch(Z.message.method){case"ping":return{};case"tools/list":return{tools:this.registry.list(Z.caller).map(($)=>IZ($,!1))};case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`)}}complete(Z){return{resultType:"complete",...Z,_meta:{[BZ]:this.serverInfo}}}initialize(Z,$,G){let W=$.protocolVersion,z=n.includes(W)?W:n[0],X=O($.capabilities)?$.capabilities:{},Y={v:z,e:pZ(X.elicitation),p:s(G),exp:Date.now()+a3},K=JZ(mZ,"gms1",Y);return S({jsonrpc:"2.0",id:Z.id,result:{protocolVersion:z,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session(Z,$){let G=Z.headers.get("mcp-session-id");if(!G)throw new J(N.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let W=FZ(mZ,"gms1",G);if(!W||W.p!==s($))throw new J(N.InvalidRequest,"Session not found.",void 0,404);return{id:G,state:W}}checkModernHeaders(Z,$,G){if(!HZ.includes(G))throw new J(N.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:UZ,requested:G},400);let W=(Y)=>new J(N.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if(Z.headers.get("mcp-protocol-version")!==G)throw W("MCP-Protocol-Version does not match the protocol version in _meta.");if(Z.headers.get("mcp-method")!==$.method)throw W("Mcp-Method does not match the method.");let z=$.params??{},X=$.method==="tools/call"||$.method==="prompts/get"?z.name:$.method==="resources/read"?z.uri:void 0;if(X!==void 0){let Y=Z.headers.get("mcp-name");if(Y===null||vZ(Y)!==X)throw W("Mcp-Name does not match the request's name.")}}async callTool(Z){let{params:$,caller:G,principal:W}=Z,z=$.name;if(typeof z!=="string")throw new J(N.InvalidParams,"tools/call needs a tool name.");let X=$.arguments??{},Y=this.registry.list(G,{names:[z]})[0];if(!Y)throw new J(N.InvalidParams,`Unknown tool: ${z}`);let K=!1;if(Y.requiresApproval){let I=Y.inputSchema.safeParse(X);if(I.ok===!1)return this.toolResult(Z,{content:[{type:"text",text:`Invalid arguments for "${z}": ${I.errors.join(", ")}`}],isError:!0});let C=await this.approval(Z,Y,X);if(C.kind==="answer")return C.result;K=!0}let U=X8(Z),H;try{H=await this.registry.execute(G,z,X,void 0,{approved:K,signal:Z.signal,...U?{progress:U}:{}})}catch(I){if(I instanceof L)return this.toolResult(Z,{content:[{type:"text",text:I.message}],isError:!0});if(I instanceof d)throw new J(N.InvalidParams,I.reason==="unknown-tool"?`Unknown tool: ${z}`:I.message);return console.error(`[gemi/mcp] "${z}" failed for ${W.via}:${W.id}:`,I),this.toolResult(Z,{content:[{type:"text",text:`"${z}" failed on the server.`}],isError:!0})}let Q=typeof H==="string"?H:JSON.stringify(H??null),V=Y.outputSchema&&(Z.era.modern||O(H))?{structuredContent:H}:{};return this.toolResult(Z,{content:[{type:"text",text:Q}],...V,isError:!1})}toolResult(Z,$){return Z.era.modern?this.complete($):$}async approval(Z,$,G){let W=Y8($,G),z=(H)=>({kind:"answer",result:this.toolResult(Z,{content:[{type:"text",text:H}],isError:!0})});if(Z.era.modern){let H=O(Z.params._meta)?Z.params._meta:{},Q=O(H[VZ])?H[VZ]:{},V=O(Z.params.inputResponses)?Z.params.inputResponses:null,I=Z.params.requestState,C=W8(G);if(V&&I!==void 0){let x=FZ(NZ,"grs1",I);if(!x||x.p!==s(Z.principal)||x.t!==$.name||x.a!==C)throw new J(N.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(x.n,x.exp))throw new J(N.InvalidParams,"requestState has already been used.");return lZ(V[dZ])?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}if(!pZ(Q.elicitation))throw new J(N.MissingRequiredClientCapability,`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let P={p:s(Z.principal),t:$.name,a:C,n:hZ(16).toString("base64url"),exp:Date.now()+uZ};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[dZ]:{method:"elicitation/create",params:{mode:"form",...W}}},requestState:JZ(NZ,"grs1",P),_meta:{[BZ]:this.serverInfo}}}}let X=Z.era;if(!X.session.e||!Z.stream)return z(`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${hZ(12).toString("base64url")}`,K=X.sessionId,U=await new Promise((H)=>{let Q=setTimeout(()=>{this.pending.delete(Y),H(null)},this.approvalTimeoutMs),V=(I)=>{clearTimeout(Q),H(I)};this.pending.set(Y,{session:K,resolve:V}),Z.signal.addEventListener("abort",()=>{this.pending.delete(Y),V(null)}),Z.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...W}:W})});return U&&!U.error&&lZ(U.result)?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}async spendNonce(Z,$){try{return await this.nonces.consume(Z,$)}catch(G){return console.error("[gemi/mcp] Spending an approval failed:",G),!1}}async respond(Z,$,G,W,z){if(!G)try{let U=await $(null,W);return S({jsonrpc:"2.0",id:Z.id,result:U},200)}finally{z?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,W]),K=new eZ(()=>X.abort());return(async()=>{try{let U=await $(K,Y);K.send({jsonrpc:"2.0",id:Z.id,result:U})}catch(U){if(U instanceof J)K.send(T(Z.id,U));else console.error("[gemi/mcp] The MCP endpoint failed:",U),K.send(T(Z.id,new J(N.InternalError,"Internal error.")))}finally{z?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized(Z){let $=this.resolvers.map((W)=>W.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',G=Z?`${$}, error="invalid_token", error_description="${Z.replace(/["\\]/g,"")}"`:$;return S(T(null,new J(N.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":G})}async failedAttempt(Z){let $=sZ(new PZ(Z,{},"api",this.endpoint.pathname)),G=await KZ(`mcp-auth-failed:${$}`,e3);return G===null?null:nZ(G)}async spend(Z){if(!this.rateLimit)return null;let $=await KZ(`mcp-endpoint:${Z.via}:${Z.id}`,this.rateLimit);return $===null?null:nZ($)}}class eZ{readable;controller;closed=!1;encoder=new TextEncoder;constructor(Z){this.readable=new ReadableStream({start:($)=>{this.controller=$},cancel:()=>{this.closed=!0,Z()}})}send(Z){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
2
+ import{Sb as oZ,Vb as t,Wb as aZ,dc as XZ}from"./chunk-4088szy9.js";import{oc as DZ,qc as e,sc as U3,tc as B3,vc as C3}from"./chunk-ktr3k768.js";import{Ac as N3,Cc as z3,Dc as X3,Ec as D,Fc as Y3,Gc as K3,Ic as H3,xc as W3}from"./chunk-7vb4eey2.js";import{Lc as F}from"./chunk-n672d4g8.js";import{Ae as _Z,Jd as p,Td as J3,Ud as LZ,Ve as yZ,Yd as r,ad as D3,ed as v,ge as TZ,hd as sZ,ie as $Z,ld as A3,me as SZ,ue as l,ye as m,ze as WZ}from"./chunk-ms9k0rx6.js";import{Xe as I3,Ye as AZ}from"./chunk-whtzggn6.js";import{Gg as qZ,Ig as ZZ,Jg as a,Kg as i,pg as b,rg as PZ}from"./chunk-pn8v6fj2.js";import{Wg as tZ}from"./chunk-49nyyjfe.js";import{Xg as G3,Zg as k}from"./chunk-tn2bryy2.js";import{_g as _}from"./chunk-cbqazg9k.js";import{eh as P3}from"./chunk-1myhm0g3.js";import{Uh as OZ}from"./chunk-qsrcdzan.js";import{_h as V3,bi as g}from"./chunk-t4yh4nf9.js";var T3="mcp",S3=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class L extends XZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}class d extends Error{reason;constructor(Z,$){super(Z);this.reason=$;this.name="McpCallRefusedError"}}var j3=/^[A-Za-z0-9_-]{1,64}$/,M3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,jZ=4000,y=1e5,k3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class f{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;constructor(Z,$,G={}){this.router=Z;this.dispatcher=$;this.files=E3(G.files);for(let[W,z]of Object.entries(Z.routes??{}))this.plans.set(W,this.plan(W,z));this.resolveScopes()}list(Z,$){if(MZ(Z),Z.kind==="local")return this.descriptors($);let G=[];for(let[W,z]of this.plans){if(!z.remote||!this.grants(Z.principal,W))continue;if(kZ(z.remote,$))G.push(z.remote)}return G}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values())if(kZ(G,Z))$.push(G);return $}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([Z,{description:$}])=>({name:Z,description:$}))}scopesFor(Z){return[...this.scopeTools].filter(([,{tools:$}])=>$.has(Z)).map(([$])=>$)}async execute(Z,$,G,W,z={}){MZ(Z);let X=this.plans.get($);if(Z.kind==="remote"){if(!X?.remote||!this.grants(Z.principal,$))throw new d(`There is no tool named "${$}".`,"unknown-tool");if(X.descriptor.requiresApproval&&z.approved!==!0)throw new d(`"${$}" needs the user's approval, and this call does not have it.`,"approval-required");W=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${$}".`);let Y=X,K=Z.kind==="remote"?Y.remote:Y.descriptor,U=K.inputSchema.safeParse(G);if(U.ok===!1)throw new L(`Invalid arguments for "${$}": ${U.errors.join(", ")}`);let H=U.value,Q={caller:Z,req:Z.req,tool:K,input:H,ctx:W},V=await this.fillPath(Y,Q),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(I!==K.url)throw new L(`"${$}" has nothing at ${V}.`,404);let C={};for(let q of Y.jsonKeys)if(H[q]!==void 0)C[q]=H[q];let P,x="";if(Y.fileFields.length>0)P=await this.formData(Y,C,Q);else if(K.method==="GET")x=c3(C);else if(Y.jsonKeys.length>0)P=C;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,w={...j?{credentials:j}:{},...z.signal?{signal:z.signal}:{},...z.progress?{progress:z.progress}:{},...Z.kind==="remote"?{identity:{user:Z.principal.user,grant:{via:Z.principal.via,id:Z.principal.id,scopes:Z.principal.scopes,...Z.principal.clientId?{clientId:Z.principal.clientId}:{}}}}:{}},u;try{let q=x?`${V}?${x}`:V;u=Object.keys(w).length>0?await this.dispatcher.dispatchAs(Z.req,K.method,q,P,w):await this.dispatcher.dispatchAs(Z.req,K.method,q,P)}catch(q){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,q),new L(`"${$}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await bZ($,u);return await this.project(Y,Q,u)}plan(Z,$){if(!j3.test(Z))throw Error(`McpRouter: "${Z}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:W,url:z,meta:X}=$;if(z.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[z]?.[W];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...z.matchAll(M3)].map(([,B,A])=>({name:B,modifier:A})),U=X.params??{};for(let B of K)if(!(B.name in U))throw Error(`${G}: the path param "${B.name}" must be bound or declared "input".`);for(let[B,A]of Object.entries(U)){if(!K.some((M)=>M.name===B))throw Error(`${G}: "${B}" in params is not a param of the url.`);if(EZ(A))v3(G,`params.${B}`,A);else RZ(G,`params.${B}`,A)}let H=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(Q.properties)}let V=Object.entries(X.files??{}).map(([B,A])=>({name:B,binder:A}));for(let B of V)RZ(G,`files.${B.name}`,B.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${G}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${G}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${G}: title must be a non-empty string.`);let I=m3(G,W,X.annotations);if(V.length>0&&W==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let C={},P=(B,A)=>{if(B in C)throw Error(`${G}: "${B}" is the input key of two params or files, and the model can only send one.`);C[B]=A},x=new Map,j=new Map;for(let B of K){let A=U[B.name];if(A==="input"){let M=b.string().describe(`The ":${B.name}" segment of the url.`);P(B.name,B.modifier==="?"||B.modifier==="*"?M.optional():M)}else if(EZ(A)){let M=A.as??B.name;P(M,A.input),j.set(B.name,{key:M,param:A})}else x.set(B.name,A)}let w={};for(let B of V)if(B.binder==="input")P(B.name,b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),w[B.name]=this.remoteFileSchema();let u=[...Object.keys(C),...V.map((B)=>B.name)];for(let B of new Set(u))if(H.includes(B))throw Error(`${G}: "${B}" is both an input field and a param or file, and the model can only send one.`);let q=Object.freeze({name:Z,description:X.description,method:W,url:z,inputSchema:wZ(X.input,Q,b.object(C)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),q3=!V.every((B)=>B.binder==="input")?null:V.length===0?q:Object.freeze({...q,inputSchema:wZ(X.input,Q,b.object(u3(C,Object.keys(w))),w)});return{descriptor:q,remote:q3,params:K,paramBinders:x,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:Z,fetch:$}=this.files,G={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${Z} bytes decoded.`}};if($)G.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let W={type:"object",description:$?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:G,required:["name","mimeType"],additionalProperties:!1},z=Object.keys(G),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],U={};for(let H of Object.keys(Y))if(!z.includes(H))K.push(`a file has no field "${H}"`);for(let H of z){let Q=Y[H];if(Q===void 0||Q===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof Q!=="string")K.push(`a file's "${H}" must be a string`);else U[H]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:U}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}async fillPath(Z,$){let{input:G,req:W}=$,z=Z.descriptor.url;for(let X of Z.params){let Y=Z.paramBinders.get(X.name),K=Z.modelParams.get(X.name),U;if(Y||K){if(U=K?await this.bind(Z,`the param "${X.name}"`,()=>K.param.bind(G[K.key],W,$),{refusals:!0}):await this.bind(Z,`the param "${X.name}"`,()=>Y(W,$)),U===void 0||U===null||U==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(U)}.`),new L(`"${Z.descriptor.name}" failed on the server.`,500)}else U=G[X.name];let H=`:${X.name}${X.modifier}`;if(U===void 0||U===null||U===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new L(`"${X.name}" of "${Z.descriptor.name}" must not be empty.`);z=z.replace(`/${H}`,"");continue}z=z.replace(H,d3(Z.descriptor.name,X,String(U)))}return z}async formData(Z,$,G){let{input:W,ctx:z}=G,X=Z.descriptor.name;if(G.caller.kind==="remote"){let K=new FormData;for(let[U,H]of Object.entries($))zZ(K,U,H);for(let U of Z.fileFields)K.append(U.name,await this.remoteFile(X,U.name,W[U.name]));return K}if(!z)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,U]of Object.entries($))zZ(Y,K,U);for(let K of Z.fileFields){let U=K.binder==="input"?W[K.name]:await this.bind(Z,`the file "${K.name}"`,()=>K.binder(z,G));if(typeof U!=="string"||U==="")throw new L(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await z.attachments.file(U))}return Y}async remoteFile(Z,$,G){let W=(Q)=>new L(`"${$}" of "${Z}" ${Q}`,400),z=G,{maxBytes:X,fetch:Y}=this.files;if(!w3(z.name))throw W("needs a name of 1 to 255 characters, without control characters or slashes.");if(!b3.test(z.mimeType))throw W(`has a mimeType that is not a media type: "${z.mimeType.slice(0,100)}".`);let K=typeof z.data==="string",U=typeof z.url==="string";if(K===U)throw W(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=z.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-f3(Q)>X)throw W(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!y3.test(Q))throw W("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],z.name,{type:z.mimeType})}if(!Y)throw W("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(z.url)}catch{throw W("has a url that is not a URL.")}if(H.protocol!=="https:")throw W("can only be fetched from an https URL.");try{let Q=await yZ(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw W(`could not be fetched: ${H.host} answered ${Q.status}.`);let V=await Q.arrayBuffer();return new File([V],z.name,{type:z.mimeType})}catch(Q){if(Q instanceof L)throw Q;throw W(`could not be fetched from ${H.host}: ${Q instanceof Error?Q.message:"failed"}.`)}}grants(Z,$){for(let G of Z.scopes??[])if(this.scopeTools.get(G)?.tools.has($))return!0;return!1}resolveScopes(){let Z=this.router.scopes;if(Z===void 0){this.scopeTools.set(T3,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof Z!=="object"||Z===null)throw Error("McpRouter: scopes must be an object of scope names.");let $=new Set([...this.plans.values()].flatMap(({descriptor:G})=>G.tags));for(let[G,W]of Object.entries(Z)){let z=`McpRouter: scope "${G}"`;if(!S3.test(G))throw Error(`${z} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof W?.description!=="string"||W.description==="")throw Error(`${z} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of W.tags??[]){if(!$.has(Y))throw Error(`${z} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:U}]of this.plans)if(U.tags.includes(Y))X.add(K)}for(let Y of W.names??[]){if(!this.plans.has(Y))throw Error(`${z} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${z} reaches no tool. Give it tags or names.`);this.scopeTools.set(G,{description:W.description,tools:X})}}async project(Z,$,G){let{name:W,outputSchema:z}=Z.descriptor;if(G.status<200||G.status>=300)return await bZ(W,G);let X=(V,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${W}" ${V}`);else console.error(`[gemi/mcp] "${W}" ${V}`,I);return new L(`"${W}" failed on the server.`,500)},Y=G.headers.get("Content-Type"),K=await G.text(),U=null;if(K!=="")try{U=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=U;if(Z.result)try{H=await Z.result(U,$)}catch(V){throw X("failed in its result projection:",V)}if(z){let V=z.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let Q=JSON.stringify(H);if(Q!==void 0&&Q.length>y)return`${Q.slice(0,y)}\u2026 [cut at ${y} of ${Q.length} characters]`;return H}async bind(Z,$,G,W={}){try{return await G()}catch(z){if(W.refusals&&z instanceof XZ)throw z;throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,z),new L(`"${Z.descriptor.name}" failed on the server.`,500)}}}function MZ(Z){if(Z?.kind==="local"&&Z.req)return;if(Z?.kind==="remote"&&Z.req&&Z.principal?.user&&typeof Z.principal.id==="string"&&Array.isArray(Z.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function kZ(Z,$){if($?.names&&!$.names.includes(Z.name))return!1;if($?.tags&&!Z.tags.some((G)=>$.tags.includes(G)))return!1;return!0}var R3=10485760;function E3(Z){let $=Z?.maxBytes??R3;if(!Number.isSafeInteger($)||$<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let G=Z?.fetchUrls===!0?{}:typeof Z?.fetchUrls==="object"&&Z.fetchUrls!==null?Z.fetchUrls:null;return{maxBytes:$,fetch:G}}function w3(Z){if(Z.length===0||Z.length>255)return!1;for(let $ of Z){let G=$.codePointAt(0);if(G<32||G===127||$==="/"||$==="\\")return!1}return!0}var b3=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,y3=/^[A-Za-z0-9+/]*={0,2}$/;function f3(Z){return Z.endsWith("==")?2:Z.endsWith("=")?1:0}function RZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function EZ(Z){return Z instanceof Object&&Z.__internal_brand==="McpModelParam"}function v3(Z,$,G){if(G.as!==void 0&&(typeof G.as!=="string"||G.as===""))throw Error(`${Z}: ${$}.as must be a non-empty string.`);let W=G.input;if(typeof W?.safeParse!=="function"||typeof W.toJSONSchema!=="function")throw Error(`${Z}: ${$}.input must be a schema, built with s.`);if(typeof G.bind!=="function")throw Error(`${Z}: ${$}.bind must be a function.`)}var g3=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function h3(Z){switch(Z){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function m3(Z,$,G){if(G!==void 0&&(typeof G!=="object"||G===null))throw Error(`${Z}: annotations must be an object of hints.`);let W=h3($);for(let[z,X]of Object.entries(G??{})){if(!g3.has(z))throw Error(`${Z}: "${z}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${Z}: annotations.${z} must be true or false.`);W[z]=X}if(W.readOnlyHint===!0&&(W.destructiveHint||W.idempotentHint))throw Error(`${Z} is read-only${G?.readOnlyHint?"":` (a ${$})`} and also ${W.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(W)}function wZ(Z,$,G,W={}){let z=G.toJSONSchema(),X=Object.fromEntries(Object.entries(W).map(([U,H])=>[U,H.toJSONSchema()])),Y={...$??{},type:"object",properties:{...$?.properties??{},...z.properties,...X},required:[...$?.required??[],...z.required??[],...Object.keys(W)],additionalProperties:!1},K=(U)=>{if(typeof U!=="object"||U===null||Array.isArray(U))return{ok:!1,errors:["expected an object"]};let H=[],Q={};if(Z){let I=Z.safeParse(U);if(I.ok===!1)H.push(...I.errors);else Q={...I.value}}let V=G.safeParse(U);if(V.ok===!1)H.push(...V.errors);else Q={...Q,...V.value};for(let[I,C]of Object.entries(W)){let P=U[I];if(P===void 0){H.push(`"${I}" is required`);continue}let x=C.safeParse(P);if(x.ok===!1)H.push(...x.errors.map((j)=>`${I}: ${j}`));else Q[I]=x.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(U){let H=K(U);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function u3(Z,$){return Object.fromEntries(Object.entries(Z).filter(([G])=>!$.includes(G)))}function d3(Z,$,G){let W=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(W.some((z)=>z==="."||z===".."))throw new L(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return W.map(encodeURIComponent).join("/")}function zZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let W of G)zZ(Z,$,W);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function c3(Z){let $=new URLSearchParams,G=(W,z)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){for(let X of z)G(W,X);return}$.append(W,typeof z==="object"?JSON.stringify(z):String(z))};for(let[W,z]of Object.entries(Z))G(W,z);return $.toString()}async function bZ(Z,$){if($.status>=200&&$.status<300){let W=$.headers.get("Content-Type");if(W&&!k3.test(W)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${W}, which is not shown.`}let z=await $.text();if(z==="")return null;if(z.length>y)return`${z.slice(0,y)}\u2026 [cut at ${y} of ${z.length} characters]`;try{return JSON.parse(z)}catch{return z}}let G=await $.text();if($.status>=400&&$.status<500){let W=G.length>jZ?`${G.slice(0,jZ)}\u2026`:G;throw new L(`"${Z}" was refused with ${$.status}${W?`: ${W}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new L(`"${Z}" failed on the server.`,$.status)}import{createHash as p3,randomBytes as i3,timingSafeEqual as l3}from"crypto";function YZ(Z){let $=Z.headers.get("authorization");if(!$)return null;let G=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec($.trim());return G?G[1]:null}class n3{options;name="api-key";constructor(Z){this.options=Z;if(typeof Z?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test(Z.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof Z.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate(Z){return`${Z}${i3(32).toString("base64url")}`}static hash(Z){return p3("sha256").update(Z).digest("hex")}static hashesMatch(Z,$){let G=Buffer.from(Z),W=Buffer.from($);return G.length===W.length&&l3(G,W)}async resolve(Z){let $=YZ(Z);if(!$?.startsWith(this.options.prefix))return null;let G=await this.options.verify($,Z);if(!G)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!G.user||typeof G.id!=="string"||G.id===""||!Array.isArray(G.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:G.user,via:this.name,id:G.id,scopes:[...G.scopes]}}}}import{createHash as rZ,randomBytes as hZ}from"crypto";async function KZ(Z,$){let G=t3();if(!G)return null;let W=await G.consume(Z,$);return W.allowed?null:Math.max(1,Math.ceil(W.retryAfter/1000))}function t3(){try{let Z=g();return Z.bound(v)?Z.make(v):null}catch{return null}}var HZ=["2026-07-28"],n=["2025-11-25","2025-06-18","2025-03-26"],UZ=[...HZ,...n],QZ="io.modelcontextprotocol/protocolVersion",VZ="io.modelcontextprotocol/clientCapabilities";var BZ="io.modelcontextprotocol/serverInfo",N={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class J extends Error{code;data;status;constructor(Z,$,G,W=200){super($);this.code=Z;this.data=G;this.status=W;this.name="JsonRpcError"}}function T(Z,$){return{jsonrpc:"2.0",id:Z,error:{code:$.code,message:$.message,...$.data!==void 0?{data:$.data}:{}}}}function fZ(Z){if(Array.isArray(Z))throw new J(N.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof Z!=="object"||Z===null||Z.jsonrpc!=="2.0")throw new J(N.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let $=Z,G=$.id,W=typeof G==="string"||typeof G==="number"&&Number.isFinite(G);if(typeof $.method==="string"){if($.params!==void 0&&(typeof $.params!=="object"||$.params===null||Array.isArray($.params)))throw new J(N.InvalidRequest,"params must be an object.",void 0,400);if(G===void 0)return{kind:"notification",message:$};if(!W)throw new J(N.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:$}}if(W&&(("result"in $)||("error"in $)))return{kind:"response",message:$};throw new J(N.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function IZ(Z,$){let G=Z.outputSchema?.toJSONSchema(),W={...Z.annotations,...Z.title&&!$?{title:Z.title}:{}};return{name:Z.name,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:Z.inputSchema.toJSONSchema(),...G&&($||G.type==="object")?{outputSchema:G}:{},...Object.keys(W).length>0?{annotations:W}:{}}}function O(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function vZ(Z){let $=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec(Z);if(!$)return Z;try{let G=Buffer.from($[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(G)}catch{return null}}import{createHmac as s3,timingSafeEqual as o3}from"crypto";function JZ(Z,$,G){let W=Buffer.from(JSON.stringify(G)).toString("base64url");return`${$}.${W}.${gZ(Z,$,W).toString("base64url")}`}function FZ(Z,$,G,W=Date.now()){if(typeof G!=="string"||G.length>8192)return null;let z=G.split(".");if(z.length!==3||z[0]!==$)return null;let[,X,Y]=z,K=Buffer.from(Y,"base64url"),U=gZ(Z,$,X);if(K.length!==U.length||!o3(K,U))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=W)return null;return H}function gZ(Z,$,G){return s3("sha256",t(Z)).update(`${$}.${G}`).digest()}var NZ="gemi.mcp.request-state.v1",mZ="gemi.mcp.session.v1",a3=86400000,uZ=600000,dZ="gemi_approval",xZ=2000,r3={limit:600,window:60},e3={limit:30,window:60};class c{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;pending=new Map;inflight=new Map;constructor(Z,$){this.registry=Z;if(typeof $.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=G8($.url);let G=$.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,t(NZ),this.context={resource:this.resource,registry:Z},this.allowedOrigins=new Set(($.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=$.rateLimit===!1?!1:$.rateLimit??r3,this.maxBodyBytes=$.maxBodyBytes??Math.ceil(Z.maxFileBytes*1.4)+1048576,this.serverInfo={name:$.server?.name??"gemi",version:$.server?.version??"1.0.0"},this.instructions=$.server?.instructions,this.nonces=$.nonces??new oZ,this.approvalTimeoutMs=$.approvalTimeoutMs??uZ;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle(Z){let $=new URL(Z.url);if($.host!==this.endpoint.host)return null;for(let z of this.resolvers){let X=await z.handle?.(Z,this.context);if(X)return X}if($.pathname!==this.endpoint.pathname)return null;let G=Z.headers.get("origin");if(G!==null&&!this.allowedOrigins.has(G))return S(T(null,new J(N.InvalidRequest,"Origin not allowed.")),403);let W=G?$8(G):{};if(Z.method==="OPTIONS")return new Response(null,{status:204,headers:{...W,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if(Z.method!=="POST")return cZ(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),W);return cZ(await this.post(Z),W)}async post(Z){let $=null;for(let Y of this.resolvers){let K=await Y.resolve(Z,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt(Z)??this.unauthorized(K.description);$={...K.principal,via:Y.name};break}if(!$)return(YZ(Z)!==null?await this.failedAttempt(Z):null)??this.unauthorized();let G=await this.spend($);if(G)return G;let W=Z.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(W))return new Response("Content-Type must be application/json.",{status:415});let z;try{z=JSON.parse(await Z8(Z,this.maxBodyBytes))}catch(Y){if(Y instanceof o)return S(T(null,new J(N.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return S(T(null,new J(N.ParseError,"Parse error.")),400)}let X=new PZ(Z,{},"api",this.endpoint.pathname);return await tZ.run(X,async()=>{try{return await this.dispatch(Z,X,$,z)}catch(Y){if(Y instanceof J){let K=O(z)&&(typeof z.id==="string"||typeof z.id==="number")?z.id:null;return S(T(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),S(T(null,new J(N.InternalError,"Internal error.")),500)}},{user:$.user})}async dispatch(Z,$,G,W){let z=fZ(W),X={kind:"remote",req:$,principal:G};if(z.kind==="response"){let P=this.session(Z,G),x=this.pending.get(String(z.message.id));if(x&&x.session===P.id)this.pending.delete(String(z.message.id)),x.resolve(z.message);return new Response(null,{status:202})}let{message:Y}=z,K=Y.params??{},U=O(K._meta)?K._meta:{};if(typeof U[QZ]==="string"){if(this.checkModernHeaders(Z,Y,U[QZ]),z.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,x)=>this.modern({principal:G,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:x}),iZ(K),Z.signal)}if(Y.method==="initialize"){if(z.kind!=="request")throw new J(N.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(z.message,K,G)}let H=this.session(Z,G),Q=Z.headers.get("mcp-protocol-version");if(Q!==null&&Q!==H.state.v)throw new J(N.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${H.state.v}.`,void 0,400);if(z.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(V,I);let C=AbortSignal.any([I.signal,Z.signal]);try{return await this.respond(Y,async(P,x)=>this.legacy({principal:G,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:x}),iZ(K)||z8(this.registry,Y,H.state),C,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern(Z){switch(Z.message.method){case"server/discover":return this.complete({supportedVersions:UZ,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:this.registry.list(Z.caller).map(($)=>IZ($,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`,void 0,404)}}async legacy(Z){switch(Z.message.method){case"ping":return{};case"tools/list":return{tools:this.registry.list(Z.caller).map(($)=>IZ($,!1))};case"tools/call":return await this.callTool(Z);default:throw new J(N.MethodNotFound,`Method not found: ${Z.message.method}`)}}complete(Z){return{resultType:"complete",...Z,_meta:{[BZ]:this.serverInfo}}}initialize(Z,$,G){let W=$.protocolVersion,z=n.includes(W)?W:n[0],X=O($.capabilities)?$.capabilities:{},Y={v:z,e:pZ(X.elicitation),p:s(G),exp:Date.now()+a3},K=JZ(mZ,"gms1",Y);return S({jsonrpc:"2.0",id:Z.id,result:{protocolVersion:z,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session(Z,$){let G=Z.headers.get("mcp-session-id");if(!G)throw new J(N.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let W=FZ(mZ,"gms1",G);if(!W||W.p!==s($))throw new J(N.InvalidRequest,"Session not found.",void 0,404);return{id:G,state:W}}checkModernHeaders(Z,$,G){if(!HZ.includes(G))throw new J(N.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:UZ,requested:G},400);let W=(Y)=>new J(N.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if(Z.headers.get("mcp-protocol-version")!==G)throw W("MCP-Protocol-Version does not match the protocol version in _meta.");if(Z.headers.get("mcp-method")!==$.method)throw W("Mcp-Method does not match the method.");let z=$.params??{},X=$.method==="tools/call"||$.method==="prompts/get"?z.name:$.method==="resources/read"?z.uri:void 0;if(X!==void 0){let Y=Z.headers.get("mcp-name");if(Y===null||vZ(Y)!==X)throw W("Mcp-Name does not match the request's name.")}}async callTool(Z){let{params:$,caller:G,principal:W}=Z,z=$.name;if(typeof z!=="string")throw new J(N.InvalidParams,"tools/call needs a tool name.");let X=$.arguments??{},Y=this.registry.list(G,{names:[z]})[0];if(!Y)throw new J(N.InvalidParams,`Unknown tool: ${z}`);let K=!1;if(Y.requiresApproval){let I=Y.inputSchema.safeParse(X);if(I.ok===!1)return this.toolResult(Z,{content:[{type:"text",text:`Invalid arguments for "${z}": ${I.errors.join(", ")}`}],isError:!0});let C=await this.approval(Z,Y,X);if(C.kind==="answer")return C.result;K=!0}let U=X8(Z),H;try{H=await this.registry.execute(G,z,X,void 0,{approved:K,signal:Z.signal,...U?{progress:U}:{}})}catch(I){if(I instanceof L)return this.toolResult(Z,{content:[{type:"text",text:I.message}],isError:!0});if(I instanceof d)throw new J(N.InvalidParams,I.reason==="unknown-tool"?`Unknown tool: ${z}`:I.message);return console.error(`[gemi/mcp] "${z}" failed for ${W.via}:${W.id}:`,I),this.toolResult(Z,{content:[{type:"text",text:`"${z}" failed on the server.`}],isError:!0})}let Q=typeof H==="string"?H:JSON.stringify(H??null),V=Y.outputSchema&&(Z.era.modern||O(H))?{structuredContent:H}:{};return this.toolResult(Z,{content:[{type:"text",text:Q}],...V,isError:!1})}toolResult(Z,$){return Z.era.modern?this.complete($):$}async approval(Z,$,G){let W=Y8($,G),z=(H)=>({kind:"answer",result:this.toolResult(Z,{content:[{type:"text",text:H}],isError:!0})});if(Z.era.modern){let H=O(Z.params._meta)?Z.params._meta:{},Q=O(H[VZ])?H[VZ]:{},V=O(Z.params.inputResponses)?Z.params.inputResponses:null,I=Z.params.requestState,C=W8(G);if(V&&I!==void 0){let x=FZ(NZ,"grs1",I);if(!x||x.p!==s(Z.principal)||x.t!==$.name||x.a!==C)throw new J(N.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(x.n,x.exp))throw new J(N.InvalidParams,"requestState has already been used.");return lZ(V[dZ])?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}if(!pZ(Q.elicitation))throw new J(N.MissingRequiredClientCapability,`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let P={p:s(Z.principal),t:$.name,a:C,n:hZ(16).toString("base64url"),exp:Date.now()+uZ};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[dZ]:{method:"elicitation/create",params:{mode:"form",...W}}},requestState:JZ(NZ,"grs1",P),_meta:{[BZ]:this.serverInfo}}}}let X=Z.era;if(!X.session.e||!Z.stream)return z(`"${$.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${hZ(12).toString("base64url")}`,K=X.sessionId,U=await new Promise((H)=>{let Q=setTimeout(()=>{this.pending.delete(Y),H(null)},this.approvalTimeoutMs),V=(I)=>{clearTimeout(Q),H(I)};this.pending.set(Y,{session:K,resolve:V}),Z.signal.addEventListener("abort",()=>{this.pending.delete(Y),V(null)}),Z.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...W}:W})});return U&&!U.error&&lZ(U.result)?{kind:"approved"}:z(`The user did not approve "${$.name}", and it did not run.`)}async spendNonce(Z,$){try{return await this.nonces.consume(Z,$)}catch(G){return console.error("[gemi/mcp] Spending an approval failed:",G),!1}}async respond(Z,$,G,W,z){if(!G)try{let U=await $(null,W);return S({jsonrpc:"2.0",id:Z.id,result:U},200)}finally{z?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,W]),K=new eZ(()=>X.abort());return(async()=>{try{let U=await $(K,Y);K.send({jsonrpc:"2.0",id:Z.id,result:U})}catch(U){if(U instanceof J)K.send(T(Z.id,U));else console.error("[gemi/mcp] The MCP endpoint failed:",U),K.send(T(Z.id,new J(N.InternalError,"Internal error.")))}finally{z?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized(Z){let $=this.resolvers.map((W)=>W.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',G=Z?`${$}, error="invalid_token", error_description="${Z.replace(/["\\]/g,"")}"`:$;return S(T(null,new J(N.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":G})}async failedAttempt(Z){let $=sZ(new PZ(Z,{},"api",this.endpoint.pathname)),G=await KZ(`mcp-auth-failed:${$}`,e3);return G===null?null:nZ(G)}async spend(Z){if(!this.rateLimit)return null;let $=await KZ(`mcp-endpoint:${Z.via}:${Z.id}`,this.rateLimit);return $===null?null:nZ($)}}class eZ{readable;controller;closed=!1;encoder=new TextEncoder;constructor(Z){this.readable=new ReadableStream({start:($)=>{this.controller=$},cancel:()=>{this.closed=!0,Z()}})}send(Z){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
3
3
  data: ${JSON.stringify(Z)}
4
4
 
5
5
  `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class o extends Error{}async function Z8(Z,$){let G=Number(Z.headers.get("content-length"));if(Number.isFinite(G)&&G>$)throw new o;if(!Z.body)return"";let W=Z.body.getReader(),z=[],X=0;for(;;){let{done:Y,value:K}=await W.read();if(Y)break;if(X+=K.byteLength,X>$)throw await W.cancel(),new o;z.push(K)}return Buffer.concat(z).toString("utf8")}function S(Z,$,G={}){return new Response(JSON.stringify(Z),{status:$,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...G}})}function cZ(Z,$){for(let[G,W]of Object.entries($))Z.headers.set(G,W);return Z}function $8(Z){return{"Access-Control-Allow-Origin":Z,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function G8(Z){let $;try{$=new URL(Z)}catch{throw Error(`route.mcp.remote.url: "${Z}" is not a URL.`)}let G=$.hostname==="localhost"||$.hostname==="127.0.0.1"||$.hostname==="[::1]";if($.protocol!=="https:"&&!($.protocol==="http:"&&G))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if($.search||$.hash||$.username||$.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if($.pathname==="/"||$.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return $}function s(Z){return rZ("sha256").update(`${Z.via}\x00${Z.id}\x00${Z.user?.id}`).digest("base64url").slice(0,32)}function W8(Z){return rZ("sha256").update(aZ(Z??{})).digest("base64url")}function pZ(Z){if(!O(Z))return!1;if(Object.keys(Z).length===0)return!0;return"form"in Z}function iZ(Z){let $=O(Z._meta)?Z._meta:{};return typeof $.progressToken==="string"||typeof $.progressToken==="number"}function z8(Z,$,G){if($.method!=="tools/call"||!G.e)return!1;let W=$.params?.name;return typeof W==="string"&&Z.descriptors({names:[W]})[0]?.requiresApproval===!0}function X8(Z){let G=(O(Z.params._meta)?Z.params._meta:{}).progressToken;if(!Z.stream||typeof G!=="string"&&typeof G!=="number")return;let W=-1/0;return(z)=>{if(typeof z?.progress!=="number"||!Number.isFinite(z.progress)||z.progress<=W)return;W=z.progress,Z.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:G,progress:z.progress,...typeof z.total==="number"?{total:z.total}:{},...typeof z.message==="string"?{message:z.message.slice(0,1000)}:{}}})}}function Y8(Z,$){let G=JSON.stringify($??{},null,1),W=G.length>xZ?`${G.slice(0,xZ)}\u2026 (${G.length-xZ} more characters not shown)`:G;return{message:`Allow "${Z.title??Z.name}" to run? ${Z.description}
@@ -3059,14 +3059,19 @@ var ComponentsProvider = (props) => {
3059
3059
  //#endregion
3060
3060
  //#region client/ClientRouterContext.tsx
3061
3061
  var ClientRouterContext = createContext({});
3062
+ /** One instance, so effects keyed on the locale list do not re-run each render. */
3063
+ var NO_LOCALES = [];
3062
3064
  var ClientRouterProvider = (props) => {
3063
3065
  const { children, pathname, currentPath, is404, is500, routeManifest, cssManifest, modulePreloadManifest, assetBase = "/", pageData, params, searchParams, breadcrumbs, urlLocaleSegment } = props;
3064
3066
  const navigationAbortControllerRef = useRef(new AbortController());
3065
3067
  const [isNavigatingSubject] = useState(() => {
3066
3068
  return new Subject(false);
3067
3069
  });
3068
- const { supportedLocales = [], locale } = useContext(I18nContext);
3069
- const { staticRoutes } = useContext(ServerDataContext);
3070
+ const i18nContext = useContext(I18nContext);
3071
+ const { staticRoutes, i18n } = useContext(ServerDataContext);
3072
+ const localeRouted = i18n?.localeRouting !== "off";
3073
+ const supportedLocales = localeRouted ? i18nContext.supportedLocales ?? NO_LOCALES : NO_LOCALES;
3074
+ const locale = localeRouted ? i18nContext.locale : null;
3070
3075
  const staticRoutesRef = useRef(new Set(staticRoutes ?? []));
3071
3076
  const [progressManager] = useState(new ProgressManager(isNavigatingSubject));
3072
3077
  const [prefetchCache] = useState(() => new PrefetchCache());
@@ -3405,4 +3410,4 @@ function useTheme() {
3405
3410
  //#endregion
3406
3411
  export { useLocation as A, QueryManagerProvider as B, useRoute as C, I18nProvider as D, I18nContext as E, createMemoryHistory as F, retryDelayFor as G, pickDefined as H, toVariantKey as I, Subject as J, shouldRetryQuery as K, applyParams as L, isAbsoluteUrl as M, ProgressManager as N, ServerDataContext as O, Action as P, QueryConfigContext as R, routeDataUrl as S, useNavigate as T, DEFAULT_STALE_TIME as U, USER_QUERY_CONFIG_KEYS as V, isRetryableQueryError as W, loadDictionary as _, useRouteTransition as a, setActiveLocale as b, ComponentsContext as c, loadViewModule as d, subscribeViewModules as f, recoverFromChunkLoadError as g, isChunkLoadError as h, RouteTransitionProvider as i, domainUrl as j, ServerDataProvider as k, ComponentsProvider as l, configureChunkLoadRecovery as m, useTheme as n, ClientRouterContext as o, CHUNK_RELOAD_MARKER as p, QueryError as q, m as r, ClientRouterProvider as s, ThemeProvider as t, initialViewModulesReady as u, loadDictionaryForRender as v, useSearchParams as w, readRoutePayload as x, registerDictionary as y, QueryManagerContext as z };
3407
3412
 
3408
- //# sourceMappingURL=ThemeProvider-BgLyzzOL.js.map
3413
+ //# sourceMappingURL=ThemeProvider-BLI4zpLu.js.map