better-call 0.0.5-beta.15 → 0.0.5-beta.17

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/index.d.cts CHANGED
@@ -1,163 +1,6 @@
1
- import { ZodSchema, ZodOptional, z } from 'zod';
2
-
3
- type UnionToIntersection<Union> = (Union extends unknown ? (distributedUnion: Union) => void : never) extends ((mergedIntersection: infer Intersection) => void) ? Intersection & Union : never;
4
- type RequiredKeysOf<BaseType extends object> = Exclude<{
5
- [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;
6
- }[keyof BaseType], undefined>;
7
- type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
8
-
9
- type CookiePrefixOptions = "host" | "secure";
10
-
11
- interface EndpointOptions {
12
- method: Method | Method[];
13
- body?: ZodSchema;
14
- query?: ZodSchema;
15
- params?: ZodSchema<any>;
16
- /**
17
- * If true headers will be required to be passed in the context
18
- */
19
- requireHeaders?: boolean;
20
- /**
21
- * If true request object will be required
22
- */
23
- requireRequest?: boolean;
24
- /**
25
- * List of endpoints that will be called before this endpoint
26
- */
27
- use?: Endpoint[];
28
- }
29
- type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {
30
- path: string;
31
- options: Option;
32
- headers?: Headers;
33
- } & Handler;
34
- type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
35
- [K in Param | keyof InferParamPath<Rest>]: string;
36
- } : Path extends `${infer _Start}:${infer Param}` ? {
37
- [K in Param]: string;
38
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
39
- type InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}` ? {
40
- [K in Param | keyof InferParamPath<Rest>]: string;
41
- } : Path extends `${infer _Start}/*` ? {
42
- [K in "_"]: string;
43
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
44
- type Prettify<T> = {
45
- [key in keyof T]: T[key];
46
- } & {};
47
- interface CookieOptions {
48
- /**
49
- * Max age in seconds
50
- */
51
- maxAge?: number;
52
- /**
53
- * Domain
54
- */
55
- domain?: string;
56
- /**
57
- * Path
58
- */
59
- path?: string;
60
- /**
61
- * Secure
62
- */
63
- secure?: boolean;
64
- /**
65
- * HttpOnly
66
- */
67
- httpOnly?: boolean;
68
- /**
69
- * SameSite
70
- */
71
- sameSite?: "strict" | "lax" | "none";
72
- /**
73
- * Expires
74
- */
75
- expires?: Date;
76
- }
77
- type ContextTools = {
78
- /**
79
- * Set header
80
- *
81
- * If it's called outside of a request it will just be ignored.
82
- */
83
- setHeader: (key: string, value: string) => void;
84
- /**
85
- * cookie setter.
86
- *
87
- * If it's called outside of a request it will just be ignored.
88
- */
89
- setCookie: (key: string, value: string, options?: CookieOptions) => void;
90
- /**
91
- * Get cookie value
92
- *
93
- * If it's called outside of a request it will just be ignored.
94
- */
95
- getCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;
96
- /**
97
- * Set signed cookie
98
- */
99
- setSignedCookie: (key: string, value: string, secret: string | BufferSource, options?: CookieOptions) => Promise<void>;
100
- /**
101
- * Get signed cookie value
102
- */
103
- getSignedCookie: (key: string, secret: string, prefix?: CookiePrefixOptions) => Promise<string | undefined>;
104
- };
105
- type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts["method"]> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
106
- type InferUse<Opts extends EndpointOptions> = Opts["use"] extends Endpoint[] ? {
107
- context: UnionToIntersection<Awaited<ReturnType<Opts["use"][number]>>>;
108
- } : {};
109
- type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U["options"] : {
110
- body?: {};
111
- requireRequest?: boolean;
112
- requireHeaders?: boolean;
113
- }> : {
114
- body?: {};
115
- requireRequest?: boolean;
116
- requireHeaders?: boolean;
117
- };
118
- type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {
119
- method: M[number];
120
- } : {
121
- method?: M;
122
- };
123
- type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt["requireHeaders"]> = HeaderReq extends true ? {
124
- headers: Headers;
125
- } : InferUseOptions<Opt>["requireHeaders"] extends true ? {
126
- headers: Headers;
127
- } : {
128
- headers?: Headers;
129
- };
130
- type InferRequest<Opt extends EndpointOptions, RequestReq = Opt["requireRequest"]> = RequestReq extends true ? {
131
- request: Request;
132
- } : InferUseOptions<Opt>["requireRequest"] extends true ? {
133
- request: Request;
134
- } : {
135
- request?: Request;
136
- };
137
- type InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {
138
- query?: z.infer<Query>;
139
- } : {
140
- query: z.infer<Query>;
141
- } : {
142
- query?: undefined;
143
- };
144
- type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {
145
- params?: Record<string, string>;
146
- } : {
147
- params: WildCard;
148
- } : {
149
- params: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;
150
- };
151
- type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;
152
- type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;
153
- type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
154
- type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = Opts["body"] & (undefined extends InferUseOptions<Opts>["body"] ? {} : InferUseOptions<Opts>["body"])> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {
155
- body?: Prettify<z.infer<Body>>;
156
- } : {
157
- body: Prettify<z.infer<Body>>;
158
- } : {
159
- body?: undefined;
160
- };
1
+ import { E as EndpointOptions, a as EndpointResponse, H as Handler, b as HasRequiredKeys, C as Context, M as Method, P as Prettify, I as InferBody, c as InferRequest, d as InferHeaders, e as ContextTools, f as Endpoint } from './router-Ch0Zw3Im.cjs';
2
+ export { j as CookieOptions, m as InferMethod, o as InferParam, h as InferParamPath, i as InferParamWildCard, n as InferQuery, k as InferUse, l as InferUseOptions, R as Router, g as createRouter } from './router-Ch0Zw3Im.cjs';
3
+ import 'zod';
161
4
 
162
5
  interface EndpointConfig {
163
6
  /**
@@ -180,32 +23,6 @@ declare function createEndpoint<Path extends string, Opts extends EndpointOption
180
23
  headers: Headers;
181
24
  };
182
25
 
183
- interface RouterConfig {
184
- /**
185
- * Throw error if error occurred other than APIError
186
- */
187
- throwError?: boolean;
188
- /**
189
- * Handle error
190
- */
191
- onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;
192
- /**
193
- * Base path for the router
194
- */
195
- basePath?: string;
196
- /**
197
- * Middlewares for the router
198
- */
199
- routerMiddleware?: {
200
- path: string;
201
- middleware: Endpoint;
202
- }[];
203
- extraContext?: Record<string, any>;
204
- }
205
- declare const createRouter: <E extends Endpoint, Config extends RouterConfig>(endpoints: E[], config?: Config) => {
206
- handler: (request: Request) => Promise<Response>;
207
- };
208
-
209
26
  type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {
210
27
  params?: Record<string, string>;
211
28
  query?: Record<string, string>;
@@ -296,4 +113,4 @@ declare class APIError extends Error {
296
113
  constructor(status: Status, body?: Record<string, any>);
297
114
  }
298
115
 
299
- export { APIError, type Context, type ContextTools, type CookieOptions, type Endpoint, type EndpointConfig, type EndpointOptions, type EndpointResponse, type Handler, type InferBody, type InferHeaders, type InferMethod, type InferParam, type InferParamPath, type InferParamWildCard, type InferQuery, type InferRequest, type InferUse, type InferUseOptions, type Method, type Middleware, type MiddlewareHandler, type Prettify, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, createRouter, getBody, shouldSerialize, statusCode };
116
+ export { APIError, Context, ContextTools, Endpoint, type EndpointConfig, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Method, type Middleware, type MiddlewareHandler, Prettify, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, getBody, shouldSerialize, statusCode };
package/dist/index.d.ts CHANGED
@@ -1,163 +1,6 @@
1
- import { ZodSchema, ZodOptional, z } from 'zod';
2
-
3
- type UnionToIntersection<Union> = (Union extends unknown ? (distributedUnion: Union) => void : never) extends ((mergedIntersection: infer Intersection) => void) ? Intersection & Union : never;
4
- type RequiredKeysOf<BaseType extends object> = Exclude<{
5
- [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;
6
- }[keyof BaseType], undefined>;
7
- type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
8
-
9
- type CookiePrefixOptions = "host" | "secure";
10
-
11
- interface EndpointOptions {
12
- method: Method | Method[];
13
- body?: ZodSchema;
14
- query?: ZodSchema;
15
- params?: ZodSchema<any>;
16
- /**
17
- * If true headers will be required to be passed in the context
18
- */
19
- requireHeaders?: boolean;
20
- /**
21
- * If true request object will be required
22
- */
23
- requireRequest?: boolean;
24
- /**
25
- * List of endpoints that will be called before this endpoint
26
- */
27
- use?: Endpoint[];
28
- }
29
- type Endpoint<Handler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>, Option extends EndpointOptions = EndpointOptions> = {
30
- path: string;
31
- options: Option;
32
- headers?: Headers;
33
- } & Handler;
34
- type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
35
- [K in Param | keyof InferParamPath<Rest>]: string;
36
- } : Path extends `${infer _Start}:${infer Param}` ? {
37
- [K in Param]: string;
38
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
39
- type InferParamWildCard<Path> = Path extends `${infer _Start}/*:${infer Param}/${infer Rest}` | `${infer _Start}/**:${infer Param}/${infer Rest}` ? {
40
- [K in Param | keyof InferParamPath<Rest>]: string;
41
- } : Path extends `${infer _Start}/*` ? {
42
- [K in "_"]: string;
43
- } : Path extends `${infer _Start}/${infer Rest}` ? InferParamPath<Rest> : undefined;
44
- type Prettify<T> = {
45
- [key in keyof T]: T[key];
46
- } & {};
47
- interface CookieOptions {
48
- /**
49
- * Max age in seconds
50
- */
51
- maxAge?: number;
52
- /**
53
- * Domain
54
- */
55
- domain?: string;
56
- /**
57
- * Path
58
- */
59
- path?: string;
60
- /**
61
- * Secure
62
- */
63
- secure?: boolean;
64
- /**
65
- * HttpOnly
66
- */
67
- httpOnly?: boolean;
68
- /**
69
- * SameSite
70
- */
71
- sameSite?: "strict" | "lax" | "none";
72
- /**
73
- * Expires
74
- */
75
- expires?: Date;
76
- }
77
- type ContextTools = {
78
- /**
79
- * Set header
80
- *
81
- * If it's called outside of a request it will just be ignored.
82
- */
83
- setHeader: (key: string, value: string) => void;
84
- /**
85
- * cookie setter.
86
- *
87
- * If it's called outside of a request it will just be ignored.
88
- */
89
- setCookie: (key: string, value: string, options?: CookieOptions) => void;
90
- /**
91
- * Get cookie value
92
- *
93
- * If it's called outside of a request it will just be ignored.
94
- */
95
- getCookie: (key: string, value: string, options?: CookieOptions) => string | undefined;
96
- /**
97
- * Set signed cookie
98
- */
99
- setSignedCookie: (key: string, value: string, secret: string | BufferSource, options?: CookieOptions) => Promise<void>;
100
- /**
101
- * Get signed cookie value
102
- */
103
- getSignedCookie: (key: string, secret: string, prefix?: CookiePrefixOptions) => Promise<string | undefined>;
104
- };
105
- type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> & InferParam<Path> & InferMethod<Opts["method"]> & InferHeaders<Opts> & InferRequest<Opts> & InferQuery<Opts["query"]>;
106
- type InferUse<Opts extends EndpointOptions> = Opts["use"] extends Endpoint[] ? {
107
- context: UnionToIntersection<Awaited<ReturnType<Opts["use"][number]>>>;
108
- } : {};
109
- type InferUseOptions<Opts extends EndpointOptions> = Opts["use"] extends Array<infer U> ? UnionToIntersection<U extends Endpoint ? U["options"] : {
110
- body?: {};
111
- requireRequest?: boolean;
112
- requireHeaders?: boolean;
113
- }> : {
114
- body?: {};
115
- requireRequest?: boolean;
116
- requireHeaders?: boolean;
117
- };
118
- type InferMethod<M extends Method | Method[]> = M extends Array<Method> ? {
119
- method: M[number];
120
- } : {
121
- method?: M;
122
- };
123
- type InferHeaders<Opt extends EndpointOptions, HeaderReq = Opt["requireHeaders"]> = HeaderReq extends true ? {
124
- headers: Headers;
125
- } : InferUseOptions<Opt>["requireHeaders"] extends true ? {
126
- headers: Headers;
127
- } : {
128
- headers?: Headers;
129
- };
130
- type InferRequest<Opt extends EndpointOptions, RequestReq = Opt["requireRequest"]> = RequestReq extends true ? {
131
- request: Request;
132
- } : InferUseOptions<Opt>["requireRequest"] extends true ? {
133
- request: Request;
134
- } : {
135
- request?: Request;
136
- };
137
- type InferQuery<Query> = Query extends ZodSchema ? Query extends ZodOptional<any> ? {
138
- query?: z.infer<Query>;
139
- } : {
140
- query: z.infer<Query>;
141
- } : {
142
- query?: undefined;
143
- };
144
- type InferParam<Path extends string, ParamPath extends InferParamPath<Path> = InferParamPath<Path>, WildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>> = ParamPath extends undefined ? WildCard extends undefined ? {
145
- params?: Record<string, string>;
146
- } : {
147
- params: WildCard;
148
- } : {
149
- params: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;
150
- };
151
- type EndpointResponse = Record<string, any> | string | boolean | number | void | undefined;
152
- type Handler<Path extends string, Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts> & ContextTools> & Extra) => Promise<R>;
153
- type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "*";
154
- type InferBody<Opts extends EndpointOptions, Body extends ZodSchema | undefined = Opts["body"] & (undefined extends InferUseOptions<Opts>["body"] ? {} : InferUseOptions<Opts>["body"])> = Body extends ZodSchema ? Body extends ZodOptional<any> ? {
155
- body?: Prettify<z.infer<Body>>;
156
- } : {
157
- body: Prettify<z.infer<Body>>;
158
- } : {
159
- body?: undefined;
160
- };
1
+ import { E as EndpointOptions, a as EndpointResponse, H as Handler, b as HasRequiredKeys, C as Context, M as Method, P as Prettify, I as InferBody, c as InferRequest, d as InferHeaders, e as ContextTools, f as Endpoint } from './router-Ch0Zw3Im.js';
2
+ export { j as CookieOptions, m as InferMethod, o as InferParam, h as InferParamPath, i as InferParamWildCard, n as InferQuery, k as InferUse, l as InferUseOptions, R as Router, g as createRouter } from './router-Ch0Zw3Im.js';
3
+ import 'zod';
161
4
 
162
5
  interface EndpointConfig {
163
6
  /**
@@ -180,32 +23,6 @@ declare function createEndpoint<Path extends string, Opts extends EndpointOption
180
23
  headers: Headers;
181
24
  };
182
25
 
183
- interface RouterConfig {
184
- /**
185
- * Throw error if error occurred other than APIError
186
- */
187
- throwError?: boolean;
188
- /**
189
- * Handle error
190
- */
191
- onError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;
192
- /**
193
- * Base path for the router
194
- */
195
- basePath?: string;
196
- /**
197
- * Middlewares for the router
198
- */
199
- routerMiddleware?: {
200
- path: string;
201
- middleware: Endpoint;
202
- }[];
203
- extraContext?: Record<string, any>;
204
- }
205
- declare const createRouter: <E extends Endpoint, Config extends RouterConfig>(endpoints: E[], config?: Config) => {
206
- handler: (request: Request) => Promise<Response>;
207
- };
208
-
209
26
  type MiddlewareHandler<Opts extends EndpointOptions, R extends EndpointResponse, Extra extends Record<string, any> = {}> = (ctx: Prettify<InferBody<Opts> & InferRequest<Opts> & InferHeaders<Opts> & {
210
27
  params?: Record<string, string>;
211
28
  query?: Record<string, string>;
@@ -296,4 +113,4 @@ declare class APIError extends Error {
296
113
  constructor(status: Status, body?: Record<string, any>);
297
114
  }
298
115
 
299
- export { APIError, type Context, type ContextTools, type CookieOptions, type Endpoint, type EndpointConfig, type EndpointOptions, type EndpointResponse, type Handler, type InferBody, type InferHeaders, type InferMethod, type InferParam, type InferParamPath, type InferParamWildCard, type InferQuery, type InferRequest, type InferUse, type InferUseOptions, type Method, type Middleware, type MiddlewareHandler, type Prettify, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, createRouter, getBody, shouldSerialize, statusCode };
116
+ export { APIError, Context, ContextTools, Endpoint, type EndpointConfig, EndpointOptions, EndpointResponse, Handler, InferBody, InferHeaders, InferRequest, Method, type Middleware, type MiddlewareHandler, Prettify, createEndpoint, createEndpointCreator, createMiddleware, createMiddlewareCreator, getBody, shouldSerialize, statusCode };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var L=Object.defineProperty;var $=(r,e,t)=>e in r?L(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var l=(r,e,t)=>$(r,typeof e!="symbol"?e+"":e,t);import{ZodError as F}from"zod";import"zod";function V(r,e){if(typeof r=="function")return y("*",{method:"*"},r);if(!e)throw new Error("Middleware handler is required");return y("*",{...r,method:"*"},e)}var j=()=>{function r(e,t){if(typeof e=="function")return y("*",{method:"*"},e);if(!t)throw new Error("Middleware handler is required");return y("*",{...e,method:"*"},t)}return r};var m=class extends Error{constructor(t,n){super(`API Error: ${t} ${n?.message??""}`,{cause:n});l(this,"status");l(this,"body");this.status=t,this.body=n??{},this.stack="",this.name="BetterCallAPIError"}};var g={name:"HMAC",hash:"SHA-256"},_=async r=>{let e=typeof r=="string"?new TextEncoder().encode(r):r;return await crypto.subtle.importKey("raw",e,g,!1,["sign","verify"])},Q=async(r,e)=>{let t=await _(e),n=await crypto.subtle.sign(g.name,t,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(n)))},W=async(r,e,t)=>{try{let n=atob(r),s=new Uint8Array(n.length);for(let o=0,i=n.length;o<i;o++)s[o]=n.charCodeAt(o);return await crypto.subtle.verify(g,t,s,new TextEncoder().encode(e))}catch{return!1}},K=/^[\w!#$%&'*.^`|~+-]+$/,v=/^[ !#-:<-[\]-~]*$/,R=(r,e)=>r.trim().split(";").reduce((n,s)=>{s=s.trim();let o=s.indexOf("=");if(o===-1)return n;let i=s.substring(0,o).trim();if(e&&e!==i||!K.test(i))return n;let p=s.substring(o+1).trim();return p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1)),v.test(p)&&(n[i]=decodeURIComponent(p)),n},{}),w=async(r,e,t)=>{let n={},s=await _(e);for(let[o,i]of Object.entries(R(r,t))){let p=i.lastIndexOf(".");if(p<1)continue;let a=i.substring(0,p),d=i.substring(p+1);if(d.length!==44||!d.endsWith("="))continue;let u=await W(d,a,s);n[o]=u?a:!1}return n},I=(r,e,t={})=>{let n=`${r}=${e}`;if(r.startsWith("__Secure-")&&!t.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(r.startsWith("__Host-")){if(!t.secure)throw new Error("__Host- Cookie must have Secure attributes");if(t.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(t.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(t&&typeof t.maxAge=="number"&&t.maxAge>=0){if(t.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(t.maxAge)}`}if(t.domain&&t.prefix!=="host"&&(n+=`; Domain=${t.domain}`),t.path&&(n+=`; Path=${t.path}`),t.expires){if(t.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${t.expires.toUTCString()}`}if(t.httpOnly&&(n+="; HttpOnly"),t.secure&&(n+="; Secure"),t.sameSite&&(n+=`; SameSite=${t.sameSite.charAt(0).toUpperCase()+t.sameSite.slice(1)}`),t.partitioned){if(!t.secure)throw new Error("Partitioned Cookie must have Secure attributes");n+="; Partitioned"}return n},x=(r,e,t)=>(e=encodeURIComponent(e),I(r,e,t)),h=async(r,e,t,n={})=>{let s=await Q(e,t);return e=`${e}.${s}`,e=encodeURIComponent(e),I(r,e,n)};var k=(r,e,t)=>{if(!r)return;let n=e;if(t==="secure")n="__Secure-"+e;else if(t==="host")n="__Host-"+e;else return;return R(r,n)[n]},b=(r,e,t,n)=>{let s;n?.prefix==="secure"?s=x("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?s=x("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):s=x(e,t,{path:"/",...n}),r.append("Set-Cookie",s)},A=async(r,e,t,n,s)=>{let o;s?.prefix==="secure"?o=await h("__Secure-"+e,t,n,{path:"/",...s,secure:!0}):s?.prefix==="host"?o=await h("__Host-"+e,t,n,{...s,path:"/",secure:!0,domain:void 0}):o=await h(e,t,n,{path:"/",...s}),r.append("Set-Cookie",o)},H=async(r,e,t,n)=>{let s=r.get("Cookie");if(!s)return;let o=t;return n==="secure"?o="__Secure-"+t:n==="host"&&(o="__Host-"+t),(await w(s,e,o))[o]};function ue(){return(r,e,t)=>y(r,e,t)}function y(r,e,t){let n=new Headers,s=async(...o)=>{let i={setHeader(a,d){n.set(a,d)},setCookie(a,d,u){b(n,a,d,u)},getCookie(a,d){let u=o[0]?.headers;return k(u?.get("Cookie")||"",a,d)},getSignedCookie(a,d,u){let c=o[0]?.headers;if(!c)throw new TypeError("Headers are required");return H(c,d,a,u)},async setSignedCookie(a,d,u,c){await A(n,a,d,u,c)},...o[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let d=await a(i),u=d.options?.body?d.options.body.parse(i.body):void 0;d&&(i={...i,body:u?{...u,...i.body}:i.body,context:{...i.context||{},...d}})}try{let a=e.body?e.body.parse(i.body):i.body;i={...i,body:a?{...a,...i.body}:i.body},i.query=e.query?e.query.parse(i.query):i.query,i.params=e.params?e.params.parse(i.params):i.params}catch(a){throw a instanceof F?new m("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!i.headers)throw new m("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!i.request)throw new m("BAD_REQUEST",{message:"Request is required"});return await t(i)};return s.path=r,s.options=e,s.method=e.method,s.headers=n,s}import{createRouter as M,addRoute as C,findRoute as q}from"rou3";async function N(r){let e=r.headers.get("content-type")||"";if(r.body){if(e.includes("application/json"))return await r.json();if(e.includes("application/x-www-form-urlencoded")){let t=await r.formData(),n={};return t.forEach((s,o)=>{n[o]=s.toString()}),n}if(e.includes("multipart/form-data")){let t=await r.formData(),n={};return t.forEach((s,o)=>{n[o]=s}),n}return e.includes("text/plain")?await r.text():e.includes("application/octet-stream")?await r.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await r.blob():e.includes("application/stream")||r.body instanceof ReadableStream?r.body:await r.text()}}function D(r){return typeof r=="object"&&r!==null&&!(r instanceof Blob)&&!(r instanceof FormData)}var U={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var xe=(r,e)=>{let t=M();for(let o of r)if(Array.isArray(o.options?.method))for(let i of o.options.method)C(t,i,o.path,o);else C(t,o.options.method,o.path,o);let n=M();for(let o of e?.routerMiddleware||[])C(n,"*",o.path,o.middleware);return{handler:async o=>{let i=new URL(o.url),p=i.pathname;e?.basePath&&(p=p.split(e.basePath)[1]);let a=o.method,d=q(t,a,p),u=d?.data,c=await N(o),O=o.headers,P=Object.fromEntries(i.searchParams),T=q(n,"*",p)?.data;if(!u)return new Response(null,{status:404,statusText:"Not Found"});try{let f={};if(T){let S=await T({path:p,method:a,headers:O,params:d?.params,request:o,body:c,query:P,...e?.extraContext});S&&(f={...S,...f})}let E=await u({path:p,method:a,headers:O,params:d?.params,request:o,body:c,query:P,...f,...e?.extraContext});if(E instanceof Response)return E;let B=D(E)?JSON.stringify(E):E;return new Response(B,{headers:u.headers})}catch(f){if(e?.onError){let E=await e.onError(f);if(E instanceof Response)return E}if(f instanceof m)return new Response(f.body?JSON.stringify(f.body):null,{status:U[f.status],statusText:f.status,headers:u.headers});if(e?.throwError)throw f;return new Response(null,{status:500,statusText:"Internal Server Error"})}}}};import"zod";export{m as APIError,y as createEndpoint,ue as createEndpointCreator,V as createMiddleware,j as createMiddlewareCreator,xe as createRouter,N as getBody,D as shouldSerialize,U as statusCode};
1
+ var $=Object.defineProperty;var Q=(r,e,t)=>e in r?$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var l=(r,e,t)=>Q(r,typeof e!="symbol"?e+"":e,t);import{ZodError as G}from"zod";import"zod";function j(r,e){if(typeof r=="function")return m("*",{method:"*"},r);if(!e)throw new Error("Middleware handler is required");return m("*",{...r,method:"*"},e)}var X=()=>{function r(e,t){if(typeof e=="function")return m("*",{method:"*"},e);if(!t)throw new Error("Middleware handler is required");return m("*",{...e,method:"*"},t)}return r};var y=class extends Error{constructor(t,n){super(`API Error: ${t} ${n?.message??""}`,{cause:n});l(this,"status");l(this,"body");this.status=t,this.body=n??{},this.stack="",this.name="BetterCallAPIError"}};var g={name:"HMAC",hash:"SHA-256"},w=async r=>{let e=typeof r=="string"?new TextEncoder().encode(r):r;return await crypto.subtle.importKey("raw",e,g,!1,["sign","verify"])},W=async(r,e)=>{let t=await w(e),n=await crypto.subtle.sign(g.name,t,new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(n)))},v=async(r,e,t)=>{try{let n=atob(r),s=new Uint8Array(n.length);for(let i=0,o=n.length;i<o;i++)s[i]=n.charCodeAt(i);return await crypto.subtle.verify(g,t,s,new TextEncoder().encode(e))}catch{return!1}},K=/^[\w!#$%&'*.^`|~+-]+$/,F=/^[ !#-:<-[\]-~]*$/,R=(r,e)=>r.trim().split(";").reduce((n,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return n;let o=s.substring(0,i).trim();if(e&&e!==o||!K.test(o))return n;let p=s.substring(i+1).trim();return p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1)),F.test(p)&&(n[o]=decodeURIComponent(p)),n},{}),I=async(r,e,t)=>{let n={},s=await w(e);for(let[i,o]of Object.entries(R(r,t))){let p=o.lastIndexOf(".");if(p<1)continue;let a=o.substring(0,p),d=o.substring(p+1);if(d.length!==44||!d.endsWith("="))continue;let u=await v(d,a,s);n[i]=u?a:!1}return n},k=(r,e,t={})=>{let n=`${r}=${e}`;if(r.startsWith("__Secure-")&&!t.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(r.startsWith("__Host-")){if(!t.secure)throw new Error("__Host- Cookie must have Secure attributes");if(t.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(t.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(t&&typeof t.maxAge=="number"&&t.maxAge>=0){if(t.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(t.maxAge)}`}if(t.domain&&t.prefix!=="host"&&(n+=`; Domain=${t.domain}`),t.path&&(n+=`; Path=${t.path}`),t.expires){if(t.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${t.expires.toUTCString()}`}if(t.httpOnly&&(n+="; HttpOnly"),t.secure&&(n+="; Secure"),t.sameSite&&(n+=`; SameSite=${t.sameSite.charAt(0).toUpperCase()+t.sameSite.slice(1)}`),t.partitioned){if(!t.secure)throw new Error("Partitioned Cookie must have Secure attributes");n+="; Partitioned"}return n},x=(r,e,t)=>(e=encodeURIComponent(e),k(r,e,t)),h=async(r,e,t,n={})=>{let s=await W(e,t);return e=`${e}.${s}`,e=encodeURIComponent(e),k(r,e,n)};var b=(r,e,t)=>{if(!r)return;let n=e;if(t==="secure")n="__Secure-"+e;else if(t==="host")n="__Host-"+e;else return;return R(r,n)[n]},A=(r,e,t,n)=>{let s;n?.prefix==="secure"?s=x("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?s=x("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):s=x(e,t,{path:"/",...n}),r.append("Set-Cookie",s)},H=async(r,e,t,n,s)=>{let i;s?.prefix==="secure"?i=await h("__Secure-"+e,t,n,{path:"/",...s,secure:!0}):s?.prefix==="host"?i=await h("__Host-"+e,t,n,{...s,path:"/",secure:!0,domain:void 0}):i=await h(e,t,n,{path:"/",...s}),r.append("Set-Cookie",i)},N=async(r,e,t,n)=>{let s=r.get("Cookie");if(!s)return;let i=t;return n==="secure"?i="__Secure-"+t:n==="host"&&(i="__Host-"+t),(await I(s,e,i))[i]};function fe(){return(r,e,t)=>m(r,e,t)}function m(r,e,t){let n=new Headers,s=async(...i)=>{let o={setHeader(a,d){n.set(a,d)},setCookie(a,d,u){A(n,a,d,u)},getCookie(a,d){let u=i[0]?.headers;return b(u?.get("Cookie")||"",a,d)},getSignedCookie(a,d,u){let c=i[0]?.headers;if(!c)throw new TypeError("Headers are required");return N(c,d,a,u)},async setSignedCookie(a,d,u,c){await H(n,a,d,u,c)},...i[0]||{},context:{}};if(e.use?.length)for(let a of e.use){let d=await a(o),u=d.options?.body?d.options.body.parse(o.body):void 0;d&&(o={...o,body:u?{...u,...o.body}:o.body,context:{...o.context||{},...d}})}try{let a=e.body?e.body.parse(o.body):o.body;o={...o,body:a?{...a,...o.body}:o.body},o.query=e.query?e.query.parse(o.query):o.query,o.params=e.params?e.params.parse(o.params):o.params}catch(a){throw a instanceof G?new y("BAD_REQUEST",{message:a.message,details:a.errors}):a}if(e.requireHeaders&&!o.headers)throw new y("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!o.request)throw new y("BAD_REQUEST",{message:"Request is required"});return await t(o)};return s.path=r,s.options=e,s.method=e.method,s.headers=n,s}import{createRouter as q,addRoute as C,findRoute as B}from"rou3";async function D(r){let e=r.headers.get("content-type")||"";if(r.body){if(e.includes("application/json"))return await r.json();if(e.includes("application/x-www-form-urlencoded")){let t=await r.formData(),n={};return t.forEach((s,i)=>{n[i]=s.toString()}),n}if(e.includes("multipart/form-data")){let t=await r.formData(),n={};return t.forEach((s,i)=>{n[i]=s}),n}return e.includes("text/plain")?await r.text():e.includes("application/octet-stream")?await r.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await r.blob():e.includes("application/stream")||r.body instanceof ReadableStream?r.body:await r.text()}}function U(r){return typeof r=="object"&&r!==null&&!(r instanceof Blob)&&!(r instanceof FormData)}var M={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var he=(r,e)=>{let t=Object.values(r),n=q();for(let o of t)if(Array.isArray(o.options?.method))for(let p of o.options.method)C(n,p,o.path,o);else C(n,o.options.method,o.path,o);let s=q();for(let o of e?.routerMiddleware||[])C(s,"*",o.path,o.middleware);return{handler:async o=>{let p=new URL(o.url),a=p.pathname;e?.basePath&&(a=a.split(e.basePath)[1]);let d=o.method,u=B(n,d,a),c=u?.data,O=await D(o),P=o.headers,T=Object.fromEntries(p.searchParams),S=B(s,"*",a)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let f={};if(S){let _=await S({path:a,method:d,headers:P,params:u?.params,request:o,body:O,query:T,...e?.extraContext});_&&(f={..._,...f})}let E=await c({path:a,method:d,headers:P,params:u?.params,request:o,body:O,query:T,...f,...e?.extraContext});if(E instanceof Response)return E;let L=U(E)?JSON.stringify(E):E;return new Response(L,{headers:c.headers})}catch(f){if(e?.onError){let E=await e.onError(f);if(E instanceof Response)return E}if(f instanceof y)return new Response(f.body?JSON.stringify(f.body):null,{status:M[f.status],statusText:f.status,headers:c.headers});if(e?.throwError)throw f;return new Response(null,{status:500,statusText:"Internal Server Error"})}},endpoints:r}};import"zod";export{y as APIError,m as createEndpoint,fe as createEndpointCreator,j as createMiddleware,X as createMiddlewareCreator,he as createRouter,D as getBody,U as shouldSerialize,M as statusCode};
2
2
  //# sourceMappingURL=index.js.map