burger-api 0.9.7 → 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 -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
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { freezeRouteAccessInfo } from '../context/route-access.js';
|
|
2
|
+
/**
|
|
3
|
+
* `RouteAccessAnalyzer` — an optional, compile-time-only static analyzer.
|
|
4
|
+
*
|
|
5
|
+
* Inspects a route's handler + hook source (`Function.prototype.toString()`)
|
|
6
|
+
* and returns a frozen `RouteAccessInfo` hint of which `BurgerContext` fields
|
|
7
|
+
* the route touches. Any failure degrades to the safe "unknown" default
|
|
8
|
+
* (every field treated as used), so a wrong verdict can never hide a field
|
|
9
|
+
* the route actually reads.
|
|
10
|
+
*
|
|
11
|
+
* A "known" result requires every function's first parameter to be a plain
|
|
12
|
+
* identifier used only as direct member access (`ctx.field` / `ctx['field']`),
|
|
13
|
+
* never bare (`helper(ctx)`, `...ctx`). `debug: true` skips analysis.
|
|
14
|
+
*/
|
|
15
|
+
const FIELD_KEYS = [
|
|
16
|
+
'params',
|
|
17
|
+
'query',
|
|
18
|
+
'headers',
|
|
19
|
+
'json',
|
|
20
|
+
'validated',
|
|
21
|
+
'set',
|
|
22
|
+
'route',
|
|
23
|
+
'wildcardParams',
|
|
24
|
+
];
|
|
25
|
+
const HOOK_STAGES = [
|
|
26
|
+
'beforeRoute',
|
|
27
|
+
'afterRoute',
|
|
28
|
+
'mapResponse',
|
|
29
|
+
'onError',
|
|
30
|
+
];
|
|
31
|
+
/**
|
|
32
|
+
* Strips block (`/* *\/`) and line (`//`) comments so that field tokens inside
|
|
33
|
+
* comments are not mistaken for live access.
|
|
34
|
+
*/
|
|
35
|
+
function stripComments(source) {
|
|
36
|
+
// Block comments first, then line comments. Replace with a space (preserving
|
|
37
|
+
// token boundaries) rather than removing, so `a/* x */.query` doesn't merge.
|
|
38
|
+
let out = source.replace(/\/\*[\s\S]*?\*\//g, ' ');
|
|
39
|
+
out = out.replace(/\/\/[^\n]*/g, ' ');
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Detects a `field` reference in source text, covering both member access
|
|
44
|
+
* (`.field`) and computed/bracket access (`['field']` / `["field"]`).
|
|
45
|
+
*/
|
|
46
|
+
function referencesField(source, field) {
|
|
47
|
+
const dot = new RegExp(`\\.\\s*${field}\\b`);
|
|
48
|
+
const bracket = new RegExp(`\\[\\s*['"]\\s*${field}\\s*['"]\\s*\\]`);
|
|
49
|
+
return dot.test(source) || bracket.test(source);
|
|
50
|
+
}
|
|
51
|
+
function safeToString(fn) {
|
|
52
|
+
try {
|
|
53
|
+
return typeof fn === 'function' ? fn.toString() : '';
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return '';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const ARROW_PARAMS = /^(?:async\s+)?(?:\(([^()]*)\)|([\w$]+))\s*=>/;
|
|
60
|
+
const FUNCTION_PARAMS = /^(?:async\s+)?function(?:\s+[\w$]+)?\s*\(([^()]*)\)/;
|
|
61
|
+
const METHOD_PARAMS = /^(?:async\s+)?(?:[\w$]+)\s*\(([^()]*)\)\s*\{/;
|
|
62
|
+
const FIRST_IDENTIFIER = /[\w$]+/;
|
|
63
|
+
/**
|
|
64
|
+
* Conservative patterns kept as an extra gate: they catch aliasing of a
|
|
65
|
+
* context variable that was never a parameter (a closure captured in
|
|
66
|
+
* another module, or `req` referenced without being declared locally).
|
|
67
|
+
*/
|
|
68
|
+
function isLegacyAmbiguous(source) {
|
|
69
|
+
// `const r = req` / `let r = req` / `var r = req` — aliasing the request.
|
|
70
|
+
if (/\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*req\b/.test(source)) {
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
// Plain reassignment `r = req` (not a comparison / function call).
|
|
74
|
+
if (/\b[A-Za-z_$][\w$]*\s*=\s*req\b/.test(source))
|
|
75
|
+
return true;
|
|
76
|
+
// Computed member access other than a quoted literal: `req[x]` / `req[`var`]`.
|
|
77
|
+
if (/\brew\s*\[\s*(?!['"`])/.test(source))
|
|
78
|
+
return true;
|
|
79
|
+
// Spread / rest: `...req`.
|
|
80
|
+
if (/\brew\s*\.\.\./.test(source))
|
|
81
|
+
return true;
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Scans ONE function's source and records the fields it reads. Returns `false`
|
|
86
|
+
* when the function cannot be proven safe to specialize (context escapes,
|
|
87
|
+
* destructured parameter, unrecognized source shape, native code), in which
|
|
88
|
+
* case the caller marks the whole route `unknown`.
|
|
89
|
+
*/
|
|
90
|
+
function scanFunction(fn, accessed) {
|
|
91
|
+
const literal = stripComments(safeToString(fn));
|
|
92
|
+
if (literal === '')
|
|
93
|
+
return true;
|
|
94
|
+
if (literal.includes('[native code]'))
|
|
95
|
+
return false;
|
|
96
|
+
let params;
|
|
97
|
+
let bodyStart = -1;
|
|
98
|
+
const arrow = ARROW_PARAMS.exec(literal);
|
|
99
|
+
if (arrow) {
|
|
100
|
+
params = arrow[1] ?? arrow[2] ?? '';
|
|
101
|
+
bodyStart = arrow[0].length;
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
const fnMatch = FUNCTION_PARAMS.exec(literal);
|
|
105
|
+
if (fnMatch) {
|
|
106
|
+
params = fnMatch[1] ?? '';
|
|
107
|
+
bodyStart = literal.indexOf('{', fnMatch[0].length);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const methodMatch = METHOD_PARAMS.exec(literal);
|
|
111
|
+
if (methodMatch) {
|
|
112
|
+
params = methodMatch[1] ?? '';
|
|
113
|
+
bodyStart = literal.indexOf('{', methodMatch[0].length - 1);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (params === undefined || bodyStart === -1)
|
|
118
|
+
return false;
|
|
119
|
+
const trimmedParams = params.trim();
|
|
120
|
+
// Destructured / rest / default-value parameter patterns hide which
|
|
121
|
+
// locals map to context fields — cannot be proven.
|
|
122
|
+
if (trimmedParams.includes('{') ||
|
|
123
|
+
trimmedParams.includes('[') ||
|
|
124
|
+
trimmedParams.includes('...') ||
|
|
125
|
+
trimmedParams.includes('=')) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
const body = literal.slice(bodyStart);
|
|
129
|
+
const nameMatch = FIRST_IDENTIFIER.exec(trimmedParams);
|
|
130
|
+
if (nameMatch) {
|
|
131
|
+
const name = nameMatch[0];
|
|
132
|
+
const nameRe = new RegExp(`\\b${name}\\b`, 'g');
|
|
133
|
+
let occurrence;
|
|
134
|
+
while ((occurrence = nameRe.exec(body)) !== null) {
|
|
135
|
+
let i = occurrence.index + name.length;
|
|
136
|
+
// Skip whitespace between the identifier and the next token.
|
|
137
|
+
while (i < body.length &&
|
|
138
|
+
(body[i] === ' ' ||
|
|
139
|
+
body[i] === '\t' ||
|
|
140
|
+
body[i] === '\n' ||
|
|
141
|
+
body[i] === '\r')) {
|
|
142
|
+
i++;
|
|
143
|
+
}
|
|
144
|
+
const next = body[i];
|
|
145
|
+
if (next === '.')
|
|
146
|
+
continue; // ctx.field
|
|
147
|
+
if (next === '?') {
|
|
148
|
+
// ctx?.field — only a clean optional member access is safe.
|
|
149
|
+
let j = i + 1;
|
|
150
|
+
while (j < body.length && body[j] === ' ')
|
|
151
|
+
j++;
|
|
152
|
+
if (body[j] === '.')
|
|
153
|
+
continue;
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
if (next === '[') {
|
|
157
|
+
// ctx['field'] is fine; a computed key is not provable.
|
|
158
|
+
let j = i + 1;
|
|
159
|
+
while (j < body.length && body[j] === ' ')
|
|
160
|
+
j++;
|
|
161
|
+
const quote = body[j];
|
|
162
|
+
if (quote === "'" || quote === '"' || quote === '`')
|
|
163
|
+
continue;
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
// Bare occurrence: the context escaped (helper call, assignment,
|
|
167
|
+
// return, spread, comparison, …) — cannot be proven.
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
for (let i = 0; i < FIELD_KEYS.length; i++) {
|
|
172
|
+
const field = FIELD_KEYS[i];
|
|
173
|
+
if (referencesField(body, field)) {
|
|
174
|
+
accessed.add(field);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Analyzes one route definition and returns a frozen `RouteAccessInfo`.
|
|
181
|
+
*
|
|
182
|
+
* `extraSources` are functions that run for this route but are not part of
|
|
183
|
+
* the definition (plugin hooks, app-level hooks, transform factories); they
|
|
184
|
+
* are scanned so a "known" result accounts for every framework-known reader.
|
|
185
|
+
*/
|
|
186
|
+
export function analyzeRouteAccess(def, debug = false, extraSources = []) {
|
|
187
|
+
// detect hook stages before debug/field analysis so hooks are
|
|
188
|
+
// always recorded even in debug mode or when field analysis is skipped.
|
|
189
|
+
const usedHooks = [];
|
|
190
|
+
const hooks = def.hooks;
|
|
191
|
+
if (hooks) {
|
|
192
|
+
for (let i = 0; i < HOOK_STAGES.length; i++) {
|
|
193
|
+
const stage = HOOK_STAGES[i];
|
|
194
|
+
const val = hooks[stage];
|
|
195
|
+
if (val !== undefined) {
|
|
196
|
+
usedHooks.push(stage);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// `debug` disables analysis per contract and forces the safe
|
|
201
|
+
// "all fields used" default when analysis cannot resolve fields.
|
|
202
|
+
if (debug) {
|
|
203
|
+
return freezeRouteAccessInfo([], /* unknown */ true, usedHooks);
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
const accessed = new Set();
|
|
207
|
+
let safe = true;
|
|
208
|
+
const scan = (value, depth = 0) => {
|
|
209
|
+
if (!safe || depth > 2)
|
|
210
|
+
return;
|
|
211
|
+
if (Array.isArray(value)) {
|
|
212
|
+
for (let i = 0; i < value.length; i++) {
|
|
213
|
+
if (!scanFunction(value[i], accessed)) {
|
|
214
|
+
safe = false;
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (typeof value === 'function') {
|
|
221
|
+
if (!scanFunction(value, accessed))
|
|
222
|
+
safe = false;
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
// Plain objects (the `transform` factory map) — scan each factory.
|
|
226
|
+
if (typeof value === 'object' &&
|
|
227
|
+
value !== null &&
|
|
228
|
+
value.constructor === Object) {
|
|
229
|
+
const record = value;
|
|
230
|
+
for (const key of Object.keys(record)) {
|
|
231
|
+
scan(record[key], depth + 1);
|
|
232
|
+
if (!safe)
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
// Handler keys are a runtime string (module exports); the map type is
|
|
238
|
+
// union-keyed, so widen for iteration.
|
|
239
|
+
const handlers = (def.handlers ?? {});
|
|
240
|
+
for (const key of Object.keys(handlers)) {
|
|
241
|
+
scan(handlers[key]);
|
|
242
|
+
}
|
|
243
|
+
// Route hooks (`hooks.ts`): stage arrays, single hooks, transform map.
|
|
244
|
+
if (hooks) {
|
|
245
|
+
const hookValues = Object.values(hooks);
|
|
246
|
+
for (let i = 0; i < hookValues.length; i++) {
|
|
247
|
+
scan(hookValues[i]);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// Plugin / app-level hooks and transform factories.
|
|
251
|
+
for (let i = 0; i < extraSources.length && safe; i++) {
|
|
252
|
+
scan(extraSources[i]);
|
|
253
|
+
}
|
|
254
|
+
if (!safe) {
|
|
255
|
+
return freezeRouteAccessInfo([], /* unknown */ true, usedHooks);
|
|
256
|
+
}
|
|
257
|
+
// Aliasing patterns: an extra conservative gate for context
|
|
258
|
+
// variables that are not parameters (`req` closures, ...).
|
|
259
|
+
let source = '';
|
|
260
|
+
for (const key of Object.keys(handlers)) {
|
|
261
|
+
source += '\n' + safeToString(handlers[key]);
|
|
262
|
+
}
|
|
263
|
+
if (hooks) {
|
|
264
|
+
const hookValues = Object.values(hooks);
|
|
265
|
+
for (let i = 0; i < hookValues.length; i++) {
|
|
266
|
+
const h = hookValues[i];
|
|
267
|
+
if (Array.isArray(h)) {
|
|
268
|
+
for (let j = 0; j < h.length; j++) {
|
|
269
|
+
source += '\n' + safeToString(h[j]);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
else if (typeof h === 'function') {
|
|
273
|
+
source += '\n' + safeToString(h);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (isLegacyAmbiguous(stripComments(source))) {
|
|
278
|
+
return freezeRouteAccessInfo([], /* unknown */ true, usedHooks);
|
|
279
|
+
}
|
|
280
|
+
return freezeRouteAccessInfo(accessed, /* unknown */ false, usedHooks);
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
// Safe default: empty set, `unknown: true` → `has()` returns true for
|
|
284
|
+
// every field. Cannot affect runtime correctness.
|
|
285
|
+
return freezeRouteAccessInfo([], /* unknown */ true, usedHooks);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ForwardHook, ResponseHook, ErrorHook } from '../lifecycle/types.js';
|
|
2
|
+
import type { ChainNode, Scope } from './node.js';
|
|
3
|
+
export declare class HookChain {
|
|
4
|
+
private nodes;
|
|
5
|
+
add(node: ChainNode): void;
|
|
6
|
+
/**
|
|
7
|
+
* Stage hooks with their function types checked against the stage:
|
|
8
|
+
* forward stages take `ForwardHook`s, response stages take
|
|
9
|
+
* `ResponseHook`s, the error stage takes `ErrorHook`s.
|
|
10
|
+
*/
|
|
11
|
+
addStage(stage: 'validation' | 'beforeRoute', fns: ForwardHook[], scope: Scope, owner: string): void;
|
|
12
|
+
addStage(stage: 'afterRoute' | 'mapResponse', fns: ResponseHook[], scope: Scope, owner: string): void;
|
|
13
|
+
addStage(stage: 'onError', fns: ErrorHook[], scope: Scope, owner: string): void;
|
|
14
|
+
getNodes(): readonly ChainNode[];
|
|
15
|
+
clear(): void;
|
|
16
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export class HookChain {
|
|
2
|
+
nodes = [];
|
|
3
|
+
add(node) {
|
|
4
|
+
this.nodes.push(node);
|
|
5
|
+
}
|
|
6
|
+
addStage(stage, fns, scope, owner) {
|
|
7
|
+
for (const fn of fns) {
|
|
8
|
+
this.nodes.push({ stage, fn, scope, owner });
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
getNodes() {
|
|
12
|
+
return this.nodes;
|
|
13
|
+
}
|
|
14
|
+
clear() {
|
|
15
|
+
this.nodes = [];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Execution order for request hooks (beforeRoute):
|
|
3
|
+
* Framework → Plugin → Global → Local
|
|
4
|
+
*
|
|
5
|
+
* Single source of truth; `test/chain/flatten-order.test.ts` asserts it stays
|
|
6
|
+
* in sync with the scope order documented in `AGENTS.md`.
|
|
7
|
+
*/
|
|
8
|
+
const SCOPE_ORDER_REQUEST = [
|
|
9
|
+
'framework',
|
|
10
|
+
'plugin',
|
|
11
|
+
'global',
|
|
12
|
+
'local',
|
|
13
|
+
];
|
|
14
|
+
/**
|
|
15
|
+
* Execution order for response/error hooks (afterRoute, mapResponse,
|
|
16
|
+
* onError): Local → Global → Plugin → Framework (nearest-first).
|
|
17
|
+
* See {@link SCOPE_ORDER_REQUEST}. Single source of truth.
|
|
18
|
+
*/
|
|
19
|
+
const SCOPE_ORDER_RESPONSE = [
|
|
20
|
+
'local',
|
|
21
|
+
'global',
|
|
22
|
+
'plugin',
|
|
23
|
+
'framework',
|
|
24
|
+
];
|
|
25
|
+
/** Buckets one hook kind by scope, in insertion order within each scope. */
|
|
26
|
+
function bucketByScope() {
|
|
27
|
+
return { framework: [], global: [], plugin: [], local: [] };
|
|
28
|
+
}
|
|
29
|
+
/** Flattens scope buckets into a single array following `order`. */
|
|
30
|
+
function orderBuckets(buckets, order) {
|
|
31
|
+
const out = [];
|
|
32
|
+
for (const scope of order)
|
|
33
|
+
out.push(...buckets[scope]);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
export function flatten(chain, _routeOwner) {
|
|
37
|
+
const nodes = chain.getNodes();
|
|
38
|
+
let validation;
|
|
39
|
+
const before = bucketByScope();
|
|
40
|
+
const after = bucketByScope();
|
|
41
|
+
const mapResp = bucketByScope();
|
|
42
|
+
const error = bucketByScope();
|
|
43
|
+
for (const node of nodes) {
|
|
44
|
+
// The ChainNode is discriminated on `stage`, so `fn` narrows to the
|
|
45
|
+
// stage's precise hook type without assertions.
|
|
46
|
+
switch (node.stage) {
|
|
47
|
+
case 'validation': {
|
|
48
|
+
validation = node.fn;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case 'beforeRoute': {
|
|
52
|
+
before[node.scope].push(node.fn);
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
case 'afterRoute': {
|
|
56
|
+
after[node.scope].push(node.fn);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
case 'mapResponse': {
|
|
60
|
+
mapResp[node.scope].push(node.fn);
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
case 'onError': {
|
|
64
|
+
error[node.scope].push(node.fn);
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const plan = {
|
|
70
|
+
beforeRoute: orderBuckets(before, SCOPE_ORDER_REQUEST),
|
|
71
|
+
afterRoute: orderBuckets(after, SCOPE_ORDER_RESPONSE),
|
|
72
|
+
mapResponse: orderBuckets(mapResp, SCOPE_ORDER_RESPONSE),
|
|
73
|
+
onError: orderBuckets(error, SCOPE_ORDER_RESPONSE),
|
|
74
|
+
};
|
|
75
|
+
if (validation)
|
|
76
|
+
plan.validation = validation;
|
|
77
|
+
return plan;
|
|
78
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ForwardHook, ResponseHook, ErrorHook } from '../lifecycle/types.js';
|
|
2
|
+
export type Scope = 'framework' | 'global' | 'plugin' | 'local';
|
|
3
|
+
/**
|
|
4
|
+
* A single hook staged in the chain, with `fn` typed to its stage.
|
|
5
|
+
* Discriminated on `stage` so the flattener can narrow `fn`.
|
|
6
|
+
*/
|
|
7
|
+
export type ChainNode = {
|
|
8
|
+
stage: 'validation' | 'beforeRoute';
|
|
9
|
+
fn: ForwardHook;
|
|
10
|
+
scope: Scope;
|
|
11
|
+
owner: string;
|
|
12
|
+
parent?: ChainNode;
|
|
13
|
+
} | {
|
|
14
|
+
stage: 'afterRoute' | 'mapResponse';
|
|
15
|
+
fn: ResponseHook;
|
|
16
|
+
scope: Scope;
|
|
17
|
+
owner: string;
|
|
18
|
+
parent?: ChainNode;
|
|
19
|
+
} | {
|
|
20
|
+
stage: 'onError';
|
|
21
|
+
fn: ErrorHook;
|
|
22
|
+
scope: Scope;
|
|
23
|
+
owner: string;
|
|
24
|
+
parent?: ChainNode;
|
|
25
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-based routing conventions for the compiler pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for the sibling files the Directory Scanner
|
|
5
|
+
* recognizes inside a route directory, and for the names that are forbidden.
|
|
6
|
+
*
|
|
7
|
+
* - A route directory is self-contained; sibling files are discovered by convention.
|
|
8
|
+
* - There is **no `middleware.ts`**. Infrastructure is written as hooks.
|
|
9
|
+
* - There is **no `use.ts`** or **`webhook.ts`**. Use ecosystem plugins instead.
|
|
10
|
+
* - `config.ts` provides per-route options exposed as `ctx.config`. Core
|
|
11
|
+
* reads only `responseValidation`; other keys (auth, cache, timeout, …)
|
|
12
|
+
* are data read by plugins / hooks.
|
|
13
|
+
*/
|
|
14
|
+
/** The convention files the scanner recognizes (without the extension). */
|
|
15
|
+
export declare const CONVENTION_FILES: readonly ['route', 'schema', 'hooks', 'openapi', 'config'];
|
|
16
|
+
/** A recognized convention file stem (the part before the extension). */
|
|
17
|
+
export type ConventionFile = (typeof CONVENTION_FILES)[number];
|
|
18
|
+
/** File extensions accepted for convention files (vision: `.ts` / `.js` / `.mjs`). */
|
|
19
|
+
export declare const CONVENTION_EXTENSIONS: readonly ['.ts', '.js', '.mjs'];
|
|
20
|
+
/**
|
|
21
|
+
* Forbidden files. BurgerAPI has no separate middleware concept — the
|
|
22
|
+
* lifecycle is expressed only through hooks. Discovery of these files is a
|
|
23
|
+
* compile-time error (fail fast).
|
|
24
|
+
*/
|
|
25
|
+
export declare const FORBIDDEN_FILES: readonly ['middleware', 'use', 'webhook'];
|
|
26
|
+
/**
|
|
27
|
+
* Returns `{ stem, ext }` when `filename` is a recognized convention file
|
|
28
|
+
* (`route.ts`, `schema.js`, `hooks.mjs`, …), or `undefined` otherwise.
|
|
29
|
+
*/
|
|
30
|
+
export declare function splitConventionName(filename: string): {
|
|
31
|
+
stem: string;
|
|
32
|
+
ext: string;
|
|
33
|
+
} | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Returns true if `name` (a file stem, no extension) is a recognized
|
|
36
|
+
* convention file.
|
|
37
|
+
*/
|
|
38
|
+
export declare function isConventionFile(stem: string): stem is ConventionFile;
|
|
39
|
+
/** HTTP lifecycle hook names (the app-level `hooks.ts` / `globalHooks`). */
|
|
40
|
+
export declare const GLOBAL_HOOK_NAMES: readonly ['onRequest', 'transform', 'beforeRoute', 'afterRoute', 'mapResponse', 'onError'];
|
|
41
|
+
/** Hook names valid in a route's `hooks.ts` (no `onRequest` — it runs pre-routing). */
|
|
42
|
+
export declare const ROUTE_HOOK_NAMES: ("afterRoute" | "beforeRoute" | "mapResponse" | "onError" | "transform")[];
|
|
43
|
+
/**
|
|
44
|
+
* Warns (once per file load) about exports a convention file declares that
|
|
45
|
+
* the framework will never read — a typo (`beforeRout`) or a hook in the
|
|
46
|
+
* wrong scope (`onRequest` in a route `hooks.ts`) would otherwise be
|
|
47
|
+
* silently ignored.
|
|
48
|
+
*/
|
|
49
|
+
export declare function warnUnknownHookExports(hooks: Record<string, unknown> | undefined, file: string, scope: 'global' | 'route'): void;
|
|
50
|
+
/**
|
|
51
|
+
* Warns about `route.ts` exports that look like handlers but will never be
|
|
52
|
+
* registered: lowercase method names (`get`) or non-function method exports.
|
|
53
|
+
*/
|
|
54
|
+
export declare function warnUnknownRouteExports(mod: Record<string, unknown>, file: string, methods: readonly string[]): void;
|
|
55
|
+
/**
|
|
56
|
+
* Resolves the default export of an app-level convention module
|
|
57
|
+
* (`plugins.ts` / `providers.ts`). A file that exists but has no default
|
|
58
|
+
* function export is a startup error, never a silent skip.
|
|
59
|
+
*
|
|
60
|
+
* @throws when the module has no default function export.
|
|
61
|
+
*/
|
|
62
|
+
export declare function requireDefaultFunctionExport(mod: unknown, label: string, filePath?: string): (...args: unknown[]) => unknown;
|
|
63
|
+
/**
|
|
64
|
+
* Validates a discovered file stem against the convention.
|
|
65
|
+
* @throws if the file is forbidden.
|
|
66
|
+
*/
|
|
67
|
+
export declare function assertConventionFile(stem: string): void;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-based routing conventions for the compiler pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for the sibling files the Directory Scanner
|
|
5
|
+
* recognizes inside a route directory, and for the names that are forbidden.
|
|
6
|
+
*
|
|
7
|
+
* - A route directory is self-contained; sibling files are discovered by convention.
|
|
8
|
+
* - There is **no `middleware.ts`**. Infrastructure is written as hooks.
|
|
9
|
+
* - There is **no `use.ts`** or **`webhook.ts`**. Use ecosystem plugins instead.
|
|
10
|
+
* - `config.ts` provides per-route options exposed as `ctx.config`. Core
|
|
11
|
+
* reads only `responseValidation`; other keys (auth, cache, timeout, …)
|
|
12
|
+
* are data read by plugins / hooks.
|
|
13
|
+
*/
|
|
14
|
+
/** The convention files the scanner recognizes (without the extension). */
|
|
15
|
+
export const CONVENTION_FILES = [
|
|
16
|
+
'route',
|
|
17
|
+
'schema',
|
|
18
|
+
'hooks',
|
|
19
|
+
'openapi',
|
|
20
|
+
'config',
|
|
21
|
+
];
|
|
22
|
+
/** File extensions accepted for convention files (vision: `.ts` / `.js` / `.mjs`). */
|
|
23
|
+
export const CONVENTION_EXTENSIONS = ['.ts', '.js', '.mjs'];
|
|
24
|
+
/**
|
|
25
|
+
* Forbidden files. BurgerAPI has no separate middleware concept — the
|
|
26
|
+
* lifecycle is expressed only through hooks. Discovery of these files is a
|
|
27
|
+
* compile-time error (fail fast).
|
|
28
|
+
*/
|
|
29
|
+
export const FORBIDDEN_FILES = ['middleware', 'use', 'webhook'];
|
|
30
|
+
/**
|
|
31
|
+
* Returns `{ stem, ext }` when `filename` is a recognized convention file
|
|
32
|
+
* (`route.ts`, `schema.js`, `hooks.mjs`, …), or `undefined` otherwise.
|
|
33
|
+
*/
|
|
34
|
+
export function splitConventionName(filename) {
|
|
35
|
+
const dot = filename.lastIndexOf('.');
|
|
36
|
+
if (dot <= 0)
|
|
37
|
+
return undefined;
|
|
38
|
+
const ext = filename.slice(dot);
|
|
39
|
+
if (!CONVENTION_EXTENSIONS.includes(ext)) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
return { stem: filename.slice(0, dot), ext };
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Returns true if `name` (a file stem, no extension) is a recognized
|
|
46
|
+
* convention file.
|
|
47
|
+
*/
|
|
48
|
+
export function isConventionFile(stem) {
|
|
49
|
+
return CONVENTION_FILES.includes(stem);
|
|
50
|
+
}
|
|
51
|
+
/** HTTP lifecycle hook names (the app-level `hooks.ts` / `globalHooks`). */
|
|
52
|
+
export const GLOBAL_HOOK_NAMES = [
|
|
53
|
+
'onRequest',
|
|
54
|
+
'transform',
|
|
55
|
+
'beforeRoute',
|
|
56
|
+
'afterRoute',
|
|
57
|
+
'mapResponse',
|
|
58
|
+
'onError',
|
|
59
|
+
];
|
|
60
|
+
/** WebSocket hooks the app-level `hooks.ts` may also export. */
|
|
61
|
+
const GLOBAL_WS_HOOK_NAMES = ['onOpen', 'onMessage', 'onClose'];
|
|
62
|
+
/** Hook names valid in a route's `hooks.ts` (no `onRequest` — it runs pre-routing). */
|
|
63
|
+
export const ROUTE_HOOK_NAMES = GLOBAL_HOOK_NAMES.filter((n) => n !== 'onRequest');
|
|
64
|
+
/**
|
|
65
|
+
* Warns (once per file load) about exports a convention file declares that
|
|
66
|
+
* the framework will never read — a typo (`beforeRout`) or a hook in the
|
|
67
|
+
* wrong scope (`onRequest` in a route `hooks.ts`) would otherwise be
|
|
68
|
+
* silently ignored.
|
|
69
|
+
*/
|
|
70
|
+
export function warnUnknownHookExports(hooks, file, scope) {
|
|
71
|
+
if (!hooks || typeof hooks !== 'object')
|
|
72
|
+
return;
|
|
73
|
+
const valid = scope === 'global'
|
|
74
|
+
? [...GLOBAL_HOOK_NAMES, ...GLOBAL_WS_HOOK_NAMES]
|
|
75
|
+
: ROUTE_HOOK_NAMES;
|
|
76
|
+
for (const key of Object.keys(hooks)) {
|
|
77
|
+
if (key === 'default' || key === '__esModule' || valid.includes(key)) {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const hint = key === 'onRequest'
|
|
81
|
+
? ' onRequest runs before routing, so it cannot be route-scoped — move it to the app-level src/hooks.ts or a plugin.'
|
|
82
|
+
: ` Valid names: ${valid.join(', ')}.`;
|
|
83
|
+
console.warn(`[burger-api] ${file}: export "${key}" is not a hook name and is ignored.${hint}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Warns about `route.ts` exports that look like handlers but will never be
|
|
88
|
+
* registered: lowercase method names (`get`) or non-function method exports.
|
|
89
|
+
*/
|
|
90
|
+
export function warnUnknownRouteExports(mod, file, methods) {
|
|
91
|
+
for (const key of Object.keys(mod)) {
|
|
92
|
+
const upper = key.toUpperCase();
|
|
93
|
+
if (!methods.includes(upper))
|
|
94
|
+
continue;
|
|
95
|
+
if (key !== upper) {
|
|
96
|
+
console.warn(`[burger-api] ${file}: export "${key}" is ignored — handler exports must be uppercase (${upper}). Valid names: ${methods.join(', ')}.`);
|
|
97
|
+
}
|
|
98
|
+
else if (typeof mod[key] !== 'function') {
|
|
99
|
+
console.warn(`[burger-api] ${file}: export "${key}" is not a function and is ignored — export a handler: export async function ${key}(ctx) { ... }`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Resolves the default export of an app-level convention module
|
|
105
|
+
* (`plugins.ts` / `providers.ts`). A file that exists but has no default
|
|
106
|
+
* function export is a startup error, never a silent skip.
|
|
107
|
+
*
|
|
108
|
+
* @throws when the module has no default function export.
|
|
109
|
+
*/
|
|
110
|
+
export function requireDefaultFunctionExport(mod, label, filePath) {
|
|
111
|
+
const fn = mod?.default;
|
|
112
|
+
if (typeof fn !== 'function') {
|
|
113
|
+
throw new Error(`[burger-api] ${label}${filePath ? ` (${filePath})` : ''} must ` +
|
|
114
|
+
'default-export a function — add: ' +
|
|
115
|
+
'export default function (burger) { ... }');
|
|
116
|
+
}
|
|
117
|
+
return fn;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Validates a discovered file stem against the convention.
|
|
121
|
+
* @throws if the file is forbidden.
|
|
122
|
+
*/
|
|
123
|
+
export function assertConventionFile(stem) {
|
|
124
|
+
if (FORBIDDEN_FILES.includes(stem)) {
|
|
125
|
+
throw new Error(`Forbidden convention file "${stem}" discovered (any of .ts/.js/.mjs). ` +
|
|
126
|
+
`BurgerAPI has no middleware or webhook concept — write ` +
|
|
127
|
+
`infrastructure code as hooks in "hooks.ts" instead.`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiler module for BurgerAPI — the build-time / dev-time route pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Filesystem scanning (convention files), module loading, and the structural
|
|
5
|
+
* route tree. Used by the CLI build pipeline and dev mode; production AOT
|
|
6
|
+
* apps consume prebuilt `apiRoutes` instead.
|
|
7
|
+
*/
|
|
8
|
+
export { DirectoryScanner } from './scanner.js';
|
|
9
|
+
export { ModuleLoader } from './module-loader.js';
|
|
10
|
+
export { RouteTree } from './route-tree.js';
|
|
11
|
+
export type { RouteModule, ScannedRoute, ScanResult, } from './route-module.js';
|
|
12
|
+
export { CONVENTION_FILES, CONVENTION_EXTENSIONS, FORBIDDEN_FILES, splitConventionName, isConventionFile, assertConventionFile, } from './conventions.js';
|
|
13
|
+
export type { ConventionFile } from './conventions.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiler module for BurgerAPI — the build-time / dev-time route pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Filesystem scanning (convention files), module loading, and the structural
|
|
5
|
+
* route tree. Used by the CLI build pipeline and dev mode; production AOT
|
|
6
|
+
* apps consume prebuilt `apiRoutes` instead.
|
|
7
|
+
*/
|
|
8
|
+
export { DirectoryScanner } from './scanner.js';
|
|
9
|
+
export { ModuleLoader } from './module-loader.js';
|
|
10
|
+
export { RouteTree } from './route-tree.js';
|
|
11
|
+
export { CONVENTION_FILES, CONVENTION_EXTENSIONS, FORBIDDEN_FILES, splitConventionName, isConventionFile, assertConventionFile, } from './conventions.js';
|