@noy4/docserve 0.3.4 → 0.3.5

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 (61) hide show
  1. package/bin.mjs +8 -213
  2. package/dist/gallery/assets/index-CGV64tuk.css +1 -0
  3. package/dist/gallery/assets/index-Cf8Uf0vA.js +10 -0
  4. package/dist/gallery/assets/index-Cf8Uf0vA.js.map +1 -0
  5. package/dist/gallery/index.html +15 -0
  6. package/dist/node/cli.mjs +4095 -0
  7. package/dist/node/cli.mjs.map +7 -0
  8. package/dist/widget/index.js +730 -495
  9. package/package.json +14 -4
  10. package/src/node/cli.mjs +155 -0
  11. package/src/node/{files.mjs → docs/files.mjs} +1 -1
  12. package/src/node/{inject.mjs → docs/inject.mjs} +1 -1
  13. package/src/node/{meta.mjs → docs/meta.mjs} +1 -1
  14. package/src/node/http/app.mjs +20 -0
  15. package/src/node/{assets.mjs → http/assets.mjs} +3 -2
  16. package/src/node/http/gallery.mjs +45 -0
  17. package/src/node/http/response.mjs +31 -0
  18. package/src/node/http/routes.mjs +59 -0
  19. package/src/node/{serve-static.mjs → http/serve-static.mjs} +1 -1
  20. package/src/node/{server.mjs → http/server.mjs} +10 -10
  21. package/src/node/{state.mjs → instances/state.mjs} +9 -5
  22. package/src/node/instances/view.mjs +19 -0
  23. package/src/node/{watch.mjs → live/watch.mjs} +1 -1
  24. package/src/node/paths.mjs +10 -0
  25. package/src/node/rpc/files.mjs +5 -0
  26. package/src/node/rpc/index.mjs +39 -0
  27. package/src/node/rpc/route.mjs +34 -0
  28. package/src/node/rpc/servers.mjs +16 -0
  29. package/src/plugins/servers/client.js +77 -0
  30. package/src/plugins/servers/commands.ts +30 -0
  31. package/src/plugins/servers/model.ts +106 -0
  32. package/src/plugins/servers/servers.css +144 -0
  33. package/src/plugins/servers/ui/ServersPopover.tsx +71 -0
  34. package/src/plugins/sidebar/ui/PageList.tsx +1 -1
  35. package/src/plugins/sidebar/ui/RadioMenu.tsx +1 -1
  36. package/src/plugins/sidebar/ui/Sidebar.tsx +3 -3
  37. package/src/plugins/sidebar/ui/TreeList.tsx +10 -3
  38. package/src/{plugins/sidebar/ui → shared/client}/preview-model.ts +18 -4
  39. package/src/{plugins/sidebar/ui/useModel.ts → shared/client/use-model.ts} +1 -8
  40. package/src/shared/types.d.ts +17 -1
  41. package/src/widget/{pages.js → api/pages.js} +4 -7
  42. package/src/widget/api/rpc-client.js +25 -0
  43. package/src/widget/api/servers.js +46 -0
  44. package/src/widget/host.js +10 -8
  45. package/src/widget/index.js +2 -0
  46. package/src/widget/{docks.js → shell/docks.js} +2 -2
  47. package/src/widget/{palette.js → shell/palette.js} +3 -3
  48. package/src/widget/{placement.js → shell/placement.js} +1 -1
  49. package/src/widget/{ui.js → shell/ui.js} +1 -1
  50. package/index.html +0 -365
  51. package/src/node/adapter.mjs +0 -67
  52. package/src/node/gallery.mjs +0 -33
  53. package/src/node/routes.mjs +0 -105
  54. /package/src/node/{dates.mjs → docs/dates.mjs} +0 -0
  55. /package/src/node/{docs-info.mjs → docs/info.mjs} +0 -0
  56. /package/src/node/{scan.mjs → docs/scan.mjs} +0 -0
  57. /package/src/node/{websocket.mjs → live/websocket.mjs} +0 -0
  58. /package/src/widget/{live.js → api/live.js} +0 -0
  59. /package/src/widget/{rpc.js → api/rpc.js} +0 -0
  60. /package/src/widget/{palette.css → shell/palette.css} +0 -0
  61. /package/src/widget/{styles.js → shell/styles.js} +0 -0
@@ -0,0 +1,4095 @@
1
+ // src/node/cli.mjs
2
+ import { execFile as execFile2, spawn } from "node:child_process";
3
+ import fs2 from "node:fs";
4
+ import path2 from "node:path";
5
+
6
+ // ../node_modules/.pnpm/cac@7.1.0/node_modules/cac/dist/index.js
7
+ function toArr(any) {
8
+ return any == null ? [] : Array.isArray(any) ? any : [any];
9
+ }
10
+ function toVal(out, key, val, opts) {
11
+ var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
12
+ out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
13
+ }
14
+ function lib_default(args, opts) {
15
+ args = args || [];
16
+ opts = opts || {};
17
+ var k, arr, arg, name, val, out = { _: [] };
18
+ var i = 0, j = 0, idx = 0, len = args.length;
19
+ const alibi = opts.alias !== void 0;
20
+ const strict = opts.unknown !== void 0;
21
+ const defaults = opts.default !== void 0;
22
+ opts.alias = opts.alias || {};
23
+ opts.string = toArr(opts.string);
24
+ opts.boolean = toArr(opts.boolean);
25
+ if (alibi) for (k in opts.alias) {
26
+ arr = opts.alias[k] = toArr(opts.alias[k]);
27
+ for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
28
+ }
29
+ for (i = opts.boolean.length; i-- > 0; ) {
30
+ arr = opts.alias[opts.boolean[i]] || [];
31
+ for (j = arr.length; j-- > 0; ) opts.boolean.push(arr[j]);
32
+ }
33
+ for (i = opts.string.length; i-- > 0; ) {
34
+ arr = opts.alias[opts.string[i]] || [];
35
+ for (j = arr.length; j-- > 0; ) opts.string.push(arr[j]);
36
+ }
37
+ if (defaults) for (k in opts.default) {
38
+ name = typeof opts.default[k];
39
+ arr = opts.alias[k] = opts.alias[k] || [];
40
+ if (opts[name] !== void 0) {
41
+ opts[name].push(k);
42
+ for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
43
+ }
44
+ }
45
+ const keys = strict ? Object.keys(opts.alias) : [];
46
+ for (i = 0; i < len; i++) {
47
+ arg = args[i];
48
+ if (arg === "--") {
49
+ out._ = out._.concat(args.slice(++i));
50
+ break;
51
+ }
52
+ for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
53
+ if (j === 0) out._.push(arg);
54
+ else if (arg.substring(j, j + 3) === "no-") {
55
+ name = arg.substring(j + 3);
56
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
57
+ out[name] = false;
58
+ } else {
59
+ for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
60
+ name = arg.substring(j, idx);
61
+ val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
62
+ arr = j === 2 ? [name] : name;
63
+ for (idx = 0; idx < arr.length; idx++) {
64
+ name = arr[idx];
65
+ if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
66
+ toVal(out, name, idx + 1 < arr.length || val, opts);
67
+ }
68
+ }
69
+ }
70
+ if (defaults) {
71
+ for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
72
+ }
73
+ if (alibi) for (k in out) {
74
+ arr = opts.alias[k] || [];
75
+ while (arr.length > 0) out[arr.shift()] = out[k];
76
+ }
77
+ return out;
78
+ }
79
+ function removeBrackets(v) {
80
+ return v.replace(/[<[].+/, "").trim();
81
+ }
82
+ function findAllBrackets(v) {
83
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
84
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
85
+ const res = [];
86
+ const parse = (match) => {
87
+ let variadic = false;
88
+ let value = match[1];
89
+ if (value.startsWith("...")) {
90
+ value = value.slice(3);
91
+ variadic = true;
92
+ }
93
+ return {
94
+ required: match[0].startsWith("<"),
95
+ value,
96
+ variadic
97
+ };
98
+ };
99
+ let angledMatch;
100
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
101
+ let squareMatch;
102
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
103
+ return res;
104
+ }
105
+ function getMriOptions(options) {
106
+ const result = {
107
+ alias: /* @__PURE__ */ Object.create(null),
108
+ boolean: []
109
+ };
110
+ for (const [index, option] of options.entries()) {
111
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
112
+ if (option.isBoolean) {
113
+ if (option.negated) {
114
+ if (!options.some((o, i) => {
115
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
116
+ })) result.boolean.push(option.names[0]);
117
+ } else result.boolean.push(option.names[0]);
118
+ }
119
+ }
120
+ return result;
121
+ }
122
+ function findLongest(arr) {
123
+ return arr.sort((a, b) => b.length - a.length)[0];
124
+ }
125
+ function padRight(str, length) {
126
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
127
+ }
128
+ function camelcase(input) {
129
+ return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
130
+ return p1 + p2.toUpperCase();
131
+ });
132
+ }
133
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set([
134
+ "__proto__",
135
+ "constructor",
136
+ "prototype"
137
+ ]);
138
+ function setDotProp(obj, keys, val) {
139
+ if (keys.some((key) => UNSAFE_KEYS.has(key))) return;
140
+ let current = obj;
141
+ for (let i = 0; i < keys.length; i++) {
142
+ const key = keys[i];
143
+ if (i === keys.length - 1) {
144
+ current[key] = val;
145
+ return;
146
+ }
147
+ if (current[key] == null) {
148
+ const nextKeyIsArrayIndex = +keys[i + 1] > -1;
149
+ current[key] = nextKeyIsArrayIndex ? [] : {};
150
+ }
151
+ current = current[key];
152
+ }
153
+ }
154
+ function setByType(obj, transforms) {
155
+ for (const [key, transform] of Object.entries(transforms)) if (transform.shouldTransform && key in obj) {
156
+ obj[key] = [obj[key]].flat();
157
+ if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
158
+ }
159
+ }
160
+ function getFileName(input) {
161
+ const m = /([^\\/]+)$/.exec(input);
162
+ return m ? m[1] : "";
163
+ }
164
+ function camelcaseOptionName(name) {
165
+ return name.split(".").map((v, i) => {
166
+ return i === 0 ? camelcase(v) : v;
167
+ }).join(".");
168
+ }
169
+ var CACError = class extends Error {
170
+ constructor(message) {
171
+ super(message);
172
+ this.name = "CACError";
173
+ if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
174
+ }
175
+ };
176
+ var Option = class {
177
+ rawName;
178
+ description;
179
+ /** Option name */
180
+ name;
181
+ /** Option name and aliases */
182
+ names;
183
+ isBoolean;
184
+ required;
185
+ config;
186
+ negated;
187
+ constructor(rawName, description, config) {
188
+ this.rawName = rawName;
189
+ this.description = description;
190
+ this.config = Object.assign({}, config);
191
+ rawName = rawName.replaceAll(".*", "");
192
+ this.negated = false;
193
+ this.names = removeBrackets(rawName).split(",").map((v) => {
194
+ let name = v.trim().replace(/^-{1,2}/, "");
195
+ if (name.startsWith("no-")) {
196
+ this.negated = true;
197
+ name = name.replace(/^no-/, "");
198
+ }
199
+ return camelcaseOptionName(name);
200
+ }).sort((a, b) => a.length - b.length);
201
+ this.name = this.names.at(-1);
202
+ if (this.negated && this.config.default == null) this.config.default = true;
203
+ if (rawName.includes("<")) this.required = true;
204
+ else if (rawName.includes("[")) this.required = false;
205
+ else this.isBoolean = true;
206
+ }
207
+ };
208
+ var runtimeInfo;
209
+ if (typeof process !== "undefined") {
210
+ let runtimeName;
211
+ if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
212
+ else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
213
+ else runtimeName = "node";
214
+ runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
215
+ } else if (typeof navigator === "undefined") runtimeInfo = `unknown`;
216
+ else runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
217
+ function getRuntimeProcessArgs() {
218
+ return typeof process === "undefined" ? void 0 : process.argv;
219
+ }
220
+ var Command = class {
221
+ rawName;
222
+ description;
223
+ config;
224
+ cli;
225
+ options;
226
+ aliasNames;
227
+ name;
228
+ args;
229
+ commandAction;
230
+ usageText;
231
+ versionNumber;
232
+ examples;
233
+ helpCallback;
234
+ globalCommand;
235
+ constructor(rawName, description, config = {}, cli) {
236
+ this.rawName = rawName;
237
+ this.description = description;
238
+ this.config = config;
239
+ this.cli = cli;
240
+ this.options = [];
241
+ this.aliasNames = [];
242
+ this.name = removeBrackets(rawName);
243
+ this.args = findAllBrackets(rawName);
244
+ this.examples = [];
245
+ }
246
+ usage(text2) {
247
+ this.usageText = text2;
248
+ return this;
249
+ }
250
+ allowUnknownOptions() {
251
+ this.config.allowUnknownOptions = true;
252
+ return this;
253
+ }
254
+ ignoreOptionDefaultValue() {
255
+ this.config.ignoreOptionDefaultValue = true;
256
+ return this;
257
+ }
258
+ version(version, customFlags = "-v, --version") {
259
+ this.versionNumber = version;
260
+ this.option(customFlags, "Display version number");
261
+ return this;
262
+ }
263
+ example(example) {
264
+ this.examples.push(example);
265
+ return this;
266
+ }
267
+ /**
268
+ * Add a option for this command
269
+ * @param rawName Raw option name(s)
270
+ * @param description Option description
271
+ * @param config Option config
272
+ */
273
+ option(rawName, description, config) {
274
+ const option = new Option(rawName, description, config);
275
+ this.options.push(option);
276
+ return this;
277
+ }
278
+ alias(name) {
279
+ this.aliasNames.push(name);
280
+ return this;
281
+ }
282
+ action(callback) {
283
+ this.commandAction = callback;
284
+ return this;
285
+ }
286
+ /**
287
+ * Check if a command name is matched by this command
288
+ * @param name Command name
289
+ */
290
+ isMatched(name) {
291
+ return this.name === name || this.aliasNames.includes(name);
292
+ }
293
+ get isDefaultCommand() {
294
+ return this.name === "" || this.aliasNames.includes("!");
295
+ }
296
+ get isGlobalCommand() {
297
+ return this instanceof GlobalCommand;
298
+ }
299
+ /**
300
+ * Check if an option is registered in this command
301
+ * @param name Option name
302
+ */
303
+ hasOption(name) {
304
+ name = name.split(".", 1)[0];
305
+ return this.options.find((option) => {
306
+ return option.names.includes(name);
307
+ });
308
+ }
309
+ outputHelp() {
310
+ const { name, commands } = this.cli;
311
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
312
+ let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
313
+ sections.push({
314
+ title: "Usage",
315
+ body: ` $ ${name} ${this.usageText || this.rawName}`
316
+ });
317
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
318
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
319
+ sections.push({
320
+ title: "Commands",
321
+ body: commands.map((command) => {
322
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
323
+ }).join("\n")
324
+ }, {
325
+ title: `For more info, run any command with the \`--help\` flag`,
326
+ body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
327
+ });
328
+ }
329
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
330
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
331
+ if (options.length > 0) {
332
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
333
+ sections.push({
334
+ title: "Options",
335
+ body: options.map((option) => {
336
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
337
+ }).join("\n")
338
+ });
339
+ }
340
+ if (this.examples.length > 0) sections.push({
341
+ title: "Examples",
342
+ body: this.examples.map((example) => {
343
+ if (typeof example === "function") return example(name);
344
+ return example;
345
+ }).join("\n")
346
+ });
347
+ if (helpCallback) sections = helpCallback(sections) || sections;
348
+ console.info(sections.map((section) => {
349
+ return section.title ? `${section.title}:
350
+ ${section.body}` : section.body;
351
+ }).join("\n\n"));
352
+ }
353
+ outputVersion() {
354
+ const { name } = this.cli;
355
+ const { versionNumber } = this.cli.globalCommand;
356
+ if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
357
+ }
358
+ checkRequiredArgs() {
359
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
360
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
361
+ }
362
+ /**
363
+ * Check if the parsed options contain any unknown options
364
+ *
365
+ * Exit and output error when true
366
+ */
367
+ checkUnknownOptions() {
368
+ const { options, globalCommand } = this.cli;
369
+ if (!this.config.allowUnknownOptions) {
370
+ for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
371
+ }
372
+ }
373
+ /**
374
+ * Check if the required string-type options exist
375
+ */
376
+ checkOptionValue() {
377
+ const { options: parsedOptions, globalCommand } = this.cli;
378
+ const options = [...globalCommand.options, ...this.options];
379
+ for (const option of options) {
380
+ const value = parsedOptions[option.name.split(".", 1)[0]];
381
+ if (option.required) {
382
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
383
+ if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
384
+ }
385
+ }
386
+ }
387
+ /**
388
+ * Check if the number of args is more than expected
389
+ */
390
+ checkUnusedArgs() {
391
+ const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
392
+ if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
393
+ }
394
+ };
395
+ var GlobalCommand = class extends Command {
396
+ constructor(cli) {
397
+ super("@@global@@", "", {}, cli);
398
+ }
399
+ };
400
+ var CAC = class extends EventTarget {
401
+ /** The program name to display in help and version message */
402
+ name;
403
+ commands;
404
+ globalCommand;
405
+ matchedCommand;
406
+ matchedCommandName;
407
+ /**
408
+ * Raw CLI arguments
409
+ */
410
+ rawArgs;
411
+ /**
412
+ * Parsed CLI arguments
413
+ */
414
+ args;
415
+ /**
416
+ * Parsed CLI options, camelCased
417
+ */
418
+ options;
419
+ showHelpOnExit;
420
+ showVersionOnExit;
421
+ /**
422
+ * @param name The program name to display in help and version message
423
+ */
424
+ constructor(name = "") {
425
+ super();
426
+ this.name = name;
427
+ this.commands = [];
428
+ this.rawArgs = [];
429
+ this.args = [];
430
+ this.options = {};
431
+ this.globalCommand = new GlobalCommand(this);
432
+ this.globalCommand.usage("<command> [options]");
433
+ }
434
+ /**
435
+ * Add a global usage text.
436
+ *
437
+ * This is not used by sub-commands.
438
+ */
439
+ usage(text2) {
440
+ this.globalCommand.usage(text2);
441
+ return this;
442
+ }
443
+ /**
444
+ * Add a sub-command
445
+ */
446
+ command(rawName, description, config) {
447
+ const command = new Command(rawName, description || "", config, this);
448
+ command.globalCommand = this.globalCommand;
449
+ this.commands.push(command);
450
+ return command;
451
+ }
452
+ /**
453
+ * Add a global CLI option.
454
+ *
455
+ * Which is also applied to sub-commands.
456
+ */
457
+ option(rawName, description, config) {
458
+ this.globalCommand.option(rawName, description, config);
459
+ return this;
460
+ }
461
+ /**
462
+ * Show help message when `-h, --help` flags appear.
463
+ *
464
+ */
465
+ help(callback) {
466
+ this.globalCommand.option("-h, --help", "Display this message");
467
+ this.globalCommand.helpCallback = callback;
468
+ this.showHelpOnExit = true;
469
+ return this;
470
+ }
471
+ /**
472
+ * Show version number when `-v, --version` flags appear.
473
+ *
474
+ */
475
+ version(version, customFlags = "-v, --version") {
476
+ this.globalCommand.version(version, customFlags);
477
+ this.showVersionOnExit = true;
478
+ return this;
479
+ }
480
+ /**
481
+ * Add a global example.
482
+ *
483
+ * This example added here will not be used by sub-commands.
484
+ */
485
+ example(example) {
486
+ this.globalCommand.example(example);
487
+ return this;
488
+ }
489
+ /**
490
+ * Output the corresponding help message
491
+ * When a sub-command is matched, output the help message for the command
492
+ * Otherwise output the global one.
493
+ *
494
+ */
495
+ outputHelp() {
496
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
497
+ else this.globalCommand.outputHelp();
498
+ }
499
+ /**
500
+ * Output the version number.
501
+ *
502
+ */
503
+ outputVersion() {
504
+ this.globalCommand.outputVersion();
505
+ }
506
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
507
+ this.args = args;
508
+ this.options = options;
509
+ if (matchedCommand) this.matchedCommand = matchedCommand;
510
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
511
+ return this;
512
+ }
513
+ unsetMatchedCommand() {
514
+ this.matchedCommand = void 0;
515
+ this.matchedCommandName = void 0;
516
+ }
517
+ /**
518
+ * Parse argv
519
+ */
520
+ parse(argv, { run: run2 = true } = {}) {
521
+ if (!argv) {
522
+ const runtimeProcessArgs = getRuntimeProcessArgs();
523
+ if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
524
+ argv = runtimeProcessArgs;
525
+ }
526
+ this.rawArgs = argv;
527
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
528
+ let shouldParse = true;
529
+ for (const command of this.commands) {
530
+ const parsed = this.mri(argv.slice(2), command);
531
+ const commandName = parsed.args[0];
532
+ if (command.isMatched(commandName)) {
533
+ shouldParse = false;
534
+ const parsedInfo = {
535
+ ...parsed,
536
+ args: parsed.args.slice(1)
537
+ };
538
+ this.setParsedInfo(parsedInfo, command, commandName);
539
+ this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
540
+ }
541
+ }
542
+ if (shouldParse) {
543
+ for (const command of this.commands) if (command.isDefaultCommand) {
544
+ shouldParse = false;
545
+ const parsed = this.mri(argv.slice(2), command);
546
+ this.setParsedInfo(parsed, command);
547
+ this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
548
+ }
549
+ }
550
+ if (shouldParse) {
551
+ const parsed = this.mri(argv.slice(2));
552
+ this.setParsedInfo(parsed);
553
+ }
554
+ if (this.options.help && this.showHelpOnExit) {
555
+ this.outputHelp();
556
+ run2 = false;
557
+ this.unsetMatchedCommand();
558
+ }
559
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
560
+ this.outputVersion();
561
+ run2 = false;
562
+ this.unsetMatchedCommand();
563
+ }
564
+ const parsedArgv = {
565
+ args: this.args,
566
+ options: this.options
567
+ };
568
+ if (run2) this.runMatchedCommand();
569
+ if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
570
+ return parsedArgv;
571
+ }
572
+ mri(argv, command) {
573
+ const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
574
+ const mriOptions = getMriOptions(cliOptions);
575
+ let argsAfterDoubleDashes = [];
576
+ const doubleDashesIndex = argv.indexOf("--");
577
+ if (doubleDashesIndex !== -1) {
578
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
579
+ argv = argv.slice(0, doubleDashesIndex);
580
+ }
581
+ let parsed = lib_default(argv, mriOptions);
582
+ parsed = Object.keys(parsed).reduce((res, name) => {
583
+ return {
584
+ ...res,
585
+ [camelcaseOptionName(name)]: parsed[name]
586
+ };
587
+ }, { _: [] });
588
+ const args = parsed._;
589
+ const options = { "--": argsAfterDoubleDashes };
590
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
591
+ const transforms = /* @__PURE__ */ Object.create(null);
592
+ for (const cliOption of cliOptions) {
593
+ if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
594
+ if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
595
+ transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
596
+ transforms[cliOption.name].shouldTransform = true;
597
+ transforms[cliOption.name].transformFunction = cliOption.config.type[0];
598
+ }
599
+ }
600
+ for (const [key, value] of Object.entries(parsed)) if (key !== "_") {
601
+ setDotProp(options, key.split("."), value);
602
+ setByType(options, transforms);
603
+ }
604
+ return {
605
+ args,
606
+ options
607
+ };
608
+ }
609
+ runMatchedCommand() {
610
+ const { args, options, matchedCommand: command } = this;
611
+ if (!command || !command.commandAction) return;
612
+ command.checkUnknownOptions();
613
+ command.checkOptionValue();
614
+ command.checkRequiredArgs();
615
+ command.checkUnusedArgs();
616
+ const actionArgs = [];
617
+ command.args.forEach((arg, index) => {
618
+ if (arg.variadic) actionArgs.push(args.slice(index));
619
+ else actionArgs.push(args[index]);
620
+ });
621
+ actionArgs.push(options);
622
+ return command.commandAction.apply(this, actionArgs);
623
+ }
624
+ };
625
+ var cac = (name = "") => new CAC(name);
626
+
627
+ // src/node/http/server.mjs
628
+ import { exec } from "node:child_process";
629
+ import { createServer } from "node:http";
630
+
631
+ // ../node_modules/.pnpm/rou3@1.0.0/node_modules/rou3/dist/index.mjs
632
+ var NullProtoObj = /* @__PURE__ */ (() => {
633
+ const e = function() {
634
+ };
635
+ return e.prototype = /* @__PURE__ */ Object.create(null), Object.freeze(e.prototype), e;
636
+ })();
637
+ function createRouter() {
638
+ return {
639
+ root: { key: "" },
640
+ static: new NullProtoObj()
641
+ };
642
+ }
643
+ var UNNAMED_GROUP_PREFIX = "__rou3_unnamed_";
644
+ var ESCAPED_GROUP_PREFIX = "__rou3_esc_";
645
+ function toUnnamedGroupKey(key) {
646
+ return typeof key === "string" ? toGroupName(key) : `${UNNAMED_GROUP_PREFIX}${key}`;
647
+ }
648
+ function toGroupName(name) {
649
+ return /^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(name) ? name : ESCAPED_GROUP_PREFIX + name.replace(/[_-]/g, (c) => c === "_" ? "__" : "_h");
650
+ }
651
+ function fromGroupName(key) {
652
+ if (key.charCodeAt(0) !== 95) return key;
653
+ if (key.startsWith("__rou3_esc_")) return key.slice(11).replace(/__|_h/g, (c) => c === "__" ? "_" : "-");
654
+ return key.startsWith("__rou3_unnamed_") ? key.slice(15) : key;
655
+ }
656
+ function emptyParam(m, segments) {
657
+ const pMap = m.paramsMap;
658
+ const params = pMap && getMatchParams(segments, pMap, m.suffix);
659
+ return !!pMap?.some(([, name, , empty]) => !empty && name > ":" && /(^|\/)(\/|$)/.test(params[name]));
660
+ }
661
+ function matchesZero(m) {
662
+ const last = m.paramsMap[m.paramsMap.length - 1];
663
+ return last[2] || !!last[3] && !last[5];
664
+ }
665
+ function normalizePath(path3) {
666
+ if (!path3.includes("/.")) return path3;
667
+ const r = [];
668
+ let s = "";
669
+ for (s of path3.split("/")) if (s === ".") continue;
670
+ else if (s === "..") {
671
+ if (r.length > 1) r.pop();
672
+ } else r.push(s);
673
+ if (s === "." || s === "..") r.push("");
674
+ return r.join("/") || "/";
675
+ }
676
+ function splitPath(path3) {
677
+ const s = path3.split("/");
678
+ s.shift();
679
+ return s;
680
+ }
681
+ function methodEntries(methods, method, reverse) {
682
+ let own = methods[method];
683
+ let any = method ? methods[""] : void 0;
684
+ if (reverse) {
685
+ own &&= own.slice().reverse();
686
+ any &&= any.slice().reverse();
687
+ }
688
+ return own && any ? any.concat(own) : own || any;
689
+ }
690
+ function reverseVariants(entries) {
691
+ let out;
692
+ for (let i = 0, j; i < entries.length; i = j) {
693
+ const token = entries[i].variants;
694
+ for (j = i + 1; token && entries[j]?.variants === token; j++) ;
695
+ if (j - i > 1) (out ??= entries.slice()).splice(i, j - i, ...entries.slice(i, j).reverse());
696
+ }
697
+ return out || entries;
698
+ }
699
+ function setParam(params, key, value, join6) {
700
+ params[key] = join6 && params[key] !== void 0 ? params[key] + "/" + value : value;
701
+ }
702
+ function getMatchParams(segments, paramsMap, suffix, slash) {
703
+ const params = new NullProtoObj();
704
+ const end = suffix ? segments.length - suffix[1] : segments.length;
705
+ for (const [index, name, optional, , , join6] of paramsMap) {
706
+ if (~index >= end && (optional || !slash)) continue;
707
+ const segment = index < 0 ? segments.slice(~index, end).join("/") : segments[suffix && index > suffix[0] ? index - suffix[0] - 1 + end : index];
708
+ if (typeof name === "string") {
709
+ setParam(params, name, segment, join6);
710
+ if (index < 0 && optional && !join6) params._ = segment;
711
+ } else {
712
+ const match = segment.match(name);
713
+ if (match) {
714
+ for (const key in match.groups) if (match.groups[key] !== void 0) setParam(params, fromGroupName(key), match.groups[key], join6);
715
+ }
716
+ }
717
+ }
718
+ return params;
719
+ }
720
+ function encodeEscapes(path3) {
721
+ if (!path3.includes("\\")) return path3;
722
+ return path3.replace(/\\([:(){}\\])/g, (_, c) => "\uFFFD" + ESCAPABLE.indexOf(c));
723
+ }
724
+ function decodeEscapes(segment, prefix) {
725
+ return segment.replace(/\uFFFD([0-5])/g, (_, i) => prefix + ESCAPABLE[i]);
726
+ }
727
+ var ESCAPABLE = ":(){}\\";
728
+ function segmentKey(segment) {
729
+ if (segment === "*" || segment.startsWith("**")) return 2;
730
+ if (segment.includes(":") || segment.includes("(") || segmentWildcards(segment).length > 0) return 1;
731
+ if (segment.includes("\\")) segment = segment.replace(/\\([\s\S])/g, "$1");
732
+ if (segment.includes("\uFFFD")) segment = decodeEscapes(segment, "");
733
+ return encodeLiteral(segment);
734
+ }
735
+ function encodeLiteral(text2) {
736
+ return /[\0- "#<>?^`{}\x7F-\uFFFC]/.test(text2) ? text2.replace(/[\0- "#<>?^`{}\x7F-\uFFFC]+/g, (run2) => encodeURIComponent(run2.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"))) : text2;
737
+ }
738
+ function checkConstraints(route) {
739
+ if (!/[\t\n\r\\({}\uFFFD-\uFFFF]/.test(route)) return;
740
+ if (/[\t\n\r\uFFFD-\uFFFF]/.test(route)) invalidSyntax("a tab, LF, CR (use %09, %0A, %0D) or U+FFFD-U+FFFF char", route);
741
+ let s = route.replace(/\\([^/])/g, (_, c) => c > "0" && c <= "9" ? "\0" : "_");
742
+ while (s !== (s = s.replace(/\([^()/]*\)/g, (group) => {
743
+ if (/[$^]|^\(\?<?[=!]/.test(group.replace(/\[[^\]]*\]/g, "")) || group.includes("\0")) invalidSyntax("an anchor, look-around, backreference or capturing group in a constraint", route);
744
+ if (classSetOp(group)) invalidSyntax("a `--` / `&&` in a class of a constraint", route);
745
+ return group[1] === "?" && group[2] !== "<" ? "" : "\0";
746
+ }))) ;
747
+ if (s.includes("(")) throw new Error(`rou3: a \`(\` must close in its own segment, escape a literal one as \`\\(\` (${route})`);
748
+ if (s.includes("\\")) invalidSyntax("a `\\` must escape a char of its segment", route);
749
+ if (/[{}]/.test(s.replace(/\{[^{}]*\}/g, ""))) invalidSyntax("unbalanced or nested `{}`", route);
750
+ }
751
+ function classSetOp(s) {
752
+ let found = false;
753
+ while (!found && /--|&&/.test(s) && s !== (s = s.replace(/\[[^[\]]*\]/g, (k) => {
754
+ found ||= /--|&&/.test(k);
755
+ return "_";
756
+ }))) ;
757
+ return found;
758
+ }
759
+ function starGroups(path3) {
760
+ if (!path3.includes("(.*)")) return [path3];
761
+ let count = 0;
762
+ let unnamed;
763
+ return [path3.replace(/\\[\s\S]|(:[A-Za-z_]\w*)?\((?!\?)(\.\*\)(?!\*))?/g, (m, name, star, at) => {
764
+ if (m[0] === "\\" || !star) {
765
+ if (m[0] === "(") count++;
766
+ return m;
767
+ }
768
+ if (name) {
769
+ const k = count;
770
+ unnamed = (index) => index === k ? name.slice(1) : index > k ? index - 1 : index;
771
+ } else count++;
772
+ return /(^|[^\\])(\\\\)*([)*}?]|:[A-Za-z_]\w*)\{?$/.test(path3.slice(0, at)) ? "\uFFFF*" : "*";
773
+ }), unnamed];
774
+ }
775
+ function absolutePattern(path3) {
776
+ return /^[/{]/.test(path3) ? path3 : `/${path3}`;
777
+ }
778
+ function dotSegments(path3) {
779
+ if (!DOT_SEGMENT.test(path3)) return path3;
780
+ const s = path3.split("/");
781
+ const out = [s[0]];
782
+ let dot = false;
783
+ for (let i = 1; i < s.length; i++) {
784
+ const m = /^(?:\.|%2e)(\.|%2e)?$/i.exec(s[i]);
785
+ if (m) {
786
+ if (m[1] && (out.length > 1 || out[0]) && !isText(out.pop())) invalidSyntax(DOT_SEGMENT_NEXT_TO, path3);
787
+ dot = true;
788
+ continue;
789
+ }
790
+ if (dot && /^[:*(]/.test(s[i])) invalidSyntax(DOT_SEGMENT_NEXT_TO, path3);
791
+ out.push(s[i]);
792
+ dot = false;
793
+ }
794
+ if (dot) out.push("");
795
+ return out.join("/");
796
+ }
797
+ var isText = (segment) => typeof segmentKey(segment = encodeEscapes(segment)) === "string" && !/[{}]|(^|[^\\])\?/.test(segment);
798
+ var DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?=\/|$)/i;
799
+ var DOT_SEGMENT_NEXT_TO = "`.` / `..` segment next to a param, catch-all or group";
800
+ function invalidSyntax(what, route) {
801
+ throw new Error(`rou3: ${what} (${route})`);
802
+ }
803
+ var MISPLACED_MODIFIER = "misplaced `?` / `+` / `*`: `?` follows `:name` or `:name(\u2026)`, `+` / `*` a whole-segment `:name`, none a catch-all (`(.*)` too); escape a literal one with `\\`";
804
+ var PARAM_MODIFIER = /^(.*)(:[A-Za-z_]\w*(?:\([^)]*\))?)([?+*])$/;
805
+ function expandModifiers(segments, input) {
806
+ for (let i = 0; i < segments.length; i++) {
807
+ const last = segments[i].charCodeAt(segments[i].length - 1);
808
+ if (last !== 63 && last !== 43 && last !== 42) continue;
809
+ const m = segments[i].match(PARAM_MODIFIER);
810
+ if (!m) continue;
811
+ const pre = segments.slice(0, i);
812
+ const suf = segments.slice(i + 1);
813
+ const without = "/" + pre.concat(m[1] || [], suf).join("/");
814
+ if (m[3] === "?" && m[1] !== "**") {
815
+ if (typeof segmentKey(m[1]) !== "string") continue;
816
+ return ["/" + pre.concat(m[1] + m[2], suf).join("/"), without];
817
+ }
818
+ if (m[1] || m[2].includes("(")) invalidSyntax(MISPLACED_MODIFIER, input);
819
+ const wc = "/" + pre.concat("**" + m[2], suf).join("/");
820
+ return m[3] === "+" ? [wc] : [wc, without];
821
+ }
822
+ }
823
+ function splitStar(segments, input) {
824
+ for (let i = 0; i < segments.length; i++) {
825
+ const segment = segments[i];
826
+ const at = segment.startsWith("**") || segment === "*" ? [] : segmentWildcards(segment);
827
+ if (at.length === 0) continue;
828
+ for (let j = i + 1; j < segments.length && at.length === 1; j++) if (!segments[j].startsWith("**") && segments[j] !== "*") at.push(...segmentWildcards(segments[j]));
829
+ if (at.length > 1) {
830
+ if (at.some((x, k) => at[k + 1] === x + 1)) invalidSyntax(MISPLACED_MODIFIER, input);
831
+ oneCatchAll(input);
832
+ }
833
+ const pre = segments.slice(0, i);
834
+ const post = segments.slice(i + 1);
835
+ const head = segment.slice(0, at[0]);
836
+ const tail = segment.slice(at[0] + 1);
837
+ if (!head) return [
838
+ [pre.concat("**", segment, post)],
839
+ i,
840
+ false
841
+ ];
842
+ if (!tail) return [
843
+ [pre.concat(segment, "**", post), segments],
844
+ i + 1,
845
+ true
846
+ ];
847
+ return [
848
+ [pre.concat(head + "*", "**", "*" + tail, post), segments],
849
+ i + 1,
850
+ true
851
+ ];
852
+ }
853
+ }
854
+ function oneCatchAll(input) {
855
+ throw new Error(`rou3: a route can have only one \`*\`, \`**\`, \`:name+\` or \`:name*\` (${input})`);
856
+ }
857
+ function splitRoute(path3) {
858
+ const s = splitPath(path3);
859
+ while (s[s.length - 1] === "") s.pop();
860
+ if (path3.includes("**")) {
861
+ for (let i = 0; i < s.length; i++) if (/^\*\*[^:{}]/.test(s[i])) s.splice(i, 1, ...s[i][2] === "*" ? ["**", s[i].slice(2)] : [s[i].slice(1)]);
862
+ }
863
+ return s;
864
+ }
865
+ function expandedRouteId(path3) {
866
+ if (path3.charCodeAt(0) !== 47) return `{${expandedRouteId(`/${path3}`)}`;
867
+ return "/" + splitRoute(encodeEscapes(path3)).map((segment) => {
868
+ const key = segmentKey(segment);
869
+ return typeof key === "string" ? key : segment;
870
+ }).join("/");
871
+ }
872
+ function addName(names, name, input) {
873
+ if (names.includes(name) || !/^[A-Za-z_]\w*$/.test(name)) invalidSyntax(`${names.includes(name) ? "duplicate" : "invalid"} param name "${decodeEscapes(name.replace(/\\(?=[\w$\x80-\ufffc])(?![^(]*\))/g, ""), "\\")}"`, input);
874
+ names.push(name);
875
+ return name;
876
+ }
877
+ function segmentWildcards(segment) {
878
+ const at = [];
879
+ let depth = 0;
880
+ for (let i = 0; i < segment.length; i++) {
881
+ const ch = segment.charCodeAt(i);
882
+ if (ch === 92) i++;
883
+ else if (ch === 40) depth++;
884
+ else if (ch === 41 && depth > 0) depth--;
885
+ else if (ch === 42 && depth === 0) at.push(i);
886
+ }
887
+ return at;
888
+ }
889
+ function scanFirstGroup(path3) {
890
+ let i = 0;
891
+ let depth = 0;
892
+ for (; i < path3.length; i++) {
893
+ const c = path3.charCodeAt(i);
894
+ if (c === 92) i++;
895
+ else if (c === 40) depth++;
896
+ else if (c === 41 && depth > 0) depth--;
897
+ else if (c === 123 && depth === 0) break;
898
+ }
899
+ if (i >= path3.length) return;
900
+ let j = i + 1;
901
+ depth = 0;
902
+ for (; j < path3.length; j++) {
903
+ const c = path3.charCodeAt(j);
904
+ if (c === 92) j++;
905
+ else if (c === 40) depth++;
906
+ else if (c === 41 && depth > 0) depth--;
907
+ else if (c === 125 && depth === 0) break;
908
+ }
909
+ if (j >= path3.length) return;
910
+ const mod = path3[j + 1];
911
+ const hasMod = mod === "?" || mod === "+" || mod === "*";
912
+ return [
913
+ path3.slice(0, i),
914
+ path3.slice(i + 1, j).replace(NAME_CHAR, "\\$&"),
915
+ path3.slice(j + (hasMod ? 2 : 1)).replace(NAME_CHAR, "\\$&"),
916
+ hasMod ? mod : void 0
917
+ ];
918
+ }
919
+ var NAME_CHAR = /^[\w$\x80-]/;
920
+ function expandGroupDelimiters(path3, input = path3) {
921
+ if (!path3.includes("{")) return;
922
+ const group = scanFirstGroup(path3);
923
+ if (!group) return;
924
+ const [pre, body, suf, mod] = group;
925
+ if (mod === "+" || mod === "*") invalidSyntax(`unsupported \`{}${mod}\``, input);
926
+ if (mod === "?" && /^(?!\*\*)./.test(pre.slice(pre.lastIndexOf("/") + 1)) && /^:[A-Za-z_]\w*(\([^)]*\))?$/.test(body) && (!suf || suf[0] === "/")) return [pre + body + "?" + suf];
927
+ const full = joinGroup(joinGroup(pre, body, input), suf, input);
928
+ const expanded = mod ? [full, joinGroup(pre, suf, input)] : [full];
929
+ if (expanded.some((e) => DOT_SEGMENT.test(e))) invalidSyntax(DOT_SEGMENT_NEXT_TO, input);
930
+ if (pre) return expanded;
931
+ if (mod && body.charCodeAt(0) === 47 && suf && !/^\{?\//.test(suf)) invalidSyntax("text after a leading `{/...}?`", input);
932
+ return expanded.map(absolutePattern);
933
+ }
934
+ function joinGroup(a, b, input) {
935
+ const m = /(?<!\\)(\\\\)*((?<!\*\*):\w+|\([^/]*[^\\]\)|\*)([(?+*\uFFFF])$/.exec(a + b[0]);
936
+ if (m) {
937
+ if (m[3] === "\uFFFF") return a + b;
938
+ if (m[3] > "(") invalidSyntax(MISPLACED_MODIFIER, input);
939
+ if (m[2] > "*") a += "([^\\x2f]+?)";
940
+ }
941
+ return a + (b.charCodeAt(0) === 65535 ? b.slice(1) : b);
942
+ }
943
+ function getParamRegexp(segment, unnamedStart, names, input, groupKey = toUnnamedGroupKey) {
944
+ let _i = unnamedStart;
945
+ let _o;
946
+ let _s = "", _d = 0, _e = -1, _g = 0, _r = 0;
947
+ const _c = [];
948
+ for (let j = 0; j < segment.length; j++) {
949
+ const c = segment.charCodeAt(j);
950
+ if (_d === 0) {
951
+ if (c === 65535) {
952
+ _s += "\uFFFF";
953
+ continue;
954
+ }
955
+ if (c === 58) _e = j + 1 + addName(names, /^[\w$\x80-\ufffc]*/.exec(segment.slice(j + 1))[0], input).length;
956
+ else if (c === 40 && /[?)]/.test(segment[j + 1])) invalidSyntax("empty or `(?` group", input);
957
+ else if (c === 63 || c === 43 || c === 42 && j === _e) {
958
+ if (c === 63 && j === segment.length - 1 && PARAM_MODIFIER.test(segment)) {
959
+ _s += "?";
960
+ _r--;
961
+ continue;
962
+ }
963
+ invalidSyntax(MISPLACED_MODIFIER, input);
964
+ } else if (c === 42) {
965
+ _e = j + 1;
966
+ _s += "([^/]*)";
967
+ _r--;
968
+ continue;
969
+ }
970
+ } else if (c === 58) {
971
+ _s += "\uFFFE:";
972
+ continue;
973
+ }
974
+ if (c === 40) {
975
+ if (_d++ === 0) _g = j;
976
+ } else if (c === 41 && _d > 0) {
977
+ if (--_d === 0) {
978
+ _e = j + 1;
979
+ const p = segment.slice(_g + 1, j);
980
+ if (p !== "[^\\x2f]+?") _c.push(p);
981
+ }
982
+ } else if (_d === 0 && c === 65533 && /[34]/.test(segment[j + 1])) {
983
+ _s += encodeLiteral("{}"[+segment[++j] - 3]);
984
+ _r += 768;
985
+ continue;
986
+ } else if (_d === 0 && /[\0- "#$).<>?[-^`{-}\x7F-\uFFFC]/.test(segment[j])) {
987
+ const esc = c === 92 && j + 1 < segment.length ? 1 : 0;
988
+ const ch = segment.slice(j + esc, j + esc + (segment.codePointAt(j + esc) > 65535 ? 2 : 1));
989
+ const encoded = encodeLiteral(ch);
990
+ j += esc + ch.length - 1;
991
+ _s += encoded !== ch ? encoded : esc && ch !== "*" ? "\uFFFE" + ch : "\\" + ch;
992
+ _r += encoded.length * 256;
993
+ continue;
994
+ }
995
+ if (_d === 0 && j >= _e && segment.charCodeAt(j - 1) !== 65533) _r += 256;
996
+ _s += segment[j];
997
+ }
998
+ const regex = decodeEscapes(_s.replace(/(?<!\uFFFE):([A-Za-z_]\w*)(?:\(([^)]*)\))?(\?$)?/g, (m, id, p, o, i, s) => {
999
+ const group = `(?<${toGroupName(id)}>${p && (p != "[^\\x2f]+?" || !/[(\uFFFF]/.test(s[i + m.length])) ? p : "[^/]+?"})`;
1000
+ return o ? (_o = id, `(?:${group})?`) : group;
1001
+ }).replace(/\((?![?<])/g, () => `(?<${groupKey(_i++)}>`), "\uFFFE").replace(/\uFFFE([\s\S])|\uFFFF/g, (_, c = "") => /[.*+?^${}()|[\]\\]/.test(c) ? `\\${c}` : c);
1002
+ const regexp = new RegExp(`^${regex}$`);
1003
+ for (const p of _c) _r += new RegExp(`^(?:${decodeEscapes(p, "\\")})$`).test("") ? -1 : 1;
1004
+ return [
1005
+ regexp,
1006
+ _i,
1007
+ _o,
1008
+ _r
1009
+ ];
1010
+ }
1011
+ function linearRegExp(regexp) {
1012
+ let source = regexp.source;
1013
+ if (!source.includes("[^/]+?)")) return regexp;
1014
+ let head = "";
1015
+ source = source.replace(/(\(\?<\w+>\[\^\/\]\*\))((?:\\[\s\S]|[^\\()]|(?:\(\?:)?\(\?<\w+>\[\^\/\]\+\?\)(?:\)\?)?)*)\$$/, (all, star, rest) => {
1016
+ if (!rest.includes("+?")) return all;
1017
+ head = `(?=[^/]*$(?<=(${rest.replace(/((?:\\[\s\S]|[^\\()])+)(?=\()|(\(\?:)?\(\?<\w+>\[\^\/\]\+\?\)(?:\)\?)?/g, (_, L, opt) => L ? L + upTo(L, true) : opt ? "" : "[^/]")})))`;
1018
+ return `${star}(?=\\1$)${rest}$`;
1019
+ });
1020
+ source = source.replace(/\[\^\/\]\+\?\)((?:\\[\s\S]|[^\\()])*)(?=(?:\(\?:)?\(\?<\w+>\[\^\/\](?:\+\?|\*)\))/g, (_, L) => `[^/]${L && upTo(L)})${L}`);
1021
+ return source === regexp.source ? regexp : new RegExp(`^${head}${source.slice(1)}`);
1022
+ }
1023
+ var upTo = (L, back) => L.replace(/^\\/, "").length < 2 ? `[^/${L}]*` : back ? `(?:[^/](?<!${L}))*` : `(?:(?!${L})[^/])*`;
1024
+ function addRoute(ctx, method = "", path3, data) {
1025
+ method = method.toUpperCase();
1026
+ path3 = absolutePattern(path3);
1027
+ checkConstraints(path3);
1028
+ const resolved = dotSegments(path3);
1029
+ const [route, unnamed] = starGroups(resolved);
1030
+ variants = void 0;
1031
+ _add(ctx, method, route, data, unnamed && expandedRouteId(resolved), path3, unnamed);
1032
+ }
1033
+ var variants;
1034
+ function _add(ctx, method, path3, data, route, input = path3, unnamed = same) {
1035
+ const groupExpanded = expandGroupDelimiters(path3, input);
1036
+ if (groupExpanded) {
1037
+ if (groupExpanded[1] !== void 0) {
1038
+ route ??= expandedRouteId(path3);
1039
+ variants ??= {};
1040
+ }
1041
+ _add(ctx, method, groupExpanded[0], data, route, input, unnamed);
1042
+ if (groupExpanded[1] !== void 0) _add(ctx, method, groupExpanded[1], data, route, input, /[*(]/.test(path3) ? skipGroup(path3, input, unnamed) : unnamed);
1043
+ return 0;
1044
+ }
1045
+ path3 = encodeEscapes(path3);
1046
+ const segments = splitRoute(path3);
1047
+ const expanded = expandModifiers(segments, input);
1048
+ if (expanded) {
1049
+ route ??= expandedRouteId(path3);
1050
+ variants ??= {};
1051
+ let count = 0;
1052
+ for (const p of expanded) count = _add(ctx, method, p, data, route, input, unnamed);
1053
+ return count;
1054
+ }
1055
+ const star = path3.includes("*");
1056
+ const split = star ? splitStar(segments, input) : void 0;
1057
+ if (split) {
1058
+ const [routes, join6, head] = split;
1059
+ if (routes.length > 1) {
1060
+ route ??= expandedRouteId(path3);
1061
+ variants ??= {};
1062
+ }
1063
+ let count = 0;
1064
+ for (const r of routes) count = _insert(ctx, method, r, data, route, input, unnamed, star, r === segments ? -1 : join6, head);
1065
+ return count;
1066
+ }
1067
+ return _insert(ctx, method, segments, data, route, input, unnamed, star);
1068
+ }
1069
+ function _insert(ctx, method, segments, data, route, input, unnamed, star, join6 = -1, head) {
1070
+ let node = ctx.root;
1071
+ let _unnamedParamIndex = 0;
1072
+ const paramsMap = [];
1073
+ const paramsRegexp = [];
1074
+ let rank = 0;
1075
+ const names = [];
1076
+ let named = false;
1077
+ const captureKey = (n) => {
1078
+ const k = unnamed(n);
1079
+ if (typeof k === "string" && !named) {
1080
+ named = true;
1081
+ addName(names, k, input);
1082
+ }
1083
+ return k;
1084
+ };
1085
+ let suffix;
1086
+ let wildcardIndex = -1;
1087
+ const trail = star ? [] : void 0;
1088
+ for (let i = 0; i < segments.length; i++) {
1089
+ let segment = segments[i];
1090
+ const key2 = segmentKey(segment);
1091
+ if (key2 === 2) {
1092
+ if (suffix) oneCatchAll(input);
1093
+ trail?.push(node);
1094
+ if (!node.wildcard) node.wildcard = { key: "**" };
1095
+ node = node.wildcard;
1096
+ const empty = segment.length === 1 || i === join6;
1097
+ paramsMap.push([
1098
+ -(i + 1),
1099
+ i === join6 ? String(captureKey(head ? _unnamedParamIndex - 1 : _unnamedParamIndex++)) : segment.length === 2 ? (addName(names, "_", input), String(unnamed(_unnamedParamIndex++))) : empty ? String(captureKey(_unnamedParamIndex++)) : addName(names, segment.slice(3), input),
1100
+ segment.length === 2 && !(i === join6 && segments[i + 1]?.charCodeAt(0) !== 42),
1101
+ empty,
1102
+ void 0,
1103
+ i === join6
1104
+ ]);
1105
+ if (i === segments.length - 1) break;
1106
+ suffix = [];
1107
+ wildcardIndex = i;
1108
+ continue;
1109
+ }
1110
+ if (key2 === 1) {
1111
+ if (suffix) suffix.push(1);
1112
+ else {
1113
+ trail?.push(node);
1114
+ if (!node.param) node.param = { key: "*" };
1115
+ node = node.param;
1116
+ }
1117
+ if (!/^:[A-Za-z_]\w*$/.test(segment)) {
1118
+ const tail = i === join6 + 1 && segment.charCodeAt(0) === 42;
1119
+ const [source, nextIndex, inPlace, segmentRank] = getParamRegexp(segment, _unnamedParamIndex - (tail ? 1 : 0), names, input, (n) => toUnnamedGroupKey(captureKey(n)));
1120
+ _unnamedParamIndex = nextIndex;
1121
+ const regexp = paramsRegexp[i] = linearRegExp(source);
1122
+ rank += segmentRank;
1123
+ if (!suffix) node.hasRegexParam = true;
1124
+ paramsMap.push([
1125
+ i,
1126
+ regexp,
1127
+ false,
1128
+ /^(?!(?:[\s\S]*:\w+(?![\w?])){2})(?:\*|:[A-Za-z_]\w*)+\??$/.test(segment),
1129
+ inPlace,
1130
+ tail
1131
+ ]);
1132
+ } else paramsMap.push([
1133
+ i,
1134
+ addName(names, segment.slice(1), input),
1135
+ false
1136
+ ]);
1137
+ continue;
1138
+ }
1139
+ if (segment.includes("?") && /(^|[^\\])\?/.test(segment)) invalidSyntax(MISPLACED_MODIFIER, input);
1140
+ segment = segments[i] = key2;
1141
+ if (suffix) {
1142
+ suffix.push(segment);
1143
+ continue;
1144
+ }
1145
+ trail?.push(node);
1146
+ const child = node.static?.[segment];
1147
+ if (child) node = child;
1148
+ else {
1149
+ const staticNode = { key: segment };
1150
+ if (!node.static) node.static = new NullProtoObj();
1151
+ node.static[segment] = staticNode;
1152
+ node = staticNode;
1153
+ }
1154
+ }
1155
+ if (suffix) {
1156
+ for (const n of trail) n.hasSuffix = true;
1157
+ node = node.suffix ??= { key: "" };
1158
+ for (let j = suffix.length - 1; j >= 0; j--) {
1159
+ const edge = suffix[j];
1160
+ if (edge === 1) node = node.param ??= { key: "*" };
1161
+ else node = (node.static ??= new NullProtoObj())[edge] ??= { key: edge };
1162
+ }
1163
+ }
1164
+ const hasParams = paramsMap.length > 0;
1165
+ const key = "/" + segments.join("/");
1166
+ const methods = node.methods ??= new NullProtoObj();
1167
+ (methods[method] ??= []).push({
1168
+ data: data ?? null,
1169
+ paramsRegexp,
1170
+ paramsMap: hasParams ? paramsMap : void 0,
1171
+ route: route ?? key,
1172
+ suffix: suffix && [wildcardIndex, suffix.length],
1173
+ variants,
1174
+ rank: rank / 2 ** 32
1175
+ });
1176
+ if (!hasParams) ctx.static[segments.length > 0 ? key : ""] = node;
1177
+ return _unnamedParamIndex;
1178
+ }
1179
+ var same = (index) => index;
1180
+ function skipGroup(path3, input, unnamed = same) {
1181
+ const [pre, body] = scanFirstGroup(path3);
1182
+ if (!/[*(]/.test(body) && !pre.endsWith("*")) return unnamed;
1183
+ const count = (p) => _add(createRouter(), "", p, void 0, void 0, input);
1184
+ const before = count(pre);
1185
+ const skip = count(absolutePattern(joinGroup(pre, body, input))) - before;
1186
+ return skip ? (index) => unnamed(index < before ? index : index + skip) : unnamed;
1187
+ }
1188
+ function collectSuffix(node, method, segments, start, pos, matches, reverse) {
1189
+ const match = node.methods && methodEntries(node.methods, method, reverse);
1190
+ if (match) {
1191
+ const end = pos + 1;
1192
+ const weighted = [];
1193
+ for (const m of reverse ? match : reverseVariants(match)) {
1194
+ const w = m.suffix[0];
1195
+ let weight = 0;
1196
+ for (const [index, , optional, empty] of m.paramsMap) if (index < 0 && !optional) weight = end > start ? empty ? 2 : 4 : -1;
1197
+ const regexps = m.paramsRegexp;
1198
+ for (let i = 0; i < regexps.length && weight >= 0; i++) if (regexps[i]) weight = regexps[i].test(segments[i > w ? i - w - 1 + end : i]) ? weight + (m.paramsMap.find((e) => e[0] === i)[3] ? 1 : 4) : -1;
1199
+ if (weight >= 0) weighted.push([m, weight + m.rank]);
1200
+ }
1201
+ for (const [m] of weighted.sort((a, b) => a[1] - b[1])) matches.push(m);
1202
+ }
1203
+ if (pos >= start) {
1204
+ if (node.param) collectSuffix(node.param, method, segments, start, pos - 1, matches, reverse);
1205
+ const staticChild = node.static?.[segments[pos]];
1206
+ if (staticChild) collectSuffix(staticChild, method, segments, start, pos - 1, matches, reverse);
1207
+ }
1208
+ }
1209
+ function hasSuffixMatch(node, method, segments, index) {
1210
+ const trie = node.wildcard?.suffix;
1211
+ if (trie && (trie.param || trie.static?.[segments[segments.length - 1]])) {
1212
+ const matches = [];
1213
+ collectSuffix(trie, method, segments, index, segments.length - 1, matches);
1214
+ if (matches.length > 0) return true;
1215
+ }
1216
+ if (index < segments.length) {
1217
+ const staticChild = node.static?.[segments[index]];
1218
+ if (staticChild?.hasSuffix && hasSuffixMatch(staticChild, method, segments, index + 1)) return true;
1219
+ if (node.param?.hasSuffix && hasSuffixMatch(node.param, method, segments, index + 1)) return true;
1220
+ }
1221
+ return false;
1222
+ }
1223
+ function rankFromEnd(matches, segments) {
1224
+ const n = segments.length;
1225
+ return matches.sort((a, b) => {
1226
+ for (let p = n - 1; p >= 0; p--) {
1227
+ const x = kindAt(a, n, p);
1228
+ const y = kindAt(b, n, p);
1229
+ if (x < 0 && y < 0) p = ~Math.min(x, y);
1230
+ else if (Math.max(x, 0) !== Math.max(y, 0)) return Math.max(x, 0) - Math.max(y, 0);
1231
+ }
1232
+ return 0;
1233
+ });
1234
+ }
1235
+ function kindAt(m, n, p) {
1236
+ const suffix = m.suffix;
1237
+ const end = suffix ? n - suffix[1] : n;
1238
+ for (const [index, name, , plain2] of m.paramsMap || []) if (index < 0) {
1239
+ if (p >= ~index && p < end) return index;
1240
+ } else if ((suffix && index > suffix[0] ? index - suffix[0] - 1 + end : index) === p) return typeof name === "string" || plain2 ? 0 : 2;
1241
+ return 3;
1242
+ }
1243
+ function _findRanked(ctx, method, segments, reverse) {
1244
+ let matches = _findAll(ctx.root, method, segments, 0, [], reverse);
1245
+ if (segments.includes("")) matches = matches.filter((m) => !emptyParam(m, segments));
1246
+ if (ctx.root.hasSuffix && matches.some((m) => m.suffix)) rankFromEnd(matches, segments);
1247
+ return matches;
1248
+ }
1249
+ function _findAll(node, method, segments, index, matches = [], reverse) {
1250
+ const segment = segments[index];
1251
+ if (node.wildcard) {
1252
+ const match = node.wildcard.methods && methodEntries(node.wildcard.methods, method, reverse);
1253
+ if (match) pushSorted(matches, index < segments.length ? match : match.filter((m) => matchesZero(m)), reverse);
1254
+ if (node.wildcard.suffix) collectSuffix(node.wildcard.suffix, method, segments, index, segments.length - 1, matches, reverse);
1255
+ }
1256
+ if (node.param && index < segments.length) {
1257
+ const start = matches.length;
1258
+ _findAll(node.param, method, segments, index + 1, matches, reverse);
1259
+ if (node.param.hasRegexParam) {
1260
+ for (let r = matches.length - 1; r >= start; r--) if (matches[r].paramsRegexp[index]?.test(segment) === false) matches.splice(r, 1);
1261
+ }
1262
+ }
1263
+ if (index < segments.length) {
1264
+ const staticChild = node.static?.[segment];
1265
+ if (staticChild) _findAll(staticChild, method, segments, index + 1, matches, reverse);
1266
+ }
1267
+ if (index === segments.length && node.methods) {
1268
+ const match = methodEntries(node.methods, method, reverse);
1269
+ if (match) pushSorted(matches, match, reverse);
1270
+ }
1271
+ return matches;
1272
+ }
1273
+ function pushSorted(matches, match, reverse) {
1274
+ if (match.length > 1) match = (reverse ? match : reverseVariants(match)).map((m) => {
1275
+ let w = m.rank;
1276
+ const { paramsRegexp: rx, paramsMap: pm } = m;
1277
+ for (let i = 0; i < rx.length; i++) if (rx[i]) w += 2;
1278
+ const last = pm?.[pm.length - 1];
1279
+ if (last && !last[2]) w += last[0] < 0 && last[3] ? 1 : 2;
1280
+ return [m, w];
1281
+ }).sort((a, b) => a[1] - b[1]).map((e) => e[0]);
1282
+ for (const m of match) matches.push(m);
1283
+ }
1284
+ function findRoute(ctx, method = "", path3, opts) {
1285
+ if (opts?.normalize) path3 = normalizePath(path3);
1286
+ const slash = path3.charCodeAt(path3.length - 1) === 47;
1287
+ if (slash) path3 = path3.slice(0, -1);
1288
+ const staticNode = ctx.static[path3];
1289
+ if (staticNode && staticNode.methods) {
1290
+ const staticMatch = staticNode.methods[method] || staticNode.methods[""];
1291
+ if (staticMatch !== void 0) return { data: staticMatch[0].data };
1292
+ }
1293
+ const segments = splitPath(path3);
1294
+ let match;
1295
+ if (segments.includes("") || ctx.root.hasSuffix && hasSuffixMatch(ctx.root, method, segments, 0)) {
1296
+ const matches = _findRanked(ctx, method, segments, true);
1297
+ match = matches[matches.length - 1];
1298
+ } else match = _lookupTree(ctx.root, method, segments, 0);
1299
+ if (match === void 0) return;
1300
+ if (opts?.params === false) return { data: match.data };
1301
+ return {
1302
+ data: match.data,
1303
+ params: match.paramsMap ? getMatchParams(segments, match.paramsMap, match.suffix, slash) : void 0
1304
+ };
1305
+ }
1306
+ function _lookupTree(node, method, segments, index) {
1307
+ if (index === segments.length) {
1308
+ if (node.methods) {
1309
+ const match = _selectMatcher(node.methods, method, segments);
1310
+ if (match) return match;
1311
+ }
1312
+ return node.wildcard?.methods ? _selectMatcher(node.wildcard.methods, method, segments, true) : void 0;
1313
+ }
1314
+ const segment = segments[index];
1315
+ if (node.static) {
1316
+ const staticChild = node.static[segment];
1317
+ if (staticChild) {
1318
+ const match = _lookupTree(staticChild, method, segments, index + 1);
1319
+ if (match) return match;
1320
+ }
1321
+ }
1322
+ if (node.param) {
1323
+ const match = _lookupTree(node.param, method, segments, index + 1);
1324
+ if (match) return match;
1325
+ }
1326
+ if (node.wildcard && node.wildcard.methods) return _selectMatcher(node.wildcard.methods, method, segments);
1327
+ }
1328
+ function _selectMatcher(methods, method, segments, optionalOnly) {
1329
+ let any = methods[""];
1330
+ const match = methods[method] || any;
1331
+ if (!match) return;
1332
+ if (match === any) any = void 0;
1333
+ const first = match[0];
1334
+ if (!any && match.length === 1 && first.paramsRegexp.length === 0) return !optionalOnly || matchesZero(first) ? first : void 0;
1335
+ let best;
1336
+ let bestWeight = -1;
1337
+ let list = match;
1338
+ for (; list; list = list === any ? void 0 : any) for (const m of list) {
1339
+ const last = m.paramsMap?.[m.paramsMap.length - 1];
1340
+ if (optionalOnly && !matchesZero(m)) continue;
1341
+ let weight = m.rank + (last && !last[2] ? last[0] < 0 && last[3] ? 1 : 2 : 0);
1342
+ const regexps = m.paramsRegexp;
1343
+ for (let i = 0; i < regexps.length; i++) if (regexps[i]) {
1344
+ if (!regexps[i].test(segments[i])) {
1345
+ weight = -1;
1346
+ break;
1347
+ }
1348
+ weight += 2;
1349
+ }
1350
+ if (weight > bestWeight) {
1351
+ best = m;
1352
+ bestWeight = weight;
1353
+ }
1354
+ }
1355
+ return best;
1356
+ }
1357
+
1358
+ // ../node_modules/.pnpm/srvx@1.0.8/node_modules/srvx/dist/_chunks/_url.mjs
1359
+ function getNativeClass(key, current) {
1360
+ let C = globalThis[key] || current;
1361
+ let P = Object.getPrototypeOf(C);
1362
+ while (typeof P === "function" && P.prototype) {
1363
+ C = P;
1364
+ P = Object.getPrototypeOf(C);
1365
+ }
1366
+ return globalThis[key] = C;
1367
+ }
1368
+ function lazyInherit(target, source, sourceKey) {
1369
+ for (const key of [...Object.getOwnPropertyNames(source), ...Object.getOwnPropertySymbols(source)]) {
1370
+ if (key === "constructor") continue;
1371
+ const targetDesc = Object.getOwnPropertyDescriptor(target, key);
1372
+ const desc = Object.getOwnPropertyDescriptor(source, key);
1373
+ let modified = false;
1374
+ if (desc.get) {
1375
+ modified = true;
1376
+ desc.get = targetDesc?.get || function() {
1377
+ return this[sourceKey][key];
1378
+ };
1379
+ }
1380
+ if (desc.set) {
1381
+ modified = true;
1382
+ desc.set = targetDesc?.set || function(value) {
1383
+ this[sourceKey][key] = value;
1384
+ };
1385
+ }
1386
+ if (!targetDesc?.value && typeof desc.value === "function") {
1387
+ modified = true;
1388
+ desc.value = function(...args) {
1389
+ return this[sourceKey][key](...args);
1390
+ };
1391
+ }
1392
+ if (modified) Object.defineProperty(target, key, desc);
1393
+ }
1394
+ }
1395
+ var _needsNormRE = /(?:(?:^|\/)(?:\.|\.\.|%2e|%2e\.|\.%2e|%2e%2e)(?:\/|$))|[\\^#"<>{}`\x00-\x20\x7f-\uffff]/i;
1396
+ var _searchNeedsNormRE = /[#"'<>\x00-\x20\x7f-\uffff]/;
1397
+ var FastURL = /* @__PURE__ */ (() => {
1398
+ const NativeURL = globalThis.URL;
1399
+ const NativeSearchParams = globalThis.URLSearchParams;
1400
+ const FastURLSearchParams = class URLSearchParams {
1401
+ #owner;
1402
+ #params;
1403
+ constructor(owner) {
1404
+ this.#owner = owner;
1405
+ }
1406
+ static [Symbol.hasInstance](val) {
1407
+ return val instanceof NativeSearchParams;
1408
+ }
1409
+ _adopt(params) {
1410
+ this.#params = params;
1411
+ }
1412
+ get _params() {
1413
+ if (!this.#params) {
1414
+ const search = this.#owner.search;
1415
+ this.#params ??= new NativeSearchParams(search);
1416
+ }
1417
+ return this.#params;
1418
+ }
1419
+ #mutable() {
1420
+ this.#owner._url;
1421
+ return this.#params;
1422
+ }
1423
+ append(name, value) {
1424
+ this.#mutable().append(name, value);
1425
+ }
1426
+ set(name, value) {
1427
+ this.#mutable().set(name, value);
1428
+ }
1429
+ delete(name, value) {
1430
+ this.#mutable().delete(name, value);
1431
+ }
1432
+ sort() {
1433
+ this.#mutable().sort();
1434
+ }
1435
+ };
1436
+ lazyInherit(FastURLSearchParams.prototype, NativeSearchParams.prototype, "_params");
1437
+ Object.setPrototypeOf(FastURLSearchParams.prototype, NativeSearchParams.prototype);
1438
+ Object.setPrototypeOf(FastURLSearchParams, NativeSearchParams);
1439
+ const FastURL2 = class URL {
1440
+ #url;
1441
+ #href;
1442
+ #protocol;
1443
+ #host;
1444
+ #pathname;
1445
+ #search;
1446
+ #searchParams;
1447
+ #pos;
1448
+ constructor(url) {
1449
+ if (typeof url === "string") {
1450
+ const isOriginForm = url[0] === "/";
1451
+ if (isOriginForm && !_searchNeedsNormRE.test(url)) this.#href = `http://localhost${url}`;
1452
+ else this.#url = new NativeURL(isOriginForm ? `http://localhost${url}` : url);
1453
+ } else if (_needsNormRE.test(url.pathname) || url.search && _searchNeedsNormRE.test(url.search)) this.#url = new NativeURL(`${url.protocol || "http:"}//${url.host || "localhost"}${url.pathname}${url.search || ""}`);
1454
+ else {
1455
+ this.#protocol = url.protocol;
1456
+ this.#host = url.host;
1457
+ this.#pathname = url.pathname;
1458
+ this.#search = url.search;
1459
+ }
1460
+ }
1461
+ static [Symbol.hasInstance](val) {
1462
+ return val instanceof NativeURL;
1463
+ }
1464
+ get _url() {
1465
+ if (this.#url) return this.#url;
1466
+ this.#url = new NativeURL(this.href);
1467
+ this.#href = void 0;
1468
+ this.#protocol = void 0;
1469
+ this.#host = void 0;
1470
+ this.#pathname = void 0;
1471
+ this.#search = void 0;
1472
+ this.#pos = void 0;
1473
+ this.#searchParams?._adopt(this.#url.searchParams);
1474
+ return this.#url;
1475
+ }
1476
+ get href() {
1477
+ if (this.#url) return this.#url.href;
1478
+ if (!this.#href) this.#href = `${this.#protocol || "http:"}//${this.#host || "localhost"}${this.#pathname || "/"}${this.#search || ""}`;
1479
+ return this.#href;
1480
+ }
1481
+ #getPos() {
1482
+ if (!this.#pos) {
1483
+ const url = this.href;
1484
+ const protoIndex = url.indexOf("://");
1485
+ const pathnameIndex = protoIndex === -1 ? -1 : url.indexOf("/", protoIndex + 4);
1486
+ const qIndex = pathnameIndex === -1 ? -1 : url.indexOf("?", pathnameIndex);
1487
+ this.#pos = [
1488
+ protoIndex,
1489
+ pathnameIndex,
1490
+ qIndex
1491
+ ];
1492
+ }
1493
+ return this.#pos;
1494
+ }
1495
+ get pathname() {
1496
+ if (this.#url) return this.#url.pathname;
1497
+ if (this.#pathname === void 0) {
1498
+ const [, pathnameIndex, queryIndex] = this.#getPos();
1499
+ if (pathnameIndex === -1) return this._url.pathname;
1500
+ this.#pathname = this.href.slice(pathnameIndex, queryIndex === -1 ? void 0 : queryIndex);
1501
+ }
1502
+ return this.#pathname;
1503
+ }
1504
+ get search() {
1505
+ if (this.#url) return this.#url.search;
1506
+ if (this.#search === void 0) {
1507
+ const [, pathnameIndex, queryIndex] = this.#getPos();
1508
+ if (pathnameIndex === -1) return this._url.search;
1509
+ const url = this.href;
1510
+ this.#search = queryIndex === -1 || queryIndex === url.length - 1 ? "" : url.slice(queryIndex);
1511
+ }
1512
+ return this.#search;
1513
+ }
1514
+ get searchParams() {
1515
+ if (this.#searchParams) return this.#searchParams;
1516
+ if (this.#url) return this.#url.searchParams;
1517
+ return this.#searchParams = new FastURLSearchParams(this);
1518
+ }
1519
+ get protocol() {
1520
+ if (this.#url) return this.#url.protocol;
1521
+ if (this.#protocol === void 0) {
1522
+ const [protocolIndex] = this.#getPos();
1523
+ if (protocolIndex === -1) return this._url.protocol;
1524
+ const url = this.href;
1525
+ this.#protocol = url.slice(0, protocolIndex + 1);
1526
+ }
1527
+ return this.#protocol;
1528
+ }
1529
+ get hash() {
1530
+ if (this.#url) return this.#url.hash;
1531
+ return "";
1532
+ }
1533
+ toString() {
1534
+ return this.href;
1535
+ }
1536
+ toJSON() {
1537
+ return this.href;
1538
+ }
1539
+ };
1540
+ lazyInherit(FastURL2.prototype, NativeURL.prototype, "_url");
1541
+ Object.setPrototypeOf(FastURL2.prototype, NativeURL.prototype);
1542
+ Object.setPrototypeOf(FastURL2, NativeURL);
1543
+ return FastURL2;
1544
+ })();
1545
+
1546
+ // ../node_modules/.pnpm/srvx@1.0.8/node_modules/srvx/dist/body-limit.mjs
1547
+ function limitBodyStream(stream, maxRequestBodySize, options) {
1548
+ const createError2 = options?.createError ?? createBodyTooLargeError;
1549
+ const reader = stream.getReader();
1550
+ let size = 0;
1551
+ return new ReadableStream({
1552
+ async pull(controller) {
1553
+ const { done, value } = await reader.read();
1554
+ if (done) {
1555
+ controller.close();
1556
+ return;
1557
+ }
1558
+ size += value.byteLength;
1559
+ if (size > maxRequestBodySize) {
1560
+ const error = createError2(maxRequestBodySize);
1561
+ reader.cancel(error).catch(() => {
1562
+ });
1563
+ controller.error(error);
1564
+ return;
1565
+ }
1566
+ controller.enqueue(value);
1567
+ },
1568
+ cancel(reason) {
1569
+ return reader.cancel(reason);
1570
+ }
1571
+ });
1572
+ }
1573
+ var BodyTooLargeError = class extends Error {
1574
+ code = "ERR_BODY_TOO_LARGE";
1575
+ statusCode = 413;
1576
+ status = 413;
1577
+ statusText = "Content Too Large";
1578
+ get name() {
1579
+ return "HTTPError";
1580
+ }
1581
+ toJSON() {
1582
+ return {
1583
+ status: this.status,
1584
+ statusText: this.statusText,
1585
+ message: this.message
1586
+ };
1587
+ }
1588
+ };
1589
+ function createBodyTooLargeError(maxRequestBodySize) {
1590
+ return new BodyTooLargeError(`Request body exceeds the maximum allowed size of ${maxRequestBodySize} bytes.`);
1591
+ }
1592
+
1593
+ // ../node_modules/.pnpm/srvx@1.0.8/node_modules/srvx/dist/_chunks/_trust-proxy.mjs
1594
+ function isTrustedProxy(trustProxy, remoteAddress) {
1595
+ if (trustProxy === void 0 || trustProxy === false) return false;
1596
+ if (trustProxy === true) return true;
1597
+ if (trustProxy === "loopback") return isLoopbackAddress(remoteAddress);
1598
+ if (remoteAddress === void 0) return false;
1599
+ if (trustProxy.includes(remoteAddress)) return true;
1600
+ const mapped = ipv4FromMapped(remoteAddress);
1601
+ return mapped !== void 0 && trustProxy.includes(mapped);
1602
+ }
1603
+ function ipv4FromMapped(address) {
1604
+ return address.startsWith("::ffff:") && address.includes(".") ? address.slice(7) : void 0;
1605
+ }
1606
+ function isLoopbackAddress(address) {
1607
+ return !!address && (address === "::1" || address.startsWith("127.") || address.startsWith("::ffff:127."));
1608
+ }
1609
+ var HOST_RE = /^(\[(?:[A-Fa-f0-9:.]+)\]|(?:[A-Za-z0-9_-]+\.)*[A-Za-z0-9_-]+|(?:\d{1,3}\.){3}\d{1,3})(:\d{1,5})?$/;
1610
+ function forwardedList(value) {
1611
+ if (!value) return [];
1612
+ const raw = Array.isArray(value) ? value.join(",") : value;
1613
+ const out = [];
1614
+ for (const part of raw.split(",")) {
1615
+ const entry = part.trim();
1616
+ if (entry) out.push(entry);
1617
+ }
1618
+ return out;
1619
+ }
1620
+ function resolveClientIP(trustProxy, peer, forwardedFor) {
1621
+ if (!isTrustedProxy(trustProxy, peer)) return peer;
1622
+ const list = forwardedList(forwardedFor);
1623
+ for (let i = list.length - 1; i >= 0; i--) if (!isTrustedProxy(trustProxy, list[i])) return list[i];
1624
+ return list.length > 0 ? list[0] : peer;
1625
+ }
1626
+ function trustedHops(trustProxy, peer, forwardedFor) {
1627
+ if (!isTrustedProxy(trustProxy, peer)) return 0;
1628
+ const list = forwardedList(forwardedFor);
1629
+ let hops = 1;
1630
+ for (let i = list.length - 1; i >= 0; i--) {
1631
+ if (!isTrustedProxy(trustProxy, list[i])) return hops;
1632
+ hops++;
1633
+ }
1634
+ return Number.POSITIVE_INFINITY;
1635
+ }
1636
+ function forwardedHopValue(value, hops) {
1637
+ if (hops <= 0) return;
1638
+ const list = forwardedList(value);
1639
+ if (list.length === 0) return;
1640
+ return list[Math.max(0, list.length - hops)];
1641
+ }
1642
+
1643
+ // ../node_modules/.pnpm/srvx@1.0.8/node_modules/srvx/dist/adapters/node.mjs
1644
+ import { Duplex, PassThrough, Readable, addAbortSignal } from "node:stream";
1645
+ import { pipeline as pipeline$1 } from "node:stream/promises";
1646
+ function sendNodeResponse(nodeRes, webRes) {
1647
+ try {
1648
+ return _sendNodeResponse(nodeRes, webRes, false) || Promise.resolve();
1649
+ } catch (error) {
1650
+ return Promise.reject(error);
1651
+ }
1652
+ }
1653
+ function handleSendError(nodeRes, error, silent) {
1654
+ if (!silent) console.error("[srvx] Failed to send response:", error);
1655
+ failResponse(nodeRes);
1656
+ }
1657
+ function failResponse(nodeRes) {
1658
+ if (nodeRes.writableEnded) return;
1659
+ if (nodeRes.headersSent) nodeRes.destroy();
1660
+ else {
1661
+ nodeRes.statusCode = 500;
1662
+ if (nodeRes.req?.httpVersion !== "2.0") nodeRes.statusMessage = "";
1663
+ nodeRes.end();
1664
+ }
1665
+ }
1666
+ function _sendNodeResponse(nodeRes, webRes, detached) {
1667
+ if (!webRes) {
1668
+ nodeRes.statusCode = 500;
1669
+ return endNodeResponse(nodeRes, detached);
1670
+ }
1671
+ if (webRes._toNodeResponse) {
1672
+ const res = webRes._toNodeResponse();
1673
+ if (res.body) {
1674
+ if (res.body instanceof ReadableStream) {
1675
+ writeHead(nodeRes, res.status, res.statusText, res.headers);
1676
+ return streamBody(res.body, nodeRes);
1677
+ } else if (typeof res.body?.pipe === "function") return pipeBody(res.body, nodeRes, res.status, res.statusText, res.headers);
1678
+ writeHead(nodeRes, res.status, res.statusText, res.headers);
1679
+ nodeRes.write(res.body);
1680
+ } else writeHead(nodeRes, res.status, res.statusText, res.headers);
1681
+ return endNodeResponse(nodeRes, detached);
1682
+ }
1683
+ const rawHeaders = [];
1684
+ for (const [key, value] of webRes.headers) rawHeaders.push(key, value);
1685
+ writeHead(nodeRes, webRes.status, webRes.statusText, rawHeaders);
1686
+ return webRes.body ? streamBody(webRes.body, nodeRes) : endNodeResponse(nodeRes, detached);
1687
+ }
1688
+ function writeHead(nodeRes, status, statusText, rawHeaders) {
1689
+ if (!nodeRes.headersSent) {
1690
+ if (nodeRes.req?.httpVersion === "2.0") nodeRes.writeHead(status, rawHeaders);
1691
+ else nodeRes.writeHead(status, safeStatusText(statusText), rawHeaders);
1692
+ }
1693
+ }
1694
+ var INVALID_REASON_PHRASE_RE = /[^\t\u0020-\u007E\u0080-\u00FF]/g;
1695
+ function safeStatusText(statusText) {
1696
+ return typeof statusText === "string" && statusText ? statusText.replace(INVALID_REASON_PHRASE_RE, "") : statusText;
1697
+ }
1698
+ function endNodeResponse(nodeRes, detached) {
1699
+ if (detached) {
1700
+ nodeRes.end();
1701
+ return;
1702
+ }
1703
+ return new Promise((resolve4) => nodeRes.end(resolve4));
1704
+ }
1705
+ function pipeBody(stream, nodeRes, status, statusText, headers) {
1706
+ if (nodeRes.destroyed) {
1707
+ stream.destroy?.();
1708
+ return;
1709
+ }
1710
+ if (nodeRes.req?.method === "HEAD") {
1711
+ if (typeof stream.destroy === "function") stream.destroy();
1712
+ else stream.abort?.();
1713
+ writeHead(nodeRes, status, statusText, headers);
1714
+ return endNodeResponse(nodeRes);
1715
+ }
1716
+ if (typeof stream.on !== "function" || typeof stream.destroy !== "function") {
1717
+ writeHead(nodeRes, status, statusText, headers);
1718
+ stream.pipe(nodeRes);
1719
+ return new Promise((resolve4) => nodeRes.on("close", resolve4));
1720
+ }
1721
+ if (stream.readableEnded && !stream.errored) {
1722
+ writeHead(nodeRes, status, statusText, headers);
1723
+ return endNodeResponse(nodeRes);
1724
+ }
1725
+ if (stream.destroyed) {
1726
+ writeHead(nodeRes, 500, "Internal Server Error", []);
1727
+ return endNodeResponse(nodeRes);
1728
+ }
1729
+ return new Promise((resolve4) => {
1730
+ function cleanup() {
1731
+ stream.off("error", onEarlyError);
1732
+ stream.off("readable", onReadable);
1733
+ stream.off("end", onEnd);
1734
+ nodeRes.off("close", onResClose);
1735
+ }
1736
+ function onEarlyError() {
1737
+ cleanup();
1738
+ stream.destroy();
1739
+ writeHead(nodeRes, 500, "Internal Server Error", []);
1740
+ endNodeResponse(nodeRes).then(resolve4);
1741
+ }
1742
+ function onReadable() {
1743
+ cleanup();
1744
+ if (nodeRes.destroyed) {
1745
+ stream.destroy();
1746
+ return resolve4();
1747
+ }
1748
+ writeHead(nodeRes, status, statusText, headers);
1749
+ pipeline$1(stream, nodeRes).catch(() => {
1750
+ }).then(() => resolve4());
1751
+ }
1752
+ function onEnd() {
1753
+ cleanup();
1754
+ if (nodeRes.destroyed) return resolve4();
1755
+ writeHead(nodeRes, status, statusText, headers);
1756
+ endNodeResponse(nodeRes).then(resolve4);
1757
+ }
1758
+ function onResClose() {
1759
+ cleanup();
1760
+ stream.destroy();
1761
+ resolve4();
1762
+ }
1763
+ stream.once("error", onEarlyError);
1764
+ stream.once("readable", onReadable);
1765
+ stream.once("end", onEnd);
1766
+ nodeRes.once("close", onResClose);
1767
+ });
1768
+ }
1769
+ function streamBody(stream, nodeRes) {
1770
+ if (nodeRes.destroyed) {
1771
+ stream.cancel().catch(() => {
1772
+ });
1773
+ return;
1774
+ }
1775
+ if (nodeRes.req?.method === "HEAD") {
1776
+ stream.cancel().catch(() => {
1777
+ });
1778
+ return endNodeResponse(nodeRes);
1779
+ }
1780
+ const reader = stream.getReader();
1781
+ function streamCancel(error) {
1782
+ reader.cancel(error).catch(() => {
1783
+ });
1784
+ if (error) nodeRes.destroy(error);
1785
+ }
1786
+ function streamHandle({ done, value }) {
1787
+ try {
1788
+ if (done) nodeRes.end();
1789
+ else if (nodeRes.write(value)) reader.read().then(streamHandle, streamCancel);
1790
+ else nodeRes.once("drain", () => reader.read().then(streamHandle, streamCancel));
1791
+ } catch (error) {
1792
+ streamCancel(error instanceof Error ? error : void 0);
1793
+ }
1794
+ }
1795
+ nodeRes.on("close", streamCancel);
1796
+ nodeRes.on("error", streamCancel);
1797
+ reader.read().then(streamHandle, streamCancel);
1798
+ return reader.closed.catch(streamCancel).finally(() => {
1799
+ nodeRes.off("close", streamCancel);
1800
+ nodeRes.off("error", streamCancel);
1801
+ });
1802
+ }
1803
+ var NodeRequestURL = class extends FastURL {
1804
+ constructor({ req, hops = 0 }) {
1805
+ const path3 = req.url || "/";
1806
+ const trusted = hops > 0;
1807
+ const forwardedHost = forwardedHopValue(req.headers["x-forwarded-host"], hops);
1808
+ let host = (forwardedHost && HOST_RE.test(forwardedHost) ? forwardedHost : void 0) || req.headers.host || req.headers[":authority"];
1809
+ if (host && !HOST_RE.test(host)) host = "_invalid_";
1810
+ else if (!host) {
1811
+ if (req.socket) host = `${req.socket.localFamily === "IPv6" ? "[" + req.socket.localAddress + "]" : req.socket.localAddress}:${req.socket?.localPort || "80"}`;
1812
+ else host = "localhost";
1813
+ }
1814
+ const forwardedProto = forwardedHopValue(req.headers["x-forwarded-proto"], hops);
1815
+ const protocol = req.socket?.encrypted || forwardedProto === "https" || trusted && req.headers[":scheme"] === "https" ? "https:" : "http:";
1816
+ if (path3[0] === "/") {
1817
+ const qIndex = path3.indexOf("?");
1818
+ super({
1819
+ protocol,
1820
+ host,
1821
+ pathname: qIndex === -1 ? path3 : path3.slice(0, qIndex) || "/",
1822
+ search: qIndex === -1 ? "" : path3.slice(qIndex) || ""
1823
+ });
1824
+ } else if (path3 === "*") super({
1825
+ protocol,
1826
+ host,
1827
+ pathname: "/*",
1828
+ search: ""
1829
+ });
1830
+ else {
1831
+ const target = URL.canParse(path3) ? new URL(path3) : void 0;
1832
+ if (target) {
1833
+ const targetHost = target.host;
1834
+ const targetPath = target.pathname;
1835
+ super({
1836
+ protocol,
1837
+ host: targetHost ? HOST_RE.test(targetHost) ? targetHost : "_invalid_" : host,
1838
+ pathname: targetPath ? targetPath[0] === "/" ? targetPath : `/${targetPath}` : "/",
1839
+ search: target.search
1840
+ });
1841
+ } else super({
1842
+ protocol,
1843
+ host,
1844
+ pathname: "/",
1845
+ search: ""
1846
+ });
1847
+ }
1848
+ }
1849
+ };
1850
+ var _nonJoinedHeaders = /* @__PURE__ */ new Set([
1851
+ "age",
1852
+ "authorization",
1853
+ "content-length",
1854
+ "content-type",
1855
+ "etag",
1856
+ "expires",
1857
+ "from",
1858
+ "host",
1859
+ "if-modified-since",
1860
+ "if-unmodified-since",
1861
+ "last-modified",
1862
+ "location",
1863
+ "max-forwards",
1864
+ "proxy-authorization",
1865
+ "referer",
1866
+ "retry-after",
1867
+ "server",
1868
+ "user-agent"
1869
+ ]);
1870
+ var _validHeaderNameRE = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
1871
+ function _isRepeated(rawHeaders, lowerName) {
1872
+ let seen = false;
1873
+ for (let i = 0; i < rawHeaders.length; i += 2) {
1874
+ const key = rawHeaders[i];
1875
+ if (key.length === lowerName.length && key.toLowerCase() === lowerName) {
1876
+ if (seen) return true;
1877
+ seen = true;
1878
+ }
1879
+ }
1880
+ return false;
1881
+ }
1882
+ var NodeRequestHeaders = /* @__PURE__ */ (() => {
1883
+ const NativeHeaders = globalThis.Headers;
1884
+ class Headers2 {
1885
+ #req;
1886
+ #headers;
1887
+ constructor(req) {
1888
+ this.#req = req;
1889
+ }
1890
+ static [Symbol.hasInstance](val) {
1891
+ return val instanceof NativeHeaders;
1892
+ }
1893
+ _adopt(headers) {
1894
+ this.#headers = headers;
1895
+ }
1896
+ get _headers() {
1897
+ if (!this.#headers) {
1898
+ const headers = new NativeHeaders();
1899
+ const rawHeaders = this.#req.rawHeaders;
1900
+ const len = rawHeaders.length;
1901
+ for (let i = 0; i < len; i += 2) {
1902
+ const key = rawHeaders[i];
1903
+ if (key.charCodeAt(0) === 58) continue;
1904
+ const value = rawHeaders[i + 1];
1905
+ headers.append(key, value);
1906
+ }
1907
+ this.#headers = headers;
1908
+ }
1909
+ return this.#headers;
1910
+ }
1911
+ get(name) {
1912
+ if (this.#headers) return this.#headers.get(name);
1913
+ const lower = name.toLowerCase();
1914
+ if (lower.charCodeAt(0) === 58) return this._headers.get(name);
1915
+ const value = this.#req.headers[lower];
1916
+ if (typeof value === "string") return _nonJoinedHeaders.has(lower) && _isRepeated(this.#req.rawHeaders, lower) ? this._headers.get(name) : value;
1917
+ if (Array.isArray(value)) return value.join(", ");
1918
+ return lower !== "__proto__" && _validHeaderNameRE.test(name) ? null : this._headers.get(name);
1919
+ }
1920
+ has(name) {
1921
+ if (this.#headers) return this.#headers.has(name);
1922
+ const lower = name.toLowerCase();
1923
+ if (lower.charCodeAt(0) === 58) return this._headers.has(name);
1924
+ if (Object.hasOwn(this.#req.headers, lower)) return true;
1925
+ return lower !== "__proto__" && _validHeaderNameRE.test(name) ? false : this._headers.has(name);
1926
+ }
1927
+ getSetCookie() {
1928
+ if (this.#headers) return this.#headers.getSetCookie();
1929
+ const value = this.#req.headers["set-cookie"];
1930
+ return Array.isArray(value) ? value.slice() : value ? [value] : [];
1931
+ }
1932
+ entries() {
1933
+ return this._headers.entries();
1934
+ }
1935
+ [Symbol.iterator]() {
1936
+ return this.entries();
1937
+ }
1938
+ }
1939
+ lazyInherit(Headers2.prototype, NativeHeaders.prototype, "_headers");
1940
+ Object.setPrototypeOf(Headers2, NativeHeaders);
1941
+ Object.setPrototypeOf(Headers2.prototype, NativeHeaders.prototype);
1942
+ return Headers2;
1943
+ })();
1944
+ var kNativeRequest = /* @__PURE__ */ Symbol.for("srvx.nativeRequest");
1945
+ function bodyUnusable() {
1946
+ return /* @__PURE__ */ new TypeError("Body is unusable: Body has already been read");
1947
+ }
1948
+ function abortError() {
1949
+ return new DOMException("The request was aborted.", "AbortError");
1950
+ }
1951
+ function erroredStream(error) {
1952
+ return new ReadableStream({ start(controller) {
1953
+ controller.error(error);
1954
+ } });
1955
+ }
1956
+ function isClientGone(req) {
1957
+ return req.aborted || !!req.errored || req.destroyed && !req.complete;
1958
+ }
1959
+ function isBodySourceFinished(req) {
1960
+ return isClientGone(req) || req.destroyed || req.readableEnded;
1961
+ }
1962
+ var NodeRequest = /* @__PURE__ */ (() => {
1963
+ const NativeRequest = getNativeClass(kNativeRequest, globalThis.Request);
1964
+ class Request2 {
1965
+ runtime;
1966
+ waitUntil;
1967
+ #req;
1968
+ #url;
1969
+ #bodyStream;
1970
+ #bodyUsed = false;
1971
+ #request;
1972
+ #headers;
1973
+ #abortController;
1974
+ #maxRequestBodySize;
1975
+ #trustProxy;
1976
+ #ip;
1977
+ #ipResolved = false;
1978
+ #remoteAddress;
1979
+ #remoteResolved = false;
1980
+ #hops;
1981
+ constructor(ctx) {
1982
+ this.#req = ctx.req;
1983
+ this.#maxRequestBodySize = ctx.maxRequestBodySize;
1984
+ this.#trustProxy = ctx.trustProxy;
1985
+ this.runtime = {
1986
+ name: "node",
1987
+ node: ctx
1988
+ };
1989
+ }
1990
+ static [Symbol.hasInstance](val) {
1991
+ return val instanceof NativeRequest;
1992
+ }
1993
+ #remoteAddr() {
1994
+ if (!this.#remoteResolved) {
1995
+ this.#remoteResolved = true;
1996
+ this.#remoteAddress = this.#req.socket?.remoteAddress;
1997
+ }
1998
+ return this.#remoteAddress;
1999
+ }
2000
+ #resolveHops() {
2001
+ if (this.#hops === void 0) this.#hops = trustedHops(this.#trustProxy, this.#remoteAddr(), this.#req.headers["x-forwarded-for"]);
2002
+ return this.#hops;
2003
+ }
2004
+ get ip() {
2005
+ if (this.#ipResolved) return this.#ip;
2006
+ this.#ipResolved = true;
2007
+ return this.#ip = resolveClientIP(this.#trustProxy, this.#remoteAddr(), this.#req.headers["x-forwarded-for"]);
2008
+ }
2009
+ get method() {
2010
+ if (this.#request) return this.#request.method;
2011
+ return this.#req.method || "GET";
2012
+ }
2013
+ get _url() {
2014
+ return this.#url ||= new NodeRequestURL({
2015
+ req: this.#req,
2016
+ hops: this.#resolveHops()
2017
+ });
2018
+ }
2019
+ set _url(url) {
2020
+ this.#url = url;
2021
+ }
2022
+ get url() {
2023
+ if (this.#request) return this.#request.url;
2024
+ return this._url.href;
2025
+ }
2026
+ get headers() {
2027
+ return this.#headers ||= new NodeRequestHeaders(this.#req);
2028
+ }
2029
+ get _abortController() {
2030
+ if (!this.#abortController) {
2031
+ this.#abortController = new AbortController();
2032
+ const { req, res } = this.runtime.node;
2033
+ const abortController = this.#abortController;
2034
+ const abort = (err) => abortController.abort?.(err);
2035
+ if (res) {
2036
+ const onClose = () => {
2037
+ const reqError = req.errored;
2038
+ if (reqError) abort(reqError);
2039
+ else if (!res.writableEnded) abort();
2040
+ };
2041
+ res.once("close", onClose);
2042
+ if (res.destroyed || isClientGone(req)) onClose();
2043
+ } else {
2044
+ const onClose = () => {
2045
+ if (!req.complete || req.aborted) abort();
2046
+ };
2047
+ req.once("close", onClose);
2048
+ if (isClientGone(req)) onClose();
2049
+ }
2050
+ }
2051
+ return this.#abortController;
2052
+ }
2053
+ get signal() {
2054
+ return this.#request ? this.#request.signal : this._abortController.signal;
2055
+ }
2056
+ #hasBody() {
2057
+ const method = this.method;
2058
+ return method !== "GET" && method !== "HEAD";
2059
+ }
2060
+ get body() {
2061
+ if (this.#request) return this.#request.body;
2062
+ if (this.#bodyStream === void 0) {
2063
+ let stream = null;
2064
+ if (this.#hasBody() && !this.#bodyUsed) {
2065
+ if ("rawBody" in this.#req && Buffer.isBuffer(this.#req.rawBody)) stream = Readable.toWeb(Readable.from([this.#req.rawBody]));
2066
+ else if (isBodySourceFinished(this.#req)) stream = erroredStream(this.#bodyError());
2067
+ else stream = Readable.toWeb(this.#req);
2068
+ }
2069
+ if (stream && this.#maxRequestBodySize !== void 0) stream = limitBodyStream(stream, this.#maxRequestBodySize);
2070
+ this.#bodyStream = stream;
2071
+ }
2072
+ return this.#bodyStream;
2073
+ }
2074
+ get bodyUsed() {
2075
+ if (this.#isBodyUsed()) return true;
2076
+ return this.#request ? this.#request.bodyUsed : false;
2077
+ }
2078
+ #isBodyUsed() {
2079
+ if (!this.#bodyUsed && this.#bodyStream && Readable.isDisturbed(this.#bodyStream)) this.#bodyUsed = true;
2080
+ return this.#bodyUsed;
2081
+ }
2082
+ #bodyError() {
2083
+ const signal = this._abortController.signal;
2084
+ if (signal.aborted) return signal.reason;
2085
+ return this.#req.errored || (isClientGone(this.#req) ? abortError() : bodyUnusable());
2086
+ }
2087
+ #readBuffered() {
2088
+ if ("rawBody" in this.#req && Buffer.isBuffer(this.#req.rawBody)) return readBody(this.#req, this.#maxRequestBodySize);
2089
+ if (isBodySourceFinished(this.#req)) return Promise.reject(this.#bodyError());
2090
+ return readBody(this.#req, this.#maxRequestBodySize);
2091
+ }
2092
+ text() {
2093
+ if (this.#isBodyUsed()) return Promise.reject(bodyUnusable());
2094
+ if (this.#request) return this.#request.text();
2095
+ if (!this.#hasBody()) return Promise.resolve("");
2096
+ this.#bodyUsed = true;
2097
+ if (this.#bodyStream !== void 0) try {
2098
+ return new Response(this.#bodyStream).text();
2099
+ } catch (error) {
2100
+ return Promise.reject(error);
2101
+ }
2102
+ return this.#readBuffered().then((buf) => buf.toString());
2103
+ }
2104
+ json() {
2105
+ if (this.#isBodyUsed()) return Promise.reject(bodyUnusable());
2106
+ if (this.#request) return this.#request.json();
2107
+ if (!this.#hasBody()) return Promise.resolve().then(() => JSON.parse(""));
2108
+ this.#bodyUsed = true;
2109
+ if (this.#bodyStream !== void 0) try {
2110
+ return new Response(this.#bodyStream).json();
2111
+ } catch (error) {
2112
+ return Promise.reject(error);
2113
+ }
2114
+ return this.#readBuffered().then((buf) => JSON.parse(buf.toString()));
2115
+ }
2116
+ arrayBuffer() {
2117
+ return this.#consumeNative("arrayBuffer");
2118
+ }
2119
+ bytes() {
2120
+ return this.#consumeNative("bytes");
2121
+ }
2122
+ blob() {
2123
+ return this.#consumeNative("blob");
2124
+ }
2125
+ formData() {
2126
+ return this.#consumeNative("formData");
2127
+ }
2128
+ #consumeNative(method) {
2129
+ if (this.#isBodyUsed()) return Promise.reject(bodyUnusable());
2130
+ try {
2131
+ return this._request[method]();
2132
+ } catch (error) {
2133
+ return Promise.reject(error);
2134
+ }
2135
+ }
2136
+ get _request() {
2137
+ if (!this.#request) {
2138
+ const body = this.#isBodyUsed() ? null : this.body;
2139
+ this.#request = new NativeRequest(this.url, {
2140
+ method: this.method,
2141
+ headers: this.headers,
2142
+ signal: this._abortController.signal,
2143
+ body,
2144
+ duplex: body ? "half" : void 0
2145
+ });
2146
+ this.#headers._adopt(this.#request.headers);
2147
+ this.#bodyStream = void 0;
2148
+ }
2149
+ return this.#request;
2150
+ }
2151
+ }
2152
+ lazyInherit(Request2.prototype, NativeRequest.prototype, "_request");
2153
+ Object.setPrototypeOf(Request2.prototype, NativeRequest.prototype);
2154
+ return Request2;
2155
+ })();
2156
+ function readBody(req, maxRequestBodySize) {
2157
+ if ("rawBody" in req && Buffer.isBuffer(req.rawBody)) {
2158
+ if (maxRequestBodySize !== void 0 && req.rawBody.length > maxRequestBodySize) return Promise.reject(createBodyTooLargeError(maxRequestBodySize));
2159
+ return Promise.resolve(req.rawBody);
2160
+ }
2161
+ return new Promise((resolve4, reject) => {
2162
+ const chunks = [];
2163
+ let size = 0;
2164
+ const cleanup = () => {
2165
+ req.off("data", onData);
2166
+ req.off("end", onEnd);
2167
+ req.off("error", onError2);
2168
+ req.off("close", onClose);
2169
+ };
2170
+ const onData = (chunk) => {
2171
+ if (maxRequestBodySize !== void 0) {
2172
+ size += chunk.length;
2173
+ if (size > maxRequestBodySize) {
2174
+ cleanup();
2175
+ req.pause?.();
2176
+ reject(createBodyTooLargeError(maxRequestBodySize));
2177
+ return;
2178
+ }
2179
+ }
2180
+ chunks.push(chunk);
2181
+ };
2182
+ const onError2 = (err) => {
2183
+ cleanup();
2184
+ reject(err);
2185
+ };
2186
+ const onEnd = () => {
2187
+ cleanup();
2188
+ if (isClientGone(req)) {
2189
+ reject(req.errored || abortError());
2190
+ return;
2191
+ }
2192
+ resolve4(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
2193
+ };
2194
+ const onClose = () => {
2195
+ cleanup();
2196
+ reject(req.errored || abortError());
2197
+ };
2198
+ req.on("data", onData).once("end", onEnd).once("error", onError2).once("close", onClose);
2199
+ });
2200
+ }
2201
+ var kNativeResponse = /* @__PURE__ */ Symbol.for("srvx.nativeResponse");
2202
+ var NodeResponse = /* @__PURE__ */ (() => {
2203
+ const NativeResponse = getNativeClass(kNativeResponse, globalThis.Response);
2204
+ class NodeResponse2 {
2205
+ #body;
2206
+ #init;
2207
+ #headers;
2208
+ #response;
2209
+ #contentLength;
2210
+ constructor(body, init) {
2211
+ this.#body = body;
2212
+ this.#init = init;
2213
+ }
2214
+ static [Symbol.hasInstance](val) {
2215
+ if (this === NodeResponse2) return val instanceof NativeResponse;
2216
+ return Object.prototype.isPrototypeOf.call(this.prototype, val);
2217
+ }
2218
+ static json(data, init) {
2219
+ const body = JSON.stringify(data);
2220
+ if (body === void 0) throw new TypeError("Value is not JSON serializable");
2221
+ let headers = init?.headers;
2222
+ if (!headers) headers = { "content-type": "application/json" };
2223
+ else {
2224
+ const merged = new Headers(headers);
2225
+ if (!merged.has("content-type")) merged.set("content-type", "application/json");
2226
+ headers = merged;
2227
+ }
2228
+ return new NodeResponse2(body, init ? {
2229
+ ...init,
2230
+ headers
2231
+ } : { headers });
2232
+ }
2233
+ get status() {
2234
+ return this.#response?.status || this.#init?.status || 200;
2235
+ }
2236
+ get statusText() {
2237
+ return this.#response?.statusText || this.#init?.statusText || "";
2238
+ }
2239
+ get headers() {
2240
+ if (this.#response) return this.#response.headers;
2241
+ if (this.#headers) return this.#headers;
2242
+ return this.#headers = new Headers(this.#init?.headers);
2243
+ }
2244
+ get ok() {
2245
+ if (this.#response) return this.#response.ok;
2246
+ const status = this.status;
2247
+ return status >= 200 && status < 300;
2248
+ }
2249
+ get _response() {
2250
+ if (this.#response) return this.#response;
2251
+ let body = this.#body;
2252
+ if (body && typeof body.pipe === "function" && !(body instanceof Readable)) {
2253
+ const stream = new PassThrough();
2254
+ body.pipe(stream);
2255
+ const abort = body.abort;
2256
+ if (abort) stream.once("close", () => abort());
2257
+ body = stream;
2258
+ }
2259
+ if (typeof body === "string") this.#contentLength = Buffer.byteLength(body);
2260
+ else if (body instanceof ArrayBuffer || body instanceof Uint8Array || body instanceof DataView) this.#contentLength = body.byteLength;
2261
+ else if (body instanceof Blob) this.#contentLength = body.size;
2262
+ this.#response = new NativeResponse(body, this.#headers ? {
2263
+ ...this.#init,
2264
+ headers: this.#headers
2265
+ } : this.#init);
2266
+ this.#init = void 0;
2267
+ this.#headers = void 0;
2268
+ this.#body = void 0;
2269
+ return this.#response;
2270
+ }
2271
+ _toNodeResponse() {
2272
+ const status = this.status;
2273
+ const statusText = this.statusText;
2274
+ let body;
2275
+ let contentType;
2276
+ let contentLength;
2277
+ if (this.#response) {
2278
+ body = this.#response.body;
2279
+ if (!this.#response.bodyUsed) contentLength = this.#contentLength;
2280
+ } else if (this.#body != null) {
2281
+ if (this.#body instanceof ReadableStream) body = this.#body;
2282
+ else if (typeof this.#body === "string") {
2283
+ body = this.#body;
2284
+ contentType = "text/plain; charset=UTF-8";
2285
+ contentLength = Buffer.byteLength(this.#body);
2286
+ } else if (this.#body instanceof ArrayBuffer) {
2287
+ body = Buffer.from(this.#body);
2288
+ contentLength = this.#body.byteLength;
2289
+ } else if (this.#body instanceof Uint8Array) {
2290
+ body = this.#body;
2291
+ contentLength = this.#body.byteLength;
2292
+ } else if (this.#body instanceof DataView) {
2293
+ body = Buffer.from(this.#body.buffer, this.#body.byteOffset, this.#body.byteLength);
2294
+ contentLength = this.#body.byteLength;
2295
+ } else if (this.#body instanceof Blob) {
2296
+ body = this.#body.stream();
2297
+ contentType = this.#body.type;
2298
+ contentLength = this.#body.size;
2299
+ } else if (typeof this.#body.pipe === "function") body = this.#body;
2300
+ else body = this._response.body;
2301
+ }
2302
+ const headers = [];
2303
+ const initHeaders = this.#init?.headers;
2304
+ const headerEntries = this.#response?.headers || this.#headers || (initHeaders ? Array.isArray(initHeaders) ? initHeaders : initHeaders?.entries ? initHeaders.entries() : Object.entries(initHeaders) : void 0);
2305
+ let hasContentTypeHeader;
2306
+ let hasContentLength;
2307
+ if (headerEntries) for (const [key, value] of headerEntries) {
2308
+ const lowerKey = typeof key === "string" ? key.toLowerCase() : String(key);
2309
+ if (Array.isArray(value)) for (const v of value) headers.push(lowerKey, v);
2310
+ else headers.push(lowerKey, value);
2311
+ if (lowerKey === "content-type") hasContentTypeHeader = true;
2312
+ else if (lowerKey === "content-length") hasContentLength = true;
2313
+ }
2314
+ if (contentType && !hasContentTypeHeader) headers.push("content-type", contentType);
2315
+ if (contentLength != null && !hasContentLength) headers.push("content-length", String(contentLength));
2316
+ this.#init = void 0;
2317
+ this.#headers = void 0;
2318
+ this.#response = void 0;
2319
+ this.#contentLength = void 0;
2320
+ this.#body = void 0;
2321
+ return {
2322
+ status,
2323
+ statusText,
2324
+ headers,
2325
+ body
2326
+ };
2327
+ }
2328
+ }
2329
+ lazyInherit(NodeResponse2.prototype, NativeResponse.prototype, "_response");
2330
+ Object.setPrototypeOf(NodeResponse2, NativeResponse);
2331
+ Object.setPrototypeOf(NodeResponse2.prototype, NativeResponse.prototype);
2332
+ return NodeResponse2;
2333
+ })();
2334
+ function toNodeHandler(handler, options) {
2335
+ if (handler.__nodeHandler) return handler.__nodeHandler;
2336
+ function convertedNodeHandler(nodeReq, nodeRes) {
2337
+ const res = handler(new NodeRequest({
2338
+ req: nodeReq,
2339
+ res: nodeRes,
2340
+ maxRequestBodySize: options?.maxRequestBodySize,
2341
+ trustProxy: options?.trustProxy
2342
+ }));
2343
+ return typeof res?.then === "function" ? res.then((resolvedRes) => send(nodeRes, resolvedRes)) : send(nodeRes, res);
2344
+ }
2345
+ convertedNodeHandler.__fetchHandler = handler;
2346
+ assignFnName(convertedNodeHandler, handler, " (converted to Node handler)");
2347
+ return convertedNodeHandler;
2348
+ }
2349
+ function send(nodeRes, webRes) {
2350
+ return sendNodeResponse(nodeRes, webRes).catch((error) => handleSendError(nodeRes, error));
2351
+ }
2352
+ function assignFnName(target, source, suffix) {
2353
+ if (source.name) try {
2354
+ Object.defineProperty(target, "name", { value: `${source.name}${suffix}` });
2355
+ } catch {
2356
+ }
2357
+ }
2358
+
2359
+ // ../node_modules/.pnpm/h3@2.0.8/node_modules/h3/dist/response.mjs
2360
+ function stripBase(pathname, base) {
2361
+ if (pathname === base || pathname.startsWith(base + "/") || pathname.startsWith(base + "?")) return "/" + pathname.slice(base.length).replace(/^\/+/, "");
2362
+ return pathname;
2363
+ }
2364
+ function hasEmptySegmentAfterBase(pathname, base) {
2365
+ return pathname.startsWith(base + "//");
2366
+ }
2367
+ var NEEDLESS_ESCAPE_SRC = String.raw`%(?:2[146-9A-E]|3[0-9ABD]|4[0-9A-F]|5[0-9ABDF]|6[1-9A-F]|7[0-9ACE])`;
2368
+ var NEEDLESS_ESCAPE_RE = /* @__PURE__ */ new RegExp(NEEDLESS_ESCAPE_SRC, "i");
2369
+ var NEEDLESS_ESCAPE_RE_G = /* @__PURE__ */ new RegExp(NEEDLESS_ESCAPE_SRC, "gi");
2370
+ function isNonCanonicalPathname(pathname) {
2371
+ return NEEDLESS_ESCAPE_RE.test(pathname);
2372
+ }
2373
+ function canonicalPathname(pathname) {
2374
+ return pathname.replace(NEEDLESS_ESCAPE_RE_G, (m) => String.fromCharCode(Number.parseInt(m.slice(1), 16)));
2375
+ }
2376
+ var ABSOLUTE_URL_RE = /^[a-z][a-z\d+\-.]*:\/\//i;
2377
+ var ROUTE_ENCODE_RE = /[\u0000-\u0020"#<>\u0060]|[^\u0000-\u007E]/gu;
2378
+ function normalizeRoute(route) {
2379
+ if (ABSOLUTE_URL_RE.test(route)) throw new Error(`Route patterns are pathnames, received URL: ${route}`);
2380
+ if (route.charCodeAt(0) !== 47) route = `/${route}`;
2381
+ route = canonicalPathname(route.replace(ROUTE_ENCODE_RE, encodeURIComponent));
2382
+ return route.includes("/.") ? resolveDotSegments(route) : route;
2383
+ }
2384
+ function resolveDotSegments(pathname) {
2385
+ const out = [];
2386
+ let dot = false;
2387
+ for (const segment of pathname.split("/")) {
2388
+ dot = segment === "." || segment === "..";
2389
+ if (!dot) out.push(segment);
2390
+ else if (segment.length === 2 && out.length > 1) out.pop();
2391
+ }
2392
+ if (dot) out.push("");
2393
+ return out.join("/");
2394
+ }
2395
+ function decodePathname(pathname) {
2396
+ try {
2397
+ return decodeURI(pathname);
2398
+ } catch {
2399
+ return;
2400
+ }
2401
+ }
2402
+ var kEventNS = "h3.internal.event.";
2403
+ var kEventRes = /* @__PURE__ */ Symbol.for(`${kEventNS}res`);
2404
+ var kEventResHeaders = /* @__PURE__ */ Symbol.for(`${kEventNS}res.headers`);
2405
+ var kEventResErrHeaders = /* @__PURE__ */ Symbol.for(`${kEventNS}res.err.headers`);
2406
+ var kMalformedURL = /* @__PURE__ */ Symbol.for(`${kEventNS}malformed`);
2407
+ var H3Event = class {
2408
+ app;
2409
+ req;
2410
+ url;
2411
+ context;
2412
+ static __is_event__ = true;
2413
+ constructor(req, context, app) {
2414
+ this.context = req.context = context || req.context || new NullProtoObj();
2415
+ this.req = req;
2416
+ this.app = app;
2417
+ const _url = req._url;
2418
+ let url = _url && _url instanceof URL ? _url : new FastURL(req.url);
2419
+ const pathname = url.pathname;
2420
+ if (pathname.includes("%")) {
2421
+ if (decodePathname(pathname) === void 0) this[kMalformedURL] = true;
2422
+ else if (isNonCanonicalPathname(pathname)) url = new FastURL(`${url.protocol}//${url.host}${canonicalPathname(pathname)}${url.search}`);
2423
+ }
2424
+ this.url = url;
2425
+ }
2426
+ get res() {
2427
+ return this[kEventRes] ||= new H3EventResponse();
2428
+ }
2429
+ get runtime() {
2430
+ return this.req.runtime;
2431
+ }
2432
+ waitUntil(promise) {
2433
+ this.req.waitUntil?.(promise);
2434
+ }
2435
+ toString() {
2436
+ return `[${this.req.method}] ${this.req.url}`;
2437
+ }
2438
+ toJSON() {
2439
+ return this.toString();
2440
+ }
2441
+ get node() {
2442
+ return this.req.runtime?.node;
2443
+ }
2444
+ get headers() {
2445
+ return this.req.headers;
2446
+ }
2447
+ get path() {
2448
+ return this.url.pathname + this.url.search;
2449
+ }
2450
+ get method() {
2451
+ return this.req.method;
2452
+ }
2453
+ };
2454
+ var H3EventResponse = class {
2455
+ status;
2456
+ statusText;
2457
+ get headers() {
2458
+ return this[kEventResHeaders] ||= new Headers();
2459
+ }
2460
+ get errHeaders() {
2461
+ return this[kEventResErrHeaders] ||= new Headers();
2462
+ }
2463
+ };
2464
+ var DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
2465
+ function sanitizeStatusMessage(statusMessage = "") {
2466
+ return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
2467
+ }
2468
+ function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
2469
+ if (!statusCode) return defaultStatusCode;
2470
+ if (typeof statusCode === "string") statusCode = +statusCode;
2471
+ if (!Number.isInteger(statusCode) || statusCode < 100 || statusCode > 599) return defaultStatusCode;
2472
+ return statusCode;
2473
+ }
2474
+ var HTTPError = class HTTPError2 extends Error {
2475
+ get name() {
2476
+ return "HTTPError";
2477
+ }
2478
+ status;
2479
+ statusText;
2480
+ headers;
2481
+ cause;
2482
+ data;
2483
+ body;
2484
+ unhandled;
2485
+ static isError(input) {
2486
+ return input instanceof Error && input?.name === "HTTPError" && input.status > 99;
2487
+ }
2488
+ static status(status, statusText, details) {
2489
+ return new HTTPError2({
2490
+ ...details,
2491
+ statusText,
2492
+ status
2493
+ });
2494
+ }
2495
+ constructor(arg1, arg2) {
2496
+ let messageInput;
2497
+ let details;
2498
+ if (typeof arg1 === "string") {
2499
+ messageInput = arg1;
2500
+ details = arg2;
2501
+ } else details = arg1;
2502
+ const status = sanitizeStatusCode(details?.status || details?.statusCode || details?.cause?.status || details?.cause?.statusCode, 500);
2503
+ const statusText = sanitizeStatusMessage(details?.statusText || details?.statusMessage || details?.cause?.statusText || details?.cause?.statusMessage);
2504
+ const message = messageInput || details?.message || details?.cause?.message || details?.statusText || details?.statusMessage || [
2505
+ "HTTPError",
2506
+ status,
2507
+ statusText
2508
+ ].filter(Boolean).join(" ");
2509
+ super(message, { cause: details });
2510
+ this.cause = details;
2511
+ this.status = status;
2512
+ this.statusText = statusText || void 0;
2513
+ const rawHeaders = details?.headers || details?.cause?.headers;
2514
+ this.headers = rawHeaders ? new Headers(rawHeaders) : void 0;
2515
+ this.unhandled = details?.unhandled ?? details?.cause?.unhandled ?? void 0;
2516
+ this.data = details?.data;
2517
+ this.body = details?.body;
2518
+ }
2519
+ get statusCode() {
2520
+ return this.status;
2521
+ }
2522
+ get statusMessage() {
2523
+ return this.statusText;
2524
+ }
2525
+ toJSON() {
2526
+ const unhandled = this.unhandled;
2527
+ return {
2528
+ status: this.status,
2529
+ statusText: this.statusText,
2530
+ unhandled,
2531
+ message: unhandled ? "HTTPError" : this.message,
2532
+ data: unhandled ? void 0 : this.data,
2533
+ ...unhandled ? void 0 : this.body
2534
+ };
2535
+ }
2536
+ };
2537
+ function hasProp(obj, prop) {
2538
+ try {
2539
+ return prop in obj;
2540
+ } catch {
2541
+ return false;
2542
+ }
2543
+ }
2544
+ function isJSONSerializable(value, _type) {
2545
+ if (value === null || value === void 0) return true;
2546
+ if (_type !== "object") return _type === "boolean" || _type === "number" || _type === "string";
2547
+ if (typeof value.toJSON === "function") return true;
2548
+ if (Array.isArray(value)) return true;
2549
+ if (typeof value.pipe === "function" || typeof value.pipeTo === "function") return false;
2550
+ if (value instanceof NullProtoObj) return true;
2551
+ const proto = Object.getPrototypeOf(value);
2552
+ return proto === Object.prototype || proto === null;
2553
+ }
2554
+ var kEventDispose = /* @__PURE__ */ Symbol.for("h3.internal.event.dispose");
2555
+ var kNotFound = /* @__PURE__ */ Symbol.for("h3.notFound");
2556
+ var kHandled = /* @__PURE__ */ Symbol.for("h3.handled");
2557
+ function toResponse(val, event, config = {}) {
2558
+ if (typeof val?.then === "function") return val.then((resolvedVal) => toResponse(resolvedVal, event, config), (r) => toResponse(toError(r), event, config));
2559
+ let response;
2560
+ try {
2561
+ response = prepareResponse(val, event, config);
2562
+ } catch (error) {
2563
+ return toResponse(toError(error), event, config);
2564
+ }
2565
+ if (typeof response?.then === "function") return toResponse(response, event, config);
2566
+ const { onResponse: onResponse2 } = config;
2567
+ if (onResponse2) return Promise.resolve().then(() => onResponse2(response, event)).catch((error) => {
2568
+ if (!config.silent) console.error(error);
2569
+ }).then(() => event[kEventDispose]?.observe(response, val) ?? response);
2570
+ return event[kEventDispose]?.observe(response, val) ?? response;
2571
+ }
2572
+ function toError(value) {
2573
+ if (value === kNotFound || value === kHandled || value instanceof Error) return value;
2574
+ if (typeof value === "number") return new HTTPError({ status: value });
2575
+ const error = new HTTPError({
2576
+ status: 500,
2577
+ unhandled: true
2578
+ });
2579
+ error.cause = value;
2580
+ return error;
2581
+ }
2582
+ var kHTTPResponse = /* @__PURE__ */ Symbol.for("h3.HTTPResponse");
2583
+ var HTTPResponse = class {
2584
+ #headers;
2585
+ #init;
2586
+ body;
2587
+ constructor(body, init) {
2588
+ this.body = body;
2589
+ this.#init = init;
2590
+ }
2591
+ get status() {
2592
+ return this.#init?.status;
2593
+ }
2594
+ get statusText() {
2595
+ return this.#init?.statusText;
2596
+ }
2597
+ get headers() {
2598
+ return this.#headers ||= new Headers(this.#init?.headers);
2599
+ }
2600
+ };
2601
+ HTTPResponse.prototype[kHTTPResponse] = true;
2602
+ function prepareResponse(val, event, config, nested) {
2603
+ if (val === kHandled) return new NodeResponse(null);
2604
+ if (val === kNotFound) val = new HTTPError({
2605
+ status: 404,
2606
+ message: `Cannot find any route matching [${event.req.method}] ${event.url}`
2607
+ });
2608
+ if (val && val instanceof Error) {
2609
+ const isHTTPError = HTTPError.isError(val);
2610
+ const error = isHTTPError ? val : new HTTPError(val);
2611
+ if (!isHTTPError) {
2612
+ error.unhandled = true;
2613
+ if (val?.stack) error.stack = val.stack;
2614
+ }
2615
+ if (error.unhandled && !config.silent) console.error(error);
2616
+ const { onError: onError2 } = config;
2617
+ const errHeaders = event[kEventRes]?.[kEventResErrHeaders];
2618
+ if (onError2 && !nested) return Promise.resolve().then(() => onError2(error, event)).catch(toError).then((newVal) => prepareResponse(newVal ?? val, event, config, true));
2619
+ event[kEventRes] = void 0;
2620
+ val = errorResponse(error, config.debug, errHeaders);
2621
+ }
2622
+ const preparedRes = event[kEventRes];
2623
+ let preparedHeaders = preparedRes?.[kEventResHeaders];
2624
+ event[kEventRes] = void 0;
2625
+ if (!(val instanceof Response)) {
2626
+ const res = prepareResponseBody(val, event, config);
2627
+ const rawStatus = res.status || preparedRes?.status;
2628
+ const status = rawStatus ? sanitizeStatusCode(rawStatus) : void 0;
2629
+ const rawStatusText = res.statusText || preparedRes?.statusText;
2630
+ return new NodeResponse(nullBody(event.req.method, status) ? null : res.body, {
2631
+ status,
2632
+ statusText: rawStatusText === void 0 ? void 0 : sanitizeStatusMessage(rawStatusText),
2633
+ headers: res.headers && preparedHeaders ? mergeHeaders(res.headers, preparedHeaders) : res.headers || preparedHeaders
2634
+ });
2635
+ }
2636
+ if (val.status >= 400) preparedHeaders = preparedRes?.[kEventResErrHeaders];
2637
+ if (preparedHeaders && !nested && !preparedHeaders.keys().next().done) return new NodeResponse(nullBody(event.req.method, val.status) ? null : val.body, {
2638
+ status: val.status,
2639
+ statusText: val.statusText,
2640
+ headers: mergeHeaders(val.headers, preparedHeaders)
2641
+ });
2642
+ return event.req.method === "HEAD" && val.body !== null ? new NodeResponse(null, {
2643
+ status: val.status,
2644
+ statusText: val.statusText,
2645
+ headers: val.headers
2646
+ }) : val;
2647
+ }
2648
+ function mergeHeaders(base, overrides, target = new Headers(base)) {
2649
+ for (const [name, value] of overrides) if (name === "set-cookie") target.append(name, value);
2650
+ else target.set(name, value);
2651
+ return target;
2652
+ }
2653
+ var frozen = (name) => (...args) => {
2654
+ throw new Error(`Headers are frozen (${name} ${args.join(", ")})`);
2655
+ };
2656
+ var FrozenHeaders = class extends Headers {
2657
+ set = frozen("set");
2658
+ append = frozen("append");
2659
+ delete = frozen("delete");
2660
+ };
2661
+ var emptyHeaders = /* @__PURE__ */ new FrozenHeaders({ "content-length": "0" });
2662
+ var jsonHeaders = /* @__PURE__ */ new FrozenHeaders({ "content-type": "application/json;charset=UTF-8" });
2663
+ function prepareResponseBody(val, event, config) {
2664
+ if (val === null || val === void 0) return {
2665
+ body: "",
2666
+ headers: emptyHeaders
2667
+ };
2668
+ const valType = typeof val;
2669
+ if (valType === "string") return { body: val };
2670
+ if (val instanceof Uint8Array) return {
2671
+ body: val,
2672
+ headers: new Headers({ "content-length": val.byteLength.toString() })
2673
+ };
2674
+ if (val instanceof HTTPResponse || val?.[kHTTPResponse] === true) return val;
2675
+ if (isJSONSerializable(val, valType)) return {
2676
+ body: JSON.stringify(val, void 0, config.debug ? 2 : void 0),
2677
+ headers: jsonHeaders
2678
+ };
2679
+ if (valType === "bigint") return {
2680
+ body: val.toString(),
2681
+ headers: jsonHeaders
2682
+ };
2683
+ if (val instanceof Blob) {
2684
+ const headers = new Headers({
2685
+ "content-type": val.type,
2686
+ "content-length": val.size.toString()
2687
+ });
2688
+ let filename = val.name;
2689
+ if (filename) {
2690
+ filename = encodeURIComponent(filename);
2691
+ headers.set("content-disposition", `filename="${filename}"; filename*=UTF-8''${filename}`);
2692
+ }
2693
+ return {
2694
+ body: val.stream(),
2695
+ headers
2696
+ };
2697
+ }
2698
+ if (valType === "symbol") return { body: val.toString() };
2699
+ if (valType === "function") return { body: `${val.name}()` };
2700
+ return { body: val };
2701
+ }
2702
+ function nullBody(method, status) {
2703
+ return method === "HEAD" || status === 100 || status === 101 || status === 102 || status === 204 || status === 205 || status === 304;
2704
+ }
2705
+ function errorResponse(error, debug, errHeaders) {
2706
+ let headers = error.headers ? mergeHeaders(jsonHeaders, error.headers) : new Headers(jsonHeaders);
2707
+ if (errHeaders) headers = mergeHeaders(headers, errHeaders);
2708
+ return new NodeResponse(JSON.stringify({
2709
+ ...error.toJSON(),
2710
+ stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : void 0
2711
+ }, void 0, debug ? 2 : void 0), {
2712
+ status: error.status,
2713
+ statusText: error.statusText,
2714
+ headers
2715
+ });
2716
+ }
2717
+
2718
+ // ../node_modules/.pnpm/h3@2.0.8/node_modules/h3/dist/middleware.mjs
2719
+ var LITERAL_ROUTE_RE = /^(?:\/[^/:*(){}\\?^\0- "#<>`\x7F-\uFFFF]+)*\/?$/;
2720
+ var LITERAL_PREFIX_ROUTE_RE = /^((?:\/[^/:*(){}\\?^\0- "#<>`\x7F-\uFFFF]+)*)\/\*\*\/?$/;
2721
+ function createRouteMatcher(route) {
2722
+ if (route.charCodeAt(0) !== 47) route = `/${route}`;
2723
+ const prefixMatch = LITERAL_PREFIX_ROUTE_RE.exec(route);
2724
+ if (prefixMatch) {
2725
+ const base = prefixMatch[1];
2726
+ const prefix = `${base}/`;
2727
+ return (pathname) => {
2728
+ if (pathname === base || pathname === prefix) return;
2729
+ if (!pathname.startsWith(prefix)) return false;
2730
+ const rest = trimTrailingSlash(pathname.slice(prefix.length));
2731
+ return {
2732
+ 0: rest,
2733
+ _: rest
2734
+ };
2735
+ };
2736
+ }
2737
+ if (LITERAL_ROUTE_RE.test(route)) {
2738
+ const base = route.endsWith("/") ? route.slice(0, -1) : route;
2739
+ return (pathname) => pathname === base || pathname === `${base}/` ? void 0 : false;
2740
+ }
2741
+ const router = createRouter();
2742
+ addRoute(router, "", route, true);
2743
+ return (pathname) => {
2744
+ const match = findRoute(router, "", pathname);
2745
+ return match ? match.params : false;
2746
+ };
2747
+ }
2748
+ function trimTrailingSlash(rest) {
2749
+ return rest.endsWith("/") ? rest.slice(0, -1) : rest;
2750
+ }
2751
+ function normalizeMiddleware(input, opts = {}) {
2752
+ const matcher = createMatcher(opts);
2753
+ if (!matcher && (input.length > 1 || input.constructor?.name === "AsyncFunction")) return input;
2754
+ return (event, next) => {
2755
+ if (matcher && !matcher(event)) return next();
2756
+ const res = input(event, next);
2757
+ return res === void 0 || res === kNotFound ? next() : res;
2758
+ };
2759
+ }
2760
+ function createMatcher(opts) {
2761
+ if (!opts.route && !opts.method && !opts.match) return;
2762
+ const routeMatcher = opts.route ? createRouteMatcher(normalizeRoute(opts.route)) : void 0;
2763
+ const method = opts.method?.toUpperCase();
2764
+ return function _middlewareMatcher(event) {
2765
+ if (method) {
2766
+ const reqMethod = event.req.method.toUpperCase();
2767
+ if (reqMethod !== method && !(method === "GET" && reqMethod === "HEAD")) return false;
2768
+ }
2769
+ if (opts.match && !opts.match(event)) return false;
2770
+ if (!routeMatcher) return true;
2771
+ const params = routeMatcher(event.url.pathname);
2772
+ if (params === false) return false;
2773
+ if (params) event.context.middlewareParams = {
2774
+ ...event.context.middlewareParams,
2775
+ ...params
2776
+ };
2777
+ return true;
2778
+ };
2779
+ }
2780
+ function composeMiddleware(middleware) {
2781
+ let chain = (event, handler) => handler(event);
2782
+ for (let i = middleware.length - 1; i >= 0; i--) {
2783
+ const fn = middleware[i];
2784
+ const inner = chain;
2785
+ chain = (event, handler) => callLayer(fn, event, handler, inner);
2786
+ }
2787
+ return chain;
2788
+ }
2789
+ function composeHandler(middleware, handler) {
2790
+ const chain = composeMiddleware(middleware);
2791
+ return function _composedHandler(event) {
2792
+ return chain(event, handler);
2793
+ };
2794
+ }
2795
+ function callMiddleware(event, middleware, handler, index = 0) {
2796
+ return index === middleware.length ? handler(event) : callLayer(middleware[index], event, handler, (_event, _handler) => callMiddleware(_event, middleware, _handler, index + 1));
2797
+ }
2798
+ function callLayer(fn, event, handler, inner) {
2799
+ let nextCalled;
2800
+ let nextResult;
2801
+ const next = () => {
2802
+ if (nextCalled) return nextResult;
2803
+ nextCalled = true;
2804
+ nextResult = inner(event, handler);
2805
+ return nextResult;
2806
+ };
2807
+ const ret = fn(event, next);
2808
+ return isUnhandledResponse(ret) ? next() : typeof ret?.then === "function" ? ret.then((resolved) => isUnhandledResponse(resolved) ? next() : resolved) : ret;
2809
+ }
2810
+ function isUnhandledResponse(val) {
2811
+ return val === void 0 || val === kNotFound;
2812
+ }
2813
+
2814
+ // ../node_modules/.pnpm/h3@2.0.8/node_modules/h3/dist/cache.mjs
2815
+ function requestWithURL(req, url) {
2816
+ const cache = new NullProtoObj();
2817
+ cache.url = url;
2818
+ cache._url = void 0;
2819
+ return new Proxy(req, {
2820
+ get(target, prop) {
2821
+ if (prop in cache) return cache[prop];
2822
+ const value = Reflect.get(target, prop);
2823
+ if (prop === "bodyUsed") return value;
2824
+ cache[prop] = typeof value === "function" && prop !== "constructor" ? value.bind(target) : value;
2825
+ return cache[prop];
2826
+ },
2827
+ set(target, prop, value) {
2828
+ if (prop !== "url" && prop !== "_url") delete cache[prop];
2829
+ return Reflect.set(target, prop, value);
2830
+ }
2831
+ });
2832
+ }
2833
+ function requestWithBaseURL(req, base, options = {}) {
2834
+ const url = new URL(options.url || req.url);
2835
+ url.pathname = stripBase(url.pathname, base);
2836
+ return requestWithURL(req, url.href);
2837
+ }
2838
+ function toRequest(input, options) {
2839
+ if (typeof input === "string") {
2840
+ let url = input;
2841
+ if (url[0] === "/") url = `http://${safeHost((options?.headers ? new Headers(options.headers) : void 0)?.get("host"))}${url}`;
2842
+ return new Request(url, options);
2843
+ } else if (options || input instanceof URL) return new Request(input, options);
2844
+ return input;
2845
+ }
2846
+ function safeHost(host) {
2847
+ return host && !/[/\\?#@\s]/.test(host) ? host : "localhost";
2848
+ }
2849
+ function toEventHandler(handler) {
2850
+ if (typeof handler === "function") return handler;
2851
+ if (typeof handler?.handler === "function" && handler.constructor?.["~h3"]) return handler.handler;
2852
+ if (typeof handler?.fetch === "function") return function _fetchHandler(event) {
2853
+ return handler.fetch(event.req);
2854
+ };
2855
+ }
2856
+ var NoHandler = () => kNotFound;
2857
+ var H3Core = class {
2858
+ static "~h3" = true;
2859
+ config;
2860
+ "~middleware";
2861
+ "~routes" = [];
2862
+ "~dispatch";
2863
+ "~composed";
2864
+ constructor(config = {}) {
2865
+ this["~middleware"] = [];
2866
+ this.config = config;
2867
+ this.fetch = this.fetch.bind(this);
2868
+ this.handler = this.handler.bind(this);
2869
+ }
2870
+ fetch(request) {
2871
+ return this["~request"](request);
2872
+ }
2873
+ handler(event) {
2874
+ const route = this["~findRoute"](event);
2875
+ if (route) {
2876
+ event.context.params = route.params;
2877
+ event.context.matchedRoute = route.data;
2878
+ }
2879
+ return (this["~dispatch"] ??= createDispatcher(this))(event, route);
2880
+ }
2881
+ "~request"(request, context) {
2882
+ const event = new H3Event(request, context, this);
2883
+ let handlerRes;
2884
+ try {
2885
+ if (event[kMalformedURL] && !this.config.allowMalformedURL) throw new HTTPError({
2886
+ status: 400,
2887
+ message: "Bad Request"
2888
+ });
2889
+ if (this.config.onRequest) {
2890
+ const hookRes = this.config.onRequest(event);
2891
+ handlerRes = typeof hookRes?.then === "function" ? hookRes.then(() => this.handler(event)) : this.handler(event);
2892
+ } else handlerRes = this.handler(event);
2893
+ } catch (error) {
2894
+ handlerRes = Promise.reject(error);
2895
+ }
2896
+ return toResponse(handlerRes, event, this.config);
2897
+ }
2898
+ "~findRoute"(_event) {
2899
+ }
2900
+ "~addRoute"(_route) {
2901
+ this["~routes"].push(_route);
2902
+ }
2903
+ "~getMiddleware"(_event, _route) {
2904
+ return this["~middleware"];
2905
+ }
2906
+ };
2907
+ function createDispatcher(app) {
2908
+ if (app["~getMiddleware"] !== H3Core.prototype["~getMiddleware"]) return (event, route) => callMiddleware(event, app["~getMiddleware"](event, route || void 0), routeHandler(route));
2909
+ const middleware = app["~middleware"];
2910
+ if (middleware.length === 0) return (event, route) => routeHandler(route)(event);
2911
+ const composed = app["~composed"] ??= composeMiddleware(middleware);
2912
+ return (event, route) => composed(event, routeHandler(route));
2913
+ }
2914
+ function routeHandler(route) {
2915
+ const data = route?.data;
2916
+ if (!data) return NoHandler;
2917
+ return data.middleware?.length ? data["~composed"] ??= composeHandler(data.middleware, data.handler) : data.handler;
2918
+ }
2919
+ var H3 = /* @__PURE__ */ (() => {
2920
+ class H32 extends H3Core {
2921
+ "~rou3";
2922
+ constructor(config = {}) {
2923
+ super(config);
2924
+ this["~rou3"] = createRouter();
2925
+ this.request = this.request.bind(this);
2926
+ config.plugins?.forEach((plugin) => plugin(this));
2927
+ }
2928
+ register(plugin) {
2929
+ plugin(this);
2930
+ return this;
2931
+ }
2932
+ request(_req, _init, context) {
2933
+ return this["~request"](toRequest(_req, _init), context);
2934
+ }
2935
+ mount(base, input) {
2936
+ base = !base || base === "/" ? "" : normalizeRoute(base).replace(/\/$/, "");
2937
+ if ("handler" in input) {
2938
+ if (input["~middleware"].length > 0) {
2939
+ this["~middleware"].push((event, next) => {
2940
+ const originalPathname = event.url.pathname;
2941
+ if (!originalPathname.startsWith(base) || originalPathname.length > base.length && originalPathname[base.length] !== "/") return next();
2942
+ if (hasEmptySegmentAfterBase(originalPathname, base)) throw new HTTPError({ status: 404 });
2943
+ event.url.pathname = stripBase(originalPathname, base);
2944
+ const restore = () => {
2945
+ event.url.pathname = originalPathname;
2946
+ };
2947
+ try {
2948
+ const result = (input["~composed"] ??= composeMiddleware(input["~middleware"]))(event, () => {
2949
+ restore();
2950
+ return next();
2951
+ });
2952
+ if (typeof result?.then === "function") return Promise.resolve(result).finally(restore);
2953
+ restore();
2954
+ return result;
2955
+ } catch (err) {
2956
+ restore();
2957
+ throw err;
2958
+ }
2959
+ });
2960
+ this["~dispatch"] = this["~composed"] = void 0;
2961
+ }
2962
+ for (const r of input["~routes"]) this["~addRoute"]({
2963
+ ...r,
2964
+ route: base + r.route
2965
+ });
2966
+ } else {
2967
+ const fetchHandler = "fetch" in input ? input.fetch : input;
2968
+ this.all(`${base}/**`, function _mountedMiddleware(event) {
2969
+ if (hasEmptySegmentAfterBase(event.url.pathname, base)) throw new HTTPError({ status: 404 });
2970
+ return fetchHandler(requestWithBaseURL(event.req, base, { url: event.url }));
2971
+ });
2972
+ }
2973
+ return this;
2974
+ }
2975
+ on(method, route, handler, opts) {
2976
+ const _method = (method || "").toUpperCase();
2977
+ route = normalizeRoute(route);
2978
+ this["~addRoute"]({
2979
+ method: _method,
2980
+ route,
2981
+ handler: toEventHandler(handler),
2982
+ middleware: opts?.middleware,
2983
+ meta: {
2984
+ ...handler.meta,
2985
+ ...opts?.meta
2986
+ }
2987
+ });
2988
+ return this;
2989
+ }
2990
+ all(route, handler, opts) {
2991
+ return this.on("", route, handler, opts);
2992
+ }
2993
+ "~findRoute"(_event) {
2994
+ const match = findRoute(this["~rou3"], _event.req.method, _event.url.pathname);
2995
+ if (match === void 0 && _event.req.method === "HEAD") return findRoute(this["~rou3"], "GET", _event.url.pathname);
2996
+ return match;
2997
+ }
2998
+ "~addRoute"(_route) {
2999
+ addRoute(this["~rou3"], _route.method, _route.route, _route);
3000
+ super["~addRoute"](_route);
3001
+ }
3002
+ use(arg1, arg2, arg3) {
3003
+ let route;
3004
+ let fn;
3005
+ let opts;
3006
+ if (typeof arg1 === "string") {
3007
+ route = arg1;
3008
+ fn = arg2;
3009
+ opts = arg3;
3010
+ } else {
3011
+ fn = arg1;
3012
+ opts = arg2;
3013
+ }
3014
+ if (typeof fn !== "function" && "handler" in fn) return this.mount(route || "", fn);
3015
+ this["~middleware"].push(normalizeMiddleware(fn, {
3016
+ ...opts,
3017
+ route
3018
+ }));
3019
+ this["~dispatch"] = this["~composed"] = void 0;
3020
+ return this;
3021
+ }
3022
+ }
3023
+ for (const method of [
3024
+ "GET",
3025
+ "POST",
3026
+ "PUT",
3027
+ "DELETE",
3028
+ "PATCH",
3029
+ "HEAD",
3030
+ "OPTIONS",
3031
+ "CONNECT",
3032
+ "TRACE",
3033
+ "QUERY"
3034
+ ]) H3Core.prototype[method.toLowerCase()] = function(route, handler, opts) {
3035
+ return this.on(method, route, handler, opts);
3036
+ };
3037
+ return H32;
3038
+ })();
3039
+
3040
+ // ../node_modules/.pnpm/h3@2.0.8/node_modules/h3/dist/h3.mjs
3041
+ function parseURLEncodedBody(body) {
3042
+ return collectEntries(new URLSearchParams(body).entries());
3043
+ }
3044
+ function parseFormData(form) {
3045
+ return collectEntries(form.entries());
3046
+ }
3047
+ function collectEntries(entries) {
3048
+ const parsed = new NullProtoObj();
3049
+ for (const [key, value] of entries) if (hasProp(parsed, key)) {
3050
+ if (!Array.isArray(parsed[key])) parsed[key] = [parsed[key]];
3051
+ parsed[key].push(value);
3052
+ } else parsed[key] = value;
3053
+ return parsed;
3054
+ }
3055
+ async function readBody2(event, options) {
3056
+ const contentType = (event.req.headers.get("content-type") || "").toLowerCase();
3057
+ const type = options?.type;
3058
+ if (type === "formData") {
3059
+ let form;
3060
+ try {
3061
+ form = await event.req.formData();
3062
+ } catch (error) {
3063
+ if (HTTPError.isError(error)) throw error;
3064
+ throw new HTTPError({
3065
+ status: 400,
3066
+ statusText: "Bad Request",
3067
+ message: "Invalid form data body"
3068
+ });
3069
+ }
3070
+ return parseFormData(form);
3071
+ }
3072
+ const text2 = await event.req.text();
3073
+ if (type === "text") return text2;
3074
+ if (!text2) return;
3075
+ if (type === "urlencoded" || !type && contentType.startsWith("application/x-www-form-urlencoded")) return parseURLEncodedBody(text2);
3076
+ try {
3077
+ return JSON.parse(text2);
3078
+ } catch {
3079
+ throw new HTTPError({
3080
+ status: 400,
3081
+ statusText: "Bad Request",
3082
+ message: "Invalid JSON body"
3083
+ });
3084
+ }
3085
+ }
3086
+
3087
+ // ../node_modules/.pnpm/h3@2.0.8/node_modules/h3/dist/_entries/node.mjs
3088
+ function toNodeHandler2(app) {
3089
+ return toNodeHandler(app.fetch);
3090
+ }
3091
+
3092
+ // src/node/http/response.mjs
3093
+ var NO_STORE = { "cache-control": "no-store" };
3094
+ function json(body, status = 200) {
3095
+ return Response.json(body, { status, headers: NO_STORE });
3096
+ }
3097
+ function text(body, status = 200, headers = {}) {
3098
+ return new Response(body, {
3099
+ status,
3100
+ headers: { "content-type": "text/plain; charset=utf-8", ...headers }
3101
+ });
3102
+ }
3103
+ function notFound(body = "Not Found") {
3104
+ return text(body, 404, NO_STORE);
3105
+ }
3106
+
3107
+ // src/node/http/serve-static.mjs
3108
+ import { createReadStream } from "node:fs";
3109
+ import { readFile, realpath as realpath2, stat } from "node:fs/promises";
3110
+ import { extname, resolve, sep as sep2 } from "node:path";
3111
+ import { Readable as Readable2 } from "node:stream";
3112
+
3113
+ // src/node/docs/scan.mjs
3114
+ import { realpathSync } from "node:fs";
3115
+ import { readdir } from "node:fs/promises";
3116
+ import { isAbsolute, join, relative, sep } from "node:path";
3117
+ var MAX_DEPTH = 3;
3118
+ async function listHtmlFiles(docsDir) {
3119
+ const out = [];
3120
+ await walk(docsDir, docsDir, 0);
3121
+ return out;
3122
+ async function walk(dir, root, depth) {
3123
+ if (depth > MAX_DEPTH) return;
3124
+ let entries;
3125
+ try {
3126
+ entries = await readdir(dir, { withFileTypes: true });
3127
+ } catch {
3128
+ return;
3129
+ }
3130
+ for (const entry of entries) {
3131
+ const full = join(dir, entry.name);
3132
+ if (shouldIgnore(entry.name)) continue;
3133
+ if (entry.isDirectory()) {
3134
+ await walk(full, root, depth + 1);
3135
+ } else if (entry.name.endsWith(".html") && !(dir === root && entry.name === "index.html")) {
3136
+ out.push(full);
3137
+ }
3138
+ }
3139
+ }
3140
+ }
3141
+ function isWithin(base, path3) {
3142
+ const rel = relative(base, path3);
3143
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
3144
+ }
3145
+ function normalizedRelative(base, path3) {
3146
+ return relative(base, path3).split(sep).join("/");
3147
+ }
3148
+ function shouldIgnore(relPath) {
3149
+ return relPath.split(/[/\\]/).filter(Boolean).some((part) => part.startsWith(".") || part === "node_modules");
3150
+ }
3151
+ function realpath(p) {
3152
+ try {
3153
+ return realpathSync(p);
3154
+ } catch {
3155
+ return p;
3156
+ }
3157
+ }
3158
+
3159
+ // src/node/http/serve-static.mjs
3160
+ var MIME = {
3161
+ ".html": "text/html",
3162
+ ".htm": "text/html",
3163
+ ".js": "text/javascript",
3164
+ ".mjs": "text/javascript",
3165
+ ".css": "text/css",
3166
+ ".json": "application/json",
3167
+ ".txt": "text/plain",
3168
+ ".md": "text/markdown",
3169
+ ".xml": "application/xml",
3170
+ ".png": "image/png",
3171
+ ".jpg": "image/jpeg",
3172
+ ".jpeg": "image/jpeg",
3173
+ ".gif": "image/gif",
3174
+ ".svg": "image/svg+xml",
3175
+ ".webp": "image/webp",
3176
+ ".ico": "image/x-icon",
3177
+ ".pdf": "application/pdf",
3178
+ ".woff": "font/woff",
3179
+ ".woff2": "font/woff2",
3180
+ ".mp4": "video/mp4",
3181
+ ".webm": "video/webm"
3182
+ };
3183
+ function contentTypeFor(path3) {
3184
+ const type = MIME[extname(path3).toLowerCase()] || "application/octet-stream";
3185
+ return type === "text/html" ? "text/html; charset=utf-8" : type;
3186
+ }
3187
+ function createStaticHandler({ root: rootDir, indexNames = ["index.html"], headers = {}, transform }) {
3188
+ const root = resolve(rootDir);
3189
+ const realRoot = realpath2(root).catch(() => root);
3190
+ return async function serve2(request) {
3191
+ const method = request.method || "GET";
3192
+ if (method !== "GET" && method !== "HEAD") return plain("Method Not Allowed", 405);
3193
+ const url = new URL(request.url);
3194
+ let pathname;
3195
+ try {
3196
+ pathname = decodeURIComponent(url.pathname);
3197
+ } catch {
3198
+ return plain("Bad Request", 400);
3199
+ }
3200
+ if (pathname.includes("\0")) return plain("Bad Request", 400);
3201
+ const abs = resolve(root, pathname.replace(/^\/+/, ""));
3202
+ if (!isWithin(root, abs)) return plain("Forbidden", 403);
3203
+ const real = await realRoot;
3204
+ const hasSlash = pathname.endsWith("/");
3205
+ let file = await statFile(abs, real);
3206
+ if (!file) {
3207
+ const isDir = await isDirectory(abs);
3208
+ if (isDir && !hasSlash) return redirect(url);
3209
+ if (isDir || hasSlash) {
3210
+ for (const name of indexNames) {
3211
+ file = await statFile(resolve(abs, name), real);
3212
+ if (file) break;
3213
+ }
3214
+ }
3215
+ if (!file) return null;
3216
+ }
3217
+ const responseHeaders = new Headers(headers);
3218
+ responseHeaders.set("content-type", contentTypeFor(file.abs));
3219
+ responseHeaders.set("content-length", String(file.size));
3220
+ responseHeaders.set("last-modified", file.mtime.toUTCString());
3221
+ if (method === "HEAD") return new Response(null, { status: 200, headers: responseHeaders });
3222
+ const type = responseHeaders.get("content-type") || "";
3223
+ if (transform && type.startsWith("text/html")) {
3224
+ const html = transform(await readFile(file.abs, "utf8"), normalizedRelative(root, file.abs));
3225
+ responseHeaders.set("content-length", String(Buffer.byteLength(html)));
3226
+ return new Response(html, { status: 200, headers: responseHeaders });
3227
+ }
3228
+ return new Response(Readable2.toWeb(createReadStream(file.abs)), { status: 200, headers: responseHeaders });
3229
+ };
3230
+ }
3231
+ async function statFile(abs, realRoot) {
3232
+ try {
3233
+ const s = await stat(abs);
3234
+ if (!s.isFile()) return null;
3235
+ const real = await realpath2(abs);
3236
+ if (real !== realRoot && !real.startsWith(realRoot + sep2)) return null;
3237
+ return { abs, size: s.size, mtime: s.mtime };
3238
+ } catch {
3239
+ return null;
3240
+ }
3241
+ }
3242
+ async function isDirectory(abs) {
3243
+ try {
3244
+ return (await stat(abs)).isDirectory();
3245
+ } catch {
3246
+ return false;
3247
+ }
3248
+ }
3249
+ function redirect(url) {
3250
+ const location = new URL(`${url.pathname}/${url.search}`, url);
3251
+ return new Response(null, { status: 301, headers: { location: location.href } });
3252
+ }
3253
+ function plain(body, status) {
3254
+ return new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
3255
+ }
3256
+
3257
+ // src/node/http/assets.mjs
3258
+ var handlers = /* @__PURE__ */ new Map();
3259
+ function handlerFor(root) {
3260
+ let handler = handlers.get(root);
3261
+ if (!handler) {
3262
+ handler = createStaticHandler({ root, headers: { "cache-control": "no-store" } });
3263
+ handlers.set(root, handler);
3264
+ }
3265
+ return handler;
3266
+ }
3267
+ async function serveAsset(root, relative2) {
3268
+ if (!relative2) return notFound();
3269
+ const encoded = relative2.split("/").map(encodeURIComponent).join("/");
3270
+ const response = await handlerFor(root)(new Request(`http://localhost/${encoded}`));
3271
+ return response ?? notFound();
3272
+ }
3273
+
3274
+ // src/node/http/gallery.mjs
3275
+ import { readFile as readFile2 } from "node:fs/promises";
3276
+ import { join as join3 } from "node:path";
3277
+
3278
+ // src/node/docs/info.mjs
3279
+ import os from "node:os";
3280
+ import { basename } from "node:path";
3281
+ function docsInfo(docsDir) {
3282
+ return {
3283
+ name: basename(docsDir) || docsDir,
3284
+ path: displayPath(docsDir),
3285
+ hue: faviconHue(docsDir)
3286
+ };
3287
+ }
3288
+ function displayPath(p) {
3289
+ const home = os.homedir();
3290
+ return p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p;
3291
+ }
3292
+ function faviconHue(s) {
3293
+ let h = 0;
3294
+ for (let i = 0; i < s.length; i++) h = h * 31 + s.charCodeAt(i) | 0;
3295
+ return (h % 360 + 360) % 360;
3296
+ }
3297
+
3298
+ // src/node/paths.mjs
3299
+ import { join as join2 } from "node:path";
3300
+ import { fileURLToPath } from "node:url";
3301
+ var PACKAGE_ROOT = fileURLToPath(new URL("../..", import.meta.url));
3302
+ var PACKAGE_JSON = join2(PACKAGE_ROOT, "package.json");
3303
+ var GALLERY_TEMPLATE = join2(PACKAGE_ROOT, "dist", "gallery", "index.html");
3304
+ var GALLERY_DIST_DIR = join2(PACKAGE_ROOT, "dist", "gallery");
3305
+ var WIDGET_SOURCE_DIR = join2(PACKAGE_ROOT, "src", "widget");
3306
+ var PLUGINS_SOURCE_DIR = join2(PACKAGE_ROOT, "src", "plugins");
3307
+ var WIDGET_DIST_DIR = join2(PACKAGE_ROOT, "dist", "widget");
3308
+
3309
+ // src/node/http/gallery.mjs
3310
+ var SHELL = join3(GALLERY_DIST_DIR, "index.html");
3311
+ async function galleryResponse(docsDir) {
3312
+ const { name, path: path3, hue } = docsInfo(docsDir);
3313
+ let html;
3314
+ try {
3315
+ html = await readFile2(SHELL, "utf8");
3316
+ } catch {
3317
+ return text("Gallery build missing: run `npm run build`", 503, { "cache-control": "no-store" });
3318
+ }
3319
+ html = html.replaceAll("__DOCS_NAME__", escapeHtml(name)).replaceAll("__DOCS_PATH__", escapeHtml(path3)).replaceAll("__DOCS_HUE__", String(hue));
3320
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } });
3321
+ }
3322
+ function escapeHtml(s) {
3323
+ return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3324
+ }
3325
+
3326
+ // src/node/docs/inject.mjs
3327
+ var WS_PATH = "/__reload";
3328
+ var MARKER = "<!--docserve-widget-->";
3329
+ var SCRIPT_SRC = "/__docserve/widget/index.js";
3330
+ function injectIntoHtml(html, page, docsDir = "") {
3331
+ if (html.includes(MARKER)) return html;
3332
+ const docs = docsInfo(docsDir);
3333
+ const tags = [
3334
+ MARKER,
3335
+ '<link rel="stylesheet" href="/__docserve/widget/widget.css" data-docserve-widget>',
3336
+ `<script type="module" src="${SCRIPT_SRC}" data-docserve-widget data-page="${escapeAttribute(page)}" data-docs-name="${escapeAttribute(docs.name)}" data-docs-path="${escapeAttribute(docs.path)}" data-docs-hue="${docs.hue}"></script>`
3337
+ ].join("\n");
3338
+ const index = html.toLowerCase().lastIndexOf("</body>");
3339
+ return index === -1 ? `${html}
3340
+ ${tags}` : `${html.slice(0, index)}${tags}
3341
+ ${html.slice(index)}`;
3342
+ }
3343
+ function escapeAttribute(value) {
3344
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3345
+ }
3346
+
3347
+ // src/node/http/routes.mjs
3348
+ var INTERNAL_PREFIX = "/__docserve/";
3349
+ var WIDGET_PREFIX = `${INTERNAL_PREFIX}widget/`;
3350
+ var PLUGINS_PREFIX = `${INTERNAL_PREFIX}plugins/`;
3351
+ var GALLERY_PREFIX = `${INTERNAL_PREFIX}gallery/`;
3352
+ function registerRoutes(app, { docsDir }) {
3353
+ const docs = createStaticHandler({
3354
+ root: docsDir,
3355
+ headers: { "cache-control": "no-store" },
3356
+ transform: (html, relative2) => injectIntoHtml(html, relative2, docsDir)
3357
+ });
3358
+ app.get(`${WIDGET_PREFIX}**`, (event) => serveWidget(event.url.pathname.slice(WIDGET_PREFIX.length)));
3359
+ app.get(`${PLUGINS_PREFIX}**`, (event) => serveAsset(PLUGINS_SOURCE_DIR, event.url.pathname.slice(PLUGINS_PREFIX.length)));
3360
+ app.get(`${GALLERY_PREFIX}**`, (event) => serveAsset(GALLERY_DIST_DIR, event.url.pathname.slice(GALLERY_PREFIX.length)));
3361
+ app.all(`${INTERNAL_PREFIX}**`, () => notFound());
3362
+ app.get("/", () => galleryResponse(docsDir));
3363
+ app.get("/index.html", () => galleryResponse(docsDir));
3364
+ app.all("/**", async (event) => await docs(event.req) ?? notFound());
3365
+ }
3366
+ async function serveWidget(relative2) {
3367
+ if (!relative2) return notFound();
3368
+ const built = await serveAsset(WIDGET_DIST_DIR, relative2);
3369
+ if (built.status !== 404) return built;
3370
+ if (/\.m?js$/.test(relative2)) {
3371
+ return text("Widget bundle missing: run `pnpm -C cli build`", 503, {
3372
+ "cache-control": "no-store"
3373
+ });
3374
+ }
3375
+ return serveAsset(WIDGET_SOURCE_DIR, relative2);
3376
+ }
3377
+
3378
+ // src/node/docs/files.mjs
3379
+ import { realpathSync as realpathSync2 } from "node:fs";
3380
+ import { stat as stat2 } from "node:fs/promises";
3381
+ import { basename as basename2 } from "node:path";
3382
+
3383
+ // src/node/docs/dates.mjs
3384
+ import { execFile } from "node:child_process";
3385
+ import { join as join4 } from "node:path";
3386
+ import { promisify } from "node:util";
3387
+ var run = promisify(execFile);
3388
+ var gitMapsCache = /* @__PURE__ */ new Map();
3389
+ async function gitDateMaps(docsDir) {
3390
+ const cwd = realpath(docsDir);
3391
+ const top = (await git(["rev-parse", "--show-toplevel"], cwd)).trim();
3392
+ const root = top ? realpath(top) : null;
3393
+ const cacheKey = root ?? cwd;
3394
+ let maps = gitMapsCache.get(cacheKey);
3395
+ if (maps) return maps;
3396
+ maps = { created: /* @__PURE__ */ new Map(), modified: /* @__PURE__ */ new Map() };
3397
+ if (root) {
3398
+ try {
3399
+ const [first, last] = await Promise.all([
3400
+ git(["log", "--diff-filter=A", "--name-only", "--format=c:%at"], cwd),
3401
+ git(["log", "--name-only", "--format=m:%at"], cwd)
3402
+ ]);
3403
+ let ts;
3404
+ for (const line of first.split("\n")) {
3405
+ if (line.startsWith("c:")) {
3406
+ ts = parseInt(line.slice(2), 10);
3407
+ } else if (line && ts !== void 0) {
3408
+ maps.created.set(join4(root, line), ts);
3409
+ }
3410
+ }
3411
+ ts = void 0;
3412
+ for (const line of last.split("\n")) {
3413
+ if (line.startsWith("m:")) {
3414
+ ts = parseInt(line.slice(2), 10);
3415
+ } else if (line && ts !== void 0) {
3416
+ maps.modified.set(join4(root, line), ts);
3417
+ }
3418
+ }
3419
+ } catch {
3420
+ }
3421
+ }
3422
+ gitMapsCache.set(cacheKey, maps);
3423
+ return maps;
3424
+ }
3425
+ async function git(args, cwd) {
3426
+ try {
3427
+ const { stdout } = await run("git", args, { cwd, timeout: 1e4, maxBuffer: 64 * 1024 * 1024 });
3428
+ return stdout;
3429
+ } catch {
3430
+ return "";
3431
+ }
3432
+ }
3433
+
3434
+ // src/node/docs/meta.mjs
3435
+ import { open } from "node:fs/promises";
3436
+ import { dirname, join as join5 } from "node:path";
3437
+ var metaCache = /* @__PURE__ */ new Map();
3438
+ async function metaOf(full, mtimeMs, docsDir) {
3439
+ const key = `${full}:${mtimeMs}`;
3440
+ const cached = metaCache.get(key);
3441
+ if (cached !== void 0) return cached;
3442
+ const meta = await extractMeta(full, docsDir);
3443
+ metaCache.set(key, meta);
3444
+ return meta;
3445
+ }
3446
+ async function extractMeta(full, docsDir) {
3447
+ const findTitle = (text2) => {
3448
+ const raw = text2.match(/<title>([^<]*)<\/title>/)?.[1]?.trim();
3449
+ return raw == null ? null : decodeEntities(raw);
3450
+ };
3451
+ const findDate = (text2) => {
3452
+ for (const tag of text2.match(/<meta\b[^>]*>/gi) ?? []) {
3453
+ if (!/\bname\s*=\s*["']created_at["']/i.test(tag)) continue;
3454
+ const d = new Date(tag.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1]?.trim() ?? "");
3455
+ if (!isNaN(d.getTime())) return Math.floor(d.getTime() / 1e3);
3456
+ }
3457
+ return null;
3458
+ };
3459
+ const attrOf = (tag, name) => {
3460
+ const m = tag.match(new RegExp(`(?<![\\w-])${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
3461
+ return m?.[1] ?? m?.[2] ?? m?.[3] ?? null;
3462
+ };
3463
+ const findFavicon = (text2) => {
3464
+ for (const tag of text2.match(/<link\b(?:"[^"]*"|'[^']*'|[^>])*>/gi) ?? []) {
3465
+ const rel = attrOf(tag, "rel");
3466
+ if (!rel || !/\bicon\b/i.test(rel)) continue;
3467
+ const href = attrOf(tag, "href")?.trim();
3468
+ if (!href) continue;
3469
+ if (/^data:/i.test(href)) return href.replaceAll("#", "%23");
3470
+ if (/^(https?:|\/\/)/i.test(href)) return href;
3471
+ const target = href.startsWith("/") ? join5(docsDir, href.split(/[?#]/)[0]) : join5(dirname(full), href.split(/[?#]/)[0]);
3472
+ if (!isWithin(docsDir, target)) return null;
3473
+ return `/${normalizedRelative(docsDir, target)}`;
3474
+ }
3475
+ return null;
3476
+ };
3477
+ try {
3478
+ const handle = await open(full, "r");
3479
+ try {
3480
+ const read = async (len, pos) => {
3481
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(len), 0, len, pos);
3482
+ return buffer.toString("utf8", 0, bytesRead);
3483
+ };
3484
+ const head = await read(4096, 0);
3485
+ let meta = {
3486
+ title: findTitle(head),
3487
+ date: findDate(head),
3488
+ favicon: findFavicon(head)
3489
+ };
3490
+ if (meta.title === null || meta.date === null || meta.favicon === null) {
3491
+ const text2 = await read(1 << 20, 0);
3492
+ meta = {
3493
+ title: meta.title ?? findTitle(text2),
3494
+ date: meta.date ?? findDate(text2),
3495
+ favicon: meta.favicon ?? findFavicon(text2)
3496
+ };
3497
+ }
3498
+ return meta;
3499
+ } finally {
3500
+ await handle.close();
3501
+ }
3502
+ } catch {
3503
+ return { title: null, date: null, favicon: null };
3504
+ }
3505
+ }
3506
+ var ENTITIES = {
3507
+ amp: "&",
3508
+ lt: "<",
3509
+ gt: ">",
3510
+ quot: '"',
3511
+ apos: "'",
3512
+ nbsp: "\xA0"
3513
+ };
3514
+ function decodeEntities(s) {
3515
+ return s.replace(/&(#[xX]?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, (m, ref) => {
3516
+ if (ref[0] === "#") {
3517
+ const hex = /[xX]/.test(ref[1]);
3518
+ const cp = parseInt(hex ? ref.slice(2) : ref.slice(1), hex ? 16 : 10);
3519
+ return cp > 0 && cp <= 1114111 ? String.fromCodePoint(cp) : m;
3520
+ }
3521
+ return ENTITIES[ref.toLowerCase()] ?? m;
3522
+ });
3523
+ }
3524
+
3525
+ // src/node/docs/files.mjs
3526
+ async function apiFiles(docsDir) {
3527
+ const paths = await listHtmlFiles(docsDir);
3528
+ const { created, modified } = await gitDateMaps(docsDir);
3529
+ const files = [];
3530
+ for (const full of paths) {
3531
+ let st;
3532
+ try {
3533
+ st = await stat2(full);
3534
+ } catch {
3535
+ continue;
3536
+ }
3537
+ const { title, date, favicon } = await metaOf(full, st.mtimeMs, docsDir);
3538
+ let key;
3539
+ try {
3540
+ key = realpathSync2(full);
3541
+ } catch {
3542
+ continue;
3543
+ }
3544
+ const rel = normalizedRelative(docsDir, full);
3545
+ files.push({
3546
+ title: title ?? basename2(full),
3547
+ url: `/${rel}`,
3548
+ filePath: full,
3549
+ favicon: favicon ?? void 0,
3550
+ created: date ?? created.get(key) ?? Math.floor(st.birthtimeMs / 1e3),
3551
+ modified: modified.get(key) ?? Math.floor(st.mtimeMs / 1e3)
3552
+ });
3553
+ }
3554
+ files.sort((a, b) => b.created - a.created || a.title.localeCompare(b.title, "ja") || a.url.localeCompare(b.url));
3555
+ return files;
3556
+ }
3557
+
3558
+ // src/node/rpc/files.mjs
3559
+ function registerFiles(rpc, { docsDir }) {
3560
+ rpc.register("docserve:pages:list", () => apiFiles(docsDir));
3561
+ }
3562
+
3563
+ // src/node/rpc/index.mjs
3564
+ var RpcError = class extends Error {
3565
+ constructor(message, status = 500) {
3566
+ super(message);
3567
+ this.name = "RpcError";
3568
+ this.status = status;
3569
+ }
3570
+ };
3571
+ function createRpc() {
3572
+ const methods = /* @__PURE__ */ new Map();
3573
+ return {
3574
+ register(name, handler) {
3575
+ if (typeof name !== "string" || !name) throw new TypeError("rpc.register expects a method name");
3576
+ if (typeof handler !== "function") throw new TypeError(`rpc.register(${name}) expects a function`);
3577
+ if (methods.has(name)) throw new Error(`rpc method already registered: ${name}`);
3578
+ methods.set(name, handler);
3579
+ return () => {
3580
+ if (methods.get(name) === handler) methods.delete(name);
3581
+ };
3582
+ },
3583
+ has(name) {
3584
+ return methods.has(name);
3585
+ },
3586
+ names() {
3587
+ return [...methods.keys()];
3588
+ },
3589
+ async call(name, args = []) {
3590
+ if (!Array.isArray(args)) throw new RpcError("args must be an array", 400);
3591
+ const handler = methods.get(name);
3592
+ if (!handler) throw new RpcError(`Unknown RPC method: ${name}`, 404);
3593
+ return handler(...args);
3594
+ }
3595
+ };
3596
+ }
3597
+
3598
+ // src/node/rpc/route.mjs
3599
+ function registerRpcRoute(app, rpc) {
3600
+ app.post("/__docserve/rpc", async (event) => {
3601
+ let payload;
3602
+ try {
3603
+ payload = await readBody2(event);
3604
+ } catch {
3605
+ return json({ error: { message: "Invalid JSON body" } }, 400);
3606
+ }
3607
+ const data = (
3608
+ /** @type {{ method?: unknown, args?: unknown }} */
3609
+ payload
3610
+ );
3611
+ const method = data?.method;
3612
+ const args = data?.args ?? [];
3613
+ if (typeof method !== "string" || !method)
3614
+ return json({ error: { message: "method must be a string" } }, 400);
3615
+ if (!Array.isArray(args))
3616
+ return json({ error: { message: "args must be an array" } }, 400);
3617
+ try {
3618
+ return json({ result: await rpc.call(method, args) });
3619
+ } catch (error) {
3620
+ const status = error instanceof RpcError ? error.status : 500;
3621
+ if (!(error instanceof RpcError)) console.error(error);
3622
+ return json({ error: { message: error instanceof Error ? error.message : String(error) } }, status);
3623
+ }
3624
+ });
3625
+ }
3626
+
3627
+ // src/node/instances/view.mjs
3628
+ import { resolve as resolve2 } from "node:path";
3629
+ function publicServers(states, currentDocsDir) {
3630
+ const current = resolve2(currentDocsDir);
3631
+ return states.map((state) => ({
3632
+ ...docsInfo(state.docsDir),
3633
+ url: state.url,
3634
+ port: state.port,
3635
+ current: resolve2(state.docsDir) === current
3636
+ })).sort((a, b) => Number(b.current) - Number(a.current) || a.name.localeCompare(b.name, "ja") || a.port - b.port);
3637
+ }
3638
+
3639
+ // src/node/instances/state.mjs
3640
+ import fs from "node:fs";
3641
+ import os2 from "node:os";
3642
+ import path from "node:path";
3643
+ var ownFile = null;
3644
+ function homeDir() {
3645
+ return process.env.DOCSERVE_HOME || path.join(os2.homedir(), ".docserve");
3646
+ }
3647
+ function stateDir() {
3648
+ return path.join(homeDir(), "state");
3649
+ }
3650
+ function fileName(state) {
3651
+ const name = path.basename(state.docsDir).replace(/[\0\\/:*?"<>|]/g, "-").replace(new RegExp("\\p{Cc}", "gu"), "").replace(/^\.+/, "").slice(0, 40).replace(/^[-.]+|[-.]+$/g, "");
3652
+ return `${state.port}-${name || "docs"}.json`;
3653
+ }
3654
+ function readStateFile(file) {
3655
+ try {
3656
+ const state = JSON.parse(fs.readFileSync(file, "utf8"));
3657
+ if (typeof state?.pid === "number" && typeof state?.port === "number" && typeof state?.url === "string" && typeof state?.docsDir === "string") {
3658
+ return {
3659
+ ...state,
3660
+ startedAt: typeof state.startedAt === "number" ? state.startedAt : 0
3661
+ };
3662
+ }
3663
+ return null;
3664
+ } catch {
3665
+ return null;
3666
+ }
3667
+ }
3668
+ function isProcessAlive(pid) {
3669
+ try {
3670
+ process.kill(pid, 0);
3671
+ return true;
3672
+ } catch {
3673
+ return false;
3674
+ }
3675
+ }
3676
+ function writeState(state) {
3677
+ fs.mkdirSync(stateDir(), { recursive: true });
3678
+ const record = { ...state, startedAt: state.startedAt ?? Date.now() };
3679
+ const file = path.join(stateDir(), fileName(record));
3680
+ const tmp = `${file}.${process.pid}.tmp`;
3681
+ fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + "\n");
3682
+ fs.renameSync(tmp, file);
3683
+ ownFile = file;
3684
+ }
3685
+ function clearState() {
3686
+ if (!ownFile) return;
3687
+ try {
3688
+ fs.rmSync(ownFile, { force: true });
3689
+ } catch {
3690
+ }
3691
+ ownFile = null;
3692
+ }
3693
+ function removeState(state) {
3694
+ try {
3695
+ fs.rmSync(path.join(stateDir(), fileName(state)), { force: true });
3696
+ } catch {
3697
+ }
3698
+ }
3699
+ function listLiveStates() {
3700
+ let entries = [];
3701
+ try {
3702
+ entries = fs.readdirSync(stateDir());
3703
+ } catch {
3704
+ }
3705
+ const states = [];
3706
+ for (const entry of entries) {
3707
+ if (!entry.endsWith(".json")) continue;
3708
+ const file = path.join(stateDir(), entry);
3709
+ const state = readStateFile(file);
3710
+ if (!state) continue;
3711
+ if (!isProcessAlive(state.pid)) {
3712
+ try {
3713
+ fs.rmSync(file, { force: true });
3714
+ } catch {
3715
+ }
3716
+ continue;
3717
+ }
3718
+ states.push(state);
3719
+ }
3720
+ return states.sort((a, b) => b.startedAt - a.startedAt || b.port - a.port);
3721
+ }
3722
+ function findByDir(docsDir) {
3723
+ const resolved = path.resolve(docsDir);
3724
+ return listLiveStates().find((state) => state.docsDir === resolved) ?? null;
3725
+ }
3726
+
3727
+ // src/node/rpc/servers.mjs
3728
+ function registerServers(rpc, { docsDir, ttl = 1e3 }) {
3729
+ let cached = null;
3730
+ let cachedAt = 0;
3731
+ rpc.register("docserve:servers:list", (force = false) => {
3732
+ const now = Date.now();
3733
+ if (force || !cached || now - cachedAt >= ttl) {
3734
+ cached = publicServers(listLiveStates(), docsDir);
3735
+ cachedAt = now;
3736
+ }
3737
+ return cached;
3738
+ });
3739
+ }
3740
+
3741
+ // src/node/http/app.mjs
3742
+ function createApp2({ docsDir }) {
3743
+ const app = new H3();
3744
+ const rpc = createRpc();
3745
+ registerFiles(rpc, { docsDir });
3746
+ registerServers(rpc, { docsDir });
3747
+ registerRpcRoute(app, rpc);
3748
+ registerRoutes(app, { docsDir });
3749
+ return app;
3750
+ }
3751
+
3752
+ // src/node/live/watch.mjs
3753
+ import { existsSync, watch } from "node:fs";
3754
+ import { basename as basename3, dirname as dirname2, resolve as resolve3 } from "node:path";
3755
+ var DEBOUNCE_MS = 50;
3756
+ var FileWatcher = class {
3757
+ constructor(options = {}) {
3758
+ this.wss = options.wss;
3759
+ this.docsDir = options.docsDir;
3760
+ this.templatePath = options.templatePath;
3761
+ this.debounceMs = options.debounceMs ?? DEBOUNCE_MS;
3762
+ this.knownFiles = /* @__PURE__ */ new Set();
3763
+ this.queue = Promise.resolve();
3764
+ this.watchers = [];
3765
+ this.pending = { pages: /* @__PURE__ */ new Set(), css: /* @__PURE__ */ new Set(), template: false };
3766
+ this.queueFlush = debounce(() => {
3767
+ const { pages, css, template } = this.pending;
3768
+ this.pending = { pages: /* @__PURE__ */ new Set(), css: /* @__PURE__ */ new Set(), template: false };
3769
+ if (pages.size || template) {
3770
+ this.enqueue(() => this.broadcastChanges({ pages: [...pages], template }));
3771
+ }
3772
+ if (css.size)
3773
+ this.enqueue(() => this.broadcastCss([...css]));
3774
+ }, this.debounceMs);
3775
+ }
3776
+ enqueue(task) {
3777
+ this.queue = this.queue.then(task).catch((error) => console.error(error));
3778
+ }
3779
+ async start() {
3780
+ try {
3781
+ this.knownFiles = new Set(
3782
+ (await listHtmlFiles(this.docsDir)).map((p) => normalizedRelative(this.docsDir, p))
3783
+ );
3784
+ } catch {
3785
+ this.knownFiles = /* @__PURE__ */ new Set();
3786
+ }
3787
+ this.watchers.push(
3788
+ watch(this.docsDir, { recursive: true }, (event, filename) => {
3789
+ if (!filename || shouldIgnore(filename)) return;
3790
+ const full = resolve3(this.docsDir, filename);
3791
+ if (!isWithin(this.docsDir, full)) return;
3792
+ const rel = normalizedRelative(this.docsDir, full);
3793
+ if (filename.endsWith(".html")) {
3794
+ this.pending.pages.add(rel);
3795
+ this.queueFlush();
3796
+ } else if (filename.endsWith(".css")) {
3797
+ this.pending.css.add(rel);
3798
+ this.queueFlush();
3799
+ }
3800
+ }).on("error", () => {
3801
+ })
3802
+ );
3803
+ if (this.templatePath) {
3804
+ const templateName = basename3(this.templatePath);
3805
+ this.watchers.push(
3806
+ watch(dirname2(this.templatePath), (event, filename) => {
3807
+ if (filename === templateName) {
3808
+ this.pending.template = true;
3809
+ this.queueFlush();
3810
+ }
3811
+ }).on("error", () => {
3812
+ })
3813
+ );
3814
+ }
3815
+ }
3816
+ async broadcastChanges({ pages, template }) {
3817
+ this.wss.broadcast({
3818
+ type: "change",
3819
+ pages,
3820
+ contentSetChanged: syncKnownFiles(this.knownFiles, this.docsDir, pages),
3821
+ templateChanged: template
3822
+ });
3823
+ }
3824
+ // Refresh linked stylesheets in place.
3825
+ broadcastCss(files) {
3826
+ this.wss.broadcast({ type: "css", files });
3827
+ }
3828
+ close() {
3829
+ this.watchers.forEach((w) => w.close());
3830
+ }
3831
+ };
3832
+ function syncKnownFiles(knownFiles, docsDir, pages) {
3833
+ let changed = false;
3834
+ for (const rel of pages) {
3835
+ if (basename3(rel) === "index.html") continue;
3836
+ const exists = existsSync(resolve3(docsDir, rel));
3837
+ const wasKnown = knownFiles.has(rel);
3838
+ if (exists === wasKnown) continue;
3839
+ if (exists) knownFiles.add(rel);
3840
+ else knownFiles.delete(rel);
3841
+ changed = true;
3842
+ }
3843
+ return changed;
3844
+ }
3845
+ function debounce(fn, ms) {
3846
+ let timer = null;
3847
+ return () => {
3848
+ clearTimeout(timer);
3849
+ timer = setTimeout(fn, ms);
3850
+ };
3851
+ }
3852
+
3853
+ // src/node/live/websocket.mjs
3854
+ import { createHash } from "node:crypto";
3855
+ var WebSocketServer = class {
3856
+ constructor(options = {}) {
3857
+ this.path = options.path;
3858
+ this.clients = /* @__PURE__ */ new Set();
3859
+ if (options.server) {
3860
+ this.attach(options.server);
3861
+ }
3862
+ }
3863
+ attach(server) {
3864
+ server.on("upgrade", (req, socket) => this.handleUpgrade(req, socket));
3865
+ }
3866
+ handleUpgrade(req, socket) {
3867
+ const url = new URL(req.url, "http://localhost");
3868
+ if (this.path && url.pathname !== this.path) {
3869
+ socket.destroy();
3870
+ return;
3871
+ }
3872
+ const key = req.headers["sec-websocket-key"];
3873
+ if (!key) {
3874
+ socket.destroy();
3875
+ return;
3876
+ }
3877
+ socket.write(
3878
+ `HTTP/1.1 101 Switching Protocols\r
3879
+ Upgrade: websocket\r
3880
+ Connection: Upgrade\r
3881
+ Sec-WebSocket-Accept: ${acceptKey(key)}\r
3882
+ \r
3883
+ `
3884
+ );
3885
+ socket.setNoDelay(true);
3886
+ this.clients.add(socket);
3887
+ socket.on("close", () => this.clients.delete(socket));
3888
+ socket.on("error", () => this.clients.delete(socket));
3889
+ socket.on("data", (buf) => {
3890
+ if (buf.length > 0 && (buf[0] & 15) === 9) {
3891
+ socket.write(Buffer.from([138, 0]));
3892
+ }
3893
+ });
3894
+ }
3895
+ broadcast(payload) {
3896
+ const frame = encodeFrame(typeof payload === "string" ? payload : JSON.stringify(payload));
3897
+ for (const socket of this.clients) {
3898
+ try {
3899
+ socket.write(frame);
3900
+ } catch {
3901
+ this.clients.delete(socket);
3902
+ }
3903
+ }
3904
+ }
3905
+ close() {
3906
+ for (const socket of this.clients) {
3907
+ try {
3908
+ socket.destroy();
3909
+ } catch {
3910
+ }
3911
+ }
3912
+ this.clients.clear();
3913
+ }
3914
+ };
3915
+ function acceptKey(key) {
3916
+ return createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
3917
+ }
3918
+ function encodeFrame(text2) {
3919
+ const payload = Buffer.from(text2);
3920
+ const len = payload.length;
3921
+ let header;
3922
+ if (len < 126) {
3923
+ header = Buffer.from([129, len]);
3924
+ } else if (len < 65536) {
3925
+ header = Buffer.alloc(4);
3926
+ header[0] = 129;
3927
+ header[1] = 126;
3928
+ header.writeUInt16BE(len, 2);
3929
+ } else {
3930
+ header = Buffer.alloc(10);
3931
+ header[0] = 129;
3932
+ header[1] = 127;
3933
+ header.writeBigUInt64BE(BigInt(len), 2);
3934
+ }
3935
+ return Buffer.concat([header, payload]);
3936
+ }
3937
+
3938
+ // src/node/http/server.mjs
3939
+ var MAX_PORT_TRIES = 20;
3940
+ async function runServer({ docsDir, port: initialPort, open: open2 = false }) {
3941
+ const wss = new WebSocketServer({ path: WS_PATH });
3942
+ const fileWatcher = new FileWatcher({ wss, docsDir, templatePath: GALLERY_TEMPLATE });
3943
+ let port = initialPort;
3944
+ let closed = false;
3945
+ const server = createServer(toNodeHandler2(createApp2({ docsDir })));
3946
+ wss.attach(server);
3947
+ const close = () => {
3948
+ if (closed) return;
3949
+ closed = true;
3950
+ process.off("SIGINT", onSignal);
3951
+ process.off("SIGTERM", onSignal);
3952
+ fileWatcher.close();
3953
+ wss.close();
3954
+ clearState();
3955
+ server.closeAllConnections();
3956
+ if (server.listening) server.close();
3957
+ };
3958
+ const onSignal = () => {
3959
+ close();
3960
+ process.exit(0);
3961
+ };
3962
+ process.on("SIGINT", onSignal);
3963
+ process.on("SIGTERM", onSignal);
3964
+ server.on("error", (err) => {
3965
+ if (err.code === "EADDRINUSE" && port < initialPort + MAX_PORT_TRIES) {
3966
+ port += 1;
3967
+ server.listen(port, "127.0.0.1");
3968
+ } else {
3969
+ console.error(err);
3970
+ process.exit(1);
3971
+ }
3972
+ });
3973
+ server.listen(port, "127.0.0.1", async () => {
3974
+ await fileWatcher.start();
3975
+ const state = { pid: process.pid, port, url: `http://localhost:${port}/`, docsDir };
3976
+ writeState(state);
3977
+ console.log(state.url);
3978
+ if (open2 && process.platform === "darwin") exec(`open ${state.url}`);
3979
+ });
3980
+ return { server, wss, fileWatcher, close };
3981
+ }
3982
+
3983
+ // src/node/cli.mjs
3984
+ var pkg = JSON.parse(fs2.readFileSync(PACKAGE_JSON, "utf8"));
3985
+ var VERSION = pkg.version;
3986
+ var DEFAULT_PORT = 4242;
3987
+ async function main(argv = process.argv) {
3988
+ const cli = cac("docserve");
3989
+ cli.usage("[dir] [command] [options]").option("--open", "Open the gallery in the browser once the port is bound").option("--port <number>", `Port to bind (default: ${DEFAULT_PORT}); falls back +1 up to 20 tries`, { default: DEFAULT_PORT }).option("--background", "Start detached; the bound port and pid land in the state dir").help().version(VERSION);
3990
+ cli.command("[dir]", "Serve a folder of HTML files (default: current directory)").usage("[dir] [options]").example("docserve ~/reports --open").action(async (dir, options) => {
3991
+ await startServer(dir, options);
3992
+ });
3993
+ cli.command("stop [dir]", "Stop the server serving [dir], or every server when [dir] is omitted").action((dir) => {
3994
+ stopServer(dir);
3995
+ });
3996
+ cli.command("status", "List the running servers (url + docs); exit 1 if none").action(() => {
3997
+ showStatus();
3998
+ });
3999
+ cli.parse(argv, { run: false });
4000
+ await cli.runMatchedCommand();
4001
+ }
4002
+ async function startServer(dir, options) {
4003
+ const docsDir = path2.resolve(dir ?? ".");
4004
+ if (!isDirectory2(docsDir))
4005
+ throw new Error(`[docserve] Directory not found: ${docsDir}`);
4006
+ const port = parsePort(options.port);
4007
+ const open2 = options.open ?? false;
4008
+ const running = findByDir(docsDir);
4009
+ if (running) {
4010
+ if (open2) openBrowser(running.url);
4011
+ console.log(`docserve is already serving this folder: ${running.url}`);
4012
+ return;
4013
+ }
4014
+ if (options.background) {
4015
+ await startBackground({ docsDir, port, open: open2 });
4016
+ return;
4017
+ }
4018
+ console.log(`docserve v${VERSION}`);
4019
+ console.log(`docs : ${docsDir}`);
4020
+ await runServer({ docsDir, port, open: open2 });
4021
+ }
4022
+ function stopServer(dir) {
4023
+ const resolved = dir ? path2.resolve(dir) : null;
4024
+ const states = resolved ? [findByDir(resolved)].filter(Boolean) : listLiveStates();
4025
+ if (!states.length) {
4026
+ if (resolved) throw new Error(`docserve is not serving ${resolved}.`);
4027
+ console.log("docserve is not running.");
4028
+ return;
4029
+ }
4030
+ for (const state of states) {
4031
+ try {
4032
+ process.kill(state.pid, "SIGTERM");
4033
+ } catch {
4034
+ }
4035
+ removeState(state);
4036
+ console.log(`Stopped docserve (${state.url})`);
4037
+ console.log(` docs : ${state.docsDir}`);
4038
+ }
4039
+ }
4040
+ function showStatus() {
4041
+ const states = listLiveStates();
4042
+ if (!states.length) throw new Error("docserve is not running.");
4043
+ for (const [index, state] of states.entries()) {
4044
+ if (index > 0) console.log();
4045
+ console.log(state.url);
4046
+ console.log(`docs : ${state.docsDir}`);
4047
+ }
4048
+ }
4049
+ async function startBackground({ docsDir, port, open: open2 }) {
4050
+ const entry = process.argv[1];
4051
+ if (!entry) throw new Error("[docserve] Cannot locate the CLI entry for --background.");
4052
+ const childArgs = [entry, docsDir];
4053
+ if (open2) childArgs.push("--open");
4054
+ childArgs.push("--port", String(port));
4055
+ const child = spawn(process.execPath, childArgs, { detached: true, stdio: "ignore" });
4056
+ child.unref();
4057
+ const state = await waitForState(child.pid);
4058
+ if (!state) throw new Error("[docserve] Server did not report startup (no state file). Try running in the foreground.");
4059
+ console.log("docserve started in the background");
4060
+ console.log(` pid : ${state.pid}`);
4061
+ console.log(` url : ${state.url}`);
4062
+ console.log(` docs : ${state.docsDir}`);
4063
+ console.log(" stop : docserve stop");
4064
+ }
4065
+ async function waitForState(pid, { timeoutMs = 1e4, intervalMs = 200 } = {}) {
4066
+ const deadline = Date.now() + timeoutMs;
4067
+ while (Date.now() < deadline) {
4068
+ const state = listLiveStates().find((entry) => entry.pid === pid);
4069
+ if (state) return state;
4070
+ await new Promise((resolve4) => setTimeout(resolve4, intervalMs));
4071
+ }
4072
+ return null;
4073
+ }
4074
+ function parsePort(value) {
4075
+ const port = Number(value ?? DEFAULT_PORT);
4076
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
4077
+ throw new Error(`[docserve] --port expects an integer between 1 and 65535, got "${value}"`);
4078
+ }
4079
+ return port;
4080
+ }
4081
+ function openBrowser(url) {
4082
+ if (process.platform === "darwin") execFile2("open", [url], () => {
4083
+ });
4084
+ }
4085
+ function isDirectory2(target) {
4086
+ try {
4087
+ return fs2.statSync(target).isDirectory();
4088
+ } catch {
4089
+ return false;
4090
+ }
4091
+ }
4092
+ export {
4093
+ main
4094
+ };
4095
+ //# sourceMappingURL=cli.mjs.map