@aura-stack/router 0.1.0 → 0.3.0

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 (43) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +17 -114
  3. package/dist/assert.cjs +64 -6
  4. package/dist/assert.d.cts +21 -1
  5. package/dist/assert.d.ts +21 -1
  6. package/dist/assert.js +8 -3
  7. package/dist/chunk-6PZEXNTS.js +31 -0
  8. package/dist/{chunk-RVJ2F7OL.js → chunk-FWDOXDWG.js} +7 -7
  9. package/dist/{chunk-RFYOPPMW.js → chunk-GJC3ODME.js} +15 -6
  10. package/dist/chunk-JIA6NLL6.js +143 -0
  11. package/dist/chunk-JNMXLKDG.js +33 -0
  12. package/dist/chunk-PT4GU6PH.js +78 -0
  13. package/dist/context.cjs +50 -47
  14. package/dist/context.d.cts +3 -2
  15. package/dist/context.d.ts +3 -2
  16. package/dist/context.js +3 -4
  17. package/dist/endpoint.cjs +29 -29
  18. package/dist/endpoint.d.cts +18 -17
  19. package/dist/endpoint.d.ts +18 -17
  20. package/dist/endpoint.js +5 -7
  21. package/dist/error.cjs +19 -7
  22. package/dist/error.d.cts +28 -3
  23. package/dist/error.d.ts +28 -3
  24. package/dist/error.js +9 -3
  25. package/dist/index.cjs +195 -116
  26. package/dist/index.d.cts +3 -1
  27. package/dist/index.d.ts +3 -1
  28. package/dist/index.js +19 -9
  29. package/dist/{middleware.cjs → middlewares.cjs} +20 -14
  30. package/dist/{middleware.d.cts → middlewares.d.cts} +1 -0
  31. package/dist/{middleware.d.ts → middlewares.d.ts} +1 -0
  32. package/dist/{middleware.js → middlewares.js} +2 -2
  33. package/dist/router.cjs +182 -103
  34. package/dist/router.d.cts +24 -2
  35. package/dist/router.d.ts +24 -2
  36. package/dist/router.js +13 -8
  37. package/dist/types.d.cts +68 -11
  38. package/dist/types.d.ts +68 -11
  39. package/package.json +10 -2
  40. package/dist/chunk-6UBPSXKR.js +0 -36
  41. package/dist/chunk-ENOBC3XN.js +0 -23
  42. package/dist/chunk-NNCUFWPI.js +0 -78
  43. package/dist/chunk-VBI7H3AK.js +0 -75
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ZodObject, z } from 'zod';
2
+ import { RouterError } from './error.js';
2
3
 
3
4
  /**
4
5
  * Route pattern must start with a slash and can contain parameters prefixed with a colon.
@@ -6,15 +7,16 @@ import { ZodObject, z } from 'zod';
6
7
  * const getUser:RoutePattern = "/users/:userId"
7
8
  * const getPostsComments:RoutePattern = "/posts/:postId/comments/:commentId"
8
9
  */
9
- type RoutePattern = `/${string}`;
10
+ type RoutePattern = `/${string}` | `/${string}/:${string}`;
10
11
  /**
11
- * HTTP methods supported by the router.
12
+ * HTTP methods defined in HTTP/1.1 specification.
13
+ * @see https://datatracker.ietf.org/doc/html/rfc7231#section-4.3
12
14
  */
13
- type HTTPMethod = "GET" | "POST" | "DELETE" | "PUT" | "PATCH";
15
+ type HTTPMethod = "GET" | "POST" | "DELETE" | "PUT" | "PATCH" | "OPTIONS" | "HEAD" | "TRACE" | "CONNECT";
14
16
  /**
15
17
  * Content types supported by the router.
16
18
  */
17
- type ContentType = "application/json" | "application/x-www-form-urlencoded" | "text/plain";
19
+ type ContentType = "application/json" | "application/x-www-form-urlencoded" | "text/plain" | "multipart/form-data" | "application/xml" | "application/octet-stream" | `text/${string}` | `image/${string}` | `video/${string}` | `audio/${string}` | "application/pdf";
18
20
  type Prettify<Obj extends object> = {
19
21
  [Key in keyof Obj]: Obj[Key];
20
22
  } & {};
@@ -33,20 +35,20 @@ type Prettify<Obj extends object> = {
33
35
  * // Expected: {}
34
36
  * type NoParams = Params<"/about">;
35
37
  */
36
- type Params<Route extends RoutePattern> = Route extends `/${string}/:${infer Param}/${infer Str}` ? Prettify<{
38
+ type GetRouteParams<Route extends RoutePattern> = Route extends `/${string}/:${infer Param}/${infer Str}` ? Prettify<{
37
39
  [K in Param]: string;
38
- } & Params<`/${Str}`>> : Route extends `/${string}/:${infer Param}` ? Prettify<{
40
+ } & GetRouteParams<`/${Str}`>> : Route extends `/${string}/:${infer Param}` ? Prettify<{
39
41
  [K in Param]: string;
40
42
  }> : Route extends `/:${infer Param}` ? Prettify<{
41
43
  [K in Param]: string;
42
44
  }> : {};
43
- type GetRouteParams<T extends RoutePattern> = Params<T>;
44
45
  /**
45
46
  * Available schemas validation for an endpoint. It can include body and searchParams schemas.
46
47
  */
47
48
  interface EndpointSchemas {
48
49
  body?: ZodObject<any>;
49
50
  searchParams?: ZodObject<any>;
51
+ params?: ZodObject<any>;
50
52
  }
51
53
  /**
52
54
  * Configuration for an endpoint, including optional schemas for request validation and middlewares.
@@ -77,12 +79,22 @@ type ContextBody<Schemas extends EndpointConfig["schemas"]> = Schemas extends {
77
79
  } : {
78
80
  body: undefined;
79
81
  };
82
+ /**
83
+ * Infer the type of route parameters from the provided value in the `EndpointConfig`.
84
+ */
85
+ type ContextParams<Schemas extends EndpointConfig["schemas"], Default = Record<string, string>> = Schemas extends {
86
+ params: ZodObject;
87
+ } ? {
88
+ params: z.infer<Schemas["params"]>;
89
+ } : {
90
+ params: Default;
91
+ };
80
92
  /**
81
93
  * Context object passed to route handlers and middlewares defined in the
82
94
  * `createEndpoint/createEndpointConfig` function or globally in the `createRouter` function.
83
95
  */
84
96
  interface RequestContext<RouteParams = Record<string, string>, Config extends EndpointConfig = EndpointConfig> {
85
- params: RouteParams;
97
+ params: ContextParams<Config["schemas"], RouteParams>["params"];
86
98
  headers: Headers;
87
99
  body: ContextBody<Config["schemas"]>["body"];
88
100
  searchParams: ContextSearchParams<Config["schemas"]>["searchParams"];
@@ -101,7 +113,7 @@ type MiddlewareFunction<RouteParams = Record<string, string>, Config extends End
101
113
  * The handler receives the request object and a context containing route parameters, headers,
102
114
  * and optionally validated body and search parameters based on the endpoint configuration.
103
115
  */
104
- type RouteHandler<Route extends RoutePattern, Config extends EndpointConfig> = (request: Request, ctx: Prettify<RequestContext<GetRouteParams<Route>, Config>>) => Promise<Response>;
116
+ type RouteHandler<Route extends RoutePattern, Config extends EndpointConfig> = (request: Request, ctx: Prettify<RequestContext<GetRouteParams<Route>, Config>>) => Response | Promise<Response>;
105
117
  /**
106
118
  * Represents a route endpoint definition, specifying the HTTP method, route pattern,
107
119
  * handler function with inferred context types, and associated configuration.
@@ -121,14 +133,59 @@ type InferMethod<Endpoints extends RouteEndpoint[]> = Endpoints extends unknown[
121
133
  * Each method is a function that takes a request and context, returning a promise of a response.
122
134
  */
123
135
  type GetHttpHandlers<Endpoints extends RouteEndpoint[]> = {
124
- [Method in InferMethod<Endpoints>]: (req: Request, ctx: RequestContext) => Promise<Response>;
136
+ [Method in InferMethod<Endpoints>]: (req: Request) => Response | Promise<Response>;
125
137
  };
126
138
  /**
127
139
  * Configuration options for `createRouter` function.
128
140
  */
129
141
  interface RouterConfig {
142
+ /**
143
+ * Prefix path for all routes/endpoints defined in the router.
144
+ *
145
+ * @example
146
+ * basePath: "/api/v1"
147
+ *
148
+ * // will match the "/users" endpoint.
149
+ * new Request("https://example.com/api/v1/users")
150
+ *
151
+ * // will NOT match the "/users" endpoint.
152
+ * new Request("https://example.com/users")
153
+ */
130
154
  basePath?: RoutePattern;
155
+ /**
156
+ * Global middlewares that run before route matching for all endpoints in the router.
157
+ * You can use this to modify the request or return a response early.
158
+ *
159
+ * @example
160
+ * middlewares: [
161
+ * async (request) => {
162
+ * if(request.headers.get("Authorization")?.startsWith("Bearer ")) {
163
+ * return Response.json({ message: "Unauthorized" }, { status: 401 })
164
+ * }
165
+ * return request
166
+ * }
167
+ * ]
168
+ */
131
169
  middlewares?: GlobalMiddleware[];
170
+ /**
171
+ * Error handler function that runs when an error is thrown in a router handler or middleware.
172
+ * It can be used to customize the default error response provided by the router. If is an internal
173
+ * error the error is from the `RouterError` class, otherwise the error is a generic
174
+ * `Error` instance which was caused by a handler or middleware, for how to distinguish them you can use
175
+ * the `isRouterError` function from the `assert` module.
176
+ *
177
+ * @param error - The error thrown in the router
178
+ * @param request - The original request that caused the error
179
+ * @returns A response to be sent back to the client
180
+ * @example
181
+ * onError: (error, request) => {
182
+ * if(isRouterError(error)) {
183
+ * return Response.json({ message: error.message }, { status: error.statusCode })
184
+ * }
185
+ * return Response.json({ message: "Internal Server Error" }, { status: 500 })
186
+ * }
187
+ */
188
+ onError?: (error: Error | RouterError, request: Request) => Response | Promise<Response>;
132
189
  }
133
190
 
134
- export type { ContentType, ContextBody, ContextSearchParams, EndpointConfig, EndpointSchemas, GetHttpHandlers, GetRouteParams, GlobalMiddleware, HTTPMethod, InferMethod, MiddlewareFunction, Params, Prettify, RequestContext, RouteEndpoint, RouteHandler, RoutePattern, RouterConfig };
191
+ export type { ContentType, ContextBody, ContextParams, ContextSearchParams, EndpointConfig, EndpointSchemas, GetHttpHandlers, GetRouteParams, GlobalMiddleware, HTTPMethod, InferMethod, MiddlewareFunction, Prettify, RequestContext, RouteEndpoint, RouteHandler, RoutePattern, RouterConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aura-stack/router",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "A lightweight TypeScript library for building, managing, and validating API routes and endpoints in Node.js applications.",
6
6
  "files": [
@@ -22,6 +22,11 @@
22
22
  "import": "./dist/endpoint.js",
23
23
  "require": "./dist/endpoint.cjs"
24
24
  },
25
+ "./error": {
26
+ "types": "./dist/error.d.ts",
27
+ "import": "./dist/error.js",
28
+ "require": "./dist/error.cjs"
29
+ },
25
30
  "./types": "./dist/types.d.ts"
26
31
  },
27
32
  "keywords": [
@@ -44,12 +49,15 @@
44
49
  },
45
50
  "scripts": {
46
51
  "dev": "tsup --watch",
52
+ "dev:docs": "pnpm --filter docs dev",
47
53
  "build": "tsup",
48
54
  "format": "prettier --write .",
49
55
  "format:check": "prettier --check .",
50
56
  "test": "vitest --run",
51
57
  "test:watch": "vitest",
58
+ "test:bench": "vitest --run bench",
52
59
  "type-check": "tsc --noEmit",
53
- "clean": "rm -rf dist"
60
+ "clean": "rm -rf dist",
61
+ "clean:cts": "rm -rf dist/*.cts"
54
62
  }
55
63
  }
@@ -1,36 +0,0 @@
1
- import {
2
- isSupportedMethod,
3
- isValidHandler,
4
- isValidRoute
5
- } from "./chunk-ENOBC3XN.js";
6
- import {
7
- AuraStackRouterError
8
- } from "./chunk-RFYOPPMW.js";
9
-
10
- // src/endpoint.ts
11
- var createRoutePattern = (route) => {
12
- const pattern = route.replace(/:[^/]+/g, "([^/]+)").replace(/\//g, "\\/");
13
- return new RegExp(`^${pattern}$`);
14
- };
15
- var createEndpoint = (method, route, handler, config = {}) => {
16
- if (!isSupportedMethod(method)) {
17
- throw new AuraStackRouterError("METHOD_NOT_ALLOWED", `Unsupported HTTP method: ${method}`);
18
- }
19
- if (!isValidRoute(route)) {
20
- throw new AuraStackRouterError("BAD_REQUEST", `Invalid route format: ${route}`);
21
- }
22
- if (!isValidHandler(handler)) {
23
- throw new AuraStackRouterError("BAD_REQUEST", "Handler must be a function");
24
- }
25
- return { method, route, handler, config };
26
- };
27
- function createEndpointConfig(...args) {
28
- if (typeof args[0] === "string") return args[1];
29
- return args[0];
30
- }
31
-
32
- export {
33
- createRoutePattern,
34
- createEndpoint,
35
- createEndpointConfig
36
- };
@@ -1,23 +0,0 @@
1
- // src/assert.ts
2
- var supportedMethods = ["GET", "POST", "DELETE", "PUT", "PATCH"];
3
- var supportedBodyMethods = ["POST", "PUT", "PATCH"];
4
- var isSupportedMethod = (method) => {
5
- return supportedMethods.includes(method);
6
- };
7
- var isSupportedBodyMethod = (method) => {
8
- return supportedBodyMethods.includes(method);
9
- };
10
- var isValidRoute = (route) => {
11
- const routePattern = /^\/[a-zA-Z0-9/_:-]*$/;
12
- return routePattern.test(route);
13
- };
14
- var isValidHandler = (handler) => {
15
- return typeof handler === "function";
16
- };
17
-
18
- export {
19
- isSupportedMethod,
20
- isSupportedBodyMethod,
21
- isValidRoute,
22
- isValidHandler
23
- };
@@ -1,78 +0,0 @@
1
- import {
2
- createRoutePattern
3
- } from "./chunk-6UBPSXKR.js";
4
- import {
5
- isSupportedBodyMethod
6
- } from "./chunk-ENOBC3XN.js";
7
- import {
8
- AuraStackRouterError
9
- } from "./chunk-RFYOPPMW.js";
10
-
11
- // src/context.ts
12
- var getRouteParams = (route, path) => {
13
- const routeRegex = createRoutePattern(route);
14
- if (!routeRegex.test(path)) {
15
- throw new AuraStackRouterError("BAD_REQUEST", `Missing required route params for route: ${route}`);
16
- }
17
- const params = routeRegex.exec(route)?.slice(1).map((seg) => seg.replace(":", ""));
18
- if (!params) return {};
19
- const values = routeRegex.exec(path)?.slice(1);
20
- return params.reduce(
21
- (previous, now, idx) => ({
22
- ...previous,
23
- [now]: decodeURIComponent(values?.[idx] ?? "")
24
- }),
25
- {}
26
- );
27
- };
28
- var getSearchParams = (url, config) => {
29
- const route = new URL(url);
30
- if (config.schemas?.searchParams) {
31
- const parsed = config.schemas.searchParams.safeParse(Object.fromEntries(route.searchParams.entries()));
32
- if (!parsed.success) {
33
- throw new AuraStackRouterError("UNPROCESSABLE_ENTITY", "Invalid search parameters");
34
- }
35
- return parsed.data;
36
- }
37
- return new URLSearchParams(route.searchParams.toString());
38
- };
39
- var getHeaders = (request) => {
40
- return new Headers(request.headers);
41
- };
42
- var getBody = async (request, config) => {
43
- if (!isSupportedBodyMethod(request.method)) {
44
- return void 0;
45
- }
46
- const contentType = request.headers.get("Content-Type") ?? "";
47
- if (contentType.includes("application/json")) {
48
- const json = await request.json();
49
- if (config.schemas?.body) {
50
- const parsed = config.schemas.body.safeParse(json);
51
- if (!parsed.success) {
52
- throw new AuraStackRouterError("UNPROCESSABLE_ENTITY", "Invalid request body");
53
- }
54
- return parsed.data;
55
- }
56
- return json;
57
- }
58
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
59
- return await request.formData();
60
- }
61
- if (contentType.includes("text/")) {
62
- return await request.text();
63
- }
64
- if (contentType.includes("application/octet-stream")) {
65
- return await request.arrayBuffer();
66
- }
67
- if (contentType.includes("image/") || contentType.includes("video/") || contentType.includes("audio/")) {
68
- return await request.blob();
69
- }
70
- return null;
71
- };
72
-
73
- export {
74
- getRouteParams,
75
- getSearchParams,
76
- getHeaders,
77
- getBody
78
- };
@@ -1,75 +0,0 @@
1
- import {
2
- getBody,
3
- getHeaders,
4
- getRouteParams,
5
- getSearchParams
6
- } from "./chunk-NNCUFWPI.js";
7
- import {
8
- createRoutePattern
9
- } from "./chunk-6UBPSXKR.js";
10
- import {
11
- executeGlobalMiddlewares,
12
- executeMiddlewares
13
- } from "./chunk-RVJ2F7OL.js";
14
- import {
15
- AuraStackRouterError
16
- } from "./chunk-RFYOPPMW.js";
17
-
18
- // src/router.ts
19
- var createRouter = (endpoints, config = {}) => {
20
- const server = {};
21
- const groups = {
22
- GET: [],
23
- POST: [],
24
- DELETE: [],
25
- PUT: [],
26
- PATCH: []
27
- };
28
- endpoints.forEach((endpoint) => groups[endpoint.method].push(endpoint));
29
- for (const method in groups) {
30
- server[method] = async (request, ctx) => {
31
- try {
32
- const globalRequest = await executeGlobalMiddlewares(request, config.middlewares);
33
- if (globalRequest instanceof Response) {
34
- return globalRequest;
35
- }
36
- const url = new URL(globalRequest.url);
37
- const pathname = url.pathname;
38
- const endpoint = groups[method].find((endpoint2) => {
39
- const withBasePath = config.basePath ? `${config.basePath}${endpoint2.route}` : endpoint2.route;
40
- const regex = createRoutePattern(withBasePath);
41
- return regex.test(pathname);
42
- });
43
- if (endpoint) {
44
- const withBasePath = config.basePath ? `${config.basePath}${endpoint.route}` : endpoint.route;
45
- const body = await getBody(globalRequest, endpoint.config);
46
- const params = getRouteParams(withBasePath, pathname);
47
- const searchParams = getSearchParams(globalRequest.url, endpoint.config);
48
- const headers = getHeaders(globalRequest);
49
- const context = {
50
- ...ctx,
51
- params,
52
- searchParams,
53
- headers,
54
- body
55
- };
56
- await executeMiddlewares(globalRequest, context, endpoint.config.middlewares);
57
- return endpoint.handler(globalRequest, context);
58
- }
59
- return Response.json({ message: "Not Found" }, { status: 404 });
60
- } catch (error) {
61
- if (error instanceof AuraStackRouterError) {
62
- const { message, status, statusText } = error;
63
- console.log("StatusText: ", statusText);
64
- return Response.json({ message }, { status, statusText });
65
- }
66
- return Response.json({ message: "Internal Server Error" }, { status: 500 });
67
- }
68
- };
69
- }
70
- return server;
71
- };
72
-
73
- export {
74
- createRouter
75
- };