@dhaneshpurohit/mockstar 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +43 -4
  3. package/dist/cli.js +1214 -875
  4. package/dist/core/config/schema.d.ts +197 -165
  5. package/dist/core/config/schema.d.ts.map +1 -1
  6. package/dist/core/http/body-cap.d.ts +37 -0
  7. package/dist/core/http/body-cap.d.ts.map +1 -0
  8. package/dist/core/http/rate-limit.d.ts +55 -0
  9. package/dist/core/http/rate-limit.d.ts.map +1 -0
  10. package/dist/core/matching/discriminators.d.ts +25 -0
  11. package/dist/core/matching/discriminators.d.ts.map +1 -1
  12. package/dist/core/matching/index.d.ts +3 -1
  13. package/dist/core/matching/index.d.ts.map +1 -1
  14. package/dist/features/openapi/converter.d.ts.map +1 -1
  15. package/dist/features/pass-through.d.ts +7 -0
  16. package/dist/features/pass-through.d.ts.map +1 -1
  17. package/dist/features/proxy/cli.d.ts +11 -0
  18. package/dist/features/proxy/cli.d.ts.map +1 -1
  19. package/dist/features/proxy/dns.d.ts +21 -3
  20. package/dist/features/proxy/dns.d.ts.map +1 -1
  21. package/dist/features/proxy/index.d.ts +1 -1
  22. package/dist/features/proxy/index.d.ts.map +1 -1
  23. package/dist/features/proxy/port-bind.d.ts +18 -1
  24. package/dist/features/proxy/port-bind.d.ts.map +1 -1
  25. package/dist/features/proxy/sni-gate.d.ts +4 -3
  26. package/dist/features/proxy/sni-gate.d.ts.map +1 -1
  27. package/dist/features/url-validator.d.ts +48 -0
  28. package/dist/features/url-validator.d.ts.map +1 -1
  29. package/dist/features/webhooks/event-registry.d.ts +7 -0
  30. package/dist/features/webhooks/event-registry.d.ts.map +1 -1
  31. package/dist/features/webhooks/journal.d.ts +23 -0
  32. package/dist/features/webhooks/journal.d.ts.map +1 -1
  33. package/dist/features/webhooks/queue.d.ts +18 -0
  34. package/dist/features/webhooks/queue.d.ts.map +1 -1
  35. package/dist/features/webhooks/types.d.ts +15 -2
  36. package/dist/features/webhooks/types.d.ts.map +1 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +1048 -826
  39. package/dist/server.d.ts +17 -0
  40. package/dist/server.d.ts.map +1 -1
  41. package/dist/version.d.ts +1 -1
  42. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -375,35 +375,57 @@ var exports_port_bind = {};
375
375
  __export(exports_port_bind, {
376
376
  runPrivileged: () => runPrivileged,
377
377
  portBindMutation: () => portBindMutation,
378
- isPlatformSupported: () => isPlatformSupported
378
+ isPlatformSupported: () => isPlatformSupported,
379
+ ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG: () => ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG,
380
+ ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV: () => ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV
379
381
  });
380
382
  import { spawn as spawn3 } from "child_process";
381
383
  import { writeFile as writeFile5 } from "fs/promises";
382
384
  import { platform as platform2 } from "os";
385
+ import { basename as basename3 } from "path";
386
+ function isInterpreterBinary(binaryPath) {
387
+ return INTERPRETER_BASENAMES.has(basename3(binaryPath).toLowerCase());
388
+ }
389
+ function assertPackagedBinary(binaryPath, allowInterpreter) {
390
+ if (!isInterpreterBinary(binaryPath))
391
+ return;
392
+ const base = basename3(binaryPath).toLowerCase();
393
+ if (!allowInterpreter) {
394
+ throw new ProxyError(`Refusing to grant the network-bind capability to '${binaryPath}': it resolves to the ` + `${base} interpreter, not a packaged mockstar binary.`, "binary_path_is_interpreter", `Build and use a packaged binary instead of running from source: \`bun run build && bun run build:binary\`, then run \`./dist/mockstar-<platform>-<arch> proxy install\` (or use a downloaded release binary / the Docker image). Granting this capability to the interpreter itself would let every program it runs bind privileged ports. If this is a single-purpose, ephemeral host (CI runner, throwaway VM/container) where that risk doesn't apply, opt in explicitly with ${ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG} or ${ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV}=1 \u2014 do not use either on a developer's own machine.`);
395
+ }
396
+ process.stderr.write(`
397
+ WARNING: granting cap_net_bind_service to '${binaryPath}' \u2014 the ${base} interpreter, not a packaged mockstar binary (${ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG} / ${ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV}=1 was set). This grants EVERY program run by this interpreter on this host the ability to bind privileged ports, until 'mockstar proxy uninstall' or 'sudo setcap -r ${binaryPath}' reverses it. Only acceptable on a single-purpose, ephemeral host (CI runner, throwaway VM/container).
398
+
399
+ `);
400
+ }
383
401
  function portBindMutation(params) {
402
+ const allowInterpreter = params.allowInterpreter ?? false;
403
+ assertPackagedBinary(params.binaryPath, allowInterpreter);
404
+ const interpreterGrant = allowInterpreter && isInterpreterBinary(params.binaryPath);
384
405
  const os = platform2();
385
406
  if (os === "linux") {
386
- return linuxSetcapMutation(params.binaryPath);
407
+ return linuxSetcapMutation(params.binaryPath, interpreterGrant);
387
408
  }
388
409
  if (os === "darwin") {
389
410
  return macosLaunchdMutation({
390
411
  plistPath: params.plistPath ?? `${process.env.HOME}/Library/LaunchAgents/com.mockstar.proxy.plist`,
391
412
  label: params.launchdLabel ?? "com.mockstar.proxy",
392
- binaryPath: params.binaryPath
413
+ binaryPath: params.binaryPath,
414
+ interpreterGrant
393
415
  });
394
416
  }
395
417
  throw new ProxyError(`Unsupported platform for port 443 bind: ${os}. macOS and Linux only in v1 (B2).`, "unsupported_platform");
396
418
  }
397
- function runPrivileged(argv) {
398
- return runCmd3("sudo", argv);
419
+ function runPrivileged(argv, opts = {}) {
420
+ return runCmd3("sudo", argv, opts);
399
421
  }
400
422
  function isPlatformSupported() {
401
423
  const os = platform2();
402
424
  return os === "linux" || os === "darwin";
403
425
  }
404
- function linuxSetcapMutation(binaryPath) {
426
+ function linuxSetcapMutation(binaryPath, interpreterGrant) {
405
427
  return {
406
- action: `setcap cap_net_bind_service=+ep ${binaryPath}`,
428
+ action: `setcap cap_net_bind_service=+ep ${binaryPath}${interpreterGrant ? " [INTERPRETER GRANT \u2014 #39 escape hatch used, see install output]" : ""}`,
407
429
  reverseCommand: { kind: "setcap_drop", path: binaryPath },
408
430
  async apply() {
409
431
  const result = await runPrivileged(["setcap", "cap_net_bind_service=+ep", binaryPath]);
@@ -416,7 +438,7 @@ function linuxSetcapMutation(binaryPath) {
416
438
  function macosLaunchdMutation(params) {
417
439
  const plistContents = macosPlist(params.label, params.binaryPath);
418
440
  return {
419
- action: `install launchd plist at ${params.plistPath}`,
441
+ action: `install launchd plist at ${params.plistPath}${params.interpreterGrant ? ` [INTERPRETER GRANT for ${params.binaryPath} \u2014 #39 escape hatch used, see install output]` : ""}`,
420
442
  reverseCommand: { kind: "launchctl_unload_and_remove", plistPath: params.plistPath },
421
443
  async apply() {
422
444
  await writeFile5(params.plistPath, plistContents, { encoding: "utf8", mode: 420 });
@@ -462,23 +484,30 @@ function macosPlist(label, binaryPath) {
462
484
  </plist>
463
485
  `;
464
486
  }
465
- function runCmd3(cmd, argv) {
487
+ function runCmd3(cmd, argv, opts = {}) {
466
488
  return new Promise((resolve8, reject) => {
467
- const child = spawn3(cmd, argv, { stdio: ["inherit", "pipe", "pipe"] });
489
+ const child = spawn3(cmd, argv, {
490
+ stdio: [opts.stdin === undefined ? "inherit" : "pipe", "pipe", "pipe"]
491
+ });
492
+ if (opts.stdin !== undefined) {
493
+ child.stdin?.end(opts.stdin, "utf8");
494
+ }
468
495
  let stdout = "";
469
496
  let stderr = "";
470
- child.stdout.on("data", (c2) => {
497
+ child.stdout?.on("data", (c2) => {
471
498
  stdout += c2.toString("utf8");
472
499
  });
473
- child.stderr.on("data", (c2) => {
500
+ child.stderr?.on("data", (c2) => {
474
501
  stderr += c2.toString("utf8");
475
502
  });
476
503
  child.on("error", reject);
477
504
  child.on("close", (code) => resolve8({ exitCode: code ?? 1, stdout, stderr }));
478
505
  });
479
506
  }
507
+ var INTERPRETER_BASENAMES, ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG = "--allow-interpreter-capability-grant", ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV = "MOCKSTAR_ALLOW_INTERPRETER_CAPABILITY_GRANT";
480
508
  var init_port_bind = __esm(() => {
481
509
  init_types();
510
+ INTERPRETER_BASENAMES = new Set(["bun", "bun-debug", "node", "deno"]);
482
511
  });
483
512
 
484
513
  // src/features/proxy/dns.ts
@@ -487,13 +516,14 @@ __export(exports_dns, {
487
516
  stopAndRemoveDnsmasq: () => stopAndRemoveDnsmasq,
488
517
  revertHostsBlock: () => revertHostsBlock,
489
518
  join: () => join6,
519
+ buildDnsmasqMutations: () => buildDnsmasqMutations,
490
520
  buildDnsMutations: () => buildDnsMutations,
491
521
  HOSTS_PATH: () => HOSTS_PATH,
492
522
  HOSTS_BLOCK_MARKER: () => HOSTS_BLOCK_MARKER,
493
523
  HOSTS_BLOCK_END: () => HOSTS_BLOCK_END
494
524
  });
495
- import { appendFile, readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
496
- import { platform as platform3 } from "os";
525
+ import { appendFile, mkdtemp as mkdtemp2, readFile as readFile7, rm as rm2, writeFile as writeFile6 } from "fs/promises";
526
+ import { platform as platform3, tmpdir as tmpdir2 } from "os";
497
527
  import { join as join6 } from "path";
498
528
  async function buildDnsMutations(config) {
499
529
  if (config.dnsMode === "hosts-fallback") {
@@ -501,22 +531,61 @@ async function buildDnsMutations(config) {
501
531
  }
502
532
  return buildDnsmasqMutations(config.hosts);
503
533
  }
504
- async function revertHostsBlock(marker) {
534
+ async function revertHostsBlock(marker, opts = {}) {
535
+ const hostsPath = opts.hostsPath ?? HOSTS_PATH;
505
536
  let existing = "";
506
537
  try {
507
- existing = await readFile7(HOSTS_PATH, "utf8");
538
+ existing = await readFile7(hostsPath, "utf8");
508
539
  } catch {
509
540
  return;
510
541
  }
511
- const start = existing.indexOf(marker);
542
+ const markerStart = existing.indexOf(marker);
512
543
  const end = existing.indexOf(HOSTS_BLOCK_END);
513
- if (start === -1 || end === -1)
514
- return;
515
- const next = existing.slice(0, start) + existing.slice(end + HOSTS_BLOCK_END.length).replace(/^\n+/, "");
516
- await runPrivileged(["tee", HOSTS_PATH]).catch(() => {
544
+ if (markerStart === -1 || end === -1)
517
545
  return;
546
+ const blockStart = existing[markerStart - 1] === `
547
+ ` ? markerStart - 1 : markerStart;
548
+ let blockEnd = end + HOSTS_BLOCK_END.length;
549
+ if (existing[blockEnd] === `
550
+ `)
551
+ blockEnd += 1;
552
+ const next = existing.slice(0, blockStart) + existing.slice(blockEnd);
553
+ await privilegedWriteFile(hostsPath, next, {
554
+ runner: opts.runner,
555
+ errorCode: "hosts_revert_failed",
556
+ hint: `Manually remove the block between '${HOSTS_BLOCK_MARKER}' and '${HOSTS_BLOCK_END}' in ${hostsPath}.`
518
557
  });
519
558
  }
559
+ async function privilegedWriteFile(path, content, opts = {
560
+ errorCode: "privileged_write_failed"
561
+ }) {
562
+ const runner = opts.runner ?? runPrivileged;
563
+ const dir = await mkdtemp2(join6(tmpdir2(), "mockstar-proxy-"));
564
+ const tmpFile = join6(dir, "content");
565
+ try {
566
+ await writeFile6(tmpFile, content, "utf8");
567
+ const mvResult = await runner(["mv", tmpFile, path]);
568
+ if (mvResult.exitCode === 0) {
569
+ process.stderr.write(`mockstar-proxy: wrote ${path} via 'mv' (atomic rename).
570
+ `);
571
+ return;
572
+ }
573
+ const mvError = mvResult.stderr.trim() || mvResult.stdout.trim() || `mv exited with code ${mvResult.exitCode}`;
574
+ const teeResult = await runner(["tee", path], { stdin: content });
575
+ if (teeResult.exitCode === 0) {
576
+ const why = "target is likely a bind mount, e.g. inside a container";
577
+ process.stderr.write(`mockstar-proxy: 'mv' failed for ${path} (${mvError}); wrote via piped 'tee' instead (${why}).
578
+ `);
579
+ return;
580
+ }
581
+ const teeError = teeResult.stderr.trim() || teeResult.stdout.trim() || `tee exited with code ${teeResult.exitCode}`;
582
+ throw new ProxyError(`Failed to write ${path}: mv failed (${mvError}); piped tee fallback also failed (${teeError})`, opts.errorCode, opts.hint);
583
+ } finally {
584
+ await rm2(dir, { recursive: true, force: true }).catch(() => {
585
+ return;
586
+ });
587
+ }
588
+ }
520
589
  async function stopAndRemoveDnsmasq() {
521
590
  const os = platform3();
522
591
  if (os === "darwin") {
@@ -554,7 +623,7 @@ ${HOSTS_BLOCK_END}
554
623
  }
555
624
  ];
556
625
  }
557
- function buildDnsmasqMutations(hosts) {
626
+ function buildDnsmasqMutations(hosts, overrides = {}) {
558
627
  const os = platform3();
559
628
  if (os !== "darwin" && os !== "linux") {
560
629
  throw new ProxyError(`dnsmasq mode not supported on platform '${os}' in v1. Use hosts-fallback mode.`, "dnsmasq_platform_unsupported");
@@ -584,10 +653,12 @@ ${hosts.map((h2) => `address=/${h2.host}/127.0.0.1`).join(`
584
653
  const content = `nameserver 127.0.0.1
585
654
  port 53
586
655
  `;
587
- const result = await runPrivileged(["tee", resolverPath]);
588
- if (result.exitCode !== 0) {
589
- throw new ProxyError(`Failed to write ${resolverPath}`, "resolver_write_failed");
590
- }
656
+ await privilegedWriteFile(resolverPath, content, {
657
+ runner: overrides.runner,
658
+ errorCode: "resolver_write_failed",
659
+ hint: `Manually create ${resolverPath} with:
660
+ ${content}`
661
+ });
591
662
  }
592
663
  });
593
664
  }
@@ -2596,20 +2667,64 @@ JSONPath.prototype.safeVm = {
2596
2667
  JSONPath.prototype.vm = vm;
2597
2668
 
2598
2669
  // src/core/matching/discriminators.ts
2599
- function evaluateDiscriminators(pred, req) {
2670
+ function compileMatcher(spec) {
2671
+ if (typeof spec === "string")
2672
+ return { kind: "exact", value: spec };
2673
+ if ("equals" in spec)
2674
+ return { kind: "exact", value: spec.equals };
2675
+ if ("regex" in spec)
2676
+ return { kind: "regex", re: new RegExp(spec.regex) };
2677
+ if ("startsWith" in spec)
2678
+ return { kind: "startsWith", value: spec.startsWith };
2679
+ return { kind: "contains", value: spec.contains };
2680
+ }
2681
+ function compileDim(record) {
2682
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2683
+ }
2684
+ function compilePredicate(pred) {
2685
+ return {
2686
+ ...pred.query && { query: compileDim(pred.query) },
2687
+ ...pred.headers && { headers: compileDim(pred.headers) },
2688
+ ...pred.body && { body: pred.body }
2689
+ };
2690
+ }
2691
+ function compiledMatchOk(compiled, got) {
2692
+ if (compiled.kind === "exact")
2693
+ return got === compiled.value;
2694
+ if (got === undefined)
2695
+ return false;
2696
+ if (compiled.kind === "regex")
2697
+ return compiled.re.test(got);
2698
+ if (compiled.kind === "startsWith")
2699
+ return got.startsWith(compiled.value);
2700
+ return got.includes(compiled.value);
2701
+ }
2702
+ function describeCompiled(m) {
2703
+ switch (m.kind) {
2704
+ case "exact":
2705
+ return `=${m.value}`;
2706
+ case "regex":
2707
+ return `~/${m.re.source}/`;
2708
+ case "startsWith":
2709
+ return `^${m.value}`;
2710
+ case "contains":
2711
+ return `*${m.value}*`;
2712
+ }
2713
+ }
2714
+ function evaluateCompiledDiscriminators(pred, req) {
2600
2715
  if (pred.query) {
2601
- for (const [field, expected] of Object.entries(pred.query)) {
2716
+ for (const [field, expected] of pred.query) {
2602
2717
  const got = req.query.get(field);
2603
- if (!stringMatchOk(expected, got)) {
2604
- return { kind: "query", field, expected: describe(expected), got };
2718
+ if (!compiledMatchOk(expected, got)) {
2719
+ return { kind: "query", field, expected: describeCompiled(expected), got };
2605
2720
  }
2606
2721
  }
2607
2722
  }
2608
2723
  if (pred.headers) {
2609
- for (const [field, expected] of Object.entries(pred.headers)) {
2724
+ for (const [field, expected] of pred.headers) {
2610
2725
  const got = req.headers.get(field.toLowerCase());
2611
- if (!stringMatchOk(expected, got)) {
2612
- return { kind: "headers", field, expected: describe(expected), got };
2726
+ if (!compiledMatchOk(expected, got)) {
2727
+ return { kind: "headers", field, expected: describeCompiled(expected), got };
2613
2728
  }
2614
2729
  }
2615
2730
  }
@@ -2634,34 +2749,6 @@ function evaluateDiscriminators(pred, req) {
2634
2749
  }
2635
2750
  return null;
2636
2751
  }
2637
- function stringMatchOk(spec, got) {
2638
- if (typeof spec === "string")
2639
- return got === spec;
2640
- if ("equals" in spec)
2641
- return got === spec.equals;
2642
- if (got === undefined)
2643
- return false;
2644
- if ("regex" in spec)
2645
- return new RegExp(spec.regex).test(got);
2646
- if ("startsWith" in spec)
2647
- return got.startsWith(spec.startsWith);
2648
- if ("contains" in spec)
2649
- return got.includes(spec.contains);
2650
- return false;
2651
- }
2652
- function describe(spec) {
2653
- if (typeof spec === "string")
2654
- return `=${spec}`;
2655
- if ("equals" in spec)
2656
- return `=${spec.equals}`;
2657
- if ("regex" in spec)
2658
- return `~/${spec.regex}/`;
2659
- if ("startsWith" in spec)
2660
- return `^${spec.startsWith}`;
2661
- if ("contains" in spec)
2662
- return `*${spec.contains}*`;
2663
- return "?";
2664
- }
2665
2752
  function deepEquals(a, b) {
2666
2753
  if (a === b)
2667
2754
  return true;
@@ -2773,7 +2860,7 @@ function buildMatchIndex(entries) {
2773
2860
  const byMethod = new Map;
2774
2861
  const wildcardMethodRoot = createNode();
2775
2862
  entries.forEach((e, i) => {
2776
- const indexed = { entry: e, order: i };
2863
+ const indexed = { entry: e, order: i, compiled: compilePredicate(e.match) };
2777
2864
  if (e.match.method === "*") {
2778
2865
  insertPattern(wildcardMethodRoot, e.match.path, indexed);
2779
2866
  return;
@@ -2807,7 +2894,7 @@ function buildMatchIndex(entries) {
2807
2894
  match(method, path, req) {
2808
2895
  const hits = orderCandidates(candidates(method, path));
2809
2896
  for (const hit of hits) {
2810
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2897
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2811
2898
  if (!failure) {
2812
2899
  return { entry: hit.value.entry, params: hit.params };
2813
2900
  }
@@ -2820,7 +2907,7 @@ function buildMatchIndex(entries) {
2820
2907
  for (const hit of hits) {
2821
2908
  if (out.length >= limit)
2822
2909
  break;
2823
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2910
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2824
2911
  if (failure)
2825
2912
  out.push({ entry: hit.value.entry, params: hit.params, failure });
2826
2913
  }
@@ -2830,7 +2917,7 @@ function buildMatchIndex(entries) {
2830
2917
  }
2831
2918
 
2832
2919
  // src/core/scenarios/evaluator.ts
2833
- function compileMatcher(spec) {
2920
+ function compileMatcher2(spec) {
2834
2921
  if (typeof spec === "string")
2835
2922
  return { kind: "exact", value: spec };
2836
2923
  if ("equals" in spec)
@@ -2841,15 +2928,15 @@ function compileMatcher(spec) {
2841
2928
  return { kind: "startsWith", value: spec.startsWith };
2842
2929
  return { kind: "contains", value: spec.contains };
2843
2930
  }
2844
- function compileDim(record) {
2845
- return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2931
+ function compileDim2(record) {
2932
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher2(v)]));
2846
2933
  }
2847
- function compilePredicate(pred) {
2934
+ function compilePredicate2(pred) {
2848
2935
  return {
2849
- ...pred.params && { params: compileDim(pred.params) },
2850
- ...pred.query && { query: compileDim(pred.query) },
2851
- ...pred.headers && { headers: compileDim(pred.headers) },
2852
- ...pred.body && { body: compileDim(pred.body) }
2936
+ ...pred.params && { params: compileDim2(pred.params) },
2937
+ ...pred.query && { query: compileDim2(pred.query) },
2938
+ ...pred.headers && { headers: compileDim2(pred.headers) },
2939
+ ...pred.body && { body: compileDim2(pred.body) }
2853
2940
  };
2854
2941
  }
2855
2942
  function compileResponse(resp) {
@@ -2878,7 +2965,7 @@ function compileResponse(resp) {
2878
2965
  function compileScenarioRules(rules) {
2879
2966
  return rules.map((rule) => ({
2880
2967
  id: rule.id,
2881
- predicate: compilePredicate(rule.when),
2968
+ predicate: compilePredicate2(rule.when),
2882
2969
  response: compileResponse(rule.response)
2883
2970
  }));
2884
2971
  }
@@ -6989,13 +7076,6 @@ function timestampUnitFor(scheme) {
6989
7076
 
6990
7077
  // src/core/config/schema.ts
6991
7078
  var MatchMethod = exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "*"]);
6992
- var StringMatch = exports_external.union([
6993
- exports_external.string(),
6994
- exports_external.object({ equals: exports_external.string() }).strict(),
6995
- exports_external.object({ regex: exports_external.string() }).strict(),
6996
- exports_external.object({ startsWith: exports_external.string() }).strict(),
6997
- exports_external.object({ contains: exports_external.string() }).strict()
6998
- ]);
6999
7079
  function isUnsafeRegex(pattern) {
7000
7080
  return /\([^)]*[*+{][^)]*\)[*+{]/.test(pattern) || /\([^)]*\|[^)]*\)[*+{]/.test(pattern);
7001
7081
  }
@@ -7003,7 +7083,7 @@ var StringMatchWithRegexGuard = exports_external.union([
7003
7083
  exports_external.string(),
7004
7084
  exports_external.object({ equals: exports_external.string() }).strict(),
7005
7085
  exports_external.object({ regex: exports_external.string() }).strict().refine((v) => !isUnsafeRegex(v.regex), (v) => ({
7006
- message: `scenario regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
7086
+ message: `regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
7007
7087
  })),
7008
7088
  exports_external.object({ startsWith: exports_external.string() }).strict(),
7009
7089
  exports_external.object({ contains: exports_external.string() }).strict()
@@ -7016,8 +7096,8 @@ var BodyMatch = exports_external.object({
7016
7096
  var MatchPredicate = exports_external.object({
7017
7097
  method: MatchMethod.default("*"),
7018
7098
  path: exports_external.string().min(1),
7019
- query: exports_external.record(StringMatch).optional(),
7020
- headers: exports_external.record(StringMatch).optional(),
7099
+ query: exports_external.record(StringMatchWithRegexGuard).optional(),
7100
+ headers: exports_external.record(StringMatchWithRegexGuard).optional(),
7021
7101
  body: BodyMatch.optional(),
7022
7102
  priority: exports_external.number().int().default(0)
7023
7103
  }).strict();
@@ -7227,7 +7307,7 @@ var MocksFile = exports_external.object({
7227
7307
  var TenantLimits = exports_external.object({
7228
7308
  maxBodyBytes: exports_external.number().int().positive().default(1048576),
7229
7309
  maxResponseBytes: exports_external.number().int().positive().default(1048576),
7230
- requestsPerSecond: exports_external.number().int().positive().default(1000),
7310
+ requestsPerSecond: exports_external.number().int().positive().default(1e4),
7231
7311
  journalSize: exports_external.number().int().positive().default(1000)
7232
7312
  }).strict();
7233
7313
  var TenantConfig = exports_external.object({
@@ -7564,130 +7644,117 @@ function preflight(bunVersion = detectBunVersion()) {
7564
7644
  };
7565
7645
  }
7566
7646
 
7567
- // node_modules/hono/dist/compose.js
7568
- var compose = (middleware, onError, onNotFound) => {
7569
- return (context, next) => {
7570
- let index2 = -1;
7571
- return dispatch(0);
7572
- async function dispatch(i) {
7573
- if (i <= index2) {
7574
- throw new Error("next() called multiple times");
7575
- }
7576
- index2 = i;
7577
- let res;
7578
- let isError = false;
7579
- let handler;
7580
- if (middleware[i]) {
7581
- handler = middleware[i][0][0];
7582
- context.req.routeIndex = i;
7583
- } else {
7584
- handler = i === middleware.length && next || undefined;
7585
- }
7586
- if (handler) {
7587
- try {
7588
- res = await handler(context, () => dispatch(i + 1));
7589
- } catch (err) {
7590
- if (err instanceof Error && onError) {
7591
- context.error = err;
7592
- res = await onError(err, context);
7593
- isError = true;
7594
- } else {
7595
- throw err;
7596
- }
7597
- }
7598
- } else {
7599
- if (context.finalized === false && onNotFound) {
7600
- res = await onNotFound(context);
7601
- }
7602
- }
7603
- if (res && (context.finalized === false || isError)) {
7604
- context.res = res;
7605
- }
7606
- return context;
7607
- }
7608
- };
7647
+ // node_modules/hono/dist/http-exception.js
7648
+ var HTTPException = class extends Error {
7649
+ res;
7650
+ status;
7651
+ constructor(status = 500, options) {
7652
+ super(options?.message, { cause: options?.cause });
7653
+ this.res = options?.res;
7654
+ this.status = status;
7655
+ }
7656
+ getResponse() {
7657
+ if (this.res)
7658
+ return new Response(this.res.body, {
7659
+ status: this.status,
7660
+ headers: this.res.headers
7661
+ });
7662
+ return new Response(this.message, { status: this.status });
7663
+ }
7609
7664
  };
7610
7665
 
7611
7666
  // node_modules/hono/dist/request/constants.js
7612
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
7667
+ var GET_MATCH_RESULT = Symbol();
7668
+
7669
+ // node_modules/hono/dist/utils/buffer.js
7670
+ var bufferToFormData = (arrayBuffer, contentType) => {
7671
+ return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
7672
+ };
7613
7673
 
7614
7674
  // node_modules/hono/dist/utils/body.js
7615
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
7675
+ var MAX_NESTED_OBJECTS = 1e4;
7676
+ var isRawRequest = (request) => ("headers" in request);
7677
+ var parseBody = async (request, options = Object.create(null)) => {
7616
7678
  const { all = false, dot = false } = options;
7617
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
7618
- const contentType = headers.get("Content-Type");
7619
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
7620
- return parseFormData(request, { all, dot });
7621
- }
7679
+ const mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
7680
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded")
7681
+ return parseFormData(request, {
7682
+ all,
7683
+ dot
7684
+ });
7622
7685
  return {};
7623
7686
  };
7624
7687
  async function parseFormData(request, options) {
7625
- const formData = await request.formData();
7626
- if (formData) {
7688
+ if (!isRawRequest(request) && request.bodyCache.formData)
7689
+ return convertFormDataToBodyData(await request.bodyCache.formData, options);
7690
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
7691
+ const arrayBuffer = await request.arrayBuffer();
7692
+ const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
7693
+ if (!isRawRequest(request))
7694
+ request.bodyCache.formData = formDataPromise;
7695
+ const formData = await formDataPromise;
7696
+ if (formData)
7627
7697
  return convertFormDataToBodyData(formData, options);
7628
- }
7629
7698
  return {};
7630
7699
  }
7631
7700
  function convertFormDataToBodyData(formData, options) {
7632
- const form = /* @__PURE__ */ Object.create(null);
7701
+ const form = Object.create(null);
7702
+ const nestingState = { count: 0 };
7633
7703
  formData.forEach((value, key) => {
7634
- const shouldParseAllValues = options.all || key.endsWith("[]");
7635
- if (!shouldParseAllValues) {
7704
+ if (!(options.all || key.endsWith("[]")))
7636
7705
  form[key] = value;
7637
- } else {
7706
+ else
7638
7707
  handleParsingAllValues(form, key, value);
7639
- }
7640
7708
  });
7641
- if (options.dot) {
7709
+ if (options.dot)
7642
7710
  Object.entries(form).forEach(([key, value]) => {
7643
- const shouldParseDotValues = key.includes(".");
7644
- if (shouldParseDotValues) {
7645
- handleParsingNestedValues(form, key, value);
7711
+ if (key.includes(".")) {
7712
+ handleParsingNestedValues(form, key, value, nestingState);
7646
7713
  delete form[key];
7647
7714
  }
7648
7715
  });
7649
- }
7650
7716
  return form;
7651
7717
  }
7652
7718
  var handleParsingAllValues = (form, key, value) => {
7653
7719
  if (form[key] !== undefined) {
7654
- if (Array.isArray(form[key])) {
7720
+ if (Array.isArray(form[key]))
7655
7721
  form[key].push(value);
7656
- } else {
7722
+ else
7657
7723
  form[key] = [form[key], value];
7658
- }
7659
- } else {
7660
- if (!key.endsWith("[]")) {
7661
- form[key] = value;
7662
- } else {
7663
- form[key] = [value];
7664
- }
7665
- }
7724
+ } else if (!key.endsWith("[]"))
7725
+ form[key] = value;
7726
+ else
7727
+ form[key] = [value];
7666
7728
  };
7667
- var handleParsingNestedValues = (form, key, value) => {
7668
- if (/(?:^|\.)__proto__\./.test(key)) {
7729
+ var handleParsingNestedValues = (form, key, value, state) => {
7730
+ if (/(?:^|\.)__proto__\./.test(key))
7669
7731
  return;
7670
- }
7671
7732
  let nestedForm = form;
7672
- const keys = key.split(".");
7733
+ const keys = key.split(".", 34);
7734
+ if (keys.length > 33)
7735
+ throwNestingLimitExceeded();
7673
7736
  keys.forEach((key2, index2) => {
7674
- if (index2 === keys.length - 1) {
7737
+ if (index2 === keys.length - 1)
7675
7738
  nestedForm[key2] = value;
7676
- } else {
7739
+ else {
7677
7740
  if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
7678
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
7741
+ if (state.count++ >= MAX_NESTED_OBJECTS)
7742
+ throwNestingLimitExceeded();
7743
+ nestedForm[key2] = Object.create(null);
7679
7744
  }
7680
7745
  nestedForm = nestedForm[key2];
7681
7746
  }
7682
7747
  });
7683
7748
  };
7749
+ var throwNestingLimitExceeded = () => {
7750
+ throw new Error("Nesting limit exceeded");
7751
+ };
7684
7752
 
7685
7753
  // node_modules/hono/dist/utils/url.js
7686
7754
  var splitPath2 = (path) => {
7687
7755
  const paths = path.split("/");
7688
- if (paths[0] === "") {
7756
+ if (paths[0] === "")
7689
7757
  paths.shift();
7690
- }
7691
7758
  return paths;
7692
7759
  };
7693
7760
  var splitRoutingPath = (routePath) => {
@@ -7702,34 +7769,46 @@ var extractGroupsFromPath = (path) => {
7702
7769
  groups.push([mark, match]);
7703
7770
  return mark;
7704
7771
  });
7705
- return { groups, path };
7772
+ return {
7773
+ groups,
7774
+ path
7775
+ };
7706
7776
  };
7707
7777
  var replaceGroupMarks = (paths, groups) => {
7708
7778
  for (let i = groups.length - 1;i >= 0; i--) {
7709
7779
  const [mark] = groups[i];
7710
- for (let j = paths.length - 1;j >= 0; j--) {
7780
+ for (let j = paths.length - 1;j >= 0; j--)
7711
7781
  if (paths[j].includes(mark)) {
7712
7782
  paths[j] = paths[j].replace(mark, groups[i][1]);
7713
7783
  break;
7714
7784
  }
7715
- }
7716
7785
  }
7717
7786
  return paths;
7718
7787
  };
7719
7788
  var patternCache = {};
7720
7789
  var getPattern = (label, next) => {
7721
- if (label === "*") {
7790
+ if (label === "*")
7722
7791
  return "*";
7723
- }
7724
7792
  const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
7725
7793
  if (match) {
7726
7794
  const cacheKey = `${label}#${next}`;
7727
7795
  if (!patternCache[cacheKey]) {
7728
- if (match[2]) {
7729
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
7730
- } else {
7731
- patternCache[cacheKey] = [label, match[1], true];
7732
- }
7796
+ if (match[2])
7797
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
7798
+ cacheKey,
7799
+ match[1],
7800
+ new RegExp(`^${match[2]}(?=/${next})`)
7801
+ ] : [
7802
+ label,
7803
+ match[1],
7804
+ new RegExp(`^${match[2]}$`)
7805
+ ];
7806
+ else
7807
+ patternCache[cacheKey] = [
7808
+ label,
7809
+ match[1],
7810
+ true
7811
+ ];
7733
7812
  }
7734
7813
  return patternCache[cacheKey];
7735
7814
  }
@@ -7748,7 +7827,7 @@ var tryDecode = (str, decoder) => {
7748
7827
  });
7749
7828
  }
7750
7829
  };
7751
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
7830
+ var decodeURIWithPreservedPercent = (value) => decodeURI(value.includes("%25") ? value.replace(/%25/g, "%2525") : value);
7752
7831
  var getPath = (request) => {
7753
7832
  const url = request.url;
7754
7833
  const start = url.indexOf("/", url.indexOf(":") + 4);
@@ -7760,10 +7839,16 @@ var getPath = (request) => {
7760
7839
  const hashIndex = url.indexOf("#", i);
7761
7840
  const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
7762
7841
  const path = url.slice(start, end);
7763
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
7764
- } else if (charCode === 63 || charCode === 35) {
7842
+ const decoded = tryDecode(path, decodeURIWithPreservedPercent);
7843
+ if (/%(?![0-9A-Fa-f]{2})/.test(path)) {
7844
+ const rewritten = new URL("http://localhost");
7845
+ rewritten.pathname = decoded.replace(/[\\\t\n\r]/g, encodeURIComponent);
7846
+ if (tryDecode(rewritten.pathname, decodeURIWithPreservedPercent) !== decoded)
7847
+ return tryDecode(path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), decodeURIWithPreservedPercent);
7848
+ }
7849
+ return decoded;
7850
+ } else if (charCode === 63 || charCode === 35)
7765
7851
  break;
7766
- }
7767
7852
  }
7768
7853
  return url.slice(start, i);
7769
7854
  };
@@ -7772,107 +7857,98 @@ var getPathNoStrict = (request) => {
7772
7857
  return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
7773
7858
  };
7774
7859
  var mergePath = (base, sub, ...rest) => {
7775
- if (rest.length) {
7860
+ if (rest.length)
7776
7861
  sub = mergePath(sub, ...rest);
7777
- }
7778
7862
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
7779
7863
  };
7780
7864
  var checkOptionalParameter = (path) => {
7781
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
7865
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":"))
7782
7866
  return null;
7783
- }
7784
7867
  const segments = path.split("/");
7785
7868
  const results = [];
7786
7869
  let basePath = "";
7787
7870
  segments.forEach((segment) => {
7788
- if (segment !== "" && !/\:/.test(segment)) {
7871
+ if (segment !== "" && !/\:/.test(segment))
7789
7872
  basePath += "/" + segment;
7790
- } else if (/\:/.test(segment)) {
7791
- if (/\?/.test(segment)) {
7792
- if (results.length === 0 && basePath === "") {
7873
+ else if (/\:/.test(segment)) {
7874
+ if (segment.charCodeAt(segment.length - 1) === 63) {
7875
+ if (results.length === 0 && basePath === "")
7793
7876
  results.push("/");
7794
- } else {
7877
+ else
7795
7878
  results.push(basePath);
7796
- }
7797
- const optionalSegment = segment.replace("?", "");
7879
+ const optionalSegment = segment.slice(0, -1);
7798
7880
  basePath += "/" + optionalSegment;
7799
7881
  results.push(basePath);
7800
- } else {
7882
+ } else
7801
7883
  basePath += "/" + segment;
7802
- }
7803
7884
  }
7804
7885
  });
7805
7886
  return results.filter((v, i, a) => a.indexOf(v) === i);
7806
7887
  };
7888
+ var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
7807
7889
  var _decodeURI = (value) => {
7808
- if (!/[%+]/.test(value)) {
7809
- return value;
7810
- }
7811
- if (value.indexOf("+") !== -1) {
7890
+ if (value.indexOf("+") !== -1)
7812
7891
  value = value.replace(/\+/g, " ");
7813
- }
7814
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
7892
+ return tryDecodeURIComponent(value);
7815
7893
  };
7816
7894
  var _getQueryParam = (url, key, multiple) => {
7895
+ const hashIndex = url.indexOf("#", 8);
7896
+ if (hashIndex !== -1)
7897
+ url = url.slice(0, hashIndex);
7817
7898
  let encoded;
7818
- if (!multiple && key && !/[%+]/.test(key)) {
7819
- let keyIndex2 = url.indexOf("?", 8);
7820
- if (keyIndex2 === -1) {
7899
+ if (!multiple && key && !/[%+&=]/.test(key)) {
7900
+ const queryIndex = url.indexOf("?", 8);
7901
+ let keyIndex2 = queryIndex;
7902
+ if (keyIndex2 === -1)
7821
7903
  return;
7822
- }
7823
- if (!url.startsWith(key, keyIndex2 + 1)) {
7904
+ if (!url.startsWith(key, keyIndex2 + 1))
7824
7905
  keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
7825
- }
7826
7906
  while (keyIndex2 !== -1) {
7827
7907
  const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
7828
- if (trailingKeyCode === 61) {
7829
- const valueIndex = keyIndex2 + key.length + 2;
7830
- const endIndex = url.indexOf("&", valueIndex);
7831
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
7832
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
7908
+ if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
7909
+ if (keyIndex2 > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex2)))
7910
+ break;
7911
+ if (trailingKeyCode === 61) {
7912
+ const valueIndex = keyIndex2 + key.length + 2;
7913
+ const endIndex = url.indexOf("&", valueIndex);
7914
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
7915
+ }
7833
7916
  return "";
7834
7917
  }
7835
7918
  keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
7836
7919
  }
7837
7920
  encoded = /[%+]/.test(url);
7838
- if (!encoded) {
7921
+ if (!encoded)
7839
7922
  return;
7840
- }
7841
7923
  }
7842
- const results = {};
7924
+ const results = Object.create(null);
7843
7925
  encoded ??= /[%+]/.test(url);
7844
7926
  let keyIndex = url.indexOf("?", 8);
7845
7927
  while (keyIndex !== -1) {
7846
7928
  const nextKeyIndex = url.indexOf("&", keyIndex + 1);
7847
7929
  let valueIndex = url.indexOf("=", keyIndex);
7848
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
7930
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1)
7849
7931
  valueIndex = -1;
7850
- }
7851
7932
  let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
7852
- if (encoded) {
7933
+ if (encoded)
7853
7934
  name = _decodeURI(name);
7854
- }
7855
7935
  keyIndex = nextKeyIndex;
7856
- if (name === "") {
7936
+ if (name === "")
7857
7937
  continue;
7858
- }
7859
7938
  let value;
7860
- if (valueIndex === -1) {
7939
+ if (valueIndex === -1)
7861
7940
  value = "";
7862
- } else {
7941
+ else {
7863
7942
  value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
7864
- if (encoded) {
7943
+ if (encoded)
7865
7944
  value = _decodeURI(value);
7866
- }
7867
7945
  }
7868
7946
  if (multiple) {
7869
- if (!(results[name] && Array.isArray(results[name]))) {
7947
+ if (!(results[name] && Array.isArray(results[name])))
7870
7948
  results[name] = [];
7871
- }
7872
7949
  results[name].push(value);
7873
- } else {
7950
+ } else
7874
7951
  results[name] ??= value;
7875
- }
7876
7952
  }
7877
7953
  return key ? results[key] : results;
7878
7954
  };
@@ -7883,7 +7959,6 @@ var getQueryParams = (url, key) => {
7883
7959
  var decodeURIComponent_ = decodeURIComponent;
7884
7960
 
7885
7961
  // node_modules/hono/dist/request.js
7886
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
7887
7962
  var HonoRequest = class {
7888
7963
  raw;
7889
7964
  #validatedData;
@@ -7895,24 +7970,22 @@ var HonoRequest = class {
7895
7970
  this.raw = request;
7896
7971
  this.path = path;
7897
7972
  this.#matchResult = matchResult;
7898
- this.#validatedData = {};
7899
7973
  }
7900
7974
  param(key) {
7901
7975
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
7902
7976
  }
7903
7977
  #getDecodedParam(key) {
7904
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
7978
+ const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
7905
7979
  const param = this.#getParamValue(paramKey);
7906
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
7980
+ return param && tryDecodeURIComponent(param);
7907
7981
  }
7908
7982
  #getAllDecodedParams() {
7909
7983
  const decoded = {};
7910
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
7984
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
7911
7985
  for (const key of keys) {
7912
7986
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
7913
- if (value !== undefined) {
7914
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
7915
- }
7987
+ if (value !== undefined)
7988
+ decoded[key] = tryDecodeURIComponent(value);
7916
7989
  }
7917
7990
  return decoded;
7918
7991
  }
@@ -7926,10 +7999,9 @@ var HonoRequest = class {
7926
7999
  return getQueryParams(this.url, key);
7927
8000
  }
7928
8001
  header(name) {
7929
- if (name) {
8002
+ if (name)
7930
8003
  return this.raw.headers.get(name) ?? undefined;
7931
- }
7932
- const headerData = {};
8004
+ const headerData = Object.create(null);
7933
8005
  this.raw.headers.forEach((value, key) => {
7934
8006
  headerData[key] = value;
7935
8007
  });
@@ -7941,18 +8013,15 @@ var HonoRequest = class {
7941
8013
  #cachedBody = (key) => {
7942
8014
  const { bodyCache, raw } = this;
7943
8015
  const cachedBody = bodyCache[key];
7944
- if (cachedBody) {
8016
+ if (cachedBody)
7945
8017
  return cachedBody;
7946
- }
7947
- const anyCachedKey = Object.keys(bodyCache)[0];
7948
- if (anyCachedKey) {
8018
+ for (const anyCachedKey in bodyCache)
7949
8019
  return bodyCache[anyCachedKey].then((body) => {
7950
- if (anyCachedKey === "json") {
8020
+ if (anyCachedKey === "json")
7951
8021
  body = JSON.stringify(body);
7952
- }
7953
- return new Response(body)[key]();
8022
+ const contentType = anyCachedKey === "formData" ? undefined : raw.headers.get("content-type");
8023
+ return new Response(body, { headers: contentType ? { "Content-Type": contentType } : undefined })[key]();
7954
8024
  });
7955
- }
7956
8025
  return bodyCache[key] = raw[key]();
7957
8026
  };
7958
8027
  json() {
@@ -7964,6 +8033,9 @@ var HonoRequest = class {
7964
8033
  arrayBuffer() {
7965
8034
  return this.#cachedBody("arrayBuffer");
7966
8035
  }
8036
+ bytes() {
8037
+ return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
8038
+ }
7967
8039
  blob() {
7968
8040
  return this.#cachedBody("blob");
7969
8041
  }
@@ -7971,10 +8043,10 @@ var HonoRequest = class {
7971
8043
  return this.#cachedBody("formData");
7972
8044
  }
7973
8045
  addValidatedData(target, data) {
7974
- this.#validatedData[target] = data;
8046
+ (this.#validatedData ??= {})[target] = data;
7975
8047
  }
7976
8048
  valid(target) {
7977
- return this.#validatedData[target];
8049
+ return this.#validatedData?.[target];
7978
8050
  }
7979
8051
  get url() {
7980
8052
  return this.raw.url;
@@ -8007,28 +8079,27 @@ var raw = (value, callbacks) => {
8007
8079
  };
8008
8080
  var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
8009
8081
  if (typeof str === "object" && !(str instanceof String)) {
8010
- if (!(str instanceof Promise)) {
8082
+ if (!(str instanceof Promise))
8011
8083
  str = str.toString();
8012
- }
8013
- if (str instanceof Promise) {
8084
+ if (str instanceof Promise)
8014
8085
  str = await str;
8015
- }
8016
8086
  }
8017
8087
  const callbacks = str.callbacks;
8018
- if (!callbacks?.length) {
8088
+ if (!callbacks?.length)
8019
8089
  return Promise.resolve(str);
8020
- }
8021
- if (buffer) {
8090
+ if (buffer)
8022
8091
  buffer[0] += str;
8023
- } else {
8092
+ else
8024
8093
  buffer = [str];
8025
- }
8026
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
8027
- if (preserveCallbacks) {
8094
+ const resStr = Promise.all(callbacks.map((c) => c({
8095
+ phase,
8096
+ buffer,
8097
+ context
8098
+ }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
8099
+ if (preserveCallbacks)
8028
8100
  return raw(await resStr, callbacks);
8029
- } else {
8101
+ else
8030
8102
  return resStr;
8031
- }
8032
8103
  };
8033
8104
 
8034
8105
  // node_modules/hono/dist/context.js
@@ -8071,40 +8142,33 @@ var Context = class {
8071
8142
  return this.#req;
8072
8143
  }
8073
8144
  get event() {
8074
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
8145
+ if (this.#executionCtx && "respondWith" in this.#executionCtx)
8075
8146
  return this.#executionCtx;
8076
- } else {
8147
+ else
8077
8148
  throw Error("This context has no FetchEvent");
8078
- }
8079
8149
  }
8080
8150
  get executionCtx() {
8081
- if (this.#executionCtx) {
8151
+ if (this.#executionCtx)
8082
8152
  return this.#executionCtx;
8083
- } else {
8153
+ else
8084
8154
  throw Error("This context has no ExecutionContext");
8085
- }
8086
8155
  }
8087
8156
  get res() {
8088
- return this.#res ||= createResponseInstance(null, {
8089
- headers: this.#preparedHeaders ??= new Headers
8090
- });
8157
+ return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers });
8091
8158
  }
8092
8159
  set res(_res) {
8093
8160
  if (this.#res && _res) {
8094
8161
  _res = createResponseInstance(_res.body, _res);
8095
8162
  for (const [k, v] of this.#res.headers.entries()) {
8096
- if (k === "content-type") {
8163
+ if (k === "content-type")
8097
8164
  continue;
8098
- }
8099
8165
  if (k === "set-cookie") {
8100
8166
  const cookies = this.#res.headers.getSetCookie();
8101
8167
  _res.headers.delete("set-cookie");
8102
- for (const cookie of cookies) {
8168
+ for (const cookie of cookies)
8103
8169
  _res.headers.append("set-cookie", cookie);
8104
- }
8105
- } else {
8170
+ } else
8106
8171
  _res.headers.set(k, v);
8107
- }
8108
8172
  }
8109
8173
  }
8110
8174
  this.#res = _res;
@@ -8120,17 +8184,15 @@ var Context = class {
8120
8184
  this.#renderer = renderer;
8121
8185
  };
8122
8186
  header = (name, value, options) => {
8123
- if (this.finalized) {
8187
+ if (this.finalized && !this.#res.bodyUsed)
8124
8188
  this.#res = createResponseInstance(this.#res.body, this.#res);
8125
- }
8126
8189
  const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
8127
- if (value === undefined) {
8190
+ if (value === undefined)
8128
8191
  headers.delete(name);
8129
- } else if (options?.append) {
8192
+ else if (options?.append)
8130
8193
  headers.append(name, value);
8131
- } else {
8194
+ else
8132
8195
  headers.set(name, value);
8133
- }
8134
8196
  };
8135
8197
  status = (status) => {
8136
8198
  this.#status = status;
@@ -8143,37 +8205,46 @@ var Context = class {
8143
8205
  return this.#var ? this.#var.get(key) : undefined;
8144
8206
  };
8145
8207
  get var() {
8146
- if (!this.#var) {
8208
+ if (!this.#var)
8147
8209
  return {};
8148
- }
8149
8210
  return Object.fromEntries(this.#var);
8150
8211
  }
8151
8212
  #newResponse(data, arg, headers) {
8152
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
8153
- if (typeof arg === "object" && "headers" in arg) {
8154
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
8155
- for (const [key, value] of argHeaders) {
8156
- if (key.toLowerCase() === "set-cookie") {
8213
+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
8214
+ if (typeof arg === "object" && arg.headers) {
8215
+ responseHeaders ??= new Headers;
8216
+ for (const [key, value] of new Headers(arg.headers))
8217
+ if (key === "set-cookie")
8157
8218
  responseHeaders.append(key, value);
8158
- } else {
8219
+ else
8159
8220
  responseHeaders.set(key, value);
8160
- }
8161
- }
8162
8221
  }
8163
8222
  if (headers) {
8164
- for (const [k, v] of Object.entries(headers)) {
8165
- if (typeof v === "string") {
8166
- responseHeaders.set(k, v);
8167
- } else {
8168
- responseHeaders.delete(k);
8169
- for (const v2 of v) {
8170
- responseHeaders.append(k, v2);
8223
+ if (!responseHeaders) {
8224
+ let count = 0;
8225
+ for (const k in headers)
8226
+ if (++count > 1 || typeof headers[k] !== "string") {
8227
+ responseHeaders = new Headers;
8228
+ break;
8171
8229
  }
8172
- }
8173
8230
  }
8231
+ if (responseHeaders)
8232
+ for (const k in headers) {
8233
+ const v = headers[k];
8234
+ if (typeof v === "string")
8235
+ responseHeaders.set(k, v);
8236
+ else {
8237
+ responseHeaders.delete(k);
8238
+ for (const v2 of v)
8239
+ responseHeaders.append(k, v2);
8240
+ }
8241
+ }
8174
8242
  }
8175
8243
  const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
8176
- return createResponseInstance(data, { status, headers: responseHeaders });
8244
+ return createResponseInstance(data, {
8245
+ status,
8246
+ headers: responseHeaders ?? headers
8247
+ });
8177
8248
  }
8178
8249
  newResponse = (...args) => this.#newResponse(...args);
8179
8250
  body = (data, arg, headers) => this.#newResponse(data, arg, headers);
@@ -8198,10 +8269,57 @@ var Context = class {
8198
8269
  };
8199
8270
  };
8200
8271
 
8272
+ // node_modules/hono/dist/compose.js
8273
+ var compose = (middleware, onError, onNotFound) => {
8274
+ return (context, next) => {
8275
+ let index2 = -1;
8276
+ return dispatch(0);
8277
+ async function dispatch(i) {
8278
+ if (i <= index2)
8279
+ throw new Error("next() called multiple times");
8280
+ index2 = i;
8281
+ let res;
8282
+ let isError = false;
8283
+ let handler;
8284
+ if (middleware[i]) {
8285
+ handler = middleware[i][0][0];
8286
+ context.req.routeIndex = i;
8287
+ } else
8288
+ handler = i === middleware.length && next || undefined;
8289
+ if (handler)
8290
+ try {
8291
+ res = await handler(context, () => dispatch(i + 1));
8292
+ } catch (err) {
8293
+ if (err instanceof Error && onError) {
8294
+ context.error = err;
8295
+ res = await onError(err, context);
8296
+ isError = true;
8297
+ } else
8298
+ throw err;
8299
+ }
8300
+ else if (context.finalized === false && onNotFound)
8301
+ res = await onNotFound(context);
8302
+ if (res && (context.finalized === false || isError))
8303
+ context.res = res;
8304
+ return context;
8305
+ }
8306
+ };
8307
+ };
8308
+
8309
+ // node_modules/hono/dist/helper/route/index.js
8310
+ var matchedRoutes = (c) => c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route);
8311
+ var routePath = (c, index2) => matchedRoutes(c).at(index2 ?? c.req.routeIndex)?.path ?? "";
8312
+
8201
8313
  // node_modules/hono/dist/router.js
8202
- var METHOD_NAME_ALL = "ALL";
8203
- var METHOD_NAME_ALL_LOWERCASE = "all";
8204
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
8314
+ var METHODS = [
8315
+ "get",
8316
+ "post",
8317
+ "put",
8318
+ "delete",
8319
+ "options",
8320
+ "patch",
8321
+ "query"
8322
+ ];
8205
8323
  var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
8206
8324
  var UnsupportedPathError = class extends Error {
8207
8325
  };
@@ -8209,6 +8327,61 @@ var UnsupportedPathError = class extends Error {
8209
8327
  // node_modules/hono/dist/utils/constants.js
8210
8328
  var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
8211
8329
 
8330
+ // node_modules/hono/dist/utils/mount.js
8331
+ var countTrailingSlashes = (path) => {
8332
+ let index2 = path.length;
8333
+ while (index2 > 0 && path.charCodeAt(index2 - 1) === 47)
8334
+ index2--;
8335
+ return path.length - index2;
8336
+ };
8337
+ var getPathPrefixLength = (c, pathPrefix, routePath2) => {
8338
+ if (!/[:*]/.test(pathPrefix))
8339
+ return pathPrefix.length;
8340
+ const path = c.req.path;
8341
+ const matchResult = c.req[GET_MATCH_RESULT];
8342
+ const paramNames = /* @__PURE__ */ new Set;
8343
+ let length = 0;
8344
+ for (const part of splitRoutingPath(pathPrefix)) {
8345
+ if (part[0] === ":" && part.endsWith("}?"))
8346
+ throw new Error(`mount(): Optional regular expression parameters are not supported in "${routePath2}".`);
8347
+ const pattern = getPattern(part);
8348
+ if (pattern && pattern !== "*") {
8349
+ const name = pattern[1];
8350
+ if (paramNames.has(name))
8351
+ throw new Error(`mount(): Duplicate path parameter "${name}" in "${routePath2}".`);
8352
+ paramNames.add(name);
8353
+ }
8354
+ if (pattern && pattern !== "*" && pattern[2] !== true) {
8355
+ const value = matchResult.length === 2 ? matchResult[1][matchResult[0][c.req.routeIndex][1][pattern[1]]] : matchResult[0][c.req.routeIndex][1][pattern[1]];
8356
+ length += value.length + 1;
8357
+ } else if (pattern || part.endsWith("*")) {
8358
+ const end = path.indexOf("/", length + 1);
8359
+ length = end === -1 ? path.length : end;
8360
+ } else
8361
+ length += part.length + 1;
8362
+ }
8363
+ return length;
8364
+ };
8365
+ var createMountedRequest = (c, pathPrefix, routePath2) => {
8366
+ if (/[^/]\*$/.test(routePath2))
8367
+ throw new Error(`mount(): Wildcard must follow "/" in "${routePath2}".`);
8368
+ const prefixLength = getPathPrefixLength(c, pathPrefix, routePath2);
8369
+ const path = c.req.path.slice(prefixLength) || "/";
8370
+ if (prefixLength > c.req.path.length || path[0] !== "/" || /\/(?:\.|%2e){1,2}(?:\/|$)/i.test(path))
8371
+ throw new HTTPException(400, { message: "Invalid mounted path" });
8372
+ const rawUrl = c.req.raw.url;
8373
+ if (/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(rawUrl))
8374
+ throw new HTTPException(400, { message: "Invalid mounted path" });
8375
+ const rawPathEnd = rawUrl.search(/[?#]/);
8376
+ const rawTrailingSlashes = countTrailingSlashes(rawPathEnd === -1 ? rawUrl : rawUrl.slice(0, rawPathEnd));
8377
+ if (rawTrailingSlashes > 1 && countTrailingSlashes(c.req.path) === rawTrailingSlashes - 1)
8378
+ throw new HTTPException(400, { message: "Invalid mounted path" });
8379
+ const url = new URL(rawUrl);
8380
+ url.pathname = path.replace(/[\\\t\n\r]/g, encodeURIComponent);
8381
+ if (path.includes("%")) {}
8382
+ return new Request(url, c.req.raw);
8383
+ };
8384
+
8212
8385
  // node_modules/hono/dist/hono-base.js
8213
8386
  var notFoundHandler = (c) => {
8214
8387
  return c.text("404 Not Found", 404);
@@ -8221,13 +8394,14 @@ var errorHandler = (err, c) => {
8221
8394
  console.error(err);
8222
8395
  return c.text("Internal Server Error", 500);
8223
8396
  };
8224
- var Hono = class _Hono {
8397
+ var Hono = class Hono2 {
8225
8398
  get;
8226
8399
  post;
8227
8400
  put;
8228
8401
  delete;
8229
8402
  options;
8230
8403
  patch;
8404
+ query;
8231
8405
  all;
8232
8406
  on;
8233
8407
  use;
@@ -8237,16 +8411,15 @@ var Hono = class _Hono {
8237
8411
  #path = "/";
8238
8412
  routes = [];
8239
8413
  constructor(options = {}) {
8240
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
8241
- allMethods.forEach((method) => {
8414
+ [...METHODS, "all"].forEach((method) => {
8242
8415
  this[method] = (args1, ...args) => {
8243
- if (typeof args1 === "string") {
8416
+ const methodName = method.toUpperCase();
8417
+ if (typeof args1 === "string")
8244
8418
  this.#path = args1;
8245
- } else {
8246
- this.#addRoute(method, this.#path, args1);
8247
- }
8419
+ else
8420
+ this.#addRoute(methodName, this.#path, args1);
8248
8421
  args.forEach((handler) => {
8249
- this.#addRoute(method, this.#path, handler);
8422
+ this.#addRoute(methodName, this.#path, handler);
8250
8423
  });
8251
8424
  return this;
8252
8425
  };
@@ -8255,22 +8428,22 @@ var Hono = class _Hono {
8255
8428
  for (const p of [path].flat()) {
8256
8429
  this.#path = p;
8257
8430
  for (const m of [method].flat()) {
8258
- handlers.map((handler) => {
8259
- this.#addRoute(m.toUpperCase(), this.#path, handler);
8260
- });
8431
+ const methodName = m.toUpperCase();
8432
+ for (const handler of handlers)
8433
+ this.#addRoute(methodName, this.#path, handler);
8261
8434
  }
8262
8435
  }
8263
8436
  return this;
8264
8437
  };
8265
8438
  this.use = (arg1, ...handlers) => {
8266
- if (typeof arg1 === "string") {
8439
+ if (typeof arg1 === "string")
8267
8440
  this.#path = arg1;
8268
- } else {
8441
+ else {
8269
8442
  this.#path = "*";
8270
8443
  handlers.unshift(arg1);
8271
8444
  }
8272
8445
  handlers.forEach((handler) => {
8273
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
8446
+ this.#addRoute("ALL", this.#path, handler);
8274
8447
  });
8275
8448
  return this;
8276
8449
  };
@@ -8279,7 +8452,7 @@ var Hono = class _Hono {
8279
8452
  this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
8280
8453
  }
8281
8454
  #clone() {
8282
- const clone = new _Hono({
8455
+ const clone = new Hono2({
8283
8456
  router: this.router,
8284
8457
  getPath: this.getPath
8285
8458
  });
@@ -8294,13 +8467,13 @@ var Hono = class _Hono {
8294
8467
  const subApp = this.basePath(path);
8295
8468
  app.routes.map((r) => {
8296
8469
  let handler;
8297
- if (app.errorHandler === errorHandler) {
8470
+ if (app.errorHandler === errorHandler)
8298
8471
  handler = r.handler;
8299
- } else {
8472
+ else {
8300
8473
  handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
8301
8474
  handler[COMPOSED_HANDLER] = r.handler;
8302
8475
  }
8303
- subApp.#addRoute(r.method, r.path, handler);
8476
+ subApp.#addRoute(r.method, r.path, handler, r.basePath);
8304
8477
  });
8305
8478
  return this;
8306
8479
  }
@@ -8321,15 +8494,14 @@ var Hono = class _Hono {
8321
8494
  let replaceRequest;
8322
8495
  let optionHandler;
8323
8496
  if (options) {
8324
- if (typeof options === "function") {
8497
+ if (typeof options === "function")
8325
8498
  optionHandler = options;
8326
- } else {
8499
+ else {
8327
8500
  optionHandler = options.optionHandler;
8328
- if (options.replaceRequest === false) {
8501
+ if (options.replaceRequest === false)
8329
8502
  replaceRequest = (request) => request;
8330
- } else {
8503
+ else
8331
8504
  replaceRequest = options.replaceRequest;
8332
- }
8333
8505
  }
8334
8506
  }
8335
8507
  const getOptions = optionHandler ? (c) => {
@@ -8342,42 +8514,38 @@ var Hono = class _Hono {
8342
8514
  } catch {}
8343
8515
  return [c.env, executionContext];
8344
8516
  };
8345
- replaceRequest ||= (() => {
8346
- const mergedPath = mergePath(this._basePath, path);
8347
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
8348
- return (request) => {
8349
- const url = new URL(request.url);
8350
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
8351
- return new Request(url, request);
8352
- };
8353
- })();
8517
+ const defaultReplaceRequest = (c) => {
8518
+ const mountedRoutePath = routePath(c);
8519
+ return createMountedRequest(c, mountedRoutePath.replace(/\/?\*$/, ""), mountedRoutePath);
8520
+ };
8354
8521
  const handler = async (c, next) => {
8355
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
8356
- if (res) {
8522
+ const res = await applicationHandler(replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c), ...getOptions(c));
8523
+ if (res)
8357
8524
  return res;
8358
- }
8359
8525
  await next();
8360
8526
  };
8361
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
8527
+ this.#addRoute("ALL", mergePath(path, "*"), handler);
8362
8528
  return this;
8363
8529
  }
8364
- #addRoute(method, path, handler) {
8365
- method = method.toUpperCase();
8530
+ #addRoute(method, path, handler, baseRoutePath) {
8366
8531
  path = mergePath(this._basePath, path);
8367
- const r = { basePath: this._basePath, path, method, handler };
8532
+ const r = {
8533
+ basePath: baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath,
8534
+ path,
8535
+ method,
8536
+ handler
8537
+ };
8368
8538
  this.router.add(method, path, [handler, r]);
8369
8539
  this.routes.push(r);
8370
8540
  }
8371
8541
  #handleError(err, c) {
8372
- if (err instanceof Error) {
8542
+ if (err instanceof Error)
8373
8543
  return this.errorHandler(err, c);
8374
- }
8375
8544
  throw err;
8376
8545
  }
8377
8546
  #dispatch(request, executionCtx, env, method) {
8378
- if (method === "HEAD") {
8547
+ if (method === "HEAD")
8379
8548
  return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
8380
- }
8381
8549
  const path = this.getPath(request, { env });
8382
8550
  const matchResult = this.router.match(method, path);
8383
8551
  const c = new Context(request, {
@@ -8402,9 +8570,8 @@ var Hono = class _Hono {
8402
8570
  return (async () => {
8403
8571
  try {
8404
8572
  const context = await composed(c);
8405
- if (!context.finalized) {
8573
+ if (!context.finalized)
8406
8574
  throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
8407
- }
8408
8575
  return context.res;
8409
8576
  } catch (err) {
8410
8577
  return this.#handleError(err, c);
@@ -8415,9 +8582,8 @@ var Hono = class _Hono {
8415
8582
  return this.#dispatch(request, rest[1], rest[0], request.method);
8416
8583
  };
8417
8584
  request = (input, requestInit, Env, executionCtx) => {
8418
- if (input instanceof Request) {
8585
+ if (input instanceof Request)
8419
8586
  return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
8420
- }
8421
8587
  input = input.toString();
8422
8588
  return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
8423
8589
  };
@@ -8428,20 +8594,21 @@ var Hono = class _Hono {
8428
8594
  };
8429
8595
  };
8430
8596
 
8597
+ // node_modules/hono/dist/router/utils.js
8598
+ var createNullObject = () => Object.create(null);
8599
+
8431
8600
  // node_modules/hono/dist/router/reg-exp-router/matcher.js
8432
8601
  var emptyParam = [];
8433
8602
  function match(method, path) {
8434
8603
  const matchers = this.buildAllMatchers();
8435
8604
  const match2 = (method2, path2) => {
8436
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
8605
+ const matcher = matchers[method2] || matchers["ALL"];
8437
8606
  const staticMatch = matcher[2][path2];
8438
- if (staticMatch) {
8607
+ if (staticMatch)
8439
8608
  return staticMatch;
8440
- }
8441
8609
  const match3 = path2.match(matcher[0]);
8442
- if (!match3) {
8610
+ if (!match3)
8443
8611
  return [[], emptyParam];
8444
- }
8445
8612
  const index2 = match3.indexOf("", 1);
8446
8613
  return [matcher[1][index2], match3];
8447
8614
  };
@@ -8451,104 +8618,101 @@ function match(method, path) {
8451
8618
 
8452
8619
  // node_modules/hono/dist/router/reg-exp-router/node.js
8453
8620
  var LABEL_REG_EXP_STR = "[^/]+";
8454
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
8455
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
8456
- var PATH_ERROR = /* @__PURE__ */ Symbol();
8457
- var regExpMetaChars = new Set(".\\+*[^]$()");
8621
+ var ONLY_WILDCARD_REG_EXP_STR = "[^]*";
8622
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/[^]*)";
8623
+ var PATH_ERROR = Symbol();
8624
+ var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
8458
8625
  function compareKey(a, b) {
8459
- if (a.length === 1) {
8626
+ if (a.length === 1)
8460
8627
  return b.length === 1 ? a < b ? -1 : 1 : -1;
8461
- }
8462
- if (b.length === 1) {
8628
+ if (b.length === 1)
8463
8629
  return 1;
8464
- }
8465
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
8466
- return 1;
8467
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
8630
+ if (a === "[^]*" || a === "(?:|/[^]*)")
8631
+ return b === "[^]*" ? -1 : 1;
8632
+ else if (b === "[^]*" || b === "(?:|/[^]*)")
8468
8633
  return -1;
8469
- }
8470
- if (a === LABEL_REG_EXP_STR) {
8634
+ if (a === "[^/]+")
8471
8635
  return 1;
8472
- } else if (b === LABEL_REG_EXP_STR) {
8636
+ else if (b === "[^/]+")
8473
8637
  return -1;
8474
- }
8475
8638
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
8476
8639
  }
8477
- var Node = class _Node {
8640
+ var Node = class Node2 {
8478
8641
  #index;
8479
8642
  #varIndex;
8480
- #children = /* @__PURE__ */ Object.create(null);
8481
- insert(tokens, index2, paramMap, context, pathErrorCheckOnly) {
8482
- if (tokens.length === 0) {
8483
- if (this.#index !== undefined) {
8484
- throw PATH_ERROR;
8485
- }
8486
- if (pathErrorCheckOnly) {
8487
- return;
8488
- }
8489
- this.#index = index2;
8490
- return;
8491
- }
8492
- const [token, ...restTokens] = tokens;
8493
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
8494
- let node;
8495
- if (pattern) {
8496
- const name = pattern[1];
8497
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
8498
- if (name && pattern[2]) {
8499
- if (regexpStr === ".*") {
8500
- throw PATH_ERROR;
8501
- }
8502
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
8503
- if (/\((?!\?:)/.test(regexpStr)) {
8504
- throw PATH_ERROR;
8505
- }
8506
- }
8507
- node = this.#children[regexpStr];
8508
- if (!node) {
8509
- if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
8510
- throw PATH_ERROR;
8511
- }
8512
- if (pathErrorCheckOnly) {
8513
- return;
8643
+ #children = createNullObject();
8644
+ insert(tokens, index2, paramMap, context, keys) {
8645
+ let node = this;
8646
+ for (let i = 0, len = tokens.length;i < len; i++) {
8647
+ const token = tokens[i];
8648
+ const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? [
8649
+ "",
8650
+ "",
8651
+ ONLY_WILDCARD_REG_EXP_STR
8652
+ ] : [
8653
+ "",
8654
+ "",
8655
+ LABEL_REG_EXP_STR
8656
+ ] : null : token === "/*" ? [
8657
+ "",
8658
+ "",
8659
+ TAIL_WILDCARD_REG_EXP_STR
8660
+ ] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
8661
+ let nextNode;
8662
+ if (pattern) {
8663
+ const name = pattern[1];
8664
+ let regexpStr = pattern[2] || "[^/]+";
8665
+ if (name && pattern[2]) {
8666
+ if (new RegExp(regexpStr).test(""))
8667
+ throw PATH_ERROR;
8668
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
8669
+ if (/\((?!\?:)/.test(regexpStr))
8670
+ throw PATH_ERROR;
8671
+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr))
8672
+ throw PATH_ERROR;
8673
+ }
8674
+ keys.push(regexpStr);
8675
+ nextNode = node.#children[regexpStr];
8676
+ if (!nextNode) {
8677
+ if (regexpStr !== "[^]*" && regexpStr !== "(?:|/[^]*)") {
8678
+ for (const k in node.#children)
8679
+ if ((regexpStr.length > 1 || k.length > 1) && k !== "[^]*" && k !== "(?:|/[^]*)")
8680
+ throw PATH_ERROR;
8681
+ }
8682
+ nextNode = node.#children[regexpStr] = new Node2;
8514
8683
  }
8515
- node = this.#children[regexpStr] = new _Node;
8516
8684
  if (name !== "") {
8517
- node.#varIndex = context.varIndex++;
8518
- }
8519
- }
8520
- if (!pathErrorCheckOnly && name !== "") {
8521
- paramMap.push([name, node.#varIndex]);
8522
- }
8523
- } else {
8524
- node = this.#children[token];
8525
- if (!node) {
8526
- if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
8527
- throw PATH_ERROR;
8685
+ nextNode.#varIndex ??= context.varIndex++;
8686
+ paramMap.push([name, nextNode.#varIndex]);
8528
8687
  }
8529
- if (pathErrorCheckOnly) {
8530
- return;
8688
+ } else {
8689
+ keys.push(token);
8690
+ nextNode = node.#children[token];
8691
+ if (!nextNode) {
8692
+ for (const k in node.#children)
8693
+ if (k.length > 1 && k !== "[^]*" && k !== "(?:|/[^]*)")
8694
+ throw PATH_ERROR;
8695
+ nextNode = node.#children[token] = new Node2;
8531
8696
  }
8532
- node = this.#children[token] = new _Node;
8533
8697
  }
8698
+ node = nextNode;
8534
8699
  }
8535
- node.insert(restTokens, index2, paramMap, context, pathErrorCheckOnly);
8700
+ if (node.#index !== undefined)
8701
+ throw PATH_ERROR;
8702
+ node.#index = index2;
8536
8703
  }
8537
8704
  buildRegExpStr() {
8538
- const childKeys = Object.keys(this.#children).sort(compareKey);
8539
- const strList = childKeys.map((k) => {
8705
+ const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
8540
8706
  const c = this.#children[k];
8541
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
8542
- });
8543
- if (typeof this.#index === "number") {
8707
+ const childStr = c.buildRegExpStr();
8708
+ return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
8709
+ }).filter(Boolean);
8710
+ if (typeof this.#index === "number" && this.#index !== -1)
8544
8711
  strList.unshift(`#${this.#index}`);
8545
- }
8546
- if (strList.length === 0) {
8712
+ if (strList.length === 0)
8547
8713
  return "";
8548
- }
8549
- if (strList.length === 1) {
8714
+ if (strList.length === 1)
8550
8715
  return strList[0];
8551
- }
8552
8716
  return "(?:" + strList.join("|") + ")";
8553
8717
  }
8554
8718
  };
@@ -8557,40 +8721,58 @@ var Node = class _Node {
8557
8721
  var Trie = class {
8558
8722
  #context = { varIndex: 0 };
8559
8723
  #root = new Node;
8560
- insert(path, index2, pathErrorCheckOnly) {
8724
+ #index = 0;
8725
+ paths = createNullObject();
8726
+ insert(path, isStatic) {
8727
+ const keys = [];
8728
+ if (isStatic) {
8729
+ this.#root.insert(path.split(""), -1, [], this.#context, keys);
8730
+ this.paths[path] = [
8731
+ -1,
8732
+ [],
8733
+ keys
8734
+ ];
8735
+ return;
8736
+ }
8561
8737
  const paramAssoc = [];
8562
8738
  const groups = [];
8739
+ let markedPath = path;
8563
8740
  for (let i = 0;; ) {
8564
8741
  let replaced = false;
8565
- path = path.replace(/\{[^}]+\}/g, (m) => {
8742
+ markedPath = markedPath.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g, (m) => {
8566
8743
  const mark = `@\\${i}`;
8567
8744
  groups[i] = [mark, m];
8568
8745
  i++;
8569
8746
  replaced = true;
8570
8747
  return mark;
8571
8748
  });
8572
- if (!replaced) {
8749
+ if (!replaced)
8573
8750
  break;
8574
- }
8575
8751
  }
8576
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
8752
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./gs) || [];
8577
8753
  for (let i = groups.length - 1;i >= 0; i--) {
8578
8754
  const [mark] = groups[i];
8579
- for (let j = tokens.length - 1;j >= 0; j--) {
8755
+ for (let j = tokens.length - 1;j >= 0; j--)
8580
8756
  if (tokens[j].indexOf(mark) !== -1) {
8581
8757
  tokens[j] = tokens[j].replace(mark, groups[i][1]);
8582
8758
  break;
8583
8759
  }
8584
- }
8585
8760
  }
8586
- this.#root.insert(tokens, index2, paramAssoc, this.#context, pathErrorCheckOnly);
8587
- return paramAssoc;
8761
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, keys);
8762
+ this.paths[path] = [
8763
+ this.#index++,
8764
+ paramAssoc,
8765
+ keys
8766
+ ];
8588
8767
  }
8589
8768
  buildRegExp() {
8590
8769
  let regexp = this.#root.buildRegExpStr();
8591
- if (regexp === "") {
8592
- return [/^$/, [], []];
8593
- }
8770
+ if (regexp === "")
8771
+ return [
8772
+ /^$/,
8773
+ [],
8774
+ []
8775
+ ];
8594
8776
  let captureIndex = 0;
8595
8777
  const indexReplacementMap = [];
8596
8778
  const paramReplacementMap = [];
@@ -8605,245 +8787,105 @@ var Trie = class {
8605
8787
  }
8606
8788
  return "";
8607
8789
  });
8608
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
8790
+ return [
8791
+ new RegExp(`^${regexp}`),
8792
+ indexReplacementMap,
8793
+ paramReplacementMap
8794
+ ];
8609
8795
  }
8610
8796
  };
8611
8797
 
8612
8798
  // node_modules/hono/dist/router/reg-exp-router/router.js
8613
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
8614
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
8615
- function buildWildcardRegExp(path) {
8616
- return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
8617
- }
8618
- function clearWildcardRegExpCache() {
8619
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
8620
- }
8621
- function buildMatcherFromPreprocessedRoutes(routes) {
8622
- const trie = new Trie;
8623
- const handlerData = [];
8624
- if (routes.length === 0) {
8625
- return nullMatcher;
8626
- }
8627
- const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
8628
- const staticMap = /* @__PURE__ */ Object.create(null);
8629
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
8630
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
8631
- if (pathErrorCheckOnly) {
8632
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
8633
- } else {
8634
- j++;
8635
- }
8636
- let paramAssoc;
8637
- try {
8638
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
8639
- } catch (e) {
8640
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
8641
- }
8642
- if (pathErrorCheckOnly) {
8643
- continue;
8644
- }
8645
- handlerData[j] = handlers.map(([h, paramCount]) => {
8646
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
8647
- paramCount -= 1;
8648
- for (;paramCount >= 0; paramCount--) {
8649
- const [key, value] = paramAssoc[paramCount];
8650
- paramIndexMap[key] = value;
8651
- }
8652
- return [h, paramIndexMap];
8653
- });
8654
- }
8655
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
8656
- for (let i = 0, len = handlerData.length;i < len; i++) {
8657
- for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
8658
- const map = handlerData[i][j]?.[1];
8659
- if (!map) {
8660
- continue;
8661
- }
8662
- const keys = Object.keys(map);
8663
- for (let k = 0, len3 = keys.length;k < len3; k++) {
8664
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
8665
- }
8666
- }
8667
- }
8668
- const handlerMap = [];
8669
- for (const i in indexReplacementMap) {
8670
- handlerMap[i] = handlerData[indexReplacementMap[i]];
8671
- }
8672
- return [regexp, handlerMap, staticMap];
8673
- }
8674
- function findMiddleware(middleware, path) {
8675
- if (!middleware) {
8676
- return;
8677
- }
8678
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
8679
- if (buildWildcardRegExp(k).test(path)) {
8680
- return [...middleware[k]];
8681
- }
8682
- }
8683
- return;
8799
+ function endsWithWildcard(keys) {
8800
+ const tail = keys[keys.length - 1];
8801
+ return tail === "[^]*" || tail === "(?:|/[^]*)";
8802
+ }
8803
+ function covers(wildcard, target) {
8804
+ const last = wildcard.length - 1;
8805
+ for (let i = 0;i < last; i++)
8806
+ if (wildcard[i] !== target[i])
8807
+ return false;
8808
+ return wildcard[last] === "[^]*" || target.length === last || target[last] === "/";
8684
8809
  }
8685
8810
  var RegExpRouter = class {
8686
8811
  name = "RegExpRouter";
8687
- #middleware;
8688
- #routes;
8812
+ #handlers;
8813
+ #tries;
8689
8814
  constructor() {
8690
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
8691
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
8815
+ this.#handlers = { ["ALL"]: [] };
8816
+ this.#tries = { ["ALL"]: new Trie };
8817
+ }
8818
+ #insertPath(method, path) {
8819
+ try {
8820
+ this.#tries[method].insert(path, !/\*|\/:/.test(path));
8821
+ } catch (e) {
8822
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
8823
+ }
8692
8824
  }
8693
8825
  add(method, path, handler) {
8694
- const middleware = this.#middleware;
8695
- const routes = this.#routes;
8696
- if (!middleware || !routes) {
8826
+ const handlers = this.#handlers;
8827
+ if (!handlers)
8697
8828
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
8698
- }
8699
- if (!middleware[method]) {
8700
- [middleware, routes].forEach((handlerMap) => {
8701
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
8702
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
8703
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
8704
- });
8705
- });
8706
- }
8707
- if (path === "/*") {
8829
+ const tries = this.#tries;
8830
+ if (!handlers[method]) {
8831
+ tries[method] = new Trie;
8832
+ handlers[method] = [...handlers["ALL"]];
8833
+ for (const p in tries["ALL"].paths)
8834
+ this.#insertPath(method, p);
8835
+ }
8836
+ if (path === "/*")
8708
8837
  path = "*";
8709
- }
8710
- const paramCount = (path.match(/\/:/g) || []).length;
8711
- if (/\*$/.test(path)) {
8712
- const re = buildWildcardRegExp(path);
8713
- if (method === METHOD_NAME_ALL) {
8714
- Object.keys(middleware).forEach((m) => {
8715
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
8716
- });
8717
- } else {
8718
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
8719
- }
8720
- Object.keys(middleware).forEach((m) => {
8721
- if (method === METHOD_NAME_ALL || method === m) {
8722
- Object.keys(middleware[m]).forEach((p) => {
8723
- re.test(p) && middleware[m][p].push([handler, paramCount]);
8724
- });
8725
- }
8726
- });
8727
- Object.keys(routes).forEach((m) => {
8728
- if (method === METHOD_NAME_ALL || method === m) {
8729
- Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
8730
- }
8731
- });
8732
- return;
8733
- }
8838
+ const methods = method === "ALL" ? Object.keys(handlers) : [method];
8734
8839
  const paths = checkOptionalParameter(path) || [path];
8735
- for (let i = 0, len = paths.length;i < len; i++) {
8736
- const path2 = paths[i];
8737
- Object.keys(routes).forEach((m) => {
8738
- if (method === METHOD_NAME_ALL || method === m) {
8739
- routes[m][path2] ||= [
8740
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
8741
- ];
8742
- routes[m][path2].push([handler, paramCount - len + i + 1]);
8743
- }
8744
- });
8745
- }
8840
+ for (const path2 of paths)
8841
+ for (const m of methods) {
8842
+ if (!tries[m].paths[path2])
8843
+ this.#insertPath(m, path2);
8844
+ handlers[m].push([handler, path2]);
8845
+ }
8746
8846
  }
8747
8847
  match = match;
8748
8848
  buildAllMatchers() {
8749
- const matchers = /* @__PURE__ */ Object.create(null);
8750
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
8751
- matchers[method] ||= this.#buildMatcher(method);
8752
- });
8753
- this.#middleware = this.#routes = undefined;
8754
- clearWildcardRegExpCache();
8849
+ const matchers = createNullObject();
8850
+ for (const method of Object.keys(this.#handlers))
8851
+ matchers[method] = this.#buildMatcher(method);
8852
+ this.#handlers = this.#tries = undefined;
8755
8853
  return matchers;
8756
8854
  }
8757
8855
  #buildMatcher(method) {
8758
- const routes = [];
8759
- let hasOwnRoute = method === METHOD_NAME_ALL;
8760
- [this.#middleware, this.#routes].forEach((r) => {
8761
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
8762
- if (ownRoute.length !== 0) {
8763
- hasOwnRoute ||= true;
8764
- routes.push(...ownRoute);
8765
- } else if (method !== METHOD_NAME_ALL) {
8766
- routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
8767
- }
8768
- });
8769
- if (!hasOwnRoute) {
8770
- return null;
8771
- } else {
8772
- return buildMatcherFromPreprocessedRoutes(routes);
8773
- }
8774
- }
8775
- };
8776
-
8777
- // node_modules/hono/dist/router/reg-exp-router/prepared-router.js
8778
- var PreparedRegExpRouter = class {
8779
- name = "PreparedRegExpRouter";
8780
- #matchers;
8781
- #relocateMap;
8782
- constructor(matchers, relocateMap) {
8783
- this.#matchers = matchers;
8784
- this.#relocateMap = relocateMap;
8785
- }
8786
- #addWildcard(method, handlerData) {
8787
- const matcher = this.#matchers[method];
8788
- matcher[1].forEach((list) => list && list.push(handlerData));
8789
- Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
8790
- }
8791
- #addPath(method, path, handler, indexes, map) {
8792
- const matcher = this.#matchers[method];
8793
- if (!map) {
8794
- matcher[2][path][0].push([handler, {}]);
8795
- } else {
8796
- indexes.forEach((index2) => {
8797
- if (typeof index2 === "number") {
8798
- matcher[1][index2].push([handler, map]);
8799
- } else {
8800
- matcher[2][index2 || path][0].push([handler, map]);
8801
- }
8802
- });
8803
- }
8804
- }
8805
- add(method, path, handler) {
8806
- if (!this.#matchers[method]) {
8807
- const all = this.#matchers[METHOD_NAME_ALL];
8808
- const staticMap = {};
8809
- for (const key in all[2]) {
8810
- staticMap[key] = [all[2][key][0].slice(), emptyParam];
8811
- }
8812
- this.#matchers[method] = [
8813
- all[0],
8814
- all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
8815
- staticMap
8816
- ];
8817
- }
8818
- if (path === "/*" || path === "*") {
8819
- const handlerData = [handler, {}];
8820
- if (method === METHOD_NAME_ALL) {
8821
- for (const m in this.#matchers) {
8822
- this.#addWildcard(m, handlerData);
8823
- }
8824
- } else {
8825
- this.#addWildcard(method, handlerData);
8826
- }
8827
- return;
8828
- }
8829
- const data = this.#relocateMap[path];
8830
- if (!data) {
8831
- throw new Error(`Path ${path} is not registered`);
8832
- }
8833
- for (const [indexes, map] of data) {
8834
- if (method === METHOD_NAME_ALL) {
8835
- for (const m in this.#matchers) {
8836
- this.#addPath(m, path, handler, indexes, map);
8837
- }
8838
- } else {
8839
- this.#addPath(method, path, handler, indexes, map);
8840
- }
8841
- }
8856
+ const handlers = this.#handlers[method];
8857
+ const trie = this.#tries[method];
8858
+ const staticMap = createNullObject();
8859
+ const handlerData = [];
8860
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
8861
+ const own = createNullObject();
8862
+ const entries = handlers.map(([h, p], i) => {
8863
+ (own[p] ??= []).push(i);
8864
+ return [h, trie.paths[p][1].reduceRight((map, [key, varIndex]) => {
8865
+ map[key] = paramReplacementMap[varIndex];
8866
+ return map;
8867
+ }, createNullObject())];
8868
+ });
8869
+ const wildcards = Object.keys(own).filter((p) => endsWithWildcard(trie.paths[p][2]));
8870
+ for (const path in trie.paths) {
8871
+ const [index2, , keys] = trie.paths[path];
8872
+ const indexes = [...own[path]];
8873
+ for (const p of wildcards)
8874
+ if (p !== path && covers(trie.paths[p][2], keys))
8875
+ indexes.push(...own[p]);
8876
+ const data = indexes.sort((a, b) => a - b).map((i) => entries[i]);
8877
+ if (index2 === -1) {
8878
+ const last = Math.max(-1, ...data.flatMap(([, map]) => Object.values(map)));
8879
+ staticMap[path] = [data, last === -1 ? emptyParam : path.match(regexp).slice(0, last + 1)];
8880
+ } else
8881
+ handlerData[index2] = data;
8882
+ }
8883
+ return [
8884
+ regexp,
8885
+ indexReplacementMap.map((i) => handlerData[i]),
8886
+ staticMap
8887
+ ];
8842
8888
  }
8843
- buildAllMatchers() {
8844
- return this.#matchers;
8845
- }
8846
- match = match;
8847
8889
  };
8848
8890
 
8849
8891
  // node_modules/hono/dist/router/smart-router/router.js
@@ -8855,15 +8897,17 @@ var SmartRouter = class {
8855
8897
  this.#routers = init.routers;
8856
8898
  }
8857
8899
  add(method, path, handler) {
8858
- if (!this.#routes) {
8900
+ if (!this.#routes)
8859
8901
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
8860
- }
8861
- this.#routes.push([method, path, handler]);
8902
+ this.#routes.push([
8903
+ method,
8904
+ path,
8905
+ handler
8906
+ ]);
8862
8907
  }
8863
8908
  match(method, path) {
8864
- if (!this.#routes) {
8909
+ if (!this.#routes)
8865
8910
  throw new Error("Fatal error");
8866
- }
8867
8911
  const routers = this.#routers;
8868
8912
  const routes = this.#routes;
8869
8913
  const len = routers.length;
@@ -8872,14 +8916,12 @@ var SmartRouter = class {
8872
8916
  for (;i < len; i++) {
8873
8917
  const router = routers[i];
8874
8918
  try {
8875
- for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
8919
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++)
8876
8920
  router.add(...routes[i2]);
8877
- }
8878
8921
  res = router.match(method, path);
8879
8922
  } catch (e) {
8880
- if (e instanceof UnsupportedPathError) {
8923
+ if (e instanceof UnsupportedPathError)
8881
8924
  continue;
8882
- }
8883
8925
  throw e;
8884
8926
  }
8885
8927
  this.match = router.match.bind(router);
@@ -8887,92 +8929,62 @@ var SmartRouter = class {
8887
8929
  this.#routes = undefined;
8888
8930
  break;
8889
8931
  }
8890
- if (i === len) {
8932
+ if (i === len)
8891
8933
  throw new Error("Fatal error");
8892
- }
8893
8934
  this.name = `SmartRouter + ${this.activeRouter.name}`;
8894
8935
  return res;
8895
8936
  }
8896
8937
  get activeRouter() {
8897
- if (this.#routes || this.#routers.length !== 1) {
8938
+ if (this.#routes || this.#routers.length !== 1)
8898
8939
  throw new Error("No active router has been determined yet.");
8899
- }
8900
8940
  return this.#routers[0];
8901
8941
  }
8902
8942
  };
8903
8943
 
8904
8944
  // node_modules/hono/dist/router/trie-router/node.js
8905
- var emptyParams = /* @__PURE__ */ Object.create(null);
8906
- var hasChildren = (children) => {
8907
- for (const _ in children) {
8908
- return true;
8909
- }
8910
- return false;
8911
- };
8912
- var Node2 = class _Node2 {
8913
- #methods;
8914
- #children;
8915
- #patterns;
8916
- #order = 0;
8945
+ var emptyParams = createNullObject();
8946
+ var order = 0;
8947
+ var Node3 = class Node4 {
8948
+ #methods = [];
8949
+ #children = createNullObject();
8950
+ #patterns = [];
8951
+ #pattern;
8917
8952
  #params = emptyParams;
8918
- constructor(method, handler, children) {
8919
- this.#children = children || /* @__PURE__ */ Object.create(null);
8920
- this.#methods = [];
8921
- if (method && handler) {
8922
- const m = /* @__PURE__ */ Object.create(null);
8923
- m[method] = { handler, possibleKeys: [], score: 0 };
8924
- this.#methods = [m];
8925
- }
8926
- this.#patterns = [];
8927
- }
8928
8953
  insert(method, path, handler) {
8929
- this.#order = ++this.#order;
8930
8954
  let curNode = this;
8931
8955
  const parts = splitRoutingPath(path);
8932
- const possibleKeys = [];
8933
- for (let i = 0, len = parts.length;i < len; i++) {
8934
- const p = parts[i];
8935
- const nextP = parts[i + 1];
8936
- const pattern = getPattern(p, nextP);
8937
- const key = Array.isArray(pattern) ? pattern[0] : p;
8938
- if (key in curNode.#children) {
8939
- curNode = curNode.#children[key];
8940
- if (pattern) {
8941
- possibleKeys.push(pattern[1]);
8942
- }
8943
- continue;
8944
- }
8945
- curNode.#children[key] = new _Node2;
8946
- if (pattern) {
8947
- curNode.#patterns.push(pattern);
8948
- possibleKeys.push(pattern[1]);
8949
- }
8950
- curNode = curNode.#children[key];
8951
- }
8952
- curNode.#methods.push({
8953
- [method]: {
8954
- handler,
8955
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
8956
- score: this.#order
8957
- }
8958
- });
8959
- return curNode;
8956
+ const possibleKeys = /* @__PURE__ */ new Set;
8957
+ let i = 0;
8958
+ for (const p of parts) {
8959
+ const nextP = parts[++i];
8960
+ const pattern = getPattern(p, nextP) || (nextP === undefined && p && p.indexOf("*") === p.length - 1 ? p : null);
8961
+ const isParam = Array.isArray(pattern);
8962
+ const key = isParam ? pattern[0] : pattern || p;
8963
+ const child = curNode.#children[key] ||= new Node4;
8964
+ if (pattern && !child.#pattern) {
8965
+ child.#pattern = pattern;
8966
+ curNode.#patterns.push(child);
8967
+ }
8968
+ curNode = child;
8969
+ if (isParam)
8970
+ possibleKeys.add(pattern[1]);
8971
+ }
8972
+ curNode.#methods.push({ [method]: {
8973
+ handler,
8974
+ possibleKeys: [...possibleKeys],
8975
+ score: ++order
8976
+ } });
8960
8977
  }
8961
8978
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
8962
8979
  for (let i = 0, len = node.#methods.length;i < len; i++) {
8963
8980
  const m = node.#methods[i];
8964
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
8965
- const processedSet = {};
8966
- if (handlerSet !== undefined) {
8967
- handlerSet.params = /* @__PURE__ */ Object.create(null);
8981
+ const handlerSet = m[method] || m["ALL"];
8982
+ if (handlerSet) {
8983
+ handlerSet.params = createNullObject();
8968
8984
  handlerSets.push(handlerSet);
8969
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
8970
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
8971
- const key = handlerSet.possibleKeys[i2];
8972
- const processed = processedSet[handlerSet.score];
8973
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
8974
- processedSet[handlerSet.score] = true;
8975
- }
8985
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
8986
+ const key = handlerSet.possibleKeys[i2];
8987
+ handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
8976
8988
  }
8977
8989
  }
8978
8990
  }
@@ -8980,8 +8992,7 @@ var Node2 = class _Node2 {
8980
8992
  search(method, path) {
8981
8993
  const handlerSets = [];
8982
8994
  this.#params = emptyParams;
8983
- const curNode = this;
8984
- let curNodes = [curNode];
8995
+ let curNodes = [this];
8985
8996
  const parts = splitPath2(path);
8986
8997
  const curNodesQueue = [];
8987
8998
  const len = parts.length;
@@ -8996,61 +9007,61 @@ var Node2 = class _Node2 {
8996
9007
  if (nextNode) {
8997
9008
  nextNode.#params = node.#params;
8998
9009
  if (isLast) {
8999
- if (nextNode.#children["*"]) {
9010
+ if (nextNode.#children["*"])
9000
9011
  this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
9001
- }
9002
9012
  this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
9003
- } else {
9013
+ } else
9004
9014
  tempNodes.push(nextNode);
9005
- }
9006
9015
  }
9007
- for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
9008
- const pattern = node.#patterns[k];
9016
+ for (const child of node.#patterns) {
9017
+ const pattern = child.#pattern;
9009
9018
  const params = node.#params === emptyParams ? {} : { ...node.#params };
9010
- if (pattern === "*") {
9011
- const astNode = node.#children["*"];
9012
- if (astNode) {
9013
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
9014
- astNode.#params = params;
9015
- tempNodes.push(astNode);
9019
+ if (typeof pattern === "string") {
9020
+ if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
9021
+ this.#pushHandlerSets(handlerSets, child, method, node.#params);
9022
+ if (pattern === "*") {
9023
+ child.#params = params;
9024
+ tempNodes.push(child);
9025
+ }
9016
9026
  }
9017
9027
  continue;
9018
9028
  }
9019
- const [key, name, matcher] = pattern;
9020
- if (!part && !(matcher instanceof RegExp)) {
9029
+ const [, name, matcher] = pattern;
9030
+ if (!part && matcher === true)
9021
9031
  continue;
9022
- }
9023
- const child = node.#children[key];
9024
- if (matcher instanceof RegExp) {
9025
- if (partOffsets === null) {
9026
- partOffsets = new Array(len);
9032
+ if (matcher !== true) {
9033
+ if (!partOffsets) {
9034
+ partOffsets = [];
9027
9035
  let offset = path[0] === "/" ? 1 : 0;
9028
9036
  for (let p = 0;p < len; p++) {
9029
9037
  partOffsets[p] = offset;
9030
9038
  offset += parts[p].length + 1;
9031
9039
  }
9032
9040
  }
9033
- const restPathString = path.substring(partOffsets[i]);
9041
+ const restPathString = path.slice(partOffsets[i]);
9034
9042
  const m = matcher.exec(restPathString);
9035
9043
  if (m) {
9036
- params[name] = m[0];
9044
+ if (!Object.hasOwn(params, name))
9045
+ params[name] = m[0];
9037
9046
  this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
9038
- if (hasChildren(child.#children)) {
9047
+ if (m[0].length === restPathString.length && child.#children["*"])
9048
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
9049
+ for (const _ in child.#children) {
9039
9050
  child.#params = params;
9040
- const componentCount = m[0].match(/\//)?.length ?? 0;
9041
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
9042
- targetCurNodes.push(child);
9051
+ const componentCount = m[0].match(/\//g)?.length ?? 0;
9052
+ (curNodesQueue[componentCount] ||= []).push(child);
9053
+ break;
9043
9054
  }
9044
9055
  continue;
9045
9056
  }
9046
9057
  }
9047
9058
  if (matcher === true || matcher.test(part)) {
9048
- params[name] = part;
9059
+ if (!Object.hasOwn(params, name))
9060
+ params[name] = part;
9049
9061
  if (isLast) {
9050
9062
  this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
9051
- if (child.#children["*"]) {
9063
+ if (child.#children["*"])
9052
9064
  this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
9053
- }
9054
9065
  } else {
9055
9066
  child.#params = params;
9056
9067
  tempNodes.push(child);
@@ -9061,11 +9072,10 @@ var Node2 = class _Node2 {
9061
9072
  const shifted = curNodesQueue.shift();
9062
9073
  curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
9063
9074
  }
9064
- if (handlerSets.length > 1) {
9075
+ if (handlerSets[1])
9065
9076
  handlerSets.sort((a, b) => {
9066
9077
  return a.score - b.score;
9067
9078
  });
9068
- }
9069
9079
  return [handlerSets.map(({ handler, params }) => [handler, params])];
9070
9080
  }
9071
9081
  };
@@ -9073,19 +9083,10 @@ var Node2 = class _Node2 {
9073
9083
  // node_modules/hono/dist/router/trie-router/router.js
9074
9084
  var TrieRouter = class {
9075
9085
  name = "TrieRouter";
9076
- #node;
9077
- constructor() {
9078
- this.#node = new Node2;
9079
- }
9086
+ #node = new Node3;
9080
9087
  add(method, path, handler) {
9081
- const results = checkOptionalParameter(path);
9082
- if (results) {
9083
- for (let i = 0, len = results.length;i < len; i++) {
9084
- this.#node.insert(method, results[i], handler);
9085
- }
9086
- return;
9087
- }
9088
- this.#node.insert(method, path, handler);
9088
+ for (const result of checkOptionalParameter(path) || [path])
9089
+ this.#node.insert(method, result, handler);
9089
9090
  }
9090
9091
  match(method, path) {
9091
9092
  return this.#node.search(method, path);
@@ -9093,12 +9094,10 @@ var TrieRouter = class {
9093
9094
  };
9094
9095
 
9095
9096
  // node_modules/hono/dist/hono.js
9096
- var Hono2 = class extends Hono {
9097
+ var Hono3 = class extends Hono {
9097
9098
  constructor(options = {}) {
9098
9099
  super(options);
9099
- this.router = options.router ?? new SmartRouter({
9100
- routers: [new RegExpRouter, new TrieRouter]
9101
- });
9100
+ this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter, new TrieRouter] });
9102
9101
  }
9103
9102
  };
9104
9103
 
@@ -9171,6 +9170,77 @@ function installProcessHandlers(opts) {
9171
9170
  process.off("uncaughtException", excHandler);
9172
9171
  };
9173
9172
  }
9173
+ // src/core/http/body-cap.ts
9174
+ function capRequestBodyStream(ctx, maxBodyBytes) {
9175
+ const original = ctx.req.raw;
9176
+ let tooLarge = false;
9177
+ if (original.body && !original.bodyUsed) {
9178
+ let total = 0;
9179
+ const limited = original.body.pipeThrough(new TransformStream({
9180
+ transform(chunk, controller) {
9181
+ total += chunk.byteLength;
9182
+ if (total > maxBodyBytes) {
9183
+ tooLarge = true;
9184
+ controller.error(new Error("body_too_large"));
9185
+ return;
9186
+ }
9187
+ controller.enqueue(chunk);
9188
+ }
9189
+ }));
9190
+ ctx.req.raw = new Request(original, { body: limited, duplex: "half" });
9191
+ }
9192
+ return { tooLarge: () => tooLarge };
9193
+ }
9194
+ function bodyTooLargeResponse(limit) {
9195
+ return new Response(JSON.stringify({ error: "body_too_large", limit }), {
9196
+ status: 413,
9197
+ headers: { "content-type": "application/json" }
9198
+ });
9199
+ }
9200
+
9201
+ // src/core/http/rate-limit.ts
9202
+ class TenantRateLimiter {
9203
+ buckets = new Map;
9204
+ now;
9205
+ constructor(opts = {}) {
9206
+ this.now = opts.now ?? (() => Date.now());
9207
+ }
9208
+ get bucketCount() {
9209
+ return this.buckets.size;
9210
+ }
9211
+ tryAcquire(tenant, limitPerSecond) {
9212
+ const nowMs = this.now();
9213
+ let bucket = this.buckets.get(tenant);
9214
+ if (!bucket) {
9215
+ bucket = { tokens: limitPerSecond, lastRefillMs: nowMs };
9216
+ this.buckets.set(tenant, bucket);
9217
+ } else {
9218
+ const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);
9219
+ if (elapsedMs > 0) {
9220
+ const refill = elapsedMs * limitPerSecond / 1000;
9221
+ bucket.tokens = Math.min(limitPerSecond, bucket.tokens + refill);
9222
+ bucket.lastRefillMs = nowMs;
9223
+ }
9224
+ }
9225
+ if (bucket.tokens >= 1) {
9226
+ bucket.tokens -= 1;
9227
+ return { allowed: true, retryAfterSeconds: 0 };
9228
+ }
9229
+ const deficitMs = (1 - bucket.tokens) / limitPerSecond * 1000;
9230
+ const retryAfterSeconds = Math.max(1, Math.ceil(deficitMs / 1000));
9231
+ return { allowed: false, retryAfterSeconds };
9232
+ }
9233
+ }
9234
+ function rateLimitedResponse(limit, retryAfterSeconds) {
9235
+ return new Response(JSON.stringify({ error: "rate_limited", limit }), {
9236
+ status: 429,
9237
+ headers: {
9238
+ "content-type": "application/json",
9239
+ "retry-after": String(retryAfterSeconds)
9240
+ }
9241
+ });
9242
+ }
9243
+
9174
9244
  // src/core/journal/ring-buffer.ts
9175
9245
  class RingBuffer {
9176
9246
  capacity;
@@ -11579,7 +11649,7 @@ function constantTimeEquals(a2, b2) {
11579
11649
 
11580
11650
  // src/features/admin/endpoints.ts
11581
11651
  function adminRouter(deps) {
11582
- const app = new Hono2;
11652
+ const app = new Hono3;
11583
11653
  app.get("/health", (ctx) => ctx.json({ status: "ok" }));
11584
11654
  app.get("/ready", (ctx) => {
11585
11655
  const ready = deps.ready.current();
@@ -11761,7 +11831,11 @@ var PRIVATE_IPV4_RANGES = [
11761
11831
  [127, 0, 0, 8],
11762
11832
  [169, 254, 0, 16],
11763
11833
  [100, 64, 0, 10],
11764
- [0, 0, 0, 8]
11834
+ [0, 0, 0, 8],
11835
+ [192, 0, 0, 24],
11836
+ [198, 18, 0, 15],
11837
+ [224, 0, 0, 4],
11838
+ [240, 0, 0, 4]
11765
11839
  ];
11766
11840
  function validateUpstreamUrl(raw2, opts = {}) {
11767
11841
  const allowedSchemes = opts.allowedSchemes ?? ["https"];
@@ -11824,12 +11898,49 @@ async function validateUpstreamUrlResolved(raw2, opts = {}) {
11824
11898
  });
11825
11899
  return parsed;
11826
11900
  }
11901
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11902
+ var DEFAULT_MAX_REDIRECT_HOPS = 5;
11903
+ async function fetchWithRedirectGuard(initialUrl, init, validation, maxRedirects = DEFAULT_MAX_REDIRECT_HOPS) {
11904
+ let currentUrl = initialUrl;
11905
+ let method = init.method;
11906
+ let body = init.body;
11907
+ let redirectsFollowed = 0;
11908
+ for (;; ) {
11909
+ const response = await fetch(currentUrl, {
11910
+ method,
11911
+ headers: init.headers,
11912
+ body: method === "GET" || method === "HEAD" ? undefined : body ?? undefined,
11913
+ redirect: "manual",
11914
+ signal: init.signal
11915
+ });
11916
+ const location = response.headers.get("location");
11917
+ if (!REDIRECT_STATUSES.has(response.status) || !location) {
11918
+ return { response, finalUrl: currentUrl, redirectsFollowed };
11919
+ }
11920
+ await response.body?.cancel();
11921
+ if (redirectsFollowed >= maxRedirects) {
11922
+ throw new UrlValidationError(currentUrl.href, `redirect chain exceeded ${maxRedirects} hop(s); blocked before following Location '${location}'`);
11923
+ }
11924
+ redirectsFollowed++;
11925
+ let nextUrl;
11926
+ try {
11927
+ nextUrl = new URL(location, currentUrl);
11928
+ } catch {
11929
+ throw new UrlValidationError(location, "redirect Location header is not a resolvable URL");
11930
+ }
11931
+ currentUrl = await validateUpstreamUrlResolved(nextUrl.href, validation);
11932
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") {
11933
+ method = "GET";
11934
+ body = null;
11935
+ }
11936
+ }
11937
+ }
11827
11938
  function isPrivateHost(hostname) {
11828
11939
  const stripped = hostname.replace(/^\[/, "").replace(/\]$/, "");
11829
11940
  const lowered = stripped.toLowerCase();
11830
11941
  if (lowered === "localhost" || lowered === "ip6-localhost" || lowered === "ip6-loopback")
11831
11942
  return true;
11832
- if (lowered === "::1" || lowered.startsWith("fe80:") || lowered.startsWith("fc") || lowered.startsWith("fd")) {
11943
+ if (isIpLiteral(stripped) && isPrivateIpv6(lowered)) {
11833
11944
  return true;
11834
11945
  }
11835
11946
  const ipv4MappedDotted = lowered.match(/^::ffff:([0-9.]+)$/);
@@ -11850,6 +11961,75 @@ function isPrivateHost(hostname) {
11850
11961
  }
11851
11962
  return false;
11852
11963
  }
11964
+ function expandIpv6(addr) {
11965
+ const halves = addr.split("::");
11966
+ if (halves.length > 2)
11967
+ return null;
11968
+ const parseGroups = (segment) => {
11969
+ if (segment === "")
11970
+ return [];
11971
+ const pieces = segment.split(":");
11972
+ const groups = [];
11973
+ for (let i2 = 0;i2 < pieces.length; i2++) {
11974
+ const piece = pieces[i2] ?? "";
11975
+ if (i2 === pieces.length - 1 && piece.includes(".")) {
11976
+ const octets = piece.split(".").map((o2) => Number.parseInt(o2, 10));
11977
+ if (octets.length !== 4 || octets.some((o2) => Number.isNaN(o2) || o2 < 0 || o2 > 255) || piece.split(".").some((o2) => !/^\d{1,3}$/.test(o2))) {
11978
+ return null;
11979
+ }
11980
+ const [a2 = 0, b2 = 0, c2 = 0, d2 = 0] = octets;
11981
+ groups.push(a2 << 8 | b2, c2 << 8 | d2);
11982
+ continue;
11983
+ }
11984
+ if (piece.length === 0 || piece.length > 4 || !/^[0-9a-f]+$/.test(piece))
11985
+ return null;
11986
+ const value = Number.parseInt(piece, 16);
11987
+ if (Number.isNaN(value))
11988
+ return null;
11989
+ groups.push(value);
11990
+ }
11991
+ return groups;
11992
+ };
11993
+ if (halves.length === 1) {
11994
+ const groups = parseGroups(halves[0] ?? "");
11995
+ return groups && groups.length === 8 ? groups : null;
11996
+ }
11997
+ const head = parseGroups(halves[0] ?? "");
11998
+ const tail = parseGroups(halves[1] ?? "");
11999
+ if (!head || !tail)
12000
+ return null;
12001
+ const missing = 8 - head.length - tail.length;
12002
+ if (missing < 0)
12003
+ return null;
12004
+ return [...head, ...Array(missing).fill(0), ...tail];
12005
+ }
12006
+ function ipv6PrefixMatch(groups, prefixGroups, prefixBits) {
12007
+ let bitsLeft = prefixBits;
12008
+ for (let i2 = 0;i2 < prefixGroups.length && bitsLeft > 0; i2++) {
12009
+ const bits = Math.min(16, bitsLeft);
12010
+ const mask = bits === 16 ? 65535 : 65535 << 16 - bits & 65535;
12011
+ if (((groups[i2] ?? 0) & mask) !== ((prefixGroups[i2] ?? 0) & mask))
12012
+ return false;
12013
+ bitsLeft -= bits;
12014
+ }
12015
+ return true;
12016
+ }
12017
+ function isPrivateIpv6(lowered) {
12018
+ const groups = expandIpv6(lowered);
12019
+ if (!groups)
12020
+ return false;
12021
+ if (groups.every((g2) => g2 === 0))
12022
+ return true;
12023
+ if (groups.slice(0, 7).every((g2) => g2 === 0) && groups[7] === 1)
12024
+ return true;
12025
+ if (ipv6PrefixMatch(groups, [64512], 7))
12026
+ return true;
12027
+ if (ipv6PrefixMatch(groups, [65152], 10))
12028
+ return true;
12029
+ if (ipv6PrefixMatch(groups, [100, 65435, 0, 0, 0, 0], 96))
12030
+ return true;
12031
+ return false;
12032
+ }
11853
12033
  function isPrivateIpv4(ip) {
11854
12034
  const parts = ip.split(".").map((p3) => Number.parseInt(p3, 10));
11855
12035
  if (parts.length !== 4 || parts.some((p3) => Number.isNaN(p3) || p3 < 0 || p3 > 255))
@@ -11861,16 +12041,13 @@ function isPrivateIpv4(ip) {
11861
12041
  }
11862
12042
  return false;
11863
12043
  }
11864
- function matchesIpv4(a2, _b, _c, _d, ra2, _rb, _rc, mask) {
11865
- if (mask === 8)
11866
- return a2 === ra2;
11867
- if (mask === 16)
11868
- return a2 === ra2 && _b === _rb;
11869
- if (mask === 12)
11870
- return a2 === ra2 && (_b & 240) === (_rb & 240);
11871
- if (mask === 10)
11872
- return a2 === ra2 && (_b & 192) === (_rb & 192);
11873
- return false;
12044
+ function matchesIpv4(a2, b2, c2, d2, ra2, rb, rc, mask) {
12045
+ if (mask <= 0 || mask > 32)
12046
+ return false;
12047
+ const value = (a2 << 24 | b2 << 16 | c2 << 8 | d2) >>> 0;
12048
+ const rangeValue = (ra2 << 24 | rb << 16 | rc << 8 | 0) >>> 0;
12049
+ const maskBits = mask === 32 ? 4294967295 : 4294967295 << 32 - mask >>> 0;
12050
+ return (value & maskBits) >>> 0 === (rangeValue & maskBits) >>> 0;
11874
12051
  }
11875
12052
 
11876
12053
  // src/features/pass-through.ts
@@ -11879,12 +12056,13 @@ async function renderPassThrough(entry, ctx, opts) {
11879
12056
  throw new Error(`renderPassThrough called for non-passthrough entry '${entry.id}'`);
11880
12057
  }
11881
12058
  const spec = entry.response;
12059
+ const validationOpts = {
12060
+ allowedSchemes: ["https", "http"],
12061
+ allowPrivateUpstreams: opts.allowPrivateUpstreams
12062
+ };
11882
12063
  let upstreamUrl;
11883
12064
  try {
11884
- upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, {
11885
- allowedSchemes: ["https", "http"],
11886
- allowPrivateUpstreams: opts.allowPrivateUpstreams
11887
- });
12065
+ upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, validationOpts);
11888
12066
  } catch (err) {
11889
12067
  opts.logger.error({
11890
12068
  event: "passthrough_url_rejected",
@@ -11911,14 +12089,16 @@ async function renderPassThrough(entry, ctx, opts) {
11911
12089
  const controller = new AbortController;
11912
12090
  const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
11913
12091
  timer.unref?.();
12092
+ const bodyCap = ctx.req.method === "GET" || ctx.req.method === "HEAD" ? null : capRequestBodyStream(ctx, opts.maxBodyBytes);
11914
12093
  const started = performance.now();
11915
12094
  try {
11916
- const upstreamRes = await fetch(targetUrl, {
12095
+ const requestBody = bodyCap ? await ctx.req.raw.arrayBuffer() : null;
12096
+ const { response: upstreamRes } = await fetchWithRedirectGuard(targetUrl, {
11917
12097
  method: ctx.req.method,
11918
12098
  headers,
11919
- body: ctx.req.method === "GET" || ctx.req.method === "HEAD" ? undefined : await ctx.req.raw.arrayBuffer(),
12099
+ body: requestBody,
11920
12100
  signal: controller.signal
11921
- });
12101
+ }, validationOpts);
11922
12102
  clearTimeout(timer);
11923
12103
  return new Response(upstreamRes.body, {
11924
12104
  status: upstreamRes.status,
@@ -11926,7 +12106,23 @@ async function renderPassThrough(entry, ctx, opts) {
11926
12106
  });
11927
12107
  } catch (err) {
11928
12108
  clearTimeout(timer);
12109
+ if (bodyCap?.tooLarge()) {
12110
+ return bodyTooLargeResponse(opts.maxBodyBytes);
12111
+ }
11929
12112
  const durationMs = performance.now() - started;
12113
+ if (err instanceof UrlValidationError) {
12114
+ opts.logger.error({
12115
+ event: "passthrough_redirect_rejected",
12116
+ entryId: entry.id,
12117
+ upstream: String(upstreamUrl),
12118
+ reason: err.reason
12119
+ });
12120
+ return new Response(JSON.stringify({
12121
+ error: "passthrough_upstream",
12122
+ upstream: String(upstreamUrl),
12123
+ reason: "upstream redirected to a URL rejected by validator"
12124
+ }), { status: 502, headers: { "content-type": "application/json" } });
12125
+ }
11930
12126
  const aborted = err instanceof DOMException && err.name === "AbortError";
11931
12127
  opts.logger.error({
11932
12128
  event: "passthrough_upstream_error",
@@ -12412,12 +12608,39 @@ class BoundedRetryQueue {
12412
12608
  #cap;
12413
12609
  #onDropped;
12414
12610
  #onSizeChange;
12611
+ #timers = new Map;
12612
+ #stopped = false;
12415
12613
  constructor(opts = {}) {
12416
12614
  this.#pq = new PQueue({ concurrency: opts.concurrency ?? DEFAULT_CONCURRENCY });
12417
12615
  this.#cap = opts.cap ?? DEFAULT_CAP;
12418
12616
  this.#onDropped = opts.onDropped;
12419
12617
  this.#onSizeChange = opts.onSizeChange;
12420
12618
  }
12619
+ stop() {
12620
+ if (this.#stopped)
12621
+ return;
12622
+ this.#stopped = true;
12623
+ for (const [timer, resolve4] of this.#timers) {
12624
+ clearTimeout(timer);
12625
+ resolve4();
12626
+ }
12627
+ this.#timers.clear();
12628
+ const abandoned = this.#waiting.splice(0, this.#waiting.length);
12629
+ for (const req of abandoned) {
12630
+ this.#dropDelivery(req);
12631
+ }
12632
+ }
12633
+ #sleep(ms) {
12634
+ if (ms <= 0 || this.#stopped)
12635
+ return Promise.resolve();
12636
+ return new Promise((resolve4) => {
12637
+ const timer = setTimeout(() => {
12638
+ this.#timers.delete(timer);
12639
+ resolve4();
12640
+ }, ms);
12641
+ this.#timers.set(timer, resolve4);
12642
+ });
12643
+ }
12421
12644
  #fireSizeChange() {
12422
12645
  if (!this.#onSizeChange)
12423
12646
  return;
@@ -12436,7 +12659,14 @@ class BoundedRetryQueue {
12436
12659
  inflight() {
12437
12660
  return this.#pq.pending;
12438
12661
  }
12662
+ liveTimerCount() {
12663
+ return this.#timers.size;
12664
+ }
12439
12665
  enqueue(req) {
12666
+ if (this.#stopped) {
12667
+ this.#dropDelivery(req);
12668
+ return;
12669
+ }
12440
12670
  while (this.size() >= this.#cap) {
12441
12671
  const oldest = this.#waiting.shift();
12442
12672
  if (oldest) {
@@ -12469,7 +12699,17 @@ class BoundedRetryQueue {
12469
12699
  if (attempt > 1) {
12470
12700
  const baseMs = req.retry.backoff[attempt - 2] ?? 0;
12471
12701
  const delayMs = applyJitter(baseMs, req.retry.jitterRatio);
12472
- await sleep(delayMs);
12702
+ await this.#sleep(delayMs);
12703
+ if (this.#stopped) {
12704
+ req.onTerminal({
12705
+ deliveryId: req.deliveryId,
12706
+ outcome: "failed",
12707
+ totalAttempts: attempt - 1,
12708
+ lastHttpStatus,
12709
+ totalDurationUs: Math.round((performance.now() - totalStart) * 1000)
12710
+ });
12711
+ return;
12712
+ }
12473
12713
  }
12474
12714
  const gate = req.circuitGate();
12475
12715
  if (gate === "open") {
@@ -12511,7 +12751,7 @@ class BoundedRetryQueue {
12511
12751
  lastError = errorToString(err);
12512
12752
  req.onAttempt({
12513
12753
  attempt,
12514
- outcome: attempt === req.retry.attempts ? "failed" : "success",
12754
+ outcome: attempt === req.retry.attempts ? "failed" : "retrying",
12515
12755
  durationUs: 0,
12516
12756
  error: lastError
12517
12757
  });
@@ -12549,11 +12789,6 @@ function applyJitter(baseMs, ratio) {
12549
12789
  const delta = baseMs * ratio;
12550
12790
  return Math.max(0, Math.round(baseMs - delta + Math.random() * 2 * delta));
12551
12791
  }
12552
- function sleep(ms) {
12553
- if (ms <= 0)
12554
- return Promise.resolve();
12555
- return new Promise((resolve4) => setTimeout(resolve4, ms));
12556
- }
12557
12792
  function errorToString(err) {
12558
12793
  if (err instanceof Error)
12559
12794
  return `${err.name}: ${err.message}`;
@@ -12673,6 +12908,13 @@ class DeliveryEventRegistry {
12673
12908
  this.#completed.delete(id);
12674
12909
  }
12675
12910
  }
12911
+ stop() {
12912
+ const pending = Array.from(this.#pending.values());
12913
+ for (const deferred of pending) {
12914
+ deferred.resolve(null);
12915
+ }
12916
+ this.#pending.clear();
12917
+ }
12676
12918
  pendingCount() {
12677
12919
  return this.#pending.size;
12678
12920
  }
@@ -12682,6 +12924,25 @@ class DeliveryEventRegistry {
12682
12924
  }
12683
12925
  // src/features/webhooks/journal.ts
12684
12926
  import { appendFileSync } from "fs";
12927
+ function redactUrlForJournal(rawUrl) {
12928
+ try {
12929
+ return `${new URL(rawUrl).origin}/[redacted]`;
12930
+ } catch {
12931
+ return "[redacted:unparseable-url]";
12932
+ }
12933
+ }
12934
+ var EMBEDDED_URL_PATTERN = /\bhttps?:\/\/[^\s'"()<>[\]{}]+/gi;
12935
+ function redactUrlsInText(text) {
12936
+ return text.replace(EMBEDDED_URL_PATTERN, (match2) => redactUrlForJournal(match2));
12937
+ }
12938
+ function redactEntry(entry) {
12939
+ return {
12940
+ ...entry,
12941
+ ...entry.resolvedUrl !== undefined && { resolvedUrl: redactUrlForJournal(entry.resolvedUrl) },
12942
+ ...entry.error !== undefined && { error: redactUrlsInText(entry.error) }
12943
+ };
12944
+ }
12945
+
12685
12946
  class WebhookJournalRegistry {
12686
12947
  #buffers = new Map;
12687
12948
  #capacityFor;
@@ -12691,11 +12952,12 @@ class WebhookJournalRegistry {
12691
12952
  this.#journalFile = opts.journalFile;
12692
12953
  }
12693
12954
  record(entry) {
12694
- const buf = this.#bufferFor(entry.tenant);
12695
- buf.push(entry);
12955
+ const redacted = redactEntry(entry);
12956
+ const buf = this.#bufferFor(redacted.tenant);
12957
+ buf.push(redacted);
12696
12958
  if (this.#journalFile) {
12697
12959
  try {
12698
- appendFileSync(this.#journalFile, `${JSON.stringify(entry)}
12960
+ appendFileSync(this.#journalFile, `${JSON.stringify(redacted)}
12699
12961
  `);
12700
12962
  } catch (err) {
12701
12963
  console.warn(`[mockstar] webhook journal file write failed: ${err.message ?? err}`);
@@ -12819,14 +13081,13 @@ function dispatchWebhooks(deps, input) {
12819
13081
  }
12820
13082
  async function performAttempt(spec, input, _deps) {
12821
13083
  const attemptStart = performance.now();
12822
- let urlString;
12823
13084
  const headerUrl = _deps.allowWebhookUrlHeader && spec.acceptHeaderOverride ? input.requestHeaders.get("x-mockstar-webhook-url") : undefined;
12824
- urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12825
- const allowedSchemes = spec.allowHttp ? ["http", "https"] : ["https"];
12826
- await validateUpstreamUrlResolved(urlString, {
12827
- allowedSchemes,
13085
+ const urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
13086
+ const validationOpts = {
13087
+ allowedSchemes: spec.allowHttp ? ["http", "https"] : ["https"],
12828
13088
  allowPrivateUpstreams: spec.allowPrivateNetworks
12829
- });
13089
+ };
13090
+ const validatedUrl = await validateUpstreamUrlResolved(urlString, validationOpts);
12830
13091
  const renderedHeaders = new Headers;
12831
13092
  for (const [key, tmpl] of spec.headers) {
12832
13093
  renderedHeaders.set(key, tmpl.render(input.templateContext));
@@ -12858,14 +13119,20 @@ async function performAttempt(spec, input, _deps) {
12858
13119
  }
12859
13120
  const signal = AbortSignal.timeout(spec.timeoutMs);
12860
13121
  let response;
13122
+ let finalUrl;
12861
13123
  try {
12862
- response = await fetch(urlString, {
13124
+ const result = await fetchWithRedirectGuard(validatedUrl, {
12863
13125
  method: spec.method,
12864
13126
  headers: renderedHeaders,
12865
- body: spec.method === "GET" || spec.method === "DELETE" ? undefined : rawBody,
13127
+ body: spec.method === "GET" || spec.method === "DELETE" ? null : rawBody,
12866
13128
  signal
12867
- });
13129
+ }, validationOpts);
13130
+ response = result.response;
13131
+ finalUrl = result.finalUrl;
12868
13132
  } catch (err) {
13133
+ if (err instanceof UrlValidationError) {
13134
+ throw new Error(`webhook delivery redirect rejected: ${err.message}`);
13135
+ }
12869
13136
  throw new Error(`webhook delivery network error: ${err.message ?? err}`);
12870
13137
  }
12871
13138
  if (!isSuccessStatus(response.status, spec.expectResponse)) {
@@ -12880,7 +13147,7 @@ async function performAttempt(spec, input, _deps) {
12880
13147
  return {
12881
13148
  httpStatus: response.status,
12882
13149
  durationUs: Math.round((performance.now() - attemptStart) * 1000),
12883
- resolvedUrl: urlString
13150
+ resolvedUrl: finalUrl.href
12884
13151
  };
12885
13152
  }
12886
13153
  function isSuccessStatus(status, expect) {
@@ -12931,6 +13198,8 @@ function makeDeliveryId() {
12931
13198
  return crypto.randomUUID();
12932
13199
  }
12933
13200
  // src/server.ts
13201
+ var UNKNOWN_TENANT_BUCKET = ":unknown:";
13202
+ var DEFAULT_REQUESTS_PER_SECOND = 1e4;
12934
13203
  function createServer(opts) {
12935
13204
  const logger = opts.logger ?? createLogger({ deterministic: opts.deterministic });
12936
13205
  const metrics = new Metrics;
@@ -12938,6 +13207,7 @@ function createServer(opts) {
12938
13207
  const snap = opts.holder.get().tenants.get(tenant);
12939
13208
  return snap?.limits.journalSize ?? 1000;
12940
13209
  });
13210
+ const rateLimiter = new TenantRateLimiter({ now: opts.rateLimiterNow });
12941
13211
  const webhookJournal = new WebhookJournalRegistry((tenant) => {
12942
13212
  const snap = opts.holder.get().tenants.get(tenant);
12943
13213
  return snap?.limits.journalSize ?? 1000;
@@ -12982,7 +13252,7 @@ function createServer(opts) {
12982
13252
  const clock = createClock({ deterministic: opts.deterministic ?? false });
12983
13253
  const handlerTimeoutMs = opts.handlerTimeoutMs ?? 5000;
12984
13254
  const genRequestId = createRequestIdGenerator(opts.deterministic ?? false);
12985
- const app = new Hono2;
13255
+ const app = new Hono3;
12986
13256
  const replayWebhook = (tenant, deliveryId) => {
12987
13257
  const snap = opts.holder.get();
12988
13258
  const tenantSnap = snap.tenants.get(tenant);
@@ -13048,6 +13318,7 @@ function createServer(opts) {
13048
13318
  clock,
13049
13319
  journal,
13050
13320
  metrics,
13321
+ rateLimiter,
13051
13322
  handlerTimeoutMs,
13052
13323
  genRequestId,
13053
13324
  webhookJournal,
@@ -13056,15 +13327,22 @@ function createServer(opts) {
13056
13327
  circuitFor,
13057
13328
  allowWebhookUrlHeader
13058
13329
  }));
13330
+ const stopWebhooks = () => {
13331
+ for (const q3 of webhookQueues.values())
13332
+ q3.stop();
13333
+ webhookEvents.stop();
13334
+ };
13059
13335
  return {
13060
13336
  hono: app,
13061
13337
  journal,
13062
13338
  metrics,
13339
+ rateLimiter,
13063
13340
  ready,
13064
13341
  uninstallCrashHandlers,
13065
13342
  webhookJournal,
13066
13343
  webhookEvents,
13067
- replayWebhook
13344
+ replayWebhook,
13345
+ stopWebhooks
13068
13346
  };
13069
13347
  }
13070
13348
  async function dispatch(ctx, deps) {
@@ -13076,28 +13354,35 @@ async function dispatch(ctx, deps) {
13076
13354
  const startedUs = performance.now() * 1000;
13077
13355
  const matchPath = effectivePath(ctx);
13078
13356
  const method = ctx.req.method;
13357
+ const observedTenant = tenantSnap ? tenant : UNKNOWN_TENANT_BUCKET;
13079
13358
  let response;
13080
13359
  let matchedMockId = null;
13081
13360
  let scenarioId;
13082
13361
  let scenarioMissReason;
13083
13362
  let webhookTrigger;
13084
13363
  try {
13085
- if (!tenantSnap) {
13364
+ const rpsLimit = tenantSnap?.limits.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;
13365
+ const rateResult = deps.rateLimiter.tryAcquire(observedTenant, rpsLimit);
13366
+ if (!rateResult.allowed) {
13367
+ response = rateLimitedResponse(rpsLimit, rateResult.retryAfterSeconds);
13368
+ } else if (!tenantSnap) {
13086
13369
  response = notFoundUnknownTenant(tenant, method, matchPath);
13087
13370
  } else {
13088
13371
  const contentLength = Number.parseInt(ctx.req.header("content-length") ?? "0", 10);
13089
13372
  if (contentLength > tenantSnap.limits.maxBodyBytes) {
13090
- response = new Response(JSON.stringify({ error: "body_too_large", limit: tenantSnap.limits.maxBodyBytes }), {
13091
- status: 413,
13092
- headers: { "content-type": "application/json" }
13093
- });
13373
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
13094
13374
  } else {
13095
- const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps);
13096
- response = result.response;
13097
- matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
13098
- scenarioId = result.scenarioId;
13099
- scenarioMissReason = result.scenarioMissReason;
13100
- webhookTrigger = result.webhookTrigger;
13375
+ const bodyResult = await safeParseBody(ctx, tenantSnap.limits.maxBodyBytes);
13376
+ if (!bodyResult.ok) {
13377
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
13378
+ } else {
13379
+ const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, bodyResult.body);
13380
+ response = result.response;
13381
+ matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
13382
+ scenarioId = result.scenarioId;
13383
+ scenarioMissReason = result.scenarioMissReason;
13384
+ webhookTrigger = result.webhookTrigger;
13385
+ }
13101
13386
  }
13102
13387
  }
13103
13388
  } catch (err) {
@@ -13118,7 +13403,7 @@ async function dispatch(ctx, deps) {
13118
13403
  const durationUs = Math.round(performance.now() * 1000 - startedUs);
13119
13404
  const entry = {
13120
13405
  timestamp: Date.now(),
13121
- tenant,
13406
+ tenant: observedTenant,
13122
13407
  requestId,
13123
13408
  method,
13124
13409
  path: matchPath,
@@ -13130,15 +13415,15 @@ async function dispatch(ctx, deps) {
13130
13415
  };
13131
13416
  deps.journal.record(entry);
13132
13417
  deps.metrics.incCounter("mockstar_requests_total", {
13133
- tenant,
13418
+ tenant: observedTenant,
13134
13419
  method,
13135
13420
  status: String(response.status),
13136
13421
  matched: matchedMockId ? "1" : "0"
13137
13422
  });
13138
- deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant }, durationUs);
13423
+ deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant: observedTenant }, durationUs);
13139
13424
  deps.logger.info({
13140
13425
  event: "request",
13141
- tenant,
13426
+ tenant: observedTenant,
13142
13427
  method,
13143
13428
  path: matchPath,
13144
13429
  status: response.status,
@@ -13187,9 +13472,8 @@ async function dispatch(ctx, deps) {
13187
13472
  });
13188
13473
  return response;
13189
13474
  }
13190
- async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps) {
13475
+ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, body) {
13191
13476
  const url = new URL(ctx.req.url);
13192
- const body = await safeParseBody(ctx);
13193
13477
  const req = {
13194
13478
  query: new Map(Array.from(url.searchParams)),
13195
13479
  headers: new Map(Array.from(ctx.req.raw.headers).map(([k2, v3]) => [k2.toLowerCase(), v3])),
@@ -13301,7 +13585,8 @@ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap,
13301
13585
  case "passthrough":
13302
13586
  response = await renderPassThrough(hit.entry, ctx, {
13303
13587
  allowPrivateUpstreams: tenantSnap.allowPrivateUpstreams,
13304
- logger: deps.logger
13588
+ logger: deps.logger,
13589
+ maxBodyBytes: tenantSnap.limits.maxBodyBytes
13305
13590
  });
13306
13591
  break;
13307
13592
  }
@@ -13319,20 +13604,27 @@ function notFoundUnknownTenant(tenant, method, path) {
13319
13604
  headers: { "content-type": "application/json" }
13320
13605
  });
13321
13606
  }
13322
- async function safeParseBody(ctx) {
13607
+ async function safeParseBody(ctx, maxBodyBytes) {
13323
13608
  const method = ctx.req.method;
13324
13609
  if (method === "GET" || method === "HEAD")
13325
- return null;
13610
+ return { ok: true, body: null };
13326
13611
  const contentType = ctx.req.header("content-type") ?? "";
13327
13612
  if (!contentType.includes("json"))
13328
- return null;
13613
+ return { ok: true, body: null };
13614
+ const { tooLarge } = capRequestBodyStream(ctx, maxBodyBytes);
13329
13615
  try {
13330
13616
  const text = await ctx.req.text();
13331
13617
  if (text.length === 0)
13332
- return null;
13333
- return JSON.parse(text);
13334
- } catch {
13335
- return null;
13618
+ return { ok: true, body: null };
13619
+ try {
13620
+ return { ok: true, body: JSON.parse(text) };
13621
+ } catch {
13622
+ return { ok: true, body: null };
13623
+ }
13624
+ } catch (err) {
13625
+ if (tooLarge())
13626
+ return { ok: false };
13627
+ throw err;
13336
13628
  }
13337
13629
  }
13338
13630
  function createRequestIdGenerator(deterministic) {
@@ -13384,6 +13676,7 @@ async function launch(opts) {
13384
13676
  holder,
13385
13677
  async stop() {
13386
13678
  watcher?.stop();
13679
+ server.stopWebhooks();
13387
13680
  server.uninstallCrashHandlers();
13388
13681
  }
13389
13682
  };
@@ -13900,10 +14193,10 @@ function convertOpenApi(doc, opts = {}) {
13900
14193
  if (!doc || typeof doc !== "object") {
13901
14194
  throw new OpenApiImportError("OpenAPI document root must be an object");
13902
14195
  }
13903
- const refs = findRefs(doc);
13904
- for (const ref of refs) {
14196
+ const refs = findRefs(doc, "$");
14197
+ for (const { ref, path } of refs) {
13905
14198
  if (!ref.startsWith("#")) {
13906
- throw new OpenApiImportError(`External $ref rejected: '${ref}'. Only in-document ($ref starting with '#') references are permitted.`, { ref });
14199
+ throw new OpenApiImportError(`External $ref rejected: '${ref}' at ${path}. Only in-document ($ref starting with '#') references are permitted.`, { ref, path });
13907
14200
  }
13908
14201
  }
13909
14202
  const openapi = doc;
@@ -13950,18 +14243,39 @@ function convertOpenApi(doc, opts = {}) {
13950
14243
  }
13951
14244
  return entries;
13952
14245
  }
13953
- function findRefs(value, acc = []) {
14246
+ function findRefs(value, path, acc = []) {
13954
14247
  if (value === null || typeof value !== "object")
13955
14248
  return acc;
13956
14249
  if (Array.isArray(value)) {
13957
- for (const v3 of value)
13958
- findRefs(v3, acc);
14250
+ value.forEach((v3, i2) => findRefs(v3, `${path}[${i2}]`, acc));
13959
14251
  return acc;
13960
14252
  }
13961
- for (const [k2, v3] of Object.entries(value)) {
13962
- if (k2 === "$ref" && typeof v3 === "string")
13963
- acc.push(v3);
13964
- findRefs(v3, acc);
14253
+ const obj = value;
14254
+ for (const [k2, v3] of Object.entries(obj)) {
14255
+ if (k2 === "$ref" && typeof v3 === "string") {
14256
+ acc.push({ ref: v3, path: `${path}.$ref` });
14257
+ continue;
14258
+ }
14259
+ if (k2 === "example")
14260
+ continue;
14261
+ if (k2 === "examples" && v3 !== null && typeof v3 === "object" && !Array.isArray(v3)) {
14262
+ for (const [name, member] of Object.entries(v3)) {
14263
+ const memberPath = `${path}.examples.${name}`;
14264
+ if (member === null || typeof member !== "object" || Array.isArray(member))
14265
+ continue;
14266
+ for (const [mk, mv] of Object.entries(member)) {
14267
+ if (mk === "value")
14268
+ continue;
14269
+ if (mk === "$ref" && typeof mv === "string") {
14270
+ acc.push({ ref: mv, path: `${memberPath}.$ref` });
14271
+ continue;
14272
+ }
14273
+ findRefs(mv, `${memberPath}.${mk}`, acc);
14274
+ }
14275
+ }
14276
+ continue;
14277
+ }
14278
+ findRefs(v3, `${path}.${k2}`, acc);
13965
14279
  }
13966
14280
  return acc;
13967
14281
  }
@@ -13969,7 +14283,7 @@ function pickExemplar(op, doc) {
13969
14283
  const responses = op.responses ?? {};
13970
14284
  const preferred = ["200", "201", "202", "204", "default"];
13971
14285
  for (const code of preferred) {
13972
- const res = responses[code];
14286
+ const res = responses[code] ?? (code === "default" ? undefined : responses[`${code[0]}XX`]);
13973
14287
  if (!res)
13974
14288
  continue;
13975
14289
  const status = code === "default" ? 200 : Number.parseInt(code, 10);
@@ -14669,7 +14983,7 @@ init_port_bind();
14669
14983
  // src/features/proxy/install-journal.ts
14670
14984
  init_types();
14671
14985
  import { createHash } from "crypto";
14672
- import { appendFile as appendFile2, mkdir as mkdir3, readFile as readFile8, rm as rm2, stat as stat4 } from "fs/promises";
14986
+ import { appendFile as appendFile2, mkdir as mkdir3, readFile as readFile8, rm as rm3, stat as stat4 } from "fs/promises";
14673
14987
  import { dirname as dirname2 } from "path";
14674
14988
  async function appendStep(path, step) {
14675
14989
  await mkdir3(dirname2(path), { recursive: true });
@@ -14688,7 +15002,7 @@ async function appendStep(path, step) {
14688
15002
  action: full.action,
14689
15003
  reverseCommand: full.reverseCommand
14690
15004
  });
14691
- const withChecksum = { ...full, checksum: sha256(payload) };
15005
+ const withChecksum = { ...full, checksum: sha2562(payload) };
14692
15006
  const line = `${JSON.stringify(withChecksum)}
14693
15007
  `;
14694
15008
  await appendFile2(path, line, { encoding: "utf8" });
@@ -14706,7 +15020,7 @@ async function* reverseSteps(path) {
14706
15020
  }
14707
15021
  }
14708
15022
  async function clearJournal(path) {
14709
- await rm2(path, { force: true });
15023
+ await rm3(path, { force: true });
14710
15024
  }
14711
15025
  async function journalFacts(path) {
14712
15026
  let exists = false;
@@ -14775,10 +15089,10 @@ var reverseCommandImpls = {
14775
15089
  });
14776
15090
  },
14777
15091
  remove_file: async ({ path }) => {
14778
- await rm2(path, { force: true });
15092
+ await rm3(path, { force: true });
14779
15093
  },
14780
15094
  remove_dir: async ({ path }) => {
14781
- await rm2(path, { recursive: true, force: true });
15095
+ await rm3(path, { recursive: true, force: true });
14782
15096
  },
14783
15097
  revert_file: async ({ path, originalContent }) => {
14784
15098
  const { writeFile: writeFile7 } = await import("fs/promises");
@@ -14803,7 +15117,7 @@ var reverseCommandImpls = {
14803
15117
  await runPrivileged2(["launchctl", "unload", "-w", plistPath]).catch(() => {
14804
15118
  return;
14805
15119
  });
14806
- await rm2(plistPath, { force: true });
15120
+ await rm3(plistPath, { force: true });
14807
15121
  },
14808
15122
  noop: async () => {}
14809
15123
  };
@@ -14825,7 +15139,7 @@ async function readAll(path) {
14825
15139
  action: parsed.action,
14826
15140
  reverseCommand: parsed.reverseCommand
14827
15141
  });
14828
- const expected = sha256(payload);
15142
+ const expected = sha2562(payload);
14829
15143
  if (expected !== parsed.checksum) {
14830
15144
  throw new ProxyError(`Install journal corruption: checksum mismatch at step ${parsed.step}`, "journal_checksum_mismatch", "Manual recovery: see docs/PROXY-RECOVERY.md");
14831
15145
  }
@@ -14833,7 +15147,7 @@ async function readAll(path) {
14833
15147
  }
14834
15148
  return out;
14835
15149
  }
14836
- function sha256(s2) {
15150
+ function sha2562(s2) {
14837
15151
  return createHash("sha256").update(s2, "utf8").digest("hex");
14838
15152
  }
14839
15153
 
@@ -14842,6 +15156,7 @@ init_dns();
14842
15156
  init_types();
14843
15157
 
14844
15158
  // src/features/proxy/cli.ts
15159
+ init_types();
14845
15160
  async function dispatchProxyCommand(argv) {
14846
15161
  const [sub, ...rest] = argv;
14847
15162
  if (!sub || sub === "--help" || sub === "help") {
@@ -14914,9 +15229,23 @@ async function install(argv) {
14914
15229
  }
14915
15230
  });
14916
15231
  mutations.push(...await buildDnsMutations(config));
14917
- mutations.push(portBindMutation({
14918
- binaryPath: process.argv[0] ?? "/usr/bin/env"
14919
- }));
15232
+ try {
15233
+ mutations.push(portBindMutation({
15234
+ binaryPath: process.execPath,
15235
+ allowInterpreter: resolveAllowInterpreterGrant(argv, process.env)
15236
+ }));
15237
+ } catch (err) {
15238
+ if (err instanceof ProxyError) {
15239
+ process.stderr.write(`
15240
+ ${err.message}
15241
+ `);
15242
+ if (err.hint)
15243
+ process.stderr.write(`${err.hint}
15244
+ `);
15245
+ return 1;
15246
+ }
15247
+ throw err;
15248
+ }
14920
15249
  try {
14921
15250
  const { applied } = await atomicInstall(journalPath, mutations, {
14922
15251
  onStep: (step) => process.stdout.write(` [${step.step}] ${step.action}
@@ -15056,6 +15385,9 @@ function defaultConfigPath() {
15056
15385
  function defaultJournalPath() {
15057
15386
  return join7(homedir(), ".mockstar", "install-state.json");
15058
15387
  }
15388
+ function resolveAllowInterpreterGrant(argv, env) {
15389
+ return argv.includes(ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG) || env[ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV] === "1";
15390
+ }
15059
15391
  function pickFlag(args, name) {
15060
15392
  const prefixed = args.find((a2) => a2.startsWith(`${name}=`));
15061
15393
  if (prefixed)
@@ -15085,6 +15417,13 @@ function proxyHelp() {
15085
15417
  "Subcommands:",
15086
15418
  " install Install local CA + DNS + port-443 capability; journaled for clean uninstall.",
15087
15419
  " Flags: --force, --dns-mode=<dnsmasq|hosts>, --config=<path>",
15420
+ ` ${ALLOW_INTERPRETER_CAPABILITY_GRANT_FLAG}`,
15421
+ " Opt-in escape hatch for #39: grants the network-bind capability",
15422
+ " even when running from source (bun) instead of a packaged binary.",
15423
+ " Grants EVERY program run by that interpreter the ability to bind",
15424
+ " privileged ports \u2014 only use on a single-purpose, ephemeral host",
15425
+ " (CI runner, throwaway VM/container), never on a dev machine. Env:",
15426
+ ` ${ALLOW_INTERPRETER_CAPABILITY_GRANT_ENV}=1 (for CI steps / Dockerfiles).`,
15088
15427
  " uninstall Reverse every journaled install mutation (LIFO).",
15089
15428
  " start Run the HTTPS proxy (requires prior install).",
15090
15429
  " Flags: --config=<path>",
@@ -15102,7 +15441,7 @@ function proxyHelp() {
15102
15441
  }
15103
15442
 
15104
15443
  // src/version.ts
15105
- var MOCKSTAR_VERSION = "0.3.0";
15444
+ var MOCKSTAR_VERSION = "0.4.1";
15106
15445
 
15107
15446
  // src/cli.ts
15108
15447
  function parseArgs(argv) {