gemi 0.235.0 → 0.236.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/client/conformance.d.ts +4 -2
- package/dist/ai/client/conformance.d.ts.map +1 -1
- package/dist/ai/client/index.js +72 -6
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +3 -3
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/call.d.ts +1 -1
- package/dist/ai/types.d.ts +5 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/useChat.d.ts +35 -0
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/{chunk-adfkz2kf.js → chunk-0e5sq42y.js} +1 -1
- package/dist/chunk-4800w7qx.js.map +2 -2
- package/dist/{chunk-cb7mgx75.js → chunk-73541m4t.js} +6 -6
- package/dist/{chunk-cb7mgx75.js.map → chunk-73541m4t.js.map} +3 -3
- package/dist/{chunk-t5gbp0yr.js → chunk-dav7mv8t.js} +2 -2
- package/dist/{chunk-t5gbp0yr.js.map → chunk-dav7mv8t.js.map} +3 -3
- package/dist/{chunk-1yws1nvb.js → chunk-hy54f691.js} +2 -2
- package/dist/{chunk-1yws1nvb.js.map → chunk-hy54f691.js.map} +1 -1
- package/dist/{chunk-2hw8sr4d.js → chunk-wbj4jh1h.js} +1 -1
- package/dist/{chunk-2hw8sr4d.js.map → chunk-wbj4jh1h.js.map} +1 -1
- package/dist/{chunk-9359fg6r.js → chunk-yknc5rgh.js} +1 -1
- package/dist/{chunk-9359fg6r.js.map → chunk-yknc5rgh.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js → RealtimeClient-DRVodyn1.js} +2 -2
- package/dist/chunks/{RealtimeClient-C5Zh3fD6.js.map → RealtimeClient-DRVodyn1.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js → ThemeProvider-1WtAS7dH.js} +4 -4
- package/dist/chunks/{ThemeProvider-bbbE-N3t.js.map → ThemeProvider-1WtAS7dH.js.map} +1 -1
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js → fetchFileRequest-CVCelZqS.js} +2 -2
- package/dist/chunks/{fetchFileRequest-JXhnEi-R.js.map → fetchFileRequest-CVCelZqS.js.map} +1 -1
- package/dist/chunks/{live-CApTRvmK.js → live-twEh9Qwt.js} +3 -3
- package/dist/chunks/{live-CApTRvmK.js.map → live-twEh9Qwt.js.map} +1 -1
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js → mutationExtras-CM77Ur-9.js} +2 -2
- package/dist/chunks/{mutationExtras-C2qSSZ2Q.js.map → mutationExtras-CM77Ur-9.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js → subscriptionStream-DQp1Krwi.js} +2 -2
- package/dist/chunks/{subscriptionStream-DQLW7dTW.js.map → subscriptionStream-DQp1Krwi.js.map} +1 -1
- package/dist/client/chunkLoadRecovery.d.ts +1 -1
- package/dist/client/index.js +4 -4
- package/dist/client/index.js.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/mcp/http/callers.d.ts +1 -1
- package/dist/testing/index.js +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-adfkz2kf.js.map → chunk-0e5sq42y.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qa as m}from"./chunk-ba1h9pm6.js";import{createElement as j}from"react";function z(i,t){let u=Object.keys(t).sort((s,p)=>p.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(u.join("|"),"g");return i.replace(r,(s)=>t[s])}async function O(i,t,u=[],r){let s=[...u.map((n)=>`${i}/views/${n}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],p=new Set;for(let n of s){let e=t.moduleGraph.getModulesByFile(n);if(e)for(let d of e)p.add(d)}let b=[],l=[],g={};for(let n of p)if(n)for(let e of n.importedModules){if(e.file.includes("module.css"))g[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))l.push(e.file)}for(let n of l){let e=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),a="";if(d)a=z(g[n],e.default);b.push({isDev:!0,id:n,content:d?a:e.code})}return b.map((n,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Q(i=[]){return i.map((t,u)=>{return j("style",{key:u,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as f}from"fs";import{basename as q}from"path";import{networkInterfaces as k}from"os";var v={name:"gemi",version:"0.
|
|
2
|
+
import{Qa as m}from"./chunk-ba1h9pm6.js";import{createElement as j}from"react";function z(i,t){let u=Object.keys(t).sort((s,p)=>p.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(u.join("|"),"g");return i.replace(r,(s)=>t[s])}async function O(i,t,u=[],r){let s=[...u.map((n)=>`${i}/views/${n}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],p=new Set;for(let n of s){let e=t.moduleGraph.getModulesByFile(n);if(e)for(let d of e)p.add(d)}let b=[],l=[],g={};for(let n of p)if(n)for(let e of n.importedModules){if(e.file.includes("module.css"))g[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))l.push(e.file)}for(let n of l){let e=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),a="";if(d)a=z(g[n],e.default);b.push({isDev:!0,id:n,content:d?a:e.code})}return b.map((n,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Q(i=[]){return i.map((t,u)=>{return j("style",{key:u,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as f}from"fs";import{basename as q}from"path";import{networkInterfaces as k}from"os";var v={name:"gemi",version:"0.236.1",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./ai/voice":"./ai/voice/index.ts","./ai/testing":"./ai/testing/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./probe":"./probe/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=@azure/communication-email --external=@azure/identity --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/ai/voice dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"GEMI_AI_LIVE=1 bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0","happy-dom":"^21.0.4",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/communication-email":"^1.1.0","@azure/identity":"^4.0.0","@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/communication-email":{optional:!0},"@azure/identity":{optional:!0},"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var E=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],$=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,t)=>$?`\x1B[${i}m${t}\x1B[0m`:t,h=(i)=>c("1",i),x=(i)=>c("2",i),o=(i)=>c("36",i),G=(i)=>c("32",i),_=(i)=>c("35",i);function A(){return v.version??"?"}function J(i){for(let t of Object.values(k()))for(let u of t??[])if((u.family==="IPv4"||u.family===4)&&!u.internal)return`http://${u.address}:${i}`;return null}function L(i){return m(i).filter((t)=>f(t)).map((t)=>q(t))}function V(i){let{port:t,rootDir:u}=i,r=`http://localhost:${t}`,s=J(t),p=L(u),b=(g,n)=>` ${G("\u279C")} ${h(g.padEnd(9))}${n}`,l=["",...E.map((g)=>_(g)),"",` ${x("gemi")} ${o(`v${A()}`)}`,"",b("Local:",o(r)),b("Network:",s?o(s):x("unavailable")),b("Env:",p.length?p.join(", "):x("none")),""];console.log(l.join(`
|
|
3
3
|
`))}function I(i,t){return Error(`app/views/${i}.tsx is missing. gemi's auth routes render it because ${t} is on. Add the view, or turn that setting off in app/config/auth.ts.`)}function T(i=process.env.SERVER_IDLE_TIMEOUT){if(i===void 0||i.trim()==="")return 10;let t=Number(i.trim());if(!Number.isInteger(t)||t<0||t>255)throw Error(`SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 (0 disables the timeout), got ${JSON.stringify(i)}.`);return t}
|
|
4
4
|
export{O as Z,Q as _,V as $,I as aa,T as ba};
|
|
5
5
|
|
|
6
|
-
//# debugId=
|
|
6
|
+
//# debugId=F3A979B6AEA6DBFC64756E2164756E21
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
"/**\n * Bun's default, and what both servers use when `SERVER_IDLE_TIMEOUT` is unset.\n */\nexport const DEFAULT_SERVER_IDLE_TIMEOUT = 10;\n\n/**\n * The `idleTimeout` (seconds) both `gemi dev` and `gemi start` pass to\n * `Bun.serve`, from `SERVER_IDLE_TIMEOUT` (#787).\n *\n * One reader for both servers, so a long-poll that works under `gemi start`\n * also works under `gemi dev`. Before this, only `httpProd` read the variable\n * and the dev server always ran at Bun's 10 seconds.\n *\n * It is the time a connection may stay silent, a response that has not started\n * included, before Bun closes it; `0` disables it. It does not apply to an\n * upgraded websocket (the HMR relay included), which has its own\n * `websocket.idleTimeout`.\n *\n * Unset or blank means the default. Anything that is not a whole number from 0\n * to 255 (Bun's own limits) fails the boot with the variable's name, instead\n * of Bun's \"expects idleTimeout to be an integer\", which does not say where the\n * value came from.\n */\nexport function serverIdleTimeout(raw: string | undefined = process.env.SERVER_IDLE_TIMEOUT): number {\n if (raw === undefined || raw.trim() === \"\") return DEFAULT_SERVER_IDLE_TIMEOUT;\n\n const seconds = Number(raw.trim());\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > 255) {\n throw new Error(\n `SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 ` +\n `(0 disables the timeout), got ${JSON.stringify(raw)}.`,\n );\n }\n return seconds;\n}\n"
|
|
9
9
|
],
|
|
10
10
|
"mappings": ";yCAAA,wBAAS,cAGT,SAAS,CAAc,CAAC,EAAc,EAAwC,CAC5E,IAAM,EAAc,OAAO,KAAK,CAAM,EACnC,KAAK,CAAC,EAAG,IAAM,EAAE,OAAS,EAAE,MAAM,EAClC,IAAI,CAAC,IAAQ,EAAI,QAAQ,sBAAuB,MAAM,CAAC,EAGpD,EAAQ,IAAI,OAAO,EAAY,KAAK,GAAG,EAAG,GAAG,EAEnD,OAAO,EAAK,QAAQ,EAAO,CAAC,IAAU,EAAO,EAAM,EAGrD,eAAsB,CAAe,CACnC,EACA,EACA,EAAyB,CAAC,EAE1B,EACA,CACA,IAAM,EAAQ,CACZ,GAAG,EAAa,IAAI,CAAC,IAAS,GAAG,WAAgB,OAAU,EAC3D,EAAS,GAAG,WAAgB,QAAe,GAAG,wBAChD,EAEM,EAAU,IAAI,IACpB,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAK,YAAY,iBAAiB,CAAI,EAClD,GAAI,EACF,QAAW,KAAK,EAAK,EAAQ,IAAI,CAAC,EAItC,IAAM,EAAS,CAAC,EACV,EAAa,CAAC,EACd,EAA2C,CAAC,EAClD,QAAW,KAAO,EAChB,GAAI,EACF,QAAW,KAAY,EAAI,gBAAiB,CAC1C,GAAI,EAAS,KAAK,SAAS,YAAY,EACrC,EAAiB,EAAS,MAAQ,EAAS,mBAAmB,IAAI,eAAe,KAAK,EAAE,EAE1F,GAAI,EAAS,KAAK,SAAS,MAAM,EAC/B,EAAW,KAAK,EAAS,IAAI,EAMrC,QAAW,KAAiB,EAAY,CACtC,IAAM,EAAY,MAAM,EAAK,iBAAiB,EAAgB,SAAS,EAEjE,EAAc,EAAc,SAAS,YAAY,EAEnD,EAAuB,GAE3B,GAAI,EACF,EAAuB,EACrB,EAAiB,GAGhB,EAA6D,OAChE,EAGF,EAAO,KAAK,CACV,MAAO,GACP,GAAI,EACJ,QAAS,EAAc,EAAuB,EAAU,IAC1D,CAAC,EAGH,OAAO,EAAO,IAAI,CAAC,EAAO,IAAM,CAC9B,OAAO,EAAc,QAAS,CAC5B,IAAK,EACL,KAAM,WACN,mBAAoB,EAAM,GAC1B,wBAAyB,CAAE,OAAQ,EAAM,OAAQ,CACnD,CAAC,EACF,EAGH,eAAsB,CAAY,CAAC,EAAS,CAAC,EAAG,CAC9C,OAAO,EAAO,IAAI,CAAC,EAAO,IAAM,CAC9B,OAAO,EAAc,QAAS,CAC5B,IAAK,EACL,GAAI,GAAO,GACX,KAAM,WACN,wBAAyB,CAAE,OAAQ,EAAM,OAAQ,CACnD,CAAC,EACF,EC3FH,qBAAS,WACT,mBAAS,aACT,4BAAS,uoIAKT,IAAM,EAAM,CACV,oKACA,mLACA,yKACA,oKACA,mLACA,yJACF,EAEM,EAAW,QAAQ,QAAQ,OAAO,KAAK,GAAK,CAAC,QAAQ,IAAI,SACzD,EAAQ,CAAC,EAAc,IAC3B,EAAW,QAAQ,KAAQ,WAAgB,EACvC,EAAO,CAAC,IAAc,EAAM,IAAK,CAAC,EAClC,EAAM,CAAC,IAAc,EAAM,IAAK,CAAC,EACjC,EAAO,CAAC,IAAc,EAAM,KAAM,CAAC,EACnC,EAAQ,CAAC,IAAc,EAAM,KAAM,CAAC,EACpC,EAAU,CAAC,IAAc,EAAM,KAAM,CAAC,EAE5C,SAAS,CAAW,EAAW,CAC7B,OAAQ,EAA6B,SAAW,IAGlD,SAAS,CAAU,CAAC,EAAsC,CACxD,QAAW,KAAU,OAAO,OAAO,EAAkB,CAAC,EACpD,QAAW,KAAS,GAAU,CAAC,EAG7B,IADa,EAAM,SAAW,QAAW,EAAM,SAAuB,IAC1D,CAAC,EAAM,SAAU,MAAO,UAAU,EAAM,WAAW,IAGnE,OAAO,KAGT,SAAS,CAAc,CAAC,EAA2B,CACjD,OAAO,EAAS,CAAO,EACpB,OAAO,CAAC,IAAS,EAAW,CAAI,CAAC,EACjC,IAAI,CAAC,IAAS,EAAS,CAAI,CAAC,EAG1B,SAAS,CAAkB,CAAC,EAGhC,CACD,IAAQ,OAAM,WAAY,EACpB,EAAQ,oBAAoB,IAC5B,EAAU,EAAW,CAAI,EACzB,EAAM,EAAe,CAAO,EAE5B,EAAM,CAAC,EAAe,IAC1B,KAAK,EAAM,QAAE,MAAM,EAAK,EAAM,OAAO,CAAC,CAAC,IAAI,IAEvC,EAAM,CACV,GACA,GAAG,EAAI,IAAI,CAAC,IAAS,EAAQ,CAAI,CAAC,EAClC,GACA,KAAK,EAAI,MAAM,KAAK,EAAK,IAAI,EAAY,GAAG,IAC5C,GACA,EAAI,SAAU,EAAK,CAAK,CAAC,EACzB,EAAI,WAAY,EAAU,EAAK,CAAO,EAAI,EAAI,aAAa,CAAC,EAC5D,EAAI,OAAQ,EAAI,OAAS,EAAI,KAAK,IAAI,EAAI,EAAI,MAAM,CAAC,EACrD,EACF,EAEA,QAAQ,IAAI,EAAI,KAAK;AAAA,CAAI,CAAC,ECjErB,SAAS,CAAwB,CAAC,EAAc,EAAoB,CACzE,OAAW,MACT,aAAa,0DAA6D,wEAE5E,ECcK,SAAS,CAAiB,CAAC,EAA0B,QAAQ,IAAI,oBAA6B,CACnG,GAAI,IAAQ,QAAa,EAAI,KAAK,IAAM,GAAI,MArBH,IAuBzC,IAAM,EAAU,OAAO,EAAI,KAAK,CAAC,EACjC,GAAI,CAAC,OAAO,UAAU,CAAO,GAAK,EAAU,GAAK,EAAU,IACzD,MAAU,MACR,qGACmC,KAAK,UAAU,CAAG,IACvD,EAEF,OAAO",
|
|
11
|
-
"debugId": "
|
|
11
|
+
"debugId": "F3A979B6AEA6DBFC64756E2164756E21",
|
|
12
12
|
"names": []
|
|
13
13
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-1yws1nvb.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ze as GJ,hh as IJ,ih as g,qh as AJ,rh as BJ,sh as RJ}from"./chunk-cb7mgx75.js";import"./chunk-zm6b938z.js";import"./chunk-2kzysesp.js";import{Bi as WJ,xi as jJ,yi as YJ}from"./chunk-fqndtpwm.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t6x1r5n6.js";import"./chunk-naj8bmj5.js";import"./chunk-np6vee9d.js";import"./chunk-5exrgw07.js";import"./chunk-jssjfvsz.js";import"./chunk-a119av2z.js";import"./chunk-m3fbewhz.js";import"./chunk-x2dmgge8.js";import"./chunk-fs94x6ef.js";import"./chunk-8476xvk9.js";import"./chunk-kvtvx64t.js";import"./chunk-9jt5qj1b.js";import"./chunk-17ewxwga.js";import"./chunk-sv2mv2q2.js";import{vm as KJ}from"./chunk-gt9ftnhn.js";import"./chunk-qvn0w2rt.js";import{Nm as PJ}from"./chunk-ka8dzc6q.js";import{Pm as f}from"./chunk-3y1h3ncf.js";import"./chunk-ts75gcfd.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
|
|
2
|
+
import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-hy54f691.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ze as GJ,hh as IJ,ih as g,qh as AJ,rh as BJ,sh as RJ}from"./chunk-73541m4t.js";import"./chunk-zm6b938z.js";import"./chunk-2kzysesp.js";import{Bi as WJ,xi as jJ,yi as YJ}from"./chunk-fqndtpwm.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t6x1r5n6.js";import"./chunk-naj8bmj5.js";import"./chunk-np6vee9d.js";import"./chunk-5exrgw07.js";import"./chunk-jssjfvsz.js";import"./chunk-a119av2z.js";import"./chunk-m3fbewhz.js";import"./chunk-x2dmgge8.js";import"./chunk-fs94x6ef.js";import"./chunk-8476xvk9.js";import"./chunk-kvtvx64t.js";import"./chunk-9jt5qj1b.js";import"./chunk-17ewxwga.js";import"./chunk-sv2mv2q2.js";import{vm as KJ}from"./chunk-gt9ftnhn.js";import"./chunk-qvn0w2rt.js";import{Nm as PJ}from"./chunk-ka8dzc6q.js";import{Pm as f}from"./chunk-3y1h3ncf.js";import"./chunk-ts75gcfd.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8" />
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"import { mkdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { availableParallelism } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { brotliCompress, constants, gzip } from \"node:zlib\";\n\nimport type { ContentEncoding } from \"../server/compression\";\n\n/**\n * Build-time compression of the client bundle (#789).\n *\n * `gemi start` compresses SSR HTML per request, but a hashed chunk is the same\n * bytes for the life of a release, so compressing it per request would spend\n * origin CPU on every visitor for a result that never changes. `gemi build`\n * writes `file.br` (brotli quality 11) and `file.gz` (gzip level 9) next to\n * every compressible build asset instead, once, and the server picks one by\n * `Accept-Encoding`.\n *\n * What the build emitted (and what it carried over from earlier releases, see\n * `previousAssets.ts`) is recorded in `dist/client/.vite/static-assets.json`,\n * with the encodings each file has. The server reads it at boot: a file in the\n * record is a content-hashed build asset, so it is sent as `immutable`, and\n * only the encodings listed for it are offered. A file not in the record (one\n * copied from `public/assets/`, or anything in a build made before this\n * existed) is served as before.\n */\n\n/** Relative to `dist/client`; beside Vite's own manifest, so never served. */\nexport const STATIC_ASSETS_RECORD = \".vite/static-assets.json\";\n\n/**\n * Below this, the encoded body plus its header is not worth a second request\n * representation: a 600-byte chunk saves a few hundred bytes at most, and\n * every file with siblings adds a `stat` per request.\n */\nexport const PRECOMPRESS_MIN_BYTES = 1024;\n\n/**\n * Text-like formats that compress well. Already-compressed formats (images,\n * `woff`/`woff2`, video) are left out: brotli shaves a percent or two off\n * them at best. Source maps are left out because a page never loads one, and\n * only devtools would gain from the extra build time.\n */\nconst COMPRESSIBLE = /\\.(?:m?js|cjs|css|svg|json|webmanifest|wasm|txt|xml|ttf|otf|eot)$/i;\n\nconst TEXT = /\\.(?:m?js|cjs|css|svg|json|webmanifest|txt|xml)$/i;\nconst FONT = /\\.(?:ttf|otf|eot)$/i;\n\nexport const SIBLING_EXTENSION: Record<ContentEncoding, string> = {\n br: \".br\",\n gzip: \".gz\",\n};\n\n/** Server preference: brotli is ~15% smaller than gzip -9 on a JS chunk. */\nconst ENCODINGS: ContentEncoding[] = [\"br\", \"gzip\"];\n\nexport interface StaticAssetsRecord {\n /**\n * Path relative to `dist/client` (`assets/client-DJhrQPW5.js`) → the\n * precompressed siblings it has, in preference order. An empty list is a\n * build asset that is served as identity only (an image, a small file).\n */\n files: Record<string, ContentEncoding[]>;\n}\n\nexport interface PrecompressStats {\n files: number;\n identityBytes: number;\n brBytes: number;\n gzipBytes: number;\n}\n\nconst brotli = promisify(brotliCompress);\nconst gzipAsync = promisify(gzip);\n\nexport function isPrecompressible(file: string): boolean {\n return COMPRESSIBLE.test(file);\n}\n\n/** `true` for `x.js.br` / `x.js.gz`: a sibling, not an asset of its own. */\nexport function isEncodedSibling(file: string): boolean {\n return file.endsWith(\".br\") || file.endsWith(\".gz\");\n}\n\nasync function encode(encoding: ContentEncoding, file: string, input: Buffer): Promise<Buffer> {\n if (encoding === \"gzip\") {\n return gzipAsync(input, { level: 9 });\n }\n return brotli(input, {\n params: {\n [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,\n [constants.BROTLI_PARAM_MODE]: TEXT.test(file)\n ? constants.BROTLI_MODE_TEXT\n : FONT.test(file)\n ? constants.BROTLI_MODE_FONT\n : constants.BROTLI_MODE_GENERIC,\n [constants.BROTLI_PARAM_SIZE_HINT]: input.length,\n },\n });\n}\n\nasync function fileSize(path: string): Promise<number | null> {\n try {\n const info = await stat(path);\n return info.isFile() ? info.size : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Writes the `.br`/`.gz` siblings of `files` (paths relative to `clientDir`)\n * and returns the encodings each one ended up with.\n *\n * A sibling is only kept when it is smaller than the file itself; one that is\n * not would cost bytes on the wire, so the file is served as identity for\n * that encoding. With `reuseExisting`, a sibling already on disk is trusted\n * rather than rebuilt — for files carried from an earlier release, whose\n * siblings were copied with them and match by content hash.\n */\nexport async function precompressAssets(\n clientDir: string,\n files: Iterable<string>,\n options: {\n reuseExisting?: boolean;\n minBytes?: number;\n concurrency?: number;\n } = {},\n): Promise<{ record: StaticAssetsRecord; stats: PrecompressStats }> {\n const minBytes = options.minBytes ?? PRECOMPRESS_MIN_BYTES;\n const record: StaticAssetsRecord = { files: {} };\n const stats: PrecompressStats = {\n files: 0,\n identityBytes: 0,\n brBytes: 0,\n gzipBytes: 0,\n };\n\n const queue = [...new Set(files)];\n for (const file of queue) {\n record.files[file] = [];\n }\n\n async function work(file: string) {\n if (!isPrecompressible(file)) {\n return;\n }\n const path = join(clientDir, file);\n const size = await fileSize(path);\n if (size === null || size < minBytes) {\n return;\n }\n\n let input: Buffer | null = null;\n const available: ContentEncoding[] = [];\n const sizes: Partial<Record<ContentEncoding, number>> = {};\n for (const encoding of ENCODINGS) {\n const siblingPath = path + SIBLING_EXTENSION[encoding];\n const existing = options.reuseExisting ? await fileSize(siblingPath) : null;\n if (existing !== null) {\n if (existing < size) {\n available.push(encoding);\n sizes[encoding] = existing;\n }\n continue;\n }\n input ??= await readFile(path);\n const output = await encode(encoding, file, input);\n if (output.length < size) {\n await writeFile(siblingPath, output);\n available.push(encoding);\n sizes[encoding] = output.length;\n }\n }\n\n record.files[file] = available;\n if (available.length > 0) {\n stats.files += 1;\n stats.identityBytes += size;\n stats.brBytes += sizes.br ?? size;\n stats.gzipBytes += sizes.gzip ?? size;\n }\n }\n\n // zlib's async calls run on the libuv thread pool; a few files in flight\n // keep it busy without reading the whole bundle into memory at once.\n const concurrency = Math.max(1, options.concurrency ?? Math.min(8, availableParallelism()));\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, queue.length) }, async () => {\n while (next < queue.length) {\n await work(queue[next++]);\n }\n }),\n );\n\n return { record, stats };\n}\n\nexport async function writeStaticAssetsRecord(clientDir: string, record: StaticAssetsRecord) {\n const path = join(clientDir, STATIC_ASSETS_RECORD);\n await mkdir(dirname(path), { recursive: true });\n // Sorted, so two builds of the same tree write the same file.\n const files = Object.fromEntries(\n Object.entries(record.files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n );\n await writeFile(path, `${JSON.stringify({ files }, null, 2)}\\n`);\n}\n\n/**\n * The record a build wrote, or `null` when there is none (a build made before\n * precompression, or an incomplete `dist/`): the server then serves every file\n * as before. A malformed entry is dropped rather than trusted.\n */\nexport async function readStaticAssetsRecord(\n clientDir: string,\n): Promise<StaticAssetsRecord | null> {\n let raw: string;\n try {\n raw = await readFile(join(clientDir, STATIC_ASSETS_RECORD), \"utf8\");\n } catch {\n return null;\n }\n let files: unknown;\n try {\n files = JSON.parse(raw)?.files;\n } catch {\n return null;\n }\n if (!files || typeof files !== \"object\") {\n return null;\n }\n const record: StaticAssetsRecord = { files: {} };\n for (const [file, encodings] of Object.entries(files)) {\n if (!Array.isArray(encodings)) continue;\n record.files[file] = ENCODINGS.filter((encoding) => encodings.includes(encoding));\n }\n return record;\n}\n",
|
|
9
9
|
"export function generateETag(lastModified: number): string {\n // Assuming the last modified timestamp is in milliseconds\n const lastModifiedStr = lastModified.toString();\n\n const hasher = new Bun.CryptoHasher(\"sha1\");\n hasher.update(lastModifiedStr);\n const hash = hasher.digest(\"hex\");\n\n return hash;\n}\n",
|
|
10
10
|
"import { DEFAULT_ASSET_BASE, assetUrl } from \"../config/assetBase\";\nimport { ISLAND_ENTRY_QUERY } from \"../internal/islandRuntime\";\n\n/** The subset of a Vite manifest entry this module reads. */\nexport interface ViteManifestChunk {\n file: string;\n imports?: string[];\n dynamicImports?: string[];\n}\n\nexport type ViteManifest = Record<string, ViteManifestChunk>;\n\n/** Vite's manifest key for the module that boots hydration. */\nexport const CLIENT_ENTRY_KEY = \"app/client.tsx\";\n\n/**\n * How the shell boots hydration in production: `module` is imported from the\n * bootstrap script, `preload` is every chunk that import pulls in — see\n * `clientEntry` in `ViewRouteDispatcher` for why the entry does not go through\n * React's `bootstrapModules`.\n *\n * `undefined` when the manifest has no client entry, which means a `dist/`\n * interrupted between the server and client build passes. Degrading beats\n * throwing here: this runs at boot, so a deref would take down API routes,\n * static assets and health checks over what is only a document concern, and\n * the dispatcher already renders a shell that simply does not hydrate.\n *\n * `assetBase` is the base the client build recorded — see `readBuiltAssetBase`.\n */\nexport function createClientEntry(\n manifest: ViteManifest,\n assetBase: string = DEFAULT_ASSET_BASE,\n): { module: string; preload: string[] } | undefined {\n const file = manifest[CLIENT_ENTRY_KEY]?.file;\n if (!file) {\n return undefined;\n }\n return {\n module: assetUrl(file, assetBase),\n preload: collectModulePreloads(manifest, CLIENT_ENTRY_KEY, assetBase),\n };\n}\n\n/**\n * Every chunk URL that importing `entryKey` pulls in, itself first.\n *\n * The browser can only discover these one parse at a time — it learns about a\n * chunk's static imports after the chunk has arrived and been parsed — so a\n * `layout -> view -> child component` graph costs one round trip per level.\n * Handing the whole list to the shell as `modulepreload` hints turns that\n * chain into one parallel fetch (#352).\n *\n * `dynamicImports` are deliberately left out: those are the pieces the app\n * asked to load lazily, and preloading them would download code the current\n * route may never render.\n */\nexport function collectModulePreloads(\n manifest: ViteManifest,\n entryKey: string,\n assetBase: string = DEFAULT_ASSET_BASE,\n): string[] {\n const urls: string[] = [];\n // Chunk graphs are cyclic often enough (two chunks importing each other\n // through a shared module) that walking them without a visited set hangs.\n const visited = new Set<string>();\n\n const walk = (key: string) => {\n if (visited.has(key)) return;\n visited.add(key);\n const chunk = manifest[key];\n if (!chunk?.file) return;\n urls.push(assetUrl(chunk.file, assetBase));\n for (const imported of chunk.imports ?? []) {\n walk(imported);\n }\n };\n\n walk(entryKey);\n\n return urls;\n}\n\n/**\n * The chunks the static import closure of `entryKey` loads lazily, each with\n * its own static closure, minus what that closure already has: every\n * `import()` in the entry's code (and its static dependencies'), one level\n * deep. An island with `preloadDynamic` gets these preloaded too (#932).\n *\n * Dynamic imports into `node_modules` are left out: those are a library's own\n * lazy pieces (gemi's client loads a few on first use), not the app's.\n */\nexport function collectDynamicPreloads(\n manifest: ViteManifest,\n entryKey: string,\n assetBase: string = DEFAULT_ASSET_BASE,\n): string[] {\n const seen = new Set(collectModulePreloads(manifest, entryKey, assetBase));\n const targets: string[] = [];\n const visited = new Set<string>();\n\n const walk = (key: string) => {\n if (visited.has(key)) return;\n visited.add(key);\n const chunk = manifest[key];\n if (!chunk) return;\n for (const target of chunk.dynamicImports ?? []) {\n if (!/(^|\\/)node_modules\\//.test(target) && !targets.includes(target)) {\n targets.push(target);\n }\n }\n for (const imported of chunk.imports ?? []) {\n walk(imported);\n }\n };\n walk(entryKey);\n\n const urls: string[] = [];\n for (const target of targets) {\n for (const url of collectModulePreloads(manifest, target, assetBase)) {\n if (!seen.has(url)) {\n seen.add(url);\n urls.push(url);\n }\n }\n }\n return urls;\n}\n\n/**\n * Every CSS file the static import closure of `entryKey` carries, in import\n * order and without repeats. Vite lists a chunk's CSS on that chunk only, not\n * on the entries that import it, so a page with no client router to load the\n * rest (a static view) has to walk the graph for it.\n */\nexport function collectCss(manifest: ViteManifest, entryKey: string): string[] {\n const files: string[] = [];\n const seen = new Set<string>();\n const visited = new Set<string>();\n\n const walk = (key: string) => {\n if (visited.has(key)) return;\n visited.add(key);\n const chunk = manifest[key] as ViteManifestChunk & { css?: string[] };\n if (!chunk) return;\n for (const imported of chunk.imports ?? []) {\n walk(imported);\n }\n for (const file of chunk.css ?? []) {\n if (!seen.has(file)) {\n seen.add(file);\n files.push(file);\n }\n }\n };\n\n walk(entryKey);\n return files;\n}\n\n/**\n * Where a static page's islands load from: each island module's entry\n * (`<key>?gemi-island`, the module plus the hydrate function), with the\n * chunks importing it pulls in, itself first. React and `react-dom/client`\n * are among those. `dynamicPreload` is what the entry loads lazily (see\n * `collectDynamicPreloads`), for an island with `preloadDynamic`.\n * `undefined` for a module the client build has no island entry for.\n */\nexport function createIslandResolver(\n manifest: ViteManifest,\n assetBase: string = DEFAULT_ASSET_BASE,\n): (moduleKey: string) => { src: string; preload: string[]; dynamicPreload: string[] } | undefined {\n const cache = new Map<\n string,\n { src: string; preload: string[]; dynamicPreload: string[] } | undefined\n >();\n return (moduleKey) => {\n if (!cache.has(moduleKey)) {\n const key = `${moduleKey}${ISLAND_ENTRY_QUERY}`;\n const file = manifest[key]?.file;\n cache.set(\n moduleKey,\n file\n ? {\n src: assetUrl(file, assetBase),\n preload: collectModulePreloads(manifest, key, assetBase),\n dynamicPreload: collectDynamicPreloads(manifest, key, assetBase),\n }\n : undefined,\n );\n }\n return cache.get(moduleKey);\n };\n}\n",
|
|
11
|
-
"/**\n * Recovery from a chunk that will not load — almost always a document from an\n * earlier release asking for a chunk the server it reached no longer has\n * (#548). The page cannot continue with the module it wanted, and a full load\n * of the URL it was heading to gets it the current release's document.\n *\n * One reload per page, guarded: a reload that lands on the same failure (a\n * chunk that is genuinely missing, a proxy that keeps refusing it) must not\n * become a loop. A `sessionStorage` marker records when each URL was reloaded\n * onto and survives the reload it guards, so a second failure for the same URL\n * inside the cooldown is left to the route's error boundary. Per URL rather\n * than per tab (#1056): while two releases serve at once every navigation can\n * miss, and a tab-wide cooldown sent the second one to the error boundary.\n * Where `sessionStorage` cannot be used, the marker lives in `window.name`\n * instead (#1186); see `chunkReloadGuard`.\n *\n * The same guard covers a navigation whose data came from another build\n * (`recoverFromBuildMismatch`).\n *\n * No DOM or React import at module scope: the server's reload stub\n * (`server/staticAssetMiss.ts`) embeds the same guard as a script.\n */\n\n/** The `sessionStorage` key the guard lives under, shared with the reload stub. */\nexport const CHUNK_RELOAD_MARKER = \"gemi:chunk-reload\";\n\n/**\n * The response header carrying the client build id on a `.json` navigation\n * (#1056). The document carries its own as `buildId`; they differ when the\n * request reached a server running another release.\n */\nexport const BUILD_HEADER = \"x-gemi-build\";\n\n/** How long after a recovery reload onto a URL another one onto it is refused. */\nexport const DEFAULT_CHUNK_RELOAD_COOLDOWN_MS = 30_000;\n\n/**\n * Where the failure surfaced: a route's view chunk during a client-side\n * navigation or hydration, a `vite:preloadError` (a lazy `import()` in app\n * code, through Vite's preload helper), or an app calling\n * `recoverFromChunkLoadError` from its own error boundary.\n */\nexport type ChunkLoadErrorSource = \"navigation\" | \"hydration\" | \"preload\" | \"app\";\n\n/**\n * Why gemi will not reload, or `null` when it will:\n * - `cooldown`: it already reloaded onto this URL within `cooldownMs`.\n * - `offline`: `navigator.onLine` is false — a reload would only fail harder.\n * - `storage`: neither `sessionStorage` nor the `window.name` fallback can\n * hold the guard, so it cannot survive the reload and the loop it prevents\n * could not be ruled out.\n */\nexport type ChunkReloadBlock = \"cooldown\" | \"offline\" | \"storage\" | null;\n\nexport interface ChunkLoadErrorContext {\n error: unknown;\n /** The URL the reload goes to: the page being navigated to. */\n url: string;\n source: ChunkLoadErrorSource;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface BuildMismatchContext {\n /** The URL the full page load goes to: the page being navigated to. */\n url: string;\n /** The build the page was loaded with. */\n clientBuild: string;\n /** The build that answered the navigation. */\n serverBuild: string;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface ChunkLoadRecoveryOptions {\n /** Default 30 000 ms. */\n cooldownMs?: number;\n /**\n * Called for every chunk load failure gemi sees, before it reloads — the\n * place to report it, or to veto the reload (unsaved input, a page that\n * would rather show its own \"a new version is available\" prompt). Return\n * `false` to skip the reload; anything else lets gemi proceed. It is called\n * when the reload is blocked too, with `blocked` saying why.\n */\n onChunkLoadError?: (context: ChunkLoadErrorContext) => boolean | void;\n /**\n * Called when a client-side navigation's data came from another build (a\n * deploy in progress, two releases behind one load balancer), before gemi\n * loads the page in full. Return `false` to skip that and render the data\n * anyway. Called when the load is blocked too, with `blocked` saying why.\n */\n onBuildMismatch?: (context: BuildMismatchContext) => boolean | void;\n}\n\nlet enabled = true;\nlet options: ChunkLoadRecoveryOptions = {};\n/**\n * The full load gemi started and the page is still waiting on: further\n * failures of the same navigation (a route with several views fails once per\n * view) report it as under way instead of starting another.\n *\n * Not a latch for the life of the page: the load can be cancelled — \"Stay\" on\n * a `beforeunload` prompt (a dirty editor), a handler that stops it — and the\n * page then keeps running with no load coming. It holds only for the\n * navigation that started it (`navigationStarted` clears it) and for the\n * cooldown, so a later failure is judged on its own: another URL loads in\n * full, the same URL inside the cooldown is refused (the data renders, the\n * view's error boundary shows), and after the cooldown it loads again.\n */\nlet pendingLoad: { url: string; at: number } | null = null;\n\n/**\n * Sets how gemi recovers from a failed chunk. `false` turns recovery off: the\n * failure goes to the route's error boundary as it did before. `init` calls\n * this with its `chunkLoadRecovery` option.\n */\nexport function configureChunkLoadRecovery(next: ChunkLoadRecoveryOptions | false | undefined) {\n enabled = next !== false;\n options = next || {};\n tidyWindowName();\n}\n\n/** For tests: back to the defaults, with no reload in flight. */\nexport function __resetChunkLoadRecovery() {\n enabled = true;\n options = {};\n pendingLoad = null;\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n}\n\n/**\n * The router calls this as each client-side navigation starts. A full load\n * still pending from an earlier one was cancelled (the page would be gone\n * otherwise), so it no longer speaks for this navigation's failures.\n */\nexport function navigationStarted() {\n pendingLoad = null;\n}\n\n/** Whether a full load onto `url` is already under way. */\nfunction loadPending(url: string): boolean {\n return (\n pendingLoad !== null &&\n pendingLoad.url === url &&\n withinCooldown(Date.now() - pendingLoad.at, cooldownMs())\n );\n}\n\n/**\n * Whether `error` is a module that failed to load rather than one that loaded\n * and threw. Each engine words it differently:\n *\n * - Chromium: `Failed to fetch dynamically imported module: <url>`\n * - Firefox: `error loading dynamically imported module: <url>`\n * - Safari: `Importing a module script failed.`, and on iOS 16\n * `Importing module '<specifier>' is not found.` (folio#2117)\n * - Vite's preload helper: `Unable to preload CSS for <url>`\n *\n * A view that throws while evaluating is not one of these, and reloading\n * would only hide it.\n */\nexport function isChunkLoadError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (name === \"ChunkLoadError\") {\n return true;\n }\n if (typeof message !== \"string\") {\n return false;\n }\n return CHUNK_LOAD_MESSAGES.some((pattern) => pattern.test(message));\n}\n\nconst CHUNK_LOAD_MESSAGES = [\n /failed to fetch dynamically imported module/i,\n /error loading dynamically imported module/i,\n /importing a module script failed/i,\n /importing module .* is not found/i,\n /unable to preload css/i,\n /failed to load module script/i,\n // A chunk that loaded but whose dependency came from another build: the\n // dependency's URL answered with the server's reload stub (or another\n // release's file), which lacks the named export the chunk imports, so the\n // module graph fails to link before any of it runs — the stub's own reload\n // never gets the chance. A production build's chunks only import names their\n // own build exports, so outside a mixed deploy this does not happen.\n // - Chromium: `The requested module './index-x.js' does not provide an export named 'a'`\n // - Firefox: `The requested module './index-x.js' doesn't provide an export named: 'a'`,\n // older releases `import not found: a`\n // - Safari: `Importing binding name 'a' is not found.`\n /requested module .* (does not|doesn't) provide an export named/i,\n /^import not found: /i,\n /importing binding name .* is not found/i,\n];\n\n/**\n * The export the server's reload stub carries, true when the stub started a\n * reload. A view chunk answered by the stub then evaluates to a module with no\n * `default`, and rendering it would put the route's error boundary on screen\n * for the moment before the page goes away.\n */\nexport const RELOAD_STUB_EXPORT = \"__gemiReload\";\n\n/**\n * How long a view waits on a full load gemi started before it gives up and\n * fails after all. The load can be cancelled (\"Stay\" on a `beforeunload`\n * prompt), and the page must not sit on its loading state for good then.\n */\nexport const RELOAD_WAIT_MS = 15_000;\n\n/**\n * A promise for a view whose page is being loaded in full: it stays pending,\n * so the route keeps its `Loading` fallback (or the server's HTML) instead of\n * flashing its error boundary while the reload is under way, and rejects with\n * `error` only if the page is still here after `RELOAD_WAIT_MS`.\n */\nexport function waitForReload(error: unknown, ms: number = RELOAD_WAIT_MS): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(error), ms);\n });\n}\n\n/**\n * Reloads the page onto `url` once for a chunk that failed to load, unless the\n * guard or the app's `onChunkLoadError` says not to. Returns whether a reload\n * was started.\n *\n * Errors that are not chunk failures are ignored (`false`), so an app's error\n * boundary can pass everything it catches here.\n */\nexport function recoverFromChunkLoadError(\n error: unknown,\n { source = \"app\", url }: { source?: ChunkLoadErrorSource; url?: string } = {},\n): boolean {\n if (typeof window === \"undefined\" || !enabled || !isChunkLoadError(error)) {\n return false;\n }\n const target = url ?? window.location.href;\n if (loadPending(target)) {\n // A route with several views fails once per view; the first one reloads.\n return true;\n }\n const blocked = reloadBlock(target);\n\n if (options.onChunkLoadError?.({ error, url: target, source, blocked }) === false) {\n return false;\n }\n return loadInFull(target, blocked);\n}\n\n/**\n * Loads `url` in full because the navigation to it got its data from another\n * build (#1056): the views this page runs were not written for that data, and\n * rendering it anyway is how a deploy turned into \"Something went wrong\". The\n * full load gets a document and views of one build. Same guard as a chunk\n * failure, once per URL per cooldown; a navigation refused here renders the\n * data as before. Returns whether the page load was started.\n */\nexport function recoverFromBuildMismatch({\n url,\n clientBuild,\n serverBuild,\n}: {\n url: string;\n clientBuild: string;\n serverBuild: string;\n}): boolean {\n if (typeof window === \"undefined\" || !enabled) {\n return false;\n }\n if (loadPending(url)) {\n return true;\n }\n const blocked = reloadBlock(url);\n if (options.onBuildMismatch?.({ url, clientBuild, serverBuild, blocked }) === false) {\n return false;\n }\n return loadInFull(url, blocked);\n}\n\n/**\n * The build that answered a `.json` navigation, when it is not `clientBuild`;\n * otherwise `null`. Unknown on either side (dev, a test double, a server from\n * before the header) is not a mismatch.\n */\nexport function otherBuild(response: Response, clientBuild: string | undefined): string | null {\n const served = response.headers?.get?.(BUILD_HEADER);\n return clientBuild && served && served !== clientBuild ? served : null;\n}\n\nfunction loadInFull(target: string, blocked: ChunkReloadBlock): boolean {\n if (blocked !== null || !markReload(target)) {\n return false;\n }\n\n pendingLoad = { url: target, at: Date.now() };\n if (target === window.location.href) {\n window.location.reload();\n } else {\n window.location.assign(target);\n }\n return true;\n}\n\nfunction cooldownMs() {\n return options.cooldownMs ?? DEFAULT_CHUNK_RELOAD_COOLDOWN_MS;\n}\n\nfunction reloadBlock(url: string): ChunkReloadBlock {\n if (typeof navigator !== \"undefined\" && navigator.onLine === false) {\n return \"offline\";\n }\n const verdict = chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), false);\n return verdict === \"ok\" ? null : verdict;\n}\n\n// A marker from the future (the clock was set back since it was written) is\n// stale rather than a cooldown that lasts until the clock catches up.\nfunction withinCooldown(elapsed: number, cooldownMs: number): boolean {\n return elapsed >= 0 && elapsed < cooldownMs;\n}\n\nfunction markReload(url: string): boolean {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), true) !== \"ok\") return false;\n // The load may yet be cancelled (\"Stay\" on a `beforeunload` prompt), and\n // then this page has to take the `window.name` marker down itself.\n tidyWindowName();\n return true;\n}\n\nlet tidyTimer: ReturnType<typeof setTimeout> | undefined;\n\n/**\n * Takes gemi's marker out of `window.name` (back to `\"\"`) once it guards\n * nothing (#1188): the page may want the name for itself, under the same\n * \"only while it is empty\" rule gemi follows. Now when nothing in it is live,\n * otherwise once the newest entry's cooldown has passed, checked again then\n * since a reload may have been recorded in the meantime. Only a name that\n * holds gemi's marker is ever cleared; see `chunkReloadGuard`'s `\"tidy\"`.\n */\nfunction tidyWindowName() {\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n if (typeof window === \"undefined\") return;\n let delay: number;\n try {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, window.location.href, cooldownMs(), \"tidy\") !== \"cooldown\") {\n return;\n }\n const held = JSON.parse(window.name.slice(CHUNK_RELOAD_MARKER.length + 1));\n // An entry from the future (clock set back) is not live and holds nothing back.\n const now = Date.now();\n const latest = Math.max(\n ...Object.values(held.m).filter((at): at is number => typeof at === \"number\" && at <= now),\n );\n delay = latest + cooldownMs() - now;\n } catch {\n return;\n }\n if (!Number.isFinite(delay)) return;\n tidyTimer = setTimeout(tidyWindowName, Math.max(0, delay) + 1);\n}\n\n/**\n * The cross-document guard, shared by the client and the server's reload stub\n * (which embeds this function's source, so it uses nothing but globals and its\n * arguments). With `claim` false it only reads: `\"cooldown\"` when a reload\n * onto `url` was recorded inside `cooldownMs`, `\"storage\"` when no marker can\n * be read at all, otherwise `\"ok\"`. With `claim` true it also records the\n * reload, and answers `\"ok\"` only once the record was written and read back\n * unchanged; a caller navigates on nothing less. With `\"tidy\"` it only looks\n * at `window.name`: a gemi marker with no live entry for this origin (expired,\n * from the future, another origin's, or one that does not parse) is cleared\n * to `\"\"` and `\"ok\"` answered; `\"cooldown\"` while an entry is still live.\n *\n * Two places can hold the marker:\n *\n * - `sessionStorage[key]`: `{ [url]: at }`, the format earlier releases read\n * and write, so a page from one and a stub from another share the guard.\n * - `window.name`, when `sessionStorage` throws or will not take the write\n * (#1186). It survives a load in the same tab, but it is shared state: the\n * page may use it, and another origin the tab goes to can read it. So it is\n * used only while it is empty or already holds gemi's marker — a value of\n * anyone else's is left exactly as it is, and the guard then fails closed —\n * and it holds no URL: `key + \":\" + { o: hash(origin), m: { [hash(origin +\n * pathname)]: at } }`. A marker written by another origin (`o` differs) or\n * one that does not parse holds no reloads and is replaced on the next\n * write. Two paths whose hashes collide share one cooldown, which only ever\n * refuses a reload.\n *\n * A reload recorded in either place counts. Entries past the cooldown — and\n * from the future, after the clock was set back — are dropped as a new one is\n * written, so the marker holds only the reloads it still guards.\n */\nexport function chunkReloadGuard(\n key: string,\n url: string,\n cooldownMs: number,\n claim: boolean | \"tidy\",\n): \"ok\" | \"cooldown\" | \"storage\" {\n const now = Date.now();\n const fresh = function (at: unknown) {\n return typeof at === \"number\" && now - at >= 0 && now - at < cooldownMs;\n };\n const parse = function (raw: string | null): Record<string, unknown> {\n try {\n const value = raw ? JSON.parse(raw) : null;\n return value && typeof value === \"object\" && !Array.isArray(value) ? value : {};\n } catch {\n return {};\n }\n };\n const live = function (marker: Record<string, unknown>) {\n const kept: Record<string, number> = {};\n for (const k in marker) if (fresh(marker[k])) kept[k] = marker[k] as number;\n return kept;\n };\n // FNV-1a, 32 bits, base 36: a short tag, not a secret.\n const hash = function (text: string) {\n let h = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);\n return (h >>> 0).toString(36);\n };\n\n let storage: Storage | null = null;\n let stored: Record<string, unknown> = {};\n try {\n storage = window.sessionStorage;\n stored = parse(storage.getItem(key));\n } catch {\n storage = null;\n }\n\n const prefix = key + \":\";\n let origin = \"\";\n let page = \"\";\n try {\n const target = new URL(url, window.location.href);\n origin = hash(new URL(window.location.href).origin);\n page = hash(target.origin + target.pathname);\n } catch {}\n // `null`: `window.name` is not ours to use (or there is no page to key on).\n let named: Record<string, unknown> | null = null;\n try {\n const name = window.name;\n if (!page) {\n named = null;\n } else if (name === \"\") {\n named = {};\n } else if (name.indexOf(prefix) === 0) {\n const held = parse(name.slice(prefix.length));\n const entries = held.m;\n named =\n held.o === origin && entries && typeof entries === \"object\" && !Array.isArray(entries)\n ? (entries as Record<string, unknown>)\n : {};\n }\n } catch {\n named = null;\n }\n\n if (claim === \"tidy\") {\n try {\n const current = window.name;\n if (named === null || current.indexOf(prefix) !== 0) return \"ok\";\n for (const k in named) if (fresh(named[k])) return \"cooldown\";\n window.name = \"\";\n } catch {}\n return \"ok\";\n }\n if (fresh(stored[url]) || (named && fresh(named[page]))) return \"cooldown\";\n if (!storage && !named) return \"storage\";\n if (!claim) return \"ok\";\n\n if (storage) {\n try {\n const nextStored = live(stored);\n nextStored[url] = now;\n const serialised = JSON.stringify(nextStored);\n storage.setItem(key, serialised);\n if (storage.getItem(key) === serialised) return \"ok\";\n } catch {}\n }\n if (named) {\n try {\n const nextNamed = live(named);\n nextNamed[page] = now;\n const value = prefix + JSON.stringify({ o: origin, m: nextNamed });\n window.name = value;\n if (window.name === value) return \"ok\";\n } catch {}\n }\n return \"storage\";\n}\n\n/**\n * The same guard as a classic script body, for the module the server sends in\n * place of a chunk it does not have. It reloads once per URL per cooldown;\n * inside the cooldown (or with no marker that would survive the reload) it\n * throws an error `isChunkLoadError` recognises, so the importing page's own\n * recovery and error boundary see the failure instead of a module that\n * silently has no exports. It runs `chunkReloadGuard` itself, so it and the\n * page's client share one marker and one reload between them. It exports\n * `RELOAD_STUB_EXPORT`, true when it reloaded, so the client can tell a view\n * answered by the stub from a view and wait for the reload instead of\n * rendering a module with no `default`.\n */\nexport function chunkReloadStubScript(\n pathname: string,\n cooldownMs: number = DEFAULT_CHUNK_RELOAD_COOLDOWN_MS,\n): string {\n const key = JSON.stringify(CHUNK_RELOAD_MARKER);\n const error = JSON.stringify(`Failed to fetch dynamically imported module: ${pathname}`);\n return (\n `var g=${chunkReloadGuard.toString()};var r=!1;` +\n `try{r=navigator.onLine!==!1&&g(${key},window.location.href,${Number(cooldownMs)},!0)===\"ok\"}catch(e){}` +\n `if(r)window.location.reload();else throw new Error(${error});export {r as ${RELOAD_STUB_EXPORT}}`\n );\n}\n",
|
|
11
|
+
"/**\n * Recovery from a chunk that will not load — almost always a document from an\n * earlier release asking for a chunk the server it reached no longer has\n * (#548). The page cannot continue with the module it wanted, and a full load\n * of the URL it was heading to gets it the current release's document.\n *\n * One reload per page, guarded: a reload that lands on the same failure (a\n * chunk that is genuinely missing, a proxy that keeps refusing it) must not\n * become a loop. A `sessionStorage` marker records when each URL was reloaded\n * onto and survives the reload it guards, so a second failure for the same URL\n * inside the cooldown is left to the route's error boundary. Per URL rather\n * than per tab (#1056): while two releases serve at once every navigation can\n * miss, and a tab-wide cooldown sent the second one to the error boundary.\n * Where `sessionStorage` cannot be used, the marker lives in `window.name`\n * instead (#1186); see `chunkReloadGuard`.\n *\n * The same guard covers a navigation whose data came from another build\n * (`recoverFromBuildMismatch`).\n *\n * No DOM or React import at module scope: the server's reload stub\n * (`server/staticAssetMiss.ts`) embeds the same guard as a script.\n */\n\n/** The `sessionStorage` key the guard lives under, shared with the reload stub. */\nexport const CHUNK_RELOAD_MARKER = \"gemi:chunk-reload\";\n\n/**\n * The response header carrying the client build id on a `.json` navigation\n * (#1056). The document carries its own as `buildId`; they differ when the\n * request reached a server running another release.\n */\nexport const BUILD_HEADER = \"x-gemi-build\";\n\n/** How long after a recovery reload onto a URL another one onto it is refused. */\nexport const DEFAULT_CHUNK_RELOAD_COOLDOWN_MS = 30_000;\n\n/**\n * Where the failure surfaced: a route's view chunk during a client-side\n * navigation or hydration, a `vite:preloadError` (a lazy `import()` in app\n * code, through Vite's preload helper), or an app calling\n * `recoverFromChunkLoadError` from its own error boundary.\n */\nexport type ChunkLoadErrorSource = \"navigation\" | \"hydration\" | \"preload\" | \"app\";\n\n/**\n * Why gemi will not reload, or `null` when it will:\n * - `cooldown`: it already reloaded onto this URL within `cooldownMs`.\n * - `offline`: `navigator.onLine` is false — a reload would only fail harder.\n * - `storage`: neither `sessionStorage` nor the `window.name` fallback can\n * hold the guard, so it cannot survive the reload and the loop it prevents\n * could not be ruled out.\n */\nexport type ChunkReloadBlock = \"cooldown\" | \"offline\" | \"storage\" | null;\n\nexport interface ChunkLoadErrorContext {\n error: unknown;\n /** The URL the reload goes to: the page being navigated to. */\n url: string;\n source: ChunkLoadErrorSource;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface BuildMismatchContext {\n /** The URL the full page load goes to: the page being navigated to. */\n url: string;\n /** The build the page was loaded with. */\n clientBuild: string;\n /** The build that answered the navigation. */\n serverBuild: string;\n /** Why gemi will not reload, or `null` when it is about to. */\n blocked: ChunkReloadBlock;\n}\n\nexport interface ChunkLoadRecoveryOptions {\n /** Default 30 000 ms. */\n cooldownMs?: number;\n /**\n * Called for every chunk load failure gemi sees, before it reloads — the\n * place to report it, or to veto the reload (unsaved input, a page that\n * would rather show its own \"a new version is available\" prompt). Return\n * `false` to skip the reload; anything else lets gemi proceed. It is called\n * when the reload is blocked too, with `blocked` saying why.\n */\n onChunkLoadError?: (context: ChunkLoadErrorContext) => boolean | void;\n /**\n * Called when a client-side navigation's data came from another build (a\n * deploy in progress, two releases behind one load balancer), before gemi\n * loads the page in full. Return `false` to skip that and render the data\n * anyway. Called when the load is blocked too, with `blocked` saying why.\n */\n onBuildMismatch?: (context: BuildMismatchContext) => boolean | void;\n}\n\nlet enabled = true;\nlet options: ChunkLoadRecoveryOptions = {};\n/**\n * The full load gemi started and the page is still waiting on: further\n * failures of the same navigation (a route with several views fails once per\n * view) report it as under way instead of starting another.\n *\n * Not a latch for the life of the page: the load can be cancelled — \"Stay\" on\n * a `beforeunload` prompt (a dirty editor), a handler that stops it — and the\n * page then keeps running with no load coming. It holds only for the\n * navigation that started it (`navigationStarted` clears it) and for the\n * cooldown, so a later failure is judged on its own: another URL loads in\n * full, the same URL inside the cooldown is refused (the data renders, the\n * view's error boundary shows), and after the cooldown it loads again.\n */\nlet pendingLoad: { url: string; at: number } | null = null;\n\n/**\n * Sets how gemi recovers from a failed chunk. `false` turns recovery off: the\n * failure goes to the route's error boundary as it did before. `init` calls\n * this with its `chunkLoadRecovery` option.\n */\nexport function configureChunkLoadRecovery(next: ChunkLoadRecoveryOptions | false | undefined) {\n enabled = next !== false;\n options = next || {};\n tidyWindowName();\n}\n\n/** For tests: back to the defaults, with no reload in flight. */\nexport function __resetChunkLoadRecovery() {\n enabled = true;\n options = {};\n pendingLoad = null;\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n}\n\n/**\n * The router calls this as each client-side navigation starts. A full load\n * still pending from an earlier one was cancelled (the page would be gone\n * otherwise), so it no longer speaks for this navigation's failures.\n */\nexport function navigationStarted() {\n pendingLoad = null;\n}\n\n/** Whether a full load onto `url` is already under way. */\nfunction loadPending(url: string): boolean {\n return (\n pendingLoad !== null &&\n pendingLoad.url === url &&\n withinCooldown(Date.now() - pendingLoad.at, cooldownMs())\n );\n}\n\n/**\n * Whether `error` is a module that failed to load rather than one that loaded\n * and threw. Each engine words it differently:\n *\n * - Chromium: `Failed to fetch dynamically imported module: <url>`\n * - Firefox: `error loading dynamically imported module: <url>`\n * - Safari: `Importing a module script failed.`, and on iOS 16\n * `Importing module '<specifier>' is not found.`\n * - Vite's preload helper: `Unable to preload CSS for <url>`\n *\n * A view that throws while evaluating is not one of these, and reloading\n * would only hide it.\n */\nexport function isChunkLoadError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (name === \"ChunkLoadError\") {\n return true;\n }\n if (typeof message !== \"string\") {\n return false;\n }\n return CHUNK_LOAD_MESSAGES.some((pattern) => pattern.test(message));\n}\n\nconst CHUNK_LOAD_MESSAGES = [\n /failed to fetch dynamically imported module/i,\n /error loading dynamically imported module/i,\n /importing a module script failed/i,\n /importing module .* is not found/i,\n /unable to preload css/i,\n /failed to load module script/i,\n // A chunk that loaded but whose dependency came from another build: the\n // dependency's URL answered with the server's reload stub (or another\n // release's file), which lacks the named export the chunk imports, so the\n // module graph fails to link before any of it runs — the stub's own reload\n // never gets the chance. A production build's chunks only import names their\n // own build exports, so outside a mixed deploy this does not happen.\n // - Chromium: `The requested module './index-x.js' does not provide an export named 'a'`\n // - Firefox: `The requested module './index-x.js' doesn't provide an export named: 'a'`,\n // older releases `import not found: a`\n // - Safari: `Importing binding name 'a' is not found.`\n /requested module .* (does not|doesn't) provide an export named/i,\n /^import not found: /i,\n /importing binding name .* is not found/i,\n];\n\n/**\n * The export the server's reload stub carries, true when the stub started a\n * reload. A view chunk answered by the stub then evaluates to a module with no\n * `default`, and rendering it would put the route's error boundary on screen\n * for the moment before the page goes away.\n */\nexport const RELOAD_STUB_EXPORT = \"__gemiReload\";\n\n/**\n * How long a view waits on a full load gemi started before it gives up and\n * fails after all. The load can be cancelled (\"Stay\" on a `beforeunload`\n * prompt), and the page must not sit on its loading state for good then.\n */\nexport const RELOAD_WAIT_MS = 15_000;\n\n/**\n * A promise for a view whose page is being loaded in full: it stays pending,\n * so the route keeps its `Loading` fallback (or the server's HTML) instead of\n * flashing its error boundary while the reload is under way, and rejects with\n * `error` only if the page is still here after `RELOAD_WAIT_MS`.\n */\nexport function waitForReload(error: unknown, ms: number = RELOAD_WAIT_MS): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => reject(error), ms);\n });\n}\n\n/**\n * Reloads the page onto `url` once for a chunk that failed to load, unless the\n * guard or the app's `onChunkLoadError` says not to. Returns whether a reload\n * was started.\n *\n * Errors that are not chunk failures are ignored (`false`), so an app's error\n * boundary can pass everything it catches here.\n */\nexport function recoverFromChunkLoadError(\n error: unknown,\n { source = \"app\", url }: { source?: ChunkLoadErrorSource; url?: string } = {},\n): boolean {\n if (typeof window === \"undefined\" || !enabled || !isChunkLoadError(error)) {\n return false;\n }\n const target = url ?? window.location.href;\n if (loadPending(target)) {\n // A route with several views fails once per view; the first one reloads.\n return true;\n }\n const blocked = reloadBlock(target);\n\n if (options.onChunkLoadError?.({ error, url: target, source, blocked }) === false) {\n return false;\n }\n return loadInFull(target, blocked);\n}\n\n/**\n * Loads `url` in full because the navigation to it got its data from another\n * build (#1056): the views this page runs were not written for that data, and\n * rendering it anyway is how a deploy turned into \"Something went wrong\". The\n * full load gets a document and views of one build. Same guard as a chunk\n * failure, once per URL per cooldown; a navigation refused here renders the\n * data as before. Returns whether the page load was started.\n */\nexport function recoverFromBuildMismatch({\n url,\n clientBuild,\n serverBuild,\n}: {\n url: string;\n clientBuild: string;\n serverBuild: string;\n}): boolean {\n if (typeof window === \"undefined\" || !enabled) {\n return false;\n }\n if (loadPending(url)) {\n return true;\n }\n const blocked = reloadBlock(url);\n if (options.onBuildMismatch?.({ url, clientBuild, serverBuild, blocked }) === false) {\n return false;\n }\n return loadInFull(url, blocked);\n}\n\n/**\n * The build that answered a `.json` navigation, when it is not `clientBuild`;\n * otherwise `null`. Unknown on either side (dev, a test double, a server from\n * before the header) is not a mismatch.\n */\nexport function otherBuild(response: Response, clientBuild: string | undefined): string | null {\n const served = response.headers?.get?.(BUILD_HEADER);\n return clientBuild && served && served !== clientBuild ? served : null;\n}\n\nfunction loadInFull(target: string, blocked: ChunkReloadBlock): boolean {\n if (blocked !== null || !markReload(target)) {\n return false;\n }\n\n pendingLoad = { url: target, at: Date.now() };\n if (target === window.location.href) {\n window.location.reload();\n } else {\n window.location.assign(target);\n }\n return true;\n}\n\nfunction cooldownMs() {\n return options.cooldownMs ?? DEFAULT_CHUNK_RELOAD_COOLDOWN_MS;\n}\n\nfunction reloadBlock(url: string): ChunkReloadBlock {\n if (typeof navigator !== \"undefined\" && navigator.onLine === false) {\n return \"offline\";\n }\n const verdict = chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), false);\n return verdict === \"ok\" ? null : verdict;\n}\n\n// A marker from the future (the clock was set back since it was written) is\n// stale rather than a cooldown that lasts until the clock catches up.\nfunction withinCooldown(elapsed: number, cooldownMs: number): boolean {\n return elapsed >= 0 && elapsed < cooldownMs;\n}\n\nfunction markReload(url: string): boolean {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, url, cooldownMs(), true) !== \"ok\") return false;\n // The load may yet be cancelled (\"Stay\" on a `beforeunload` prompt), and\n // then this page has to take the `window.name` marker down itself.\n tidyWindowName();\n return true;\n}\n\nlet tidyTimer: ReturnType<typeof setTimeout> | undefined;\n\n/**\n * Takes gemi's marker out of `window.name` (back to `\"\"`) once it guards\n * nothing (#1188): the page may want the name for itself, under the same\n * \"only while it is empty\" rule gemi follows. Now when nothing in it is live,\n * otherwise once the newest entry's cooldown has passed, checked again then\n * since a reload may have been recorded in the meantime. Only a name that\n * holds gemi's marker is ever cleared; see `chunkReloadGuard`'s `\"tidy\"`.\n */\nfunction tidyWindowName() {\n clearTimeout(tidyTimer);\n tidyTimer = undefined;\n if (typeof window === \"undefined\") return;\n let delay: number;\n try {\n if (chunkReloadGuard(CHUNK_RELOAD_MARKER, window.location.href, cooldownMs(), \"tidy\") !== \"cooldown\") {\n return;\n }\n const held = JSON.parse(window.name.slice(CHUNK_RELOAD_MARKER.length + 1));\n // An entry from the future (clock set back) is not live and holds nothing back.\n const now = Date.now();\n const latest = Math.max(\n ...Object.values(held.m).filter((at): at is number => typeof at === \"number\" && at <= now),\n );\n delay = latest + cooldownMs() - now;\n } catch {\n return;\n }\n if (!Number.isFinite(delay)) return;\n tidyTimer = setTimeout(tidyWindowName, Math.max(0, delay) + 1);\n}\n\n/**\n * The cross-document guard, shared by the client and the server's reload stub\n * (which embeds this function's source, so it uses nothing but globals and its\n * arguments). With `claim` false it only reads: `\"cooldown\"` when a reload\n * onto `url` was recorded inside `cooldownMs`, `\"storage\"` when no marker can\n * be read at all, otherwise `\"ok\"`. With `claim` true it also records the\n * reload, and answers `\"ok\"` only once the record was written and read back\n * unchanged; a caller navigates on nothing less. With `\"tidy\"` it only looks\n * at `window.name`: a gemi marker with no live entry for this origin (expired,\n * from the future, another origin's, or one that does not parse) is cleared\n * to `\"\"` and `\"ok\"` answered; `\"cooldown\"` while an entry is still live.\n *\n * Two places can hold the marker:\n *\n * - `sessionStorage[key]`: `{ [url]: at }`, the format earlier releases read\n * and write, so a page from one and a stub from another share the guard.\n * - `window.name`, when `sessionStorage` throws or will not take the write\n * (#1186). It survives a load in the same tab, but it is shared state: the\n * page may use it, and another origin the tab goes to can read it. So it is\n * used only while it is empty or already holds gemi's marker — a value of\n * anyone else's is left exactly as it is, and the guard then fails closed —\n * and it holds no URL: `key + \":\" + { o: hash(origin), m: { [hash(origin +\n * pathname)]: at } }`. A marker written by another origin (`o` differs) or\n * one that does not parse holds no reloads and is replaced on the next\n * write. Two paths whose hashes collide share one cooldown, which only ever\n * refuses a reload.\n *\n * A reload recorded in either place counts. Entries past the cooldown — and\n * from the future, after the clock was set back — are dropped as a new one is\n * written, so the marker holds only the reloads it still guards.\n */\nexport function chunkReloadGuard(\n key: string,\n url: string,\n cooldownMs: number,\n claim: boolean | \"tidy\",\n): \"ok\" | \"cooldown\" | \"storage\" {\n const now = Date.now();\n const fresh = function (at: unknown) {\n return typeof at === \"number\" && now - at >= 0 && now - at < cooldownMs;\n };\n const parse = function (raw: string | null): Record<string, unknown> {\n try {\n const value = raw ? JSON.parse(raw) : null;\n return value && typeof value === \"object\" && !Array.isArray(value) ? value : {};\n } catch {\n return {};\n }\n };\n const live = function (marker: Record<string, unknown>) {\n const kept: Record<string, number> = {};\n for (const k in marker) if (fresh(marker[k])) kept[k] = marker[k] as number;\n return kept;\n };\n // FNV-1a, 32 bits, base 36: a short tag, not a secret.\n const hash = function (text: string) {\n let h = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);\n return (h >>> 0).toString(36);\n };\n\n let storage: Storage | null = null;\n let stored: Record<string, unknown> = {};\n try {\n storage = window.sessionStorage;\n stored = parse(storage.getItem(key));\n } catch {\n storage = null;\n }\n\n const prefix = key + \":\";\n let origin = \"\";\n let page = \"\";\n try {\n const target = new URL(url, window.location.href);\n origin = hash(new URL(window.location.href).origin);\n page = hash(target.origin + target.pathname);\n } catch {}\n // `null`: `window.name` is not ours to use (or there is no page to key on).\n let named: Record<string, unknown> | null = null;\n try {\n const name = window.name;\n if (!page) {\n named = null;\n } else if (name === \"\") {\n named = {};\n } else if (name.indexOf(prefix) === 0) {\n const held = parse(name.slice(prefix.length));\n const entries = held.m;\n named =\n held.o === origin && entries && typeof entries === \"object\" && !Array.isArray(entries)\n ? (entries as Record<string, unknown>)\n : {};\n }\n } catch {\n named = null;\n }\n\n if (claim === \"tidy\") {\n try {\n const current = window.name;\n if (named === null || current.indexOf(prefix) !== 0) return \"ok\";\n for (const k in named) if (fresh(named[k])) return \"cooldown\";\n window.name = \"\";\n } catch {}\n return \"ok\";\n }\n if (fresh(stored[url]) || (named && fresh(named[page]))) return \"cooldown\";\n if (!storage && !named) return \"storage\";\n if (!claim) return \"ok\";\n\n if (storage) {\n try {\n const nextStored = live(stored);\n nextStored[url] = now;\n const serialised = JSON.stringify(nextStored);\n storage.setItem(key, serialised);\n if (storage.getItem(key) === serialised) return \"ok\";\n } catch {}\n }\n if (named) {\n try {\n const nextNamed = live(named);\n nextNamed[page] = now;\n const value = prefix + JSON.stringify({ o: origin, m: nextNamed });\n window.name = value;\n if (window.name === value) return \"ok\";\n } catch {}\n }\n return \"storage\";\n}\n\n/**\n * The same guard as a classic script body, for the module the server sends in\n * place of a chunk it does not have. It reloads once per URL per cooldown;\n * inside the cooldown (or with no marker that would survive the reload) it\n * throws an error `isChunkLoadError` recognises, so the importing page's own\n * recovery and error boundary see the failure instead of a module that\n * silently has no exports. It runs `chunkReloadGuard` itself, so it and the\n * page's client share one marker and one reload between them. It exports\n * `RELOAD_STUB_EXPORT`, true when it reloaded, so the client can tell a view\n * answered by the stub from a view and wait for the reload instead of\n * rendering a module with no `default`.\n */\nexport function chunkReloadStubScript(\n pathname: string,\n cooldownMs: number = DEFAULT_CHUNK_RELOAD_COOLDOWN_MS,\n): string {\n const key = JSON.stringify(CHUNK_RELOAD_MARKER);\n const error = JSON.stringify(`Failed to fetch dynamically imported module: ${pathname}`);\n return (\n `var g=${chunkReloadGuard.toString()};var r=!1;` +\n `try{r=navigator.onLine!==!1&&g(${key},window.location.href,${Number(cooldownMs)},!0)===\"ok\"}catch(e){}` +\n `if(r)window.location.reload();else throw new Error(${error});export {r as ${RELOAD_STUB_EXPORT}}`\n );\n}\n",
|
|
12
12
|
"import { isReservedAssetPath, RESERVED_ROUTE_PREFIX } from \"../services/router/ViewRouteDispatcher\";\nimport { chunkReloadStubScript } from \"../client/chunkLoadRecovery\";\n\n/**\n * A JavaScript module under `/assets/` — the only shape a client build chunk\n * has. Vite writes every chunk into `assets/` with a `.js` extension (`.mjs`\n * is accepted for a build configured to emit it).\n *\n * The extension is matched at the end of the path, not anywhere in it:\n * `includes(\".js\")` also matched `app.js.map` and `data.json`, so a missing\n * source map was answered with a script that reloads the page.\n */\nconst BUILD_CHUNK = new RegExp(`^${RESERVED_ROUTE_PREFIX}/.+\\\\.m?js$`);\n\nexport function isBuildChunkPath(pathname: string): boolean {\n return BUILD_CHUNK.test(pathname);\n}\n\n/**\n * `/assets` or anything under it — the prefix the router refuses to mount a\n * route on at boot, so nothing there is ever the app's to answer. Defined\n * beside that check so the two cannot drift apart.\n */\nexport { isReservedAssetPath };\n\n/**\n * The answer to a static-looking request with no file behind it in\n * `dist/client`, or `undefined` to hand the request to the app.\n *\n * A missing build chunk is almost always a document rendered by another\n * release asking for its own chunks — a deploy between page load and a lazy\n * `import()`, or two releases serving at once. The page cannot continue with\n * the chunk it wanted, so it gets a module that reloads it onto this release's\n * document. Only for build chunks: outside `/assets/` a `.js` path may be an\n * app route, and a classic `<script src>` answered with a reload reloads\n * forever.\n *\n * `no-store` because the stub is a stand-in for one release's chunk, served\n * under that chunk's URL. Cached — by the browser or by an edge in front of\n * the origin — it would outlive the deploy that caused it and answer the\n * request after the real chunk is back.\n *\n * The body is only the reload. An earlier version opened with\n * `if(caches){caches?.delete(distPath)}`, which was wrong three times over:\n * `CacheStorage.delete` takes a cache *name*, not a URL, so a filesystem path\n * matched nothing; that path told anyone who asked for a missing chunk where\n * the server keeps its files; and `caches` is `[SecureContext]`, so on a\n * plain-http origin the bare identifier is not defined at all and reading it\n * threw a `ReferenceError` before the reload below could run — the recovery\n * failing exactly where it was needed.\n *\n * The reload is guarded by the same `sessionStorage` marker the client\n * router's chunk recovery uses (`client/chunkLoadRecovery.ts`), so the stub\n * and the router together reload once per cooldown. A chunk that is still\n * missing after that reload makes the stub throw a chunk-load error instead —\n * the importing `import()` rejects and the route's error boundary shows,\n * where an unguarded reload used to loop.\n */\nexport function staticAssetMiss(pathname: string): Response | undefined {\n if (isBuildChunkPath(pathname)) {\n return new Response(chunkReloadStubScript(pathname), {\n headers: {\n \"Content-Type\": \"application/javascript\",\n \"Cache-Control\": \"no-store\",\n },\n });\n }\n\n // `/assets` is reserved for build output (the router rejects routes there\n // at boot), so a miss is a miss — 404 without paying for an SSR render.\n if (isReservedAssetPath(pathname)) {\n return new Response(\"Not found\", { status: 404 });\n }\n\n // Anywhere else the public-file pattern matched on extension alone, so this\n // may well be an app route — a file route like\n // `this.file(() => Bun.file(...))` mounted at `/files/logo.svg` lands here\n // too. The app answers it rather than a 404 on its behalf.\n return undefined;\n}\n",
|
|
13
13
|
"/**\n * A second place to find a build asset this server does not have (#1269).\n *\n * While two releases serve one app (a weighted rollout across revisions, two\n * origins behind a load balancer with no affinity), a document from one\n * release asks for its hashed files and each request can land on the other.\n * Neither release has the other's files, and a reload only rolls the dice\n * again. With a fallback base set — a bucket or blob container the deploy\n * uploads every release's `dist/client/assets` to before it takes traffic —\n * a miss under `/assets/` is fetched from there and streamed back, so any\n * release answers any recent release's chunks, stylesheets and fonts. Without\n * a file there either, the miss is answered as before (the reload stub for a\n * chunk, a 404 for the rest).\n *\n * Read at boot from `GEMI_ASSET_FALLBACK_URL`. Unset, nothing changes.\n */\n\n/** How long the fallback may take to start answering before the miss is answered locally. */\nexport const ASSET_FALLBACK_TIMEOUT_MS = 3_000;\n/** How long a path the fallback did not have is not asked for again. */\nexport const ASSET_FALLBACK_MISS_TTL_MS = 30_000;\n/** At most this many remembered misses, oldest dropped first. */\nconst MAX_REMEMBERED_MISSES = 1_000;\n\n/** Marks a response that came from the fallback, for whoever debugs a deploy. */\nexport const ASSET_FALLBACK_HEADER = \"x-gemi-asset-fallback\";\n\nexport interface AssetFallbackOptions {\n /** Absolute http(s) URL the `/assets/...` path is resolved against. */\n base: string;\n timeoutMs?: number;\n missTtlMs?: number;\n fetch?: typeof fetch;\n now?: () => number;\n}\n\nexport type AssetFallback = (req: Request, pathname: string) => Promise<Response | undefined>;\n\n/**\n * `GEMI_ASSET_FALLBACK_URL`, checked: an absolute http(s) URL, given a\n * trailing `/`. Anything else is reported and ignored, since a typo must not\n * cost the server its boot.\n */\nexport function assetFallbackBase(value: string | undefined): string | undefined {\n const raw = value?.trim();\n if (!raw) return undefined;\n try {\n const url = new URL(raw);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") throw new Error(\"not http(s)\");\n url.search = \"\";\n url.hash = \"\";\n return url.href.endsWith(\"/\") ? url.href : `${url.href}/`;\n } catch {\n console.error(\n `GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify(raw)}); missing assets are not looked up anywhere else.`,\n );\n return undefined;\n }\n}\n\n/**\n * The lookup for one fallback base. Answers `undefined` whenever the fallback\n * has nothing usable — a non-200, a timeout, a network error, a method other\n * than GET/HEAD — and remembers that for `missTtlMs`, so a path that is\n * really gone (an old tab days later, a scanner) costs the fallback one\n * request per window, not one per hit.\n */\nexport function createAssetFallback({\n base,\n timeoutMs = ASSET_FALLBACK_TIMEOUT_MS,\n missTtlMs = ASSET_FALLBACK_MISS_TTL_MS,\n fetch: fetchImpl = fetch,\n now = Date.now,\n}: AssetFallbackOptions): AssetFallback {\n const misses = new Map<string, number>();\n\n const remember = (pathname: string) => {\n misses.delete(pathname);\n misses.set(pathname, now() + missTtlMs);\n if (misses.size > MAX_REMEMBERED_MISSES) {\n misses.delete(misses.keys().next().value!);\n }\n };\n\n return async (req, pathname) => {\n if (req.method !== \"GET\" && req.method !== \"HEAD\") return undefined;\n\n const until = misses.get(pathname);\n if (until !== undefined) {\n if (until > now()) return undefined;\n misses.delete(pathname);\n }\n\n // The path is the request's own, already normalised by `URL`; resolved\n // relative to the base (without its leading `/`) so a base with a path\n // keeps it, and checked to stay under it.\n let target: URL;\n try {\n target = new URL(pathname.replace(/^\\/+/, \"\"), base);\n } catch {\n return undefined;\n }\n if (!target.href.startsWith(base)) return undefined;\n\n // The timeout covers the wait for the answer to start, not the body: a\n // large file that has started streaming is left to finish.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let upstream: Response;\n try {\n upstream = await fetchImpl(target.href, {\n method: req.method,\n signal: controller.signal,\n redirect: \"error\",\n });\n } catch {\n remember(pathname);\n return undefined;\n } finally {\n clearTimeout(timer);\n }\n\n if (upstream.status !== 200) {\n // Drained so the connection can be reused.\n upstream.body?.cancel().catch(() => {});\n remember(pathname);\n return undefined;\n }\n\n // The extension decides first, as it does for the files this server has:\n // a store that labels a chunk `application/octet-stream` would otherwise\n // get it refused as a module script.\n const byExtension = Bun.file(pathname).type;\n const headers = new Headers({\n \"Content-Type\":\n (byExtension !== \"application/octet-stream\" && byExtension) ||\n upstream.headers.get(\"content-type\") ||\n \"application/octet-stream\",\n // Content-hashed, like every file the build writes under `/assets/`.\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n [ASSET_FALLBACK_HEADER]: \"1\",\n });\n // `fetch` decodes a compressed answer, so the upstream length only holds\n // for one that was not encoded.\n const length = upstream.headers.get(\"content-length\");\n if (length && !upstream.headers.get(\"content-encoding\")) {\n headers.set(\"Content-Length\", length);\n }\n return new Response(req.method === \"HEAD\" ? null : upstream.body, { status: 200, headers });\n };\n}\n",
|
|
14
14
|
"import { stringEraRefusal } from \"../http/Error\";\nimport { isApiPath } from \"../services/router/apiPath\";\n\n// The production server's last resort: an error nothing on the way here turned\n// into a response. Request breakers (auth, 404s, 416s) are answered by the\n// dispatchers before this, so what arrives is a genuine failure — and its\n// message and stack are for the developer, not for whoever triggered it. They\n// can carry absolute paths, dependency versions, SQL fragments and column\n// names. The dev server renders them on purpose (`httpDev.ts`); this does not.\n\nconst GENERIC_500_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Internal Server Error</title>\n <style>\n body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: grid; place-items: center; }\n main { text-align: center; padding: 16px; }\n h1 { font-size: 1.5rem; margin: 0 0 0.5rem; }\n p { margin: 0; opacity: 0.7; }\n </style>\n </head>\n <body>\n <main>\n <h1>Something went wrong</h1>\n <p>Please try again later.</p>\n </main>\n </body>\n</html>`;\n\nexport function unhandledErrorResponse(\n err: unknown,\n pathname: string,\n onException?: (error: Error) => void,\n): Response {\n // `onException` is the report, and the default one `App` installs is a\n // `console.error`, so logging here as well printed every failure twice\n // (three times for `/api`, whose dispatcher logs before rethrowing). Only\n // without a reporter does this log itself.\n //\n // Reported for `/api` too: an app's error tracking should see an API failure\n // that got this far, not only a page one. `onRequestFail` is a different\n // hook (route config, called by the dispatchers), so this is not a second\n // report through the same channel.\n if (!onException) {\n console.error(err);\n } else {\n try {\n // The hook is typed to receive an `Error`; a thrown string or object is\n // wrapped so a reporter reading `.stack` or `.name` gets one.\n onException(err instanceof Error ? err : new Error(String(err), { cause: err }));\n } catch (reportError) {\n // A broken reporter must not turn a 500 into a leaked stack either.\n console.error(err);\n console.error(reportError);\n }\n }\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({ error: stringEraRefusal(\"server_error\", \"Internal Server Error\", 500) }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(GENERIC_500_HTML, {\n status: 500,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Dc as _3,Qc as L3,jc as f3,nc as V2,oc as w3,pc as I3,pd as O3,xc as P3}from"./chunk-t5gbp0yr.js";import{Bd as n}from"./chunk-gvr7cwxn.js";import{ke as l2,me as P2,pe as s3,qe as t3,re as _$,te as q$}from"./chunk-8mpptpn5.js";import{Be as c3,De as p3,Ne as C,Oe as i3,Pe as l3,Re as n3,Se as A$,ve as E$,we as d3,ze as Z3}from"./chunk-x185900b.js";import{Ve as B}from"./chunk-9kt24ctk.js";import{$g as z$,Ah as N$,Ff as L$,Gf as n2,Gh as M$,Ig as z3,Kf as B2,Lf as Q2,Tg as r2,Vg as o,Zg as Z$,_g as e2,ah as G$,bg as c2,eh as g2,ff as t,fh as f2,gf as U$,hf as m2,jh as w2,kh as W$,lf as y3,lh as Y2,mg as F2,mh as X$,ng as d2,nh as Y$,of as k$,og as R,oh as v2,pf as b$,ph as Z2,rg as F$,sf as B$,sg as V$,sh as w$,tg as H$,th as a,uh as i2,vf as I$,vg as g,zh as J$}from"./chunk-cb7mgx75.js";import{Si as d,fj as a2,vj as B3,zj as X2}from"./chunk-fqndtpwm.js";import{Bj as a3}from"./chunk-h1wmpa03.js";import{Hj as l,Lj as T$,Mj as _2,Nj as h}from"./chunk-t6x1r5n6.js";import{Vj as u}from"./chunk-naj8bmj5.js";import{$j as p2}from"./chunk-np6vee9d.js";import{ck as O$,dk as s2,gk as I2,hk as o2,kk as D$}from"./chunk-5exrgw07.js";import{Dk as e3,yk as r3}from"./chunk-jssjfvsz.js";import{Tk as u3,Vk as c,fl as W2}from"./chunk-m3fbewhz.js";import{hl as q}from"./chunk-x2dmgge8.js";import{nl as S$}from"./chunk-fs94x6ef.js";import{Sl as R$}from"./chunk-8476xvk9.js";import{gm as t2}from"./chunk-1xz206e1.js";import{nm as N2,qm as k}from"./chunk-17ewxwga.js";import{zm as u2}from"./chunk-qvn0w2rt.js";import{Pm as $$}from"./chunk-3y1h3ncf.js";var v$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var G3=/^[A-Za-z0-9_-]{1,64}$/,h$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,W3=4000,E=1e5,m$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,j3=new WeakMap;function D9($){return j3.get($)}class s{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=i$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,u$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(U3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(U3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new m(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let U=Q.value,V={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,V),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${H}.`,404);let P={};for(let x of Y.jsonKeys)if(U[x]!==void 0)P[x]=U[x];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,V);else if(K.method==="GET")J=Z8(P);else if(Y.jsonKeys.length>0)I=P;let D=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(V)):void 0,j={...D?{credentials:D}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let x=J?`${H}?${J}`:H;T=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,x,I,j):await this.dispatcher.dispatchAs($.req,K.method,x,I)}catch(x){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,x),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await N3(Z,T);return await this.project(Y,V,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" 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 z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(h$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(H3(S))o$(z,`params.${N}`,S);else V3(z,`params.${N}`,S)}let U=[],V;if(X.input){if(V=X.input.toJSONSchema(),V.type!=="object"||!V.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(V.properties)}let H=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of H)V3(z,`files.${N.name}`,N.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=J3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,D=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=l.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(H3(S)){let w=S.as??N.name;I(w,S.input),D.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let j={};for(let N of H)if(N.binder==="input")I(N.name,l.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let T=[...Object.keys(P),...H.map((N)=>N.name)];for(let N of new Set(T))if(U.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let x=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:F3(X.input,V,l.object(P)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),A=!H.every((N)=>N.binder==="input")?null:H.length===0?x:Object.freeze({...x,inputSchema:F3(X.input,V,l.object(e$(P,Object.keys(j))),j)});return{kind:"route",descriptor:x,remote:A,params:K,paramBinders:J,modelParams:D,fileFields:H,jsonKeys:U,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={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 ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let V=Y[U];if(V===void 0||V===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof V!=="string")K.push(`a file's "${U}" must be a string`);else Q[U]=V}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" 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 z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:J3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!K2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let U=G.signal??new AbortController().signal;return Q3(X,Y.value,K3(Y3(X,Q,U,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(O2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return j3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(A,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(A,N):c$(A,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await X3(this.runNative($,{...K,ctx:G},G),Q)}let U=$.meta.remote,V=await this.bind($,"the remote context",()=>U.context(K));if(typeof V!=="object"||V===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,V),new O(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=Y3($,V,P,I);if(!W.approved&&K2($)&&await Q3($,K.input,K3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let D;try{D=await X3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(A){if(P.aborted&&A===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${H} ms.`,504)}if(A instanceof O)throw A;if(A instanceof n||A instanceof m)throw new O(A.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,A),new O(`"${X}" failed on the server.`,500)}let j=(A)=>{return console.error(`[gemi/mcp] "${X}" ${A}`),new O(`"${X}" failed on the server.`,500)};if(P3(D))throw j("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(A){throw j(`could not read an image it showed: ${A}`)}let x=D;if($.descriptor.outputSchema){let A=$.descriptor.outputSchema.safeParse(x);if(A.ok===!1)throw j(`answered what its output schema refuses: ${A.errors.join(", ")}`);x=A.value}for(let A of T)W.images?.(A);if(x===void 0)return null;if(typeof x==="string")return x.length>E?`${x.slice(0,E)}\u2026 [cut at ${E} of ${x.length} characters]`:x;let z2=JSON.stringify(x);if(z2!==void 0&&z2.length>E)return`${z2.slice(0,E)}\u2026 [cut at ${E} of ${z2.length} characters]`;return x}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let U=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${U}`,"");continue}W=W.replace(U,$8($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,U]of Object.entries(Z))j2(K,Q,U);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)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,Q]of Object.entries(Z))j2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(V)=>new O(`"${Z}" of "${$}" ${V}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!l$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!n$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let V=W.data.replace(/\s+/g,"");if(Math.floor(V.length*3/4)-t$(V)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(V.length%4!==0||!s$.test(V))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(V,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let V=await B3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!V.ok)throw G(`could not be fetched: ${U.host} answered ${V.status}.`);let H=await V.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(V){if(V instanceof O)throw V;throw G(`could not be fetched from ${U.host}: ${V instanceof Error?V.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(v$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!g$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await N3(G,z);let X=(H,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,F);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=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 U=Q;if($.result)try{U=await $.result(Q,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let V=JSON.stringify(U);if(V!==void 0&&V.length>E)return`${V.slice(0,E)}\u2026 [cut at ${E} of ${V.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function u$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function d$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function X3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!d$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function c$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function Y3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(V)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${V}.`,{retryable:!1})},U={put:async(V,H={})=>{if(!H.showModel)return K("attachment store")();let F=H.mimeType||V.type;if(!/^image\//i.test(F))throw new n(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=V.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(V instanceof File?V.name:"image"),mimeType:F,size:V.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(V)=>O3({...V,signal:V.signal?AbortSignal.any([z,V.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:_3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:L3(),meter:I3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function K3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Q3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function O2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.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 U3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var p$=10485760;function i$($){let Z=$?.maxBytes??p$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function l$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var n$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function t$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function H3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function o$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var a$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function r$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function J3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?r$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!a$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function F3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,U])=>[Q,U.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let U=[],V={};if($){let F=$.safeParse(Q);if(F.ok===!1)U.push(...F.errors);else V={...F.value}}let H=z.safeParse(Q);if(H.ok===!1)U.push(...H.errors);else V={...V,...H.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){U.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((D)=>`${F}: ${D}`));else V[F]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:V}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let U=K(Q);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function e$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function $8($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function j2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)j2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function Z8($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function N3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!m$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>E)return`${W.slice(0,E)}\u2026 [cut at ${E} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>W3?`${z.slice(0,W3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as z8,randomBytes as G8,timingSafeEqual as W8}from"crypto";function D2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class X8{options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${G8(32).toString("base64url")}`}static hash($){return z8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&W8(z,G)}async resolve($){let Z=D2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as v3,randomBytes as C3}from"crypto";async function x2($,Z){let z=Y8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function Y8(){try{let $=k();return $.bound(t)?$.make(t):null}catch{return null}}var A2=["2026-07-28"],U2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...A2,...U2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function x3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as K8,timingSafeEqual as Q8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!Q8(K,Q))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function A3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",S3="gemi.mcp.session.v1",U8=86400000,q3=600000,T3="gemi_approval",b2=2000,V8={limit:600,window:60},H8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=N8(Z.url);let G=Z.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,V2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.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.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??V8,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new f3,this.approvalTimeoutMs=Z.approvalTimeoutMs??q3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?F8(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"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($.method!=="POST")return M3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return M3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(D2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),R3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),V=$.headers.get("mcp-protocol-version");if(V!==null&&V!==U.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${V} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(H,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),R3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=U2.includes(G)?G:U2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:k3(X.elicitation),p:H2(z),exp:Date.now()+U8},K=k2(S3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(S3,"gms1",z);if(!G||G.p!==H2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||x3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,D)=>{G.outcome="denied",G.reason=J,G.message=D},K=(J,D,j)=>{if(G.outcome="error",G.message=J,D!==void 0)G.status=D;if(j!==void 0)G.error=j},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let j=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(j),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let j=await this.approval($,Q,z,Y,G);if(j.kind==="answer")return j.result;G.approved=!0}}let U=P8($),V=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>V.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let j=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,j),new _(L.InvalidParams,j)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let D=`"${Z}" failed on the server.`;return K(D,void 0,J),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}let F=typeof H==="string"?H:JSON.stringify(H??null),P=Q.outputSchema&&($.era.modern||M(H))?{structuredContent:H}:{},I=[...V.length>0&&H===null?[]:[{type:"text",text:F}],...V];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,D=B8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==H2($.principal)||T.t!==Z.name||T.a!==D)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return E3(I[T3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!k3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:H2($.principal),t:Z.name,a:D,n:C3(16).toString("base64url"),exp:Date.now()+q3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[T3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",j),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${C3(12).toString("base64url")}`,V=Q.sessionId,H=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(U),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(U,{session:V,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&E3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new g3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=y3(new d($,{},"api",this.endpoint.pathname)),z=await x2(`mcp-auth-failed:${Z}`,H8);return z===null?null:b3(z)}async spend($){if(!this.rateLimit)return null;let Z=await x2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:b3(Z)}}class g3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
2
|
+
import{Dc as _3,Qc as L3,jc as f3,nc as V2,oc as w3,pc as I3,pd as O3,xc as P3}from"./chunk-dav7mv8t.js";import{Bd as n}from"./chunk-gvr7cwxn.js";import{ke as l2,me as P2,pe as s3,qe as t3,re as _$,te as q$}from"./chunk-8mpptpn5.js";import{Be as c3,De as p3,Ne as C,Oe as i3,Pe as l3,Re as n3,Se as A$,ve as E$,we as d3,ze as Z3}from"./chunk-x185900b.js";import{Ve as B}from"./chunk-9kt24ctk.js";import{$g as z$,Ah as N$,Ff as L$,Gf as n2,Gh as M$,Ig as z3,Kf as B2,Lf as Q2,Tg as r2,Vg as o,Zg as Z$,_g as e2,ah as G$,bg as c2,eh as g2,ff as t,fh as f2,gf as U$,hf as m2,jh as w2,kh as W$,lf as y3,lh as Y2,mg as F2,mh as X$,ng as d2,nh as Y$,of as k$,og as R,oh as v2,pf as b$,ph as Z2,rg as F$,sf as B$,sg as V$,sh as w$,tg as H$,th as a,uh as i2,vf as I$,vg as g,zh as J$}from"./chunk-73541m4t.js";import{Si as d,fj as a2,vj as B3,zj as X2}from"./chunk-fqndtpwm.js";import{Bj as a3}from"./chunk-h1wmpa03.js";import{Hj as l,Lj as T$,Mj as _2,Nj as h}from"./chunk-t6x1r5n6.js";import{Vj as u}from"./chunk-naj8bmj5.js";import{$j as p2}from"./chunk-np6vee9d.js";import{ck as O$,dk as s2,gk as I2,hk as o2,kk as D$}from"./chunk-5exrgw07.js";import{Dk as e3,yk as r3}from"./chunk-jssjfvsz.js";import{Tk as u3,Vk as c,fl as W2}from"./chunk-m3fbewhz.js";import{hl as q}from"./chunk-x2dmgge8.js";import{nl as S$}from"./chunk-fs94x6ef.js";import{Sl as R$}from"./chunk-8476xvk9.js";import{gm as t2}from"./chunk-1xz206e1.js";import{nm as N2,qm as k}from"./chunk-17ewxwga.js";import{zm as u2}from"./chunk-qvn0w2rt.js";import{Pm as $$}from"./chunk-3y1h3ncf.js";var v$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var G3=/^[A-Za-z0-9_-]{1,64}$/,h$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,W3=4000,E=1e5,m$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,j3=new WeakMap;function D9($){return j3.get($)}class s{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=i$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,u$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(U3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(U3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new m(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let U=Q.value,V={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,V),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${H}.`,404);let P={};for(let x of Y.jsonKeys)if(U[x]!==void 0)P[x]=U[x];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,V);else if(K.method==="GET")J=Z8(P);else if(Y.jsonKeys.length>0)I=P;let D=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(V)):void 0,j={...D?{credentials:D}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let x=J?`${H}?${J}`:H;T=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,x,I,j):await this.dispatcher.dispatchAs($.req,K.method,x,I)}catch(x){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,x),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await N3(Z,T);return await this.project(Y,V,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" 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 z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(h$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(H3(S))o$(z,`params.${N}`,S);else V3(z,`params.${N}`,S)}let U=[],V;if(X.input){if(V=X.input.toJSONSchema(),V.type!=="object"||!V.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(V.properties)}let H=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of H)V3(z,`files.${N.name}`,N.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=J3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,D=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=l.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(H3(S)){let w=S.as??N.name;I(w,S.input),D.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let j={};for(let N of H)if(N.binder==="input")I(N.name,l.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let T=[...Object.keys(P),...H.map((N)=>N.name)];for(let N of new Set(T))if(U.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let x=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:F3(X.input,V,l.object(P)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),A=!H.every((N)=>N.binder==="input")?null:H.length===0?x:Object.freeze({...x,inputSchema:F3(X.input,V,l.object(e$(P,Object.keys(j))),j)});return{kind:"route",descriptor:x,remote:A,params:K,paramBinders:J,modelParams:D,fileFields:H,jsonKeys:U,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={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 ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let V=Y[U];if(V===void 0||V===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof V!=="string")K.push(`a file's "${U}" must be a string`);else Q[U]=V}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" 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 z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:J3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!K2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let U=G.signal??new AbortController().signal;return Q3(X,Y.value,K3(Y3(X,Q,U,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(O2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return j3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(A,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(A,N):c$(A,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await X3(this.runNative($,{...K,ctx:G},G),Q)}let U=$.meta.remote,V=await this.bind($,"the remote context",()=>U.context(K));if(typeof V!=="object"||V===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,V),new O(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=Y3($,V,P,I);if(!W.approved&&K2($)&&await Q3($,K.input,K3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let D;try{D=await X3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(A){if(P.aborted&&A===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${H} ms.`,504)}if(A instanceof O)throw A;if(A instanceof n||A instanceof m)throw new O(A.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,A),new O(`"${X}" failed on the server.`,500)}let j=(A)=>{return console.error(`[gemi/mcp] "${X}" ${A}`),new O(`"${X}" failed on the server.`,500)};if(P3(D))throw j("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(A){throw j(`could not read an image it showed: ${A}`)}let x=D;if($.descriptor.outputSchema){let A=$.descriptor.outputSchema.safeParse(x);if(A.ok===!1)throw j(`answered what its output schema refuses: ${A.errors.join(", ")}`);x=A.value}for(let A of T)W.images?.(A);if(x===void 0)return null;if(typeof x==="string")return x.length>E?`${x.slice(0,E)}\u2026 [cut at ${E} of ${x.length} characters]`:x;let z2=JSON.stringify(x);if(z2!==void 0&&z2.length>E)return`${z2.slice(0,E)}\u2026 [cut at ${E} of ${z2.length} characters]`;return x}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let U=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${U}`,"");continue}W=W.replace(U,$8($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,U]of Object.entries(Z))j2(K,Q,U);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)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,Q]of Object.entries(Z))j2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(V)=>new O(`"${Z}" of "${$}" ${V}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!l$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!n$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let V=W.data.replace(/\s+/g,"");if(Math.floor(V.length*3/4)-t$(V)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(V.length%4!==0||!s$.test(V))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(V,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let V=await B3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!V.ok)throw G(`could not be fetched: ${U.host} answered ${V.status}.`);let H=await V.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(V){if(V instanceof O)throw V;throw G(`could not be fetched from ${U.host}: ${V instanceof Error?V.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(v$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!g$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await N3(G,z);let X=(H,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,F);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=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 U=Q;if($.result)try{U=await $.result(Q,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let V=JSON.stringify(U);if(V!==void 0&&V.length>E)return`${V.slice(0,E)}\u2026 [cut at ${E} of ${V.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function u$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function d$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function X3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!d$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function c$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function Y3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(V)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${V}.`,{retryable:!1})},U={put:async(V,H={})=>{if(!H.showModel)return K("attachment store")();let F=H.mimeType||V.type;if(!/^image\//i.test(F))throw new n(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=V.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(V instanceof File?V.name:"image"),mimeType:F,size:V.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(V)=>O3({...V,signal:V.signal?AbortSignal.any([z,V.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:_3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:L3(),meter:I3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function K3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Q3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function O2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.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 U3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var p$=10485760;function i$($){let Z=$?.maxBytes??p$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function l$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var n$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function t$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function H3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function o$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var a$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function r$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function J3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?r$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!a$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function F3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,U])=>[Q,U.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let U=[],V={};if($){let F=$.safeParse(Q);if(F.ok===!1)U.push(...F.errors);else V={...F.value}}let H=z.safeParse(Q);if(H.ok===!1)U.push(...H.errors);else V={...V,...H.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){U.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((D)=>`${F}: ${D}`));else V[F]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:V}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let U=K(Q);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function e$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function $8($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function j2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)j2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function Z8($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function N3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!m$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>E)return`${W.slice(0,E)}\u2026 [cut at ${E} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>W3?`${z.slice(0,W3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as z8,randomBytes as G8,timingSafeEqual as W8}from"crypto";function D2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class X8{options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${G8(32).toString("base64url")}`}static hash($){return z8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&W8(z,G)}async resolve($){let Z=D2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as v3,randomBytes as C3}from"crypto";async function x2($,Z){let z=Y8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function Y8(){try{let $=k();return $.bound(t)?$.make(t):null}catch{return null}}var A2=["2026-07-28"],U2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...A2,...U2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function x3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as K8,timingSafeEqual as Q8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!Q8(K,Q))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function A3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",S3="gemi.mcp.session.v1",U8=86400000,q3=600000,T3="gemi_approval",b2=2000,V8={limit:600,window:60},H8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=N8(Z.url);let G=Z.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,V2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.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.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??V8,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new f3,this.approvalTimeoutMs=Z.approvalTimeoutMs??q3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?F8(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"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($.method!=="POST")return M3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return M3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(D2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),R3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),V=$.headers.get("mcp-protocol-version");if(V!==null&&V!==U.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${V} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(H,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),R3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=U2.includes(G)?G:U2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:k3(X.elicitation),p:H2(z),exp:Date.now()+U8},K=k2(S3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(S3,"gms1",z);if(!G||G.p!==H2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||x3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,D)=>{G.outcome="denied",G.reason=J,G.message=D},K=(J,D,j)=>{if(G.outcome="error",G.message=J,D!==void 0)G.status=D;if(j!==void 0)G.error=j},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let j=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(j),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let j=await this.approval($,Q,z,Y,G);if(j.kind==="answer")return j.result;G.approved=!0}}let U=P8($),V=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>V.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let j=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,j),new _(L.InvalidParams,j)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let D=`"${Z}" failed on the server.`;return K(D,void 0,J),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}let F=typeof H==="string"?H:JSON.stringify(H??null),P=Q.outputSchema&&($.era.modern||M(H))?{structuredContent:H}:{},I=[...V.length>0&&H===null?[]:[{type:"text",text:F}],...V];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,D=B8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==H2($.principal)||T.t!==Z.name||T.a!==D)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return E3(I[T3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!k3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:H2($.principal),t:Z.name,a:D,n:C3(16).toString("base64url"),exp:Date.now()+q3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[T3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",j),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${C3(12).toString("base64url")}`,V=Q.sessionId,H=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(U),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(U,{session:V,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&E3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new g3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=y3(new d($,{},"api",this.endpoint.pathname)),z=await x2(`mcp-auth-failed:${Z}`,H8);return z===null?null:b3(z)}async spend($){if(!this.rateLimit)return null;let Z=await x2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:b3(Z)}}class g3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
3
3
|
data: ${JSON.stringify($)}
|
|
4
4
|
|
|
5
5
|
`))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class J2 extends Error{}async function J8($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new J2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new J2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function M3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function F8($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function N8($){let Z;try{Z=new URL($)}catch{throw Error(`route.mcp.remote.url: "${$}" is not a URL.`)}let z=Z.hostname==="localhost"||Z.hostname==="127.0.0.1"||Z.hostname==="[::1]";if(Z.protocol!=="https:"&&!(Z.protocol==="http:"&&z))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if(Z.search||Z.hash||Z.username||Z.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if(Z.pathname==="/"||Z.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return Z}function H2($){return v3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function B8($){return v3("sha256").update(w3($??{})).digest("base64url")}function k3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function R3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function I8($,Z,z){if(Z.method!=="tools/call"||!z.e)return!1;let G=Z.params?.name;return typeof G==="string"&&$.descriptors({names:[G]})[0]?.requiresApproval===!0}function P8($){let z=(M($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function _8($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
|