blink 0.1.66 → 0.1.68

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.
@@ -1,6 +1,8 @@
1
1
  import { Chat, ChatBehavior, Message } from "../index.browser-Db4eudpn.js";
2
2
  import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, streamSSE } from "../client-J5gD4j_a.js";
3
3
  import { UIMessageChunk } from "ai";
4
+ import * as hono_types0 from "hono/types";
5
+ import * as hono_hono_base0 from "hono/hono-base";
4
6
 
5
7
  //#region src/http/async-iterable-stream.d.ts
6
8
  /**
@@ -52,9 +54,154 @@ type APIBindings = {
52
54
  * server.listen(options.port);
53
55
  * ```
54
56
  */
57
+ declare const api: hono_hono_base0.HonoBase<{
58
+ Bindings: APIBindings;
59
+ }, hono_types0.BlankSchema | hono_types0.MergeSchemaPath<{
60
+ "/kv/:key": {
61
+ $get: {
62
+ input: {
63
+ param: {
64
+ key: string;
65
+ };
66
+ };
67
+ output: {
68
+ error: string;
69
+ };
70
+ outputFormat: "json";
71
+ status: 400;
72
+ } | {
73
+ input: {
74
+ param: {
75
+ key: string;
76
+ };
77
+ };
78
+ output: {
79
+ value: string | undefined;
80
+ };
81
+ outputFormat: "json";
82
+ status: 200;
83
+ };
84
+ };
85
+ } & {
86
+ "/kv/:key": {
87
+ $post: {
88
+ input: {
89
+ json: {
90
+ value: string;
91
+ };
92
+ } & {
93
+ param: {
94
+ key: string;
95
+ };
96
+ };
97
+ output: {
98
+ error: string;
99
+ };
100
+ outputFormat: "json";
101
+ status: 400;
102
+ } | {
103
+ input: {
104
+ json: {
105
+ value: string;
106
+ };
107
+ } & {
108
+ param: {
109
+ key: string;
110
+ };
111
+ };
112
+ output: null;
113
+ outputFormat: "body";
114
+ status: 204;
115
+ };
116
+ };
117
+ } & {
118
+ "/kv/:key": {
119
+ $delete: {
120
+ input: {
121
+ param: {
122
+ key: string;
123
+ };
124
+ };
125
+ output: {
126
+ error: string;
127
+ };
128
+ outputFormat: "json";
129
+ status: 400;
130
+ } | {
131
+ input: {
132
+ param: {
133
+ key: string;
134
+ };
135
+ };
136
+ output: null;
137
+ outputFormat: "body";
138
+ status: 204;
139
+ };
140
+ };
141
+ }, "/storage"> | hono_types0.MergeSchemaPath<{
142
+ "/:id": {
143
+ $post: {
144
+ input: {
145
+ param: {
146
+ id: string;
147
+ };
148
+ };
149
+ output: {
150
+ error: string;
151
+ };
152
+ outputFormat: "json";
153
+ status: 400;
154
+ } | {
155
+ input: {
156
+ param: {
157
+ id: string;
158
+ };
159
+ };
160
+ output: {
161
+ id: string;
162
+ };
163
+ outputFormat: "json";
164
+ status: 200;
165
+ };
166
+ };
167
+ } & {
168
+ "/:id/sendMessages": {
169
+ $post: {
170
+ input: {
171
+ json: {
172
+ messages: Message[];
173
+ behavior: ChatBehavior;
174
+ };
175
+ } & {
176
+ param: {
177
+ id: string;
178
+ };
179
+ };
180
+ output: {
181
+ error: string;
182
+ };
183
+ outputFormat: "json";
184
+ status: 400;
185
+ } | {
186
+ input: {
187
+ json: {
188
+ messages: Message[];
189
+ behavior: ChatBehavior;
190
+ };
191
+ } & {
192
+ param: {
193
+ id: string;
194
+ };
195
+ };
196
+ output: null;
197
+ outputFormat: "body";
198
+ status: 204;
199
+ };
200
+ };
201
+ }, "/chat">, "/">;
55
202
  //#endregion
56
203
  //#region src/http/convert-response-to-ui-message-stream.d.ts
57
204
  type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
58
205
  declare function convertResponseToUIMessageStream(response: Response): ReadableStream<UIMessageChunk>;
59
206
  //#endregion
60
- export { APIBindings, APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormat, StreamResponseFormatHeader, convertResponseToUIMessageStream, createAsyncIterableStream, streamSSE };
207
+ export { APIBindings, APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormat, StreamResponseFormatHeader, api, convertResponseToUIMessageStream, createAsyncIterableStream, streamSSE };
@@ -1 +1 @@
1
- import{APIServerURLEnvironmentVariable as e,Client as t,StreamResponseFormatHeader as n,checkOptionalParameter as r,convertResponseToUIMessageStream as i,decodeURIComponent_ as a,getPath as o,getPathNoStrict as s,getPattern as c,getQueryParam as l,getQueryParams as u,mergePath as d,parse as f,splitPath as p,splitRoutingPath as m,streamSSE as h,tryDecode as g}from"../client-DsiYP47H.js";function ee(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}var _=(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}},te=Symbol(),ne=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof x?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?re(e,{all:n,dot:r}):{}};async function re(e,t){let n=await e.formData();return n?v(n,t):{}}function v(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?y(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(ie(n,e,t),delete n[e])}),n}var y=(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]},ie=(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])})},b=e=>g(e,a),x=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)?b(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)?b(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return l(this.url,e)}queries(e){return u(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 ne(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[te](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ae={Stringify:1,BeforeStream:2,Stream:3},S=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},C=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=>C(e,t,!1,r,i))).then(()=>i[0]));return n?S(await o,a):o},w=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),oe=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 x(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`)continue;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,T(w,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?C(e,ae.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))},E=`ALL`,se=`all`,D=[`get`,`post`,`put`,`delete`,`options`,`patch`],O=`Can not add a route since the matcher is already built.`,k=class extends Error{},ce=`__COMPOSED_HANDLER`,le=e=>e.text(`404 Not Found`,404),A=(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)},j=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...D,se];t.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(E,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??o:s}#clone(){let e=new j({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=le;errorHandler=A;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===A?r=e.handler:(r=async(n,r)=>(await _([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ce]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=d(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]};r||=(()=>{let t=d(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)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(E,d(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=d(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 oe(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=_(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${d(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},M=`[^/]+`,N=`.*`,P=`(?:|/.*)`,F=Symbol(),I=new Set(`.\\+*[^]$()`);function L(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===N||e===P?1:t===N||t===P?-1:e===M?1:t===M?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var R=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw F;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,N]:[``,``,M]:a===`/*`?[``,``,P]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||M;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw F;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==N&&e!==P))throw F;if(i)return;c=this.#children[t]=new R,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!==N&&e!==P))throw F;if(i)return;c=this.#children[a]=new R}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(L),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:I.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},z=class{#context={varIndex:0};#root=new R;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]}},B=[],V=[/^$/,[],Object.create(null)],H=Object.create(null);function U(e){return H[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function ue(){H=Object.create(null)}function de(e){let t=new z,n=[];if(e.length===0)return V;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)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===F?new k(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 W(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(U(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[E]:Object.create(null)},this.#routes={[E]:Object.create(null)}}add(e,t,n){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(O);i[e]||[i,a].forEach(t=>{t[e]=Object.create(null),Object.keys(t[E]).forEach(n=>{t[e][n]=[...t[E][n]]})}),t===`/*`&&(t=`*`);let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let r=U(t);e===E?Object.keys(i).forEach(e=>{i[e][t]||=W(i[e],t)||W(i[E],t)||[]}):i[e][t]||=W(i[e],t)||W(i[E],t)||[],Object.keys(i).forEach(t=>{(e===E||e===t)&&Object.keys(i[t]).forEach(e=>{r.test(e)&&i[t][e].push([n,o])})}),Object.keys(a).forEach(t=>{(e===E||e===t)&&Object.keys(a[t]).forEach(e=>r.test(e)&&a[t][e].push([n,o]))});return}let s=r(t)||[t];for(let t=0,r=s.length;t<r;t++){let c=s[t];Object.keys(a).forEach(s=>{(e===E||e===s)&&(a[s][c]||=[...W(i[s],c)||W(i[E],c)||[]],a[s][c].push([n,o-r+t+1]))})}}match(e,t){ue();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[E],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];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===E;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!==E&&t.push(...Object.keys(r[E]).map(e=>[e,r[E][e]])):(n||=!0,t.push(...i))}),n?de(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(O);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 k)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]}},G=Object.create(null),K=class{#methods;#children;#patterns;#order=0;#params=G;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,i=m(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=c(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new K,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.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[E],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==G||r&&r!==G))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=G;let r=this,i=[r],a=p(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],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,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===G?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.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,n=o[e]||=[];n.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)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new K}add(e,t,n){let i=r(t);if(i){for(let t=0,r=i.length;t<r;t++)this.#node.insert(e,i[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},q=class extends j{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=f(r,e);return i[e]}if(!r)return{};let i=f(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ge=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},_e=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ve=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ye=/^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||!_e.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ve.test(a)||ye.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 ge(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(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=he(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>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new q,be=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 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.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},xe=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)});new q().route(`/storage`,be).route(`/chat`,xe);export{e as APIServerURLEnvironmentVariable,t as Client,n as StreamResponseFormatHeader,i as convertResponseToUIMessageStream,ee as createAsyncIterableStream,h as streamSSE};
1
+ import{APIServerURLEnvironmentVariable as e,Client as t,StreamResponseFormatHeader as n,checkOptionalParameter as r,convertResponseToUIMessageStream as i,decodeURIComponent_ as a,getPath as o,getPathNoStrict as s,getPattern as c,getQueryParam as l,getQueryParams as u,mergePath as d,parse as f,splitPath as p,splitRoutingPath as m,streamSSE as h,tryDecode as g}from"../client-BbZudkEc.js";function ee(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}var _=(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}},te=Symbol(),ne=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof x?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?re(e,{all:n,dot:r}):{}};async function re(e,t){let n=await e.formData();return n?v(n,t):{}}function v(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?y(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(ie(n,e,t),delete n[e])}),n}var y=(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]},ie=(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])})},b=e=>g(e,a),x=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)?b(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)?b(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return l(this.url,e)}queries(e){return u(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 ne(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[te](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ae={Stringify:1,BeforeStream:2,Stream:3},S=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},C=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=>C(e,t,!1,r,i))).then(()=>i[0]));return n?S(await o,a):o},w=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),oe=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 x(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`)continue;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,T(w,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?C(e,ae.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))},E=`ALL`,se=`all`,D=[`get`,`post`,`put`,`delete`,`options`,`patch`],O=`Can not add a route since the matcher is already built.`,k=class extends Error{},ce=`__COMPOSED_HANDLER`,le=e=>e.text(`404 Not Found`,404),A=(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)},j=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...D,se];t.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(E,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??o:s}#clone(){let e=new j({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=le;errorHandler=A;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===A?r=e.handler:(r=async(n,r)=>(await _([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ce]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=d(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]};r||=(()=>{let t=d(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)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(E,d(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=d(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 oe(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=_(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${d(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},M=`[^/]+`,N=`.*`,P=`(?:|/.*)`,F=Symbol(),I=new Set(`.\\+*[^]$()`);function L(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===N||e===P?1:t===N||t===P?-1:e===M?1:t===M?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var R=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw F;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,N]:[``,``,M]:a===`/*`?[``,``,P]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||M;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw F;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==N&&e!==P))throw F;if(i)return;c=this.#children[t]=new R,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!==N&&e!==P))throw F;if(i)return;c=this.#children[a]=new R}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(L),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:I.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},z=class{#context={varIndex:0};#root=new R;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]}},B=[],V=[/^$/,[],Object.create(null)],H=Object.create(null);function U(e){return H[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function ue(){H=Object.create(null)}function de(e){let t=new z,n=[];if(e.length===0)return V;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)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===F?new k(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 W(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(U(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[E]:Object.create(null)},this.#routes={[E]:Object.create(null)}}add(e,t,n){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(O);i[e]||[i,a].forEach(t=>{t[e]=Object.create(null),Object.keys(t[E]).forEach(n=>{t[e][n]=[...t[E][n]]})}),t===`/*`&&(t=`*`);let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let r=U(t);e===E?Object.keys(i).forEach(e=>{i[e][t]||=W(i[e],t)||W(i[E],t)||[]}):i[e][t]||=W(i[e],t)||W(i[E],t)||[],Object.keys(i).forEach(t=>{(e===E||e===t)&&Object.keys(i[t]).forEach(e=>{r.test(e)&&i[t][e].push([n,o])})}),Object.keys(a).forEach(t=>{(e===E||e===t)&&Object.keys(a[t]).forEach(e=>r.test(e)&&a[t][e].push([n,o]))});return}let s=r(t)||[t];for(let t=0,r=s.length;t<r;t++){let c=s[t];Object.keys(a).forEach(s=>{(e===E||e===s)&&(a[s][c]||=[...W(i[s],c)||W(i[E],c)||[]],a[s][c].push([n,o-r+t+1]))})}}match(e,t){ue();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[E],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];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===E;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!==E&&t.push(...Object.keys(r[E]).map(e=>[e,r[E][e]])):(n||=!0,t.push(...i))}),n?de(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(O);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 k)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]}},G=Object.create(null),K=class{#methods;#children;#patterns;#order=0;#params=G;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,i=m(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=c(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new K,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.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[E],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==G||r&&r!==G))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=G;let r=this,i=[r],a=p(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],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,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===G?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.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,n=o[e]||=[];n.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)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new K}add(e,t,n){let i=r(t);if(i){for(let t=0,r=i.length;t<r;t++)this.#node.insert(e,i[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},q=class extends j{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=f(r,e);return i[e]}if(!r)return{};let i=f(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ge=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},_e=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ve=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ye=/^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||!_e.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ve.test(a)||ye.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 ge(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(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=he(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>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new q,be=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 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.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},xe=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),Se=new q().route(`/storage`,be).route(`/chat`,xe);export{e as APIServerURLEnvironmentVariable,t as Client,n as StreamResponseFormatHeader,Se as api,i as convertResponseToUIMessageStream,ee as createAsyncIterableStream,h as streamSSE};
@@ -1 +1 @@
1
- const e=require(`./client-C9uh5T54.cjs`);let t=require(`ai`);t=e.__toESM(t);const n=Object.freeze({upsert:async t=>{let n=await e.client.chat[`:id`].$post({param:{id:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:t}},message:async(t,n,r)=>{let i=await e.client.chat[`:id`].sendMessages.$post({param:{id:t},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),r=Object.freeze({kv:Object.freeze({get:async t=>{let n=await e.client.storage.kv[`:key`].$get({param:{key:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(t,n)=>{let r=await e.client.storage.kv[`:key`].$post({param:{key:t},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async t=>{let n=await e.client.storage.kv[`:key`].$delete({param:{key:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function i(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var a=class extends Error{constructor(e,t){super(e),this.response=t}};function o(e){return e}const s={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let n={};for(let[t,r]of Object.entries(e.tools)){let e=r.execute;n[t]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let r=e.messages[e.messages.length-1];if(!r?.parts)return n;let o=[];for(let n of r.parts){if(!(0,t.isToolUIPart)(n))continue;let r=(0,t.getToolName)(n),i=e.tools[r];if(!i||n.state!==`output-available`||!i.execute||!c(n.output))continue;n.output.outcome===`approved`&&o.push({toolName:(0,t.getToolName)(n),tool:i,input:n.input,toolCallId:n.toolCallId})}if(o.length>0){let n=(0,t.createUIMessageStream)({execute:async({writer:n})=>{n.write({type:`start-step`}),await Promise.all(o.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);n.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let a=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:(0,t.convertToModelMessages)(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(i(a))for await(let e of a)n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:a})}catch(e){n.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),n.write({type:`finish`})}});throw new a(`Executing tools`,n)}return n},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function c(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function l(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function u(t,n){let r=new Headers(t.headers);return r.set(e.StreamResponseFormatHeader,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}Object.defineProperty(exports,`chat`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`isToolApprovalOutput`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`lastUIOptions`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`storage`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`toolWithApproval`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`tools`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`withResponseFormat`,{enumerable:!0,get:function(){return u}});
1
+ const e=require(`./client-DFaZjb1-.cjs`);let t=require(`ai`);t=e.__toESM(t);const n=Object.freeze({upsert:async t=>{let n=await e.client.chat[`:id`].$post({param:{id:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:t}},message:async(t,n,r)=>{let i=await e.client.chat[`:id`].sendMessages.$post({param:{id:t},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),r=Object.freeze({kv:Object.freeze({get:async t=>{let n=await e.client.storage.kv[`:key`].$get({param:{key:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(t,n)=>{let r=await e.client.storage.kv[`:key`].$post({param:{key:t},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async t=>{let n=await e.client.storage.kv[`:key`].$delete({param:{key:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function i(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var a=class extends Error{constructor(e,t){super(e),this.response=t}};function o(e){return e}const s={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let n={};for(let[t,r]of Object.entries(e.tools)){let e=r.execute;n[t]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let r=e.messages[e.messages.length-1];if(!r?.parts)return n;let o=[];for(let n of r.parts){if(!(0,t.isToolUIPart)(n))continue;let r=(0,t.getToolName)(n),i=e.tools[r];if(!i||n.state!==`output-available`||!i.execute||!c(n.output))continue;n.output.outcome===`approved`&&o.push({toolName:(0,t.getToolName)(n),tool:i,input:n.input,toolCallId:n.toolCallId})}if(o.length>0){let n=(0,t.createUIMessageStream)({execute:async({writer:n})=>{n.write({type:`start-step`}),await Promise.all(o.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);n.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let a=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:(0,t.convertToModelMessages)(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(i(a))for await(let e of a)n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:a})}catch(e){n.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),n.write({type:`finish`})}});throw new a(`Executing tools`,n)}return n},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function c(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function l(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function u(t,n){let r=new Headers(t.headers);return r.set(e.StreamResponseFormatHeader,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}Object.defineProperty(exports,`chat`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`isToolApprovalOutput`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`lastUIOptions`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`storage`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`toolWithApproval`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`tools`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`withResponseFormat`,{enumerable:!0,get:function(){return u}});
@@ -1 +1 @@
1
- import{StreamResponseFormatHeader as e,client as t}from"./client-DsiYP47H.js";import{convertToModelMessages as n,createUIMessageStream as r,getToolName as i,isToolUIPart as a}from"ai";const o=Object.freeze({upsert:async e=>{let n=await t.chat[`:id`].$post({param:{id:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:e}},message:async(e,n,r)=>{let i=await t.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),s=Object.freeze({kv:Object.freeze({get:async e=>{let n=await t.storage.kv[`:key`].$get({param:{key:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(e,n)=>{let r=await t.storage.kv[`:key`].$post({param:{key:e},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async e=>{let n=await t.storage.kv[`:key`].$delete({param:{key:e}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function c(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var l=class extends Error{constructor(e,t){super(e),this.response=t}};function u(e){return e}const d={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let t={};for(let[n,r]of Object.entries(e.tools)){let e=r.execute;t[n]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let o=e.messages[e.messages.length-1];if(!o?.parts)return t;let s=[];for(let t of o.parts){if(!a(t))continue;let n=i(t),r=e.tools[n];if(!r||t.state!==`output-available`||!r.execute||!f(t.output))continue;t.output.outcome===`approved`&&s.push({toolName:i(t),tool:r,input:t.input,toolCallId:t.toolCallId})}if(s.length>0){let t=r({execute:async({writer:t})=>{t.write({type:`start-step`}),await Promise.all(s.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);t.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let i=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:n(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(c(i))for await(let e of i)t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:i})}catch(e){t.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),t.write({type:`finish`})}});throw new l(`Executing tools`,t)}return t},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function f(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function p(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function m(t,n){let r=new Headers(t.headers);return r.set(e,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}export{o as chat,f as isToolApprovalOutput,p as lastUIOptions,s as storage,u as toolWithApproval,d as tools,m as withResponseFormat};
1
+ import{StreamResponseFormatHeader as e,client as t}from"./client-BbZudkEc.js";import{convertToModelMessages as n,createUIMessageStream as r,getToolName as i,isToolUIPart as a}from"ai";const o=Object.freeze({upsert:async e=>{let n=await t.chat[`:id`].$post({param:{id:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:e}},message:async(e,n,r)=>{let i=await t.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),s=Object.freeze({kv:Object.freeze({get:async e=>{let n=await t.storage.kv[`:key`].$get({param:{key:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(e,n)=>{let r=await t.storage.kv[`:key`].$post({param:{key:e},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async e=>{let n=await t.storage.kv[`:key`].$delete({param:{key:e}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function c(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var l=class extends Error{constructor(e,t){super(e),this.response=t}};function u(e){return e}const d={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let t={};for(let[n,r]of Object.entries(e.tools)){let e=r.execute;t[n]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let o=e.messages[e.messages.length-1];if(!o?.parts)return t;let s=[];for(let t of o.parts){if(!a(t))continue;let n=i(t),r=e.tools[n];if(!r||t.state!==`output-available`||!r.execute||!f(t.output))continue;t.output.outcome===`approved`&&s.push({toolName:i(t),tool:r,input:t.input,toolCallId:t.toolCallId})}if(s.length>0){let t=r({execute:async({writer:t})=>{t.write({type:`start-step`}),await Promise.all(s.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);t.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let i=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:n(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(c(i))for await(let e of i)t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:i})}catch(e){t.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),t.write({type:`finish`})}});throw new l(`Executing tools`,t)}return t},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function f(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function p(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function m(t,n){let r=new Headers(t.headers);return r.set(e,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}export{o as chat,f as isToolApprovalOutput,p as lastUIOptions,s as storage,u as toolWithApproval,d as tools,m as withResponseFormat};
@@ -1 +1 @@
1
- const e=require(`../client-C9uh5T54.cjs`),t=require(`../index.browser-CFap1r_Y.cjs`);let n=require(`react`);n=e.__toESM(n);function r({agent:e,capabilities:r,messages:i}){let[a,o]=(0,n.useState)(void 0),[s,c]=(0,n.useState)(!0),[l,u]=(0,n.useState)(void 0),d=(0,n.useMemo)(()=>t.lastUIOptions(i),[i]),[f,p]=(0,n.useState)(void 0),m=(0,n.useCallback)((e,t)=>{if(!l)return!1;let n=l[e];return n?n.values.some(e=>e.id===t):!1},[l]);(0,n.useEffect)(()=>{if(!d&&!l){p(void 0);return}p(e=>{let t={...d,...e};for(let[e,n]of Object.entries(t))m(e,n)||delete t[e];for(let[e,n]of Object.entries(l??{}))t[e]||(t[e]=n.defaultValue);return t})},[d,l,m]),(0,n.useEffect)(()=>{if(r&&!r.options||!e){u(void 0),p(void 0),o(void 0);return}let t=new AbortController;return c(!0),o(void 0),e.provideUIOptions(f?{selectedOptions:f}:{},{signal:t.signal}).then(e=>{t.signal.aborted||u(t=>JSON.stringify(t)===JSON.stringify(e)?t:e)}).catch(e=>{t.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{t.abort()}},[e,r,f]);let h=(0,n.useCallback)((e,t)=>{m(e,t)&&p(n=>n?{...n,[e]:t}:{[e]:t})},[m]);return{schema:l,options:f,setOption:h,loading:s,error:a}}exports.useOptions=r;
1
+ const e=require(`../client-DFaZjb1-.cjs`),t=require(`../index.browser-BwGhLjB7.cjs`);let n=require(`react`);n=e.__toESM(n);function r({agent:e,capabilities:r,messages:i}){let[a,o]=(0,n.useState)(void 0),[s,c]=(0,n.useState)(!0),[l,u]=(0,n.useState)(void 0),d=(0,n.useRef)(l);(0,n.useEffect)(()=>{d.current=l},[l]);let[f,p]=(0,n.useState)(()=>t.lastUIOptions(i));(0,n.useEffect)(()=>{p(e=>{let n=t.lastUIOptions(i);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[i]);let[m,h]=(0,n.useState)(void 0),g=(0,n.useCallback)((e,t)=>{if(!d.current)return!1;let n=d.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,n.useCallback)(e=>{h(t=>{let n={...f,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(d.current??{}))n[e]||(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[f,g]);(0,n.useEffect)(()=>{if(!f&&!l){h(void 0);return}_()},[f,l,_]),(0,n.useEffect)(()=>{if(r&&!r.options||!e){u(void 0),h(void 0),o(void 0);return}let t=new AbortController;return c(!0),o(void 0),e.provideUIOptions(m?{selectedOptions:m}:{},{signal:t.signal}).then(e=>{t.signal.aborted||u(t=>JSON.stringify(t)===JSON.stringify(e)?t:e)}).catch(e=>{t.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{t.abort()}},[e,r,m]);let v=(0,n.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:l,options:m,setOption:v,loading:s,error:a}}exports.useOptions=r;
@@ -1 +1 @@
1
- import"../client-DsiYP47H.js";import{lastUIOptions as e}from"../index.browser-CeE1x4lk.js";import{useCallback as t,useEffect as n,useMemo as r,useState as i}from"react";function a({agent:a,capabilities:o,messages:s}){let[c,l]=i(void 0),[u,d]=i(!0),[f,p]=i(void 0),m=r(()=>e(s),[s]),[h,g]=i(void 0),_=t((e,t)=>{if(!f)return!1;let n=f[e];return n?n.values.some(e=>e.id===t):!1},[f]);n(()=>{if(!m&&!f){g(void 0);return}g(e=>{let t={...m,...e};for(let[e,n]of Object.entries(t))_(e,n)||delete t[e];for(let[e,n]of Object.entries(f??{}))t[e]||(t[e]=n.defaultValue);return t})},[m,f,_]),n(()=>{if(o&&!o.options||!a){p(void 0),g(void 0),l(void 0);return}let e=new AbortController;return d(!0),l(void 0),a.provideUIOptions(h?{selectedOptions:h}:{},{signal:e.signal}).then(t=>{e.signal.aborted||p(e=>JSON.stringify(e)===JSON.stringify(t)?e:t)}).catch(t=>{e.signal.aborted||l(t instanceof Error?t:Error(String(t)))}).finally(()=>{d(!1)}),()=>{e.abort()}},[a,o,h]);let v=t((e,t)=>{_(e,t)&&g(n=>n?{...n,[e]:t}:{[e]:t})},[_]);return{schema:f,options:h,setOption:v,loading:u,error:c}}export{a as useOptions};
1
+ import"../client-BbZudkEc.js";import{lastUIOptions as e}from"../index.browser-Dj8kjB6X.js";import{useCallback as t,useEffect as n,useRef as r,useState as i}from"react";function a({agent:a,capabilities:o,messages:s}){let[c,l]=i(void 0),[u,d]=i(!0),[f,p]=i(void 0),m=r(f);n(()=>{m.current=f},[f]);let[h,g]=i(()=>e(s));n(()=>{g(t=>{let n=e(s);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[s]);let[_,v]=i(void 0),y=t((e,t)=>{if(!m.current)return!1;let n=m.current[e];return n?n.values.some(e=>e.id===t):!1},[]),b=t(e=>{v(t=>{let n={...h,...t,...e};for(let[e,t]of Object.entries(n))y(e,t)||delete n[e];for(let[e,t]of Object.entries(m.current??{}))n[e]||(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[h,y]);n(()=>{if(!h&&!f){v(void 0);return}b()},[h,f,b]),n(()=>{if(o&&!o.options||!a){p(void 0),v(void 0),l(void 0);return}let e=new AbortController;return d(!0),l(void 0),a.provideUIOptions(_?{selectedOptions:_}:{},{signal:e.signal}).then(t=>{e.signal.aborted||p(e=>JSON.stringify(e)===JSON.stringify(t)?e:t)}).catch(t=>{e.signal.aborted||l(t instanceof Error?t:Error(String(t)))}).finally(()=>{d(!1)}),()=>{e.abort()}},[a,o,_]);let x=t((e,t)=>{b({[e]:t})},[b]);return{schema:f,options:_,setOption:x,loading:u,error:c}}export{a as useOptions};
@@ -1,4 +1,4 @@
1
- import{__commonJSMin as e,__export as t,__reExport as n,__require as r,__toESM as i}from"./chunk-ByIbJXPc.js";import{Y as a}from"./dist-CN69Y-yA.js";import{open_default as o}from"./open-Cr8lEmcs.js";import{createRequire as s}from"node:module";import{createReadStream as c}from"node:fs";import l from"node:process";import{dirname as u,join as d}from"path";import{existsSync as f,mkdirSync as p,readFileSync as m,writeFileSync as h}from"fs";import{createRequire as g}from"module";import*as _ from"fs/promises";import v,{z as y}from"zod";import"zod/v4";import"zod/v3";import*as b from"node:fs/promises";import{spawn as x}from"child_process";import S from"node:os";import C from"node:tty";y.object({email:y.string().email(),password:y.string().min(8)}),y.object({email:y.string().email(),code:y.string()}),y.object({email:y.string().email(),password:y.string().min(8)});var w=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}};const T=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch(r){throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},E=y.object({per_page:y.number().int().positive().max(100).default(10).optional(),page:y.number().int().nonnegative().default(0).optional()}),D=e=>y.object({has_more:y.boolean(),items:y.array(e)}),O=y.object({limit:y.number().int().positive().max(100).default(10).optional(),cursor:y.string().optional()}),k=e=>y.object({next_cursor:y.string().nullable(),items:y.array(e)}),A=y.record(y.string().min(1).max(64),y.string().max(512)).nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),j=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i;y.object({agent_id:y.uuid(),deployment_id:y.uuid()}),y.object({agent_id:y.uuid(),deployment_id:y.uuid()});const ee=y.object({path:y.string(),id:y.uuid()}),M=ee.or(y.object({path:y.string(),data:y.string().max(1024*1024*5)})),N=y.enum([`production`,`preview`]);y.object({agent_id:y.uuid(),files:y.array(M),target:N,entrypoint:y.string().optional(),message:y.string().max(128).optional()});const P=y.object({id:y.uuid(),number:y.number().int().positive(),created_at:y.iso.datetime(),updated_at:y.iso.datetime(),created_by:y.uuid().nullable(),created_from:y.enum([`cli`]),agent_id:y.uuid(),files:y.array(ee),status:y.enum([`success`,`failed`,`deploying`,`pending`]),target:N,error_message:y.string().nullable(),user_message:y.string().nullable(),platform:y.enum([`lambda`]),platform_memory_mb:y.number().int().positive(),platform_region:y.string().nullable()});y.object({id:y.uuid(),created_at:y.string().datetime(),updated_at:y.string().datetime(),agent_id:y.uuid(),deployment_id:y.uuid(),level:y.enum([`log`,`info`,`warning`,`error`]),message:y.string()}),E.extend({agent_id:y.uuid(),order:y.enum([`asc`,`desc`]).default(`asc`).optional()}),D(P);var te=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);return await T(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await T(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await T(t,200)}async promote(){}async logs(){}};y.object({agent_id:y.uuid(),target:N.array().optional()}),y.object({id:y.uuid(),created_at:y.date(),updated_at:y.date(),created_by:y.uuid(),updated_by:y.uuid(),key:y.string(),value:y.string().nullable(),secret:y.boolean(),target:N.array()});const ne=y.object({key:y.string(),value:y.string(),secret:y.boolean(),target:N.array().optional(),upsert:y.boolean().optional()});ne.extend({agent_id:y.uuid()}),y.object({agent_id:y.uuid(),id:y.uuid()}),y.object({agent_id:y.uuid(),id:y.uuid(),key:y.string().optional(),value:y.string().optional(),secret:y.boolean().optional(),target:N.array().default([`preview`,`production`]).optional()});var F=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await T(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await T(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await T(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await T(t,200),t.json()}};const I=y.object({id:y.string(),agent_id:y.uuid(),agent_deployment_id:y.uuid(),received_at:y.date(),request_method:y.string(),request_handler_location:y.string().nullable(),duration_ms:y.number().nullable(),error:y.string().nullable(),response_status:y.number().nullable()});I.extend({request_headers:y.record(y.string(),y.string()),request_headers_redacted:y.boolean(),request_body:y.string().nullable(),request_body_redacted:y.boolean(),response_headers:y.record(y.string(),y.string()).nullable(),response_headers_redacted:y.boolean(),response_body:y.string().nullable(),response_body_redacted:y.boolean()}),O.extend({agent_id:y.string(),agent_deployment_id:y.number().optional()}),k(I);var re=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await T(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await T(n,200),n.json()}};O.extend({agent_id:y.uuid(),agent_deployment_id:y.uuid().optional()}),y.object({agent_id:y.uuid(),run_id:y.uuid()});var ie=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await T(t,200),t.json()}};const ae=y.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),oe=y.enum([`tool_call`,`queued_message`]),se=y.object({id:y.uuid(),number:y.number().int().positive(),chat_id:y.uuid(),chat_run_id:y.uuid(),agent_id:y.uuid(),agent_deployment_id:y.uuid(),started_at:y.string().datetime(),status:ae,error:y.string().nullable(),continuation_reason:oe.nullable(),response_status:y.number().nullable(),response_message_id:y.uuid().nullable()});se.extend({heartbeat_at:y.date(),completed_at:y.date().nullable(),interrupted_at:y.date().nullable(),first_message_id:y.uuid().nullable(),last_message_id:y.uuid().nullable(),response_headers:y.record(y.string(),y.string()).nullable(),response_headers_redacted:y.boolean(),response_body:y.string().nullable(),response_body_redacted:y.boolean()}),O.extend({chat_id:y.uuid(),run_id:y.uuid().optional()}),k(se);var ce=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await T(t,200),t.json()}};O.extend({agent_id:y.uuid(),agent_deployment_id:y.uuid().optional(),chat_id:y.uuid().optional(),run_id:y.uuid().optional(),status:ae.optional()}),k(se);var le=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await T(t,200),t.json()}};v.object({start_time:v.iso.datetime().pipe(v.coerce.date()),end_time:v.iso.datetime().pipe(v.coerce.date()),message_pattern:v.string().optional(),limit:v.string().pipe(v.coerce.number().min(1).max(1e4)).optional()});const ue=v.object({timestamp:v.iso.datetime().pipe(v.coerce.date()),message:v.string(),level:v.enum([`info`,`error`,`warn`])}),de=v.object({logs:v.array(ue)});var fe=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await T(n,200);let r=await n.json();return de.parse(r)}};const pe=y.enum([`private`,`public`]);y.object({organization_id:y.uuid(),name:y.string().regex(j),description:y.string().optional(),visibility:pe.default(`private`).optional(),files:y.array(M).optional(),entrypoint:y.string().optional(),env:y.array(ne).optional()});const me=y.object({id:y.uuid(),organization_id:y.uuid(),created_at:y.iso.datetime(),updated_at:y.iso.datetime(),created_by:y.uuid(),name:y.string().regex(j),description:y.string().nullable(),avatar_url:y.string().nullable(),visibility:pe,active_deployment_id:y.uuid().nullable(),webhook_route:y.string().url().nullable().describe(`The route for the agent's webhook. Only visible to owners.`)});y.object({id:y.uuid(),name:y.string().regex(j).optional(),description:y.string().optional(),visibility:pe.optional(),active_deployment_id:y.uuid().optional()}),E.extend({organization_id:y.uuid().optional()}),D(me);var he=class{constructor(e){this.client=e,this.deployments=new te(e),this.env=new F(e),this.webhook=new re(e),this.runs=new ie(e),this.steps=new le(e),this.logs=new fe(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await T(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await T(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await T(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await T(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await T(t,204)}},ge=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await T(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await T(t,200),new File([await t.blob()],``)}};const _e=y.enum([`owner`,`admin`,`billing_admin`,`member`]),ve=y.object({user_id:y.uuid(),organization_id:y.uuid(),role:_e,created_at:y.date(),updated_at:y.date()}),ye=y.object({id:y.uuid(),created_at:y.date(),updated_at:y.date(),display_name:y.string().nullable(),email:y.email(),avatar_url:y.url().nullable(),username:y.string()}),be=ve.extend({user:ye});E.extend({organization_id:y.uuid()}),D(be),y.object({organization_id:y.uuid(),user_id:y.uuid()});const xe=y.object({role:y.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()});xe.extend({organization_id:y.uuid(),user_id:y.uuid()});var Se=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await T(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await T(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await T(t,200),t.json()}},Ce=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await T(t,200),t.json()}};y.object({id:y.uuid(),name:y.string(),created_at:y.date(),updated_at:y.date(),membership:ve.nullable(),members_url:y.url(),invites_url:y.url(),avatar_url:y.url().nullable()}),y.object({name:y.string().regex(j)});var we=class{constructor(e){this.client=e,this.members=new Se(e),this.agents=new Ce(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await T(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await T(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await T(t,201),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await T(t,204)}};v.object({id:v.uuid(),created_at:v.date(),updated_at:v.date(),email:v.string().email(),email_verified:v.boolean(),display_name:v.string(),username:v.string(),organization_id:v.uuid(),avatar_url:v.string().url().nullable()});var Te=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await T(t,200),t.json()}},Ee=`vercel.ai.error`,De=Symbol.for(Ee),Oe,ke=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Oe]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ee)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Oe=De;var Ae=ke,je=`AI_APICallError`,Me=`vercel.ai.error.${je}`,Ne=Symbol.for(Me),Pe;Pe=Ne;var Fe=`AI_EmptyResponseBodyError`,Ie=`vercel.ai.error.${Fe}`,Le=Symbol.for(Ie),Re;Re=Le;function ze(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Be=`AI_InvalidArgumentError`,Ve=`vercel.ai.error.${Be}`,He=Symbol.for(Ve),Ue,We=class extends Ae{constructor({message:e,cause:t,argument:n}){super({name:Be,message:e,cause:t}),this[Ue]=!0,this.argument=n}static isInstance(e){return Ae.hasMarker(e,Ve)}};Ue=He;var Ge=`AI_InvalidPromptError`,Ke=`vercel.ai.error.${Ge}`,qe=Symbol.for(Ke),Je;Je=qe;var Ye=`AI_InvalidResponseDataError`,Xe=`vercel.ai.error.${Ye}`,Ze=Symbol.for(Xe),Qe;Qe=Ze;var $e=`AI_JSONParseError`,et=`vercel.ai.error.${$e}`,tt=Symbol.for(et),nt,rt=class extends Ae{constructor({text:e,cause:t}){super({name:$e,message:`JSON parsing failed: Text: ${e}.
1
+ import{__commonJSMin as e,__export as t,__reExport as n,__require as r,__toESM as i}from"./chunk-ByIbJXPc.js";import{Y as a}from"./dist-NqrnQGst.js";import{open_default as o}from"./open-CSMQaj0E.js";import{createRequire as s}from"node:module";import{createReadStream as c}from"node:fs";import l from"node:process";import{dirname as u,join as d}from"path";import{existsSync as f,mkdirSync as p,readFileSync as m,writeFileSync as h}from"fs";import{createRequire as g}from"module";import*as _ from"fs/promises";import v,{z as y}from"zod";import"zod/v4";import"zod/v3";import*as b from"node:fs/promises";import{spawn as x}from"child_process";import S from"node:os";import C from"node:tty";y.object({email:y.string().email(),password:y.string().min(8)}),y.object({email:y.string().email(),code:y.string()}),y.object({email:y.string().email(),password:y.string().min(8)});var w=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}};const T=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch(r){throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},E=y.object({per_page:y.number().int().positive().max(100).default(10).optional(),page:y.number().int().nonnegative().default(0).optional()}),D=e=>y.object({has_more:y.boolean(),items:y.array(e)}),O=y.object({limit:y.number().int().positive().max(100).default(10).optional(),cursor:y.string().optional()}),k=e=>y.object({next_cursor:y.string().nullable(),items:y.array(e)}),A=y.record(y.string().min(1).max(64),y.string().max(512)).nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),j=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i;y.object({agent_id:y.uuid(),deployment_id:y.uuid()}),y.object({agent_id:y.uuid(),deployment_id:y.uuid()});const ee=y.object({path:y.string(),id:y.uuid()}),M=ee.or(y.object({path:y.string(),data:y.string().max(1024*1024*5)})),N=y.enum([`production`,`preview`]);y.object({agent_id:y.uuid(),files:y.array(M),target:N,entrypoint:y.string().optional(),message:y.string().max(128).optional()});const P=y.object({id:y.uuid(),number:y.number().int().positive(),created_at:y.iso.datetime(),updated_at:y.iso.datetime(),created_by:y.uuid().nullable(),created_from:y.enum([`cli`]),agent_id:y.uuid(),files:y.array(ee),status:y.enum([`success`,`failed`,`deploying`,`pending`]),target:N,error_message:y.string().nullable(),user_message:y.string().nullable(),platform:y.enum([`lambda`]),platform_memory_mb:y.number().int().positive(),platform_region:y.string().nullable()});y.object({id:y.uuid(),created_at:y.string().datetime(),updated_at:y.string().datetime(),agent_id:y.uuid(),deployment_id:y.uuid(),level:y.enum([`log`,`info`,`warning`,`error`]),message:y.string()}),E.extend({agent_id:y.uuid(),order:y.enum([`asc`,`desc`]).default(`asc`).optional()}),D(P);var te=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);return await T(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await T(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await T(t,200)}async promote(){}async logs(){}};y.object({agent_id:y.uuid(),target:N.array().optional()}),y.object({id:y.uuid(),created_at:y.date(),updated_at:y.date(),created_by:y.uuid(),updated_by:y.uuid(),key:y.string(),value:y.string().nullable(),secret:y.boolean(),target:N.array()});const ne=y.object({key:y.string(),value:y.string(),secret:y.boolean(),target:N.array().optional(),upsert:y.boolean().optional()});ne.extend({agent_id:y.uuid()}),y.object({agent_id:y.uuid(),id:y.uuid()}),y.object({agent_id:y.uuid(),id:y.uuid(),key:y.string().optional(),value:y.string().optional(),secret:y.boolean().optional(),target:N.array().default([`preview`,`production`]).optional()});var F=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await T(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await T(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await T(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await T(t,200),t.json()}};const I=y.object({id:y.string(),agent_id:y.uuid(),agent_deployment_id:y.uuid(),received_at:y.date(),request_method:y.string(),request_handler_location:y.string().nullable(),duration_ms:y.number().nullable(),error:y.string().nullable(),response_status:y.number().nullable()});I.extend({request_headers:y.record(y.string(),y.string()),request_headers_redacted:y.boolean(),request_body:y.string().nullable(),request_body_redacted:y.boolean(),response_headers:y.record(y.string(),y.string()).nullable(),response_headers_redacted:y.boolean(),response_body:y.string().nullable(),response_body_redacted:y.boolean()}),O.extend({agent_id:y.string(),agent_deployment_id:y.number().optional()}),k(I);var re=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await T(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await T(n,200),n.json()}};O.extend({agent_id:y.uuid(),agent_deployment_id:y.uuid().optional()}),y.object({agent_id:y.uuid(),run_id:y.uuid()});var ie=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await T(t,200),t.json()}};const ae=y.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),oe=y.enum([`tool_call`,`queued_message`]),se=y.object({id:y.uuid(),number:y.number().int().positive(),chat_id:y.uuid(),chat_run_id:y.uuid(),agent_id:y.uuid(),agent_deployment_id:y.uuid(),started_at:y.string().datetime(),status:ae,error:y.string().nullable(),continuation_reason:oe.nullable(),response_status:y.number().nullable(),response_message_id:y.uuid().nullable()});se.extend({heartbeat_at:y.date(),completed_at:y.date().nullable(),interrupted_at:y.date().nullable(),first_message_id:y.uuid().nullable(),last_message_id:y.uuid().nullable(),response_headers:y.record(y.string(),y.string()).nullable(),response_headers_redacted:y.boolean(),response_body:y.string().nullable(),response_body_redacted:y.boolean()}),O.extend({chat_id:y.uuid(),run_id:y.uuid().optional()}),k(se);var ce=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await T(t,200),t.json()}};O.extend({agent_id:y.uuid(),agent_deployment_id:y.uuid().optional(),chat_id:y.uuid().optional(),run_id:y.uuid().optional(),status:ae.optional()}),k(se);var le=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await T(t,200),t.json()}};v.object({start_time:v.iso.datetime().pipe(v.coerce.date()),end_time:v.iso.datetime().pipe(v.coerce.date()),message_pattern:v.string().optional(),limit:v.string().pipe(v.coerce.number().min(1).max(1e4)).optional()});const ue=v.object({timestamp:v.iso.datetime().pipe(v.coerce.date()),message:v.string(),level:v.enum([`info`,`error`,`warn`])}),de=v.object({logs:v.array(ue)});var fe=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await T(n,200);let r=await n.json();return de.parse(r)}};const pe=y.enum([`private`,`public`]);y.object({organization_id:y.uuid(),name:y.string().regex(j),description:y.string().optional(),visibility:pe.default(`private`).optional(),files:y.array(M).optional(),entrypoint:y.string().optional(),env:y.array(ne).optional()});const me=y.object({id:y.uuid(),organization_id:y.uuid(),created_at:y.iso.datetime(),updated_at:y.iso.datetime(),created_by:y.uuid(),name:y.string().regex(j),description:y.string().nullable(),avatar_url:y.string().nullable(),visibility:pe,active_deployment_id:y.uuid().nullable(),webhook_route:y.string().url().nullable().describe(`The route for the agent's webhook. Only visible to owners.`)});y.object({id:y.uuid(),name:y.string().regex(j).optional(),description:y.string().optional(),visibility:pe.optional(),active_deployment_id:y.uuid().optional()}),E.extend({organization_id:y.uuid().optional()}),D(me);var he=class{constructor(e){this.client=e,this.deployments=new te(e),this.env=new F(e),this.webhook=new re(e),this.runs=new ie(e),this.steps=new le(e),this.logs=new fe(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await T(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await T(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await T(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await T(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await T(t,204)}},ge=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await T(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await T(t,200),new File([await t.blob()],``)}};const _e=y.enum([`owner`,`admin`,`billing_admin`,`member`]),ve=y.object({user_id:y.uuid(),organization_id:y.uuid(),role:_e,created_at:y.date(),updated_at:y.date()}),ye=y.object({id:y.uuid(),created_at:y.date(),updated_at:y.date(),display_name:y.string().nullable(),email:y.email(),avatar_url:y.url().nullable(),username:y.string()}),be=ve.extend({user:ye});E.extend({organization_id:y.uuid()}),D(be),y.object({organization_id:y.uuid(),user_id:y.uuid()});const xe=y.object({role:y.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()});xe.extend({organization_id:y.uuid(),user_id:y.uuid()});var Se=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await T(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await T(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await T(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await T(t,200),t.json()}},Ce=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await T(t,200),t.json()}};y.object({id:y.uuid(),name:y.string(),created_at:y.date(),updated_at:y.date(),membership:ve.nullable(),members_url:y.url(),invites_url:y.url(),avatar_url:y.url().nullable()}),y.object({name:y.string().regex(j)});var we=class{constructor(e){this.client=e,this.members=new Se(e),this.agents=new Ce(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await T(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await T(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await T(t,201),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await T(t,204)}};v.object({id:v.uuid(),created_at:v.date(),updated_at:v.date(),email:v.string().email(),email_verified:v.boolean(),display_name:v.string(),username:v.string(),organization_id:v.uuid(),avatar_url:v.string().url().nullable()});var Te=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await T(t,200),t.json()}},Ee=`vercel.ai.error`,De=Symbol.for(Ee),Oe,ke=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Oe]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ee)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Oe=De;var Ae=ke,je=`AI_APICallError`,Me=`vercel.ai.error.${je}`,Ne=Symbol.for(Me),Pe;Pe=Ne;var Fe=`AI_EmptyResponseBodyError`,Ie=`vercel.ai.error.${Fe}`,Le=Symbol.for(Ie),Re;Re=Le;function ze(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Be=`AI_InvalidArgumentError`,Ve=`vercel.ai.error.${Be}`,He=Symbol.for(Ve),Ue,We=class extends Ae{constructor({message:e,cause:t,argument:n}){super({name:Be,message:e,cause:t}),this[Ue]=!0,this.argument=n}static isInstance(e){return Ae.hasMarker(e,Ve)}};Ue=He;var Ge=`AI_InvalidPromptError`,Ke=`vercel.ai.error.${Ge}`,qe=Symbol.for(Ke),Je;Je=qe;var Ye=`AI_InvalidResponseDataError`,Xe=`vercel.ai.error.${Ye}`,Ze=Symbol.for(Xe),Qe;Qe=Ze;var $e=`AI_JSONParseError`,et=`vercel.ai.error.${$e}`,tt=Symbol.for(et),nt,rt=class extends Ae{constructor({text:e,cause:t}){super({name:$e,message:`JSON parsing failed: Text: ${e}.
2
2
  Error message: ${ze(t)}`,cause:t}),this[nt]=!0,this.text=e}static isInstance(e){return Ae.hasMarker(e,et)}};nt=tt;var it=`AI_LoadAPIKeyError`,at=`vercel.ai.error.${it}`,ot=Symbol.for(at),st;st=ot;var ct=`AI_LoadSettingError`,lt=`vercel.ai.error.${ct}`,ut=Symbol.for(lt),dt;dt=ut;var ft=`AI_NoContentGeneratedError`,pt=`vercel.ai.error.${ft}`,mt=Symbol.for(pt),ht;ht=mt;var gt=`AI_NoSuchModelError`,_t=`vercel.ai.error.${gt}`,vt=Symbol.for(_t),yt;yt=vt;var bt=`AI_TooManyEmbeddingValuesForCallError`,xt=`vercel.ai.error.${bt}`,St=Symbol.for(xt),Ct;Ct=St;var wt=`AI_TypeValidationError`,Tt=`vercel.ai.error.${wt}`,Et=Symbol.for(Tt),Dt,Ot=class e extends Ae{constructor({value:e,cause:t}){super({name:wt,message:`Type validation failed: Value: ${JSON.stringify(e)}.
3
3
  Error message: ${ze(t)}`,cause:t}),this[Dt]=!0,this.value=e}static isInstance(e){return Ae.hasMarker(e,Tt)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Dt=Et;var kt=Ot,At=`AI_UnsupportedFunctionalityError`,jt=`vercel.ai.error.${At}`,Mt=Symbol.for(jt),Nt;Nt=Mt;var Pt=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new We({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`};Pt();var Ft=/"__proto__"\s*:/,It=/"constructor"\s*:/;function Lt(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Ft.test(e)===!1&&It.test(e)===!1?t:Rt(t)}function Rt(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function zt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Lt(e)}finally{Error.stackTraceLimit=t}}var Bt=Symbol.for(`vercel.ai.validator`);function Vt(e){return{[Bt]:!0,validate:e}}function Ht(e){return typeof e==`object`&&!!e&&Bt in e&&e[Bt]===!0&&`validate`in e}function Ut(e){return Ht(e)?e:Wt(e)}function Wt(e){return Vt(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new kt({value:t,cause:n.issues})}})}async function Gt({value:e,schema:t}){let n=Ut(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:kt.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:kt.wrap({value:e,cause:t}),rawValue:e}}}async function Kt({text:e,schema:t}){try{let n=zt(e);return t==null?{success:!0,value:n,rawValue:n}:await Gt({value:n,schema:t})}catch(t){return{success:!1,error:rt.isInstance(t)?t:new rt({text:e,cause:t}),rawValue:void 0}}}var{btoa:qt,atob:Jt}=globalThis,Yt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Xt(e){}function Zt(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Xt,onError:n=Xt,onRetry:r=Xt,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Qt(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
4
4
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Yt(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Yt(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
@@ -1 +1 @@
1
- import{import_websocket as e}from"./wrapper-B4vDwpOq.js";import{open_default as t}from"./open-Cr8lEmcs.js";import{WorkspaceConnect as n}from"./connect-Cxa-uIEb.js";import"./events-CWgtj8lb.js";async function r(){let r=crypto.randomUUID(),i=new e.default(`wss://blink.so/legacy-auth?id=${r}`),a=new Promise((e,t)=>{i.onopen=()=>{e()},i.onerror=e=>{t(e)}});await a;let o=new Promise((e,t)=>{i.onmessage=t=>{e(t.data.toString())}}),s=`https://blink.so/legacy-auth?id=${r}&type=workspace`;console.log(`Opening the following URL in your browser: ${s}`),await t(s);let c=await o,l=new n({url:`wss://blink.so/api/connect`,token:c});l.onConnect(()=>{console.log(`Connected to Blink`)}),l.onDisconnect(()=>{console.log(`Disconnected from Blink`)})}export{r as default};
1
+ import{import_websocket as e}from"./wrapper-B4vDwpOq.js";import{open_default as t}from"./open-CSMQaj0E.js";import{WorkspaceConnect as n}from"./connect-Cxa-uIEb.js";import"./events-CWgtj8lb.js";async function r(){let r=crypto.randomUUID(),i=new e.default(`wss://blink.so/legacy-auth?id=${r}`),a=new Promise((e,t)=>{i.onopen=()=>{e()},i.onerror=e=>{t(e)}});await a;let o=new Promise((e,t)=>{i.onmessage=t=>{e(t.data.toString())}}),s=`https://blink.so/legacy-auth?id=${r}&type=workspace`;console.log(`Opening the following URL in your browser: ${s}`),await t(s);let c=await o,l=new n({url:`wss://blink.so/api/connect`,token:c});l.onConnect(()=>{console.log(`Connected to Blink`)}),l.onDisconnect(()=>{console.log(`Disconnected from Blink`)})}export{r as default};