burger-api 0.9.7 → 1.0.0-beta.1
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/README.md +84 -241
- package/dist/src/adapter/bun/index.d.ts +14 -0
- package/dist/src/adapter/bun/index.js +73 -0
- package/dist/src/adapter/bun/types.d.ts +15 -0
- package/dist/src/adapter/bun/types.js +1 -0
- package/dist/src/adapter/index.d.ts +1 -0
- package/dist/src/adapter/index.js +1 -0
- package/dist/src/adapter/types.d.ts +49 -0
- package/dist/src/adapter/types.js +1 -0
- package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
- package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
- package/dist/src/adapter/web-standard/index.d.ts +8 -0
- package/dist/src/adapter/web-standard/index.js +7 -0
- package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
- package/dist/src/analysis/route-access-analyzer.js +287 -0
- package/dist/src/chain/chain.d.ts +16 -0
- package/dist/src/chain/chain.js +17 -0
- package/dist/src/chain/flattener.d.ts +3 -0
- package/dist/src/chain/flattener.js +78 -0
- package/dist/src/chain/node.d.ts +25 -0
- package/dist/src/chain/node.js +1 -0
- package/dist/src/compiler/conventions.d.ts +67 -0
- package/dist/src/compiler/conventions.js +129 -0
- package/dist/src/compiler/index.d.ts +13 -0
- package/dist/src/compiler/index.js +11 -0
- package/dist/src/compiler/module-loader.d.ts +75 -0
- package/dist/src/compiler/module-loader.js +276 -0
- package/dist/src/compiler/route-module.d.ts +97 -0
- package/dist/src/compiler/route-module.js +1 -0
- package/dist/src/compiler/route-tree.d.ts +19 -0
- package/dist/src/compiler/route-tree.js +28 -0
- package/dist/src/compiler/scanner.d.ts +42 -0
- package/dist/src/compiler/scanner.js +240 -0
- package/dist/src/context/context-set.d.ts +26 -0
- package/dist/src/context/context-set.js +45 -0
- package/dist/src/context/context.d.ts +357 -0
- package/dist/src/context/context.js +401 -0
- package/dist/src/context/query-parser.d.ts +23 -0
- package/dist/src/context/query-parser.js +132 -0
- package/dist/src/context/route-access.d.ts +7 -0
- package/dist/src/context/route-access.js +18 -0
- package/dist/src/context/types.d.ts +62 -0
- package/dist/src/context/types.js +5 -0
- package/dist/src/core/asset-mime.d.ts +9 -0
- package/dist/src/core/asset-mime.js +35 -0
- package/dist/src/core/assets.d.ts +30 -0
- package/dist/src/core/assets.js +67 -0
- package/dist/src/core/docs-providers.d.ts +13 -0
- package/dist/src/core/docs-providers.js +89 -0
- package/dist/src/core/embedded-assets.d.ts +18 -0
- package/dist/src/core/embedded-assets.js +13 -0
- package/dist/src/core/openapi.d.ts +9 -10
- package/dist/src/core/openapi.js +333 -127
- package/dist/src/core/page-router.d.ts +13 -17
- package/dist/src/core/page-router.js +86 -55
- package/dist/src/core/server.d.ts +20 -11
- package/dist/src/core/server.js +41 -45
- package/dist/src/errors/forbidden.d.ts +14 -0
- package/dist/src/errors/forbidden.js +16 -0
- package/dist/src/errors/http-error.d.ts +49 -0
- package/dist/src/errors/http-error.js +155 -0
- package/dist/src/errors/method-not-allowed.d.ts +13 -0
- package/dist/src/errors/method-not-allowed.js +15 -0
- package/dist/src/errors/not-found.d.ts +14 -0
- package/dist/src/errors/not-found.js +16 -0
- package/dist/src/errors/unauthorized.d.ts +14 -0
- package/dist/src/errors/unauthorized.js +16 -0
- package/dist/src/index.d.ts +275 -50
- package/dist/src/index.js +974 -333
- package/dist/src/lifecycle/executor.d.ts +64 -0
- package/dist/src/lifecycle/executor.js +201 -0
- package/dist/src/lifecycle/hook-runner.d.ts +11 -0
- package/dist/src/lifecycle/hook-runner.js +156 -0
- package/dist/src/lifecycle/jit.d.ts +50 -0
- package/dist/src/lifecycle/jit.js +258 -0
- package/dist/src/lifecycle/transform.d.ts +26 -0
- package/dist/src/lifecycle/transform.js +99 -0
- package/dist/src/lifecycle/types.d.ts +135 -0
- package/dist/src/lifecycle/types.js +1 -0
- package/dist/src/plugin/composer.d.ts +3 -0
- package/dist/src/plugin/composer.js +28 -0
- package/dist/src/plugin/registry.d.ts +25 -0
- package/dist/src/plugin/registry.js +107 -0
- package/dist/src/plugin/types.d.ts +20 -0
- package/dist/src/plugin/types.js +1 -0
- package/dist/src/router/allow-cache.d.ts +20 -0
- package/dist/src/router/allow-cache.js +26 -0
- package/dist/src/router/compiler.d.ts +39 -0
- package/dist/src/router/compiler.js +867 -0
- package/dist/src/router/define.d.ts +67 -0
- package/dist/src/router/define.js +34 -0
- package/dist/src/router/index.d.ts +6 -0
- package/dist/src/router/index.js +5 -0
- package/dist/src/router/param-extract.d.ts +33 -0
- package/dist/src/router/param-extract.js +87 -0
- package/dist/src/router/regex-matcher.d.ts +42 -0
- package/dist/src/router/regex-matcher.js +216 -0
- package/dist/src/router/router.d.ts +214 -0
- package/dist/src/router/router.js +670 -0
- package/dist/src/router/static-map.d.ts +39 -0
- package/dist/src/router/static-map.js +48 -0
- package/dist/src/router/trie.d.ts +69 -0
- package/dist/src/router/trie.js +572 -0
- package/dist/src/router/types.d.ts +104 -0
- package/dist/src/router/types.js +1 -0
- package/dist/src/runtime/capabilities.d.ts +29 -0
- package/dist/src/runtime/capabilities.js +48 -0
- package/dist/src/types/index.d.ts +260 -109
- package/dist/src/types/index.js +1 -1
- package/dist/src/types/inference.d.ts +78 -0
- package/dist/src/types/inference.js +20 -0
- package/dist/src/types/openapi-config.d.ts +164 -0
- package/dist/src/types/openapi-config.js +8 -0
- package/dist/src/utils/env.d.ts +13 -0
- package/dist/src/utils/env.js +24 -0
- package/dist/src/utils/fs.d.ts +29 -0
- package/dist/src/utils/fs.js +75 -0
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +2 -2
- package/dist/src/utils/pathConversion.js +13 -7
- package/dist/src/utils/response.d.ts +42 -6
- package/dist/src/utils/response.js +189 -7
- package/dist/src/utils/routing.d.ts +32 -13
- package/dist/src/utils/routing.js +41 -18
- package/dist/src/utils/thenable.d.ts +8 -0
- package/dist/src/utils/thenable.js +12 -0
- package/dist/src/utils/timing-safe.d.ts +9 -0
- package/dist/src/utils/timing-safe.js +20 -0
- package/dist/src/utils/wildcard.d.ts +6 -7
- package/dist/src/utils/wildcard.js +38 -55
- package/dist/src/validation/adapter.d.ts +54 -0
- package/dist/src/validation/adapter.js +75 -0
- package/dist/src/validation/adapters/standard.d.ts +11 -0
- package/dist/src/validation/adapters/standard.js +110 -0
- package/dist/src/validation/adapters/zod.d.ts +9 -0
- package/dist/src/validation/adapters/zod.js +128 -0
- package/dist/src/validation/cache.d.ts +26 -0
- package/dist/src/validation/cache.js +35 -0
- package/dist/src/validation/coerce.d.ts +28 -0
- package/dist/src/validation/coerce.js +176 -0
- package/dist/src/validation/compiler.d.ts +27 -0
- package/dist/src/validation/compiler.js +191 -0
- package/dist/src/validation/error.d.ts +69 -0
- package/dist/src/validation/error.js +137 -0
- package/dist/src/validation/index.d.ts +16 -0
- package/dist/src/validation/index.js +12 -0
- package/dist/src/validation/response.d.ts +25 -0
- package/dist/src/validation/response.js +85 -0
- package/dist/src/validation/types.d.ts +148 -0
- package/dist/src/validation/types.js +6 -0
- package/dist/src/validation/validator.d.ts +39 -0
- package/dist/src/validation/validator.js +441 -0
- package/dist/src/ws/adapter.d.ts +230 -0
- package/dist/src/ws/adapter.js +660 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +178 -0
- package/dist/src/ws/index.d.ts +11 -0
- package/dist/src/ws/index.js +8 -0
- package/dist/src/ws/platform.d.ts +82 -0
- package/dist/src/ws/platform.js +122 -0
- package/dist/src/ws/router.d.ts +47 -0
- package/dist/src/ws/router.js +183 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +253 -0
- package/dist/src/ws/types.d.ts +381 -0
- package/dist/src/ws/types.js +213 -0
- package/package.json +72 -60
- package/dist/src/core/api-router.d.ts +0 -65
- package/dist/src/core/api-router.js +0 -264
- package/dist/src/core/swagger-ui.d.ts +0 -1
- package/dist/src/core/swagger-ui.js +0 -33
- package/dist/src/middleware/validator.d.ts +0 -14
- package/dist/src/middleware/validator.js +0 -133
- package/dist/src/utils/error.d.ts +0 -17
- package/dist/src/utils/error.js +0 -63
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index';
|
|
1
|
+
import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Constants for route handling.
|
|
4
4
|
*/
|
|
@@ -15,31 +15,50 @@ export declare const ROUTE_CONSTANTS: {
|
|
|
15
15
|
WILDCARD_START: string;
|
|
16
16
|
};
|
|
17
17
|
/**
|
|
18
|
-
* Supported HTTP methods
|
|
18
|
+
* Supported HTTP methods as a literal tuple; the names double as the
|
|
19
|
+
* `HTTPMethod` union.
|
|
19
20
|
*/
|
|
20
|
-
export declare const HTTP_METHODS:
|
|
21
|
+
export declare const HTTP_METHODS: readonly ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
|
|
21
22
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
|
|
23
|
+
* The closed set of HTTP methods a route can handle, uppercase as used in
|
|
24
|
+
* `RouteDefinition.handlers` and `request.method`.
|
|
25
|
+
*/
|
|
26
|
+
export type HTTPMethod = (typeof HTTP_METHODS)[number];
|
|
27
|
+
/**
|
|
28
|
+
* Lowercase form of `HTTPMethod`, used by the lowercase-keyed maps
|
|
29
|
+
* (`RouteSchema`, `openapi`, compiled validators).
|
|
30
|
+
*/
|
|
31
|
+
export type LowercaseHTTPMethod = Lowercase<HTTPMethod>;
|
|
32
|
+
/**
|
|
33
|
+
* Scores a route path by specificity: +1 per static segment, 0 per dynamic
|
|
34
|
+
* (`:param`, `[param]`), -1 per wildcard. Higher means more static; sorting by
|
|
35
|
+
* it puts static first, dynamic second, wildcard last.
|
|
25
36
|
* @param path The route path to evaluate.
|
|
26
|
-
* @returns The specificity score
|
|
37
|
+
* @returns The specificity score.
|
|
27
38
|
*/
|
|
28
39
|
export declare const getRouteSpecificity: (path: string) => number;
|
|
29
40
|
/**
|
|
30
|
-
* Compares two routes for sorting
|
|
31
|
-
*
|
|
32
|
-
* If specificity is equal, sorts alphabetically by path.
|
|
41
|
+
* Compares two routes for sorting: higher specificity first (Static >
|
|
42
|
+
* Dynamic > Wildcard), ties alphabetically by path.
|
|
33
43
|
* @param a The first route to compare.
|
|
34
44
|
* @param b The second route to compare.
|
|
35
|
-
* @returns Negative if a comes
|
|
45
|
+
* @returns Negative if a comes first, positive if b does, zero if equal.
|
|
36
46
|
*/
|
|
37
47
|
export declare const compareRoutes: (a: PageDefinition | RouteDefinition, b: PageDefinition | RouteDefinition) => number;
|
|
38
48
|
/**
|
|
39
|
-
* Collects all routes from the trie
|
|
49
|
+
* Collects all routes from the trie as `RouteDefinition` objects.
|
|
40
50
|
* @param node The current node in the trie.
|
|
41
51
|
* @param currentPath The current path being traversed.
|
|
42
52
|
* @param routes The array of collected routes.
|
|
43
|
-
* @returns
|
|
53
|
+
* @returns The collected routes.
|
|
44
54
|
*/
|
|
45
55
|
export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
|
|
56
|
+
/**
|
|
57
|
+
* Copies a per-method map (`schema.ts` / `openapi.ts` / `config.ts` exports)
|
|
58
|
+
* with uppercase method keys (`GET`) lowercased (`get`) for the validation
|
|
59
|
+
* compiler, OpenAPI generator and route compiler. Non-method keys (e.g.
|
|
60
|
+
* `coerce`) pass through; never mutates the input (module namespaces are
|
|
61
|
+
* frozen). Returns the input unchanged when it has no uppercase method key,
|
|
62
|
+
* so default-only configs keep their object identity.
|
|
63
|
+
*/
|
|
64
|
+
export declare function lowercaseMethodKeys(raw: Record<string, unknown> | object): Record<string, unknown>;
|
|
@@ -19,7 +19,8 @@ export const ROUTE_CONSTANTS = {
|
|
|
19
19
|
WILDCARD_START: '[...',
|
|
20
20
|
};
|
|
21
21
|
/**
|
|
22
|
-
* Supported HTTP methods
|
|
22
|
+
* Supported HTTP methods as a literal tuple; the names double as the
|
|
23
|
+
* `HTTPMethod` union.
|
|
23
24
|
*/
|
|
24
25
|
export const HTTP_METHODS = [
|
|
25
26
|
'GET',
|
|
@@ -31,30 +32,34 @@ export const HTTP_METHODS = [
|
|
|
31
32
|
'OPTIONS',
|
|
32
33
|
];
|
|
33
34
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
35
|
+
* Scores a route path by specificity: +1 per static segment, 0 per dynamic
|
|
36
|
+
* (`:param`, `[param]`), -1 per wildcard. Higher means more static; sorting by
|
|
37
|
+
* it puts static first, dynamic second, wildcard last.
|
|
37
38
|
* @param path The route path to evaluate.
|
|
38
|
-
* @returns The specificity score
|
|
39
|
+
* @returns The specificity score.
|
|
39
40
|
*/
|
|
40
41
|
export const getRouteSpecificity = (path) => {
|
|
41
42
|
const segments = path.split('/').filter(Boolean);
|
|
42
43
|
return segments.reduce((score, segment) => {
|
|
43
|
-
if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)
|
|
44
|
-
|
|
44
|
+
if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX) ||
|
|
45
|
+
(segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
|
|
46
|
+
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END))) {
|
|
47
|
+
return score - 1; // Wildcard routes get the penalty (lowest priority)
|
|
45
48
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX) ||
|
|
50
|
+
(segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
51
|
+
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END))) {
|
|
52
|
+
return score; // Dynamic routes get no static credit
|
|
53
|
+
}
|
|
54
|
+
return score + 1; // Static routes get the credit (highest priority)
|
|
49
55
|
}, 0);
|
|
50
56
|
};
|
|
51
57
|
/**
|
|
52
|
-
* Compares two routes for sorting
|
|
53
|
-
*
|
|
54
|
-
* If specificity is equal, sorts alphabetically by path.
|
|
58
|
+
* Compares two routes for sorting: higher specificity first (Static >
|
|
59
|
+
* Dynamic > Wildcard), ties alphabetically by path.
|
|
55
60
|
* @param a The first route to compare.
|
|
56
61
|
* @param b The second route to compare.
|
|
57
|
-
* @returns Negative if a comes
|
|
62
|
+
* @returns Negative if a comes first, positive if b does, zero if equal.
|
|
58
63
|
*/
|
|
59
64
|
export const compareRoutes = (a, b) => {
|
|
60
65
|
const aSpecificity = getRouteSpecificity(a.path);
|
|
@@ -66,14 +71,13 @@ export const compareRoutes = (a, b) => {
|
|
|
66
71
|
return a.path.localeCompare(b.path);
|
|
67
72
|
};
|
|
68
73
|
/**
|
|
69
|
-
* Collects all routes from the trie
|
|
74
|
+
* Collects all routes from the trie as `RouteDefinition` objects.
|
|
70
75
|
* @param node The current node in the trie.
|
|
71
76
|
* @param currentPath The current path being traversed.
|
|
72
77
|
* @param routes The array of collected routes.
|
|
73
|
-
* @returns
|
|
78
|
+
* @returns The collected routes.
|
|
74
79
|
*/
|
|
75
80
|
export function collectRoutes(node, currentPath = '', routes = []) {
|
|
76
|
-
// If this node has a route definition, add it
|
|
77
81
|
if (node.route) {
|
|
78
82
|
routes.push({
|
|
79
83
|
...node.route,
|
|
@@ -91,9 +95,28 @@ export function collectRoutes(node, currentPath = '', routes = []) {
|
|
|
91
95
|
}
|
|
92
96
|
// Traverse wildcard child if exists (lowest priority)
|
|
93
97
|
if (node.wildcardChild) {
|
|
94
|
-
// const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
|
|
95
98
|
const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
|
|
96
99
|
collectRoutes(node.wildcardChild, wildcardPath, routes);
|
|
97
100
|
}
|
|
98
101
|
return routes;
|
|
99
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Copies a per-method map (`schema.ts` / `openapi.ts` / `config.ts` exports)
|
|
105
|
+
* with uppercase method keys (`GET`) lowercased (`get`) for the validation
|
|
106
|
+
* compiler, OpenAPI generator and route compiler. Non-method keys (e.g.
|
|
107
|
+
* `coerce`) pass through; never mutates the input (module namespaces are
|
|
108
|
+
* frozen). Returns the input unchanged when it has no uppercase method key,
|
|
109
|
+
* so default-only configs keep their object identity.
|
|
110
|
+
*/
|
|
111
|
+
export function lowercaseMethodKeys(raw) {
|
|
112
|
+
const entries = Object.entries(raw);
|
|
113
|
+
if (!entries.some(([key]) => HTTP_METHODS.includes(key))) {
|
|
114
|
+
return raw;
|
|
115
|
+
}
|
|
116
|
+
const out = {};
|
|
117
|
+
for (const [key, value] of entries) {
|
|
118
|
+
const isMethod = HTTP_METHODS.includes(key);
|
|
119
|
+
out[isMethod ? key.toLowerCase() : key] = value;
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hot-path thenable probe used by the sync-first lifecycle stages.
|
|
3
|
+
*
|
|
4
|
+
* `await` on a synchronous value still costs a microtask; checking
|
|
5
|
+
* `typeof value.then === 'function'` first lets a step that returned a plain
|
|
6
|
+
* value continue without suspending.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isThenable(value: unknown): value is PromiseLike<unknown>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hot-path thenable probe used by the sync-first lifecycle stages.
|
|
3
|
+
*
|
|
4
|
+
* `await` on a synchronous value still costs a microtask; checking
|
|
5
|
+
* `typeof value.then === 'function'` first lets a step that returned a plain
|
|
6
|
+
* value continue without suspending.
|
|
7
|
+
*/
|
|
8
|
+
export function isThenable(value) {
|
|
9
|
+
return (value !== null &&
|
|
10
|
+
value !== undefined &&
|
|
11
|
+
typeof value.then === 'function');
|
|
12
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Portable constant-time string comparison (WinterCG-safe, no `node:crypto`).
|
|
3
|
+
*
|
|
4
|
+
* XORs UTF-8 bytes over the longer length, so comparison time does not depend
|
|
5
|
+
* on match position. Length is still observable via the iteration bound —
|
|
6
|
+
* acceptable for server-controlled credentials; equal-length values (e.g.
|
|
7
|
+
* hashed credentials) leak nothing.
|
|
8
|
+
*/
|
|
9
|
+
export declare function timingSafeEqual(a: string, b: string): boolean;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Portable constant-time string comparison (WinterCG-safe, no `node:crypto`).
|
|
3
|
+
*
|
|
4
|
+
* XORs UTF-8 bytes over the longer length, so comparison time does not depend
|
|
5
|
+
* on match position. Length is still observable via the iteration bound —
|
|
6
|
+
* acceptable for server-controlled credentials; equal-length values (e.g.
|
|
7
|
+
* hashed credentials) leak nothing.
|
|
8
|
+
*/
|
|
9
|
+
export function timingSafeEqual(a, b) {
|
|
10
|
+
const aBytes = new TextEncoder().encode(a);
|
|
11
|
+
const bBytes = new TextEncoder().encode(b);
|
|
12
|
+
const maxLen = Math.max(aBytes.length, bBytes.length);
|
|
13
|
+
let diff = aBytes.length ^ bBytes.length;
|
|
14
|
+
for (let i = 0; i < maxLen; i++) {
|
|
15
|
+
const av = i < aBytes.length ? aBytes[i] : 0;
|
|
16
|
+
const bv = i < bBytes.length ? bBytes[i] : 0;
|
|
17
|
+
diff |= av ^ bv;
|
|
18
|
+
}
|
|
19
|
+
return diff === 0;
|
|
20
|
+
}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import type { BurgerRequest } from '../types/index';
|
|
2
1
|
/**
|
|
3
|
-
* Extracts the pathname from a full URL string, removing query parameters
|
|
2
|
+
* Extracts the pathname from a full URL string, removing query parameters and
|
|
3
|
+
* fragments.
|
|
4
4
|
* @param url - The full URL string (e.g., "http://localhost:4000/api/users/123/profile?id=1")
|
|
5
5
|
* @returns The extracted pathname (e.g., "/api/users/123/profile")
|
|
6
6
|
*/
|
|
7
7
|
export declare function extractPathnameFromUrl(url: string): string;
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* @param baseSegmentCount - Number of segments before the wildcard (e.g., 3 for "/api/users/:userId/*")
|
|
9
|
+
* True when the pathname of a full URL string ends with `/`, without
|
|
10
|
+
* allocating the pathname. Needed where Bun's native wildcard handler does not
|
|
11
|
+
* expose `request.params['*']`.
|
|
13
12
|
*/
|
|
14
|
-
export declare function
|
|
13
|
+
export declare function urlPathnameEndsWithSlash(url: string): boolean;
|
|
@@ -1,66 +1,49 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Extracts the pathname from a full URL string, removing query parameters
|
|
2
|
+
* Extracts the pathname from a full URL string, removing query parameters and
|
|
3
|
+
* fragments.
|
|
3
4
|
* @param url - The full URL string (e.g., "http://localhost:4000/api/users/123/profile?id=1")
|
|
4
5
|
* @returns The extracted pathname (e.g., "/api/users/123/profile")
|
|
5
6
|
*/
|
|
6
7
|
export function extractPathnameFromUrl(url) {
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
//
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
8
|
+
// Where the authority ends. The charCode checks fast-path http/https
|
|
9
|
+
// instead of scanning for '://'.
|
|
10
|
+
const authorityEnd = url.charCodeAt(4) === 58 /* : */
|
|
11
|
+
? 7
|
|
12
|
+
: url.charCodeAt(5) === 58 /* : */
|
|
13
|
+
? 8
|
|
14
|
+
: url.indexOf('://') + 3;
|
|
15
|
+
// Path starts at the first "/" after the authority; no path segment
|
|
16
|
+
// falls back to index 0.
|
|
17
|
+
const found = url.indexOf('/', authorityEnd);
|
|
18
|
+
const pathStart = found === -1 ? 0 : found;
|
|
19
|
+
// Single scan for `?` or `#`. Raw URL strings may still carry a fragment
|
|
20
|
+
// even though the URL parser strips it.
|
|
21
|
+
for (let i = pathStart; i < url.length; i++) {
|
|
22
|
+
const code = url.charCodeAt(i);
|
|
23
|
+
if (code === 63 /* ? */ || code === 35 /* # */) {
|
|
24
|
+
return url.slice(pathStart, i);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return url.slice(pathStart);
|
|
21
28
|
}
|
|
22
29
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* @param baseSegmentCount - Number of segments before the wildcard (e.g., 3 for "/api/users/:userId/*")
|
|
30
|
+
* True when the pathname of a full URL string ends with `/`, without
|
|
31
|
+
* allocating the pathname. Needed where Bun's native wildcard handler does not
|
|
32
|
+
* expose `request.params['*']`.
|
|
27
33
|
*/
|
|
28
|
-
export function
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const wildcardParams = [];
|
|
41
|
-
let segmentCount = 0; // Counts how many segments we've seen
|
|
42
|
-
let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
|
|
43
|
-
// Loop through each character in the pathname
|
|
44
|
-
// When we hit "/" or end of string, we know we found a segment
|
|
45
|
-
for (let i = start; i <= pathname.length; i++) {
|
|
46
|
-
// Found end of a segment (either "/" or end of string)
|
|
47
|
-
if (i === pathname.length || pathname[i] === '/') {
|
|
48
|
-
// Make sure it's not an empty segment (from double slashes)
|
|
49
|
-
if (i > start) {
|
|
50
|
-
// Only save segments AFTER we've skipped the base segments
|
|
51
|
-
// Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
|
|
52
|
-
if (segmentCount >= baseSegmentCount) {
|
|
53
|
-
// Extract this segment from the pathname
|
|
54
|
-
// Example: pathname.substring(5, 13) might give "settings"
|
|
55
|
-
wildcardParams.push(pathname.substring(start, i));
|
|
56
|
-
}
|
|
57
|
-
segmentCount++; // Increment count for next segment
|
|
58
|
-
}
|
|
59
|
-
start = i + 1; // Move start position to character after "/"
|
|
60
|
-
}
|
|
34
|
+
export function urlPathnameEndsWithSlash(url) {
|
|
35
|
+
const authorityEnd = url.charCodeAt(4) === 58 /* : */
|
|
36
|
+
? 7
|
|
37
|
+
: url.charCodeAt(5) === 58 /* : */
|
|
38
|
+
? 8
|
|
39
|
+
: url.indexOf('://') + 3;
|
|
40
|
+
const found = url.indexOf('/', authorityEnd);
|
|
41
|
+
const pathStart = found === -1 ? 0 : found;
|
|
42
|
+
for (let i = pathStart; i < url.length; i++) {
|
|
43
|
+
const code = url.charCodeAt(i);
|
|
44
|
+
if (code === 63 /* ? */ || code === 35 /* # */) {
|
|
45
|
+
return url.charCodeAt(i - 1) === 47;
|
|
61
46
|
}
|
|
62
|
-
// Done! wildcardParams now contains only the wildcard segments
|
|
63
|
-
// Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
|
|
64
|
-
request.wildcardParams = wildcardParams;
|
|
65
47
|
}
|
|
48
|
+
return url.charCodeAt(url.length - 1) === 47;
|
|
66
49
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The validator adapter layer — the only place that decides which schema
|
|
3
|
+
* library a schema uses.
|
|
4
|
+
*
|
|
5
|
+
* Defines the `ValidatorAdapter` interface, detects which adapter a schema
|
|
6
|
+
* belongs to (Zod first, then Standard), and allows registering additional
|
|
7
|
+
* adapters. Detection runs when the app starts only; never when a request
|
|
8
|
+
* comes in. Schema-check logic lives in each adapter implementation.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
import type { SchemaInput, ValidationSlot, CompiledValidator } from './types.js';
|
|
12
|
+
/**
|
|
13
|
+
* A stable connector between BurgerAPI's request flow and a concrete schema
|
|
14
|
+
* library. The coordinator and cache depend only on this interface, never on
|
|
15
|
+
* a concrete library.
|
|
16
|
+
*/
|
|
17
|
+
export interface ValidatorAdapter {
|
|
18
|
+
/** Stable identity for a schema; drives cache sharing. */
|
|
19
|
+
identity(schema: SchemaInput): string;
|
|
20
|
+
/**
|
|
21
|
+
* Prepare a schema slot into a reusable `CompiledValidator`. The
|
|
22
|
+
* `validate` call is the sole runtime entry point.
|
|
23
|
+
*/
|
|
24
|
+
compile(schema: SchemaInput, slot: ValidationSlot): CompiledValidator;
|
|
25
|
+
/** Whether this adapter can handle the given schema. */
|
|
26
|
+
supports(schema: SchemaInput): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Whether a compiled validator for this schema is safe to cache and
|
|
29
|
+
* share. Adapters return false when the structural identity cannot
|
|
30
|
+
* capture the schema's runtime semantics (e.g. refinements with function
|
|
31
|
+
* checks, self-coercing schemas) — such schemas compile fresh per route.
|
|
32
|
+
*/
|
|
33
|
+
cacheable?(schema: SchemaInput): boolean;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* True when the value is a Zod 4 schema. Detection is structural — the `_zod`
|
|
37
|
+
* internals marker — so schemas from a second zod copy (a duplicate install)
|
|
38
|
+
* are recognized too, not only instances of this package's `z.ZodType`.
|
|
39
|
+
*/
|
|
40
|
+
export declare function isZodSchema(value: unknown): value is z.ZodTypeAny;
|
|
41
|
+
/** The Zod adapter registers itself here at module load. */
|
|
42
|
+
export declare function __setZodAdapter(adapter: ValidatorAdapter): void;
|
|
43
|
+
/** The Standard Schema adapter registers itself here at module load. */
|
|
44
|
+
export declare function __setStandardAdapter(adapter: ValidatorAdapter): void;
|
|
45
|
+
/** Register an additional adapter (checked after the built-in Zod check). */
|
|
46
|
+
export declare function registerAdapter(adapter: ValidatorAdapter): void;
|
|
47
|
+
/**
|
|
48
|
+
* Returns the adapter that should handle `schema`.
|
|
49
|
+
*
|
|
50
|
+
* Detection order: Zod brand first (default provider), then any registered
|
|
51
|
+
* adapter, then the built-in Standard Schema adapter. Throws on unknown
|
|
52
|
+
* schemas to fail fast at compile time — never a request-time surprise.
|
|
53
|
+
*/
|
|
54
|
+
export declare function detectAdapter(schema: SchemaInput): ValidatorAdapter;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The validator adapter layer — the only place that decides which schema
|
|
3
|
+
* library a schema uses.
|
|
4
|
+
*
|
|
5
|
+
* Defines the `ValidatorAdapter` interface, detects which adapter a schema
|
|
6
|
+
* belongs to (Zod first, then Standard), and allows registering additional
|
|
7
|
+
* adapters. Detection runs when the app starts only; never when a request
|
|
8
|
+
* comes in. Schema-check logic lives in each adapter implementation.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
/**
|
|
12
|
+
* True when the value is a Zod 4 schema. Detection is structural — the `_zod`
|
|
13
|
+
* internals marker — so schemas from a second zod copy (a duplicate install)
|
|
14
|
+
* are recognized too, not only instances of this package's `z.ZodType`.
|
|
15
|
+
*/
|
|
16
|
+
export function isZodSchema(value) {
|
|
17
|
+
if (typeof value !== 'object' || value === null)
|
|
18
|
+
return false;
|
|
19
|
+
const internals = value._zod;
|
|
20
|
+
return typeof internals === 'object' && internals !== null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* True when the value carries the Standard Schema v1 `~standard` contract.
|
|
24
|
+
* Some libraries make schemas callable, so functions count too.
|
|
25
|
+
*/
|
|
26
|
+
function isStandardSchema(value) {
|
|
27
|
+
return ((typeof value === 'object' || typeof value === 'function') &&
|
|
28
|
+
value !== null &&
|
|
29
|
+
'~standard' in value &&
|
|
30
|
+
typeof value['~standard']?.validate === 'function');
|
|
31
|
+
}
|
|
32
|
+
/** Registered additional adapters (checked after the built-in Zod check). */
|
|
33
|
+
const registered = [];
|
|
34
|
+
/** The Zod adapter singleton, set by the Zod adapter module on load. */
|
|
35
|
+
let zodAdapterInstance;
|
|
36
|
+
/** The Standard Schema adapter singleton, set on load. */
|
|
37
|
+
let standardAdapterInstance;
|
|
38
|
+
/** The Zod adapter registers itself here at module load. */
|
|
39
|
+
export function __setZodAdapter(adapter) {
|
|
40
|
+
zodAdapterInstance = adapter;
|
|
41
|
+
}
|
|
42
|
+
/** The Standard Schema adapter registers itself here at module load. */
|
|
43
|
+
export function __setStandardAdapter(adapter) {
|
|
44
|
+
standardAdapterInstance = adapter;
|
|
45
|
+
}
|
|
46
|
+
/** Register an additional adapter (checked after the built-in Zod check). */
|
|
47
|
+
export function registerAdapter(adapter) {
|
|
48
|
+
registered.push(adapter);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Returns the adapter that should handle `schema`.
|
|
52
|
+
*
|
|
53
|
+
* Detection order: Zod brand first (default provider), then any registered
|
|
54
|
+
* adapter, then the built-in Standard Schema adapter. Throws on unknown
|
|
55
|
+
* schemas to fail fast at compile time — never a request-time surprise.
|
|
56
|
+
*/
|
|
57
|
+
export function detectAdapter(schema) {
|
|
58
|
+
if (isZodSchema(schema) && zodAdapterInstance) {
|
|
59
|
+
return zodAdapterInstance;
|
|
60
|
+
}
|
|
61
|
+
for (const adapter of registered) {
|
|
62
|
+
if (adapter.supports(schema))
|
|
63
|
+
return adapter;
|
|
64
|
+
}
|
|
65
|
+
if (isStandardSchema(schema) && standardAdapterInstance) {
|
|
66
|
+
return standardAdapterInstance;
|
|
67
|
+
}
|
|
68
|
+
if (isStandardSchema(schema)) {
|
|
69
|
+
throw new Error('[burger-api] Standard Schema adapter is not loaded. ' +
|
|
70
|
+
'This is an internal wiring error (Standard Schema adapter missing).');
|
|
71
|
+
}
|
|
72
|
+
throw new Error('[burger-api] Unsupported schema: not a Zod schema and not a ' +
|
|
73
|
+
'Standard Schema (missing "~standard" contract). ' +
|
|
74
|
+
'Wrap the value with a supported provider.');
|
|
75
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Standard Schema adapter — supports Valibot/ArkType/`~standard`
|
|
3
|
+
* libraries with no framework change.
|
|
4
|
+
*
|
|
5
|
+
* Computes identity from the `~standard` contract and compiles into a
|
|
6
|
+
* `CompiledValidator` whose `validate` calls `schema['~standard'].validate`
|
|
7
|
+
* and normalizes the result into the common `ValidationResult` shape. Depends
|
|
8
|
+
* only on the `~standard` contract, never on a specific library.
|
|
9
|
+
*/
|
|
10
|
+
import type { ValidatorAdapter } from '../adapter.js';
|
|
11
|
+
export declare const StandardAdapter: ValidatorAdapter;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Standard Schema adapter — supports Valibot/ArkType/`~standard`
|
|
3
|
+
* libraries with no framework change.
|
|
4
|
+
*
|
|
5
|
+
* Computes identity from the `~standard` contract and compiles into a
|
|
6
|
+
* `CompiledValidator` whose `validate` calls `schema['~standard'].validate`
|
|
7
|
+
* and normalizes the result into the common `ValidationResult` shape. Depends
|
|
8
|
+
* only on the `~standard` contract, never on a specific library.
|
|
9
|
+
*/
|
|
10
|
+
/** Flattens a Standard Schema issue path into `(string | number)[]`. */
|
|
11
|
+
function normalizePath(path) {
|
|
12
|
+
if (!path)
|
|
13
|
+
return [];
|
|
14
|
+
return path.map((p) => typeof p === 'object' && p !== null && 'key' in p
|
|
15
|
+
? p.key
|
|
16
|
+
: p);
|
|
17
|
+
}
|
|
18
|
+
function normalizeIssues(issues) {
|
|
19
|
+
return issues.map((issue) => ({
|
|
20
|
+
path: normalizePath(issue.path),
|
|
21
|
+
message: issue.message,
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
export const StandardAdapter = {
|
|
25
|
+
identity(schema) {
|
|
26
|
+
const std = schema;
|
|
27
|
+
const vendor = std['~standard'].vendor ?? 'unknown';
|
|
28
|
+
// Fingerprint from the `~standard.types`, falling back to a stable
|
|
29
|
+
// stringification of the schema.
|
|
30
|
+
let fingerprint;
|
|
31
|
+
try {
|
|
32
|
+
const types = std['~standard'].types;
|
|
33
|
+
fingerprint = JSON.stringify(types ?? String(std));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
fingerprint = String(std);
|
|
37
|
+
}
|
|
38
|
+
return 'standard:' + vendor + ':' + fingerprint;
|
|
39
|
+
},
|
|
40
|
+
supports(schema) {
|
|
41
|
+
return ((typeof schema === 'object' || typeof schema === 'function') &&
|
|
42
|
+
schema !== null &&
|
|
43
|
+
'~standard' in schema &&
|
|
44
|
+
typeof schema['~standard']?.validate ===
|
|
45
|
+
'function');
|
|
46
|
+
},
|
|
47
|
+
/**
|
|
48
|
+
* Standard Schema vendors expose no reliable structural identity —
|
|
49
|
+
* `~standard.types` often serializes the same for different schemas, so
|
|
50
|
+
* cache sharing could validate a slot with the WRONG schema (silently
|
|
51
|
+
* stripping fields). Correctness first: always compile fresh; the cost is
|
|
52
|
+
* trivial.
|
|
53
|
+
*/
|
|
54
|
+
cacheable() {
|
|
55
|
+
return false;
|
|
56
|
+
},
|
|
57
|
+
compile(schema, slot) {
|
|
58
|
+
const std = schema;
|
|
59
|
+
const identity = this.identity(schema);
|
|
60
|
+
// `~standard.validate` may be sync or async; the pipeline validates
|
|
61
|
+
// synchronously per slot. Probe here so a bad schema fails fast at
|
|
62
|
+
// startup instead of throwing a 500 on the first matching request.
|
|
63
|
+
let isAsync = false;
|
|
64
|
+
try {
|
|
65
|
+
const probe = std['~standard'].validate(undefined);
|
|
66
|
+
if (probe instanceof Promise) {
|
|
67
|
+
isAsync = true;
|
|
68
|
+
probe.catch(() => { });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// A sync throw on the probe is fine — the real call re-runs it.
|
|
73
|
+
}
|
|
74
|
+
if (isAsync) {
|
|
75
|
+
throw new Error('[burger-api] Standard Schema validator for slot "' +
|
|
76
|
+
slot +
|
|
77
|
+
'" is async (`~standard.validate` returned a Promise). ' +
|
|
78
|
+
'BurgerAPI validation is synchronous; use a sync ' +
|
|
79
|
+
'`~standard` validator for request validation.');
|
|
80
|
+
}
|
|
81
|
+
const validate = (value) => {
|
|
82
|
+
const result = std['~standard'].validate(value);
|
|
83
|
+
if (result instanceof Promise) {
|
|
84
|
+
// Defensive: should never happen after the compile-time probe,
|
|
85
|
+
// but guard so we never return a Promise where a sync result is
|
|
86
|
+
// expected.
|
|
87
|
+
throw new Error('[burger-api] Standard Schema validator for slot "' +
|
|
88
|
+
slot +
|
|
89
|
+
'" returned a Promise at request time. Use a sync ' +
|
|
90
|
+
'`~standard` validator for request validation.');
|
|
91
|
+
}
|
|
92
|
+
if ('issues' in result && result.issues) {
|
|
93
|
+
return {
|
|
94
|
+
success: false,
|
|
95
|
+
issues: normalizeIssues(result.issues),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
return { success: true, data: result.value };
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
kind: 'standard',
|
|
102
|
+
slot,
|
|
103
|
+
identity,
|
|
104
|
+
validate,
|
|
105
|
+
// `~standard.coercible` marks schemas that transform their own input
|
|
106
|
+
// during validate — framework coercion must not run on them.
|
|
107
|
+
coercible: std['~standard'].coercible === true,
|
|
108
|
+
};
|
|
109
|
+
},
|
|
110
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Zod adapter — the default schema provider for BurgerAPI.
|
|
3
|
+
*
|
|
4
|
+
* Computes a stable identity, compiles a Zod schema into a reusable
|
|
5
|
+
* `CompiledValidator`, and normalizes Zod `issues` into `ValidationIssue[]`.
|
|
6
|
+
* Delegates validation to `safeParse` and leaves coercion to the coercer.
|
|
7
|
+
*/
|
|
8
|
+
import type { ValidatorAdapter } from '../adapter.js';
|
|
9
|
+
export declare const ZodAdapter: ValidatorAdapter;
|