@nivora/matrix 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @nivora/matrix might be problematic. Click here for more details.

Files changed (134) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/app-path-routes-manifest.json +12 -0
  3. package/.next/build-manifest.json +20 -0
  4. package/.next/diagnostics/build-diagnostics.json +6 -0
  5. package/.next/diagnostics/framework.json +1 -0
  6. package/.next/export-marker.json +6 -0
  7. package/.next/images-manifest.json +66 -0
  8. package/.next/next-minimal-server.js.nft.json +1 -0
  9. package/.next/next-server.js.nft.json +1 -0
  10. package/.next/package.json +1 -0
  11. package/.next/prerender-manifest.json +90 -0
  12. package/.next/react-loadable-manifest.json +1 -0
  13. package/.next/required-server-files.js +165 -0
  14. package/.next/required-server-files.json +165 -0
  15. package/.next/routes-manifest.json +109 -0
  16. package/.next/server/app/_global-error/page.js +3 -0
  17. package/.next/server/app/_global-error/page.js.nft.json +1 -0
  18. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -0
  19. package/.next/server/app/_global-error.html +2 -0
  20. package/.next/server/app/_global-error.meta +16 -0
  21. package/.next/server/app/_global-error.rsc +12 -0
  22. package/.next/server/app/_global-error.segments/_full.segment.rsc +12 -0
  23. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +5 -0
  24. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +4 -0
  25. package/.next/server/app/_global-error.segments/_head.segment.rsc +5 -0
  26. package/.next/server/app/_global-error.segments/_index.segment.rsc +4 -0
  27. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -0
  28. package/.next/server/app/_not-found/page.js +2 -0
  29. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  30. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
  31. package/.next/server/app/_not-found.html +1 -0
  32. package/.next/server/app/_not-found.meta +16 -0
  33. package/.next/server/app/_not-found.rsc +15 -0
  34. package/.next/server/app/_not-found.segments/_full.segment.rsc +15 -0
  35. package/.next/server/app/_not-found.segments/_head.segment.rsc +6 -0
  36. package/.next/server/app/_not-found.segments/_index.segment.rsc +6 -0
  37. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -0
  38. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +4 -0
  39. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -0
  40. package/.next/server/app/builder/page.js +24 -0
  41. package/.next/server/app/builder/page.js.nft.json +1 -0
  42. package/.next/server/app/builder/page_client-reference-manifest.js +1 -0
  43. package/.next/server/app/favicon.ico/route.js +1 -0
  44. package/.next/server/app/favicon.ico/route.js.nft.json +1 -0
  45. package/.next/server/app/favicon.ico.body +0 -0
  46. package/.next/server/app/favicon.ico.meta +1 -0
  47. package/.next/server/app/guide/page.js +2 -0
  48. package/.next/server/app/guide/page.js.nft.json +1 -0
  49. package/.next/server/app/guide/page_client-reference-manifest.js +1 -0
  50. package/.next/server/app/matrix/page.js +2 -0
  51. package/.next/server/app/matrix/page.js.nft.json +1 -0
  52. package/.next/server/app/matrix/page_client-reference-manifest.js +1 -0
  53. package/.next/server/app/page.js +2 -0
  54. package/.next/server/app/page.js.nft.json +1 -0
  55. package/.next/server/app/page_client-reference-manifest.js +1 -0
  56. package/.next/server/app/releases/[id]/page.js +51 -0
  57. package/.next/server/app/releases/[id]/page.js.nft.json +1 -0
  58. package/.next/server/app/releases/[id]/page_client-reference-manifest.js +1 -0
  59. package/.next/server/app/releases/page.js +34 -0
  60. package/.next/server/app/releases/page.js.nft.json +1 -0
  61. package/.next/server/app/releases/page_client-reference-manifest.js +1 -0
  62. package/.next/server/app/specs/[id]/page.js +2 -0
  63. package/.next/server/app/specs/[id]/page.js.nft.json +1 -0
  64. package/.next/server/app/specs/[id]/page_client-reference-manifest.js +1 -0
  65. package/.next/server/app-paths-manifest.json +12 -0
  66. package/.next/server/chunks/13.js +1 -0
  67. package/.next/server/chunks/135.js +34 -0
  68. package/.next/server/chunks/390.js +1 -0
  69. package/.next/server/chunks/445.js +22 -0
  70. package/.next/server/chunks/471.js +13 -0
  71. package/.next/server/chunks/476.js +23 -0
  72. package/.next/server/chunks/530.js +72 -0
  73. package/.next/server/chunks/870.js +1 -0
  74. package/.next/server/functions-config-manifest.json +4 -0
  75. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  76. package/.next/server/middleware-build-manifest.js +1 -0
  77. package/.next/server/middleware-manifest.json +6 -0
  78. package/.next/server/middleware-react-loadable-manifest.js +1 -0
  79. package/.next/server/next-font-manifest.js +1 -0
  80. package/.next/server/next-font-manifest.json +1 -0
  81. package/.next/server/pages/404.html +1 -0
  82. package/.next/server/pages/500.html +2 -0
  83. package/.next/server/pages-manifest.json +4 -0
  84. package/.next/server/server-reference-manifest.js +1 -0
  85. package/.next/server/server-reference-manifest.json +1 -0
  86. package/.next/server/webpack-runtime.js +1 -0
  87. package/.next/static/8ZUFcYHRSRlY1FYWZ33gH/_buildManifest.js +1 -0
  88. package/.next/static/8ZUFcYHRSRlY1FYWZ33gH/_ssgManifest.js +1 -0
  89. package/.next/static/chunks/4bd1b696-67e30520d621c4dd.js +1 -0
  90. package/.next/static/chunks/500-b84d19d842172eba.js +1 -0
  91. package/.next/static/chunks/794-9353bb3ab9a73e90.js +2 -0
  92. package/.next/static/chunks/app/_global-error/page-aba28f88d5781771.js +1 -0
  93. package/.next/static/chunks/app/_not-found/page-90fe62e7982fba87.js +1 -0
  94. package/.next/static/chunks/app/builder/page-e10754eb65a4f784.js +10 -0
  95. package/.next/static/chunks/app/guide/page-9c9dff9c5e3ddefe.js +1 -0
  96. package/.next/static/chunks/app/layout-550e25f5579f1a32.js +1 -0
  97. package/.next/static/chunks/app/matrix/page-b2418abb52a7acd8.js +1 -0
  98. package/.next/static/chunks/app/page-9c9dff9c5e3ddefe.js +1 -0
  99. package/.next/static/chunks/app/releases/[id]/page-d8069a1802686478.js +1 -0
  100. package/.next/static/chunks/app/releases/page-26a520d9789e69f5.js +1 -0
  101. package/.next/static/chunks/app/specs/[id]/page-7065af5d4d103f16.js +1 -0
  102. package/.next/static/chunks/framework-d7de93249215fb06.js +1 -0
  103. package/.next/static/chunks/main-17e3a04cf2f94dca.js +5 -0
  104. package/.next/static/chunks/main-app-6d93e914b4a54c7e.js +1 -0
  105. package/.next/static/chunks/next/dist/client/components/builtin/app-error-aba28f88d5781771.js +1 -0
  106. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-aba28f88d5781771.js +1 -0
  107. package/.next/static/chunks/next/dist/client/components/builtin/global-error-ebbdf863aa6a4349.js +1 -0
  108. package/.next/static/chunks/next/dist/client/components/builtin/not-found-aba28f88d5781771.js +1 -0
  109. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-aba28f88d5781771.js +1 -0
  110. package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  111. package/.next/static/chunks/webpack-650bc85863e2a9e7.js +1 -0
  112. package/.next/static/css/f29e518c867dffaa.css +1 -0
  113. package/.next/trace-build +1 -0
  114. package/.next/types/app/builder/page.ts +86 -0
  115. package/.next/types/app/guide/page.ts +86 -0
  116. package/.next/types/app/layout.ts +86 -0
  117. package/.next/types/app/matrix/page.ts +86 -0
  118. package/.next/types/app/page.ts +86 -0
  119. package/.next/types/app/releases/[id]/page.ts +86 -0
  120. package/.next/types/app/releases/page.ts +86 -0
  121. package/.next/types/app/specs/[id]/page.ts +86 -0
  122. package/.next/types/package.json +1 -0
  123. package/.next/types/routes.d.ts +63 -0
  124. package/.next/types/validator.ts +115 -0
  125. package/README.md +185 -0
  126. package/bin/cli.js +3650 -0
  127. package/bin/cli.ts +170 -0
  128. package/next.config.ts +11 -0
  129. package/package.json +59 -0
  130. package/public/file.svg +1 -0
  131. package/public/globe.svg +1 -0
  132. package/public/next.svg +1 -0
  133. package/public/vercel.svg +1 -0
  134. package/public/window.svg +1 -0
package/bin/cli.js ADDED
@@ -0,0 +1,3650 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import { createRequire } from "node:module";
4
+ var __create = Object.create;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __toESM = (mod, isNodeMode, target) => {
10
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
11
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
12
+ for (let key of __getOwnPropNames(mod))
13
+ if (!__hasOwnProp.call(to, key))
14
+ __defProp(to, key, {
15
+ get: () => mod[key],
16
+ enumerable: true
17
+ });
18
+ return to;
19
+ };
20
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
21
+ var __export = (target, all) => {
22
+ for (var name in all)
23
+ __defProp(target, name, {
24
+ get: all[name],
25
+ enumerable: true,
26
+ configurable: true,
27
+ set: (newValue) => all[name] = () => newValue
28
+ });
29
+ };
30
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
31
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
32
+
33
+ // node_modules/commander/lib/error.js
34
+ var require_error = __commonJS((exports) => {
35
+ class CommanderError extends Error {
36
+ constructor(exitCode, code, message) {
37
+ super(message);
38
+ Error.captureStackTrace(this, this.constructor);
39
+ this.name = this.constructor.name;
40
+ this.code = code;
41
+ this.exitCode = exitCode;
42
+ this.nestedError = undefined;
43
+ }
44
+ }
45
+
46
+ class InvalidArgumentError extends CommanderError {
47
+ constructor(message) {
48
+ super(1, "commander.invalidArgument", message);
49
+ Error.captureStackTrace(this, this.constructor);
50
+ this.name = this.constructor.name;
51
+ }
52
+ }
53
+ exports.CommanderError = CommanderError;
54
+ exports.InvalidArgumentError = InvalidArgumentError;
55
+ });
56
+
57
+ // node_modules/commander/lib/argument.js
58
+ var require_argument = __commonJS((exports) => {
59
+ var { InvalidArgumentError } = require_error();
60
+
61
+ class Argument {
62
+ constructor(name, description) {
63
+ this.description = description || "";
64
+ this.variadic = false;
65
+ this.parseArg = undefined;
66
+ this.defaultValue = undefined;
67
+ this.defaultValueDescription = undefined;
68
+ this.argChoices = undefined;
69
+ switch (name[0]) {
70
+ case "<":
71
+ this.required = true;
72
+ this._name = name.slice(1, -1);
73
+ break;
74
+ case "[":
75
+ this.required = false;
76
+ this._name = name.slice(1, -1);
77
+ break;
78
+ default:
79
+ this.required = true;
80
+ this._name = name;
81
+ break;
82
+ }
83
+ if (this._name.endsWith("...")) {
84
+ this.variadic = true;
85
+ this._name = this._name.slice(0, -3);
86
+ }
87
+ }
88
+ name() {
89
+ return this._name;
90
+ }
91
+ _collectValue(value, previous) {
92
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
93
+ return [value];
94
+ }
95
+ previous.push(value);
96
+ return previous;
97
+ }
98
+ default(value, description) {
99
+ this.defaultValue = value;
100
+ this.defaultValueDescription = description;
101
+ return this;
102
+ }
103
+ argParser(fn) {
104
+ this.parseArg = fn;
105
+ return this;
106
+ }
107
+ choices(values) {
108
+ this.argChoices = values.slice();
109
+ this.parseArg = (arg, previous) => {
110
+ if (!this.argChoices.includes(arg)) {
111
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
112
+ }
113
+ if (this.variadic) {
114
+ return this._collectValue(arg, previous);
115
+ }
116
+ return arg;
117
+ };
118
+ return this;
119
+ }
120
+ argRequired() {
121
+ this.required = true;
122
+ return this;
123
+ }
124
+ argOptional() {
125
+ this.required = false;
126
+ return this;
127
+ }
128
+ }
129
+ function humanReadableArgName(arg) {
130
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
131
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
132
+ }
133
+ exports.Argument = Argument;
134
+ exports.humanReadableArgName = humanReadableArgName;
135
+ });
136
+
137
+ // node_modules/commander/lib/help.js
138
+ var require_help = __commonJS((exports) => {
139
+ var { humanReadableArgName } = require_argument();
140
+
141
+ class Help {
142
+ constructor() {
143
+ this.helpWidth = undefined;
144
+ this.minWidthToWrap = 40;
145
+ this.sortSubcommands = false;
146
+ this.sortOptions = false;
147
+ this.showGlobalOptions = false;
148
+ }
149
+ prepareContext(contextOptions) {
150
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
151
+ }
152
+ visibleCommands(cmd) {
153
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
154
+ const helpCommand = cmd._getHelpCommand();
155
+ if (helpCommand && !helpCommand._hidden) {
156
+ visibleCommands.push(helpCommand);
157
+ }
158
+ if (this.sortSubcommands) {
159
+ visibleCommands.sort((a, b) => {
160
+ return a.name().localeCompare(b.name());
161
+ });
162
+ }
163
+ return visibleCommands;
164
+ }
165
+ compareOptions(a, b) {
166
+ const getSortKey = (option) => {
167
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
168
+ };
169
+ return getSortKey(a).localeCompare(getSortKey(b));
170
+ }
171
+ visibleOptions(cmd) {
172
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
173
+ const helpOption = cmd._getHelpOption();
174
+ if (helpOption && !helpOption.hidden) {
175
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
176
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
177
+ if (!removeShort && !removeLong) {
178
+ visibleOptions.push(helpOption);
179
+ } else if (helpOption.long && !removeLong) {
180
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
181
+ } else if (helpOption.short && !removeShort) {
182
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
183
+ }
184
+ }
185
+ if (this.sortOptions) {
186
+ visibleOptions.sort(this.compareOptions);
187
+ }
188
+ return visibleOptions;
189
+ }
190
+ visibleGlobalOptions(cmd) {
191
+ if (!this.showGlobalOptions)
192
+ return [];
193
+ const globalOptions = [];
194
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
195
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
196
+ globalOptions.push(...visibleOptions);
197
+ }
198
+ if (this.sortOptions) {
199
+ globalOptions.sort(this.compareOptions);
200
+ }
201
+ return globalOptions;
202
+ }
203
+ visibleArguments(cmd) {
204
+ if (cmd._argsDescription) {
205
+ cmd.registeredArguments.forEach((argument) => {
206
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
207
+ });
208
+ }
209
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
210
+ return cmd.registeredArguments;
211
+ }
212
+ return [];
213
+ }
214
+ subcommandTerm(cmd) {
215
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
216
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
217
+ }
218
+ optionTerm(option) {
219
+ return option.flags;
220
+ }
221
+ argumentTerm(argument) {
222
+ return argument.name();
223
+ }
224
+ longestSubcommandTermLength(cmd, helper) {
225
+ return helper.visibleCommands(cmd).reduce((max, command) => {
226
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
227
+ }, 0);
228
+ }
229
+ longestOptionTermLength(cmd, helper) {
230
+ return helper.visibleOptions(cmd).reduce((max, option) => {
231
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
232
+ }, 0);
233
+ }
234
+ longestGlobalOptionTermLength(cmd, helper) {
235
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
236
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
237
+ }, 0);
238
+ }
239
+ longestArgumentTermLength(cmd, helper) {
240
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
241
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
242
+ }, 0);
243
+ }
244
+ commandUsage(cmd) {
245
+ let cmdName = cmd._name;
246
+ if (cmd._aliases[0]) {
247
+ cmdName = cmdName + "|" + cmd._aliases[0];
248
+ }
249
+ let ancestorCmdNames = "";
250
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
251
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
252
+ }
253
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
254
+ }
255
+ commandDescription(cmd) {
256
+ return cmd.description();
257
+ }
258
+ subcommandDescription(cmd) {
259
+ return cmd.summary() || cmd.description();
260
+ }
261
+ optionDescription(option) {
262
+ const extraInfo = [];
263
+ if (option.argChoices) {
264
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
265
+ }
266
+ if (option.defaultValue !== undefined) {
267
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
268
+ if (showDefault) {
269
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
270
+ }
271
+ }
272
+ if (option.presetArg !== undefined && option.optional) {
273
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
274
+ }
275
+ if (option.envVar !== undefined) {
276
+ extraInfo.push(`env: ${option.envVar}`);
277
+ }
278
+ if (extraInfo.length > 0) {
279
+ const extraDescription = `(${extraInfo.join(", ")})`;
280
+ if (option.description) {
281
+ return `${option.description} ${extraDescription}`;
282
+ }
283
+ return extraDescription;
284
+ }
285
+ return option.description;
286
+ }
287
+ argumentDescription(argument) {
288
+ const extraInfo = [];
289
+ if (argument.argChoices) {
290
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
291
+ }
292
+ if (argument.defaultValue !== undefined) {
293
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
294
+ }
295
+ if (extraInfo.length > 0) {
296
+ const extraDescription = `(${extraInfo.join(", ")})`;
297
+ if (argument.description) {
298
+ return `${argument.description} ${extraDescription}`;
299
+ }
300
+ return extraDescription;
301
+ }
302
+ return argument.description;
303
+ }
304
+ formatItemList(heading, items, helper) {
305
+ if (items.length === 0)
306
+ return [];
307
+ return [helper.styleTitle(heading), ...items, ""];
308
+ }
309
+ groupItems(unsortedItems, visibleItems, getGroup) {
310
+ const result = new Map;
311
+ unsortedItems.forEach((item) => {
312
+ const group = getGroup(item);
313
+ if (!result.has(group))
314
+ result.set(group, []);
315
+ });
316
+ visibleItems.forEach((item) => {
317
+ const group = getGroup(item);
318
+ if (!result.has(group)) {
319
+ result.set(group, []);
320
+ }
321
+ result.get(group).push(item);
322
+ });
323
+ return result;
324
+ }
325
+ formatHelp(cmd, helper) {
326
+ const termWidth = helper.padWidth(cmd, helper);
327
+ const helpWidth = helper.helpWidth ?? 80;
328
+ function callFormatItem(term, description) {
329
+ return helper.formatItem(term, termWidth, description, helper);
330
+ }
331
+ let output = [
332
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
333
+ ""
334
+ ];
335
+ const commandDescription = helper.commandDescription(cmd);
336
+ if (commandDescription.length > 0) {
337
+ output = output.concat([
338
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
339
+ ""
340
+ ]);
341
+ }
342
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
343
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
344
+ });
345
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
346
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
347
+ optionGroups.forEach((options, group) => {
348
+ const optionList = options.map((option) => {
349
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
350
+ });
351
+ output = output.concat(this.formatItemList(group, optionList, helper));
352
+ });
353
+ if (helper.showGlobalOptions) {
354
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
355
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
356
+ });
357
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
358
+ }
359
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
360
+ commandGroups.forEach((commands, group) => {
361
+ const commandList = commands.map((sub) => {
362
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
363
+ });
364
+ output = output.concat(this.formatItemList(group, commandList, helper));
365
+ });
366
+ return output.join(`
367
+ `);
368
+ }
369
+ displayWidth(str) {
370
+ return stripColor(str).length;
371
+ }
372
+ styleTitle(str) {
373
+ return str;
374
+ }
375
+ styleUsage(str) {
376
+ return str.split(" ").map((word) => {
377
+ if (word === "[options]")
378
+ return this.styleOptionText(word);
379
+ if (word === "[command]")
380
+ return this.styleSubcommandText(word);
381
+ if (word[0] === "[" || word[0] === "<")
382
+ return this.styleArgumentText(word);
383
+ return this.styleCommandText(word);
384
+ }).join(" ");
385
+ }
386
+ styleCommandDescription(str) {
387
+ return this.styleDescriptionText(str);
388
+ }
389
+ styleOptionDescription(str) {
390
+ return this.styleDescriptionText(str);
391
+ }
392
+ styleSubcommandDescription(str) {
393
+ return this.styleDescriptionText(str);
394
+ }
395
+ styleArgumentDescription(str) {
396
+ return this.styleDescriptionText(str);
397
+ }
398
+ styleDescriptionText(str) {
399
+ return str;
400
+ }
401
+ styleOptionTerm(str) {
402
+ return this.styleOptionText(str);
403
+ }
404
+ styleSubcommandTerm(str) {
405
+ return str.split(" ").map((word) => {
406
+ if (word === "[options]")
407
+ return this.styleOptionText(word);
408
+ if (word[0] === "[" || word[0] === "<")
409
+ return this.styleArgumentText(word);
410
+ return this.styleSubcommandText(word);
411
+ }).join(" ");
412
+ }
413
+ styleArgumentTerm(str) {
414
+ return this.styleArgumentText(str);
415
+ }
416
+ styleOptionText(str) {
417
+ return str;
418
+ }
419
+ styleArgumentText(str) {
420
+ return str;
421
+ }
422
+ styleSubcommandText(str) {
423
+ return str;
424
+ }
425
+ styleCommandText(str) {
426
+ return str;
427
+ }
428
+ padWidth(cmd, helper) {
429
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
430
+ }
431
+ preformatted(str) {
432
+ return /\n[^\S\r\n]/.test(str);
433
+ }
434
+ formatItem(term, termWidth, description, helper) {
435
+ const itemIndent = 2;
436
+ const itemIndentStr = " ".repeat(itemIndent);
437
+ if (!description)
438
+ return itemIndentStr + term;
439
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
440
+ const spacerWidth = 2;
441
+ const helpWidth = this.helpWidth ?? 80;
442
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
443
+ let formattedDescription;
444
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
445
+ formattedDescription = description;
446
+ } else {
447
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
448
+ formattedDescription = wrappedDescription.replace(/\n/g, `
449
+ ` + " ".repeat(termWidth + spacerWidth));
450
+ }
451
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
452
+ ${itemIndentStr}`);
453
+ }
454
+ boxWrap(str, width) {
455
+ if (width < this.minWidthToWrap)
456
+ return str;
457
+ const rawLines = str.split(/\r\n|\n/);
458
+ const chunkPattern = /[\s]*[^\s]+/g;
459
+ const wrappedLines = [];
460
+ rawLines.forEach((line) => {
461
+ const chunks = line.match(chunkPattern);
462
+ if (chunks === null) {
463
+ wrappedLines.push("");
464
+ return;
465
+ }
466
+ let sumChunks = [chunks.shift()];
467
+ let sumWidth = this.displayWidth(sumChunks[0]);
468
+ chunks.forEach((chunk) => {
469
+ const visibleWidth = this.displayWidth(chunk);
470
+ if (sumWidth + visibleWidth <= width) {
471
+ sumChunks.push(chunk);
472
+ sumWidth += visibleWidth;
473
+ return;
474
+ }
475
+ wrappedLines.push(sumChunks.join(""));
476
+ const nextChunk = chunk.trimStart();
477
+ sumChunks = [nextChunk];
478
+ sumWidth = this.displayWidth(nextChunk);
479
+ });
480
+ wrappedLines.push(sumChunks.join(""));
481
+ });
482
+ return wrappedLines.join(`
483
+ `);
484
+ }
485
+ }
486
+ function stripColor(str) {
487
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
488
+ return str.replace(sgrPattern, "");
489
+ }
490
+ exports.Help = Help;
491
+ exports.stripColor = stripColor;
492
+ });
493
+
494
+ // node_modules/commander/lib/option.js
495
+ var require_option = __commonJS((exports) => {
496
+ var { InvalidArgumentError } = require_error();
497
+
498
+ class Option {
499
+ constructor(flags, description) {
500
+ this.flags = flags;
501
+ this.description = description || "";
502
+ this.required = flags.includes("<");
503
+ this.optional = flags.includes("[");
504
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
505
+ this.mandatory = false;
506
+ const optionFlags = splitOptionFlags(flags);
507
+ this.short = optionFlags.shortFlag;
508
+ this.long = optionFlags.longFlag;
509
+ this.negate = false;
510
+ if (this.long) {
511
+ this.negate = this.long.startsWith("--no-");
512
+ }
513
+ this.defaultValue = undefined;
514
+ this.defaultValueDescription = undefined;
515
+ this.presetArg = undefined;
516
+ this.envVar = undefined;
517
+ this.parseArg = undefined;
518
+ this.hidden = false;
519
+ this.argChoices = undefined;
520
+ this.conflictsWith = [];
521
+ this.implied = undefined;
522
+ this.helpGroupHeading = undefined;
523
+ }
524
+ default(value, description) {
525
+ this.defaultValue = value;
526
+ this.defaultValueDescription = description;
527
+ return this;
528
+ }
529
+ preset(arg) {
530
+ this.presetArg = arg;
531
+ return this;
532
+ }
533
+ conflicts(names) {
534
+ this.conflictsWith = this.conflictsWith.concat(names);
535
+ return this;
536
+ }
537
+ implies(impliedOptionValues) {
538
+ let newImplied = impliedOptionValues;
539
+ if (typeof impliedOptionValues === "string") {
540
+ newImplied = { [impliedOptionValues]: true };
541
+ }
542
+ this.implied = Object.assign(this.implied || {}, newImplied);
543
+ return this;
544
+ }
545
+ env(name) {
546
+ this.envVar = name;
547
+ return this;
548
+ }
549
+ argParser(fn) {
550
+ this.parseArg = fn;
551
+ return this;
552
+ }
553
+ makeOptionMandatory(mandatory = true) {
554
+ this.mandatory = !!mandatory;
555
+ return this;
556
+ }
557
+ hideHelp(hide = true) {
558
+ this.hidden = !!hide;
559
+ return this;
560
+ }
561
+ _collectValue(value, previous) {
562
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
563
+ return [value];
564
+ }
565
+ previous.push(value);
566
+ return previous;
567
+ }
568
+ choices(values) {
569
+ this.argChoices = values.slice();
570
+ this.parseArg = (arg, previous) => {
571
+ if (!this.argChoices.includes(arg)) {
572
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
573
+ }
574
+ if (this.variadic) {
575
+ return this._collectValue(arg, previous);
576
+ }
577
+ return arg;
578
+ };
579
+ return this;
580
+ }
581
+ name() {
582
+ if (this.long) {
583
+ return this.long.replace(/^--/, "");
584
+ }
585
+ return this.short.replace(/^-/, "");
586
+ }
587
+ attributeName() {
588
+ if (this.negate) {
589
+ return camelcase(this.name().replace(/^no-/, ""));
590
+ }
591
+ return camelcase(this.name());
592
+ }
593
+ helpGroup(heading) {
594
+ this.helpGroupHeading = heading;
595
+ return this;
596
+ }
597
+ is(arg) {
598
+ return this.short === arg || this.long === arg;
599
+ }
600
+ isBoolean() {
601
+ return !this.required && !this.optional && !this.negate;
602
+ }
603
+ }
604
+
605
+ class DualOptions {
606
+ constructor(options) {
607
+ this.positiveOptions = new Map;
608
+ this.negativeOptions = new Map;
609
+ this.dualOptions = new Set;
610
+ options.forEach((option) => {
611
+ if (option.negate) {
612
+ this.negativeOptions.set(option.attributeName(), option);
613
+ } else {
614
+ this.positiveOptions.set(option.attributeName(), option);
615
+ }
616
+ });
617
+ this.negativeOptions.forEach((value, key) => {
618
+ if (this.positiveOptions.has(key)) {
619
+ this.dualOptions.add(key);
620
+ }
621
+ });
622
+ }
623
+ valueFromOption(value, option) {
624
+ const optionKey = option.attributeName();
625
+ if (!this.dualOptions.has(optionKey))
626
+ return true;
627
+ const preset = this.negativeOptions.get(optionKey).presetArg;
628
+ const negativeValue = preset !== undefined ? preset : false;
629
+ return option.negate === (negativeValue === value);
630
+ }
631
+ }
632
+ function camelcase(str) {
633
+ return str.split("-").reduce((str2, word) => {
634
+ return str2 + word[0].toUpperCase() + word.slice(1);
635
+ });
636
+ }
637
+ function splitOptionFlags(flags) {
638
+ let shortFlag;
639
+ let longFlag;
640
+ const shortFlagExp = /^-[^-]$/;
641
+ const longFlagExp = /^--[^-]/;
642
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
643
+ if (shortFlagExp.test(flagParts[0]))
644
+ shortFlag = flagParts.shift();
645
+ if (longFlagExp.test(flagParts[0]))
646
+ longFlag = flagParts.shift();
647
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
648
+ shortFlag = flagParts.shift();
649
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
650
+ shortFlag = longFlag;
651
+ longFlag = flagParts.shift();
652
+ }
653
+ if (flagParts[0].startsWith("-")) {
654
+ const unsupportedFlag = flagParts[0];
655
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
656
+ if (/^-[^-][^-]/.test(unsupportedFlag))
657
+ throw new Error(`${baseError}
658
+ - a short flag is a single dash and a single character
659
+ - either use a single dash and a single character (for a short flag)
660
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
661
+ if (shortFlagExp.test(unsupportedFlag))
662
+ throw new Error(`${baseError}
663
+ - too many short flags`);
664
+ if (longFlagExp.test(unsupportedFlag))
665
+ throw new Error(`${baseError}
666
+ - too many long flags`);
667
+ throw new Error(`${baseError}
668
+ - unrecognised flag format`);
669
+ }
670
+ if (shortFlag === undefined && longFlag === undefined)
671
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
672
+ return { shortFlag, longFlag };
673
+ }
674
+ exports.Option = Option;
675
+ exports.DualOptions = DualOptions;
676
+ });
677
+
678
+ // node_modules/commander/lib/suggestSimilar.js
679
+ var require_suggestSimilar = __commonJS((exports) => {
680
+ var maxDistance = 3;
681
+ function editDistance(a, b) {
682
+ if (Math.abs(a.length - b.length) > maxDistance)
683
+ return Math.max(a.length, b.length);
684
+ const d = [];
685
+ for (let i = 0;i <= a.length; i++) {
686
+ d[i] = [i];
687
+ }
688
+ for (let j = 0;j <= b.length; j++) {
689
+ d[0][j] = j;
690
+ }
691
+ for (let j = 1;j <= b.length; j++) {
692
+ for (let i = 1;i <= a.length; i++) {
693
+ let cost = 1;
694
+ if (a[i - 1] === b[j - 1]) {
695
+ cost = 0;
696
+ } else {
697
+ cost = 1;
698
+ }
699
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
700
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
701
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
702
+ }
703
+ }
704
+ }
705
+ return d[a.length][b.length];
706
+ }
707
+ function suggestSimilar(word, candidates) {
708
+ if (!candidates || candidates.length === 0)
709
+ return "";
710
+ candidates = Array.from(new Set(candidates));
711
+ const searchingOptions = word.startsWith("--");
712
+ if (searchingOptions) {
713
+ word = word.slice(2);
714
+ candidates = candidates.map((candidate) => candidate.slice(2));
715
+ }
716
+ let similar = [];
717
+ let bestDistance = maxDistance;
718
+ const minSimilarity = 0.4;
719
+ candidates.forEach((candidate) => {
720
+ if (candidate.length <= 1)
721
+ return;
722
+ const distance = editDistance(word, candidate);
723
+ const length = Math.max(word.length, candidate.length);
724
+ const similarity = (length - distance) / length;
725
+ if (similarity > minSimilarity) {
726
+ if (distance < bestDistance) {
727
+ bestDistance = distance;
728
+ similar = [candidate];
729
+ } else if (distance === bestDistance) {
730
+ similar.push(candidate);
731
+ }
732
+ }
733
+ });
734
+ similar.sort((a, b) => a.localeCompare(b));
735
+ if (searchingOptions) {
736
+ similar = similar.map((candidate) => `--${candidate}`);
737
+ }
738
+ if (similar.length > 1) {
739
+ return `
740
+ (Did you mean one of ${similar.join(", ")}?)`;
741
+ }
742
+ if (similar.length === 1) {
743
+ return `
744
+ (Did you mean ${similar[0]}?)`;
745
+ }
746
+ return "";
747
+ }
748
+ exports.suggestSimilar = suggestSimilar;
749
+ });
750
+
751
+ // node_modules/commander/lib/command.js
752
+ var require_command = __commonJS((exports) => {
753
+ var EventEmitter = __require("node:events").EventEmitter;
754
+ var childProcess = __require("node:child_process");
755
+ var path = __require("node:path");
756
+ var fs = __require("node:fs");
757
+ var process2 = __require("node:process");
758
+ var { Argument, humanReadableArgName } = require_argument();
759
+ var { CommanderError } = require_error();
760
+ var { Help, stripColor } = require_help();
761
+ var { Option, DualOptions } = require_option();
762
+ var { suggestSimilar } = require_suggestSimilar();
763
+
764
+ class Command extends EventEmitter {
765
+ constructor(name) {
766
+ super();
767
+ this.commands = [];
768
+ this.options = [];
769
+ this.parent = null;
770
+ this._allowUnknownOption = false;
771
+ this._allowExcessArguments = false;
772
+ this.registeredArguments = [];
773
+ this._args = this.registeredArguments;
774
+ this.args = [];
775
+ this.rawArgs = [];
776
+ this.processedArgs = [];
777
+ this._scriptPath = null;
778
+ this._name = name || "";
779
+ this._optionValues = {};
780
+ this._optionValueSources = {};
781
+ this._storeOptionsAsProperties = false;
782
+ this._actionHandler = null;
783
+ this._executableHandler = false;
784
+ this._executableFile = null;
785
+ this._executableDir = null;
786
+ this._defaultCommandName = null;
787
+ this._exitCallback = null;
788
+ this._aliases = [];
789
+ this._combineFlagAndOptionalValue = true;
790
+ this._description = "";
791
+ this._summary = "";
792
+ this._argsDescription = undefined;
793
+ this._enablePositionalOptions = false;
794
+ this._passThroughOptions = false;
795
+ this._lifeCycleHooks = {};
796
+ this._showHelpAfterError = false;
797
+ this._showSuggestionAfterError = true;
798
+ this._savedState = null;
799
+ this._outputConfiguration = {
800
+ writeOut: (str) => process2.stdout.write(str),
801
+ writeErr: (str) => process2.stderr.write(str),
802
+ outputError: (str, write) => write(str),
803
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
804
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
805
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
806
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
807
+ stripColor: (str) => stripColor(str)
808
+ };
809
+ this._hidden = false;
810
+ this._helpOption = undefined;
811
+ this._addImplicitHelpCommand = undefined;
812
+ this._helpCommand = undefined;
813
+ this._helpConfiguration = {};
814
+ this._helpGroupHeading = undefined;
815
+ this._defaultCommandGroup = undefined;
816
+ this._defaultOptionGroup = undefined;
817
+ }
818
+ copyInheritedSettings(sourceCommand) {
819
+ this._outputConfiguration = sourceCommand._outputConfiguration;
820
+ this._helpOption = sourceCommand._helpOption;
821
+ this._helpCommand = sourceCommand._helpCommand;
822
+ this._helpConfiguration = sourceCommand._helpConfiguration;
823
+ this._exitCallback = sourceCommand._exitCallback;
824
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
825
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
826
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
827
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
828
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
829
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
830
+ return this;
831
+ }
832
+ _getCommandAndAncestors() {
833
+ const result = [];
834
+ for (let command = this;command; command = command.parent) {
835
+ result.push(command);
836
+ }
837
+ return result;
838
+ }
839
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
840
+ let desc = actionOptsOrExecDesc;
841
+ let opts = execOpts;
842
+ if (typeof desc === "object" && desc !== null) {
843
+ opts = desc;
844
+ desc = null;
845
+ }
846
+ opts = opts || {};
847
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
848
+ const cmd = this.createCommand(name);
849
+ if (desc) {
850
+ cmd.description(desc);
851
+ cmd._executableHandler = true;
852
+ }
853
+ if (opts.isDefault)
854
+ this._defaultCommandName = cmd._name;
855
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
856
+ cmd._executableFile = opts.executableFile || null;
857
+ if (args)
858
+ cmd.arguments(args);
859
+ this._registerCommand(cmd);
860
+ cmd.parent = this;
861
+ cmd.copyInheritedSettings(this);
862
+ if (desc)
863
+ return this;
864
+ return cmd;
865
+ }
866
+ createCommand(name) {
867
+ return new Command(name);
868
+ }
869
+ createHelp() {
870
+ return Object.assign(new Help, this.configureHelp());
871
+ }
872
+ configureHelp(configuration) {
873
+ if (configuration === undefined)
874
+ return this._helpConfiguration;
875
+ this._helpConfiguration = configuration;
876
+ return this;
877
+ }
878
+ configureOutput(configuration) {
879
+ if (configuration === undefined)
880
+ return this._outputConfiguration;
881
+ this._outputConfiguration = {
882
+ ...this._outputConfiguration,
883
+ ...configuration
884
+ };
885
+ return this;
886
+ }
887
+ showHelpAfterError(displayHelp = true) {
888
+ if (typeof displayHelp !== "string")
889
+ displayHelp = !!displayHelp;
890
+ this._showHelpAfterError = displayHelp;
891
+ return this;
892
+ }
893
+ showSuggestionAfterError(displaySuggestion = true) {
894
+ this._showSuggestionAfterError = !!displaySuggestion;
895
+ return this;
896
+ }
897
+ addCommand(cmd, opts) {
898
+ if (!cmd._name) {
899
+ throw new Error(`Command passed to .addCommand() must have a name
900
+ - specify the name in Command constructor or using .name()`);
901
+ }
902
+ opts = opts || {};
903
+ if (opts.isDefault)
904
+ this._defaultCommandName = cmd._name;
905
+ if (opts.noHelp || opts.hidden)
906
+ cmd._hidden = true;
907
+ this._registerCommand(cmd);
908
+ cmd.parent = this;
909
+ cmd._checkForBrokenPassThrough();
910
+ return this;
911
+ }
912
+ createArgument(name, description) {
913
+ return new Argument(name, description);
914
+ }
915
+ argument(name, description, parseArg, defaultValue) {
916
+ const argument = this.createArgument(name, description);
917
+ if (typeof parseArg === "function") {
918
+ argument.default(defaultValue).argParser(parseArg);
919
+ } else {
920
+ argument.default(parseArg);
921
+ }
922
+ this.addArgument(argument);
923
+ return this;
924
+ }
925
+ arguments(names) {
926
+ names.trim().split(/ +/).forEach((detail) => {
927
+ this.argument(detail);
928
+ });
929
+ return this;
930
+ }
931
+ addArgument(argument) {
932
+ const previousArgument = this.registeredArguments.slice(-1)[0];
933
+ if (previousArgument?.variadic) {
934
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
935
+ }
936
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
937
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
938
+ }
939
+ this.registeredArguments.push(argument);
940
+ return this;
941
+ }
942
+ helpCommand(enableOrNameAndArgs, description) {
943
+ if (typeof enableOrNameAndArgs === "boolean") {
944
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
945
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
946
+ this._initCommandGroup(this._getHelpCommand());
947
+ }
948
+ return this;
949
+ }
950
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
951
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
952
+ const helpDescription = description ?? "display help for command";
953
+ const helpCommand = this.createCommand(helpName);
954
+ helpCommand.helpOption(false);
955
+ if (helpArgs)
956
+ helpCommand.arguments(helpArgs);
957
+ if (helpDescription)
958
+ helpCommand.description(helpDescription);
959
+ this._addImplicitHelpCommand = true;
960
+ this._helpCommand = helpCommand;
961
+ if (enableOrNameAndArgs || description)
962
+ this._initCommandGroup(helpCommand);
963
+ return this;
964
+ }
965
+ addHelpCommand(helpCommand, deprecatedDescription) {
966
+ if (typeof helpCommand !== "object") {
967
+ this.helpCommand(helpCommand, deprecatedDescription);
968
+ return this;
969
+ }
970
+ this._addImplicitHelpCommand = true;
971
+ this._helpCommand = helpCommand;
972
+ this._initCommandGroup(helpCommand);
973
+ return this;
974
+ }
975
+ _getHelpCommand() {
976
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
977
+ if (hasImplicitHelpCommand) {
978
+ if (this._helpCommand === undefined) {
979
+ this.helpCommand(undefined, undefined);
980
+ }
981
+ return this._helpCommand;
982
+ }
983
+ return null;
984
+ }
985
+ hook(event, listener) {
986
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
987
+ if (!allowedValues.includes(event)) {
988
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
989
+ Expecting one of '${allowedValues.join("', '")}'`);
990
+ }
991
+ if (this._lifeCycleHooks[event]) {
992
+ this._lifeCycleHooks[event].push(listener);
993
+ } else {
994
+ this._lifeCycleHooks[event] = [listener];
995
+ }
996
+ return this;
997
+ }
998
+ exitOverride(fn) {
999
+ if (fn) {
1000
+ this._exitCallback = fn;
1001
+ } else {
1002
+ this._exitCallback = (err) => {
1003
+ if (err.code !== "commander.executeSubCommandAsync") {
1004
+ throw err;
1005
+ } else {}
1006
+ };
1007
+ }
1008
+ return this;
1009
+ }
1010
+ _exit(exitCode, code, message) {
1011
+ if (this._exitCallback) {
1012
+ this._exitCallback(new CommanderError(exitCode, code, message));
1013
+ }
1014
+ process2.exit(exitCode);
1015
+ }
1016
+ action(fn) {
1017
+ const listener = (args) => {
1018
+ const expectedArgsCount = this.registeredArguments.length;
1019
+ const actionArgs = args.slice(0, expectedArgsCount);
1020
+ if (this._storeOptionsAsProperties) {
1021
+ actionArgs[expectedArgsCount] = this;
1022
+ } else {
1023
+ actionArgs[expectedArgsCount] = this.opts();
1024
+ }
1025
+ actionArgs.push(this);
1026
+ return fn.apply(this, actionArgs);
1027
+ };
1028
+ this._actionHandler = listener;
1029
+ return this;
1030
+ }
1031
+ createOption(flags, description) {
1032
+ return new Option(flags, description);
1033
+ }
1034
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1035
+ try {
1036
+ return target.parseArg(value, previous);
1037
+ } catch (err) {
1038
+ if (err.code === "commander.invalidArgument") {
1039
+ const message = `${invalidArgumentMessage} ${err.message}`;
1040
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1041
+ }
1042
+ throw err;
1043
+ }
1044
+ }
1045
+ _registerOption(option) {
1046
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1047
+ if (matchingOption) {
1048
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1049
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1050
+ - already used by option '${matchingOption.flags}'`);
1051
+ }
1052
+ this._initOptionGroup(option);
1053
+ this.options.push(option);
1054
+ }
1055
+ _registerCommand(command) {
1056
+ const knownBy = (cmd) => {
1057
+ return [cmd.name()].concat(cmd.aliases());
1058
+ };
1059
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1060
+ if (alreadyUsed) {
1061
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1062
+ const newCmd = knownBy(command).join("|");
1063
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1064
+ }
1065
+ this._initCommandGroup(command);
1066
+ this.commands.push(command);
1067
+ }
1068
+ addOption(option) {
1069
+ this._registerOption(option);
1070
+ const oname = option.name();
1071
+ const name = option.attributeName();
1072
+ if (option.negate) {
1073
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1074
+ if (!this._findOption(positiveLongFlag)) {
1075
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1076
+ }
1077
+ } else if (option.defaultValue !== undefined) {
1078
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1079
+ }
1080
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1081
+ if (val == null && option.presetArg !== undefined) {
1082
+ val = option.presetArg;
1083
+ }
1084
+ const oldValue = this.getOptionValue(name);
1085
+ if (val !== null && option.parseArg) {
1086
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1087
+ } else if (val !== null && option.variadic) {
1088
+ val = option._collectValue(val, oldValue);
1089
+ }
1090
+ if (val == null) {
1091
+ if (option.negate) {
1092
+ val = false;
1093
+ } else if (option.isBoolean() || option.optional) {
1094
+ val = true;
1095
+ } else {
1096
+ val = "";
1097
+ }
1098
+ }
1099
+ this.setOptionValueWithSource(name, val, valueSource);
1100
+ };
1101
+ this.on("option:" + oname, (val) => {
1102
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1103
+ handleOptionValue(val, invalidValueMessage, "cli");
1104
+ });
1105
+ if (option.envVar) {
1106
+ this.on("optionEnv:" + oname, (val) => {
1107
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1108
+ handleOptionValue(val, invalidValueMessage, "env");
1109
+ });
1110
+ }
1111
+ return this;
1112
+ }
1113
+ _optionEx(config, flags, description, fn, defaultValue) {
1114
+ if (typeof flags === "object" && flags instanceof Option) {
1115
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1116
+ }
1117
+ const option = this.createOption(flags, description);
1118
+ option.makeOptionMandatory(!!config.mandatory);
1119
+ if (typeof fn === "function") {
1120
+ option.default(defaultValue).argParser(fn);
1121
+ } else if (fn instanceof RegExp) {
1122
+ const regex = fn;
1123
+ fn = (val, def) => {
1124
+ const m = regex.exec(val);
1125
+ return m ? m[0] : def;
1126
+ };
1127
+ option.default(defaultValue).argParser(fn);
1128
+ } else {
1129
+ option.default(fn);
1130
+ }
1131
+ return this.addOption(option);
1132
+ }
1133
+ option(flags, description, parseArg, defaultValue) {
1134
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1135
+ }
1136
+ requiredOption(flags, description, parseArg, defaultValue) {
1137
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1138
+ }
1139
+ combineFlagAndOptionalValue(combine = true) {
1140
+ this._combineFlagAndOptionalValue = !!combine;
1141
+ return this;
1142
+ }
1143
+ allowUnknownOption(allowUnknown = true) {
1144
+ this._allowUnknownOption = !!allowUnknown;
1145
+ return this;
1146
+ }
1147
+ allowExcessArguments(allowExcess = true) {
1148
+ this._allowExcessArguments = !!allowExcess;
1149
+ return this;
1150
+ }
1151
+ enablePositionalOptions(positional = true) {
1152
+ this._enablePositionalOptions = !!positional;
1153
+ return this;
1154
+ }
1155
+ passThroughOptions(passThrough = true) {
1156
+ this._passThroughOptions = !!passThrough;
1157
+ this._checkForBrokenPassThrough();
1158
+ return this;
1159
+ }
1160
+ _checkForBrokenPassThrough() {
1161
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1162
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1163
+ }
1164
+ }
1165
+ storeOptionsAsProperties(storeAsProperties = true) {
1166
+ if (this.options.length) {
1167
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1168
+ }
1169
+ if (Object.keys(this._optionValues).length) {
1170
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1171
+ }
1172
+ this._storeOptionsAsProperties = !!storeAsProperties;
1173
+ return this;
1174
+ }
1175
+ getOptionValue(key) {
1176
+ if (this._storeOptionsAsProperties) {
1177
+ return this[key];
1178
+ }
1179
+ return this._optionValues[key];
1180
+ }
1181
+ setOptionValue(key, value) {
1182
+ return this.setOptionValueWithSource(key, value, undefined);
1183
+ }
1184
+ setOptionValueWithSource(key, value, source) {
1185
+ if (this._storeOptionsAsProperties) {
1186
+ this[key] = value;
1187
+ } else {
1188
+ this._optionValues[key] = value;
1189
+ }
1190
+ this._optionValueSources[key] = source;
1191
+ return this;
1192
+ }
1193
+ getOptionValueSource(key) {
1194
+ return this._optionValueSources[key];
1195
+ }
1196
+ getOptionValueSourceWithGlobals(key) {
1197
+ let source;
1198
+ this._getCommandAndAncestors().forEach((cmd) => {
1199
+ if (cmd.getOptionValueSource(key) !== undefined) {
1200
+ source = cmd.getOptionValueSource(key);
1201
+ }
1202
+ });
1203
+ return source;
1204
+ }
1205
+ _prepareUserArgs(argv, parseOptions) {
1206
+ if (argv !== undefined && !Array.isArray(argv)) {
1207
+ throw new Error("first parameter to parse must be array or undefined");
1208
+ }
1209
+ parseOptions = parseOptions || {};
1210
+ if (argv === undefined && parseOptions.from === undefined) {
1211
+ if (process2.versions?.electron) {
1212
+ parseOptions.from = "electron";
1213
+ }
1214
+ const execArgv = process2.execArgv ?? [];
1215
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1216
+ parseOptions.from = "eval";
1217
+ }
1218
+ }
1219
+ if (argv === undefined) {
1220
+ argv = process2.argv;
1221
+ }
1222
+ this.rawArgs = argv.slice();
1223
+ let userArgs;
1224
+ switch (parseOptions.from) {
1225
+ case undefined:
1226
+ case "node":
1227
+ this._scriptPath = argv[1];
1228
+ userArgs = argv.slice(2);
1229
+ break;
1230
+ case "electron":
1231
+ if (process2.defaultApp) {
1232
+ this._scriptPath = argv[1];
1233
+ userArgs = argv.slice(2);
1234
+ } else {
1235
+ userArgs = argv.slice(1);
1236
+ }
1237
+ break;
1238
+ case "user":
1239
+ userArgs = argv.slice(0);
1240
+ break;
1241
+ case "eval":
1242
+ userArgs = argv.slice(1);
1243
+ break;
1244
+ default:
1245
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1246
+ }
1247
+ if (!this._name && this._scriptPath)
1248
+ this.nameFromFilename(this._scriptPath);
1249
+ this._name = this._name || "program";
1250
+ return userArgs;
1251
+ }
1252
+ parse(argv, parseOptions) {
1253
+ this._prepareForParse();
1254
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1255
+ this._parseCommand([], userArgs);
1256
+ return this;
1257
+ }
1258
+ async parseAsync(argv, parseOptions) {
1259
+ this._prepareForParse();
1260
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1261
+ await this._parseCommand([], userArgs);
1262
+ return this;
1263
+ }
1264
+ _prepareForParse() {
1265
+ if (this._savedState === null) {
1266
+ this.saveStateBeforeParse();
1267
+ } else {
1268
+ this.restoreStateBeforeParse();
1269
+ }
1270
+ }
1271
+ saveStateBeforeParse() {
1272
+ this._savedState = {
1273
+ _name: this._name,
1274
+ _optionValues: { ...this._optionValues },
1275
+ _optionValueSources: { ...this._optionValueSources }
1276
+ };
1277
+ }
1278
+ restoreStateBeforeParse() {
1279
+ if (this._storeOptionsAsProperties)
1280
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1281
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1282
+ this._name = this._savedState._name;
1283
+ this._scriptPath = null;
1284
+ this.rawArgs = [];
1285
+ this._optionValues = { ...this._savedState._optionValues };
1286
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1287
+ this.args = [];
1288
+ this.processedArgs = [];
1289
+ }
1290
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1291
+ if (fs.existsSync(executableFile))
1292
+ return;
1293
+ 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";
1294
+ const executableMissing = `'${executableFile}' does not exist
1295
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1296
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1297
+ - ${executableDirMessage}`;
1298
+ throw new Error(executableMissing);
1299
+ }
1300
+ _executeSubCommand(subcommand, args) {
1301
+ args = args.slice();
1302
+ let launchWithNode = false;
1303
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1304
+ function findFile(baseDir, baseName) {
1305
+ const localBin = path.resolve(baseDir, baseName);
1306
+ if (fs.existsSync(localBin))
1307
+ return localBin;
1308
+ if (sourceExt.includes(path.extname(baseName)))
1309
+ return;
1310
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1311
+ if (foundExt)
1312
+ return `${localBin}${foundExt}`;
1313
+ return;
1314
+ }
1315
+ this._checkForMissingMandatoryOptions();
1316
+ this._checkForConflictingOptions();
1317
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1318
+ let executableDir = this._executableDir || "";
1319
+ if (this._scriptPath) {
1320
+ let resolvedScriptPath;
1321
+ try {
1322
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1323
+ } catch {
1324
+ resolvedScriptPath = this._scriptPath;
1325
+ }
1326
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1327
+ }
1328
+ if (executableDir) {
1329
+ let localFile = findFile(executableDir, executableFile);
1330
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1331
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1332
+ if (legacyName !== this._name) {
1333
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1334
+ }
1335
+ }
1336
+ executableFile = localFile || executableFile;
1337
+ }
1338
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1339
+ let proc;
1340
+ if (process2.platform !== "win32") {
1341
+ if (launchWithNode) {
1342
+ args.unshift(executableFile);
1343
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1344
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1345
+ } else {
1346
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1347
+ }
1348
+ } else {
1349
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1350
+ args.unshift(executableFile);
1351
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1352
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1353
+ }
1354
+ if (!proc.killed) {
1355
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1356
+ signals.forEach((signal) => {
1357
+ process2.on(signal, () => {
1358
+ if (proc.killed === false && proc.exitCode === null) {
1359
+ proc.kill(signal);
1360
+ }
1361
+ });
1362
+ });
1363
+ }
1364
+ const exitCallback = this._exitCallback;
1365
+ proc.on("close", (code) => {
1366
+ code = code ?? 1;
1367
+ if (!exitCallback) {
1368
+ process2.exit(code);
1369
+ } else {
1370
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1371
+ }
1372
+ });
1373
+ proc.on("error", (err) => {
1374
+ if (err.code === "ENOENT") {
1375
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1376
+ } else if (err.code === "EACCES") {
1377
+ throw new Error(`'${executableFile}' not executable`);
1378
+ }
1379
+ if (!exitCallback) {
1380
+ process2.exit(1);
1381
+ } else {
1382
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1383
+ wrappedError.nestedError = err;
1384
+ exitCallback(wrappedError);
1385
+ }
1386
+ });
1387
+ this.runningCommand = proc;
1388
+ }
1389
+ _dispatchSubcommand(commandName, operands, unknown) {
1390
+ const subCommand = this._findCommand(commandName);
1391
+ if (!subCommand)
1392
+ this.help({ error: true });
1393
+ subCommand._prepareForParse();
1394
+ let promiseChain;
1395
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1396
+ promiseChain = this._chainOrCall(promiseChain, () => {
1397
+ if (subCommand._executableHandler) {
1398
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1399
+ } else {
1400
+ return subCommand._parseCommand(operands, unknown);
1401
+ }
1402
+ });
1403
+ return promiseChain;
1404
+ }
1405
+ _dispatchHelpCommand(subcommandName) {
1406
+ if (!subcommandName) {
1407
+ this.help();
1408
+ }
1409
+ const subCommand = this._findCommand(subcommandName);
1410
+ if (subCommand && !subCommand._executableHandler) {
1411
+ subCommand.help();
1412
+ }
1413
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1414
+ }
1415
+ _checkNumberOfArguments() {
1416
+ this.registeredArguments.forEach((arg, i) => {
1417
+ if (arg.required && this.args[i] == null) {
1418
+ this.missingArgument(arg.name());
1419
+ }
1420
+ });
1421
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1422
+ return;
1423
+ }
1424
+ if (this.args.length > this.registeredArguments.length) {
1425
+ this._excessArguments(this.args);
1426
+ }
1427
+ }
1428
+ _processArguments() {
1429
+ const myParseArg = (argument, value, previous) => {
1430
+ let parsedValue = value;
1431
+ if (value !== null && argument.parseArg) {
1432
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1433
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1434
+ }
1435
+ return parsedValue;
1436
+ };
1437
+ this._checkNumberOfArguments();
1438
+ const processedArgs = [];
1439
+ this.registeredArguments.forEach((declaredArg, index) => {
1440
+ let value = declaredArg.defaultValue;
1441
+ if (declaredArg.variadic) {
1442
+ if (index < this.args.length) {
1443
+ value = this.args.slice(index);
1444
+ if (declaredArg.parseArg) {
1445
+ value = value.reduce((processed, v) => {
1446
+ return myParseArg(declaredArg, v, processed);
1447
+ }, declaredArg.defaultValue);
1448
+ }
1449
+ } else if (value === undefined) {
1450
+ value = [];
1451
+ }
1452
+ } else if (index < this.args.length) {
1453
+ value = this.args[index];
1454
+ if (declaredArg.parseArg) {
1455
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1456
+ }
1457
+ }
1458
+ processedArgs[index] = value;
1459
+ });
1460
+ this.processedArgs = processedArgs;
1461
+ }
1462
+ _chainOrCall(promise, fn) {
1463
+ if (promise?.then && typeof promise.then === "function") {
1464
+ return promise.then(() => fn());
1465
+ }
1466
+ return fn();
1467
+ }
1468
+ _chainOrCallHooks(promise, event) {
1469
+ let result = promise;
1470
+ const hooks = [];
1471
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1472
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1473
+ hooks.push({ hookedCommand, callback });
1474
+ });
1475
+ });
1476
+ if (event === "postAction") {
1477
+ hooks.reverse();
1478
+ }
1479
+ hooks.forEach((hookDetail) => {
1480
+ result = this._chainOrCall(result, () => {
1481
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1482
+ });
1483
+ });
1484
+ return result;
1485
+ }
1486
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1487
+ let result = promise;
1488
+ if (this._lifeCycleHooks[event] !== undefined) {
1489
+ this._lifeCycleHooks[event].forEach((hook) => {
1490
+ result = this._chainOrCall(result, () => {
1491
+ return hook(this, subCommand);
1492
+ });
1493
+ });
1494
+ }
1495
+ return result;
1496
+ }
1497
+ _parseCommand(operands, unknown) {
1498
+ const parsed = this.parseOptions(unknown);
1499
+ this._parseOptionsEnv();
1500
+ this._parseOptionsImplied();
1501
+ operands = operands.concat(parsed.operands);
1502
+ unknown = parsed.unknown;
1503
+ this.args = operands.concat(unknown);
1504
+ if (operands && this._findCommand(operands[0])) {
1505
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1506
+ }
1507
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1508
+ return this._dispatchHelpCommand(operands[1]);
1509
+ }
1510
+ if (this._defaultCommandName) {
1511
+ this._outputHelpIfRequested(unknown);
1512
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1513
+ }
1514
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1515
+ this.help({ error: true });
1516
+ }
1517
+ this._outputHelpIfRequested(parsed.unknown);
1518
+ this._checkForMissingMandatoryOptions();
1519
+ this._checkForConflictingOptions();
1520
+ const checkForUnknownOptions = () => {
1521
+ if (parsed.unknown.length > 0) {
1522
+ this.unknownOption(parsed.unknown[0]);
1523
+ }
1524
+ };
1525
+ const commandEvent = `command:${this.name()}`;
1526
+ if (this._actionHandler) {
1527
+ checkForUnknownOptions();
1528
+ this._processArguments();
1529
+ let promiseChain;
1530
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1531
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1532
+ if (this.parent) {
1533
+ promiseChain = this._chainOrCall(promiseChain, () => {
1534
+ this.parent.emit(commandEvent, operands, unknown);
1535
+ });
1536
+ }
1537
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1538
+ return promiseChain;
1539
+ }
1540
+ if (this.parent?.listenerCount(commandEvent)) {
1541
+ checkForUnknownOptions();
1542
+ this._processArguments();
1543
+ this.parent.emit(commandEvent, operands, unknown);
1544
+ } else if (operands.length) {
1545
+ if (this._findCommand("*")) {
1546
+ return this._dispatchSubcommand("*", operands, unknown);
1547
+ }
1548
+ if (this.listenerCount("command:*")) {
1549
+ this.emit("command:*", operands, unknown);
1550
+ } else if (this.commands.length) {
1551
+ this.unknownCommand();
1552
+ } else {
1553
+ checkForUnknownOptions();
1554
+ this._processArguments();
1555
+ }
1556
+ } else if (this.commands.length) {
1557
+ checkForUnknownOptions();
1558
+ this.help({ error: true });
1559
+ } else {
1560
+ checkForUnknownOptions();
1561
+ this._processArguments();
1562
+ }
1563
+ }
1564
+ _findCommand(name) {
1565
+ if (!name)
1566
+ return;
1567
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1568
+ }
1569
+ _findOption(arg) {
1570
+ return this.options.find((option) => option.is(arg));
1571
+ }
1572
+ _checkForMissingMandatoryOptions() {
1573
+ this._getCommandAndAncestors().forEach((cmd) => {
1574
+ cmd.options.forEach((anOption) => {
1575
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1576
+ cmd.missingMandatoryOptionValue(anOption);
1577
+ }
1578
+ });
1579
+ });
1580
+ }
1581
+ _checkForConflictingLocalOptions() {
1582
+ const definedNonDefaultOptions = this.options.filter((option) => {
1583
+ const optionKey = option.attributeName();
1584
+ if (this.getOptionValue(optionKey) === undefined) {
1585
+ return false;
1586
+ }
1587
+ return this.getOptionValueSource(optionKey) !== "default";
1588
+ });
1589
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1590
+ optionsWithConflicting.forEach((option) => {
1591
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1592
+ if (conflictingAndDefined) {
1593
+ this._conflictingOption(option, conflictingAndDefined);
1594
+ }
1595
+ });
1596
+ }
1597
+ _checkForConflictingOptions() {
1598
+ this._getCommandAndAncestors().forEach((cmd) => {
1599
+ cmd._checkForConflictingLocalOptions();
1600
+ });
1601
+ }
1602
+ parseOptions(args) {
1603
+ const operands = [];
1604
+ const unknown = [];
1605
+ let dest = operands;
1606
+ function maybeOption(arg) {
1607
+ return arg.length > 1 && arg[0] === "-";
1608
+ }
1609
+ const negativeNumberArg = (arg) => {
1610
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1611
+ return false;
1612
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1613
+ };
1614
+ let activeVariadicOption = null;
1615
+ let activeGroup = null;
1616
+ let i = 0;
1617
+ while (i < args.length || activeGroup) {
1618
+ const arg = activeGroup ?? args[i++];
1619
+ activeGroup = null;
1620
+ if (arg === "--") {
1621
+ if (dest === unknown)
1622
+ dest.push(arg);
1623
+ dest.push(...args.slice(i));
1624
+ break;
1625
+ }
1626
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1627
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1628
+ continue;
1629
+ }
1630
+ activeVariadicOption = null;
1631
+ if (maybeOption(arg)) {
1632
+ const option = this._findOption(arg);
1633
+ if (option) {
1634
+ if (option.required) {
1635
+ const value = args[i++];
1636
+ if (value === undefined)
1637
+ this.optionMissingArgument(option);
1638
+ this.emit(`option:${option.name()}`, value);
1639
+ } else if (option.optional) {
1640
+ let value = null;
1641
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1642
+ value = args[i++];
1643
+ }
1644
+ this.emit(`option:${option.name()}`, value);
1645
+ } else {
1646
+ this.emit(`option:${option.name()}`);
1647
+ }
1648
+ activeVariadicOption = option.variadic ? option : null;
1649
+ continue;
1650
+ }
1651
+ }
1652
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1653
+ const option = this._findOption(`-${arg[1]}`);
1654
+ if (option) {
1655
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1656
+ this.emit(`option:${option.name()}`, arg.slice(2));
1657
+ } else {
1658
+ this.emit(`option:${option.name()}`);
1659
+ activeGroup = `-${arg.slice(2)}`;
1660
+ }
1661
+ continue;
1662
+ }
1663
+ }
1664
+ if (/^--[^=]+=/.test(arg)) {
1665
+ const index = arg.indexOf("=");
1666
+ const option = this._findOption(arg.slice(0, index));
1667
+ if (option && (option.required || option.optional)) {
1668
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1669
+ continue;
1670
+ }
1671
+ }
1672
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1673
+ dest = unknown;
1674
+ }
1675
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1676
+ if (this._findCommand(arg)) {
1677
+ operands.push(arg);
1678
+ unknown.push(...args.slice(i));
1679
+ break;
1680
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1681
+ operands.push(arg, ...args.slice(i));
1682
+ break;
1683
+ } else if (this._defaultCommandName) {
1684
+ unknown.push(arg, ...args.slice(i));
1685
+ break;
1686
+ }
1687
+ }
1688
+ if (this._passThroughOptions) {
1689
+ dest.push(arg, ...args.slice(i));
1690
+ break;
1691
+ }
1692
+ dest.push(arg);
1693
+ }
1694
+ return { operands, unknown };
1695
+ }
1696
+ opts() {
1697
+ if (this._storeOptionsAsProperties) {
1698
+ const result = {};
1699
+ const len = this.options.length;
1700
+ for (let i = 0;i < len; i++) {
1701
+ const key = this.options[i].attributeName();
1702
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1703
+ }
1704
+ return result;
1705
+ }
1706
+ return this._optionValues;
1707
+ }
1708
+ optsWithGlobals() {
1709
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1710
+ }
1711
+ error(message, errorOptions) {
1712
+ this._outputConfiguration.outputError(`${message}
1713
+ `, this._outputConfiguration.writeErr);
1714
+ if (typeof this._showHelpAfterError === "string") {
1715
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1716
+ `);
1717
+ } else if (this._showHelpAfterError) {
1718
+ this._outputConfiguration.writeErr(`
1719
+ `);
1720
+ this.outputHelp({ error: true });
1721
+ }
1722
+ const config = errorOptions || {};
1723
+ const exitCode = config.exitCode || 1;
1724
+ const code = config.code || "commander.error";
1725
+ this._exit(exitCode, code, message);
1726
+ }
1727
+ _parseOptionsEnv() {
1728
+ this.options.forEach((option) => {
1729
+ if (option.envVar && option.envVar in process2.env) {
1730
+ const optionKey = option.attributeName();
1731
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1732
+ if (option.required || option.optional) {
1733
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1734
+ } else {
1735
+ this.emit(`optionEnv:${option.name()}`);
1736
+ }
1737
+ }
1738
+ }
1739
+ });
1740
+ }
1741
+ _parseOptionsImplied() {
1742
+ const dualHelper = new DualOptions(this.options);
1743
+ const hasCustomOptionValue = (optionKey) => {
1744
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1745
+ };
1746
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1747
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1748
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1749
+ });
1750
+ });
1751
+ }
1752
+ missingArgument(name) {
1753
+ const message = `error: missing required argument '${name}'`;
1754
+ this.error(message, { code: "commander.missingArgument" });
1755
+ }
1756
+ optionMissingArgument(option) {
1757
+ const message = `error: option '${option.flags}' argument missing`;
1758
+ this.error(message, { code: "commander.optionMissingArgument" });
1759
+ }
1760
+ missingMandatoryOptionValue(option) {
1761
+ const message = `error: required option '${option.flags}' not specified`;
1762
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1763
+ }
1764
+ _conflictingOption(option, conflictingOption) {
1765
+ const findBestOptionFromValue = (option2) => {
1766
+ const optionKey = option2.attributeName();
1767
+ const optionValue = this.getOptionValue(optionKey);
1768
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1769
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1770
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1771
+ return negativeOption;
1772
+ }
1773
+ return positiveOption || option2;
1774
+ };
1775
+ const getErrorMessage = (option2) => {
1776
+ const bestOption = findBestOptionFromValue(option2);
1777
+ const optionKey = bestOption.attributeName();
1778
+ const source = this.getOptionValueSource(optionKey);
1779
+ if (source === "env") {
1780
+ return `environment variable '${bestOption.envVar}'`;
1781
+ }
1782
+ return `option '${bestOption.flags}'`;
1783
+ };
1784
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1785
+ this.error(message, { code: "commander.conflictingOption" });
1786
+ }
1787
+ unknownOption(flag) {
1788
+ if (this._allowUnknownOption)
1789
+ return;
1790
+ let suggestion = "";
1791
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1792
+ let candidateFlags = [];
1793
+ let command = this;
1794
+ do {
1795
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1796
+ candidateFlags = candidateFlags.concat(moreFlags);
1797
+ command = command.parent;
1798
+ } while (command && !command._enablePositionalOptions);
1799
+ suggestion = suggestSimilar(flag, candidateFlags);
1800
+ }
1801
+ const message = `error: unknown option '${flag}'${suggestion}`;
1802
+ this.error(message, { code: "commander.unknownOption" });
1803
+ }
1804
+ _excessArguments(receivedArgs) {
1805
+ if (this._allowExcessArguments)
1806
+ return;
1807
+ const expected = this.registeredArguments.length;
1808
+ const s = expected === 1 ? "" : "s";
1809
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1810
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1811
+ this.error(message, { code: "commander.excessArguments" });
1812
+ }
1813
+ unknownCommand() {
1814
+ const unknownName = this.args[0];
1815
+ let suggestion = "";
1816
+ if (this._showSuggestionAfterError) {
1817
+ const candidateNames = [];
1818
+ this.createHelp().visibleCommands(this).forEach((command) => {
1819
+ candidateNames.push(command.name());
1820
+ if (command.alias())
1821
+ candidateNames.push(command.alias());
1822
+ });
1823
+ suggestion = suggestSimilar(unknownName, candidateNames);
1824
+ }
1825
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1826
+ this.error(message, { code: "commander.unknownCommand" });
1827
+ }
1828
+ version(str, flags, description) {
1829
+ if (str === undefined)
1830
+ return this._version;
1831
+ this._version = str;
1832
+ flags = flags || "-V, --version";
1833
+ description = description || "output the version number";
1834
+ const versionOption = this.createOption(flags, description);
1835
+ this._versionOptionName = versionOption.attributeName();
1836
+ this._registerOption(versionOption);
1837
+ this.on("option:" + versionOption.name(), () => {
1838
+ this._outputConfiguration.writeOut(`${str}
1839
+ `);
1840
+ this._exit(0, "commander.version", str);
1841
+ });
1842
+ return this;
1843
+ }
1844
+ description(str, argsDescription) {
1845
+ if (str === undefined && argsDescription === undefined)
1846
+ return this._description;
1847
+ this._description = str;
1848
+ if (argsDescription) {
1849
+ this._argsDescription = argsDescription;
1850
+ }
1851
+ return this;
1852
+ }
1853
+ summary(str) {
1854
+ if (str === undefined)
1855
+ return this._summary;
1856
+ this._summary = str;
1857
+ return this;
1858
+ }
1859
+ alias(alias) {
1860
+ if (alias === undefined)
1861
+ return this._aliases[0];
1862
+ let command = this;
1863
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1864
+ command = this.commands[this.commands.length - 1];
1865
+ }
1866
+ if (alias === command._name)
1867
+ throw new Error("Command alias can't be the same as its name");
1868
+ const matchingCommand = this.parent?._findCommand(alias);
1869
+ if (matchingCommand) {
1870
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1871
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1872
+ }
1873
+ command._aliases.push(alias);
1874
+ return this;
1875
+ }
1876
+ aliases(aliases) {
1877
+ if (aliases === undefined)
1878
+ return this._aliases;
1879
+ aliases.forEach((alias) => this.alias(alias));
1880
+ return this;
1881
+ }
1882
+ usage(str) {
1883
+ if (str === undefined) {
1884
+ if (this._usage)
1885
+ return this._usage;
1886
+ const args = this.registeredArguments.map((arg) => {
1887
+ return humanReadableArgName(arg);
1888
+ });
1889
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1890
+ }
1891
+ this._usage = str;
1892
+ return this;
1893
+ }
1894
+ name(str) {
1895
+ if (str === undefined)
1896
+ return this._name;
1897
+ this._name = str;
1898
+ return this;
1899
+ }
1900
+ helpGroup(heading) {
1901
+ if (heading === undefined)
1902
+ return this._helpGroupHeading ?? "";
1903
+ this._helpGroupHeading = heading;
1904
+ return this;
1905
+ }
1906
+ commandsGroup(heading) {
1907
+ if (heading === undefined)
1908
+ return this._defaultCommandGroup ?? "";
1909
+ this._defaultCommandGroup = heading;
1910
+ return this;
1911
+ }
1912
+ optionsGroup(heading) {
1913
+ if (heading === undefined)
1914
+ return this._defaultOptionGroup ?? "";
1915
+ this._defaultOptionGroup = heading;
1916
+ return this;
1917
+ }
1918
+ _initOptionGroup(option) {
1919
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1920
+ option.helpGroup(this._defaultOptionGroup);
1921
+ }
1922
+ _initCommandGroup(cmd) {
1923
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1924
+ cmd.helpGroup(this._defaultCommandGroup);
1925
+ }
1926
+ nameFromFilename(filename) {
1927
+ this._name = path.basename(filename, path.extname(filename));
1928
+ return this;
1929
+ }
1930
+ executableDir(path2) {
1931
+ if (path2 === undefined)
1932
+ return this._executableDir;
1933
+ this._executableDir = path2;
1934
+ return this;
1935
+ }
1936
+ helpInformation(contextOptions) {
1937
+ const helper = this.createHelp();
1938
+ const context = this._getOutputContext(contextOptions);
1939
+ helper.prepareContext({
1940
+ error: context.error,
1941
+ helpWidth: context.helpWidth,
1942
+ outputHasColors: context.hasColors
1943
+ });
1944
+ const text = helper.formatHelp(this, helper);
1945
+ if (context.hasColors)
1946
+ return text;
1947
+ return this._outputConfiguration.stripColor(text);
1948
+ }
1949
+ _getOutputContext(contextOptions) {
1950
+ contextOptions = contextOptions || {};
1951
+ const error = !!contextOptions.error;
1952
+ let baseWrite;
1953
+ let hasColors;
1954
+ let helpWidth;
1955
+ if (error) {
1956
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1957
+ hasColors = this._outputConfiguration.getErrHasColors();
1958
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1959
+ } else {
1960
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1961
+ hasColors = this._outputConfiguration.getOutHasColors();
1962
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1963
+ }
1964
+ const write = (str) => {
1965
+ if (!hasColors)
1966
+ str = this._outputConfiguration.stripColor(str);
1967
+ return baseWrite(str);
1968
+ };
1969
+ return { error, write, hasColors, helpWidth };
1970
+ }
1971
+ outputHelp(contextOptions) {
1972
+ let deprecatedCallback;
1973
+ if (typeof contextOptions === "function") {
1974
+ deprecatedCallback = contextOptions;
1975
+ contextOptions = undefined;
1976
+ }
1977
+ const outputContext = this._getOutputContext(contextOptions);
1978
+ const eventContext = {
1979
+ error: outputContext.error,
1980
+ write: outputContext.write,
1981
+ command: this
1982
+ };
1983
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1984
+ this.emit("beforeHelp", eventContext);
1985
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1986
+ if (deprecatedCallback) {
1987
+ helpInformation = deprecatedCallback(helpInformation);
1988
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1989
+ throw new Error("outputHelp callback must return a string or a Buffer");
1990
+ }
1991
+ }
1992
+ outputContext.write(helpInformation);
1993
+ if (this._getHelpOption()?.long) {
1994
+ this.emit(this._getHelpOption().long);
1995
+ }
1996
+ this.emit("afterHelp", eventContext);
1997
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1998
+ }
1999
+ helpOption(flags, description) {
2000
+ if (typeof flags === "boolean") {
2001
+ if (flags) {
2002
+ if (this._helpOption === null)
2003
+ this._helpOption = undefined;
2004
+ if (this._defaultOptionGroup) {
2005
+ this._initOptionGroup(this._getHelpOption());
2006
+ }
2007
+ } else {
2008
+ this._helpOption = null;
2009
+ }
2010
+ return this;
2011
+ }
2012
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2013
+ if (flags || description)
2014
+ this._initOptionGroup(this._helpOption);
2015
+ return this;
2016
+ }
2017
+ _getHelpOption() {
2018
+ if (this._helpOption === undefined) {
2019
+ this.helpOption(undefined, undefined);
2020
+ }
2021
+ return this._helpOption;
2022
+ }
2023
+ addHelpOption(option) {
2024
+ this._helpOption = option;
2025
+ this._initOptionGroup(option);
2026
+ return this;
2027
+ }
2028
+ help(contextOptions) {
2029
+ this.outputHelp(contextOptions);
2030
+ let exitCode = Number(process2.exitCode ?? 0);
2031
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2032
+ exitCode = 1;
2033
+ }
2034
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2035
+ }
2036
+ addHelpText(position, text) {
2037
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2038
+ if (!allowedValues.includes(position)) {
2039
+ throw new Error(`Unexpected value for position to addHelpText.
2040
+ Expecting one of '${allowedValues.join("', '")}'`);
2041
+ }
2042
+ const helpEvent = `${position}Help`;
2043
+ this.on(helpEvent, (context) => {
2044
+ let helpStr;
2045
+ if (typeof text === "function") {
2046
+ helpStr = text({ error: context.error, command: context.command });
2047
+ } else {
2048
+ helpStr = text;
2049
+ }
2050
+ if (helpStr) {
2051
+ context.write(`${helpStr}
2052
+ `);
2053
+ }
2054
+ });
2055
+ return this;
2056
+ }
2057
+ _outputHelpIfRequested(args) {
2058
+ const helpOption = this._getHelpOption();
2059
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2060
+ if (helpRequested) {
2061
+ this.outputHelp();
2062
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2063
+ }
2064
+ }
2065
+ }
2066
+ function incrementNodeInspectorPort(args) {
2067
+ return args.map((arg) => {
2068
+ if (!arg.startsWith("--inspect")) {
2069
+ return arg;
2070
+ }
2071
+ let debugOption;
2072
+ let debugHost = "127.0.0.1";
2073
+ let debugPort = "9229";
2074
+ let match;
2075
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2076
+ debugOption = match[1];
2077
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2078
+ debugOption = match[1];
2079
+ if (/^\d+$/.test(match[3])) {
2080
+ debugPort = match[3];
2081
+ } else {
2082
+ debugHost = match[3];
2083
+ }
2084
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2085
+ debugOption = match[1];
2086
+ debugHost = match[3];
2087
+ debugPort = match[4];
2088
+ }
2089
+ if (debugOption && debugPort !== "0") {
2090
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2091
+ }
2092
+ return arg;
2093
+ });
2094
+ }
2095
+ function useColor() {
2096
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2097
+ return false;
2098
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2099
+ return true;
2100
+ return;
2101
+ }
2102
+ exports.Command = Command;
2103
+ exports.useColor = useColor;
2104
+ });
2105
+
2106
+ // node_modules/commander/index.js
2107
+ var require_commander = __commonJS((exports) => {
2108
+ var { Argument } = require_argument();
2109
+ var { Command } = require_command();
2110
+ var { CommanderError, InvalidArgumentError } = require_error();
2111
+ var { Help } = require_help();
2112
+ var { Option } = require_option();
2113
+ exports.program = new Command;
2114
+ exports.createCommand = (name) => new Command(name);
2115
+ exports.createOption = (flags, description) => new Option(flags, description);
2116
+ exports.createArgument = (name, description) => new Argument(name, description);
2117
+ exports.Command = Command;
2118
+ exports.Option = Option;
2119
+ exports.Argument = Argument;
2120
+ exports.Help = Help;
2121
+ exports.CommanderError = CommanderError;
2122
+ exports.InvalidArgumentError = InvalidArgumentError;
2123
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2124
+ });
2125
+
2126
+ // src/lib/database/index.ts
2127
+ var exports_database = {};
2128
+ __export(exports_database, {
2129
+ isDatabaseEmpty: () => isDatabaseEmpty,
2130
+ getTimestamp: () => getTimestamp,
2131
+ getSpecsDir: () => getSpecsDir,
2132
+ getDb: () => getDb,
2133
+ generateId: () => generateId,
2134
+ databaseExists: () => databaseExists,
2135
+ closeDb: () => closeDb
2136
+ });
2137
+ import { Database } from "bun:sqlite";
2138
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
2139
+ import { join as join3, dirname as dirname2 } from "path";
2140
+ import { fileURLToPath as fileURLToPath2 } from "url";
2141
+ function getDbPath() {
2142
+ if (process.env.MACHINE_DB_PATH) {
2143
+ return process.env.MACHINE_DB_PATH;
2144
+ }
2145
+ return join3(process.cwd(), "machine.db");
2146
+ }
2147
+ function getDb() {
2148
+ if (!db) {
2149
+ const dbPath = getDbPath();
2150
+ db = new Database(dbPath, { create: true });
2151
+ db.exec("PRAGMA foreign_keys = ON");
2152
+ initDatabase();
2153
+ }
2154
+ return db;
2155
+ }
2156
+ function initDatabase() {
2157
+ if (!db)
2158
+ return;
2159
+ const schemaPath = join3(__dirname3, "schema.sql");
2160
+ const schema = readFileSync2(schemaPath, "utf-8");
2161
+ db.exec(schema);
2162
+ }
2163
+ function closeDb() {
2164
+ if (db) {
2165
+ db.close();
2166
+ db = null;
2167
+ }
2168
+ }
2169
+ function getTimestamp() {
2170
+ return new Date().toISOString().split("T")[0];
2171
+ }
2172
+ function generateId(prefix, existingIds) {
2173
+ const numbers = existingIds.filter((id) => id.startsWith(prefix)).map((id) => {
2174
+ const match = id.match(new RegExp(`${prefix}-(\\d+)`));
2175
+ return match ? parseInt(match[1], 10) : 0;
2176
+ });
2177
+ const maxNum = numbers.length > 0 ? Math.max(...numbers) : 0;
2178
+ return `${prefix}-${String(maxNum + 1).padStart(3, "0")}`;
2179
+ }
2180
+ function isDatabaseEmpty() {
2181
+ const database = getDb();
2182
+ const result = database.query("SELECT COUNT(*) as count FROM urs").get();
2183
+ return result.count === 0;
2184
+ }
2185
+ function databaseExists() {
2186
+ const dbPath = getDbPath();
2187
+ return existsSync3(dbPath);
2188
+ }
2189
+ function getSpecsDir() {
2190
+ if (process.env.MACHINE_SPECS_DIR) {
2191
+ return process.env.MACHINE_SPECS_DIR;
2192
+ }
2193
+ return join3(process.cwd(), "specs");
2194
+ }
2195
+ var __dirname3, db = null;
2196
+ var init_database = __esm(() => {
2197
+ __dirname3 = dirname2(fileURLToPath2(import.meta.url));
2198
+ });
2199
+
2200
+ // src/lib/database/fs-repo.ts
2201
+ var exports_fs_repo = {};
2202
+ __export(exports_fs_repo, {
2203
+ syncFS: () => syncFS,
2204
+ loadFSMetadata: () => loadFSMetadata,
2205
+ loadAllFSMetadata: () => loadAllFSMetadata,
2206
+ getFSByURS: () => getFSByURS,
2207
+ deleteFS: () => deleteFS
2208
+ });
2209
+ function syncFS(fs) {
2210
+ const db2 = getDb();
2211
+ db2.query(`
2212
+ INSERT INTO fs (id, title, file_path, description, requirements,
2213
+ scenario_count, created_at, updated_at)
2214
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
2215
+ ON CONFLICT(id) DO UPDATE SET
2216
+ title = excluded.title,
2217
+ file_path = excluded.file_path,
2218
+ description = excluded.description,
2219
+ requirements = excluded.requirements,
2220
+ scenario_count = excluded.scenario_count,
2221
+ updated_at = excluded.updated_at
2222
+ `).run(fs.id, fs.title, fs.file_path, fs.description, JSON.stringify(fs.requirements), fs.scenario_count, fs.created_at, getTimestamp());
2223
+ db2.query("DELETE FROM fs_urs_link WHERE fs_id = ?").run(fs.id);
2224
+ for (const ursId of fs.urs_ids) {
2225
+ const ursExists = db2.query("SELECT id FROM urs WHERE id = ?").get(ursId);
2226
+ if (ursExists) {
2227
+ db2.query(`
2228
+ INSERT OR IGNORE INTO fs_urs_link (fs_id, urs_id) VALUES (?, ?)
2229
+ `).run(fs.id, ursId);
2230
+ }
2231
+ }
2232
+ }
2233
+ function loadAllFSMetadata() {
2234
+ const db2 = getDb();
2235
+ const rows = db2.query(`
2236
+ SELECT id, title, file_path, description, requirements,
2237
+ scenario_count, created_at, updated_at
2238
+ FROM fs
2239
+ ORDER BY id
2240
+ `).all();
2241
+ return rows.map((row) => {
2242
+ const fsId = row.id;
2243
+ const ursLinks = db2.query(`
2244
+ SELECT urs_id FROM fs_urs_link WHERE fs_id = ?
2245
+ `).all(fsId);
2246
+ const riskLinks = db2.query(`
2247
+ SELECT risk_id FROM risk_fs_link WHERE fs_id = ?
2248
+ `).all(fsId);
2249
+ return {
2250
+ id: fsId,
2251
+ type: "fs",
2252
+ title: row.title,
2253
+ file_path: row.file_path,
2254
+ description: row.description,
2255
+ requirements: JSON.parse(row.requirements || "[]"),
2256
+ urs_ids: ursLinks.map((l) => l.urs_id),
2257
+ risk_ids: riskLinks.map((l) => l.risk_id),
2258
+ scenario_count: row.scenario_count,
2259
+ created_at: row.created_at,
2260
+ updated_at: row.updated_at
2261
+ };
2262
+ });
2263
+ }
2264
+ function loadFSMetadata(id) {
2265
+ const db2 = getDb();
2266
+ const row = db2.query(`
2267
+ SELECT id, title, file_path, description, requirements,
2268
+ scenario_count, created_at, updated_at
2269
+ FROM fs
2270
+ WHERE id = ?
2271
+ `).get(id);
2272
+ if (!row)
2273
+ return null;
2274
+ const ursLinks = db2.query(`
2275
+ SELECT urs_id FROM fs_urs_link WHERE fs_id = ?
2276
+ `).all(id);
2277
+ const riskLinks = db2.query(`
2278
+ SELECT risk_id FROM risk_fs_link WHERE fs_id = ?
2279
+ `).all(id);
2280
+ return {
2281
+ id: row.id,
2282
+ type: "fs",
2283
+ title: row.title,
2284
+ file_path: row.file_path,
2285
+ description: row.description,
2286
+ requirements: JSON.parse(row.requirements || "[]"),
2287
+ urs_ids: ursLinks.map((l) => l.urs_id),
2288
+ risk_ids: riskLinks.map((l) => l.risk_id),
2289
+ scenario_count: row.scenario_count,
2290
+ created_at: row.created_at,
2291
+ updated_at: row.updated_at
2292
+ };
2293
+ }
2294
+ function getFSByURS(ursId) {
2295
+ const db2 = getDb();
2296
+ const links = db2.query(`
2297
+ SELECT fs_id FROM fs_urs_link WHERE urs_id = ?
2298
+ `).all(ursId);
2299
+ return links.map((l) => l.fs_id);
2300
+ }
2301
+ function deleteFS(id) {
2302
+ const db2 = getDb();
2303
+ const result = db2.query("DELETE FROM fs WHERE id = ?").run(id);
2304
+ return result.changes > 0;
2305
+ }
2306
+ var init_fs_repo = __esm(() => {
2307
+ init_database();
2308
+ });
2309
+
2310
+ // src/lib/database/embeddings.ts
2311
+ import { EmbeddingModel, FlagEmbedding } from "fastembed";
2312
+ async function getEmbeddingModel() {
2313
+ if (!embeddingModel) {
2314
+ embeddingModel = await FlagEmbedding.init({
2315
+ model: EmbeddingModel.BGESmallENV15
2316
+ });
2317
+ }
2318
+ return embeddingModel;
2319
+ }
2320
+ async function generateEmbedding(text) {
2321
+ const model = await getEmbeddingModel();
2322
+ const embedding = await model.queryEmbed(text);
2323
+ return new Float32Array(embedding);
2324
+ }
2325
+ async function generateEmbeddings(texts) {
2326
+ if (texts.length === 0)
2327
+ return [];
2328
+ const model = await getEmbeddingModel();
2329
+ const results = [];
2330
+ const batchSize = 256;
2331
+ const embeddings = model.embed(texts, batchSize);
2332
+ for await (const batch of embeddings) {
2333
+ for (const embedding of batch) {
2334
+ results.push(new Float32Array(embedding));
2335
+ }
2336
+ }
2337
+ if (results.length !== texts.length) {
2338
+ console.warn(`Expected ${texts.length} embeddings, got ${results.length}`);
2339
+ }
2340
+ return results;
2341
+ }
2342
+ function cosineSimilarity(a, b) {
2343
+ if (a.length !== b.length) {
2344
+ throw new Error("Vectors must have the same length");
2345
+ }
2346
+ let dotProduct = 0;
2347
+ let normA = 0;
2348
+ let normB = 0;
2349
+ for (let i = 0;i < a.length; i++) {
2350
+ dotProduct += a[i] * b[i];
2351
+ normA += a[i] * a[i];
2352
+ normB += b[i] * b[i];
2353
+ }
2354
+ const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
2355
+ return magnitude === 0 ? 0 : dotProduct / magnitude;
2356
+ }
2357
+ function serializeEmbedding(embedding) {
2358
+ return Buffer.from(embedding.buffer);
2359
+ }
2360
+ function deserializeEmbedding(buffer) {
2361
+ return new Float32Array(buffer.buffer, buffer.byteOffset, buffer.length / 4);
2362
+ }
2363
+ var embeddingModel = null;
2364
+ var init_embeddings = () => {};
2365
+
2366
+ // src/lib/database/step-repo.ts
2367
+ var exports_step_repo = {};
2368
+ __export(exports_step_repo, {
2369
+ searchSteps: () => searchSteps,
2370
+ reindexAllSteps: () => reindexAllSteps,
2371
+ indexSteps: () => indexSteps,
2372
+ getStepsForFS: () => getStepsForFS,
2373
+ getStepCount: () => getStepCount
2374
+ });
2375
+ async function indexSteps(fsId, scenarios) {
2376
+ const db2 = getDb();
2377
+ db2.query("DELETE FROM step WHERE fs_id = ?").run(fsId);
2378
+ const stepsToIndex = [];
2379
+ for (const scenario of scenarios) {
2380
+ for (const step of scenario.steps) {
2381
+ stepsToIndex.push({
2382
+ scenarioName: scenario.name,
2383
+ stepText: step
2384
+ });
2385
+ }
2386
+ }
2387
+ if (stepsToIndex.length === 0)
2388
+ return 0;
2389
+ const texts = stepsToIndex.map((s) => s.stepText);
2390
+ const embeddings = await generateEmbeddings(texts);
2391
+ const stmt = db2.query(`
2392
+ INSERT INTO step (fs_id, scenario_name, step_text, embedding)
2393
+ VALUES (?, ?, ?, ?)
2394
+ `);
2395
+ for (let i = 0;i < stepsToIndex.length; i++) {
2396
+ const step = stepsToIndex[i];
2397
+ const embedding = embeddings[i];
2398
+ stmt.run(fsId, step.scenarioName, step.stepText, serializeEmbedding(embedding));
2399
+ }
2400
+ return stepsToIndex.length;
2401
+ }
2402
+ async function searchSteps(query, limit = 10) {
2403
+ const db2 = getDb();
2404
+ const queryEmbedding = await generateEmbedding(query);
2405
+ const rows = db2.query(`
2406
+ SELECT fs_id, scenario_name, step_text, embedding
2407
+ FROM step
2408
+ WHERE embedding IS NOT NULL
2409
+ `).all();
2410
+ const results = rows.map((row) => {
2411
+ const embedding = deserializeEmbedding(row.embedding);
2412
+ const similarity = cosineSimilarity(queryEmbedding, embedding);
2413
+ return {
2414
+ fsId: row.fs_id,
2415
+ scenarioName: row.scenario_name,
2416
+ stepText: row.step_text,
2417
+ similarity
2418
+ };
2419
+ });
2420
+ return results.sort((a, b) => b.similarity - a.similarity).slice(0, limit);
2421
+ }
2422
+ async function reindexAllSteps(fsItems) {
2423
+ let total = 0;
2424
+ let indexed = 0;
2425
+ for (const fs of fsItems) {
2426
+ for (const scenario of fs.scenarios) {
2427
+ total += scenario.steps.length;
2428
+ }
2429
+ indexed += await indexSteps(fs.id, fs.scenarios);
2430
+ }
2431
+ return { total, indexed };
2432
+ }
2433
+ function getStepCount(fsId) {
2434
+ const db2 = getDb();
2435
+ const result = db2.query(`
2436
+ SELECT COUNT(*) as count FROM step WHERE fs_id = ?
2437
+ `).get(fsId);
2438
+ return result.count;
2439
+ }
2440
+ function getStepsForFS(fsId) {
2441
+ const db2 = getDb();
2442
+ const rows = db2.query(`
2443
+ SELECT scenario_name, step_text FROM step
2444
+ WHERE fs_id = ?
2445
+ ORDER BY id
2446
+ `).all(fsId);
2447
+ return rows.map((r) => ({
2448
+ scenarioName: r.scenario_name,
2449
+ stepText: r.step_text
2450
+ }));
2451
+ }
2452
+ var init_step_repo = __esm(() => {
2453
+ init_database();
2454
+ init_embeddings();
2455
+ });
2456
+
2457
+ // src/lib/database/urs-repo.ts
2458
+ var exports_urs_repo = {};
2459
+ __export(exports_urs_repo, {
2460
+ validateURS: () => validateURS,
2461
+ updateURS: () => updateURS,
2462
+ loadURS: () => loadURS,
2463
+ loadAllURS: () => loadAllURS,
2464
+ deleteURS: () => deleteURS,
2465
+ createURS: () => createURS,
2466
+ canDeleteURS: () => canDeleteURS
2467
+ });
2468
+ function loadAllURS() {
2469
+ const db2 = getDb();
2470
+ const rows = db2.query(`
2471
+ SELECT id, title, status, priority, owner, category,
2472
+ created_at, updated_at, business_need, intended_use,
2473
+ acceptance_criteria, regulatory_refs
2474
+ FROM urs
2475
+ ORDER BY id
2476
+ `).all();
2477
+ return rows.map((row) => ({
2478
+ id: row.id,
2479
+ type: "urs",
2480
+ title: row.title,
2481
+ status: row.status,
2482
+ priority: row.priority,
2483
+ owner: row.owner,
2484
+ category: row.category,
2485
+ created_at: row.created_at,
2486
+ updated_at: row.updated_at,
2487
+ business_need: row.business_need,
2488
+ intended_use: row.intended_use,
2489
+ acceptance_criteria: JSON.parse(row.acceptance_criteria),
2490
+ regulatory_refs: JSON.parse(row.regulatory_refs)
2491
+ }));
2492
+ }
2493
+ function loadURS(id) {
2494
+ const db2 = getDb();
2495
+ const row = db2.query(`
2496
+ SELECT id, title, status, priority, owner, category,
2497
+ created_at, updated_at, business_need, intended_use,
2498
+ acceptance_criteria, regulatory_refs
2499
+ FROM urs
2500
+ WHERE id = ?
2501
+ `).get(id);
2502
+ if (!row)
2503
+ return null;
2504
+ return {
2505
+ id: row.id,
2506
+ type: "urs",
2507
+ title: row.title,
2508
+ status: row.status,
2509
+ priority: row.priority,
2510
+ owner: row.owner,
2511
+ category: row.category,
2512
+ created_at: row.created_at,
2513
+ updated_at: row.updated_at,
2514
+ business_need: row.business_need,
2515
+ intended_use: row.intended_use,
2516
+ acceptance_criteria: JSON.parse(row.acceptance_criteria),
2517
+ regulatory_refs: JSON.parse(row.regulatory_refs)
2518
+ };
2519
+ }
2520
+ function createURS(data, forcedId) {
2521
+ const db2 = getDb();
2522
+ const existingIds = loadAllURS().map((u) => u.id);
2523
+ const id = forcedId || generateId("URS", existingIds);
2524
+ const timestamp = getTimestamp();
2525
+ const urs = {
2526
+ ...data,
2527
+ id,
2528
+ type: "urs",
2529
+ created_at: timestamp,
2530
+ updated_at: timestamp
2531
+ };
2532
+ db2.query(`
2533
+ INSERT INTO urs (id, title, status, priority, owner, category,
2534
+ created_at, updated_at, business_need, intended_use,
2535
+ acceptance_criteria, regulatory_refs)
2536
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2537
+ `).run(urs.id, urs.title, urs.status, urs.priority, urs.owner, urs.category, urs.created_at, urs.updated_at, urs.business_need, urs.intended_use, JSON.stringify(urs.acceptance_criteria), JSON.stringify(urs.regulatory_refs));
2538
+ return urs;
2539
+ }
2540
+ function updateURS(id, data) {
2541
+ const existing = loadURS(id);
2542
+ if (!existing)
2543
+ return null;
2544
+ const db2 = getDb();
2545
+ const updated = {
2546
+ ...existing,
2547
+ ...data,
2548
+ id: existing.id,
2549
+ type: "urs",
2550
+ updated_at: getTimestamp()
2551
+ };
2552
+ db2.query(`
2553
+ UPDATE urs SET
2554
+ title = ?, status = ?, priority = ?, owner = ?, category = ?,
2555
+ updated_at = ?, business_need = ?, intended_use = ?,
2556
+ acceptance_criteria = ?, regulatory_refs = ?
2557
+ WHERE id = ?
2558
+ `).run(updated.title, updated.status, updated.priority, updated.owner, updated.category, updated.updated_at, updated.business_need, updated.intended_use, JSON.stringify(updated.acceptance_criteria), JSON.stringify(updated.regulatory_refs), id);
2559
+ return updated;
2560
+ }
2561
+ function deleteURS(id) {
2562
+ const db2 = getDb();
2563
+ const result = db2.query("DELETE FROM urs WHERE id = ?").run(id);
2564
+ return result.changes > 0;
2565
+ }
2566
+ function validateURS(urs) {
2567
+ const errors = [];
2568
+ if (!urs.title?.trim()) {
2569
+ errors.push({ field: "title", message: "Title is required" });
2570
+ }
2571
+ if (!urs.owner?.trim()) {
2572
+ errors.push({ field: "owner", message: "Owner is required" });
2573
+ }
2574
+ if (!urs.business_need?.trim()) {
2575
+ errors.push({ field: "business_need", message: "Business need is required" });
2576
+ }
2577
+ if (!urs.intended_use?.trim()) {
2578
+ errors.push({ field: "intended_use", message: "Intended use is required" });
2579
+ }
2580
+ return { valid: errors.length === 0, errors };
2581
+ }
2582
+ function canDeleteURS(ursId) {
2583
+ const db2 = getDb();
2584
+ const links = db2.query(`
2585
+ SELECT COUNT(*) as count FROM fs_urs_link WHERE urs_id = ?
2586
+ `).get(ursId);
2587
+ if (links.count > 0) {
2588
+ return {
2589
+ canDelete: false,
2590
+ reason: `URS is linked to ${links.count} Functional Specification(s)`
2591
+ };
2592
+ }
2593
+ return { canDelete: true };
2594
+ }
2595
+ var init_urs_repo = __esm(() => {
2596
+ init_database();
2597
+ });
2598
+
2599
+ // src/lib/database/risk-repo.ts
2600
+ var exports_risk_repo = {};
2601
+ __export(exports_risk_repo, {
2602
+ validateRisk: () => validateRisk,
2603
+ updateRisk: () => updateRisk,
2604
+ loadRisk: () => loadRisk,
2605
+ loadAllRisks: () => loadAllRisks,
2606
+ getRisksByFS: () => getRisksByFS,
2607
+ deleteRisk: () => deleteRisk,
2608
+ createRisk: () => createRisk
2609
+ });
2610
+ function loadAllRisks() {
2611
+ const db2 = getDb();
2612
+ const risks = db2.query(`
2613
+ SELECT id, title, status, category, gamp_category,
2614
+ created_at, updated_at, impact, probability, risk_level, residual_risk
2615
+ FROM risk
2616
+ ORDER BY id
2617
+ `).all();
2618
+ return risks.map((row) => loadRiskWithDetails(row));
2619
+ }
2620
+ function loadRisk(id) {
2621
+ const db2 = getDb();
2622
+ const row = db2.query(`
2623
+ SELECT id, title, status, category, gamp_category,
2624
+ created_at, updated_at, impact, probability, risk_level, residual_risk
2625
+ FROM risk
2626
+ WHERE id = ?
2627
+ `).get(id);
2628
+ if (!row)
2629
+ return null;
2630
+ return loadRiskWithDetails(row);
2631
+ }
2632
+ function loadRiskWithDetails(row) {
2633
+ const db2 = getDb();
2634
+ const riskId = row.id;
2635
+ const items = db2.query(`
2636
+ SELECT item_id, description, impact, probability
2637
+ FROM risk_item
2638
+ WHERE risk_id = ?
2639
+ ORDER BY item_id
2640
+ `).all(riskId);
2641
+ const mitigations = db2.query(`
2642
+ SELECT risk_item_id, control, test
2643
+ FROM mitigation
2644
+ WHERE risk_id = ?
2645
+ `).all(riskId);
2646
+ const fsLinks = db2.query(`
2647
+ SELECT fs_id FROM risk_fs_link WHERE risk_id = ?
2648
+ `).all(riskId);
2649
+ return {
2650
+ id: riskId,
2651
+ type: "risk",
2652
+ title: row.title,
2653
+ status: row.status,
2654
+ category: row.category,
2655
+ gamp_category: row.gamp_category,
2656
+ created_at: row.created_at,
2657
+ updated_at: row.updated_at,
2658
+ fs_ids: fsLinks.map((l) => l.fs_id),
2659
+ impact: row.impact,
2660
+ probability: row.probability,
2661
+ risk_level: row.risk_level,
2662
+ risks: items.map((item) => ({
2663
+ id: item.item_id,
2664
+ description: item.description,
2665
+ impact: item.impact,
2666
+ probability: item.probability
2667
+ })),
2668
+ mitigations: mitigations.map((m) => ({
2669
+ risk_id: m.risk_item_id,
2670
+ control: m.control,
2671
+ test: m.test
2672
+ })),
2673
+ residual_risk: row.residual_risk
2674
+ };
2675
+ }
2676
+ function createRisk(data, forcedId) {
2677
+ const db2 = getDb();
2678
+ const existingIds = loadAllRisks().map((r) => r.id);
2679
+ const id = forcedId || generateId("RISK", existingIds);
2680
+ const timestamp = getTimestamp();
2681
+ db2.query(`
2682
+ INSERT INTO risk (id, title, status, category, gamp_category,
2683
+ created_at, updated_at, impact, probability,
2684
+ risk_level, residual_risk)
2685
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2686
+ `).run(id, data.title, data.status, data.category, data.gamp_category, timestamp, timestamp, data.impact, data.probability, data.risk_level, data.residual_risk);
2687
+ for (const fsId of data.fs_ids) {
2688
+ db2.query(`
2689
+ INSERT OR IGNORE INTO risk_fs_link (risk_id, fs_id) VALUES (?, ?)
2690
+ `).run(id, fsId);
2691
+ }
2692
+ for (const item of data.risks) {
2693
+ db2.query(`
2694
+ INSERT INTO risk_item (risk_id, item_id, description, impact, probability)
2695
+ VALUES (?, ?, ?, ?, ?)
2696
+ `).run(id, item.id, item.description, item.impact, item.probability);
2697
+ }
2698
+ for (const mitigation of data.mitigations) {
2699
+ db2.query(`
2700
+ INSERT INTO mitigation (risk_id, risk_item_id, control, test)
2701
+ VALUES (?, ?, ?, ?)
2702
+ `).run(id, mitigation.risk_id, mitigation.control, mitigation.test);
2703
+ }
2704
+ return loadRisk(id);
2705
+ }
2706
+ function updateRisk(id, data) {
2707
+ const existing = loadRisk(id);
2708
+ if (!existing)
2709
+ return null;
2710
+ const db2 = getDb();
2711
+ const timestamp = getTimestamp();
2712
+ db2.query(`
2713
+ UPDATE risk SET
2714
+ title = ?, status = ?, category = ?, gamp_category = ?,
2715
+ updated_at = ?, impact = ?, probability = ?, risk_level = ?,
2716
+ residual_risk = ?
2717
+ WHERE id = ?
2718
+ `).run(data.title ?? existing.title, data.status ?? existing.status, data.category ?? existing.category, data.gamp_category ?? existing.gamp_category, timestamp, data.impact ?? existing.impact, data.probability ?? existing.probability, data.risk_level ?? existing.risk_level, data.residual_risk ?? existing.residual_risk, id);
2719
+ if (data.fs_ids) {
2720
+ db2.query("DELETE FROM risk_fs_link WHERE risk_id = ?").run(id);
2721
+ for (const fsId of data.fs_ids) {
2722
+ db2.query(`
2723
+ INSERT OR IGNORE INTO risk_fs_link (risk_id, fs_id) VALUES (?, ?)
2724
+ `).run(id, fsId);
2725
+ }
2726
+ }
2727
+ if (data.risks) {
2728
+ db2.query("DELETE FROM risk_item WHERE risk_id = ?").run(id);
2729
+ for (const item of data.risks) {
2730
+ db2.query(`
2731
+ INSERT INTO risk_item (risk_id, item_id, description, impact, probability)
2732
+ VALUES (?, ?, ?, ?, ?)
2733
+ `).run(id, item.id, item.description, item.impact, item.probability);
2734
+ }
2735
+ }
2736
+ if (data.mitigations) {
2737
+ db2.query("DELETE FROM mitigation WHERE risk_id = ?").run(id);
2738
+ for (const mitigation of data.mitigations) {
2739
+ db2.query(`
2740
+ INSERT INTO mitigation (risk_id, risk_item_id, control, test)
2741
+ VALUES (?, ?, ?, ?)
2742
+ `).run(id, mitigation.risk_id, mitigation.control, mitigation.test);
2743
+ }
2744
+ }
2745
+ return loadRisk(id);
2746
+ }
2747
+ function deleteRisk(id) {
2748
+ const db2 = getDb();
2749
+ const result = db2.query("DELETE FROM risk WHERE id = ?").run(id);
2750
+ return result.changes > 0;
2751
+ }
2752
+ function validateRisk(risk) {
2753
+ const errors = [];
2754
+ if (!risk.title?.trim()) {
2755
+ errors.push({ field: "title", message: "Title is required" });
2756
+ }
2757
+ if (!risk.category?.trim()) {
2758
+ errors.push({ field: "category", message: "Category is required" });
2759
+ }
2760
+ if (!risk.fs_ids?.length) {
2761
+ errors.push({ field: "fs_ids", message: "At least one FS must be linked" });
2762
+ }
2763
+ return { valid: errors.length === 0, errors };
2764
+ }
2765
+ function getRisksByFS(fsId) {
2766
+ const db2 = getDb();
2767
+ const links = db2.query(`
2768
+ SELECT risk_id FROM risk_fs_link WHERE fs_id = ?
2769
+ `).all(fsId);
2770
+ return links.map((l) => loadRisk(l.risk_id)).filter((r) => r !== null);
2771
+ }
2772
+ var init_risk_repo = __esm(() => {
2773
+ init_database();
2774
+ });
2775
+
2776
+ // src/lib/gherkin-parser.ts
2777
+ var exports_gherkin_parser = {};
2778
+ __export(exports_gherkin_parser, {
2779
+ parseGherkinFS: () => parseGherkinFS
2780
+ });
2781
+ import { statSync } from "fs";
2782
+ import { basename } from "path";
2783
+ function parseGherkinFS(content, filePath) {
2784
+ const lines = content.split(`
2785
+ `);
2786
+ const scenarios = [];
2787
+ const fileTags = [];
2788
+ let featureStarted = false;
2789
+ for (const line of lines) {
2790
+ const trimmed = line.trim();
2791
+ if (trimmed.startsWith("@") && !featureStarted) {
2792
+ const tags = trimmed.split(/\s+/).filter((t) => t.startsWith("@"));
2793
+ fileTags.push(...tags);
2794
+ } else if (trimmed.startsWith("Feature:")) {
2795
+ featureStarted = true;
2796
+ break;
2797
+ }
2798
+ }
2799
+ const featureLine = lines.find((l) => l.trim().startsWith("Feature:"));
2800
+ const featureMatch = featureLine?.match(/Feature:\s*(.+)/);
2801
+ const fullTitle = featureMatch?.[1] || basename(filePath);
2802
+ const idMatch = fullTitle.match(/^(FS-\d+)/);
2803
+ const id = idMatch?.[1] || basename(filePath, ".requirement").toUpperCase();
2804
+ const featureIndex = lines.findIndex((l) => l.trim().startsWith("Feature:"));
2805
+ let description = "";
2806
+ const requirements = [];
2807
+ for (let i = featureIndex + 1;i < lines.length; i++) {
2808
+ const trimmed = lines[i].trim();
2809
+ if (trimmed.startsWith("Scenario") || trimmed.startsWith("Background") || trimmed.startsWith("@")) {
2810
+ break;
2811
+ }
2812
+ if (trimmed.startsWith("-")) {
2813
+ requirements.push(trimmed.substring(1).trim());
2814
+ } else if (trimmed && !trimmed.startsWith("Requirements:")) {
2815
+ description += (description ? " " : "") + trimmed;
2816
+ }
2817
+ }
2818
+ let currentScenario = null;
2819
+ let inExamples = false;
2820
+ let exampleHeaders = [];
2821
+ for (let i = 0;i < lines.length; i++) {
2822
+ const trimmed = lines[i].trim();
2823
+ if (trimmed.startsWith("Scenario Outline:") || trimmed.startsWith("Scenario:")) {
2824
+ if (currentScenario) {
2825
+ scenarios.push(currentScenario);
2826
+ }
2827
+ const isOutline = trimmed.startsWith("Scenario Outline:");
2828
+ const name = trimmed.replace(/Scenario( Outline)?:\s*/, "");
2829
+ const scenarioTags = [];
2830
+ for (let j = i - 1;j >= 0; j--) {
2831
+ const prevLine = lines[j].trim();
2832
+ if (prevLine.startsWith("@")) {
2833
+ const tags = prevLine.split(/\s+/).filter((t) => t.startsWith("@"));
2834
+ scenarioTags.unshift(...tags);
2835
+ } else if (prevLine) {
2836
+ break;
2837
+ }
2838
+ }
2839
+ currentScenario = {
2840
+ name,
2841
+ tags: scenarioTags,
2842
+ steps: [],
2843
+ line: i + 1,
2844
+ is_outline: isOutline
2845
+ };
2846
+ inExamples = false;
2847
+ }
2848
+ if (currentScenario && !inExamples && /^(Given|When|Then|And|But)\s/.test(trimmed)) {
2849
+ currentScenario.steps.push(trimmed);
2850
+ }
2851
+ if (trimmed.startsWith("Examples:")) {
2852
+ inExamples = true;
2853
+ exampleHeaders = [];
2854
+ }
2855
+ if (inExamples && trimmed.startsWith("|")) {
2856
+ const cells = trimmed.split("|").map((c) => c.trim()).filter((c) => c);
2857
+ if (exampleHeaders.length === 0) {
2858
+ exampleHeaders = cells;
2859
+ if (currentScenario) {
2860
+ currentScenario.examples = {};
2861
+ for (const header of exampleHeaders) {
2862
+ currentScenario.examples[header] = [];
2863
+ }
2864
+ }
2865
+ } else if (currentScenario?.examples) {
2866
+ for (let j = 0;j < cells.length && j < exampleHeaders.length; j++) {
2867
+ currentScenario.examples[exampleHeaders[j]].push(cells[j]);
2868
+ }
2869
+ }
2870
+ }
2871
+ }
2872
+ if (currentScenario) {
2873
+ scenarios.push(currentScenario);
2874
+ }
2875
+ const ursIds = fileTags.filter((t) => t.match(/@URS-\d+/)).map((t) => t.replace("@", ""));
2876
+ const riskIds = fileTags.filter((t) => t.match(/@RISK-\d+/)).map((t) => t.replace("@", ""));
2877
+ let createdAt = new Date().toISOString().split("T")[0];
2878
+ let updatedAt = createdAt;
2879
+ try {
2880
+ const stats = statSync(filePath);
2881
+ createdAt = stats.birthtime.toISOString().split("T")[0];
2882
+ updatedAt = stats.mtime.toISOString().split("T")[0];
2883
+ } catch {}
2884
+ return {
2885
+ id,
2886
+ type: "fs",
2887
+ title: fullTitle,
2888
+ file_path: filePath,
2889
+ description,
2890
+ requirements,
2891
+ urs_ids: ursIds,
2892
+ risk_ids: riskIds,
2893
+ scenarios,
2894
+ scenario_count: scenarios.length,
2895
+ created_at: createdAt,
2896
+ updated_at: updatedAt
2897
+ };
2898
+ }
2899
+ var init_gherkin_parser = () => {};
2900
+
2901
+ // src/lib/database/release-repo.ts
2902
+ var exports_release_repo = {};
2903
+ __export(exports_release_repo, {
2904
+ updateRelease: () => updateRelease,
2905
+ removeFSFromRelease: () => removeFSFromRelease,
2906
+ loadRelease: () => loadRelease,
2907
+ loadAllReleases: () => loadAllReleases,
2908
+ getReleasesForFS: () => getReleasesForFS,
2909
+ getFSForRelease: () => getFSForRelease,
2910
+ deleteRelease: () => deleteRelease,
2911
+ createRelease: () => createRelease,
2912
+ addFSToRelease: () => addFSToRelease
2913
+ });
2914
+ function loadAllReleases() {
2915
+ const db2 = getDb();
2916
+ const releases = db2.query(`
2917
+ SELECT r.*,
2918
+ (SELECT COUNT(*) FROM release_fs WHERE release_id = r.id) as fs_count,
2919
+ (SELECT COUNT(*) FROM test_run WHERE release_id = r.id) as test_runs
2920
+ FROM release r
2921
+ ORDER BY r.created_at DESC
2922
+ `).all();
2923
+ return releases.map((r) => {
2924
+ const latestRun = db2.query(`
2925
+ SELECT passed, total FROM test_run
2926
+ WHERE release_id = ?
2927
+ ORDER BY run_date DESC LIMIT 1
2928
+ `).get(r.id);
2929
+ return {
2930
+ ...r,
2931
+ latest_pass_rate: latestRun && latestRun.total > 0 ? latestRun.passed / latestRun.total * 100 : null
2932
+ };
2933
+ });
2934
+ }
2935
+ function loadRelease(id) {
2936
+ const db2 = getDb();
2937
+ const row = db2.query(`SELECT * FROM release WHERE id = ?`).get(id);
2938
+ return row;
2939
+ }
2940
+ function createRelease(data) {
2941
+ const db2 = getDb();
2942
+ const existingIds = loadAllReleases().map((r) => r.id);
2943
+ const id = generateId("REL", existingIds);
2944
+ const timestamp = getTimestamp();
2945
+ db2.query(`
2946
+ INSERT INTO release (id, version, name, status, created_at, notes)
2947
+ VALUES (?, ?, ?, 'planning', ?, ?)
2948
+ `).run(id, data.version, data.name, timestamp, data.notes || null);
2949
+ return loadRelease(id);
2950
+ }
2951
+ function updateRelease(id, data) {
2952
+ const existing = loadRelease(id);
2953
+ if (!existing)
2954
+ return null;
2955
+ const db2 = getDb();
2956
+ const releasedAt = data.status === "released" && existing.status !== "released" ? getTimestamp() : data.released_at ?? existing.released_at;
2957
+ db2.query(`
2958
+ UPDATE release SET
2959
+ version = ?, name = ?, status = ?, released_at = ?, notes = ?
2960
+ WHERE id = ?
2961
+ `).run(data.version ?? existing.version, data.name ?? existing.name, data.status ?? existing.status, releasedAt, data.notes ?? existing.notes, id);
2962
+ return loadRelease(id);
2963
+ }
2964
+ function deleteRelease(id) {
2965
+ const db2 = getDb();
2966
+ const result = db2.query("DELETE FROM release WHERE id = ?").run(id);
2967
+ return result.changes > 0;
2968
+ }
2969
+ function addFSToRelease(releaseId, fsId) {
2970
+ const db2 = getDb();
2971
+ const timestamp = getTimestamp();
2972
+ db2.query(`
2973
+ INSERT OR IGNORE INTO release_fs (release_id, fs_id, added_at)
2974
+ VALUES (?, ?, ?)
2975
+ `).run(releaseId, fsId, timestamp);
2976
+ }
2977
+ function removeFSFromRelease(releaseId, fsId) {
2978
+ const db2 = getDb();
2979
+ db2.query(`DELETE FROM release_fs WHERE release_id = ? AND fs_id = ?`).run(releaseId, fsId);
2980
+ }
2981
+ function getFSForRelease(releaseId) {
2982
+ const db2 = getDb();
2983
+ const rows = db2.query(`
2984
+ SELECT fs_id FROM release_fs WHERE release_id = ? ORDER BY added_at
2985
+ `).all(releaseId);
2986
+ return rows.map((r) => r.fs_id);
2987
+ }
2988
+ function getReleasesForFS(fsId) {
2989
+ const db2 = getDb();
2990
+ const rows = db2.query(`
2991
+ SELECT r.* FROM release r
2992
+ JOIN release_fs rf ON r.id = rf.release_id
2993
+ WHERE rf.fs_id = ?
2994
+ ORDER BY r.created_at DESC
2995
+ `).all(fsId);
2996
+ return rows;
2997
+ }
2998
+ var init_release_repo = __esm(() => {
2999
+ init_database();
3000
+ });
3001
+
3002
+ // src/lib/database/test-repo.ts
3003
+ var exports_test_repo = {};
3004
+ __export(exports_test_repo, {
3005
+ loadTestRuns: () => loadTestRuns,
3006
+ loadTestRun: () => loadTestRun,
3007
+ importCucumberResults: () => importCucumberResults,
3008
+ deleteTestRun: () => deleteTestRun,
3009
+ createTestRun: () => createTestRun
3010
+ });
3011
+ import { readFileSync as readFileSync4 } from "fs";
3012
+ function loadTestRuns(releaseId) {
3013
+ const db2 = getDb();
3014
+ return db2.query(`
3015
+ SELECT * FROM test_run WHERE release_id = ? ORDER BY run_date DESC
3016
+ `).all(releaseId);
3017
+ }
3018
+ function loadTestRun(id) {
3019
+ const db2 = getDb();
3020
+ const run = db2.query(`SELECT * FROM test_run WHERE id = ?`).get(id);
3021
+ if (!run)
3022
+ return null;
3023
+ const results = db2.query(`
3024
+ SELECT * FROM test_result WHERE test_run_id = ? ORDER BY fs_id, scenario_name
3025
+ `).all(id);
3026
+ return { ...run, results };
3027
+ }
3028
+ function createTestRun(releaseId, results) {
3029
+ const db2 = getDb();
3030
+ const timestamp = getTimestamp();
3031
+ const stats = {
3032
+ total: results.length,
3033
+ passed: results.filter((r) => r.status === "passed").length,
3034
+ failed: results.filter((r) => r.status === "failed").length,
3035
+ skipped: results.filter((r) => r.status === "skipped" || r.status === "pending").length
3036
+ };
3037
+ const result = db2.query(`
3038
+ INSERT INTO test_run (release_id, run_date, source, total, passed, failed, skipped)
3039
+ VALUES (?, ?, 'manual', ?, ?, ?, ?)
3040
+ `).run(releaseId, timestamp, stats.total, stats.passed, stats.failed, stats.skipped);
3041
+ const runId = Number(result.lastInsertRowid);
3042
+ for (const r of results) {
3043
+ db2.query(`
3044
+ INSERT INTO test_result (test_run_id, fs_id, scenario_name, status, duration_ms, error_message)
3045
+ VALUES (?, ?, ?, ?, ?, ?)
3046
+ `).run(runId, r.fs_id, r.scenario_name, r.status, r.duration_ms || null, r.error_message || null);
3047
+ }
3048
+ return loadTestRuns(releaseId).find((r) => r.id === runId);
3049
+ }
3050
+ function importCucumberResults(releaseId, jsonPath) {
3051
+ const content = readFileSync4(jsonPath, "utf-8");
3052
+ const cucumberData = JSON.parse(content);
3053
+ const results = [];
3054
+ for (const feature of cucumberData) {
3055
+ const fsIdMatch = feature.name?.match(/(FS-\d+)/) || feature.uri?.match(/(FS-\d+)/i);
3056
+ const fsId = fsIdMatch ? fsIdMatch[1].toUpperCase() : feature.uri?.replace(/.*\//, "").replace(".feature", "") || "UNKNOWN";
3057
+ for (const element of feature.elements || []) {
3058
+ if (element.type !== "scenario")
3059
+ continue;
3060
+ let status = "passed";
3061
+ let totalDuration = 0;
3062
+ let errorMessage;
3063
+ for (const step of element.steps || []) {
3064
+ if (step.result) {
3065
+ totalDuration += step.result.duration || 0;
3066
+ if (step.result.status === "failed") {
3067
+ status = "failed";
3068
+ errorMessage = step.result.error_message;
3069
+ } else if (step.result.status === "skipped" && status !== "failed") {
3070
+ status = "skipped";
3071
+ } else if (step.result.status === "pending" && status !== "failed" && status !== "skipped") {
3072
+ status = "pending";
3073
+ }
3074
+ }
3075
+ }
3076
+ results.push({
3077
+ fs_id: fsId,
3078
+ scenario_name: element.name || "Unknown Scenario",
3079
+ status,
3080
+ duration_ms: Math.round(totalDuration / 1e6),
3081
+ error_message: errorMessage
3082
+ });
3083
+ }
3084
+ }
3085
+ const db2 = getDb();
3086
+ const timestamp = new Date().toISOString();
3087
+ const stats = {
3088
+ total: results.length,
3089
+ passed: results.filter((r) => r.status === "passed").length,
3090
+ failed: results.filter((r) => r.status === "failed").length,
3091
+ skipped: results.filter((r) => r.status === "skipped" || r.status === "pending").length
3092
+ };
3093
+ const result = db2.query(`
3094
+ INSERT INTO test_run (release_id, run_date, source, total, passed, failed, skipped)
3095
+ VALUES (?, ?, 'cucumber', ?, ?, ?, ?)
3096
+ `).run(releaseId, timestamp, stats.total, stats.passed, stats.failed, stats.skipped);
3097
+ const runId = Number(result.lastInsertRowid);
3098
+ for (const r of results) {
3099
+ db2.query(`
3100
+ INSERT INTO test_result (test_run_id, fs_id, scenario_name, status, duration_ms, error_message)
3101
+ VALUES (?, ?, ?, ?, ?, ?)
3102
+ `).run(runId, r.fs_id, r.scenario_name, r.status, r.duration_ms || null, r.error_message || null);
3103
+ }
3104
+ return loadTestRuns(releaseId).find((r) => r.id === runId);
3105
+ }
3106
+ function deleteTestRun(id) {
3107
+ const db2 = getDb();
3108
+ const result = db2.query("DELETE FROM test_run WHERE id = ?").run(id);
3109
+ return result.changes > 0;
3110
+ }
3111
+ var init_test_repo = __esm(() => {
3112
+ init_database();
3113
+ });
3114
+
3115
+ // node_modules/commander/esm.mjs
3116
+ var import__ = __toESM(require_commander(), 1);
3117
+ var {
3118
+ program,
3119
+ createCommand,
3120
+ createArgument,
3121
+ createOption,
3122
+ CommanderError,
3123
+ InvalidArgumentError,
3124
+ InvalidOptionArgumentError,
3125
+ Command,
3126
+ Argument,
3127
+ Option,
3128
+ Help
3129
+ } = import__.default;
3130
+
3131
+ // src/config.ts
3132
+ import { existsSync, readFileSync } from "fs";
3133
+ import { join, resolve } from "path";
3134
+ var DEFAULT_CONFIG = {
3135
+ specsDir: "./specs",
3136
+ dbPath: "./machine.db",
3137
+ port: 3000,
3138
+ rootDir: process.cwd()
3139
+ };
3140
+ var cachedConfig = null;
3141
+ async function loadConfigFile(rootDir) {
3142
+ const configPath = join(rootDir, "machine.config.ts");
3143
+ if (!existsSync(configPath)) {
3144
+ return {};
3145
+ }
3146
+ try {
3147
+ const mod = await import(configPath);
3148
+ return mod.default || mod;
3149
+ } catch (err) {
3150
+ console.warn(`Warning: Could not load ${configPath}:`, err);
3151
+ return {};
3152
+ }
3153
+ }
3154
+ function loadPackageJsonConfig(rootDir) {
3155
+ const pkgPath = join(rootDir, "package.json");
3156
+ if (!existsSync(pkgPath)) {
3157
+ return {};
3158
+ }
3159
+ try {
3160
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
3161
+ return pkg.machine || {};
3162
+ } catch {
3163
+ return {};
3164
+ }
3165
+ }
3166
+ async function loadConfig(cliOptions = {}) {
3167
+ const rootDir = cliOptions.rootDir || process.cwd();
3168
+ const fileConfig = await loadConfigFile(rootDir);
3169
+ const pkgConfig = loadPackageJsonConfig(rootDir);
3170
+ const config = {
3171
+ ...DEFAULT_CONFIG,
3172
+ ...pkgConfig,
3173
+ ...fileConfig,
3174
+ ...cliOptions,
3175
+ rootDir
3176
+ };
3177
+ config.specsDir = resolve(rootDir, config.specsDir);
3178
+ config.dbPath = resolve(rootDir, config.dbPath);
3179
+ cachedConfig = config;
3180
+ return config;
3181
+ }
3182
+
3183
+ // src/commands/serve.ts
3184
+ import { spawn, spawnSync } from "child_process";
3185
+ import { join as join2, dirname } from "path";
3186
+ import { fileURLToPath } from "url";
3187
+ import { existsSync as existsSync2 } from "fs";
3188
+ var __dirname2 = dirname(fileURLToPath(import.meta.url));
3189
+ function hasBun() {
3190
+ const result = spawnSync("bun", ["--version"], { stdio: "ignore" });
3191
+ return result.status === 0;
3192
+ }
3193
+ async function serveCommand(config) {
3194
+ console.log("\uD83D\uDE80 Starting @nivora/machine server...");
3195
+ console.log(` Specs: ${config.specsDir}`);
3196
+ console.log(` Database: ${config.dbPath}`);
3197
+ console.log(` Port: ${config.port}`);
3198
+ console.log("");
3199
+ const env = {
3200
+ ...process.env,
3201
+ MACHINE_SPECS_DIR: config.specsDir,
3202
+ MACHINE_DB_PATH: config.dbPath,
3203
+ PORT: String(config.port)
3204
+ };
3205
+ const packageRoot = join2(__dirname2, "..", "..");
3206
+ const hasProductionBuild = existsSync2(join2(packageRoot, ".next", "BUILD_ID"));
3207
+ const script = hasProductionBuild ? "start" : "dev";
3208
+ const runtime = hasBun() ? "bun" : "npm";
3209
+ spawn(runtime, ["run", script], {
3210
+ cwd: packageRoot,
3211
+ env,
3212
+ stdio: "inherit"
3213
+ });
3214
+ }
3215
+
3216
+ // src/commands/sync.ts
3217
+ import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync } from "fs";
3218
+ import { join as join4 } from "path";
3219
+
3220
+ // src/config.ts
3221
+ var DEFAULT_CONFIG2 = {
3222
+ specsDir: "./specs",
3223
+ dbPath: "./machine.db",
3224
+ port: 3000,
3225
+ rootDir: process.cwd()
3226
+ };
3227
+ var cachedConfig2 = null;
3228
+ function setConfig(config) {
3229
+ cachedConfig2 = config;
3230
+ }
3231
+
3232
+ // src/commands/sync.ts
3233
+ async function syncCommand(config) {
3234
+ console.log("\uD83D\uDD04 Syncing database...");
3235
+ console.log(` Specs: ${config.specsDir}`);
3236
+ console.log(` Database: ${config.dbPath}`);
3237
+ console.log("");
3238
+ setConfig(config);
3239
+ const { getDb: getDb2, closeDb: closeDb2 } = await Promise.resolve().then(() => (init_database(), exports_database));
3240
+ const { syncFS: syncFS2 } = await Promise.resolve().then(() => (init_fs_repo(), exports_fs_repo));
3241
+ const { reindexAllSteps: reindexAllSteps2 } = await Promise.resolve().then(() => (init_step_repo(), exports_step_repo));
3242
+ const { loadAllURS: loadAllURS2, loadURS: loadURS2, createURS: createURS2 } = await Promise.resolve().then(() => (init_urs_repo(), exports_urs_repo));
3243
+ const { loadAllRisks: loadAllRisks2, loadRisk: loadRisk2, createRisk: createRisk2 } = await Promise.resolve().then(() => (init_risk_repo(), exports_risk_repo));
3244
+ const { parseGherkinFS: parseGherkinFS2 } = await Promise.resolve().then(() => (init_gherkin_parser(), exports_gherkin_parser));
3245
+ getDb2();
3246
+ console.log("✓ Database initialized");
3247
+ console.log("");
3248
+ const fsDir = join4(config.specsDir, "fs");
3249
+ if (!existsSync4(fsDir)) {
3250
+ console.log(`⚠ No fs/ directory found at ${fsDir}`);
3251
+ console.log(" Run `machine init` to create the specs directory structure.");
3252
+ closeDb2();
3253
+ return;
3254
+ }
3255
+ const fsFiles = readdirSync(fsDir).filter((f) => f.endsWith(".requirement"));
3256
+ console.log(`Syncing ${fsFiles.length} FS files...`);
3257
+ const fsItems = [];
3258
+ const referencedURS = new Set;
3259
+ const referencedRisks = new Set;
3260
+ for (const file of fsFiles) {
3261
+ const filePath = join4(fsDir, file);
3262
+ const content = readFileSync3(filePath, "utf-8");
3263
+ const fsData = parseGherkinFS2(content, filePath);
3264
+ syncFS2(fsData);
3265
+ fsItems.push(fsData);
3266
+ fsData.urs_ids.forEach((id) => referencedURS.add(id));
3267
+ fsData.risk_ids.forEach((id) => referencedRisks.add(id));
3268
+ console.log(` ✓ ${fsData.id}: ${fsData.title}`);
3269
+ }
3270
+ console.log(` → Synced ${fsItems.length} FS documents`);
3271
+ console.log("");
3272
+ let stubUrsCount = 0;
3273
+ for (const ursId of referencedURS) {
3274
+ if (!loadURS2(ursId)) {
3275
+ createURS2({
3276
+ title: `${ursId} (Undefined)`,
3277
+ status: "draft",
3278
+ priority: "medium",
3279
+ owner: "Unassigned",
3280
+ category: "Uncategorized",
3281
+ business_need: "",
3282
+ intended_use: "",
3283
+ acceptance_criteria: [],
3284
+ regulatory_refs: []
3285
+ }, ursId);
3286
+ stubUrsCount++;
3287
+ console.log(` + Created stub URS: ${ursId}`);
3288
+ }
3289
+ }
3290
+ let stubRiskCount = 0;
3291
+ for (const riskId of referencedRisks) {
3292
+ if (!loadRisk2(riskId)) {
3293
+ const fsIds = fsItems.filter((fs) => fs.risk_ids.includes(riskId)).map((fs) => fs.id);
3294
+ createRisk2({
3295
+ title: `${riskId} (Undefined)`,
3296
+ status: "draft",
3297
+ category: "Uncategorized",
3298
+ gamp_category: 4,
3299
+ fs_ids: fsIds,
3300
+ impact: "medium",
3301
+ probability: "medium",
3302
+ risk_level: "medium",
3303
+ risks: [],
3304
+ mitigations: [],
3305
+ residual_risk: "pending"
3306
+ }, riskId);
3307
+ stubRiskCount++;
3308
+ console.log(` + Created stub Risk: ${riskId}`);
3309
+ }
3310
+ }
3311
+ if (stubUrsCount > 0 || stubRiskCount > 0) {
3312
+ console.log(` → Created ${stubUrsCount} URS stubs, ${stubRiskCount} Risk stubs`);
3313
+ console.log("");
3314
+ }
3315
+ console.log(`Current totals:`);
3316
+ console.log(` - URS: ${loadAllURS2().length} documents`);
3317
+ console.log(` - Risk: ${loadAllRisks2().length} documents`);
3318
+ console.log("");
3319
+ console.log("Indexing steps with embeddings...");
3320
+ const { indexed } = await reindexAllSteps2(fsItems.map((fs) => ({ id: fs.id, scenarios: fs.scenarios })));
3321
+ console.log(` → Indexed ${indexed} steps`);
3322
+ console.log("");
3323
+ console.log("✅ Sync complete!");
3324
+ closeDb2();
3325
+ }
3326
+
3327
+ // src/commands/init.ts
3328
+ import { existsSync as existsSync5, mkdirSync, writeFileSync } from "fs";
3329
+ import { join as join5 } from "path";
3330
+ var EXAMPLE_FS = `@URS-001
3331
+ Feature: FS-001 Example Feature
3332
+ This is an example functional specification.
3333
+
3334
+ Requirements:
3335
+ - FR-001.1: The system shall do something
3336
+ - FR-001.2: The system shall do something else
3337
+
3338
+ Scenario: Example scenario
3339
+ Given a precondition exists
3340
+ When an action is performed
3341
+ Then an expected result occurs
3342
+ `;
3343
+ async function initCommand(config) {
3344
+ console.log("\uD83D\uDCC1 Initializing specs directory...");
3345
+ console.log(` Location: ${config.specsDir}`);
3346
+ console.log("");
3347
+ const dirs = ["fs"];
3348
+ for (const dir of dirs) {
3349
+ const dirPath = join5(config.specsDir, dir);
3350
+ if (!existsSync5(dirPath)) {
3351
+ mkdirSync(dirPath, { recursive: true });
3352
+ console.log(` ✓ Created ${dir}/`);
3353
+ } else {
3354
+ console.log(` · ${dir}/ already exists`);
3355
+ }
3356
+ }
3357
+ const fsDir = join5(config.specsDir, "fs");
3358
+ const examplePath = join5(fsDir, "FS-001-example.requirement");
3359
+ if (!existsSync5(examplePath)) {
3360
+ writeFileSync(examplePath, EXAMPLE_FS, "utf-8");
3361
+ console.log(` ✓ Created example FS: FS-001-example.requirement`);
3362
+ }
3363
+ console.log("");
3364
+ console.log("✅ Specs directory initialized!");
3365
+ console.log("");
3366
+ console.log("Next steps:");
3367
+ console.log(" 1. Edit specs/fs/*.requirement files");
3368
+ console.log(" 2. Run `machine sync` to index files");
3369
+ console.log(" 3. Run `machine serve` to start the UI");
3370
+ }
3371
+
3372
+ // src/commands/search.ts
3373
+ async function searchCommand(config, query, limit) {
3374
+ console.log(`\uD83D\uDD0D Searching for: "${query}"`);
3375
+ console.log("");
3376
+ setConfig(config);
3377
+ const { searchSteps: searchSteps2 } = await Promise.resolve().then(() => (init_step_repo(), exports_step_repo));
3378
+ const { closeDb: closeDb2 } = await Promise.resolve().then(() => (init_database(), exports_database));
3379
+ try {
3380
+ const results = await searchSteps2(query, limit);
3381
+ if (results.length === 0) {
3382
+ console.log("No matching steps found.");
3383
+ return;
3384
+ }
3385
+ console.log(`Found ${results.length} matching steps:`);
3386
+ console.log("");
3387
+ for (const result of results) {
3388
+ const score = (result.similarity * 100).toFixed(1);
3389
+ console.log(` [${score}%] ${result.fsId} / ${result.scenarioName}`);
3390
+ console.log(` ${result.stepText}`);
3391
+ console.log("");
3392
+ }
3393
+ } finally {
3394
+ closeDb2();
3395
+ }
3396
+ }
3397
+
3398
+ // src/commands/release.ts
3399
+ async function releaseCommand(config, action, options) {
3400
+ setConfig(config);
3401
+ const { getDb: getDb2, closeDb: closeDb2 } = await Promise.resolve().then(() => (init_database(), exports_database));
3402
+ const {
3403
+ loadAllReleases: loadAllReleases2,
3404
+ loadRelease: loadRelease2,
3405
+ createRelease: createRelease2,
3406
+ updateRelease: updateRelease2,
3407
+ addFSToRelease: addFSToRelease2
3408
+ } = await Promise.resolve().then(() => (init_release_repo(), exports_release_repo));
3409
+ getDb2();
3410
+ try {
3411
+ switch (action) {
3412
+ case "list": {
3413
+ const releases = loadAllReleases2();
3414
+ if (releases.length === 0) {
3415
+ console.log('No releases found. Create one with: machine release create -v 1.0.0 -n "My Release"');
3416
+ return;
3417
+ }
3418
+ console.log(`\uD83D\uDCE6 Releases:
3419
+ `);
3420
+ for (const r of releases) {
3421
+ const statusIcon = r.status === "released" ? "✅" : r.status === "testing" ? "\uD83E\uDDEA" : "\uD83D\uDCCB";
3422
+ const passRate = r.latest_pass_rate !== null ? ` (${r.latest_pass_rate.toFixed(0)}% pass)` : "";
3423
+ console.log(` ${statusIcon} ${r.id} v${r.version} - ${r.name}`);
3424
+ console.log(` Status: ${r.status} | ${r.fs_count} features | ${r.test_runs} test runs${passRate}`);
3425
+ console.log(` Created: ${r.created_at}${r.released_at ? ` | Released: ${r.released_at}` : ""}`);
3426
+ console.log("");
3427
+ }
3428
+ break;
3429
+ }
3430
+ case "create": {
3431
+ const { version, name, notes } = options;
3432
+ const release = createRelease2({ version, name, notes });
3433
+ console.log(`✅ Created release: ${release.id} v${version} - ${name}`);
3434
+ break;
3435
+ }
3436
+ case "tag": {
3437
+ const { releaseId, fsIds } = options;
3438
+ const release = loadRelease2(releaseId);
3439
+ if (!release) {
3440
+ console.error(`❌ Release not found: ${releaseId}`);
3441
+ process.exit(1);
3442
+ }
3443
+ for (const fsId of fsIds) {
3444
+ addFSToRelease2(releaseId, fsId);
3445
+ console.log(` + Tagged ${fsId} to ${releaseId}`);
3446
+ }
3447
+ console.log(`✅ Tagged ${fsIds.length} features to ${releaseId}`);
3448
+ break;
3449
+ }
3450
+ case "status": {
3451
+ const { releaseId, status } = options;
3452
+ const release = loadRelease2(releaseId);
3453
+ if (!release) {
3454
+ console.error(`❌ Release not found: ${releaseId}`);
3455
+ process.exit(1);
3456
+ }
3457
+ if (!["planning", "testing", "released"].includes(status)) {
3458
+ console.error(`❌ Invalid status: ${status}. Must be: planning, testing, or released`);
3459
+ process.exit(1);
3460
+ }
3461
+ updateRelease2(releaseId, { status });
3462
+ console.log(`✅ Updated ${releaseId} status to: ${status}`);
3463
+ break;
3464
+ }
3465
+ }
3466
+ } finally {
3467
+ closeDb2();
3468
+ }
3469
+ }
3470
+
3471
+ // src/commands/import-results.ts
3472
+ import { existsSync as existsSync6 } from "fs";
3473
+ import { resolve as resolve2 } from "path";
3474
+ async function importResultsCommand(config, file, options) {
3475
+ const { releaseId } = options;
3476
+ if (!releaseId) {
3477
+ console.error("❌ Error: --releaseId is required");
3478
+ console.log("Usage: machine release import-results <file> --releaseId <id>");
3479
+ process.exit(1);
3480
+ }
3481
+ const filePath = resolve2(process.cwd(), file);
3482
+ if (!existsSync6(filePath)) {
3483
+ console.error(`❌ Error: File not found: ${filePath}`);
3484
+ process.exit(1);
3485
+ }
3486
+ setConfig(config);
3487
+ const { getDb: getDb2, closeDb: closeDb2 } = await Promise.resolve().then(() => (init_database(), exports_database));
3488
+ const { loadRelease: loadRelease2 } = await Promise.resolve().then(() => (init_release_repo(), exports_release_repo));
3489
+ const { importCucumberResults: importCucumberResults2 } = await Promise.resolve().then(() => (init_test_repo(), exports_test_repo));
3490
+ getDb2();
3491
+ try {
3492
+ const release = loadRelease2(releaseId);
3493
+ if (!release) {
3494
+ console.error(`❌ Error: Release not found: ${releaseId}`);
3495
+ process.exit(1);
3496
+ }
3497
+ if (release.status === "released") {
3498
+ console.error(`❌ Error: Cannot import results for a 'released' version. Change status to 'testing' first.`);
3499
+ process.exit(1);
3500
+ }
3501
+ console.log(`\uD83D\uDCE6 Importing results for Release ${releaseId}...`);
3502
+ console.log(` File: ${file}`);
3503
+ const run = importCucumberResults2(releaseId, filePath);
3504
+ console.log("");
3505
+ console.log(run.failed > 0 ? "❌ Test Run Completed (With Failures)" : "✅ Test Run Completed (Passed)");
3506
+ console.log(`----------------------------------------`);
3507
+ console.log(` Run ID: ${run.id}`);
3508
+ console.log(` Passed: ${run.passed}`);
3509
+ console.log(` Failed: ${run.failed}`);
3510
+ console.log(` Skipped: ${run.skipped}`);
3511
+ console.log(` Total: ${run.total}`);
3512
+ console.log("");
3513
+ if (run.failed > 0) {
3514
+ console.log(`⚠️ Warning: ${run.failed} failures detected.`);
3515
+ console.log(` You must raise defects for these failures to proceed with release.`);
3516
+ console.log(` Visit the dashboard to manage defects: http://localhost:3000/releases/${releaseId}`);
3517
+ }
3518
+ } catch (error) {
3519
+ console.error("❌ Error importing results:", error);
3520
+ process.exit(1);
3521
+ } finally {
3522
+ closeDb2();
3523
+ }
3524
+ }
3525
+
3526
+ // src/commands/test.ts
3527
+ async function testCommand(config, action, options) {
3528
+ setConfig(config);
3529
+ const { getDb: getDb2, closeDb: closeDb2 } = await Promise.resolve().then(() => (init_database(), exports_database));
3530
+ const { importCucumberResults: importCucumberResults2, loadTestRuns: loadTestRuns2 } = await Promise.resolve().then(() => (init_test_repo(), exports_test_repo));
3531
+ const { loadRelease: loadRelease2 } = await Promise.resolve().then(() => (init_release_repo(), exports_release_repo));
3532
+ getDb2();
3533
+ try {
3534
+ switch (action) {
3535
+ case "import": {
3536
+ const { releaseId, jsonPath } = options;
3537
+ const release = loadRelease2(releaseId);
3538
+ if (!release) {
3539
+ console.error(`❌ Release not found: ${releaseId}`);
3540
+ process.exit(1);
3541
+ }
3542
+ console.log(`\uD83D\uDCE5 Importing test results from: ${jsonPath}`);
3543
+ const run = importCucumberResults2(releaseId, jsonPath);
3544
+ console.log(`
3545
+ ✅ Imported test run #${run.id}`);
3546
+ console.log(` Total: ${run.total} scenarios`);
3547
+ console.log(` ✓ Passed: ${run.passed}`);
3548
+ console.log(` ✗ Failed: ${run.failed}`);
3549
+ console.log(` ○ Skipped: ${run.skipped}`);
3550
+ console.log(` Pass rate: ${run.total > 0 ? (run.passed / run.total * 100).toFixed(1) : 0}%`);
3551
+ break;
3552
+ }
3553
+ case "list": {
3554
+ const { releaseId } = options;
3555
+ const release = loadRelease2(releaseId);
3556
+ if (!release) {
3557
+ console.error(`❌ Release not found: ${releaseId}`);
3558
+ process.exit(1);
3559
+ }
3560
+ const runs = loadTestRuns2(releaseId);
3561
+ if (runs.length === 0) {
3562
+ console.log(`No test runs for ${releaseId}. Import results with: machine test import ./results.json -r ${releaseId}`);
3563
+ return;
3564
+ }
3565
+ console.log(`\uD83E\uDDEA Test runs for ${releaseId} v${release.version}:
3566
+ `);
3567
+ for (const run of runs) {
3568
+ const passRate = run.total > 0 ? (run.passed / run.total * 100).toFixed(1) : 0;
3569
+ const statusIcon = run.failed > 0 ? "❌" : "✅";
3570
+ console.log(` ${statusIcon} Run #${run.id} - ${run.run_date}`);
3571
+ console.log(` Source: ${run.source} | ${passRate}% pass (${run.passed}/${run.total})`);
3572
+ if (run.failed > 0) {
3573
+ console.log(` Failed: ${run.failed} scenarios`);
3574
+ }
3575
+ console.log("");
3576
+ }
3577
+ break;
3578
+ }
3579
+ }
3580
+ } finally {
3581
+ closeDb2();
3582
+ }
3583
+ }
3584
+
3585
+ // bin/cli.ts
3586
+ var program2 = new Command;
3587
+ program2.name("machine").description("Requirements documentation system with semantic search").version("0.1.0");
3588
+ program2.command("serve").description("Start the documentation server").option("-p, --port <port>", "Port to run server on", "3000").option("-s, --specs <dir>", "Specs directory", "./specs").option("-d, --db <path>", "Database path", "./machine.db").action(async (options) => {
3589
+ const config = await loadConfig({
3590
+ port: parseInt(options.port, 10),
3591
+ specsDir: options.specs,
3592
+ dbPath: options.db
3593
+ });
3594
+ await serveCommand(config);
3595
+ });
3596
+ program2.command("sync").description("Sync FS files to database and index steps").option("-s, --specs <dir>", "Specs directory", "./specs").option("-d, --db <path>", "Database path", "./machine.db").action(async (options) => {
3597
+ const config = await loadConfig({
3598
+ specsDir: options.specs,
3599
+ dbPath: options.db
3600
+ });
3601
+ await syncCommand(config);
3602
+ });
3603
+ program2.command("init").description("Initialize a new specs directory").option("-s, --specs <dir>", "Specs directory to create", "./specs").action(async (options) => {
3604
+ const config = await loadConfig({
3605
+ specsDir: options.specs
3606
+ });
3607
+ await initCommand(config);
3608
+ });
3609
+ program2.command("search <query>").description("Semantic search for steps").option("-n, --limit <n>", "Number of results", "10").option("-s, --specs <dir>", "Specs directory", "./specs").option("-d, --db <path>", "Database path", "./machine.db").action(async (query, options) => {
3610
+ const config = await loadConfig({
3611
+ specsDir: options.specs,
3612
+ dbPath: options.db
3613
+ });
3614
+ await searchCommand(config, query, parseInt(options.limit, 10));
3615
+ });
3616
+ var release = program2.command("release").description("Manage releases");
3617
+ release.command("list").description("List all releases").option("-d, --db <path>", "Database path", "./machine.db").action(async (options) => {
3618
+ const config = await loadConfig({ dbPath: options.db });
3619
+ await releaseCommand(config, "list");
3620
+ });
3621
+ release.command("create").description("Create a new release").requiredOption("-v, --version <version>", "Release version (e.g., 1.0.0)").requiredOption("-n, --name <name>", "Release name").option("--notes <notes>", "Release notes").option("-d, --db <path>", "Database path", "./machine.db").action(async (options) => {
3622
+ const config = await loadConfig({ dbPath: options.db });
3623
+ await releaseCommand(config, "create", {
3624
+ version: options.version,
3625
+ name: options.name,
3626
+ notes: options.notes
3627
+ });
3628
+ });
3629
+ release.command("tag <releaseId>").description("Tag features to a release").requiredOption("--fs <fsIds...>", "FS IDs to tag").option("-d, --db <path>", "Database path", "./machine.db").action(async (releaseId, options) => {
3630
+ const config = await loadConfig({ dbPath: options.db });
3631
+ await releaseCommand(config, "tag", { releaseId, fsIds: options.fs });
3632
+ });
3633
+ release.command("status <releaseId>").description("Update release status").requiredOption("--status <status>", "New status (planning|testing|released)").option("-d, --db <path>", "Database path", "./machine.db").action(async (releaseId, options) => {
3634
+ const config = await loadConfig({ dbPath: options.db });
3635
+ await releaseCommand(config, "status", { releaseId, status: options.status });
3636
+ });
3637
+ release.command("import-results <file>").description("Import Cucumber JSON results into a release").requiredOption("--releaseId <id>", "Release ID").option("-d, --db <path>", "Database path", "./machine.db").action(async (file, options) => {
3638
+ const config = await loadConfig({ dbPath: options.db });
3639
+ await importResultsCommand(config, file, { releaseId: options.releaseId });
3640
+ });
3641
+ var test = program2.command("test").description("Manage test results");
3642
+ test.command("import <jsonPath>").description("Import Cucumber JSON test results").requiredOption("-r, --release <releaseId>", "Release ID").option("-d, --db <path>", "Database path", "./machine.db").action(async (jsonPath, options) => {
3643
+ const config = await loadConfig({ dbPath: options.db });
3644
+ await testCommand(config, "import", { releaseId: options.release, jsonPath });
3645
+ });
3646
+ test.command("list <releaseId>").description("List test runs for a release").option("-d, --db <path>", "Database path", "./machine.db").action(async (releaseId, options) => {
3647
+ const config = await loadConfig({ dbPath: options.db });
3648
+ await testCommand(config, "list", { releaseId });
3649
+ });
3650
+ program2.parse();