@plinthjs/http 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,3091 @@
1
+ 'use strict';
2
+
3
+ var events = require('events');
4
+ var fs = require('fs');
5
+ var path2 = require('path');
6
+ var support = require('@plinthjs/support');
7
+ var crypto = require('crypto');
8
+ var http = require('http');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var path2__default = /*#__PURE__*/_interopDefault(path2);
13
+
14
+ // src/controller.ts
15
+ var Controller = class {
16
+ };
17
+ var MIME_TYPES = {
18
+ txt: "text/plain; charset=utf-8",
19
+ html: "text/html; charset=utf-8",
20
+ htm: "text/html; charset=utf-8",
21
+ css: "text/css; charset=utf-8",
22
+ csv: "text/csv; charset=utf-8",
23
+ js: "text/javascript; charset=utf-8",
24
+ mjs: "text/javascript; charset=utf-8",
25
+ json: "application/json; charset=utf-8",
26
+ xml: "application/xml; charset=utf-8",
27
+ pdf: "application/pdf",
28
+ zip: "application/zip",
29
+ gz: "application/gzip",
30
+ png: "image/png",
31
+ jpg: "image/jpeg",
32
+ jpeg: "image/jpeg",
33
+ gif: "image/gif",
34
+ webp: "image/webp",
35
+ svg: "image/svg+xml",
36
+ ico: "image/x-icon",
37
+ woff: "font/woff",
38
+ woff2: "font/woff2",
39
+ ttf: "font/ttf",
40
+ mp4: "video/mp4",
41
+ mp3: "audio/mpeg",
42
+ wav: "audio/wav",
43
+ bin: "application/octet-stream"
44
+ };
45
+ function mimeTypeFor(filePath) {
46
+ const ext = path2__default.default.extname(filePath).slice(1).toLowerCase();
47
+ return MIME_TYPES[ext] ?? "application/octet-stream";
48
+ }
49
+ function contentDisposition(filename) {
50
+ const ascii = filename.replaceAll(/[^ -~]/g, "_").replaceAll(/["\\]/g, String.raw`\$&`);
51
+ let header = `attachment; filename="${ascii}"`;
52
+ if (/[^ -~]/.test(filename)) {
53
+ header += `; filename*=UTF-8''${encodeURIComponent(filename)}`;
54
+ }
55
+ return header;
56
+ }
57
+ function isIterableValue(value) {
58
+ if (typeof value !== "object" || value === null) return false;
59
+ const candidate = value;
60
+ return typeof candidate[Symbol.iterator] === "function" || typeof candidate[Symbol.asyncIterator] === "function";
61
+ }
62
+ function stringifyJson(value) {
63
+ return JSON.stringify(value);
64
+ }
65
+ async function* jsonArrayChunks(items) {
66
+ yield "[";
67
+ let first = true;
68
+ for await (const item of items) {
69
+ yield `${first ? "" : ","}${stringifyJson(item) ?? "null"}`;
70
+ first = false;
71
+ }
72
+ yield "]";
73
+ }
74
+ async function* jsonChunks(data) {
75
+ if (isIterableValue(data)) {
76
+ yield* jsonArrayChunks(data);
77
+ return;
78
+ }
79
+ yield "{";
80
+ let first = true;
81
+ for (const [key, value] of Object.entries(data)) {
82
+ yield `${first ? "" : ","}${JSON.stringify(key)}:`;
83
+ first = false;
84
+ if (isIterableValue(value)) yield* jsonArrayChunks(value);
85
+ else yield stringifyJson(value) ?? "null";
86
+ }
87
+ yield "}";
88
+ }
89
+ function serializeCookie(name, value, options = {}) {
90
+ const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path ?? "/"}`];
91
+ if (options.maxAge !== void 0) parts.push(`Max-Age=${Math.floor(options.maxAge)}`);
92
+ if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);
93
+ if (options.domain) parts.push(`Domain=${options.domain}`);
94
+ if (options.secure) parts.push("Secure");
95
+ if (options.httpOnly) parts.push("HttpOnly");
96
+ if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
97
+ return parts.join("; ");
98
+ }
99
+ var Response = class _Response {
100
+ /** The HTTP status code. */
101
+ status;
102
+ /** The response headers (canonical-ish casing as set). */
103
+ headers;
104
+ /** The response body, already serialized to a string (or `null` for no body). */
105
+ body;
106
+ /** Any `Set-Cookie` header values, kept separate so multiple cookies survive serialization. */
107
+ setCookies = [];
108
+ /**
109
+ * The encoding used to flush {@link Response.body}. Text bodies are UTF-8; binary file bodies are
110
+ * read and written as `'binary'` (latin1) so every byte survives the string round-trip intact and
111
+ * matches the `Content-Length` set by {@link Response.file}/{@link Response.download}.
112
+ */
113
+ bodyEncoding = "utf8";
114
+ /** Flash intent queued by {@link Response.with}; drained by the session layer (Laravel flash). */
115
+ flashData = {};
116
+ /** The streaming body source, when this is a streamed response (see {@link Response.stream}). */
117
+ streamSource;
118
+ /** The registered response macros, shared across all instances (the `Response::macro` registry). */
119
+ static macros = /* @__PURE__ */ new Map();
120
+ constructor(body, status) {
121
+ this.status = status;
122
+ this.headers = {};
123
+ this.body = body;
124
+ }
125
+ /** Begin building a response with an optional body and status. The `response()` helper equivalent. */
126
+ static make(body = null, status = 200) {
127
+ return new _Response(body, status);
128
+ }
129
+ /** Build a JSON response, serializing `data` and setting `Content-Type`. The `response()->json()` equivalent. */
130
+ static json(data, status = 200) {
131
+ return new _Response(null, status).json(data, status);
132
+ }
133
+ /** Build a plain-text response. */
134
+ static text(body, status = 200) {
135
+ return new _Response(null, status).text(body);
136
+ }
137
+ /** Build an HTML response. */
138
+ static html(body, status = 200) {
139
+ return new _Response(null, status).html(body);
140
+ }
141
+ /** Build an empty `204 No Content` response. The `response()->noContent()` equivalent. */
142
+ static noContent(status = 204) {
143
+ return new _Response(null, status).noContent(status);
144
+ }
145
+ /** Build a redirect to `url`. The `redirect()` helper equivalent. */
146
+ static redirect(url, status = 302) {
147
+ return new _Response(null, status).redirect(url, status);
148
+ }
149
+ /** Build a redirect to `url`. The `redirect()->to()` / `Redirect::to()` equivalent. */
150
+ static redirectTo(url, status = 302) {
151
+ return new _Response(null, status).redirect(url, status);
152
+ }
153
+ /**
154
+ * Build a redirect back to the previous URL, falling back to `fallback` (default `/`) when no
155
+ * referer is known. The `back()` / `redirect()->back()` equivalent.
156
+ *
157
+ * As a static this has no request in scope, so it relies on `fallback`; middleware that knows the
158
+ * incoming `Referer` should pass it explicitly.
159
+ */
160
+ static back(fallback = "/", status = 302) {
161
+ return new _Response(null, status).redirect(fallback, status);
162
+ }
163
+ // --- File responses ------------------------------------------------------
164
+ /**
165
+ * Build a response that serves the file at `path` inline (no download prompt), inferring
166
+ * `Content-Type` from the extension and setting `Content-Length`. The `response()->file()`
167
+ * equivalent. The file is read synchronously into the body.
168
+ */
169
+ static file(filePath, headers = {}) {
170
+ const buffer = fs.readFileSync(filePath);
171
+ const response = new _Response(buffer.toString("binary"), 200);
172
+ response.bodyEncoding = "binary";
173
+ response.headers["Content-Type"] = mimeTypeFor(filePath);
174
+ response.headers["Content-Length"] = String(buffer.byteLength);
175
+ Object.assign(response.headers, headers);
176
+ return response;
177
+ }
178
+ /**
179
+ * Build a download response (`Content-Disposition: attachment`) for the file at `path`, using
180
+ * `name` as the download filename (defaulting to the path's basename). The `response()->download()`
181
+ * equivalent. The file is read synchronously into the body.
182
+ */
183
+ static download(filePath, name, headers = {}) {
184
+ const buffer = fs.readFileSync(filePath);
185
+ const filename = name ?? path2__default.default.basename(filePath);
186
+ const response = new _Response(buffer.toString("binary"), 200);
187
+ response.bodyEncoding = "binary";
188
+ response.headers["Content-Type"] = mimeTypeFor(filePath);
189
+ response.headers["Content-Length"] = String(buffer.byteLength);
190
+ response.headers["Content-Disposition"] = contentDisposition(filename);
191
+ Object.assign(response.headers, headers);
192
+ return response;
193
+ }
194
+ // --- Streaming responses (the `response()->stream*()` family) -------------
195
+ /**
196
+ * Build a streamed response: `source` (an iterable, async iterable, or a generator/factory
197
+ * returning one) is consumed chunk by chunk as the response is flushed, each chunk written to the
198
+ * client as it yields — the `response()->stream()` equivalent. No `Content-Length` is set, so
199
+ * Node serves it with chunked transfer encoding. The kernel/server adapter flushes streamed
200
+ * responses via {@link Response.writeStreamTo}.
201
+ */
202
+ static stream(source, status = 200, headers = {}) {
203
+ const response = new _Response(null, status);
204
+ response.streamSource = source;
205
+ Object.assign(response.headers, headers);
206
+ return response;
207
+ }
208
+ /**
209
+ * Build a streamed download: like {@link Response.stream} but with
210
+ * `Content-Disposition: attachment` for `filename` and a default `application/octet-stream`
211
+ * content type (override via `headers`). The `response()->streamDownload()` equivalent.
212
+ */
213
+ static streamDownload(source, filename, headers = {}) {
214
+ return _Response.stream(source, 200, {
215
+ "Content-Type": "application/octet-stream",
216
+ "Content-Disposition": contentDisposition(filename),
217
+ ...headers
218
+ });
219
+ }
220
+ /**
221
+ * Build a streamed JSON response — the `response()->streamJson()` equivalent. An iterable (or
222
+ * async iterable) of rows is streamed as one JSON array, each row serialized as it yields; an
223
+ * object is emitted key by key with iterable values streamed as arrays and plain values encoded
224
+ * in place. Useful for serializing large result sets without buffering them.
225
+ */
226
+ static streamJson(data, status = 200) {
227
+ return _Response.stream(jsonChunks(data), status, {
228
+ "Content-Type": "application/json; charset=utf-8"
229
+ });
230
+ }
231
+ /** Whether this is a streamed response (flush it with {@link Response.writeStreamTo}). */
232
+ isStream() {
233
+ return this.streamSource !== void 0;
234
+ }
235
+ // --- Macros (the `Response::macro` extension point) -----------------------
236
+ /**
237
+ * Register a reusable response builder under `name`. The Laravel `Response::macro()` equivalent —
238
+ * application code installs a named factory once and invokes it via {@link Response.callMacro}
239
+ * (`Response.callMacro('caps', text)`). Re-registering a name overwrites the previous macro.
240
+ */
241
+ static macro(name, fn) {
242
+ _Response.macros.set(name, fn);
243
+ }
244
+ /** Whether a macro named `name` has been registered. The `Response::hasMacro()` equivalent. */
245
+ static hasMacro(name) {
246
+ return _Response.macros.has(name);
247
+ }
248
+ /** Install many macros at once from a plain object of builders. The `Macroable::mixin()` analog. */
249
+ static mixin(macros) {
250
+ for (const [name, fn] of Object.entries(macros)) _Response.macros.set(name, fn);
251
+ }
252
+ /**
253
+ * Invoke a previously {@link Response.macro registered} macro by name, forwarding `args` and
254
+ * returning the {@link Response} it builds. Throws when no macro is registered under `name` (the
255
+ * `BadMethodCallException` Laravel raises for an unknown macro). Typed pragmatically: callers cast
256
+ * `args` to the macro's expected parameters.
257
+ */
258
+ static callMacro(name, ...args) {
259
+ const fn = _Response.macros.get(name);
260
+ if (fn === void 0) throw new Error(`Response macro [${name}] is not defined.`);
261
+ return fn(...args);
262
+ }
263
+ // --- Fluent builders -----------------------------------------------------
264
+ /** Set the status code. */
265
+ setStatus(code) {
266
+ this.status = code;
267
+ return this;
268
+ }
269
+ /** Set a single header. The `->header()` equivalent. */
270
+ header(name, value) {
271
+ this.headers[name] = value;
272
+ return this;
273
+ }
274
+ /** Merge a header map onto the response. The `->withHeaders()` equivalent. */
275
+ withHeaders(headers) {
276
+ Object.assign(this.headers, headers);
277
+ return this;
278
+ }
279
+ /** Serialize `data` to JSON, set the body and `Content-Type`, and (optionally) the status. */
280
+ json(data, status) {
281
+ if (status !== void 0) this.status = status;
282
+ this.headers["Content-Type"] = "application/json; charset=utf-8";
283
+ this.body = JSON.stringify(data);
284
+ return this;
285
+ }
286
+ /** Set a plain-text body and `Content-Type`. */
287
+ text(body) {
288
+ this.headers["Content-Type"] = "text/plain; charset=utf-8";
289
+ this.body = body;
290
+ return this;
291
+ }
292
+ /** Set an HTML body and `Content-Type`. */
293
+ html(body) {
294
+ this.headers["Content-Type"] = "text/html; charset=utf-8";
295
+ this.body = body;
296
+ return this;
297
+ }
298
+ /** Clear the body and set a no-content status. */
299
+ noContent(status = 204) {
300
+ this.status = status;
301
+ this.body = null;
302
+ return this;
303
+ }
304
+ /** Turn this into a redirect to `url` with a `Location` header. */
305
+ redirect(url, status = 302) {
306
+ this.status = status;
307
+ this.headers["Location"] = url;
308
+ this.body = null;
309
+ return this;
310
+ }
311
+ /** Alias of {@link Response.redirect} reading as `redirect()->to()`. */
312
+ redirectTo(url, status = 302) {
313
+ return this.redirect(url, status);
314
+ }
315
+ /** Retarget this redirect at `fallback` (the previous-URL fallback when no referer is known). */
316
+ back(fallback = "/", status = 302) {
317
+ return this.redirect(fallback, status);
318
+ }
319
+ with(keyOrData, value) {
320
+ if (typeof keyOrData === "string") {
321
+ this.flashData[keyOrData] = value;
322
+ } else {
323
+ Object.assign(this.flashData, keyOrData);
324
+ }
325
+ return this;
326
+ }
327
+ /**
328
+ * Flash an `input` bag for repopulating a form after a redirect. The `redirect()->withInput()`
329
+ * equivalent: the bag is stored under the `input` flash key.
330
+ */
331
+ withInput(input) {
332
+ this.flashData["input"] = input;
333
+ return this;
334
+ }
335
+ /**
336
+ * Flash a validation `errors` bag. The `redirect()->withErrors()` equivalent: the bag is stored
337
+ * under the `errors` flash key for the next request's view.
338
+ */
339
+ withErrors(errors) {
340
+ this.flashData["errors"] = errors;
341
+ return this;
342
+ }
343
+ /** The queued flash intent (a copy) for the session layer to consume. */
344
+ flashes() {
345
+ return { ...this.flashData };
346
+ }
347
+ /** Read a single queued flash value by key, or `undefined` when absent. */
348
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is a caller-supplied cast for the stored flash value
349
+ getFlash(key) {
350
+ return key in this.flashData ? this.flashData[key] : void 0;
351
+ }
352
+ /** Queue a `Set-Cookie` header. Multiple calls accumulate distinct cookies. */
353
+ cookie(name, value, options) {
354
+ this.setCookies.push(serializeCookie(name, value, options));
355
+ return this;
356
+ }
357
+ /** The queued `Set-Cookie` header values (a copy). */
358
+ cookies() {
359
+ return [...this.setCookies];
360
+ }
361
+ // --- Output --------------------------------------------------------------
362
+ /** Write the status, headers, and cookies (everything before the body) to `res`. */
363
+ writeHead(res) {
364
+ const headers = this.headers;
365
+ for (const name of Object.keys(headers)) res.setHeader(name, headers[name]);
366
+ if (this.setCookies.length > 0) res.setHeader("Set-Cookie", this.setCookies);
367
+ res.statusCode = this.status;
368
+ }
369
+ /**
370
+ * Flush this response to a Node {@link ServerResponse}: status, headers, cookies, then body.
371
+ * Streamed responses ({@link Response.stream}) must be flushed with the async
372
+ * {@link Response.writeStreamTo} instead — calling `writeTo` on one throws so a stream is never
373
+ * silently dropped.
374
+ */
375
+ writeTo(res) {
376
+ if (this.streamSource !== void 0) {
377
+ throw new Error("This is a streamed response; flush it with writeStreamTo() instead.");
378
+ }
379
+ this.writeHead(res);
380
+ if (this.body === null) {
381
+ res.end();
382
+ } else {
383
+ res.end(this.body, this.bodyEncoding);
384
+ }
385
+ }
386
+ /**
387
+ * Flush a streamed response to a Node {@link ServerResponse}: status, headers, and cookies first,
388
+ * then each chunk the {@link StreamSource} yields is written as it arrives (respecting
389
+ * backpressure via `drain`), and the response is ended when the source completes. Falls back to
390
+ * {@link Response.writeTo} semantics when this response has no stream.
391
+ */
392
+ async writeStreamTo(res) {
393
+ const source = this.streamSource;
394
+ if (source === void 0) {
395
+ this.writeTo(res);
396
+ return;
397
+ }
398
+ this.writeHead(res);
399
+ const iterable = typeof source === "function" ? source() : source;
400
+ for await (const chunk of iterable) {
401
+ if (!res.write(chunk)) await events.once(res, "drain");
402
+ }
403
+ res.end();
404
+ }
405
+ };
406
+
407
+ // src/exceptions.ts
408
+ var EXCEPTION_HANDLER = /* @__PURE__ */ Symbol("mason.exceptionHandler");
409
+ var HttpException = class extends Error {
410
+ constructor(status, message = "", headers = {}) {
411
+ super(message);
412
+ this.status = status;
413
+ this.name = "HttpException";
414
+ this.headers = headers;
415
+ }
416
+ status;
417
+ /** Extra headers to attach to the rendered response. */
418
+ headers;
419
+ };
420
+ var NotFoundHttpException = class extends HttpException {
421
+ constructor(message = "Not Found") {
422
+ super(404, message);
423
+ this.name = "NotFoundHttpException";
424
+ }
425
+ };
426
+ var MethodNotAllowedHttpException = class extends HttpException {
427
+ constructor(allowed = [], message = "Method Not Allowed") {
428
+ super(405, message, allowed.length > 0 ? { Allow: allowed.join(", ") } : {});
429
+ this.name = "MethodNotAllowedHttpException";
430
+ }
431
+ };
432
+ function reasonPhrase(status) {
433
+ const phrases = {
434
+ 400: "Bad Request",
435
+ 401: "Unauthorized",
436
+ 403: "Forbidden",
437
+ 404: "Not Found",
438
+ 405: "Method Not Allowed",
439
+ 422: "Unprocessable Entity",
440
+ 500: "Internal Server Error"
441
+ };
442
+ return phrases[status] ?? "Error";
443
+ }
444
+ var ExceptionHandler = class {
445
+ /**
446
+ * @param debug When `true`, non-HTTP errors expose their real message (and a stack hint in JSON);
447
+ * otherwise they render a generic `500`. The `APP_DEBUG` equivalent.
448
+ */
449
+ constructor(debug = false) {
450
+ this.debug = debug;
451
+ }
452
+ debug;
453
+ /** Reportable callbacks, run in registration order by {@link ExceptionHandler.report}. */
454
+ reportCallbacks = [];
455
+ /** Renderable callbacks, tried in registration order by {@link ExceptionHandler.render}. */
456
+ renderCallbacks = [];
457
+ /**
458
+ * Error constructors whose instances are not reported. Seeded with {@link HttpException} (an
459
+ * `instanceof` check, so every subclass — 404/405/… — is covered too), mirroring Laravel's small
460
+ * internal don't-report list. Extend with {@link ExceptionHandler.ignore} / shrink with
461
+ * {@link ExceptionHandler.stopIgnoring}.
462
+ */
463
+ ignored = [HttpException];
464
+ /** The terminal report sink; a no-op by default. Replace via {@link ExceptionHandler.reportUsing}. */
465
+ reportSink = () => {
466
+ };
467
+ /** When `true`, an already-reported error instance is skipped on later {@link report} calls. */
468
+ deduplicate = false;
469
+ /** Exception mappings, applied (first match wins) before reporting/rendering. See {@link map}. */
470
+ mappers = [];
471
+ /** Per-constructor log levels consulted by {@link ExceptionHandler.levelFor}. */
472
+ levels = [];
473
+ /**
474
+ * Input keys never flashed back to the session on a validation redirect — the Laravel
475
+ * `$dontFlash` list, seeded with its defaults. `@plinthjs/http` itself has no redirect/flash path,
476
+ * so the list is stored here and exposed via {@link ExceptionHandler.getDontFlash} for the
477
+ * session/validation layer to consume when it re-flashes old input.
478
+ */
479
+ dontFlashKeys = ["current_password", "password", "password_confirmation"];
480
+ /** Error instances already reported, for {@link ExceptionHandler.withoutDuplicates} de-duplication. */
481
+ reported = /* @__PURE__ */ new WeakSet();
482
+ /**
483
+ * The status code an error should render as: an {@link HttpException}'s status, a numeric `status`
484
+ * carried structurally by the error (e.g. a validation `422` or authorization `403`), else `500`.
485
+ */
486
+ statusFor(error) {
487
+ if (error instanceof HttpException) return error.status;
488
+ return carriedStatus(error) ?? 500;
489
+ }
490
+ // --- Exception mapping / levels / dontFlash --------------------------------
491
+ /**
492
+ * Map one exception type to another: whenever an instance of `from` reaches the handler, it is
493
+ * first converted via `to` and the *result* is reported and rendered instead. The Laravel
494
+ * `$exceptions->map(From::class, fn ($e) => new To(..., $e))` equivalent. Mappings are checked in
495
+ * registration order; the first `instanceof` match applies (once — the mapped error is not
496
+ * re-mapped). Chains.
497
+ */
498
+ map(from, to) {
499
+ this.mappers.push([from, to]);
500
+ return this;
501
+ }
502
+ /** Apply the first matching {@link ExceptionHandler.map} mapping to `error`, if any. */
503
+ mapException(error) {
504
+ for (const [from, to] of this.mappers) {
505
+ if (error instanceof from) return to(error);
506
+ }
507
+ return error;
508
+ }
509
+ /**
510
+ * Set the log level instances of `ctor` are reported at — the Laravel
511
+ * `$exceptions->level(Type::class, LogLevel::WARNING)` equivalent. The level is surfaced as the
512
+ * `level` key of the context passed to the {@link ReportSink}. Chains.
513
+ */
514
+ level(ctor, logLevel) {
515
+ this.levels.push([ctor, logLevel]);
516
+ return this;
517
+ }
518
+ /** The log level `error` reports at: the first registered `instanceof` match, else `'error'`. */
519
+ levelFor(error) {
520
+ for (const [ctor, logLevel] of this.levels) {
521
+ if (error instanceof ctor) return logLevel;
522
+ }
523
+ return "error";
524
+ }
525
+ /**
526
+ * Replace the list of input keys that must never be flashed back on a validation redirect — the
527
+ * Laravel `$exceptions->dontFlash([...])` equivalent. Defaults to `current_password`, `password`,
528
+ * and `password_confirmation`. There is no redirect/flash path inside `@plinthjs/http`, so the list
529
+ * is exposed via {@link ExceptionHandler.getDontFlash} for the session/validation layer that
530
+ * re-flashes old input. Chains.
531
+ */
532
+ dontFlash(keys) {
533
+ this.dontFlashKeys = [...keys];
534
+ return this;
535
+ }
536
+ /** The input keys never flashed back on a validation redirect (a copy). */
537
+ getDontFlash() {
538
+ return [...this.dontFlashKeys];
539
+ }
540
+ // --- Reporting (the `report()` half of Laravel's Handler) -----------------
541
+ /**
542
+ * Register a reportable callback. Runs in order during {@link ExceptionHandler.report}; returning
543
+ * `false` from a callback stops all further reporting of that error. Chains.
544
+ */
545
+ reportable(callback) {
546
+ this.reportCallbacks.push(callback);
547
+ return this;
548
+ }
549
+ /**
550
+ * Add error constructors to the don't-report list (the Laravel `ignore()` / `$dontReport`
551
+ * equivalent). Matching is by `instanceof`, so a base class also suppresses its subclasses. Chains.
552
+ */
553
+ ignore(...classes) {
554
+ this.ignored.push(...classes);
555
+ return this;
556
+ }
557
+ /** Alias of {@link ExceptionHandler.ignore} — the Laravel `$dontReport` spelling. */
558
+ dontReport(...classes) {
559
+ return this.ignore(...classes);
560
+ }
561
+ /** Remove error constructors from the don't-report list. The Laravel `stopIgnoring()` equivalent. */
562
+ stopIgnoring(...classes) {
563
+ const drop = new Set(classes);
564
+ for (let i = this.ignored.length - 1; i >= 0; i--) {
565
+ if (drop.has(this.ignored[i])) this.ignored.splice(i, 1);
566
+ }
567
+ return this;
568
+ }
569
+ /** Whether `error` should be reported: `false` when it (or a superclass) is in the ignore list. */
570
+ shouldReport(error) {
571
+ for (const ctor of this.ignored) {
572
+ if (error instanceof ctor) return false;
573
+ }
574
+ return true;
575
+ }
576
+ /** Replace the terminal report sink (the logger seam). The Laravel `reportable`/logger wiring. */
577
+ reportUsing(sink) {
578
+ this.reportSink = sink;
579
+ return this;
580
+ }
581
+ /** De-duplicate reports: the same error instance is reported at most once. The `withoutDuplicates()` flag. */
582
+ withoutDuplicates() {
583
+ this.deduplicate = true;
584
+ return this;
585
+ }
586
+ /**
587
+ * A hook for additional report context, merged into every report. Override in a subclass to attach
588
+ * request-scoped data (user id, etc.). The Laravel `Handler::context()` equivalent.
589
+ */
590
+ context() {
591
+ return {};
592
+ }
593
+ /**
594
+ * Report `error`: if {@link ExceptionHandler.shouldReport} and not a duplicate (when
595
+ * {@link ExceptionHandler.withoutDuplicates} is on), run the reportable callbacks in order — a
596
+ * `false` return stops the chain (the default sink is skipped) — otherwise fall through to the
597
+ * terminal sink. The Laravel `Handler::report()` equivalent.
598
+ */
599
+ report(error) {
600
+ const mapped = this.mapException(error);
601
+ if (!this.shouldReport(mapped)) return;
602
+ if (this.deduplicate && typeof mapped === "object" && mapped !== null) {
603
+ if (this.reported.has(mapped)) return;
604
+ this.reported.add(mapped);
605
+ }
606
+ for (const callback of this.reportCallbacks) {
607
+ if (callback(mapped) === false) return;
608
+ }
609
+ this.reportSink(mapped, { level: this.levelFor(mapped), ...this.context() });
610
+ }
611
+ /** Register a renderable callback, tried first by {@link ExceptionHandler.render}. Chains. */
612
+ renderable(callback) {
613
+ this.renderCallbacks.push(callback);
614
+ return this;
615
+ }
616
+ /**
617
+ * Render `error` to a {@link Response}, negotiating JSON vs. HTML from `req`. Any
618
+ * {@link ExceptionHandler.map} mapping is applied first, so renderables and the default rendering
619
+ * see the mapped error.
620
+ */
621
+ render(req, rawError) {
622
+ const error = this.mapException(rawError);
623
+ for (const callback of this.renderCallbacks) {
624
+ const response = callback(error, req);
625
+ if (response !== void 0) return response;
626
+ }
627
+ const status = this.statusFor(error);
628
+ const isHttp = error instanceof HttpException;
629
+ const message = this.messageFor(error, status, isHttp);
630
+ const extraHeaders = isHttp ? error.headers : {};
631
+ const errors = carriedErrors(error);
632
+ if (req.wantsJson()) {
633
+ const payload = { message, status };
634
+ if (errors !== void 0) payload["errors"] = errors;
635
+ if (this.debug && error instanceof Error && error.stack) payload["exception"] = error.stack;
636
+ return Response.json(payload, status).withHeaders(extraHeaders);
637
+ }
638
+ if (errors !== void 0) {
639
+ const back = req.header("referer") ?? "/";
640
+ return Response.redirectTo(back).withErrors(errors).withInput(req.except(this.dontFlashKeys));
641
+ }
642
+ const html = `<!doctype html><html><head><title>${status} ${reasonPhrase(status)}</title></head><body><h1>${status} ${reasonPhrase(status)}</h1><p>${escapeHtml(message)}</p></body></html>`;
643
+ return Response.html(html, status).withHeaders(extraHeaders);
644
+ }
645
+ /** The user-facing message for an error, hiding internals for non-debug `500`s. */
646
+ messageFor(error, status, isHttp) {
647
+ if (isHttp && error instanceof HttpException && error.message) return error.message;
648
+ if (status >= 500 && !this.debug) return reasonPhrase(status);
649
+ if (error instanceof Error && error.message) return error.message;
650
+ return reasonPhrase(status);
651
+ }
652
+ };
653
+ function carriedStatus(error) {
654
+ if (typeof error === "object" && error !== null && "status" in error) {
655
+ const { status } = error;
656
+ if (typeof status === "number") return status;
657
+ }
658
+ return void 0;
659
+ }
660
+ function carriedErrors(error) {
661
+ if (typeof error === "object" && error !== null && "errors" in error) {
662
+ const { errors } = error;
663
+ if (typeof errors === "object" && errors !== null) {
664
+ return errors;
665
+ }
666
+ }
667
+ return void 0;
668
+ }
669
+ function escapeHtml(input) {
670
+ return input.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
671
+ }
672
+
673
+ // src/middleware.ts
674
+ function isTerminable(entry) {
675
+ return typeof entry === "object" && typeof entry.terminate === "function";
676
+ }
677
+ function toHandle(entry) {
678
+ return typeof entry === "function" ? entry : entry.handle;
679
+ }
680
+ function composeMiddleware(stack, destination) {
681
+ let next = destination;
682
+ for (let index = stack.length - 1; index >= 0; index -= 1) {
683
+ const entry = stack[index];
684
+ if (entry === void 0) continue;
685
+ const handle = toHandle(entry);
686
+ const inner = next;
687
+ next = (request) => handle(request, inner);
688
+ }
689
+ return next;
690
+ }
691
+ function runMiddleware(req, stack, destination) {
692
+ return composeMiddleware(stack, destination)(req);
693
+ }
694
+ async function terminateMiddleware(req, res, stack) {
695
+ for (const entry of stack) {
696
+ if (isTerminable(entry)) {
697
+ await entry.terminate(req, res);
698
+ }
699
+ }
700
+ }
701
+
702
+ // src/kernel.ts
703
+ function isClassConstructor(fn) {
704
+ return Function.prototype.toString.call(fn).startsWith("class");
705
+ }
706
+ function sameReferences(a, b) {
707
+ return a.length === b.length && a.every((reference, index) => reference === b[index]);
708
+ }
709
+ var HttpKernel = class _HttpKernel {
710
+ router;
711
+ middleware;
712
+ container;
713
+ exceptionHandler;
714
+ /** Composed per-route pipelines; see {@link HttpKernel.routePipeline} for the reuse rules. */
715
+ pipelines = /* @__PURE__ */ new WeakMap();
716
+ /** Resolved route actions (`null` = plain closure). `route.handler` is immutable, so no staleness. */
717
+ actions = /* @__PURE__ */ new WeakMap();
718
+ constructor(router, options = {}) {
719
+ this.router = router;
720
+ this.middleware = options.middleware ?? [];
721
+ this.container = options.container;
722
+ this.exceptionHandler = _HttpKernel.resolveHandler(options.exceptionHandler, this.container);
723
+ }
724
+ /**
725
+ * Choose the {@link ExceptionHandler} by precedence: an explicit `options.exceptionHandler` wins;
726
+ * otherwise a handler bound under {@link EXCEPTION_HANDLER} in the container (so an app or service
727
+ * provider can install a custom handler) is resolved; otherwise a fresh {@link ExceptionHandler}.
728
+ */
729
+ static resolveHandler(explicit, container) {
730
+ if (explicit !== void 0) return explicit;
731
+ if (container?.bound(EXCEPTION_HANDLER) === true) {
732
+ return container.make(EXCEPTION_HANDLER);
733
+ }
734
+ return new ExceptionHandler();
735
+ }
736
+ /**
737
+ * The active {@link ExceptionHandler} (after applying the {@link HttpKernel.resolveHandler}
738
+ * precedence). Exposed so app wiring can configure its report sink, ignore list, etc.
739
+ */
740
+ getExceptionHandler() {
741
+ return this.exceptionHandler;
742
+ }
743
+ /**
744
+ * Report `error` (guarded so a throwing report can never break rendering — the Laravel handler
745
+ * also isolates reporting from rendering), then render it to a {@link Response}. Used at both
746
+ * pipeline catch sites so every thrown error is both reported and rendered.
747
+ */
748
+ reportThenRender(req, error) {
749
+ try {
750
+ this.exceptionHandler.report(error);
751
+ } catch {
752
+ }
753
+ return this.exceptionHandler.render(req, error);
754
+ }
755
+ /** Run `req` through the full pipeline and return the resulting {@link Response}. */
756
+ async handle(req) {
757
+ let routeTerminables = [];
758
+ const dispatch2 = async (outerReq) => {
759
+ try {
760
+ const matched = this.router.match(outerReq.method(), outerReq.path(), outerReq.host());
761
+ if (matched.type === "not-found") throw new NotFoundHttpException();
762
+ if (matched.type === "method-not-allowed") {
763
+ throw new MethodNotAllowedHttpException(matched.allowed);
764
+ }
765
+ const entry = this.routePipeline(matched.route);
766
+ routeTerminables = entry.terminables;
767
+ let prepared = outerReq.withParams(matched.params);
768
+ const routeName = matched.route.getName();
769
+ if (routeName !== void 0) prepared = prepared.withRouteName(routeName);
770
+ const bound = await this.bindModels(prepared, matched.params);
771
+ return await entry.pipeline(bound);
772
+ } catch (error) {
773
+ return this.reportThenRender(outerReq, error);
774
+ }
775
+ };
776
+ let response;
777
+ try {
778
+ response = this.middleware.length === 0 ? await dispatch2(req) : await runMiddleware(req, this.middleware, dispatch2);
779
+ } catch (error) {
780
+ response = this.reportThenRender(req, error);
781
+ }
782
+ if (req.method() === "HEAD") response.body = null;
783
+ if (this.middleware.length > 0) {
784
+ await terminateMiddleware(req, response, [...this.middleware, ...routeTerminables]);
785
+ } else if (routeTerminables.length > 0) {
786
+ await terminateMiddleware(req, response, routeTerminables);
787
+ }
788
+ return response;
789
+ }
790
+ /**
791
+ * The composed pipeline for `route` (its resolved middleware stack ending in the route action).
792
+ * Cached per route so alias/group resolution and closure composition happen once, not per
793
+ * request. A cached entry is reused only while the route's reference list is unchanged
794
+ * ({@link sameReferences} — `route.middleware(...)` can append after registration), and stacks
795
+ * containing `string` references are never cached: their alias/group registrations live in
796
+ * mutable router registries and must be re-resolved each dispatch.
797
+ */
798
+ routePipeline(route) {
799
+ const source = route.getMiddleware();
800
+ const cached = this.pipelines.get(route);
801
+ if (cached !== void 0 && sameReferences(cached.source, source)) return cached;
802
+ const entries = this.router.resolveMiddleware(source);
803
+ const built = {
804
+ source,
805
+ terminables: entries.filter((entry) => isTerminable(entry)),
806
+ pipeline: composeMiddleware(entries, (request) => this.runAction(route, request))
807
+ };
808
+ if (!source.some((reference) => typeof reference === "string")) {
809
+ this.pipelines.set(route, built);
810
+ }
811
+ return built;
812
+ }
813
+ /**
814
+ * Resolve the router's route-model bindings for the matched params, attaching the resolved models
815
+ * to the request. A binding that resolves to nullish is a 404 (implicit-binding "not found").
816
+ */
817
+ async bindModels(req, params) {
818
+ const keys = Object.keys(params);
819
+ if (keys.length === 0) return req;
820
+ let resolved;
821
+ for (const key of keys) {
822
+ const resolver = this.router.binding(key);
823
+ if (resolver === void 0) continue;
824
+ const value = params[key];
825
+ if (value === void 0) continue;
826
+ const model = await resolver(value, req);
827
+ if (model === null || model === void 0) throw new NotFoundHttpException();
828
+ resolved ??= {};
829
+ resolved[key] = model;
830
+ }
831
+ return resolved === void 0 ? req : req.withBoundModels(resolved);
832
+ }
833
+ /**
834
+ * Invoke a route's handler and coerce the result. A handler is one of: a closure (called with the
835
+ * request), a `[Controller, method]` action, a `[Controller]` / bare-class invokable (its
836
+ * `__invoke` is called), all resolved through the container. Bare-class invokables are told apart
837
+ * from closures by {@link HttpKernel.resolveAction}.
838
+ */
839
+ async runAction(route, req) {
840
+ let target = this.actions.get(route);
841
+ if (target === void 0) {
842
+ target = _HttpKernel.resolveAction(route.handler) ?? null;
843
+ this.actions.set(route, target);
844
+ }
845
+ if (target === null) {
846
+ return _HttpKernel.toResponse(await route.handler(req));
847
+ }
848
+ const [controller, method] = target;
849
+ const instance = this.resolveController(controller);
850
+ const action = instance[method];
851
+ if (typeof action !== "function") {
852
+ throw new TypeError(`Controller action [${controller.name}@${method}] is not callable.`);
853
+ }
854
+ return _HttpKernel.toResponse(await action.call(instance, req));
855
+ }
856
+ /**
857
+ * Normalize a {@link RouteHandler} to the controller class plus the method to invoke, or
858
+ * `undefined` when it is a plain closure. A `[Controller, method]` tuple maps to itself; a
859
+ * `[Controller]` tuple or a bare controller **class** maps to `[Controller, '__invoke']` (the
860
+ * single-action controller form). Classes are distinguished from closures by their stringified
861
+ * source (`class …`), so `router.get(path, Controller)` dispatches to `__invoke` while
862
+ * `router.get(path, (req) => …)` stays a closure.
863
+ */
864
+ static resolveAction(handler) {
865
+ if (Array.isArray(handler)) {
866
+ const [controller, method] = handler;
867
+ return [controller, method ?? "__invoke"];
868
+ }
869
+ if (typeof handler === "function" && isClassConstructor(handler)) {
870
+ return [handler, "__invoke"];
871
+ }
872
+ return void 0;
873
+ }
874
+ /** Resolve a controller instance from the container, or construct it directly when none is set. */
875
+ resolveController(controller) {
876
+ const instance = this.container ? this.container.make(controller) : new controller();
877
+ return instance;
878
+ }
879
+ /** Coerce a handler result into a {@link Response}: strings → HTML, objects → JSON, nullish → 204. */
880
+ static toResponse(result) {
881
+ if (result instanceof Response) return result;
882
+ if (result === null || result === void 0) return Response.noContent();
883
+ if (typeof result === "string") return Response.html(result);
884
+ return Response.json(result);
885
+ }
886
+ };
887
+
888
+ // src/multipart.ts
889
+ var CRLF = "\r\n";
890
+ var HEADER_SEPARATOR = Buffer.from(CRLF + CRLF, "utf8");
891
+ function boundaryFromContentType(contentType) {
892
+ if (contentType === void 0) return void 0;
893
+ const lower = contentType.toLowerCase();
894
+ if (!lower.includes("multipart/form-data")) return void 0;
895
+ const match = /;\s*boundary=("([^"]*)"|[^;]+)/i.exec(contentType);
896
+ if (match === null) return void 0;
897
+ const raw = match[2] ?? match[1] ?? "";
898
+ return raw.trim().length === 0 ? void 0 : raw.trim();
899
+ }
900
+ function parseHeaders(headerBlock) {
901
+ const headers = /* @__PURE__ */ new Map();
902
+ for (const line of headerBlock.split(CRLF)) {
903
+ if (line.length === 0) continue;
904
+ const colon = line.indexOf(":");
905
+ if (colon === -1) continue;
906
+ const name = line.slice(0, colon).trim().toLowerCase();
907
+ const value = line.slice(colon + 1).trim();
908
+ if (name.length > 0) headers.set(name, value);
909
+ }
910
+ return headers;
911
+ }
912
+ function dispositionParam(disposition, key) {
913
+ const quoted = new RegExp(`${key}${String.raw`\s*=\s*`}"([^"]*)"`, "i").exec(disposition);
914
+ if (quoted !== null) return quoted[1];
915
+ const bare = new RegExp(`${key}${String.raw`\s*=\s*`}([^;]+)`, "i").exec(disposition);
916
+ if (bare === null) return void 0;
917
+ return bare[1] === void 0 ? void 0 : bare[1].trim();
918
+ }
919
+ function parsePart(part, fields, files) {
920
+ const headerEnd = part.indexOf(HEADER_SEPARATOR);
921
+ if (headerEnd === -1) return;
922
+ const headerBlock = part.subarray(0, headerEnd).toString("utf8");
923
+ const body = part.subarray(headerEnd + HEADER_SEPARATOR.length);
924
+ const headers = parseHeaders(headerBlock);
925
+ const disposition = headers.get("content-disposition");
926
+ if (disposition === void 0) return;
927
+ const name = dispositionParam(disposition, "name");
928
+ if (name === void 0) return;
929
+ const filename = dispositionParam(disposition, "filename");
930
+ if (filename === void 0) {
931
+ fields.push({ name, value: body.toString("utf8") });
932
+ return;
933
+ }
934
+ files.push({
935
+ name,
936
+ filename,
937
+ contentType: headers.get("content-type") ?? "application/octet-stream",
938
+ // Copy out of the source buffer so the part owns an independent slice of bytes.
939
+ content: Buffer.from(body)
940
+ });
941
+ }
942
+ function parseMultipart(buffer, boundary) {
943
+ const fields = [];
944
+ const files = [];
945
+ if (buffer.length === 0 || boundary.length === 0) return { fields, files };
946
+ const delimiter = Buffer.from(`--${boundary}`, "utf8");
947
+ const positions = [];
948
+ let from = buffer.indexOf(delimiter, 0);
949
+ while (from !== -1) {
950
+ positions.push(from);
951
+ from = buffer.indexOf(delimiter, from + delimiter.length);
952
+ }
953
+ if (positions.length < 2) return { fields, files };
954
+ for (let i = 0; i < positions.length - 1; i++) {
955
+ let start = positions[i] + delimiter.length;
956
+ const end = positions[i + 1];
957
+ if (buffer[start] === 45 && buffer[start + 1] === 45) break;
958
+ if (buffer[start] === 13 && buffer[start + 1] === 10) start += 2;
959
+ let stop = end;
960
+ if (buffer[stop - 2] === 13 && buffer[stop - 1] === 10) stop -= 2;
961
+ if (stop <= start) continue;
962
+ parsePart(buffer.subarray(start, stop), fields, files);
963
+ }
964
+ return { fields, files };
965
+ }
966
+ var UploadedFile = class {
967
+ /** The original filename the client supplied. The `getClientOriginalName()` value. */
968
+ clientOriginalName;
969
+ /** The declared MIME type of the upload. */
970
+ mimeType;
971
+ /** The size of the uploaded content in bytes. */
972
+ size;
973
+ /** The uploaded bytes, held in memory. */
974
+ content;
975
+ constructor(init) {
976
+ this.clientOriginalName = init.clientOriginalName;
977
+ this.mimeType = init.mimeType;
978
+ this.content = init.content;
979
+ this.size = init.content.byteLength;
980
+ }
981
+ /** The raw uploaded bytes. The `get()` content accessor (Laravel `$file->get()`). */
982
+ get() {
983
+ return this.content;
984
+ }
985
+ /** The raw uploaded bytes — an alias for {@link UploadedFile.get} reading more naturally as bytes. */
986
+ buffer() {
987
+ return this.content;
988
+ }
989
+ /** The client-supplied original filename. The `$file->getClientOriginalName()` equivalent. */
990
+ getClientOriginalName() {
991
+ return this.clientOriginalName;
992
+ }
993
+ /**
994
+ * The file extension derived from the client original name (lower-cased, no leading dot), or `''`
995
+ * when the name has none. The `$file->getClientOriginalExtension()` equivalent.
996
+ */
997
+ getClientOriginalExtension() {
998
+ return path2__default.default.extname(this.clientOriginalName).slice(1).toLowerCase();
999
+ }
1000
+ /** The declared MIME type of the upload. The `$file->getMimeType()` equivalent. */
1001
+ getMimeType() {
1002
+ return this.mimeType;
1003
+ }
1004
+ /** The size of the uploaded content in bytes. The `$file->getSize()` equivalent. */
1005
+ getSize() {
1006
+ return this.size;
1007
+ }
1008
+ /**
1009
+ * Whether the upload is valid — here, simply that it carries a non-empty filename. Mirrors the
1010
+ * Laravel `$file->isValid()` predicate at this layer (no PHP upload-error codes exist in Node).
1011
+ */
1012
+ isValid() {
1013
+ return this.clientOriginalName.length > 0;
1014
+ }
1015
+ /**
1016
+ * Write the upload to `directory` under a generated unique name, creating the directory as needed,
1017
+ * and return the full path written. The `$file->store('dir')` equivalent (sans disk abstraction).
1018
+ */
1019
+ store(directory) {
1020
+ return this.storeAs(directory, this.hashName());
1021
+ }
1022
+ /**
1023
+ * Write the upload to `directory` under `name`, creating the directory as needed, and return the
1024
+ * full path written. The `$file->storeAs('dir', 'name')` equivalent.
1025
+ */
1026
+ storeAs(directory, name) {
1027
+ const destination = path2__default.default.join(directory, name);
1028
+ return this.move(destination);
1029
+ }
1030
+ /**
1031
+ * Write the upload to the exact file path `destination`, creating its parent directory as needed,
1032
+ * and return `destination`. The `$file->move()` equivalent — the documented filesystem seam.
1033
+ */
1034
+ move(destination) {
1035
+ fs.mkdirSync(path2__default.default.dirname(destination), { recursive: true });
1036
+ fs.writeFileSync(destination, this.content);
1037
+ return destination;
1038
+ }
1039
+ /**
1040
+ * A unique storage filename preserving the original extension — a timestamp/random base, the way
1041
+ * Laravel's `hashName()` produces a collision-resistant name. Used by {@link UploadedFile.store}.
1042
+ */
1043
+ hashName() {
1044
+ const extension = this.getClientOriginalExtension();
1045
+ const base = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1046
+ return extension.length > 0 ? `${base}.${extension}` : base;
1047
+ }
1048
+ };
1049
+
1050
+ // src/request.ts
1051
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
1052
+ var PayloadTooLargeHttpException = class extends HttpException {
1053
+ constructor(message = "Payload Too Large") {
1054
+ super(413, message);
1055
+ this.name = "PayloadTooLargeHttpException";
1056
+ }
1057
+ };
1058
+ function normalizeHeaders(headers) {
1059
+ const map = /* @__PURE__ */ new Map();
1060
+ if (!headers) return map;
1061
+ for (const key of Object.keys(headers)) {
1062
+ const raw = headers[key];
1063
+ if (raw === void 0) continue;
1064
+ map.set(key.toLowerCase(), Array.isArray(raw) ? raw.join(", ") : raw);
1065
+ }
1066
+ return map;
1067
+ }
1068
+ function parseUrlEncoded(input) {
1069
+ const out = {};
1070
+ const params = new URLSearchParams(input);
1071
+ for (const [key, val] of params.entries()) out[key] = val;
1072
+ return out;
1073
+ }
1074
+ var DUMMY_HOST = "http://localhost";
1075
+ function stripPort(host) {
1076
+ if (host === void 0 || host.length === 0) return void 0;
1077
+ const colon = host.lastIndexOf(":");
1078
+ return colon === -1 ? host : host.slice(0, colon);
1079
+ }
1080
+ var EMPTY_BUFFER = Buffer.alloc(0);
1081
+ function isPlainPath(target) {
1082
+ if (target.length === 0 || target.codePointAt(0) !== 47) return false;
1083
+ let prev = 47;
1084
+ for (let i = 1; i < target.length; i++) {
1085
+ const code = target.codePointAt(i) ?? 0;
1086
+ if (code <= 32 || code >= 127) return false;
1087
+ if (code === 34 || // "
1088
+ code === 35 || // #
1089
+ code === 60 || // <
1090
+ code === 62 || // >
1091
+ code === 63 || // ?
1092
+ code === 92 || // \
1093
+ code === 94 || // ^
1094
+ code === 96 || // `
1095
+ code === 123 || // {
1096
+ code === 124 || // |
1097
+ code === 125) {
1098
+ return false;
1099
+ }
1100
+ if (code === 46 && prev === 47) return false;
1101
+ prev = code;
1102
+ }
1103
+ return true;
1104
+ }
1105
+ var TRUTHY_STRINGS = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
1106
+ function coerceBoolean(val) {
1107
+ if (typeof val === "boolean") return val;
1108
+ if (typeof val === "number") return val === 1;
1109
+ if (typeof val === "string") return TRUTHY_STRINGS.has(val.trim().toLowerCase());
1110
+ return false;
1111
+ }
1112
+ function coerceNumber(val) {
1113
+ if (typeof val === "number") return Number.isFinite(val) ? val : void 0;
1114
+ if (typeof val === "boolean") return val ? 1 : 0;
1115
+ if (typeof val === "string") {
1116
+ const trimmed = val.trim();
1117
+ if (trimmed.length === 0) return void 0;
1118
+ const num = Number(trimmed);
1119
+ return Number.isFinite(num) ? num : void 0;
1120
+ }
1121
+ return void 0;
1122
+ }
1123
+ var Request = class _Request {
1124
+ _method;
1125
+ /** The raw request target as received (`/users?page=2`); URL work happens lazily off it. */
1126
+ _target;
1127
+ /** Memoized WHATWG parse of {@link Request._target}; built only when normalization is needed. */
1128
+ _url;
1129
+ /** Memoized pathname; a {@link isPlainPath plain} target resolves by slicing, sparing `new URL`. */
1130
+ _pathname;
1131
+ _host;
1132
+ /** The host as received (port included, if any) — backs {@link Request.httpHost}. */
1133
+ _httpHost;
1134
+ /** The matched route's name, attached by the kernel after a successful match (for `routeIs`). */
1135
+ _routeName;
1136
+ _headers;
1137
+ /** Lazily-decoded utf8 view of {@link Request._rawBuffer} (eager when constructed from a string). */
1138
+ _rawBody;
1139
+ _rawBuffer;
1140
+ /** Memoized parsed body; `undefined` until the first input access forces the parse. */
1141
+ _parsedBody;
1142
+ /** Memoized result of parsing a `multipart/form-data` body; `undefined` until first accessed. */
1143
+ _multipart;
1144
+ _routeParams;
1145
+ _attributes;
1146
+ _boundModels;
1147
+ _mergedInput;
1148
+ /**
1149
+ * Construct from already-resolved primitives. Prefer {@link Request.fromNode} for a live
1150
+ * {@link IncomingMessage}; this constructor is what synthetic tests use directly.
1151
+ */
1152
+ constructor(init = {}) {
1153
+ this._method = init.method === void 0 ? "GET" : init.method.toUpperCase();
1154
+ this._target = init.url ?? "/";
1155
+ this._url = void 0;
1156
+ this._pathname = void 0;
1157
+ this._headers = normalizeHeaders(init.headers);
1158
+ const rawHost = init.host ?? this._headers.get("host");
1159
+ this._httpHost = rawHost === void 0 || rawHost.length === 0 ? void 0 : rawHost;
1160
+ this._host = stripPort(rawHost);
1161
+ this._routeName = void 0;
1162
+ this._rawBody = init.body;
1163
+ this._rawBuffer = init.bodyBuffer ?? (init.body === void 0 || init.body.length === 0 ? EMPTY_BUFFER : Buffer.from(init.body, "utf8"));
1164
+ this._parsedBody = void 0;
1165
+ this._multipart = void 0;
1166
+ this._routeParams = {};
1167
+ this._attributes = /* @__PURE__ */ new Map();
1168
+ this._boundModels = /* @__PURE__ */ new Map();
1169
+ this._mergedInput = {};
1170
+ }
1171
+ /**
1172
+ * Build a {@link Request} from a live Node {@link IncomingMessage}, draining and parsing the body.
1173
+ * The Laravel `Request::capture()` equivalent for the `node:http` runtime. The body is buffered
1174
+ * up to {@link FromNodeOptions.maxBodyBytes} (default 1 MiB); anything larger rejects with a
1175
+ * {@link PayloadTooLargeHttpException} without buffering past the cap.
1176
+ */
1177
+ static fromNode(req, options = {}) {
1178
+ const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
1179
+ const headers = req.headers;
1180
+ const method = req.method ?? "GET";
1181
+ const url = req.url ?? "/";
1182
+ const declared = headers["content-length"];
1183
+ if (declared !== void 0 && Number(declared) > maxBodyBytes) {
1184
+ return Promise.reject(new PayloadTooLargeHttpException());
1185
+ }
1186
+ if ((declared === void 0 || declared === "0") && headers["transfer-encoding"] === void 0) {
1187
+ return Promise.resolve(new _Request({ method, url, headers }));
1188
+ }
1189
+ return new Promise((resolve, reject) => {
1190
+ let single;
1191
+ let chunks;
1192
+ let total = 0;
1193
+ let settled = false;
1194
+ const onData = (chunk) => {
1195
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1196
+ total += buf.length;
1197
+ if (total > maxBodyBytes) {
1198
+ settled = true;
1199
+ req.removeListener("data", onData);
1200
+ req.pause();
1201
+ reject(new PayloadTooLargeHttpException());
1202
+ return;
1203
+ }
1204
+ if (chunks === void 0) {
1205
+ if (single === void 0) single = buf;
1206
+ else {
1207
+ chunks = [single, buf];
1208
+ single = void 0;
1209
+ }
1210
+ } else {
1211
+ chunks.push(buf);
1212
+ }
1213
+ };
1214
+ req.on("data", onData);
1215
+ req.once("end", () => {
1216
+ if (settled) return;
1217
+ settled = true;
1218
+ const bodyBuffer = chunks === void 0 ? single ?? EMPTY_BUFFER : Buffer.concat(chunks, total);
1219
+ resolve(new _Request({ method, url, headers, bodyBuffer }));
1220
+ });
1221
+ req.once("error", (error) => {
1222
+ if (settled) return;
1223
+ settled = true;
1224
+ reject(error);
1225
+ });
1226
+ });
1227
+ }
1228
+ /** The memoized WHATWG parse of the request target, for the paths that need normalization. */
1229
+ urlObject() {
1230
+ this._url ??= new URL(this._target, DUMMY_HOST);
1231
+ return this._url;
1232
+ }
1233
+ /** The URL-normalized pathname (untrimmed), via the plain-target fast path when possible. */
1234
+ pathname() {
1235
+ let pathname = this._pathname;
1236
+ if (pathname === void 0) {
1237
+ pathname = isPlainPath(this._target) ? this._target : this.urlObject().pathname;
1238
+ this._pathname = pathname;
1239
+ }
1240
+ return pathname;
1241
+ }
1242
+ /** The URL-normalized search component (`?…` or the empty string). */
1243
+ searchString() {
1244
+ if (this._pathname === void 0) this.pathname();
1245
+ const url = this._url;
1246
+ return url === void 0 ? "" : url.search;
1247
+ }
1248
+ /** The raw body as utf8 text, decoded from the byte buffer on first use and memoized. */
1249
+ rawBody() {
1250
+ let raw = this._rawBody;
1251
+ if (raw === void 0) {
1252
+ raw = this._rawBuffer.length === 0 ? "" : this._rawBuffer.toString("utf8");
1253
+ this._rawBody = raw;
1254
+ }
1255
+ return raw;
1256
+ }
1257
+ /** Parse the body on first access and memoize; clones share the memo (the body is immutable). */
1258
+ parsedBody() {
1259
+ this._parsedBody ??= this.parseBody();
1260
+ return this._parsedBody;
1261
+ }
1262
+ /** Parse the raw body according to the `Content-Type`, falling back to an empty object. */
1263
+ parseBody() {
1264
+ const type = (this._headers.get("content-type") ?? "").toLowerCase();
1265
+ if (type.includes("application/json")) {
1266
+ const raw = this.rawBody();
1267
+ if (raw.length === 0) return {};
1268
+ try {
1269
+ const parsed = JSON.parse(raw);
1270
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
1271
+ return parsed;
1272
+ }
1273
+ return {};
1274
+ } catch {
1275
+ return {};
1276
+ }
1277
+ }
1278
+ if (type.includes("application/x-www-form-urlencoded")) {
1279
+ const raw = this.rawBody();
1280
+ if (raw.length === 0) return {};
1281
+ return parseUrlEncoded(raw);
1282
+ }
1283
+ return {};
1284
+ }
1285
+ /** Whether the `Content-Type` declares a `multipart/form-data` body. */
1286
+ isMultipart() {
1287
+ return (this._headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data");
1288
+ }
1289
+ /**
1290
+ * Parse the `multipart/form-data` body once and memoize it. Returns an empty result for any
1291
+ * non-multipart request (so json/urlencoded handling is never disturbed) and is best-effort on a
1292
+ * malformed body. The parse reads the binary-safe {@link Request._rawBuffer}, not the utf8 string.
1293
+ */
1294
+ multipart() {
1295
+ if (this._multipart !== void 0) return this._multipart;
1296
+ let result = { fields: [], files: [] };
1297
+ if (this.isMultipart()) {
1298
+ const boundary = boundaryFromContentType(this._headers.get("content-type"));
1299
+ if (boundary !== void 0) result = parseMultipart(this._rawBuffer, boundary);
1300
+ }
1301
+ this._multipart = result;
1302
+ return result;
1303
+ }
1304
+ // --- Method / URL --------------------------------------------------------
1305
+ /** The HTTP verb (upper-case). The `$request->method()` equivalent. */
1306
+ method() {
1307
+ return this._method;
1308
+ }
1309
+ /** Whether the request uses the given verb (case-insensitive). The `$request->isMethod()` equivalent. */
1310
+ isMethod(method) {
1311
+ return this._method === method.toUpperCase();
1312
+ }
1313
+ /** The path with no query string, e.g. `/users`. The `$request->path()` equivalent. */
1314
+ path() {
1315
+ const pathname = this.pathname();
1316
+ if (pathname.length > 1 && pathname.endsWith("/")) return pathname.replace(/\/+$/, "");
1317
+ return pathname;
1318
+ }
1319
+ /** The full request target including any query string. The `$request->fullUrl()` equivalent. */
1320
+ url() {
1321
+ return `${this.pathname()}${this.searchString()}`;
1322
+ }
1323
+ /**
1324
+ * The request host without any port (e.g. `acme.myapp.com`), from the constructor `host` or the
1325
+ * `Host` header, or `undefined` when neither is present. The `$request->host()` equivalent, used
1326
+ * by the {@link import('./router').Router}'s subdomain/domain routing.
1327
+ */
1328
+ host() {
1329
+ return this._host;
1330
+ }
1331
+ /**
1332
+ * The request host **including** any port (e.g. `acme.myapp.com:8080`), as received from the
1333
+ * constructor `host` or the `Host` header. The `$request->httpHost()` equivalent; `undefined`
1334
+ * when no host is known (a synthetic request without a `Host` header).
1335
+ */
1336
+ httpHost() {
1337
+ return this._httpHost;
1338
+ }
1339
+ /**
1340
+ * The scheme plus host (e.g. `https://acme.myapp.com:8080`) — the `$request->schemeAndHttpHost()`
1341
+ * equivalent. The scheme is read from the first `X-Forwarded-Proto` hop, defaulting to `http`
1342
+ * (Mason's adapter sits on plain `node:http`; a TLS-terminating proxy sets the header).
1343
+ * `undefined` when no host is known.
1344
+ */
1345
+ schemeAndHttpHost() {
1346
+ if (this._httpHost === void 0) return void 0;
1347
+ return `${this.scheme()}://${this._httpHost}`;
1348
+ }
1349
+ /** The request scheme: the first `X-Forwarded-Proto` hop, defaulting to `http`. */
1350
+ scheme() {
1351
+ const forwarded = this._headers.get("x-forwarded-proto");
1352
+ if (forwarded !== void 0) {
1353
+ const first = forwarded.split(",")[0]?.trim().toLowerCase();
1354
+ if (first === "http" || first === "https") return first;
1355
+ }
1356
+ return "http";
1357
+ }
1358
+ /**
1359
+ * Whether the request arrived over HTTPS — the `$request->isSecure()` equivalent. Reads the first
1360
+ * `X-Forwarded-Proto` hop (Mason sits on plain `node:http` behind a TLS-terminating proxy), so it
1361
+ * is the trust-proxy signal a `secure` cookie or HSTS header should gate on.
1362
+ */
1363
+ isSecure() {
1364
+ return this.scheme() === "https";
1365
+ }
1366
+ /**
1367
+ * The full URL including the query string — `scheme://host/path?query` when the host is known,
1368
+ * otherwise just `/path?query` (matching {@link Request.url} for host-less synthetic requests).
1369
+ * The `$request->fullUrl()` equivalent.
1370
+ */
1371
+ fullUrl() {
1372
+ const base = this.schemeAndHttpHost();
1373
+ return base === void 0 ? this.url() : `${base}${this.pathname()}${this.searchString()}`;
1374
+ }
1375
+ /**
1376
+ * The {@link Request.fullUrl} with `query` merged into the current query string (existing keys
1377
+ * are overridden). The `$request->fullUrlWithQuery()` equivalent.
1378
+ */
1379
+ fullUrlWithQuery(query) {
1380
+ const params = new URLSearchParams(this.urlObject().searchParams);
1381
+ for (const [key, value] of Object.entries(query)) params.set(key, String(value));
1382
+ return this.rebuildFullUrl(params);
1383
+ }
1384
+ /**
1385
+ * The {@link Request.fullUrl} with the given query `keys` removed. The
1386
+ * `$request->fullUrlWithoutQuery()` equivalent.
1387
+ */
1388
+ fullUrlWithoutQuery(keys) {
1389
+ const params = new URLSearchParams(this.urlObject().searchParams);
1390
+ for (const key of keys) params.delete(key);
1391
+ return this.rebuildFullUrl(params);
1392
+ }
1393
+ /** Reassemble the full URL from the current scheme/host/path plus an edited query bag. */
1394
+ rebuildFullUrl(params) {
1395
+ const search = params.toString();
1396
+ const base = this.schemeAndHttpHost() ?? "";
1397
+ return `${base}${this.pathname()}${search.length > 0 ? `?${search}` : ""}`;
1398
+ }
1399
+ // --- Path / route matching (the `is()` family, `*` wildcards) --------------
1400
+ /**
1401
+ * Whether the request path matches any of the wildcard `patterns` — `*` matches any run of
1402
+ * characters. Patterns are matched against the path **without** its leading slash (so
1403
+ * `req.is('admin/*')` matches `/admin/users`), mirroring `$request->is()`.
1404
+ */
1405
+ is(...patterns) {
1406
+ const path3 = this.path().replace(/^\//, "");
1407
+ return patterns.some((pattern) => support.Str.is(pattern, path3));
1408
+ }
1409
+ /**
1410
+ * Whether the matched route's name matches any of the wildcard `patterns` (e.g.
1411
+ * `req.routeIs('users.*')`). The kernel attaches the name after a successful match via
1412
+ * {@link Request.withRouteName}; `false` for an unnamed or unmatched route. The
1413
+ * `$request->routeIs()` equivalent.
1414
+ */
1415
+ routeIs(...patterns) {
1416
+ if (this._routeName === void 0) return false;
1417
+ const name = this._routeName;
1418
+ return patterns.some((pattern) => support.Str.is(pattern, name));
1419
+ }
1420
+ /**
1421
+ * Whether {@link Request.fullUrl} matches any of the wildcard `patterns`. The
1422
+ * `$request->fullUrlIs()` equivalent.
1423
+ */
1424
+ fullUrlIs(...patterns) {
1425
+ const url = this.fullUrl();
1426
+ return patterns.some((pattern) => support.Str.is(pattern, url));
1427
+ }
1428
+ query(key, def) {
1429
+ if (key === void 0) return this.queryAll();
1430
+ if (this.searchString().length === 0) return def;
1431
+ const val = this.urlObject().searchParams.get(key);
1432
+ return val ?? def;
1433
+ }
1434
+ /** Every query parameter as a plain object. The `$request->query()` (no-arg) equivalent. */
1435
+ queryAll() {
1436
+ const out = {};
1437
+ if (this.searchString().length === 0) return out;
1438
+ for (const [key, val] of this.urlObject().searchParams.entries()) out[key] = val;
1439
+ return out;
1440
+ }
1441
+ // --- Headers -------------------------------------------------------------
1442
+ /** Read a single header (case-insensitive), or `def` when absent. The `$request->header()` equivalent. */
1443
+ header(name, def) {
1444
+ return this._headers.get(name.toLowerCase()) ?? def;
1445
+ }
1446
+ /** Every header as a plain object (lower-cased names). The `$request->headers->all()` equivalent. */
1447
+ headers() {
1448
+ return Object.fromEntries(this._headers.entries());
1449
+ }
1450
+ // --- Input (query + body merged) -----------------------------------------
1451
+ /**
1452
+ * The merged input bag: query parameters overlaid with the parsed body (body wins), then with any
1453
+ * values supplied via {@link Request.merge}/{@link Request.mergeIfMissing} (merged values win).
1454
+ */
1455
+ all() {
1456
+ const out = this.queryAll();
1457
+ if (this.isMultipart()) {
1458
+ for (const field of this.multipart().fields) out[field.name] = field.value;
1459
+ }
1460
+ return Object.assign(out, this.parsedBody(), this._mergedInput);
1461
+ }
1462
+ /** Read a merged input value by key, or `def` when absent. The `$request->input()` equivalent. */
1463
+ input(key, def) {
1464
+ const all = this.all();
1465
+ return key in all ? all[key] : def;
1466
+ }
1467
+ /** Only the named keys from the merged input. The `$request->only()` equivalent. */
1468
+ only(keys) {
1469
+ const all = this.all();
1470
+ const out = {};
1471
+ for (const key of keys) if (key in all) out[key] = all[key];
1472
+ return out;
1473
+ }
1474
+ /** Every merged input value except the named keys. The `$request->except()` equivalent. */
1475
+ except(keys) {
1476
+ const all = this.all();
1477
+ const drop = new Set(keys);
1478
+ const out = {};
1479
+ for (const [key, val] of Object.entries(all)) if (!drop.has(key)) out[key] = val;
1480
+ return out;
1481
+ }
1482
+ /** Whether the merged input contains the key. The `$request->has()` equivalent. */
1483
+ has(key) {
1484
+ return key in this.all();
1485
+ }
1486
+ // --- Typed input (the `InteractsWithInput` coercion family) ---------------
1487
+ /** Every merged-input key. The `$request->keys()` equivalent. */
1488
+ keys() {
1489
+ return Object.keys(this.all());
1490
+ }
1491
+ /**
1492
+ * Read an input value coerced to a boolean — `true`/`1`/`'1'`/`'true'`/`'on'`/`'yes'` (strings
1493
+ * case-insensitive) are `true`, anything else `false`. When the key is absent, `def` (default
1494
+ * `false`) is returned. The `$request->boolean()` equivalent.
1495
+ */
1496
+ boolean(key, def) {
1497
+ const all = this.all();
1498
+ if (!(key in all)) return def ?? false;
1499
+ return coerceBoolean(all[key]);
1500
+ }
1501
+ /**
1502
+ * Read an input value coerced to an integer (a finite number, truncated toward zero). When the key
1503
+ * is absent or its value has no numeric reading, `def` (default `0`) is returned. The
1504
+ * `$request->integer()` equivalent.
1505
+ */
1506
+ integer(key, def) {
1507
+ const all = this.all();
1508
+ if (!(key in all)) return def ?? 0;
1509
+ const num = coerceNumber(all[key]);
1510
+ return num === void 0 ? def ?? 0 : Math.trunc(num);
1511
+ }
1512
+ /**
1513
+ * Read an input value coerced to a floating-point number. When the key is absent or its value has
1514
+ * no numeric reading, `def` (default `0`) is returned. The `$request->float()` equivalent.
1515
+ */
1516
+ float(key, def) {
1517
+ const all = this.all();
1518
+ if (!(key in all)) return def ?? 0;
1519
+ const num = coerceNumber(all[key]);
1520
+ return num ?? def ?? 0;
1521
+ }
1522
+ /**
1523
+ * Read an input value coerced to a primitive string. When the key is absent, `def` (default `''`)
1524
+ * is returned. The Laravel `$request->string()` equivalent — note this returns a primitive
1525
+ * `string` rather than a `Stringable`; wrap it with `@plinthjs/support`'s `Str.of()` for fluent
1526
+ * helpers if needed.
1527
+ */
1528
+ string(key, def) {
1529
+ const all = this.all();
1530
+ if (!(key in all)) return def ?? "";
1531
+ return String(all[key]);
1532
+ }
1533
+ /**
1534
+ * Read an input value if (and only if) it is one of `values`, else `undefined`. Generic over the
1535
+ * union of allowed values. The Laravel `$request->enum()` equivalent (returning the value, not a
1536
+ * native enum case). Comparison is by strict equality against the supplied members.
1537
+ */
1538
+ enum(key, values) {
1539
+ const value = this.input(key);
1540
+ return values.includes(value) ? value : void 0;
1541
+ }
1542
+ /**
1543
+ * Wrap the input in a `@plinthjs/support` {@link Collection}: the value at `key` when given (an array
1544
+ * value is collected as-is; any other single value is wrapped as a one-element collection), or all
1545
+ * input values when omitted. The `$request->collect()` equivalent.
1546
+ */
1547
+ collect(key) {
1548
+ if (key === void 0) return support.collect(Object.values(this.all()));
1549
+ const value = this.input(key);
1550
+ if (Array.isArray(value)) return support.collect(value);
1551
+ return value === void 0 ? support.collect([]) : support.collect([value]);
1552
+ }
1553
+ /**
1554
+ * Whether the key is present AND its value is not "blank" (empty string/array/object, or nullish).
1555
+ * The `$request->filled()` equivalent.
1556
+ */
1557
+ filled(key) {
1558
+ const all = this.all();
1559
+ return key in all && support.filled(all[key]);
1560
+ }
1561
+ /** Whether the key is absent OR its value is blank. The inverse of {@link Request.filled}. */
1562
+ isNotFilled(key) {
1563
+ return !this.filled(key);
1564
+ }
1565
+ /** Whether the key is absent from the merged input. The `$request->missing()` equivalent. */
1566
+ missing(key) {
1567
+ return !this.has(key);
1568
+ }
1569
+ /** Whether any of the given keys is present in the merged input. The `$request->hasAny()` equivalent. */
1570
+ hasAny(keys) {
1571
+ const all = this.all();
1572
+ return keys.some((key) => key in all);
1573
+ }
1574
+ /**
1575
+ * Whether any of the given keys is present AND not blank. The `$request->anyFilled()` equivalent.
1576
+ */
1577
+ anyFilled(keys) {
1578
+ return keys.some((key) => this.filled(key));
1579
+ }
1580
+ /**
1581
+ * Run `cb` when `key` is **absent** from the merged input, returning its result; otherwise return
1582
+ * `def`. The `$request->whenMissing()` equivalent.
1583
+ */
1584
+ whenMissing(key, cb, def) {
1585
+ if (this.missing(key)) return cb();
1586
+ return def;
1587
+ }
1588
+ /**
1589
+ * Run `cb` with the input value when `key` is present, returning its result; otherwise return
1590
+ * `def`. The `$request->whenHas()` equivalent.
1591
+ */
1592
+ whenHas(key, cb, def) {
1593
+ const all = this.all();
1594
+ if (key in all) return cb(all[key]);
1595
+ return def;
1596
+ }
1597
+ /**
1598
+ * Run `cb` with the input value when `key` is present AND not blank, returning its result;
1599
+ * otherwise return `def`. The `$request->whenFilled()` equivalent.
1600
+ */
1601
+ whenFilled(key, cb, def) {
1602
+ const all = this.all();
1603
+ if (key in all && support.filled(all[key])) return cb(all[key]);
1604
+ return def;
1605
+ }
1606
+ /**
1607
+ * Return a copy of this request with `input` merged into its input bag, overriding any existing
1608
+ * keys. Immutable: the original is unchanged. The `$request->merge()` equivalent.
1609
+ */
1610
+ merge(input) {
1611
+ const clone = this.cloneRequest();
1612
+ Object.assign(clone._mergedInput, input);
1613
+ return clone;
1614
+ }
1615
+ /**
1616
+ * Return a copy of this request with only the keys of `input` that are not already present in the
1617
+ * merged input added. Immutable: the original is unchanged. The `$request->mergeIfMissing()`
1618
+ * equivalent.
1619
+ */
1620
+ mergeIfMissing(input) {
1621
+ const all = this.all();
1622
+ const additions = {};
1623
+ for (const [key, val] of Object.entries(input)) {
1624
+ if (!(key in all)) additions[key] = val;
1625
+ }
1626
+ const clone = this.cloneRequest();
1627
+ Object.assign(clone._mergedInput, additions);
1628
+ return clone;
1629
+ }
1630
+ // --- Body / content negotiation ------------------------------------------
1631
+ /** The raw, unparsed request body. */
1632
+ body() {
1633
+ return this.rawBody();
1634
+ }
1635
+ /**
1636
+ * Parse and return the JSON body, or `def` when the body is absent/invalid. Unlike {@link all},
1637
+ * this returns the decoded value verbatim (arrays and scalars included). The `$request->json()`
1638
+ * equivalent.
1639
+ */
1640
+ json(def) {
1641
+ const raw = this.rawBody();
1642
+ if (raw.length === 0) return def;
1643
+ try {
1644
+ return JSON.parse(raw);
1645
+ } catch {
1646
+ return def;
1647
+ }
1648
+ }
1649
+ /** Whether the `Content-Type` declares a JSON body. The `$request->isJson()` equivalent. */
1650
+ isJson() {
1651
+ return (this._headers.get("content-type") ?? "").toLowerCase().includes("/json");
1652
+ }
1653
+ /** Whether the client prefers a JSON response (Accept / XHR). The `$request->wantsJson()` equivalent. */
1654
+ wantsJson() {
1655
+ const accept = (this._headers.get("accept") ?? "").toLowerCase();
1656
+ if (accept.includes("/json") || accept.includes("+json")) return true;
1657
+ return (this._headers.get("x-requested-with") ?? "").toLowerCase() === "xmlhttprequest";
1658
+ }
1659
+ // --- Auth / cookies ------------------------------------------------------
1660
+ /** The bearer token from `Authorization: Bearer …`, or `undefined`. The `$request->bearerToken()` equivalent. */
1661
+ bearerToken() {
1662
+ const auth = this._headers.get("authorization");
1663
+ if (!auth) return void 0;
1664
+ const match = /^Bearer\s+(.+)$/i.exec(auth);
1665
+ return match ? match[1] : void 0;
1666
+ }
1667
+ /** Read a cookie by name from the `Cookie` header, or `undefined`. The `$request->cookie()` equivalent. */
1668
+ cookie(name) {
1669
+ return this.cookies()[name];
1670
+ }
1671
+ /** Every cookie parsed from the `Cookie` header. */
1672
+ cookies() {
1673
+ const raw = this._headers.get("cookie");
1674
+ const out = {};
1675
+ if (!raw) return out;
1676
+ for (const pair of raw.split(";")) {
1677
+ const eq = pair.indexOf("=");
1678
+ if (eq === -1) continue;
1679
+ const key = pair.slice(0, eq).trim();
1680
+ if (key.length === 0) continue;
1681
+ const val = pair.slice(eq + 1).trim();
1682
+ out[key] = decodeURIComponent(val);
1683
+ }
1684
+ return out;
1685
+ }
1686
+ /** The client IP, read from `X-Forwarded-For` (first hop) then `X-Real-IP`. The `$request->ip()` equivalent. */
1687
+ ip() {
1688
+ const forwarded = this._headers.get("x-forwarded-for");
1689
+ if (forwarded) {
1690
+ const first = forwarded.split(",")[0];
1691
+ if (first) return first.trim();
1692
+ }
1693
+ return this._headers.get("x-real-ip") ?? void 0;
1694
+ }
1695
+ // --- Files (the `multipart/form-data` upload accessors) -------------------
1696
+ /**
1697
+ * The uploaded file(s) for `key`: a single {@link UploadedFile} when one part used the name, an
1698
+ * array when several did, or `undefined` when none did. The `$request->file('avatar')` equivalent.
1699
+ */
1700
+ file(key) {
1701
+ const matches = this.files(key);
1702
+ if (matches.length === 0) return void 0;
1703
+ if (matches.length === 1) return matches[0];
1704
+ return matches;
1705
+ }
1706
+ /** Every uploaded file submitted under `key`, as an array (empty when none). */
1707
+ files(key) {
1708
+ const out = [];
1709
+ for (const part of this.multipart().files) {
1710
+ if (part.name === key) {
1711
+ out.push(
1712
+ new UploadedFile({
1713
+ clientOriginalName: part.filename,
1714
+ mimeType: part.contentType,
1715
+ content: part.content
1716
+ })
1717
+ );
1718
+ }
1719
+ }
1720
+ return out;
1721
+ }
1722
+ /** Whether a file was uploaded under `key`. The `$request->hasFile('avatar')` equivalent. */
1723
+ hasFile(key) {
1724
+ return this.multipart().files.some((part) => part.name === key);
1725
+ }
1726
+ /**
1727
+ * Every uploaded file keyed by its form field name. A field with multiple files yields an array; a
1728
+ * single-file field yields one {@link UploadedFile}. The `$request->allFiles()` equivalent.
1729
+ */
1730
+ allFiles() {
1731
+ const grouped = /* @__PURE__ */ new Map();
1732
+ for (const part of this.multipart().files) {
1733
+ const file = new UploadedFile({
1734
+ clientOriginalName: part.filename,
1735
+ mimeType: part.contentType,
1736
+ content: part.content
1737
+ });
1738
+ const existing = grouped.get(part.name);
1739
+ if (existing === void 0) grouped.set(part.name, [file]);
1740
+ else existing.push(file);
1741
+ }
1742
+ const out = {};
1743
+ for (const [name, list] of grouped) out[name] = list.length === 1 ? list[0] : list;
1744
+ return out;
1745
+ }
1746
+ // --- Route parameters ----------------------------------------------------
1747
+ /**
1748
+ * A structural copy carrying route parameters and attributes forward (kept immutable). Every
1749
+ * parsed artifact — headers, URL memos, body buffer, parsed/multipart memos — is immutable once
1750
+ * built, so clones share it by reference; only the per-clone bags (route params, attributes,
1751
+ * bound models, merged input) are copied.
1752
+ */
1753
+ cloneRequest() {
1754
+ const clone = new _Request();
1755
+ clone._method = this._method;
1756
+ clone._target = this._target;
1757
+ clone._url = this._url;
1758
+ clone._pathname = this._pathname;
1759
+ clone._host = this._host;
1760
+ clone._httpHost = this._httpHost;
1761
+ clone._routeName = this._routeName;
1762
+ clone._headers = this._headers;
1763
+ clone._rawBody = this._rawBody;
1764
+ clone._rawBuffer = this._rawBuffer;
1765
+ clone._parsedBody = this._parsedBody;
1766
+ clone._multipart = this._multipart;
1767
+ Object.assign(clone._routeParams, this._routeParams);
1768
+ Object.assign(clone._mergedInput, this._mergedInput);
1769
+ for (const [key, value] of this._attributes) clone._attributes.set(key, value);
1770
+ for (const [key, value] of this._boundModels) clone._boundModels.set(key, value);
1771
+ return clone;
1772
+ }
1773
+ /**
1774
+ * Return a copy of this request with the matched route's name attached (read by
1775
+ * {@link Request.routeIs}). Immutable: the original is unchanged. The kernel calls this after a
1776
+ * successful match on a named route.
1777
+ */
1778
+ withRouteName(name) {
1779
+ const clone = this.cloneRequest();
1780
+ clone._routeName = name;
1781
+ return clone;
1782
+ }
1783
+ /**
1784
+ * Return a copy of this request with route parameters attached. Immutable: the original is
1785
+ * unchanged. The router calls this after a successful match.
1786
+ */
1787
+ withParams(params) {
1788
+ const clone = this.cloneRequest();
1789
+ Object.assign(clone._routeParams, params);
1790
+ return clone;
1791
+ }
1792
+ /**
1793
+ * Return a copy of this request with an arbitrary attribute attached — the `$request->attributes`
1794
+ * bag equivalent. Middleware use this to hand request-scoped values (the session, the
1795
+ * authenticated user, …) to downstream handlers without mutating the original.
1796
+ */
1797
+ withAttribute(key, value) {
1798
+ const clone = this.cloneRequest();
1799
+ clone._attributes.set(key, value);
1800
+ return clone;
1801
+ }
1802
+ /** Read a middleware-attached attribute, or `undefined` when absent. */
1803
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T is a caller-supplied cast for the stored value; removing it forces a cast at every call site
1804
+ attribute(key) {
1805
+ return this._attributes.get(key);
1806
+ }
1807
+ /**
1808
+ * Return a copy of this request with `name` set to `value` (case-insensitive) — e.g. a `forceJson`
1809
+ * middleware setting `Accept: application/json`. The header map is copied (clones normally share it
1810
+ * by reference), so the original request is untouched.
1811
+ */
1812
+ withHeader(name, value) {
1813
+ const clone = this.cloneRequest();
1814
+ clone._headers = new Map(this._headers);
1815
+ clone._headers.set(name.toLowerCase(), value);
1816
+ return clone;
1817
+ }
1818
+ /**
1819
+ * Return a copy with resolved route-model bindings attached. The {@link HttpKernel} calls this
1820
+ * after resolving the {@link import('./router').Router}'s bindings for a matched route; handlers
1821
+ * read the resolved model with {@link route}.
1822
+ */
1823
+ withBoundModels(models) {
1824
+ const clone = this.cloneRequest();
1825
+ for (const [key, value] of Object.entries(models)) clone._boundModels.set(key, value);
1826
+ return clone;
1827
+ }
1828
+ /**
1829
+ * The route value for `key`: the resolved bound model when route-model binding applied, otherwise
1830
+ * the raw route parameter (the Laravel `$request->route('user')`). `undefined` when neither exists.
1831
+ */
1832
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- caller-supplied cast for the resolved bound model
1833
+ route(key) {
1834
+ if (this._boundModels.has(key)) return this._boundModels.get(key);
1835
+ return key in this._routeParams ? this._routeParams[key] : void 0;
1836
+ }
1837
+ /** Read a single route parameter, or `def` when absent. The `$request->route('id')` equivalent. */
1838
+ param(name, def) {
1839
+ return name in this._routeParams ? this._routeParams[name] : def;
1840
+ }
1841
+ /** Every route parameter as a plain object. */
1842
+ params() {
1843
+ return { ...this._routeParams };
1844
+ }
1845
+ };
1846
+ var SIGNATURE_PARAM = "signature";
1847
+ var EXPIRES_PARAM = "expires";
1848
+ var ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
1849
+ function escapeRegex(input) {
1850
+ return input.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
1851
+ }
1852
+ function normalizePath(path3) {
1853
+ if (path3 === "/" || path3.startsWith("/") && !path3.endsWith("/") && !path3.includes("//")) {
1854
+ return path3;
1855
+ }
1856
+ let result = path3.startsWith("/") ? path3 : `/${path3}`;
1857
+ result = result.replaceAll(/\/{2,}/g, "/");
1858
+ if (result.length > 1 && result.endsWith("/")) result = result.slice(0, -1);
1859
+ return result;
1860
+ }
1861
+ function compileDomain(domain) {
1862
+ const params = [];
1863
+ let pattern = "";
1864
+ let remaining = domain;
1865
+ while (remaining.length > 0) {
1866
+ const required = /^\{(\w+)\}/.exec(remaining);
1867
+ if (required) {
1868
+ params.push(required[1]);
1869
+ pattern += "([^.]+)";
1870
+ remaining = remaining.slice(required[0].length);
1871
+ continue;
1872
+ }
1873
+ const next = remaining.indexOf("{");
1874
+ const literal = next === -1 ? remaining : remaining.slice(0, next);
1875
+ pattern += escapeRegex(literal);
1876
+ remaining = next === -1 ? "" : remaining.slice(literal.length);
1877
+ }
1878
+ return { regex: new RegExp(`^${pattern}$`, "i"), params };
1879
+ }
1880
+ function parseSegments(path3) {
1881
+ const result = [];
1882
+ for (const segment of path3.split("/")) {
1883
+ if (segment.length === 0) continue;
1884
+ const optional = /^\{(\w+)\?\}$/.exec(segment);
1885
+ if (optional) {
1886
+ result.push({ kind: "optional", name: optional[1] });
1887
+ continue;
1888
+ }
1889
+ const required = /^\{(\w+)\}$/.exec(segment);
1890
+ if (required) {
1891
+ result.push({ kind: "required", name: required[1] });
1892
+ continue;
1893
+ }
1894
+ result.push({ kind: "literal", value: segment });
1895
+ }
1896
+ return result;
1897
+ }
1898
+ function compilePath(path3) {
1899
+ const params = [];
1900
+ let pattern = "";
1901
+ for (const segment of parseSegments(path3)) {
1902
+ if (segment.kind === "optional") {
1903
+ params.push(segment.name);
1904
+ pattern += "(?:/([^/]+))?";
1905
+ } else if (segment.kind === "required") {
1906
+ params.push(segment.name);
1907
+ pattern += "/([^/]+)";
1908
+ } else {
1909
+ pattern += `/${escapeRegex(segment.value)}`;
1910
+ }
1911
+ }
1912
+ return { regex: new RegExp(`^${pattern === "" ? "/" : pattern}$`), params };
1913
+ }
1914
+ function countSegments(path3) {
1915
+ if (path3.length <= 1) return 0;
1916
+ let count = 1;
1917
+ for (let index = 1; index < path3.length; index += 1) {
1918
+ if (path3.codePointAt(index) === 47) count += 1;
1919
+ }
1920
+ return count;
1921
+ }
1922
+ function firstSegment(path3) {
1923
+ if (path3.length <= 1) return "";
1924
+ const end = path3.indexOf("/", 1);
1925
+ return end === -1 ? path3.slice(1) : path3.slice(1, end);
1926
+ }
1927
+ function canonicalize(pathname, params) {
1928
+ const entries = [...params.entries()].filter(([key]) => key !== SIGNATURE_PARAM);
1929
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1930
+ const search = new URLSearchParams(entries).toString();
1931
+ return search.length > 0 ? `${pathname}?${search}` : pathname;
1932
+ }
1933
+ function sign(key, payload) {
1934
+ return crypto.createHmac("sha256", key).update(payload).digest("hex");
1935
+ }
1936
+ function hashEquals(a, b) {
1937
+ const left = Buffer.from(a, "hex");
1938
+ const right = Buffer.from(b, "hex");
1939
+ if (left.length === 0 || left.length !== right.length) return false;
1940
+ return crypto.timingSafeEqual(left, right);
1941
+ }
1942
+ function toUnixSeconds(expiresAt) {
1943
+ return expiresAt instanceof Date ? Math.floor(expiresAt.getTime() / 1e3) : Math.floor(expiresAt);
1944
+ }
1945
+ function middlewareName(entry) {
1946
+ if (typeof entry === "string") return entry;
1947
+ if (typeof entry === "function") return entry.name;
1948
+ return entry.constructor.name;
1949
+ }
1950
+ function isControllerAction(handler) {
1951
+ return Array.isArray(handler) && handler.length === 2 && typeof handler[1] === "string";
1952
+ }
1953
+ function isInvokableTuple(handler) {
1954
+ return Array.isArray(handler) && handler.length === 1;
1955
+ }
1956
+ function toSerializableAction(handler) {
1957
+ if (isControllerAction(handler)) return handler;
1958
+ if (isInvokableTuple(handler)) return [handler[0], "__invoke"];
1959
+ if (typeof handler === "function" && isClass(handler)) return [handler, "__invoke"];
1960
+ return void 0;
1961
+ }
1962
+ function isClass(fn) {
1963
+ return Function.prototype.toString.call(fn).startsWith("class");
1964
+ }
1965
+ var WHERE_PATTERNS = {
1966
+ number: "[0-9]+",
1967
+ alpha: "[a-zA-Z]+",
1968
+ alphanumeric: "[a-zA-Z0-9]+",
1969
+ uuid: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
1970
+ ulid: "[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}"
1971
+ };
1972
+ function compileConstraint(pattern) {
1973
+ const source = typeof pattern === "string" ? pattern : pattern.source;
1974
+ return new RegExp(`^(?:${source})$`);
1975
+ }
1976
+ var Route = class {
1977
+ methods;
1978
+ path;
1979
+ handler;
1980
+ compiled;
1981
+ routeName;
1982
+ routeMiddleware;
1983
+ domainPattern;
1984
+ compiledDomain;
1985
+ /** Per-parameter constraints; a parameter only matches when its value satisfies the regex. */
1986
+ constraints = /* @__PURE__ */ new Map();
1987
+ constructor(methods, path3, handler, middleware = [], domain) {
1988
+ this.methods = methods;
1989
+ this.path = path3;
1990
+ this.handler = handler;
1991
+ this.compiled = compilePath(path3);
1992
+ this.routeMiddleware = [...middleware];
1993
+ if (domain !== void 0) this.setDomain(domain);
1994
+ }
1995
+ /** Name this route so it can be resolved by {@link Router.url}. The `->name()` equivalent. */
1996
+ name(name) {
1997
+ this.routeName = name;
1998
+ return this;
1999
+ }
2000
+ /** This route's name, or `undefined` if unnamed. */
2001
+ getName() {
2002
+ return this.routeName;
2003
+ }
2004
+ /**
2005
+ * Constrain this route to a host pattern (e.g. `{account}.myapp.com`). The `->domain()`
2006
+ * equivalent: the route only matches when the request host matches, and any `{param}` labels in
2007
+ * the domain are extracted into the route's parameters (ahead of path params). Chains like the
2008
+ * other builders.
2009
+ */
2010
+ domain(domain) {
2011
+ this.setDomain(domain);
2012
+ return this;
2013
+ }
2014
+ /** Compile and store the domain pattern; shared by the constructor and {@link Route.domain}. */
2015
+ setDomain(domain) {
2016
+ this.domainPattern = domain;
2017
+ this.compiledDomain = compileDomain(domain);
2018
+ }
2019
+ /** This route's domain pattern, or `undefined` when it matches any host. */
2020
+ getDomain() {
2021
+ return this.domainPattern;
2022
+ }
2023
+ /**
2024
+ * Match a request `host` against this route's domain. Returns the extracted domain params (an
2025
+ * empty object when the route has no domain — a domain-less route matches any host, mirroring
2026
+ * Laravel), or `undefined` when the route has a domain that the host does not satisfy (including
2027
+ * when the route requires a domain but no host was supplied).
2028
+ */
2029
+ matchDomain(host) {
2030
+ if (this.compiledDomain === void 0) return {};
2031
+ if (host === void 0) return void 0;
2032
+ const result = this.compiledDomain.regex.exec(host);
2033
+ if (!result) return void 0;
2034
+ const params = {};
2035
+ for (const [index, name] of this.compiledDomain.params.entries()) {
2036
+ const value = result[index + 1];
2037
+ if (value !== void 0) params[name] = decodeURIComponent(value);
2038
+ }
2039
+ return params;
2040
+ }
2041
+ where(paramOrPatterns, pattern) {
2042
+ if (typeof paramOrPatterns === "string") {
2043
+ if (pattern === void 0) {
2044
+ throw new Error(`Route.where('${paramOrPatterns}') requires a pattern.`);
2045
+ }
2046
+ this.constraints.set(paramOrPatterns, compileConstraint(pattern));
2047
+ return this;
2048
+ }
2049
+ for (const [param, value] of Object.entries(paramOrPatterns)) {
2050
+ this.constraints.set(param, compileConstraint(value));
2051
+ }
2052
+ return this;
2053
+ }
2054
+ /** Constrain `param` to digits only. The Laravel `->whereNumber()` equivalent. Chains. */
2055
+ whereNumber(param) {
2056
+ return this.where(param, WHERE_PATTERNS.number);
2057
+ }
2058
+ /** Constrain `param` to ASCII letters only. The Laravel `->whereAlpha()` equivalent. Chains. */
2059
+ whereAlpha(param) {
2060
+ return this.where(param, WHERE_PATTERNS.alpha);
2061
+ }
2062
+ /** Constrain `param` to letters and digits. The Laravel `->whereAlphaNumeric()` equivalent. Chains. */
2063
+ whereAlphaNumeric(param) {
2064
+ return this.where(param, WHERE_PATTERNS.alphanumeric);
2065
+ }
2066
+ /** Constrain `param` to a UUID shape. The Laravel `->whereUuid()` equivalent. Chains. */
2067
+ whereUuid(param) {
2068
+ return this.where(param, WHERE_PATTERNS.uuid);
2069
+ }
2070
+ /** Constrain `param` to a ULID shape. The Laravel `->whereUlid()` equivalent. Chains. */
2071
+ whereUlid(param) {
2072
+ return this.where(param, WHERE_PATTERNS.ulid);
2073
+ }
2074
+ /** Constrain `param` to one of `values` (matched literally). The `->whereIn()` equivalent. Chains. */
2075
+ whereIn(param, values) {
2076
+ const alternation = values.map((value) => escapeRegex(value)).join("|");
2077
+ return this.where(param, alternation.length > 0 ? alternation : "(?!)");
2078
+ }
2079
+ /**
2080
+ * Append middleware that wraps only this route. Accepts concrete entries (function/class) and
2081
+ * `string` names referencing a registered alias or middleware group (resolved at match time). The
2082
+ * `->middleware()` equivalent.
2083
+ */
2084
+ middleware(...entries) {
2085
+ this.routeMiddleware.push(...entries);
2086
+ return this;
2087
+ }
2088
+ /**
2089
+ * The middleware stack for this route (a copy), as registered — so `string` alias/group names are
2090
+ * returned verbatim. The {@link Router} resolves these to concrete entries via
2091
+ * {@link Router.resolveMiddleware} when dispatching a matched route.
2092
+ */
2093
+ getMiddleware() {
2094
+ return [...this.routeMiddleware];
2095
+ }
2096
+ /** The ordered names of this route's path parameters. */
2097
+ parameterNames() {
2098
+ return [...this.compiled.params];
2099
+ }
2100
+ /**
2101
+ * Extract route parameters if `path` matches this route's pattern, else `undefined`. Any
2102
+ * {@link Route.where} constraints are enforced here: a parameter value that fails its constraint
2103
+ * makes the whole route a non-match (so an absent optional parameter is never constrained).
2104
+ */
2105
+ match(path3) {
2106
+ const result = this.compiled.regex.exec(path3);
2107
+ if (!result) return void 0;
2108
+ const params = {};
2109
+ for (const [index, name] of this.compiled.params.entries()) {
2110
+ const value = result[index + 1];
2111
+ if (value !== void 0) {
2112
+ params[name] = value.includes("%") ? decodeURIComponent(value) : value;
2113
+ }
2114
+ }
2115
+ if (this.constraints.size > 0) {
2116
+ for (const [name, regex] of this.constraints) {
2117
+ const value = params[name];
2118
+ if (value !== void 0 && !regex.test(value)) return void 0;
2119
+ }
2120
+ }
2121
+ return params;
2122
+ }
2123
+ /** Whether this route serves `method` (HEAD falls through to GET). */
2124
+ handlesMethod(method) {
2125
+ const verb = method.toUpperCase();
2126
+ if (this.methods.includes(verb)) return true;
2127
+ return verb === "HEAD" && this.methods.includes("GET");
2128
+ }
2129
+ /** Build a concrete path from this route's pattern, substituting `params`. */
2130
+ url(params = {}) {
2131
+ const filled = this.path.replaceAll(/\{(\w+)\??\}/g, (_full, name) => {
2132
+ const value = params[name];
2133
+ if (value === void 0) {
2134
+ if (this.path.includes(`{${name}?}`)) return "";
2135
+ throw new Error(`Missing parameter [${name}] for route [${this.path}].`);
2136
+ }
2137
+ return encodeURIComponent(String(value));
2138
+ });
2139
+ return normalizePath(filled);
2140
+ }
2141
+ };
2142
+ var RESOURCE_SPECS = [
2143
+ { method: "index", verbs: ["GET"], suffix: void 0, member: false },
2144
+ { method: "create", verbs: ["GET"], suffix: "create", member: false },
2145
+ { method: "store", verbs: ["POST"], suffix: void 0, member: false },
2146
+ { method: "show", verbs: ["GET"], suffix: void 0, member: true },
2147
+ { method: "edit", verbs: ["GET"], suffix: "edit", member: true },
2148
+ { method: "update", verbs: ["PUT", "PATCH"], suffix: void 0, member: true },
2149
+ { method: "destroy", verbs: ["DELETE"], suffix: void 0, member: true }
2150
+ ];
2151
+ var API_EXCLUDED = ["create", "edit"];
2152
+ var ResourceRegistration = class {
2153
+ constructor(resourceName, controller, api, context, register, options = {}) {
2154
+ this.resourceName = resourceName;
2155
+ this.controller = controller;
2156
+ this.api = api;
2157
+ this.context = context;
2158
+ this.register = register;
2159
+ if (options.only !== void 0) this.onlyMethods = [...options.only];
2160
+ if (options.except !== void 0) this.exceptMethods = [...options.except];
2161
+ if (options.names !== void 0) Object.assign(this.nameOverrides, options.names);
2162
+ if (options.shallow === true) this.isShallow = true;
2163
+ if (typeof options.parameters === "string") this.parameterName = options.parameters;
2164
+ else if (options.parameters !== void 0) Object.assign(this.parameterMap, options.parameters);
2165
+ }
2166
+ resourceName;
2167
+ controller;
2168
+ api;
2169
+ context;
2170
+ register;
2171
+ onlyMethods;
2172
+ exceptMethods;
2173
+ nameOverrides = {};
2174
+ parameterName;
2175
+ parameterMap = {};
2176
+ isShallow = false;
2177
+ builtRoutes;
2178
+ /** Register only these resource methods. Chains. Re-resolving after the first build is a no-op. */
2179
+ only(methods) {
2180
+ this.onlyMethods = [...methods];
2181
+ return this;
2182
+ }
2183
+ /** Register every resource method except these. Chains. */
2184
+ except(methods) {
2185
+ this.exceptMethods = [...methods];
2186
+ return this;
2187
+ }
2188
+ /** Override generated route names per method (e.g. `{ show: 'users.profile' }`). Chains. */
2189
+ names(overrides) {
2190
+ Object.assign(this.nameOverrides, overrides);
2191
+ return this;
2192
+ }
2193
+ /** Override the URI parameter name (string) or per-resource-name map. Chains. */
2194
+ parameters(value) {
2195
+ if (typeof value === "string") this.parameterName = value;
2196
+ else Object.assign(this.parameterMap, value);
2197
+ return this;
2198
+ }
2199
+ /** Mark this resource's member routes as shallow (trailing-param-only URIs). Chains. */
2200
+ shallow(value) {
2201
+ this.isShallow = value ?? true;
2202
+ return this;
2203
+ }
2204
+ /** The methods this registration will produce, after applying `only`/`except` (and `api`). */
2205
+ selectedMethods() {
2206
+ let excluded = this.api ? [...API_EXCLUDED] : [];
2207
+ if (this.exceptMethods !== void 0) excluded = [...excluded, ...this.exceptMethods];
2208
+ return RESOURCE_SPECS.map((spec) => spec.method).filter((method) => {
2209
+ if (this.onlyMethods !== void 0 && !this.onlyMethods.includes(method)) return false;
2210
+ return !excluded.includes(method);
2211
+ });
2212
+ }
2213
+ /** The resolved URI parameter name for this resource (override → string map → singular of name). */
2214
+ resolvedParameter() {
2215
+ const mapped = this.parameterMap[this.resourceName];
2216
+ if (mapped !== void 0) return mapped;
2217
+ if (this.parameterName !== void 0) return this.parameterName;
2218
+ return support.Str.singular(this.resourceName);
2219
+ }
2220
+ /** Build (once) and register every selected route, returning them. Idempotent. */
2221
+ resolve() {
2222
+ if (this.builtRoutes !== void 0) return this.builtRoutes;
2223
+ const param = this.resolvedParameter();
2224
+ const selected = new Set(this.selectedMethods());
2225
+ const built = [];
2226
+ for (const spec of RESOURCE_SPECS) {
2227
+ if (!selected.has(spec.method)) continue;
2228
+ const route = this.buildRoute(spec, param);
2229
+ this.register(route);
2230
+ built.push(route);
2231
+ }
2232
+ this.builtRoutes = built;
2233
+ return built;
2234
+ }
2235
+ /**
2236
+ * Construct a single resource {@link Route} for `spec`, naming it `name.method` and applying the
2237
+ * captured group prefix/middleware/domain (so a resource declared inside a group is grouped).
2238
+ */
2239
+ buildRoute(spec, param) {
2240
+ const shallowMember = this.isShallow && spec.member;
2241
+ const base = shallowMember ? support.Str.singular(this.resourceName) : this.resourceName;
2242
+ const segments = [base];
2243
+ if (spec.member) segments.push(`{${param}}`);
2244
+ if (spec.suffix !== void 0) segments.push(spec.suffix);
2245
+ const fullPath = normalizePath(`${this.context.prefix}/${segments.join("/")}`);
2246
+ const route = new Route(
2247
+ [...spec.verbs],
2248
+ fullPath,
2249
+ [this.controller, spec.method],
2250
+ this.context.middleware,
2251
+ this.context.domain
2252
+ );
2253
+ if (Object.keys(this.context.where).length > 0) route.where(this.context.where);
2254
+ route.name(this.nameOverrides[spec.method] ?? `${this.resourceName}.${spec.method}`);
2255
+ return route;
2256
+ }
2257
+ };
2258
+ var SINGLETON_SPECS = [
2259
+ { method: "show", verbs: ["GET"], suffix: void 0, api: true },
2260
+ { method: "edit", verbs: ["GET"], suffix: "edit", api: false },
2261
+ { method: "update", verbs: ["PUT", "PATCH"], suffix: void 0, api: true }
2262
+ ];
2263
+ var SingletonRegistration = class {
2264
+ constructor(resourceName, controller, api, context, register) {
2265
+ this.resourceName = resourceName;
2266
+ this.controller = controller;
2267
+ this.api = api;
2268
+ this.context = context;
2269
+ this.register = register;
2270
+ }
2271
+ resourceName;
2272
+ controller;
2273
+ api;
2274
+ context;
2275
+ register;
2276
+ isDestroyable = false;
2277
+ builtRoutes;
2278
+ /** Also register `DELETE name` → `destroy`. The Laravel `->destroyable()` equivalent. Chains. */
2279
+ destroyable(value) {
2280
+ this.isDestroyable = value ?? true;
2281
+ return this;
2282
+ }
2283
+ /** Build (once) and register every selected route, returning them. Idempotent. */
2284
+ resolve() {
2285
+ if (this.builtRoutes !== void 0) return this.builtRoutes;
2286
+ const built = [];
2287
+ for (const spec of SINGLETON_SPECS) {
2288
+ if (this.api && !spec.api) continue;
2289
+ built.push(this.buildRoute(spec.method, spec.verbs, spec.suffix));
2290
+ }
2291
+ if (this.isDestroyable) built.push(this.buildRoute("destroy", ["DELETE"]));
2292
+ this.builtRoutes = built;
2293
+ return built;
2294
+ }
2295
+ /** Construct and register a single singleton {@link Route}, named `name.method`. */
2296
+ buildRoute(method, verbs, suffix) {
2297
+ const segments = suffix === void 0 ? this.resourceName : `${this.resourceName}/${suffix}`;
2298
+ const fullPath = normalizePath(`${this.context.prefix}/${segments}`);
2299
+ const route = new Route(
2300
+ [...verbs],
2301
+ fullPath,
2302
+ [this.controller, method],
2303
+ this.context.middleware,
2304
+ this.context.domain
2305
+ );
2306
+ if (Object.keys(this.context.where).length > 0) route.where(this.context.where);
2307
+ route.name(`${this.resourceName}.${method}`);
2308
+ this.register(route);
2309
+ return route;
2310
+ }
2311
+ };
2312
+ var Router = class _Router {
2313
+ routes = [];
2314
+ groupStack = [];
2315
+ fallbackHandler;
2316
+ bindings = /* @__PURE__ */ new Map();
2317
+ middlewareGroups = /* @__PURE__ */ new Map();
2318
+ middlewareAliases = /* @__PURE__ */ new Map();
2319
+ signingKey;
2320
+ pendingResources = [];
2321
+ viewRenderer;
2322
+ dispatchIndex;
2323
+ constructor(options = {}) {
2324
+ this.signingKey = options.key;
2325
+ this.viewRenderer = options.viewRenderer;
2326
+ }
2327
+ /** Register a `GET` route (also answers `HEAD`). */
2328
+ get(path3, handler) {
2329
+ return this.addRoute(["GET"], path3, handler);
2330
+ }
2331
+ /** Register a `POST` route. */
2332
+ post(path3, handler) {
2333
+ return this.addRoute(["POST"], path3, handler);
2334
+ }
2335
+ /** Register a `PUT` route. */
2336
+ put(path3, handler) {
2337
+ return this.addRoute(["PUT"], path3, handler);
2338
+ }
2339
+ /** Register a `PATCH` route. */
2340
+ patch(path3, handler) {
2341
+ return this.addRoute(["PATCH"], path3, handler);
2342
+ }
2343
+ /** Register a `DELETE` route. */
2344
+ delete(path3, handler) {
2345
+ return this.addRoute(["DELETE"], path3, handler);
2346
+ }
2347
+ /** Register an `OPTIONS` route. */
2348
+ options(path3, handler) {
2349
+ return this.addRoute(["OPTIONS"], path3, handler);
2350
+ }
2351
+ /** Register a route answering every standard verb. The `Route::any()` equivalent. */
2352
+ any(path3, handler) {
2353
+ return this.addRoute([...ALL_METHODS], path3, handler);
2354
+ }
2355
+ /** Register a route for an explicit set of verbs. The `Route::match()` equivalent. */
2356
+ on(methods, path3, handler) {
2357
+ return this.addRoute(methods, path3, handler);
2358
+ }
2359
+ // --- Convenience routes (the `Route::view` / `Route::redirect` family) -----
2360
+ /**
2361
+ * Install the renderer {@link Router.view} routes defer to — the seam an app (or a view package)
2362
+ * plugs its template engine into. The Laravel view-factory binding equivalent. Chains.
2363
+ */
2364
+ renderViewsUsing(renderer) {
2365
+ this.viewRenderer = renderer;
2366
+ return this;
2367
+ }
2368
+ /**
2369
+ * Register a `GET` route that renders `view` with `data` — the Laravel `Route::view()` equivalent.
2370
+ * `@plinthjs/http` ships no template engine, so rendering is deferred to the {@link ViewRenderer}
2371
+ * configured via {@link Router.renderViewsUsing} (or the `viewRenderer` construction option);
2372
+ * dispatching the route without one throws a clear error. The renderer's string becomes an HTML
2373
+ * {@link Response}.
2374
+ */
2375
+ view(uri, view, data = {}) {
2376
+ return this.get(uri, async (req) => {
2377
+ if (this.viewRenderer === void 0) {
2378
+ throw new Error(
2379
+ `No view renderer is configured to render [${view}]. Install one with renderViewsUsing() or the { viewRenderer } Router option.`
2380
+ );
2381
+ }
2382
+ return Response.html(await this.viewRenderer(view, data, req));
2383
+ });
2384
+ }
2385
+ /**
2386
+ * Register a route answering every verb with a redirect to `destination` (default `302`). The
2387
+ * Laravel `Route::redirect()` equivalent.
2388
+ */
2389
+ redirect(uri, destination, status = 302) {
2390
+ return this.any(uri, () => Response.redirect(destination, status));
2391
+ }
2392
+ /** Register a `301` redirect route. The Laravel `Route::permanentRedirect()` equivalent. */
2393
+ permanentRedirect(uri, destination) {
2394
+ return this.redirect(uri, destination, 301);
2395
+ }
2396
+ // --- Resource routes (the `Route::resource` family) -----------------------
2397
+ /**
2398
+ * Register the seven canonical RESTful routes for `controller` under `name`, mapping each verb+URI
2399
+ * to a controller method — the Laravel `Route::resource()` equivalent:
2400
+ *
2401
+ * - `GET name` → `index` (`name.index`)
2402
+ * - `GET name/create` → `create` (`name.create`)
2403
+ * - `POST name` → `store` (`name.store`)
2404
+ * - `GET name/{param}` → `show` (`name.show`)
2405
+ * - `GET name/{param}/edit` → `edit` (`name.edit`)
2406
+ * - `PUT|PATCH name/{param}` → `update` (`name.update`)
2407
+ * - `DELETE name/{param}` → `destroy` (`name.destroy`)
2408
+ *
2409
+ * `{param}` defaults to `Str.singular(name)` (override via `options.parameters` or `.parameters()`).
2410
+ * Returns a {@link ResourceRegistration} whose `.only()` / `.except()` / `.names()` /
2411
+ * `.parameters()` / `.shallow()` narrow or rename the set; the same controls are accepted via
2412
+ * `options`. Routes are **deferred**: they materialize (as normal, named, middleware-able,
2413
+ * cacheable {@link Route}s) the first time the router is matched/enumerated/url'd/cached, so
2414
+ * chaining after this call still takes effect. The enclosing {@link Router.group} context is
2415
+ * captured now and applied at build time.
2416
+ */
2417
+ resource(name, controller, options) {
2418
+ return this.registerResource(name, controller, false, options);
2419
+ }
2420
+ /**
2421
+ * Like {@link Router.resource} but for APIs: registers the same routes minus `create` and `edit`
2422
+ * (the HTML form-presenting endpoints). The Laravel `Route::apiResource()` equivalent.
2423
+ */
2424
+ apiResource(name, controller, options) {
2425
+ return this.registerResource(name, controller, true, options);
2426
+ }
2427
+ /** Shared builder for {@link Router.resource} / {@link Router.apiResource}. */
2428
+ registerResource(name, controller, api, options) {
2429
+ const registration = new ResourceRegistration(
2430
+ name,
2431
+ controller,
2432
+ api,
2433
+ this.currentResourceContext(),
2434
+ (route) => {
2435
+ this.registerRoute(route);
2436
+ },
2437
+ options ?? {}
2438
+ );
2439
+ this.pendingResources.push(registration);
2440
+ return registration;
2441
+ }
2442
+ /**
2443
+ * Register a singleton resource — routes for a resource with exactly one instance (a profile, a
2444
+ * settings page), mapping `GET name` → `show`, `GET name/edit` → `edit`, and `PUT|PATCH name` →
2445
+ * `update` (no `{param}` segment, no `index`/`create`/`store`). The Laravel `Route::singleton()`
2446
+ * equivalent. Chain {@link SingletonRegistration.destroyable} to add `DELETE name` → `destroy`.
2447
+ * Registration is deferred exactly like {@link Router.resource}.
2448
+ */
2449
+ singleton(name, controller) {
2450
+ return this.registerSingleton(name, controller, false);
2451
+ }
2452
+ /**
2453
+ * Like {@link Router.singleton} but for APIs: omits the HTML `edit` route, registering only
2454
+ * `show` and `update` (plus `destroy` after `.destroyable()`). The Laravel
2455
+ * `Route::apiSingleton()` equivalent.
2456
+ */
2457
+ apiSingleton(name, controller) {
2458
+ return this.registerSingleton(name, controller, true);
2459
+ }
2460
+ /** Shared builder for {@link Router.singleton} / {@link Router.apiSingleton}. */
2461
+ registerSingleton(name, controller, api) {
2462
+ const registration = new SingletonRegistration(
2463
+ name,
2464
+ controller,
2465
+ api,
2466
+ this.currentResourceContext(),
2467
+ (route) => {
2468
+ this.registerRoute(route);
2469
+ }
2470
+ );
2471
+ this.pendingResources.push(registration);
2472
+ return registration;
2473
+ }
2474
+ /** Snapshot the active group stack into a {@link ResourceContext} for deferred resource building. */
2475
+ currentResourceContext() {
2476
+ const prefix = this.groupStack.map((frame) => frame.prefix).join("");
2477
+ const middleware = this.groupStack.flatMap((frame) => [...frame.middleware]);
2478
+ let domain;
2479
+ for (const frame of this.groupStack) {
2480
+ if (frame.domain !== void 0) domain = frame.domain;
2481
+ }
2482
+ return { prefix, middleware, domain, where: this.currentGroupWhere() };
2483
+ }
2484
+ /** The merged group-level parameter constraints, innermost group winning on a key clash. */
2485
+ currentGroupWhere() {
2486
+ const merged = {};
2487
+ for (const frame of this.groupStack) Object.assign(merged, frame.where);
2488
+ return merged;
2489
+ }
2490
+ /**
2491
+ * Materialize any not-yet-built resource registrations into real routes. Idempotent and cheap
2492
+ * after the first call; invoked by {@link Router.match}, {@link Router.getRoutes},
2493
+ * {@link Router.url}, and {@link Router.toCache} so deferred resources are always resolved before
2494
+ * the routes are observed.
2495
+ */
2496
+ flushResources() {
2497
+ if (this.pendingResources.length === 0) return;
2498
+ const pending = this.pendingResources.splice(0);
2499
+ for (const registration of pending) registration.resolve();
2500
+ }
2501
+ /** Apply a shared prefix and/or middleware to every route registered inside `callback`. */
2502
+ group(options, callback) {
2503
+ const prefix = options.prefix === void 0 ? "" : normalizePath(options.prefix);
2504
+ const middleware = options.middleware === void 0 ? [] : Array.isArray(options.middleware) ? options.middleware : [options.middleware];
2505
+ this.groupStack.push({ prefix, middleware, domain: options.domain, where: options.where ?? {} });
2506
+ try {
2507
+ callback(this);
2508
+ } finally {
2509
+ this.groupStack.pop();
2510
+ }
2511
+ return this;
2512
+ }
2513
+ /** Register a fallback handler invoked when no route matches. The `Route::fallback()` equivalent. */
2514
+ fallback(handler) {
2515
+ this.fallbackHandler = handler;
2516
+ return this;
2517
+ }
2518
+ /** Register a route-model binding: a `{key}` param resolves through `resolver` (`Route::bind`). */
2519
+ bind(key, resolver) {
2520
+ this.bindings.set(key, resolver);
2521
+ return this;
2522
+ }
2523
+ /** The binding resolver registered for `key`, if any. */
2524
+ binding(key) {
2525
+ return this.bindings.get(key);
2526
+ }
2527
+ // --- Middleware groups + aliases (the `$middlewareGroups` / `$middlewareAliases` family) ------
2528
+ /**
2529
+ * Register a named middleware *group* — a list of references (concrete entries and/or other
2530
+ * alias/group names) that expand in place wherever the group name is used on a route or group. The
2531
+ * Laravel `Route::middlewareGroup('web', [...])` equivalent. Re-registering a name replaces it.
2532
+ * Names are resolved (recursively) at match time by {@link Router.resolveMiddleware}.
2533
+ */
2534
+ middlewareGroup(name, entries) {
2535
+ this.middlewareGroups.set(name, [...entries]);
2536
+ return this;
2537
+ }
2538
+ /**
2539
+ * Register a middleware *alias* — a short `string` name for a single concrete {@link MiddlewareEntry}.
2540
+ * The Laravel `$middlewareAliases` / `Route::aliasMiddleware('auth', Authenticate)` equivalent.
2541
+ * Re-registering a name replaces it.
2542
+ */
2543
+ aliasMiddleware(name, entry) {
2544
+ this.middlewareAliases.set(name, entry);
2545
+ return this;
2546
+ }
2547
+ /**
2548
+ * The references registered for a middleware group, or `undefined` when no group is registered
2549
+ * under `name`. Returns a copy; mutating it does not affect the registration.
2550
+ */
2551
+ getMiddlewareGroup(name) {
2552
+ const group = this.middlewareGroups.get(name);
2553
+ return group === void 0 ? void 0 : [...group];
2554
+ }
2555
+ /** The concrete entry registered for a middleware alias, or `undefined` when none is registered. */
2556
+ getMiddlewareAlias(name) {
2557
+ return this.middlewareAliases.get(name);
2558
+ }
2559
+ /**
2560
+ * Resolve a middleware reference list to concrete {@link MiddlewareEntry entries}, expanding
2561
+ * `string` names: a name resolves first as an **alias** (→ its single entry), else as a **group**
2562
+ * (→ its references, expanded recursively). An unknown name **throws** — mirroring Laravel, which
2563
+ * raises when a route references a middleware that is neither an alias nor a group. Cyclic group
2564
+ * references (a group that, directly or transitively, contains itself) also throw rather than
2565
+ * recursing without bound. Function/class entries pass through unchanged and in order.
2566
+ *
2567
+ * The {@link HttpKernel} calls this on a matched route's {@link Route.getMiddleware} stack before
2568
+ * running it.
2569
+ */
2570
+ resolveMiddleware(references) {
2571
+ return this.expandMiddleware(references, []);
2572
+ }
2573
+ /**
2574
+ * Recursive worker for {@link Router.resolveMiddleware}. `groupPath` is the stack of group names
2575
+ * currently being expanded; revisiting a name already on the path is a cycle (a group that
2576
+ * directly or transitively contains itself) and throws. The same group may still appear in
2577
+ * sibling branches — only re-entrancy along a single path is rejected.
2578
+ */
2579
+ expandMiddleware(references, groupPath) {
2580
+ const resolved = [];
2581
+ for (const reference of references) {
2582
+ if (typeof reference !== "string") {
2583
+ resolved.push(reference);
2584
+ continue;
2585
+ }
2586
+ const alias = this.middlewareAliases.get(reference);
2587
+ if (alias !== void 0) {
2588
+ resolved.push(alias);
2589
+ continue;
2590
+ }
2591
+ const group = this.middlewareGroups.get(reference);
2592
+ if (group !== void 0) {
2593
+ if (groupPath.includes(reference)) {
2594
+ throw new Error(
2595
+ `Middleware group [${reference}] references itself (via ${[...groupPath, reference].join(" -> ")}); resolve the cycle.`
2596
+ );
2597
+ }
2598
+ resolved.push(...this.expandMiddleware(group, [...groupPath, reference]));
2599
+ continue;
2600
+ }
2601
+ throw new Error(
2602
+ `Middleware [${reference}] is not a registered alias or group. Register it with aliasMiddleware()/middlewareGroup(), or pass a concrete middleware entry.`
2603
+ );
2604
+ }
2605
+ return resolved;
2606
+ }
2607
+ /** Every registered route (a copy). Pending resource registrations are materialized first. */
2608
+ getRoutes() {
2609
+ this.flushResources();
2610
+ return [...this.routes];
2611
+ }
2612
+ // --- Route caching (the `route:cache` family) -----------------------------
2613
+ /**
2614
+ * Serialize the registered routes to a plain, JSON-serializable {@link RouteCache} snapshot
2615
+ * (methods, path, name, domain, middleware names, and the `[controller, method]` action).
2616
+ *
2617
+ * Closures cannot be serialized. Mirroring Laravel's `route:cache` — which aborts with
2618
+ * "Unable to prepare route … for serialization. Uses Closure." — this **throws** when any route
2619
+ * uses a closure handler, rather than silently dropping it, so a cache is always complete or
2620
+ * absent. Rehydrate with {@link Router.loadCache} or {@link Router.fromCache}.
2621
+ */
2622
+ toCache() {
2623
+ this.flushResources();
2624
+ const routes = [];
2625
+ for (const route of this.routes) {
2626
+ const { handler } = route;
2627
+ const serializable = toSerializableAction(handler);
2628
+ if (serializable === void 0) {
2629
+ const named = route.getName();
2630
+ const label = named === void 0 ? route.path : `${route.path} (${named})`;
2631
+ throw new Error(
2632
+ `Unable to prepare route [${label}] for caching: it uses a Closure handler. Convert it to a [Controller, method] action before caching routes.`
2633
+ );
2634
+ }
2635
+ const [controller, method] = serializable;
2636
+ routes.push({
2637
+ methods: [...route.methods],
2638
+ path: route.path,
2639
+ name: route.getName(),
2640
+ domain: route.getDomain(),
2641
+ middleware: route.getMiddleware().map((entry) => middlewareName(entry)),
2642
+ action: [controller.name, method]
2643
+ });
2644
+ }
2645
+ return { routes };
2646
+ }
2647
+ /**
2648
+ * Rehydrate a {@link RouteCache} onto this Router, appending the cached routes. `options.controller`
2649
+ * maps each cached controller name back to its constructor; an optional `options.middleware`
2650
+ * resolver reattaches middleware by name (omitted middleware are skipped). Returns `this`.
2651
+ */
2652
+ loadCache(snapshot, options) {
2653
+ for (const cached of snapshot.routes) {
2654
+ const [controllerName, method] = cached.action;
2655
+ const controller = options.controller(controllerName);
2656
+ const middleware = options.middleware === void 0 ? [] : cached.middleware.map((name) => options.middleware(name));
2657
+ const route = new Route(
2658
+ [...cached.methods],
2659
+ cached.path,
2660
+ [controller, method],
2661
+ middleware,
2662
+ cached.domain
2663
+ );
2664
+ if (cached.name !== void 0) route.name(cached.name);
2665
+ this.registerRoute(route);
2666
+ }
2667
+ return this;
2668
+ }
2669
+ /**
2670
+ * Build a fresh {@link Router} from a {@link RouteCache} snapshot, resolving cached controller
2671
+ * names through `resolver`. The static `route:cache` rehydration entry point; pass
2672
+ * {@link LoadCacheOptions} (or a bare {@link ControllerResolver}) plus optional {@link RouterOptions}.
2673
+ */
2674
+ static fromCache(snapshot, resolver, options = {}) {
2675
+ const router = new _Router(options);
2676
+ const load = typeof resolver === "function" ? { controller: resolver } : resolver;
2677
+ return router.loadCache(snapshot, load);
2678
+ }
2679
+ /**
2680
+ * Resolve an inbound `method`+`path` to a route, a 405, or a 404. When `host` is supplied, routes
2681
+ * carrying a {@link Route.domain domain} only match a host that satisfies the pattern, and the
2682
+ * domain's `{param}` labels are merged into the result ahead of the path params; routes without a
2683
+ * domain match regardless of host. When `host` is omitted, domain-carrying routes are skipped
2684
+ * (host-agnostic call sites keep their prior behavior for domain-less routes).
2685
+ */
2686
+ match(method, path3, host) {
2687
+ this.flushResources();
2688
+ const index = this.dispatchIndex ?? this.buildDispatchIndex();
2689
+ const normalized = normalizePath(path3);
2690
+ const verb = method.toUpperCase();
2691
+ const staticEntries = index.staticPaths.get(normalized);
2692
+ const bucket = index.dynamicByLength.get(countSegments(normalized));
2693
+ let firstEntries;
2694
+ let wildcardEntries;
2695
+ if (bucket !== void 0) {
2696
+ firstEntries = bucket.byFirst.get(firstSegment(normalized));
2697
+ if (bucket.wildcard.length > 0) wildcardEntries = bucket.wildcard;
2698
+ }
2699
+ let allowed;
2700
+ let staticAt = 0;
2701
+ let firstAt = 0;
2702
+ let wildcardAt = 0;
2703
+ for (; ; ) {
2704
+ const nextStatic = staticEntries === void 0 ? void 0 : staticEntries[staticAt];
2705
+ const nextFirst = firstEntries === void 0 ? void 0 : firstEntries[firstAt];
2706
+ const nextWildcard = wildcardEntries === void 0 ? void 0 : wildcardEntries[wildcardAt];
2707
+ let entry = nextStatic;
2708
+ let source = 0;
2709
+ if (nextFirst !== void 0 && (entry === void 0 || nextFirst.order < entry.order)) {
2710
+ entry = nextFirst;
2711
+ source = 1;
2712
+ }
2713
+ if (nextWildcard !== void 0 && (entry === void 0 || nextWildcard.order < entry.order)) {
2714
+ entry = nextWildcard;
2715
+ source = 2;
2716
+ }
2717
+ if (entry === void 0) break;
2718
+ const fromStatic = source === 0;
2719
+ if (fromStatic) staticAt += 1;
2720
+ else if (source === 1) firstAt += 1;
2721
+ else wildcardAt += 1;
2722
+ const { route } = entry;
2723
+ let domainParams;
2724
+ if (route.getDomain() !== void 0) {
2725
+ domainParams = route.matchDomain(host);
2726
+ if (domainParams === void 0) continue;
2727
+ }
2728
+ const params = fromStatic ? {} : route.match(normalized);
2729
+ if (params === void 0) continue;
2730
+ if (route.methods.includes(verb) || verb === "HEAD" && route.methods.includes("GET")) {
2731
+ const merged = domainParams === void 0 ? params : { ...domainParams, ...params };
2732
+ return { type: "matched", route, params: merged };
2733
+ }
2734
+ allowed ??= /* @__PURE__ */ new Set();
2735
+ for (const routeVerb of route.methods) allowed.add(routeVerb);
2736
+ }
2737
+ if (allowed !== void 0 && allowed.size > 0) {
2738
+ return { type: "method-not-allowed", allowed: [...allowed] };
2739
+ }
2740
+ if (this.fallbackHandler !== void 0) {
2741
+ const route = new Route([verb], normalized, this.fallbackHandler);
2742
+ return { type: "matched", route, params: {} };
2743
+ }
2744
+ return { type: "not-found" };
2745
+ }
2746
+ /** Build (and memoize) the {@link DispatchIndex} over the current route list. */
2747
+ buildDispatchIndex() {
2748
+ const staticPaths = /* @__PURE__ */ new Map();
2749
+ const dynamicByLength = /* @__PURE__ */ new Map();
2750
+ for (const [order, route] of this.routes.entries()) {
2751
+ const segments = parseSegments(route.path);
2752
+ let optionalCount = 0;
2753
+ let staticPath = "";
2754
+ let isStatic = true;
2755
+ for (const segment of segments) {
2756
+ if (segment.kind === "literal") {
2757
+ staticPath += `/${segment.value}`;
2758
+ } else {
2759
+ isStatic = false;
2760
+ if (segment.kind === "optional") optionalCount += 1;
2761
+ }
2762
+ }
2763
+ const entry = { route, order };
2764
+ if (isStatic) {
2765
+ const key = staticPath === "" ? "/" : staticPath;
2766
+ const list = staticPaths.get(key);
2767
+ if (list === void 0) staticPaths.set(key, [entry]);
2768
+ else list.push(entry);
2769
+ continue;
2770
+ }
2771
+ const head = segments[0];
2772
+ const firstLiteral = head?.kind === "literal" ? head.value : void 0;
2773
+ for (let count = segments.length - optionalCount; count <= segments.length; count += 1) {
2774
+ let bucket = dynamicByLength.get(count);
2775
+ if (bucket === void 0) {
2776
+ bucket = { byFirst: /* @__PURE__ */ new Map(), wildcard: [] };
2777
+ dynamicByLength.set(count, bucket);
2778
+ }
2779
+ if (firstLiteral === void 0) {
2780
+ bucket.wildcard.push(entry);
2781
+ } else {
2782
+ const list = bucket.byFirst.get(firstLiteral);
2783
+ if (list === void 0) bucket.byFirst.set(firstLiteral, [entry]);
2784
+ else list.push(entry);
2785
+ }
2786
+ }
2787
+ }
2788
+ const index = { staticPaths, dynamicByLength };
2789
+ this.dispatchIndex = index;
2790
+ return index;
2791
+ }
2792
+ /** Append a registered route and drop the dispatch index so the next match rebuilds it. */
2793
+ registerRoute(route) {
2794
+ this.routes.push(route);
2795
+ this.dispatchIndex = void 0;
2796
+ }
2797
+ /** Build a URL for a named route, optionally appending a query string. The `route()` helper. */
2798
+ url(name, params = {}, query) {
2799
+ this.flushResources();
2800
+ const route = this.routes.find((candidate) => candidate.getName() === name);
2801
+ if (route === void 0) throw new Error(`Route [${name}] is not defined.`);
2802
+ let url = route.url(params);
2803
+ if (query !== void 0) {
2804
+ const search = new URLSearchParams();
2805
+ for (const [key, value] of Object.entries(query)) search.set(key, String(value));
2806
+ const rendered = search.toString();
2807
+ if (rendered.length > 0) url += `?${rendered}`;
2808
+ }
2809
+ return url;
2810
+ }
2811
+ // --- Signed URLs (the `URL::signedRoute` family) --------------------------
2812
+ /** Set (or replace) the secret used to sign and verify URLs. The app-key configuration step. */
2813
+ setSigningKey(key) {
2814
+ this.signingKey = key;
2815
+ return this;
2816
+ }
2817
+ /** The configured signing key, asserting one is set (signing without a key is a programmer error). */
2818
+ requireKey() {
2819
+ if (this.signingKey === void 0 || this.signingKey.length === 0) {
2820
+ throw new Error(
2821
+ "A signing key is required; construct the Router with { key } or setSigningKey()."
2822
+ );
2823
+ }
2824
+ return this.signingKey;
2825
+ }
2826
+ /**
2827
+ * Build a signed URL for the named route. The Laravel `URL::signedRoute()` equivalent: the route
2828
+ * URL is generated as usual, an optional `expires` (a {@link Date} or unix-seconds number) is
2829
+ * appended, and an HMAC `signature` over the canonical URL is added last. Verify it later with
2830
+ * {@link Router.hasValidSignature}.
2831
+ */
2832
+ signedUrl(name, params = {}, expiresAt, query = {}) {
2833
+ const key = this.requireKey();
2834
+ const search = new URLSearchParams();
2835
+ for (const [param, value] of Object.entries(query)) search.set(param, String(value));
2836
+ if (expiresAt !== void 0) search.set(EXPIRES_PARAM, String(toUnixSeconds(expiresAt)));
2837
+ const pathname = this.url(name, params);
2838
+ const signature = sign(key, canonicalize(pathname, search));
2839
+ search.set(SIGNATURE_PARAM, signature);
2840
+ return `${pathname}?${search.toString()}`;
2841
+ }
2842
+ /**
2843
+ * Build a signed URL that expires after `expiresIn` seconds from now. The Laravel
2844
+ * `URL::temporarySignedRoute()` equivalent (with the expiry expressed in seconds rather than a
2845
+ * `DateTime`/minutes).
2846
+ */
2847
+ temporarySignedUrl(name, expiresIn, params = {}, query = {}) {
2848
+ const expiresAt = Math.floor(Date.now() / 1e3) + Math.floor(expiresIn);
2849
+ return this.signedUrl(name, params, expiresAt, query);
2850
+ }
2851
+ /**
2852
+ * Validate the signature on a `path?query` string, returning a {@link SignatureResult} describing
2853
+ * the outcome (`valid`, `missing`, `invalid`, or `expired`). The low-level check behind
2854
+ * {@link Router.hasValidSignature}; a `false`-returning caller can use this to distinguish *why*.
2855
+ */
2856
+ validateSignature(url) {
2857
+ const key = this.requireKey();
2858
+ const parsed = new URL(url, "http://localhost");
2859
+ const provided = parsed.searchParams.get(SIGNATURE_PARAM);
2860
+ if (provided === null) return "missing";
2861
+ const expected = sign(key, canonicalize(parsed.pathname, parsed.searchParams));
2862
+ if (!hashEquals(provided, expected)) return "invalid";
2863
+ const expires = parsed.searchParams.get(EXPIRES_PARAM);
2864
+ if (expires !== null && Number(expires) < Math.floor(Date.now() / 1e3)) return "expired";
2865
+ return "valid";
2866
+ }
2867
+ /**
2868
+ * Whether `req` carries a valid (and unexpired) signature. The `$request->hasValidSignature()`
2869
+ * equivalent: recomputes the HMAC over the request's path+query (minus `signature`) and compares
2870
+ * in constant time.
2871
+ */
2872
+ hasValidSignature(req) {
2873
+ return this.validateSignature(req.url()) === "valid";
2874
+ }
2875
+ /**
2876
+ * A middleware that aborts unsigned/invalid/expired requests with a `403` (the Laravel
2877
+ * `signed` / `ValidateSignature` middleware). On a valid signature it passes control inward.
2878
+ */
2879
+ signedMiddleware() {
2880
+ return (req, next) => {
2881
+ if (this.validateSignature(req.url()) !== "valid") {
2882
+ throw new HttpException(403, "Invalid signature.");
2883
+ }
2884
+ return next(req);
2885
+ };
2886
+ }
2887
+ addRoute(methods, path3, handler) {
2888
+ const prefix = this.groupStack.map((frame) => frame.prefix).join("");
2889
+ const groupMiddleware = this.groupStack.flatMap((frame) => [...frame.middleware]);
2890
+ const fullPath = normalizePath(`${prefix}${normalizePath(path3)}`);
2891
+ let domain;
2892
+ for (const frame of this.groupStack) {
2893
+ if (frame.domain !== void 0) domain = frame.domain;
2894
+ }
2895
+ const route = new Route(methods, fullPath, handler, groupMiddleware, domain);
2896
+ const groupWhere = this.currentGroupWhere();
2897
+ if (Object.keys(groupWhere).length > 0) route.where(groupWhere);
2898
+ this.registerRoute(route);
2899
+ return route;
2900
+ }
2901
+ };
2902
+ async function dispatch(kernel, nodeReq, nodeRes, options) {
2903
+ let request;
2904
+ try {
2905
+ request = await Request.fromNode(nodeReq, options);
2906
+ } catch (error) {
2907
+ if (error instanceof PayloadTooLargeHttpException) {
2908
+ nodeRes.writeHead(413, {
2909
+ "Content-Type": "text/plain; charset=utf-8",
2910
+ Connection: "close"
2911
+ });
2912
+ nodeRes.end("Payload Too Large");
2913
+ return;
2914
+ }
2915
+ throw error;
2916
+ }
2917
+ const response = await kernel.handle(request);
2918
+ if (response.isStream()) {
2919
+ await response.writeStreamTo(nodeRes);
2920
+ } else {
2921
+ response.writeTo(nodeRes);
2922
+ }
2923
+ }
2924
+ function createServer(kernel, options = {}) {
2925
+ return http.createServer((nodeReq, nodeRes) => {
2926
+ void dispatch(kernel, nodeReq, nodeRes, options).catch(() => {
2927
+ if (nodeRes.headersSent) {
2928
+ nodeRes.destroy();
2929
+ } else {
2930
+ nodeRes.statusCode = 500;
2931
+ nodeRes.end("Internal Server Error");
2932
+ }
2933
+ });
2934
+ });
2935
+ }
2936
+ function serve(kernel, port, host, options) {
2937
+ const server = createServer(kernel, options);
2938
+ return new Promise((resolve, reject) => {
2939
+ const onError = (error) => {
2940
+ server.off("listening", onListening);
2941
+ reject(error);
2942
+ };
2943
+ const onListening = () => {
2944
+ server.off("error", onError);
2945
+ resolve(server);
2946
+ };
2947
+ server.once("error", onError);
2948
+ if (host === void 0) server.listen(port, onListening);
2949
+ else server.listen(port, host, onListening);
2950
+ });
2951
+ }
2952
+ function gracefulShutdown(server, options = {}) {
2953
+ const signals = options.signals ?? ["SIGTERM", "SIGINT"];
2954
+ const timeout = options.timeout ?? 1e4;
2955
+ const exit = options.exit ?? ((code) => {
2956
+ process.exit(code);
2957
+ });
2958
+ let shuttingDown = false;
2959
+ const handler = () => {
2960
+ if (shuttingDown) return;
2961
+ shuttingDown = true;
2962
+ let timedOut = false;
2963
+ const timer = setTimeout(() => {
2964
+ timedOut = true;
2965
+ void Promise.resolve(options.onShutdown?.()).finally(() => {
2966
+ exit(1);
2967
+ });
2968
+ }, timeout);
2969
+ timer.unref();
2970
+ server.close(() => {
2971
+ if (timedOut) return;
2972
+ clearTimeout(timer);
2973
+ void Promise.resolve(options.onShutdown?.()).then(
2974
+ () => {
2975
+ exit(0);
2976
+ },
2977
+ () => {
2978
+ exit(1);
2979
+ }
2980
+ );
2981
+ });
2982
+ };
2983
+ for (const signal of signals) process.on(signal, handler);
2984
+ return () => {
2985
+ for (const signal of signals) process.off(signal, handler);
2986
+ };
2987
+ }
2988
+
2989
+ // src/presets.ts
2990
+ function securityHeaders(options = {}) {
2991
+ const frameOptions = options.frameOptions ?? "SAMEORIGIN";
2992
+ const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
2993
+ const noSniff = options.noSniff ?? true;
2994
+ const hstsValue = options.hsts === void 0 || options.hsts === false ? void 0 : `max-age=${String((options.hsts === true ? void 0 : options.hsts.maxAge) ?? 31536e3)}; includeSubDomains`;
2995
+ return async (req, next) => {
2996
+ const res = await next(req);
2997
+ const set = (name, value) => {
2998
+ res.headers[name] ??= value;
2999
+ };
3000
+ if (noSniff) set("X-Content-Type-Options", "nosniff");
3001
+ if (frameOptions !== false) set("X-Frame-Options", frameOptions);
3002
+ if (referrerPolicy !== false) set("Referrer-Policy", referrerPolicy);
3003
+ if (hstsValue !== void 0 && req.isSecure()) set("Strict-Transport-Security", hstsValue);
3004
+ return res;
3005
+ };
3006
+ }
3007
+ function resolveOrigin(option, origin) {
3008
+ const setting = option ?? "*";
3009
+ if (setting === "*") return "*";
3010
+ if (origin === void 0) return void 0;
3011
+ if (typeof setting === "function") return setting(origin) ? origin : void 0;
3012
+ if (typeof setting === "string") return setting === origin ? origin : void 0;
3013
+ return setting.includes(origin) ? origin : void 0;
3014
+ }
3015
+ function cors(options = {}) {
3016
+ const methods = (options.methods ?? ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"]).join(", ");
3017
+ const maxAge = String(options.maxAge ?? 86400);
3018
+ return async (req, next) => {
3019
+ const origin = req.header("origin");
3020
+ const allowOrigin = resolveOrigin(options.origin, origin);
3021
+ const headers = {};
3022
+ if (allowOrigin !== void 0) {
3023
+ headers["Access-Control-Allow-Origin"] = allowOrigin;
3024
+ if (allowOrigin !== "*") headers["Vary"] = "Origin";
3025
+ if (options.credentials === true) headers["Access-Control-Allow-Credentials"] = "true";
3026
+ if (options.exposedHeaders !== void 0 && options.exposedHeaders.length > 0) {
3027
+ headers["Access-Control-Expose-Headers"] = options.exposedHeaders.join(", ");
3028
+ }
3029
+ }
3030
+ if (req.method() === "OPTIONS") {
3031
+ const allowHeaders = options.allowedHeaders === void 0 ? req.header("access-control-request-headers") : options.allowedHeaders.join(", ");
3032
+ return Response.make("", 204).withHeaders({
3033
+ ...headers,
3034
+ "Access-Control-Allow-Methods": methods,
3035
+ "Access-Control-Max-Age": maxAge,
3036
+ ...allowHeaders === void 0 ? {} : { "Access-Control-Allow-Headers": allowHeaders }
3037
+ });
3038
+ }
3039
+ const res = await next(req);
3040
+ return res.withHeaders(headers);
3041
+ };
3042
+ }
3043
+ function throttle(options) {
3044
+ const max = options.max ?? 60;
3045
+ const decaySeconds = options.decaySeconds ?? 60;
3046
+ const keyFor = options.key ?? ((req) => `${req.ip() ?? "unknown"}|${req.method()}|${req.path()}`);
3047
+ return async (req, next) => {
3048
+ const key = `mason-throttle:${keyFor(req)}`;
3049
+ if (options.limiter.tooManyAttempts(key, max)) {
3050
+ const retryAfter = options.limiter.availableIn(key);
3051
+ return Response.json({ message: "Too Many Attempts." }, 429).withHeaders({
3052
+ "Retry-After": String(retryAfter),
3053
+ "X-RateLimit-Limit": String(max),
3054
+ "X-RateLimit-Remaining": "0"
3055
+ });
3056
+ }
3057
+ options.limiter.hit(key, decaySeconds);
3058
+ return next(req);
3059
+ };
3060
+ }
3061
+
3062
+ // src/index.ts
3063
+ var VERSION = "0.1.0";
3064
+
3065
+ exports.Controller = Controller;
3066
+ exports.EXCEPTION_HANDLER = EXCEPTION_HANDLER;
3067
+ exports.ExceptionHandler = ExceptionHandler;
3068
+ exports.HttpException = HttpException;
3069
+ exports.HttpKernel = HttpKernel;
3070
+ exports.MethodNotAllowedHttpException = MethodNotAllowedHttpException;
3071
+ exports.NotFoundHttpException = NotFoundHttpException;
3072
+ exports.PayloadTooLargeHttpException = PayloadTooLargeHttpException;
3073
+ exports.Request = Request;
3074
+ exports.ResourceRegistration = ResourceRegistration;
3075
+ exports.Response = Response;
3076
+ exports.Route = Route;
3077
+ exports.Router = Router;
3078
+ exports.SingletonRegistration = SingletonRegistration;
3079
+ exports.UploadedFile = UploadedFile;
3080
+ exports.VERSION = VERSION;
3081
+ exports.cors = cors;
3082
+ exports.createServer = createServer;
3083
+ exports.gracefulShutdown = gracefulShutdown;
3084
+ exports.isTerminable = isTerminable;
3085
+ exports.runMiddleware = runMiddleware;
3086
+ exports.securityHeaders = securityHeaders;
3087
+ exports.serve = serve;
3088
+ exports.terminateMiddleware = terminateMiddleware;
3089
+ exports.throttle = throttle;
3090
+ //# sourceMappingURL=index.cjs.map
3091
+ //# sourceMappingURL=index.cjs.map