@astralos/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +79 -0
  2. package/README.md +31 -2
  3. package/dist/astral.js +4584 -0
  4. package/package.json +36 -4
package/dist/astral.js ADDED
@@ -0,0 +1,4584 @@
1
+ #!/usr/bin/env node
2
+
3
+ // node_modules/commander/lib/error.js
4
+ class CommanderError extends Error {
5
+ constructor(exitCode, code, message) {
6
+ super(message);
7
+ Error.captureStackTrace(this, this.constructor);
8
+ this.name = this.constructor.name;
9
+ this.code = code;
10
+ this.exitCode = exitCode;
11
+ this.nestedError = undefined;
12
+ }
13
+ }
14
+
15
+ class InvalidArgumentError extends CommanderError {
16
+ constructor(message) {
17
+ super(1, "commander.invalidArgument", message);
18
+ Error.captureStackTrace(this, this.constructor);
19
+ this.name = this.constructor.name;
20
+ }
21
+ }
22
+
23
+ // node_modules/commander/lib/argument.js
24
+ class Argument {
25
+ constructor(name, description) {
26
+ this.description = description || "";
27
+ this.variadic = false;
28
+ this.parseArg = undefined;
29
+ this.defaultValue = undefined;
30
+ this.defaultValueDescription = undefined;
31
+ this.argChoices = undefined;
32
+ switch (name[0]) {
33
+ case "<":
34
+ this.required = true;
35
+ this._name = name.slice(1, -1);
36
+ break;
37
+ case "[":
38
+ this.required = false;
39
+ this._name = name.slice(1, -1);
40
+ break;
41
+ default:
42
+ this.required = true;
43
+ this._name = name;
44
+ break;
45
+ }
46
+ if (this._name.endsWith("...")) {
47
+ this.variadic = true;
48
+ this._name = this._name.slice(0, -3);
49
+ }
50
+ }
51
+ name() {
52
+ return this._name;
53
+ }
54
+ _collectValue(value, previous) {
55
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
56
+ return [value];
57
+ }
58
+ previous.push(value);
59
+ return previous;
60
+ }
61
+ default(value, description) {
62
+ this.defaultValue = value;
63
+ this.defaultValueDescription = description;
64
+ return this;
65
+ }
66
+ argParser(fn) {
67
+ this.parseArg = fn;
68
+ return this;
69
+ }
70
+ choices(values) {
71
+ this.argChoices = values.slice();
72
+ this.parseArg = (arg, previous) => {
73
+ if (!this.argChoices.includes(arg)) {
74
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
75
+ }
76
+ if (this.variadic) {
77
+ return this._collectValue(arg, previous);
78
+ }
79
+ return arg;
80
+ };
81
+ return this;
82
+ }
83
+ argRequired() {
84
+ this.required = true;
85
+ return this;
86
+ }
87
+ argOptional() {
88
+ this.required = false;
89
+ return this;
90
+ }
91
+ }
92
+ function humanReadableArgName(arg) {
93
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
94
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
95
+ }
96
+
97
+ // node_modules/commander/lib/command.js
98
+ import { EventEmitter } from "node:events";
99
+ import childProcess from "node:child_process";
100
+ import path from "node:path";
101
+ import fs from "node:fs";
102
+ import process2 from "node:process";
103
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
104
+
105
+ // node_modules/commander/lib/help.js
106
+ import { stripVTControlCharacters } from "node:util";
107
+
108
+ class Help {
109
+ constructor() {
110
+ this.helpWidth = undefined;
111
+ this.minWidthToWrap = 40;
112
+ this.sortSubcommands = false;
113
+ this.sortOptions = false;
114
+ this.showGlobalOptions = false;
115
+ }
116
+ prepareContext(contextOptions) {
117
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
118
+ }
119
+ visibleCommands(cmd) {
120
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
121
+ const helpCommand = cmd._getHelpCommand();
122
+ if (helpCommand && !helpCommand._hidden) {
123
+ visibleCommands.push(helpCommand);
124
+ }
125
+ if (this.sortSubcommands) {
126
+ visibleCommands.sort((a, b) => {
127
+ return a.name().localeCompare(b.name());
128
+ });
129
+ }
130
+ return visibleCommands;
131
+ }
132
+ compareOptions(a, b) {
133
+ const getSortKey = (option) => {
134
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
135
+ };
136
+ return getSortKey(a).localeCompare(getSortKey(b));
137
+ }
138
+ visibleOptions(cmd) {
139
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
140
+ const helpOption = cmd._getHelpOption();
141
+ if (helpOption && !helpOption.hidden) {
142
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
143
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
144
+ if (!removeShort && !removeLong) {
145
+ visibleOptions.push(helpOption);
146
+ } else if (helpOption.long && !removeLong) {
147
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
148
+ } else if (helpOption.short && !removeShort) {
149
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
150
+ }
151
+ }
152
+ if (this.sortOptions) {
153
+ visibleOptions.sort(this.compareOptions);
154
+ }
155
+ return visibleOptions;
156
+ }
157
+ visibleGlobalOptions(cmd) {
158
+ if (!this.showGlobalOptions)
159
+ return [];
160
+ const globalOptions = [];
161
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
162
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
163
+ globalOptions.push(...visibleOptions);
164
+ }
165
+ if (this.sortOptions) {
166
+ globalOptions.sort(this.compareOptions);
167
+ }
168
+ return globalOptions;
169
+ }
170
+ visibleArguments(cmd) {
171
+ if (cmd._argsDescription) {
172
+ cmd.registeredArguments.forEach((argument) => {
173
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
174
+ });
175
+ }
176
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
177
+ return cmd.registeredArguments;
178
+ }
179
+ return [];
180
+ }
181
+ subcommandTerm(cmd) {
182
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
183
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
184
+ }
185
+ optionTerm(option) {
186
+ return option.flags;
187
+ }
188
+ argumentTerm(argument) {
189
+ return argument.name();
190
+ }
191
+ longestSubcommandTermLength(cmd, helper) {
192
+ return helper.visibleCommands(cmd).reduce((max, command) => {
193
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
194
+ }, 0);
195
+ }
196
+ longestOptionTermLength(cmd, helper) {
197
+ return helper.visibleOptions(cmd).reduce((max, option) => {
198
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
199
+ }, 0);
200
+ }
201
+ longestGlobalOptionTermLength(cmd, helper) {
202
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
203
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
204
+ }, 0);
205
+ }
206
+ longestArgumentTermLength(cmd, helper) {
207
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
208
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
209
+ }, 0);
210
+ }
211
+ commandUsage(cmd) {
212
+ let cmdName = cmd._name;
213
+ if (cmd._aliases[0]) {
214
+ cmdName = cmdName + "|" + cmd._aliases[0];
215
+ }
216
+ let ancestorCmdNames = "";
217
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
218
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
219
+ }
220
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
221
+ }
222
+ commandDescription(cmd) {
223
+ return cmd.description();
224
+ }
225
+ subcommandDescription(cmd) {
226
+ return cmd.summary() || cmd.description();
227
+ }
228
+ optionDescription(option) {
229
+ const extraInfo = [];
230
+ if (option.argChoices) {
231
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
232
+ }
233
+ if (option.defaultValue !== undefined) {
234
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
235
+ if (showDefault) {
236
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
237
+ }
238
+ }
239
+ if (option.presetArg !== undefined && option.optional) {
240
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
241
+ }
242
+ if (option.envVar !== undefined) {
243
+ extraInfo.push(`env: ${option.envVar}`);
244
+ }
245
+ if (extraInfo.length > 0) {
246
+ const extraDescription = `(${extraInfo.join(", ")})`;
247
+ if (option.description) {
248
+ return `${option.description} ${extraDescription}`;
249
+ }
250
+ return extraDescription;
251
+ }
252
+ return option.description;
253
+ }
254
+ argumentDescription(argument) {
255
+ const extraInfo = [];
256
+ if (argument.argChoices) {
257
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
258
+ }
259
+ if (argument.defaultValue !== undefined) {
260
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
261
+ }
262
+ if (extraInfo.length > 0) {
263
+ const extraDescription = `(${extraInfo.join(", ")})`;
264
+ if (argument.description) {
265
+ return `${argument.description} ${extraDescription}`;
266
+ }
267
+ return extraDescription;
268
+ }
269
+ return argument.description;
270
+ }
271
+ formatItemList(heading, items, helper) {
272
+ if (items.length === 0)
273
+ return [];
274
+ return [helper.styleTitle(heading), ...items, ""];
275
+ }
276
+ groupItems(unsortedItems, visibleItems, getGroup) {
277
+ const result = new Map;
278
+ unsortedItems.forEach((item) => {
279
+ const group = getGroup(item);
280
+ if (!result.has(group))
281
+ result.set(group, []);
282
+ });
283
+ visibleItems.forEach((item) => {
284
+ const group = getGroup(item);
285
+ if (!result.has(group)) {
286
+ result.set(group, []);
287
+ }
288
+ result.get(group).push(item);
289
+ });
290
+ return result;
291
+ }
292
+ formatHelp(cmd, helper) {
293
+ const termWidth = helper.padWidth(cmd, helper);
294
+ const helpWidth = helper.helpWidth ?? 80;
295
+ function callFormatItem(term, description) {
296
+ return helper.formatItem(term, termWidth, description, helper);
297
+ }
298
+ let output = [
299
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
300
+ ""
301
+ ];
302
+ const commandDescription = helper.commandDescription(cmd);
303
+ if (commandDescription.length > 0) {
304
+ output = output.concat([
305
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
306
+ ""
307
+ ]);
308
+ }
309
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
310
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
311
+ });
312
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
313
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
314
+ optionGroups.forEach((options, group) => {
315
+ const optionList = options.map((option) => {
316
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
317
+ });
318
+ output = output.concat(this.formatItemList(group, optionList, helper));
319
+ });
320
+ if (helper.showGlobalOptions) {
321
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
322
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
323
+ });
324
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
325
+ }
326
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
327
+ commandGroups.forEach((commands, group) => {
328
+ const commandList = commands.map((sub) => {
329
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
330
+ });
331
+ output = output.concat(this.formatItemList(group, commandList, helper));
332
+ });
333
+ return output.join(`
334
+ `);
335
+ }
336
+ displayWidth(str) {
337
+ return stripVTControlCharacters(str).length;
338
+ }
339
+ styleTitle(str) {
340
+ return str;
341
+ }
342
+ styleUsage(str) {
343
+ return str.split(" ").map((word) => {
344
+ if (word === "[options]")
345
+ return this.styleOptionText(word);
346
+ if (word === "[command]")
347
+ return this.styleSubcommandText(word);
348
+ if (word[0] === "[" || word[0] === "<")
349
+ return this.styleArgumentText(word);
350
+ return this.styleCommandText(word);
351
+ }).join(" ");
352
+ }
353
+ styleCommandDescription(str) {
354
+ return this.styleDescriptionText(str);
355
+ }
356
+ styleOptionDescription(str) {
357
+ return this.styleDescriptionText(str);
358
+ }
359
+ styleSubcommandDescription(str) {
360
+ return this.styleDescriptionText(str);
361
+ }
362
+ styleArgumentDescription(str) {
363
+ return this.styleDescriptionText(str);
364
+ }
365
+ styleDescriptionText(str) {
366
+ return str;
367
+ }
368
+ styleOptionTerm(str) {
369
+ return this.styleOptionText(str);
370
+ }
371
+ styleSubcommandTerm(str) {
372
+ return str.split(" ").map((word) => {
373
+ if (word === "[options]")
374
+ return this.styleOptionText(word);
375
+ if (word[0] === "[" || word[0] === "<")
376
+ return this.styleArgumentText(word);
377
+ return this.styleSubcommandText(word);
378
+ }).join(" ");
379
+ }
380
+ styleArgumentTerm(str) {
381
+ return this.styleArgumentText(str);
382
+ }
383
+ styleOptionText(str) {
384
+ return str;
385
+ }
386
+ styleArgumentText(str) {
387
+ return str;
388
+ }
389
+ styleSubcommandText(str) {
390
+ return str;
391
+ }
392
+ styleCommandText(str) {
393
+ return str;
394
+ }
395
+ padWidth(cmd, helper) {
396
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
397
+ }
398
+ preformatted(str) {
399
+ return /\n[^\S\r\n]/.test(str);
400
+ }
401
+ formatItem(term, termWidth, description, helper) {
402
+ const itemIndent = 2;
403
+ const itemIndentStr = " ".repeat(itemIndent);
404
+ if (!description)
405
+ return itemIndentStr + term;
406
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
407
+ const spacerWidth = 2;
408
+ const helpWidth = this.helpWidth ?? 80;
409
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
410
+ let formattedDescription;
411
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
412
+ formattedDescription = description;
413
+ } else {
414
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
415
+ formattedDescription = wrappedDescription.replace(/\n/g, `
416
+ ` + " ".repeat(termWidth + spacerWidth));
417
+ }
418
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
419
+ ${itemIndentStr}`);
420
+ }
421
+ boxWrap(str, width) {
422
+ if (width < this.minWidthToWrap)
423
+ return str;
424
+ const rawLines = str.split(/\r\n|\n/);
425
+ const chunkPattern = /[\s]*[^\s]+/g;
426
+ const wrappedLines = [];
427
+ rawLines.forEach((line) => {
428
+ const chunks = line.match(chunkPattern);
429
+ if (chunks === null) {
430
+ wrappedLines.push("");
431
+ return;
432
+ }
433
+ let sumChunks = [chunks.shift()];
434
+ let sumWidth = this.displayWidth(sumChunks[0]);
435
+ chunks.forEach((chunk) => {
436
+ const visibleWidth = this.displayWidth(chunk);
437
+ if (sumWidth + visibleWidth <= width) {
438
+ sumChunks.push(chunk);
439
+ sumWidth += visibleWidth;
440
+ return;
441
+ }
442
+ wrappedLines.push(sumChunks.join(""));
443
+ const nextChunk = chunk.trimStart();
444
+ sumChunks = [nextChunk];
445
+ sumWidth = this.displayWidth(nextChunk);
446
+ });
447
+ wrappedLines.push(sumChunks.join(""));
448
+ });
449
+ return wrappedLines.join(`
450
+ `);
451
+ }
452
+ }
453
+
454
+ // node_modules/commander/lib/option.js
455
+ class Option {
456
+ constructor(flags, description) {
457
+ this.flags = flags;
458
+ this.description = description || "";
459
+ this.required = flags.includes("<");
460
+ this.optional = flags.includes("[");
461
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
462
+ this.mandatory = false;
463
+ const optionFlags = splitOptionFlags(flags);
464
+ this.short = optionFlags.shortFlag;
465
+ this.long = optionFlags.longFlag;
466
+ this.negate = false;
467
+ if (this.long) {
468
+ this.negate = this.long.startsWith("--no-");
469
+ }
470
+ this.defaultValue = undefined;
471
+ this.defaultValueDescription = undefined;
472
+ this.presetArg = undefined;
473
+ this.envVar = undefined;
474
+ this.parseArg = undefined;
475
+ this.hidden = false;
476
+ this.argChoices = undefined;
477
+ this.conflictsWith = [];
478
+ this.implied = undefined;
479
+ this.helpGroupHeading = undefined;
480
+ }
481
+ default(value, description) {
482
+ this.defaultValue = value;
483
+ this.defaultValueDescription = description;
484
+ return this;
485
+ }
486
+ preset(arg) {
487
+ this.presetArg = arg;
488
+ return this;
489
+ }
490
+ conflicts(names) {
491
+ this.conflictsWith = this.conflictsWith.concat(names);
492
+ return this;
493
+ }
494
+ implies(impliedOptionValues) {
495
+ let newImplied = impliedOptionValues;
496
+ if (typeof impliedOptionValues === "string") {
497
+ newImplied = { [impliedOptionValues]: true };
498
+ }
499
+ this.implied = Object.assign(this.implied || {}, newImplied);
500
+ return this;
501
+ }
502
+ env(name) {
503
+ this.envVar = name;
504
+ return this;
505
+ }
506
+ argParser(fn) {
507
+ this.parseArg = fn;
508
+ return this;
509
+ }
510
+ makeOptionMandatory(mandatory = true) {
511
+ this.mandatory = !!mandatory;
512
+ return this;
513
+ }
514
+ hideHelp(hide = true) {
515
+ this.hidden = !!hide;
516
+ return this;
517
+ }
518
+ _collectValue(value, previous) {
519
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
520
+ return [value];
521
+ }
522
+ previous.push(value);
523
+ return previous;
524
+ }
525
+ choices(values) {
526
+ this.argChoices = values.slice();
527
+ this.parseArg = (arg, previous) => {
528
+ if (!this.argChoices.includes(arg)) {
529
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
530
+ }
531
+ if (this.variadic) {
532
+ return this._collectValue(arg, previous);
533
+ }
534
+ return arg;
535
+ };
536
+ return this;
537
+ }
538
+ name() {
539
+ if (this.long) {
540
+ return this.long.replace(/^--/, "");
541
+ }
542
+ return this.short.replace(/^-/, "");
543
+ }
544
+ attributeName() {
545
+ if (this.negate) {
546
+ return camelcase(this.name().replace(/^no-/, ""));
547
+ }
548
+ return camelcase(this.name());
549
+ }
550
+ helpGroup(heading) {
551
+ this.helpGroupHeading = heading;
552
+ return this;
553
+ }
554
+ is(arg) {
555
+ return this.short === arg || this.long === arg;
556
+ }
557
+ isBoolean() {
558
+ return !this.required && !this.optional && !this.negate;
559
+ }
560
+ }
561
+
562
+ class DualOptions {
563
+ constructor(options) {
564
+ this.positiveOptions = new Map;
565
+ this.negativeOptions = new Map;
566
+ this.dualOptions = new Set;
567
+ options.forEach((option) => {
568
+ if (option.negate) {
569
+ this.negativeOptions.set(option.attributeName(), option);
570
+ } else {
571
+ this.positiveOptions.set(option.attributeName(), option);
572
+ }
573
+ });
574
+ this.negativeOptions.forEach((value, key) => {
575
+ if (this.positiveOptions.has(key)) {
576
+ this.dualOptions.add(key);
577
+ }
578
+ });
579
+ }
580
+ valueFromOption(value, option) {
581
+ const optionKey = option.attributeName();
582
+ if (!this.dualOptions.has(optionKey))
583
+ return true;
584
+ const preset = this.negativeOptions.get(optionKey).presetArg;
585
+ const negativeValue = preset !== undefined ? preset : false;
586
+ return option.negate === (negativeValue === value);
587
+ }
588
+ }
589
+ function camelcase(str) {
590
+ return str.split("-").reduce((str, word) => {
591
+ return str + word[0].toUpperCase() + word.slice(1);
592
+ });
593
+ }
594
+ function splitOptionFlags(flags) {
595
+ let shortFlag;
596
+ let longFlag;
597
+ const shortFlagExp = /^-[^-]$/;
598
+ const longFlagExp = /^--[^-]/;
599
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
600
+ if (shortFlagExp.test(flagParts[0]))
601
+ shortFlag = flagParts.shift();
602
+ if (longFlagExp.test(flagParts[0]))
603
+ longFlag = flagParts.shift();
604
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
605
+ shortFlag = flagParts.shift();
606
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
607
+ shortFlag = longFlag;
608
+ longFlag = flagParts.shift();
609
+ }
610
+ if (flagParts[0].startsWith("-")) {
611
+ const unsupportedFlag = flagParts[0];
612
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
613
+ if (/^-[^-][^-]/.test(unsupportedFlag))
614
+ throw new Error(`${baseError}
615
+ - a short flag is a single dash and a single character
616
+ - either use a single dash and a single character (for a short flag)
617
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
618
+ if (shortFlagExp.test(unsupportedFlag))
619
+ throw new Error(`${baseError}
620
+ - too many short flags`);
621
+ if (longFlagExp.test(unsupportedFlag))
622
+ throw new Error(`${baseError}
623
+ - too many long flags`);
624
+ throw new Error(`${baseError}
625
+ - unrecognised flag format`);
626
+ }
627
+ if (shortFlag === undefined && longFlag === undefined)
628
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
629
+ return { shortFlag, longFlag };
630
+ }
631
+
632
+ // node_modules/commander/lib/suggestSimilar.js
633
+ var maxDistance = 3;
634
+ function editDistance(a, b) {
635
+ if (Math.abs(a.length - b.length) > maxDistance)
636
+ return Math.max(a.length, b.length);
637
+ const d = [];
638
+ for (let i = 0;i <= a.length; i++) {
639
+ d[i] = [i];
640
+ }
641
+ for (let j = 0;j <= b.length; j++) {
642
+ d[0][j] = j;
643
+ }
644
+ for (let j = 1;j <= b.length; j++) {
645
+ for (let i = 1;i <= a.length; i++) {
646
+ let cost;
647
+ if (a[i - 1] === b[j - 1]) {
648
+ cost = 0;
649
+ } else {
650
+ cost = 1;
651
+ }
652
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
653
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
654
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
655
+ }
656
+ }
657
+ }
658
+ return d[a.length][b.length];
659
+ }
660
+ function suggestSimilar(word, candidates) {
661
+ if (!candidates || candidates.length === 0)
662
+ return "";
663
+ candidates = Array.from(new Set(candidates));
664
+ const searchingOptions = word.startsWith("--");
665
+ if (searchingOptions) {
666
+ word = word.slice(2);
667
+ candidates = candidates.map((candidate) => candidate.slice(2));
668
+ }
669
+ let similar = [];
670
+ let bestDistance = maxDistance;
671
+ const minSimilarity = 0.4;
672
+ candidates.forEach((candidate) => {
673
+ if (candidate.length <= 1)
674
+ return;
675
+ const distance = editDistance(word, candidate);
676
+ const length = Math.max(word.length, candidate.length);
677
+ const similarity = (length - distance) / length;
678
+ if (similarity > minSimilarity) {
679
+ if (distance < bestDistance) {
680
+ bestDistance = distance;
681
+ similar = [candidate];
682
+ } else if (distance === bestDistance) {
683
+ similar.push(candidate);
684
+ }
685
+ }
686
+ });
687
+ similar.sort((a, b) => a.localeCompare(b));
688
+ if (searchingOptions) {
689
+ similar = similar.map((candidate) => `--${candidate}`);
690
+ }
691
+ if (similar.length > 1) {
692
+ return `
693
+ (Did you mean one of ${similar.join(", ")}?)`;
694
+ }
695
+ if (similar.length === 1) {
696
+ return `
697
+ (Did you mean ${similar[0]}?)`;
698
+ }
699
+ return "";
700
+ }
701
+
702
+ // node_modules/commander/lib/command.js
703
+ class Command extends EventEmitter {
704
+ constructor(name) {
705
+ super();
706
+ this.commands = [];
707
+ this.options = [];
708
+ this.parent = null;
709
+ this._allowUnknownOption = false;
710
+ this._allowExcessArguments = false;
711
+ this.registeredArguments = [];
712
+ this._args = this.registeredArguments;
713
+ this.args = [];
714
+ this.rawArgs = [];
715
+ this.processedArgs = [];
716
+ this._scriptPath = null;
717
+ this._name = name || "";
718
+ this._optionValues = {};
719
+ this._optionValueSources = {};
720
+ this._storeOptionsAsProperties = false;
721
+ this._actionHandler = null;
722
+ this._executableHandler = false;
723
+ this._executableFile = null;
724
+ this._executableDir = null;
725
+ this._defaultCommandName = null;
726
+ this._exitCallback = null;
727
+ this._aliases = [];
728
+ this._combineFlagAndOptionalValue = true;
729
+ this._description = "";
730
+ this._summary = "";
731
+ this._argsDescription = undefined;
732
+ this._enablePositionalOptions = false;
733
+ this._passThroughOptions = false;
734
+ this._lifeCycleHooks = {};
735
+ this._showHelpAfterError = false;
736
+ this._showSuggestionAfterError = true;
737
+ this._savedState = null;
738
+ this._outputConfiguration = {
739
+ writeOut: (str) => process2.stdout.write(str),
740
+ writeErr: (str) => process2.stderr.write(str),
741
+ outputError: (str, write) => write(str),
742
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
743
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
744
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
745
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
746
+ stripColor: (str) => stripVTControlCharacters2(str)
747
+ };
748
+ this._hidden = false;
749
+ this._helpOption = undefined;
750
+ this._addImplicitHelpCommand = undefined;
751
+ this._helpCommand = undefined;
752
+ this._helpConfiguration = {};
753
+ this._helpGroupHeading = undefined;
754
+ this._defaultCommandGroup = undefined;
755
+ this._defaultOptionGroup = undefined;
756
+ }
757
+ copyInheritedSettings(sourceCommand) {
758
+ this._outputConfiguration = sourceCommand._outputConfiguration;
759
+ this._helpOption = sourceCommand._helpOption;
760
+ this._helpCommand = sourceCommand._helpCommand;
761
+ this._helpConfiguration = sourceCommand._helpConfiguration;
762
+ this._exitCallback = sourceCommand._exitCallback;
763
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
764
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
765
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
766
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
767
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
768
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
769
+ return this;
770
+ }
771
+ _getCommandAndAncestors() {
772
+ const result = [];
773
+ for (let command = this;command; command = command.parent) {
774
+ result.push(command);
775
+ }
776
+ return result;
777
+ }
778
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
779
+ let desc = actionOptsOrExecDesc;
780
+ let opts = execOpts;
781
+ if (typeof desc === "object" && desc !== null) {
782
+ opts = desc;
783
+ desc = null;
784
+ }
785
+ opts = opts || {};
786
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
787
+ const cmd = this.createCommand(name);
788
+ if (desc) {
789
+ cmd.description(desc);
790
+ cmd._executableHandler = true;
791
+ }
792
+ if (opts.isDefault)
793
+ this._defaultCommandName = cmd._name;
794
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
795
+ cmd._executableFile = opts.executableFile || null;
796
+ if (args)
797
+ cmd.arguments(args);
798
+ this._registerCommand(cmd);
799
+ cmd.parent = this;
800
+ cmd.copyInheritedSettings(this);
801
+ if (desc)
802
+ return this;
803
+ return cmd;
804
+ }
805
+ createCommand(name) {
806
+ return new Command(name);
807
+ }
808
+ createHelp() {
809
+ return Object.assign(new Help, this.configureHelp());
810
+ }
811
+ configureHelp(configuration) {
812
+ if (configuration === undefined)
813
+ return this._helpConfiguration;
814
+ this._helpConfiguration = configuration;
815
+ return this;
816
+ }
817
+ configureOutput(configuration) {
818
+ if (configuration === undefined)
819
+ return this._outputConfiguration;
820
+ this._outputConfiguration = {
821
+ ...this._outputConfiguration,
822
+ ...configuration
823
+ };
824
+ return this;
825
+ }
826
+ showHelpAfterError(displayHelp = true) {
827
+ if (typeof displayHelp !== "string")
828
+ displayHelp = !!displayHelp;
829
+ this._showHelpAfterError = displayHelp;
830
+ return this;
831
+ }
832
+ showSuggestionAfterError(displaySuggestion = true) {
833
+ this._showSuggestionAfterError = !!displaySuggestion;
834
+ return this;
835
+ }
836
+ addCommand(cmd, opts) {
837
+ if (!cmd._name) {
838
+ throw new Error(`Command passed to .addCommand() must have a name
839
+ - specify the name in Command constructor or using .name()`);
840
+ }
841
+ opts = opts || {};
842
+ if (opts.isDefault)
843
+ this._defaultCommandName = cmd._name;
844
+ if (opts.noHelp || opts.hidden)
845
+ cmd._hidden = true;
846
+ this._registerCommand(cmd);
847
+ cmd.parent = this;
848
+ cmd._checkForBrokenPassThrough();
849
+ return this;
850
+ }
851
+ createArgument(name, description) {
852
+ return new Argument(name, description);
853
+ }
854
+ argument(name, description, parseArg, defaultValue) {
855
+ const argument = this.createArgument(name, description);
856
+ if (typeof parseArg === "function") {
857
+ argument.default(defaultValue).argParser(parseArg);
858
+ } else {
859
+ argument.default(parseArg);
860
+ }
861
+ this.addArgument(argument);
862
+ return this;
863
+ }
864
+ arguments(names) {
865
+ names.trim().split(/ +/).forEach((detail) => {
866
+ this.argument(detail);
867
+ });
868
+ return this;
869
+ }
870
+ addArgument(argument) {
871
+ const previousArgument = this.registeredArguments.slice(-1)[0];
872
+ if (previousArgument?.variadic) {
873
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
874
+ }
875
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
876
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
877
+ }
878
+ this.registeredArguments.push(argument);
879
+ return this;
880
+ }
881
+ helpCommand(enableOrNameAndArgs, description) {
882
+ if (typeof enableOrNameAndArgs === "boolean") {
883
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
884
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
885
+ this._initCommandGroup(this._getHelpCommand());
886
+ }
887
+ return this;
888
+ }
889
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
890
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
891
+ const helpDescription = description ?? "display help for command";
892
+ const helpCommand = this.createCommand(helpName);
893
+ helpCommand.helpOption(false);
894
+ if (helpArgs)
895
+ helpCommand.arguments(helpArgs);
896
+ if (helpDescription)
897
+ helpCommand.description(helpDescription);
898
+ this._addImplicitHelpCommand = true;
899
+ this._helpCommand = helpCommand;
900
+ if (enableOrNameAndArgs || description)
901
+ this._initCommandGroup(helpCommand);
902
+ return this;
903
+ }
904
+ addHelpCommand(helpCommand, deprecatedDescription) {
905
+ if (typeof helpCommand !== "object") {
906
+ this.helpCommand(helpCommand, deprecatedDescription);
907
+ return this;
908
+ }
909
+ this._addImplicitHelpCommand = true;
910
+ this._helpCommand = helpCommand;
911
+ this._initCommandGroup(helpCommand);
912
+ return this;
913
+ }
914
+ _getHelpCommand() {
915
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
916
+ if (hasImplicitHelpCommand) {
917
+ if (this._helpCommand === undefined) {
918
+ this.helpCommand(undefined, undefined);
919
+ }
920
+ return this._helpCommand;
921
+ }
922
+ return null;
923
+ }
924
+ hook(event, listener) {
925
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
926
+ if (!allowedValues.includes(event)) {
927
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
928
+ Expecting one of '${allowedValues.join("', '")}'`);
929
+ }
930
+ if (this._lifeCycleHooks[event]) {
931
+ this._lifeCycleHooks[event].push(listener);
932
+ } else {
933
+ this._lifeCycleHooks[event] = [listener];
934
+ }
935
+ return this;
936
+ }
937
+ exitOverride(fn) {
938
+ if (fn) {
939
+ this._exitCallback = fn;
940
+ } else {
941
+ this._exitCallback = (err) => {
942
+ if (err.code !== "commander.executeSubCommandAsync") {
943
+ throw err;
944
+ }
945
+ };
946
+ }
947
+ return this;
948
+ }
949
+ _exit(exitCode, code, message) {
950
+ if (this._exitCallback) {
951
+ this._exitCallback(new CommanderError(exitCode, code, message));
952
+ }
953
+ process2.exit(exitCode);
954
+ }
955
+ action(fn) {
956
+ const listener = (args) => {
957
+ const expectedArgsCount = this.registeredArguments.length;
958
+ const actionArgs = args.slice(0, expectedArgsCount);
959
+ if (this._storeOptionsAsProperties) {
960
+ actionArgs[expectedArgsCount] = this;
961
+ } else {
962
+ actionArgs[expectedArgsCount] = this.opts();
963
+ }
964
+ actionArgs.push(this);
965
+ return fn.apply(this, actionArgs);
966
+ };
967
+ this._actionHandler = listener;
968
+ return this;
969
+ }
970
+ createOption(flags, description) {
971
+ return new Option(flags, description);
972
+ }
973
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
974
+ try {
975
+ return target.parseArg(value, previous);
976
+ } catch (err) {
977
+ if (err.code === "commander.invalidArgument") {
978
+ const message = `${invalidArgumentMessage} ${err.message}`;
979
+ this.error(message, { exitCode: err.exitCode, code: err.code });
980
+ }
981
+ throw err;
982
+ }
983
+ }
984
+ _registerOption(option) {
985
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
986
+ if (matchingOption) {
987
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
988
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
989
+ - already used by option '${matchingOption.flags}'`);
990
+ }
991
+ this._initOptionGroup(option);
992
+ this.options.push(option);
993
+ }
994
+ _registerCommand(command) {
995
+ const knownBy = (cmd) => {
996
+ return [cmd.name()].concat(cmd.aliases());
997
+ };
998
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
999
+ if (alreadyUsed) {
1000
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1001
+ const newCmd = knownBy(command).join("|");
1002
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1003
+ }
1004
+ this._initCommandGroup(command);
1005
+ this.commands.push(command);
1006
+ }
1007
+ addOption(option) {
1008
+ this._registerOption(option);
1009
+ const oname = option.name();
1010
+ const name = option.attributeName();
1011
+ if (option.defaultValue !== undefined) {
1012
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1013
+ }
1014
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1015
+ if (val == null && option.presetArg !== undefined) {
1016
+ val = option.presetArg;
1017
+ }
1018
+ const oldValue = this.getOptionValue(name);
1019
+ if (val !== null && option.parseArg) {
1020
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1021
+ } else if (val !== null && option.variadic) {
1022
+ val = option._collectValue(val, oldValue);
1023
+ }
1024
+ if (val == null) {
1025
+ if (option.negate) {
1026
+ val = false;
1027
+ } else if (option.isBoolean() || option.optional) {
1028
+ val = true;
1029
+ } else {
1030
+ val = "";
1031
+ }
1032
+ }
1033
+ this.setOptionValueWithSource(name, val, valueSource);
1034
+ };
1035
+ this.on("option:" + oname, (val) => {
1036
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1037
+ handleOptionValue(val, invalidValueMessage, "cli");
1038
+ });
1039
+ if (option.envVar) {
1040
+ this.on("optionEnv:" + oname, (val) => {
1041
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1042
+ handleOptionValue(val, invalidValueMessage, "env");
1043
+ });
1044
+ }
1045
+ return this;
1046
+ }
1047
+ _optionEx(config, flags, description, fn, defaultValue) {
1048
+ if (typeof flags === "object" && flags instanceof Option) {
1049
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1050
+ }
1051
+ const option = this.createOption(flags, description);
1052
+ option.makeOptionMandatory(!!config.mandatory);
1053
+ if (typeof fn === "function") {
1054
+ option.default(defaultValue).argParser(fn);
1055
+ } else if (fn instanceof RegExp) {
1056
+ const regex = fn;
1057
+ fn = (val, def) => {
1058
+ const m = regex.exec(val);
1059
+ return m ? m[0] : def;
1060
+ };
1061
+ option.default(defaultValue).argParser(fn);
1062
+ } else {
1063
+ option.default(fn);
1064
+ }
1065
+ return this.addOption(option);
1066
+ }
1067
+ option(flags, description, parseArg, defaultValue) {
1068
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1069
+ }
1070
+ requiredOption(flags, description, parseArg, defaultValue) {
1071
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1072
+ }
1073
+ combineFlagAndOptionalValue(combine = true) {
1074
+ this._combineFlagAndOptionalValue = !!combine;
1075
+ return this;
1076
+ }
1077
+ allowUnknownOption(allowUnknown = true) {
1078
+ this._allowUnknownOption = !!allowUnknown;
1079
+ return this;
1080
+ }
1081
+ allowExcessArguments(allowExcess = true) {
1082
+ this._allowExcessArguments = !!allowExcess;
1083
+ return this;
1084
+ }
1085
+ enablePositionalOptions(positional = true) {
1086
+ this._enablePositionalOptions = !!positional;
1087
+ return this;
1088
+ }
1089
+ passThroughOptions(passThrough = true) {
1090
+ this._passThroughOptions = !!passThrough;
1091
+ this._checkForBrokenPassThrough();
1092
+ return this;
1093
+ }
1094
+ _checkForBrokenPassThrough() {
1095
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1096
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1097
+ }
1098
+ }
1099
+ storeOptionsAsProperties(storeAsProperties = true) {
1100
+ if (this.options.length) {
1101
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1102
+ }
1103
+ if (Object.keys(this._optionValues).length) {
1104
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1105
+ }
1106
+ this._storeOptionsAsProperties = !!storeAsProperties;
1107
+ return this;
1108
+ }
1109
+ getOptionValue(key) {
1110
+ if (this._storeOptionsAsProperties) {
1111
+ return this[key];
1112
+ }
1113
+ return this._optionValues[key];
1114
+ }
1115
+ setOptionValue(key, value) {
1116
+ return this.setOptionValueWithSource(key, value, undefined);
1117
+ }
1118
+ setOptionValueWithSource(key, value, source) {
1119
+ if (this._storeOptionsAsProperties) {
1120
+ this[key] = value;
1121
+ } else {
1122
+ this._optionValues[key] = value;
1123
+ }
1124
+ this._optionValueSources[key] = source;
1125
+ return this;
1126
+ }
1127
+ getOptionValueSource(key) {
1128
+ return this._optionValueSources[key];
1129
+ }
1130
+ getOptionValueSourceWithGlobals(key) {
1131
+ let source;
1132
+ this._getCommandAndAncestors().forEach((cmd) => {
1133
+ if (cmd.getOptionValueSource(key) !== undefined) {
1134
+ source = cmd.getOptionValueSource(key);
1135
+ }
1136
+ });
1137
+ return source;
1138
+ }
1139
+ _prepareUserArgs(argv, parseOptions) {
1140
+ if (argv !== undefined && !Array.isArray(argv)) {
1141
+ throw new Error("first parameter to parse must be array or undefined");
1142
+ }
1143
+ parseOptions = parseOptions || {};
1144
+ if (argv === undefined && parseOptions.from === undefined) {
1145
+ if (process2.versions?.electron) {
1146
+ parseOptions.from = "electron";
1147
+ }
1148
+ const execArgv = process2.execArgv ?? [];
1149
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1150
+ parseOptions.from = "eval";
1151
+ }
1152
+ }
1153
+ if (argv === undefined) {
1154
+ argv = process2.argv;
1155
+ }
1156
+ this.rawArgs = argv.slice();
1157
+ let userArgs;
1158
+ switch (parseOptions.from) {
1159
+ case undefined:
1160
+ case "node":
1161
+ this._scriptPath = argv[1];
1162
+ userArgs = argv.slice(2);
1163
+ break;
1164
+ case "electron":
1165
+ if (process2.defaultApp) {
1166
+ this._scriptPath = argv[1];
1167
+ userArgs = argv.slice(2);
1168
+ } else {
1169
+ userArgs = argv.slice(1);
1170
+ }
1171
+ break;
1172
+ case "user":
1173
+ userArgs = argv.slice(0);
1174
+ break;
1175
+ case "eval":
1176
+ userArgs = argv.slice(1);
1177
+ break;
1178
+ default:
1179
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1180
+ }
1181
+ if (!this._name && this._scriptPath)
1182
+ this.nameFromFilename(this._scriptPath);
1183
+ this._name = this._name || "program";
1184
+ return userArgs;
1185
+ }
1186
+ parse(argv, parseOptions) {
1187
+ this._prepareForParse();
1188
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1189
+ this._parseCommand([], userArgs);
1190
+ return this;
1191
+ }
1192
+ async parseAsync(argv, parseOptions) {
1193
+ this._prepareForParse();
1194
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1195
+ await this._parseCommand([], userArgs);
1196
+ return this;
1197
+ }
1198
+ _prepareForParse() {
1199
+ if (this._savedState === null) {
1200
+ this.options.filter((option) => option.negate && option.defaultValue === undefined && this.getOptionValue(option.attributeName()) === undefined).forEach((option) => {
1201
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1202
+ if (!this._findOption(positiveLongFlag)) {
1203
+ this.setOptionValueWithSource(option.attributeName(), true, "default");
1204
+ }
1205
+ });
1206
+ this.saveStateBeforeParse();
1207
+ } else {
1208
+ this.restoreStateBeforeParse();
1209
+ }
1210
+ }
1211
+ saveStateBeforeParse() {
1212
+ this._savedState = {
1213
+ _name: this._name,
1214
+ _optionValues: { ...this._optionValues },
1215
+ _optionValueSources: { ...this._optionValueSources }
1216
+ };
1217
+ }
1218
+ restoreStateBeforeParse() {
1219
+ if (this._storeOptionsAsProperties)
1220
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1221
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1222
+ this._name = this._savedState._name;
1223
+ this._scriptPath = null;
1224
+ this.rawArgs = [];
1225
+ this._optionValues = { ...this._savedState._optionValues };
1226
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1227
+ this.args = [];
1228
+ this.processedArgs = [];
1229
+ }
1230
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1231
+ if (fs.existsSync(executableFile))
1232
+ return;
1233
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1234
+ const executableMissing = `'${executableFile}' does not exist
1235
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1236
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1237
+ - ${executableDirMessage}`;
1238
+ throw new Error(executableMissing);
1239
+ }
1240
+ _executeSubCommand(subcommand, args) {
1241
+ args = args.slice();
1242
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1243
+ function findFile(baseDir, baseName) {
1244
+ const localBin = path.resolve(baseDir, baseName);
1245
+ if (fs.existsSync(localBin))
1246
+ return localBin;
1247
+ if (sourceExt.includes(path.extname(baseName)))
1248
+ return;
1249
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1250
+ if (foundExt)
1251
+ return `${localBin}${foundExt}`;
1252
+ return;
1253
+ }
1254
+ this._checkForMissingMandatoryOptions();
1255
+ this._checkForConflictingOptions();
1256
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1257
+ let executableDir = this._executableDir || "";
1258
+ if (this._scriptPath) {
1259
+ let resolvedScriptPath;
1260
+ try {
1261
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1262
+ } catch {
1263
+ resolvedScriptPath = this._scriptPath;
1264
+ }
1265
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1266
+ }
1267
+ if (executableDir) {
1268
+ let localFile = findFile(executableDir, executableFile);
1269
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1270
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1271
+ if (legacyName !== this._name) {
1272
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1273
+ }
1274
+ }
1275
+ executableFile = localFile || executableFile;
1276
+ }
1277
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
1278
+ let proc;
1279
+ if (process2.platform !== "win32") {
1280
+ if (launchWithNode) {
1281
+ args.unshift(executableFile);
1282
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1283
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1284
+ } else {
1285
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1286
+ }
1287
+ } else {
1288
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1289
+ args.unshift(executableFile);
1290
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1291
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1292
+ }
1293
+ if (!proc.killed) {
1294
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1295
+ signals.forEach((signal) => {
1296
+ process2.on(signal, () => {
1297
+ if (proc.killed === false && proc.exitCode === null) {
1298
+ proc.kill(signal);
1299
+ }
1300
+ });
1301
+ });
1302
+ }
1303
+ const exitCallback = this._exitCallback;
1304
+ proc.on("close", (code) => {
1305
+ code = code ?? 1;
1306
+ if (!exitCallback) {
1307
+ process2.exit(code);
1308
+ } else {
1309
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1310
+ }
1311
+ });
1312
+ proc.on("error", (err) => {
1313
+ if (err.code === "ENOENT") {
1314
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1315
+ } else if (err.code === "EACCES") {
1316
+ throw new Error(`'${executableFile}' not executable`);
1317
+ }
1318
+ if (!exitCallback) {
1319
+ process2.exit(1);
1320
+ } else {
1321
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1322
+ wrappedError.nestedError = err;
1323
+ exitCallback(wrappedError);
1324
+ }
1325
+ });
1326
+ this.runningCommand = proc;
1327
+ }
1328
+ _dispatchSubcommand(commandName, operands, unknown) {
1329
+ const subCommand = this._findCommand(commandName);
1330
+ if (!subCommand)
1331
+ this.help({ error: true });
1332
+ subCommand._prepareForParse();
1333
+ let promiseChain;
1334
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1335
+ promiseChain = this._chainOrCall(promiseChain, () => {
1336
+ if (subCommand._executableHandler) {
1337
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1338
+ } else {
1339
+ return subCommand._parseCommand(operands, unknown);
1340
+ }
1341
+ });
1342
+ return promiseChain;
1343
+ }
1344
+ _dispatchHelpCommand(subcommandName) {
1345
+ if (!subcommandName) {
1346
+ this.help();
1347
+ }
1348
+ const subCommand = this._findCommand(subcommandName);
1349
+ if (subCommand && !subCommand._executableHandler) {
1350
+ subCommand.help();
1351
+ }
1352
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1353
+ }
1354
+ _checkNumberOfArguments() {
1355
+ this.registeredArguments.forEach((arg, i) => {
1356
+ if (arg.required && this.args[i] == null) {
1357
+ this.missingArgument(arg.name());
1358
+ }
1359
+ });
1360
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1361
+ return;
1362
+ }
1363
+ if (this.args.length > this.registeredArguments.length) {
1364
+ this._excessArguments(this.args);
1365
+ }
1366
+ }
1367
+ _processArguments() {
1368
+ const myParseArg = (argument, value, previous) => {
1369
+ let parsedValue = value;
1370
+ if (value !== null && argument.parseArg) {
1371
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1372
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1373
+ }
1374
+ return parsedValue;
1375
+ };
1376
+ this._checkNumberOfArguments();
1377
+ const processedArgs = [];
1378
+ this.registeredArguments.forEach((declaredArg, index) => {
1379
+ let value = declaredArg.defaultValue;
1380
+ if (declaredArg.variadic) {
1381
+ if (index < this.args.length) {
1382
+ value = this.args.slice(index);
1383
+ if (declaredArg.parseArg) {
1384
+ value = value.reduce((processed, v) => {
1385
+ return myParseArg(declaredArg, v, processed);
1386
+ }, declaredArg.defaultValue);
1387
+ }
1388
+ } else if (value === undefined) {
1389
+ value = [];
1390
+ }
1391
+ } else if (index < this.args.length) {
1392
+ value = this.args[index];
1393
+ if (declaredArg.parseArg) {
1394
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1395
+ }
1396
+ }
1397
+ processedArgs[index] = value;
1398
+ });
1399
+ this.processedArgs = processedArgs;
1400
+ }
1401
+ _chainOrCall(promise, fn) {
1402
+ if (promise?.then && typeof promise.then === "function") {
1403
+ return promise.then(() => fn());
1404
+ }
1405
+ return fn();
1406
+ }
1407
+ _chainOrCallHooks(promise, event) {
1408
+ let result = promise;
1409
+ const hooks = [];
1410
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1411
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1412
+ hooks.push({ hookedCommand, callback });
1413
+ });
1414
+ });
1415
+ if (event === "postAction") {
1416
+ hooks.reverse();
1417
+ }
1418
+ hooks.forEach((hookDetail) => {
1419
+ result = this._chainOrCall(result, () => {
1420
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1421
+ });
1422
+ });
1423
+ return result;
1424
+ }
1425
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1426
+ let result = promise;
1427
+ if (this._lifeCycleHooks[event] !== undefined) {
1428
+ this._lifeCycleHooks[event].forEach((hook) => {
1429
+ result = this._chainOrCall(result, () => {
1430
+ return hook(this, subCommand);
1431
+ });
1432
+ });
1433
+ }
1434
+ return result;
1435
+ }
1436
+ _parseCommand(operands, unknown) {
1437
+ const parsed = this.parseOptions(unknown);
1438
+ this._parseOptionsEnv();
1439
+ this._parseOptionsImplied();
1440
+ operands = operands.concat(parsed.operands);
1441
+ unknown = parsed.unknown;
1442
+ this.args = operands.concat(unknown);
1443
+ if (operands && this._findCommand(operands[0])) {
1444
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1445
+ }
1446
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1447
+ return this._dispatchHelpCommand(operands[1]);
1448
+ }
1449
+ if (this._defaultCommandName) {
1450
+ this._outputHelpIfRequested(unknown);
1451
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1452
+ }
1453
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1454
+ this.help({ error: true });
1455
+ }
1456
+ this._outputHelpIfRequested(parsed.unknown);
1457
+ this._checkForMissingMandatoryOptions();
1458
+ this._checkForConflictingOptions();
1459
+ const checkForUnknownOptions = () => {
1460
+ if (parsed.unknown.length > 0) {
1461
+ this.unknownOption(parsed.unknown[0]);
1462
+ }
1463
+ };
1464
+ const commandEvent = `command:${this.name()}`;
1465
+ if (this._actionHandler) {
1466
+ checkForUnknownOptions();
1467
+ this._processArguments();
1468
+ let promiseChain;
1469
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1470
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1471
+ if (this.parent) {
1472
+ promiseChain = this._chainOrCall(promiseChain, () => {
1473
+ this.parent.emit(commandEvent, operands, unknown);
1474
+ });
1475
+ }
1476
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1477
+ return promiseChain;
1478
+ }
1479
+ if (this.parent?.listenerCount(commandEvent)) {
1480
+ checkForUnknownOptions();
1481
+ this._processArguments();
1482
+ this.parent.emit(commandEvent, operands, unknown);
1483
+ } else if (operands.length) {
1484
+ if (this._findCommand("*")) {
1485
+ return this._dispatchSubcommand("*", operands, unknown);
1486
+ }
1487
+ if (this.listenerCount("command:*")) {
1488
+ this.emit("command:*", operands, unknown);
1489
+ } else if (this.commands.length) {
1490
+ this.unknownCommand();
1491
+ } else {
1492
+ checkForUnknownOptions();
1493
+ this._processArguments();
1494
+ }
1495
+ } else if (this.commands.length) {
1496
+ checkForUnknownOptions();
1497
+ this.help({ error: true });
1498
+ } else {
1499
+ checkForUnknownOptions();
1500
+ this._processArguments();
1501
+ }
1502
+ }
1503
+ _findCommand(name) {
1504
+ if (!name)
1505
+ return;
1506
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1507
+ }
1508
+ _findOption(arg) {
1509
+ return this.options.find((option) => option.is(arg));
1510
+ }
1511
+ _checkForMissingMandatoryOptions() {
1512
+ this._getCommandAndAncestors().forEach((cmd) => {
1513
+ cmd.options.forEach((anOption) => {
1514
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1515
+ cmd.missingMandatoryOptionValue(anOption);
1516
+ }
1517
+ });
1518
+ });
1519
+ }
1520
+ _checkForConflictingLocalOptions() {
1521
+ const definedNonDefaultOptions = this.options.filter((option) => {
1522
+ const optionKey = option.attributeName();
1523
+ if (this.getOptionValue(optionKey) === undefined) {
1524
+ return false;
1525
+ }
1526
+ return this.getOptionValueSource(optionKey) !== "default";
1527
+ });
1528
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1529
+ optionsWithConflicting.forEach((option) => {
1530
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1531
+ if (conflictingAndDefined) {
1532
+ this._conflictingOption(option, conflictingAndDefined);
1533
+ }
1534
+ });
1535
+ }
1536
+ _checkForConflictingOptions() {
1537
+ this._getCommandAndAncestors().forEach((cmd) => {
1538
+ cmd._checkForConflictingLocalOptions();
1539
+ });
1540
+ }
1541
+ parseOptions(args) {
1542
+ const operands = [];
1543
+ const unknown = [];
1544
+ let dest = operands;
1545
+ function maybeOption(arg) {
1546
+ return arg.length > 1 && arg[0] === "-";
1547
+ }
1548
+ const negativeNumberArg = (arg) => {
1549
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1550
+ return false;
1551
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1552
+ };
1553
+ let activeVariadicOption = null;
1554
+ let activeGroup = null;
1555
+ let i = 0;
1556
+ while (i < args.length || activeGroup) {
1557
+ const arg = activeGroup ?? args[i++];
1558
+ activeGroup = null;
1559
+ if (arg === "--") {
1560
+ if (dest === unknown)
1561
+ dest.push(arg);
1562
+ dest.push(...args.slice(i));
1563
+ break;
1564
+ }
1565
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1566
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1567
+ continue;
1568
+ }
1569
+ activeVariadicOption = null;
1570
+ if (maybeOption(arg)) {
1571
+ const option = this._findOption(arg);
1572
+ if (option) {
1573
+ if (option.required) {
1574
+ const value = args[i++];
1575
+ if (value === undefined)
1576
+ this.optionMissingArgument(option);
1577
+ this.emit(`option:${option.name()}`, value);
1578
+ } else if (option.optional) {
1579
+ let value = null;
1580
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1581
+ value = args[i++];
1582
+ }
1583
+ this.emit(`option:${option.name()}`, value);
1584
+ } else {
1585
+ this.emit(`option:${option.name()}`);
1586
+ }
1587
+ activeVariadicOption = option.variadic ? option : null;
1588
+ continue;
1589
+ }
1590
+ }
1591
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1592
+ const option = this._findOption(`-${arg[1]}`);
1593
+ if (option) {
1594
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1595
+ this.emit(`option:${option.name()}`, arg.slice(2));
1596
+ } else {
1597
+ this.emit(`option:${option.name()}`);
1598
+ activeGroup = `-${arg.slice(2)}`;
1599
+ }
1600
+ continue;
1601
+ }
1602
+ }
1603
+ if (/^--[^=]+=/.test(arg)) {
1604
+ const index = arg.indexOf("=");
1605
+ const option = this._findOption(arg.slice(0, index));
1606
+ if (option && (option.required || option.optional)) {
1607
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1608
+ continue;
1609
+ }
1610
+ }
1611
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1612
+ dest = unknown;
1613
+ }
1614
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1615
+ if (this._findCommand(arg)) {
1616
+ operands.push(arg);
1617
+ unknown.push(...args.slice(i));
1618
+ break;
1619
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1620
+ operands.push(arg, ...args.slice(i));
1621
+ break;
1622
+ } else if (this._defaultCommandName) {
1623
+ unknown.push(arg, ...args.slice(i));
1624
+ break;
1625
+ }
1626
+ }
1627
+ if (this._passThroughOptions) {
1628
+ dest.push(arg, ...args.slice(i));
1629
+ break;
1630
+ }
1631
+ dest.push(arg);
1632
+ }
1633
+ return { operands, unknown };
1634
+ }
1635
+ opts() {
1636
+ if (this._storeOptionsAsProperties) {
1637
+ const result = {};
1638
+ const len = this.options.length;
1639
+ for (let i = 0;i < len; i++) {
1640
+ const key = this.options[i].attributeName();
1641
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1642
+ }
1643
+ return result;
1644
+ }
1645
+ return this._optionValues;
1646
+ }
1647
+ optsWithGlobals() {
1648
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1649
+ }
1650
+ error(message, errorOptions) {
1651
+ this._outputConfiguration.outputError(`${message}
1652
+ `, this._outputConfiguration.writeErr);
1653
+ if (typeof this._showHelpAfterError === "string") {
1654
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1655
+ `);
1656
+ } else if (this._showHelpAfterError) {
1657
+ this._outputConfiguration.writeErr(`
1658
+ `);
1659
+ this.outputHelp({ error: true });
1660
+ }
1661
+ const config = errorOptions || {};
1662
+ const exitCode = config.exitCode || 1;
1663
+ const code = config.code || "commander.error";
1664
+ this._exit(exitCode, code, message);
1665
+ }
1666
+ _parseOptionsEnv() {
1667
+ this.options.forEach((option) => {
1668
+ if (option.envVar && option.envVar in process2.env) {
1669
+ const optionKey = option.attributeName();
1670
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1671
+ if (option.required || option.optional) {
1672
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1673
+ } else {
1674
+ this.emit(`optionEnv:${option.name()}`);
1675
+ }
1676
+ }
1677
+ }
1678
+ });
1679
+ }
1680
+ _parseOptionsImplied() {
1681
+ const dualHelper = new DualOptions(this.options);
1682
+ const hasCustomOptionValue = (optionKey) => {
1683
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1684
+ };
1685
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1686
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1687
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1688
+ });
1689
+ });
1690
+ }
1691
+ missingArgument(name) {
1692
+ const message = `error: missing required argument '${name}'`;
1693
+ this.error(message, { code: "commander.missingArgument" });
1694
+ }
1695
+ optionMissingArgument(option) {
1696
+ const message = `error: option '${option.flags}' argument missing`;
1697
+ this.error(message, { code: "commander.optionMissingArgument" });
1698
+ }
1699
+ missingMandatoryOptionValue(option) {
1700
+ const message = `error: required option '${option.flags}' not specified`;
1701
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1702
+ }
1703
+ _conflictingOption(option, conflictingOption) {
1704
+ const findBestOptionFromValue = (option) => {
1705
+ const optionKey = option.attributeName();
1706
+ const optionValue = this.getOptionValue(optionKey);
1707
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1708
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1709
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1710
+ return negativeOption;
1711
+ }
1712
+ return positiveOption || option;
1713
+ };
1714
+ const getErrorMessage = (option) => {
1715
+ const bestOption = findBestOptionFromValue(option);
1716
+ const optionKey = bestOption.attributeName();
1717
+ const source = this.getOptionValueSource(optionKey);
1718
+ if (source === "env") {
1719
+ return `environment variable '${bestOption.envVar}'`;
1720
+ }
1721
+ return `option '${bestOption.flags}'`;
1722
+ };
1723
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1724
+ this.error(message, { code: "commander.conflictingOption" });
1725
+ }
1726
+ unknownOption(flag) {
1727
+ if (this._allowUnknownOption)
1728
+ return;
1729
+ let suggestion = "";
1730
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1731
+ let candidateFlags = [];
1732
+ let command = this;
1733
+ do {
1734
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1735
+ candidateFlags = candidateFlags.concat(moreFlags);
1736
+ command = command.parent;
1737
+ } while (command && !command._enablePositionalOptions);
1738
+ suggestion = suggestSimilar(flag, candidateFlags);
1739
+ }
1740
+ const message = `error: unknown option '${flag}'${suggestion}`;
1741
+ this.error(message, { code: "commander.unknownOption" });
1742
+ }
1743
+ _excessArguments(receivedArgs) {
1744
+ if (this._allowExcessArguments)
1745
+ return;
1746
+ const expected = this.registeredArguments.length;
1747
+ const s = expected === 1 ? "" : "s";
1748
+ const received = receivedArgs.length;
1749
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1750
+ const details = receivedArgs.join(", ");
1751
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
1752
+ this.error(message, { code: "commander.excessArguments" });
1753
+ }
1754
+ unknownCommand() {
1755
+ const unknownName = this.args[0];
1756
+ let suggestion = "";
1757
+ if (this._showSuggestionAfterError) {
1758
+ const candidateNames = [];
1759
+ this.createHelp().visibleCommands(this).forEach((command) => {
1760
+ candidateNames.push(command.name());
1761
+ if (command.alias())
1762
+ candidateNames.push(command.alias());
1763
+ });
1764
+ suggestion = suggestSimilar(unknownName, candidateNames);
1765
+ }
1766
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1767
+ this.error(message, { code: "commander.unknownCommand" });
1768
+ }
1769
+ version(str, flags, description) {
1770
+ if (str === undefined)
1771
+ return this._version;
1772
+ this._version = str;
1773
+ flags = flags || "-V, --version";
1774
+ description = description || "output the version number";
1775
+ const versionOption = this.createOption(flags, description);
1776
+ this._versionOptionName = versionOption.attributeName();
1777
+ this._registerOption(versionOption);
1778
+ this.on("option:" + versionOption.name(), () => {
1779
+ this._outputConfiguration.writeOut(`${str}
1780
+ `);
1781
+ this._exit(0, "commander.version", str);
1782
+ });
1783
+ return this;
1784
+ }
1785
+ description(str, argsDescription) {
1786
+ if (str === undefined && argsDescription === undefined)
1787
+ return this._description;
1788
+ this._description = str;
1789
+ if (argsDescription) {
1790
+ this._argsDescription = argsDescription;
1791
+ }
1792
+ return this;
1793
+ }
1794
+ summary(str) {
1795
+ if (str === undefined)
1796
+ return this._summary;
1797
+ this._summary = str;
1798
+ return this;
1799
+ }
1800
+ alias(alias) {
1801
+ if (alias === undefined)
1802
+ return this._aliases[0];
1803
+ let command = this;
1804
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1805
+ command = this.commands[this.commands.length - 1];
1806
+ }
1807
+ if (alias === command._name)
1808
+ throw new Error("Command alias can't be the same as its name");
1809
+ const matchingCommand = this.parent?._findCommand(alias);
1810
+ if (matchingCommand) {
1811
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1812
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1813
+ }
1814
+ command._aliases.push(alias);
1815
+ return this;
1816
+ }
1817
+ aliases(aliases) {
1818
+ if (aliases === undefined)
1819
+ return this._aliases;
1820
+ aliases.forEach((alias) => this.alias(alias));
1821
+ return this;
1822
+ }
1823
+ usage(str) {
1824
+ if (str === undefined) {
1825
+ if (this._usage)
1826
+ return this._usage;
1827
+ const args = this.registeredArguments.map((arg) => {
1828
+ return humanReadableArgName(arg);
1829
+ });
1830
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1831
+ }
1832
+ this._usage = str;
1833
+ return this;
1834
+ }
1835
+ name(str) {
1836
+ if (str === undefined)
1837
+ return this._name;
1838
+ this._name = str;
1839
+ return this;
1840
+ }
1841
+ helpGroup(heading) {
1842
+ if (heading === undefined)
1843
+ return this._helpGroupHeading ?? "";
1844
+ this._helpGroupHeading = heading;
1845
+ return this;
1846
+ }
1847
+ commandsGroup(heading) {
1848
+ if (heading === undefined)
1849
+ return this._defaultCommandGroup ?? "";
1850
+ this._defaultCommandGroup = heading;
1851
+ return this;
1852
+ }
1853
+ optionsGroup(heading) {
1854
+ if (heading === undefined)
1855
+ return this._defaultOptionGroup ?? "";
1856
+ this._defaultOptionGroup = heading;
1857
+ return this;
1858
+ }
1859
+ _initOptionGroup(option) {
1860
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1861
+ option.helpGroup(this._defaultOptionGroup);
1862
+ }
1863
+ _initCommandGroup(cmd) {
1864
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1865
+ cmd.helpGroup(this._defaultCommandGroup);
1866
+ }
1867
+ nameFromFilename(filename) {
1868
+ this._name = path.basename(filename, path.extname(filename));
1869
+ return this;
1870
+ }
1871
+ executableDir(path2) {
1872
+ if (path2 === undefined)
1873
+ return this._executableDir;
1874
+ this._executableDir = path2;
1875
+ return this;
1876
+ }
1877
+ helpInformation(contextOptions) {
1878
+ const helper = this.createHelp();
1879
+ const context = this._getOutputContext(contextOptions);
1880
+ helper.prepareContext({
1881
+ error: context.error,
1882
+ helpWidth: context.helpWidth,
1883
+ outputHasColors: context.hasColors
1884
+ });
1885
+ const text = helper.formatHelp(this, helper);
1886
+ if (context.hasColors)
1887
+ return text;
1888
+ return this._outputConfiguration.stripColor(text);
1889
+ }
1890
+ _getOutputContext(contextOptions) {
1891
+ contextOptions = contextOptions || {};
1892
+ const error = !!contextOptions.error;
1893
+ let baseWrite;
1894
+ let hasColors;
1895
+ let helpWidth;
1896
+ if (error) {
1897
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1898
+ hasColors = this._outputConfiguration.getErrHasColors();
1899
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1900
+ } else {
1901
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1902
+ hasColors = this._outputConfiguration.getOutHasColors();
1903
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1904
+ }
1905
+ const write = (str) => {
1906
+ if (!hasColors)
1907
+ str = this._outputConfiguration.stripColor(str);
1908
+ return baseWrite(str);
1909
+ };
1910
+ return { error, write, hasColors, helpWidth };
1911
+ }
1912
+ outputHelp(contextOptions) {
1913
+ let deprecatedCallback;
1914
+ if (typeof contextOptions === "function") {
1915
+ deprecatedCallback = contextOptions;
1916
+ contextOptions = undefined;
1917
+ }
1918
+ const outputContext = this._getOutputContext(contextOptions);
1919
+ const eventContext = {
1920
+ error: outputContext.error,
1921
+ write: outputContext.write,
1922
+ command: this
1923
+ };
1924
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1925
+ this.emit("beforeHelp", eventContext);
1926
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1927
+ if (deprecatedCallback) {
1928
+ helpInformation = deprecatedCallback(helpInformation);
1929
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1930
+ throw new Error("outputHelp callback must return a string or a Buffer");
1931
+ }
1932
+ }
1933
+ outputContext.write(helpInformation);
1934
+ if (this._getHelpOption()?.long) {
1935
+ this.emit(this._getHelpOption().long);
1936
+ }
1937
+ this.emit("afterHelp", eventContext);
1938
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1939
+ }
1940
+ helpOption(flags, description) {
1941
+ if (typeof flags === "boolean") {
1942
+ if (flags) {
1943
+ if (this._helpOption === null)
1944
+ this._helpOption = undefined;
1945
+ if (this._defaultOptionGroup) {
1946
+ this._initOptionGroup(this._getHelpOption());
1947
+ }
1948
+ } else {
1949
+ this._helpOption = null;
1950
+ }
1951
+ return this;
1952
+ }
1953
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
1954
+ if (flags || description)
1955
+ this._initOptionGroup(this._helpOption);
1956
+ return this;
1957
+ }
1958
+ _getHelpOption() {
1959
+ if (this._helpOption === undefined) {
1960
+ this.helpOption(undefined, undefined);
1961
+ }
1962
+ return this._helpOption;
1963
+ }
1964
+ addHelpOption(option) {
1965
+ this._helpOption = option;
1966
+ this._initOptionGroup(option);
1967
+ return this;
1968
+ }
1969
+ help(contextOptions) {
1970
+ this.outputHelp(contextOptions);
1971
+ let exitCode = Number(process2.exitCode ?? 0);
1972
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1973
+ exitCode = 1;
1974
+ }
1975
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1976
+ }
1977
+ addHelpText(position, text) {
1978
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1979
+ if (!allowedValues.includes(position)) {
1980
+ throw new Error(`Unexpected value for position to addHelpText.
1981
+ Expecting one of '${allowedValues.join("', '")}'`);
1982
+ }
1983
+ const helpEvent = `${position}Help`;
1984
+ this.on(helpEvent, (context) => {
1985
+ let helpStr;
1986
+ if (typeof text === "function") {
1987
+ helpStr = text({ error: context.error, command: context.command });
1988
+ } else {
1989
+ helpStr = text;
1990
+ }
1991
+ if (helpStr) {
1992
+ context.write(`${helpStr}
1993
+ `);
1994
+ }
1995
+ });
1996
+ return this;
1997
+ }
1998
+ _outputHelpIfRequested(args) {
1999
+ const helpOption = this._getHelpOption();
2000
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2001
+ if (helpRequested) {
2002
+ this.outputHelp();
2003
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2004
+ }
2005
+ }
2006
+ }
2007
+ function incrementNodeInspectorPort(args) {
2008
+ return args.map((arg) => {
2009
+ if (!arg.startsWith("--inspect")) {
2010
+ return arg;
2011
+ }
2012
+ let debugOption;
2013
+ let debugHost = "127.0.0.1";
2014
+ let debugPort = "9229";
2015
+ let match;
2016
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2017
+ debugOption = match[1];
2018
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2019
+ debugOption = match[1];
2020
+ if (/^\d+$/.test(match[3])) {
2021
+ debugPort = match[3];
2022
+ } else {
2023
+ debugHost = match[3];
2024
+ }
2025
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2026
+ debugOption = match[1];
2027
+ debugHost = match[3];
2028
+ debugPort = match[4];
2029
+ }
2030
+ if (debugOption && debugPort !== "0") {
2031
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2032
+ }
2033
+ return arg;
2034
+ });
2035
+ }
2036
+ function useColor() {
2037
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2038
+ return false;
2039
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2040
+ return true;
2041
+ return;
2042
+ }
2043
+
2044
+ // node_modules/commander/index.js
2045
+ var program = new Command;
2046
+
2047
+ // src/commands/auth.ts
2048
+ import { hostname } from "node:os";
2049
+
2050
+ // src/config.ts
2051
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
2052
+ import { join as join3 } from "node:path";
2053
+
2054
+ // node_modules/smol-toml/dist/error.js
2055
+ /*!
2056
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2057
+ * SPDX-License-Identifier: BSD-3-Clause
2058
+ *
2059
+ * Redistribution and use in source and binary forms, with or without
2060
+ * modification, are permitted provided that the following conditions are met:
2061
+ *
2062
+ * 1. Redistributions of source code must retain the above copyright notice, this
2063
+ * list of conditions and the following disclaimer.
2064
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2065
+ * this list of conditions and the following disclaimer in the
2066
+ * documentation and/or other materials provided with the distribution.
2067
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2068
+ * may be used to endorse or promote products derived from this software without
2069
+ * specific prior written permission.
2070
+ *
2071
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2072
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2073
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2074
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2075
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2076
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2077
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2078
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2079
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2080
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2081
+ */
2082
+ function getLineColFromPtr(string, ptr) {
2083
+ let lines = string.slice(0, ptr).split(/\r?\n/);
2084
+ return [lines.length, lines.pop().length + 1];
2085
+ }
2086
+ function makeCodeBlock(string, line, column) {
2087
+ let lines = string.split(/\r?\n/);
2088
+ let codeblock = "";
2089
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
2090
+ for (let i = line - 1;i <= line + 1; i++) {
2091
+ let l = lines[i - 1];
2092
+ if (!l)
2093
+ continue;
2094
+ codeblock += i.toString().padEnd(numberLen, " ");
2095
+ codeblock += ": ";
2096
+ codeblock += l;
2097
+ codeblock += `
2098
+ `;
2099
+ if (i === line) {
2100
+ codeblock += " ".repeat(numberLen + column + 2);
2101
+ codeblock += `^
2102
+ `;
2103
+ }
2104
+ }
2105
+ return codeblock;
2106
+ }
2107
+
2108
+ class TomlError extends Error {
2109
+ line;
2110
+ column;
2111
+ codeblock;
2112
+ constructor(message, options) {
2113
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
2114
+ const codeblock = makeCodeBlock(options.toml, line, column);
2115
+ super(`Invalid TOML document: ${message}
2116
+
2117
+ ${codeblock}`, options);
2118
+ this.line = line;
2119
+ this.column = column;
2120
+ this.codeblock = codeblock;
2121
+ }
2122
+ static x(message, ctx, ptr) {
2123
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
2124
+ }
2125
+ }
2126
+
2127
+ // node_modules/smol-toml/dist/primitive.js
2128
+ /*!
2129
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2130
+ * SPDX-License-Identifier: BSD-3-Clause
2131
+ *
2132
+ * Redistribution and use in source and binary forms, with or without
2133
+ * modification, are permitted provided that the following conditions are met:
2134
+ *
2135
+ * 1. Redistributions of source code must retain the above copyright notice, this
2136
+ * list of conditions and the following disclaimer.
2137
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2138
+ * this list of conditions and the following disclaimer in the
2139
+ * documentation and/or other materials provided with the distribution.
2140
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2141
+ * may be used to endorse or promote products derived from this software without
2142
+ * specific prior written permission.
2143
+ *
2144
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2145
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2146
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2147
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2148
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2149
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2150
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2151
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2152
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2153
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2154
+ */
2155
+ function parseString(ctx) {
2156
+ let startPtr = ctx.p;
2157
+ let c = ctx.s.charCodeAt(ctx.p++);
2158
+ let first = c;
2159
+ let isLiteral = c === 39;
2160
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
2161
+ if (isMultiline) {
2162
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
2163
+ ctx.p++;
2164
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
2165
+ ctx.p += 2;
2166
+ }
2167
+ let parsed = "";
2168
+ let sliceStart = ctx.p;
2169
+ let state = 0;
2170
+ for (;ctx.p < ctx.s.length; ctx.p++) {
2171
+ c = ctx.s.charCodeAt(ctx.p);
2172
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
2173
+ state = state && 3;
2174
+ } else if (c < 32 && c !== 9 || c === 127) {
2175
+ TomlError.x("control characters are not allowed in strings", ctx);
2176
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
2177
+ if (isMultiline) {
2178
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2179
+ ctx.p++;
2180
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
2181
+ ctx.p++;
2182
+ }
2183
+ if (!state) {
2184
+ let s = ctx.s.slice(sliceStart, ctx.p);
2185
+ parsed = parsed ? parsed + s : s;
2186
+ }
2187
+ ctx.p += isMultiline ? 3 : 1;
2188
+ return parsed;
2189
+ } else if (!state) {
2190
+ if (!isLiteral && c === 92) {
2191
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
2192
+ state = 1;
2193
+ }
2194
+ } else if (state === 1) {
2195
+ if (c === 120 || c === 117 || c === 85) {
2196
+ let errPtr = ctx.p++ - 1;
2197
+ let value = 0;
2198
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
2199
+ for (let j = 0;j < len; j++, ctx.p++) {
2200
+ let hex = ctx.s.charCodeAt(ctx.p);
2201
+ let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
2202
+ if (digit < 0)
2203
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
2204
+ value = value << 4 | digit;
2205
+ }
2206
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
2207
+ TomlError.x("invalid unicode escape", ctx, errPtr);
2208
+ }
2209
+ parsed += String.fromCodePoint(value);
2210
+ sliceStart = ctx.p--;
2211
+ state = 0;
2212
+ } else if (isMultiline && (c === 32 || c === 9)) {
2213
+ state = 2;
2214
+ } else {
2215
+ if (c === 98)
2216
+ parsed += "\b";
2217
+ else if (c === 116)
2218
+ parsed += "\t";
2219
+ else if (c === 110)
2220
+ parsed += `
2221
+ `;
2222
+ else if (c === 102)
2223
+ parsed += "\f";
2224
+ else if (c === 114)
2225
+ parsed += "\r";
2226
+ else if (c === 101)
2227
+ parsed += "\x1B";
2228
+ else if (c === 34)
2229
+ parsed += '"';
2230
+ else if (c === 92)
2231
+ parsed += "\\";
2232
+ else
2233
+ TomlError.x("unrecognised escape sequence", ctx);
2234
+ sliceStart = ctx.p + 1;
2235
+ state = 0;
2236
+ }
2237
+ } else if (c !== 32 && c !== 9) {
2238
+ if (state === 2)
2239
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
2240
+ state = !isLiteral && c === 92 ? 1 : 0;
2241
+ sliceStart = ctx.p;
2242
+ }
2243
+ }
2244
+ TomlError.x("unfinished string", ctx, startPtr);
2245
+ }
2246
+
2247
+ // node_modules/smol-toml/dist/date.js
2248
+ /*!
2249
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2250
+ * SPDX-License-Identifier: BSD-3-Clause
2251
+ *
2252
+ * Redistribution and use in source and binary forms, with or without
2253
+ * modification, are permitted provided that the following conditions are met:
2254
+ *
2255
+ * 1. Redistributions of source code must retain the above copyright notice, this
2256
+ * list of conditions and the following disclaimer.
2257
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2258
+ * this list of conditions and the following disclaimer in the
2259
+ * documentation and/or other materials provided with the distribution.
2260
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2261
+ * may be used to endorse or promote products derived from this software without
2262
+ * specific prior written permission.
2263
+ *
2264
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2265
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2266
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2267
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2268
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2269
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2270
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2271
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2272
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2273
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2274
+ */
2275
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
2276
+
2277
+ class TomlDate extends Date {
2278
+ #hasDate = false;
2279
+ #hasTime = false;
2280
+ #offset = null;
2281
+ constructor(date, fasttype, unsafeDelim) {
2282
+ let hasDate = true;
2283
+ let hasTime = true;
2284
+ let offset = "Z";
2285
+ let c;
2286
+ if (typeof date === "string") {
2287
+ if (fasttype)
2288
+ prep: {
2289
+ if (fasttype < 3) {
2290
+ if (+date.slice(11, 13) > 23) {
2291
+ date = "";
2292
+ break prep;
2293
+ }
2294
+ if (fasttype === 2) {
2295
+ offset = null;
2296
+ date += "Z";
2297
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
2298
+ offset = date.slice(date.length - 6);
2299
+ }
2300
+ if (unsafeDelim)
2301
+ date = date.slice(0, 10) + "T" + date.slice(11);
2302
+ } else if (fasttype === 4) {
2303
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
2304
+ }
2305
+ hasDate = fasttype !== 4;
2306
+ hasTime = fasttype !== 3;
2307
+ }
2308
+ else {
2309
+ let match = date.match(DATE_TIME_RE);
2310
+ if (match) {
2311
+ if (!match[1]) {
2312
+ hasDate = false;
2313
+ date = `0000-01-01T${date}`;
2314
+ }
2315
+ hasTime = !!match[2];
2316
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
2317
+ if (match[2] && +match[2] > 23) {
2318
+ date = "";
2319
+ } else {
2320
+ offset = match[3] || null;
2321
+ if (!offset && hasTime)
2322
+ date += "Z";
2323
+ }
2324
+ } else {
2325
+ date = "";
2326
+ }
2327
+ }
2328
+ }
2329
+ super(date);
2330
+ if (!isNaN(this.getTime())) {
2331
+ this.#hasDate = hasDate;
2332
+ this.#hasTime = hasTime;
2333
+ this.#offset = offset;
2334
+ }
2335
+ }
2336
+ isDateTime() {
2337
+ return this.#hasDate && this.#hasTime;
2338
+ }
2339
+ isLocal() {
2340
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
2341
+ }
2342
+ isDate() {
2343
+ return this.#hasDate && !this.#hasTime;
2344
+ }
2345
+ isTime() {
2346
+ return this.#hasTime && !this.#hasDate;
2347
+ }
2348
+ isValid() {
2349
+ return this.#hasDate || this.#hasTime;
2350
+ }
2351
+ toISOString() {
2352
+ let iso = super.toISOString();
2353
+ if (this.isDate())
2354
+ return iso.slice(0, 10);
2355
+ if (this.isTime())
2356
+ return iso.slice(11, 23);
2357
+ if (this.#offset === null)
2358
+ return iso.slice(0, -1);
2359
+ if (this.#offset === "Z" || this.#offset === "z")
2360
+ return iso;
2361
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
2362
+ offset = this.#offset[0] === "-" ? offset : -offset;
2363
+ let offsetDate = new Date(this.getTime() - offset * 60000);
2364
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
2365
+ }
2366
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
2367
+ let date = new TomlDate(jsDate);
2368
+ date.#offset = offset;
2369
+ return date;
2370
+ }
2371
+ static wrapAsLocalDateTime(jsDate) {
2372
+ let date = new TomlDate(jsDate);
2373
+ date.#offset = null;
2374
+ return date;
2375
+ }
2376
+ static wrapAsLocalDate(jsDate) {
2377
+ let date = new TomlDate(jsDate);
2378
+ date.#hasTime = false;
2379
+ date.#offset = null;
2380
+ return date;
2381
+ }
2382
+ static wrapAsLocalTime(jsDate) {
2383
+ let date = new TomlDate(jsDate);
2384
+ date.#hasDate = false;
2385
+ date.#offset = null;
2386
+ return date;
2387
+ }
2388
+ }
2389
+
2390
+ // node_modules/smol-toml/dist/extract.js
2391
+ /*!
2392
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2393
+ * SPDX-License-Identifier: BSD-3-Clause
2394
+ *
2395
+ * Redistribution and use in source and binary forms, with or without
2396
+ * modification, are permitted provided that the following conditions are met:
2397
+ *
2398
+ * 1. Redistributions of source code must retain the above copyright notice, this
2399
+ * list of conditions and the following disclaimer.
2400
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2401
+ * this list of conditions and the following disclaimer in the
2402
+ * documentation and/or other materials provided with the distribution.
2403
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2404
+ * may be used to endorse or promote products derived from this software without
2405
+ * specific prior written permission.
2406
+ *
2407
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2408
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2409
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2410
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2411
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2412
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2413
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2414
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2415
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2416
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2417
+ */
2418
+ function isDigit(char, base = 10) {
2419
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
2420
+ }
2421
+ function isEndOfValue(char, delim) {
2422
+ return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
2423
+ }
2424
+ function extractValue(ctx, end) {
2425
+ let errPtr = ctx.p;
2426
+ let c = ctx.s.charCodeAt(ctx.p);
2427
+ if (c === 91 || c === 123) {
2428
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
2429
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
2430
+ ctx.d++;
2431
+ return value;
2432
+ }
2433
+ if (c === 34 || c === 39) {
2434
+ return parseString(ctx);
2435
+ }
2436
+ if (c === 116) {
2437
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
2438
+ TomlError.x("invalid value", ctx, errPtr);
2439
+ return ctx.p++, true;
2440
+ }
2441
+ if (c === 102) {
2442
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
2443
+ TomlError.x("invalid value", ctx, errPtr);
2444
+ return ctx.p++, false;
2445
+ }
2446
+ if (c === 43 || c === 45) {
2447
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
2448
+ }
2449
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
2450
+ return parseDate(ctx, c, end);
2451
+ }
2452
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
2453
+ return parseTime(ctx, c, end);
2454
+ }
2455
+ return parseNumber(ctx, ctx.p, c, 0, end);
2456
+ }
2457
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
2458
+ let c = startChr;
2459
+ let state = 0;
2460
+ let hasUnderscores = false;
2461
+ if (c === 105) {
2462
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
2463
+ TomlError.x("invalid value", ctx, startPtr);
2464
+ return ctx.p++, (sign || 1) / 0;
2465
+ }
2466
+ if (c === 110) {
2467
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
2468
+ TomlError.x("invalid value", ctx, startPtr);
2469
+ return ctx.p++, NaN;
2470
+ }
2471
+ if (c === 48) {
2472
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
2473
+ return ctx.bi === true ? 0n : 0;
2474
+ if (!sign) {
2475
+ if (c === 120)
2476
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
2477
+ else if (c === 98)
2478
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
2479
+ else if (c === 111)
2480
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
2481
+ }
2482
+ if (c === 46)
2483
+ state = 2;
2484
+ else if (c === 101 || c === 69)
2485
+ state = 4;
2486
+ else
2487
+ TomlError.x("illegal leading zero", ctx, startPtr);
2488
+ } else if (!isDigit(c))
2489
+ TomlError.x("invalid value", ctx, startPtr);
2490
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2491
+ if (!state)
2492
+ state = 1;
2493
+ if (c === 95) {
2494
+ if (!(state & 1))
2495
+ TomlError.x("illegal underscore", ctx);
2496
+ state += 11;
2497
+ hasUnderscores = true;
2498
+ } else if (state === 1 && c === 46)
2499
+ state = 2;
2500
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
2501
+ state = 4;
2502
+ else if (state === 4 && (c === 43 || c === 45)) {
2503
+ state = 6;
2504
+ } else if (!isDigit(c))
2505
+ TomlError.x(`illegal character in numeric literal`, ctx);
2506
+ else if (state > 9)
2507
+ state -= 11;
2508
+ else if (!(state & 1))
2509
+ state++;
2510
+ }
2511
+ if (!state) {
2512
+ let val = (startChr - 48) * (sign || 1);
2513
+ return ctx.bi === true ? BigInt(val) : val;
2514
+ }
2515
+ if (!(state & 1))
2516
+ TomlError.x("unfinished numeric value", ctx, startPtr);
2517
+ let str = ctx.s.slice(startPtr, ctx.p);
2518
+ if (hasUnderscores)
2519
+ str = str.replaceAll("_", "");
2520
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
2521
+ }
2522
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
2523
+ let c, underscore = 1;
2524
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
2525
+ if (c === 95) {
2526
+ if (underscore & 1)
2527
+ TomlError.x("illegal underscore", ctx);
2528
+ underscore = 3;
2529
+ } else if (!isDigit(c, base))
2530
+ TomlError.x(`illegal character in numeric literal`, ctx);
2531
+ else if (underscore & 1)
2532
+ underscore--;
2533
+ }
2534
+ if (underscore & 1)
2535
+ TomlError.x("unfinished numeric value", ctx);
2536
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
2537
+ if (underscore)
2538
+ str = str.replaceAll("_", "");
2539
+ return parseInteger(ctx, str, base, startPtr);
2540
+ }
2541
+ function parseInteger(ctx, str, base, startPtr) {
2542
+ if (ctx.bi !== true)
2543
+ int: {
2544
+ let val = parseInt(str, base);
2545
+ if (!Number.isSafeInteger(val)) {
2546
+ if (ctx.bi)
2547
+ break int;
2548
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
2549
+ }
2550
+ return val;
2551
+ }
2552
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
2553
+ }
2554
+ function parseDate(ctx, c, endChr) {
2555
+ let startPtr = ctx.p++, unsafeSeparator;
2556
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
2557
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
2558
+ }
2559
+ ctx.p += 5;
2560
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
2561
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
2562
+ if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
2563
+ let t = ctx.s.slice(startPtr, ctx.p);
2564
+ return readDate(ctx, t, 3, false, startPtr);
2565
+ }
2566
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
2567
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
2568
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
2569
+ ctx.p += 3;
2570
+ if (ctx.s.charCodeAt(ctx.p) === 46)
2571
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
2572
+ ;
2573
+ if (c = ctx.s.charCodeAt(ctx.p)) {
2574
+ if (c === 90 || c === 122) {
2575
+ let t = ctx.s.slice(startPtr, ++ctx.p);
2576
+ return readDate(ctx, t, 1, unsafeSeparator, startPtr, "[+00:00]");
2577
+ }
2578
+ if (c === 43 || c === 45) {
2579
+ let t = ctx.s.slice(startPtr, ctx.p += 6);
2580
+ return readDate(ctx, t, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
2581
+ }
2582
+ }
2583
+ let t = ctx.s.slice(startPtr, ctx.p);
2584
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
2585
+ }
2586
+ function parseTime(ctx, c, endChr) {
2587
+ let start = ctx.p;
2588
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
2589
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
2590
+ }
2591
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
2592
+ ctx.p += 3;
2593
+ if (ctx.s.charCodeAt(ctx.p) === 46)
2594
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
2595
+ ;
2596
+ let t = ctx.s.slice(start, ctx.p);
2597
+ return readDate(ctx, t, 4, false, start);
2598
+ }
2599
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
2600
+ if (ctx.ld) {
2601
+ let date = new TomlDate(str, type, unsafeDelim);
2602
+ if (!date.isValid())
2603
+ TomlError.x("invalid date", ctx, errPtr);
2604
+ return date;
2605
+ }
2606
+ try {
2607
+ if (temporalSuffix)
2608
+ str += temporalSuffix;
2609
+ switch (type) {
2610
+ case 1:
2611
+ return Temporal.ZonedDateTime.from(str);
2612
+ case 2:
2613
+ return Temporal.PlainDateTime.from(str);
2614
+ case 3:
2615
+ return Temporal.PlainDate.from(str);
2616
+ case 4:
2617
+ return Temporal.PlainTime.from(str);
2618
+ }
2619
+ } catch (e) {
2620
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
2621
+ }
2622
+ }
2623
+
2624
+ // node_modules/smol-toml/dist/util.js
2625
+ /*!
2626
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2627
+ * SPDX-License-Identifier: BSD-3-Clause
2628
+ *
2629
+ * Redistribution and use in source and binary forms, with or without
2630
+ * modification, are permitted provided that the following conditions are met:
2631
+ *
2632
+ * 1. Redistributions of source code must retain the above copyright notice, this
2633
+ * list of conditions and the following disclaimer.
2634
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2635
+ * this list of conditions and the following disclaimer in the
2636
+ * documentation and/or other materials provided with the distribution.
2637
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2638
+ * may be used to endorse or promote products derived from this software without
2639
+ * specific prior written permission.
2640
+ *
2641
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2642
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2643
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2644
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2645
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2646
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2647
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2648
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2649
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2650
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2651
+ */
2652
+ function skipComment(ctx) {
2653
+ for (;ctx.p < ctx.s.length; ctx.p++) {
2654
+ let c = ctx.s.charCodeAt(ctx.p);
2655
+ if (c === 10)
2656
+ break;
2657
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
2658
+ ctx.p++;
2659
+ break;
2660
+ }
2661
+ if (c < 32 && c !== 9 || c === 127) {
2662
+ TomlError.x("control characters are not allowed in comments", ctx);
2663
+ }
2664
+ }
2665
+ }
2666
+ function skipVoid(ctx, banNewLines, banComments) {
2667
+ let c;
2668
+ while (ctx.p < ctx.s.length) {
2669
+ while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
2670
+ ctx.p++;
2671
+ if (banComments || c !== 35)
2672
+ break;
2673
+ skipComment(ctx);
2674
+ }
2675
+ }
2676
+
2677
+ // node_modules/smol-toml/dist/struct.js
2678
+ /*!
2679
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2680
+ * SPDX-License-Identifier: BSD-3-Clause
2681
+ *
2682
+ * Redistribution and use in source and binary forms, with or without
2683
+ * modification, are permitted provided that the following conditions are met:
2684
+ *
2685
+ * 1. Redistributions of source code must retain the above copyright notice, this
2686
+ * list of conditions and the following disclaimer.
2687
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2688
+ * this list of conditions and the following disclaimer in the
2689
+ * documentation and/or other materials provided with the distribution.
2690
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2691
+ * may be used to endorse or promote products derived from this software without
2692
+ * specific prior written permission.
2693
+ *
2694
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2695
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2696
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2697
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2698
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2699
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2700
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2701
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2702
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2703
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2704
+ */
2705
+ function parseKey(ctx, end = 61) {
2706
+ let startPtr;
2707
+ let state = 0;
2708
+ let parsed = [];
2709
+ let sliceStart;
2710
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
2711
+ do {
2712
+ if (c === end) {
2713
+ if (!state)
2714
+ TomlError.x("unexpected end of key", ctx);
2715
+ if (state === 1)
2716
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
2717
+ return ctx.p++, parsed;
2718
+ } else if (c === 46) {
2719
+ if (!state)
2720
+ TomlError.x("illegal empty bare key", ctx);
2721
+ if (state === 1)
2722
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
2723
+ state = 0;
2724
+ } else if (!state && (c === 34 || c === 39)) {
2725
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
2726
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
2727
+ parsed.push(parseString(ctx));
2728
+ state = 2;
2729
+ ctx.p--;
2730
+ } else if (c === 32 || c === 9) {
2731
+ if (state === 1) {
2732
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
2733
+ state = 2;
2734
+ }
2735
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
2736
+ TomlError.x("illegal character in key", ctx);
2737
+ } else if (!state) {
2738
+ state = 1;
2739
+ sliceStart = ctx.p;
2740
+ }
2741
+ } while (c = ctx.s.charCodeAt(++ctx.p));
2742
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
2743
+ }
2744
+ function parseInlineTable(ctx) {
2745
+ let startPtr = ctx.p++;
2746
+ let res = Object.create(null);
2747
+ let seen = new Set;
2748
+ let c;
2749
+ while (ctx.p < ctx.s.length) {
2750
+ skipVoid(ctx);
2751
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
2752
+ ctx.p++;
2753
+ return res;
2754
+ }
2755
+ let k;
2756
+ let t = res;
2757
+ let hasOwn = false;
2758
+ let errPtr = ctx.p;
2759
+ let key = parseKey(ctx);
2760
+ for (let i = 0;i < key.length; i++) {
2761
+ if (i)
2762
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
2763
+ k = key[i];
2764
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
2765
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
2766
+ }
2767
+ let unsafe = k === "__proto__";
2768
+ if (ctx.uk && (unsafe || k === "constructor")) {
2769
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
2770
+ break;
2771
+ }
2772
+ if (!hasOwn && unsafe) {
2773
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
2774
+ }
2775
+ }
2776
+ if (hasOwn) {
2777
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
2778
+ }
2779
+ skipVoid(ctx, true, true);
2780
+ let value = extractValue(ctx, 125);
2781
+ if (t && typeof (t[k] = value) === "object")
2782
+ seen.add(value);
2783
+ skipVoid(ctx);
2784
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
2785
+ return res;
2786
+ }
2787
+ if (c !== 44)
2788
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
2789
+ }
2790
+ TomlError.x("unfinished table", ctx, startPtr);
2791
+ }
2792
+ function parseArray(ctx) {
2793
+ let startPtr = ctx.p++;
2794
+ let res = [];
2795
+ let c;
2796
+ while (ctx.p < ctx.s.length) {
2797
+ skipVoid(ctx);
2798
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
2799
+ ctx.p++;
2800
+ return res;
2801
+ }
2802
+ res.push(extractValue(ctx, 93));
2803
+ skipVoid(ctx);
2804
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
2805
+ return res;
2806
+ }
2807
+ if (c !== 44)
2808
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
2809
+ }
2810
+ TomlError.x("unfinished array", ctx, startPtr);
2811
+ }
2812
+
2813
+ // node_modules/smol-toml/dist/parse.js
2814
+ /*!
2815
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2816
+ * SPDX-License-Identifier: BSD-3-Clause
2817
+ *
2818
+ * Redistribution and use in source and binary forms, with or without
2819
+ * modification, are permitted provided that the following conditions are met:
2820
+ *
2821
+ * 1. Redistributions of source code must retain the above copyright notice, this
2822
+ * list of conditions and the following disclaimer.
2823
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2824
+ * this list of conditions and the following disclaimer in the
2825
+ * documentation and/or other materials provided with the distribution.
2826
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2827
+ * may be used to endorse or promote products derived from this software without
2828
+ * specific prior written permission.
2829
+ *
2830
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2831
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2832
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2833
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2834
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2835
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2836
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2837
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2838
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2839
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2840
+ */
2841
+ function peekTable(ctx, key, table, meta, type) {
2842
+ let t = table;
2843
+ let m = meta;
2844
+ let k;
2845
+ let hasOwn = false;
2846
+ let state;
2847
+ for (let i = 0;i < key.length; i++) {
2848
+ if (i) {
2849
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
2850
+ m = (state = m[k]).c;
2851
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
2852
+ return null;
2853
+ }
2854
+ if (state.t === 2) {
2855
+ let l = t.length - 1;
2856
+ t = t[l];
2857
+ m = m[l].c;
2858
+ }
2859
+ }
2860
+ k = key[i];
2861
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
2862
+ return null;
2863
+ }
2864
+ if (!hasOwn) {
2865
+ let unsafe = k === "__proto__";
2866
+ if (ctx.uk && (unsafe || k === "constructor"))
2867
+ return false;
2868
+ if (unsafe) {
2869
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
2870
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
2871
+ }
2872
+ m[k] = {
2873
+ t: i < key.length - 1 && type === 2 ? 3 : type,
2874
+ d: false,
2875
+ i: 0,
2876
+ c: Object.create(null)
2877
+ };
2878
+ }
2879
+ }
2880
+ state = m[k];
2881
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
2882
+ return null;
2883
+ }
2884
+ if (type === 2) {
2885
+ if (!state.d) {
2886
+ state.d = true;
2887
+ t[k] = [];
2888
+ }
2889
+ t[k].push(t = Object.create(null));
2890
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: Object.create(null) };
2891
+ }
2892
+ if (state.d) {
2893
+ return null;
2894
+ }
2895
+ state.d = true;
2896
+ if (type === 1) {
2897
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
2898
+ } else if (type === 0 && hasOwn) {
2899
+ return null;
2900
+ }
2901
+ return [k, t, state.c];
2902
+ }
2903
+ function validateTablePeek(ctx, peek, ptr) {
2904
+ if (peek === null || ctx.uk === 2)
2905
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
2906
+ }
2907
+ function parse(toml, options = {}) {
2908
+ let ctx = {
2909
+ s: toml,
2910
+ p: 0,
2911
+ d: options.maxDepth ?? 1000,
2912
+ bi: options.integersAsBigInt ?? false,
2913
+ ld: options.useLegacyDate ?? true,
2914
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
2915
+ };
2916
+ let res = Object.create(null);
2917
+ let meta = Object.create(null);
2918
+ let tmp;
2919
+ let skipping = false;
2920
+ let tbl = res;
2921
+ let m = meta;
2922
+ if (toml.charCodeAt(0) === 65279)
2923
+ ctx.p++;
2924
+ skipVoid(ctx);
2925
+ while (ctx.p < toml.length) {
2926
+ if (toml.charCodeAt(ctx.p) === 91) {
2927
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
2928
+ tmp = ctx.p += +isTableArray;
2929
+ skipping = false;
2930
+ let k = parseKey(ctx, 93);
2931
+ if (isTableArray) {
2932
+ if (toml.charCodeAt(ctx.p) !== 93) {
2933
+ TomlError.x("expected end of table array declaration", ctx);
2934
+ }
2935
+ ctx.p++;
2936
+ }
2937
+ let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
2938
+ if (!p) {
2939
+ validateTablePeek(ctx, p, tmp);
2940
+ skipping = true;
2941
+ } else {
2942
+ m = p[2];
2943
+ tbl = p[1];
2944
+ }
2945
+ } else {
2946
+ tmp = ctx.p;
2947
+ let k = parseKey(ctx);
2948
+ let p = peekTable(ctx, k, tbl, m, 0);
2949
+ if (!p && !skipping)
2950
+ validateTablePeek(ctx, p, tmp);
2951
+ skipVoid(ctx, true, true);
2952
+ let v = extractValue(ctx, undefined);
2953
+ if (p && !skipping)
2954
+ p[1][p[0]] = v;
2955
+ }
2956
+ skipVoid(ctx, true);
2957
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
2958
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
2959
+ }
2960
+ skipVoid(ctx);
2961
+ }
2962
+ return res;
2963
+ }
2964
+
2965
+ // node_modules/smol-toml/dist/stringify.js
2966
+ /*!
2967
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2968
+ * SPDX-License-Identifier: BSD-3-Clause
2969
+ *
2970
+ * Redistribution and use in source and binary forms, with or without
2971
+ * modification, are permitted provided that the following conditions are met:
2972
+ *
2973
+ * 1. Redistributions of source code must retain the above copyright notice, this
2974
+ * list of conditions and the following disclaimer.
2975
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2976
+ * this list of conditions and the following disclaimer in the
2977
+ * documentation and/or other materials provided with the distribution.
2978
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2979
+ * may be used to endorse or promote products derived from this software without
2980
+ * specific prior written permission.
2981
+ *
2982
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2983
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2984
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2985
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2986
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2987
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2988
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2989
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2990
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2991
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2992
+ */
2993
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
2994
+ var HAS_WELLFORMED = !!"".isWellFormed;
2995
+ function extendedTypeOf(obj) {
2996
+ let type = typeof obj;
2997
+ if (type === "object") {
2998
+ if (Array.isArray(obj))
2999
+ return "array";
3000
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date)
3001
+ return "date";
3002
+ if (globalThis.Temporal) {
3003
+ if (obj.until) {
3004
+ if (obj instanceof Temporal.ZonedDateTime)
3005
+ return "temporal/tz+uc";
3006
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
3007
+ return "temporal/uc";
3008
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
3009
+ return "temporal";
3010
+ if (obj instanceof Temporal.PlainYearMonth)
3011
+ return "temporal/x";
3012
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) {
3013
+ return "temporal/x";
3014
+ }
3015
+ }
3016
+ }
3017
+ return type;
3018
+ }
3019
+ function isArrayOfTables(obj) {
3020
+ for (let i = 0;i < obj.length; i++) {
3021
+ if (extendedTypeOf(obj[i]) !== "object")
3022
+ return false;
3023
+ }
3024
+ return obj.length != 0;
3025
+ }
3026
+ function formatWellFormedStringUnchecked(s) {
3027
+ return JSON.stringify(s).replaceAll("", "\\u007f");
3028
+ }
3029
+ function formatString(s) {
3030
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
3031
+ }
3032
+ function formatKey(s) {
3033
+ if (BARE_KEY.test(s))
3034
+ return s;
3035
+ if (HAS_WELLFORMED && !s.isWellFormed())
3036
+ throw new RangeError("key contains illegal lone surrogates");
3037
+ return formatWellFormedStringUnchecked(s);
3038
+ }
3039
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
3040
+ if (depth === 0) {
3041
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
3042
+ }
3043
+ switch (type) {
3044
+ case "number":
3045
+ if (isNaN(val))
3046
+ return "nan";
3047
+ if (val === Infinity)
3048
+ return "inf";
3049
+ if (val === -Infinity)
3050
+ return "-inf";
3051
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
3052
+ return val.toFixed(1);
3053
+ case "bigint":
3054
+ case "boolean":
3055
+ case "temporal":
3056
+ return val.toString();
3057
+ case "string":
3058
+ return formatString(val);
3059
+ case "date":
3060
+ if (isNaN(val.getTime()))
3061
+ throw new TypeError("cannot serialize invalid date");
3062
+ return val.toISOString();
3063
+ case "object":
3064
+ return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
3065
+ case "array":
3066
+ return stringifyArray(val, depth, numberAsFloat, strictTemporal);
3067
+ case "temporal/tz+uc":
3068
+ if (strictTemporal) {
3069
+ let tz = val.timeZoneId;
3070
+ let tzc = tz.charCodeAt(0);
3071
+ if (tzc !== 43 && tzc !== 45 && (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || tz !== "UTC" && tz !== "UCT" && tz !== "Universal" && tz !== "Zulu" && !tz.startsWith("GMT") && tz !== "Greenwich" && !tz.startsWith("Etc/"))) {
3072
+ throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
3073
+ }
3074
+ }
3075
+ case "temporal/uc":
3076
+ if (strictTemporal && val.calendarId !== "iso8601")
3077
+ throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
3078
+ return val.toString({
3079
+ calendarName: "never",
3080
+ timeZoneName: "never"
3081
+ });
3082
+ case "temporal/x":
3083
+ throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
3084
+ }
3085
+ }
3086
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
3087
+ let keys = Object.keys(obj);
3088
+ if (keys.length === 0)
3089
+ return "{}";
3090
+ let res = "{ ";
3091
+ for (let i = 0;i < keys.length; i++) {
3092
+ let k = keys[i];
3093
+ if (i)
3094
+ res += ", ";
3095
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
3096
+ }
3097
+ return res + " }";
3098
+ }
3099
+ function stringifyArray(array, depth, numberAsFloat, strictTemporal) {
3100
+ if (array.length === 0)
3101
+ return "[]";
3102
+ let res = "[ ";
3103
+ for (let i = 0;i < array.length; i++) {
3104
+ if (i)
3105
+ res += ", ";
3106
+ if (array[i] === null || array[i] === undefined) {
3107
+ throw new TypeError("arrays cannot contain null or undefined values");
3108
+ }
3109
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);
3110
+ }
3111
+ return res + " ]";
3112
+ }
3113
+ function stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {
3114
+ if (depth === 0) {
3115
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
3116
+ }
3117
+ let res = "";
3118
+ for (let i = 0;i < array.length; i++) {
3119
+ res += `${res && `
3120
+ `}[[${key}]]
3121
+ `;
3122
+ res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);
3123
+ }
3124
+ return res;
3125
+ }
3126
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
3127
+ if (depth === 0) {
3128
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
3129
+ }
3130
+ let preamble = "";
3131
+ let tables = "";
3132
+ let keys = Object.keys(obj);
3133
+ for (let i = 0;i < keys.length; i++) {
3134
+ let k = keys[i];
3135
+ if (obj[k] !== null && obj[k] !== undefined) {
3136
+ let type = extendedTypeOf(obj[k]);
3137
+ if (type === "symbol" || type === "function") {
3138
+ throw new TypeError(`cannot serialize values of type '${type}'`);
3139
+ }
3140
+ let key = formatKey(k);
3141
+ if (type === "array" && isArrayOfTables(obj[k])) {
3142
+ tables += (tables && `
3143
+ `) + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
3144
+ } else if (type === "object") {
3145
+ let tblKey = prefix ? `${prefix}.${key}` : key;
3146
+ tables += (tables && `
3147
+ `) + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
3148
+ } else {
3149
+ preamble += key;
3150
+ preamble += " = ";
3151
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
3152
+ preamble += `
3153
+ `;
3154
+ }
3155
+ }
3156
+ }
3157
+ if (tableKey && (preamble || !tables))
3158
+ preamble = preamble ? `[${tableKey}]
3159
+ ${preamble}` : `[${tableKey}]`;
3160
+ return preamble && tables ? `${preamble}
3161
+ ${tables}` : preamble || tables;
3162
+ }
3163
+ function stringify(obj, { maxDepth = 1000, numbersAsFloat = false, strictTemporal = false } = {}) {
3164
+ if (extendedTypeOf(obj) !== "object") {
3165
+ throw new TypeError("stringify can only be called with an object");
3166
+ }
3167
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
3168
+ if (str[str.length - 1] !== `
3169
+ `)
3170
+ return str + `
3171
+ `;
3172
+ return str;
3173
+ }
3174
+
3175
+ // node_modules/smol-toml/dist/index.js
3176
+ /*!
3177
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
3178
+ * SPDX-License-Identifier: BSD-3-Clause
3179
+ *
3180
+ * Redistribution and use in source and binary forms, with or without
3181
+ * modification, are permitted provided that the following conditions are met:
3182
+ *
3183
+ * 1. Redistributions of source code must retain the above copyright notice, this
3184
+ * list of conditions and the following disclaimer.
3185
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
3186
+ * this list of conditions and the following disclaimer in the
3187
+ * documentation and/or other materials provided with the distribution.
3188
+ * 3. Neither the name of the copyright holder nor the names of its contributors
3189
+ * may be used to endorse or promote products derived from this software without
3190
+ * specific prior written permission.
3191
+ *
3192
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
3193
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
3194
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
3195
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
3196
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3197
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
3198
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
3199
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
3200
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3201
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3202
+ */
3203
+
3204
+ // src/paths.ts
3205
+ import { homedir } from "node:os";
3206
+ import { join } from "node:path";
3207
+ var configDir = (env = process.env) => env.ASTRAL_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "astral");
3208
+ var cacheDir = (env = process.env) => env.ASTRAL_CACHE_DIR || join(env.XDG_CACHE_HOME || join(homedir(), ".cache"), "astral");
3209
+
3210
+ // src/credentials.ts
3211
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3212
+ import { join as join2 } from "node:path";
3213
+ var credentialsPath = (env = process.env) => join2(configDir(env), "credentials.json");
3214
+ var readFile = (env) => {
3215
+ try {
3216
+ const parsed = JSON.parse(readFileSync(credentialsPath(env), "utf8"));
3217
+ return { profiles: typeof parsed.profiles === "object" && parsed.profiles ? parsed.profiles : {} };
3218
+ } catch {
3219
+ return { profiles: {} };
3220
+ }
3221
+ };
3222
+ var writeFile = (file, env) => {
3223
+ const path = credentialsPath(env);
3224
+ if (Object.keys(file.profiles).length === 0) {
3225
+ rmSync(path, { force: true });
3226
+ return;
3227
+ }
3228
+ mkdirSync(configDir(env), { recursive: true, mode: 448 });
3229
+ writeFileSync(path, `${JSON.stringify(file, null, 2)}
3230
+ `, { mode: 384 });
3231
+ chmodSync(path, 384);
3232
+ };
3233
+ var readCredential = (profile, env = process.env) => {
3234
+ const credential = readFile(env).profiles[profile];
3235
+ return credential && typeof credential.token === "string" && credential.token ? credential : null;
3236
+ };
3237
+ var saveCredential = (profile, credential, env = process.env) => {
3238
+ const file = readFile(env);
3239
+ file.profiles[profile] = credential;
3240
+ writeFile(file, env);
3241
+ };
3242
+ var deleteCredential = (profile, env = process.env) => {
3243
+ const file = readFile(env);
3244
+ if (!file.profiles[profile])
3245
+ return false;
3246
+ delete file.profiles[profile];
3247
+ writeFile(file, env);
3248
+ return true;
3249
+ };
3250
+
3251
+ // src/config.ts
3252
+ var DEFAULT_API_URL = "https://www.astralos.ai";
3253
+ var DEFAULT_PROFILE = "default";
3254
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3255
+ var configPath = (env = process.env) => join3(configDir(env), "config.toml");
3256
+ var readConfig = (env = process.env) => {
3257
+ let raw;
3258
+ try {
3259
+ raw = readFileSync2(configPath(env), "utf8");
3260
+ } catch {
3261
+ return { profiles: {} };
3262
+ }
3263
+ const parsed = parse(raw);
3264
+ const profiles = {};
3265
+ if (isObject(parsed.profiles)) {
3266
+ for (const [name, value] of Object.entries(parsed.profiles)) {
3267
+ if (!isObject(value))
3268
+ continue;
3269
+ profiles[name] = {
3270
+ ...typeof value.api_url === "string" ? { api_url: value.api_url } : {},
3271
+ ...typeof value.workspace_id === "string" ? { workspace_id: value.workspace_id } : {}
3272
+ };
3273
+ }
3274
+ }
3275
+ return {
3276
+ ...typeof parsed.current_profile === "string" ? { current_profile: parsed.current_profile } : {},
3277
+ profiles
3278
+ };
3279
+ };
3280
+ var writeConfig = (config, env = process.env) => {
3281
+ mkdirSync2(configDir(env), { recursive: true, mode: 448 });
3282
+ writeFileSync2(configPath(env), stringify(config), { mode: 384 });
3283
+ };
3284
+ var updateProfile = (name, patch, env = process.env) => {
3285
+ const config = readConfig(env);
3286
+ config.profiles[name] = { ...config.profiles[name], ...patch };
3287
+ writeConfig(config, env);
3288
+ };
3289
+ var resolveContext = (params = {}) => {
3290
+ const env = params.env ?? process.env;
3291
+ const config = readConfig(env);
3292
+ const profile = params.profile || env.ASTRAL_PROFILE || config.current_profile || DEFAULT_PROFILE;
3293
+ const stored = config.profiles[profile] ?? {};
3294
+ const credential = env.ASTRAL_TOKEN ? null : readCredential(profile, env);
3295
+ return {
3296
+ profile,
3297
+ apiUrl: (env.ASTRAL_API_URL || stored.api_url || DEFAULT_API_URL).replace(/\/+$/, ""),
3298
+ workspaceId: env.ASTRAL_WORKSPACE || stored.workspace_id || credential?.workspace_id || null,
3299
+ token: env.ASTRAL_TOKEN || credential?.token || null,
3300
+ tokenSource: env.ASTRAL_TOKEN ? "env" : credential ? "credentials" : null
3301
+ };
3302
+ };
3303
+
3304
+ // src/errors.ts
3305
+ var EXIT = {
3306
+ ok: 0,
3307
+ failure: 1,
3308
+ invalid_input: 2,
3309
+ auth: 3,
3310
+ permission_denied: 4,
3311
+ not_found: 5,
3312
+ rate_limited: 6,
3313
+ upstream_error: 7,
3314
+ approval_required: 10
3315
+ };
3316
+ var EXIT_FOR_ERROR = {
3317
+ invalid_input: EXIT.invalid_input,
3318
+ auth_required: EXIT.auth,
3319
+ auth_failed: EXIT.auth,
3320
+ permission_denied: EXIT.permission_denied,
3321
+ not_found: EXIT.not_found,
3322
+ rate_limited: EXIT.rate_limited,
3323
+ upstream_error: EXIT.upstream_error,
3324
+ approval_required: EXIT.approval_required
3325
+ };
3326
+ var exitCodeFor = (type) => EXIT_FOR_ERROR[type] ?? EXIT.failure;
3327
+
3328
+ class CliError extends Error {
3329
+ error;
3330
+ constructor(error) {
3331
+ super(error.message);
3332
+ this.name = "CliError";
3333
+ this.error = error;
3334
+ }
3335
+ get exitCode() {
3336
+ return exitCodeFor(this.error.type);
3337
+ }
3338
+ }
3339
+ var cliError = (type, message, details) => new CliError({ type, message, ...details ? { details } : {} });
3340
+
3341
+ // ../aios-next/src/features/api-tokens/shared/v1-contract.ts
3342
+ var ASTRAL_API_VERSION = "1";
3343
+ var ASTRAL_API_VERSION_HEADER = "Astral-Api-Version";
3344
+ var ASTRAL_WORKSPACE_HEADER = "Astral-Workspace";
3345
+ var ASTRAL_APPROVAL_HEADER = "Astral-Approval";
3346
+ // package.json
3347
+ var package_default = {
3348
+ name: "@astralos/cli",
3349
+ version: "0.1.1",
3350
+ license: "MIT",
3351
+ description: "The Astral command line. Every Astral tool, from a terminal or an agent.",
3352
+ publishConfig: {
3353
+ access: "public"
3354
+ },
3355
+ repository: {
3356
+ type: "git",
3357
+ url: "git+https://github.com/amadk/aios.git",
3358
+ directory: "projects/astral-cli"
3359
+ },
3360
+ type: "module",
3361
+ bin: {
3362
+ astral: "dist/astral.js"
3363
+ },
3364
+ files: [
3365
+ "dist"
3366
+ ],
3367
+ engines: {
3368
+ node: ">=20"
3369
+ },
3370
+ scripts: {
3371
+ dev: "bun src/cli.ts",
3372
+ build: "bun build src/cli.ts --target node --outfile dist/astral.js",
3373
+ prepack: "bun run build",
3374
+ typecheck: "tsc --noEmit",
3375
+ test: "bun test"
3376
+ },
3377
+ devDependencies: {
3378
+ "@types/bun": "latest",
3379
+ "@types/node": "^22.10.2",
3380
+ commander: "^15.0.0",
3381
+ "smol-toml": "^1.9.1",
3382
+ typescript: "^5.7.2"
3383
+ }
3384
+ };
3385
+
3386
+ // src/http.ts
3387
+ var ERROR_TYPES = new Set([
3388
+ "auth_required",
3389
+ "auth_failed",
3390
+ "permission_denied",
3391
+ "rate_limited",
3392
+ "not_found",
3393
+ "invalid_input",
3394
+ "upstream_error",
3395
+ "approval_required"
3396
+ ]);
3397
+ var errorTypeForStatus = (status) => {
3398
+ if (status === 400 || status === 422)
3399
+ return "invalid_input";
3400
+ if (status === 401)
3401
+ return "auth_required";
3402
+ if (status === 403)
3403
+ return "permission_denied";
3404
+ if (status === 404)
3405
+ return "not_found";
3406
+ if (status === 429)
3407
+ return "rate_limited";
3408
+ return "upstream_error";
3409
+ };
3410
+ var isEnvelope = (value) => {
3411
+ if (typeof value !== "object" || value === null || !("ok" in value))
3412
+ return false;
3413
+ const ok = value.ok;
3414
+ if (ok === true)
3415
+ return "data" in value;
3416
+ if (ok !== false)
3417
+ return false;
3418
+ const error = value.error;
3419
+ return typeof error?.type === "string" && ERROR_TYPES.has(error.type) && typeof error.message === "string";
3420
+ };
3421
+
3422
+ class ApiClient {
3423
+ context;
3424
+ fetchImpl;
3425
+ constructor(context, fetchImpl = fetch) {
3426
+ this.context = context;
3427
+ this.fetchImpl = fetchImpl;
3428
+ }
3429
+ url(path) {
3430
+ return `${this.context.apiUrl}${path}`;
3431
+ }
3432
+ async raw(params) {
3433
+ const headers = {
3434
+ Accept: "application/json",
3435
+ "User-Agent": `astral-cli/${package_default.version}`,
3436
+ [ASTRAL_API_VERSION_HEADER]: ASTRAL_API_VERSION,
3437
+ ...params.headers
3438
+ };
3439
+ if (this.context.token && params.auth !== false)
3440
+ headers.Authorization = `Bearer ${this.context.token}`;
3441
+ if (this.context.workspaceId)
3442
+ headers[ASTRAL_WORKSPACE_HEADER] = this.context.workspaceId;
3443
+ let body;
3444
+ if (params.form) {
3445
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
3446
+ body = new URLSearchParams(params.form).toString();
3447
+ } else if (params.json !== undefined) {
3448
+ headers["Content-Type"] = "application/json";
3449
+ body = JSON.stringify(params.json);
3450
+ }
3451
+ const { response, parsed } = await this.send(params.path, { method: params.method, headers, body, signal: params.signal });
3452
+ if (response.status === 304)
3453
+ return { status: 304, headers: response.headers, envelope: null };
3454
+ if (isEnvelope(parsed))
3455
+ return { status: response.status, headers: response.headers, envelope: parsed };
3456
+ throw cliError(errorTypeForStatus(response.status), `The API answered HTTP ${response.status} without a v1 envelope.`, {
3457
+ status: response.status
3458
+ });
3459
+ }
3460
+ async oauth(path, form) {
3461
+ const { response, parsed } = await this.send(path, {
3462
+ method: "POST",
3463
+ headers: {
3464
+ Accept: "application/json",
3465
+ "Content-Type": "application/x-www-form-urlencoded",
3466
+ "User-Agent": `astral-cli/${package_default.version}`,
3467
+ [ASTRAL_API_VERSION_HEADER]: ASTRAL_API_VERSION
3468
+ },
3469
+ body: new URLSearchParams(form).toString()
3470
+ });
3471
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
3472
+ throw cliError(errorTypeForStatus(response.status), `The API answered HTTP ${response.status} without JSON.`);
3473
+ }
3474
+ return { status: response.status, body: parsed };
3475
+ }
3476
+ async send(path, init) {
3477
+ let response;
3478
+ try {
3479
+ response = await this.fetchImpl(this.url(path), init);
3480
+ } catch (error) {
3481
+ const reason = error instanceof Error ? error.message : String(error);
3482
+ throw cliError("upstream_error", `Could not reach ${this.context.apiUrl}: ${reason}`);
3483
+ }
3484
+ if (response.status === 304)
3485
+ return { response, parsed: null };
3486
+ const text = await response.text();
3487
+ try {
3488
+ return { response, parsed: text ? JSON.parse(text) : null };
3489
+ } catch {
3490
+ return { response, parsed: null };
3491
+ }
3492
+ }
3493
+ async call(params) {
3494
+ const { envelope } = await this.raw(params);
3495
+ if (!envelope)
3496
+ throw cliError("upstream_error", "The API answered with no body.");
3497
+ if (!envelope.ok)
3498
+ throw new CliError(envelope.error);
3499
+ return envelope.data;
3500
+ }
3501
+ }
3502
+
3503
+ // src/output.ts
3504
+ var pretty = (value) => typeof value === "string" ? value : JSON.stringify(value, null, 2);
3505
+ var emit = (params) => {
3506
+ const { runtime, globals, data, human } = params;
3507
+ if (globals.json) {
3508
+ runtime.stdout(JSON.stringify({ ok: true, data }, null, 2));
3509
+ return;
3510
+ }
3511
+ runtime.stdout(human ? human(data) : pretty(data));
3512
+ };
3513
+ var emitError = (params) => {
3514
+ const { runtime, json, error } = params;
3515
+ if (json) {
3516
+ runtime.stdout(JSON.stringify({ ok: false, error }, null, 2));
3517
+ return;
3518
+ }
3519
+ const lines = [`Error (${error.type}): ${error.message}`];
3520
+ const url = error.details?.approval_url;
3521
+ if (typeof url === "string")
3522
+ lines.push(`Approve it here: ${url}`);
3523
+ if (error.type === "auth_required")
3524
+ lines.push("Run `astral login`, or set ASTRAL_TOKEN.");
3525
+ runtime.stderr(lines.join(`
3526
+ `));
3527
+ };
3528
+ var table = (rows, columns) => {
3529
+ if (rows.length === 0)
3530
+ return "(none)";
3531
+ const cell = (value) => value === null || value === undefined ? "-" : String(value);
3532
+ const widths = columns.map((column) => Math.max(column.length, ...rows.map((row) => cell(row[column]).length)));
3533
+ const line = (values) => values.map((value, i) => value.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
3534
+ return [line(columns.map((column) => column.toUpperCase())), ...rows.map((row) => line(columns.map((c) => cell(row[c]))))].join(`
3535
+ `);
3536
+ };
3537
+
3538
+ // src/prompt.ts
3539
+ import { createInterface } from "node:readline/promises";
3540
+ var confirm = async (params) => {
3541
+ const { runtime, globals, question } = params;
3542
+ if (globals.yes)
3543
+ return;
3544
+ if (!runtime.interactive) {
3545
+ throw cliError("invalid_input", `${question} Pass --yes to confirm.`, { reason: "confirmation_required" });
3546
+ }
3547
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
3548
+ try {
3549
+ const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
3550
+ if (answer !== "y" && answer !== "yes")
3551
+ throw cliError("invalid_input", "Cancelled.", { reason: "cancelled" });
3552
+ } finally {
3553
+ rl.close();
3554
+ }
3555
+ };
3556
+ var select = async (params) => {
3557
+ const { runtime, question, choices } = params;
3558
+ if (!runtime.interactive)
3559
+ throw cliError("invalid_input", "A selection needs an interactive terminal.");
3560
+ if (choices.length === 0)
3561
+ throw cliError("not_found", "There are no sites to link.");
3562
+ runtime.stderr(choices.map((choice, index) => `${index + 1}. ${choice}`).join(`
3563
+ `));
3564
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
3565
+ try {
3566
+ const answer = (await rl.question(`${question} [1-${choices.length}] `)).trim();
3567
+ const index = Number(answer) - 1;
3568
+ if (!/^\d+$/.test(answer) || !Number.isInteger(index) || index < 0 || index >= choices.length) {
3569
+ throw cliError("invalid_input", "Choose a number from the list.");
3570
+ }
3571
+ return index;
3572
+ } finally {
3573
+ rl.close();
3574
+ }
3575
+ };
3576
+ var readStdin = async () => {
3577
+ const chunks = [];
3578
+ for await (const chunk of process.stdin)
3579
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
3580
+ return Buffer.concat(chunks).toString("utf8");
3581
+ };
3582
+
3583
+ // src/runtime.ts
3584
+ var globalsOf = (command) => command.optsWithGlobals();
3585
+ var clientFor = (runtime, globals) => new ApiClient(resolveContext({ profile: globals.profile, env: runtime.env }), runtime.fetchImpl);
3586
+ var defaultRuntime = () => ({
3587
+ env: process.env,
3588
+ fetchImpl: (input, init) => fetch(input, init),
3589
+ stdout: (text) => process.stdout.write(text.endsWith(`
3590
+ `) ? text : `${text}
3591
+ `),
3592
+ stderr: (text) => process.stderr.write(text.endsWith(`
3593
+ `) ? text : `${text}
3594
+ `),
3595
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
3596
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
3597
+ now: () => new Date
3598
+ });
3599
+
3600
+ // src/commands/auth.ts
3601
+ var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
3602
+ var SLOW_DOWN_STEP_SECONDS = 5;
3603
+ var str = (value) => typeof value === "string" && value ? value : null;
3604
+ var remember = (params) => {
3605
+ const { runtime, context, apiUrl, result } = params;
3606
+ updateProfile(context.profile, { ...apiUrl ? { api_url: result.api_url } : {}, workspace_id: result.workspace_id }, runtime.env);
3607
+ const config = readConfig(runtime.env);
3608
+ if (!config.current_profile)
3609
+ writeConfig({ ...config, current_profile: context.profile }, runtime.env);
3610
+ };
3611
+ var loginWithToken = async (params) => {
3612
+ const { runtime, context, token } = params;
3613
+ const whoami = await new ApiClient({ ...context, token }, runtime.fetchImpl).call({
3614
+ method: "GET",
3615
+ path: "/api/v1/whoami"
3616
+ });
3617
+ if (!whoami.workspace_id)
3618
+ throw cliError("auth_failed", "The token has no workspace.");
3619
+ saveCredential(context.profile, {
3620
+ token,
3621
+ workspace_id: whoami.workspace_id,
3622
+ ...whoami.token ? { token_id: whoami.token.id, expires_at: whoami.token.expires_at } : {}
3623
+ }, runtime.env);
3624
+ return {
3625
+ profile: context.profile,
3626
+ api_url: context.apiUrl,
3627
+ workspace_id: whoami.workspace_id,
3628
+ token_id: whoami.token?.id ?? null,
3629
+ expires_at: whoami.token?.expires_at ?? null
3630
+ };
3631
+ };
3632
+ var loginWithDevice = async (params) => {
3633
+ const { runtime, context, scopes, name } = params;
3634
+ const client = new ApiClient({ ...context, token: null }, runtime.fetchImpl);
3635
+ const started = await client.oauth("/api/v1/auth/device/code", { client_id: name, scope: scopes.join(" ") });
3636
+ const deviceCode = str(started.body.device_code);
3637
+ const userCode = str(started.body.user_code);
3638
+ if (!deviceCode || !userCode) {
3639
+ const reason = str(started.body.error_description) ?? str(started.body.error) ?? `HTTP ${started.status}`;
3640
+ throw cliError(started.body.error === "invalid_scope" ? "invalid_input" : "upstream_error", `Login could not start: ${reason}`);
3641
+ }
3642
+ const verifyUrl = str(started.body.verification_uri_complete) ?? str(started.body.verification_uri) ?? context.apiUrl;
3643
+ runtime.stderr(`Open ${verifyUrl}
3644
+ and confirm the code ${userCode}. Waiting for approval...`);
3645
+ let interval = typeof started.body.interval === "number" ? started.body.interval : 5;
3646
+ const expiresIn = typeof started.body.expires_in === "number" ? started.body.expires_in : 600;
3647
+ const deadline = runtime.now().getTime() + expiresIn * 1000;
3648
+ while (runtime.now().getTime() < deadline) {
3649
+ await runtime.sleep(interval * 1000);
3650
+ const polled = await client.oauth("/api/v1/auth/device/token", { grant_type: DEVICE_GRANT, device_code: deviceCode });
3651
+ const token = str(polled.body.access_token);
3652
+ const workspaceId = str(polled.body.workspace_id);
3653
+ if (token && workspaceId) {
3654
+ const expiresInSeconds = typeof polled.body.expires_in === "number" ? polled.body.expires_in : null;
3655
+ const expiresAt = expiresInSeconds ? new Date(runtime.now().getTime() + expiresInSeconds * 1000).toISOString() : null;
3656
+ const tokenId = str(polled.body.token_id);
3657
+ saveCredential(context.profile, { token, workspace_id: workspaceId, ...tokenId ? { token_id: tokenId } : {}, ...expiresAt ? { expires_at: expiresAt } : {} }, runtime.env);
3658
+ return { profile: context.profile, api_url: context.apiUrl, workspace_id: workspaceId, token_id: tokenId, expires_at: expiresAt };
3659
+ }
3660
+ const error = str(polled.body.error);
3661
+ const description = str(polled.body.error_description) ?? error ?? `HTTP ${polled.status}`;
3662
+ if (error === "authorization_pending")
3663
+ continue;
3664
+ if (error === "slow_down") {
3665
+ interval += SLOW_DOWN_STEP_SECONDS;
3666
+ continue;
3667
+ }
3668
+ if (error === "access_denied")
3669
+ throw cliError("permission_denied", `Login denied: ${description}`);
3670
+ throw cliError("auth_failed", `Login failed: ${description}`);
3671
+ }
3672
+ throw cliError("auth_failed", "Login failed: the code expired before anyone approved it.");
3673
+ };
3674
+ var registerAuth = (program, runtime) => {
3675
+ program.command("login").description("sign in from this terminal (a browser approves the device)").option("--api-url <url>", "the Astral API to sign in to").option("--with-token", "read an access token from stdin instead of the browser flow").option("--scope <scope...>", "token scopes, for example sites:write code:read", ["*"]).option("--name <name>", "a name for the token", `astral-cli on ${hostname()}`).action(async (options, command) => {
3676
+ const globals = globalsOf(command);
3677
+ const env = { ...runtime.env, ASTRAL_TOKEN: undefined, ...options.apiUrl ? { ASTRAL_API_URL: options.apiUrl } : {} };
3678
+ const context = resolveContext({ profile: globals.profile, env });
3679
+ let result;
3680
+ if (options.withToken) {
3681
+ const token = (await readStdin()).trim();
3682
+ if (!token)
3683
+ throw cliError("invalid_input", "Pipe the token on stdin, for example: echo $TOKEN | astral login --with-token");
3684
+ result = await loginWithToken({ runtime, context, token });
3685
+ } else {
3686
+ result = await loginWithDevice({ runtime, context, scopes: options.scope ?? ["*"], name: options.name ?? "astral-cli" });
3687
+ }
3688
+ remember({ runtime, context, apiUrl: options.apiUrl, result });
3689
+ emit({
3690
+ runtime,
3691
+ globals,
3692
+ data: result,
3693
+ human: (r) => `Signed in. Profile ${r.profile}, workspace ${r.workspace_id}.`
3694
+ });
3695
+ });
3696
+ program.command("logout").description("revoke this profile's token and forget it").action(async (_options, command) => {
3697
+ const globals = globalsOf(command);
3698
+ const context = resolveContext({ profile: globals.profile, env: { ...runtime.env, ASTRAL_TOKEN: undefined } });
3699
+ const credential = readCredential(context.profile, runtime.env);
3700
+ let revoked = false;
3701
+ let warning = null;
3702
+ if (credential?.token_id) {
3703
+ try {
3704
+ await new ApiClient({ ...context, token: credential.token }, runtime.fetchImpl).call({
3705
+ method: "DELETE",
3706
+ path: `/api/v1/tokens/${encodeURIComponent(credential.token_id)}`
3707
+ });
3708
+ revoked = true;
3709
+ } catch (error) {
3710
+ warning = `The server did not revoke the token: ${error instanceof Error ? error.message : String(error)}`;
3711
+ }
3712
+ }
3713
+ const removed = deleteCredential(context.profile, runtime.env);
3714
+ if (warning)
3715
+ runtime.stderr(`Warning: ${warning}`);
3716
+ if (runtime.env.ASTRAL_TOKEN)
3717
+ runtime.stderr("Note: ASTRAL_TOKEN is still set in this shell.");
3718
+ emit({
3719
+ runtime,
3720
+ globals,
3721
+ data: { profile: context.profile, removed, revoked },
3722
+ human: (d) => d.removed ? `Signed out of profile ${d.profile}.` : `Profile ${d.profile} was not signed in.`
3723
+ });
3724
+ });
3725
+ program.command("whoami").description("show who this CLI acts for").action(async (_options, command) => {
3726
+ const globals = globalsOf(command);
3727
+ const data = await clientFor(runtime, globals).call({ method: "GET", path: "/api/v1/whoami" });
3728
+ emit({
3729
+ runtime,
3730
+ globals,
3731
+ data,
3732
+ human: (d) => [
3733
+ `${d.principal.type} ${d.principal.agent_id ?? d.principal.user_id}`,
3734
+ `workspace ${d.workspace_id ?? "-"}`,
3735
+ d.token ? `token ${d.token.name} (${d.token.scopes.join(" ")}), expires ${d.token.expires_at}` : `auth ${d.auth}`
3736
+ ].join(`
3737
+ `)
3738
+ });
3739
+ });
3740
+ registerToken(program, runtime);
3741
+ };
3742
+ var registerToken = (program, runtime) => {
3743
+ const token = program.command("token").description("manage access tokens for CI and outside agents");
3744
+ token.command("create").description("create an access token (the secret is shown once)").requiredOption("--name <name>", "what the token is for").option("--scope <scope...>", "scopes, for example sites:write code:read (default: *)").option("--expires-in-days <days>", "days until the token expires").option("--agent <agent_id>", "make the token act for this agent").action(async (options, command) => {
3745
+ const globals = globalsOf(command);
3746
+ const days = options.expiresInDays === undefined ? undefined : Number(options.expiresInDays);
3747
+ if (days !== undefined && !Number.isInteger(days))
3748
+ throw cliError("invalid_input", "--expires-in-days must be a whole number.");
3749
+ const data = await clientFor(runtime, globals).call({
3750
+ method: "POST",
3751
+ path: "/api/v1/tokens",
3752
+ json: {
3753
+ name: options.name,
3754
+ ...options.scope ? { scopes: options.scope } : {},
3755
+ ...days !== undefined ? { expires_in_days: days } : {},
3756
+ ...options.agent ? { agent_id: options.agent } : {}
3757
+ }
3758
+ });
3759
+ emit({
3760
+ runtime,
3761
+ globals,
3762
+ data,
3763
+ human: (d) => `${d.token}
3764
+
3765
+ This is the only time the token is shown. Token id: ${d.record.id}, expires ${d.record.expires_at}.`
3766
+ });
3767
+ });
3768
+ token.command("list").description("list your tokens in this workspace").action(async (_options, command) => {
3769
+ const globals = globalsOf(command);
3770
+ const data = await clientFor(runtime, globals).call({ method: "GET", path: "/api/v1/tokens" });
3771
+ emit({
3772
+ runtime,
3773
+ globals,
3774
+ data,
3775
+ human: (d) => table(d.tokens.map((t) => ({ ...t, scopes: t.scopes.join(" "), state: t.revoked_at ? "revoked" : "active" })), ["id", "name", "prefix", "scopes", "state", "expires_at", "last_used_at"])
3776
+ });
3777
+ });
3778
+ token.command("revoke <id>").description("revoke a token now").action(async (id, _options, command) => {
3779
+ const globals = globalsOf(command);
3780
+ await confirm({ runtime, globals, question: `Revoke token ${id}?` });
3781
+ const data = await clientFor(runtime, globals).call({
3782
+ method: "DELETE",
3783
+ path: `/api/v1/tokens/${encodeURIComponent(id)}`
3784
+ });
3785
+ emit({ runtime, globals, data, human: (d) => `Revoked token ${d.token.name} (${d.token.id}).` });
3786
+ });
3787
+ };
3788
+
3789
+ // src/approvals.ts
3790
+ var TIMED_OUT = Symbol("timed out");
3791
+ var beforeDeadline = async (runtime, deadline, send) => {
3792
+ const controller = new AbortController;
3793
+ let timer;
3794
+ const expired = new Promise((resolve) => {
3795
+ timer = setTimeout(() => {
3796
+ controller.abort();
3797
+ resolve(TIMED_OUT);
3798
+ }, Math.max(0, deadline - runtime.now().getTime()));
3799
+ });
3800
+ try {
3801
+ return await Promise.race([send(controller.signal), expired]);
3802
+ } catch (error) {
3803
+ if (controller.signal.aborted)
3804
+ return TIMED_OUT;
3805
+ throw error;
3806
+ } finally {
3807
+ clearTimeout(timer);
3808
+ }
3809
+ };
3810
+ var callWithApproval = async (params) => {
3811
+ const { client, request, runtime, globals } = params;
3812
+ const timeout = Number(globals.waitTimeout ?? 900);
3813
+ if (!Number.isFinite(timeout) || timeout <= 0)
3814
+ throw cliError("invalid_input", "--wait-timeout must be a positive number of seconds.");
3815
+ let approvalError;
3816
+ try {
3817
+ return await client.call(request);
3818
+ } catch (error) {
3819
+ if (!(error instanceof CliError) || error.error.type !== "approval_required" || !globals.wait)
3820
+ throw error;
3821
+ approvalError = error;
3822
+ }
3823
+ const details = approvalError.error.details;
3824
+ const id = details?.approval_id;
3825
+ if (typeof id !== "string" || !id)
3826
+ throw approvalError;
3827
+ const url = typeof details?.approval_url === "string" ? details.approval_url : client.url(`/approve/${encodeURIComponent(id)}`);
3828
+ runtime.stderr(`Waiting for approval: ${url}`);
3829
+ const deadline = runtime.now().getTime() + timeout * 1000;
3830
+ const expiresAt = typeof details?.expires_at === "string" ? Date.parse(details.expires_at) : Infinity;
3831
+ while (runtime.now().getTime() < deadline) {
3832
+ if (runtime.now().getTime() >= expiresAt)
3833
+ throw cliError("approval_required", "The approval expired before the call was approved.", details);
3834
+ await runtime.sleep(Math.min(2000, deadline - runtime.now().getTime()));
3835
+ if (runtime.now().getTime() >= deadline)
3836
+ break;
3837
+ const answer = await beforeDeadline(runtime, deadline, (signal) => client.call({ method: "GET", path: `/api/v1/approvals/${encodeURIComponent(id)}`, signal }));
3838
+ if (answer === TIMED_OUT)
3839
+ break;
3840
+ const { approval } = answer;
3841
+ if (approval.status === "approved") {
3842
+ return client.call({ ...request, headers: { ...request.headers, [ASTRAL_APPROVAL_HEADER]: id } });
3843
+ }
3844
+ if (approval.status === "denied")
3845
+ throw cliError("permission_denied", "The call's approval was denied.");
3846
+ if (approval.status === "expired" || approval.status === "consumed") {
3847
+ throw cliError("approval_required", `The approval is ${approval.status}; request a new approval.`, details);
3848
+ }
3849
+ }
3850
+ throw cliError("approval_required", "Timed out waiting for approval.", details);
3851
+ };
3852
+
3853
+ // src/git.ts
3854
+ import { spawn } from "node:child_process";
3855
+ var runGit = ({ args, env, cwd, stdio }) => new Promise((resolve, reject) => {
3856
+ const child = spawn("git", args, {
3857
+ cwd,
3858
+ env: { ...process.env, ...env },
3859
+ stdio: stdio === "inherit" ? "inherit" : ["ignore", "pipe", "inherit"]
3860
+ });
3861
+ let stdout = "";
3862
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => {
3863
+ stdout += chunk;
3864
+ });
3865
+ child.on("error", reject);
3866
+ child.on("close", (code) => resolve({ status: code ?? 1, stdout }));
3867
+ });
3868
+ var shellQuote = (word) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
3869
+ var selfCommand = () => process.argv[1] ? [process.execPath, process.argv[1]] : ["astral"];
3870
+ var parseCredentialRequest = (text) => {
3871
+ const fields = {};
3872
+ for (const line of text.split(`
3873
+ `)) {
3874
+ const at = line.indexOf("=");
3875
+ if (at > 0)
3876
+ fields[line.slice(0, at)] = line.slice(at + 1).replace(/\r$/, "");
3877
+ }
3878
+ return fields;
3879
+ };
3880
+
3881
+ // src/commands/code-git.ts
3882
+ var depsOf = (runtime) => ({
3883
+ git: runtime.git ?? runGit,
3884
+ readStdin: runtime.readStdin ?? (async () => {
3885
+ let text = "";
3886
+ for await (const chunk of process.stdin)
3887
+ text += String(chunk);
3888
+ return text;
3889
+ }),
3890
+ self: selfCommand
3891
+ });
3892
+ var USERNAME_ENV = "ASTRAL_GIT_USERNAME";
3893
+ var PASSWORD_ENV = "ASTRAL_GIT_PASSWORD";
3894
+ var URL_ENV = "ASTRAL_GIT_URL";
3895
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3896
+ var toolPath = (name) => `/api/v1/tools/${encodeURIComponent(name)}`;
3897
+ var readCredentials = async (client, id) => (await client.call({ method: "POST", path: toolPath("code.git_read_credentials"), json: { id } })).credentials;
3898
+ var resolveRepo = async (client, ref) => {
3899
+ if (UUID.test(ref))
3900
+ return { id: ref, name: ref, kind: "astral" };
3901
+ const { repos } = await client.call({
3902
+ method: "POST",
3903
+ path: toolPath("code.list_repos"),
3904
+ json: { q: ref, kind: "astral" }
3905
+ });
3906
+ const matches = repos.filter((repo) => repo.name === ref);
3907
+ if (matches.length === 0)
3908
+ throw cliError("not_found", `No Astral repo named ${ref}.`);
3909
+ if (matches.length > 1) {
3910
+ throw cliError("invalid_input", `More than one repo is named ${ref}. Use the repo id.`, { ids: matches.map((repo) => repo.id) });
3911
+ }
3912
+ return matches[0];
3913
+ };
3914
+ var helperConfig = (params) => {
3915
+ const helper = `!${[...params.self, "--profile", params.profile, "code", "credential", "--repo", params.repoId].map(shellQuote).join(" ")}`;
3916
+ return [`credential.${params.url}.useHttpPath=true`, `credential.${params.url}.helper=`, `credential.${params.url}.helper=${helper}`];
3917
+ };
3918
+ var asFlags = (pairs) => pairs.flatMap((pair) => ["-c", pair]);
3919
+ var cloneConfig = (params) => asFlags([`astral.repoId=${params.repoId}`, `astral.profile=${params.profile}`, ...helperConfig(params)]);
3920
+ var trimSlashes = (path) => path.replace(/^\/+|\/+$/g, "");
3921
+ var matchesRemote = (request, url) => {
3922
+ let remote;
3923
+ try {
3924
+ remote = new URL(url);
3925
+ } catch {
3926
+ return false;
3927
+ }
3928
+ if (!request.protocol || !request.host || request.path === undefined)
3929
+ return false;
3930
+ return request.protocol === remote.protocol.replace(/:$/, "") && request.host.toLowerCase() === remote.host && trimSlashes(request.path) === trimSlashes(decodeURIComponent(remote.pathname));
3931
+ };
3932
+ var gitConfig = async (deps, key) => {
3933
+ const result = await deps.git({ args: ["config", "--get", key], stdio: "pipe" });
3934
+ const value = result.stdout.trim();
3935
+ return result.status === 0 && value ? value : null;
3936
+ };
3937
+ var credentialEnv = (credentials) => ({
3938
+ [USERNAME_ENV]: credentials.username,
3939
+ [PASSWORD_ENV]: credentials.password,
3940
+ [URL_ENV]: credentials.url,
3941
+ GIT_TERMINAL_PROMPT: "0"
3942
+ });
3943
+ var registerCodeGit = (program, runtime) => {
3944
+ const deps = depsOf(runtime);
3945
+ const code = program.commands.find((command) => command.name() === "code") ?? program.command("code").description("Astral repos: clone, push, and the code tools");
3946
+ code.command("clone <repo> [dir]").description("clone an Astral repo (id or name) and set up git credentials for it").action(async (ref, dir, _options, command) => {
3947
+ const globals = globalsOf(command);
3948
+ const client = clientFor(runtime, globals);
3949
+ const repo = await resolveRepo(client, ref);
3950
+ const credentials = await readCredentials(client, repo.id);
3951
+ const target = dir ?? (repo.name === repo.id ? repo.id : repo.name);
3952
+ const config = cloneConfig({ url: credentials.url, repoId: repo.id, profile: client.context.profile, self: deps.self() });
3953
+ const result = await deps.git({
3954
+ args: ["clone", ...config, credentials.url, target],
3955
+ env: { ...runtime.env, ...credentialEnv(credentials) },
3956
+ stdio: "inherit"
3957
+ });
3958
+ if (result.status !== 0)
3959
+ throw cliError("upstream_error", `git clone exited with ${result.status}.`, { git_exit: result.status });
3960
+ emit({
3961
+ runtime,
3962
+ globals,
3963
+ data: { repo_id: repo.id, dir: target, url: credentials.url, default_branch: credentials.default_branch },
3964
+ human: (data) => `Cloned ${repo.name} into ${data.dir}. \`astral code push\` pushes to it.`
3965
+ });
3966
+ });
3967
+ code.command("push [git-args...]").description("push to the Astral repo of this clone (needs approval); args go to git push").allowUnknownOption().option("--repo <id>", "the repo id (default: git config astral.repoId)").option("--no-wait", "exit 10 with the approval link instead of waiting").option("--wait-timeout <seconds>", "how long to wait for approval", "900").action(async (args, options, command) => {
3968
+ const globals = globalsOf(command);
3969
+ const repoId = options.repo ?? await gitConfig(deps, "astral.repoId");
3970
+ if (!repoId)
3971
+ throw cliError("invalid_input", "This is not a clone made by `astral code clone`. Use --repo <id>.");
3972
+ const profile = globals.profile || runtime.env.ASTRAL_PROFILE || (options.repo ? undefined : await gitConfig(deps, "astral.profile") ?? undefined);
3973
+ const client = clientFor(runtime, { ...globals, profile });
3974
+ const { credentials } = await callWithApproval({
3975
+ client,
3976
+ runtime,
3977
+ globals: { ...globals, wait: options.wait, waitTimeout: options.waitTimeout },
3978
+ request: { method: "POST", path: toolPath("code.git_write_credentials"), json: { id: repoId } }
3979
+ });
3980
+ const helper = helperConfig({ url: credentials.url, repoId, profile: client.context.profile, self: deps.self() });
3981
+ const result = await deps.git({
3982
+ args: [...asFlags(helper), "push", ...args],
3983
+ env: { ...runtime.env, ...credentialEnv(credentials) },
3984
+ stdio: "inherit"
3985
+ });
3986
+ if (result.status !== 0)
3987
+ throw cliError("upstream_error", `git push exited with ${result.status}.`, { git_exit: result.status });
3988
+ emit({ runtime, globals, data: { repo_id: repoId, pushed: true }, human: () => "Pushed." });
3989
+ });
3990
+ code.command("credential <operation>").description("git credential helper (git runs it; you do not)").option("--repo <id>", "the repo id").action(async (operation, options, command) => {
3991
+ if (operation !== "get")
3992
+ return;
3993
+ const request = parseCredentialRequest(await deps.readStdin());
3994
+ const globals = globalsOf(command);
3995
+ const credentials = await helperCredentials(runtime, globals, options.repo);
3996
+ if (!credentials || !matchesRemote(request, credentials.url))
3997
+ return;
3998
+ const lines = [`username=${credentials.username}`, `password=${credentials.password}`];
3999
+ const expiry = Date.parse(credentials.expires_at);
4000
+ if (Number.isFinite(expiry))
4001
+ lines.push(`password_expiry_utc=${Math.floor(expiry / 1000)}`);
4002
+ runtime.stdout(`${lines.join(`
4003
+ `)}
4004
+ `);
4005
+ });
4006
+ };
4007
+ var helperCredentials = async (runtime, globals, repoId) => {
4008
+ const username = runtime.env[USERNAME_ENV];
4009
+ const password = runtime.env[PASSWORD_ENV];
4010
+ if (username || password) {
4011
+ const url = runtime.env[URL_ENV];
4012
+ return username && password && url ? { url, username, password, expires_at: "", default_branch: "" } : null;
4013
+ }
4014
+ if (!repoId)
4015
+ return null;
4016
+ return readCredentials(clientFor(runtime, globals), repoId);
4017
+ };
4018
+
4019
+ // src/catalog.ts
4020
+ import { createHash } from "node:crypto";
4021
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
4022
+ import { join as join4 } from "node:path";
4023
+ var catalogPath = (client, env) => {
4024
+ const { profile, apiUrl, workspaceId, token } = client.context;
4025
+ const key = createHash("sha256").update(JSON.stringify([profile, apiUrl, workspaceId, token])).digest("hex");
4026
+ return join4(cacheDir(env), `catalog-${key}.json`);
4027
+ };
4028
+ var readCache = (path) => {
4029
+ try {
4030
+ const cached = JSON.parse(readFileSync3(path, "utf8"));
4031
+ return cached.catalog && Array.isArray(cached.catalog.tools) && typeof cached.catalog.version === "string" ? cached : null;
4032
+ } catch {
4033
+ return null;
4034
+ }
4035
+ };
4036
+ var loadCatalog = async (runtime, globals = {}) => {
4037
+ const client = clientFor(runtime, globals);
4038
+ if (!client.context.token)
4039
+ throw cliError("auth_required", "Sign in to load the tool catalog.");
4040
+ const path = catalogPath(client, runtime.env);
4041
+ const cached = readCache(path);
4042
+ let response;
4043
+ try {
4044
+ response = await client.raw({
4045
+ method: "GET",
4046
+ path: "/api/v1/catalog",
4047
+ ...cached?.etag ? { headers: { "If-None-Match": cached.etag } } : {}
4048
+ });
4049
+ } catch (error) {
4050
+ if (cached && error instanceof CliError && error.error.type === "upstream_error")
4051
+ return cached.catalog;
4052
+ throw error;
4053
+ }
4054
+ if (response.status === 304 && cached)
4055
+ return cached.catalog;
4056
+ if (!response.envelope)
4057
+ throw cliError("upstream_error", "The catalog response has no body or cached catalog.");
4058
+ if (!response.envelope.ok)
4059
+ throw new CliError(response.envelope.error);
4060
+ const catalog = response.envelope.data;
4061
+ try {
4062
+ mkdirSync3(cacheDir(runtime.env), { recursive: true, mode: 448 });
4063
+ writeFileSync3(path, JSON.stringify({ etag: response.headers.get("etag"), catalog }), { mode: 384 });
4064
+ } catch {
4065
+ runtime.stderr("Warning: could not save the tool catalog cache.");
4066
+ }
4067
+ return catalog;
4068
+ };
4069
+
4070
+ // src/commands/tools.ts
4071
+ import { readFile as readFile2 } from "node:fs/promises";
4072
+ var parseInput = (text) => {
4073
+ let input;
4074
+ try {
4075
+ input = JSON.parse(text);
4076
+ } catch {
4077
+ throw cliError("invalid_input", "Input must be valid JSON.");
4078
+ }
4079
+ if (typeof input !== "object" || input === null || Array.isArray(input))
4080
+ throw cliError("invalid_input", "Input must be a JSON object.");
4081
+ return input;
4082
+ };
4083
+ var callInput = async (options) => {
4084
+ if (options.input !== undefined && options.inputFile !== undefined)
4085
+ throw cliError("invalid_input", "Use only one of --input and --input-file.");
4086
+ if (options.inputFile !== undefined) {
4087
+ let text;
4088
+ try {
4089
+ text = options.inputFile === "-" ? await readStdin() : await readFile2(options.inputFile, "utf8");
4090
+ } catch (error) {
4091
+ throw cliError("invalid_input", `Could not read input file: ${error instanceof Error ? error.message : String(error)}`);
4092
+ }
4093
+ return parseInput(text);
4094
+ }
4095
+ return options.input === undefined ? {} : parseInput(options.input);
4096
+ };
4097
+ var registerTools = (program, runtime) => {
4098
+ const tools = program.command("tools").description("browse the tool catalog");
4099
+ tools.command("list").description("list available tools").option("--app <app>", "only tools from this app").action(async (options, command) => {
4100
+ const globals = globalsOf(command);
4101
+ const catalog = await loadCatalog(runtime, globals);
4102
+ const data = catalog.tools.filter((tool) => !options.app || tool.app === options.app);
4103
+ emit({ runtime, globals, data, human: (items) => table(items.map((tool) => ({ ...tool, description: tool.description.split(`
4104
+ `)[0] })), ["name", "access", "approval", "description"]) });
4105
+ });
4106
+ tools.command("describe <app.tool>").description("show a tool's description and input schema").action(async (name, _options, command) => {
4107
+ const globals = globalsOf(command);
4108
+ const catalog = await loadCatalog(runtime, globals);
4109
+ const tool = catalog.tools.find((item) => item.name === name);
4110
+ if (!tool)
4111
+ throw cliError("not_found", `No tool named ${name}.`);
4112
+ if (globals.json) {
4113
+ runtime.stdout(JSON.stringify(tool, null, 2));
4114
+ return;
4115
+ }
4116
+ emit({ runtime, globals, data: tool, human: (item) => `${item.name}
4117
+ ${item.description}
4118
+
4119
+ Input schema:
4120
+ ${JSON.stringify(item.input_schema, null, 2)}` });
4121
+ });
4122
+ program.command("call <app.tool>").description("call a tool with JSON input").option("--input <json>", "input as a JSON object").option("--input-file <path>", "read JSON from a file, or - for stdin").action(async (name, options, command) => {
4123
+ if (!/^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$/.test(name))
4124
+ throw cliError("invalid_input", "Use a tool name in app.tool form.");
4125
+ const globals = globalsOf(command);
4126
+ const data = await callWithApproval({
4127
+ client: clientFor(runtime, globals),
4128
+ runtime,
4129
+ globals,
4130
+ request: { method: "POST", path: `/api/v1/tools/${encodeURIComponent(name)}`, json: await callInput(options) }
4131
+ });
4132
+ emit({ runtime, globals, data });
4133
+ });
4134
+ };
4135
+
4136
+ // src/commands/generated.ts
4137
+ var object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4138
+ var kebab = (name) => name.replace(/_/g, "-");
4139
+ var validateValue = (name, value, schema) => {
4140
+ const type = schema.type;
4141
+ const valid = type === "string" ? typeof value === "string" : type === "number" ? typeof value === "number" && Number.isFinite(value) : type === "integer" ? typeof value === "number" && Number.isInteger(value) : type === "boolean" ? typeof value === "boolean" : type === "array" ? Array.isArray(value) : type === "object" ? object(value) : true;
4142
+ if (!valid)
4143
+ throw cliError("invalid_input", `${name} must be ${type}.`);
4144
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
4145
+ throw cliError("invalid_input", `${name} must be one of: ${schema.enum.map(String).join(", ")}.`);
4146
+ }
4147
+ if (Array.isArray(value) && object(schema.items)) {
4148
+ for (const item of value)
4149
+ validateValue(name, item, schema.items);
4150
+ }
4151
+ };
4152
+ var flagValue = (name, text, schema) => {
4153
+ let value = text;
4154
+ if (schema.type === "number" || schema.type === "integer")
4155
+ value = text.trim() ? Number(text) : NaN;
4156
+ if (schema.type === "boolean") {
4157
+ if (text !== "true" && text !== "false")
4158
+ throw cliError("invalid_input", `${name} must be true or false.`);
4159
+ value = text === "true";
4160
+ }
4161
+ if (schema.type === "object" || schema.type === "array") {
4162
+ try {
4163
+ value = JSON.parse(text);
4164
+ } catch {
4165
+ throw cliError("invalid_input", `${name} must be valid JSON.`);
4166
+ }
4167
+ }
4168
+ validateValue(name, value, schema);
4169
+ return value;
4170
+ };
4171
+ var addFlags = (command, tool) => {
4172
+ const properties = object(tool.input_schema.properties) ? tool.input_schema.properties : {};
4173
+ const bindings = [];
4174
+ for (const [name, schema] of Object.entries(properties)) {
4175
+ if (!object(schema))
4176
+ continue;
4177
+ const flag = `--${kebab(name)}`;
4178
+ if (command.options.some((option) => option.long === flag))
4179
+ continue;
4180
+ const description = typeof schema.description === "string" ? schema.description : name;
4181
+ const option = new Option(schema.type === "boolean" ? flag : `${flag} <value>`, description);
4182
+ if (schema.type === "array") {
4183
+ const items = object(schema.items) ? schema.items : {};
4184
+ option.argParser((text, previous) => [...Array.isArray(previous) ? previous : [], flagValue(flag, text, items)]);
4185
+ } else if (schema.type !== "boolean") {
4186
+ option.argParser((text) => flagValue(flag, text, schema));
4187
+ }
4188
+ command.addOption(option);
4189
+ bindings.push({ name, schema, option });
4190
+ if (schema.type === "boolean")
4191
+ command.addOption(new Option(`--no-${kebab(name)}`, `disable ${name}`));
4192
+ }
4193
+ return bindings;
4194
+ };
4195
+ var registerTool = (command, tool, runtime) => {
4196
+ command.description(tool.description).option("--input <json>", "JSON input, overridden by explicit flags");
4197
+ const bindings = addFlags(command, tool);
4198
+ command.action(async (options, called) => {
4199
+ const input = typeof options.input === "string" ? { ...parseInput(options.input) } : {};
4200
+ for (const { name, option } of bindings) {
4201
+ const key = option.attributeName();
4202
+ if (called.getOptionValueSource(key) === "cli")
4203
+ input[name] = options[key];
4204
+ }
4205
+ const required = Array.isArray(tool.input_schema.required) ? tool.input_schema.required : [];
4206
+ for (const name of required) {
4207
+ if (typeof name === "string" && !Object.hasOwn(input, name))
4208
+ throw cliError("invalid_input", `Missing required input ${name}. Use --${kebab(name)} or --input.`);
4209
+ }
4210
+ const properties = object(tool.input_schema.properties) ? tool.input_schema.properties : {};
4211
+ for (const [name, schema] of Object.entries(properties)) {
4212
+ if (object(schema) && Object.hasOwn(input, name))
4213
+ validateValue(name, input[name], schema);
4214
+ }
4215
+ const globals = globalsOf(called);
4216
+ const data = await callWithApproval({
4217
+ client: clientFor(runtime, globals),
4218
+ runtime,
4219
+ globals,
4220
+ request: { method: "POST", path: `/api/v1/tools/${encodeURIComponent(tool.name)}`, json: input }
4221
+ });
4222
+ emit({ runtime, globals, data });
4223
+ });
4224
+ };
4225
+ var findCommand = (program, name) => program.commands.find((command) => command.name() === name || command.aliases().includes(name));
4226
+ var addGeneratedCommands = (program, runtime, catalog) => {
4227
+ for (const tool of catalog.tools) {
4228
+ let app = findCommand(program, tool.app);
4229
+ if (app && app.commands.length === 0)
4230
+ continue;
4231
+ if (!app)
4232
+ app = program.command(tool.app).description(`tools from ${tool.app}`);
4233
+ const name = kebab(tool.tool);
4234
+ if (findCommand(app, name))
4235
+ continue;
4236
+ registerTool(app.command(name), tool, runtime);
4237
+ }
4238
+ };
4239
+ var registerGenerated = async (program, runtime, argv) => {
4240
+ const { operands } = program.parseOptions(argv);
4241
+ const name = operands[0] === "help" ? operands[1] : operands[0];
4242
+ if (!name || argv.includes("--version") || argv.includes("-V"))
4243
+ return;
4244
+ const app = findCommand(program, name);
4245
+ const toolName = operands[0] === "help" ? operands[2] : operands[1];
4246
+ if (app && (app.commands.length === 0 || !toolName || findCommand(app, toolName)))
4247
+ return;
4248
+ addGeneratedCommands(program, runtime, await loadCatalog(runtime, globalsOf(program)));
4249
+ };
4250
+
4251
+ // src/commands/project.ts
4252
+ import { existsSync as existsSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
4253
+ import { join as join6 } from "node:path";
4254
+
4255
+ // src/project.ts
4256
+ import { existsSync, readFileSync as readFileSync4 } from "node:fs";
4257
+ import { dirname, join as join5, resolve } from "node:path";
4258
+ var projectPath = (cwd) => {
4259
+ let directory = resolve(cwd);
4260
+ while (true) {
4261
+ const path = join5(directory, ".astral", "project.json");
4262
+ if (existsSync(path))
4263
+ return path;
4264
+ const parent = dirname(directory);
4265
+ if (parent === directory)
4266
+ return;
4267
+ directory = parent;
4268
+ }
4269
+ };
4270
+ var findProject = (cwd) => {
4271
+ const path = projectPath(cwd);
4272
+ if (!path)
4273
+ return null;
4274
+ let value;
4275
+ try {
4276
+ value = JSON.parse(readFileSync4(path, "utf8"));
4277
+ } catch {
4278
+ throw cliError("invalid_input", `Could not read ${path}. Run astral unlink to remove the link.`);
4279
+ }
4280
+ if (typeof value !== "object" || value === null || !("site_id" in value) || typeof value.site_id !== "string" || !value.site_id.trim()) {
4281
+ throw cliError("invalid_input", `Invalid project link in ${path}: site_id must be a non-empty string.`);
4282
+ }
4283
+ for (const key of ["site_name", "repo_id", "workspace_id"]) {
4284
+ if (key in value && typeof value[key] !== "string") {
4285
+ throw cliError("invalid_input", `Invalid project link in ${path}: ${key} must be a string.`);
4286
+ }
4287
+ }
4288
+ return { directory: dirname(dirname(path)), path, project: value };
4289
+ };
4290
+ var projectSiteId = (cwd) => findProject(cwd)?.project.site_id;
4291
+
4292
+ // src/commands/project.ts
4293
+ var finalDeployment = (status) => ["ready", "error", "canceled"].includes(status);
4294
+ var siteCall = (client, tool, input) => client.call({ method: "POST", path: `/api/v1/tools/sites.${tool}`, json: input });
4295
+ var deploymentState = async (client, id, deploymentId) => {
4296
+ const site = await siteCall(client, "status", { id });
4297
+ if (!deploymentId || site.latest_deployment?.id === deploymentId) {
4298
+ return { site, deployment: site.latest_deployment };
4299
+ }
4300
+ const history = await siteCall(client, "list_deployments", { id, limit: 100 });
4301
+ const deployment = history.deployments.find((row) => row.id === deploymentId);
4302
+ if (!deployment)
4303
+ throw cliError("not_found", `Deployment ${deploymentId} is not in the site's retained history.`);
4304
+ return { site, deployment };
4305
+ };
4306
+ var resolveSite = async (client, runtime, requested) => {
4307
+ if (!requested && !runtime.interactive)
4308
+ throw cliError("invalid_input", "Pass --site <id-or-name> to link in a non-interactive terminal.");
4309
+ if (requested && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(requested)) {
4310
+ return siteCall(client, "get", { id: requested });
4311
+ }
4312
+ const { deployments } = await siteCall(client, "list", {});
4313
+ let chosen;
4314
+ if (requested) {
4315
+ const matches = deployments.filter((site) => site.id === requested || site.name === requested);
4316
+ if (matches.length > 1)
4317
+ throw cliError("invalid_input", `More than one site is named ${requested}. Pass its id instead.`);
4318
+ chosen = matches[0];
4319
+ if (!chosen)
4320
+ throw cliError("not_found", `No site has the id or exact name ${requested}.`);
4321
+ } else {
4322
+ const index = await select({ runtime, question: "Link which site?", choices: deployments.map((site) => `${site.name} (${site.id})`) });
4323
+ chosen = deployments[index];
4324
+ }
4325
+ if (!chosen)
4326
+ throw cliError("not_found", "No site was selected.");
4327
+ return siteCall(client, "get", { id: chosen.id });
4328
+ };
4329
+ var writeProject = (cwd, site, workspaceId) => {
4330
+ const workspace = site.workspace_id ?? workspaceId;
4331
+ const project = {
4332
+ site_id: site.id,
4333
+ site_name: site.name,
4334
+ ...site.source?.repo_id ? { repo_id: site.source.repo_id } : {},
4335
+ ...workspace ? { workspace_id: workspace } : {}
4336
+ };
4337
+ const directory = join6(cwd, ".astral");
4338
+ mkdirSync4(directory, { recursive: true });
4339
+ writeFileSync4(join6(directory, "project.json"), `${JSON.stringify(project, null, 2)}
4340
+ `, { mode: 384 });
4341
+ const ignorePath = join6(cwd, ".gitignore");
4342
+ if (existsSync2(ignorePath)) {
4343
+ const ignore = readFileSync5(ignorePath, "utf8");
4344
+ if (!ignore.split(/\r?\n/).some((line) => /^\/?\.astral\/?$/.test(line.trim()))) {
4345
+ writeFileSync4(ignorePath, `${ignore}${ignore && !ignore.endsWith(`
4346
+ `) ? `
4347
+ ` : ""}.astral
4348
+ `);
4349
+ }
4350
+ }
4351
+ return project;
4352
+ };
4353
+ var deploy = async (client, runtime, options, globals) => {
4354
+ const id = options.site ?? projectSiteId(process.cwd());
4355
+ if (!id)
4356
+ throw cliError("invalid_input", "Pass --site <id>, or link this folder with astral link first.");
4357
+ if (options.prod && options.branch) {
4358
+ throw cliError("invalid_input", "--branch is only supported for previews. Production deploys use the site's configured branch.");
4359
+ }
4360
+ const result = await callWithApproval({
4361
+ client,
4362
+ runtime,
4363
+ globals,
4364
+ request: {
4365
+ method: "POST",
4366
+ path: `/api/v1/tools/sites.${options.prod ? "deploy" : "deploy_preview"}`,
4367
+ json: { id, ...options.branch ? { branch: options.branch } : {} }
4368
+ }
4369
+ });
4370
+ if (options.detach || !result.deployment_id || !result.deployment_status)
4371
+ return result;
4372
+ let error = null;
4373
+ while (!finalDeployment(result.deployment_status)) {
4374
+ await runtime.sleep(2000);
4375
+ const state = await deploymentState(client, id, result.deployment_id);
4376
+ if (!state.deployment)
4377
+ throw cliError("upstream_error", "The API did not return the deployment's status.");
4378
+ result.deployment_status = state.deployment.status;
4379
+ error = state.deployment.error;
4380
+ if (options.prod) {
4381
+ result.status = state.site.status;
4382
+ result.production_url = state.site.production_url;
4383
+ } else if (state.deployment.url) {
4384
+ result.url = state.deployment.url;
4385
+ }
4386
+ }
4387
+ if (result.deployment_status !== "ready") {
4388
+ throw cliError("upstream_error", `Deployment ${result.deployment_id} ended ${result.deployment_status}${error ? `: ${error}` : "."}`, {
4389
+ deployment_id: result.deployment_id,
4390
+ deployment_status: result.deployment_status,
4391
+ error
4392
+ });
4393
+ }
4394
+ return result;
4395
+ };
4396
+ var registerProject = (program, runtime) => {
4397
+ program.command("link").description("link this folder to a site").option("--site <id-or-name>", "the site id or exact name").action(async (options, command) => {
4398
+ const globals = globalsOf(command);
4399
+ const client = clientFor(runtime, globals);
4400
+ const site = await resolveSite(client, runtime, options.site);
4401
+ const project = writeProject(process.cwd(), site, client.context.workspaceId);
4402
+ emit({ runtime, globals, data: project, human: () => `Linked ${site.name} (${site.id}).` });
4403
+ });
4404
+ program.command("unlink").description("remove this folder's site link").action(async (_options, command) => {
4405
+ const linked = projectPath(process.cwd());
4406
+ if (linked)
4407
+ rmSync2(linked);
4408
+ emit({ runtime, globals: globalsOf(command), data: { removed: Boolean(linked) }, human: () => linked ? "Site link removed." : "This folder is not linked." });
4409
+ });
4410
+ program.command("open").description("print the linked site's production URL").action(async (_options, command) => {
4411
+ const id = projectSiteId(process.cwd());
4412
+ if (!id)
4413
+ throw cliError("invalid_input", "This folder is not linked. Run astral link --site <id-or-name> first.");
4414
+ const globals = globalsOf(command);
4415
+ const site = await siteCall(clientFor(runtime, globals), "get", { id });
4416
+ if (!site.production_url)
4417
+ throw cliError("not_found", "This site has no production URL. Deploy it first.");
4418
+ emit({ runtime, globals, data: { url: site.production_url }, human: (data) => data.url });
4419
+ });
4420
+ program.command("deploy").description("deploy the linked site (preview unless --prod)").option("--prod", "deploy to production").option("--branch <branch>", "the branch for a preview").option("--site <id>", "override the linked site").option("--detach", "return once the deployment starts; do not wait for the build").action(async (options, command) => {
4421
+ const globals = globalsOf(command);
4422
+ const data = await deploy(clientFor(runtime, globals), runtime, options, globals);
4423
+ emit({
4424
+ runtime,
4425
+ globals,
4426
+ data,
4427
+ human: (result) => [result.deployment_status, result.url ?? result.production_url].filter(Boolean).join(`
4428
+ `)
4429
+ });
4430
+ });
4431
+ };
4432
+
4433
+ // src/commands/sites-logs.ts
4434
+ var logs = async (runtime, command, options) => {
4435
+ const globals = globalsOf(command);
4436
+ const client = clientFor(runtime, globals);
4437
+ const seen = new Map;
4438
+ const print = (lines) => {
4439
+ const counts = new Map;
4440
+ for (const line of lines) {
4441
+ const occurrence = (counts.get(line) ?? 0) + 1;
4442
+ counts.set(line, occurrence);
4443
+ if (options.follow && occurrence <= (seen.get(line) ?? 0))
4444
+ continue;
4445
+ runtime.stdout(globals.json ? JSON.stringify({ ok: true, data: { line } }) : line);
4446
+ }
4447
+ for (const [line, count] of counts)
4448
+ seen.set(line, Math.max(count, seen.get(line) ?? 0));
4449
+ };
4450
+ if (!options.follow) {
4451
+ const result = await siteCall(client, "logs", {
4452
+ id: options.site,
4453
+ ...options.deployment ? { deployment_id: options.deployment } : {}
4454
+ });
4455
+ print(result.lines);
4456
+ return;
4457
+ }
4458
+ let stopped = false;
4459
+ let interrupt = () => {};
4460
+ const interrupted = new Promise((resolve) => {
4461
+ interrupt = resolve;
4462
+ });
4463
+ const stop = () => {
4464
+ stopped = true;
4465
+ interrupt();
4466
+ };
4467
+ process.once("SIGINT", stop);
4468
+ try {
4469
+ let deploymentId = options.deployment;
4470
+ while (!stopped) {
4471
+ const state = await deploymentState(client, options.site, deploymentId);
4472
+ deploymentId ??= state.deployment?.id;
4473
+ if (!deploymentId)
4474
+ throw cliError("not_found", "This site has no deployment to follow.");
4475
+ if (stopped)
4476
+ break;
4477
+ const result = await siteCall(client, "logs", { id: options.site, deployment_id: deploymentId });
4478
+ if (stopped)
4479
+ break;
4480
+ print(result.lines);
4481
+ if (state.deployment && finalDeployment(state.deployment.status))
4482
+ break;
4483
+ await Promise.race([runtime.sleep(2000), interrupted]);
4484
+ }
4485
+ } finally {
4486
+ process.removeListener("SIGINT", stop);
4487
+ }
4488
+ };
4489
+ var registerSitesLogs = (program, runtime) => {
4490
+ const sites = program.commands.find((command) => command.name() === "sites") ?? program.command("sites").description("manage sites");
4491
+ const generated = sites.commands.find((command) => command.name() === "logs");
4492
+ if (generated)
4493
+ sites.commands.splice(sites.commands.indexOf(generated), 1);
4494
+ sites.command("logs").description("read deployment logs, or follow a build to completion").requiredOption("--site <id>", "the site id").option("--follow", "poll every two seconds until the deployment finishes").option("--deployment <id>", "a retained deployment id (default: latest)").action(async (options, command) => logs(runtime, command, options));
4495
+ };
4496
+
4497
+ // src/commands/workspace.ts
4498
+ var registerWorkspace = (program, runtime) => {
4499
+ const workspace = program.command("workspace").description("switch between signed-in workspaces (profiles)");
4500
+ workspace.command("list").description("list profiles").action((_options, command) => {
4501
+ const globals = globalsOf(command);
4502
+ const config = readConfig(runtime.env);
4503
+ const current = resolveContext({ profile: globals.profile, env: runtime.env }).profile;
4504
+ const names = new Set(Object.keys(config.profiles));
4505
+ names.add(current);
4506
+ const profiles = [...names].sort().map((name) => {
4507
+ const context = resolveContext({ profile: name, env: { ...runtime.env, ASTRAL_TOKEN: undefined } });
4508
+ return {
4509
+ profile: name,
4510
+ current: name === current,
4511
+ workspace_id: context.workspaceId,
4512
+ api_url: context.apiUrl,
4513
+ signed_in: readCredential(name, runtime.env) !== null
4514
+ };
4515
+ });
4516
+ emit({
4517
+ runtime,
4518
+ globals,
4519
+ data: { profiles },
4520
+ human: (data) => table(data.profiles.map((p) => ({ ...p, profile: p.current ? `* ${p.profile}` : ` ${p.profile}` })), ["profile", "workspace_id", "api_url", "signed_in"])
4521
+ });
4522
+ });
4523
+ workspace.command("use <profile>").description("make a profile the current one").action((name, _options, command) => {
4524
+ const globals = globalsOf(command);
4525
+ const config = readConfig(runtime.env);
4526
+ if (!config.profiles[name] && !readCredential(name, runtime.env)) {
4527
+ throw cliError("not_found", `No profile named ${name}. Run \`astral login --profile ${name}\` first.`);
4528
+ }
4529
+ writeConfig({ ...config, current_profile: name }, runtime.env);
4530
+ emit({ runtime, globals, data: { current_profile: name }, human: () => `Now using profile ${name}.` });
4531
+ });
4532
+ workspace.command("current").description("show the profile, workspace and API this shell uses").action((_options, command) => {
4533
+ const globals = globalsOf(command);
4534
+ const context = resolveContext({ profile: globals.profile, env: runtime.env });
4535
+ const data = {
4536
+ profile: context.profile,
4537
+ workspace_id: context.workspaceId,
4538
+ api_url: context.apiUrl,
4539
+ token_source: context.tokenSource
4540
+ };
4541
+ emit({
4542
+ runtime,
4543
+ globals,
4544
+ data,
4545
+ human: (d) => [`profile: ${d.profile}`, `workspace: ${d.workspace_id ?? "-"}`, `api: ${d.api_url}`, `token: ${d.token_source ?? "none"}`].join(`
4546
+ `)
4547
+ });
4548
+ });
4549
+ };
4550
+
4551
+ // src/main.ts
4552
+ var buildProgram = async (runtime) => {
4553
+ const program = new Command("astral").description("The Astral command line. Every Astral tool, from a terminal or an agent.").version(package_default.version).option("--json", "print the v1 JSON envelope").option("--profile <name>", "use this profile (default: ASTRAL_PROFILE, then the current profile)").option("-y, --yes", "answer yes to every confirmation").option("--wait", "wait for a person to approve a tool call").option("--wait-timeout <seconds>", "maximum approval wait in seconds", "900").showHelpAfterError().configureOutput({ writeOut: runtime.stdout, writeErr: runtime.stderr }).exitOverride();
4554
+ registerAuth(program, runtime);
4555
+ registerWorkspace(program, runtime);
4556
+ registerCodeGit(program, runtime);
4557
+ registerTools(program, runtime);
4558
+ registerProject(program, runtime);
4559
+ registerSitesLogs(program, runtime);
4560
+ return program;
4561
+ };
4562
+ var run = async (argv, runtime) => {
4563
+ const json = argv.includes("--json");
4564
+ try {
4565
+ const program = await buildProgram(runtime);
4566
+ await registerGenerated(program, runtime, argv);
4567
+ await program.parseAsync(argv, { from: "user" });
4568
+ return EXIT.ok;
4569
+ } catch (error) {
4570
+ if (error instanceof CommanderError) {
4571
+ return error.exitCode === 0 ? EXIT.ok : EXIT.invalid_input;
4572
+ }
4573
+ if (error instanceof CliError) {
4574
+ emitError({ runtime, json, error: error.error });
4575
+ return error.exitCode;
4576
+ }
4577
+ const message = error instanceof Error ? error.message : String(error);
4578
+ emitError({ runtime, json, error: { type: "upstream_error", message } });
4579
+ return EXIT.failure;
4580
+ }
4581
+ };
4582
+
4583
+ // src/cli.ts
4584
+ process.exitCode = await run(process.argv.slice(2), defaultRuntime());