burger-api 0.9.6 → 1.0.0-beta
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 +201 -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 +47 -0
- package/dist/src/errors/http-error.js +146 -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 +263 -50
- package/dist/src/index.js +919 -332
- 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 +817 -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 +201 -0
- package/dist/src/router/router.js +600 -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 +172 -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 +2 -9
- package/dist/src/utils/wildcard.js +20 -58
- 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 +79 -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 +219 -0
- package/dist/src/ws/adapter.js +623 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +156 -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 +81 -0
- package/dist/src/ws/platform.js +113 -0
- package/dist/src/ws/router.d.ts +48 -0
- package/dist/src/ws/router.js +174 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +193 -0
- package/dist/src/ws/types.d.ts +380 -0
- package/dist/src/ws/types.js +213 -0
- package/package.json +72 -59
- 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
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineRoute` and `defineHooks`: type helpers that infer `ctx` from a schema.
|
|
3
|
+
* No runtime behavior; the schema argument keeps types and values in sync.
|
|
4
|
+
*/
|
|
5
|
+
import type { BurgerContext, BurgerValidated } from '../context/context.js';
|
|
6
|
+
import type { InferValidated } from '../types/inference.js';
|
|
7
|
+
import type { MethodSchema, RequestHandler } from '../types/index.js';
|
|
8
|
+
import type { ErrorHook, ForwardHookResult, ResponseHookResult, RouteHooks } from '../lifecycle/types.js';
|
|
9
|
+
/**
|
|
10
|
+
* Defines a route handler whose `ctx.validated` is typed from `schema`.
|
|
11
|
+
* Returns `handler` unchanged.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { defineRoute } from 'burger-api';
|
|
15
|
+
* import { GET as GetSchema } from './schema';
|
|
16
|
+
*
|
|
17
|
+
* export const GET = defineRoute(GetSchema, (ctx) => {
|
|
18
|
+
* const { name } = ctx.validated.query; // typed from the schema
|
|
19
|
+
* return Response.json({ message: `Hello, ${name}!` });
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export declare function defineRoute<T extends MethodSchema>(schema: T, handler: (ctx: BurgerContext<T>) => Promise<Response> | Response): RequestHandler;
|
|
24
|
+
/**
|
|
25
|
+
* The `ctx` a {@link defineHooks} hook receives. Unlike a handler (which
|
|
26
|
+
* belongs to ONE method), route hooks run for EVERY method of the route, so
|
|
27
|
+
* each `ctx.validated` slot may be `undefined` (`POST`'s `body` is absent on
|
|
28
|
+
* a `GET`). After validation `ctx.validated` is always an object, so
|
|
29
|
+
* `ctx.validated.query?.q` needs no extra guard.
|
|
30
|
+
*/
|
|
31
|
+
export type HookContext<T> = Omit<BurgerContext<T>, 'validated'> & {
|
|
32
|
+
validated: Partial<InferValidated<T>> & BurgerValidated;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* `transform` and `onError` may run before validation (`onError` also for
|
|
36
|
+
* a validation failure), so `ctx.validated` itself may be `undefined`.
|
|
37
|
+
*/
|
|
38
|
+
export type PreValidationHookContext<T> = Omit<BurgerContext<T>, 'validated'> & {
|
|
39
|
+
validated: (Partial<InferValidated<T>> & BurgerValidated) | undefined;
|
|
40
|
+
};
|
|
41
|
+
type TypedForwardHook<T> = (ctx: HookContext<T>) => ForwardHookResult | Promise<ForwardHookResult>;
|
|
42
|
+
type TypedResponseHook<T> = (ctx: HookContext<T>) => ResponseHookResult | Promise<ResponseHookResult>;
|
|
43
|
+
type TypedErrorHook<T> = (error: Error, ctx: PreValidationHookContext<T>) => ReturnType<ErrorHook>;
|
|
44
|
+
/**
|
|
45
|
+
* The `hooks.ts` counterpart to {@link defineRoute}'s handler typing: same
|
|
46
|
+
* field shapes as {@link RouteHooks}, with `ctx` bound to the route's schema
|
|
47
|
+
* (every validated slot possibly `undefined` — see {@link HookContext}).
|
|
48
|
+
*/
|
|
49
|
+
export interface TypedRouteHooks<T> {
|
|
50
|
+
beforeRoute?: TypedForwardHook<T> | TypedForwardHook<T>[];
|
|
51
|
+
afterRoute?: TypedResponseHook<T> | TypedResponseHook<T>[];
|
|
52
|
+
mapResponse?: TypedResponseHook<T> | TypedResponseHook<T>[];
|
|
53
|
+
onError?: TypedErrorHook<T> | TypedErrorHook<T>[];
|
|
54
|
+
transform?: Record<string, (ctx: PreValidationHookContext<T>) => unknown>;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Defines route hooks whose `ctx.validated` is typed from `schema`.
|
|
58
|
+
* Returns `hooks` unchanged.
|
|
59
|
+
*
|
|
60
|
+
* ```ts
|
|
61
|
+
* export const { beforeRoute } = defineHooks(GetSchema, {
|
|
62
|
+
* beforeRoute: (ctx) => { ctx.validated?.query; },
|
|
63
|
+
* });
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
export declare function defineHooks<T extends MethodSchema>(schema: T, hooks: TypedRouteHooks<T>): RouteHooks;
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineRoute` and `defineHooks`: type helpers that infer `ctx` from a schema.
|
|
3
|
+
* No runtime behavior; the schema argument keeps types and values in sync.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Defines a route handler whose `ctx.validated` is typed from `schema`.
|
|
7
|
+
* Returns `handler` unchanged.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { defineRoute } from 'burger-api';
|
|
11
|
+
* import { GET as GetSchema } from './schema';
|
|
12
|
+
*
|
|
13
|
+
* export const GET = defineRoute(GetSchema, (ctx) => {
|
|
14
|
+
* const { name } = ctx.validated.query; // typed from the schema
|
|
15
|
+
* return Response.json({ message: `Hello, ${name}!` });
|
|
16
|
+
* });
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export function defineRoute(schema, handler) {
|
|
20
|
+
return handler;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Defines route hooks whose `ctx.validated` is typed from `schema`.
|
|
24
|
+
* Returns `hooks` unchanged.
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* export const { beforeRoute } = defineHooks(GetSchema, {
|
|
28
|
+
* beforeRoute: (ctx) => { ctx.validated?.query; },
|
|
29
|
+
* });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export function defineHooks(schema, hooks) {
|
|
33
|
+
return hooks;
|
|
34
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Router } from './router.js';
|
|
2
|
+
export { RouterCompiler } from './compiler.js';
|
|
3
|
+
export { Trie } from './trie.js';
|
|
4
|
+
export { StaticMap } from './static-map.js';
|
|
5
|
+
export { AllowCache } from './allow-cache.js';
|
|
6
|
+
export type { CompiledHandler, CompiledRoute, CompiledRouter, RouterConfig, } from './types.js';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ContextInit } from '../context/types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Web-Standard param extraction for native route dispatch.
|
|
4
|
+
*
|
|
5
|
+
* Bun's native `routes` map matches a pattern but does not expose extracted
|
|
6
|
+
* params, so this derives the same `ContextInit` the trie would produce from
|
|
7
|
+
* the `Request` URL — identical behavior, and the logic stays
|
|
8
|
+
* runtime-agnostic (WinterCG). Non-Bun adapters dispatch through
|
|
9
|
+
* `Router.fetch` + trie and never use it.
|
|
10
|
+
*
|
|
11
|
+
* The pattern's segment layout is compiled once per route
|
|
12
|
+
* (`compilePatternSegments`); request handling does one URL scan and decodes
|
|
13
|
+
* only `%`-bearing segments.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Compile-time pattern layout: which pattern segments are params and where
|
|
17
|
+
* the wildcard sits. Built once per route (never per request).
|
|
18
|
+
*/
|
|
19
|
+
export interface CompiledPatternSegments {
|
|
20
|
+
/** Param name per pattern segment (`undefined` for static / wildcard). */
|
|
21
|
+
names: (string | undefined)[];
|
|
22
|
+
/** Index of the `*` pattern segment, or `-1`. */
|
|
23
|
+
wildcardIndex: number;
|
|
24
|
+
}
|
|
25
|
+
/** Compiles a route pattern (e.g. `/users/:id/*`) into its segment layout. */
|
|
26
|
+
export declare function compilePatternSegments(pattern: string): CompiledPatternSegments;
|
|
27
|
+
/**
|
|
28
|
+
* Builds the `ContextInit` (params / wildcardParams / route) for a request
|
|
29
|
+
* Bun dispatched to a native `:param` or `*` route. `pattern` is the
|
|
30
|
+
* route-definition path (e.g. `/users/:id`, `/files/*`); `compiled` is the
|
|
31
|
+
* layout produced by {@link compilePatternSegments} at route-compile time.
|
|
32
|
+
*/
|
|
33
|
+
export declare function extractCtxInitWithSegments(request: Request, pattern: string, compiled: CompiledPatternSegments): ContextInit;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { extractPathnameFromUrl } from '../utils/wildcard.js';
|
|
2
|
+
import { ROUTE_CONSTANTS } from '../utils/routing.js';
|
|
3
|
+
/** Compiles a route pattern (e.g. `/users/:id/*`) into its segment layout. */
|
|
4
|
+
export function compilePatternSegments(pattern) {
|
|
5
|
+
const raw = pattern.split('/');
|
|
6
|
+
// Drop the leading '' before the first '/'.
|
|
7
|
+
const names = new Array(raw.length > 0 ? raw.length - 1 : 0);
|
|
8
|
+
let wildcardIndex = -1;
|
|
9
|
+
for (let i = 1; i < raw.length; i++) {
|
|
10
|
+
const segment = raw[i];
|
|
11
|
+
if (segment === ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX) {
|
|
12
|
+
wildcardIndex = i - 1;
|
|
13
|
+
}
|
|
14
|
+
else if (segment.charCodeAt(0) === 58 /* ':' — DYNAMIC_SEGMENT_PREFIX */) {
|
|
15
|
+
names[i - 1] = segment.slice(1);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return { names, wildcardIndex };
|
|
19
|
+
}
|
|
20
|
+
/** Decodes a path segment only when it actually carries a percent escape. */
|
|
21
|
+
function decodeSegment(segment) {
|
|
22
|
+
if (segment === '' || segment.indexOf('%') === -1)
|
|
23
|
+
return segment;
|
|
24
|
+
try {
|
|
25
|
+
return decodeURIComponent(segment);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return segment;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Splits a pathname into segments, preserving a single trailing empty segment
|
|
33
|
+
* when the path ends with `/` (so `/users/` yields `["users", ""]` and a
|
|
34
|
+
* `:param` captures the empty value, matching the trie).
|
|
35
|
+
*/
|
|
36
|
+
function splitPath(pathname, out) {
|
|
37
|
+
let start = pathname.charCodeAt(0) === 47 /* '/' */ ? 1 : 0;
|
|
38
|
+
let count = 0;
|
|
39
|
+
for (let i = start; i < pathname.length; i++) {
|
|
40
|
+
if (pathname.charCodeAt(i) === 47 /* '/' */) {
|
|
41
|
+
out[count++] = pathname.slice(start, i);
|
|
42
|
+
start = i + 1;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (start < pathname.length || pathname.length > 1) {
|
|
46
|
+
out[count++] = pathname.slice(start);
|
|
47
|
+
}
|
|
48
|
+
out.length = count;
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Builds the `ContextInit` (params / wildcardParams / route) for a request
|
|
53
|
+
* Bun dispatched to a native `:param` or `*` route. `pattern` is the
|
|
54
|
+
* route-definition path (e.g. `/users/:id`, `/files/*`); `compiled` is the
|
|
55
|
+
* layout produced by {@link compilePatternSegments} at route-compile time.
|
|
56
|
+
*/
|
|
57
|
+
export function extractCtxInitWithSegments(request, pattern, compiled) {
|
|
58
|
+
const pathname = extractPathnameFromUrl(request.url);
|
|
59
|
+
const pathSegments = [];
|
|
60
|
+
splitPath(pathname, pathSegments);
|
|
61
|
+
const names = compiled.names;
|
|
62
|
+
const wildcardIndex = compiled.wildcardIndex;
|
|
63
|
+
let params;
|
|
64
|
+
for (let i = 0; i < names.length; i++) {
|
|
65
|
+
const name = names[i];
|
|
66
|
+
if (name === undefined)
|
|
67
|
+
continue;
|
|
68
|
+
if (params === undefined)
|
|
69
|
+
params = {};
|
|
70
|
+
// A pattern segment without a URL segment captures the empty value
|
|
71
|
+
// (matches the trie's `/users/` → `:id === ""` behavior).
|
|
72
|
+
const raw = pathSegments[i];
|
|
73
|
+
params[name] = raw === undefined ? '' : decodeSegment(raw);
|
|
74
|
+
}
|
|
75
|
+
const ctx = { route: { path: pathname, pattern } };
|
|
76
|
+
if (params !== undefined)
|
|
77
|
+
ctx.params = params;
|
|
78
|
+
if (wildcardIndex !== -1) {
|
|
79
|
+
const count = pathSegments.length - wildcardIndex;
|
|
80
|
+
const wildcardParams = new Array(count > 0 ? count : 0);
|
|
81
|
+
for (let i = 0; i < count; i++) {
|
|
82
|
+
wildcardParams[i] = decodeSegment(pathSegments[wildcardIndex + i]);
|
|
83
|
+
}
|
|
84
|
+
ctx.wildcardParams = wildcardParams;
|
|
85
|
+
}
|
|
86
|
+
return ctx;
|
|
87
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { CompiledHandler } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* RegExp matcher for the dynamic (`:param` / `*`) route set.
|
|
4
|
+
*
|
|
5
|
+
* The trie stays the reference; this is an opt-in replacement for its
|
|
6
|
+
* dispatch role on runtimes without a native pattern router (WinterCG).
|
|
7
|
+
*
|
|
8
|
+
* - Numeric capture groups, never named: two routes may reuse a param name.
|
|
9
|
+
* - A wrapper group per alternative identifies which branch matched (a
|
|
10
|
+
* base-path wildcard hit leaves all inner captures undefined).
|
|
11
|
+
* - Two tiers preserve priority: param routes first, wildcard routes only
|
|
12
|
+
* when the param tier misses, matching the trie's `param > wildcard`
|
|
13
|
+
* fallback. Within a tier, alternatives are ordered by specificity.
|
|
14
|
+
* - Segment-exact `[^/]*` captures reproduce the trie's trailing-slash
|
|
15
|
+
* semantics (`/users/` → `:id === ""`).
|
|
16
|
+
* - Oversized route sets return `null` from the builder and stay on the trie.
|
|
17
|
+
*/
|
|
18
|
+
export interface RegexRouteEntry {
|
|
19
|
+
/** Route-definition path (internal format: `:param` / `*`). */
|
|
20
|
+
path: string;
|
|
21
|
+
handler: CompiledHandler;
|
|
22
|
+
methods: Set<string>;
|
|
23
|
+
isWildcard: boolean;
|
|
24
|
+
}
|
|
25
|
+
export interface RegexMatch {
|
|
26
|
+
handler: CompiledHandler;
|
|
27
|
+
methods: Set<string>;
|
|
28
|
+
params: Record<string, string>;
|
|
29
|
+
wildcardParams?: string[];
|
|
30
|
+
isWildcard: boolean;
|
|
31
|
+
pattern: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Builds the matcher from the dynamic route set.
|
|
35
|
+
*
|
|
36
|
+
* @param order optional authoritative pattern order (from
|
|
37
|
+
* `Trie.orderedPatterns()`); when supplied, alternatives keep this
|
|
38
|
+
* exact sequence. When omitted, the specificity heuristic orders them.
|
|
39
|
+
* @returns a matcher function, or `null` when the route set should stay on
|
|
40
|
+
* the trie (empty set, size cap exceeded, or unusable patterns).
|
|
41
|
+
*/
|
|
42
|
+
export declare function buildRegexMatcher(entries: RegexRouteEntry[], order?: string[]): ((path: string) => RegexMatch | null) | null;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { ROUTE_CONSTANTS } from '../utils/routing.js';
|
|
2
|
+
/** Hard limits that trigger a graceful fall back to the trie. */
|
|
3
|
+
const MAX_ROUTES = 5000;
|
|
4
|
+
const MAX_SOURCE_LENGTH = 100_000;
|
|
5
|
+
/**
|
|
6
|
+
* Builds the matcher from the dynamic route set.
|
|
7
|
+
*
|
|
8
|
+
* @param order optional authoritative pattern order (from
|
|
9
|
+
* `Trie.orderedPatterns()`); when supplied, alternatives keep this
|
|
10
|
+
* exact sequence. When omitted, the specificity heuristic orders them.
|
|
11
|
+
* @returns a matcher function, or `null` when the route set should stay on
|
|
12
|
+
* the trie (empty set, size cap exceeded, or unusable patterns).
|
|
13
|
+
*/
|
|
14
|
+
export function buildRegexMatcher(entries, order) {
|
|
15
|
+
if (entries.length === 0 || entries.length > MAX_ROUTES)
|
|
16
|
+
return null;
|
|
17
|
+
const tier = compileTier(entries, order);
|
|
18
|
+
if (!tier)
|
|
19
|
+
return null;
|
|
20
|
+
if (tier.regex.source.length > MAX_SOURCE_LENGTH)
|
|
21
|
+
return null;
|
|
22
|
+
// Trie semantics: "/" is the zero-segment path. A single leading param
|
|
23
|
+
// (`/:id`) must NOT capture it — only an explicit root route may match.
|
|
24
|
+
const hasRootEntry = entries.some((e) => splitPattern(e.path).length === 0);
|
|
25
|
+
return (path) => {
|
|
26
|
+
if (path === '/' && !hasRootEntry)
|
|
27
|
+
return null;
|
|
28
|
+
return execTier(tier, path);
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function compileTier(entries, order) {
|
|
32
|
+
if (entries.length === 0)
|
|
33
|
+
return null;
|
|
34
|
+
const byPath = new Map(entries.map((e) => [e.path, e]));
|
|
35
|
+
let alternatives;
|
|
36
|
+
if (order && order.length > 0) {
|
|
37
|
+
alternatives = [];
|
|
38
|
+
for (const path of order) {
|
|
39
|
+
const entry = byPath.get(path);
|
|
40
|
+
if (entry)
|
|
41
|
+
alternatives.push(compileAlternative(entry));
|
|
42
|
+
}
|
|
43
|
+
// Patterns present in entries but missing from the order (should
|
|
44
|
+
// not happen — both derive from the same compile pass) go last.
|
|
45
|
+
for (const entry of entries) {
|
|
46
|
+
if (!order.includes(entry.path)) {
|
|
47
|
+
alternatives.push(compileAlternative(entry));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
alternatives = entries
|
|
53
|
+
.map((entry) => compileAlternative(entry))
|
|
54
|
+
.sort(compareAlternatives);
|
|
55
|
+
}
|
|
56
|
+
const source = alternatives.map((a) => a.source).join('|');
|
|
57
|
+
return { regex: new RegExp(source), alternatives };
|
|
58
|
+
}
|
|
59
|
+
function compileAlternative(entry) {
|
|
60
|
+
const segments = splitPattern(entry.path);
|
|
61
|
+
const groupNames = [];
|
|
62
|
+
let body = '';
|
|
63
|
+
// A literal root route ("/") matches the bare slash — the trie reaches
|
|
64
|
+
// its root-node handler for the zero-segment path.
|
|
65
|
+
if (segments.length === 0) {
|
|
66
|
+
return { source: '(^/$)', groupNames, entry };
|
|
67
|
+
}
|
|
68
|
+
for (let i = 0; i < segments.length; i++) {
|
|
69
|
+
const seg = segments[i];
|
|
70
|
+
const lastWildcard = i === segments.length - 1 &&
|
|
71
|
+
(seg === ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX ||
|
|
72
|
+
seg.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX));
|
|
73
|
+
if (lastWildcard) {
|
|
74
|
+
// Wildcard: optional `/rest`. Keeping the leading slash inside
|
|
75
|
+
// the capture preserves the trailing-slash distinction
|
|
76
|
+
// (`/files` → undefined, `/files/` → '/').
|
|
77
|
+
body += '(/.*)?';
|
|
78
|
+
groupNames.push('*');
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
if (seg.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
|
|
82
|
+
body += '/([^/]*)';
|
|
83
|
+
groupNames.push(seg.slice(1));
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
body += '/' + escapeLiteral(seg);
|
|
87
|
+
}
|
|
88
|
+
// One wrapper group per alternative identifies the matching branch.
|
|
89
|
+
return { source: `(^${body}$)`, groupNames, entry };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Ascending sort key — lower is tried earlier. Deepest literal anchoring
|
|
93
|
+
* wins, then fewer dynamics, then a later first-dynamic position
|
|
94
|
+
* (`/x/b/:c` before `/x/:a/y`), then params before wildcards.
|
|
95
|
+
*/
|
|
96
|
+
function compareAlternatives(a, b) {
|
|
97
|
+
const ka = specificityKey(a);
|
|
98
|
+
const kb = specificityKey(b);
|
|
99
|
+
for (let i = 0; i < 4; i++) {
|
|
100
|
+
if (ka[i] !== kb[i])
|
|
101
|
+
return ka[i] - kb[i];
|
|
102
|
+
}
|
|
103
|
+
// Deterministic tiebreak for otherwise-equal shapes.
|
|
104
|
+
return a.entry.path < b.entry.path ? -1 : a.entry.path > b.entry.path ? 1 : 0;
|
|
105
|
+
}
|
|
106
|
+
function specificityKey(a) {
|
|
107
|
+
const segs = splitPattern(a.entry.path);
|
|
108
|
+
let paramCount = 0;
|
|
109
|
+
let wildcardCount = 0;
|
|
110
|
+
let firstDynamic = Number.MAX_SAFE_INTEGER;
|
|
111
|
+
for (let i = 0; i < segs.length; i++) {
|
|
112
|
+
const s = segs[i];
|
|
113
|
+
if (s.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
|
|
114
|
+
wildcardCount++;
|
|
115
|
+
paramCount++;
|
|
116
|
+
if (firstDynamic === Number.MAX_SAFE_INTEGER)
|
|
117
|
+
firstDynamic = i;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (s.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
|
|
121
|
+
paramCount++;
|
|
122
|
+
if (firstDynamic === Number.MAX_SAFE_INTEGER)
|
|
123
|
+
firstDynamic = i;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return [
|
|
127
|
+
-(segs.length - paramCount),
|
|
128
|
+
paramCount,
|
|
129
|
+
firstDynamic === Number.MAX_SAFE_INTEGER
|
|
130
|
+
? Number.MAX_SAFE_INTEGER
|
|
131
|
+
: -firstDynamic,
|
|
132
|
+
wildcardCount,
|
|
133
|
+
];
|
|
134
|
+
}
|
|
135
|
+
function execTier(tier, path) {
|
|
136
|
+
const match = tier.regex.exec(path);
|
|
137
|
+
if (!match)
|
|
138
|
+
return null;
|
|
139
|
+
// Locate the matched alternative via its wrapper group.
|
|
140
|
+
let absStart = 1; // match[0] occupies index 0
|
|
141
|
+
const alternatives = tier.alternatives;
|
|
142
|
+
for (let i = 0; i < alternatives.length; i++) {
|
|
143
|
+
const candidate = alternatives[i];
|
|
144
|
+
const width = candidate.groupNames.length + 1; // inner + wrapper
|
|
145
|
+
if (match[absStart] !== undefined) {
|
|
146
|
+
return materialize(candidate, match, absStart);
|
|
147
|
+
}
|
|
148
|
+
absStart += width;
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
function materialize(alt, match, absStart) {
|
|
153
|
+
const params = {};
|
|
154
|
+
let rawWildcard;
|
|
155
|
+
for (let i = 0; i < alt.groupNames.length; i++) {
|
|
156
|
+
const name = alt.groupNames[i];
|
|
157
|
+
const value = match[absStart + 1 + i];
|
|
158
|
+
if (value === undefined)
|
|
159
|
+
continue;
|
|
160
|
+
if (name === '*') {
|
|
161
|
+
rawWildcard = value;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
params[name] = safeDecode(value);
|
|
165
|
+
}
|
|
166
|
+
let wildcardParams;
|
|
167
|
+
if (rawWildcard !== undefined) {
|
|
168
|
+
// rawWildcard keeps its leading '/' ('/a/b'); normalize exactly like
|
|
169
|
+
// the trie: base hit → [], '/files/' → [''], '/files/a/' → ['a',''].
|
|
170
|
+
wildcardParams = splitWildcard(rawWildcard);
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
handler: alt.entry.handler,
|
|
174
|
+
methods: alt.entry.methods,
|
|
175
|
+
params,
|
|
176
|
+
wildcardParams,
|
|
177
|
+
isWildcard: rawWildcard !== undefined || alt.entry.isWildcard,
|
|
178
|
+
pattern: alt.entry.path,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function splitPattern(path) {
|
|
182
|
+
return path.split('/').slice(1).filter((s) => s !== '');
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Splits a raw wildcard capture (`/a/b`, `/`, `/files/`) into decoded
|
|
186
|
+
* segments without `split().map()` per request; a trailing empty segment is
|
|
187
|
+
* preserved exactly like `String.split('/')`.
|
|
188
|
+
*/
|
|
189
|
+
function splitWildcard(rawWildcard) {
|
|
190
|
+
if (rawWildcard === '/')
|
|
191
|
+
return [''];
|
|
192
|
+
const body = rawWildcard.slice(1);
|
|
193
|
+
const out = [];
|
|
194
|
+
let start = 0;
|
|
195
|
+
for (let i = 0; i < body.length; i++) {
|
|
196
|
+
if (body.charCodeAt(i) === 47 /* '/' */) {
|
|
197
|
+
out.push(safeDecode(body.slice(start, i)));
|
|
198
|
+
start = i + 1;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
out.push(safeDecode(body.slice(start)));
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
function escapeLiteral(segment) {
|
|
205
|
+
return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
206
|
+
}
|
|
207
|
+
function safeDecode(segment) {
|
|
208
|
+
if (segment === '' || segment.indexOf('%') === -1)
|
|
209
|
+
return segment;
|
|
210
|
+
try {
|
|
211
|
+
return decodeURIComponent(segment);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return segment;
|
|
215
|
+
}
|
|
216
|
+
}
|