better-call 1.1.5 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +35 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  3. package/dist/adapters/node/request.cjs +125 -0
  4. package/dist/adapters/node/request.cjs.map +1 -0
  5. package/dist/{node.d.ts → adapters/node/request.d.cts} +2 -6
  6. package/dist/adapters/node/request.d.mts +16 -0
  7. package/dist/{node.js → adapters/node/request.mjs} +2 -13
  8. package/dist/adapters/node/request.mjs.map +1 -0
  9. package/dist/client.cjs +8 -1
  10. package/dist/client.cjs.map +1 -1
  11. package/dist/client.d.cts +12 -13
  12. package/dist/client.d.mts +53 -0
  13. package/dist/client.mjs +14 -0
  14. package/dist/client.mjs.map +1 -0
  15. package/dist/context.cjs +102 -0
  16. package/dist/context.cjs.map +1 -0
  17. package/dist/context.d.cts +340 -0
  18. package/dist/context.d.mts +340 -0
  19. package/dist/context.mjs +102 -0
  20. package/dist/context.mjs.map +1 -0
  21. package/dist/cookies.cjs +87 -0
  22. package/dist/cookies.cjs.map +1 -0
  23. package/dist/cookies.d.cts +103 -0
  24. package/dist/cookies.d.mts +103 -0
  25. package/dist/cookies.mjs +84 -0
  26. package/dist/cookies.mjs.map +1 -0
  27. package/dist/crypto.cjs +39 -0
  28. package/dist/crypto.cjs.map +1 -0
  29. package/dist/crypto.mjs +36 -0
  30. package/dist/crypto.mjs.map +1 -0
  31. package/dist/endpoint.cjs +70 -0
  32. package/dist/endpoint.cjs.map +1 -0
  33. package/dist/endpoint.d.cts +428 -0
  34. package/dist/endpoint.d.mts +428 -0
  35. package/dist/endpoint.mjs +70 -0
  36. package/dist/endpoint.mjs.map +1 -0
  37. package/dist/error.cjs +141 -0
  38. package/dist/error.cjs.map +1 -0
  39. package/dist/error.d.cts +103 -0
  40. package/dist/error.d.mts +103 -0
  41. package/dist/error.mjs +135 -0
  42. package/dist/error.mjs.map +1 -0
  43. package/dist/helper.d.cts +12 -0
  44. package/dist/helper.d.mts +12 -0
  45. package/dist/index.cjs +26 -968
  46. package/dist/index.d.cts +11 -14
  47. package/dist/index.d.mts +11 -0
  48. package/dist/index.mjs +10 -0
  49. package/dist/middleware.cjs +39 -0
  50. package/dist/middleware.cjs.map +1 -0
  51. package/dist/middleware.d.cts +123 -0
  52. package/dist/middleware.d.mts +123 -0
  53. package/dist/middleware.mjs +39 -0
  54. package/dist/middleware.mjs.map +1 -0
  55. package/dist/node.cjs +4 -151
  56. package/dist/node.cjs.map +1 -1
  57. package/dist/node.d.cts +2 -13
  58. package/dist/node.d.mts +9 -0
  59. package/dist/node.mjs +15 -0
  60. package/dist/node.mjs.map +1 -0
  61. package/dist/openapi.cjs +191 -0
  62. package/dist/openapi.cjs.map +1 -0
  63. package/dist/openapi.d.cts +113 -0
  64. package/dist/openapi.d.mts +113 -0
  65. package/dist/openapi.mjs +189 -0
  66. package/dist/openapi.mjs.map +1 -0
  67. package/dist/router.cjs +117 -0
  68. package/dist/router.cjs.map +1 -0
  69. package/dist/router.d.cts +4 -1242
  70. package/dist/router.d.mts +97 -0
  71. package/dist/router.mjs +116 -0
  72. package/dist/router.mjs.map +1 -0
  73. package/dist/standard-schema.d.cts +59 -0
  74. package/dist/standard-schema.d.mts +59 -0
  75. package/dist/to-response.cjs +96 -0
  76. package/dist/to-response.cjs.map +1 -0
  77. package/dist/to-response.d.cts +12 -0
  78. package/dist/to-response.d.mts +12 -0
  79. package/dist/to-response.mjs +96 -0
  80. package/dist/to-response.mjs.map +1 -0
  81. package/dist/utils.cjs +77 -0
  82. package/dist/utils.cjs.map +1 -0
  83. package/dist/utils.mjs +74 -0
  84. package/dist/utils.mjs.map +1 -0
  85. package/dist/validator.cjs +58 -0
  86. package/dist/validator.cjs.map +1 -0
  87. package/dist/validator.mjs +57 -0
  88. package/dist/validator.mjs.map +1 -0
  89. package/package.json +23 -13
  90. package/dist/client.d.ts +0 -54
  91. package/dist/client.js +0 -13
  92. package/dist/client.js.map +0 -1
  93. package/dist/index.cjs.map +0 -1
  94. package/dist/index.d.ts +0 -14
  95. package/dist/index.js +0 -951
  96. package/dist/index.js.map +0 -1
  97. package/dist/node.js.map +0 -1
  98. package/dist/router.d.ts +0 -1335
package/dist/index.d.cts CHANGED
@@ -1,14 +1,11 @@
1
- import { $ as statusCodes, A as InferMiddlewareQuery, B as createInternalContext, C as InferBody, D as InferInputMethod, E as InferHeadersInput, F as InferRequest, G as serializeCookie, H as CookiePrefixOptions, I as InferRequestInput, J as BetterCallError, K as serializeSignedCookie, L as InferUse, M as InferParamInput, N as InferQuery, O as InferMethod, P as InferQueryInput, Q as makeErrorForHideStackFrame, R as InputContext, S as HTTPMethod, T as InferHeaders, U as getCookieKey, V as CookieOptions, W as parseCookies, X as ValidationError, Y as Status, Z as hideInternalStackFrames, _ as MiddlewareContext, a as EndpointBaseOptions, at as MergeObject, b as MiddlewareResponse, c as EndpointOptions, ct as UnionToIntersection, d as OpenAPIParameter, et as StandardSchemaV1, f as OpenAPISchemaType, g as Middleware, h as getHTML, i as Endpoint, it as IsEmptyObject, j as InferParam, k as InferMiddlewareBody, l as StrictEndpoint, m as generator, n as RouterConfig, nt as InferParamPath, o as EndpointBodyMethodOptions, ot as Prettify, p as Path, q as APIError, r as createRouter, rt as InferParamWildCard, s as EndpointContext, st as RequiredKeysOf, t as Router, tt as HasRequiredKeys, u as createEndpoint, v as MiddlewareInputContext, w as InferBodyInput, x as createMiddleware, y as MiddlewareOptions, z as Method } from "./router.cjs";
2
-
3
- //#region src/to-response.d.ts
4
- type JSONResponse = {
5
- body: Record<string, any>;
6
- routerResponse: ResponseInit | undefined;
7
- status?: number;
8
- headers?: Record<string, string> | Headers;
9
- _flag: "json";
10
- };
11
- declare function toResponse(data?: any, init?: ResponseInit): Response;
12
- //#endregion
13
- export { APIError, BetterCallError, CookieOptions, CookiePrefixOptions, Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, HTTPMethod, HasRequiredKeys, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferParamPath, InferParamWildCard, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, IsEmptyObject, JSONResponse, MergeObject, Method, Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, OpenAPIParameter, OpenAPISchemaType, Path, Prettify, RequiredKeysOf, Router, RouterConfig, StandardSchemaV1, Status, StrictEndpoint, UnionToIntersection, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
14
- //# sourceMappingURL=index.d.cts.map
1
+ import { HasRequiredKeys, InferParamPath, InferParamWildCard, IsEmptyObject, MergeObject, Prettify, RequiredKeysOf, UnionToIntersection } from "./helper.cjs";
2
+ import { StandardSchemaV1 } from "./standard-schema.cjs";
3
+ import { APIError, BetterCallError, Status, ValidationError, hideInternalStackFrames, makeErrorForHideStackFrame, statusCodes } from "./error.cjs";
4
+ import { CookieOptions, CookiePrefixOptions, getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.cjs";
5
+ import { HTTPMethod, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, Method, createInternalContext } from "./context.cjs";
6
+ import { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware } from "./middleware.cjs";
7
+ import { OpenAPIParameter, OpenAPISchemaType, Path, generator, getHTML } from "./openapi.cjs";
8
+ import { Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, StrictEndpoint, createEndpoint } from "./endpoint.cjs";
9
+ import { Router, RouterConfig, createRouter } from "./router.cjs";
10
+ import { JSONResponse, toResponse } from "./to-response.cjs";
11
+ export { APIError, BetterCallError, CookieOptions, CookiePrefixOptions, Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, HTTPMethod, HasRequiredKeys, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferParamPath, InferParamWildCard, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, IsEmptyObject, JSONResponse, MergeObject, Method, Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, OpenAPIParameter, OpenAPISchemaType, Path, Prettify, RequiredKeysOf, Router, RouterConfig, StandardSchemaV1, Status, StrictEndpoint, UnionToIntersection, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
@@ -0,0 +1,11 @@
1
+ import { HasRequiredKeys, InferParamPath, InferParamWildCard, IsEmptyObject, MergeObject, Prettify, RequiredKeysOf, UnionToIntersection } from "./helper.mjs";
2
+ import { StandardSchemaV1 } from "./standard-schema.mjs";
3
+ import { APIError, BetterCallError, Status, ValidationError, hideInternalStackFrames, makeErrorForHideStackFrame, statusCodes } from "./error.mjs";
4
+ import { CookieOptions, CookiePrefixOptions, getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.mjs";
5
+ import { HTTPMethod, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, Method, createInternalContext } from "./context.mjs";
6
+ import { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware } from "./middleware.mjs";
7
+ import { OpenAPIParameter, OpenAPISchemaType, Path, generator, getHTML } from "./openapi.mjs";
8
+ import { Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, StrictEndpoint, createEndpoint } from "./endpoint.mjs";
9
+ import { Router, RouterConfig, createRouter } from "./router.mjs";
10
+ import { JSONResponse, toResponse } from "./to-response.mjs";
11
+ export { APIError, BetterCallError, CookieOptions, CookiePrefixOptions, Endpoint, EndpointBaseOptions, EndpointBodyMethodOptions, EndpointContext, EndpointOptions, HTTPMethod, HasRequiredKeys, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferParamPath, InferParamWildCard, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, IsEmptyObject, JSONResponse, MergeObject, Method, Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, OpenAPIParameter, OpenAPISchemaType, Path, Prettify, RequiredKeysOf, Router, RouterConfig, StandardSchemaV1, Status, StrictEndpoint, UnionToIntersection, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
package/dist/index.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import { APIError, BetterCallError, ValidationError, hideInternalStackFrames, makeErrorForHideStackFrame, statusCodes } from "./error.mjs";
2
+ import { toResponse } from "./to-response.mjs";
3
+ import { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.mjs";
4
+ import { createInternalContext } from "./context.mjs";
5
+ import { createEndpoint } from "./endpoint.mjs";
6
+ import { createMiddleware } from "./middleware.mjs";
7
+ import { generator, getHTML } from "./openapi.mjs";
8
+ import { createRouter } from "./router.mjs";
9
+
10
+ export { APIError, BetterCallError, ValidationError, createEndpoint, createInternalContext, createMiddleware, createRouter, generator, getCookieKey, getHTML, hideInternalStackFrames, makeErrorForHideStackFrame, parseCookies, serializeCookie, serializeSignedCookie, statusCodes, toResponse };
@@ -0,0 +1,39 @@
1
+ const require_context = require('./context.cjs');
2
+ require('./endpoint.cjs');
3
+
4
+ //#region src/middleware.ts
5
+ function createMiddleware(optionsOrHandler, handler) {
6
+ const internalHandler = async (inputCtx) => {
7
+ const context = inputCtx;
8
+ const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler;
9
+ const internalContext = await require_context.createInternalContext(context, {
10
+ options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler,
11
+ path: "/"
12
+ });
13
+ if (!_handler) throw new Error("handler must be defined");
14
+ const response = await _handler(internalContext);
15
+ const headers = internalContext.responseHeaders;
16
+ return context.returnHeaders ? {
17
+ headers,
18
+ response
19
+ } : response;
20
+ };
21
+ internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler;
22
+ return internalHandler;
23
+ }
24
+ createMiddleware.create = (opts) => {
25
+ function fn(optionsOrHandler, handler) {
26
+ if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler);
27
+ if (!handler) throw new Error("Middleware handler is required");
28
+ return createMiddleware({
29
+ ...optionsOrHandler,
30
+ method: "*",
31
+ use: [...opts?.use || [], ...optionsOrHandler.use || []]
32
+ }, handler);
33
+ }
34
+ return fn;
35
+ };
36
+
37
+ //#endregion
38
+ exports.createMiddleware = createMiddleware;
39
+ //# sourceMappingURL=middleware.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.cjs","names":["createInternalContext"],"sources":["../src/middleware.ts"],"sourcesContent":["import {\n\tcreateEndpoint,\n\ttype Endpoint,\n\ttype EndpointContext,\n\ttype EndpointOptions,\n} from \"./endpoint\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferBodyInput,\n\ttype InferHeaders,\n\ttype InferHeadersInput,\n\ttype InferMiddlewareBody,\n\ttype InferMiddlewareQuery,\n\ttype InferQuery,\n\ttype InferQueryInput,\n\ttype InferRequest,\n\ttype InferRequestInput,\n\ttype InferUse,\n\ttype InputContext,\n} from \"./context\";\nimport type { Prettify } from \"./helper\";\n\nexport interface MiddlewareOptions extends Omit<EndpointOptions, \"method\"> {}\n\nexport type MiddlewareResponse = null | void | undefined | Record<string, any>;\n\nexport type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<\n\tstring,\n\tOptions & {\n\t\tmethod: \"*\";\n\t}\n> & {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: string;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: string;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists\n\t */\n\tbody: InferMiddlewareBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferMiddlewareQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the\n\t * params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*`\n\t * then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the\n\t * wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: string;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context>;\n};\n\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\toptions: Options,\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tconst internalHandler = async (inputCtx: InputContext<any, any>) => {\n\t\tconst context = inputCtx as InputContext<any, any>;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath: \"/\",\n\t\t});\n\n\t\tif (!_handler) {\n\t\t\tthrow new Error(\"handler must be defined\");\n\t\t}\n\t\tconst response = await _handler(internalContext as any);\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn context.returnHeaders\n\t\t\t? {\n\t\t\t\t\theaders,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t: response;\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\n\nexport type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> &\n\tInferQueryInput<Options> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\tuse?: Middleware[];\n\t};\n\nexport type Middleware<\n\tOptions extends MiddlewareOptions = MiddlewareOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = any,\n> = Handler & {\n\toptions: Options;\n};\n\ncreateMiddleware.create = <\n\tE extends {\n\t\tuse?: Middleware[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype InferredContext = InferUse<E[\"use\"]>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\toptions: Options,\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createMiddleware(\n\t\t\t\t{\n\t\t\t\t\tuse: opts?.use,\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst middleware = createMiddleware(\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t\tuse: [...(opts?.use || []), ...(optionsOrHandler.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn middleware as any;\n\t}\n\treturn fn;\n};\n"],"mappings":";;;;AA0IA,SAAgB,iBAAiB,kBAAuB,SAAe;CACtE,MAAM,kBAAkB,OAAO,aAAqC;EACnE,MAAM,UAAU;EAChB,MAAM,WAAW,OAAO,qBAAqB,aAAa,mBAAmB;EAE7E,MAAM,kBAAkB,MAAMA,sCAAsB,SAAS;GAC5D,SAFe,OAAO,qBAAqB,aAAa,EAAE,GAAG;GAG7D,MAAM;GACN,CAAC;AAEF,MAAI,CAAC,SACJ,OAAM,IAAI,MAAM,0BAA0B;EAE3C,MAAM,WAAW,MAAM,SAAS,gBAAuB;EACvD,MAAM,UAAU,gBAAgB;AAChC,SAAO,QAAQ,gBACZ;GACA;GACA;GACA,GACA;;AAEJ,iBAAgB,UAAU,OAAO,qBAAqB,aAAa,EAAE,GAAG;AACxE,QAAO;;AAmBR,iBAAiB,UAKhB,SACI;CASJ,SAAS,GAAG,kBAAuB,SAAe;AACjD,MAAI,OAAO,qBAAqB,WAC/B,QAAO,iBACN,EACC,KAAK,MAAM,KACX,EACD,iBACA;AAEF,MAAI,CAAC,QACJ,OAAM,IAAI,MAAM,iCAAiC;AAUlD,SARmB,iBAClB;GACC,GAAG;GACH,QAAQ;GACR,KAAK,CAAC,GAAI,MAAM,OAAO,EAAE,EAAG,GAAI,iBAAiB,OAAO,EAAE,CAAE;GAC5D,EACD,QACA;;AAGF,QAAO"}
@@ -0,0 +1,123 @@
1
+ import { Prettify } from "./helper.cjs";
2
+ import { InferBodyInput, InferHeaders, InferHeadersInput, InferMiddlewareBody, InferMiddlewareQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse } from "./context.cjs";
3
+ import { EndpointContext, EndpointOptions } from "./endpoint.cjs";
4
+
5
+ //#region src/middleware.d.ts
6
+ interface MiddlewareOptions extends Omit<EndpointOptions, "method"> {}
7
+ type MiddlewareResponse = null | void | undefined | Record<string, any>;
8
+ type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<string, Options & {
9
+ method: "*";
10
+ }> & {
11
+ /**
12
+ * Method
13
+ *
14
+ * The request method
15
+ */
16
+ method: string;
17
+ /**
18
+ * Path
19
+ *
20
+ * The path of the endpoint
21
+ */
22
+ path: string;
23
+ /**
24
+ * Body
25
+ *
26
+ * The body object will be the parsed JSON from the request and validated
27
+ * against the body schema if it exists
28
+ */
29
+ body: InferMiddlewareBody<Options>;
30
+ /**
31
+ * Query
32
+ *
33
+ * The query object will be the parsed query string from the request
34
+ * and validated against the query schema if it exists
35
+ */
36
+ query: InferMiddlewareQuery<Options>;
37
+ /**
38
+ * Params
39
+ *
40
+ * If the path is `/user/:id` and the request is `/user/1` then the
41
+ * params will
42
+ * be `{ id: "1" }` and if the path includes a wildcard like `/user/*`
43
+ * then the
44
+ * params will be `{ _: "1" }` where `_` is the wildcard key. If the
45
+ * wildcard
46
+ * is named like `/user/**:name` then the params will be `{ name: string }`
47
+ */
48
+ params: string;
49
+ /**
50
+ * Request object
51
+ *
52
+ * If `requireRequest` is set to true in the endpoint options this will be
53
+ * required
54
+ */
55
+ request: InferRequest<Options>;
56
+ /**
57
+ * Headers
58
+ *
59
+ * If `requireHeaders` is set to true in the endpoint options this will be
60
+ * required
61
+ */
62
+ headers: InferHeaders<Options>;
63
+ /**
64
+ * Set header
65
+ *
66
+ * If it's called outside of a request it will just be ignored.
67
+ */
68
+ setHeader: (key: string, value: string) => void;
69
+ /**
70
+ * Get header
71
+ *
72
+ * If it's called outside of a request it will just return null
73
+ *
74
+ * @param key - The key of the header
75
+ * @returns
76
+ */
77
+ getHeader: (key: string) => string | null;
78
+ /**
79
+ * JSON
80
+ *
81
+ * a helper function to create a JSON response with
82
+ * the correct headers
83
+ * and status code. If `asResponse` is set to true in
84
+ * the context then
85
+ * it will return a Response object instead of the
86
+ * JSON object.
87
+ *
88
+ * @param json - The JSON object to return
89
+ * @param routerResponse - The response object to
90
+ * return if `asResponse` is
91
+ * true in the context this will take precedence
92
+ */
93
+ json: <R extends Record<string, any> | null>(json: R, routerResponse?: {
94
+ status?: number;
95
+ headers?: Record<string, string>;
96
+ response?: Response;
97
+ } | Response) => Promise<R>;
98
+ /**
99
+ * Middleware context
100
+ */
101
+ context: Prettify<Context>;
102
+ };
103
+ declare function createMiddleware<Options extends MiddlewareOptions, R>(options: Options, handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
104
+ declare function createMiddleware<Options extends MiddlewareOptions, R>(handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
105
+ declare namespace createMiddleware {
106
+ var create: <E extends {
107
+ use?: Middleware[];
108
+ }>(opts?: E) => {
109
+ <Options extends MiddlewareOptions, R>(options: Options, handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R>): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;
110
+ <Options extends MiddlewareOptions, R_1>(handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R_1>): (inputContext: MiddlewareInputContext<Options>) => Promise<R_1>;
111
+ };
112
+ }
113
+ type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> & InferQueryInput<Options> & InferRequestInput<Options> & InferHeadersInput<Options> & {
114
+ asResponse?: boolean;
115
+ returnHeaders?: boolean;
116
+ use?: Middleware[];
117
+ };
118
+ type Middleware<Options extends MiddlewareOptions = MiddlewareOptions, Handler extends (inputCtx: any) => Promise<any> = any> = Handler & {
119
+ options: Options;
120
+ };
121
+ //#endregion
122
+ export { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware };
123
+ //# sourceMappingURL=middleware.d.cts.map
@@ -0,0 +1,123 @@
1
+ import { Prettify } from "./helper.mjs";
2
+ import { InferBodyInput, InferHeaders, InferHeadersInput, InferMiddlewareBody, InferMiddlewareQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse } from "./context.mjs";
3
+ import { EndpointContext, EndpointOptions } from "./endpoint.mjs";
4
+
5
+ //#region src/middleware.d.ts
6
+ interface MiddlewareOptions extends Omit<EndpointOptions, "method"> {}
7
+ type MiddlewareResponse = null | void | undefined | Record<string, any>;
8
+ type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<string, Options & {
9
+ method: "*";
10
+ }> & {
11
+ /**
12
+ * Method
13
+ *
14
+ * The request method
15
+ */
16
+ method: string;
17
+ /**
18
+ * Path
19
+ *
20
+ * The path of the endpoint
21
+ */
22
+ path: string;
23
+ /**
24
+ * Body
25
+ *
26
+ * The body object will be the parsed JSON from the request and validated
27
+ * against the body schema if it exists
28
+ */
29
+ body: InferMiddlewareBody<Options>;
30
+ /**
31
+ * Query
32
+ *
33
+ * The query object will be the parsed query string from the request
34
+ * and validated against the query schema if it exists
35
+ */
36
+ query: InferMiddlewareQuery<Options>;
37
+ /**
38
+ * Params
39
+ *
40
+ * If the path is `/user/:id` and the request is `/user/1` then the
41
+ * params will
42
+ * be `{ id: "1" }` and if the path includes a wildcard like `/user/*`
43
+ * then the
44
+ * params will be `{ _: "1" }` where `_` is the wildcard key. If the
45
+ * wildcard
46
+ * is named like `/user/**:name` then the params will be `{ name: string }`
47
+ */
48
+ params: string;
49
+ /**
50
+ * Request object
51
+ *
52
+ * If `requireRequest` is set to true in the endpoint options this will be
53
+ * required
54
+ */
55
+ request: InferRequest<Options>;
56
+ /**
57
+ * Headers
58
+ *
59
+ * If `requireHeaders` is set to true in the endpoint options this will be
60
+ * required
61
+ */
62
+ headers: InferHeaders<Options>;
63
+ /**
64
+ * Set header
65
+ *
66
+ * If it's called outside of a request it will just be ignored.
67
+ */
68
+ setHeader: (key: string, value: string) => void;
69
+ /**
70
+ * Get header
71
+ *
72
+ * If it's called outside of a request it will just return null
73
+ *
74
+ * @param key - The key of the header
75
+ * @returns
76
+ */
77
+ getHeader: (key: string) => string | null;
78
+ /**
79
+ * JSON
80
+ *
81
+ * a helper function to create a JSON response with
82
+ * the correct headers
83
+ * and status code. If `asResponse` is set to true in
84
+ * the context then
85
+ * it will return a Response object instead of the
86
+ * JSON object.
87
+ *
88
+ * @param json - The JSON object to return
89
+ * @param routerResponse - The response object to
90
+ * return if `asResponse` is
91
+ * true in the context this will take precedence
92
+ */
93
+ json: <R extends Record<string, any> | null>(json: R, routerResponse?: {
94
+ status?: number;
95
+ headers?: Record<string, string>;
96
+ response?: Response;
97
+ } | Response) => Promise<R>;
98
+ /**
99
+ * Middleware context
100
+ */
101
+ context: Prettify<Context>;
102
+ };
103
+ declare function createMiddleware<Options extends MiddlewareOptions, R>(options: Options, handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
104
+ declare function createMiddleware<Options extends MiddlewareOptions, R>(handler: (context: MiddlewareContext<Options>) => Promise<R>): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;
105
+ declare namespace createMiddleware {
106
+ var create: <E extends {
107
+ use?: Middleware[];
108
+ }>(opts?: E) => {
109
+ <Options extends MiddlewareOptions, R>(options: Options, handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R>): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;
110
+ <Options extends MiddlewareOptions, R_1>(handler: (ctx: MiddlewareContext<Options, InferUse<E["use"]>>) => Promise<R_1>): (inputContext: MiddlewareInputContext<Options>) => Promise<R_1>;
111
+ };
112
+ }
113
+ type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> & InferQueryInput<Options> & InferRequestInput<Options> & InferHeadersInput<Options> & {
114
+ asResponse?: boolean;
115
+ returnHeaders?: boolean;
116
+ use?: Middleware[];
117
+ };
118
+ type Middleware<Options extends MiddlewareOptions = MiddlewareOptions, Handler extends (inputCtx: any) => Promise<any> = any> = Handler & {
119
+ options: Options;
120
+ };
121
+ //#endregion
122
+ export { Middleware, MiddlewareContext, MiddlewareInputContext, MiddlewareOptions, MiddlewareResponse, createMiddleware };
123
+ //# sourceMappingURL=middleware.d.mts.map
@@ -0,0 +1,39 @@
1
+ import { createInternalContext } from "./context.mjs";
2
+ import "./endpoint.mjs";
3
+
4
+ //#region src/middleware.ts
5
+ function createMiddleware(optionsOrHandler, handler) {
6
+ const internalHandler = async (inputCtx) => {
7
+ const context = inputCtx;
8
+ const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler;
9
+ const internalContext = await createInternalContext(context, {
10
+ options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler,
11
+ path: "/"
12
+ });
13
+ if (!_handler) throw new Error("handler must be defined");
14
+ const response = await _handler(internalContext);
15
+ const headers = internalContext.responseHeaders;
16
+ return context.returnHeaders ? {
17
+ headers,
18
+ response
19
+ } : response;
20
+ };
21
+ internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler;
22
+ return internalHandler;
23
+ }
24
+ createMiddleware.create = (opts) => {
25
+ function fn(optionsOrHandler, handler) {
26
+ if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler);
27
+ if (!handler) throw new Error("Middleware handler is required");
28
+ return createMiddleware({
29
+ ...optionsOrHandler,
30
+ method: "*",
31
+ use: [...opts?.use || [], ...optionsOrHandler.use || []]
32
+ }, handler);
33
+ }
34
+ return fn;
35
+ };
36
+
37
+ //#endregion
38
+ export { createMiddleware };
39
+ //# sourceMappingURL=middleware.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["import {\n\tcreateEndpoint,\n\ttype Endpoint,\n\ttype EndpointContext,\n\ttype EndpointOptions,\n} from \"./endpoint\";\nimport {\n\tcreateInternalContext,\n\ttype InferBody,\n\ttype InferBodyInput,\n\ttype InferHeaders,\n\ttype InferHeadersInput,\n\ttype InferMiddlewareBody,\n\ttype InferMiddlewareQuery,\n\ttype InferQuery,\n\ttype InferQueryInput,\n\ttype InferRequest,\n\ttype InferRequestInput,\n\ttype InferUse,\n\ttype InputContext,\n} from \"./context\";\nimport type { Prettify } from \"./helper\";\n\nexport interface MiddlewareOptions extends Omit<EndpointOptions, \"method\"> {}\n\nexport type MiddlewareResponse = null | void | undefined | Record<string, any>;\n\nexport type MiddlewareContext<Options extends MiddlewareOptions, Context = {}> = EndpointContext<\n\tstring,\n\tOptions & {\n\t\tmethod: \"*\";\n\t}\n> & {\n\t/**\n\t * Method\n\t *\n\t * The request method\n\t */\n\tmethod: string;\n\t/**\n\t * Path\n\t *\n\t * The path of the endpoint\n\t */\n\tpath: string;\n\t/**\n\t * Body\n\t *\n\t * The body object will be the parsed JSON from the request and validated\n\t * against the body schema if it exists\n\t */\n\tbody: InferMiddlewareBody<Options>;\n\t/**\n\t * Query\n\t *\n\t * The query object will be the parsed query string from the request\n\t * and validated against the query schema if it exists\n\t */\n\tquery: InferMiddlewareQuery<Options>;\n\t/**\n\t * Params\n\t *\n\t * If the path is `/user/:id` and the request is `/user/1` then the\n\t * params will\n\t * be `{ id: \"1\" }` and if the path includes a wildcard like `/user/*`\n\t * then the\n\t * params will be `{ _: \"1\" }` where `_` is the wildcard key. If the\n\t * wildcard\n\t * is named like `/user/**:name` then the params will be `{ name: string }`\n\t */\n\tparams: string;\n\t/**\n\t * Request object\n\t *\n\t * If `requireRequest` is set to true in the endpoint options this will be\n\t * required\n\t */\n\trequest: InferRequest<Options>;\n\t/**\n\t * Headers\n\t *\n\t * If `requireHeaders` is set to true in the endpoint options this will be\n\t * required\n\t */\n\theaders: InferHeaders<Options>;\n\t/**\n\t * Set header\n\t *\n\t * If it's called outside of a request it will just be ignored.\n\t */\n\tsetHeader: (key: string, value: string) => void;\n\t/**\n\t * Get header\n\t *\n\t * If it's called outside of a request it will just return null\n\t *\n\t * @param key - The key of the header\n\t * @returns\n\t */\n\tgetHeader: (key: string) => string | null;\n\t/**\n\t * JSON\n\t *\n\t * a helper function to create a JSON response with\n\t * the correct headers\n\t * and status code. If `asResponse` is set to true in\n\t * the context then\n\t * it will return a Response object instead of the\n\t * JSON object.\n\t *\n\t * @param json - The JSON object to return\n\t * @param routerResponse - The response object to\n\t * return if `asResponse` is\n\t * true in the context this will take precedence\n\t */\n\tjson: <R extends Record<string, any> | null>(\n\t\tjson: R,\n\t\trouterResponse?:\n\t\t\t| {\n\t\t\t\t\tstatus?: number;\n\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\tresponse?: Response;\n\t\t\t }\n\t\t\t| Response,\n\t) => Promise<R>;\n\t/**\n\t * Middleware context\n\t */\n\tcontext: Prettify<Context>;\n};\n\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\toptions: Options,\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware<Options extends MiddlewareOptions, R>(\n\thandler: (context: MiddlewareContext<Options>) => Promise<R>,\n): <InputCtx extends MiddlewareInputContext<Options>>(inputContext: InputCtx) => Promise<R>;\nexport function createMiddleware(optionsOrHandler: any, handler?: any) {\n\tconst internalHandler = async (inputCtx: InputContext<any, any>) => {\n\t\tconst context = inputCtx as InputContext<any, any>;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath: \"/\",\n\t\t});\n\n\t\tif (!_handler) {\n\t\t\tthrow new Error(\"handler must be defined\");\n\t\t}\n\t\tconst response = await _handler(internalContext as any);\n\t\tconst headers = internalContext.responseHeaders;\n\t\treturn context.returnHeaders\n\t\t\t? {\n\t\t\t\t\theaders,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t: response;\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\n\nexport type MiddlewareInputContext<Options extends MiddlewareOptions> = InferBodyInput<Options> &\n\tInferQueryInput<Options> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\tuse?: Middleware[];\n\t};\n\nexport type Middleware<\n\tOptions extends MiddlewareOptions = MiddlewareOptions,\n\tHandler extends (inputCtx: any) => Promise<any> = any,\n> = Handler & {\n\toptions: Options;\n};\n\ncreateMiddleware.create = <\n\tE extends {\n\t\tuse?: Middleware[];\n\t},\n>(\n\topts?: E,\n) => {\n\ttype InferredContext = InferUse<E[\"use\"]>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\toptions: Options,\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn<Options extends MiddlewareOptions, R>(\n\t\thandler: (ctx: MiddlewareContext<Options, InferredContext>) => Promise<R>,\n\t): (inputContext: MiddlewareInputContext<Options>) => Promise<R>;\n\tfunction fn(optionsOrHandler: any, handler?: any) {\n\t\tif (typeof optionsOrHandler === \"function\") {\n\t\t\treturn createMiddleware(\n\t\t\t\t{\n\t\t\t\t\tuse: opts?.use,\n\t\t\t\t},\n\t\t\t\toptionsOrHandler,\n\t\t\t);\n\t\t}\n\t\tif (!handler) {\n\t\t\tthrow new Error(\"Middleware handler is required\");\n\t\t}\n\t\tconst middleware = createMiddleware(\n\t\t\t{\n\t\t\t\t...optionsOrHandler,\n\t\t\t\tmethod: \"*\",\n\t\t\t\tuse: [...(opts?.use || []), ...(optionsOrHandler.use || [])],\n\t\t\t},\n\t\t\thandler,\n\t\t);\n\t\treturn middleware as any;\n\t}\n\treturn fn;\n};\n"],"mappings":";;;;AA0IA,SAAgB,iBAAiB,kBAAuB,SAAe;CACtE,MAAM,kBAAkB,OAAO,aAAqC;EACnE,MAAM,UAAU;EAChB,MAAM,WAAW,OAAO,qBAAqB,aAAa,mBAAmB;EAE7E,MAAM,kBAAkB,MAAM,sBAAsB,SAAS;GAC5D,SAFe,OAAO,qBAAqB,aAAa,EAAE,GAAG;GAG7D,MAAM;GACN,CAAC;AAEF,MAAI,CAAC,SACJ,OAAM,IAAI,MAAM,0BAA0B;EAE3C,MAAM,WAAW,MAAM,SAAS,gBAAuB;EACvD,MAAM,UAAU,gBAAgB;AAChC,SAAO,QAAQ,gBACZ;GACA;GACA;GACA,GACA;;AAEJ,iBAAgB,UAAU,OAAO,qBAAqB,aAAa,EAAE,GAAG;AACxE,QAAO;;AAmBR,iBAAiB,UAKhB,SACI;CASJ,SAAS,GAAG,kBAAuB,SAAe;AACjD,MAAI,OAAO,qBAAqB,WAC/B,QAAO,iBACN,EACC,KAAK,MAAM,KACX,EACD,iBACA;AAEF,MAAI,CAAC,QACJ,OAAM,IAAI,MAAM,iCAAiC;AAUlD,SARmB,iBAClB;GACC,GAAG;GACH,QAAQ;GACR,KAAK,CAAC,GAAI,MAAM,OAAO,EAAE,EAAG,GAAI,iBAAiB,OAAO,EAAE,CAAE;GAC5D,EACD,QACA;;AAGF,QAAO"}
package/dist/node.cjs CHANGED
@@ -1,155 +1,9 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
1
+ const require_request = require('./adapters/node/request.cjs');
26
2
 
27
- //#endregion
28
- let set_cookie_parser = require("set-cookie-parser");
29
- set_cookie_parser = __toESM(set_cookie_parser);
30
-
31
- //#region src/adapters/node/request.ts
32
- function get_raw_body(req, body_size_limit) {
33
- const h = req.headers;
34
- if (!h["content-type"]) return null;
35
- const content_length = Number(h["content-length"]);
36
- if (req.httpVersionMajor === 1 && isNaN(content_length) && h["transfer-encoding"] == null || content_length === 0) return null;
37
- let length = content_length;
38
- if (body_size_limit) {
39
- if (!length) length = body_size_limit;
40
- else if (length > body_size_limit) throw Error(`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`);
41
- }
42
- if (req.destroyed) {
43
- const readable = new ReadableStream();
44
- readable.cancel();
45
- return readable;
46
- }
47
- let size = 0;
48
- let cancelled = false;
49
- return new ReadableStream({
50
- start(controller) {
51
- req.on("error", (error) => {
52
- cancelled = true;
53
- controller.error(error);
54
- });
55
- req.on("end", () => {
56
- if (cancelled) return;
57
- controller.close();
58
- });
59
- req.on("data", (chunk) => {
60
- if (cancelled) return;
61
- size += chunk.length;
62
- if (size > length) {
63
- cancelled = true;
64
- controller.error(/* @__PURE__ */ new Error(`request body size exceeded ${content_length ? "'content-length'" : "BODY_SIZE_LIMIT"} of ${length}`));
65
- return;
66
- }
67
- controller.enqueue(chunk);
68
- if (controller.desiredSize === null || controller.desiredSize <= 0) req.pause();
69
- });
70
- },
71
- pull() {
72
- req.resume();
73
- },
74
- cancel(reason) {
75
- cancelled = true;
76
- req.destroy(reason);
77
- }
78
- });
79
- }
80
- function getRequest({ request, base, bodySizeLimit }) {
81
- const baseUrl = request?.baseUrl;
82
- const fullPath = baseUrl ? baseUrl + request.url : request.url;
83
- const maybeConsumedReq = request;
84
- let body = void 0;
85
- const method = request.method;
86
- if (method !== "GET" && method !== "HEAD") if (maybeConsumedReq.body !== void 0) {
87
- const bodyContent = typeof maybeConsumedReq.body === "string" ? maybeConsumedReq.body : JSON.stringify(maybeConsumedReq.body);
88
- body = new ReadableStream({ start(controller) {
89
- controller.enqueue(new TextEncoder().encode(bodyContent));
90
- controller.close();
91
- } });
92
- } else body = get_raw_body(request, bodySizeLimit);
93
- return new Request(base + fullPath, {
94
- duplex: "half",
95
- method: request.method,
96
- body,
97
- headers: request.headers
98
- });
99
- }
100
- async function setResponse(res, response) {
101
- for (const [key, value] of response.headers) try {
102
- res.setHeader(key, key === "set-cookie" ? set_cookie_parser.splitCookiesString(response.headers.get(key)) : value);
103
- } catch (error) {
104
- res.getHeaderNames().forEach((name) => res.removeHeader(name));
105
- res.writeHead(500).end(String(error));
106
- return;
107
- }
108
- res.writeHead(response.status);
109
- if (!response.body) {
110
- res.end();
111
- return;
112
- }
113
- if (response.body.locked) {
114
- res.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");
115
- return;
116
- }
117
- const reader = response.body.getReader();
118
- if (res.destroyed) {
119
- reader.cancel();
120
- return;
121
- }
122
- const cancel = (error) => {
123
- res.off("close", cancel);
124
- res.off("error", cancel);
125
- reader.cancel(error).catch(() => {});
126
- if (error) res.destroy(error);
127
- };
128
- res.on("close", cancel);
129
- res.on("error", cancel);
130
- next();
131
- async function next() {
132
- try {
133
- for (;;) {
134
- const { done, value } = await reader.read();
135
- if (done) break;
136
- if (!res.write(value)) {
137
- res.once("drain", next);
138
- return;
139
- }
140
- }
141
- res.end();
142
- } catch (error) {
143
- cancel(error instanceof Error ? error : new Error(String(error)));
144
- }
145
- }
146
- }
147
-
148
- //#endregion
149
3
  //#region src/adapters/node/index.ts
150
4
  function toNodeHandler(handler) {
151
5
  return async (req, res) => {
152
- return setResponse(res, await handler(getRequest({
6
+ return require_request.setResponse(res, await handler(require_request.getRequest({
153
7
  base: `${req.headers["x-forwarded-proto"] || (req.socket.encrypted ? "https" : "http")}://${req.headers[":authority"] || req.headers.host}`,
154
8
  request: req
155
9
  })));
@@ -157,8 +11,7 @@ function toNodeHandler(handler) {
157
11
  }
158
12
 
159
13
  //#endregion
160
- exports.__toESM = __toESM;
161
- exports.getRequest = getRequest;
162
- exports.setResponse = setResponse;
14
+ exports.getRequest = require_request.getRequest;
15
+ exports.setResponse = require_request.setResponse;
163
16
  exports.toNodeHandler = toNodeHandler;
164
17
  //# sourceMappingURL=node.cjs.map
package/dist/node.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":[],"sources":["../src/adapters/node/request.ts","../src/adapters/node/index.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport * as set_cookie_parser from \"set-cookie-parser\";\n\nfunction get_raw_body(req: IncomingMessage, body_size_limit?: number) {\n\tconst h = req.headers;\n\n\tif (!h[\"content-type\"]) return null;\n\n\tconst content_length = Number(h[\"content-length\"]);\n\n\t// check if no request body\n\tif (\n\t\t(req.httpVersionMajor === 1 && isNaN(content_length) && h[\"transfer-encoding\"] == null) ||\n\t\tcontent_length === 0\n\t) {\n\t\treturn null;\n\t}\n\n\tlet length = content_length;\n\n\tif (body_size_limit) {\n\t\tif (!length) {\n\t\t\tlength = body_size_limit;\n\t\t} else if (length > body_size_limit) {\n\t\t\tthrow Error(\n\t\t\t\t`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tif (req.destroyed) {\n\t\tconst readable = new ReadableStream();\n\t\treadable.cancel();\n\t\treturn readable;\n\t}\n\n\tlet size = 0;\n\tlet cancelled = false;\n\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\treq.on(\"error\", (error) => {\n\t\t\t\tcancelled = true;\n\t\t\t\tcontroller.error(error);\n\t\t\t});\n\n\t\t\treq.on(\"end\", () => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\treq.on(\"data\", (chunk) => {\n\t\t\t\tif (cancelled) return;\n\n\t\t\t\tsize += chunk.length;\n\n\t\t\t\tif (size > length) {\n\t\t\t\t\tcancelled = true;\n\n\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`request body size exceeded ${\n\t\t\t\t\t\t\t\tcontent_length ? \"'content-length'\" : \"BODY_SIZE_LIMIT\"\n\t\t\t\t\t\t\t} of ${length}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcontroller.enqueue(chunk);\n\n\t\t\t\tif (controller.desiredSize === null || controller.desiredSize <= 0) {\n\t\t\t\t\treq.pause();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tpull() {\n\t\t\treq.resume();\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tcancelled = true;\n\t\t\treq.destroy(reason);\n\t\t},\n\t});\n}\n\nexport function getRequest({\n\trequest,\n\tbase,\n\tbodySizeLimit,\n}: {\n\tbase: string;\n\tbodySizeLimit?: number;\n\trequest: IncomingMessage;\n}) {\n\t// In Express sub-routers, `request.url` is relative to the mount path (e.g., '/auth/xxx'),\n\t// and `request.baseUrl` holds the mount path (e.g., '/api').\n\t// Build the full path as baseUrl + url when available to preserve the full route.\n\tconst baseUrl = (request as any)?.baseUrl as string | undefined;\n\tconst fullPath = baseUrl ? baseUrl + request.url : request.url;\n\n\t// Check if body has already been parsed by Express middleware\n\tconst maybeConsumedReq = request as any;\n\tlet body = undefined;\n\n\tconst method = request.method;\n\t// Request with GET/HEAD method cannot have body.\n\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t// If body was already parsed by Express body-parser middleware\n\t\tif (maybeConsumedReq.body !== undefined) {\n\t\t\t// Convert parsed body back to a ReadableStream\n\t\t\tconst bodyContent =\n\t\t\t\ttypeof maybeConsumedReq.body === \"string\"\n\t\t\t\t\t? maybeConsumedReq.body\n\t\t\t\t\t: JSON.stringify(maybeConsumedReq.body);\n\n\t\t\tbody = new ReadableStream({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(new TextEncoder().encode(bodyContent));\n\t\t\t\t\tcontroller.close();\n\t\t\t\t},\n\t\t\t});\n\t\t} else {\n\t\t\t// Otherwise, get the raw body stream\n\t\t\tbody = get_raw_body(request, bodySizeLimit);\n\t\t}\n\t}\n\n\treturn new Request(base + fullPath, {\n\t\t// @ts-expect-error\n\t\tduplex: \"half\",\n\t\tmethod: request.method,\n\t\tbody,\n\t\theaders: request.headers as Record<string, string>,\n\t});\n}\n\nexport async function setResponse(res: ServerResponse, response: Response) {\n\tfor (const [key, value] of response.headers as any) {\n\t\ttry {\n\t\t\tres.setHeader(\n\t\t\t\tkey,\n\t\t\t\tkey === \"set-cookie\"\n\t\t\t\t\t? set_cookie_parser.splitCookiesString(response.headers.get(key) as string)\n\t\t\t\t\t: value,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tres.getHeaderNames().forEach((name) => res.removeHeader(name));\n\t\t\tres.writeHead(500).end(String(error));\n\t\t\treturn;\n\t\t}\n\t}\n\n\tres.writeHead(response.status);\n\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\n\tif (response.body.locked) {\n\t\tres.end(\n\t\t\t\"Fatal error: Response body is locked. \" +\n\t\t\t\t\"This can happen when the response was already read (for example through 'response.json()' or 'response.text()').\",\n\t\t);\n\t\treturn;\n\t}\n\n\tconst reader = response.body.getReader();\n\n\tif (res.destroyed) {\n\t\treader.cancel();\n\t\treturn;\n\t}\n\n\tconst cancel = (error?: Error) => {\n\t\tres.off(\"close\", cancel);\n\t\tres.off(\"error\", cancel);\n\n\t\t// If the reader has already been interrupted with an error earlier,\n\t\t// then it will appear here, it is useless, but it needs to be catch.\n\t\treader.cancel(error).catch(() => {});\n\t\tif (error) res.destroy(error);\n\t};\n\n\tres.on(\"close\", cancel);\n\tres.on(\"error\", cancel);\n\n\tnext();\n\tasync function next() {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (!res.write(value)) {\n\t\t\t\t\tres.once(\"drain\", next);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tcancel(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request\";\nimport type { Router } from \"../../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol =\n\t\t\treq.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\treturn setResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n"],"mappings":"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"}
1
+ {"version":3,"file":"node.cjs","names":["setResponse","getRequest"],"sources":["../src/adapters/node/index.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { getRequest, setResponse } from \"./request\";\nimport type { Router } from \"../../router.js\";\n\nexport function toNodeHandler(handler: Router[\"handler\"]) {\n\treturn async (req: IncomingMessage, res: ServerResponse) => {\n\t\tconst protocol =\n\t\t\treq.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n\t\tconst base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n\t\tconst response = await handler(getRequest({ base, request: req }));\n\t\treturn setResponse(res, response);\n\t};\n}\n\nexport { getRequest, setResponse };\n"],"mappings":";;;AAKA,SAAgB,cAAc,SAA4B;AACzD,QAAO,OAAO,KAAsB,QAAwB;AAK3D,SAAOA,4BAAY,KADF,MAAM,QAAQC,2BAAW;GAAE,MAD/B,GADZ,IAAI,QAAQ,yBAA0B,IAAI,OAAe,YAAY,UAAU,QACvD,KAAK,IAAI,QAAQ,iBAAiB,IAAI,QAAQ;GACrB,SAAS;GAAK,CAAC,CAAC,CACjC"}
package/dist/node.d.cts CHANGED
@@ -1,18 +1,7 @@
1
- import { t as Router } from "./router.cjs";
1
+ import { getRequest, setResponse } from "./adapters/node/request.cjs";
2
+ import { Router } from "./router.cjs";
2
3
  import { IncomingMessage, ServerResponse } from "node:http";
3
4
 
4
- //#region src/adapters/node/request.d.ts
5
- declare function getRequest({
6
- request,
7
- base,
8
- bodySizeLimit
9
- }: {
10
- base: string;
11
- bodySizeLimit?: number;
12
- request: IncomingMessage;
13
- }): Request;
14
- declare function setResponse(res: ServerResponse, response: Response): Promise<void>;
15
- //#endregion
16
5
  //#region src/adapters/node/index.d.ts
17
6
  declare function toNodeHandler(handler: Router["handler"]): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
18
7
  //#endregion
@@ -0,0 +1,9 @@
1
+ import { getRequest, setResponse } from "./adapters/node/request.mjs";
2
+ import { Router } from "./router.mjs";
3
+ import { IncomingMessage, ServerResponse } from "node:http";
4
+
5
+ //#region src/adapters/node/index.d.ts
6
+ declare function toNodeHandler(handler: Router["handler"]): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
7
+ //#endregion
8
+ export { getRequest, setResponse, toNodeHandler };
9
+ //# sourceMappingURL=node.d.mts.map