better-call 0.3.3 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/set-cookie-parser/lib/set-cookie.js","../src/endpoint.ts","../src/error.ts","../src/helper.ts","../src/cookie.ts","../src/cookie-utils.ts","../src/router.ts","../src/utils.ts","../src/middleware.ts","../src/types.ts","../src/adapter/request.ts","../src/adapter/node.ts"],"sourcesContent":["\"use strict\";\n\nvar defaultParseOptions = {\n decodeValues: true,\n map: false,\n silent: false,\n};\n\nfunction isNonEmptyString(str) {\n return typeof str === \"string\" && !!str.trim();\n}\n\nfunction parseString(setCookieValue, options) {\n var parts = setCookieValue.split(\";\").filter(isNonEmptyString);\n\n var nameValuePairStr = parts.shift();\n var parsed = parseNameValuePair(nameValuePairStr);\n var name = parsed.name;\n var value = parsed.value;\n\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n try {\n value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value\n } catch (e) {\n console.error(\n \"set-cookie-parser encountered an error while decoding a cookie with value '\" +\n value +\n \"'. Set options.decodeValues to false to disable this feature.\",\n e\n );\n }\n\n var cookie = {\n name: name,\n value: value,\n };\n\n parts.forEach(function (part) {\n var sides = part.split(\"=\");\n var key = sides.shift().trimLeft().toLowerCase();\n var value = sides.join(\"=\");\n if (key === \"expires\") {\n cookie.expires = new Date(value);\n } else if (key === \"max-age\") {\n cookie.maxAge = parseInt(value, 10);\n } else if (key === \"secure\") {\n cookie.secure = true;\n } else if (key === \"httponly\") {\n cookie.httpOnly = true;\n } else if (key === \"samesite\") {\n cookie.sameSite = value;\n } else if (key === \"partitioned\") {\n cookie.partitioned = true;\n } else {\n cookie[key] = value;\n }\n });\n\n return cookie;\n}\n\nfunction parseNameValuePair(nameValuePairStr) {\n // Parses name-value-pair according to rfc6265bis draft\n\n var name = \"\";\n var value = \"\";\n var nameValueArr = nameValuePairStr.split(\"=\");\n if (nameValueArr.length > 1) {\n name = nameValueArr.shift();\n value = nameValueArr.join(\"=\"); // everything after the first =, joined by a \"=\" if there was more than one part\n } else {\n value = nameValuePairStr;\n }\n\n return { name: name, value: value };\n}\n\nfunction parse(input, options) {\n options = options\n ? Object.assign({}, defaultParseOptions, options)\n : defaultParseOptions;\n\n if (!input) {\n if (!options.map) {\n return [];\n } else {\n return {};\n }\n }\n\n if (input.headers) {\n if (typeof input.headers.getSetCookie === \"function\") {\n // for fetch responses - they combine headers of the same type in the headers array,\n // but getSetCookie returns an uncombined array\n input = input.headers.getSetCookie();\n } else if (input.headers[\"set-cookie\"]) {\n // fast-path for node.js (which automatically normalizes header names to lower-case\n input = input.headers[\"set-cookie\"];\n } else {\n // slow-path for other environments - see #25\n var sch =\n input.headers[\n Object.keys(input.headers).find(function (key) {\n return key.toLowerCase() === \"set-cookie\";\n })\n ];\n // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36\n if (!sch && input.headers.cookie && !options.silent) {\n console.warn(\n \"Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning.\"\n );\n }\n input = sch;\n }\n }\n if (!Array.isArray(input)) {\n input = [input];\n }\n\n if (!options.map) {\n return input.filter(isNonEmptyString).map(function (str) {\n return parseString(str, options);\n });\n } else {\n var cookies = {};\n return input.filter(isNonEmptyString).reduce(function (cookies, str) {\n var cookie = parseString(str, options);\n cookies[cookie.name] = cookie;\n return cookies;\n }, cookies);\n }\n}\n\n/*\n Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas\n that are within a single set-cookie field-value, such as in the Expires portion.\n\n This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2\n Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128\n React Native's fetch does this for *every* header, including set-cookie.\n\n Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25\n Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation\n*/\nfunction splitCookiesString(cookiesString) {\n if (Array.isArray(cookiesString)) {\n return cookiesString;\n }\n if (typeof cookiesString !== \"string\") {\n return [];\n }\n\n var cookiesStrings = [];\n var pos = 0;\n var start;\n var ch;\n var lastComma;\n var nextStart;\n var cookiesSeparatorFound;\n\n function skipWhitespace() {\n while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n pos += 1;\n }\n return pos < cookiesString.length;\n }\n\n function notSpecialChar() {\n ch = cookiesString.charAt(pos);\n\n return ch !== \"=\" && ch !== \";\" && ch !== \",\";\n }\n\n while (pos < cookiesString.length) {\n start = pos;\n cookiesSeparatorFound = false;\n\n while (skipWhitespace()) {\n ch = cookiesString.charAt(pos);\n if (ch === \",\") {\n // ',' is a cookie separator if we have later first '=', not ';' or ','\n lastComma = pos;\n pos += 1;\n\n skipWhitespace();\n nextStart = pos;\n\n while (pos < cookiesString.length && notSpecialChar()) {\n pos += 1;\n }\n\n // currently special character\n if (pos < cookiesString.length && cookiesString.charAt(pos) === \"=\") {\n // we found cookies separator\n cookiesSeparatorFound = true;\n // pos is inside the next cookie, so back up and return it.\n pos = nextStart;\n cookiesStrings.push(cookiesString.substring(start, lastComma));\n start = pos;\n } else {\n // in param ',' or param separator ';',\n // we continue from that comma\n pos = lastComma + 1;\n }\n } else {\n pos += 1;\n }\n }\n\n if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length));\n }\n }\n\n return cookiesStrings;\n}\n\nmodule.exports = parse;\nmodule.exports.parse = parse;\nmodule.exports.parseString = parseString;\nmodule.exports.splitCookiesString = splitCookiesString;\n","\"use server\";\nimport { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { getCookie, getSignedCookie, setCookie, setSignedCookie } from \"./cookie-utils\";\nimport type { CookiePrefixOptions, CookieOptions } from \"./cookie\";\n\nexport interface EndpointConfig {\n\t/**\n\t * Throw when the response isn't in 200 range\n\t */\n\tthrowOnError?: boolean;\n}\n\nexport function createEndpointCreator<\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(opts?: E) {\n\treturn <Path extends string, Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (\n\t\t\tctx: Prettify<\n\t\t\t\tContext<Path, Opts> &\n\t\t\t\t\tInferUse<Opts[\"use\"]> &\n\t\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\t\tOmit<ContextTools, \"_flag\">\n\t\t\t>,\n\t\t) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t};\n}\n\nexport function createEndpoint<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n>(path: Path, options: Opts, handler: Handler<Path, Opts, R>) {\n\tlet responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async <C extends HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]>(\n\t\t...ctx: C\n\t) => {\n\t\tlet internalCtx = {\n\t\t\tsetHeader(key: string, value: string) {\n\t\t\t\tresponseHeader.set(key, value);\n\t\t\t},\n\t\t\tsetCookie(key: string, value: string, options?: CookieOptions) {\n\t\t\t\tsetCookie(responseHeader, key, value, options);\n\t\t\t},\n\t\t\tgetCookie(key: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tconst cookieH = header?.get(\"cookie\");\n\t\t\t\tconst cookie = getCookie(cookieH || \"\", key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tgetSignedCookie(key: string, secret: string, prefix?: CookiePrefixOptions) {\n\t\t\t\tconst header = ctx[0]?.headers;\n\t\t\t\tif (!header) {\n\t\t\t\t\tthrow new TypeError(\"Headers are required\");\n\t\t\t\t}\n\t\t\t\tconst cookie = getSignedCookie(header, secret, key, prefix);\n\t\t\t\treturn cookie;\n\t\t\t},\n\t\t\tasync setSignedCookie(\n\t\t\t\tkey: string,\n\t\t\t\tvalue: string,\n\t\t\t\tsecret: string | BufferSource,\n\t\t\t\toptions?: CookieOptions,\n\t\t\t) {\n\t\t\t\tawait setSignedCookie(responseHeader, key, value, secret, options);\n\t\t\t},\n\t\t\tredirect(url: string) {\n\t\t\t\tresponseHeader.set(\"Location\", url);\n\t\t\t\treturn new APIError(\"FOUND\");\n\t\t\t},\n\t\t\tjson,\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?.asResponse ? \"router\" : (ctx[0] as any)?._flag,\n\t\t\tresponseHeader,\n\t\t\tpath: path,\n\t\t\t...(ctx[0] || {}),\n\t\t};\n\t\tif (options.use?.length) {\n\t\t\tlet middlewareContexts = {};\n\t\t\tlet middlewareBody = {};\n\t\t\tfor (const middleware of options.use) {\n\t\t\t\tif (typeof middleware !== \"function\") {\n\t\t\t\t\tconsole.warn(\"Middleware is not a function\", {\n\t\t\t\t\t\tmiddleware,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst res = (await middleware(internalCtx)) as Endpoint;\n\t\t\t\tif (res) {\n\t\t\t\t\tconst body = res.options?.body\n\t\t\t\t\t\t? res.options.body.parse(internalCtx.body)\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tmiddlewareContexts = {\n\t\t\t\t\t\t...middlewareContexts,\n\t\t\t\t\t\t...res,\n\t\t\t\t\t};\n\t\t\t\t\tmiddlewareBody = {\n\t\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t\t...body,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: {\n\t\t\t\t\t...middlewareBody,\n\t\t\t\t\t...(internalCtx.body as Record<string, any>),\n\t\t\t\t},\n\t\t\t\tcontext: {\n\t\t\t\t\t...(internalCtx.context || {}),\n\t\t\t\t\t...middlewareContexts,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\ttry {\n\t\t\tconst body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body;\n\t\t\tinternalCtx = {\n\t\t\t\t...internalCtx,\n\t\t\t\tbody: body\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...body,\n\t\t\t\t\t\t\t...(internalCtx.body as Record<string, any>),\n\t\t\t\t\t\t}\n\t\t\t\t\t: internalCtx.body,\n\t\t\t};\n\t\t\tinternalCtx.query = options.query\n\t\t\t\t? options.query.parse(internalCtx.query)\n\t\t\t\t: internalCtx.query;\n\t\t} catch (e) {\n\t\t\tif (e instanceof ZodError) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: e.message,\n\t\t\t\t\tdetails: e.errors,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t\tif (options.requireHeaders && !internalCtx.headers) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Headers are required\",\n\t\t\t});\n\t\t}\n\t\tif (options.requireRequest && !internalCtx.request) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Request is required\",\n\t\t\t});\n\t\t}\n\t\t// If request is provided but headers are not provided\n\t\t// then set headers from request\n\t\tif (internalCtx.request && !internalCtx.headers) {\n\t\t\tinternalCtx.headers = internalCtx.request.headers;\n\t\t}\n\t\ttry {\n\t\t\tlet res = (await handler(internalCtx as any)) as any;\n\t\t\tlet actualResponse: any = res;\n\n\t\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t\t});\n\t\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\t\theaders: responseHeader,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tactualResponse = res.body;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponseHeader = new Headers();\n\n\t\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\t\treturn actualResponse as C extends [{ asResponse: true }]\n\t\t\t\t? Response\n\t\t\t\t: R extends {\n\t\t\t\t\t\t\t_flag: \"json\";\n\t\t\t\t\t\t}\n\t\t\t\t\t? R extends { body: infer B }\n\t\t\t\t\t\t? B\n\t\t\t\t\t\t: null\n\t\t\t\t\t: ReturnT;\n\t\t} catch (e) {\n\t\t\tif (e instanceof APIError) {\n\t\t\t\tresponseHeader.set(\"Content-Type\", \"application/json\");\n\t\t\t\te.headers = responseHeader;\n\t\t\t\tresponseHeader = new Headers();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t};\n\thandle.path = path;\n\thandle.options = options;\n\thandle.method = options.method;\n\thandle.headers = responseHeader;\n\treturn handle;\n}\n","import type { statusCode } from \"./utils\";\n\ntype Status = keyof typeof statusCode;\n\nexport class APIError extends Error {\n\tstatus: Status;\n\theaders: Headers;\n\tbody: {\n\t\tcode?: string;\n\t\tmessage?: string;\n\t\t[key: string]: any;\n\t};\n\tconstructor(status: Status, body?: Record<string, any>, headers?: Headers) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.body.code = body?.message\n\t\t\t? body.message\n\t\t\t\t\t.toUpperCase()\n\t\t\t\t\t.replace(/ /g, \"_\")\n\t\t\t\t\t.replace(/[^A-Z0-9_]/g, \"\")\n\t\t\t: status;\n\t\tthis.stack = \"\";\n\n\t\tthis.headers = headers ?? new Headers();\n\t\tif (!this.headers.has(\"Content-Type\")) {\n\t\t\tthis.headers.set(\"Content-Type\", \"application/json\");\n\t\t}\n\t\tthis.name = \"BetterCallAPIError\";\n\t}\n}\n","export type UnionToIntersection<Union> = (\n\tUnion extends unknown\n\t\t? (distributedUnion: Union) => void\n\t\t: never\n) extends (mergedIntersection: infer Intersection) => void\n\t? Intersection & Union\n\t: never;\n\nexport type RequiredKeysOf<BaseType extends object> = Exclude<\n\t{\n\t\t[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]> ? Key : never;\n\t}[keyof BaseType],\n\tundefined\n>;\n\nexport type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never\n\t? false\n\t: true;\n\n/**\n * this function will return a json response and\n * infers the type of the body\n */\nexport const json = <T>(\n\tbody: T,\n\toption?: {\n\t\tstatus?: number;\n\t\tstatusText?: string;\n\t\theaders?: Record<string, string>;\n\t\t/**\n\t\t * this body will take precedence over the body in the options if both are provided.\n\t\t * This is useful if you want to return body without inferring the type.\n\t\t */\n\t\tbody?: any;\n\t},\n) => {\n\treturn {\n\t\tresponse: {\n\t\t\tbody: option?.body ?? body,\n\t\t\tstatus: option?.status ?? 200,\n\t\t\tstatusText: option?.statusText ?? \"OK\",\n\t\t\theaders: option?.headers,\n\t\t},\n\t\tbody,\n\t\t_flag: \"json\" as const,\n\t};\n};\n","//https://github.com/honojs/hono/blob/main/src/utils/cookie.ts\nimport { subtle } from \"uncrypto\";\n\nexport type Cookie = Record<string, string>;\nexport type SignedCookie = Record<string, string | false>;\n\ntype PartitionCookieConstraint =\n\t| { partition: true; secure: true }\n\t| { partition?: boolean; secure?: boolean }; // reset to default\ntype SecureCookieConstraint = { secure: true };\ntype HostCookieConstraint = { secure: true; path: \"/\"; domain?: undefined };\n\nexport type CookieOptions = {\n\tdomain?: string;\n\texpires?: Date;\n\thttpOnly?: boolean;\n\tmaxAge?: number;\n\tpath?: string;\n\tsecure?: boolean;\n\tsigningSecret?: string;\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\tpartitioned?: boolean;\n\tprefix?: CookiePrefixOptions;\n} & PartitionCookieConstraint;\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieConstraint<Name> = Name extends `__Secure-${string}`\n\t? CookieOptions & SecureCookieConstraint\n\t: Name extends `__Host-${string}`\n\t\t? CookieOptions & HostCookieConstraint\n\t\t: CookieOptions;\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nconst getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nconst verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\n// all alphanumeric chars and all of _!#$%&'*.^`|~+-\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\nconst validCookieNameRegEx = /^[\\w!#$%&'*.^`|~+-]+$/;\n\n// all ASCII chars 32-126 except 34, 59, and 92 (i.e. space to tilde but not double quote, semicolon, or backslash)\n// (see: https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1)\n//\n// note: the spec also prohibits comma and space, but we allow both since they are very common in the real world\n// (see: https://github.com/golang/go/issues/7243)\nconst validCookieValueRegEx = /^[ !#-:<-[\\]-~]*$/;\n\nexport const parse = (cookie: string, name?: string): Cookie => {\n\tconst pairs = cookie.trim().split(\";\");\n\treturn pairs.reduce((parsedCookie, pairStr) => {\n\t\tpairStr = pairStr.trim();\n\t\tconst valueStartPos = pairStr.indexOf(\"=\");\n\t\tif (valueStartPos === -1) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tconst cookieName = pairStr.substring(0, valueStartPos).trim();\n\t\tif ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {\n\t\t\treturn parsedCookie;\n\t\t}\n\n\t\tlet cookieValue = pairStr.substring(valueStartPos + 1).trim();\n\t\tif (cookieValue.startsWith('\"') && cookieValue.endsWith('\"')) {\n\t\t\tcookieValue = cookieValue.slice(1, -1);\n\t\t}\n\t\tif (validCookieValueRegEx.test(cookieValue)) {\n\t\t\tparsedCookie[cookieName] = decodeURIComponent(cookieValue);\n\t\t}\n\n\t\treturn parsedCookie;\n\t}, {} as Cookie);\n};\n\nexport const parseSigned = async (\n\tcookie: string,\n\tsecret: string | BufferSource,\n\tname?: string,\n): Promise<SignedCookie> => {\n\tconst parsedCookie: SignedCookie = {};\n\tconst secretKey = await getCryptoKey(secret);\n\n\tfor (const [key, value] of Object.entries(parse(cookie, name))) {\n\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\tif (signatureStartPos < 1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\tparsedCookie[key] = isVerified ? signedValue : false;\n\t}\n\n\treturn parsedCookie;\n};\n\nconst _serialize = (name: string, value: string, opt: CookieOptions = {}): string => {\n\tlet cookie = `${name}=${value}`;\n\n\tif (name.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (name.startsWith(\"__Host-\")) {\n\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.2\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.2\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.2.1\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\t// FIXME: replace link to RFC\n\t\t// https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html#section-2.3\n\t\tif (!opt.secure) {\n\t\t\tthrow new Error(\"Partitioned Cookie must have Secure attributes\");\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serialize = <Name extends string>(\n\tname: Name,\n\tvalue: string,\n\topt?: CookieConstraint<Name>,\n): string => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n\nexport const serializeSigned = async (\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt: CookieOptions = {},\n): Promise<string> => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(name, value, opt);\n};\n\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n","//https://github.com/honojs/hono/blob/main/src/helper/cookie/index.ts\n\nimport {\n\tparse,\n\tparseSigned,\n\tserialize,\n\tserializeSigned,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookie\";\n\nexport const getCookie = (cookie: string, key: string, prefix?: CookiePrefixOptions) => {\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tconst obj = parse(cookie, finalKey);\n\treturn obj[finalKey];\n};\n\nexport const setCookie = (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\topt?: CookieOptions,\n): void => {\n\tconst existingCookies = header.get(\"Set-Cookie\");\n\tif (existingCookies) {\n\t\tconst cookies = existingCookies.split(\", \");\n\t\tconst updatedCookies = cookies.filter((cookie) => !cookie.startsWith(`${name}=`));\n\t\theader.delete(\"Set-Cookie\");\n\t\tupdatedCookies.forEach((cookie) => header.append(\"Set-Cookie\", cookie));\n\t}\n\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = serialize(\"__Secure-\" + name, value, { path: \"/\", ...opt, secure: true });\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = serialize(\"__Host-\" + name, value, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = serialize(name, value, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const setSignedCookie = async (\n\theader: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: string | BufferSource,\n\topt?: CookieOptions,\n): Promise<void> => {\n\tlet cookie;\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = await serializeSigned(\"__Secure-\" + name, value, secret, {\n\t\t\tpath: \"/\",\n\t\t\t...opt,\n\t\t\tsecure: true,\n\t\t});\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = await serializeSigned(\"__Host-\" + name, value, secret, {\n\t\t\t...opt,\n\t\t\tpath: \"/\",\n\t\t\tsecure: true,\n\t\t\tdomain: undefined,\n\t\t});\n\t} else {\n\t\tcookie = await serializeSigned(name, value, secret, { path: \"/\", ...opt });\n\t}\n\theader.append(\"Set-Cookie\", cookie);\n};\n\nexport const getSignedCookie = async (\n\theader: Headers,\n\tsecret: string,\n\tkey: string,\n\tprefix?: CookiePrefixOptions,\n) => {\n\tconst cookie = header.get(\"cookie\");\n\tif (!cookie) {\n\t\treturn undefined;\n\t}\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t}\n\t}\n\tconst obj = await parseSigned(cookie, secret, finalKey);\n\treturn obj[finalKey];\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Endpoint } from \"./types\";\n\nexport interface RouterConfig {\n\t/**\n\t * Throw error if error occurred other than APIError\n\t */\n\tthrowError?: boolean;\n\t/**\n\t * Handle error\n\t */\n\tonError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;\n\t/**\n\t * Base path for the router\n\t */\n\tbasePath?: string;\n\t/**\n\t * Middlewares for the router\n\t */\n\trouterMiddleware?: {\n\t\tpath: string;\n\t\tmiddleware: Endpoint;\n\t}[];\n\textraContext?: Record<string, any>;\n\tonResponse?: (res: Response) => any | Promise<any>;\n\tonRequest?: (req: Request) => any | Promise<any>;\n}\n\nexport const createRouter = <E extends Record<string, Endpoint>, Config extends RouterConfig>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tconst _endpoints = Object.values(endpoints);\n\tconst router = createRou3Router();\n\tfor (const endpoint of _endpoints) {\n\t\tif (endpoint.options.metadata?.SERVER_ONLY) continue;\n\t\tif (Array.isArray(endpoint.options?.method)) {\n\t\t\tfor (const method of endpoint.options.method) {\n\t\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t\t}\n\t\t} else {\n\t\t\taddRoute(router, endpoint.options.method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tconst middlewareRouter = createRou3Router();\n\tfor (const route of config?.routerMiddleware || []) {\n\t\taddRoute(middlewareRouter, \"*\", route.path, route.middleware);\n\t}\n\n\tconst handler = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tlet path = url.pathname;\n\t\tif (config?.basePath) {\n\t\t\tpath = path.split(config.basePath)[1];\n\t\t}\n\t\tif (!path?.length) {\n\t\t\tconfig?.onError?.(new APIError(\"NOT_FOUND\"));\n\t\t\tconsole.warn(\n\t\t\t\t`[better-call]: Make sure the URL has the basePath (${config?.basePath}).`,\n\t\t\t);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 404,\n\t\t\t\tstatusText: \"Not Found\",\n\t\t\t});\n\t\t}\n\t\tconst method = request.method;\n\t\tconst route = findRoute(router, method, path);\n\t\tconst handler = route?.data as Endpoint;\n\t\tconst body = await getBody(request);\n\t\tconst headers = request.headers;\n\t\tconst query = Object.fromEntries(url.searchParams);\n\t\tconst routerMiddleware = findAllRoutes(middlewareRouter, \"*\", path);\n\t\t//handler 404\n\t\tif (!handler) {\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 404,\n\t\t\t\tstatusText: \"Not Found\",\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tlet middlewareContext: Record<string, any> = {};\n\t\t\tif (routerMiddleware?.length) {\n\t\t\t\tfor (const route of routerMiddleware) {\n\t\t\t\t\tconst middleware = route.data as Endpoint;\n\t\t\t\t\tconst res = await middleware({\n\t\t\t\t\t\tpath: path,\n\t\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\t\trequest: request,\n\t\t\t\t\t\tbody: body,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (res) {\n\t\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t\t...res,\n\t\t\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst handlerRes = await handler({\n\t\t\t\tpath: path,\n\t\t\t\tmethod: method as \"GET\",\n\t\t\t\theaders,\n\t\t\t\tparams: route?.params as any,\n\t\t\t\trequest: request,\n\t\t\t\tbody: body,\n\t\t\t\tquery,\n\t\t\t\t_flag: \"router\",\n\t\t\t\tcontext: {\n\t\t\t\t\t...middlewareContext,\n\t\t\t\t\t...config?.extraContext,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (handlerRes instanceof Response) {\n\t\t\t\treturn handlerRes;\n\t\t\t}\n\t\t\tconst resBody = shouldSerialize(handlerRes) ? JSON.stringify(handlerRes) : handlerRes;\n\t\t\treturn new Response(resBody as any, {\n\t\t\t\theaders: handler.headers,\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (config?.onError) {\n\t\t\t\tconst onErrorRes = await config.onError(e);\n\t\t\t\tif (onErrorRes instanceof Response) {\n\t\t\t\t\treturn onErrorRes;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e instanceof APIError) {\n\t\t\t\treturn new Response(e.body ? JSON.stringify(e.body) : null, {\n\t\t\t\t\tstatus: statusCode[e.status],\n\t\t\t\t\tstatusText: e.status,\n\t\t\t\t\theaders: e.headers,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (config?.throwError) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\treturn {\n\t\thandler: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await handler(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","export async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n\nexport function shouldSerialize(body: any) {\n\treturn (\n\t\ttypeof body === \"object\" &&\n\t\tbody !== null &&\n\t\t!(body instanceof Blob) &&\n\t\t!(body instanceof FormData)\n\t);\n}\n\nexport const statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n","import type {\n\tContextTools,\n\tEndpoint,\n\tEndpointOptions,\n\tEndpointResponse,\n\tHandler,\n\tInferBody,\n\tInferHeaders,\n\tInferRequest,\n\tInferUse,\n\tPrettify,\n} from \"./types\";\nimport { createEndpoint } from \"./endpoint\";\n\nexport type MiddlewareHandler<\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n\tExtra extends Record<string, any> = {},\n> = (\n\tctx: Prettify<\n\t\tInferBody<Opts> &\n\t\t\tInferRequest<Opts> &\n\t\t\tInferHeaders<Opts> & {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t\tquery?: Record<string, string>;\n\t\t\t} & ContextTools\n\t> &\n\t\tExtra,\n) => Promise<R>;\n\nexport function createMiddleware<Opts extends EndpointOptions, R extends EndpointResponse>(\n\toptionsOrHandler: MiddlewareHandler<Opts, R>,\n): Endpoint<Handler<string, Opts, R>, Opts>;\nexport function createMiddleware<\n\tOpts extends Omit<EndpointOptions, \"method\">,\n\tR extends EndpointResponse,\n>(\n\toptionsOrHandler: Opts,\n\thandler: MiddlewareHandler<\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n): Endpoint<\n\tHandler<\n\t\tstring,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t},\n\t\tR\n\t>,\n\tOpts & {\n\t\tmethod: \"*\";\n\t}\n>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tif (typeof optionsOrHandler === \"function\") {\n\t\treturn createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\toptionsOrHandler,\n\t\t);\n\t}\n\tif (!handler) {\n\t\tthrow new Error(\"Middleware handler is required\");\n\t}\n\tconst endpoint = createEndpoint(\n\t\t\"*\",\n\t\t{\n\t\t\t...optionsOrHandler,\n\t\t\tmethod: \"*\",\n\t\t},\n\t\thandler,\n\t);\n\treturn endpoint as any;\n}\n\nexport const createMiddlewareCreator = <\n\tE extends {\n\t\tuse?: Endpoint[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype H<Opts extends EndpointOptions, R extends EndpointResponse> = (\n\t\tctx: Prettify<\n\t\t\tInferBody<Opts> &\n\t\t\t\tInferUse<E[\"use\"]> &\n\t\t\t\tInferRequest<Opts> &\n\t\t\t\tInferHeaders<Opts> & {\n\t\t\t\t\tparams?: Record<string, string>;\n\t\t\t\t\tquery?: Record<string, string>;\n\t\t\t\t} & ContextTools\n\t\t>,\n\t) => Promise<R>;\n\tfunction fn<Opts extends EndpointOptions, R extends EndpointResponse>(\n\t\toptionsOrHandler: H<Opts, R>,\n\t): Endpoint<Handler<string, Opts, R>, Opts>;\n\tfunction fn<Opts extends Omit<EndpointOptions, \"method\">, R extends EndpointResponse>(\n\t\toptionsOrHandler: Opts,\n\t\thandler: H<\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t): Endpoint<\n\t\tHandler<\n\t\t\tstring,\n\t\t\tOpts & {\n\t\t\t\tmethod: \"*\";\n\t\t\t},\n\t\t\tR\n\t\t>,\n\t\tOpts & {\n\t\t\tmethod: \"*\";\n\t\t}\n\t>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createEndpoint(\n\t\t\t\t\"*\",\n\t\t\t\t{\n\t\t\t\t\tmethod: \"*\",\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst endpoint = createEndpoint(\n\t\t\t\"*\",\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn endpoint as any;\n\t}\n\treturn fn;\n};\n\nexport type Middleware<\n\tOpts extends EndpointOptions = EndpointOptions,\n\tR extends EndpointResponse = EndpointResponse,\n> = (\n\topts: Opts,\n\thandler: (ctx: {\n\t\tbody?: InferBody<Opts>;\n\t\tparams?: Record<string, string>;\n\t\tquery?: Record<string, string>;\n\t}) => Promise<R>,\n) => Endpoint;\n","import { z, type ZodOptional, type ZodSchema } from \"zod\";\nimport type { json, UnionToIntersection } from \"./helper\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\n\nexport type OpenAPISchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" | \"object\";\n\nexport interface OpenAPIParameter {\n\tin: \"query\" | \"path\" | \"header\" | \"cookie\";\n\tname?: string;\n\tdescription?: string;\n\trequired?: boolean;\n\tschema?: {\n\t\ttype: OpenAPISchemaType;\n\t\tformat?: string;\n\t\titems?: {\n\t\t\ttype: OpenAPISchemaType;\n\t\t};\n\t\tenum?: string[];\n\t\tminLength?: number;\n\t\tdescription?: string;\n\t\tdefault?: string;\n\t\texample?: string;\n\t};\n}\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: ZodSchema;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: ZodSchema;\n\t/**\n\t * If true headers will be required to be passed in the context\n\t */\n\trequireHeaders?: boolean;\n\t/**\n\t * If true request object will be required\n\t */\n\trequireRequest?: boolean;\n\t/**\n\t * List of endpoints that will be called before this endpoint\n\t */\n\tuse?: Endpoint[];\n\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?: {\n\t\t/**\n\t\t * If true this endpoint will only be available on the server\n\t\t */\n\t\tSERVER_ONLY?: boolean;\n\t\t$Infer?: {\n\t\t\tbody?: Record<string, any>;\n\t\t};\n\t\topenapi?: {\n\t\t\tsummary?: string;\n\t\t\tdescription?: string;\n\t\t\ttags?: string[];\n\t\t\toperationId?: string;\n\t\t\tparameters?: OpenAPIParameter[];\n\t\t\trequestBody?: {\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tresponses?: {\n\t\t\t\t[status: string]: {\n\t\t\t\t\tdescription: string;\n\t\t\t\t\tcontent?: {\n\t\t\t\t\t\t\"application/json\"?: {\n\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\"text/plain\"?: {\n\t\t\t\t\t\t\tschema?: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\"text/html\"?: {\n\t\t\t\t\t\t\tschema?: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\t[key: string]: any;\n\t};\n}\n\nexport type Endpoint<\n\tHandler extends (ctx: any) => Promise<any> = (ctx: any) => Promise<any>,\n\tOption extends EndpointOptions = EndpointOptions,\n> = {\n\tpath: string;\n\toptions: Option;\n\theaders?: Headers;\n} & Handler;\n\nexport type InferParamPath<Path> = Path extends `${infer _Start}:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}:${infer Param}`\n\t\t? { [K in Param]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type InferParamWildCard<Path> = Path extends\n\t| `${infer _Start}/*:${infer Param}/${infer Rest}`\n\t| `${infer _Start}/**:${infer Param}/${infer Rest}`\n\t? { [K in Param | keyof InferParamPath<Rest>]: string }\n\t: Path extends `${infer _Start}/*`\n\t\t? { [K in \"_\"]: string }\n\t\t: Path extends `${infer _Start}/${infer Rest}`\n\t\t\t? InferParamPath<Rest>\n\t\t\t: undefined;\n\nexport type Prettify<T> = {\n\t[key in keyof T]: T[key];\n} & {};\n\nexport type ContextTools = {\n\t/**\n\t * the current path\n\t */\n\tpath: string;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * cookie setter.\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => void;\n\t/**\n\t * Get cookie value\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => string | undefined;\n\t/**\n\t * Set signed cookie\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string | BufferSource,\n\t\toptions?: CookieOptions,\n\t) => Promise<void>;\n\t/**\n\t * Get signed cookie value\n\t */\n\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | undefined>;\n\t/**\n\t * Redirect to url\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * json response helper\n\t */\n\tjson: typeof json;\n\t/**\n\t * response header\n\t */\n\tresponseHeader: Headers;\n};\n\nexport type Context<Path extends string, Opts extends EndpointOptions> = InferBody<Opts> &\n\tInferParam<Path> &\n\tInferMethod<Opts[\"method\"]> &\n\tInferHeaders<Opts> &\n\tInferRequest<Opts> &\n\tInferQuery<Opts[\"query\"]> & {\n\t\t/**\n\t\t * This is used internally.\n\t\t * But you can use it to change the response form.\n\t\t *\n\t\t * - `json` will be set only when using `ctx.json` helper.\n\t\t * - `router` will be set when the handler is called from the router.\n\t\t * You can use this to change the response form to be a `Response` object.\n\t\t * - `default` will be used normally when the handler is called as a normal function.\n\t\t *\n\t\t * @internal\n\t\t */\n\t\t_flag?: \"json\" | \"router\" | \"default\";\n\t\t/**\n\t\t * Force the response to be a `Response` object.\n\t\t */\n\t\tasResponse?: boolean;\n\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Endpoint[]\n\t? {\n\t\t\tcontext: UnionToIntersection<Awaited<ReturnType<Opts[number]>>>;\n\t\t}\n\t: {};\n\nexport type InferUseOptions<Opts extends EndpointOptions> = Opts[\"use\"] extends Array<infer U>\n\t? UnionToIntersection<\n\t\t\tU extends Endpoint\n\t\t\t\t? U[\"options\"]\n\t\t\t\t: {\n\t\t\t\t\t\tbody?: {};\n\t\t\t\t\t\trequireRequest?: boolean;\n\t\t\t\t\t\trequireHeaders?: boolean;\n\t\t\t\t\t}\n\t\t>\n\t: {\n\t\t\tbody?: {};\n\t\t\trequireRequest?: boolean;\n\t\t\trequireHeaders?: boolean;\n\t\t};\n\nexport type InferMethod<M extends Method | Method[]> = M extends Array<Method>\n\t? {\n\t\t\tmethod: M[number];\n\t\t}\n\t: {\n\t\t\tmethod?: M;\n\t\t};\n\nexport type InferHeaders<\n\tOpt extends EndpointOptions,\n\tHeaderReq = Opt[\"requireHeaders\"],\n> = HeaderReq extends true\n\t? {\n\t\t\theaders: Headers;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: Headers;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: Headers;\n\t\t\t};\n\nexport type InferRequest<\n\tOpt extends EndpointOptions,\n\tRequestReq = Opt[\"requireRequest\"],\n> = RequestReq extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: InferUseOptions<Opt>[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferQuery<Query> = Query extends ZodSchema\n\t? Query extends ZodOptional<any>\n\t\t? {\n\t\t\t\tquery?: z.infer<Query>;\n\t\t\t}\n\t\t: {\n\t\t\t\tquery: z.infer<Query>;\n\t\t\t}\n\t: {\n\t\t\tquery?: undefined;\n\t\t};\n\nexport type InferParam<\n\tPath extends string,\n\tParamPath extends InferParamPath<Path> = InferParamPath<Path>,\n\tWildCard extends InferParamWildCard<Path> = InferParamWildCard<Path>,\n> = ParamPath extends undefined\n\t? WildCard extends undefined\n\t\t? {\n\t\t\t\tparams?: Record<string, string>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: WildCard;\n\t\t\t}\n\t: {\n\t\t\tparams: Prettify<ParamPath & (WildCard extends undefined ? {} : WildCard)>;\n\t\t};\n\nexport type EndpointBody =\n\t| Record<string, any>\n\t| string\n\t| boolean\n\t| number\n\t| void\n\t| undefined\n\t| null\n\t| unknown;\n\nexport type EndpointResponse =\n\t| {\n\t\t\tresponse: {\n\t\t\t\tstatus?: number;\n\t\t\t\tstatusText?: string;\n\t\t\t\theaders?: Headers;\n\t\t\t\tbody: any;\n\t\t\t};\n\t\t\tbody: EndpointBody;\n\t\t\t_flag: \"json\";\n\t }\n\t| EndpointBody;\n\nexport type Handler<\n\tPath extends string,\n\tOpts extends EndpointOptions,\n\tR extends EndpointResponse,\n> = (ctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & ContextTools>) => Promise<R>;\n\nexport type Method = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"*\";\n\nexport type InferBody<\n\tOpts extends EndpointOptions,\n\tBody extends ZodSchema | undefined = Opts[\"body\"] &\n\t\t(undefined extends InferUseOptions<Opts>[\"body\"] ? {} : InferUseOptions<Opts>[\"body\"]),\n> = Opts[\"metadata\"] extends { $Infer: { body: infer B } }\n\t? { body: B }\n\t: Body extends ZodSchema\n\t\t? Body extends ZodOptional<any>\n\t\t\t? {\n\t\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t\t}\n\t\t: {\n\t\t\t\tbody?: undefined;\n\t\t\t};\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\treturn new Request(base + request.url, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody: get_raw_body(request, bodySizeLimit),\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request.js\";\nimport type { Router } from \"../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol =\n\t\t\treq.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\tsetResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;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,cAAI,KAAK,SAAS,IAAI;AACtB;AAAA,QACD;AAAA,MACD;AACA,UAAI,IAAI;AAAA,IACT,SAAS,OAAO;AACf,aAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,IACjE;AAAA,EACD;AACD;;;AC1KO,SAAS,cAAc,SAA4B;AACzD,SAAO,OAAO,KAAsB,QAAwB;AAC3D,UAAM,WACL,IAAI,QAAQ,mBAAmB,MAAO,IAAI,OAAe,YAAY,UAAU;AAChF,UAAM,OAAO,GAAG,QAAQ,MAAM,IAAI,QAAQ,YAAY,KAAK,IAAI,QAAQ,IAAI;AAC3E,UAAM,WAAW,MAAM,QAAQ,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC;AACjE,gBAAY,KAAK,QAAQ;AAAA,EAC1B;AACD;","names":["value","parse","cookies","splitCookiesString","cookie","options","handler","route"]}
1
+ {"version":3,"sources":["../src/error.ts","../src/to-response.ts","../src/validator.ts","../src/crypto.ts","../src/cookies.ts","../src/context.ts","../src/middleware.ts","../src/endpoint.ts","../src/router.ts","../src/openapi.ts","../src/utils.ts"],"sourcesContent":["export const _statusCode = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n\nexport type Status =\n\t| 100\n\t| 101\n\t| 102\n\t| 103\n\t| 200\n\t| 201\n\t| 202\n\t| 203\n\t| 204\n\t| 205\n\t| 206\n\t| 207\n\t| 208\n\t| 226\n\t| 300\n\t| 301\n\t| 302\n\t| 303\n\t| 304\n\t| 305\n\t| 306\n\t| 307\n\t| 308\n\t| 400\n\t| 401\n\t| 402\n\t| 403\n\t| 404\n\t| 405\n\t| 406\n\t| 407\n\t| 408\n\t| 409\n\t| 410\n\t| 411\n\t| 412\n\t| 413\n\t| 414\n\t| 415\n\t| 416\n\t| 417\n\t| 418\n\t| 421\n\t| 422\n\t| 423\n\t| 424\n\t| 425\n\t| 426\n\t| 428\n\t| 429\n\t| 431\n\t| 451\n\t| 500\n\t| 501\n\t| 502\n\t| 503\n\t| 504\n\t| 505\n\t| 506\n\t| 507\n\t| 508\n\t| 510\n\t| 511;\n\nexport class APIError extends Error {\n\tconstructor(\n\t\tpublic status: keyof typeof _statusCode | Status = \"INTERNAL_SERVER_ERROR\",\n\t\tpublic body:\n\t\t\t| ({\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: string;\n\t\t\t } & Record<string, any>)\n\t\t\t| undefined = undefined,\n\t\tpublic headers: HeadersInit = {},\n\t\tpublic statusCode = typeof status === \"number\" ? status : _statusCode[status],\n\t) {\n\t\tsuper(body?.message);\n\t\tthis.name = \"APIError\";\n\t\tthis.status = status;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body\n\t\t\t? {\n\t\t\t\t\tcode: body?.message\n\t\t\t\t\t\t?.toUpperCase()\n\t\t\t\t\t\t.replace(/ /g, \"_\")\n\t\t\t\t\t\t.replace(/[^A-Z0-9_]/g, \"\"),\n\t\t\t\t\t...body,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tthis.stack = \"\";\n\t}\n}\n","import { APIError } from \"./error\";\n\nfunction isJSONSerializable(value: any) {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn true;\n\t}\n\tif (value.buffer) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t(value.constructor && value.constructor.name === \"Object\") ||\n\t\ttypeof value.toJSON === \"function\"\n\t);\n}\n\nexport function toResponse(data?: any, init?: ResponseInit): Response {\n\tif (data instanceof Response) {\n\t\tif (init?.headers instanceof Headers) {\n\t\t\tinit.headers.forEach((value, key) => {\n\t\t\t\tdata.headers.set(key, value);\n\t\t\t});\n\t\t}\n\t\treturn data;\n\t}\n\tif (data?._flag === \"json\") {\n\t\tconst routerResponse = data.routerResponse;\n\t\tif (routerResponse instanceof Response) {\n\t\t\treturn routerResponse;\n\t\t}\n\t\treturn toResponse(data.body, {\n\t\t\theaders: data.headers,\n\t\t\tstatus: data.status,\n\t\t});\n\t}\n\tif (data instanceof APIError) {\n\t\treturn toResponse(data.body, {\n\t\t\tstatus: data.statusCode,\n\t\t\tstatusText: data.status.toString(),\n\t\t\theaders: {\n\t\t\t\t...(data.headers instanceof Headers\n\t\t\t\t\t? Object.fromEntries(data.headers.entries())\n\t\t\t\t\t: data?.headers),\n\t\t\t\t...(init?.headers instanceof Headers\n\t\t\t\t\t? Object.fromEntries(init.headers.entries())\n\t\t\t\t\t: init?.headers),\n\t\t\t},\n\t\t});\n\t}\n\tlet body = data;\n\tlet headers = new Headers(init?.headers);\n\tif (!data) {\n\t\theaders.set(\"content-type\", \"application/json\");\n\t} else if (typeof data === \"string\") {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"text/plain\");\n\t} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/octet-stream\");\n\t} else if (data instanceof Blob) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", data.type || \"application/octet-stream\");\n\t} else if (data instanceof FormData) {\n\t\tbody = data;\n\t} else if (data instanceof URLSearchParams) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\t} else if (data instanceof ReadableStream) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/octet-stream\");\n\t} else if (isJSONSerializable(data)) {\n\t\tbody = JSON.stringify(data);\n\t\theaders.set(\"Content-Type\", \"application/json\");\n\t}\n\n\treturn new Response(body, {\n\t\t...init,\n\t\theaders,\n\t});\n}\n","import type { EndpointOptions } from \"./endpoint\";\nimport type { InputContext } from \"./context\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\n\ntype ValidationResponse =\n\t| {\n\t\t\tdata: {\n\t\t\t\tbody: any;\n\t\t\t\tquery: any;\n\t\t\t};\n\t\t\terror: null;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: {\n\t\t\t\tmessage: string;\n\t\t\t};\n\t };\n\n/**\n * Runs validation on body and query\n * @returns error and data object\n */\nexport async function runValidation(\n\toptions: EndpointOptions,\n\tcontext: InputContext<any, any> = {},\n): Promise<ValidationResponse> {\n\tlet request = {\n\t\tbody: context.body,\n\t\tquery: context.query,\n\t} as {\n\t\tbody: any;\n\t\tquery: any;\n\t};\n\tif (options.body) {\n\t\tconst result = await options.body[\"~standard\"].validate(context.body);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"body\"),\n\t\t\t};\n\t\t}\n\t\trequest.body = result.value;\n\t}\n\n\tif (options.query) {\n\t\tconst result = await options.query[\"~standard\"].validate(context.query);\n\t\tif (result.issues) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: fromError(result.issues, \"query\"),\n\t\t\t};\n\t\t}\n\t\trequest.query = result.value;\n\t}\n\tif (options.requireHeaders && !context.headers) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Headers is required\" },\n\t\t};\n\t}\n\tif (options.requireRequest && !context.request) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: { message: \"Request is required\" },\n\t\t};\n\t}\n\treturn {\n\t\tdata: request,\n\t\terror: null,\n\t};\n}\n\nexport function fromError(error: readonly StandardSchemaV1.Issue[], validating: string) {\n\tconst errorMessages: string[] = [];\n\n\tfor (const issue of error) {\n\t\tconst message = issue.message;\n\t\terrorMessages.push(message);\n\t}\n\treturn {\n\t\tmessage: `Invalid ${validating} parameters`,\n\t};\n}\n","import { subtle } from \"uncrypto\";\n\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nexport const getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await subtle.importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\n\nexport const verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await subtle.sign(algorithm.name, key, new TextEncoder().encode(value));\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n","import { signCookieValue } from \"./crypto\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\nexport function parseCookies(cookieHeader: string) {\n\tconst cookies = cookieHeader.split(\";\");\n\tconst cookieMap = new Map<string, string>();\n\n\tcookies.forEach((cookie) => {\n\t\tconst [name, value] = cookie.trim().split(\"=\");\n\t\tcookieMap.set(name, decodeURIComponent(value));\n\t});\n\treturn cookieMap;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (key: string, value: string, opt?: CookieOptions) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n","import type { EndpointOptions } from \"./endpoint\";\nimport { _statusCode, APIError, type Status } from \"./error\";\nimport type {\n\tInferParamPath,\n\tInferParamWildCard,\n\tInput,\n\tIsEmptyObject,\n\tPrettify,\n\tUnionToIntersection,\n} from \"./helper\";\nimport type { Middleware, MiddlewareOptions } from \"./middleware\";\nimport { runValidation } from \"./validator\";\nimport {\n\tgetCookieKey,\n\tparseCookies,\n\tserializeCookie,\n\tserializeSignedCookie,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookies\";\nimport { getCryptoKey, verifySignature } from \"./crypto\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport type HTTPMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\nexport type Method = HTTPMethod | \"*\";\n\nexport type InferBodyInput<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer Body;\n\t\t};\n\t}\n\t\t? Body\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"body\"]>\n\t\t\t: undefined;\n\nexport type InferBody<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer Body;\n\t\t};\n\t}\n\t\t? Body\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"body\"]>\n\t\t\t: any;\n\nexport type InferQueryInput<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined;\n\nexport type InferQuery<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined;\n\nexport type InferMethod<Options extends EndpointOptions> = Options[\"method\"] extends Array<Method>\n\t? Options[\"method\"][number]\n\t: Options[\"method\"] extends \"*\"\n\t\t? HTTPMethod\n\t\t: Options[\"method\"];\n\nexport type InferInputMethod<Options extends EndpointOptions> =\n\tOptions[\"method\"] extends Array<Method>\n\t\t? Options[\"method\"][number]\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"] | undefined;\n\nexport type InferParam<Path extends string> = IsEmptyObject<\n\tInferParamPath<Path> & InferParamWildCard<Path>\n> extends true\n\t? Record<string, any> | undefined\n\t: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\nexport type InferRequest<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true ? Request : Request | undefined;\n\nexport type InferHeaders<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true ? Headers : Headers | undefined;\n\nexport type InferHeadersInput<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true ? HeadersInit : HeadersInit | undefined;\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Middleware[]\n\t? UnionToIntersection<Awaited<ReturnType<Opts[number]>>>\n\t: {};\n\nexport type InferMiddlewareBody<Options extends MiddlewareOptions> =\n\tOptions[\"body\"] extends StandardSchemaV1<infer T> ? T : any;\n\nexport type InferMiddlewareQuery<Options extends MiddlewareOptions> =\n\tOptions[\"query\"] extends StandardSchemaV1<infer T> ? T : Record<string, any> | undefined;\n\nexport type InputContext<Path extends string, Options extends EndpointOptions> = Input<{\n\t/**\n\t * Payload\n\t */\n\tbody: InferBodyInput<Options>;\n\t/**\n\t * Request Method\n\t */\n\tmethod: InferInputMethod<Options>;\n\t/**\n\t * Query Params\n\t */\n\tquery: InferQueryInput<Options>;\n\t/**\n\t * Dynamic Params\n\t */\n\tparams: InferParam<Path>;\n\t/**\n\t * Request Object\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t */\n\theaders: InferHeadersInput<Options>;\n\t/**\n\t * Return a `Response` object\n\t */\n\tasResponse?: boolean;\n\t/**\n\t * include headers on the return\n\t */\n\treturnHeaders?: boolean;\n\t/**\n\t * Middlewares to use\n\t */\n\tuse?: Middleware[];\n\t/**\n\t * Customize the path\n\t */\n\tpath?: string;\n}>;\n\nexport const createInternalContext = async (\n\tcontext: InputContext<any, any>,\n\t{\n\t\toptions,\n\t\tpath,\n\t}: {\n\t\toptions: EndpointOptions;\n\t\tpath: string;\n\t},\n) => {\n\tconst headers = new Headers();\n\tconst { data, error } = await runValidation(options, context);\n\tif (error) {\n\t\tthrow new APIError(400, {\n\t\t\tmessage: error.message,\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t});\n\t}\n\tconst requestHeaders: Headers | null =\n\t\t\"headers\" in context\n\t\t\t? context.headers instanceof Headers\n\t\t\t\t? context.headers\n\t\t\t\t: new Headers(context.headers)\n\t\t\t: \"request\" in context && context.request instanceof Request\n\t\t\t\t? context.request.headers\n\t\t\t\t: null;\n\tconst requestCookies = requestHeaders?.get(\"cookie\");\n\tconst parsedCookies = requestCookies ? parseCookies(requestCookies) : undefined;\n\tconst internalContext = {\n\t\t...context,\n\t\tbody: data.body,\n\t\tquery: data.query,\n\t\tpath: context.path || path,\n\t\tcontext: \"context\" in context && context.context ? context.context : {},\n\t\treturned: undefined as any,\n\t\theaders: context?.headers,\n\t\trequest: context?.request,\n\t\tparams: \"params\" in context ? context.params : undefined,\n\t\tmethod: context.method,\n\t\tsetHeader: (key: string, value: string) => {\n\t\t\theaders.set(key, value);\n\t\t},\n\t\tgetHeader: (key: string) => {\n\t\t\tif (!requestHeaders) return null;\n\t\t\treturn requestHeaders.get(key);\n\t\t},\n\t\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn parsedCookies?.get(finalKey) || null;\n\t\t},\n\t\tgetSignedCookie: async (key: string, secret: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst value = parsedCookies?.get(finalKey);\n\t\t\tif (!value) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\t\tif (signatureStartPos < 1) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst secretKey = await getCryptoKey(secret);\n\t\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\t\treturn isVerified ? signedValue : false;\n\t\t},\n\t\tsetCookie: (key: string, value: string, options?: CookieOptions) => {\n\t\t\tconst cookie = serializeCookie(key, value, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tsetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tvalue: string,\n\t\t\tsecret: string,\n\t\t\toptions?: CookieOptions,\n\t\t) => {\n\t\t\tconst cookie = await serializeSignedCookie(key, value, secret, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tredirect: (url: string) => {\n\t\t\theaders.set(\"location\", url);\n\t\t\treturn new APIError(\"FOUND\", undefined, headers);\n\t\t},\n\t\terror: (\n\t\t\tstatus: keyof typeof _statusCode | Status,\n\t\t\tbody?:\n\t\t\t\t| {\n\t\t\t\t\t\tmessage?: string;\n\t\t\t\t\t\tcode?: string;\n\t\t\t\t }\n\t\t\t\t| undefined,\n\t\t\theaders?: HeadersInit,\n\t\t) => {\n\t\t\treturn new APIError(status, body, headers);\n\t\t},\n\t\tjson: (\n\t\t\tjson: Record<string, any>,\n\t\t\trouterResponse?:\n\t\t\t\t| {\n\t\t\t\t\t\tstatus?: number;\n\t\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\t\tresponse?: Response;\n\t\t\t\t\t\tbody?: Record<string, string>;\n\t\t\t\t }\n\t\t\t\t| Response,\n\t\t) => {\n\t\t\tif (!context.asResponse) {\n\t\t\t\treturn json;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbody: routerResponse?.body || json,\n\t\t\t\trouterResponse,\n\t\t\t\t_flag: \"json\",\n\t\t\t};\n\t\t},\n\t\tresponseHeaders: headers,\n\t};\n\t//if context was shimmed through the input we want to apply it\n\tfor (const middleware of options.use || []) {\n\t\tconst response = (await middleware({\n\t\t\t...internalContext,\n\t\t\treturnHeaders: true,\n\t\t\tasResponse: false,\n\t\t})) as {\n\t\t\tresponse?: any;\n\t\t\theaders?: Headers;\n\t\t};\n\t\tif (response.response) {\n\t\t\tObject.assign(internalContext.context, response.response);\n\t\t}\n\t\t/**\n\t\t * Apply headers from the middleware to the endpoint headers\n\t\t */\n\t\tif (response.headers) {\n\t\t\tresponse.headers.forEach((value, key) => {\n\t\t\t\tinternalContext.responseHeaders.set(key, value);\n\t\t\t});\n\t\t}\n\t}\n\treturn internalContext;\n};\n","import {\n\tcreateEndpoint,\n\ttype Endpoint,\n\ttype EndpointContext,\n\ttype EndpointOptions,\n} from \"./endpoint\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferHeaders,\n\ttype InferMiddlewareBody,\n\ttype InferMiddlewareQuery,\n\ttype InferQuery,\n\ttype InferRequest,\n\ttype InferUse,\n\ttype InputContext,\n} from \"./context\";\nimport type { Input, Prettify } from \"./helper\";\n\nexport interface MiddlewareOptions extends Omit<EndpointOptions, \"method\"> {}\n\nexport type MiddlewareResponse = null | void | undefined | Record<string, any>;\n\nexport type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<\n\tstring,\n\tOptions & {\n\t\tmethod: \"*\";\n\t}\n> & {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: string;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: string;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists\n\t */\n\tbody: InferMiddlewareBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferMiddlewareQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the\n\t * params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*`\n\t * then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the\n\t * wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: string;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context>;\n};\n\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\toptions: Options,\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tconst internalHandler = async (inputCtx: InputContext<any, any>) => {\n\t\tconst context = inputCtx as InputContext<any, any>;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath: \"/\",\n\t\t});\n\n\t\tif (!_handler) {\n\t\t\tthrow new Error(\"handler must be defined\");\n\t\t}\n\t\tconst response = await _handler(internalContext as any);\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn context.returnHeaders\n\t\t\t? {\n\t\t\t\t\theaders,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t: response;\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\n\nexport type MiddlewareInputContext<Options extends MiddlewareOptions> = Input<{\n\t/**\n\t * Payload\n\t */\n\tbody: InferBody<Options>;\n\t/**\n\t * Query Params\n\t */\n\tquery: InferQuery<Options>;\n\t/**\n\t * Request Object\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Return a `Response` object\n\t */\n\tasResponse?: boolean;\n\t/**\n\t * include headers on the return\n\t */\n\treturnHeaders?: boolean;\n\t/**\n\t * Middlewares to use\n\t */\n\tuse?: Middleware[];\n}>;\n\nexport type Middleware<\n\tOptions extends MiddlewareOptions = MiddlewareOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = any,\n> = Handler & {\n\toptions: Options;\n};\n\ncreateMiddleware.create = <\n\tE extends {\n\t\tuse?: Middleware[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype InferredContext = InferUse<E[\"use\"]>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\toptions: Options,\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createMiddleware(\n\t\t\t\t{\n\t\t\t\t\tuse: opts?.use,\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst middleware = createMiddleware(\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t\tuse: [...(opts?.use || []), ...(optionsOrHandler.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn middleware as any;\n\t}\n\treturn fn;\n};\n","import type { HasRequiredKeys, Prettify } from \"./helper\";\nimport { toResponse } from \"./to-response\";\nimport { type Middleware } from \"./middleware\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferHeaders,\n\ttype InferMethod,\n\ttype InferParam,\n\ttype InferQuery,\n\ttype InferRequest,\n\ttype InferUse,\n\ttype InputContext,\n\ttype Method,\n} from \"./context\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookies\";\nimport { APIError, type _statusCode, type Status } from \"./error\";\nimport type { OpenAPIParameter, OpenAPISchemaType } from \"./openapi\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport interface EndpointOptions {\n\t/**\n\t * Request Method\n\t */\n\tmethod: Method | Method[];\n\t/**\n\t * Body Schema\n\t */\n\tbody?: StandardSchemaV1;\n\t/**\n\t * Query Schema\n\t */\n\tquery?: StandardSchemaV1;\n\t/**\n\t * If true headers will be required to be passed in the context\n\t */\n\trequireHeaders?: boolean;\n\t/**\n\t * If true request object will be required\n\t */\n\trequireRequest?: boolean;\n\t/**\n\t * Clone the request object from the router\n\t */\n\tcloneRequest?: boolean;\n\t/**\n\t * Endpoint metadata\n\t */\n\tmetadata?: {\n\t\t/**\n\t\t * Open API definition\n\t\t */\n\t\topenAPI?: {\n\t\t\tsummary?: string;\n\t\t\tdescription?: string;\n\t\t\ttags?: string[];\n\t\t\toperationId?: string;\n\t\t\tparameters?: OpenAPIParameter[];\n\t\t\trequestBody?: {\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tresponses?: {\n\t\t\t\t[status: string]: {\n\t\t\t\t\tdescription: string;\n\t\t\t\t\tcontent?: {\n\t\t\t\t\t\t\"application/json\"?: {\n\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\"text/plain\"?: {\n\t\t\t\t\t\t\tschema?: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\"text/html\"?: {\n\t\t\t\t\t\t\tschema?: {\n\t\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\t/**\n\t\t * Infer body and query type from ts interface\n\t\t *\n\t\t * useful for generic and dynamic types\n\t\t *\n\t\t * @example\n\t\t * ```ts\n\t\t * const endpoint = createEndpoint(\"/path\", {\n\t\t * \t\tmethod: \"POST\",\n\t\t * \t\tbody: z.record(z.string()),\n\t\t * \t\t$Infer: {\n\t\t * \t\t\tbody: {} as {\n\t\t * \t\t\t\ttype: InferTypeFromOptions<Option> // custom type inference\n\t\t * \t\t\t}\n\t\t * \t\t}\n\t\t * \t}, async(ctx)=>{\n\t\t * \t\tconst body = ctx.body\n\t\t * \t})\n\t\t * ```\n\t\t */\n\t\t$Infer?: {\n\t\t\t/**\n\t\t\t * Body\n\t\t\t */\n\t\t\tbody?: any;\n\t\t\t/**\n\t\t\t * Query\n\t\t\t */\n\t\t\tquery?: Record<string, any>;\n\t\t};\n\t\t/**\n\t\t * If enabled, endpoint won't be exposed over a router\n\t\t */\n\t\tSERVER_ONLY?: boolean;\n\t\t/**\n\t\t * Extra metadata\n\t\t */\n\t\t[key: string]: any;\n\t};\n\t/**\n\t * List of middlewares to use\n\t */\n\tuse?: Middleware[];\n}\n\nexport type EndpointContext<Path extends string, Options extends EndpointOptions, Context = {}> = {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: InferMethod<Options>;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: Path;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists.\n\t */\n\tbody: InferBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*` then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: InferParam<Path>;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * Get a cookie value from the request\n\t *\n\t * @param key - The key of the cookie\n\t * @param prefix - The prefix of the cookie between `__Secure-` and `__Host-`\n\t * @returns - The value of the cookie\n\t */\n\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => string | null;\n\t/**\n\t * Get a signed cookie value from the request\n\t *\n\t * @param key - The key of the cookie\n\t * @param secret - The secret of the signed cookie\n\t * @param prefix - The prefix of the cookie between `__Secure-` and `__Host-`\n\t * @returns\n\t */\n\tgetSignedCookie: (\n\t\tkey: string,\n\t\tsecret: string,\n\t\tprefix?: CookiePrefixOptions,\n\t) => Promise<string | null>;\n\t/**\n\t * Set a cookie value in the response\n\t *\n\t * @param key - The key of the cookie\n\t * @param value - The value to set\n\t * @param options - The options of the cookie\n\t * @returns - The cookie string\n\t */\n\tsetCookie: (key: string, value: string, options?: CookieOptions) => string;\n\t/**\n\t * Set signed cookie\n\t *\n\t * @param key - The key of the cookie\n\t * @param value - The value to set\n\t * @param secret - The secret to sign the cookie with\n\t * @param options - The options of the cookie\n\t * @returns - The cookie string\n\t */\n\tsetSignedCookie: (\n\t\tkey: string,\n\t\tvalue: string,\n\t\tsecret: string,\n\t\toptions?: CookieOptions,\n\t) => Promise<string>;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t\t\tbody?: Record<string, string>;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context & InferUse<Options[\"use\"]>>;\n\t/**\n\t * Redirect to a new URL\n\t */\n\tredirect: (url: string) => APIError;\n\t/**\n\t * Return error\n\t */\n\terror: (\n\t\tstatus: keyof typeof _statusCode | Status,\n\t\tbody?: {\n\t\t\tmessage?: string;\n\t\t\tcode?: string;\n\t\t} & Record<string, any>,\n\t\theaders?: HeadersInit,\n\t) => APIError;\n};\n\nexport const createEndpoint = <Path extends string, Options extends EndpointOptions, R>(\n\tpath: Path,\n\toptions: Options,\n\thandler: (context: EndpointContext<Path, Options>) => Promise<R>,\n) => {\n\tconst internalHandler = async <Context extends InputContext<Path, Options>>(\n\t\t...inputCtx: HasRequiredKeys<Context> extends true ? [Context] : [Context?]\n\t) => {\n\t\tconst context = (inputCtx[0] || {}) as InputContext<any, any>;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath,\n\t\t});\n\t\tconst response = await handler(internalContext as any).catch((e) => {\n\t\t\tif (e instanceof APIError && context.asResponse) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t});\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn (\n\t\t\tcontext.asResponse\n\t\t\t\t? toResponse(response, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t})\n\t\t\t\t: context.returnHeaders\n\t\t\t\t\t? {\n\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t}\n\t\t\t\t\t: response\n\t\t) as Context[\"asResponse\"] extends true\n\t\t\t? Response\n\t\t\t: Context[\"returnHeaders\"] extends true\n\t\t\t\t? {\n\t\t\t\t\t\theaders: Headers;\n\t\t\t\t\t\tresponse: R;\n\t\t\t\t\t}\n\t\t\t\t: R;\n\t};\n\tinternalHandler.options = options;\n\tinternalHandler.path = path;\n\treturn internalHandler;\n};\n\ncreateEndpoint.create = <E extends { use?: Middleware[] }>(opts?: E) => {\n\treturn <Path extends string, Opts extends EndpointOptions, R>(\n\t\tpath: Path,\n\t\toptions: Opts,\n\t\thandler: (ctx: EndpointContext<Path, Opts, InferUse<E[\"use\"]>>) => Promise<R>,\n\t) => {\n\t\treturn createEndpoint(\n\t\t\tpath,\n\t\t\t{\n\t\t\t\t...options,\n\t\t\t\tuse: [...(options?.use || []), ...(opts?.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t};\n};\n\nexport type Endpoint<\n\tPath extends string = string,\n\tOptions extends EndpointOptions = EndpointOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = (inputCtx: any) => Promise<any>,\n> = Handler & {\n\toptions: Options;\n\tpath: Path;\n};\n","import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from \"rou3\";\nimport { createEndpoint, type Endpoint } from \"./endpoint\";\nimport { generator, getHTML } from \"./openapi\";\nimport type { Middleware } from \"./middleware\";\nimport { getBody } from \"./utils\";\nimport { APIError } from \"./error\";\nimport { toResponse } from \"./to-response\";\n\nexport interface RouterConfig {\n\tthrowError?: boolean;\n\tonError?: (e: unknown) => void | Promise<void> | Response | Promise<Response>;\n\tbasePath?: string;\n\trouterMiddleware?: Array<{\n\t\tpath: string;\n\t\tmiddleware: Middleware;\n\t}>;\n\t/**\n\t * additional Context that needs to passed to endpoints\n\t *\n\t * this will be available on `ctx.context` on endpoints\n\t */\n\trouterContext?: Record<string, any>;\n\t/**\n\t * A callback to run before any response\n\t */\n\tonResponse?: (res: Response) => any | Promise<any>;\n\t/**\n\t * A callback to run before any request\n\t */\n\tonRequest?: (req: Request) => any | Promise<any>;\n\t/**\n\t * Open API route configuration\n\t */\n\topenAPI?: {\n\t\t/**\n\t\t * Disable openapi route\n\t\t *\n\t\t * @default false\n\t\t */\n\t\tdisabled?: boolean;\n\t\t/**\n\t\t * A path to display open api using scalar\n\t\t *\n\t\t * @default \"/api/reference\"\n\t\t */\n\t\tpath?: string;\n\t\t/**\n\t\t * Scalar Configuration\n\t\t */\n\t\tscalar?: {\n\t\t\t/**\n\t\t\t * Title\n\t\t\t * @default \"Open API Reference\"\n\t\t\t */\n\t\t\ttitle?: string;\n\t\t\t/**\n\t\t\t * Description\n\t\t\t *\n\t\t\t * @default \"Better Call Open API Reference\"\n\t\t\t */\n\t\t\tdescription?: string;\n\t\t\t/**\n\t\t\t * Logo URL\n\t\t\t */\n\t\t\tlogo?: string;\n\t\t\t/**\n\t\t\t * Scalar theme\n\t\t\t * @default \"saturn\"\n\t\t\t */\n\t\t\ttheme?: string;\n\t\t};\n\t};\n}\n\nexport const createRouter = <E extends Record<string, Endpoint>, Config extends RouterConfig>(\n\tendpoints: E,\n\tconfig?: Config,\n) => {\n\tif (!config?.openAPI?.disabled) {\n\t\tconst openAPI = {\n\t\t\tpath: \"/api/reference\",\n\t\t\t...config?.openAPI,\n\t\t};\n\t\t//@ts-expect-error\n\t\tendpoints[\"openAPI\"] = createEndpoint(\n\t\t\topenAPI.path,\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t},\n\t\t\tasync (c) => {\n\t\t\t\tconst schema = await generator(endpoints);\n\t\t\t\treturn new Response(getHTML(schema, openAPI.scalar), {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t}\n\tconst router = createRou3Router();\n\tconst middlewareRouter = createRou3Router();\n\n\tfor (const endpoint of Object.values(endpoints)) {\n\t\tif (!endpoint.options) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (endpoint.options?.metadata?.SERVER_ONLY) continue;\n\n\t\tconst methods = Array.isArray(endpoint.options?.method)\n\t\t\t? endpoint.options.method\n\t\t\t: [endpoint.options?.method];\n\n\t\tfor (const method of methods) {\n\t\t\taddRoute(router, method, endpoint.path, endpoint);\n\t\t}\n\t}\n\n\tif (config?.routerMiddleware?.length) {\n\t\tfor (const { path, middleware } of config.routerMiddleware) {\n\t\t\taddRoute(middlewareRouter, \"*\", path, middleware);\n\t\t}\n\t}\n\n\tconst processRequest = async (request: Request) => {\n\t\tconst url = new URL(request.url);\n\t\tconst path = config?.basePath ? url.pathname.split(config.basePath)[1] : url.pathname;\n\n\t\tif (!path?.length) {\n\t\t\tconfig?.onError?.(new Error(\"NOT_FOUND\"));\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\tconst route = findRoute(router, request.method, path);\n\t\tif (!route?.data) {\n\t\t\treturn new Response(null, { status: 404, statusText: \"Not Found\" });\n\t\t}\n\n\t\tconst handler = route.data as Endpoint;\n\t\tconst context = {\n\t\t\tpath,\n\t\t\tmethod: request.method as \"GET\",\n\t\t\theaders: request.headers,\n\t\t\tparams: route.params as any,\n\t\t\trequest: request,\n\t\t\tbody: await getBody(handler.options.cloneRequest ? request.clone() : request),\n\t\t\tquery: Object.fromEntries(url.searchParams),\n\t\t\t_flag: \"router\" as const,\n\t\t\tasResponse: true,\n\t\t\tcontext: config?.routerContext,\n\t\t};\n\n\t\ttry {\n\t\t\tconst middlewareRoutes = findAllRoutes(middlewareRouter, \"*\", path);\n\t\t\tif (middlewareRoutes?.length) {\n\t\t\t\tfor (const { data: middleware, params } of middlewareRoutes) {\n\t\t\t\t\tconst res = await (middleware as Endpoint)({\n\t\t\t\t\t\t...context,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tasResponse: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (res instanceof Response) return res;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst response = (await handler(context)) as Response;\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (error instanceof APIError) {\n\t\t\t\treturn toResponse(error);\n\t\t\t}\n\t\t\tconsole.error(`# SERVER_ERROR: `, error);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\",\n\t\t\t});\n\t\t}\n\t};\n\n\treturn {\n\t\thandler: async (request: Request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) {\n\t\t\t\treturn onReq;\n\t\t\t}\n\t\t\tconst req = onReq instanceof Request ? onReq : request;\n\t\t\tconst res = await processRequest(req);\n\t\t\tconst onRes = await config?.onResponse?.(res);\n\t\t\tif (onRes instanceof Response) {\n\t\t\t\treturn onRes;\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tendpoints,\n\t};\n};\n\nexport type Router = ReturnType<typeof createRouter>;\n","import { ZodObject, ZodOptional, ZodSchema } from \"zod\";\nimport type { Endpoint, EndpointOptions } from \"./endpoint\";\n\nexport type OpenAPISchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\" | \"object\";\n\nexport interface OpenAPIParameter {\n\tin: \"query\" | \"path\" | \"header\" | \"cookie\";\n\tname?: string;\n\tdescription?: string;\n\trequired?: boolean;\n\tschema?: {\n\t\ttype: OpenAPISchemaType;\n\t\tformat?: string;\n\t\titems?: {\n\t\t\ttype: OpenAPISchemaType;\n\t\t};\n\t\tenum?: string[];\n\t\tminLength?: number;\n\t\tdescription?: string;\n\t\tdefault?: string;\n\t\texample?: string;\n\t};\n}\n\nexport interface Path {\n\tget?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n\tpost?: {\n\t\ttags?: string[];\n\t\toperationId?: string;\n\t\tdescription?: string;\n\t\tsecurity?: [{ bearerAuth: string[] }];\n\t\tparameters?: OpenAPIParameter[];\n\t\trequestBody?: {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\tresponses?: {\n\t\t\t[key in string]: {\n\t\t\t\tdescription?: string;\n\t\t\t\tcontent: {\n\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype?: OpenAPISchemaType;\n\t\t\t\t\t\t\tproperties?: Record<string, any>;\n\t\t\t\t\t\t\trequired?: string[];\n\t\t\t\t\t\t\t$ref?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\nconst paths: Record<string, Path> = {};\n\nfunction getTypeFromZodType(zodType: ZodSchema) {\n\tswitch (zodType.constructor.name) {\n\t\tcase \"ZodString\":\n\t\t\treturn \"string\";\n\t\tcase \"ZodNumber\":\n\t\t\treturn \"number\";\n\t\tcase \"ZodBoolean\":\n\t\t\treturn \"boolean\";\n\t\tcase \"ZodObject\":\n\t\t\treturn \"object\";\n\t\tcase \"ZodArray\":\n\t\t\treturn \"array\";\n\t\tdefault:\n\t\t\treturn \"string\";\n\t}\n}\n\nfunction getParameters(options: EndpointOptions) {\n\tconst parameters: OpenAPIParameter[] = [];\n\tif (options.metadata?.openAPI?.parameters) {\n\t\tparameters.push(...options.metadata.openAPI.parameters);\n\t\treturn parameters;\n\t}\n\tif (options.query instanceof ZodObject) {\n\t\tObject.entries(options.query.shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodSchema) {\n\t\t\t\tparameters.push({\n\t\t\t\t\tname: key,\n\t\t\t\t\tin: \"query\",\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\t\t...(\"minLength\" in value && value.minLength\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tminLength: value.minLength as number,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tdescription: value.description,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\treturn parameters;\n}\n\nfunction getRequestBody(options: EndpointOptions): any {\n\tif (options.metadata?.openAPI?.requestBody) {\n\t\treturn options.metadata.openAPI.requestBody;\n\t}\n\tif (!options.body) return undefined;\n\tif (options.body instanceof ZodObject || options.body instanceof ZodOptional) {\n\t\t// @ts-ignore\n\t\tconst shape = options.body.shape;\n\t\tif (!shape) return undefined;\n\t\tconst properties: Record<string, any> = {};\n\t\tconst required: string[] = [];\n\t\tObject.entries(shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodSchema) {\n\t\t\t\tproperties[key] = {\n\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\tdescription: value.description,\n\t\t\t\t};\n\t\t\t\tif (!(value instanceof ZodOptional)) {\n\t\t\t\t\trequired.push(key);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\trequired: options.body instanceof ZodOptional ? false : options.body ? true : false,\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties,\n\t\t\t\t\t\trequired,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction getResponse(responses?: Record<string, any>) {\n\treturn {\n\t\t\"400\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n\t\t},\n\t\t\"401\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"message\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Unauthorized. Due to missing or invalid authentication.\",\n\t\t},\n\t\t\"403\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Forbidden. You do not have permission to access this resource or to perform this action.\",\n\t\t},\n\t\t\"404\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Not Found. The requested resource was not found.\",\n\t\t},\n\t\t\"429\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription: \"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n\t\t},\n\t\t\"500\": {\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tdescription:\n\t\t\t\t\"Internal Server Error. This is a problem with the server that you cannot fix.\",\n\t\t},\n\t\t...responses,\n\t} as any;\n}\n\nexport async function generator(\n\tendpoints: Record<string, Endpoint>,\n\tconfig?: {\n\t\turl: string;\n\t},\n) {\n\tconst components = {\n\t\tschemas: {},\n\t};\n\n\tObject.entries(endpoints).forEach(([_, value]) => {\n\t\tconst options = value.options as EndpointOptions;\n\t\tif (options.metadata?.SERVER_ONLY) return;\n\t\tif (options.method === \"GET\") {\n\t\t\tpaths[value.path] = {\n\t\t\t\tget: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openAPI?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openAPI?.description,\n\t\t\t\t\toperationId: options.metadata?.openAPI?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openAPI?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tif (options.method === \"POST\") {\n\t\t\tconst body = getRequestBody(options);\n\t\t\tpaths[value.path] = {\n\t\t\t\tpost: {\n\t\t\t\t\ttags: [\"Default\", ...(options.metadata?.openAPI?.tags || [])],\n\t\t\t\t\tdescription: options.metadata?.openAPI?.description,\n\t\t\t\t\toperationId: options.metadata?.openAPI?.operationId,\n\t\t\t\t\tsecurity: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbearerAuth: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tparameters: getParameters(options),\n\t\t\t\t\t...(body\n\t\t\t\t\t\t? { requestBody: body }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\t\t\t//set body none\n\t\t\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\tresponses: getResponse(options.metadata?.openAPI?.responses),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t});\n\n\tconst res = {\n\t\topenapi: \"3.1.1\",\n\t\tinfo: {\n\t\t\ttitle: \"Better Auth\",\n\t\t\tdescription: \"API Reference for your Better Auth Instance\",\n\t\t\tversion: \"1.1.0\",\n\t\t},\n\t\tcomponents,\n\t\tsecurity: [\n\t\t\t{\n\t\t\t\tapiKeyCookie: [],\n\t\t\t},\n\t\t],\n\t\tservers: [\n\t\t\t{\n\t\t\t\turl: config?.url,\n\t\t\t},\n\t\t],\n\t\ttags: [\n\t\t\t{\n\t\t\t\tname: \"Default\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.\",\n\t\t\t},\n\t\t],\n\t\tpaths,\n\t};\n\treturn res;\n}\n\nexport const getHTML = (\n\tapiReference: Record<string, any>,\n\tconfig?: {\n\t\tlogo?: string;\n\t\ttheme?: string;\n\t\ttitle?: string;\n\t\tdescription?: string;\n\t},\n) => `<!doctype html>\n<html>\n <head>\n <title>Scalar API Reference</title>\n <meta charset=\"utf-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <script\n id=\"api-reference\"\n type=\"application/json\">\n ${JSON.stringify(apiReference)}\n </script>\n\t <script>\n var configuration = {\n\t \tfavicon: ${config?.logo ? `data:image/svg+xml;utf8,${encodeURIComponent(config.logo)}` : undefined} ,\n\t \ttheme: ${config?.theme || \"saturn\"},\n metaData: {\n\t\t\ttitle: ${config?.title || \"Open API Reference\"},\n\t\t\tdescription: ${config?.description || \"Better Call Open API\"},\n\t\t}\n }\n document.getElementById('api-reference').dataset.configuration =\n JSON.stringify(configuration)\n </script>\n\t <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n </body>\n</html>`;\n","export async function getBody(request: Request) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\n\tif (!request.body) {\n\t\treturn undefined;\n\t}\n\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn await request.json();\n\t}\n\n\tif (contentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, string> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result: Record<string, any> = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (contentType.includes(\"text/plain\")) {\n\t\treturn await request.text();\n\t}\n\n\tif (contentType.includes(\"application/octet-stream\")) {\n\t\treturn await request.arrayBuffer();\n\t}\n\n\tif (\n\t\tcontentType.includes(\"application/pdf\") ||\n\t\tcontentType.includes(\"image/\") ||\n\t\tcontentType.includes(\"video/\")\n\t) {\n\t\tconst blob = await request.blob();\n\t\treturn blob;\n\t}\n\n\tif (contentType.includes(\"application/stream\") || request.body instanceof ReadableStream) {\n\t\treturn request.body;\n\t}\n\n\treturn await request.text();\n}\n"],"mappings":";AAAO,IAAM,cAAc;AAAA,EAC1B,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,OAAO;AAAA,EACP,WAAW;AAAA,EACX,cAAc;AAAA,EACd,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,+BAA+B;AAAA,EAC/B,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,MAA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vC,aAAO,IAAI,SAAS,MAAM;AAAA,QACzB,QAAQ;AAAA,QACR,YAAY;AAAA,MACb,CAAC;AAAA,IACF;AAAA,EACD;AAEA,SAAO;AAAA,IACN,SAAS,OAAO,YAAqB;AACpC,YAAM,QAAQ,MAAM,QAAQ,YAAY,OAAO;AAC/C,UAAI,iBAAiB,UAAU;AAC9B,eAAO;AAAA,MACR;AACA,YAAM,MAAM,iBAAiB,UAAU,QAAQ;AAC/C,YAAM,MAAM,MAAM,eAAe,GAAG;AACpC,YAAM,QAAQ,MAAM,QAAQ,aAAa,GAAG;AAC5C,UAAI,iBAAiB,UAAU;AAC9B,eAAO;AAAA,MACR;AACA,aAAO;AAAA,IACR;AAAA,IACA;AAAA,EACD;AACD;","names":["options","headers","createEndpoint","createEndpoint"]}
package/dist/node.cjs ADDED
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/adapters/node/index.ts
31
+ var node_exports = {};
32
+ __export(node_exports, {
33
+ getRequest: () => getRequest,
34
+ setResponse: () => setResponse,
35
+ toNodeHandler: () => toNodeHandler
36
+ });
37
+ module.exports = __toCommonJS(node_exports);
38
+
39
+ // src/adapters/node/request.ts
40
+ var set_cookie_parser = __toESM(require("set-cookie-parser"), 1);
41
+ function get_raw_body(req, body_size_limit) {
42
+ const h = req.headers;
43
+ if (!h["content-type"]) return null;
44
+ const content_length = Number(h["content-length"]);
45
+ if (req.httpVersionMajor === 1 && isNaN(content_length) && h["transfer-encoding"] == null || content_length === 0) {
46
+ return null;
47
+ }
48
+ let length = content_length;
49
+ if (body_size_limit) {
50
+ if (!length) {
51
+ length = body_size_limit;
52
+ } else if (length > body_size_limit) {
53
+ throw Error(
54
+ `Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`
55
+ );
56
+ }
57
+ }
58
+ if (req.destroyed) {
59
+ const readable = new ReadableStream();
60
+ readable.cancel();
61
+ return readable;
62
+ }
63
+ let size = 0;
64
+ let cancelled = false;
65
+ return new ReadableStream({
66
+ start(controller) {
67
+ req.on("error", (error) => {
68
+ cancelled = true;
69
+ controller.error(error);
70
+ });
71
+ req.on("end", () => {
72
+ if (cancelled) return;
73
+ controller.close();
74
+ });
75
+ req.on("data", (chunk) => {
76
+ if (cancelled) return;
77
+ size += chunk.length;
78
+ if (size > length) {
79
+ cancelled = true;
80
+ controller.error(
81
+ new Error(
82
+ `request body size exceeded ${content_length ? "'content-length'" : "BODY_SIZE_LIMIT"} of ${length}`
83
+ )
84
+ );
85
+ return;
86
+ }
87
+ controller.enqueue(chunk);
88
+ if (controller.desiredSize === null || controller.desiredSize <= 0) {
89
+ req.pause();
90
+ }
91
+ });
92
+ },
93
+ pull() {
94
+ req.resume();
95
+ },
96
+ cancel(reason) {
97
+ cancelled = true;
98
+ req.destroy(reason);
99
+ }
100
+ });
101
+ }
102
+ function getRequest({
103
+ request,
104
+ base,
105
+ bodySizeLimit
106
+ }) {
107
+ return new Request(base + request.url, {
108
+ // @ts-expect-error
109
+ duplex: "half",
110
+ method: request.method,
111
+ body: get_raw_body(request, bodySizeLimit),
112
+ headers: request.headers
113
+ });
114
+ }
115
+ async function setResponse(res, response) {
116
+ for (const [key, value] of response.headers) {
117
+ try {
118
+ res.setHeader(
119
+ key,
120
+ key === "set-cookie" ? set_cookie_parser.splitCookiesString(response.headers.get(key)) : value
121
+ );
122
+ } catch (error) {
123
+ res.getHeaderNames().forEach((name) => res.removeHeader(name));
124
+ res.writeHead(500).end(String(error));
125
+ return;
126
+ }
127
+ }
128
+ res.writeHead(response.status);
129
+ if (!response.body) {
130
+ res.end();
131
+ return;
132
+ }
133
+ if (response.body.locked) {
134
+ res.end(
135
+ "Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."
136
+ );
137
+ return;
138
+ }
139
+ const reader = response.body.getReader();
140
+ if (res.destroyed) {
141
+ reader.cancel();
142
+ return;
143
+ }
144
+ const cancel = (error) => {
145
+ res.off("close", cancel);
146
+ res.off("error", cancel);
147
+ reader.cancel(error).catch(() => {
148
+ });
149
+ if (error) res.destroy(error);
150
+ };
151
+ res.on("close", cancel);
152
+ res.on("error", cancel);
153
+ next();
154
+ async function next() {
155
+ try {
156
+ for (; ; ) {
157
+ const { done, value } = await reader.read();
158
+ if (done) break;
159
+ if (!res.write(value)) {
160
+ res.once("drain", next);
161
+ return;
162
+ }
163
+ }
164
+ res.end();
165
+ } catch (error) {
166
+ cancel(error instanceof Error ? error : new Error(String(error)));
167
+ }
168
+ }
169
+ }
170
+
171
+ // src/adapters/node/index.ts
172
+ function toNodeHandler(handler) {
173
+ return async (req, res) => {
174
+ const protocol = req.headers["x-forwarded-proto"] || (req.socket.encrypted ? "https" : "http");
175
+ const base = `${protocol}://${req.headers[":authority"] || req.headers.host}`;
176
+ const response = await handler(getRequest({ base, request: req }));
177
+ setResponse(res, response);
178
+ };
179
+ }
180
+ // Annotate the CommonJS export names for ESM import in node:
181
+ 0 && (module.exports = {
182
+ getRequest,
183
+ setResponse,
184
+ toNodeHandler
185
+ });
186
+ //# sourceMappingURL=node.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/node/index.ts","../src/adapters/node/request.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request\";\nimport type { Router } from \"../../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol =\n\t\t\treq.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\tsetResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\treturn new Request(base + request.url, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody: get_raw_body(request, bodySizeLimit),\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,wBAAmC;AAEnC,SAAS,aAAa,KAAsB,iBAA0B;AACrE,QAAM,IAAI,IAAI;AAEd,MAAI,CAAC,EAAE,cAAc,EAAG,QAAO;AAE/B,QAAM,iBAAiB,OAAO,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,KAAM;AAEV,YAAI,CAAC,IAAI,MAAM,KAAK,GAAG;AACtB,cAAI,KAAK,SAAS,IAAI;AACtB;AAAA,QACD;AAAA,MACD;AACA,UAAI,IAAI;AAAA,IACT,SAAS,OAAO;AACf,aAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;AAAA,IACjE;AAAA,EACD;AACD;;;AD1KO,SAAS,cAAc,SAA4B;AACzD,SAAO,OAAO,KAAsB,QAAwB;AAC3D,UAAM,WACL,IAAI,QAAQ,mBAAmB,MAAO,IAAI,OAAe,YAAY,UAAU;AAChF,UAAM,OAAO,GAAG,QAAQ,MAAM,IAAI,QAAQ,YAAY,KAAK,IAAI,QAAQ,IAAI;AAC3E,UAAM,WAAW,MAAM,QAAQ,WAAW,EAAE,MAAM,SAAS,IAAI,CAAC,CAAC;AACjE,gBAAY,KAAK,QAAQ;AAAA,EAC1B;AACD;","names":[]}
@@ -0,0 +1,14 @@
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { j as Router } from './router-DNpkEV0c.cjs';
3
+ import '@standard-schema/spec';
4
+
5
+ declare function getRequest({ request, base, bodySizeLimit, }: {
6
+ base: string;
7
+ bodySizeLimit?: number;
8
+ request: IncomingMessage;
9
+ }): Request;
10
+ declare function setResponse(res: ServerResponse, response: Response): Promise<void>;
11
+
12
+ declare function toNodeHandler(handler: Router["handler"]): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
13
+
14
+ export { getRequest, setResponse, toNodeHandler };
package/dist/node.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { j as Router } from './router-DNpkEV0c.js';
3
+ import '@standard-schema/spec';
4
+
5
+ declare function getRequest({ request, base, bodySizeLimit, }: {
6
+ base: string;
7
+ bodySizeLimit?: number;
8
+ request: IncomingMessage;
9
+ }): Request;
10
+ declare function setResponse(res: ServerResponse, response: Response): Promise<void>;
11
+
12
+ declare function toNodeHandler(handler: Router["handler"]): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
13
+
14
+ export { getRequest, setResponse, toNodeHandler };