@zero-server/sdk 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/body.d.ts +14 -0
  113. package/types/cli.d.ts +2 -0
  114. package/types/cluster.d.ts +75 -75
  115. package/types/env.d.ts +80 -80
  116. package/types/errors.d.ts +316 -316
  117. package/types/fetch.d.ts +43 -43
  118. package/types/grpc.d.ts +432 -432
  119. package/types/index.d.ts +384 -384
  120. package/types/lifecycle.d.ts +60 -60
  121. package/types/middleware.d.ts +320 -320
  122. package/types/observe.d.ts +304 -304
  123. package/types/orm.d.ts +1887 -1887
  124. package/types/request.d.ts +109 -109
  125. package/types/response.d.ts +157 -157
  126. package/types/router.d.ts +78 -78
  127. package/types/sse.d.ts +78 -78
  128. package/types/websocket.d.ts +126 -126
@@ -1,436 +1,436 @@
1
- /**
2
- * @module router
3
- * @description Full-featured pattern-matching router with named parameters,
4
- * wildcard catch-alls, sequential handler chains, sub-router
5
- * mounting, and route introspection.
6
- *
7
- * @example
8
- * const { Router } = require('@zero-server/sdk');
9
- *
10
- * const api = new Router();
11
- *
12
- * api.get('/users/:id', (req, res) => {
13
- * res.json({ id: req.params.id });
14
- * });
15
- *
16
- * api.route('/posts')
17
- * .get((req, res) => res.json([]))
18
- * .post((req, res) => res.json({ created: true }));
19
- *
20
- * app.use('/api', api);
21
- */
22
-
23
- const log = require('../debug')('zero:router');
24
-
25
- /**
26
- * Convert a route path pattern into a RegExp and extract named parameter keys.
27
- * Supports `:param` segments and trailing `*` wildcards.
28
- *
29
- * @private
30
- * @param {string} path - Route pattern (e.g. '/users/:id', '/api/*').
31
- * @returns {{ regex: RegExp, keys: string[] }} Compiled regex and ordered parameter names.
32
- */
33
- function pathToRegex(path)
34
- {
35
- // Wildcard catch-all: /api/*
36
- if (path.endsWith('*'))
37
- {
38
- const prefix = path.slice(0, -1); // e.g. "/api/"
39
- const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
- return { regex: new RegExp('^' + escaped + '(.*)$'), keys: ['0'] };
41
- }
42
-
43
- const parts = path.split('/').filter(Boolean);
44
- const keys = [];
45
- const pattern = parts.map(p =>
46
- {
47
- if (p.startsWith(':')) { keys.push(p.slice(1)); return '([^/]+)'; }
48
- return p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
49
- }).join('/');
50
- return { regex: new RegExp('^/' + pattern + '/?$'), keys };
51
- }
52
-
53
- /**
54
- * Join two path segments, avoiding double slashes.
55
- * @private
56
- * @param {string} base - Base path prefix.
57
- * @param {string} child - Child path segment.
58
- * @returns {string} Formatted string.
59
- */
60
- function joinPath(base, child)
61
- {
62
- if (base === '/') return child;
63
- if (child === '/') return base;
64
- return base.replace(/\/$/, '') + '/' + child.replace(/^\//, '');
65
- }
66
-
67
- class Router
68
- {
69
- /**
70
- * Create a new Router with an empty route table.
71
- * Can be used standalone as a sub-router or internally by App.
72
- */
73
- constructor()
74
- {
75
- this.routes = [];
76
- /** @type {{ prefix: string, router: Router }[]} */
77
- this._children = [];
78
- /**
79
- * Parameter pre-processing handlers (set by parent App).
80
- * @type {Object<string, Function[]>}
81
- */
82
- this._paramHandlers = {};
83
- }
84
-
85
- // -- Core ------------------------------------------------
86
-
87
- /**
88
- * Register a route.
89
- *
90
- * @param {string} method - HTTP method (e.g. 'GET') or 'ALL' to match any.
91
- * @param {string} path - Route pattern.
92
- * @param {Function[]} handlers - One or more handler functions `(req, res, next) => void`.
93
- * @param {object} [options] - Configuration options.
94
- * @param {boolean} [options.secure] - When `true`, route matches only HTTPS requests;
95
- * when `false`, only HTTP. Omit to match both.
96
- */
97
- add(method, path, handlers, options = {})
98
- {
99
- const { regex, keys } = pathToRegex(path);
100
- const entry = { method: method.toUpperCase(), path, regex, keys, handlers };
101
- if (options.secure !== undefined) entry.secure = !!options.secure;
102
- this.routes.push(entry);
103
- log.debug('route added %s %s', method.toUpperCase(), path);
104
- }
105
-
106
- /**
107
- * Mount a child Router under a path prefix.
108
- * Requests matching the prefix are delegated to the child router with
109
- * the prefix stripped from `req.url`.
110
- *
111
- * @param {string} prefix - Path prefix (e.g. '/api').
112
- * @param {Router} router - Child router instance.
113
- * @returns {Router} `this` for chaining.
114
- */
115
- use(prefix, router)
116
- {
117
- if (typeof prefix === 'string' && router instanceof Router)
118
- {
119
- const cleanPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
120
- this._children.push({ prefix: cleanPrefix, router });
121
- log.debug('mounted child router at %s', cleanPrefix);
122
- }
123
- return this;
124
- }
125
-
126
- /**
127
- * Match an incoming request against the route table and execute the first
128
- * matching handler chain. Delegates to child routers when mounted.
129
- * Sends a 404 JSON response when no route matches.
130
- *
131
- * @param {import('./request')} req - Wrapped request.
132
- * @param {import('./response')} res - Wrapped response.
133
- */
134
- handle(req, res)
135
- {
136
- if (!this._matchAndExecute(req, res))
137
- {
138
- res.status(404).json({ error: 'Not Found' });
139
- }
140
- }
141
-
142
- /**
143
- * Try to handle a request without sending 404 on miss.
144
- * Used internally by parent routers to probe child routers.
145
- *
146
- * @param {import('./request')} req - HTTP request object.
147
- * @param {import('./response')} res - HTTP response object.
148
- * @returns {boolean} `true` if a route matched.
149
- * @private
150
- */
151
- _tryHandle(req, res)
152
- {
153
- return this._matchAndExecute(req, res);
154
- }
155
-
156
- /**
157
- * Shared route matching and handler execution.
158
- * Returns `true` if a route matched (handler invoked), `false` otherwise.
159
- *
160
- * @param {import('./request')} req - HTTP request object.
161
- * @param {import('./response')} res - HTTP response object.
162
- * @returns {boolean} Boolean result.
163
- * @private
164
- */
165
- _matchAndExecute(req, res)
166
- {
167
- const method = req.method.toUpperCase();
168
- const url = req.url.split('?')[0];
169
- log.debug('%s %s', method, url);
170
-
171
- // Try own routes first
172
- for (let ri = 0; ri < this.routes.length; ri++)
173
- {
174
- const r = this.routes[ri];
175
- if (r.method !== 'ALL' && r.method !== method) continue;
176
- if (r.secure === true && !req.secure) continue;
177
- if (r.secure === false && req.secure) continue;
178
- const m = url.match(r.regex);
179
- if (!m) continue;
180
- req.params = {};
181
- for (let i = 0; i < r.keys.length; i++)
182
- {
183
- req.params[r.keys[i]] = decodeURIComponent(m[i + 1] || '');
184
- }
185
-
186
- // Run param pre-processing handlers
187
- const paramHandlers = this._paramHandlers || {};
188
- let paramKeys;
189
- let paramCount = 0;
190
- for (let i = 0; i < r.keys.length; i++)
191
- {
192
- if (paramHandlers[r.keys[i]])
193
- {
194
- if (!paramKeys) paramKeys = [];
195
- paramKeys.push(r.keys[i]);
196
- paramCount++;
197
- }
198
- }
199
-
200
- let pIdx = 0;
201
- const runParams = () =>
202
- {
203
- if (pIdx < paramCount)
204
- {
205
- const pk = paramKeys[pIdx++];
206
- const fns = paramHandlers[pk];
207
- let fIdx = 0;
208
- const nextParam = () =>
209
- {
210
- if (fIdx < fns.length)
211
- {
212
- const fn = fns[fIdx++];
213
- try
214
- {
215
- const result = fn(req, res, nextParam, req.params[pk]);
216
- if (result && typeof result.catch === 'function')
217
- {
218
- result.catch(e => this._handleRouteError(e, req, res));
219
- }
220
- }
221
- catch (e) { this._handleRouteError(e, req, res); }
222
- }
223
- else { runParams(); }
224
- };
225
- nextParam();
226
- }
227
- else { runHandlers(); }
228
- };
229
-
230
- let idx = 0;
231
- const runHandlers = () =>
232
- {
233
- if (idx < r.handlers.length)
234
- {
235
- const h = r.handlers[idx++];
236
- try
237
- {
238
- const result = h(req, res, runHandlers);
239
- if (result && typeof result.catch === 'function')
240
- {
241
- result.catch(e => this._handleRouteError(e, req, res));
242
- }
243
- }
244
- catch (e)
245
- {
246
- this._handleRouteError(e, req, res);
247
- }
248
- }
249
- };
250
-
251
- if (paramCount > 0) runParams();
252
- else runHandlers();
253
- return true;
254
- }
255
-
256
- // Try child routers
257
- for (let ci = 0; ci < this._children.length; ci++)
258
- {
259
- const child = this._children[ci];
260
- if (url === child.prefix || url.startsWith(child.prefix + '/'))
261
- {
262
- const origUrl = req.url;
263
- const origBaseUrl = req.baseUrl || '';
264
- req.baseUrl = origBaseUrl + child.prefix;
265
- req.url = req.url.slice(child.prefix.length) || '/';
266
- child.router._paramHandlers = this._paramHandlers;
267
- try
268
- {
269
- const found = child.router._matchAndExecute(req, res);
270
- if (found) return true;
271
- }
272
- catch (e) { this._handleRouteError(e, req, res); return true; }
273
- req.url = origUrl;
274
- req.baseUrl = origBaseUrl;
275
- }
276
- }
277
-
278
- return false;
279
- }
280
-
281
- // -- Route Shortcuts ----------------------------------------
282
-
283
- /**
284
- * @private
285
- * Extract an options object from the head of the handlers array when
286
- * the first argument is a plain object (not a function).
287
- *
288
- * Allows: `router.get('/path', { secure: true }, handler)`
289
- */
290
- _extractOpts(fns)
291
- {
292
- let opts = {};
293
- if (fns.length > 0 && typeof fns[0] === 'object' && typeof fns[0] !== 'function')
294
- {
295
- opts = fns.shift();
296
- }
297
- return opts;
298
- }
299
-
300
- /**
301
- * @see Router#add — shortcut for GET requests.
302
- * @param {string} path - Route pattern.
303
- * @param {...Function} fns - Handler functions.
304
- * @returns {Router} `this` for chaining.
305
- */
306
- get(path, ...fns) { const o = this._extractOpts(fns); this.add('GET', path, fns, o); return this; }
307
- /**
308
- * @see Router#add — shortcut for POST requests.
309
- * @param {string} path - Route pattern.
310
- * @param {...Function} fns - Handler functions.
311
- * @returns {Router} `this` for chaining.
312
- */
313
- post(path, ...fns) { const o = this._extractOpts(fns); this.add('POST', path, fns, o); return this; }
314
- /**
315
- * @see Router#add — shortcut for PUT requests.
316
- * @param {string} path - Route pattern.
317
- * @param {...Function} fns - Handler functions.
318
- * @returns {Router} `this` for chaining.
319
- */
320
- put(path, ...fns) { const o = this._extractOpts(fns); this.add('PUT', path, fns, o); return this; }
321
- /**
322
- * @see Router#add — shortcut for DELETE requests.
323
- * @param {string} path - Route pattern.
324
- * @param {...Function} fns - Handler functions.
325
- * @returns {Router} `this` for chaining.
326
- */
327
- delete(path, ...fns) { const o = this._extractOpts(fns); this.add('DELETE', path, fns, o); return this; }
328
- /**
329
- * @see Router#add — shortcut for PATCH requests.
330
- * @param {string} path - Route pattern.
331
- * @param {...Function} fns - Handler functions.
332
- * @returns {Router} `this` for chaining.
333
- */
334
- patch(path, ...fns) { const o = this._extractOpts(fns); this.add('PATCH', path, fns, o); return this; }
335
- /**
336
- * @see Router#add — shortcut for OPTIONS requests.
337
- * @param {string} path - Route pattern.
338
- * @param {...Function} fns - Handler functions.
339
- * @returns {Router} `this` for chaining.
340
- */
341
- options(path, ...fns) { const o = this._extractOpts(fns); this.add('OPTIONS', path, fns, o); return this; }
342
- /**
343
- * @see Router#add — shortcut for HEAD requests.
344
- * @param {string} path - Route pattern.
345
- * @param {...Function} fns - Handler functions.
346
- * @returns {Router} `this` for chaining.
347
- */
348
- head(path, ...fns) { const o = this._extractOpts(fns); this.add('HEAD', path, fns, o); return this; }
349
- /**
350
- * @see Router#add — matches every HTTP method.
351
- * @param {string} path - Route pattern.
352
- * @param {...Function} fns - Handler functions.
353
- * @returns {Router} `this` for chaining.
354
- */
355
- all(path, ...fns) { const o = this._extractOpts(fns); this.add('ALL', path, fns, o); return this; }
356
-
357
- /**
358
- * Chainable route builder — register multiple methods on the same path.
359
- *
360
- * @example
361
- * router.route('/users')
362
- * .get((req, res) => { ... })
363
- * .post((req, res) => { ... });
364
- *
365
- * @param {string} path - Route pattern.
366
- * @returns {{ get, post, put, delete, patch, options, head, all: Function }} Chain object with HTTP verb methods.
367
- */
368
- route(path)
369
- {
370
- const self = this;
371
- const chain = {};
372
- for (const m of ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'all'])
373
- {
374
- chain[m] = (...fns) => { const o = self._extractOpts(fns); self.add(m.toUpperCase(), path, fns, o); return chain; };
375
- }
376
- return chain;
377
- }
378
-
379
- // -- Introspection -----------------------------------
380
-
381
- /**
382
- * Handle an error thrown by a route handler.
383
- * Delegates to the app-level error handler if available, otherwise
384
- * sends a generic 500 JSON response.
385
- *
386
- * @param {Error} err - Error object.
387
- * @param {import('../http/request')} req - HTTP request object.
388
- * @param {import('../http/response')} res - HTTP response object.
389
- * @private
390
- */
391
- _handleRouteError(err, req, res)
392
- {
393
- log.error('route error: %s', err.message || err);
394
- // Check if the app has an error handler (set via app.onError())
395
- if (req.app && req.app._errorHandler)
396
- {
397
- return req.app._errorHandler(err, req, res, () => {});
398
- }
399
- const statusCode = err.statusCode || err.status || 500;
400
- if (!res.headersSent && !(res.raw && res.raw.headersSent))
401
- {
402
- res.status(statusCode).json(
403
- typeof err.toJSON === 'function'
404
- ? err.toJSON()
405
- : { error: err.message || 'Internal Server Error' }
406
- );
407
- }
408
- }
409
-
410
- /**
411
- * Return a flat list of all registered routes, including those in
412
- * mounted child routers. Useful for debugging or auto-documentation.
413
- *
414
- * @param {string} [prefix=''] - Internal: accumulated prefix from parent routers.
415
- * @returns {{ method: string, path: string, secure?: boolean }[]} Registered routes.
416
- */
417
- inspect(prefix = '')
418
- {
419
- const list = [];
420
- for (const r of this.routes)
421
- {
422
- const entry = { method: r.method, path: joinPath(prefix, r.path) };
423
- if (r.secure === true) entry.secure = true;
424
- else if (r.secure === false) entry.secure = false;
425
- list.push(entry);
426
- }
427
- for (const child of this._children)
428
- {
429
- const childPrefix = prefix ? joinPath(prefix, child.prefix) : child.prefix;
430
- list.push(...child.router.inspect(childPrefix));
431
- }
432
- return list;
433
- }
434
- }
435
-
436
- module.exports = Router;
1
+ /**
2
+ * @module router
3
+ * @description Full-featured pattern-matching router with named parameters,
4
+ * wildcard catch-alls, sequential handler chains, sub-router
5
+ * mounting, and route introspection.
6
+ *
7
+ * @example
8
+ * const { Router } = require('@zero-server/sdk');
9
+ *
10
+ * const api = new Router();
11
+ *
12
+ * api.get('/users/:id', (req, res) => {
13
+ * res.json({ id: req.params.id });
14
+ * });
15
+ *
16
+ * api.route('/posts')
17
+ * .get((req, res) => res.json([]))
18
+ * .post((req, res) => res.json({ created: true }));
19
+ *
20
+ * app.use('/api', api);
21
+ */
22
+
23
+ const log = require('../debug')('zero:router');
24
+
25
+ /**
26
+ * Convert a route path pattern into a RegExp and extract named parameter keys.
27
+ * Supports `:param` segments and trailing `*` wildcards.
28
+ *
29
+ * @private
30
+ * @param {string} path - Route pattern (e.g. '/users/:id', '/api/*').
31
+ * @returns {{ regex: RegExp, keys: string[] }} Compiled regex and ordered parameter names.
32
+ */
33
+ function pathToRegex(path)
34
+ {
35
+ // Wildcard catch-all: /api/*
36
+ if (path.endsWith('*'))
37
+ {
38
+ const prefix = path.slice(0, -1); // e.g. "/api/"
39
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
+ return { regex: new RegExp('^' + escaped + '(.*)$'), keys: ['0'] };
41
+ }
42
+
43
+ const parts = path.split('/').filter(Boolean);
44
+ const keys = [];
45
+ const pattern = parts.map(p =>
46
+ {
47
+ if (p.startsWith(':')) { keys.push(p.slice(1)); return '([^/]+)'; }
48
+ return p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
49
+ }).join('/');
50
+ return { regex: new RegExp('^/' + pattern + '/?$'), keys };
51
+ }
52
+
53
+ /**
54
+ * Join two path segments, avoiding double slashes.
55
+ * @private
56
+ * @param {string} base - Base path prefix.
57
+ * @param {string} child - Child path segment.
58
+ * @returns {string} Formatted string.
59
+ */
60
+ function joinPath(base, child)
61
+ {
62
+ if (base === '/') return child;
63
+ if (child === '/') return base;
64
+ return base.replace(/\/$/, '') + '/' + child.replace(/^\//, '');
65
+ }
66
+
67
+ class Router
68
+ {
69
+ /**
70
+ * Create a new Router with an empty route table.
71
+ * Can be used standalone as a sub-router or internally by App.
72
+ */
73
+ constructor()
74
+ {
75
+ this.routes = [];
76
+ /** @type {{ prefix: string, router: Router }[]} */
77
+ this._children = [];
78
+ /**
79
+ * Parameter pre-processing handlers (set by parent App).
80
+ * @type {Object<string, Function[]>}
81
+ */
82
+ this._paramHandlers = {};
83
+ }
84
+
85
+ // -- Core ------------------------------------------------
86
+
87
+ /**
88
+ * Register a route.
89
+ *
90
+ * @param {string} method - HTTP method (e.g. 'GET') or 'ALL' to match any.
91
+ * @param {string} path - Route pattern.
92
+ * @param {Function[]} handlers - One or more handler functions `(req, res, next) => void`.
93
+ * @param {object} [options] - Configuration options.
94
+ * @param {boolean} [options.secure] - When `true`, route matches only HTTPS requests;
95
+ * when `false`, only HTTP. Omit to match both.
96
+ */
97
+ add(method, path, handlers, options = {})
98
+ {
99
+ const { regex, keys } = pathToRegex(path);
100
+ const entry = { method: method.toUpperCase(), path, regex, keys, handlers };
101
+ if (options.secure !== undefined) entry.secure = !!options.secure;
102
+ this.routes.push(entry);
103
+ log.debug('route added %s %s', method.toUpperCase(), path);
104
+ }
105
+
106
+ /**
107
+ * Mount a child Router under a path prefix.
108
+ * Requests matching the prefix are delegated to the child router with
109
+ * the prefix stripped from `req.url`.
110
+ *
111
+ * @param {string} prefix - Path prefix (e.g. '/api').
112
+ * @param {Router} router - Child router instance.
113
+ * @returns {Router} `this` for chaining.
114
+ */
115
+ use(prefix, router)
116
+ {
117
+ if (typeof prefix === 'string' && router instanceof Router)
118
+ {
119
+ const cleanPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
120
+ this._children.push({ prefix: cleanPrefix, router });
121
+ log.debug('mounted child router at %s', cleanPrefix);
122
+ }
123
+ return this;
124
+ }
125
+
126
+ /**
127
+ * Match an incoming request against the route table and execute the first
128
+ * matching handler chain. Delegates to child routers when mounted.
129
+ * Sends a 404 JSON response when no route matches.
130
+ *
131
+ * @param {import('./request')} req - Wrapped request.
132
+ * @param {import('./response')} res - Wrapped response.
133
+ */
134
+ handle(req, res)
135
+ {
136
+ if (!this._matchAndExecute(req, res))
137
+ {
138
+ res.status(404).json({ error: 'Not Found' });
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Try to handle a request without sending 404 on miss.
144
+ * Used internally by parent routers to probe child routers.
145
+ *
146
+ * @param {import('./request')} req - HTTP request object.
147
+ * @param {import('./response')} res - HTTP response object.
148
+ * @returns {boolean} `true` if a route matched.
149
+ * @private
150
+ */
151
+ _tryHandle(req, res)
152
+ {
153
+ return this._matchAndExecute(req, res);
154
+ }
155
+
156
+ /**
157
+ * Shared route matching and handler execution.
158
+ * Returns `true` if a route matched (handler invoked), `false` otherwise.
159
+ *
160
+ * @param {import('./request')} req - HTTP request object.
161
+ * @param {import('./response')} res - HTTP response object.
162
+ * @returns {boolean} Boolean result.
163
+ * @private
164
+ */
165
+ _matchAndExecute(req, res)
166
+ {
167
+ const method = req.method.toUpperCase();
168
+ const url = req.url.split('?')[0];
169
+ log.debug('%s %s', method, url);
170
+
171
+ // Try own routes first
172
+ for (let ri = 0; ri < this.routes.length; ri++)
173
+ {
174
+ const r = this.routes[ri];
175
+ if (r.method !== 'ALL' && r.method !== method) continue;
176
+ if (r.secure === true && !req.secure) continue;
177
+ if (r.secure === false && req.secure) continue;
178
+ const m = url.match(r.regex);
179
+ if (!m) continue;
180
+ req.params = {};
181
+ for (let i = 0; i < r.keys.length; i++)
182
+ {
183
+ req.params[r.keys[i]] = decodeURIComponent(m[i + 1] || '');
184
+ }
185
+
186
+ // Run param pre-processing handlers
187
+ const paramHandlers = this._paramHandlers || {};
188
+ let paramKeys;
189
+ let paramCount = 0;
190
+ for (let i = 0; i < r.keys.length; i++)
191
+ {
192
+ if (paramHandlers[r.keys[i]])
193
+ {
194
+ if (!paramKeys) paramKeys = [];
195
+ paramKeys.push(r.keys[i]);
196
+ paramCount++;
197
+ }
198
+ }
199
+
200
+ let pIdx = 0;
201
+ const runParams = () =>
202
+ {
203
+ if (pIdx < paramCount)
204
+ {
205
+ const pk = paramKeys[pIdx++];
206
+ const fns = paramHandlers[pk];
207
+ let fIdx = 0;
208
+ const nextParam = () =>
209
+ {
210
+ if (fIdx < fns.length)
211
+ {
212
+ const fn = fns[fIdx++];
213
+ try
214
+ {
215
+ const result = fn(req, res, nextParam, req.params[pk]);
216
+ if (result && typeof result.catch === 'function')
217
+ {
218
+ result.catch(e => this._handleRouteError(e, req, res));
219
+ }
220
+ }
221
+ catch (e) { this._handleRouteError(e, req, res); }
222
+ }
223
+ else { runParams(); }
224
+ };
225
+ nextParam();
226
+ }
227
+ else { runHandlers(); }
228
+ };
229
+
230
+ let idx = 0;
231
+ const runHandlers = () =>
232
+ {
233
+ if (idx < r.handlers.length)
234
+ {
235
+ const h = r.handlers[idx++];
236
+ try
237
+ {
238
+ const result = h(req, res, runHandlers);
239
+ if (result && typeof result.catch === 'function')
240
+ {
241
+ result.catch(e => this._handleRouteError(e, req, res));
242
+ }
243
+ }
244
+ catch (e)
245
+ {
246
+ this._handleRouteError(e, req, res);
247
+ }
248
+ }
249
+ };
250
+
251
+ if (paramCount > 0) runParams();
252
+ else runHandlers();
253
+ return true;
254
+ }
255
+
256
+ // Try child routers
257
+ for (let ci = 0; ci < this._children.length; ci++)
258
+ {
259
+ const child = this._children[ci];
260
+ if (url === child.prefix || url.startsWith(child.prefix + '/'))
261
+ {
262
+ const origUrl = req.url;
263
+ const origBaseUrl = req.baseUrl || '';
264
+ req.baseUrl = origBaseUrl + child.prefix;
265
+ req.url = req.url.slice(child.prefix.length) || '/';
266
+ child.router._paramHandlers = this._paramHandlers;
267
+ try
268
+ {
269
+ const found = child.router._matchAndExecute(req, res);
270
+ if (found) return true;
271
+ }
272
+ catch (e) { this._handleRouteError(e, req, res); return true; }
273
+ req.url = origUrl;
274
+ req.baseUrl = origBaseUrl;
275
+ }
276
+ }
277
+
278
+ return false;
279
+ }
280
+
281
+ // -- Route Shortcuts ----------------------------------------
282
+
283
+ /**
284
+ * @private
285
+ * Extract an options object from the head of the handlers array when
286
+ * the first argument is a plain object (not a function).
287
+ *
288
+ * Allows: `router.get('/path', { secure: true }, handler)`
289
+ */
290
+ _extractOpts(fns)
291
+ {
292
+ let opts = {};
293
+ if (fns.length > 0 && typeof fns[0] === 'object' && typeof fns[0] !== 'function')
294
+ {
295
+ opts = fns.shift();
296
+ }
297
+ return opts;
298
+ }
299
+
300
+ /**
301
+ * @see Router#add — shortcut for GET requests.
302
+ * @param {string} path - Route pattern.
303
+ * @param {...Function} fns - Handler functions.
304
+ * @returns {Router} `this` for chaining.
305
+ */
306
+ get(path, ...fns) { const o = this._extractOpts(fns); this.add('GET', path, fns, o); return this; }
307
+ /**
308
+ * @see Router#add — shortcut for POST requests.
309
+ * @param {string} path - Route pattern.
310
+ * @param {...Function} fns - Handler functions.
311
+ * @returns {Router} `this` for chaining.
312
+ */
313
+ post(path, ...fns) { const o = this._extractOpts(fns); this.add('POST', path, fns, o); return this; }
314
+ /**
315
+ * @see Router#add — shortcut for PUT requests.
316
+ * @param {string} path - Route pattern.
317
+ * @param {...Function} fns - Handler functions.
318
+ * @returns {Router} `this` for chaining.
319
+ */
320
+ put(path, ...fns) { const o = this._extractOpts(fns); this.add('PUT', path, fns, o); return this; }
321
+ /**
322
+ * @see Router#add — shortcut for DELETE requests.
323
+ * @param {string} path - Route pattern.
324
+ * @param {...Function} fns - Handler functions.
325
+ * @returns {Router} `this` for chaining.
326
+ */
327
+ delete(path, ...fns) { const o = this._extractOpts(fns); this.add('DELETE', path, fns, o); return this; }
328
+ /**
329
+ * @see Router#add — shortcut for PATCH requests.
330
+ * @param {string} path - Route pattern.
331
+ * @param {...Function} fns - Handler functions.
332
+ * @returns {Router} `this` for chaining.
333
+ */
334
+ patch(path, ...fns) { const o = this._extractOpts(fns); this.add('PATCH', path, fns, o); return this; }
335
+ /**
336
+ * @see Router#add — shortcut for OPTIONS requests.
337
+ * @param {string} path - Route pattern.
338
+ * @param {...Function} fns - Handler functions.
339
+ * @returns {Router} `this` for chaining.
340
+ */
341
+ options(path, ...fns) { const o = this._extractOpts(fns); this.add('OPTIONS', path, fns, o); return this; }
342
+ /**
343
+ * @see Router#add — shortcut for HEAD requests.
344
+ * @param {string} path - Route pattern.
345
+ * @param {...Function} fns - Handler functions.
346
+ * @returns {Router} `this` for chaining.
347
+ */
348
+ head(path, ...fns) { const o = this._extractOpts(fns); this.add('HEAD', path, fns, o); return this; }
349
+ /**
350
+ * @see Router#add — matches every HTTP method.
351
+ * @param {string} path - Route pattern.
352
+ * @param {...Function} fns - Handler functions.
353
+ * @returns {Router} `this` for chaining.
354
+ */
355
+ all(path, ...fns) { const o = this._extractOpts(fns); this.add('ALL', path, fns, o); return this; }
356
+
357
+ /**
358
+ * Chainable route builder — register multiple methods on the same path.
359
+ *
360
+ * @example
361
+ * router.route('/users')
362
+ * .get((req, res) => { ... })
363
+ * .post((req, res) => { ... });
364
+ *
365
+ * @param {string} path - Route pattern.
366
+ * @returns {{ get, post, put, delete, patch, options, head, all: Function }} Chain object with HTTP verb methods.
367
+ */
368
+ route(path)
369
+ {
370
+ const self = this;
371
+ const chain = {};
372
+ for (const m of ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'all'])
373
+ {
374
+ chain[m] = (...fns) => { const o = self._extractOpts(fns); self.add(m.toUpperCase(), path, fns, o); return chain; };
375
+ }
376
+ return chain;
377
+ }
378
+
379
+ // -- Introspection -----------------------------------
380
+
381
+ /**
382
+ * Handle an error thrown by a route handler.
383
+ * Delegates to the app-level error handler if available, otherwise
384
+ * sends a generic 500 JSON response.
385
+ *
386
+ * @param {Error} err - Error object.
387
+ * @param {import('../http/request')} req - HTTP request object.
388
+ * @param {import('../http/response')} res - HTTP response object.
389
+ * @private
390
+ */
391
+ _handleRouteError(err, req, res)
392
+ {
393
+ log.error('route error: %s', err.message || err);
394
+ // Check if the app has an error handler (set via app.onError())
395
+ if (req.app && req.app._errorHandler)
396
+ {
397
+ return req.app._errorHandler(err, req, res, () => {});
398
+ }
399
+ const statusCode = err.statusCode || err.status || 500;
400
+ if (!res.headersSent && !(res.raw && res.raw.headersSent))
401
+ {
402
+ res.status(statusCode).json(
403
+ typeof err.toJSON === 'function'
404
+ ? err.toJSON()
405
+ : { error: err.message || 'Internal Server Error' }
406
+ );
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Return a flat list of all registered routes, including those in
412
+ * mounted child routers. Useful for debugging or auto-documentation.
413
+ *
414
+ * @param {string} [prefix=''] - Internal: accumulated prefix from parent routers.
415
+ * @returns {{ method: string, path: string, secure?: boolean }[]} Registered routes.
416
+ */
417
+ inspect(prefix = '')
418
+ {
419
+ const list = [];
420
+ for (const r of this.routes)
421
+ {
422
+ const entry = { method: r.method, path: joinPath(prefix, r.path) };
423
+ if (r.secure === true) entry.secure = true;
424
+ else if (r.secure === false) entry.secure = false;
425
+ list.push(entry);
426
+ }
427
+ for (const child of this._children)
428
+ {
429
+ const childPrefix = prefix ? joinPath(prefix, child.prefix) : child.prefix;
430
+ list.push(...child.router.inspect(childPrefix));
431
+ }
432
+ return list;
433
+ }
434
+ }
435
+
436
+ module.exports = Router;