blink 1.0.2 → 1.0.3
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/browser/agent/client/index.d.cts +3 -3
- package/dist/browser/agent/client/index.d.ts +3 -3
- package/dist/browser/agent/index.browser.d.cts +2 -2
- package/dist/browser/agent/index.browser.d.ts +2 -2
- package/dist/browser/control/index.cjs +1 -1
- package/dist/browser/control/index.d.cts +1 -14
- package/dist/browser/control/index.d.ts +1 -14
- package/dist/browser/control/index.js +1 -1
- package/dist/browser/{index-DOlaPX7h.d.cts → index-BuSW8KtX.d.cts} +2 -2
- package/dist/browser/{index-DI_Uur6m.d.ts → index-DlpszmpD.d.ts} +2 -2
- package/dist/browser/{index.browser-CDI1ZMFY.d.cts → index.browser-B7J1hNLv.d.cts} +1 -1
- package/dist/browser/{index.browser-Bl_A-0Oi.d.ts → index.browser-DTgCIWGS.d.ts} +1 -1
- package/dist/browser/react/index.browser.d.cts +3 -3
- package/dist/browser/react/index.browser.d.ts +3 -3
- package/dist/browser/{types-BLp0Jj7t.d.ts → types-DUs3b5a3.d.cts} +0 -6
- package/dist/browser/{types-BqlgEayM.d.cts → types-keN8L-ZK.d.ts} +0 -6
- package/dist/cli/{chat-manager-DZ9QZlwl.js → chat-manager-CZFcRdLU.js} +1 -1
- package/dist/cli/{dev-9tnTg1In.js → dev-DnkYQ26a.js} +43 -49
- package/dist/cli/index.js +2 -2
- package/dist/cli/{init-Dw0vfw4Q.js → init-DFXOMY0k.js} +2 -2
- package/dist/cli/{run-3J2fAygU.js → run-Bsh7xK4H.js} +1 -1
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.d.cts +1 -1
- package/dist/node/agent/index.node.d.ts +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/{index.node-DcnbPo29.d.ts → index.node-B-Qt76A7.d.ts} +0 -6
- package/dist/node/{index.node-Pp_tfHk8.d.cts → index.node-ChGmUBWY.d.cts} +0 -6
- package/dist/node/{index.node-BMk549Xd.cjs → index.node-CziivD-D.cjs} +30 -30
- package/dist/node/{index.node-fEk-5iyZ.js → index.node-X0B5XDkx.js} +30 -30
- package/dist/node/react/index.node.cjs +2 -2
- package/dist/node/react/index.node.d.cts +2 -1
- package/dist/node/react/index.node.d.ts +2 -1
- package/dist/node/react/index.node.js +2 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "../../types-
|
|
2
|
-
import { StreamResponseFormatHeader } from "../../index.browser-
|
|
3
|
-
import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, streamSSE } from "../../index-
|
|
1
|
+
import "../../types-DUs3b5a3.cjs";
|
|
2
|
+
import { StreamResponseFormatHeader } from "../../index.browser-B7J1hNLv.cjs";
|
|
3
|
+
import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, streamSSE } from "../../index-BuSW8KtX.cjs";
|
|
4
4
|
export { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, StreamResponseFormatHeader, streamSSE };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "../../types-
|
|
2
|
-
import { StreamResponseFormatHeader } from "../../index.browser-
|
|
3
|
-
import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, streamSSE } from "../../index-
|
|
1
|
+
import "../../types-keN8L-ZK.js";
|
|
2
|
+
import { StreamResponseFormatHeader } from "../../index.browser-DTgCIWGS.js";
|
|
3
|
+
import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, streamSSE } from "../../index-DlpszmpD.js";
|
|
4
4
|
export { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, StreamResponseFormatHeader, streamSSE };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { AgentChat, AgentOtel, AgentStore, Chat, ChatEvent, ChatHandler, ChatResponse, ID, NewMessage, SendBehavior, SendOptions, UpsertedChat } from "../types-
|
|
2
|
-
import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-
|
|
1
|
+
import { AgentChat, AgentOtel, AgentStore, Chat, ChatEvent, ChatHandler, ChatResponse, ID, NewMessage, SendBehavior, SendOptions, UpsertedChat } from "../types-DUs3b5a3.cjs";
|
|
2
|
+
import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-B7J1hNLv.cjs";
|
|
3
3
|
export { AgentChat, AgentOtel, AgentStore, Chat, ChatEvent, ChatHandler, ChatResponse, ContextFromTools, ExtractUIOptions, ID, NewMessage, SendBehavior, SendOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, UpsertedChat, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { AgentChat, AgentOtel, AgentStore, Chat, ChatEvent, ChatHandler, ChatResponse, ID, NewMessage, SendBehavior, SendOptions, UpsertedChat } from "../types-
|
|
2
|
-
import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-
|
|
1
|
+
import { AgentChat, AgentOtel, AgentStore, Chat, ChatEvent, ChatHandler, ChatResponse, ID, NewMessage, SendBehavior, SendOptions, UpsertedChat } from "../types-keN8L-ZK.js";
|
|
2
|
+
import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-DTgCIWGS.js";
|
|
3
3
|
export { AgentChat, AgentOtel, AgentStore, Chat, ChatEvent, ChatHandler, ChatResponse, ContextFromTools, ExtractUIOptions, ID, NewMessage, SendBehavior, SendOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, UpsertedChat, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`../cookie-BEyEPQZM.cjs`);var t=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},n=Symbol(),r=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,a=(e instanceof l?e.raw.headers:e.headers).get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?i(e,{all:n,dot:r}):{}};async function i(e,t){let n=await e.formData();return n?a(n,t):{}}function a(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?o(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(s(n,e,t),delete n[e])}),n}var o=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},s=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},c=t=>e.tryDecode(t,e.decodeURIComponent_),l=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?c(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?c(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await r(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[n](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},u={Stringify:1,BeforeStream:2,Stream:3},d=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},f=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>f(e,t,!1,r,i))).then(()=>i[0]));return n?d(await o,a):o},p=`text/plain; charset=UTF-8`,m=(e,t)=>({"Content-Type":e,...t}),h=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new l(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,m(p,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,m(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,m(`text/html; charset=UTF-8`,n));return typeof e==`object`?f(e,u.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},g=`ALL`,_=`all`,ee=[`get`,`post`,`put`,`delete`,`options`,`patch`],v=`Can not add a route since the matcher is already built.`,y=class extends Error{},b=`__COMPOSED_HANDLER`,x=e=>e.text(`404 Not Found`,404),S=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},C=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){[...ee,_].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(g,this.#path,e)}),this);let{strict:n,...r}=t;Object.assign(this,r),this.getPath=n??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new C({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=x;errorHandler=S;route(e,n){let r=this.basePath(e);return n.routes.map(e=>{let i;n.errorHandler===S?i=e.handler:(i=async(r,i)=>(await t([],n.errorHandler)(r,()=>e.handler(r,i))).res,i[b]=e.handler),r.#addRoute(e.method,e.path,i)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})(),this.#addRoute(g,e.mergePath(t,`*`),async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()}),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,n,r,`GET`)))();let a=this.getPath(e,{env:r}),o=this.router.match(i,a),s=new h(e,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=t(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},w=`[^/]+`,T=`.*`,E=`(?:|/.*)`,D=Symbol(),O=new Set(`.\\+*[^]$()`);function te(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===T||e===E?1:t===T||t===E?-1:e===w?1:t===w?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var k=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw D;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,T]:[``,``,w]:a===`/*`?[``,``,E]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||w;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw D;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==T&&e!==E))throw D;if(i)return;c=this.#children[t]=new k,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==T&&e!==E))throw D;if(i)return;c=this.#children[a]=new k}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(te).map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:O.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&e.unshift(`#${this.#index}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},A=class{#context={varIndex:0};#root=new k;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},j=[],M=[/^$/,[],Object.create(null)],N=Object.create(null);function P(e){return N[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function F(){N=Object.create(null)}function I(e){let t=new A,n=[];if(e.length===0)return M;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),j]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===D?new y(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function L(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(P(n).test(t))return[...e[n]]}}var ne=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[g]:Object.create(null)},this.#routes={[g]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(v);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[g]).forEach(n=>{e[t][n]=[...e[g][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=P(n);t===g?Object.keys(i).forEach(e=>{i[e][n]||=L(i[e],n)||L(i[g],n)||[]}):i[t][n]||=L(i[t],n)||L(i[g],n)||[],Object.keys(i).forEach(n=>{(t===g||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===g||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===g||t===s)&&(a[s][c]||=[...L(i[s],c)||L(i[g],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){F();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[g],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],j];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===g;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==g&&t.push(...Object.keys(r[g]).map(e=>[e,r[g][e]])):(n||=!0,t.push(...i))}),n?I(t):null}},R=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(v);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof y)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new B,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[g],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=z;let i=[this],a=e.splitPath(n),o=[];for(let e=0,n=a.length;e<n;e++){let s=a[e],c=e===n-1,l=[];for(let n=0,u=i.length;n<u;n++){let u=i[n],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,i=u.#patterns.length;n<i;n++){let i=u.#patterns[n],d=u.#params===z?{}:{...u.#params};if(i===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0;(o[t]||=[]).push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},V=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},H=class extends C{constructor(e={}){super(e),this.router=e.router??new R({routers:[new ne,new V]})}},U=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;return r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n),e.parse(i,t)[t]}return i?e.parse(i):{}},W=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},G=(e,t)=>new Response(e,{headers:{"Content-Type":t}}).formData(),K=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,q=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,J=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!K.test(a))break;try{i=await n.req.json()}catch{throw new W(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(q.test(a)||J.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await G(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new W(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=U(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Q=()=>new H,re=Q().get(`/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?X(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),ie=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},$=Y(`param`,e=>({id:e.id})),ae=Q().post(`/:key`,async e=>{let{key:t,err:n}=ie(e);return n?X(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,$,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,$,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,Y(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):X(e,`ID is required`)}).delete(`/:id/messages`,$,Y(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).post(`/:id/reset`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.reset(t),e.body(null,204)}).delete(`/:id`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),oe=Q().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),se=new H().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,re).route(`/chat`,ae).route(`/otlp`,oe);exports.api=se;
|
|
1
|
+
const e=require(`../cookie-BEyEPQZM.cjs`);var t=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},n=Symbol(),r=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,a=(e instanceof l?e.raw.headers:e.headers).get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?i(e,{all:n,dot:r}):{}};async function i(e,t){let n=await e.formData();return n?a(n,t):{}}function a(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?o(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(s(n,e,t),delete n[e])}),n}var o=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},s=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},c=t=>e.tryDecode(t,e.decodeURIComponent_),l=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?c(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?c(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await r(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[n](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},u={Stringify:1,BeforeStream:2,Stream:3},d=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},f=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>f(e,t,!1,r,i))).then(()=>i[0]));return n?d(await o,a):o},p=`text/plain; charset=UTF-8`,m=(e,t)=>({"Content-Type":e,...t}),h=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new l(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,m(p,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,m(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,m(`text/html; charset=UTF-8`,n));return typeof e==`object`?f(e,u.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},g=`ALL`,_=`all`,ee=[`get`,`post`,`put`,`delete`,`options`,`patch`],v=`Can not add a route since the matcher is already built.`,y=class extends Error{},b=`__COMPOSED_HANDLER`,x=e=>e.text(`404 Not Found`,404),S=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},C=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){[...ee,_].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(g,this.#path,e)}),this);let{strict:n,...r}=t;Object.assign(this,r),this.getPath=n??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new C({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=x;errorHandler=S;route(e,n){let r=this.basePath(e);return n.routes.map(e=>{let i;n.errorHandler===S?i=e.handler:(i=async(r,i)=>(await t([],n.errorHandler)(r,()=>e.handler(r,i))).res,i[b]=e.handler),r.#addRoute(e.method,e.path,i)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})(),this.#addRoute(g,e.mergePath(t,`*`),async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()}),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,n,r,`GET`)))();let a=this.getPath(e,{env:r}),o=this.router.match(i,a),s=new h(e,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=t(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},w=`[^/]+`,T=`.*`,E=`(?:|/.*)`,D=Symbol(),O=new Set(`.\\+*[^]$()`);function te(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===T||e===E?1:t===T||t===E?-1:e===w?1:t===w?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var k=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw D;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,T]:[``,``,w]:a===`/*`?[``,``,E]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||w;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw D;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==T&&e!==E))throw D;if(i)return;c=this.#children[t]=new k,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==T&&e!==E))throw D;if(i)return;c=this.#children[a]=new k}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(te).map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:O.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&e.unshift(`#${this.#index}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},A=class{#context={varIndex:0};#root=new k;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},j=[],M=[/^$/,[],Object.create(null)],N=Object.create(null);function P(e){return N[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function F(){N=Object.create(null)}function I(e){let t=new A,n=[];if(e.length===0)return M;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),j]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===D?new y(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function L(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(P(n).test(t))return[...e[n]]}}var ne=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[g]:Object.create(null)},this.#routes={[g]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(v);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[g]).forEach(n=>{e[t][n]=[...e[g][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=P(n);t===g?Object.keys(i).forEach(e=>{i[e][n]||=L(i[e],n)||L(i[g],n)||[]}):i[t][n]||=L(i[t],n)||L(i[g],n)||[],Object.keys(i).forEach(n=>{(t===g||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===g||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===g||t===s)&&(a[s][c]||=[...L(i[s],c)||L(i[g],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){F();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[g],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],j];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===g;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==g&&t.push(...Object.keys(r[g]).map(e=>[e,r[g][e]])):(n||=!0,t.push(...i))}),n?I(t):null}},R=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(v);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof y)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new B,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[g],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=z;let i=[this],a=e.splitPath(n),o=[];for(let e=0,n=a.length;e<n;e++){let s=a[e],c=e===n-1,l=[];for(let n=0,u=i.length;n<u;n++){let u=i[n],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,i=u.#patterns.length;n<i;n++){let i=u.#patterns[n],d=u.#params===z?{}:{...u.#params};if(i===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0;(o[t]||=[]).push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},V=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},H=class extends C{constructor(e={}){super(e),this.router=e.router??new R({routers:[new ne,new V]})}},U=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;return r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n),e.parse(i,t)[t]}return i?e.parse(i):{}},W=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},G=(e,t)=>new Response(e,{headers:{"Content-Type":t}}).formData(),K=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,q=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,J=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!K.test(a))break;try{i=await n.req.json()}catch{throw new W(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(q.test(a)||J.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await G(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new W(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=U(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Q=()=>new H,re=Q().get(`/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?X(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),ie=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},$=Y(`param`,e=>({id:e.id})),ae=Q().post(`/:key`,async e=>{let{key:t,err:n}=ie(e);return n?X(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,$,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,$,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,Y(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):X(e,`ID is required`)}).delete(`/:id/messages`,$,Y(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,$,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),oe=Q().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),se=new H().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,re).route(`/chat`,ae).route(`/otlp`,oe);exports.api=se;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentChat, AgentOtel, AgentStore, ID, NewMessage, SendOptions } from "../types-
|
|
1
|
+
import { AgentChat, AgentOtel, AgentStore, ID, NewMessage, SendOptions } from "../types-DUs3b5a3.cjs";
|
|
2
2
|
import { UIMessage } from "ai";
|
|
3
3
|
import * as hono_types0 from "hono/types";
|
|
4
4
|
import * as hono_utils_http_status0 from "hono/utils/http-status";
|
|
@@ -405,19 +405,6 @@ declare const api: hono_hono_base0.HonoBase<{
|
|
|
405
405
|
status: 204;
|
|
406
406
|
};
|
|
407
407
|
};
|
|
408
|
-
} & {
|
|
409
|
-
"/:id/reset": {
|
|
410
|
-
$post: {
|
|
411
|
-
input: {
|
|
412
|
-
param: {
|
|
413
|
-
id: string;
|
|
414
|
-
};
|
|
415
|
-
};
|
|
416
|
-
output: null;
|
|
417
|
-
outputFormat: "body";
|
|
418
|
-
status: 204;
|
|
419
|
-
};
|
|
420
|
-
};
|
|
421
408
|
} & {
|
|
422
409
|
"/:id": {
|
|
423
410
|
$delete: {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentChat, AgentOtel, AgentStore, ID, NewMessage, SendOptions } from "../types-
|
|
1
|
+
import { AgentChat, AgentOtel, AgentStore, ID, NewMessage, SendOptions } from "../types-keN8L-ZK.js";
|
|
2
2
|
import { UIMessage } from "ai";
|
|
3
3
|
import * as hono_types0 from "hono/types";
|
|
4
4
|
import * as hono_utils_http_status0 from "hono/utils/http-status";
|
|
@@ -405,19 +405,6 @@ declare const api: hono_hono_base0.HonoBase<{
|
|
|
405
405
|
status: 204;
|
|
406
406
|
};
|
|
407
407
|
};
|
|
408
|
-
} & {
|
|
409
|
-
"/:id/reset": {
|
|
410
|
-
$post: {
|
|
411
|
-
input: {
|
|
412
|
-
param: {
|
|
413
|
-
id: string;
|
|
414
|
-
};
|
|
415
|
-
};
|
|
416
|
-
output: null;
|
|
417
|
-
outputFormat: "body";
|
|
418
|
-
status: 204;
|
|
419
|
-
};
|
|
420
|
-
};
|
|
421
408
|
} & {
|
|
422
409
|
"/:id": {
|
|
423
410
|
$delete: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{checkOptionalParameter as e,decodeURIComponent_ as t,getPath as n,getPathNoStrict as r,getPattern as i,getQueryParam as a,getQueryParams as o,mergePath as s,parse as c,splitPath as l,splitRoutingPath as u,tryDecode as d}from"../cookie-C6gQJ2Nm.js";var f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(e instanceof y?e.raw.headers:e.headers).get(`Content-Type`);return i?.startsWith(`multipart/form-data`)||i?.startsWith(`application/x-www-form-urlencoded`)?h(e,{all:n,dot:r}):{}};async function h(e,t){let n=await e.formData();return n?g(n,t):{}}function g(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(_(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},v=e=>d(e,t),y=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?v(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?v(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return a(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},b=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>b(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},x=`text/plain; charset=UTF-8`,S=(e,t)=>({"Content-Type":e,...t}),re=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new y(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,S(x,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,S(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,S(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},C=`ALL`,ie=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],w=`Can not add a route since the matcher is already built.`,T=class extends Error{},E=`__COMPOSED_HANDLER`,D=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){[...ae,ie].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(C,this.#path,e)}),this);let{strict:t,...i}=e;Object.assign(this,i),this.getPath=t??!0?e.getPath??n:r}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=D;errorHandler=O;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===O?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[E]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=s(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=s(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})(),this.#addRoute(C,s(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#addRoute(e,t,n){e=e.toUpperCase(),t=s(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new re(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),oe=new Set(`.\\+*[^]$()`);function se(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(se).map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:oe.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&e.unshift(`#${this.#index}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},ce=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],I=[/^$/,[],Object.create(null)],L=Object.create(null);function R(e){return L[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function z(){L=Object.create(null)}function B(e){let t=new ce,n=[];if(e.length===0)return I;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new T(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function V(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(R(n).test(t))return[...e[n]]}}var H=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[C]:Object.create(null)},this.#routes={[C]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(w);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[C]).forEach(n=>{e[t][n]=[...e[C][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===C?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[C],n)||[]}):i[t][n]||=V(i[t],n)||V(i[C],n)||[],Object.keys(i).forEach(n=>{(t===C||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===C||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===C||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[C],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){z();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[C],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===C;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==C&&t.push(...Object.keys(r[C]).map(e=>[e,r[C][e]])):(n||=!0,t.push(...i))}),n?B(t):null}},U=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(w);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof T)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,a=u(t),o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e],n=a[e+1],s=i(t,n),c=Array.isArray(s)?s[0]:t;if(c in r.#children){r=r.#children[c],s&&o.push(s[1]);continue}r.#children[c]=new G,s&&(r.#patterns.push(s),o.push(s[1])),r=r.#children[c]}return r.#methods.push({[e]:{handler:n,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[C],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=[this],i=l(t),a=[];for(let t=0,o=i.length;t<o;t++){let s=i[t],c=t===o-1,l=[];for(let o=0,u=r.length;o<u;o++){let u=r[o],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,o=u.#patterns.length;r<o;r++){let o=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(o===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=o;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=i.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0;(a[e]||=[]).push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}r=l.concat(a.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;return n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t),c(r,e)[e]}return r?c(r):{}},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},de=(e,t)=>new Response(e,{headers:{"Content-Type":t}}).formData(),fe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,pe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!fe.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(pe.test(a)||me.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await de(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ue(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Y=(e,t)=>e.json({error:t},400),X=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Z=()=>new K,he=Z().get(`/:key`,async e=>{let{key:t,err:n}=X(e);if(n)return Y(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Y(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Y(t,`Value must be a string`):Y(t,`Value is required`)}),async e=>{let{key:t,err:n}=X(e);if(n)return Y(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=X(e);return n?Y(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),ge=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},Q=J(`param`,e=>({id:e.id})),$=Z().post(`/:key`,async e=>{let{key:t,err:n}=ge(e);return n?Y(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Q,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Q,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,J(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Y(e,`ID is required`)}).delete(`/:id/messages`,Q,J(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).post(`/:id/reset`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.reset(t),e.body(null,204)}).delete(`/:id`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),_e=Z().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ve=new K().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,he).route(`/chat`,$).route(`/otlp`,_e);export{ve as api};
|
|
1
|
+
import{checkOptionalParameter as e,decodeURIComponent_ as t,getPath as n,getPathNoStrict as r,getPattern as i,getQueryParam as a,getQueryParams as o,mergePath as s,parse as c,splitPath as l,splitRoutingPath as u,tryDecode as d}from"../cookie-C6gQJ2Nm.js";var f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(e instanceof y?e.raw.headers:e.headers).get(`Content-Type`);return i?.startsWith(`multipart/form-data`)||i?.startsWith(`application/x-www-form-urlencoded`)?h(e,{all:n,dot:r}):{}};async function h(e,t){let n=await e.formData();return n?g(n,t):{}}function g(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(_(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},v=e=>d(e,t),y=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?v(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?v(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return a(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},b=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>b(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},x=`text/plain; charset=UTF-8`,S=(e,t)=>({"Content-Type":e,...t}),re=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new y(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,S(x,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,S(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,S(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},C=`ALL`,ie=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],w=`Can not add a route since the matcher is already built.`,T=class extends Error{},E=`__COMPOSED_HANDLER`,D=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){[...ae,ie].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(C,this.#path,e)}),this);let{strict:t,...i}=e;Object.assign(this,i),this.getPath=t??!0?e.getPath??n:r}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=D;errorHandler=O;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===O?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[E]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=s(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=s(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})(),this.#addRoute(C,s(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#addRoute(e,t,n){e=e.toUpperCase(),t=s(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new re(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),oe=new Set(`.\\+*[^]$()`);function se(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(se).map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:oe.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&e.unshift(`#${this.#index}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},ce=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],I=[/^$/,[],Object.create(null)],L=Object.create(null);function R(e){return L[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function z(){L=Object.create(null)}function B(e){let t=new ce,n=[];if(e.length===0)return I;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new T(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function V(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(R(n).test(t))return[...e[n]]}}var H=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[C]:Object.create(null)},this.#routes={[C]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(w);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[C]).forEach(n=>{e[t][n]=[...e[C][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===C?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[C],n)||[]}):i[t][n]||=V(i[t],n)||V(i[C],n)||[],Object.keys(i).forEach(n=>{(t===C||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===C||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===C||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[C],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){z();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[C],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===C;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==C&&t.push(...Object.keys(r[C]).map(e=>[e,r[C][e]])):(n||=!0,t.push(...i))}),n?B(t):null}},U=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(w);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof T)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,a=u(t),o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e],n=a[e+1],s=i(t,n),c=Array.isArray(s)?s[0]:t;if(c in r.#children){r=r.#children[c],s&&o.push(s[1]);continue}r.#children[c]=new G,s&&(r.#patterns.push(s),o.push(s[1])),r=r.#children[c]}return r.#methods.push({[e]:{handler:n,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[C],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=[this],i=l(t),a=[];for(let t=0,o=i.length;t<o;t++){let s=i[t],c=t===o-1,l=[];for(let o=0,u=r.length;o<u;o++){let u=r[o],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,o=u.#patterns.length;r<o;r++){let o=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(o===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=o;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=i.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0;(a[e]||=[]).push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}r=l.concat(a.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;return n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t),c(r,e)[e]}return r?c(r):{}},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},de=(e,t)=>new Response(e,{headers:{"Content-Type":t}}).formData(),fe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,pe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!fe.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(pe.test(a)||me.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await de(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ue(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Y=(e,t)=>e.json({error:t},400),X=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Z=()=>new K,he=Z().get(`/:key`,async e=>{let{key:t,err:n}=X(e);if(n)return Y(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Y(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Y(t,`Value must be a string`):Y(t,`Value is required`)}),async e=>{let{key:t,err:n}=X(e);if(n)return Y(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=X(e);return n?Y(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),ge=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},Q=J(`param`,e=>({id:e.id})),$=Z().post(`/:key`,async e=>{let{key:t,err:n}=ge(e);return n?Y(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Q,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Q,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,J(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Y(e,`ID is required`)}).delete(`/:id/messages`,Q,J(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,Q,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),_e=Z().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ve=new K().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,he).route(`/chat`,$).route(`/otlp`,_e);export{ve as api};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ID } from "./types-
|
|
2
|
-
import { UIOptions, UIOptionsSchema } from "./index.browser-
|
|
1
|
+
import { ID } from "./types-DUs3b5a3.cjs";
|
|
2
|
+
import { UIOptions, UIOptionsSchema } from "./index.browser-B7J1hNLv.cjs";
|
|
3
3
|
import { UIMessage, UIMessageChunk } from "ai";
|
|
4
4
|
|
|
5
5
|
//#region src/agent/client/index.d.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ID } from "./types-
|
|
2
|
-
import { UIOptions, UIOptionsSchema } from "./index.browser-
|
|
1
|
+
import { ID } from "./types-keN8L-ZK.js";
|
|
2
|
+
import { UIOptions, UIOptionsSchema } from "./index.browser-DTgCIWGS.js";
|
|
3
3
|
import { UIMessage, UIMessageChunk } from "ai";
|
|
4
4
|
|
|
5
5
|
//#region src/agent/client/index.d.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../types-
|
|
2
|
-
import { UIOptions, UIOptionsSchema } from "../index.browser-
|
|
3
|
-
import { CapabilitiesResponse, Client } from "../index-
|
|
1
|
+
import "../types-DUs3b5a3.cjs";
|
|
2
|
+
import { UIOptions, UIOptionsSchema } from "../index.browser-B7J1hNLv.cjs";
|
|
3
|
+
import { CapabilitiesResponse, Client } from "../index-BuSW8KtX.cjs";
|
|
4
4
|
import { UIMessage } from "ai";
|
|
5
5
|
|
|
6
6
|
//#region src/react/use-options.d.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../types-
|
|
2
|
-
import { UIOptions, UIOptionsSchema } from "../index.browser-
|
|
3
|
-
import { CapabilitiesResponse, Client } from "../index-
|
|
1
|
+
import "../types-keN8L-ZK.js";
|
|
2
|
+
import { UIOptions, UIOptionsSchema } from "../index.browser-DTgCIWGS.js";
|
|
3
|
+
import { CapabilitiesResponse, Client } from "../index-DlpszmpD.js";
|
|
4
4
|
import { UIMessage } from "ai";
|
|
5
5
|
|
|
6
6
|
//#region src/react/use-options.d.ts
|
|
@@ -107,12 +107,6 @@ interface AgentChat<MESSAGE extends UIMessage = UIMessage> {
|
|
|
107
107
|
* @param id the ID of the chat.
|
|
108
108
|
*/
|
|
109
109
|
stop(id: ID): Promise<void>;
|
|
110
|
-
/**
|
|
111
|
-
* Reset a chat.
|
|
112
|
-
*
|
|
113
|
-
* @param id the ID of the chat.
|
|
114
|
-
*/
|
|
115
|
-
reset(id: ID): Promise<void>;
|
|
116
110
|
/**
|
|
117
111
|
* Delete a chat.
|
|
118
112
|
*
|
|
@@ -107,12 +107,6 @@ interface AgentChat<MESSAGE extends UIMessage = UIMessage> {
|
|
|
107
107
|
* @param id the ID of the chat.
|
|
108
108
|
*/
|
|
109
109
|
stop(id: ID): Promise<void>;
|
|
110
|
-
/**
|
|
111
|
-
* Reset a chat.
|
|
112
|
-
*
|
|
113
|
-
* @param id the ID of the chat.
|
|
114
|
-
*/
|
|
115
|
-
reset(id: ID): Promise<void>;
|
|
116
110
|
/**
|
|
117
111
|
* Delete a chat.
|
|
118
112
|
*
|