blink 0.1.71 → 0.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/browser/agent/client/index.cjs +21 -0
  2. package/dist/browser/agent/client/index.d.cts +4 -0
  3. package/dist/browser/agent/client/index.d.ts +4 -0
  4. package/dist/browser/agent/client/index.js +21 -0
  5. package/dist/browser/agent/index.browser.cjs +1 -0
  6. package/dist/browser/agent/index.browser.d.cts +3 -0
  7. package/dist/browser/agent/index.browser.d.ts +3 -0
  8. package/dist/browser/agent/index.browser.js +1 -0
  9. package/dist/browser/chat-B5eFQu26.d.cts +129 -0
  10. package/dist/browser/chat-BN7SYTWY.d.ts +129 -0
  11. package/dist/browser/control/index.cjs +1 -0
  12. package/dist/browser/control/index.d.cts +187 -0
  13. package/dist/browser/control/index.d.ts +187 -0
  14. package/dist/browser/control/index.js +1 -0
  15. package/dist/browser/index-B5faDAC2.d.ts +53 -0
  16. package/dist/browser/index-C-GJWB97.d.cts +53 -0
  17. package/dist/browser/index.browser-09e-NXpn.cjs +1 -0
  18. package/dist/browser/index.browser-0KfCzcI7.js +1 -0
  19. package/dist/browser/index.browser-BUMCZUeQ.d.ts +180 -0
  20. package/dist/browser/index.browser-CnGab8Yp.d.cts +180 -0
  21. package/dist/browser/index.node-DJv-HF6j.js +3 -0
  22. package/dist/browser/index.node-mda_IL6K.cjs +3 -0
  23. package/dist/browser/react/index.cjs +1 -1
  24. package/dist/browser/react/index.d.cts +6 -5
  25. package/dist/browser/react/index.d.ts +6 -5
  26. package/dist/browser/react/index.js +1 -1
  27. package/dist/browser/validator-CvSEfFnI.cjs +1 -0
  28. package/dist/browser/validator-DOrmtI_l.js +1 -0
  29. package/dist/cli/{dev-Cr9A596F.js → dev-C5lfmoC7.js} +99 -103
  30. package/dist/cli/index.js +2 -2
  31. package/dist/cli/{init-LfebhEg-.js → init-DRNYG3Kd.js} +23 -21
  32. package/dist/node/agent/index.node.cjs +10 -0
  33. package/dist/node/agent/index.node.d.cts +2 -0
  34. package/dist/node/agent/index.node.d.ts +2 -0
  35. package/dist/node/agent/index.node.js +10 -0
  36. package/dist/node/index.node-BBpGHHxe.d.ts +460 -0
  37. package/dist/node/index.node-iaeCqAo6.d.cts +460 -0
  38. package/dist/node/test.d.cts +20 -50
  39. package/dist/node/test.d.ts +20 -50
  40. package/package.json +21 -19
  41. package/dist/browser/api/index.browser.cjs +0 -1
  42. package/dist/browser/api/index.browser.d.cts +0 -2
  43. package/dist/browser/api/index.browser.d.ts +0 -2
  44. package/dist/browser/api/index.browser.js +0 -1
  45. package/dist/browser/client-BNZw1xmD.d.ts +0 -94
  46. package/dist/browser/client-BbZudkEc.js +0 -21
  47. package/dist/browser/client-DFaZjb1-.cjs +0 -21
  48. package/dist/browser/client-pA8tYXh4.d.cts +0 -94
  49. package/dist/browser/http/index.cjs +0 -1
  50. package/dist/browser/http/index.d.cts +0 -207
  51. package/dist/browser/http/index.d.ts +0 -207
  52. package/dist/browser/http/index.js +0 -1
  53. package/dist/browser/index.browser-BwGhLjB7.cjs +0 -1
  54. package/dist/browser/index.browser-C4ugtCzv.d.cts +0 -312
  55. package/dist/browser/index.browser-Dj8kjB6X.js +0 -1
  56. package/dist/browser/index.browser-U_1Biz16.d.ts +0 -312
  57. package/dist/node/api/index.node.cjs +0 -30
  58. package/dist/node/api/index.node.d.cts +0 -82
  59. package/dist/node/api/index.node.d.ts +0 -82
  60. package/dist/node/api/index.node.js +0 -30
  61. package/dist/node/index.browser-BD5kUTEx.d.cts +0 -312
  62. package/dist/node/index.browser-CHE_CNu8.d.ts +0 -312
@@ -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(`../client-DFaZjb1-.cjs`),t=require(`../index.browser-BwGhLjB7.cjs`);let n=require(`react`);n=e.__toESM(n);function r({agent:e,capabilities:r,messages:i}){let[a,o]=(0,n.useState)(void 0),[s,c]=(0,n.useState)(!0),[l,u]=(0,n.useState)(void 0),d=(0,n.useRef)(l);(0,n.useEffect)(()=>{d.current=l},[l]);let[f,p]=(0,n.useState)(()=>t.lastUIOptions(i));(0,n.useEffect)(()=>{p(e=>{let n=t.lastUIOptions(i);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[i]);let[m,h]=(0,n.useState)(void 0),g=(0,n.useCallback)((e,t)=>{if(!d.current)return!1;let n=d.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,n.useCallback)(e=>{h(t=>{let n={...f,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(d.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[f,g]);(0,n.useEffect)(()=>{if(!f&&!l){h(void 0);return}_()},[f,l,_]);let v=(0,n.useRef)(void 0),y=(0,n.useRef)(void 0);(0,n.useEffect)(()=>{e!==y.current&&(y.current=e,u(void 0),h(void 0),o(void 0),c(!0),v.current=void 0)},[e]),(0,n.useEffect)(()=>{if(r&&!r.options||!e){u(void 0),h(void 0),o(void 0),v.current=void 0;return}let t=m?JSON.stringify(m):``;if(v.current===t){c(!1),o(void 0);return}let n=new AbortController;return c(!0),o(void 0),e.provideUIOptions(m?{selectedOptions:m}:{},{signal:n.signal}).then(e=>{n.signal.aborted||(u(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{n.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{n.abort()}},[e,r,m]);let b=(0,n.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:l,options:m,setOption:b,loading:s,error:a}}exports.useOptions=r;
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 { Options, OptionsSchema } from "../index.browser-C4ugtCzv.cjs";
2
- import { CapabilitiesResponse, Client } from "../client-pA8tYXh4.cjs";
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, "provideUIOptions">;
21
+ agent?: Pick<Client, "ui">;
21
22
  capabilities?: CapabilitiesResponse;
22
23
  messages: UIMessage[];
23
24
  }): {
24
- schema: OptionsSchema<Options> | undefined;
25
- options: Options | undefined;
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 { Options, OptionsSchema } from "../index.browser-U_1Biz16.js";
2
- import { CapabilitiesResponse, Client } from "../client-BNZw1xmD.js";
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, "provideUIOptions">;
21
+ agent?: Pick<Client, "ui">;
21
22
  capabilities?: CapabilitiesResponse;
22
23
  messages: UIMessage[];
23
24
  }): {
24
- schema: OptionsSchema<Options> | undefined;
25
- options: Options | undefined;
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"../client-BbZudkEc.js";import{lastUIOptions as e}from"../index.browser-Dj8kjB6X.js";import{useCallback as t,useEffect as n,useRef as r,useState as i}from"react";function a({agent:a,capabilities:o,messages:s}){let[c,l]=i(void 0),[u,d]=i(!0),[f,p]=i(void 0),m=r(f);n(()=>{m.current=f},[f]);let[h,g]=i(()=>e(s));n(()=>{g(t=>{let n=e(s);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[s]);let[_,v]=i(void 0),y=t((e,t)=>{if(!m.current)return!1;let n=m.current[e];return n?n.values.some(e=>e.id===t):!1},[]),b=t(e=>{v(t=>{let n={...h,...t,...e};for(let[e,t]of Object.entries(n))y(e,t)||delete n[e];for(let[e,t]of Object.entries(m.current??{}))!n[e]&&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.options||!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.provideUIOptions(_?{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};
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};