blink 0.1.72 → 0.1.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/agent/client/index.cjs +21 -0
- package/dist/browser/agent/client/index.d.cts +4 -0
- package/dist/browser/agent/client/index.d.ts +4 -0
- package/dist/browser/agent/client/index.js +21 -0
- package/dist/browser/agent/index.browser.cjs +1 -0
- package/dist/browser/agent/index.browser.d.cts +3 -0
- package/dist/browser/agent/index.browser.d.ts +3 -0
- package/dist/browser/agent/index.browser.js +1 -0
- package/dist/browser/chat-B5eFQu26.d.cts +129 -0
- package/dist/browser/chat-BN7SYTWY.d.ts +129 -0
- package/dist/browser/control/index.cjs +1 -0
- package/dist/browser/control/index.d.cts +187 -0
- package/dist/browser/control/index.d.ts +187 -0
- package/dist/browser/control/index.js +1 -0
- package/dist/browser/index-B5faDAC2.d.ts +53 -0
- package/dist/browser/index-C-GJWB97.d.cts +53 -0
- package/dist/browser/index.browser-09e-NXpn.cjs +1 -0
- package/dist/browser/index.browser-0KfCzcI7.js +1 -0
- package/dist/browser/index.browser-BUMCZUeQ.d.ts +180 -0
- package/dist/browser/index.browser-CnGab8Yp.d.cts +180 -0
- package/dist/browser/index.node-DJv-HF6j.js +3 -0
- package/dist/browser/index.node-mda_IL6K.cjs +3 -0
- package/dist/browser/react/index.cjs +1 -1
- package/dist/browser/react/index.d.cts +6 -5
- package/dist/browser/react/index.d.ts +6 -5
- package/dist/browser/react/index.js +1 -1
- package/dist/browser/validator-CvSEfFnI.cjs +1 -0
- package/dist/browser/validator-DOrmtI_l.js +1 -0
- package/dist/cli/{auth-Dw-wJ1IM.js → auth-BUNIOupD.js} +1 -1
- package/dist/cli/{chat-CvTLq5E0.js → chat-L0VBV1Zr.js} +1 -1
- package/dist/cli/{dev-Cr9A596F.js → dev-CMwHkKBI.js} +133 -137
- package/dist/cli/index.js +4 -4
- package/dist/cli/{init-LfebhEg-.js → init-B6vWokUI.js} +24 -22
- package/dist/cli/login-DKW_KVCA.js +1 -0
- package/dist/node/agent/index.node.cjs +10 -0
- package/dist/node/agent/index.node.d.cts +2 -0
- package/dist/node/agent/index.node.d.ts +2 -0
- package/dist/node/agent/index.node.js +10 -0
- package/dist/node/index.node-BBpGHHxe.d.ts +460 -0
- package/dist/node/index.node-iaeCqAo6.d.cts +460 -0
- package/dist/node/test.d.cts +20 -50
- package/dist/node/test.d.ts +20 -50
- package/package.json +21 -19
- package/dist/browser/api/index.browser.cjs +0 -1
- package/dist/browser/api/index.browser.d.cts +0 -2
- package/dist/browser/api/index.browser.d.ts +0 -2
- package/dist/browser/api/index.browser.js +0 -1
- package/dist/browser/client-3mJjOKuh.d.ts +0 -94
- package/dist/browser/client-B7xl9jGk.d.cts +0 -94
- package/dist/browser/client-BbZudkEc.js +0 -21
- package/dist/browser/client-DFaZjb1-.cjs +0 -21
- package/dist/browser/http/index.cjs +0 -1
- package/dist/browser/http/index.d.cts +0 -207
- package/dist/browser/http/index.d.ts +0 -207
- package/dist/browser/http/index.js +0 -1
- package/dist/browser/index.browser-BwGhLjB7.cjs +0 -1
- package/dist/browser/index.browser-Dj8kjB6X.js +0 -1
- package/dist/browser/index.browser-c6tjyX5u.d.cts +0 -316
- package/dist/browser/index.browser-ekIUKJkA.d.ts +0 -316
- package/dist/cli/login-KHDcJ0iZ.js +0 -1
- package/dist/node/api/index.node.cjs +0 -30
- package/dist/node/api/index.node.d.cts +0 -82
- package/dist/node/api/index.node.d.ts +0 -82
- package/dist/node/api/index.node.js +0 -30
- package/dist/node/index.browser-Bo1v3lXu.d.cts +0 -316
- package/dist/node/index.browser-Dhyi8IHz.d.ts +0 -316
- /package/dist/cli/{dist-CN69Y-yA.js → dist-NqrnQGst.js} +0 -0
- /package/dist/cli/{open-Cr8lEmcs.js → open-CSMQaj0E.js} +0 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { Promisable } from "./chat-B5eFQu26.cjs";
|
|
2
|
+
import { InferToolInput, InferToolOutput, Tool, ToolSet, UIMessage } from "ai";
|
|
3
|
+
|
|
4
|
+
//#region src/agent/ui.d.ts
|
|
5
|
+
type UIOptionIcon = `lucide:${string}` | `simple-icons:${string}`;
|
|
6
|
+
type UIOptionSelectValue<ID extends string = string> = {
|
|
7
|
+
readonly id: ID;
|
|
8
|
+
readonly label: string;
|
|
9
|
+
/**
|
|
10
|
+
* description will provide additional context to the user in the UI.
|
|
11
|
+
*/
|
|
12
|
+
readonly description?: string | Array<{
|
|
13
|
+
readonly text: string;
|
|
14
|
+
readonly color?: "primary" | "muted" | "warning";
|
|
15
|
+
}>;
|
|
16
|
+
/**
|
|
17
|
+
* icon is a slug of a Lucide or SimpleIcons icon.
|
|
18
|
+
* This will only be rendered in a web-based UI.
|
|
19
|
+
*
|
|
20
|
+
* Find icons:
|
|
21
|
+
* - https://simpleicons.org/
|
|
22
|
+
* - https://lucide.dev/icons/
|
|
23
|
+
*/
|
|
24
|
+
readonly icon?: UIOptionIcon;
|
|
25
|
+
};
|
|
26
|
+
type UIOptionSelect<Values extends readonly UIOptionSelectValue[] = readonly UIOptionSelectValue[]> = {
|
|
27
|
+
readonly type: "select";
|
|
28
|
+
/**
|
|
29
|
+
* label indicates the purpose of the option.
|
|
30
|
+
* If omitted, it will not be displayed in the UI.
|
|
31
|
+
*/
|
|
32
|
+
readonly label?: string;
|
|
33
|
+
/**
|
|
34
|
+
* icon is a slug of a Lucide or SimpleIcons icon.
|
|
35
|
+
* This will only be rendered in a web-based UI.
|
|
36
|
+
*
|
|
37
|
+
* Find icons:
|
|
38
|
+
* - https://simpleicons.org/
|
|
39
|
+
* - https://lucide.dev/icons/
|
|
40
|
+
*/
|
|
41
|
+
readonly icon?: UIOptionIcon;
|
|
42
|
+
/**
|
|
43
|
+
* defaultValue is the default value for the option.
|
|
44
|
+
* If omitted, the option will not be selected by default.
|
|
45
|
+
*/
|
|
46
|
+
readonly defaultValue: Values[number]["id"];
|
|
47
|
+
readonly values: Values;
|
|
48
|
+
};
|
|
49
|
+
type UIOptions = Record<string, string>;
|
|
50
|
+
type WithUIOptions<OPTIONS extends UIOptions, MESSAGE extends UIMessage = UIMessage> = MESSAGE & {
|
|
51
|
+
readonly role: "user";
|
|
52
|
+
readonly metadata: MESSAGE["metadata"] & {
|
|
53
|
+
readonly options: OPTIONS;
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
type ExtractUIOptions<M> = M extends WithUIOptions<infer O> ? O : UIOptions;
|
|
57
|
+
type UIOptionsSchema<OPTIONS extends UIOptions = UIOptions> = { [K in keyof OPTIONS]: UIOptionSelect<Array<UIOptionSelectValue<OPTIONS[K]>>> };
|
|
58
|
+
interface UIEvent<MESSAGE extends UIMessage> {
|
|
59
|
+
readonly selectedOptions?: ExtractUIOptions<MESSAGE>;
|
|
60
|
+
}
|
|
61
|
+
type UIHandler<MESSAGE extends UIMessage> = (event: UIEvent<MESSAGE>) => Promisable<UIOptionsSchema<ExtractUIOptions<MESSAGE>> | void>;
|
|
62
|
+
/**
|
|
63
|
+
* lastUIOptions finds the last user message with options.
|
|
64
|
+
* Options are stored in message metadata to preserve the history
|
|
65
|
+
* of changing options.
|
|
66
|
+
*
|
|
67
|
+
* @param messages - The messages to search.
|
|
68
|
+
* @returns The last user message with options, or undefined if no such message exists.
|
|
69
|
+
*/
|
|
70
|
+
declare function lastUIOptions<MESSAGE extends UIMessage>(messages: MESSAGE[]): ExtractUIOptions<MESSAGE> | undefined;
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/agent/tools.d.ts
|
|
73
|
+
/**
|
|
74
|
+
* ToolWithContext is a tool that supports the "withContext" method.
|
|
75
|
+
*
|
|
76
|
+
* @param CONTEXT The context type.
|
|
77
|
+
* @param TOOL The tool type.
|
|
78
|
+
* @returns The tool with the given context.
|
|
79
|
+
*/
|
|
80
|
+
type ToolWithContext<CONTEXT, TOOL extends Tool> = TOOL & {
|
|
81
|
+
withContext(context: CONTEXT): TOOL;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* ToolWithApproval is a tool that supports the "autoApprove" method.
|
|
85
|
+
*
|
|
86
|
+
* @param TOOL The tool type.
|
|
87
|
+
* @returns The tool with the given approval.
|
|
88
|
+
*/
|
|
89
|
+
type ToolWithApproval<INPUT, OUTPUT> = Tool<INPUT, OUTPUT> & {
|
|
90
|
+
/**
|
|
91
|
+
* autoApprove is a function that can be used to automatically approve
|
|
92
|
+
* an approval tool call based on the input.
|
|
93
|
+
*
|
|
94
|
+
* @param input The input to the tool.
|
|
95
|
+
* @returns Whether the tool call should be approved.
|
|
96
|
+
*/
|
|
97
|
+
autoApprove?: (input: INPUT) => Promise<boolean> | boolean;
|
|
98
|
+
};
|
|
99
|
+
type ToolSetWithApproval<TOOLS extends ToolSet> = { [K in keyof TOOLS]: ToolWithApproval<InferToolInput<TOOLS[K]>, InferToolOutput<TOOLS[K]>> };
|
|
100
|
+
/**
|
|
101
|
+
* toolWithApproval is a helper for inferring the execute and autoApprove
|
|
102
|
+
* arguments of a tool.
|
|
103
|
+
*
|
|
104
|
+
* @param tool The tool to wrap.
|
|
105
|
+
* @returns The wrapped tool.
|
|
106
|
+
*/
|
|
107
|
+
declare function toolWithApproval<INPUT, OUTPUT>(tool: ToolWithApproval<INPUT, OUTPUT>): ToolWithApproval<INPUT, OUTPUT>;
|
|
108
|
+
/**
|
|
109
|
+
* Tools are helpers for managing tools.
|
|
110
|
+
*/
|
|
111
|
+
declare const tools: Readonly<{
|
|
112
|
+
/**
|
|
113
|
+
* withContext adds context to a set of tools that supports the "withContext" method.
|
|
114
|
+
*
|
|
115
|
+
* @param context
|
|
116
|
+
* @param tools
|
|
117
|
+
* @returns
|
|
118
|
+
*/
|
|
119
|
+
withContext<const TOOLS extends ToolsWithContext>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: Tool };
|
|
120
|
+
/**
|
|
121
|
+
* @internal
|
|
122
|
+
* @deprecated Use withContext instead - it's the same thing.
|
|
123
|
+
*/
|
|
124
|
+
with<const TOOLS extends ToolsWithContext>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: Tool };
|
|
125
|
+
/**
|
|
126
|
+
* withApproval ensures a set of tools need explicit user approval
|
|
127
|
+
* before they are executed.
|
|
128
|
+
*
|
|
129
|
+
* This works by replacing the execution of all provided tools with
|
|
130
|
+
* special output that interfaces must handle.
|
|
131
|
+
*
|
|
132
|
+
* On approval, the tool will be executed with the verbatim input.
|
|
133
|
+
*
|
|
134
|
+
* @returns Tools that should be sent in `streamText`.
|
|
135
|
+
*/
|
|
136
|
+
withApproval<TOOLSET extends ToolSet, TOOLS extends ToolSetWithApproval<TOOLSET>, MESSAGE extends UIMessage>(options: {
|
|
137
|
+
messages: MESSAGE[];
|
|
138
|
+
tools: TOOLS;
|
|
139
|
+
abortSignal?: AbortSignal;
|
|
140
|
+
}): Promise<TOOLS>;
|
|
141
|
+
/**
|
|
142
|
+
* prefix adds a prefix to all the tools in a tool set.
|
|
143
|
+
*
|
|
144
|
+
* @param tools The tool set to prefix.
|
|
145
|
+
* @param prefix The prefix to add to the tools.
|
|
146
|
+
* @returns The prefixed tool set.
|
|
147
|
+
*/
|
|
148
|
+
prefix(tools: ToolSet, prefix: string): ToolSet;
|
|
149
|
+
}>;
|
|
150
|
+
type ToolsWithContext = Record<string, Tool & {
|
|
151
|
+
withContext(context: unknown): Tool;
|
|
152
|
+
}>;
|
|
153
|
+
type ContextFromTools<TOOLS extends ToolsWithContext> = TOOLS[keyof TOOLS] extends {
|
|
154
|
+
withContext(context: infer C): any;
|
|
155
|
+
} ? C : never;
|
|
156
|
+
/**
|
|
157
|
+
* ToolApprovalOutput is the output of a tool that requires approval.
|
|
158
|
+
*
|
|
159
|
+
* This should be consumed by the UI to display an approval prompt.
|
|
160
|
+
*/
|
|
161
|
+
interface ToolApprovalOutput {
|
|
162
|
+
type: "tool-approval";
|
|
163
|
+
outcome: "pending" | "approved" | "rejected";
|
|
164
|
+
reason?: string;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* isToolApprovalOutput checks if an output is a tool approval output.
|
|
168
|
+
*/
|
|
169
|
+
declare function isToolApprovalOutput(output: unknown): output is ToolApprovalOutput;
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/agent/index.browser.d.ts
|
|
172
|
+
type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
|
|
173
|
+
/**
|
|
174
|
+
* StreamResponseFormatHeader indicates to a client the stream response
|
|
175
|
+
* format that the agent is using.
|
|
176
|
+
*/
|
|
177
|
+
declare const StreamResponseFormatHeader = "x-blink-stream-response-format";
|
|
178
|
+
declare function withResponseFormat(response: Response, format: StreamResponseFormat): Response;
|
|
179
|
+
//#endregion
|
|
180
|
+
export { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{CustomChatResponseError as e}from"./index.browser-0KfCzcI7.js";import{Hono as t,validator as n}from"./validator-DOrmtI_l.js";import"http";const r=new t().post(`/chat`,n(`json`,e=>({messages:e.messages,chat:e.chat})),async t=>{let n=t.env.listeners.chat,r=t.req.valid(`json`);for(let a of n){let n;try{n=await a({key:r.chat.key,messages:r.messages,abortSignal:t.req.raw.signal,context:t.env.context})}catch(t){if(t instanceof e)n=t.response;else throw t}if(!n)continue;if(n instanceof Response)return n;let o;if(n instanceof ReadableStream)o=n;else if(typeof n==`object`&&`toUIMessageStream`in n)o=n.toUIMessageStream({messageMetadata:({part:e})=>{switch(e.type){case`finish`:return{totalUsage:e.totalUsage};case`finish-step`:return{usage:e.usage,model:e.response.modelId}}}});else throw Error(`Invalid chat handler result! Must be a Response, ReadableStream, or toUIMessageStream function.`);return new Response(o.pipeThrough(new TransformStream({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}\n\n`)},flush(e){e.enqueue(`data: [DONE]
|
|
2
|
+
|
|
3
|
+
`)}})).pipeThrough(new TextEncoderStream),{headers:i})}return t.json({error:`No chat handlers found.`},404)}).get(`/capabilities`,async e=>{let t=e.env.listeners,n={ui:t.ui.length>0,chat:t.chat.length>0,request:t.request.length>0,error:t.error.length>0};return e.json(n,200)}).get(`/health`,async e=>e.body(`OK`,200)).get(`/ui`,async e=>{let t=e.req.query(`selected_options`),n;if(t)try{n=JSON.parse(t)}catch{return e.json({error:`Invalid selected_options query parameter!`},400)}let r=e.env.listeners.ui;for(let t of r){let r=await t({selectedOptions:n});if(!r)continue;return e.json(r,200)}return e.json({error:`No UI listener returned a response`},404)});new t().route(`/_agent`,r).all(`*`,async e=>{let t=e.env.listeners.request;for(let n of t){let t=await n(e.req.raw,e.env.context);if(t)return t}return e.json({error:`No request handlers found.`},404)});const i={"content-type":`text/event-stream`,"cache-control":`no-cache, no-transform`,connection:`keep-alive`,"x-accel-buffering":`no`};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require(`./index.browser-09e-NXpn.cjs`),t=require(`./validator-CvSEfFnI.cjs`),n=new t.Hono().post(`/chat`,t.validator(`json`,e=>({messages:e.messages,chat:e.chat})),async t=>{let n=t.env.listeners.chat,r=t.req.valid(`json`);for(let a of n){let n;try{n=await a({key:r.chat.key,messages:r.messages,abortSignal:t.req.raw.signal,context:t.env.context})}catch(t){if(t instanceof e.CustomChatResponseError)n=t.response;else throw t}if(!n)continue;if(n instanceof Response)return n;let o;if(n instanceof ReadableStream)o=n;else if(typeof n==`object`&&`toUIMessageStream`in n)o=n.toUIMessageStream({messageMetadata:({part:e})=>{switch(e.type){case`finish`:return{totalUsage:e.totalUsage};case`finish-step`:return{usage:e.usage,model:e.response.modelId}}}});else throw Error(`Invalid chat handler result! Must be a Response, ReadableStream, or toUIMessageStream function.`);return new Response(o.pipeThrough(new TransformStream({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}\n\n`)},flush(e){e.enqueue(`data: [DONE]
|
|
2
|
+
|
|
3
|
+
`)}})).pipeThrough(new TextEncoderStream),{headers:i})}return t.json({error:`No chat handlers found.`},404)}).get(`/capabilities`,async e=>{let t=e.env.listeners,n={ui:t.ui.length>0,chat:t.chat.length>0,request:t.request.length>0,error:t.error.length>0};return e.json(n,200)}).get(`/health`,async e=>e.body(`OK`,200)).get(`/ui`,async e=>{let t=e.req.query(`selected_options`),n;if(t)try{n=JSON.parse(t)}catch{return e.json({error:`Invalid selected_options query parameter!`},400)}let r=e.env.listeners.ui;for(let t of r){let r=await t({selectedOptions:n});if(!r)continue;return e.json(r,200)}return e.json({error:`No UI listener returned a response`},404)}),r=new t.Hono().route(`/_agent`,n).all(`*`,async e=>{let t=e.env.listeners.request;for(let n of t){let t=await n(e.req.raw,e.env.context);if(t)return t}return e.json({error:`No request handlers found.`},404)}),i={"content-type":`text/event-stream`,"cache-control":`no-cache, no-transform`,connection:`keep-alive`,"x-accel-buffering":`no`};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`../
|
|
1
|
+
const e=require(`../index.browser-09e-NXpn.cjs`);require(`../validator-CvSEfFnI.cjs`),require(`../index.node-mda_IL6K.cjs`);let t=require(`react`);t=e.__toESM(t);function n({agent:n,capabilities:r,messages:i}){let[a,o]=(0,t.useState)(void 0),[s,c]=(0,t.useState)(!0),[l,u]=(0,t.useState)(void 0),d=(0,t.useRef)(l);(0,t.useEffect)(()=>{d.current=l},[l]);let[f,p]=(0,t.useState)(()=>e.lastUIOptions(i));(0,t.useEffect)(()=>{p(t=>{let n=e.lastUIOptions(i);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[i]);let[m,h]=(0,t.useState)(void 0),g=(0,t.useCallback)((e,t)=>{if(!d.current)return!1;let n=d.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,t.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]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[f,g]);(0,t.useEffect)(()=>{if(!f&&!l){h(void 0);return}_()},[f,l,_]);let v=(0,t.useRef)(void 0),y=(0,t.useRef)(void 0);(0,t.useEffect)(()=>{n!==y.current&&(y.current=n,u(void 0),h(void 0),o(void 0),c(!0),v.current=void 0)},[n]),(0,t.useEffect)(()=>{if(r&&!r.ui||!n){u(void 0),h(void 0),o(void 0),v.current=void 0;return}let e=m?JSON.stringify(m):``;if(v.current===e){c(!1),o(void 0);return}let t=new AbortController;return c(!0),o(void 0),n.ui(m?{selectedOptions:m}:{},{signal:t.signal}).then(n=>{t.signal.aborted||(u(e=>JSON.stringify(e)===JSON.stringify(n)?e:n),v.current=e)}).catch(e=>{t.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{t.abort()}},[n,r,m]);let b=(0,t.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:l,options:m,setOption:b,loading:s,error:a}}exports.useOptions=n;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import "../chat-B5eFQu26.cjs";
|
|
2
|
+
import { UIOptions, UIOptionsSchema } from "../index.browser-CnGab8Yp.cjs";
|
|
3
|
+
import { CapabilitiesResponse, Client } from "../index-C-GJWB97.cjs";
|
|
3
4
|
import { UIMessage } from "ai";
|
|
4
5
|
|
|
5
6
|
//#region src/react/use-options.d.ts
|
|
@@ -17,12 +18,12 @@ declare function useOptions({
|
|
|
17
18
|
capabilities,
|
|
18
19
|
messages
|
|
19
20
|
}: {
|
|
20
|
-
agent?: Pick<Client, "
|
|
21
|
+
agent?: Pick<Client, "ui">;
|
|
21
22
|
capabilities?: CapabilitiesResponse;
|
|
22
23
|
messages: UIMessage[];
|
|
23
24
|
}): {
|
|
24
|
-
schema:
|
|
25
|
-
options:
|
|
25
|
+
schema: UIOptionsSchema<UIOptions> | undefined;
|
|
26
|
+
options: UIOptions | undefined;
|
|
26
27
|
setOption: (id: string, value: string) => void;
|
|
27
28
|
loading: boolean;
|
|
28
29
|
error: Error | undefined;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import "../chat-BN7SYTWY.js";
|
|
2
|
+
import { UIOptions, UIOptionsSchema } from "../index.browser-BUMCZUeQ.js";
|
|
3
|
+
import { CapabilitiesResponse, Client } from "../index-B5faDAC2.js";
|
|
3
4
|
import { UIMessage } from "ai";
|
|
4
5
|
|
|
5
6
|
//#region src/react/use-options.d.ts
|
|
@@ -17,12 +18,12 @@ declare function useOptions({
|
|
|
17
18
|
capabilities,
|
|
18
19
|
messages
|
|
19
20
|
}: {
|
|
20
|
-
agent?: Pick<Client, "
|
|
21
|
+
agent?: Pick<Client, "ui">;
|
|
21
22
|
capabilities?: CapabilitiesResponse;
|
|
22
23
|
messages: UIMessage[];
|
|
23
24
|
}): {
|
|
24
|
-
schema:
|
|
25
|
-
options:
|
|
25
|
+
schema: UIOptionsSchema<UIOptions> | undefined;
|
|
26
|
+
options: UIOptions | undefined;
|
|
26
27
|
setOption: (id: string, value: string) => void;
|
|
27
28
|
loading: boolean;
|
|
28
29
|
error: Error | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{lastUIOptions as e}from"../index.browser-0KfCzcI7.js";import"../validator-DOrmtI_l.js";import"../index.node-DJv-HF6j.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]&&t.defaultValue!==void 0&&(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]);let x=r(void 0),S=r(void 0);n(()=>{a!==S.current&&(S.current=a,p(void 0),v(void 0),l(void 0),d(!0),x.current=void 0)},[a]),n(()=>{if(o&&!o.ui||!a){p(void 0),v(void 0),l(void 0),x.current=void 0;return}let e=_?JSON.stringify(_):``;if(x.current===e){d(!1),l(void 0);return}let t=new AbortController;return d(!0),l(void 0),a.ui(_?{selectedOptions:_}:{},{signal:t.signal}).then(n=>{t.signal.aborted||(p(e=>JSON.stringify(e)===JSON.stringify(n)?e:n),x.current=e)}).catch(e=>{t.signal.aborted||l(e instanceof Error?e:Error(String(e)))}).finally(()=>{d(!1)}),()=>{t.abort()}},[a,o,_]);let C=t((e,t)=>{b({[e]:t})},[b]);return{schema:f,options:_,setOption:C,loading:u,error:c}}export{a as useOptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=(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}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof w?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(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]},o=(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])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),v=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},y=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,S)):e,b=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return y(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=y(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=y(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},x=b,ee=(e,t)=>b(e,t,!0),S=decodeURIComponent,C=e=>p(e,S),w=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?C(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?C(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return x(this.url,e)}queries(e){return ee(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 n(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[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},T=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=>T(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},E=`text/plain; charset=UTF-8`,D=(e,t)=>({"Content-Type":e,...t}),O=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 w(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,D(E,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,D(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,D(`text/html; charset=UTF-8`,n));return typeof e==`object`?T(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},k=`ALL`,re=`all`,A=[`get`,`post`,`put`,`delete`,`options`,`patch`],j=`Can not add a route since the matcher is already built.`,M=class extends Error{},ie=`__COMPOSED_HANDLER`,N=e=>e.text(`404 Not Found`,404),P=(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)},F=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...A,re];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(k,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new F({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=N;errorHandler=P;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===P?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[ie]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(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=_(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(k,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(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(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new O(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(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${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},I=`[^/]+`,L=`.*`,R=`(?:|/.*)`,z=Symbol(),ae=new Set(`.\\+*[^]$()`);function B(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===L||e===R?1:t===L||t===R?-1:e===I?1:t===I?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var V=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw z;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,L]:[``,``,I]:a===`/*`?[``,``,R]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||I;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw z;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==L&&e!==R))throw z;if(i)return;c=this.#children[t]=new V,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!==L&&e!==R))throw z;if(i)return;c=this.#children[a]=new V}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(B),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ae.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(`|`)+`)`}},H=class{#context={varIndex:0};#root=new V;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]}},U=[],W=[/^$/,[],Object.create(null)],G=Object.create(null);function K(e){return G[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function q(){G=Object.create(null)}function oe(e){let t=new H,n=[];if(e.length===0)return W;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)]),U]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===z?new M(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 J(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(K(n).test(t))return[...e[n]]}}var se=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[k]:Object.create(null)},this.#routes={[k]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(j);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[k]).forEach(n=>{t[e][n]=[...t[k][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=K(t);e===k?Object.keys(r).forEach(e=>{r[e][t]||=J(r[e],t)||J(r[k],t)||[]}):r[e][t]||=J(r[e],t)||J(r[k],t)||[],Object.keys(r).forEach(t=>{(e===k||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===k||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=v(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===k||e===o)&&(i[o][c]||=[...J(r[o],c)||J(r[k],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){q();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[k],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],U];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===k;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!==k&&t.push(...Object.keys(r[k]).map(e=>[e,r[k][e]])):(n||=!0,t.push(...i))}),n?oe(t):null}},ce=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(j);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 M)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]}},Y=Object.create(null),X=class{#methods;#children;#patterns;#order=0;#params=Y;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=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(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 X,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[k],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==Y||r&&r!==Y))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=Y;let r=this,i=[r],a=s(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===Y?{}:{...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])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new X}add(e,t,n){let r=v(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},ue=class extends F{constructor(e={}){super(e),this.router=e.router??new ce({routers:[new se,new le]})}},de=/^[\w!#$%&'*.^`|~+-]+$/,Z=/^[ !#-:<-[\]-~]*$/,Q=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!de.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),Z.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,S),t))break}return r},fe=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},pe=(e,t,n)=>(t=encodeURIComponent(t),fe(e,t,n)),me=(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=Q(r,e);return i[e]}if(!r)return{};let i=Q(r);return i},$=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})}},he=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},ge=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,_e=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ve=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ye=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!ge.test(a))break;try{i=await n.req.json()}catch{throw new $(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(_e.test(a)||ve.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 he(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new $(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=me(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};Object.defineProperty(exports,`Hono`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`serialize`,{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,`validator`,{enumerable:!0,get:function(){return ye}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=(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}},t=Symbol(),n=async(e,t=Object.create(null))=>{let{all:n=!1,dot:i=!1}=t,a=e instanceof w?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?r(e,{all:n,dot:i}):{}};async function r(e,t){let n=await e.formData();return n?i(n,t):{}}function i(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?a(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(o(n,e,t),delete n[e])}),n}var a=(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]},o=(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])})},s=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},c=e=>{let{groups:t,path:n}=l(e),r=s(n);return u(r,t)},l=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},u=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},d={},f=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return d[r]||(n[2]?d[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:d[r]=[e,n[1],!0]),d[r]}return null},p=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},m=e=>p(e,decodeURI),h=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.slice(n,e===-1?void 0:e);return m(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},g=e=>{let t=h(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},_=(e,t,...n)=>(n.length&&(t=_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),v=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},y=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:p(e,S)):e,b=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return y(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=y(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=y(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},x=b,ee=(e,t)=>b(e,t,!0),S=decodeURIComponent,C=e=>p(e,S),w=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?C(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?C(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return x(this.url,e)}queries(e){return ee(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 n(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[t](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},T=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=>T(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},E=`text/plain; charset=UTF-8`,D=(e,t)=>({"Content-Type":e,...t}),O=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 w(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,D(E,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,D(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,D(`text/html; charset=UTF-8`,n));return typeof e==`object`?T(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},k=`ALL`,re=`all`,A=[`get`,`post`,`put`,`delete`,`options`,`patch`],j=`Can not add a route since the matcher is already built.`,M=class extends Error{},ie=`__COMPOSED_HANDLER`,N=e=>e.text(`404 Not Found`,404),P=(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)},F=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...A,re];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(k,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??h:g}#clone(){let e=new F({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=N;errorHandler=P;route(t,n){let r=this.basePath(t);return n.routes.map(t=>{let i;n.errorHandler===P?i=t.handler:(i=async(r,i)=>(await e([],n.errorHandler)(r,()=>t.handler(r,i))).res,i[ie]=t.handler),r.#addRoute(t.method,t.path,i)}),this}basePath(e){let t=this.#clone();return t._basePath=_(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=_(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(k,_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=_(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(t,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(t,n,r,`GET`)))();let a=this.getPath(t,{env:r}),o=this.router.match(i,a),s=new O(t,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=e(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,s)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(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${_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},I=`[^/]+`,L=`.*`,R=`(?:|/.*)`,z=Symbol(),ae=new Set(`.\\+*[^]$()`);function B(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===L||e===R?1:t===L||t===R?-1:e===I?1:t===I?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var V=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw z;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,L]:[``,``,I]:a===`/*`?[``,``,R]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||I;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw z;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==L&&e!==R))throw z;if(i)return;c=this.#children[t]=new V,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!==L&&e!==R))throw z;if(i)return;c=this.#children[a]=new V}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(B),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ae.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(`|`)+`)`}},H=class{#context={varIndex:0};#root=new V;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]}},U=[],W=[/^$/,[],Object.create(null)],G=Object.create(null);function K(e){return G[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function q(){G=Object.create(null)}function oe(e){let t=new H,n=[];if(e.length===0)return W;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)]),U]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===z?new M(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 J(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(K(n).test(t))return[...e[n]]}}var se=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[k]:Object.create(null)},this.#routes={[k]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(j);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[k]).forEach(n=>{t[e][n]=[...t[k][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=K(t);e===k?Object.keys(r).forEach(e=>{r[e][t]||=J(r[e],t)||J(r[k],t)||[]}):r[e][t]||=J(r[e],t)||J(r[k],t)||[],Object.keys(r).forEach(t=>{(e===k||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===k||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=v(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===k||e===o)&&(i[o][c]||=[...J(r[o],c)||J(r[k],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){q();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[k],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],U];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===k;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!==k&&t.push(...Object.keys(r[k]).map(e=>[e,r[k][e]])):(n||=!0,t.push(...i))}),n?oe(t):null}},ce=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(j);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 M)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]}},Y=Object.create(null),X=class{#methods;#children;#patterns;#order=0;#params=Y;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=c(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=f(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 X,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[k],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==Y||r&&r!==Y))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=Y;let r=this,i=[r],a=s(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===Y?{}:{...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])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new X}add(e,t,n){let r=v(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},ue=class extends F{constructor(e={}){super(e),this.router=e.router??new ce({routers:[new se,new le]})}},de=/^[\w!#$%&'*.^`|~+-]+$/,Z=/^[ !#-:<-[\]-~]*$/,Q=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!de.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),Z.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:p(a,S),t))break}return r},fe=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith(`__Secure-`)&&!n.secure)throw Error(`__Secure- Cookie must have Secure attributes`);if(e.startsWith(`__Host-`)){if(!n.secure)throw Error(`__Host- Cookie must have Secure attributes`);if(n.path!==`/`)throw Error(`__Host- Cookie must have Path attributes with "/"`);if(n.domain)throw Error(`__Host- Cookie must not have Domain attributes`)}if(n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw Error(`Partitioned Cookie must have Secure attributes`);r+=`; Partitioned`}return r},pe=(e,t,n)=>(t=encodeURIComponent(t),fe(e,t,n)),me=(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=Q(r,e);return i[e]}if(!r)return{};let i=Q(r);return i},$=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})}},he=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},ge=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,_e=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ve=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ye=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!ge.test(a))break;try{i=await n.req.json()}catch{throw new $(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(_e.test(a)||ve.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 he(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new $(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=me(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};export{ue as Hono,pe as serialize,ye as validator};
|
|
@@ -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-
|
|
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};
|