better-call 0.1.29 → 0.1.32

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/client.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-C6H0OIeC.cjs';
1
+ import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-p6UAV6VY.cjs';
2
2
  import { BetterFetchOption, BetterFetchResponse } from '@better-fetch/fetch';
3
3
  import 'zod';
4
4
 
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-C6H0OIeC.js';
1
+ import { R as Router, U as UnionToIntersection, E as Endpoint, H as HasRequiredKeys } from './router-p6UAV6VY.js';
2
2
  import { BetterFetchOption, BetterFetchResponse } from '@better-fetch/fetch';
3
3
  import 'zod';
4
4
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var F=Object.create;var R=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var V=(t,e,n)=>e in t?R(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Z=(t,e)=>{for(var n in e)R(t,n,{get:e[n],enumerable:!0})},N=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of G(e))!Y.call(t,o)&&o!==n&&R(t,o,{get:()=>e[o],enumerable:!(r=W(e,o))||r.enumerable});return t};var J=(t,e,n)=>(n=t!=null?F(z(t)):{},N(e||!t||!t.__esModule?R(n,"default",{value:t,enumerable:!0}):n,t)),X=t=>N(R({},"__esModule",{value:!0}),t);var P=(t,e,n)=>V(t,typeof e!="symbol"?e+"":e,n);var ue={};Z(ue,{APIError:()=>l,createEndpoint:()=>E,createEndpointCreator:()=>oe,createMiddleware:()=>ie,createMiddlewareCreator:()=>ae,createRouter:()=>se,getBody:()=>w,getRequest:()=>I,setResponse:()=>k,shouldSerialize:()=>S,statusCode:()=>b,toNodeHandler:()=>pe});module.exports=X(ue);var j=require("zod");var l=class extends Error{constructor(n,r){super(`API Error: ${n} ${r?.message??""}`,{cause:r});P(this,"status");P(this,"body");this.status=n,this.body=r??{},this.stack="",this.name="BetterCallAPIError"}};var U=(t,e)=>({response:{body:e?.body??t,status:e?.status??200,statusText:e?.statusText??"OK",headers:e?.headers},body:t,_flag:"json"});var T={name:"HMAC",hash:"SHA-256"},D=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await crypto.subtle.importKey("raw",e,T,!1,["sign","verify"])},ee=async(t,e)=>{let n=await D(e),r=await crypto.subtle.sign(T.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(r)))},te=async(t,e,n)=>{try{let r=atob(t),o=new Uint8Array(r.length);for(let i=0,s=r.length;i<s;i++)o[i]=r.charCodeAt(i);return await crypto.subtle.verify(T,n,o,new TextEncoder().encode(e))}catch{return!1}},ne=/^[\w!#$%&'*.^`|~+-]+$/,re=/^[ !#-:<-[\]-~]*$/,_=(t,e)=>t.trim().split(";").reduce((r,o)=>{o=o.trim();let i=o.indexOf("=");if(i===-1)return r;let s=o.substring(0,i).trim();if(e&&e!==s||!ne.test(s))return r;let a=o.substring(i+1).trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),re.test(a)&&(r[s]=decodeURIComponent(a)),r},{}),M=async(t,e,n)=>{let r={},o=await D(e);for(let[i,s]of Object.entries(_(t,n))){let a=s.lastIndexOf(".");if(a<1)continue;let u=s.substring(0,a),d=s.substring(a+1);if(d.length!==44||!d.endsWith("="))continue;let p=await te(d,u,o);r[i]=p?u:!1}return r},B=(t,e,n={})=>{let r=`${t}=${e}`;if(t.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(t.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},O=(t,e,n)=>(e=encodeURIComponent(e),B(t,e,n)),C=async(t,e,n,r={})=>{let o=await ee(e,n);return e=`${e}.${o}`,e=encodeURIComponent(e),B(t,e,r)};var q=(t,e,n)=>{if(!t)return;let r=e;if(n)if(n==="secure")r="__Secure-"+e;else if(n==="host")r="__Host-"+e;else return;return _(t,r)[r]},L=(t,e,n,r)=>{let o;r?.prefix==="secure"?o=O("__Secure-"+e,n,{path:"/",...r,secure:!0}):r?.prefix==="host"?o=O("__Host-"+e,n,{...r,path:"/",secure:!0,domain:void 0}):o=O(e,n,{path:"/",...r}),t.append("Set-Cookie",o)},$=async(t,e,n,r,o)=>{let i;o?.prefix==="secure"?i=await C("__Secure-"+e,n,r,{path:"/",...o,secure:!0}):o?.prefix==="host"?i=await C("__Host-"+e,n,r,{...o,path:"/",secure:!0,domain:void 0}):i=await C(e,n,r,{path:"/",...o}),t.append("Set-Cookie",i)},v=async(t,e,n,r)=>{let o=t.get("cookie");if(!o)return;let i=n;return r&&(r==="secure"?i="__Secure-"+n:r==="host"&&(i="__Host-"+n)),(await M(o,e,i))[i]};function oe(t){return(e,n,r)=>E(e,{...n,use:[...n?.use||[],...t?.use||[]]},r)}function E(t,e,n){let r=new Headers,o=async(...i)=>{let s={setHeader(d,p){r.set(d,p)},setCookie(d,p,c){L(r,d,p,c)},getCookie(d,p){let f=i[0]?.headers?.get("cookie");return q(f||"",d,p)},getSignedCookie(d,p,c){let f=i[0]?.headers;if(!f)throw new TypeError("Headers are required");return v(f,p,d,c)},async setSignedCookie(d,p,c,f){await $(r,d,p,c,f)},redirect(d){return r.set("Location",d),new l("FOUND")},json:U,...i[0]||{},context:i[0]?.context||{},_flag:i[0]?._flag,responseHeader:r};if(e.use?.length){let d={},p={};for(let c of e.use){let f=await c(s);if(f){let g=f.options?.body?f.options.body.parse(s.body):void 0;d={...d,...f},p={...p,...g}}}s={...s,body:{...p,...s.body},context:{...s.context||{},...d}}}try{let d=e.body?e.body.parse(s.body):s.body;s={...s,body:d?{...d,...s.body}:s.body},s.query=e.query?e.query.parse(s.query):s.query}catch(d){throw d instanceof j.ZodError?new l("BAD_REQUEST",{message:d.message,details:d.errors}):d}if(e.requireHeaders&&!s.headers)throw new l("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!s.request)throw new l("BAD_REQUEST",{message:"Request is required"});let a=await n(s),u=a;if(a&&typeof a=="object"&&"_flag"in a)if(a._flag==="json"&&s._flag==="router"){let d=a.response.headers;Object.keys(d||{}).forEach(p=>{r.set(p,d[p])}),u=new Response(JSON.stringify(a.response.body),{status:a.response.status??200,statusText:a.response.statusText,headers:r})}else u=a.body;return u};return o.path=t,o.options=e,o.method=e.method,o.headers=r,o}var h=require("rou3");async function w(t){let e=t.headers.get("content-type")||"";if(t.body){if(e.includes("application/json"))return await t.json();if(e.includes("application/x-www-form-urlencoded")){let n=await t.formData(),r={};return n.forEach((o,i)=>{r[i]=o.toString()}),r}if(e.includes("multipart/form-data")){let n=await t.formData(),r={};return n.forEach((o,i)=>{r[i]=o}),r}return e.includes("text/plain")?await t.text():e.includes("application/octet-stream")?await t.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await t.blob():e.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function S(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var b={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var se=(t,e)=>{let n=Object.values(t),r=(0,h.createRouter)();for(let s of n)if(Array.isArray(s.options?.method))for(let a of s.options.method)(0,h.addRoute)(r,a,s.path,s);else(0,h.addRoute)(r,s.options.method,s.path,s);let o=(0,h.createRouter)();for(let s of e?.routerMiddleware||[])(0,h.addRoute)(o,"*",s.path,s.middleware);return{handler:async s=>{let a=new URL(s.url),u=a.pathname;e?.basePath&&(u=u.split(e.basePath)[1]);let d=s.method,p=(0,h.findRoute)(r,d,u),c=p?.data,f=await w(s),g=s.headers,H=Object.fromEntries(a.searchParams),A=(0,h.findRoute)(o,"*",u)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let y={};if(A){let x=await A({path:u,method:d,headers:g,params:p?.params,request:s,body:f,query:H,context:{...e?.extraContext}});if(x instanceof Response)return x;if(x?._flag==="json")return new Response(JSON.stringify(x),{headers:x.headers});x&&(y={...x,...y})}let m=await c({path:u,method:d,headers:g,params:p?.params,request:s,body:f,query:H,_flag:"router",context:{...y,...e?.extraContext}});if(m instanceof Response)return m;let Q=S(m)?JSON.stringify(m):m;return new Response(Q,{headers:c.headers})}catch(y){if(e?.onError){let m=await e.onError(y);if(m instanceof Response)return m}if(y instanceof l)return new Response(y.body?JSON.stringify(y.body):null,{status:b[y.status],statusText:y.status,headers:c.headers});if(e?.throwError)throw y;return new Response(null,{status:500,statusText:"Internal Server Error"})}},endpoints:t}};function ie(t,e){if(typeof t=="function")return E("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return E("*",{...t,method:"*"},e)}var ae=t=>{function e(n,r){if(typeof n=="function")return E("*",{method:"*"},n);if(!r)throw new Error("Middleware handler is required");return E("*",{...n,method:"*"},r)}return e};var be=require("zod");var Ue=require("http");var ke=require("http"),K=J(require("set-cookie-parser"),1);function de(t,e){let n=t.headers;if(!n["content-type"])return null;let r=Number(n["content-length"]);if(t.httpVersionMajor===1&&isNaN(r)&&n["transfer-encoding"]==null||r===0)return null;let o=r;if(e){if(!o)o=e;else if(o>e)throw Error(`Received content-length of ${o}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let i=0,s=!1;return new ReadableStream({start(a){t.on("error",u=>{s=!0,a.error(u)}),t.on("end",()=>{s||a.close()}),t.on("data",u=>{if(!s){if(i+=u.length,i>o){s=!0,a.error(new Error(`request body size exceeded ${r?"'content-length'":"BODY_SIZE_LIMIT"} of ${o}`));return}a.enqueue(u),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){s=!0,t.destroy(a)}})}function I({request:t,base:e,bodySizeLimit:n}){return new Request(e+t.url,{duplex:"half",method:t.method,body:de(t,n),headers:t.headers})}async function k(t,e){for(let[i,s]of e.headers)try{t.setHeader(i,i==="set-cookie"?K.splitCookiesString(e.headers.get(i)):s)}catch(a){t.getHeaderNames().forEach(u=>t.removeHeader(u)),t.writeHead(500).end(String(a));return}if(t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let n=e.body.getReader();if(t.destroyed){n.cancel();return}let r=i=>{t.off("close",r),t.off("error",r),n.cancel(i).catch(()=>{}),i&&t.destroy(i)};t.on("close",r),t.on("error",r),o();async function o(){try{for(;;){let{done:i,value:s}=await n.read();if(i)break;if(!t.write(s)){t.once("drain",o);return}}t.end()}catch(i){r(i instanceof Error?i:new Error(String(i)))}}}function pe(t){return async(e,n)=>{let o=`${e.connection?.encrypted?"https":"http"}://${e.headers[":authority"]||e.headers.host}`,i=await t(I({base:o,request:e}));k(n,i)}}0&&(module.exports={APIError,createEndpoint,createEndpointCreator,createMiddleware,createMiddlewareCreator,createRouter,getBody,getRequest,setResponse,shouldSerialize,statusCode,toNodeHandler});
1
+ "use strict";var F=Object.create;var R=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var V=(t,e,n)=>e in t?R(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Z=(t,e)=>{for(var n in e)R(t,n,{get:e[n],enumerable:!0})},N=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of G(e))!Y.call(t,s)&&s!==n&&R(t,s,{get:()=>e[s],enumerable:!(r=W(e,s))||r.enumerable});return t};var J=(t,e,n)=>(n=t!=null?F(z(t)):{},N(e||!t||!t.__esModule?R(n,"default",{value:t,enumerable:!0}):n,t)),X=t=>N(R({},"__esModule",{value:!0}),t);var P=(t,e,n)=>V(t,typeof e!="symbol"?e+"":e,n);var ue={};Z(ue,{APIError:()=>m,createEndpoint:()=>x,createEndpointCreator:()=>oe,createMiddleware:()=>ie,createMiddlewareCreator:()=>ae,createRouter:()=>se,getBody:()=>_,getRequest:()=>I,setResponse:()=>k,shouldSerialize:()=>S,statusCode:()=>b,toNodeHandler:()=>pe});module.exports=X(ue);var j=require("zod");var m=class extends Error{constructor(n,r){super(`API Error: ${n} ${r?.message??""}`,{cause:r});P(this,"status");P(this,"body");this.status=n,this.body=r??{},this.stack="",this.name="BetterCallAPIError"}};var U=(t,e)=>({response:{body:e?.body??t,status:e?.status??200,statusText:e?.statusText??"OK",headers:e?.headers},body:t,_flag:"json"});var T={name:"HMAC",hash:"SHA-256"},D=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await crypto.subtle.importKey("raw",e,T,!1,["sign","verify"])},ee=async(t,e)=>{let n=await D(e),r=await crypto.subtle.sign(T.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(r)))},te=async(t,e,n)=>{try{let r=atob(t),s=new Uint8Array(r.length);for(let i=0,o=r.length;i<o;i++)s[i]=r.charCodeAt(i);return await crypto.subtle.verify(T,n,s,new TextEncoder().encode(e))}catch{return!1}},ne=/^[\w!#$%&'*.^`|~+-]+$/,re=/^[ !#-:<-[\]-~]*$/,w=(t,e)=>t.trim().split(";").reduce((r,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return r;let o=s.substring(0,i).trim();if(e&&e!==o||!ne.test(o))return r;let a=s.substring(i+1).trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),re.test(a)&&(r[o]=decodeURIComponent(a)),r},{}),M=async(t,e,n)=>{let r={},s=await D(e);for(let[i,o]of Object.entries(w(t,n))){let a=o.lastIndexOf(".");if(a<1)continue;let p=o.substring(0,a),d=o.substring(a+1);if(d.length!==44||!d.endsWith("="))continue;let u=await te(d,p,s);r[i]=u?p:!1}return r},B=(t,e,n={})=>{let r=`${t}=${e}`;if(t.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(t.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},O=(t,e,n)=>(e=encodeURIComponent(e),B(t,e,n)),C=async(t,e,n,r={})=>{let s=await ee(e,n);return e=`${e}.${s}`,e=encodeURIComponent(e),B(t,e,r)};var q=(t,e,n)=>{if(!t)return;let r=e;if(n)if(n==="secure")r="__Secure-"+e;else if(n==="host")r="__Host-"+e;else return;return w(t,r)[r]},L=(t,e,n,r)=>{let s;r?.prefix==="secure"?s=O("__Secure-"+e,n,{path:"/",...r,secure:!0}):r?.prefix==="host"?s=O("__Host-"+e,n,{...r,path:"/",secure:!0,domain:void 0}):s=O(e,n,{path:"/",...r}),t.append("Set-Cookie",s)},$=async(t,e,n,r,s)=>{let i;s?.prefix==="secure"?i=await C("__Secure-"+e,n,r,{path:"/",...s,secure:!0}):s?.prefix==="host"?i=await C("__Host-"+e,n,r,{...s,path:"/",secure:!0,domain:void 0}):i=await C(e,n,r,{path:"/",...s}),t.append("Set-Cookie",i)},v=async(t,e,n,r)=>{let s=t.get("cookie");if(!s)return;let i=n;return r&&(r==="secure"?i="__Secure-"+n:r==="host"&&(i="__Host-"+n)),(await M(s,e,i))[i]};function oe(t){return(e,n,r)=>x(e,{...n,use:[...n?.use||[],...t?.use||[]]},r)}function x(t,e,n){let r=new Headers,s=async(...i)=>{let o={setHeader(d,u){r.set(d,u)},setCookie(d,u,c){L(r,d,u,c)},getCookie(d,u){let f=i[0]?.headers?.get("cookie");return q(f||"",d,u)},getSignedCookie(d,u,c){let f=i[0]?.headers;if(!f)throw new TypeError("Headers are required");return v(f,u,d,c)},async setSignedCookie(d,u,c,f){await $(r,d,u,c,f)},redirect(d){return r.set("Location",d),new m("FOUND")},json:U,...i[0]||{},context:i[0]?.context||{},_flag:i[0]?._flag,responseHeader:r};if(e.use?.length){let d={},u={};for(let c of e.use){let f=await c(o);if(f){let g=f.options?.body?f.options.body.parse(o.body):void 0;d={...d,...f},u={...u,...g}}}o={...o,body:{...u,...o.body},context:{...o.context||{},...d}}}try{let d=e.body?e.body.parse(o.body):o.body;o={...o,body:d?{...d,...o.body}:o.body},o.query=e.query?e.query.parse(o.query):o.query}catch(d){throw d instanceof j.ZodError?new m("BAD_REQUEST",{message:d.message,details:d.errors}):d}if(e.requireHeaders&&!o.headers)throw new m("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!o.request)throw new m("BAD_REQUEST",{message:"Request is required"});let a=await n(o),p=a;if(a&&typeof a=="object"&&"_flag"in a)if(a._flag==="json"&&o._flag==="router"){let d=a.response.headers;Object.keys(d||{}).forEach(u=>{r.set(u,d[u])}),p=new Response(JSON.stringify(a.response.body),{status:a.response.status??200,statusText:a.response.statusText,headers:r})}else p=a.body;return p};return s.path=t,s.options=e,s.method=e.method,s.headers=r,s}var l=require("rou3");async function _(t){let e=t.headers.get("content-type")||"";if(t.body){if(e.includes("application/json"))return await t.json();if(e.includes("application/x-www-form-urlencoded")){let n=await t.formData(),r={};return n.forEach((s,i)=>{r[i]=s.toString()}),r}if(e.includes("multipart/form-data")){let n=await t.formData(),r={};return n.forEach((s,i)=>{r[i]=s}),r}return e.includes("text/plain")?await t.text():e.includes("application/octet-stream")?await t.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await t.blob():e.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function S(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var b={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var se=(t,e)=>{let n=Object.values(t),r=(0,l.createRouter)();for(let o of n)if(Array.isArray(o.options?.method))for(let a of o.options.method)(0,l.addRoute)(r,a,o.path,o);else(0,l.addRoute)(r,o.options.method,o.path,o);let s=(0,l.createRouter)();for(let o of e?.routerMiddleware||[])(0,l.addRoute)(s,"*",o.path,o.middleware);let i=async o=>{let a=new URL(o.url),p=a.pathname;e?.basePath&&(p=p.split(e.basePath)[1]);let d=o.method,u=(0,l.findRoute)(r,d,p),c=u?.data,f=await _(o),g=o.headers,H=Object.fromEntries(a.searchParams),A=(0,l.findRoute)(s,"*",p)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let y={};if(A){let E=await A({path:p,method:d,headers:g,params:u?.params,request:o,body:f,query:H,context:{...e?.extraContext}});if(E instanceof Response)return E;if(E?._flag==="json")return new Response(JSON.stringify(E),{headers:E.headers});E&&(y={...E,...y})}let h=await c({path:p,method:d,headers:g,params:u?.params,request:o,body:f,query:H,_flag:"router",context:{...y,...e?.extraContext}});if(h instanceof Response)return h;let Q=S(h)?JSON.stringify(h):h;return new Response(Q,{headers:c.headers})}catch(y){if(e?.onError){let h=await e.onError(y);if(h instanceof Response)return h}if(y instanceof m)return new Response(y.body?JSON.stringify(y.body):null,{status:b[y.status],statusText:y.status,headers:c.headers});if(e?.throwError)throw y;return new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async o=>{let a=e?.transformRequest?e.transformRequest(o):o,p=await i(a);return e?.transformResponse?e.transformResponse(p):p},endpoints:t}};function ie(t,e){if(typeof t=="function")return x("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return x("*",{...t,method:"*"},e)}var ae=t=>{function e(n,r){if(typeof n=="function")return x("*",{method:"*"},n);if(!r)throw new Error("Middleware handler is required");return x("*",{...n,method:"*"},r)}return e};var be=require("zod");var Ue=require("http");var ke=require("http"),K=J(require("set-cookie-parser"),1);function de(t,e){let n=t.headers;if(!n["content-type"])return null;let r=Number(n["content-length"]);if(t.httpVersionMajor===1&&isNaN(r)&&n["transfer-encoding"]==null||r===0)return null;let s=r;if(e){if(!s)s=e;else if(s>e)throw Error(`Received content-length of ${s}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let i=0,o=!1;return new ReadableStream({start(a){t.on("error",p=>{o=!0,a.error(p)}),t.on("end",()=>{o||a.close()}),t.on("data",p=>{if(!o){if(i+=p.length,i>s){o=!0,a.error(new Error(`request body size exceeded ${r?"'content-length'":"BODY_SIZE_LIMIT"} of ${s}`));return}a.enqueue(p),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){o=!0,t.destroy(a)}})}function I({request:t,base:e,bodySizeLimit:n}){return new Request(e+t.url,{duplex:"half",method:t.method,body:de(t,n),headers:t.headers})}async function k(t,e){for(let[i,o]of e.headers)try{t.setHeader(i,i==="set-cookie"?K.splitCookiesString(e.headers.get(i)):o)}catch(a){t.getHeaderNames().forEach(p=>t.removeHeader(p)),t.writeHead(500).end(String(a));return}if(t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let n=e.body.getReader();if(t.destroyed){n.cancel();return}let r=i=>{t.off("close",r),t.off("error",r),n.cancel(i).catch(()=>{}),i&&t.destroy(i)};t.on("close",r),t.on("error",r),s();async function s(){try{for(;;){let{done:i,value:o}=await n.read();if(i)break;if(!t.write(o)){t.once("drain",s);return}}t.end()}catch(i){r(i instanceof Error?i:new Error(String(i)))}}}function pe(t){return async(e,n)=>{let s=`${e.connection?.encrypted?"https":"http"}://${e.headers[":authority"]||e.headers.host}`,i=await t(I({base:s,request:e}));k(n,i)}}0&&(module.exports={APIError,createEndpoint,createEndpointCreator,createMiddleware,createMiddlewareCreator,createRouter,getBody,getRequest,setResponse,shouldSerialize,statusCode,toNodeHandler});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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/node.ts","../src/adapter/request.ts"],"sourcesContent":["export * from \"./endpoint\";\nexport * from \"./router\";\nexport * from \"./middleware\";\nexport * from \"./error\";\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./adapter\";\n","import { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\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 } 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\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\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\t...(ctx[0] || {}),\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?._flag as string,\n\t\t\tresponseHeader,\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\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,\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,\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//@ts-expect-error\n\t\tlet res = (await handler(internalCtx)) as any;\n\n\t\tlet actualResponse: any = res;\n\n\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t});\n\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\theaders: responseHeader,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tactualResponse = res.body;\n\t\t\t}\n\t\t}\n\n\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\treturn actualResponse as R extends {\n\t\t\t_flag: \"json\";\n\t\t}\n\t\t\t? R extends { body: infer B }\n\t\t\t\t? B\n\t\t\t\t: null\n\t\t\t: Awaited<ReturnT>;\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\tbody: Record<string, any>;\n\tconstructor(status: Status, body?: Record<string, any>) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\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\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): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.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 crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\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 crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\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\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\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\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\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","//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\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\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 } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, Method } from \"./types\";\n\ninterface 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}\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 (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\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 middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined;\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 (middleware) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\tpath: path,\n\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\trequest: request,\n\t\t\t\t\tbody: body,\n\t\t\t\t\tquery,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (res) {\n\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t...res,\n\t\t\t\t\t\t...middlewareContext,\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: handler.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,\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 { CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\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?: Record<string, any>;\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 interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\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 * internal flags\n\t */\n\t_flag?: string;\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\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> = (\n\tctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & Omit<ContextTools, \"_flag\">>,\n) => 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> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n","import { 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 = (req.connection 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 { 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":"ksBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,mBAAAC,EAAA,0BAAAC,GAAA,qBAAAC,GAAA,4BAAAC,GAAA,iBAAAC,GAAA,YAAAC,EAAA,eAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,eAAAC,EAAA,kBAAAC,KAAA,eAAAC,EAAAd,ICAA,IAAAe,EAAyB,eCIlB,IAAMC,EAAN,cAAuB,KAAM,CAGnC,YAAYC,EAAgBC,EAA4B,CACvD,MAAM,cAAcD,CAAM,IAAIC,GAAM,SAAW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CAACR,EAAI,MAAMG,CAAK,EAAG,CACtBH,EAAI,KAAK,QAASO,CAAI,EACtB,MACD,CACD,CACAP,EAAI,IAAI,CACT,OAASR,EAAO,CACfc,EAAOd,aAAiB,MAAQA,EAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC,CAAC,CACjE,CACD,CACD,CD1KO,SAASiB,GAAcC,EAA4B,CACzD,MAAO,OAAOC,EAAsBC,IAAwB,CAE3D,IAAMC,EAAO,GADKF,EAAI,YAAoB,UAAY,QAAU,MACxC,MAAMA,EAAI,QAAQ,YAAY,GAAKA,EAAI,QAAQ,IAAI,GACrEG,EAAW,MAAMJ,EAAQK,EAAW,CAAE,KAAAF,EAAM,QAASF,CAAI,CAAC,CAAC,EACjEK,EAAYJ,EAAKE,CAAQ,CAC1B,CACD","names":["src_exports","__export","APIError","createEndpoint","createEndpointCreator","createMiddleware","createMiddlewareCreator","createRouter","getBody","getRequest","setResponse","shouldSerialize","statusCode","toNodeHandler","__toCommonJS","import_zod","APIError","status","body","__publicField","json","body","option","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","len","validCookieNameRegEx","validCookieValueRegEx","parse","cookie","name","parsedCookie","pairStr","valueStartPos","cookieName","cookieValue","parseSigned","secretKey","signatureStartPos","signedValue","isVerified","_serialize","opt","serialize","serializeSigned","getCookie","cookie","key","prefix","finalKey","parse","setCookie","header","name","value","opt","serialize","setSignedCookie","secret","serializeSigned","getSignedCookie","parseSigned","createEndpointCreator","opts","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","setCookie","prefix","cookieH","getCookie","secret","header","getSignedCookie","setSignedCookie","url","APIError","json","middlewareContexts","middlewareBody","middleware","res","body","e","actualResponse","h","import_rou3","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","_endpoints","router","createRou3Router","endpoint","method","middlewareRouter","route","request","url","path","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","opts","fn","import_zod","import_node_http","import_node_http","set_cookie_parser","get_raw_body","req","body_size_limit","h","content_length","length","readable","size","cancelled","controller","error","chunk","reason","getRequest","request","base","bodySizeLimit","setResponse","res","response","key","value","name","reader","cancel","next","done","toNodeHandler","handler","req","res","base","response","getRequest","setResponse"]}
1
+ {"version":3,"sources":["../src/index.ts","../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/node.ts","../src/adapter/request.ts"],"sourcesContent":["export * from \"./endpoint\";\nexport * from \"./router\";\nexport * from \"./middleware\";\nexport * from \"./error\";\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./adapter\";\n","import { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\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 } 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\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\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\t...(ctx[0] || {}),\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?._flag as string,\n\t\t\tresponseHeader,\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\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,\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,\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//@ts-expect-error\n\t\tlet res = (await handler(internalCtx)) as any;\n\n\t\tlet actualResponse: any = res;\n\n\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t});\n\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\theaders: responseHeader,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tactualResponse = res.body;\n\t\t\t}\n\t\t}\n\n\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\treturn actualResponse as R extends {\n\t\t\t_flag: \"json\";\n\t\t}\n\t\t\t? R extends { body: infer B }\n\t\t\t\t? B\n\t\t\t\t: null\n\t\t\t: Awaited<ReturnT>;\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\tbody: Record<string, any>;\n\tconstructor(status: Status, body?: Record<string, any>) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\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\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): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.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 crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\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 crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\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\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\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\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\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","//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\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\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 } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, EndpointResponse, Method } from \"./types\";\n\ninterface 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\ttransformResponse?: (res: Response) => Response;\n\ttransformRequest?: (req: Request) => Request;\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 (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\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 middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined;\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 (middleware) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\tpath: path,\n\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\trequest: request,\n\t\t\t\t\tbody: body,\n\t\t\t\t\tquery,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (res) {\n\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t...res,\n\t\t\t\t\t\t...middlewareContext,\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: handler.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 req = config?.transformRequest ? config.transformRequest(request) : request;\n\t\t\tconst res = await handler(req);\n\t\t\tif (config?.transformResponse) {\n\t\t\t\treturn config.transformResponse(res);\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 { CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\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?: Record<string, any>;\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 interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\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 * internal flags\n\t */\n\t_flag?: string;\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\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> = (\n\tctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & Omit<ContextTools, \"_flag\">>,\n) => 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> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n","import { 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 = (req.connection 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 { 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":"ksBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,mBAAAC,EAAA,0BAAAC,GAAA,qBAAAC,GAAA,4BAAAC,GAAA,iBAAAC,GAAA,YAAAC,EAAA,eAAAC,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,EAAUd,GAAkB,CACjCQ,EAAI,IAAI,QAASM,CAAM,EACvBN,EAAI,IAAI,QAASM,CAAM,EAIvBD,EAAO,OAAOb,CAAK,EAAE,MAAM,IAAM,CAAC,CAAC,EAC/BA,GAAOQ,EAAI,QAAQR,CAAK,CAC7B,EAEAQ,EAAI,GAAG,QAASM,CAAM,EACtBN,EAAI,GAAG,QAASM,CAAM,EAEtBC,EAAK,EACL,eAAeA,GAAO,CACrB,GAAI,CACH,OAAS,CACR,GAAM,CAAE,KAAAC,EAAM,MAAAL,CAAM,EAAI,MAAME,EAAO,KAAK,EAE1C,GAAIG,EAAM,MAEV,GAAI,CAACR,EAAI,MAAMG,CAAK,EAAG,CACtBH,EAAI,KAAK,QAASO,CAAI,EACtB,MACD,CACD,CACAP,EAAI,IAAI,CACT,OAASR,EAAO,CACfc,EAAOd,aAAiB,MAAQA,EAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC,CAAC,CACjE,CACD,CACD,CD1KO,SAASiB,GAAcC,EAA4B,CACzD,MAAO,OAAOC,EAAsBC,IAAwB,CAE3D,IAAMC,EAAO,GADKF,EAAI,YAAoB,UAAY,QAAU,MACxC,MAAMA,EAAI,QAAQ,YAAY,GAAKA,EAAI,QAAQ,IAAI,GACrEG,EAAW,MAAMJ,EAAQK,EAAW,CAAE,KAAAF,EAAM,QAASF,CAAI,CAAC,CAAC,EACjEK,EAAYJ,EAAKE,CAAQ,CAC1B,CACD","names":["src_exports","__export","APIError","createEndpoint","createEndpointCreator","createMiddleware","createMiddlewareCreator","createRouter","getBody","getRequest","setResponse","shouldSerialize","statusCode","toNodeHandler","__toCommonJS","import_zod","APIError","status","body","__publicField","json","body","option","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","len","validCookieNameRegEx","validCookieValueRegEx","parse","cookie","name","parsedCookie","pairStr","valueStartPos","cookieName","cookieValue","parseSigned","secretKey","signatureStartPos","signedValue","isVerified","_serialize","opt","serialize","serializeSigned","getCookie","cookie","key","prefix","finalKey","parse","setCookie","header","name","value","opt","serialize","setSignedCookie","secret","serializeSigned","getSignedCookie","parseSigned","createEndpointCreator","opts","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","setCookie","prefix","cookieH","getCookie","secret","header","getSignedCookie","setSignedCookie","url","APIError","json","middlewareContexts","middlewareBody","middleware","res","body","e","actualResponse","h","import_rou3","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","_endpoints","router","createRou3Router","endpoint","method","middlewareRouter","route","handler","request","url","path","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","req","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","opts","fn","import_zod","import_node_http","import_node_http","set_cookie_parser","get_raw_body","req","body_size_limit","h","content_length","length","readable","size","cancelled","controller","error","chunk","reason","getRequest","request","base","bodySizeLimit","setResponse","res","response","key","value","name","reader","cancel","next","done","toNodeHandler","handler","req","res","base","response","getRequest","setResponse"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router } from './router-C6H0OIeC.cjs';
2
- export { A as APIError, n as CookieOptions, r as EndpointBody, o as InferMethod, q as InferParam, l as InferParamPath, m as InferParamWildCard, p as InferQuery, i as createRouter, j as getBody, s as shouldSerialize, k as statusCode } from './router-C6H0OIeC.cjs';
1
+ import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router } from './router-p6UAV6VY.cjs';
2
+ export { A as APIError, n as CookieOptions, r as EndpointBody, o as InferMethod, q as InferParam, l as InferParamPath, m as InferParamWildCard, p as InferQuery, i as createRouter, j as getBody, s as shouldSerialize, k as statusCode } from './router-p6UAV6VY.cjs';
3
3
  import { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import 'zod';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router } from './router-C6H0OIeC.js';
2
- export { A as APIError, n as CookieOptions, r as EndpointBody, o as InferMethod, q as InferParam, l as InferParamPath, m as InferParamWildCard, p as InferQuery, i as createRouter, j as getBody, s as shouldSerialize, k as statusCode } from './router-C6H0OIeC.js';
1
+ import { E as Endpoint, a as EndpointOptions, b as EndpointResponse, P as Prettify, C as Context, I as InferUse, c as ContextTools, H as HasRequiredKeys, M as Method, d as Handler, e as InferBody, f as InferRequest, g as InferHeaders, h as InferUseOptions, R as Router } from './router-p6UAV6VY.js';
2
+ export { A as APIError, n as CookieOptions, r as EndpointBody, o as InferMethod, q as InferParam, l as InferParamPath, m as InferParamWildCard, p as InferQuery, i as createRouter, j as getBody, s as shouldSerialize, k as statusCode } from './router-p6UAV6VY.js';
3
3
  import { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import 'zod';
5
5
 
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Q=Object.defineProperty;var F=(t,e,n)=>e in t?Q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var O=(t,e,n)=>F(t,typeof e!="symbol"?e+"":e,n);import{ZodError as V}from"zod";var l=class extends Error{constructor(n,r){super(`API Error: ${n} ${r?.message??""}`,{cause:r});O(this,"status");O(this,"body");this.status=n,this.body=r??{},this.stack="",this.name="BetterCallAPIError"}};var S=(t,e)=>({response:{body:e?.body??t,status:e?.status??200,statusText:e?.statusText??"OK",headers:e?.headers},body:t,_flag:"json"});var C={name:"HMAC",hash:"SHA-256"},b=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await crypto.subtle.importKey("raw",e,C,!1,["sign","verify"])},W=async(t,e)=>{let n=await b(e),r=await crypto.subtle.sign(C.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(r)))},G=async(t,e,n)=>{try{let r=atob(t),s=new Uint8Array(r.length);for(let i=0,o=r.length;i<o;i++)s[i]=r.charCodeAt(i);return await crypto.subtle.verify(C,n,s,new TextEncoder().encode(e))}catch{return!1}},z=/^[\w!#$%&'*.^`|~+-]+$/,Y=/^[ !#-:<-[\]-~]*$/,P=(t,e)=>t.trim().split(";").reduce((r,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return r;let o=s.substring(0,i).trim();if(e&&e!==o||!z.test(o))return r;let a=s.substring(i+1).trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),Y.test(a)&&(r[o]=decodeURIComponent(a)),r},{}),I=async(t,e,n)=>{let r={},s=await b(e);for(let[i,o]of Object.entries(P(t,n))){let a=o.lastIndexOf(".");if(a<1)continue;let u=o.substring(0,a),d=o.substring(a+1);if(d.length!==44||!d.endsWith("="))continue;let p=await G(d,u,s);r[i]=p?u:!1}return r},k=(t,e,n={})=>{let r=`${t}=${e}`;if(t.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(t.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},g=(t,e,n)=>(e=encodeURIComponent(e),k(t,e,n)),R=async(t,e,n,r={})=>{let s=await W(e,n);return e=`${e}.${s}`,e=encodeURIComponent(e),k(t,e,r)};var H=(t,e,n)=>{if(!t)return;let r=e;if(n)if(n==="secure")r="__Secure-"+e;else if(n==="host")r="__Host-"+e;else return;return P(t,r)[r]},A=(t,e,n,r)=>{let s;r?.prefix==="secure"?s=g("__Secure-"+e,n,{path:"/",...r,secure:!0}):r?.prefix==="host"?s=g("__Host-"+e,n,{...r,path:"/",secure:!0,domain:void 0}):s=g(e,n,{path:"/",...r}),t.append("Set-Cookie",s)},N=async(t,e,n,r,s)=>{let i;s?.prefix==="secure"?i=await R("__Secure-"+e,n,r,{path:"/",...s,secure:!0}):s?.prefix==="host"?i=await R("__Host-"+e,n,r,{...s,path:"/",secure:!0,domain:void 0}):i=await R(e,n,r,{path:"/",...s}),t.append("Set-Cookie",i)},U=async(t,e,n,r)=>{let s=t.get("cookie");if(!s)return;let i=n;return r&&(r==="secure"?i="__Secure-"+n:r==="host"&&(i="__Host-"+n)),(await I(s,e,i))[i]};function pe(t){return(e,n,r)=>E(e,{...n,use:[...n?.use||[],...t?.use||[]]},r)}function E(t,e,n){let r=new Headers,s=async(...i)=>{let o={setHeader(d,p){r.set(d,p)},setCookie(d,p,c){A(r,d,p,c)},getCookie(d,p){let f=i[0]?.headers?.get("cookie");return H(f||"",d,p)},getSignedCookie(d,p,c){let f=i[0]?.headers;if(!f)throw new TypeError("Headers are required");return U(f,p,d,c)},async setSignedCookie(d,p,c,f){await N(r,d,p,c,f)},redirect(d){return r.set("Location",d),new l("FOUND")},json:S,...i[0]||{},context:i[0]?.context||{},_flag:i[0]?._flag,responseHeader:r};if(e.use?.length){let d={},p={};for(let c of e.use){let f=await c(o);if(f){let x=f.options?.body?f.options.body.parse(o.body):void 0;d={...d,...f},p={...p,...x}}}o={...o,body:{...p,...o.body},context:{...o.context||{},...d}}}try{let d=e.body?e.body.parse(o.body):o.body;o={...o,body:d?{...d,...o.body}:o.body},o.query=e.query?e.query.parse(o.query):o.query}catch(d){throw d instanceof V?new l("BAD_REQUEST",{message:d.message,details:d.errors}):d}if(e.requireHeaders&&!o.headers)throw new l("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!o.request)throw new l("BAD_REQUEST",{message:"Request is required"});let a=await n(o),u=a;if(a&&typeof a=="object"&&"_flag"in a)if(a._flag==="json"&&o._flag==="router"){let d=a.response.headers;Object.keys(d||{}).forEach(p=>{r.set(p,d[p])}),u=new Response(JSON.stringify(a.response.body),{status:a.response.status??200,statusText:a.response.statusText,headers:r})}else u=a.body;return u};return s.path=t,s.options=e,s.method=e.method,s.headers=r,s}import{createRouter as q,addRoute as T,findRoute as L}from"rou3";async function D(t){let e=t.headers.get("content-type")||"";if(t.body){if(e.includes("application/json"))return await t.json();if(e.includes("application/x-www-form-urlencoded")){let n=await t.formData(),r={};return n.forEach((s,i)=>{r[i]=s.toString()}),r}if(e.includes("multipart/form-data")){let n=await t.formData(),r={};return n.forEach((s,i)=>{r[i]=s}),r}return e.includes("text/plain")?await t.text():e.includes("application/octet-stream")?await t.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await t.blob():e.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function M(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var B={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var he=(t,e)=>{let n=Object.values(t),r=q();for(let o of n)if(Array.isArray(o.options?.method))for(let a of o.options.method)T(r,a,o.path,o);else T(r,o.options.method,o.path,o);let s=q();for(let o of e?.routerMiddleware||[])T(s,"*",o.path,o.middleware);return{handler:async o=>{let a=new URL(o.url),u=a.pathname;e?.basePath&&(u=u.split(e.basePath)[1]);let d=o.method,p=L(r,d,u),c=p?.data,f=await D(o),x=o.headers,_=Object.fromEntries(a.searchParams),w=L(s,"*",u)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let y={};if(w){let m=await w({path:u,method:d,headers:x,params:p?.params,request:o,body:f,query:_,context:{...e?.extraContext}});if(m instanceof Response)return m;if(m?._flag==="json")return new Response(JSON.stringify(m),{headers:m.headers});m&&(y={...m,...y})}let h=await c({path:u,method:d,headers:x,params:p?.params,request:o,body:f,query:_,_flag:"router",context:{...y,...e?.extraContext}});if(h instanceof Response)return h;let K=M(h)?JSON.stringify(h):h;return new Response(K,{headers:c.headers})}catch(y){if(e?.onError){let h=await e.onError(y);if(h instanceof Response)return h}if(y instanceof l)return new Response(y.body?JSON.stringify(y.body):null,{status:B[y.status],statusText:y.status,headers:c.headers});if(e?.throwError)throw y;return new Response(null,{status:500,statusText:"Internal Server Error"})}},endpoints:t}};function Ee(t,e){if(typeof t=="function")return E("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return E("*",{...t,method:"*"},e)}var ge=t=>{function e(n,r){if(typeof n=="function")return E("*",{method:"*"},n);if(!r)throw new Error("Middleware handler is required");return E("*",{...n,method:"*"},r)}return e};import"zod";import*as $ from"set-cookie-parser";function Z(t,e){let n=t.headers;if(!n["content-type"])return null;let r=Number(n["content-length"]);if(t.httpVersionMajor===1&&isNaN(r)&&n["transfer-encoding"]==null||r===0)return null;let s=r;if(e){if(!s)s=e;else if(s>e)throw Error(`Received content-length of ${s}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let i=0,o=!1;return new ReadableStream({start(a){t.on("error",u=>{o=!0,a.error(u)}),t.on("end",()=>{o||a.close()}),t.on("data",u=>{if(!o){if(i+=u.length,i>s){o=!0,a.error(new Error(`request body size exceeded ${r?"'content-length'":"BODY_SIZE_LIMIT"} of ${s}`));return}a.enqueue(u),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){o=!0,t.destroy(a)}})}function v({request:t,base:e,bodySizeLimit:n}){return new Request(e+t.url,{duplex:"half",method:t.method,body:Z(t,n),headers:t.headers})}async function j(t,e){for(let[i,o]of e.headers)try{t.setHeader(i,i==="set-cookie"?$.splitCookiesString(e.headers.get(i)):o)}catch(a){t.getHeaderNames().forEach(u=>t.removeHeader(u)),t.writeHead(500).end(String(a));return}if(t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let n=e.body.getReader();if(t.destroyed){n.cancel();return}let r=i=>{t.off("close",r),t.off("error",r),n.cancel(i).catch(()=>{}),i&&t.destroy(i)};t.on("close",r),t.on("error",r),s();async function s(){try{for(;;){let{done:i,value:o}=await n.read();if(i)break;if(!t.write(o)){t.once("drain",s);return}}t.end()}catch(i){r(i instanceof Error?i:new Error(String(i)))}}}function _e(t){return async(e,n)=>{let s=`${e.connection?.encrypted?"https":"http"}://${e.headers[":authority"]||e.headers.host}`,i=await t(v({base:s,request:e}));j(n,i)}}export{l as APIError,E as createEndpoint,pe as createEndpointCreator,Ee as createMiddleware,ge as createMiddlewareCreator,he as createRouter,D as getBody,v as getRequest,j as setResponse,M as shouldSerialize,B as statusCode,_e as toNodeHandler};
1
+ var Q=Object.defineProperty;var F=(t,e,n)=>e in t?Q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var O=(t,e,n)=>F(t,typeof e!="symbol"?e+"":e,n);import{ZodError as V}from"zod";var m=class extends Error{constructor(n,r){super(`API Error: ${n} ${r?.message??""}`,{cause:r});O(this,"status");O(this,"body");this.status=n,this.body=r??{},this.stack="",this.name="BetterCallAPIError"}};var S=(t,e)=>({response:{body:e?.body??t,status:e?.status??200,statusText:e?.statusText??"OK",headers:e?.headers},body:t,_flag:"json"});var C={name:"HMAC",hash:"SHA-256"},b=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await crypto.subtle.importKey("raw",e,C,!1,["sign","verify"])},W=async(t,e)=>{let n=await b(e),r=await crypto.subtle.sign(C.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(r)))},G=async(t,e,n)=>{try{let r=atob(t),s=new Uint8Array(r.length);for(let i=0,o=r.length;i<o;i++)s[i]=r.charCodeAt(i);return await crypto.subtle.verify(C,n,s,new TextEncoder().encode(e))}catch{return!1}},z=/^[\w!#$%&'*.^`|~+-]+$/,Y=/^[ !#-:<-[\]-~]*$/,P=(t,e)=>t.trim().split(";").reduce((r,s)=>{s=s.trim();let i=s.indexOf("=");if(i===-1)return r;let o=s.substring(0,i).trim();if(e&&e!==o||!z.test(o))return r;let a=s.substring(i+1).trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),Y.test(a)&&(r[o]=decodeURIComponent(a)),r},{}),I=async(t,e,n)=>{let r={},s=await b(e);for(let[i,o]of Object.entries(P(t,n))){let a=o.lastIndexOf(".");if(a<1)continue;let p=o.substring(0,a),d=o.substring(a+1);if(d.length!==44||!d.endsWith("="))continue;let u=await G(d,p,s);r[i]=u?p:!1}return r},k=(t,e,n={})=>{let r=`${t}=${e}`;if(t.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(t.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},g=(t,e,n)=>(e=encodeURIComponent(e),k(t,e,n)),R=async(t,e,n,r={})=>{let s=await W(e,n);return e=`${e}.${s}`,e=encodeURIComponent(e),k(t,e,r)};var H=(t,e,n)=>{if(!t)return;let r=e;if(n)if(n==="secure")r="__Secure-"+e;else if(n==="host")r="__Host-"+e;else return;return P(t,r)[r]},A=(t,e,n,r)=>{let s;r?.prefix==="secure"?s=g("__Secure-"+e,n,{path:"/",...r,secure:!0}):r?.prefix==="host"?s=g("__Host-"+e,n,{...r,path:"/",secure:!0,domain:void 0}):s=g(e,n,{path:"/",...r}),t.append("Set-Cookie",s)},N=async(t,e,n,r,s)=>{let i;s?.prefix==="secure"?i=await R("__Secure-"+e,n,r,{path:"/",...s,secure:!0}):s?.prefix==="host"?i=await R("__Host-"+e,n,r,{...s,path:"/",secure:!0,domain:void 0}):i=await R(e,n,r,{path:"/",...s}),t.append("Set-Cookie",i)},U=async(t,e,n,r)=>{let s=t.get("cookie");if(!s)return;let i=n;return r&&(r==="secure"?i="__Secure-"+n:r==="host"&&(i="__Host-"+n)),(await I(s,e,i))[i]};function pe(t){return(e,n,r)=>x(e,{...n,use:[...n?.use||[],...t?.use||[]]},r)}function x(t,e,n){let r=new Headers,s=async(...i)=>{let o={setHeader(d,u){r.set(d,u)},setCookie(d,u,c){A(r,d,u,c)},getCookie(d,u){let f=i[0]?.headers?.get("cookie");return H(f||"",d,u)},getSignedCookie(d,u,c){let f=i[0]?.headers;if(!f)throw new TypeError("Headers are required");return U(f,u,d,c)},async setSignedCookie(d,u,c,f){await N(r,d,u,c,f)},redirect(d){return r.set("Location",d),new m("FOUND")},json:S,...i[0]||{},context:i[0]?.context||{},_flag:i[0]?._flag,responseHeader:r};if(e.use?.length){let d={},u={};for(let c of e.use){let f=await c(o);if(f){let E=f.options?.body?f.options.body.parse(o.body):void 0;d={...d,...f},u={...u,...E}}}o={...o,body:{...u,...o.body},context:{...o.context||{},...d}}}try{let d=e.body?e.body.parse(o.body):o.body;o={...o,body:d?{...d,...o.body}:o.body},o.query=e.query?e.query.parse(o.query):o.query}catch(d){throw d instanceof V?new m("BAD_REQUEST",{message:d.message,details:d.errors}):d}if(e.requireHeaders&&!o.headers)throw new m("BAD_REQUEST",{message:"Headers are required"});if(e.requireRequest&&!o.request)throw new m("BAD_REQUEST",{message:"Request is required"});let a=await n(o),p=a;if(a&&typeof a=="object"&&"_flag"in a)if(a._flag==="json"&&o._flag==="router"){let d=a.response.headers;Object.keys(d||{}).forEach(u=>{r.set(u,d[u])}),p=new Response(JSON.stringify(a.response.body),{status:a.response.status??200,statusText:a.response.statusText,headers:r})}else p=a.body;return p};return s.path=t,s.options=e,s.method=e.method,s.headers=r,s}import{createRouter as q,addRoute as T,findRoute as L}from"rou3";async function D(t){let e=t.headers.get("content-type")||"";if(t.body){if(e.includes("application/json"))return await t.json();if(e.includes("application/x-www-form-urlencoded")){let n=await t.formData(),r={};return n.forEach((s,i)=>{r[i]=s.toString()}),r}if(e.includes("multipart/form-data")){let n=await t.formData(),r={};return n.forEach((s,i)=>{r[i]=s}),r}return e.includes("text/plain")?await t.text():e.includes("application/octet-stream")?await t.arrayBuffer():e.includes("application/pdf")||e.includes("image/")||e.includes("video/")?await t.blob():e.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function M(t){return typeof t=="object"&&t!==null&&!(t instanceof Blob)&&!(t instanceof FormData)}var B={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};var le=(t,e)=>{let n=Object.values(t),r=q();for(let o of n)if(Array.isArray(o.options?.method))for(let a of o.options.method)T(r,a,o.path,o);else T(r,o.options.method,o.path,o);let s=q();for(let o of e?.routerMiddleware||[])T(s,"*",o.path,o.middleware);let i=async o=>{let a=new URL(o.url),p=a.pathname;e?.basePath&&(p=p.split(e.basePath)[1]);let d=o.method,u=L(r,d,p),c=u?.data,f=await D(o),E=o.headers,w=Object.fromEntries(a.searchParams),_=L(s,"*",p)?.data;if(!c)return new Response(null,{status:404,statusText:"Not Found"});try{let y={};if(_){let h=await _({path:p,method:d,headers:E,params:u?.params,request:o,body:f,query:w,context:{...e?.extraContext}});if(h instanceof Response)return h;if(h?._flag==="json")return new Response(JSON.stringify(h),{headers:h.headers});h&&(y={...h,...y})}let l=await c({path:p,method:d,headers:E,params:u?.params,request:o,body:f,query:w,_flag:"router",context:{...y,...e?.extraContext}});if(l instanceof Response)return l;let K=M(l)?JSON.stringify(l):l;return new Response(K,{headers:c.headers})}catch(y){if(e?.onError){let l=await e.onError(y);if(l instanceof Response)return l}if(y instanceof m)return new Response(y.body?JSON.stringify(y.body):null,{status:B[y.status],statusText:y.status,headers:c.headers});if(e?.throwError)throw y;return new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async o=>{let a=e?.transformRequest?e.transformRequest(o):o,p=await i(a);return e?.transformResponse?e.transformResponse(p):p},endpoints:t}};function xe(t,e){if(typeof t=="function")return x("*",{method:"*"},t);if(!e)throw new Error("Middleware handler is required");return x("*",{...t,method:"*"},e)}var ge=t=>{function e(n,r){if(typeof n=="function")return x("*",{method:"*"},n);if(!r)throw new Error("Middleware handler is required");return x("*",{...n,method:"*"},r)}return e};import"zod";import*as $ from"set-cookie-parser";function Z(t,e){let n=t.headers;if(!n["content-type"])return null;let r=Number(n["content-length"]);if(t.httpVersionMajor===1&&isNaN(r)&&n["transfer-encoding"]==null||r===0)return null;let s=r;if(e){if(!s)s=e;else if(s>e)throw Error(`Received content-length of ${s}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let i=0,o=!1;return new ReadableStream({start(a){t.on("error",p=>{o=!0,a.error(p)}),t.on("end",()=>{o||a.close()}),t.on("data",p=>{if(!o){if(i+=p.length,i>s){o=!0,a.error(new Error(`request body size exceeded ${r?"'content-length'":"BODY_SIZE_LIMIT"} of ${s}`));return}a.enqueue(p),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){o=!0,t.destroy(a)}})}function v({request:t,base:e,bodySizeLimit:n}){return new Request(e+t.url,{duplex:"half",method:t.method,body:Z(t,n),headers:t.headers})}async function j(t,e){for(let[i,o]of e.headers)try{t.setHeader(i,i==="set-cookie"?$.splitCookiesString(e.headers.get(i)):o)}catch(a){t.getHeaderNames().forEach(p=>t.removeHeader(p)),t.writeHead(500).end(String(a));return}if(t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let n=e.body.getReader();if(t.destroyed){n.cancel();return}let r=i=>{t.off("close",r),t.off("error",r),n.cancel(i).catch(()=>{}),i&&t.destroy(i)};t.on("close",r),t.on("error",r),s();async function s(){try{for(;;){let{done:i,value:o}=await n.read();if(i)break;if(!t.write(o)){t.once("drain",s);return}}t.end()}catch(i){r(i instanceof Error?i:new Error(String(i)))}}}function we(t){return async(e,n)=>{let s=`${e.connection?.encrypted?"https":"http"}://${e.headers[":authority"]||e.headers.host}`,i=await t(v({base:s,request:e}));j(n,i)}}export{m as APIError,x as createEndpoint,pe as createEndpointCreator,xe as createMiddleware,ge as createMiddlewareCreator,le as createRouter,D as getBody,v as getRequest,j as setResponse,M as shouldSerialize,B as statusCode,we as toNodeHandler};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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":["import { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\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 } 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\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\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\t...(ctx[0] || {}),\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?._flag as string,\n\t\t\tresponseHeader,\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\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,\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,\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//@ts-expect-error\n\t\tlet res = (await handler(internalCtx)) as any;\n\n\t\tlet actualResponse: any = res;\n\n\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t});\n\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\theaders: responseHeader,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tactualResponse = res.body;\n\t\t\t}\n\t\t}\n\n\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\treturn actualResponse as R extends {\n\t\t\t_flag: \"json\";\n\t\t}\n\t\t\t? R extends { body: infer B }\n\t\t\t\t? B\n\t\t\t\t: null\n\t\t\t: Awaited<ReturnT>;\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\tbody: Record<string, any>;\n\tconstructor(status: Status, body?: Record<string, any>) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\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\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): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.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 crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\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 crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\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\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\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\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\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","//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\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\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 } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, Method } from \"./types\";\n\ninterface 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}\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 (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\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 middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined;\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 (middleware) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\tpath: path,\n\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\trequest: request,\n\t\t\t\t\tbody: body,\n\t\t\t\t\tquery,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (res) {\n\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t...res,\n\t\t\t\t\t\t...middlewareContext,\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: handler.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,\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 { CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\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?: Record<string, any>;\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 interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\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 * internal flags\n\t */\n\t_flag?: string;\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\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> = (\n\tctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & Omit<ContextTools, \"_flag\">>,\n) => 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> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n","import { 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 { 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 = (req.connection 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":"oKAAA,OAAS,YAAAA,MAAgB,MCIlB,IAAMC,EAAN,cAAuB,KAAM,CAGnC,YAAYC,EAAgBC,EAA4B,CACvD,MAAM,cAAcD,CAAM,IAAIC,GAAM,SAAW,EAAE,GAAI,CACpD,MAAOA,CACR,CAAC,EALFC,EAAA,eACAA,EAAA,aAKC,KAAK,OAASF,EACd,KAAK,KAAOC,GAA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AAO,CACfc,EAAOd,aAAiB,MAAQA,EAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC,CAAC,CACjE,CACD,CACD,CC1KO,SAASiB,GAAcC,EAA4B,CACzD,MAAO,OAAOC,EAAsBC,IAAwB,CAE3D,IAAMC,EAAO,GADKF,EAAI,YAAoB,UAAY,QAAU,MACxC,MAAMA,EAAI,QAAQ,YAAY,GAAKA,EAAI,QAAQ,IAAI,GACrEG,EAAW,MAAMJ,EAAQK,EAAW,CAAE,KAAAF,EAAM,QAASF,CAAI,CAAC,CAAC,EACjEK,EAAYJ,EAAKE,CAAQ,CAC1B,CACD","names":["ZodError","APIError","status","body","__publicField","json","body","option","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","len","validCookieNameRegEx","validCookieValueRegEx","parse","cookie","name","parsedCookie","pairStr","valueStartPos","cookieName","cookieValue","parseSigned","secretKey","signatureStartPos","signedValue","isVerified","_serialize","opt","serialize","serializeSigned","getCookie","cookie","key","prefix","finalKey","parse","setCookie","header","name","value","opt","serialize","setSignedCookie","secret","serializeSigned","getSignedCookie","parseSigned","createEndpointCreator","opts","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","setCookie","prefix","cookieH","getCookie","secret","header","getSignedCookie","setSignedCookie","url","APIError","json","middlewareContexts","middlewareBody","middleware","res","body","e","ZodError","actualResponse","h","createRou3Router","addRoute","findRoute","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","_endpoints","router","createRou3Router","endpoint","method","addRoute","middlewareRouter","route","request","url","path","findRoute","handler","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","opts","fn","set_cookie_parser","get_raw_body","req","body_size_limit","h","content_length","length","readable","size","cancelled","controller","error","chunk","reason","getRequest","request","base","bodySizeLimit","setResponse","res","response","key","value","name","reader","cancel","next","done","toNodeHandler","handler","req","res","base","response","getRequest","setResponse"]}
1
+ {"version":3,"sources":["../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":["import { ZodError } from \"zod\";\nimport { APIError } from \"./error\";\nimport { json, type HasRequiredKeys } from \"./helper\";\nimport type {\n\tContext,\n\tContextTools,\n\tCookieOptions,\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 } 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\tconst responseHeader = new Headers();\n\ttype Ctx = Context<Path, Opts>;\n\tconst handle = async (...ctx: HasRequiredKeys<Ctx> extends true ? [Ctx] : [Ctx?]) => {\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\t...(ctx[0] || {}),\n\t\t\tcontext: (ctx[0] as any)?.context || {},\n\t\t\t_flag: (ctx[0] as any)?._flag as string,\n\t\t\tresponseHeader,\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\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,\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,\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//@ts-expect-error\n\t\tlet res = (await handler(internalCtx)) as any;\n\n\t\tlet actualResponse: any = res;\n\n\t\tif (res && typeof res === \"object\" && \"_flag\" in res) {\n\t\t\tif (res._flag === \"json\" && internalCtx._flag === \"router\") {\n\t\t\t\tconst h = res.response.headers as Record<string, string>;\n\t\t\t\tObject.keys(h || {}).forEach((key) => {\n\t\t\t\t\tresponseHeader.set(key, h[key as keyof typeof h]);\n\t\t\t\t});\n\t\t\t\tactualResponse = new Response(JSON.stringify(res.response.body), {\n\t\t\t\t\tstatus: res.response.status ?? 200,\n\t\t\t\t\tstatusText: res.response.statusText,\n\t\t\t\t\theaders: responseHeader,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tactualResponse = res.body;\n\t\t\t}\n\t\t}\n\n\t\ttype ReturnT = Awaited<ReturnType<Handler<Path, Opts, R>>>;\n\t\treturn actualResponse as R extends {\n\t\t\t_flag: \"json\";\n\t\t}\n\t\t\t? R extends { body: infer B }\n\t\t\t\t? B\n\t\t\t\t: null\n\t\t\t: Awaited<ReturnT>;\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\tbody: Record<string, any>;\n\tconstructor(status: Status, body?: Record<string, any>) {\n\t\tsuper(`API Error: ${status} ${body?.message ?? \"\"}`, {\n\t\t\tcause: body,\n\t\t});\n\t\tthis.status = status;\n\t\tthis.body = body ?? {};\n\t\tthis.stack = \"\";\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\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): Promise<CryptoKey> => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await crypto.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 crypto.subtle.sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\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 crypto.subtle.verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\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\t// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13#section-4.1.3.1\n\t\tthrow new Error(\"__Secure- Cookie must have Secure attributes\");\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\tthrow new Error(\"__Host- Cookie must have Secure attributes\");\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\tthrow new Error('__Host- Cookie must have Path attributes with \"/\"');\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\tthrow new Error(\"__Host- Cookie must not have Domain attributes\");\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","//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\t// Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.\n\t// Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)\n\t// and must not have a Domain attribute.\n\t// Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'\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 } from \"rou3\";\nimport { getBody, shouldSerialize, statusCode } from \"./utils\";\nimport { APIError } from \"./error\";\nimport type { Middleware, MiddlewareHandler } from \"./middleware\";\nimport type { Endpoint, EndpointResponse, Method } from \"./types\";\n\ninterface 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\ttransformResponse?: (res: Response) => Response;\n\ttransformRequest?: (req: Request) => Request;\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 (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\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 middleware = findRoute(middlewareRouter, \"*\", path)?.data as Endpoint | undefined;\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 (middleware) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\tpath: path,\n\t\t\t\t\tmethod: method as \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t\tparams: route?.params as any,\n\t\t\t\t\trequest: request,\n\t\t\t\t\tbody: body,\n\t\t\t\t\tquery,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...config?.extraContext,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (res instanceof Response) {\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t\tif (res?._flag === \"json\") {\n\t\t\t\t\treturn new Response(JSON.stringify(res), {\n\t\t\t\t\t\theaders: res.headers,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (res) {\n\t\t\t\t\tmiddlewareContext = {\n\t\t\t\t\t\t...res,\n\t\t\t\t\t\t...middlewareContext,\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: handler.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 req = config?.transformRequest ? config.transformRequest(request) : request;\n\t\t\tconst res = await handler(req);\n\t\t\tif (config?.transformResponse) {\n\t\t\t\treturn config.transformResponse(res);\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 { CookiePrefixOptions } from \"./cookie\";\nimport type { APIError } from \"./error\";\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?: Record<string, any>;\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 interface CookieOptions {\n\t/**\n\t * Max age in seconds\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Domain\n\t */\n\tdomain?: string;\n\t/**\n\t * Path\n\t */\n\tpath?: string;\n\t/**\n\t * Secure\n\t */\n\tsecure?: boolean;\n\t/**\n\t * HttpOnly\n\t */\n\thttpOnly?: boolean;\n\n\t/**\n\t * SameSite\n\t */\n\tsameSite?: \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Expires\n\t */\n\texpires?: Date;\n}\n\nexport type ContextTools = {\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 * internal flags\n\t */\n\t_flag?: string;\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\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> = (\n\tctx: Prettify<Context<Path, Opts> & InferUse<Opts[\"use\"]> & Omit<ContextTools, \"_flag\">>,\n) => 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> = Body extends ZodSchema\n\t? Body extends ZodOptional<any>\n\t\t? {\n\t\t\t\tbody?: Prettify<z.infer<Body>>;\n\t\t\t}\n\t\t: {\n\t\t\t\tbody: Prettify<z.infer<Body>>;\n\t\t\t}\n\t: {\n\t\t\tbody?: undefined;\n\t\t};\n","import { 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 { 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 = (req.connection 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":"oKAAA,OAAS,YAAAA,MAAgB,MCIlB,IAAMC,EAAN,cAAuB,KAAM,CAGnC,YAAYC,EAAgBC,EAA4B,CACvD,MAAM,cAAcD,CAAM,IAAIC,GAAM,SAAW,EAAE,GAAI,CACpD,MAAOA,CACR,CAAC,EALFC,EAAA,eACAA,EAAA,aAKC,KAAK,OAASF,EACd,KAAK,KAAOC,GAAQ,CAAC,EACrB,KAAK,MAAQ,GACb,KAAK,KAAO,oBACb,CACD,ECOO,IAAME,EAAO,CACnBC,EACAC,KAWO,CACN,SAAU,CACT,KAAMA,GAAQ,MAAQD,EACtB,OAAQC,GAAQ,QAAU,IAC1B,WAAYA,GAAQ,YAAc,KAClC,QAASA,GAAQ,OAClB,EACA,KAAAD,EACA,MAAO,MACR,GCdD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AM,OAAOA,CAAK,CAAC,CAAC,CACjE,CACD,CACD,CC1KO,SAASiB,GAAcC,EAA4B,CACzD,MAAO,OAAOC,EAAsBC,IAAwB,CAE3D,IAAMC,EAAO,GADKF,EAAI,YAAoB,UAAY,QAAU,MACxC,MAAMA,EAAI,QAAQ,YAAY,GAAKA,EAAI,QAAQ,IAAI,GACrEG,EAAW,MAAMJ,EAAQK,EAAW,CAAE,KAAAF,EAAM,QAASF,CAAI,CAAC,CAAC,EACjEK,EAAYJ,EAAKE,CAAQ,CAC1B,CACD","names":["ZodError","APIError","status","body","__publicField","json","body","option","algorithm","getCryptoKey","secret","secretBuf","makeSignature","value","key","signature","verifySignature","base64Signature","signatureBinStr","len","validCookieNameRegEx","validCookieValueRegEx","parse","cookie","name","parsedCookie","pairStr","valueStartPos","cookieName","cookieValue","parseSigned","secretKey","signatureStartPos","signedValue","isVerified","_serialize","opt","serialize","serializeSigned","getCookie","cookie","key","prefix","finalKey","parse","setCookie","header","name","value","opt","serialize","setSignedCookie","secret","serializeSigned","getSignedCookie","parseSigned","createEndpointCreator","opts","path","options","handler","createEndpoint","responseHeader","handle","ctx","internalCtx","key","value","setCookie","prefix","cookieH","getCookie","secret","header","getSignedCookie","setSignedCookie","url","APIError","json","middlewareContexts","middlewareBody","middleware","res","body","e","ZodError","actualResponse","h","createRou3Router","addRoute","findRoute","getBody","request","contentType","formData","result","value","key","shouldSerialize","body","statusCode","createRouter","endpoints","config","_endpoints","router","createRou3Router","endpoint","method","addRoute","middlewareRouter","route","handler","request","url","path","findRoute","body","getBody","headers","query","middleware","middlewareContext","res","handlerRes","resBody","shouldSerialize","e","onErrorRes","APIError","statusCode","req","createMiddleware","optionsOrHandler","handler","createEndpoint","createMiddlewareCreator","opts","fn","set_cookie_parser","get_raw_body","req","body_size_limit","h","content_length","length","readable","size","cancelled","controller","error","chunk","reason","getRequest","request","base","bodySizeLimit","setResponse","res","response","key","value","name","reader","cancel","next","done","toNodeHandler","handler","req","res","base","response","getRequest","setResponse"]}
@@ -303,6 +303,8 @@ interface RouterConfig {
303
303
  middleware: Endpoint;
304
304
  }[];
305
305
  extraContext?: Record<string, any>;
306
+ transformResponse?: (res: Response) => Response;
307
+ transformRequest?: (req: Request) => Request;
306
308
  }
307
309
  declare const createRouter: <E extends Record<string, Endpoint>, Config extends RouterConfig>(endpoints: E, config?: Config) => {
308
310
  handler: (request: Request) => Promise<Response>;
@@ -303,6 +303,8 @@ interface RouterConfig {
303
303
  middleware: Endpoint;
304
304
  }[];
305
305
  extraContext?: Record<string, any>;
306
+ transformResponse?: (res: Response) => Response;
307
+ transformRequest?: (req: Request) => Request;
306
308
  }
307
309
  declare const createRouter: <E extends Record<string, Endpoint>, Config extends RouterConfig>(endpoints: E, config?: Config) => {
308
310
  handler: (request: Request) => Promise<Response>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-call",
3
- "version": "0.1.29",
3
+ "version": "0.1.32",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",