@apps-in-toss/web-framework 0.0.7 → 0.0.8

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 (59) hide show
  1. package/dist/chunk-5AYTRYXW.js +27 -0
  2. package/dist/chunk-MHAJE5QI.js +34 -0
  3. package/dist/cli.cjs +4528 -543
  4. package/dist/cli.d.cts +2 -1
  5. package/dist/cli.d.ts +2 -1
  6. package/dist/cli.js +3486 -493
  7. package/dist/config/index.cjs +17 -4
  8. package/dist/config/index.d.cts +19 -3
  9. package/dist/config/index.d.ts +19 -3
  10. package/dist/config/index.js +7714 -23
  11. package/dist/lib-EUN4APCZ.js +1007 -0
  12. package/dist/lib-OD73GAMK.js +1007 -0
  13. package/package.json +14 -12
  14. package/src-web/closeView.d.ts +24 -0
  15. package/src-web/generateHapticFeedback.d.ts +52 -0
  16. package/src-web/getDeviceId.d.ts +32 -0
  17. package/src-web/getLocale.d.ts +31 -0
  18. package/src-web/getNetworkStatus.d.ts +55 -0
  19. package/src-web/getSchemeUri.d.ts +26 -0
  20. package/src-web/index.js +1 -0
  21. package/src-web/setScreenAwakeMode.d.ts +69 -0
  22. package/src-web/setSecureScreen.d.ts +34 -0
  23. package/src-web/share.d.ts +37 -0
  24. package/dist/chunk-CH3CIAIW.js +0 -7688
  25. package/dist/chunk-DI2VGQ6M.js +0 -53
  26. package/dist/chunk-HL7M3JLX.js +0 -53
  27. package/dist/chunk-I3ZDGLIW.js +0 -19
  28. package/dist/chunk-LJBVSTWE.js +0 -7687
  29. package/dist/chunk-OMIGZ2S7.js +0 -7689
  30. package/dist/chunk-TZCMTMV7.js +0 -38
  31. package/dist/cli/index.cjs +0 -644
  32. package/dist/cli/index.d.cts +0 -2
  33. package/dist/cli/index.d.ts +0 -2
  34. package/dist/cli/index.js +0 -592
  35. package/dist/closeView.d.ts +0 -1
  36. package/dist/generateHapticFeedback.d.ts +0 -1
  37. package/dist/getDeviceId.d.ts +0 -1
  38. package/dist/getLocale.d.ts +0 -1
  39. package/dist/getNetworkStatus.d.ts +0 -1
  40. package/dist/getSchemeUri.d.ts +0 -1
  41. package/dist/index.cjs +0 -18
  42. package/dist/index.d.cts +0 -2
  43. package/dist/index.js +0 -1
  44. package/dist/plugins/index.cjs +0 -7682
  45. package/dist/plugins/index.d.cts +0 -15
  46. package/dist/plugins/index.d.ts +0 -15
  47. package/dist/plugins/index.js +0 -11
  48. package/dist/setScreenAwakeMode.d.ts +0 -1
  49. package/dist/setSecureScreen.d.ts +0 -1
  50. package/dist/share.d.ts +0 -1
  51. package/react-native/.bedrock/.env.js +0 -4
  52. /package/{dist → src-web}/fetchAlbumPhotos.d.ts +0 -0
  53. /package/{dist → src-web}/fetchContacts.d.ts +0 -0
  54. /package/{dist → src-web}/getClipboardText.d.ts +0 -0
  55. /package/{dist → src-web}/getCurrentLocation.d.ts +0 -0
  56. /package/{dist → src-web}/index.d.ts +0 -0
  57. /package/{dist → src-web}/openCamera.d.ts +0 -0
  58. /package/{dist → src-web}/setClipboardText.d.ts +0 -0
  59. /package/{dist → src-web}/startUpdateLocation.d.ts +0 -0
package/dist/cli.js CHANGED
@@ -2,561 +2,3554 @@ import { createRequire } from 'module'; const require = createRequire(import.met
2
2
  import {
3
3
  __dirname,
4
4
  __require,
5
- loadConfig
6
- } from "./chunk-HL7M3JLX.js";
5
+ init_esm_shims
6
+ } from "./chunk-MHAJE5QI.js";
7
7
 
8
8
  // src/cli.ts
9
- import { Cli } from "clipanion";
9
+ init_esm_shims();
10
10
 
11
- // src/BuildCommand/BuildCommand.ts
12
- import { Command, Option } from "clipanion";
13
- import picocolors from "picocolors";
11
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/index.mjs
12
+ init_esm_shims();
14
13
 
15
- // src/BuildCommand/build.ts
14
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/Command.mjs
15
+ init_esm_shims();
16
+
17
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/options/utils.mjs
18
+ init_esm_shims();
19
+
20
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/errors.mjs
21
+ init_esm_shims();
22
+
23
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/constants.mjs
24
+ init_esm_shims();
25
+ var SpecialToken;
26
+ (function(SpecialToken2) {
27
+ SpecialToken2["StartOfInput"] = "\0";
28
+ SpecialToken2["EndOfInput"] = "";
29
+ SpecialToken2["EndOfPartialInput"] = "";
30
+ })(SpecialToken || (SpecialToken = {}));
31
+ var NodeType;
32
+ (function(NodeType2) {
33
+ NodeType2[NodeType2["InitialNode"] = 0] = "InitialNode";
34
+ NodeType2[NodeType2["SuccessNode"] = 1] = "SuccessNode";
35
+ NodeType2[NodeType2["ErrorNode"] = 2] = "ErrorNode";
36
+ NodeType2[NodeType2["CustomNode"] = 3] = "CustomNode";
37
+ })(NodeType || (NodeType = {}));
38
+ var HELP_COMMAND_INDEX = -1;
39
+ var HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/;
40
+ var OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/;
41
+ var BATCH_REGEX = /^-[a-zA-Z]{2,}$/;
42
+ var BINDING_REGEX = /^([^=]+)=([\s\S]*)$/;
43
+ var IS_DEBUG = process.env.DEBUG_CLI === `1`;
44
+
45
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/errors.mjs
46
+ var UsageError = class extends Error {
47
+ constructor(message) {
48
+ super(message);
49
+ this.clipanion = { type: `usage` };
50
+ this.name = `UsageError`;
51
+ }
52
+ };
53
+ var UnknownSyntaxError = class extends Error {
54
+ constructor(input, candidates) {
55
+ super();
56
+ this.input = input;
57
+ this.candidates = candidates;
58
+ this.clipanion = { type: `none` };
59
+ this.name = `UnknownSyntaxError`;
60
+ if (this.candidates.length === 0) {
61
+ this.message = `Command not found, but we're not sure what's the alternative.`;
62
+ } else if (this.candidates.every((candidate) => candidate.reason !== null && candidate.reason === candidates[0].reason)) {
63
+ const [{ reason }] = this.candidates;
64
+ this.message = `${reason}
65
+
66
+ ${this.candidates.map(({ usage }) => `$ ${usage}`).join(`
67
+ `)}`;
68
+ } else if (this.candidates.length === 1) {
69
+ const [{ usage }] = this.candidates;
70
+ this.message = `Command not found; did you mean:
71
+
72
+ $ ${usage}
73
+ ${whileRunning(input)}`;
74
+ } else {
75
+ this.message = `Command not found; did you mean one of:
76
+
77
+ ${this.candidates.map(({ usage }, index) => {
78
+ return `${`${index}.`.padStart(4)} ${usage}`;
79
+ }).join(`
80
+ `)}
81
+
82
+ ${whileRunning(input)}`;
83
+ }
84
+ }
85
+ };
86
+ var AmbiguousSyntaxError = class extends Error {
87
+ constructor(input, usages) {
88
+ super();
89
+ this.input = input;
90
+ this.usages = usages;
91
+ this.clipanion = { type: `none` };
92
+ this.name = `AmbiguousSyntaxError`;
93
+ this.message = `Cannot find which to pick amongst the following alternatives:
94
+
95
+ ${this.usages.map((usage, index) => {
96
+ return `${`${index}.`.padStart(4)} ${usage}`;
97
+ }).join(`
98
+ `)}
99
+
100
+ ${whileRunning(input)}`;
101
+ }
102
+ };
103
+ var whileRunning = (input) => `While running ${input.filter((token) => {
104
+ return token !== SpecialToken.EndOfInput && token !== SpecialToken.EndOfPartialInput;
105
+ }).map((token) => {
106
+ const json = JSON.stringify(token);
107
+ if (token.match(/\s/) || token.length === 0 || json !== `"${token}"`) {
108
+ return json;
109
+ } else {
110
+ return token;
111
+ }
112
+ }).join(` `)}`;
113
+
114
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/options/utils.mjs
115
+ var isOptionSymbol = Symbol(`clipanion/isOption`);
116
+ function cleanValidationError(message, { mergeName = false } = {}) {
117
+ const match = message.match(/^([^:]+): (.*)$/m);
118
+ if (!match)
119
+ return `validation failed`;
120
+ let [, path2, line] = match;
121
+ if (mergeName)
122
+ line = line[0].toLowerCase() + line.slice(1);
123
+ line = path2 !== `.` || !mergeName ? `${path2.replace(/^\.(\[|$)/, `$1`)}: ${line}` : `: ${line}`;
124
+ return line;
125
+ }
126
+ function formatError(message, errors) {
127
+ if (errors.length === 1) {
128
+ return new UsageError(`${message}${cleanValidationError(errors[0], { mergeName: true })}`);
129
+ } else {
130
+ return new UsageError(`${message}:
131
+ ${errors.map((error) => `
132
+ - ${cleanValidationError(error)}`).join(``)}`);
133
+ }
134
+ }
135
+
136
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/Command.mjs
137
+ var Command = class {
138
+ constructor() {
139
+ this.help = false;
140
+ }
141
+ /**
142
+ * Defines the usage information for the given command.
143
+ */
144
+ static Usage(usage) {
145
+ return usage;
146
+ }
147
+ /**
148
+ * Standard error handler which will simply rethrow the error. Can be used
149
+ * to add custom logic to handle errors from the command or simply return
150
+ * the parent class error handling.
151
+ */
152
+ async catch(error) {
153
+ throw error;
154
+ }
155
+ async validateAndExecute() {
156
+ const commandClass = this.constructor;
157
+ const cascade = commandClass.schema;
158
+ if (Array.isArray(cascade)) {
159
+ const { isDict, isUnknown, applyCascade } = await import("./lib-OD73GAMK.js");
160
+ const schema = applyCascade(isDict(isUnknown()), cascade);
161
+ const errors = [];
162
+ const coercions = [];
163
+ const check = schema(this, { errors, coercions });
164
+ if (!check)
165
+ throw formatError(`Invalid option schema`, errors);
166
+ for (const [, op] of coercions) {
167
+ op();
168
+ }
169
+ } else if (cascade != null) {
170
+ throw new Error(`Invalid command schema`);
171
+ }
172
+ const exitCode = await this.execute();
173
+ if (typeof exitCode !== `undefined`) {
174
+ return exitCode;
175
+ } else {
176
+ return 0;
177
+ }
178
+ }
179
+ };
180
+ Command.isOption = isOptionSymbol;
181
+ Command.Default = [];
182
+
183
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/Cli.mjs
184
+ init_esm_shims();
185
+
186
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/platform/node.mjs
187
+ init_esm_shims();
188
+ import tty from "tty";
189
+ function getDefaultColorDepth() {
190
+ if (tty && `getColorDepth` in tty.WriteStream.prototype)
191
+ return tty.WriteStream.prototype.getColorDepth();
192
+ if (process.env.FORCE_COLOR === `0`)
193
+ return 1;
194
+ if (process.env.FORCE_COLOR === `1`)
195
+ return 8;
196
+ if (typeof process.stdout !== `undefined` && process.stdout.isTTY)
197
+ return 8;
198
+ return 1;
199
+ }
200
+ var gContextStorage;
201
+ function getCaptureActivator(context) {
202
+ let contextStorage = gContextStorage;
203
+ if (typeof contextStorage === `undefined`) {
204
+ if (context.stdout === process.stdout && context.stderr === process.stderr)
205
+ return null;
206
+ const { AsyncLocalStorage: LazyAsyncLocalStorage } = __require("async_hooks");
207
+ contextStorage = gContextStorage = new LazyAsyncLocalStorage();
208
+ const origStdoutWrite = process.stdout._write;
209
+ process.stdout._write = function(chunk, encoding, cb) {
210
+ const context2 = contextStorage.getStore();
211
+ if (typeof context2 === `undefined`)
212
+ return origStdoutWrite.call(this, chunk, encoding, cb);
213
+ return context2.stdout.write(chunk, encoding, cb);
214
+ };
215
+ const origStderrWrite = process.stderr._write;
216
+ process.stderr._write = function(chunk, encoding, cb) {
217
+ const context2 = contextStorage.getStore();
218
+ if (typeof context2 === `undefined`)
219
+ return origStderrWrite.call(this, chunk, encoding, cb);
220
+ return context2.stderr.write(chunk, encoding, cb);
221
+ };
222
+ }
223
+ return (fn) => {
224
+ return contextStorage.run(context, fn);
225
+ };
226
+ }
227
+
228
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/core.mjs
229
+ init_esm_shims();
230
+ function debug(str) {
231
+ if (IS_DEBUG) {
232
+ console.log(str);
233
+ }
234
+ }
235
+ var basicHelpState = {
236
+ candidateUsage: null,
237
+ requiredOptions: [],
238
+ errorMessage: null,
239
+ ignoreOptions: false,
240
+ path: [],
241
+ positionals: [],
242
+ options: [],
243
+ remainder: null,
244
+ selectedIndex: HELP_COMMAND_INDEX,
245
+ tokens: []
246
+ };
247
+ function makeStateMachine() {
248
+ const stateMachine = {
249
+ nodes: []
250
+ };
251
+ for (let t = 0; t < NodeType.CustomNode; ++t)
252
+ stateMachine.nodes.push(makeNode());
253
+ return stateMachine;
254
+ }
255
+ function makeAnyOfMachine(inputs) {
256
+ const output = makeStateMachine();
257
+ const heads = [];
258
+ let offset = output.nodes.length;
259
+ for (const input of inputs) {
260
+ heads.push(offset);
261
+ for (let t = 0; t < input.nodes.length; ++t)
262
+ if (!isTerminalNode(t))
263
+ output.nodes.push(cloneNode(input.nodes[t], offset));
264
+ offset += input.nodes.length - NodeType.CustomNode + 1;
265
+ }
266
+ for (const head of heads)
267
+ registerShortcut(output, NodeType.InitialNode, head);
268
+ return output;
269
+ }
270
+ function injectNode(machine, node) {
271
+ machine.nodes.push(node);
272
+ return machine.nodes.length - 1;
273
+ }
274
+ function simplifyMachine(input) {
275
+ const visited = /* @__PURE__ */ new Set();
276
+ const process2 = (node) => {
277
+ if (visited.has(node))
278
+ return;
279
+ visited.add(node);
280
+ const nodeDef = input.nodes[node];
281
+ for (const transitions of Object.values(nodeDef.statics))
282
+ for (const { to } of transitions)
283
+ process2(to);
284
+ for (const [, { to }] of nodeDef.dynamics)
285
+ process2(to);
286
+ for (const { to } of nodeDef.shortcuts)
287
+ process2(to);
288
+ const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to));
289
+ while (nodeDef.shortcuts.length > 0) {
290
+ const { to } = nodeDef.shortcuts.shift();
291
+ const toDef = input.nodes[to];
292
+ for (const [segment, transitions] of Object.entries(toDef.statics)) {
293
+ const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment) ? nodeDef.statics[segment] = [] : nodeDef.statics[segment];
294
+ for (const transition of transitions) {
295
+ if (!store.some(({ to: to2 }) => transition.to === to2)) {
296
+ store.push(transition);
297
+ }
298
+ }
299
+ }
300
+ for (const [test, transition] of toDef.dynamics)
301
+ if (!nodeDef.dynamics.some(([otherTest, { to: to2 }]) => test === otherTest && transition.to === to2))
302
+ nodeDef.dynamics.push([test, transition]);
303
+ for (const transition of toDef.shortcuts) {
304
+ if (!shortcuts.has(transition.to)) {
305
+ nodeDef.shortcuts.push(transition);
306
+ shortcuts.add(transition.to);
307
+ }
308
+ }
309
+ }
310
+ };
311
+ process2(NodeType.InitialNode);
312
+ }
313
+ function debugMachine(machine, { prefix = `` } = {}) {
314
+ if (IS_DEBUG) {
315
+ debug(`${prefix}Nodes are:`);
316
+ for (let t = 0; t < machine.nodes.length; ++t) {
317
+ debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`);
318
+ }
319
+ }
320
+ }
321
+ function runMachineInternal(machine, input, partial = false) {
322
+ debug(`Running a vm on ${JSON.stringify(input)}`);
323
+ let branches = [{
324
+ node: NodeType.InitialNode,
325
+ state: {
326
+ candidateUsage: null,
327
+ requiredOptions: [],
328
+ errorMessage: null,
329
+ ignoreOptions: false,
330
+ options: [],
331
+ path: [],
332
+ positionals: [],
333
+ remainder: null,
334
+ selectedIndex: null,
335
+ tokens: []
336
+ }
337
+ }];
338
+ debugMachine(machine, { prefix: ` ` });
339
+ const tokens = [SpecialToken.StartOfInput, ...input];
340
+ for (let t = 0; t < tokens.length; ++t) {
341
+ const segment = tokens[t];
342
+ const isEOI = segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput;
343
+ const segmentIndex = t - 1;
344
+ debug(` Processing ${JSON.stringify(segment)}`);
345
+ const nextBranches = [];
346
+ for (const { node, state } of branches) {
347
+ debug(` Current node is ${node}`);
348
+ const nodeDef = machine.nodes[node];
349
+ if (node === NodeType.ErrorNode) {
350
+ nextBranches.push({ node, state });
351
+ continue;
352
+ }
353
+ console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`);
354
+ const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment);
355
+ if (!partial || t < tokens.length - 1 || hasExactMatch) {
356
+ if (hasExactMatch) {
357
+ const transitions = nodeDef.statics[segment];
358
+ for (const { to, reducer } of transitions) {
359
+ nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });
360
+ debug(` Static transition to ${to} found`);
361
+ }
362
+ } else {
363
+ debug(` No static transition found`);
364
+ }
365
+ } else {
366
+ let hasMatches = false;
367
+ for (const candidate of Object.keys(nodeDef.statics)) {
368
+ if (!candidate.startsWith(segment))
369
+ continue;
370
+ if (segment === candidate) {
371
+ for (const { to, reducer } of nodeDef.statics[candidate]) {
372
+ nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });
373
+ debug(` Static transition to ${to} found`);
374
+ }
375
+ } else {
376
+ for (const { to } of nodeDef.statics[candidate]) {
377
+ nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } });
378
+ debug(` Static transition to ${to} found (partial match)`);
379
+ }
380
+ }
381
+ hasMatches = true;
382
+ }
383
+ if (!hasMatches) {
384
+ debug(` No partial static transition found`);
385
+ }
386
+ }
387
+ if (!isEOI) {
388
+ for (const [test, { to, reducer }] of nodeDef.dynamics) {
389
+ if (execute(tests, test, state, segment, segmentIndex)) {
390
+ nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });
391
+ debug(` Dynamic transition to ${to} found (via ${test})`);
392
+ }
393
+ }
394
+ }
395
+ }
396
+ if (nextBranches.length === 0 && isEOI && input.length === 1) {
397
+ return [{
398
+ node: NodeType.InitialNode,
399
+ state: basicHelpState
400
+ }];
401
+ }
402
+ if (nextBranches.length === 0) {
403
+ throw new UnknownSyntaxError(input, branches.filter(({ node }) => {
404
+ return node !== NodeType.ErrorNode;
405
+ }).map(({ state }) => {
406
+ return { usage: state.candidateUsage, reason: null };
407
+ }));
408
+ }
409
+ if (nextBranches.every(({ node }) => node === NodeType.ErrorNode)) {
410
+ throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => {
411
+ return { usage: state.candidateUsage, reason: state.errorMessage };
412
+ }));
413
+ }
414
+ branches = trimSmallerBranches(nextBranches);
415
+ }
416
+ if (branches.length > 0) {
417
+ debug(` Results:`);
418
+ for (const branch of branches) {
419
+ debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`);
420
+ }
421
+ } else {
422
+ debug(` No results`);
423
+ }
424
+ return branches;
425
+ }
426
+ function runMachine(machine, input, { endToken = SpecialToken.EndOfInput } = {}) {
427
+ const branches = runMachineInternal(machine, [...input, endToken]);
428
+ return selectBestState(input, branches.map(({ state }) => {
429
+ return state;
430
+ }));
431
+ }
432
+ function trimSmallerBranches(branches) {
433
+ let maxPathSize = 0;
434
+ for (const { state } of branches)
435
+ if (state.path.length > maxPathSize)
436
+ maxPathSize = state.path.length;
437
+ return branches.filter(({ state }) => {
438
+ return state.path.length === maxPathSize;
439
+ });
440
+ }
441
+ function selectBestState(input, states) {
442
+ const terminalStates = states.filter((state) => {
443
+ return state.selectedIndex !== null;
444
+ });
445
+ if (terminalStates.length === 0)
446
+ throw new Error();
447
+ const requiredOptionsSetStates = terminalStates.filter((state) => state.selectedIndex === HELP_COMMAND_INDEX || state.requiredOptions.every((names) => names.some((name) => state.options.find((opt) => opt.name === name))));
448
+ if (requiredOptionsSetStates.length === 0) {
449
+ throw new UnknownSyntaxError(input, terminalStates.map((state) => ({
450
+ usage: state.candidateUsage,
451
+ reason: null
452
+ })));
453
+ }
454
+ let maxPathSize = 0;
455
+ for (const state of requiredOptionsSetStates)
456
+ if (state.path.length > maxPathSize)
457
+ maxPathSize = state.path.length;
458
+ const bestPathBranches = requiredOptionsSetStates.filter((state) => {
459
+ return state.path.length === maxPathSize;
460
+ });
461
+ const getPositionalCount = (state) => state.positionals.filter(({ extra }) => {
462
+ return !extra;
463
+ }).length + state.options.length;
464
+ const statesWithPositionalCount = bestPathBranches.map((state) => {
465
+ return { state, positionalCount: getPositionalCount(state) };
466
+ });
467
+ let maxPositionalCount = 0;
468
+ for (const { positionalCount } of statesWithPositionalCount)
469
+ if (positionalCount > maxPositionalCount)
470
+ maxPositionalCount = positionalCount;
471
+ const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => {
472
+ return positionalCount === maxPositionalCount;
473
+ }).map(({ state }) => {
474
+ return state;
475
+ });
476
+ const fixedStates = aggregateHelpStates(bestPositionalStates);
477
+ if (fixedStates.length > 1)
478
+ throw new AmbiguousSyntaxError(input, fixedStates.map((state) => state.candidateUsage));
479
+ return fixedStates[0];
480
+ }
481
+ function aggregateHelpStates(states) {
482
+ const notHelps = [];
483
+ const helps = [];
484
+ for (const state of states) {
485
+ if (state.selectedIndex === HELP_COMMAND_INDEX) {
486
+ helps.push(state);
487
+ } else {
488
+ notHelps.push(state);
489
+ }
490
+ }
491
+ if (helps.length > 0) {
492
+ notHelps.push({
493
+ ...basicHelpState,
494
+ path: findCommonPrefix(...helps.map((state) => state.path)),
495
+ options: helps.reduce((options, state) => options.concat(state.options), [])
496
+ });
497
+ }
498
+ return notHelps;
499
+ }
500
+ function findCommonPrefix(firstPath, secondPath, ...rest) {
501
+ if (secondPath === void 0)
502
+ return Array.from(firstPath);
503
+ return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest);
504
+ }
505
+ function makeNode() {
506
+ return {
507
+ dynamics: [],
508
+ shortcuts: [],
509
+ statics: {}
510
+ };
511
+ }
512
+ function isTerminalNode(node) {
513
+ return node === NodeType.SuccessNode || node === NodeType.ErrorNode;
514
+ }
515
+ function cloneTransition(input, offset = 0) {
516
+ const to = !isTerminalNode(input.to) ? input.to >= NodeType.CustomNode ? input.to + offset - NodeType.CustomNode + 1 : input.to + offset : input.to;
517
+ return {
518
+ to,
519
+ reducer: input.reducer
520
+ };
521
+ }
522
+ function cloneNode(input, offset = 0) {
523
+ const output = makeNode();
524
+ for (const [test, transition] of input.dynamics)
525
+ output.dynamics.push([test, cloneTransition(transition, offset)]);
526
+ for (const transition of input.shortcuts)
527
+ output.shortcuts.push(cloneTransition(transition, offset));
528
+ for (const [segment, transitions] of Object.entries(input.statics))
529
+ output.statics[segment] = transitions.map((transition) => cloneTransition(transition, offset));
530
+ return output;
531
+ }
532
+ function registerDynamic(machine, from, test, to, reducer) {
533
+ machine.nodes[from].dynamics.push([
534
+ test,
535
+ { to, reducer }
536
+ ]);
537
+ }
538
+ function registerShortcut(machine, from, to, reducer) {
539
+ machine.nodes[from].shortcuts.push({ to, reducer });
540
+ }
541
+ function registerStatic(machine, from, test, to, reducer) {
542
+ const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test) ? machine.nodes[from].statics[test] = [] : machine.nodes[from].statics[test];
543
+ store.push({ to, reducer });
544
+ }
545
+ function execute(store, callback, state, segment, segmentIndex) {
546
+ if (Array.isArray(callback)) {
547
+ const [name, ...args] = callback;
548
+ return store[name](state, segment, segmentIndex, ...args);
549
+ } else {
550
+ return store[callback](state, segment, segmentIndex);
551
+ }
552
+ }
553
+ var tests = {
554
+ always: () => {
555
+ return true;
556
+ },
557
+ isOptionLike: (state, segment) => {
558
+ return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`));
559
+ },
560
+ isNotOptionLike: (state, segment) => {
561
+ return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`);
562
+ },
563
+ isOption: (state, segment, segmentIndex, name) => {
564
+ return !state.ignoreOptions && segment === name;
565
+ },
566
+ isBatchOption: (state, segment, segmentIndex, names) => {
567
+ return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every((name) => names.has(`-${name}`));
568
+ },
569
+ isBoundOption: (state, segment, segmentIndex, names, options) => {
570
+ const optionParsing = segment.match(BINDING_REGEX);
571
+ return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.has(optionParsing[1]) && options.filter((opt) => opt.nameSet.includes(optionParsing[1])).every((opt) => opt.allowBinding);
572
+ },
573
+ isNegatedOption: (state, segment, segmentIndex, name) => {
574
+ return !state.ignoreOptions && segment === `--no-${name.slice(2)}`;
575
+ },
576
+ isHelp: (state, segment) => {
577
+ return !state.ignoreOptions && HELP_REGEX.test(segment);
578
+ },
579
+ isUnsupportedOption: (state, segment, segmentIndex, names) => {
580
+ return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.has(segment);
581
+ },
582
+ isInvalidOption: (state, segment) => {
583
+ return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment);
584
+ }
585
+ };
586
+ var reducers = {
587
+ setCandidateState: (state, segment, segmentIndex, candidateState) => {
588
+ return { ...state, ...candidateState };
589
+ },
590
+ setSelectedIndex: (state, segment, segmentIndex, index) => {
591
+ return { ...state, selectedIndex: index };
592
+ },
593
+ pushBatch: (state, segment, segmentIndex, names) => {
594
+ const options = state.options.slice();
595
+ const tokens = state.tokens.slice();
596
+ for (let t = 1; t < segment.length; ++t) {
597
+ const name = names.get(`-${segment[t]}`);
598
+ const slice = t === 1 ? [0, 2] : [t, t + 1];
599
+ options.push({ name, value: true });
600
+ tokens.push({ segmentIndex, type: `option`, option: name, slice });
601
+ }
602
+ return { ...state, options, tokens };
603
+ },
604
+ pushBound: (state, segment, segmentIndex) => {
605
+ const [, name, value] = segment.match(BINDING_REGEX);
606
+ const options = state.options.concat({ name, value });
607
+ const tokens = state.tokens.concat([
608
+ { segmentIndex, type: `option`, slice: [0, name.length], option: name },
609
+ { segmentIndex, type: `assign`, slice: [name.length, name.length + 1] },
610
+ { segmentIndex, type: `value`, slice: [name.length + 1, name.length + value.length + 1] }
611
+ ]);
612
+ return { ...state, options, tokens };
613
+ },
614
+ pushPath: (state, segment, segmentIndex) => {
615
+ const path2 = state.path.concat(segment);
616
+ const tokens = state.tokens.concat({ segmentIndex, type: `path` });
617
+ return { ...state, path: path2, tokens };
618
+ },
619
+ pushPositional: (state, segment, segmentIndex) => {
620
+ const positionals = state.positionals.concat({ value: segment, extra: false });
621
+ const tokens = state.tokens.concat({ segmentIndex, type: `positional` });
622
+ return { ...state, positionals, tokens };
623
+ },
624
+ pushExtra: (state, segment, segmentIndex) => {
625
+ const positionals = state.positionals.concat({ value: segment, extra: true });
626
+ const tokens = state.tokens.concat({ segmentIndex, type: `positional` });
627
+ return { ...state, positionals, tokens };
628
+ },
629
+ pushExtraNoLimits: (state, segment, segmentIndex) => {
630
+ const positionals = state.positionals.concat({ value: segment, extra: NoLimits });
631
+ const tokens = state.tokens.concat({ segmentIndex, type: `positional` });
632
+ return { ...state, positionals, tokens };
633
+ },
634
+ pushTrue: (state, segment, segmentIndex, name) => {
635
+ const options = state.options.concat({ name, value: true });
636
+ const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });
637
+ return { ...state, options, tokens };
638
+ },
639
+ pushFalse: (state, segment, segmentIndex, name) => {
640
+ const options = state.options.concat({ name, value: false });
641
+ const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });
642
+ return { ...state, options, tokens };
643
+ },
644
+ pushUndefined: (state, segment, segmentIndex, name) => {
645
+ const options = state.options.concat({ name: segment, value: void 0 });
646
+ const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: segment });
647
+ return { ...state, options, tokens };
648
+ },
649
+ pushStringValue: (state, segment, segmentIndex) => {
650
+ var _a;
651
+ const lastOption = state.options[state.options.length - 1];
652
+ const options = state.options.slice();
653
+ const tokens = state.tokens.concat({ segmentIndex, type: `value` });
654
+ lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]);
655
+ return { ...state, options, tokens };
656
+ },
657
+ setStringValue: (state, segment, segmentIndex) => {
658
+ const lastOption = state.options[state.options.length - 1];
659
+ const options = state.options.slice();
660
+ const tokens = state.tokens.concat({ segmentIndex, type: `value` });
661
+ lastOption.value = segment;
662
+ return { ...state, options, tokens };
663
+ },
664
+ inhibateOptions: (state) => {
665
+ return { ...state, ignoreOptions: true };
666
+ },
667
+ useHelp: (state, segment, segmentIndex, command) => {
668
+ const [
669
+ ,
670
+ /* name */
671
+ ,
672
+ index
673
+ ] = segment.match(HELP_REGEX);
674
+ if (typeof index !== `undefined`) {
675
+ return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] };
676
+ } else {
677
+ return { ...state, options: [{ name: `-c`, value: String(command) }] };
678
+ }
679
+ },
680
+ setError: (state, segment, segmentIndex, errorMessage) => {
681
+ if (segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput) {
682
+ return { ...state, errorMessage: `${errorMessage}.` };
683
+ } else {
684
+ return { ...state, errorMessage: `${errorMessage} ("${segment}").` };
685
+ }
686
+ },
687
+ setOptionArityError: (state, segment) => {
688
+ const lastOption = state.options[state.options.length - 1];
689
+ return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` };
690
+ }
691
+ };
692
+ var NoLimits = Symbol();
693
+ var CommandBuilder = class {
694
+ constructor(cliIndex, cliOpts) {
695
+ this.allOptionNames = /* @__PURE__ */ new Map();
696
+ this.arity = { leading: [], trailing: [], extra: [], proxy: false };
697
+ this.options = [];
698
+ this.paths = [];
699
+ this.cliIndex = cliIndex;
700
+ this.cliOpts = cliOpts;
701
+ }
702
+ addPath(path2) {
703
+ this.paths.push(path2);
704
+ }
705
+ setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) {
706
+ Object.assign(this.arity, { leading, trailing, extra, proxy });
707
+ }
708
+ addPositional({ name = `arg`, required = true } = {}) {
709
+ if (!required && this.arity.extra === NoLimits)
710
+ throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`);
711
+ if (!required && this.arity.trailing.length > 0)
712
+ throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`);
713
+ if (!required && this.arity.extra !== NoLimits) {
714
+ this.arity.extra.push(name);
715
+ } else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) {
716
+ this.arity.leading.push(name);
717
+ } else {
718
+ this.arity.trailing.push(name);
719
+ }
720
+ }
721
+ addRest({ name = `arg`, required = 0 } = {}) {
722
+ if (this.arity.extra === NoLimits)
723
+ throw new Error(`Infinite lists cannot be declared multiple times in the same command`);
724
+ if (this.arity.trailing.length > 0)
725
+ throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`);
726
+ for (let t = 0; t < required; ++t)
727
+ this.addPositional({ name });
728
+ this.arity.extra = NoLimits;
729
+ }
730
+ addProxy({ required = 0 } = {}) {
731
+ this.addRest({ required });
732
+ this.arity.proxy = true;
733
+ }
734
+ addOption({ names: nameSet, description, arity = 0, hidden = false, required = false, allowBinding = true }) {
735
+ if (!allowBinding && arity > 1)
736
+ throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`);
737
+ if (!Number.isInteger(arity))
738
+ throw new Error(`The arity must be an integer, got ${arity}`);
739
+ if (arity < 0)
740
+ throw new Error(`The arity must be positive, got ${arity}`);
741
+ const preferredName = nameSet.reduce((longestName, name) => {
742
+ return name.length > longestName.length ? name : longestName;
743
+ }, ``);
744
+ for (const name of nameSet)
745
+ this.allOptionNames.set(name, preferredName);
746
+ this.options.push({ preferredName, nameSet, description, arity, hidden, required, allowBinding });
747
+ }
748
+ setContext(context) {
749
+ this.context = context;
750
+ }
751
+ usage({ detailed = true, inlineOptions = true } = {}) {
752
+ const segments = [this.cliOpts.binaryName];
753
+ const detailedOptionList = [];
754
+ if (this.paths.length > 0)
755
+ segments.push(...this.paths[0]);
756
+ if (detailed) {
757
+ for (const { preferredName, nameSet, arity, hidden, description, required } of this.options) {
758
+ if (hidden)
759
+ continue;
760
+ const args = [];
761
+ for (let t = 0; t < arity; ++t)
762
+ args.push(` #${t}`);
763
+ const definition = `${nameSet.join(`,`)}${args.join(``)}`;
764
+ if (!inlineOptions && description) {
765
+ detailedOptionList.push({ preferredName, nameSet, definition, description, required });
766
+ } else {
767
+ segments.push(required ? `<${definition}>` : `[${definition}]`);
768
+ }
769
+ }
770
+ segments.push(...this.arity.leading.map((name) => `<${name}>`));
771
+ if (this.arity.extra === NoLimits)
772
+ segments.push(`...`);
773
+ else
774
+ segments.push(...this.arity.extra.map((name) => `[${name}]`));
775
+ segments.push(...this.arity.trailing.map((name) => `<${name}>`));
776
+ }
777
+ const usage = segments.join(` `);
778
+ return { usage, options: detailedOptionList };
779
+ }
780
+ compile() {
781
+ if (typeof this.context === `undefined`)
782
+ throw new Error(`Assertion failed: No context attached`);
783
+ const machine = makeStateMachine();
784
+ let firstNode = NodeType.InitialNode;
785
+ const candidateUsage = this.usage().usage;
786
+ const requiredOptions = this.options.filter((opt) => opt.required).map((opt) => opt.nameSet);
787
+ firstNode = injectNode(machine, makeNode());
788
+ registerStatic(machine, NodeType.InitialNode, SpecialToken.StartOfInput, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]);
789
+ const positionalArgument = this.arity.proxy ? `always` : `isNotOptionLike`;
790
+ const paths = this.paths.length > 0 ? this.paths : [[]];
791
+ for (const path2 of paths) {
792
+ let lastPathNode = firstNode;
793
+ if (path2.length > 0) {
794
+ const optionPathNode = injectNode(machine, makeNode());
795
+ registerShortcut(machine, lastPathNode, optionPathNode);
796
+ this.registerOptions(machine, optionPathNode);
797
+ lastPathNode = optionPathNode;
798
+ }
799
+ for (let t = 0; t < path2.length; ++t) {
800
+ const nextPathNode = injectNode(machine, makeNode());
801
+ registerStatic(machine, lastPathNode, path2[t], nextPathNode, `pushPath`);
802
+ lastPathNode = nextPathNode;
803
+ if (t + 1 < path2.length) {
804
+ const helpNode = injectNode(machine, makeNode());
805
+ registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);
806
+ registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);
807
+ }
808
+ }
809
+ if (this.arity.leading.length > 0 || !this.arity.proxy) {
810
+ const helpNode = injectNode(machine, makeNode());
811
+ registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);
812
+ registerDynamic(machine, helpNode, `always`, helpNode, `pushExtra`);
813
+ registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);
814
+ this.registerOptions(machine, lastPathNode);
815
+ }
816
+ if (this.arity.leading.length > 0) {
817
+ registerStatic(machine, lastPathNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
818
+ registerStatic(machine, lastPathNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
819
+ }
820
+ let lastLeadingNode = lastPathNode;
821
+ for (let t = 0; t < this.arity.leading.length; ++t) {
822
+ const nextLeadingNode = injectNode(machine, makeNode());
823
+ if (!this.arity.proxy || t + 1 !== this.arity.leading.length)
824
+ this.registerOptions(machine, nextLeadingNode);
825
+ if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) {
826
+ registerStatic(machine, nextLeadingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
827
+ registerStatic(machine, nextLeadingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
828
+ }
829
+ registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`);
830
+ lastLeadingNode = nextLeadingNode;
831
+ }
832
+ let lastExtraNode = lastLeadingNode;
833
+ if (this.arity.extra === NoLimits || this.arity.extra.length > 0) {
834
+ const extraShortcutNode = injectNode(machine, makeNode());
835
+ registerShortcut(machine, lastLeadingNode, extraShortcutNode);
836
+ if (this.arity.extra === NoLimits) {
837
+ const extraNode = injectNode(machine, makeNode());
838
+ if (!this.arity.proxy)
839
+ this.registerOptions(machine, extraNode);
840
+ registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`);
841
+ registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`);
842
+ registerShortcut(machine, extraNode, extraShortcutNode);
843
+ } else {
844
+ for (let t = 0; t < this.arity.extra.length; ++t) {
845
+ const nextExtraNode = injectNode(machine, makeNode());
846
+ if (!this.arity.proxy || t > 0)
847
+ this.registerOptions(machine, nextExtraNode);
848
+ registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`);
849
+ registerShortcut(machine, nextExtraNode, extraShortcutNode);
850
+ lastExtraNode = nextExtraNode;
851
+ }
852
+ }
853
+ lastExtraNode = extraShortcutNode;
854
+ }
855
+ if (this.arity.trailing.length > 0) {
856
+ registerStatic(machine, lastExtraNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
857
+ registerStatic(machine, lastExtraNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
858
+ }
859
+ let lastTrailingNode = lastExtraNode;
860
+ for (let t = 0; t < this.arity.trailing.length; ++t) {
861
+ const nextTrailingNode = injectNode(machine, makeNode());
862
+ if (!this.arity.proxy)
863
+ this.registerOptions(machine, nextTrailingNode);
864
+ if (t + 1 < this.arity.trailing.length) {
865
+ registerStatic(machine, nextTrailingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);
866
+ registerStatic(machine, nextTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
867
+ }
868
+ registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`);
869
+ lastTrailingNode = nextTrailingNode;
870
+ }
871
+ registerDynamic(machine, lastTrailingNode, positionalArgument, NodeType.ErrorNode, [`setError`, `Extraneous positional argument`]);
872
+ registerStatic(machine, lastTrailingNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
873
+ registerStatic(machine, lastTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);
874
+ }
875
+ return {
876
+ machine,
877
+ context: this.context
878
+ };
879
+ }
880
+ registerOptions(machine, node) {
881
+ registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`);
882
+ registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, [`pushBatch`, this.allOptionNames]);
883
+ registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`);
884
+ registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NodeType.ErrorNode, [`setError`, `Unsupported option name`]);
885
+ registerDynamic(machine, node, [`isInvalidOption`], NodeType.ErrorNode, [`setError`, `Invalid option name`]);
886
+ for (const option of this.options) {
887
+ if (option.arity === 0) {
888
+ for (const name of option.nameSet) {
889
+ registerDynamic(machine, node, [`isOption`, name], node, [`pushTrue`, option.preferredName]);
890
+ if (name.startsWith(`--`) && !name.startsWith(`--no-`)) {
891
+ registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, option.preferredName]);
892
+ }
893
+ }
894
+ } else {
895
+ let lastNode = injectNode(machine, makeNode());
896
+ for (const name of option.nameSet)
897
+ registerDynamic(machine, node, [`isOption`, name], lastNode, [`pushUndefined`, option.preferredName]);
898
+ for (let t = 0; t < option.arity; ++t) {
899
+ const nextNode = injectNode(machine, makeNode());
900
+ registerStatic(machine, lastNode, SpecialToken.EndOfInput, NodeType.ErrorNode, `setOptionArityError`);
901
+ registerStatic(machine, lastNode, SpecialToken.EndOfPartialInput, NodeType.ErrorNode, `setOptionArityError`);
902
+ registerDynamic(machine, lastNode, `isOptionLike`, NodeType.ErrorNode, `setOptionArityError`);
903
+ const action = option.arity === 1 ? `setStringValue` : `pushStringValue`;
904
+ registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action);
905
+ lastNode = nextNode;
906
+ }
907
+ registerShortcut(machine, lastNode, node);
908
+ }
909
+ }
910
+ }
911
+ };
912
+ var CliBuilder = class _CliBuilder {
913
+ static build(cbs, opts = {}) {
914
+ return new _CliBuilder(opts).commands(cbs).compile();
915
+ }
916
+ constructor({ binaryName = `...` } = {}) {
917
+ this.builders = [];
918
+ this.opts = { binaryName };
919
+ }
920
+ getBuilderByIndex(n) {
921
+ if (!(n >= 0 && n < this.builders.length))
922
+ throw new Error(`Assertion failed: Out-of-bound command index (${n})`);
923
+ return this.builders[n];
924
+ }
925
+ commands(cbs) {
926
+ for (const cb of cbs)
927
+ cb(this.command());
928
+ return this;
929
+ }
930
+ command() {
931
+ const builder = new CommandBuilder(this.builders.length, this.opts);
932
+ this.builders.push(builder);
933
+ return builder;
934
+ }
935
+ compile() {
936
+ const machines = [];
937
+ const contexts = [];
938
+ for (const builder of this.builders) {
939
+ const { machine: machine2, context } = builder.compile();
940
+ machines.push(machine2);
941
+ contexts.push(context);
942
+ }
943
+ const machine = makeAnyOfMachine(machines);
944
+ simplifyMachine(machine);
945
+ return {
946
+ machine,
947
+ contexts,
948
+ process: (input, { partial } = {}) => {
949
+ const endToken = partial ? SpecialToken.EndOfPartialInput : SpecialToken.EndOfInput;
950
+ return runMachine(machine, input, { endToken });
951
+ }
952
+ };
953
+ }
954
+ };
955
+
956
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/format.mjs
957
+ init_esm_shims();
958
+ var MAX_LINE_LENGTH = 80;
959
+ var richLine = Array(MAX_LINE_LENGTH).fill(`\u2501`);
960
+ for (let t = 0; t <= 24; ++t)
961
+ richLine[richLine.length - t] = `\x1B[38;5;${232 + t}m\u2501`;
962
+ var richFormat = {
963
+ header: (str) => `\x1B[1m\u2501\u2501\u2501 ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\x1B[0m`,
964
+ bold: (str) => `\x1B[1m${str}\x1B[22m`,
965
+ error: (str) => `\x1B[31m\x1B[1m${str}\x1B[22m\x1B[39m`,
966
+ code: (str) => `\x1B[36m${str}\x1B[39m`
967
+ };
968
+ var textFormat = {
969
+ header: (str) => str,
970
+ bold: (str) => str,
971
+ error: (str) => str,
972
+ code: (str) => str
973
+ };
974
+ function dedent(text) {
975
+ const lines = text.split(`
976
+ `);
977
+ const nonEmptyLines = lines.filter((line) => line.match(/\S/));
978
+ const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0;
979
+ return lines.map((line) => line.slice(indent).trimRight()).join(`
980
+ `);
981
+ }
982
+ function formatMarkdownish(text, { format, paragraphs }) {
983
+ text = text.replace(/\r\n?/g, `
984
+ `);
985
+ text = dedent(text);
986
+ text = text.replace(/^\n+|\n+$/g, ``);
987
+ text = text.replace(/^(\s*)-([^\n]*?)\n+/gm, `$1-$2
988
+
989
+ `);
990
+ text = text.replace(/\n(\n)?\n*/g, ($0, $1) => $1 ? $1 : ` `);
991
+ if (paragraphs) {
992
+ text = text.split(/\n/).map((paragraph) => {
993
+ const bulletMatch = paragraph.match(/^\s*[*-][\t ]+(.*)/);
994
+ if (!bulletMatch)
995
+ return paragraph.match(/(.{1,80})(?: |$)/g).join(`
996
+ `);
997
+ const indent = paragraph.length - paragraph.trimStart().length;
998
+ return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => {
999
+ return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line;
1000
+ }).join(`
1001
+ `);
1002
+ }).join(`
1003
+
1004
+ `);
1005
+ }
1006
+ text = text.replace(/(`+)((?:.|[\n])*?)\1/g, ($0, $1, $2) => {
1007
+ return format.code($1 + $2 + $1);
1008
+ });
1009
+ text = text.replace(/(\*\*)((?:.|[\n])*?)\1/g, ($0, $1, $2) => {
1010
+ return format.bold($1 + $2 + $1);
1011
+ });
1012
+ return text ? `${text}
1013
+ ` : ``;
1014
+ }
1015
+
1016
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/HelpCommand.mjs
1017
+ init_esm_shims();
1018
+ var HelpCommand = class _HelpCommand extends Command {
1019
+ static from(state, contexts) {
1020
+ const command = new _HelpCommand(contexts);
1021
+ command.path = state.path;
1022
+ for (const opt of state.options) {
1023
+ switch (opt.name) {
1024
+ case `-c`:
1025
+ {
1026
+ command.commands.push(Number(opt.value));
1027
+ }
1028
+ break;
1029
+ case `-i`:
1030
+ {
1031
+ command.index = Number(opt.value);
1032
+ }
1033
+ break;
1034
+ }
1035
+ }
1036
+ return command;
1037
+ }
1038
+ constructor(contexts) {
1039
+ super();
1040
+ this.contexts = contexts;
1041
+ this.commands = [];
1042
+ }
1043
+ async execute() {
1044
+ let commands = this.commands;
1045
+ if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length)
1046
+ commands = [commands[this.index]];
1047
+ if (commands.length === 0) {
1048
+ this.context.stdout.write(this.cli.usage());
1049
+ } else if (commands.length === 1) {
1050
+ this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true }));
1051
+ } else if (commands.length > 1) {
1052
+ this.context.stdout.write(`Multiple commands match your selection:
1053
+ `);
1054
+ this.context.stdout.write(`
1055
+ `);
1056
+ let index = 0;
1057
+ for (const command of this.commands)
1058
+ this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) }));
1059
+ this.context.stdout.write(`
1060
+ `);
1061
+ this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.
1062
+ `);
1063
+ }
1064
+ }
1065
+ };
1066
+
1067
+ // ../../.yarn/__virtual__/clipanion-virtual-8d4993908b/0/cache/clipanion-npm-4.0.0-rc.4-8228e3d944-047b415b59.zip/node_modules/clipanion/lib/advanced/Cli.mjs
1068
+ var errorCommandSymbol = Symbol(`clipanion/errorCommand`);
1069
+ var Cli = class _Cli {
1070
+ /**
1071
+ * Creates a new Cli and registers all commands passed as parameters.
1072
+ *
1073
+ * @param commandClasses The Commands to register
1074
+ * @returns The created `Cli` instance
1075
+ */
1076
+ static from(commandClasses, options = {}) {
1077
+ const cli2 = new _Cli(options);
1078
+ const resolvedCommandClasses = Array.isArray(commandClasses) ? commandClasses : [commandClasses];
1079
+ for (const commandClass of resolvedCommandClasses)
1080
+ cli2.register(commandClass);
1081
+ return cli2;
1082
+ }
1083
+ constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors } = {}) {
1084
+ this.registrations = /* @__PURE__ */ new Map();
1085
+ this.builder = new CliBuilder({ binaryName: binaryNameOpt });
1086
+ this.binaryLabel = binaryLabel;
1087
+ this.binaryName = binaryNameOpt;
1088
+ this.binaryVersion = binaryVersion;
1089
+ this.enableCapture = enableCapture;
1090
+ this.enableColors = enableColors;
1091
+ }
1092
+ /**
1093
+ * Registers a command inside the CLI.
1094
+ */
1095
+ register(commandClass) {
1096
+ var _a;
1097
+ if (this.registrations.has(commandClass))
1098
+ throw new RangeError(`${commandClass.name} has already been registered`);
1099
+ const specs = /* @__PURE__ */ new Map();
1100
+ const command = new commandClass();
1101
+ for (const key in command) {
1102
+ const value = command[key];
1103
+ if (typeof value === `object` && value !== null && value[Command.isOption]) {
1104
+ specs.set(key, value);
1105
+ }
1106
+ }
1107
+ const builder = this.builder.command();
1108
+ const index = builder.cliIndex;
1109
+ const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths;
1110
+ if (typeof paths !== `undefined`)
1111
+ for (const path2 of paths)
1112
+ builder.addPath(path2);
1113
+ this.registrations.set(commandClass, { specs, builder, index });
1114
+ for (const [key, { definition }] of specs.entries())
1115
+ definition(builder, key);
1116
+ builder.setContext({
1117
+ commandClass
1118
+ });
1119
+ }
1120
+ process(opts, contextArg) {
1121
+ const { input, context: userContext, partial } = typeof opts === `object` && Array.isArray(opts) ? { input: opts, context: contextArg } : opts;
1122
+ const { contexts, process: process2 } = this.builder.compile();
1123
+ const state = process2(input, { partial });
1124
+ const context = {
1125
+ ..._Cli.defaultContext,
1126
+ ...userContext
1127
+ };
1128
+ switch (state.selectedIndex) {
1129
+ case HELP_COMMAND_INDEX: {
1130
+ const command = HelpCommand.from(state, contexts);
1131
+ command.context = context;
1132
+ command.tokens = state.tokens;
1133
+ return command;
1134
+ }
1135
+ default:
1136
+ {
1137
+ const { commandClass } = contexts[state.selectedIndex];
1138
+ const record = this.registrations.get(commandClass);
1139
+ if (typeof record === `undefined`)
1140
+ throw new Error(`Assertion failed: Expected the command class to have been registered.`);
1141
+ const command = new commandClass();
1142
+ command.context = context;
1143
+ command.tokens = state.tokens;
1144
+ command.path = state.path;
1145
+ try {
1146
+ for (const [key, { transformer }] of record.specs.entries())
1147
+ command[key] = transformer(record.builder, key, state, context);
1148
+ return command;
1149
+ } catch (error) {
1150
+ error[errorCommandSymbol] = command;
1151
+ throw error;
1152
+ }
1153
+ }
1154
+ break;
1155
+ }
1156
+ }
1157
+ async run(input, userContext) {
1158
+ var _a, _b;
1159
+ let command;
1160
+ const context = {
1161
+ ..._Cli.defaultContext,
1162
+ ...userContext
1163
+ };
1164
+ const colored = (_a = this.enableColors) !== null && _a !== void 0 ? _a : context.colorDepth > 1;
1165
+ if (!Array.isArray(input)) {
1166
+ command = input;
1167
+ } else {
1168
+ try {
1169
+ command = this.process(input, context);
1170
+ } catch (error) {
1171
+ context.stdout.write(this.error(error, { colored }));
1172
+ return 1;
1173
+ }
1174
+ }
1175
+ if (command.help) {
1176
+ context.stdout.write(this.usage(command, { colored, detailed: true }));
1177
+ return 0;
1178
+ }
1179
+ command.context = context;
1180
+ command.cli = {
1181
+ binaryLabel: this.binaryLabel,
1182
+ binaryName: this.binaryName,
1183
+ binaryVersion: this.binaryVersion,
1184
+ enableCapture: this.enableCapture,
1185
+ enableColors: this.enableColors,
1186
+ definitions: () => this.definitions(),
1187
+ definition: (command2) => this.definition(command2),
1188
+ error: (error, opts) => this.error(error, opts),
1189
+ format: (colored2) => this.format(colored2),
1190
+ process: (input2, subContext) => this.process(input2, { ...context, ...subContext }),
1191
+ run: (input2, subContext) => this.run(input2, { ...context, ...subContext }),
1192
+ usage: (command2, opts) => this.usage(command2, opts)
1193
+ };
1194
+ const activate = this.enableCapture ? (_b = getCaptureActivator(context)) !== null && _b !== void 0 ? _b : noopCaptureActivator : noopCaptureActivator;
1195
+ let exitCode;
1196
+ try {
1197
+ exitCode = await activate(() => command.validateAndExecute().catch((error) => command.catch(error).then(() => 0)));
1198
+ } catch (error) {
1199
+ context.stdout.write(this.error(error, { colored, command }));
1200
+ return 1;
1201
+ }
1202
+ return exitCode;
1203
+ }
1204
+ async runExit(input, context) {
1205
+ process.exitCode = await this.run(input, context);
1206
+ }
1207
+ definition(commandClass, { colored = false } = {}) {
1208
+ if (!commandClass.usage)
1209
+ return null;
1210
+ const { usage: path2 } = this.getUsageByRegistration(commandClass, { detailed: false });
1211
+ const { usage, options } = this.getUsageByRegistration(commandClass, { detailed: true, inlineOptions: false });
1212
+ const category = typeof commandClass.usage.category !== `undefined` ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) : void 0;
1213
+ const description = typeof commandClass.usage.description !== `undefined` ? formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false }) : void 0;
1214
+ const details = typeof commandClass.usage.details !== `undefined` ? formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true }) : void 0;
1215
+ const examples = typeof commandClass.usage.examples !== `undefined` ? commandClass.usage.examples.map(([label, cli2]) => [formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli2.replace(/\$0/g, this.binaryName)]) : void 0;
1216
+ return { path: path2, usage, category, description, details, examples, options };
1217
+ }
1218
+ definitions({ colored = false } = {}) {
1219
+ const data = [];
1220
+ for (const commandClass of this.registrations.keys()) {
1221
+ const usage = this.definition(commandClass, { colored });
1222
+ if (!usage)
1223
+ continue;
1224
+ data.push(usage);
1225
+ }
1226
+ return data;
1227
+ }
1228
+ usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) {
1229
+ var _a;
1230
+ if (command === null) {
1231
+ for (const commandClass2 of this.registrations.keys()) {
1232
+ const paths = commandClass2.paths;
1233
+ const isDocumented = typeof commandClass2.usage !== `undefined`;
1234
+ const isExclusivelyDefault = !paths || paths.length === 0 || paths.length === 1 && paths[0].length === 0;
1235
+ const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some((path2) => path2.length === 0)) !== null && _a !== void 0 ? _a : false);
1236
+ if (isDefault) {
1237
+ if (command) {
1238
+ command = null;
1239
+ break;
1240
+ } else {
1241
+ command = commandClass2;
1242
+ }
1243
+ } else {
1244
+ if (isDocumented) {
1245
+ command = null;
1246
+ continue;
1247
+ }
1248
+ }
1249
+ }
1250
+ if (command) {
1251
+ detailed = true;
1252
+ }
1253
+ }
1254
+ const commandClass = command !== null && command instanceof Command ? command.constructor : command;
1255
+ let result = ``;
1256
+ if (!commandClass) {
1257
+ const commandsByCategories = /* @__PURE__ */ new Map();
1258
+ for (const [commandClass2, { index }] of this.registrations.entries()) {
1259
+ if (typeof commandClass2.usage === `undefined`)
1260
+ continue;
1261
+ const category = typeof commandClass2.usage.category !== `undefined` ? formatMarkdownish(commandClass2.usage.category, { format: this.format(colored), paragraphs: false }) : null;
1262
+ let categoryCommands = commandsByCategories.get(category);
1263
+ if (typeof categoryCommands === `undefined`)
1264
+ commandsByCategories.set(category, categoryCommands = []);
1265
+ const { usage } = this.getUsageByIndex(index);
1266
+ categoryCommands.push({ commandClass: commandClass2, usage });
1267
+ }
1268
+ const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => {
1269
+ if (a === null)
1270
+ return -1;
1271
+ if (b === null)
1272
+ return 1;
1273
+ return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` });
1274
+ });
1275
+ const hasLabel = typeof this.binaryLabel !== `undefined`;
1276
+ const hasVersion = typeof this.binaryVersion !== `undefined`;
1277
+ if (hasLabel || hasVersion) {
1278
+ if (hasLabel && hasVersion)
1279
+ result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}
1280
+
1281
+ `;
1282
+ else if (hasLabel)
1283
+ result += `${this.format(colored).header(`${this.binaryLabel}`)}
1284
+ `;
1285
+ else
1286
+ result += `${this.format(colored).header(`${this.binaryVersion}`)}
1287
+ `;
1288
+ result += ` ${this.format(colored).bold(prefix)}${this.binaryName} <command>
1289
+ `;
1290
+ } else {
1291
+ result += `${this.format(colored).bold(prefix)}${this.binaryName} <command>
1292
+ `;
1293
+ }
1294
+ for (const categoryName of categoryNames) {
1295
+ const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => {
1296
+ return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` });
1297
+ });
1298
+ const header = categoryName !== null ? categoryName.trim() : `General commands`;
1299
+ result += `
1300
+ `;
1301
+ result += `${this.format(colored).header(`${header}`)}
1302
+ `;
1303
+ for (const { commandClass: commandClass2, usage } of commands) {
1304
+ const doc = commandClass2.usage.description || `undocumented`;
1305
+ result += `
1306
+ `;
1307
+ result += ` ${this.format(colored).bold(usage)}
1308
+ `;
1309
+ result += ` ${formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`;
1310
+ }
1311
+ }
1312
+ result += `
1313
+ `;
1314
+ result += formatMarkdownish(`You can also print more details about any of these commands by calling them with the \`-h,--help\` flag right after the command name.`, { format: this.format(colored), paragraphs: true });
1315
+ } else {
1316
+ if (!detailed) {
1317
+ const { usage } = this.getUsageByRegistration(commandClass);
1318
+ result += `${this.format(colored).bold(prefix)}${usage}
1319
+ `;
1320
+ } else {
1321
+ const { description = ``, details = ``, examples = [] } = commandClass.usage || {};
1322
+ if (description !== ``) {
1323
+ result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, ($0) => $0.toUpperCase());
1324
+ result += `
1325
+ `;
1326
+ }
1327
+ if (details !== `` || examples.length > 0) {
1328
+ result += `${this.format(colored).header(`Usage`)}
1329
+ `;
1330
+ result += `
1331
+ `;
1332
+ }
1333
+ const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false });
1334
+ result += `${this.format(colored).bold(prefix)}${usage}
1335
+ `;
1336
+ if (options.length > 0) {
1337
+ result += `
1338
+ `;
1339
+ result += `${this.format(colored).header(`Options`)}
1340
+ `;
1341
+ const maxDefinitionLength = options.reduce((length, option) => {
1342
+ return Math.max(length, option.definition.length);
1343
+ }, 0);
1344
+ result += `
1345
+ `;
1346
+ for (const { definition, description: description2 } of options) {
1347
+ result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${formatMarkdownish(description2, { format: this.format(colored), paragraphs: false })}`;
1348
+ }
1349
+ }
1350
+ if (details !== ``) {
1351
+ result += `
1352
+ `;
1353
+ result += `${this.format(colored).header(`Details`)}
1354
+ `;
1355
+ result += `
1356
+ `;
1357
+ result += formatMarkdownish(details, { format: this.format(colored), paragraphs: true });
1358
+ }
1359
+ if (examples.length > 0) {
1360
+ result += `
1361
+ `;
1362
+ result += `${this.format(colored).header(`Examples`)}
1363
+ `;
1364
+ for (const [description2, example] of examples) {
1365
+ result += `
1366
+ `;
1367
+ result += formatMarkdownish(description2, { format: this.format(colored), paragraphs: false });
1368
+ result += `${example.replace(/^/m, ` ${this.format(colored).bold(prefix)}`).replace(/\$0/g, this.binaryName)}
1369
+ `;
1370
+ }
1371
+ }
1372
+ }
1373
+ }
1374
+ return result;
1375
+ }
1376
+ error(error, _a) {
1377
+ var _b;
1378
+ var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a;
1379
+ if (!error || typeof error !== `object` || !(`stack` in error))
1380
+ error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`);
1381
+ let result = ``;
1382
+ let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`);
1383
+ if (name === `Error`)
1384
+ name = `Internal Error`;
1385
+ result += `${this.format(colored).error(name)}: ${error.message}
1386
+ `;
1387
+ const meta = error.clipanion;
1388
+ if (typeof meta !== `undefined`) {
1389
+ if (meta.type === `usage`) {
1390
+ result += `
1391
+ `;
1392
+ result += this.usage(command);
1393
+ }
1394
+ } else {
1395
+ if (error.stack) {
1396
+ result += `${error.stack.replace(/^.*\n/, ``)}
1397
+ `;
1398
+ }
1399
+ }
1400
+ return result;
1401
+ }
1402
+ format(colored) {
1403
+ var _a;
1404
+ return ((_a = colored !== null && colored !== void 0 ? colored : this.enableColors) !== null && _a !== void 0 ? _a : _Cli.defaultContext.colorDepth > 1) ? richFormat : textFormat;
1405
+ }
1406
+ getUsageByRegistration(klass, opts) {
1407
+ const record = this.registrations.get(klass);
1408
+ if (typeof record === `undefined`)
1409
+ throw new Error(`Assertion failed: Unregistered command`);
1410
+ return this.getUsageByIndex(record.index, opts);
1411
+ }
1412
+ getUsageByIndex(n, opts) {
1413
+ return this.builder.getBuilderByIndex(n).usage(opts);
1414
+ }
1415
+ };
1416
+ Cli.defaultContext = {
1417
+ env: process.env,
1418
+ stdin: process.stdin,
1419
+ stdout: process.stdout,
1420
+ stderr: process.stderr,
1421
+ colorDepth: getDefaultColorDepth()
1422
+ };
1423
+ function noopCaptureActivator(fn) {
1424
+ return fn();
1425
+ }
1426
+
1427
+ // src/commands/DevCommand.ts
1428
+ init_esm_shims();
1429
+
1430
+ // ../../.yarn/__virtual__/@hono-node-server-virtual-cf2888014c/0/cache/@hono-node-server-npm-1.13.8-e78cfff928-5880892fdd.zip/node_modules/@hono/node-server/dist/index.mjs
1431
+ init_esm_shims();
1432
+ import { createServer as createServerHTTP } from "http";
1433
+ import { Http2ServerRequest } from "http2";
1434
+ import { Readable } from "stream";
1435
+ import crypto from "crypto";
1436
+ var RequestError = class extends Error {
1437
+ static name = "RequestError";
1438
+ constructor(message, options) {
1439
+ super(message, options);
1440
+ }
1441
+ };
1442
+ var toRequestError = (e) => {
1443
+ if (e instanceof RequestError) {
1444
+ return e;
1445
+ }
1446
+ return new RequestError(e.message, { cause: e });
1447
+ };
1448
+ var GlobalRequest = global.Request;
1449
+ var Request2 = class extends GlobalRequest {
1450
+ constructor(input, options) {
1451
+ if (typeof input === "object" && getRequestCache in input) {
1452
+ input = input[getRequestCache]();
1453
+ }
1454
+ if (typeof options?.body?.getReader !== "undefined") {
1455
+ ;
1456
+ options.duplex ??= "half";
1457
+ }
1458
+ super(input, options);
1459
+ }
1460
+ };
1461
+ var newRequestFromIncoming = (method, url, incoming, abortController) => {
1462
+ const headerRecord = [];
1463
+ const rawHeaders = incoming.rawHeaders;
1464
+ for (let i = 0; i < rawHeaders.length; i += 2) {
1465
+ const { [i]: key, [i + 1]: value } = rawHeaders;
1466
+ if (key.charCodeAt(0) !== /*:*/
1467
+ 58) {
1468
+ headerRecord.push([key, value]);
1469
+ }
1470
+ }
1471
+ const init = {
1472
+ method,
1473
+ headers: headerRecord,
1474
+ signal: abortController.signal
1475
+ };
1476
+ if (method === "TRACE") {
1477
+ init.method = "GET";
1478
+ const req = new Request2(url, init);
1479
+ Object.defineProperty(req, "method", {
1480
+ get() {
1481
+ return "TRACE";
1482
+ }
1483
+ });
1484
+ return req;
1485
+ }
1486
+ if (!(method === "GET" || method === "HEAD")) {
1487
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
1488
+ init.body = new ReadableStream({
1489
+ start(controller) {
1490
+ controller.enqueue(incoming.rawBody);
1491
+ controller.close();
1492
+ }
1493
+ });
1494
+ } else {
1495
+ init.body = Readable.toWeb(incoming);
1496
+ }
1497
+ }
1498
+ return new Request2(url, init);
1499
+ };
1500
+ var getRequestCache = Symbol("getRequestCache");
1501
+ var requestCache = Symbol("requestCache");
1502
+ var incomingKey = Symbol("incomingKey");
1503
+ var urlKey = Symbol("urlKey");
1504
+ var abortControllerKey = Symbol("abortControllerKey");
1505
+ var getAbortController = Symbol("getAbortController");
1506
+ var requestPrototype = {
1507
+ get method() {
1508
+ return this[incomingKey].method || "GET";
1509
+ },
1510
+ get url() {
1511
+ return this[urlKey];
1512
+ },
1513
+ [getAbortController]() {
1514
+ this[getRequestCache]();
1515
+ return this[abortControllerKey];
1516
+ },
1517
+ [getRequestCache]() {
1518
+ this[abortControllerKey] ||= new AbortController();
1519
+ return this[requestCache] ||= newRequestFromIncoming(
1520
+ this.method,
1521
+ this[urlKey],
1522
+ this[incomingKey],
1523
+ this[abortControllerKey]
1524
+ );
1525
+ }
1526
+ };
1527
+ [
1528
+ "body",
1529
+ "bodyUsed",
1530
+ "cache",
1531
+ "credentials",
1532
+ "destination",
1533
+ "headers",
1534
+ "integrity",
1535
+ "mode",
1536
+ "redirect",
1537
+ "referrer",
1538
+ "referrerPolicy",
1539
+ "signal",
1540
+ "keepalive"
1541
+ ].forEach((k) => {
1542
+ Object.defineProperty(requestPrototype, k, {
1543
+ get() {
1544
+ return this[getRequestCache]()[k];
1545
+ }
1546
+ });
1547
+ });
1548
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
1549
+ Object.defineProperty(requestPrototype, k, {
1550
+ value: function() {
1551
+ return this[getRequestCache]()[k]();
1552
+ }
1553
+ });
1554
+ });
1555
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
1556
+ var newRequest = (incoming, defaultHostname) => {
1557
+ const req = Object.create(requestPrototype);
1558
+ req[incomingKey] = incoming;
1559
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
1560
+ if (!host) {
1561
+ throw new RequestError("Missing host header");
1562
+ }
1563
+ const url = new URL(
1564
+ `${incoming instanceof Http2ServerRequest || incoming.socket && incoming.socket.encrypted ? "https" : "http"}://${host}${incoming.url}`
1565
+ );
1566
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
1567
+ throw new RequestError("Invalid host header");
1568
+ }
1569
+ req[urlKey] = url.href;
1570
+ return req;
1571
+ };
1572
+ function writeFromReadableStream(stream, writable) {
1573
+ if (stream.locked) {
1574
+ throw new TypeError("ReadableStream is locked.");
1575
+ } else if (writable.destroyed) {
1576
+ stream.cancel();
1577
+ return;
1578
+ }
1579
+ const reader = stream.getReader();
1580
+ writable.on("close", cancel);
1581
+ writable.on("error", cancel);
1582
+ reader.read().then(flow, cancel);
1583
+ return reader.closed.finally(() => {
1584
+ writable.off("close", cancel);
1585
+ writable.off("error", cancel);
1586
+ });
1587
+ function cancel(error) {
1588
+ reader.cancel(error).catch(() => {
1589
+ });
1590
+ if (error) {
1591
+ writable.destroy(error);
1592
+ }
1593
+ }
1594
+ function onDrain() {
1595
+ reader.read().then(flow, cancel);
1596
+ }
1597
+ function flow({ done, value }) {
1598
+ try {
1599
+ if (done) {
1600
+ writable.end();
1601
+ } else if (!writable.write(value)) {
1602
+ writable.once("drain", onDrain);
1603
+ } else {
1604
+ return reader.read().then(flow, cancel);
1605
+ }
1606
+ } catch (e) {
1607
+ cancel(e);
1608
+ }
1609
+ }
1610
+ }
1611
+ var buildOutgoingHttpHeaders = (headers) => {
1612
+ const res = {};
1613
+ if (!(headers instanceof Headers)) {
1614
+ headers = new Headers(headers ?? void 0);
1615
+ }
1616
+ const cookies = [];
1617
+ for (const [k, v] of headers) {
1618
+ if (k === "set-cookie") {
1619
+ cookies.push(v);
1620
+ } else {
1621
+ res[k] = v;
1622
+ }
1623
+ }
1624
+ if (cookies.length > 0) {
1625
+ res["set-cookie"] = cookies;
1626
+ }
1627
+ res["content-type"] ??= "text/plain; charset=UTF-8";
1628
+ return res;
1629
+ };
1630
+ var responseCache = Symbol("responseCache");
1631
+ var getResponseCache = Symbol("getResponseCache");
1632
+ var cacheKey = Symbol("cache");
1633
+ var GlobalResponse = global.Response;
1634
+ var Response2 = class _Response {
1635
+ #body;
1636
+ #init;
1637
+ [getResponseCache]() {
1638
+ delete this[cacheKey];
1639
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
1640
+ }
1641
+ constructor(body, init) {
1642
+ this.#body = body;
1643
+ if (init instanceof _Response) {
1644
+ const cachedGlobalResponse = init[responseCache];
1645
+ if (cachedGlobalResponse) {
1646
+ this.#init = cachedGlobalResponse;
1647
+ this[getResponseCache]();
1648
+ return;
1649
+ } else {
1650
+ this.#init = init.#init;
1651
+ }
1652
+ } else {
1653
+ this.#init = init;
1654
+ }
1655
+ if (typeof body === "string" || typeof body?.getReader !== "undefined") {
1656
+ let headers = init?.headers || { "content-type": "text/plain; charset=UTF-8" };
1657
+ if (headers instanceof Headers) {
1658
+ headers = buildOutgoingHttpHeaders(headers);
1659
+ }
1660
+ ;
1661
+ this[cacheKey] = [init?.status || 200, body, headers];
1662
+ }
1663
+ }
1664
+ };
1665
+ [
1666
+ "body",
1667
+ "bodyUsed",
1668
+ "headers",
1669
+ "ok",
1670
+ "redirected",
1671
+ "status",
1672
+ "statusText",
1673
+ "trailers",
1674
+ "type",
1675
+ "url"
1676
+ ].forEach((k) => {
1677
+ Object.defineProperty(Response2.prototype, k, {
1678
+ get() {
1679
+ return this[getResponseCache]()[k];
1680
+ }
1681
+ });
1682
+ });
1683
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
1684
+ Object.defineProperty(Response2.prototype, k, {
1685
+ value: function() {
1686
+ return this[getResponseCache]()[k]();
1687
+ }
1688
+ });
1689
+ });
1690
+ Object.setPrototypeOf(Response2, GlobalResponse);
1691
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
1692
+ var stateKey = Reflect.ownKeys(new GlobalResponse()).find(
1693
+ (k) => typeof k === "symbol" && k.toString() === "Symbol(state)"
1694
+ );
1695
+ if (!stateKey) {
1696
+ console.warn("Failed to find Response internal state key");
1697
+ }
1698
+ function getInternalBody(response) {
1699
+ if (!stateKey) {
1700
+ return;
1701
+ }
1702
+ if (response instanceof Response2) {
1703
+ response = response[getResponseCache]();
1704
+ }
1705
+ const state = response[stateKey];
1706
+ return state && state.body || void 0;
1707
+ }
1708
+ var X_ALREADY_SENT = "x-hono-already-sent";
1709
+ var webFetch = global.fetch;
1710
+ if (typeof global.crypto === "undefined") {
1711
+ global.crypto = crypto;
1712
+ }
1713
+ global.fetch = (info, init) => {
1714
+ init = {
1715
+ // Disable compression handling so people can return the result of a fetch
1716
+ // directly in the loader without messing with the Content-Encoding header.
1717
+ compress: false,
1718
+ ...init
1719
+ };
1720
+ return webFetch(info, init);
1721
+ };
1722
+ var regBuffer = /^no$/i;
1723
+ var regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
1724
+ var handleRequestError = () => new Response(null, {
1725
+ status: 400
1726
+ });
1727
+ var handleFetchError = (e) => new Response(null, {
1728
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
1729
+ });
1730
+ var handleResponseError = (e, outgoing) => {
1731
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
1732
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
1733
+ console.info("The user aborted a request.");
1734
+ } else {
1735
+ console.error(e);
1736
+ if (!outgoing.headersSent) {
1737
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
1738
+ }
1739
+ outgoing.end(`Error: ${err.message}`);
1740
+ outgoing.destroy(err);
1741
+ }
1742
+ };
1743
+ var responseViaCache = (res, outgoing) => {
1744
+ const [status, body, header] = res[cacheKey];
1745
+ if (typeof body === "string") {
1746
+ header["Content-Length"] = Buffer.byteLength(body);
1747
+ outgoing.writeHead(status, header);
1748
+ outgoing.end(body);
1749
+ } else {
1750
+ outgoing.writeHead(status, header);
1751
+ return writeFromReadableStream(body, outgoing)?.catch(
1752
+ (e) => handleResponseError(e, outgoing)
1753
+ );
1754
+ }
1755
+ };
1756
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
1757
+ if (res instanceof Promise) {
1758
+ if (options.errorHandler) {
1759
+ try {
1760
+ res = await res;
1761
+ } catch (err) {
1762
+ const errRes = await options.errorHandler(err);
1763
+ if (!errRes) {
1764
+ return;
1765
+ }
1766
+ res = errRes;
1767
+ }
1768
+ } else {
1769
+ res = await res.catch(handleFetchError);
1770
+ }
1771
+ }
1772
+ if (cacheKey in res) {
1773
+ return responseViaCache(res, outgoing);
1774
+ }
1775
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
1776
+ const internalBody = getInternalBody(res);
1777
+ if (internalBody) {
1778
+ const { length, source, stream } = internalBody;
1779
+ if (source instanceof Uint8Array && source.byteLength !== length) {
1780
+ } else {
1781
+ if (length) {
1782
+ resHeaderRecord["content-length"] = length;
1783
+ }
1784
+ outgoing.writeHead(res.status, resHeaderRecord);
1785
+ if (typeof source === "string" || source instanceof Uint8Array) {
1786
+ outgoing.end(source);
1787
+ } else if (source instanceof Blob) {
1788
+ outgoing.end(new Uint8Array(await source.arrayBuffer()));
1789
+ } else {
1790
+ await writeFromReadableStream(stream, outgoing);
1791
+ }
1792
+ return;
1793
+ }
1794
+ }
1795
+ if (res.body) {
1796
+ const {
1797
+ "transfer-encoding": transferEncoding,
1798
+ "content-encoding": contentEncoding,
1799
+ "content-length": contentLength,
1800
+ "x-accel-buffering": accelBuffering,
1801
+ "content-type": contentType
1802
+ } = resHeaderRecord;
1803
+ if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
1804
+ accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
1805
+ outgoing.writeHead(res.status, resHeaderRecord);
1806
+ await writeFromReadableStream(res.body, outgoing);
1807
+ } else {
1808
+ const buffer = await res.arrayBuffer();
1809
+ resHeaderRecord["content-length"] = buffer.byteLength;
1810
+ outgoing.writeHead(res.status, resHeaderRecord);
1811
+ outgoing.end(new Uint8Array(buffer));
1812
+ }
1813
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
1814
+ } else {
1815
+ outgoing.writeHead(res.status, resHeaderRecord);
1816
+ outgoing.end();
1817
+ }
1818
+ };
1819
+ var getRequestListener = (fetchCallback, options = {}) => {
1820
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
1821
+ Object.defineProperty(global, "Request", {
1822
+ value: Request2
1823
+ });
1824
+ Object.defineProperty(global, "Response", {
1825
+ value: Response2
1826
+ });
1827
+ }
1828
+ return async (incoming, outgoing) => {
1829
+ let res, req;
1830
+ try {
1831
+ req = newRequest(incoming, options.hostname);
1832
+ outgoing.on("close", () => {
1833
+ const abortController = req[abortControllerKey];
1834
+ if (!abortController) {
1835
+ return;
1836
+ }
1837
+ if (incoming.errored) {
1838
+ req[abortControllerKey].abort(incoming.errored.toString());
1839
+ } else if (!outgoing.writableFinished) {
1840
+ req[abortControllerKey].abort("Client connection prematurely closed.");
1841
+ }
1842
+ });
1843
+ res = fetchCallback(req, { incoming, outgoing });
1844
+ if (cacheKey in res) {
1845
+ return responseViaCache(res, outgoing);
1846
+ }
1847
+ } catch (e) {
1848
+ if (!res) {
1849
+ if (options.errorHandler) {
1850
+ res = await options.errorHandler(req ? e : toRequestError(e));
1851
+ if (!res) {
1852
+ return;
1853
+ }
1854
+ } else if (!req) {
1855
+ res = handleRequestError();
1856
+ } else {
1857
+ res = handleFetchError(e);
1858
+ }
1859
+ } else {
1860
+ return handleResponseError(e, outgoing);
1861
+ }
1862
+ }
1863
+ try {
1864
+ return responseViaResponseObject(res, outgoing, options);
1865
+ } catch (e) {
1866
+ return handleResponseError(e, outgoing);
1867
+ }
1868
+ };
1869
+ };
1870
+ var createAdaptorServer = (options) => {
1871
+ const fetchCallback = options.fetch;
1872
+ const requestListener = getRequestListener(fetchCallback, {
1873
+ hostname: options.hostname,
1874
+ overrideGlobalObjects: options.overrideGlobalObjects
1875
+ });
1876
+ const createServer = options.createServer || createServerHTTP;
1877
+ const server = createServer(options.serverOptions || {}, requestListener);
1878
+ return server;
1879
+ };
1880
+ var serve = (options, listeningListener) => {
1881
+ const server = createAdaptorServer(options);
1882
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
1883
+ const serverInfo = server.address();
1884
+ listeningListener && listeningListener(serverInfo);
1885
+ });
1886
+ return server;
1887
+ };
1888
+
1889
+ // src/server.ts
1890
+ init_esm_shims();
16
1891
  import fs from "fs";
17
1892
  import path from "path";
18
- import { createArtifact } from "@apps-in-toss/framework/cli-presets";
19
- import * as mpack from "@react-native-bedrock/mpack-next";
20
- import { statusPlugin } from "@react-native-bedrock/mpack-next/plugins";
21
- import { execa } from "execa";
22
- import presets from "react-native-bedrock/presets";
23
-
24
- // src/utils/getPackageManager.ts
25
- function getPackageManager({ isExecutor = false } = {}) {
26
- const userAgent = process.env.npm_config_user_agent;
27
- const packageManagerCommands = {
28
- npm: isExecutor ? "npx" : "npm",
29
- pnpm: "pnpm",
30
- yarn: "yarn"
1893
+ import { transform } from "@babel/core";
1894
+
1895
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/index.js
1896
+ init_esm_shims();
1897
+
1898
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/hono.js
1899
+ init_esm_shims();
1900
+
1901
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/hono-base.js
1902
+ init_esm_shims();
1903
+
1904
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/compose.js
1905
+ init_esm_shims();
1906
+ var compose = (middleware, onError, onNotFound) => {
1907
+ return (context, next) => {
1908
+ let index = -1;
1909
+ return dispatch(0);
1910
+ async function dispatch(i) {
1911
+ if (i <= index) {
1912
+ throw new Error("next() called multiple times");
1913
+ }
1914
+ index = i;
1915
+ let res;
1916
+ let isError = false;
1917
+ let handler;
1918
+ if (middleware[i]) {
1919
+ handler = middleware[i][0][0];
1920
+ context.req.routeIndex = i;
1921
+ } else {
1922
+ handler = i === middleware.length && next || void 0;
1923
+ }
1924
+ if (handler) {
1925
+ try {
1926
+ res = await handler(context, () => dispatch(i + 1));
1927
+ } catch (err) {
1928
+ if (err instanceof Error && onError) {
1929
+ context.error = err;
1930
+ res = await onError(err, context);
1931
+ isError = true;
1932
+ } else {
1933
+ throw err;
1934
+ }
1935
+ }
1936
+ } else {
1937
+ if (context.finalized === false && onNotFound) {
1938
+ res = await onNotFound(context);
1939
+ }
1940
+ }
1941
+ if (res && (context.finalized === false || isError)) {
1942
+ context.res = res;
1943
+ }
1944
+ return context;
1945
+ }
31
1946
  };
32
- if (!userAgent) {
33
- return {
34
- packageManager: packageManagerCommands["npm"],
35
- version: "0.0.0"
1947
+ };
1948
+
1949
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/context.js
1950
+ init_esm_shims();
1951
+
1952
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/request.js
1953
+ init_esm_shims();
1954
+
1955
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/utils/body.js
1956
+ init_esm_shims();
1957
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
1958
+ const { all = false, dot = false } = options;
1959
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
1960
+ const contentType = headers.get("Content-Type");
1961
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
1962
+ return parseFormData(request, { all, dot });
1963
+ }
1964
+ return {};
1965
+ };
1966
+ async function parseFormData(request, options) {
1967
+ const formData = await request.formData();
1968
+ if (formData) {
1969
+ return convertFormDataToBodyData(formData, options);
1970
+ }
1971
+ return {};
1972
+ }
1973
+ function convertFormDataToBodyData(formData, options) {
1974
+ const form = /* @__PURE__ */ Object.create(null);
1975
+ formData.forEach((value, key) => {
1976
+ const shouldParseAllValues = options.all || key.endsWith("[]");
1977
+ if (!shouldParseAllValues) {
1978
+ form[key] = value;
1979
+ } else {
1980
+ handleParsingAllValues(form, key, value);
1981
+ }
1982
+ });
1983
+ if (options.dot) {
1984
+ Object.entries(form).forEach(([key, value]) => {
1985
+ const shouldParseDotValues = key.includes(".");
1986
+ if (shouldParseDotValues) {
1987
+ handleParsingNestedValues(form, key, value);
1988
+ delete form[key];
1989
+ }
1990
+ });
1991
+ }
1992
+ return form;
1993
+ }
1994
+ var handleParsingAllValues = (form, key, value) => {
1995
+ if (form[key] !== void 0) {
1996
+ if (Array.isArray(form[key])) {
1997
+ ;
1998
+ form[key].push(value);
1999
+ } else {
2000
+ form[key] = [form[key], value];
2001
+ }
2002
+ } else {
2003
+ form[key] = value;
2004
+ }
2005
+ };
2006
+ var handleParsingNestedValues = (form, key, value) => {
2007
+ let nestedForm = form;
2008
+ const keys = key.split(".");
2009
+ keys.forEach((key2, index) => {
2010
+ if (index === keys.length - 1) {
2011
+ nestedForm[key2] = value;
2012
+ } else {
2013
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
2014
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
2015
+ }
2016
+ nestedForm = nestedForm[key2];
2017
+ }
2018
+ });
2019
+ };
2020
+
2021
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/utils/url.js
2022
+ init_esm_shims();
2023
+ var splitPath = (path2) => {
2024
+ const paths = path2.split("/");
2025
+ if (paths[0] === "") {
2026
+ paths.shift();
2027
+ }
2028
+ return paths;
2029
+ };
2030
+ var splitRoutingPath = (routePath) => {
2031
+ const { groups, path: path2 } = extractGroupsFromPath(routePath);
2032
+ const paths = splitPath(path2);
2033
+ return replaceGroupMarks(paths, groups);
2034
+ };
2035
+ var extractGroupsFromPath = (path2) => {
2036
+ const groups = [];
2037
+ path2 = path2.replace(/\{[^}]+\}/g, (match, index) => {
2038
+ const mark = `@${index}`;
2039
+ groups.push([mark, match]);
2040
+ return mark;
2041
+ });
2042
+ return { groups, path: path2 };
2043
+ };
2044
+ var replaceGroupMarks = (paths, groups) => {
2045
+ for (let i = groups.length - 1; i >= 0; i--) {
2046
+ const [mark] = groups[i];
2047
+ for (let j = paths.length - 1; j >= 0; j--) {
2048
+ if (paths[j].includes(mark)) {
2049
+ paths[j] = paths[j].replace(mark, groups[i][1]);
2050
+ break;
2051
+ }
2052
+ }
2053
+ }
2054
+ return paths;
2055
+ };
2056
+ var patternCache = {};
2057
+ var getPattern = (label, next) => {
2058
+ if (label === "*") {
2059
+ return "*";
2060
+ }
2061
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2062
+ if (match) {
2063
+ const cacheKey2 = `${label}#${next}`;
2064
+ if (!patternCache[cacheKey2]) {
2065
+ if (match[2]) {
2066
+ patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
2067
+ } else {
2068
+ patternCache[cacheKey2] = [label, match[1], true];
2069
+ }
2070
+ }
2071
+ return patternCache[cacheKey2];
2072
+ }
2073
+ return null;
2074
+ };
2075
+ var tryDecode = (str, decoder) => {
2076
+ try {
2077
+ return decoder(str);
2078
+ } catch {
2079
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
2080
+ try {
2081
+ return decoder(match);
2082
+ } catch {
2083
+ return match;
2084
+ }
2085
+ });
2086
+ }
2087
+ };
2088
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
2089
+ var getPath = (request) => {
2090
+ const url = request.url;
2091
+ const start = url.indexOf("/", 8);
2092
+ let i = start;
2093
+ for (; i < url.length; i++) {
2094
+ const charCode = url.charCodeAt(i);
2095
+ if (charCode === 37) {
2096
+ const queryIndex = url.indexOf("?", i);
2097
+ const path2 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
2098
+ return tryDecodeURI(path2.includes("%25") ? path2.replace(/%25/g, "%2525") : path2);
2099
+ } else if (charCode === 63) {
2100
+ break;
2101
+ }
2102
+ }
2103
+ return url.slice(start, i);
2104
+ };
2105
+ var getPathNoStrict = (request) => {
2106
+ const result = getPath(request);
2107
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
2108
+ };
2109
+ var mergePath = (base, sub, ...rest) => {
2110
+ if (rest.length) {
2111
+ sub = mergePath(sub, ...rest);
2112
+ }
2113
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
2114
+ };
2115
+ var checkOptionalParameter = (path2) => {
2116
+ if (path2.charCodeAt(path2.length - 1) !== 63 || !path2.includes(":")) {
2117
+ return null;
2118
+ }
2119
+ const segments = path2.split("/");
2120
+ const results = [];
2121
+ let basePath = "";
2122
+ segments.forEach((segment) => {
2123
+ if (segment !== "" && !/\:/.test(segment)) {
2124
+ basePath += "/" + segment;
2125
+ } else if (/\:/.test(segment)) {
2126
+ if (/\?/.test(segment)) {
2127
+ if (results.length === 0 && basePath === "") {
2128
+ results.push("/");
2129
+ } else {
2130
+ results.push(basePath);
2131
+ }
2132
+ const optionalSegment = segment.replace("?", "");
2133
+ basePath += "/" + optionalSegment;
2134
+ results.push(basePath);
2135
+ } else {
2136
+ basePath += "/" + segment;
2137
+ }
2138
+ }
2139
+ });
2140
+ return results.filter((v, i, a) => a.indexOf(v) === i);
2141
+ };
2142
+ var _decodeURI = (value) => {
2143
+ if (!/[%+]/.test(value)) {
2144
+ return value;
2145
+ }
2146
+ if (value.indexOf("+") !== -1) {
2147
+ value = value.replace(/\+/g, " ");
2148
+ }
2149
+ return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
2150
+ };
2151
+ var _getQueryParam = (url, key, multiple) => {
2152
+ let encoded;
2153
+ if (!multiple && key && !/[%+]/.test(key)) {
2154
+ let keyIndex2 = url.indexOf(`?${key}`, 8);
2155
+ if (keyIndex2 === -1) {
2156
+ keyIndex2 = url.indexOf(`&${key}`, 8);
2157
+ }
2158
+ while (keyIndex2 !== -1) {
2159
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
2160
+ if (trailingKeyCode === 61) {
2161
+ const valueIndex = keyIndex2 + key.length + 2;
2162
+ const endIndex = url.indexOf("&", valueIndex);
2163
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
2164
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
2165
+ return "";
2166
+ }
2167
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
2168
+ }
2169
+ encoded = /[%+]/.test(url);
2170
+ if (!encoded) {
2171
+ return void 0;
2172
+ }
2173
+ }
2174
+ const results = {};
2175
+ encoded ??= /[%+]/.test(url);
2176
+ let keyIndex = url.indexOf("?", 8);
2177
+ while (keyIndex !== -1) {
2178
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
2179
+ let valueIndex = url.indexOf("=", keyIndex);
2180
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
2181
+ valueIndex = -1;
2182
+ }
2183
+ let name = url.slice(
2184
+ keyIndex + 1,
2185
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
2186
+ );
2187
+ if (encoded) {
2188
+ name = _decodeURI(name);
2189
+ }
2190
+ keyIndex = nextKeyIndex;
2191
+ if (name === "") {
2192
+ continue;
2193
+ }
2194
+ let value;
2195
+ if (valueIndex === -1) {
2196
+ value = "";
2197
+ } else {
2198
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
2199
+ if (encoded) {
2200
+ value = _decodeURI(value);
2201
+ }
2202
+ }
2203
+ if (multiple) {
2204
+ if (!(results[name] && Array.isArray(results[name]))) {
2205
+ results[name] = [];
2206
+ }
2207
+ ;
2208
+ results[name].push(value);
2209
+ } else {
2210
+ results[name] ??= value;
2211
+ }
2212
+ }
2213
+ return key ? results[key] : results;
2214
+ };
2215
+ var getQueryParam = _getQueryParam;
2216
+ var getQueryParams = (url, key) => {
2217
+ return _getQueryParam(url, key, true);
2218
+ };
2219
+ var decodeURIComponent_ = decodeURIComponent;
2220
+
2221
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/request.js
2222
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
2223
+ var HonoRequest = class {
2224
+ raw;
2225
+ #validatedData;
2226
+ #matchResult;
2227
+ routeIndex = 0;
2228
+ path;
2229
+ bodyCache = {};
2230
+ constructor(request, path2 = "/", matchResult = [[]]) {
2231
+ this.raw = request;
2232
+ this.path = path2;
2233
+ this.#matchResult = matchResult;
2234
+ this.#validatedData = {};
2235
+ }
2236
+ param(key) {
2237
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
2238
+ }
2239
+ #getDecodedParam(key) {
2240
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
2241
+ const param = this.#getParamValue(paramKey);
2242
+ return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0;
2243
+ }
2244
+ #getAllDecodedParams() {
2245
+ const decoded = {};
2246
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
2247
+ for (const key of keys) {
2248
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
2249
+ if (value && typeof value === "string") {
2250
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
2251
+ }
2252
+ }
2253
+ return decoded;
2254
+ }
2255
+ #getParamValue(paramKey) {
2256
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
2257
+ }
2258
+ query(key) {
2259
+ return getQueryParam(this.url, key);
2260
+ }
2261
+ queries(key) {
2262
+ return getQueryParams(this.url, key);
2263
+ }
2264
+ header(name) {
2265
+ if (name) {
2266
+ return this.raw.headers.get(name) ?? void 0;
2267
+ }
2268
+ const headerData = {};
2269
+ this.raw.headers.forEach((value, key) => {
2270
+ headerData[key] = value;
2271
+ });
2272
+ return headerData;
2273
+ }
2274
+ async parseBody(options) {
2275
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
2276
+ }
2277
+ #cachedBody = (key) => {
2278
+ const { bodyCache, raw: raw2 } = this;
2279
+ const cachedBody = bodyCache[key];
2280
+ if (cachedBody) {
2281
+ return cachedBody;
2282
+ }
2283
+ const anyCachedKey = Object.keys(bodyCache)[0];
2284
+ if (anyCachedKey) {
2285
+ return bodyCache[anyCachedKey].then((body) => {
2286
+ if (anyCachedKey === "json") {
2287
+ body = JSON.stringify(body);
2288
+ }
2289
+ return new Response(body)[key]();
2290
+ });
2291
+ }
2292
+ return bodyCache[key] = raw2[key]();
2293
+ };
2294
+ json() {
2295
+ return this.#cachedBody("json");
2296
+ }
2297
+ text() {
2298
+ return this.#cachedBody("text");
2299
+ }
2300
+ arrayBuffer() {
2301
+ return this.#cachedBody("arrayBuffer");
2302
+ }
2303
+ blob() {
2304
+ return this.#cachedBody("blob");
2305
+ }
2306
+ formData() {
2307
+ return this.#cachedBody("formData");
2308
+ }
2309
+ addValidatedData(target, data) {
2310
+ this.#validatedData[target] = data;
2311
+ }
2312
+ valid(target) {
2313
+ return this.#validatedData[target];
2314
+ }
2315
+ get url() {
2316
+ return this.raw.url;
2317
+ }
2318
+ get method() {
2319
+ return this.raw.method;
2320
+ }
2321
+ get matchedRoutes() {
2322
+ return this.#matchResult[0].map(([[, route]]) => route);
2323
+ }
2324
+ get routePath() {
2325
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
2326
+ }
2327
+ };
2328
+
2329
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/utils/html.js
2330
+ init_esm_shims();
2331
+ var HtmlEscapedCallbackPhase = {
2332
+ Stringify: 1,
2333
+ BeforeStream: 2,
2334
+ Stream: 3
2335
+ };
2336
+ var raw = (value, callbacks) => {
2337
+ const escapedString = new String(value);
2338
+ escapedString.isEscaped = true;
2339
+ escapedString.callbacks = callbacks;
2340
+ return escapedString;
2341
+ };
2342
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
2343
+ if (typeof str === "object" && !(str instanceof String)) {
2344
+ if (!(str instanceof Promise)) {
2345
+ str = str.toString();
2346
+ }
2347
+ if (str instanceof Promise) {
2348
+ str = await str;
2349
+ }
2350
+ }
2351
+ const callbacks = str.callbacks;
2352
+ if (!callbacks?.length) {
2353
+ return Promise.resolve(str);
2354
+ }
2355
+ if (buffer) {
2356
+ buffer[0] += str;
2357
+ } else {
2358
+ buffer = [str];
2359
+ }
2360
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
2361
+ (res) => Promise.all(
2362
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
2363
+ ).then(() => buffer[0])
2364
+ );
2365
+ if (preserveCallbacks) {
2366
+ return raw(await resStr, callbacks);
2367
+ } else {
2368
+ return resStr;
2369
+ }
2370
+ };
2371
+
2372
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/context.js
2373
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
2374
+ var setHeaders = (headers, map = {}) => {
2375
+ for (const key of Object.keys(map)) {
2376
+ headers.set(key, map[key]);
2377
+ }
2378
+ return headers;
2379
+ };
2380
+ var Context = class {
2381
+ #rawRequest;
2382
+ #req;
2383
+ env = {};
2384
+ #var;
2385
+ finalized = false;
2386
+ error;
2387
+ #status = 200;
2388
+ #executionCtx;
2389
+ #headers;
2390
+ #preparedHeaders;
2391
+ #res;
2392
+ #isFresh = true;
2393
+ #layout;
2394
+ #renderer;
2395
+ #notFoundHandler;
2396
+ #matchResult;
2397
+ #path;
2398
+ constructor(req, options) {
2399
+ this.#rawRequest = req;
2400
+ if (options) {
2401
+ this.#executionCtx = options.executionCtx;
2402
+ this.env = options.env;
2403
+ this.#notFoundHandler = options.notFoundHandler;
2404
+ this.#path = options.path;
2405
+ this.#matchResult = options.matchResult;
2406
+ }
2407
+ }
2408
+ get req() {
2409
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
2410
+ return this.#req;
2411
+ }
2412
+ get event() {
2413
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
2414
+ return this.#executionCtx;
2415
+ } else {
2416
+ throw Error("This context has no FetchEvent");
2417
+ }
2418
+ }
2419
+ get executionCtx() {
2420
+ if (this.#executionCtx) {
2421
+ return this.#executionCtx;
2422
+ } else {
2423
+ throw Error("This context has no ExecutionContext");
2424
+ }
2425
+ }
2426
+ get res() {
2427
+ this.#isFresh = false;
2428
+ return this.#res ||= new Response("404 Not Found", { status: 404 });
2429
+ }
2430
+ set res(_res) {
2431
+ this.#isFresh = false;
2432
+ if (this.#res && _res) {
2433
+ try {
2434
+ for (const [k, v] of this.#res.headers.entries()) {
2435
+ if (k === "content-type") {
2436
+ continue;
2437
+ }
2438
+ if (k === "set-cookie") {
2439
+ const cookies = this.#res.headers.getSetCookie();
2440
+ _res.headers.delete("set-cookie");
2441
+ for (const cookie of cookies) {
2442
+ _res.headers.append("set-cookie", cookie);
2443
+ }
2444
+ } else {
2445
+ _res.headers.set(k, v);
2446
+ }
2447
+ }
2448
+ } catch (e) {
2449
+ if (e instanceof TypeError && e.message.includes("immutable")) {
2450
+ this.res = new Response(_res.body, {
2451
+ headers: _res.headers,
2452
+ status: _res.status
2453
+ });
2454
+ return;
2455
+ } else {
2456
+ throw e;
2457
+ }
2458
+ }
2459
+ }
2460
+ this.#res = _res;
2461
+ this.finalized = true;
2462
+ }
2463
+ render = (...args) => {
2464
+ this.#renderer ??= (content) => this.html(content);
2465
+ return this.#renderer(...args);
2466
+ };
2467
+ setLayout = (layout) => this.#layout = layout;
2468
+ getLayout = () => this.#layout;
2469
+ setRenderer = (renderer) => {
2470
+ this.#renderer = renderer;
2471
+ };
2472
+ header = (name, value, options) => {
2473
+ if (value === void 0) {
2474
+ if (this.#headers) {
2475
+ this.#headers.delete(name);
2476
+ } else if (this.#preparedHeaders) {
2477
+ delete this.#preparedHeaders[name.toLocaleLowerCase()];
2478
+ }
2479
+ if (this.finalized) {
2480
+ this.res.headers.delete(name);
2481
+ }
2482
+ return;
2483
+ }
2484
+ if (options?.append) {
2485
+ if (!this.#headers) {
2486
+ this.#isFresh = false;
2487
+ this.#headers = new Headers(this.#preparedHeaders);
2488
+ this.#preparedHeaders = {};
2489
+ }
2490
+ this.#headers.append(name, value);
2491
+ } else {
2492
+ if (this.#headers) {
2493
+ this.#headers.set(name, value);
2494
+ } else {
2495
+ this.#preparedHeaders ??= {};
2496
+ this.#preparedHeaders[name.toLowerCase()] = value;
2497
+ }
2498
+ }
2499
+ if (this.finalized) {
2500
+ if (options?.append) {
2501
+ this.res.headers.append(name, value);
2502
+ } else {
2503
+ this.res.headers.set(name, value);
2504
+ }
2505
+ }
2506
+ };
2507
+ status = (status) => {
2508
+ this.#isFresh = false;
2509
+ this.#status = status;
2510
+ };
2511
+ set = (key, value) => {
2512
+ this.#var ??= /* @__PURE__ */ new Map();
2513
+ this.#var.set(key, value);
2514
+ };
2515
+ get = (key) => {
2516
+ return this.#var ? this.#var.get(key) : void 0;
2517
+ };
2518
+ get var() {
2519
+ if (!this.#var) {
2520
+ return {};
2521
+ }
2522
+ return Object.fromEntries(this.#var);
2523
+ }
2524
+ #newResponse(data, arg, headers) {
2525
+ if (this.#isFresh && !headers && !arg && this.#status === 200) {
2526
+ return new Response(data, {
2527
+ headers: this.#preparedHeaders
2528
+ });
2529
+ }
2530
+ if (arg && typeof arg !== "number") {
2531
+ const header = new Headers(arg.headers);
2532
+ if (this.#headers) {
2533
+ this.#headers.forEach((v, k) => {
2534
+ if (k === "set-cookie") {
2535
+ header.append(k, v);
2536
+ } else {
2537
+ header.set(k, v);
2538
+ }
2539
+ });
2540
+ }
2541
+ const headers2 = setHeaders(header, this.#preparedHeaders);
2542
+ return new Response(data, {
2543
+ headers: headers2,
2544
+ status: arg.status ?? this.#status
2545
+ });
2546
+ }
2547
+ const status = typeof arg === "number" ? arg : this.#status;
2548
+ this.#preparedHeaders ??= {};
2549
+ this.#headers ??= new Headers();
2550
+ setHeaders(this.#headers, this.#preparedHeaders);
2551
+ if (this.#res) {
2552
+ this.#res.headers.forEach((v, k) => {
2553
+ if (k === "set-cookie") {
2554
+ this.#headers?.append(k, v);
2555
+ } else {
2556
+ this.#headers?.set(k, v);
2557
+ }
2558
+ });
2559
+ setHeaders(this.#headers, this.#preparedHeaders);
2560
+ }
2561
+ headers ??= {};
2562
+ for (const [k, v] of Object.entries(headers)) {
2563
+ if (typeof v === "string") {
2564
+ this.#headers.set(k, v);
2565
+ } else {
2566
+ this.#headers.delete(k);
2567
+ for (const v2 of v) {
2568
+ this.#headers.append(k, v2);
2569
+ }
2570
+ }
2571
+ }
2572
+ return new Response(data, {
2573
+ status,
2574
+ headers: this.#headers
2575
+ });
2576
+ }
2577
+ newResponse = (...args) => this.#newResponse(...args);
2578
+ body = (data, arg, headers) => {
2579
+ return typeof arg === "number" ? this.#newResponse(data, arg, headers) : this.#newResponse(data, arg);
2580
+ };
2581
+ text = (text, arg, headers) => {
2582
+ if (!this.#preparedHeaders) {
2583
+ if (this.#isFresh && !headers && !arg) {
2584
+ return new Response(text);
2585
+ }
2586
+ this.#preparedHeaders = {};
2587
+ }
2588
+ this.#preparedHeaders["content-type"] = TEXT_PLAIN;
2589
+ if (typeof arg === "number") {
2590
+ return this.#newResponse(text, arg, headers);
2591
+ }
2592
+ return this.#newResponse(text, arg);
2593
+ };
2594
+ json = (object, arg, headers) => {
2595
+ const body = JSON.stringify(object);
2596
+ this.#preparedHeaders ??= {};
2597
+ this.#preparedHeaders["content-type"] = "application/json";
2598
+ return typeof arg === "number" ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg);
2599
+ };
2600
+ html = (html, arg, headers) => {
2601
+ this.#preparedHeaders ??= {};
2602
+ this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
2603
+ if (typeof html === "object") {
2604
+ return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
2605
+ return typeof arg === "number" ? this.#newResponse(html2, arg, headers) : this.#newResponse(html2, arg);
2606
+ });
2607
+ }
2608
+ return typeof arg === "number" ? this.#newResponse(html, arg, headers) : this.#newResponse(html, arg);
2609
+ };
2610
+ redirect = (location, status) => {
2611
+ this.#headers ??= new Headers();
2612
+ this.#headers.set("Location", String(location));
2613
+ return this.newResponse(null, status ?? 302);
2614
+ };
2615
+ notFound = () => {
2616
+ this.#notFoundHandler ??= () => new Response();
2617
+ return this.#notFoundHandler(this);
2618
+ };
2619
+ };
2620
+
2621
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router.js
2622
+ init_esm_shims();
2623
+ var METHOD_NAME_ALL = "ALL";
2624
+ var METHOD_NAME_ALL_LOWERCASE = "all";
2625
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
2626
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
2627
+ var UnsupportedPathError = class extends Error {
2628
+ };
2629
+
2630
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/utils/constants.js
2631
+ init_esm_shims();
2632
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
2633
+
2634
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/hono-base.js
2635
+ var notFoundHandler = (c) => {
2636
+ return c.text("404 Not Found", 404);
2637
+ };
2638
+ var errorHandler = (err, c) => {
2639
+ if ("getResponse" in err) {
2640
+ return err.getResponse();
2641
+ }
2642
+ console.error(err);
2643
+ return c.text("Internal Server Error", 500);
2644
+ };
2645
+ var Hono = class {
2646
+ get;
2647
+ post;
2648
+ put;
2649
+ delete;
2650
+ options;
2651
+ patch;
2652
+ all;
2653
+ on;
2654
+ use;
2655
+ router;
2656
+ getPath;
2657
+ _basePath = "/";
2658
+ #path = "/";
2659
+ routes = [];
2660
+ constructor(options = {}) {
2661
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
2662
+ allMethods.forEach((method) => {
2663
+ this[method] = (args1, ...args) => {
2664
+ if (typeof args1 === "string") {
2665
+ this.#path = args1;
2666
+ } else {
2667
+ this.#addRoute(method, this.#path, args1);
2668
+ }
2669
+ args.forEach((handler) => {
2670
+ this.#addRoute(method, this.#path, handler);
2671
+ });
2672
+ return this;
2673
+ };
2674
+ });
2675
+ this.on = (method, path2, ...handlers) => {
2676
+ for (const p of [path2].flat()) {
2677
+ this.#path = p;
2678
+ for (const m of [method].flat()) {
2679
+ handlers.map((handler) => {
2680
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
2681
+ });
2682
+ }
2683
+ }
2684
+ return this;
36
2685
  };
2686
+ this.use = (arg1, ...handlers) => {
2687
+ if (typeof arg1 === "string") {
2688
+ this.#path = arg1;
2689
+ } else {
2690
+ this.#path = "*";
2691
+ handlers.unshift(arg1);
2692
+ }
2693
+ handlers.forEach((handler) => {
2694
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
2695
+ });
2696
+ return this;
2697
+ };
2698
+ const { strict, ...optionsWithoutStrict } = options;
2699
+ Object.assign(this, optionsWithoutStrict);
2700
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
37
2701
  }
38
- const [packageManagerInfo] = userAgent.match(/(\w+)\/(\d+\.\d+\.\d+)/) || [];
39
- const [packageManager, version2] = packageManagerInfo?.split("/") ?? ["npm", null];
40
- if (!packageManager) {
41
- return {
42
- packageManager: packageManagerCommands["npm"],
43
- version: "0.0.0"
2702
+ #clone() {
2703
+ const clone = new Hono({
2704
+ router: this.router,
2705
+ getPath: this.getPath
2706
+ });
2707
+ clone.routes = this.routes;
2708
+ return clone;
2709
+ }
2710
+ #notFoundHandler = notFoundHandler;
2711
+ errorHandler = errorHandler;
2712
+ route(path2, app2) {
2713
+ const subApp = this.basePath(path2);
2714
+ app2.routes.map((r) => {
2715
+ let handler;
2716
+ if (app2.errorHandler === errorHandler) {
2717
+ handler = r.handler;
2718
+ } else {
2719
+ handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
2720
+ handler[COMPOSED_HANDLER] = r.handler;
2721
+ }
2722
+ subApp.#addRoute(r.method, r.path, handler);
2723
+ });
2724
+ return this;
2725
+ }
2726
+ basePath(path2) {
2727
+ const subApp = this.#clone();
2728
+ subApp._basePath = mergePath(this._basePath, path2);
2729
+ return subApp;
2730
+ }
2731
+ onError = (handler) => {
2732
+ this.errorHandler = handler;
2733
+ return this;
2734
+ };
2735
+ notFound = (handler) => {
2736
+ this.#notFoundHandler = handler;
2737
+ return this;
2738
+ };
2739
+ mount(path2, applicationHandler, options) {
2740
+ let replaceRequest;
2741
+ let optionHandler;
2742
+ if (options) {
2743
+ if (typeof options === "function") {
2744
+ optionHandler = options;
2745
+ } else {
2746
+ optionHandler = options.optionHandler;
2747
+ replaceRequest = options.replaceRequest;
2748
+ }
2749
+ }
2750
+ const getOptions = optionHandler ? (c) => {
2751
+ const options2 = optionHandler(c);
2752
+ return Array.isArray(options2) ? options2 : [options2];
2753
+ } : (c) => {
2754
+ let executionContext = void 0;
2755
+ try {
2756
+ executionContext = c.executionCtx;
2757
+ } catch {
2758
+ }
2759
+ return [c.env, executionContext];
44
2760
  };
2761
+ replaceRequest ||= (() => {
2762
+ const mergedPath = mergePath(this._basePath, path2);
2763
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2764
+ return (request) => {
2765
+ const url = new URL(request.url);
2766
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2767
+ return new Request(url, request);
2768
+ };
2769
+ })();
2770
+ const handler = async (c, next) => {
2771
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2772
+ if (res) {
2773
+ return res;
2774
+ }
2775
+ await next();
2776
+ };
2777
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path2, "*"), handler);
2778
+ return this;
45
2779
  }
46
- return {
47
- packageManager: packageManagerCommands[packageManager],
48
- version: version2 ?? "0.0.0"
2780
+ #addRoute(method, path2, handler) {
2781
+ method = method.toUpperCase();
2782
+ path2 = mergePath(this._basePath, path2);
2783
+ const r = { path: path2, method, handler };
2784
+ this.router.add(method, path2, [handler, r]);
2785
+ this.routes.push(r);
2786
+ }
2787
+ #handleError(err, c) {
2788
+ if (err instanceof Error) {
2789
+ return this.errorHandler(err, c);
2790
+ }
2791
+ throw err;
2792
+ }
2793
+ #dispatch(request, executionCtx, env, method) {
2794
+ if (method === "HEAD") {
2795
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
2796
+ }
2797
+ const path2 = this.getPath(request, { env });
2798
+ const matchResult = this.router.match(method, path2);
2799
+ const c = new Context(request, {
2800
+ path: path2,
2801
+ matchResult,
2802
+ env,
2803
+ executionCtx,
2804
+ notFoundHandler: this.#notFoundHandler
2805
+ });
2806
+ if (matchResult[0].length === 1) {
2807
+ let res;
2808
+ try {
2809
+ res = matchResult[0][0][0][0](c, async () => {
2810
+ c.res = await this.#notFoundHandler(c);
2811
+ });
2812
+ } catch (err) {
2813
+ return this.#handleError(err, c);
2814
+ }
2815
+ return res instanceof Promise ? res.then(
2816
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2817
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2818
+ }
2819
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2820
+ return (async () => {
2821
+ try {
2822
+ const context = await composed(c);
2823
+ if (!context.finalized) {
2824
+ throw new Error(
2825
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2826
+ );
2827
+ }
2828
+ return context.res;
2829
+ } catch (err) {
2830
+ return this.#handleError(err, c);
2831
+ }
2832
+ })();
2833
+ }
2834
+ fetch = (request, ...rest) => {
2835
+ return this.#dispatch(request, rest[1], rest[0], request.method);
49
2836
  };
50
- }
2837
+ request = (input, requestInit, Env, executionCtx) => {
2838
+ if (input instanceof Request) {
2839
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2840
+ }
2841
+ input = input.toString();
2842
+ return this.fetch(
2843
+ new Request(
2844
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2845
+ requestInit
2846
+ ),
2847
+ Env,
2848
+ executionCtx
2849
+ );
2850
+ };
2851
+ fire = () => {
2852
+ addEventListener("fetch", (event) => {
2853
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2854
+ });
2855
+ };
2856
+ };
51
2857
 
52
- // src/BuildCommand/build.ts
53
- async function build({ distDirname, cache }) {
54
- const config = await loadConfig();
55
- const rootDir = process.cwd();
56
- const reactNativeProjectDir = path.resolve(__dirname, "..", "react-native");
57
- const projectRootTmp = path.resolve(process.cwd(), ".bedrock");
58
- await fs.promises.mkdir(projectRootTmp, { recursive: true });
59
- await fs.promises.writeFile(
60
- path.join(projectRootTmp, "metadata.json"),
61
- JSON.stringify({ appName: config.appName, webPort: config.web.port })
62
- );
63
- const appName = config.appName;
64
- const { packageManager } = getPackageManager({ isExecutor: true });
65
- const distDir = path.join(rootDir, distDirname);
66
- const webDistDir = path.join(distDir, "web");
67
- await fs.promises.rm(distDir, { recursive: true, force: true });
68
- await execa(packageManager, config.web.commands.build.split(" "), {
69
- cwd: process.cwd(),
70
- stdio: "inherit"
71
- });
72
- await fs.promises.mkdir(webDistDir, { recursive: true });
73
- const items = await fs.promises.readdir(distDir);
74
- for (const item of items) {
75
- const src = path.join(distDir, item);
76
- const dest = path.join(webDistDir, item);
77
- if (src === webDistDir) {
78
- continue;
2858
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/reg-exp-router/index.js
2859
+ init_esm_shims();
2860
+
2861
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/reg-exp-router/router.js
2862
+ init_esm_shims();
2863
+
2864
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/reg-exp-router/node.js
2865
+ init_esm_shims();
2866
+ var LABEL_REG_EXP_STR = "[^/]+";
2867
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
2868
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2869
+ var PATH_ERROR = Symbol();
2870
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2871
+ function compareKey(a, b) {
2872
+ if (a.length === 1) {
2873
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2874
+ }
2875
+ if (b.length === 1) {
2876
+ return 1;
2877
+ }
2878
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2879
+ return 1;
2880
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2881
+ return -1;
2882
+ }
2883
+ if (a === LABEL_REG_EXP_STR) {
2884
+ return 1;
2885
+ } else if (b === LABEL_REG_EXP_STR) {
2886
+ return -1;
2887
+ }
2888
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2889
+ }
2890
+ var Node = class {
2891
+ #index;
2892
+ #varIndex;
2893
+ #children = /* @__PURE__ */ Object.create(null);
2894
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2895
+ if (tokens.length === 0) {
2896
+ if (this.#index !== void 0) {
2897
+ throw PATH_ERROR;
2898
+ }
2899
+ if (pathErrorCheckOnly) {
2900
+ return;
2901
+ }
2902
+ this.#index = index;
2903
+ return;
79
2904
  }
80
- await fs.promises.rename(src, dest);
81
- }
82
- const buildResults = await mpack.runBundle({
83
- clean: false,
84
- metafile: false,
85
- dev: false,
86
- rootDir: reactNativeProjectDir,
87
- cache,
88
- plugins: [statusPlugin],
89
- config: {
90
- appName,
91
- services: {
92
- sentry: {
93
- enabled: false
2905
+ const [token, ...restTokens] = tokens;
2906
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2907
+ let node;
2908
+ if (pattern) {
2909
+ const name = pattern[1];
2910
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2911
+ if (name && pattern[2]) {
2912
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2913
+ if (/\((?!\?:)/.test(regexpStr)) {
2914
+ throw PATH_ERROR;
94
2915
  }
95
- },
96
- concurrency: 2,
97
- tasks: [
98
- {
99
- tag: `${appName}-ios`,
100
- presets: [presets.service()],
101
- build: {
102
- babel: {
103
- conditions: [(_code) => _code.includes("Ait")],
104
- plugins: [
105
- [
106
- __require.resolve("@apps-in-toss/babel-plugin-json"),
107
- { jsonPath: "./.bedrock/metadata.json", identifierName: "Ait" }
108
- ]
109
- ]
110
- },
111
- platform: "ios",
112
- entry: path.join(reactNativeProjectDir, "src", "_app.tsx"),
113
- outfile: path.join(distDir, `${appName}.ios.js`)
114
- }
115
- },
116
- {
117
- tag: `${appName}-android`,
118
- presets: [presets.service()],
119
- build: {
120
- babel: {
121
- conditions: [(_code) => _code.includes("Ait")],
122
- plugins: [
123
- [
124
- __require.resolve("@apps-in-toss/babel-plugin-json"),
125
- { jsonPath: "./.bedrock/metadata.json", identifierName: "Ait" }
126
- ]
127
- ]
128
- },
129
- platform: "android",
130
- entry: path.join(reactNativeProjectDir, "src", "_app.tsx"),
131
- outfile: path.join(distDir, `${appName}.android.js`)
132
- }
2916
+ }
2917
+ node = this.#children[regexpStr];
2918
+ if (!node) {
2919
+ if (Object.keys(this.#children).some(
2920
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2921
+ )) {
2922
+ throw PATH_ERROR;
133
2923
  }
134
- ]
2924
+ if (pathErrorCheckOnly) {
2925
+ return;
2926
+ }
2927
+ node = this.#children[regexpStr] = new Node();
2928
+ if (name !== "") {
2929
+ node.#varIndex = context.varIndex++;
2930
+ }
2931
+ }
2932
+ if (!pathErrorCheckOnly && name !== "") {
2933
+ paramMap.push([name, node.#varIndex]);
2934
+ }
2935
+ } else {
2936
+ node = this.#children[token];
2937
+ if (!node) {
2938
+ if (Object.keys(this.#children).some(
2939
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2940
+ )) {
2941
+ throw PATH_ERROR;
2942
+ }
2943
+ if (pathErrorCheckOnly) {
2944
+ return;
2945
+ }
2946
+ node = this.#children[token] = new Node();
2947
+ }
135
2948
  }
136
- });
137
- const artifactOutfile = await createArtifact({
138
- buildResults,
139
- rootDir,
140
- reactNativeProjectDir,
141
- webOutDir: webDistDir
142
- });
143
- if (!artifactOutfile) {
144
- throw new Error("\uC544\uD2F0\uD329\uD2B8 \uC0DD\uC131\uC5D0 \uC2E4\uD328\uD588\uC5B4\uC694.");
2949
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
145
2950
  }
146
- return artifactOutfile;
147
- }
148
-
149
- // src/constants.ts
150
- var APP_MANIFEST_NAME = "app.json";
151
- var DEFAULT_DIST_DIR = "dist";
152
- var API_BASE_URL = "https://apps-in-toss.toss.im/console";
153
- var DEFAULT_LOCALHOST_PORT = 8081;
154
- var DEFAULT_HOST = "localhost";
155
-
156
- // src/BuildCommand/BuildCommand.ts
157
- var BuildCommand = class extends Command {
158
- static paths = [[`build`]];
159
- static usage = Command.Usage({
160
- category: "Build",
161
- description: "Apps In Toss \uBE4C\uB4DC \uC544\uD2F0\uD329\uD2B8\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4",
162
- examples: [["\uBE4C\uB4DC \uC544\uD2F0\uD329\uD2B8 \uC0DD\uC131\uD558\uAE30", "ait build"]]
163
- });
164
- cache = Option.Boolean("--cache", true);
165
- async execute() {
166
- const artifactOutfile = await build({
167
- distDirname: DEFAULT_DIST_DIR,
168
- cache: this.cache
2951
+ buildRegExpStr() {
2952
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2953
+ const strList = childKeys.map((k) => {
2954
+ const c = this.#children[k];
2955
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
169
2956
  });
170
- console.log(`
171
- ${picocolors.blue(artifactOutfile)}
172
- `);
2957
+ if (typeof this.#index === "number") {
2958
+ strList.unshift(`#${this.#index}`);
2959
+ }
2960
+ if (strList.length === 0) {
2961
+ return "";
2962
+ }
2963
+ if (strList.length === 1) {
2964
+ return strList[0];
2965
+ }
2966
+ return "(?:" + strList.join("|") + ")";
173
2967
  }
174
2968
  };
175
2969
 
176
- // src/DeployCommand/DeployCommand.ts
177
- import assert from "assert";
178
- import path2 from "path";
179
- import * as p from "@clack/prompts";
180
- import { Command as Command2, Option as Option2 } from "clipanion";
181
- import Debug2 from "debug";
182
- import picocolors2 from "picocolors";
183
-
184
- // src/DeployCommand/upload.ts
185
- import * as fs2 from "fs";
186
- import Debug from "debug";
187
- var debug = Debug("cli:deploy");
188
- async function uploadArtifact(config) {
189
- debug("uploadArtifact", config);
190
- const response = await fetch(
191
- `${API_BASE_URL}/api-public/v3/appsintossconsole/bundles/${config.appName}/sandbox/upload`,
192
- {
193
- method: "POST",
194
- headers: {
195
- "Content-Type": "application/octet-stream",
196
- "X-Ait-Console-Api-Key": config.apiKey
197
- },
198
- body: fs2.createReadStream(config.artifactPath),
199
- duplex: "half"
2970
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/reg-exp-router/trie.js
2971
+ init_esm_shims();
2972
+ var Trie = class {
2973
+ #context = { varIndex: 0 };
2974
+ #root = new Node();
2975
+ insert(path2, index, pathErrorCheckOnly) {
2976
+ const paramAssoc = [];
2977
+ const groups = [];
2978
+ for (let i = 0; ; ) {
2979
+ let replaced = false;
2980
+ path2 = path2.replace(/\{[^}]+\}/g, (m) => {
2981
+ const mark = `@\\${i}`;
2982
+ groups[i] = [mark, m];
2983
+ i++;
2984
+ replaced = true;
2985
+ return mark;
2986
+ });
2987
+ if (!replaced) {
2988
+ break;
2989
+ }
200
2990
  }
201
- );
202
- return handleResponse(response);
203
- }
204
- async function handleResponse(response) {
205
- debug(`Response ${response.status} ${response.statusText}`);
206
- if (!response.ok) {
207
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
208
- }
209
- const data = await response.clone().json();
210
- debug("uploadArtifact response", data);
211
- if (data.resultType !== "SUCCESS") {
212
- const errorCode = data?.error?.errorCode ?? "-1";
213
- const errorReason = data?.error.reason ?? "unknown";
214
- throw new Error(`${errorReason} (Code: ${errorCode})`);
215
- }
216
- const result = data.success;
217
- return result.deploymentId;
218
- }
219
-
220
- // src/utils/readZipContent.ts
221
- import yauzl from "yauzl";
222
- function readZipContent(zipPath, fileName) {
223
- return new Promise((resolve, reject) => {
224
- yauzl.open(zipPath, { lazyEntries: true }, (error, zipFile) => {
225
- if (error) {
226
- reject(error);
227
- return;
2991
+ const tokens = path2.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2992
+ for (let i = groups.length - 1; i >= 0; i--) {
2993
+ const [mark] = groups[i];
2994
+ for (let j = tokens.length - 1; j >= 0; j--) {
2995
+ if (tokens[j].indexOf(mark) !== -1) {
2996
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2997
+ break;
2998
+ }
228
2999
  }
229
- zipFile.on("entry", (entry) => {
230
- if (entry.fileName === fileName) {
231
- zipFile.openReadStream(entry, (error2, readStream) => {
232
- if (error2) {
233
- throw error2;
234
- }
235
- let fileData = "";
236
- readStream.on("data", (chunk) => fileData += chunk.toString("utf8")).on("end", () => {
237
- zipFile.close();
238
- resolve(fileData);
239
- });
240
- });
241
- } else {
242
- zipFile.readEntry();
243
- }
244
- }).on("end", () => {
245
- zipFile.close();
246
- reject(new Error(`'${fileName}' not found in zip file`));
247
- }).on("error", (error2) => {
248
- zipFile.close();
249
- reject(error2);
250
- });
251
- zipFile.readEntry();
3000
+ }
3001
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
3002
+ return paramAssoc;
3003
+ }
3004
+ buildRegExp() {
3005
+ let regexp = this.#root.buildRegExpStr();
3006
+ if (regexp === "") {
3007
+ return [/^$/, [], []];
3008
+ }
3009
+ let captureIndex = 0;
3010
+ const indexReplacementMap = [];
3011
+ const paramReplacementMap = [];
3012
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
3013
+ if (handlerIndex !== void 0) {
3014
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
3015
+ return "$()";
3016
+ }
3017
+ if (paramIndex !== void 0) {
3018
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
3019
+ return "";
3020
+ }
3021
+ return "";
252
3022
  });
253
- });
254
- }
3023
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
3024
+ }
3025
+ };
255
3026
 
256
- // src/DeployCommand/DeployCommand.ts
257
- var debug2 = Debug2("cli:deploy");
258
- var DeployCommand = class extends Command2 {
259
- static paths = [["deploy"]];
260
- apiKey = Option2.String("--api-key", {
261
- required: false,
262
- description: "\uC54C\uD30C \uBC30\uD3EC\uB97C \uC704\uD55C API \uD0A4"
263
- });
264
- async execute() {
265
- const apiKey = this.apiKey || await p.password({
266
- message: "\uC571\uC778\uD1A0\uC2A4 \uBC30\uD3EC API \uD0A4\uB97C \uC785\uB825\uD574\uC8FC\uC138\uC694",
267
- validate: (value) => {
268
- if (value.length === 0) {
269
- return "API \uD0A4\uB294 \uD544\uC218 \uC785\uB825 \uD56D\uBAA9\uC785\uB2C8\uB2E4.";
270
- }
271
- return;
3027
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/reg-exp-router/router.js
3028
+ var emptyParam = [];
3029
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
3030
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
3031
+ function buildWildcardRegExp(path2) {
3032
+ return wildcardRegExpCache[path2] ??= new RegExp(
3033
+ path2 === "*" ? "" : `^${path2.replace(
3034
+ /\/\*$|([.\\+*[^\]$()])/g,
3035
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
3036
+ )}$`
3037
+ );
3038
+ }
3039
+ function clearWildcardRegExpCache() {
3040
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
3041
+ }
3042
+ function buildMatcherFromPreprocessedRoutes(routes) {
3043
+ const trie = new Trie();
3044
+ const handlerData = [];
3045
+ if (routes.length === 0) {
3046
+ return nullMatcher;
3047
+ }
3048
+ const routesWithStaticPathFlag = routes.map(
3049
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
3050
+ ).sort(
3051
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
3052
+ );
3053
+ const staticMap = /* @__PURE__ */ Object.create(null);
3054
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
3055
+ const [pathErrorCheckOnly, path2, handlers] = routesWithStaticPathFlag[i];
3056
+ if (pathErrorCheckOnly) {
3057
+ staticMap[path2] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
3058
+ } else {
3059
+ j++;
3060
+ }
3061
+ let paramAssoc;
3062
+ try {
3063
+ paramAssoc = trie.insert(path2, j, pathErrorCheckOnly);
3064
+ } catch (e) {
3065
+ throw e === PATH_ERROR ? new UnsupportedPathError(path2) : e;
3066
+ }
3067
+ if (pathErrorCheckOnly) {
3068
+ continue;
3069
+ }
3070
+ handlerData[j] = handlers.map(([h, paramCount]) => {
3071
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
3072
+ paramCount -= 1;
3073
+ for (; paramCount >= 0; paramCount--) {
3074
+ const [key, value] = paramAssoc[paramCount];
3075
+ paramIndexMap[key] = value;
272
3076
  }
3077
+ return [h, paramIndexMap];
273
3078
  });
274
- if (p.isCancel(apiKey)) {
275
- return;
3079
+ }
3080
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
3081
+ for (let i = 0, len = handlerData.length; i < len; i++) {
3082
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
3083
+ const map = handlerData[i][j]?.[1];
3084
+ if (!map) {
3085
+ continue;
3086
+ }
3087
+ const keys = Object.keys(map);
3088
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
3089
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
3090
+ }
276
3091
  }
277
- try {
278
- const artifactOutfile = await build({
279
- distDirname: DEFAULT_DIST_DIR,
280
- cache: false
281
- });
282
- const rootDir = process.cwd();
283
- const resolvedArtifactPath = path2.resolve(rootDir, artifactOutfile);
284
- const appIdentifier = await readZipContent(resolvedArtifactPath, APP_MANIFEST_NAME).then((rawAppManifest) => {
285
- const appManifest = JSON.parse(rawAppManifest);
286
- const appIdentifier2 = appManifest.appName;
287
- assert(typeof appIdentifier2 === "string", "invalid appName");
288
- return appIdentifier2;
289
- }).catch((error) => {
290
- debug2("invalid ait file", error);
291
- throw new Error("\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 ait \uD30C\uC77C\uC785\uB2C8\uB2E4");
3092
+ }
3093
+ const handlerMap = [];
3094
+ for (const i in indexReplacementMap) {
3095
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
3096
+ }
3097
+ return [regexp, handlerMap, staticMap];
3098
+ }
3099
+ function findMiddleware(middleware, path2) {
3100
+ if (!middleware) {
3101
+ return void 0;
3102
+ }
3103
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
3104
+ if (buildWildcardRegExp(k).test(path2)) {
3105
+ return [...middleware[k]];
3106
+ }
3107
+ }
3108
+ return void 0;
3109
+ }
3110
+ var RegExpRouter = class {
3111
+ name = "RegExpRouter";
3112
+ #middleware;
3113
+ #routes;
3114
+ constructor() {
3115
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3116
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3117
+ }
3118
+ add(method, path2, handler) {
3119
+ const middleware = this.#middleware;
3120
+ const routes = this.#routes;
3121
+ if (!middleware || !routes) {
3122
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3123
+ }
3124
+ if (!middleware[method]) {
3125
+ ;
3126
+ [middleware, routes].forEach((handlerMap) => {
3127
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
3128
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
3129
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
3130
+ });
292
3131
  });
293
- let deploymentId = null;
294
- const colorAppName = picocolors2.underline(picocolors2.cyan(appIdentifier));
295
- await p.tasks([
296
- {
297
- title: `${colorAppName} \uC571 \uBC30\uD3EC \uC911...`,
298
- task: async () => {
299
- deploymentId = await uploadArtifact({
300
- artifactPath: resolvedArtifactPath,
301
- appName: appIdentifier,
302
- apiKey
303
- });
304
- return `${colorAppName} \uBC30\uD3EC\uAC00 \uC644\uB8CC\uB418\uC5C8\uC5B4\uC694`;
305
- }
306
- }
307
- ]);
308
- if (deploymentId) {
309
- p.note(picocolors2.underline(picocolors2.green(`intoss-sandbox://${appIdentifier}?_deploymentId=${deploymentId}`)));
310
- }
311
- } catch (error) {
312
- if (error instanceof Error) {
313
- p.log.error(error.message);
3132
+ }
3133
+ if (path2 === "/*") {
3134
+ path2 = "*";
3135
+ }
3136
+ const paramCount = (path2.match(/\/:/g) || []).length;
3137
+ if (/\*$/.test(path2)) {
3138
+ const re = buildWildcardRegExp(path2);
3139
+ if (method === METHOD_NAME_ALL) {
3140
+ Object.keys(middleware).forEach((m) => {
3141
+ middleware[m][path2] ||= findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];
3142
+ });
314
3143
  } else {
315
- console.error(error);
3144
+ middleware[method][path2] ||= findMiddleware(middleware[method], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];
316
3145
  }
317
- process.exit(1);
3146
+ Object.keys(middleware).forEach((m) => {
3147
+ if (method === METHOD_NAME_ALL || method === m) {
3148
+ Object.keys(middleware[m]).forEach((p) => {
3149
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
3150
+ });
3151
+ }
3152
+ });
3153
+ Object.keys(routes).forEach((m) => {
3154
+ if (method === METHOD_NAME_ALL || method === m) {
3155
+ Object.keys(routes[m]).forEach(
3156
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
3157
+ );
3158
+ }
3159
+ });
3160
+ return;
3161
+ }
3162
+ const paths = checkOptionalParameter(path2) || [path2];
3163
+ for (let i = 0, len = paths.length; i < len; i++) {
3164
+ const path22 = paths[i];
3165
+ Object.keys(routes).forEach((m) => {
3166
+ if (method === METHOD_NAME_ALL || method === m) {
3167
+ routes[m][path22] ||= [
3168
+ ...findMiddleware(middleware[m], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
3169
+ ];
3170
+ routes[m][path22].push([handler, paramCount - len + i + 1]);
3171
+ }
3172
+ });
318
3173
  }
319
3174
  }
320
- };
321
-
322
- // src/DevCommand/DevCommand.ts
323
- import fs3 from "fs";
324
- import path3 from "path";
325
- import * as mpack2 from "@react-native-bedrock/mpack-next";
326
- import { Command as Command3, Option as Option3 } from "clipanion";
327
- import { execa as execa2 } from "execa";
328
- import presets2 from "react-native-bedrock/presets";
329
- var DevCommand = class extends Command3 {
330
- static paths = [[`dev`]];
331
- static usage = Command3.Usage({
332
- category: "Development",
333
- description: "AppsInToss \uAC1C\uBC1C \uC11C\uBC84\uB97C \uC2E4\uD589\uD569\uB2C8\uB2E4",
334
- examples: [["\uAC1C\uBC1C \uC11C\uBC84 \uC2E4\uD589\uD558\uAE30", "ait dev"]]
335
- });
336
- host = Option3.String("--host");
337
- port = Option3.String("--port");
338
- async execute() {
339
- const config = await loadConfig();
340
- const serverOptions = {
341
- host: this.host,
342
- port: this.port ? parseInt(this.port, 10) : void 0
3175
+ match(method, path2) {
3176
+ clearWildcardRegExpCache();
3177
+ const matchers = this.#buildAllMatchers();
3178
+ this.match = (method2, path22) => {
3179
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
3180
+ const staticMatch = matcher[2][path22];
3181
+ if (staticMatch) {
3182
+ return staticMatch;
3183
+ }
3184
+ const match = path22.match(matcher[0]);
3185
+ if (!match) {
3186
+ return [[], emptyParam];
3187
+ }
3188
+ const index = match.indexOf("", 1);
3189
+ return [matcher[1][index], match];
343
3190
  };
344
- const cwd = path3.resolve(__dirname, "..", "react-native");
345
- const projectRootTmp = path3.resolve(process.cwd(), ".bedrock");
346
- await fs3.promises.mkdir(projectRootTmp, { recursive: true });
347
- await fs3.promises.writeFile(
348
- path3.join(projectRootTmp, "metadata.json"),
349
- JSON.stringify({ appName: config.appName, webPort: config.web.port })
350
- );
351
- const appName = config.appName;
352
- await mpack2.runServer({
353
- host: serverOptions.host,
354
- port: serverOptions.port,
355
- enableEmbeddedReactDevTools: true,
356
- enableRouterGen: false,
357
- onServerReady: async () => {
358
- this.context.stdout.write(
359
- `Server is running on http://${serverOptions.host || DEFAULT_HOST}:${serverOptions.port || DEFAULT_LOCALHOST_PORT}
360
- `
3191
+ return this.match(method, path2);
3192
+ }
3193
+ #buildAllMatchers() {
3194
+ const matchers = /* @__PURE__ */ Object.create(null);
3195
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
3196
+ matchers[method] ||= this.#buildMatcher(method);
3197
+ });
3198
+ this.#middleware = this.#routes = void 0;
3199
+ return matchers;
3200
+ }
3201
+ #buildMatcher(method) {
3202
+ const routes = [];
3203
+ let hasOwnRoute = method === METHOD_NAME_ALL;
3204
+ [this.#middleware, this.#routes].forEach((r) => {
3205
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path2) => [path2, r[method][path2]]) : [];
3206
+ if (ownRoute.length !== 0) {
3207
+ hasOwnRoute ||= true;
3208
+ routes.push(...ownRoute);
3209
+ } else if (method !== METHOD_NAME_ALL) {
3210
+ routes.push(
3211
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path2) => [path2, r[METHOD_NAME_ALL][path2]])
361
3212
  );
362
- const { packageManager } = getPackageManager({ isExecutor: true });
363
- await execa2(packageManager, config.web.commands.dev.split(" "), {
364
- cwd: process.cwd(),
365
- stdio: "inherit"
366
- });
367
- },
368
- cwd,
369
- config: {
370
- appName,
371
- services: {
372
- sentry: {
373
- enabled: false
374
- }
375
- },
376
- devServer: {
377
- presets: [presets2.service()],
378
- build: {
379
- entry: "./src/_app.tsx"
380
- }
381
- },
382
- tasks: []
383
3213
  }
384
3214
  });
3215
+ if (!hasOwnRoute) {
3216
+ return null;
3217
+ } else {
3218
+ return buildMatcherFromPreprocessedRoutes(routes);
3219
+ }
385
3220
  }
386
3221
  };
387
3222
 
388
- // src/InitCommand/InitCommand.ts
389
- import fs5 from "fs";
390
- import path5 from "path";
391
- import * as p2 from "@clack/prompts";
392
- import { Command as Command4 } from "clipanion";
393
- import { kebabCase, merge } from "es-toolkit";
394
- import { execa as execa3 } from "execa";
395
- import yaml from "yaml";
396
-
397
- // src/InitCommand/templates/index.tsx
398
- var CONFIG_TEMPLATE = `import { defineConfig } from '@apps-in-toss/web-framework';
399
-
400
- export default defineConfig({
401
- appName: '%%appName%%',
402
- web: {
403
- port: %%webPort%%,
404
- commands: {
405
- dev: '%%webDevCommand%%',
406
- build: '%%webBuildCommand%%',
407
- },
408
- },
409
- });
410
- `;
3223
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/smart-router/index.js
3224
+ init_esm_shims();
411
3225
 
412
- // src/utils/getPackageRoot.ts
413
- import fs4 from "fs";
414
- import path4 from "path";
415
- function getPackageRoot() {
416
- let cwd = process.cwd();
417
- const root = path4.parse(cwd).root;
418
- while (cwd !== root) {
419
- if (fs4.existsSync(path4.join(cwd, "package.json"))) {
420
- return cwd;
3226
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/smart-router/router.js
3227
+ init_esm_shims();
3228
+ var SmartRouter = class {
3229
+ name = "SmartRouter";
3230
+ #routers = [];
3231
+ #routes = [];
3232
+ constructor(init) {
3233
+ this.#routers = init.routers;
3234
+ }
3235
+ add(method, path2, handler) {
3236
+ if (!this.#routes) {
3237
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
421
3238
  }
422
- cwd = path4.dirname(cwd);
3239
+ this.#routes.push([method, path2, handler]);
423
3240
  }
424
- return cwd;
425
- }
426
-
427
- // src/utils/transformTemplate.ts
428
- function transformTemplate(templateString, values) {
429
- let result = templateString;
430
- for (const key in values) {
431
- const placeholder = `%%${key}%%`;
432
- result = result.replace(new RegExp(placeholder, "g"), values[key]);
3241
+ match(method, path2) {
3242
+ if (!this.#routes) {
3243
+ throw new Error("Fatal error");
3244
+ }
3245
+ const routers = this.#routers;
3246
+ const routes = this.#routes;
3247
+ const len = routers.length;
3248
+ let i = 0;
3249
+ let res;
3250
+ for (; i < len; i++) {
3251
+ const router = routers[i];
3252
+ try {
3253
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
3254
+ router.add(...routes[i2]);
3255
+ }
3256
+ res = router.match(method, path2);
3257
+ } catch (e) {
3258
+ if (e instanceof UnsupportedPathError) {
3259
+ continue;
3260
+ }
3261
+ throw e;
3262
+ }
3263
+ this.match = router.match.bind(router);
3264
+ this.#routers = [router];
3265
+ this.#routes = void 0;
3266
+ break;
3267
+ }
3268
+ if (i === len) {
3269
+ throw new Error("Fatal error");
3270
+ }
3271
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
3272
+ return res;
433
3273
  }
434
- return result;
435
- }
3274
+ get activeRouter() {
3275
+ if (this.#routes || this.#routers.length !== 1) {
3276
+ throw new Error("No active router has been determined yet.");
3277
+ }
3278
+ return this.#routers[0];
3279
+ }
3280
+ };
436
3281
 
437
- // src/InitCommand/InitCommand.ts
438
- var InitCommand = class extends Command4 {
439
- static paths = [[`init`]];
440
- async execute() {
441
- const cwd = getPackageRoot();
442
- p2.intro("\u{1F680} \uC571 \uCD08\uAE30\uD654\uB97C \uC2DC\uC791\uD569\uB2C8\uB2E4");
443
- const appName = await p2.text({
444
- message: "Enter app name",
445
- validate: (value) => {
446
- if (!value) {
447
- return "\uC571 \uC774\uB984\uC744 \uC785\uB825\uD574\uC8FC\uC138\uC694";
448
- }
449
- const kebabCaseValue = kebabCase(value);
450
- if (value !== kebabCaseValue) {
451
- return `\uC571 \uC774\uB984\uC740 \uCF00\uBC25-\uCF00\uC774\uC2A4 \uD615\uC2DD\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4 (\uC608\uC2DC: ${kebabCaseValue})`;
3282
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/trie-router/index.js
3283
+ init_esm_shims();
3284
+
3285
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/trie-router/router.js
3286
+ init_esm_shims();
3287
+
3288
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/trie-router/node.js
3289
+ init_esm_shims();
3290
+ var emptyParams = /* @__PURE__ */ Object.create(null);
3291
+ var Node2 = class {
3292
+ #methods;
3293
+ #children;
3294
+ #patterns;
3295
+ #order = 0;
3296
+ #params = emptyParams;
3297
+ constructor(method, handler, children) {
3298
+ this.#children = children || /* @__PURE__ */ Object.create(null);
3299
+ this.#methods = [];
3300
+ if (method && handler) {
3301
+ const m = /* @__PURE__ */ Object.create(null);
3302
+ m[method] = { handler, possibleKeys: [], score: 0 };
3303
+ this.#methods = [m];
3304
+ }
3305
+ this.#patterns = [];
3306
+ }
3307
+ insert(method, path2, handler) {
3308
+ this.#order = ++this.#order;
3309
+ let curNode = this;
3310
+ const parts = splitRoutingPath(path2);
3311
+ const possibleKeys = [];
3312
+ for (let i = 0, len = parts.length; i < len; i++) {
3313
+ const p = parts[i];
3314
+ const nextP = parts[i + 1];
3315
+ const pattern = getPattern(p, nextP);
3316
+ const key = Array.isArray(pattern) ? pattern[0] : p;
3317
+ if (Object.keys(curNode.#children).includes(key)) {
3318
+ curNode = curNode.#children[key];
3319
+ const pattern2 = getPattern(p, nextP);
3320
+ if (pattern2) {
3321
+ possibleKeys.push(pattern2[1]);
452
3322
  }
453
- return;
3323
+ continue;
454
3324
  }
455
- });
456
- if (p2.isCancel(appName)) {
457
- p2.cancel("\uCD08\uAE30\uD654\uAC00 \uCDE8\uC18C\uB418\uC5C8\uC2B5\uB2C8\uB2E4");
458
- return;
459
- }
460
- p2.log.step(`\uC571 \uC774\uB984\uC774 '${appName}'\uC73C\uB85C \uC124\uC815\uB418\uC5C8\uC2B5\uB2C8\uB2E4`);
461
- const webPort = await p2.text({
462
- message: "Enter web port",
463
- placeholder: "5173",
464
- defaultValue: "5173"
465
- });
466
- if (p2.isCancel(webPort)) {
467
- p2.cancel("\uCD08\uAE30\uD654\uAC00 \uCDE8\uC18C\uB418\uC5C8\uC2B5\uB2C8\uB2E4");
468
- return;
3325
+ curNode.#children[key] = new Node2();
3326
+ if (pattern) {
3327
+ curNode.#patterns.push(pattern);
3328
+ possibleKeys.push(pattern[1]);
3329
+ }
3330
+ curNode = curNode.#children[key];
469
3331
  }
470
- p2.log.step("package.json \uC2A4\uD06C\uB9BD\uD2B8\uB97C \uC124\uC815\uD558\uB294 \uC911...");
471
- const packageJson = await fs5.promises.readFile(path5.join(cwd, "package.json"), {
472
- encoding: "utf-8"
473
- });
474
- const scripts = JSON.parse(packageJson);
475
- const original = {
476
- dev: scripts?.scripts?.dev || scripts?.scripts?.start,
477
- build: scripts?.scripts?.build
3332
+ const m = /* @__PURE__ */ Object.create(null);
3333
+ const handlerSet = {
3334
+ handler,
3335
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
3336
+ score: this.#order
478
3337
  };
479
- scripts.scripts.dev = "ait dev";
480
- scripts.scripts.build = "ait build";
481
- scripts.scripts.deploy = "ait deploy";
482
- await fs5.promises.writeFile(path5.join(cwd, "package.json"), JSON.stringify(scripts, null, 2), {
483
- encoding: "utf-8"
484
- });
485
- p2.log.step("apps-in-toss.config.web.ts \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uB294 \uC911...");
486
- const config = transformTemplate(CONFIG_TEMPLATE, {
487
- appName,
488
- webPort,
489
- webDevCommand: original.dev === "ait dev" ? "" : original.dev,
490
- webBuildCommand: original.build === "ait build" ? "" : original.build
491
- });
492
- await fs5.promises.writeFile(path5.join(cwd, "apps-in-toss.config.web.ts"), config, {
493
- encoding: "utf-8"
494
- });
495
- p2.log.step(".gitignore \uD30C\uC77C\uC744 \uC5C5\uB370\uC774\uD2B8\uD558\uB294 \uC911...");
496
- await fs5.promises.appendFile(path5.join(cwd, ".gitignore"), "\n.bedrock\n");
497
- p2.log.step("app.json \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uB294 \uC911...");
498
- await fs5.promises.writeFile(
499
- path5.join(cwd, "app.json"),
500
- JSON.stringify({
501
- clientId: "",
502
- appName,
503
- permissions: []
504
- }),
505
- {
506
- encoding: "utf-8"
507
- }
508
- );
509
- const isPnP = fs5.existsSync(path5.join(cwd, ".pnp.cjs"));
510
- if (isPnP) {
511
- const yarnrcPath = path5.join(cwd, ".yarnrc.yml");
512
- let yarnrc = {};
513
- try {
514
- const yarnrcContent = await fs5.promises.readFile(yarnrcPath, { encoding: "utf-8" });
515
- yarnrc = yaml.parse(yarnrcContent);
516
- } catch {
517
- p2.log.info(".yarnrc.yml \uD30C\uC77C\uC774 \uC5C6\uC5B4 \uC0C8\uB85C \uC0DD\uC131\uD569\uB2C8\uB2E4.");
3338
+ m[method] = handlerSet;
3339
+ curNode.#methods.push(m);
3340
+ return curNode;
3341
+ }
3342
+ #getHandlerSets(node, method, nodeParams, params) {
3343
+ const handlerSets = [];
3344
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
3345
+ const m = node.#methods[i];
3346
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
3347
+ const processedSet = {};
3348
+ if (handlerSet !== void 0) {
3349
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
3350
+ handlerSets.push(handlerSet);
3351
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
3352
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
3353
+ const key = handlerSet.possibleKeys[i2];
3354
+ const processed = processedSet[handlerSet.score];
3355
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
3356
+ processedSet[handlerSet.score] = true;
3357
+ }
3358
+ }
518
3359
  }
519
- p2.log.step(".yarnrc.yml \uD30C\uC77C\uC744 \uC5C5\uB370\uC774\uD2B8\uD558\uB294 \uC911...");
520
- yarnrc.packageExtensions = merge(yarnrc.packageExtensions, {
521
- "@react-native-community/cli-debugger-ui@*": {
522
- dependencies: {
523
- "@babel/runtime": "^7"
3360
+ }
3361
+ return handlerSets;
3362
+ }
3363
+ search(method, path2) {
3364
+ const handlerSets = [];
3365
+ this.#params = emptyParams;
3366
+ const curNode = this;
3367
+ let curNodes = [curNode];
3368
+ const parts = splitPath(path2);
3369
+ const curNodesQueue = [];
3370
+ for (let i = 0, len = parts.length; i < len; i++) {
3371
+ const part = parts[i];
3372
+ const isLast = i === len - 1;
3373
+ const tempNodes = [];
3374
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
3375
+ const node = curNodes[j];
3376
+ const nextNode = node.#children[part];
3377
+ if (nextNode) {
3378
+ nextNode.#params = node.#params;
3379
+ if (isLast) {
3380
+ if (nextNode.#children["*"]) {
3381
+ handlerSets.push(
3382
+ ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
3383
+ );
3384
+ }
3385
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
3386
+ } else {
3387
+ tempNodes.push(nextNode);
3388
+ }
3389
+ }
3390
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
3391
+ const pattern = node.#patterns[k];
3392
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
3393
+ if (pattern === "*") {
3394
+ const astNode = node.#children["*"];
3395
+ if (astNode) {
3396
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
3397
+ astNode.#params = params;
3398
+ tempNodes.push(astNode);
3399
+ }
3400
+ continue;
3401
+ }
3402
+ if (part === "") {
3403
+ continue;
524
3404
  }
525
- },
526
- "react-native-video@*": {
527
- peerDependencies: {
528
- react: "*",
529
- "react-native": "*"
3405
+ const [key, name, matcher] = pattern;
3406
+ const child = node.#children[key];
3407
+ const restPathString = parts.slice(i).join("/");
3408
+ if (matcher instanceof RegExp) {
3409
+ const m = matcher.exec(restPathString);
3410
+ if (m) {
3411
+ params[name] = m[0];
3412
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
3413
+ if (Object.keys(child.#children).length) {
3414
+ child.#params = params;
3415
+ const componentCount = m[0].match(/\//)?.length ?? 0;
3416
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
3417
+ targetCurNodes.push(child);
3418
+ }
3419
+ continue;
3420
+ }
530
3421
  }
531
- },
532
- "react-native-fast-image@*": {
533
- dependencies: {
534
- "@babel/runtime": "^7"
3422
+ if (matcher === true || matcher.test(part)) {
3423
+ params[name] = part;
3424
+ if (isLast) {
3425
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
3426
+ if (child.#children["*"]) {
3427
+ handlerSets.push(
3428
+ ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
3429
+ );
3430
+ }
3431
+ } else {
3432
+ child.#params = params;
3433
+ tempNodes.push(child);
3434
+ }
535
3435
  }
536
3436
  }
3437
+ }
3438
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
3439
+ }
3440
+ if (handlerSets.length > 1) {
3441
+ handlerSets.sort((a, b) => {
3442
+ return a.score - b.score;
537
3443
  });
538
- await fs5.promises.writeFile(yarnrcPath, yaml.stringify(yarnrc), { encoding: "utf-8" });
539
- await execa3("yarn", ["install"], {
540
- cwd,
541
- stdio: "inherit"
542
- });
543
3444
  }
544
- p2.outro("\u2728 \uCD08\uAE30\uD654\uAC00 \uC644\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4!");
3445
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
3446
+ }
3447
+ };
3448
+
3449
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/router/trie-router/router.js
3450
+ var TrieRouter = class {
3451
+ name = "TrieRouter";
3452
+ #node;
3453
+ constructor() {
3454
+ this.#node = new Node2();
3455
+ }
3456
+ add(method, path2, handler) {
3457
+ const results = checkOptionalParameter(path2);
3458
+ if (results) {
3459
+ for (let i = 0, len = results.length; i < len; i++) {
3460
+ this.#node.insert(method, results[i], handler);
3461
+ }
3462
+ return;
3463
+ }
3464
+ this.#node.insert(method, path2, handler);
3465
+ }
3466
+ match(method, path2) {
3467
+ return this.#node.search(method, path2);
3468
+ }
3469
+ };
3470
+
3471
+ // ../../.yarn/cache/hono-npm-4.7.4-9bd547bbac-b189c5b755.zip/node_modules/hono/dist/hono.js
3472
+ var Hono2 = class extends Hono {
3473
+ constructor(options = {}) {
3474
+ super(options);
3475
+ this.router = options.router ?? new SmartRouter({
3476
+ routers: [new RegExpRouter(), new TrieRouter()]
3477
+ });
545
3478
  }
546
3479
  };
547
3480
 
548
- // package.json
549
- var version = "0.1.6-next.6";
3481
+ // src/server.ts
3482
+ var app = new Hono2();
3483
+ app.get("/status", (c) => {
3484
+ c.header("X-React-Native-Project-Root", path.resolve(__dirname, "..", "react-native"));
3485
+ return c.text("packager-status:running");
3486
+ });
3487
+ app.get("/permissions", (c) => {
3488
+ return c.text("contacts:rw");
3489
+ });
3490
+ app.get("/oauth/scope", (c) => {
3491
+ return c.text("user_email;user_name");
3492
+ });
3493
+ app.get("/index.bundle", async (c) => {
3494
+ const platform = c.req.query("platform");
3495
+ const bundle = fs.readFileSync(path.resolve(__dirname, "..", "dist", `app-name.${platform}.js`), "utf-8");
3496
+ c.header("Surrogate-Control", "no-store");
3497
+ c.header("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
3498
+ c.header("Pragma", "no-cache");
3499
+ c.header("Expires", "0");
3500
+ c.header("Content-Type", "application/javascript");
3501
+ const result = await transform(bundle, {
3502
+ plugins: [
3503
+ [
3504
+ "@apps-in-toss/babel-plugin-json",
3505
+ {
3506
+ json: {
3507
+ appName: "web-framework",
3508
+ webPort: 5173
3509
+ },
3510
+ identifierName: "Ait"
3511
+ }
3512
+ ]
3513
+ ]
3514
+ });
3515
+ if (!result?.code) {
3516
+ return c.text("Error", 500);
3517
+ }
3518
+ return c.body(result.code);
3519
+ });
3520
+
3521
+ // src/commands/DevCommand.ts
3522
+ var DevCommand = class extends Command {
3523
+ static paths = [[`dev`]];
3524
+ static usage = Command.Usage({
3525
+ category: "Development",
3526
+ description: "Bedrock \uAC1C\uBC1C \uC11C\uBC84\uB97C \uC2E4\uD589\uD569\uB2C8\uB2E4",
3527
+ examples: [["\uAC1C\uBC1C \uC11C\uBC84 \uC2E4\uD589\uD558\uAE30", "bedrock dev"]]
3528
+ });
3529
+ async execute() {
3530
+ serve(
3531
+ {
3532
+ hostname: "0.0.0.0",
3533
+ fetch: app.fetch,
3534
+ port: 8081
3535
+ },
3536
+ (info) => {
3537
+ console.log(`Listening on http://localhost:${info.port}`);
3538
+ }
3539
+ );
3540
+ }
3541
+ };
550
3542
 
551
3543
  // src/cli.ts
552
3544
  var cli = new Cli({
553
- binaryLabel: "apps-in-toss",
554
- binaryName: "apps-in-toss",
555
- binaryVersion: version,
3545
+ binaryLabel: "bedrock",
3546
+ binaryName: "bedrock",
556
3547
  enableCapture: true
557
3548
  });
558
- cli.register(InitCommand);
559
- cli.register(DevCommand);
560
- cli.register(BuildCommand);
561
- cli.register(DeployCommand);
562
- cli.runExit(process.argv.slice(2));
3549
+ async function initialize() {
3550
+ cli.register(DevCommand);
3551
+ cli.runExit(process.argv.slice(2));
3552
+ }
3553
+ export {
3554
+ initialize
3555
+ };