poe-code 3.0.186 → 3.0.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/cli/commands/experiment.js +1 -1
  2. package/dist/cli/commands/experiment.js.map +1 -1
  3. package/dist/cli/commands/pipeline-init.js +1 -1
  4. package/dist/cli/commands/pipeline-init.js.map +1 -1
  5. package/dist/cli/commands/pipeline.js +1 -1
  6. package/dist/cli/commands/pipeline.js.map +1 -1
  7. package/dist/cli/commands/spawn.js +2 -1
  8. package/dist/cli/commands/spawn.js.map +1 -1
  9. package/dist/cli/program.js +6 -6
  10. package/dist/cli/program.js.map +1 -1
  11. package/dist/index.js +122 -225
  12. package/dist/index.js.map +4 -4
  13. package/dist/providers/claude-code.js +2 -76
  14. package/dist/providers/claude-code.js.map +4 -4
  15. package/dist/providers/codex.js +2 -76
  16. package/dist/providers/codex.js.map +4 -4
  17. package/dist/providers/goose.js +2 -76
  18. package/dist/providers/goose.js.map +4 -4
  19. package/dist/providers/kimi.js +2 -76
  20. package/dist/providers/kimi.js.map +4 -4
  21. package/dist/providers/opencode.js +2 -76
  22. package/dist/providers/opencode.js.map +4 -4
  23. package/dist/providers/poe-agent.js +23 -107
  24. package/dist/providers/poe-agent.js.map +4 -4
  25. package/dist/sdk/experiment.js +1 -1
  26. package/dist/sdk/experiment.js.map +1 -1
  27. package/package.json +10 -30
  28. package/packages/design-system/dist/prompts/primitives/cancel.d.ts +1 -1
  29. package/packages/design-system/dist/prompts/primitives/cancel.js +1 -1
  30. package/packages/cmdkit/dist/cli.compile-check.d.ts +0 -1
  31. package/packages/cmdkit/dist/cli.compile-check.js +0 -26
  32. package/packages/cmdkit/dist/cli.d.ts +0 -12
  33. package/packages/cmdkit/dist/cli.js +0 -2331
  34. package/packages/cmdkit/dist/cli.js.map +0 -7
  35. package/packages/cmdkit/dist/index.compile-check.d.ts +0 -1
  36. package/packages/cmdkit/dist/index.compile-check.js +0 -50
  37. package/packages/cmdkit/dist/index.d.ts +0 -164
  38. package/packages/cmdkit/dist/index.js +0 -561
  39. package/packages/cmdkit/dist/index.js.map +0 -7
  40. package/packages/cmdkit/dist/mcp.compile-check.d.ts +0 -1
  41. package/packages/cmdkit/dist/mcp.compile-check.js +0 -26
  42. package/packages/cmdkit/dist/mcp.d.ts +0 -31
  43. package/packages/cmdkit/dist/mcp.js +0 -1254
  44. package/packages/cmdkit/dist/mcp.js.map +0 -7
  45. package/packages/cmdkit/dist/number-schema.d.ts +0 -3
  46. package/packages/cmdkit/dist/number-schema.js +0 -8
  47. package/packages/cmdkit/dist/renderer.d.ts +0 -5
  48. package/packages/cmdkit/dist/renderer.js +0 -164
  49. package/packages/cmdkit/dist/renderer.js.map +0 -7
  50. package/packages/cmdkit/dist/schema-scope.d.ts +0 -4
  51. package/packages/cmdkit/dist/schema-scope.js +0 -34
  52. package/packages/cmdkit/dist/sdk.compile-check.d.ts +0 -1
  53. package/packages/cmdkit/dist/sdk.compile-check.js +0 -79
  54. package/packages/cmdkit/dist/sdk.d.ts +0 -63
  55. package/packages/cmdkit/dist/sdk.js +0 -369
  56. package/packages/cmdkit/dist/sdk.js.map +0 -7
  57. package/packages/cmdkit-openapi/dist/api-command.d.ts +0 -7
  58. package/packages/cmdkit-openapi/dist/api-command.js +0 -4
  59. package/packages/cmdkit-openapi/dist/auth/bearer-token-auth.d.ts +0 -8
  60. package/packages/cmdkit-openapi/dist/auth/bearer-token-auth.js +0 -216
  61. package/packages/cmdkit-openapi/dist/auth/types.d.ts +0 -9
  62. package/packages/cmdkit-openapi/dist/auth/types.js +0 -1
  63. package/packages/cmdkit-openapi/dist/bin/generate.d.ts +0 -40
  64. package/packages/cmdkit-openapi/dist/bin/generate.js +0 -248
  65. package/packages/cmdkit-openapi/dist/define-client.d.ts +0 -20
  66. package/packages/cmdkit-openapi/dist/define-client.js +0 -148
  67. package/packages/cmdkit-openapi/dist/generate.d.ts +0 -210
  68. package/packages/cmdkit-openapi/dist/generate.js +0 -1091
  69. package/packages/cmdkit-openapi/dist/group-by-noun.d.ts +0 -6
  70. package/packages/cmdkit-openapi/dist/group-by-noun.js +0 -17
  71. package/packages/cmdkit-openapi/dist/http.d.ts +0 -26
  72. package/packages/cmdkit-openapi/dist/http.js +0 -123
  73. package/packages/cmdkit-openapi/dist/index.d.ts +0 -12
  74. package/packages/cmdkit-openapi/dist/index.js +0 -6
  75. package/packages/cmdkit-openapi/dist/interpreter.d.ts +0 -6
  76. package/packages/cmdkit-openapi/dist/interpreter.js +0 -289
  77. package/packages/cmdkit-openapi/dist/lock.d.ts +0 -14
  78. package/packages/cmdkit-openapi/dist/lock.js +0 -48
  79. package/packages/cmdkit-openapi/dist/naming.d.ts +0 -24
  80. package/packages/cmdkit-openapi/dist/naming.js +0 -218
  81. package/packages/cmdkit-openapi/dist/request-shape.d.ts +0 -15
  82. package/packages/cmdkit-openapi/dist/request-shape.js +0 -5
  83. package/packages/cmdkit-openapi/dist/runtime.d.ts +0 -13
  84. package/packages/cmdkit-openapi/dist/runtime.js +0 -94
  85. package/packages/cmdkit-openapi/dist/spec-source.d.ts +0 -11
  86. package/packages/cmdkit-openapi/dist/spec-source.js +0 -63
  87. package/packages/cmdkit-schema/dist/index.compile-check.d.ts +0 -1
  88. package/packages/cmdkit-schema/dist/index.compile-check.js +0 -12
  89. package/packages/cmdkit-schema/dist/index.d.ts +0 -124
  90. package/packages/cmdkit-schema/dist/index.js +0 -175
@@ -1,2331 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
-
27
- // node_modules/sisteransi/src/index.js
28
- var require_src = __commonJS({
29
- "node_modules/sisteransi/src/index.js"(exports, module) {
30
- "use strict";
31
- var ESC = "\x1B";
32
- var CSI = `${ESC}[`;
33
- var beep = "\x07";
34
- var cursor = {
35
- to(x, y) {
36
- if (!y) return `${CSI}${x + 1}G`;
37
- return `${CSI}${y + 1};${x + 1}H`;
38
- },
39
- move(x, y) {
40
- let ret = "";
41
- if (x < 0) ret += `${CSI}${-x}D`;
42
- else if (x > 0) ret += `${CSI}${x}C`;
43
- if (y < 0) ret += `${CSI}${-y}A`;
44
- else if (y > 0) ret += `${CSI}${y}B`;
45
- return ret;
46
- },
47
- up: (count = 1) => `${CSI}${count}A`,
48
- down: (count = 1) => `${CSI}${count}B`,
49
- forward: (count = 1) => `${CSI}${count}C`,
50
- backward: (count = 1) => `${CSI}${count}D`,
51
- nextLine: (count = 1) => `${CSI}E`.repeat(count),
52
- prevLine: (count = 1) => `${CSI}F`.repeat(count),
53
- left: `${CSI}G`,
54
- hide: `${CSI}?25l`,
55
- show: `${CSI}?25h`,
56
- save: `${ESC}7`,
57
- restore: `${ESC}8`
58
- };
59
- var scroll = {
60
- up: (count = 1) => `${CSI}S`.repeat(count),
61
- down: (count = 1) => `${CSI}T`.repeat(count)
62
- };
63
- var erase = {
64
- screen: `${CSI}2J`,
65
- up: (count = 1) => `${CSI}1J`.repeat(count),
66
- down: (count = 1) => `${CSI}J`.repeat(count),
67
- line: `${CSI}2K`,
68
- lineEnd: `${CSI}K`,
69
- lineStart: `${CSI}1K`,
70
- lines(count) {
71
- let clear = "";
72
- for (let i = 0; i < count; i++)
73
- clear += this.line + (i < count - 1 ? cursor.up() : "");
74
- if (count)
75
- clear += cursor.left;
76
- return clear;
77
- }
78
- };
79
- module.exports = { cursor, scroll, erase, beep };
80
- }
81
- });
82
-
83
- // packages/cmdkit/src/cli.ts
84
- import { access, readFile, writeFile } from "node:fs/promises";
85
- import path from "node:path";
86
- import { Command as CommanderCommand, CommanderError, InvalidArgumentError, Option } from "commander";
87
-
88
- // packages/design-system/src/tokens/colors.ts
89
- import chalk from "chalk";
90
- var dark = {
91
- header: (text4) => chalk.magentaBright.bold(text4),
92
- divider: (text4) => chalk.dim(text4),
93
- prompt: (text4) => chalk.cyan(text4),
94
- number: (text4) => chalk.cyanBright(text4),
95
- intro: (text4) => chalk.bgMagenta.white(` Poe - ${text4} `),
96
- resolvedSymbol: chalk.magenta("\u25C7"),
97
- errorSymbol: chalk.red("\u25A0"),
98
- accent: (text4) => chalk.cyan(text4),
99
- muted: (text4) => chalk.dim(text4),
100
- success: (text4) => chalk.green(text4),
101
- warning: (text4) => chalk.yellow(text4),
102
- error: (text4) => chalk.red(text4),
103
- info: (text4) => chalk.magenta(text4),
104
- badge: (text4) => chalk.bgYellow.black(` ${text4} `)
105
- };
106
- var light = {
107
- header: (text4) => chalk.hex("#a200ff").bold(text4),
108
- divider: (text4) => chalk.hex("#666666")(text4),
109
- prompt: (text4) => chalk.hex("#006699").bold(text4),
110
- number: (text4) => chalk.hex("#0077cc").bold(text4),
111
- intro: (text4) => chalk.bgHex("#a200ff").white(` Poe - ${text4} `),
112
- resolvedSymbol: chalk.hex("#a200ff")("\u25C7"),
113
- errorSymbol: chalk.hex("#cc0000")("\u25A0"),
114
- accent: (text4) => chalk.hex("#006699").bold(text4),
115
- muted: (text4) => chalk.hex("#666666")(text4),
116
- success: (text4) => chalk.hex("#008800")(text4),
117
- warning: (text4) => chalk.hex("#cc6600")(text4),
118
- error: (text4) => chalk.hex("#cc0000")(text4),
119
- info: (text4) => chalk.hex("#a200ff")(text4),
120
- badge: (text4) => chalk.bgHex("#cc6600").white(` ${text4} `)
121
- };
122
-
123
- // packages/design-system/src/tokens/typography.ts
124
- import chalk2 from "chalk";
125
- var typography = {
126
- bold: (text4) => chalk2.bold(text4),
127
- dim: (text4) => chalk2.dim(text4),
128
- italic: (text4) => chalk2.italic(text4),
129
- underline: (text4) => chalk2.underline(text4),
130
- strikethrough: (text4) => chalk2.strikethrough(text4)
131
- };
132
-
133
- // packages/design-system/src/tokens/widths.ts
134
- var widths = {
135
- header: 60,
136
- helpColumn: 24,
137
- maxLine: 80
138
- };
139
-
140
- // packages/design-system/src/components/text.ts
141
- import chalk3 from "chalk";
142
-
143
- // packages/design-system/src/internal/output-format.ts
144
- import { AsyncLocalStorage } from "node:async_hooks";
145
- var VALID_FORMATS = /* @__PURE__ */ new Set(["terminal", "markdown", "json"]);
146
- var formatStorage = new AsyncLocalStorage();
147
- var cached;
148
- function resolveOutputFormat(env = process.env) {
149
- const scoped = formatStorage.getStore();
150
- if (scoped) {
151
- return scoped;
152
- }
153
- if (cached) {
154
- return cached;
155
- }
156
- const raw = env.OUTPUT_FORMAT?.toLowerCase();
157
- cached = VALID_FORMATS.has(raw) ? raw : "terminal";
158
- return cached;
159
- }
160
- function resetOutputFormatCache() {
161
- cached = void 0;
162
- }
163
-
164
- // packages/design-system/src/internal/theme-detect.ts
165
- function detectThemeFromEnv(env) {
166
- const apple = env.APPLE_INTERFACE_STYLE;
167
- if (typeof apple === "string") {
168
- return apple.toLowerCase() === "dark" ? "dark" : "light";
169
- }
170
- const vscodeKind = env.VSCODE_COLOR_THEME_KIND;
171
- if (typeof vscodeKind === "string") {
172
- const normalized = vscodeKind.toLowerCase();
173
- if (normalized.includes("light")) {
174
- return "light";
175
- }
176
- if (normalized.includes("dark")) {
177
- return "dark";
178
- }
179
- }
180
- const colorFGBG = env.COLORFGBG;
181
- if (typeof colorFGBG === "string") {
182
- const parts = colorFGBG.split(";").map((part) => Number.parseInt(part, 10));
183
- const background = parts.at(-1);
184
- if (Number.isFinite(background)) {
185
- return background >= 8 ? "light" : "dark";
186
- }
187
- }
188
- return void 0;
189
- }
190
- function resolveThemeName(env = process.env) {
191
- const raw = (env.POE_CODE_THEME ?? env.POE_THEME)?.toLowerCase();
192
- if (raw === "light" || raw === "dark") {
193
- return raw;
194
- }
195
- const detected = detectThemeFromEnv(env);
196
- if (detected) {
197
- return detected;
198
- }
199
- return "dark";
200
- }
201
- var cachedTheme;
202
- function getTheme(env) {
203
- if (cachedTheme) {
204
- return cachedTheme;
205
- }
206
- const themeName = resolveThemeName(env);
207
- cachedTheme = themeName === "light" ? light : dark;
208
- return cachedTheme;
209
- }
210
-
211
- // packages/design-system/src/components/text.ts
212
- var text = {
213
- intro(content) {
214
- const format = resolveOutputFormat();
215
- if (format === "json") return content;
216
- if (format === "markdown") return `**${content}**`;
217
- return getTheme().intro(content);
218
- },
219
- heading(content) {
220
- const format = resolveOutputFormat();
221
- if (format === "json") return content;
222
- if (format === "markdown") return `## ${content}`;
223
- return getTheme().header(content);
224
- },
225
- section(content) {
226
- const format = resolveOutputFormat();
227
- if (format === "json") return content;
228
- if (format === "markdown") return `**${content}**`;
229
- return typography.bold(content);
230
- },
231
- command(content) {
232
- const format = resolveOutputFormat();
233
- if (format === "json") return content;
234
- if (format === "markdown") return `\`${content}\``;
235
- return getTheme().accent(content);
236
- },
237
- argument(content) {
238
- const format = resolveOutputFormat();
239
- if (format === "json") return content;
240
- if (format === "markdown") return `<${content}>`;
241
- return getTheme().muted(content);
242
- },
243
- option(content) {
244
- const format = resolveOutputFormat();
245
- if (format === "json") return content;
246
- if (format === "markdown") return `\`${content}\``;
247
- return chalk3.yellow(content);
248
- },
249
- example(content) {
250
- const format = resolveOutputFormat();
251
- if (format === "json") return content;
252
- if (format === "markdown") return `\`${content}\``;
253
- return getTheme().muted(content);
254
- },
255
- usageCommand(content) {
256
- const format = resolveOutputFormat();
257
- if (format === "json") return content;
258
- if (format === "markdown") return `\`${content}\``;
259
- return chalk3.green(content);
260
- },
261
- link(content) {
262
- const format = resolveOutputFormat();
263
- if (format === "json") return content;
264
- if (format === "markdown") return `[${content}](${content})`;
265
- return getTheme().accent(content);
266
- },
267
- muted(content) {
268
- const format = resolveOutputFormat();
269
- if (format === "json") return content;
270
- if (format === "markdown") return `*${content}*`;
271
- return getTheme().muted(content);
272
- },
273
- badge(content) {
274
- const format = resolveOutputFormat();
275
- if (format === "json") return content;
276
- if (format === "markdown") return `[${content}]`;
277
- return getTheme().badge(content);
278
- },
279
- selectLabel(label, detail) {
280
- if (!detail) {
281
- return label;
282
- }
283
- const format = resolveOutputFormat();
284
- if (format !== "terminal") {
285
- return `${label} \u2014 ${detail}`;
286
- }
287
- return `${label} ${typography.dim("\u2014")} ${typography.dim(detail)}`;
288
- }
289
- };
290
-
291
- // packages/design-system/src/components/symbols.ts
292
- import chalk4 from "chalk";
293
- var symbols = {
294
- get info() {
295
- const format = resolveOutputFormat();
296
- if (format === "json") return "info";
297
- if (format === "markdown") return "(i)";
298
- return chalk4.magenta("\u25CF");
299
- },
300
- get success() {
301
- const format = resolveOutputFormat();
302
- if (format === "json") return "success";
303
- if (format === "markdown") return "[ok]";
304
- return chalk4.magenta("\u25C6");
305
- },
306
- get resolved() {
307
- const format = resolveOutputFormat();
308
- if (format === "json") return "resolved";
309
- if (format === "markdown") return ">";
310
- return getTheme().resolvedSymbol;
311
- },
312
- get errorResolved() {
313
- const format = resolveOutputFormat();
314
- if (format === "json") return "error";
315
- if (format === "markdown") return "[!]";
316
- return getTheme().errorSymbol;
317
- },
318
- get bar() {
319
- const format = resolveOutputFormat();
320
- if (format === "json") return "";
321
- if (format === "markdown") return "|";
322
- return "\u2502";
323
- },
324
- cornerTopRight: "\u256E",
325
- cornerBottomRight: "\u256F",
326
- get warning() {
327
- const format = resolveOutputFormat();
328
- if (format === "json") return "warning";
329
- if (format === "markdown") return "[!]";
330
- return "\u25B2";
331
- },
332
- get active() {
333
- const format = resolveOutputFormat();
334
- if (format === "json") return "active";
335
- if (format === "markdown") return "[x]";
336
- return "\u25C6";
337
- },
338
- get inactive() {
339
- const format = resolveOutputFormat();
340
- if (format === "json") return "inactive";
341
- if (format === "markdown") return "[ ]";
342
- return "\u25CB";
343
- }
344
- };
345
-
346
- // packages/design-system/src/components/logger.ts
347
- import chalk6 from "chalk";
348
-
349
- // packages/design-system/src/prompts/primitives/log.ts
350
- import chalk5 from "chalk";
351
-
352
- // packages/design-system/src/internal/strip-ansi.ts
353
- function stripAnsi(value) {
354
- return value.replace(/\u001b\[[0-9;]*m/g, "");
355
- }
356
-
357
- // packages/design-system/src/prompts/primitives/log.ts
358
- function writeTerminalMessage(msg, {
359
- symbol = chalk5.gray("\u2502"),
360
- secondarySymbol = chalk5.gray("\u2502"),
361
- spacing: spacing2 = 1,
362
- withGuide = true
363
- } = {}) {
364
- const lines = [];
365
- const showGuide = withGuide !== false;
366
- const contentLines = msg.split("\n");
367
- const prefix = showGuide ? `${symbol} ` : "";
368
- const continuationPrefix = showGuide ? `${secondarySymbol} ` : "";
369
- const emptyGuide = showGuide ? secondarySymbol : "";
370
- for (let index = 0; index < spacing2; index += 1) {
371
- lines.push(emptyGuide);
372
- }
373
- if (contentLines.length === 0) {
374
- process.stdout.write("\n");
375
- return;
376
- }
377
- const [firstLine = "", ...continuationLines] = contentLines;
378
- if (firstLine.length > 0) {
379
- lines.push(`${prefix}${firstLine}`);
380
- } else {
381
- lines.push(showGuide ? symbol : "");
382
- }
383
- for (const line of continuationLines) {
384
- if (line.length > 0) {
385
- lines.push(`${continuationPrefix}${line}`);
386
- continue;
387
- }
388
- lines.push(emptyGuide);
389
- }
390
- process.stdout.write(`${lines.join("\n")}
391
- `);
392
- }
393
- function message(msg, options) {
394
- const format = resolveOutputFormat();
395
- if (format === "markdown") {
396
- process.stdout.write(`- ${stripAnsi(msg)}
397
- `);
398
- return;
399
- }
400
- if (format === "json") {
401
- process.stdout.write(
402
- `${JSON.stringify({ level: "message", message: stripAnsi(msg) })}
403
- `
404
- );
405
- return;
406
- }
407
- writeTerminalMessage(msg, options);
408
- }
409
- function info(msg) {
410
- const format = resolveOutputFormat();
411
- if (format === "markdown") {
412
- process.stdout.write(`- **info:** ${stripAnsi(msg)}
413
- `);
414
- return;
415
- }
416
- if (format === "json") {
417
- process.stdout.write(
418
- `${JSON.stringify({ level: "info", message: stripAnsi(msg) })}
419
- `
420
- );
421
- return;
422
- }
423
- message(msg, { symbol: symbols.info });
424
- }
425
- function success(msg) {
426
- const format = resolveOutputFormat();
427
- if (format === "markdown") {
428
- process.stdout.write(`- **success:** ${stripAnsi(msg)}
429
- `);
430
- return;
431
- }
432
- if (format === "json") {
433
- process.stdout.write(
434
- `${JSON.stringify({ level: "success", message: stripAnsi(msg) })}
435
- `
436
- );
437
- return;
438
- }
439
- message(msg, { symbol: symbols.success });
440
- }
441
- function warn(msg) {
442
- const format = resolveOutputFormat();
443
- if (format === "markdown") {
444
- process.stdout.write(`- **warning:** ${stripAnsi(msg)}
445
- `);
446
- return;
447
- }
448
- if (format === "json") {
449
- process.stdout.write(
450
- `${JSON.stringify({ level: "warn", message: stripAnsi(msg) })}
451
- `
452
- );
453
- return;
454
- }
455
- message(msg, { symbol: chalk5.yellow("\u25B2") });
456
- }
457
- function error(msg) {
458
- const format = resolveOutputFormat();
459
- if (format === "markdown") {
460
- process.stdout.write(`- **error:** ${stripAnsi(msg)}
461
- `);
462
- return;
463
- }
464
- if (format === "json") {
465
- process.stdout.write(
466
- `${JSON.stringify({ level: "error", message: stripAnsi(msg) })}
467
- `
468
- );
469
- return;
470
- }
471
- message(msg, { symbol: chalk5.red("\u25A0") });
472
- }
473
- var log = {
474
- info,
475
- success,
476
- message,
477
- warn,
478
- error
479
- };
480
-
481
- // packages/design-system/src/components/logger.ts
482
- function createLogger(emitter) {
483
- const emit = (level, message2) => {
484
- if (emitter) {
485
- emitter(message2);
486
- return;
487
- }
488
- if (level === "success") {
489
- log.success(message2);
490
- return;
491
- }
492
- if (level === "warn") {
493
- log.warn(message2);
494
- return;
495
- }
496
- if (level === "error") {
497
- log.error(message2);
498
- return;
499
- }
500
- log.info(message2);
501
- };
502
- return {
503
- info(message2) {
504
- emit("info", message2);
505
- },
506
- success(message2) {
507
- emit("success", message2);
508
- },
509
- warn(message2) {
510
- emit("warn", message2);
511
- },
512
- error(message2) {
513
- emit("error", message2);
514
- },
515
- resolved(label, value) {
516
- if (emitter) {
517
- emitter(`${label}: ${value}`);
518
- return;
519
- }
520
- log.message(`${label}
521
- ${value}`, { symbol: symbols.resolved });
522
- },
523
- errorResolved(label, value) {
524
- if (emitter) {
525
- emitter(`${label}: ${value}`);
526
- return;
527
- }
528
- log.message(`${label}
529
- ${value}`, { symbol: symbols.errorResolved });
530
- },
531
- message(message2, symbol) {
532
- if (emitter) {
533
- emitter(message2);
534
- return;
535
- }
536
- log.message(message2, { symbol: symbol ?? chalk6.gray("\u2502") });
537
- }
538
- };
539
- }
540
- var logger = createLogger();
541
-
542
- // packages/design-system/src/components/help-formatter.ts
543
- function formatCommand(name, description) {
544
- const paddedName = name.padEnd(widths.helpColumn);
545
- return ` ${text.command(paddedName)} ${description}`;
546
- }
547
- function formatOption(flags, description) {
548
- const paddedFlags = flags.padEnd(widths.helpColumn);
549
- return ` ${text.option(paddedFlags)} ${description}`;
550
- }
551
- function formatCommandList(commands) {
552
- return commands.map((cmd) => formatCommand(cmd.name, cmd.description)).join("\n");
553
- }
554
- function formatOptionList(options) {
555
- return options.map((opt) => formatOption(opt.flags, opt.description)).join("\n");
556
- }
557
-
558
- // packages/design-system/src/components/table.ts
559
- import { Table } from "console-table-printer";
560
- function renderTableTerminal(options) {
561
- const { theme, columns, rows } = options;
562
- const table = new Table({
563
- style: {
564
- headerTop: {
565
- left: theme.muted("\u250C"),
566
- mid: theme.muted("\u252C"),
567
- right: theme.muted("\u2510"),
568
- other: theme.muted("\u2500")
569
- },
570
- headerBottom: {
571
- left: theme.muted("\u251C"),
572
- mid: theme.muted("\u253C"),
573
- right: theme.muted("\u2524"),
574
- other: theme.muted("\u2500")
575
- },
576
- tableBottom: {
577
- left: theme.muted("\u2514"),
578
- mid: theme.muted("\u2534"),
579
- right: theme.muted("\u2518"),
580
- other: theme.muted("\u2500")
581
- },
582
- vertical: theme.muted("\u2502"),
583
- rowSeparator: {
584
- left: theme.muted("\u251C"),
585
- mid: theme.muted("\u253C"),
586
- right: theme.muted("\u2524"),
587
- other: theme.muted("\u2500")
588
- }
589
- },
590
- columns: columns.map((col) => ({
591
- name: col.name,
592
- title: theme.header(col.title),
593
- alignment: col.alignment,
594
- maxLen: col.maxLen
595
- }))
596
- });
597
- for (const row of rows) {
598
- table.addRow(row);
599
- }
600
- return table.render();
601
- }
602
- function renderTableMarkdown(options) {
603
- const { columns, rows } = options;
604
- const header = `| ${columns.map((c) => c.title).join(" | ")} |`;
605
- const separator = `| ${columns.map((c) => c.alignment === "right" ? "---:" : ":---").join(" | ")} |`;
606
- const dataRows = rows.map(
607
- (row) => `| ${columns.map((c) => stripAnsi(row[c.name] ?? "").replace(/\|/g, "\\|")).join(" | ")} |`
608
- );
609
- return [header, separator, ...dataRows].join("\n");
610
- }
611
- function renderTableJson(options) {
612
- const { columns, rows } = options;
613
- const cleaned = rows.map((row) => {
614
- const obj = {};
615
- for (const col of columns) {
616
- obj[col.name] = stripAnsi(row[col.name] ?? "");
617
- }
618
- return obj;
619
- });
620
- return JSON.stringify(cleaned, null, 2);
621
- }
622
- function renderTable(options) {
623
- const format = resolveOutputFormat();
624
- switch (format) {
625
- case "markdown":
626
- return renderTableMarkdown(options);
627
- case "json":
628
- return renderTableJson(options);
629
- default:
630
- return renderTableTerminal(options);
631
- }
632
- }
633
-
634
- // packages/design-system/src/acp/components.ts
635
- import chalk7 from "chalk";
636
-
637
- // packages/design-system/src/acp/writer.ts
638
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
639
- var storage = new AsyncLocalStorage2();
640
-
641
- // packages/design-system/src/acp/components.ts
642
- var AGENT_PREFIX = `${chalk7.green.bold("\u2713")} agent: `;
643
-
644
- // packages/design-system/src/dashboard/buffer.ts
645
- import chalk8 from "chalk";
646
-
647
- // packages/design-system/src/dashboard/terminal.ts
648
- import readline from "node:readline";
649
- import { PassThrough } from "node:stream";
650
-
651
- // packages/design-system/src/prompts/index.ts
652
- import chalk15 from "chalk";
653
- import * as clack from "@clack/prompts";
654
-
655
- // packages/design-system/src/prompts/primitives/cancel.ts
656
- import chalk9 from "chalk";
657
-
658
- // node_modules/@clack/core/dist/index.mjs
659
- var import_sisteransi = __toESM(require_src(), 1);
660
- import { stdout as R, stdin as q } from "node:process";
661
- import * as k from "node:readline";
662
- import ot from "node:readline";
663
- import { ReadStream as J } from "node:tty";
664
- var P = new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*", "yu");
665
- var ct = new RegExp("\\p{M}+", "gu");
666
- var pt = { limit: 1 / 0, ellipsis: "" };
667
- var ft = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 };
668
- var j = "\x07";
669
- var Q = "[";
670
- var dt = "]";
671
- var U = `${dt}8;;`;
672
- var et = new RegExp(`(?:\\${Q}(?<code>\\d+)m|\\${U}(?<uri>.*)${j})`, "y");
673
- var At = ["up", "down", "left", "right", "space", "enter", "cancel"];
674
- var _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true };
675
- var bt = globalThis.process.platform.startsWith("win");
676
- var z = /* @__PURE__ */ Symbol("clack:cancel");
677
- function Ct(t) {
678
- return t === z;
679
- }
680
-
681
- // packages/design-system/src/prompts/primitives/cancel.ts
682
- function cancel(msg = "") {
683
- if (resolveOutputFormat() !== "terminal") {
684
- return;
685
- }
686
- process.stdout.write(`${chalk9.gray("\u2514")} ${chalk9.red(msg)}
687
-
688
- `);
689
- }
690
-
691
- // packages/design-system/src/prompts/primitives/intro.ts
692
- import chalk10 from "chalk";
693
-
694
- // packages/design-system/src/prompts/primitives/note.ts
695
- import chalk11 from "chalk";
696
- function getVisibleWidth(value) {
697
- return stripAnsi(value).length;
698
- }
699
- function renderTerminalNote(message2, title) {
700
- const contentLines = ["", ...message2.split("\n"), ""];
701
- const visibleTitle = stripAnsi(title ?? "");
702
- const contentWidth = Math.max(
703
- visibleTitle.length,
704
- ...contentLines.map((line) => getVisibleWidth(line))
705
- ) + 2;
706
- const titleLine = `${chalk11.green("\u25C7")} ${chalk11.reset(title ?? "")} ${chalk11.gray(
707
- `${"\u2500".repeat(Math.max(contentWidth - visibleTitle.length - 1, 1))}\u256E`
708
- )}`;
709
- const content = contentLines.map((line) => {
710
- const padding = " ".repeat(contentWidth - getVisibleWidth(line));
711
- return `${chalk11.gray("\u2502")} ${line}${padding}${chalk11.gray("\u2502")}`;
712
- });
713
- const bottom = chalk11.gray(`\u251C${"\u2500".repeat(contentWidth + 2)}\u256F`);
714
- return [chalk11.gray("\u2502"), titleLine, ...content, bottom].join("\n");
715
- }
716
- function note(message2, title) {
717
- const format = resolveOutputFormat();
718
- const strippedMessage = stripAnsi(message2);
719
- const strippedTitle = stripAnsi(title ?? "");
720
- if (format === "markdown") {
721
- const lines = strippedMessage.split("\n");
722
- const heading = strippedTitle ? `> **${strippedTitle}**
723
- ` : "";
724
- const body = lines.map((line) => `> ${line}`).join("\n");
725
- process.stdout.write(`${heading}${body}
726
- `);
727
- return;
728
- }
729
- if (format === "json") {
730
- process.stdout.write(
731
- `${JSON.stringify({
732
- type: "note",
733
- title: strippedTitle,
734
- message: strippedMessage
735
- })}
736
- `
737
- );
738
- return;
739
- }
740
- process.stdout.write(`${renderTerminalNote(message2, title)}
741
- `);
742
- }
743
-
744
- // packages/design-system/src/prompts/primitives/outro.ts
745
- import chalk12 from "chalk";
746
-
747
- // packages/design-system/src/prompts/primitives/spinner.ts
748
- import chalk14 from "chalk";
749
-
750
- // packages/design-system/src/static/spinner.ts
751
- import chalk13 from "chalk";
752
-
753
- // packages/design-system/src/prompts/index.ts
754
- async function select2(opts) {
755
- return clack.select(opts);
756
- }
757
- async function text3(opts) {
758
- return clack.text(opts);
759
- }
760
- async function confirm2(opts) {
761
- return clack.confirm(opts);
762
- }
763
-
764
- // packages/design-system/src/static/menu.ts
765
- import chalk16 from "chalk";
766
-
767
- // packages/cmdkit/src/index.ts
768
- import { fileURLToPath } from "node:url";
769
- var commandSourcePathSymbol = /* @__PURE__ */ Symbol("cmdkit.command.sourcePath");
770
- var UserError = class extends Error {
771
- constructor(message2) {
772
- super(message2);
773
- this.name = "UserError";
774
- }
775
- };
776
- function parseSimpleSemver(value) {
777
- const parts = value.split(".");
778
- if (parts.length !== 3) {
779
- return void 0;
780
- }
781
- const parsed = parts.map((part) => {
782
- if (part.length === 0) {
783
- return Number.NaN;
784
- }
785
- for (const char of part) {
786
- if (char < "0" || char > "9") {
787
- return Number.NaN;
788
- }
789
- }
790
- return Number(part);
791
- });
792
- if (parsed.some((part) => !Number.isInteger(part) || part < 0)) {
793
- return void 0;
794
- }
795
- return parsed;
796
- }
797
- function parseMinimumApiVersion(requirement) {
798
- if (!requirement.startsWith(">=")) {
799
- return void 0;
800
- }
801
- return parseSimpleSemver(requirement.slice(2).trim());
802
- }
803
- function compareSemver(left, right) {
804
- for (let index = 0; index < left.length; index += 1) {
805
- if (left[index] === right[index]) {
806
- continue;
807
- }
808
- return left[index] > right[index] ? 1 : -1;
809
- }
810
- return 0;
811
- }
812
- function resolveCommandSecrets(command, env = process.env) {
813
- const secrets = {};
814
- for (const [name, secret] of Object.entries(command.secrets)) {
815
- const value = env[secret.env];
816
- if (value === void 0 && secret.optional !== true) {
817
- const details = secret.description ? `
818
- ${secret.description}` : "";
819
- throw new UserError(`Error: Missing required secret ${secret.env}${details}`);
820
- }
821
- secrets[name] = value;
822
- }
823
- return secrets;
824
- }
825
- async function assertCommandRequirements(command, context, options = {}) {
826
- const requires = command.requires;
827
- if (requires === void 0) {
828
- return;
829
- }
830
- const env = options.env ?? process.env;
831
- const authEnvVar = options.authEnvVar ?? "POE_API_KEY";
832
- if (requires.auth === true && env[authEnvVar] === void 0) {
833
- throw new UserError(
834
- `Error: Command "${command.name}" requires authentication.
835
- Run 'poe-code login' first.`
836
- );
837
- }
838
- if (requires.apiVersion !== void 0) {
839
- const minimumVersion = parseMinimumApiVersion(requires.apiVersion);
840
- if (minimumVersion === void 0) {
841
- throw new UserError(
842
- `Error: Command "${command.name}" has invalid apiVersion requirement "${requires.apiVersion}". Expected format ">=X.Y.Z".`
843
- );
844
- }
845
- if (options.apiVersion === void 0) {
846
- throw new UserError(
847
- `Error: Command "${command.name}" requires API version ${requires.apiVersion}, but no runner API version was provided.`
848
- );
849
- }
850
- const runnerVersion = parseSimpleSemver(options.apiVersion);
851
- if (runnerVersion === void 0) {
852
- throw new UserError(
853
- `Error: Command "${command.name}" requires API version ${requires.apiVersion}, but runner API version "${options.apiVersion}" is not valid semver.`
854
- );
855
- }
856
- if (compareSemver(runnerVersion, minimumVersion) < 0) {
857
- throw new UserError(
858
- `Error: Command "${command.name}" requires API version ${requires.apiVersion}, but runner API version is ${options.apiVersion}.`
859
- );
860
- }
861
- }
862
- const checkResult = await requires.check?.(context);
863
- if (checkResult && !checkResult.ok) {
864
- throw new UserError(checkResult.message ?? "Command precondition failed.");
865
- }
866
- }
867
- function getCommandSourcePath(command) {
868
- return command[commandSourcePathSymbol];
869
- }
870
-
871
- // packages/cmdkit/src/number-schema.ts
872
- function isValidNumberSchemaValue(value, schema) {
873
- return typeof value === "number" && Number.isFinite(value) && (schema.jsonType !== "integer" || Number.isInteger(value));
874
- }
875
- function getExpectedNumberDescription(schema) {
876
- return schema.jsonType === "integer" ? "an integer" : "a number";
877
- }
878
-
879
- // packages/cmdkit/src/renderer.ts
880
- function isObject(value) {
881
- return value !== null && typeof value === "object" && !Array.isArray(value);
882
- }
883
- function isArrayOfObjects(value) {
884
- return Array.isArray(value) && value.every((entry) => isObject(entry));
885
- }
886
- function stringifyValue(value) {
887
- if (value === void 0) {
888
- return "";
889
- }
890
- if (typeof value === "string") {
891
- return value;
892
- }
893
- return stringifyJson(value);
894
- }
895
- function stringifyJson(value, spaces) {
896
- try {
897
- return JSON.stringify(
898
- value,
899
- (_key, currentValue) => typeof currentValue === "bigint" ? currentValue.toString() : currentValue,
900
- spaces
901
- ) ?? String(value);
902
- } catch {
903
- return String(value);
904
- }
905
- }
906
- function renderObjectTable(result, primitives) {
907
- const rows = Object.entries(result).map(([key, value]) => ({
908
- key,
909
- value: stringifyValue(value)
910
- }));
911
- return primitives.renderTable({
912
- theme: primitives.getTheme(),
913
- columns: [
914
- {
915
- name: "key",
916
- title: "Key",
917
- alignment: "left",
918
- maxLen: Math.max("Key".length, ...rows.map((row) => row.key.length))
919
- },
920
- {
921
- name: "value",
922
- title: "Value",
923
- alignment: "left",
924
- maxLen: Math.max("Value".length, ...rows.map((row) => row.value.length))
925
- }
926
- ],
927
- rows
928
- });
929
- }
930
- function renderObjectMarkdown(result) {
931
- return Object.entries(result).map(([key, value]) => `- ${key}: ${stringifyValue(value)}`).join("\n");
932
- }
933
- function getColumnNames(rows) {
934
- const names = /* @__PURE__ */ new Set();
935
- for (const row of rows) {
936
- for (const name of Object.keys(row)) {
937
- names.add(name);
938
- }
939
- }
940
- return [...names];
941
- }
942
- function renderArrayTable(result, primitives) {
943
- if (result.length === 0) {
944
- return "[]";
945
- }
946
- const columnNames = getColumnNames(result);
947
- return primitives.renderTable({
948
- theme: primitives.getTheme(),
949
- columns: columnNames.map((name) => ({
950
- name,
951
- title: name,
952
- alignment: "left",
953
- maxLen: Math.max(
954
- name.length,
955
- ...result.map((row) => name in row ? stringifyValue(row[name]).length : 0)
956
- )
957
- })),
958
- rows: result.map(
959
- (row) => Object.fromEntries(
960
- columnNames.map((name) => [name, name in row ? stringifyValue(row[name]) : ""])
961
- )
962
- )
963
- });
964
- }
965
- function renderArrayMarkdown(result) {
966
- if (result.length === 0) {
967
- return "[]";
968
- }
969
- const columnNames = getColumnNames(result);
970
- const header = `| ${columnNames.join(" | ")} |`;
971
- const separator = `| ${columnNames.map(() => ":---").join(" | ")} |`;
972
- const rows = result.map(
973
- (row) => `| ${columnNames.map((name) => name in row ? stringifyValue(row[name]).replaceAll("|", "\\|") : "").join(" | ")} |`
974
- );
975
- return [header, separator, ...rows].join("\n");
976
- }
977
- function autoRender(result, output, primitives) {
978
- if (result === null || result === void 0) {
979
- if (output === "json") {
980
- return stringifyJson({ ok: true }, 2);
981
- }
982
- return "Done.";
983
- }
984
- if (typeof result === "string") {
985
- if (output === "json") {
986
- return stringifyJson({ result }, 2);
987
- }
988
- return result;
989
- }
990
- if (isObject(result)) {
991
- if (output === "rich") {
992
- return renderObjectTable(result, primitives);
993
- }
994
- if (output === "md") {
995
- return renderObjectMarkdown(result);
996
- }
997
- return stringifyJson(result, 2);
998
- }
999
- if (isArrayOfObjects(result)) {
1000
- if (output === "md") {
1001
- return renderArrayMarkdown(result);
1002
- }
1003
- if (output === "json") {
1004
- return stringifyJson(result, 2);
1005
- }
1006
- return renderArrayTable(result, primitives);
1007
- }
1008
- return stringifyJson(result, 2);
1009
- }
1010
- function renderResult(command, result, output, primitives, write = (chunk) => {
1011
- process.stdout.write(chunk);
1012
- }) {
1013
- if (output === "json" && command.render?.json) {
1014
- const payload2 = command.render.json(result, primitives);
1015
- if (payload2 !== void 0) {
1016
- write(`${stringifyJson(payload2, 2)}
1017
- `);
1018
- }
1019
- return;
1020
- }
1021
- if (output === "md" && command.render?.markdown) {
1022
- const payload2 = command.render.markdown(result, primitives);
1023
- if (typeof payload2 === "string" && payload2.length > 0) {
1024
- write(`${payload2}
1025
- `);
1026
- }
1027
- return;
1028
- }
1029
- if (output === "rich" && command.render?.rich) {
1030
- command.render.rich(result, primitives);
1031
- return;
1032
- }
1033
- const payload = autoRender(result, output, primitives);
1034
- if (payload.length > 0) {
1035
- write(`${payload}
1036
- `);
1037
- }
1038
- }
1039
-
1040
- // packages/cmdkit/src/cli.ts
1041
- var RESERVED_SERVICE_NAMES = /* @__PURE__ */ new Set(["params", "secrets", "fetch", "fs", "env", "progress"]);
1042
- function inferProgramName(argv) {
1043
- const entrypoint = argv[1];
1044
- if (typeof entrypoint !== "string" || entrypoint.length === 0) {
1045
- return "cmdkit";
1046
- }
1047
- const parsed = path.parse(entrypoint);
1048
- return parsed.name.length > 0 ? parsed.name : "cmdkit";
1049
- }
1050
- function normalizeRoots(roots, argv) {
1051
- if (!Array.isArray(roots)) {
1052
- return roots;
1053
- }
1054
- return {
1055
- kind: "group",
1056
- name: inferProgramName(argv),
1057
- aliases: [],
1058
- secrets: {},
1059
- children: roots
1060
- };
1061
- }
1062
- var HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h"]);
1063
- function unwrapOptional(schema) {
1064
- if (schema.kind === "optional") {
1065
- return unwrapOptional(schema.inner);
1066
- }
1067
- return schema;
1068
- }
1069
- function splitWords(value) {
1070
- const words = [];
1071
- let current = "";
1072
- for (let index = 0; index < value.length; index += 1) {
1073
- const char = value[index] ?? "";
1074
- const lower = char.toLowerCase();
1075
- const upper = char.toUpperCase();
1076
- const isSeparator = char === "-" || char === "_" || char === " " || char === ".";
1077
- if (isSeparator) {
1078
- if (current.length > 0) {
1079
- words.push(current.toLowerCase());
1080
- current = "";
1081
- }
1082
- continue;
1083
- }
1084
- const isUppercase = char !== lower && char === upper;
1085
- const previous = value[index - 1];
1086
- const next = value[index + 1];
1087
- const previousIsLowercase = previous !== void 0 && previous === previous.toLowerCase() && previous !== previous.toUpperCase();
1088
- const nextIsLowercase = next !== void 0 && next === next.toLowerCase() && next !== next.toUpperCase();
1089
- if (isUppercase && current.length > 0 && (previousIsLowercase || nextIsLowercase)) {
1090
- words.push(current.toLowerCase());
1091
- current = char;
1092
- continue;
1093
- }
1094
- current += char;
1095
- }
1096
- if (current.length > 0) {
1097
- words.push(current.toLowerCase());
1098
- }
1099
- return words;
1100
- }
1101
- function formatSegment(segment, casing) {
1102
- const separator = casing === "snake" ? "_" : "-";
1103
- return splitWords(segment).join(separator);
1104
- }
1105
- function toOptionFlag(path2, casing) {
1106
- return `--${path2.map((segment) => formatSegment(segment, casing)).join(".")}`;
1107
- }
1108
- function toOptionAttribute(path2, casing) {
1109
- return path2.map((segment) => {
1110
- const formatted = formatSegment(segment, casing);
1111
- if (casing === "snake") {
1112
- return formatted;
1113
- }
1114
- const words = formatted.split("-");
1115
- return words.map(
1116
- (word, index) => index === 0 ? word : `${word[0]?.toUpperCase() ?? ""}${word.slice(1)}`
1117
- ).join("");
1118
- }).join(".");
1119
- }
1120
- function toDisplayPath(path2) {
1121
- return path2.join(".");
1122
- }
1123
- function collectFields(schema, casing, path2 = [], inheritedOptional = false) {
1124
- const fields = [];
1125
- for (const [key, rawChildSchema] of Object.entries(schema.shape)) {
1126
- const nextPath = [...path2, key];
1127
- const optional = inheritedOptional || rawChildSchema.kind === "optional";
1128
- const childSchema = unwrapOptional(rawChildSchema);
1129
- if (childSchema.kind === "object") {
1130
- fields.push(...collectFields(childSchema, casing, nextPath, optional));
1131
- continue;
1132
- }
1133
- fields.push({
1134
- path: nextPath,
1135
- displayPath: toDisplayPath(nextPath),
1136
- optionAttribute: toOptionAttribute(nextPath, casing),
1137
- commanderOptionAttribute: toCommanderOptionAttribute(nextPath, casing),
1138
- optionFlag: toOptionFlag(nextPath, casing),
1139
- shortFlag: childSchema.short,
1140
- schema: childSchema,
1141
- description: childSchema.description,
1142
- optional,
1143
- hasDefault: childSchema.default !== void 0,
1144
- defaultValue: childSchema.default
1145
- });
1146
- }
1147
- return fields;
1148
- }
1149
- function toCommanderOptionAttribute(path2, casing) {
1150
- const optionAttribute = toOptionAttribute(path2, casing);
1151
- const optionFlag = toOptionFlag(path2, casing);
1152
- if (!GLOBAL_LONG_OPTION_FLAGS.has(optionFlag)) {
1153
- return optionAttribute;
1154
- }
1155
- return `param_${optionAttribute}`;
1156
- }
1157
- function assignPositionals(fields, positional) {
1158
- if (positional.length === 0) {
1159
- return fields;
1160
- }
1161
- const byPath = new Map(fields.map((field) => [field.displayPath, field]));
1162
- let variadicPositionSeen = false;
1163
- positional.forEach((name, index) => {
1164
- const field = byPath.get(name);
1165
- if (field === void 0) {
1166
- throw new UserError(`Positional parameter "${name}" does not exist in params.`);
1167
- }
1168
- if (field.schema.kind === "array") {
1169
- if (index !== positional.length - 1) {
1170
- throw new UserError(`Positional array parameter "${name}" must be the last positional.`);
1171
- }
1172
- variadicPositionSeen = true;
1173
- }
1174
- if (variadicPositionSeen && field.schema.kind !== "array") {
1175
- throw new UserError(`Positional parameter "${name}" cannot appear after a positional array.`);
1176
- }
1177
- field.positionalIndex = index;
1178
- field.variadicPosition = field.schema.kind === "array";
1179
- });
1180
- return fields;
1181
- }
1182
- function formatOptionFlags(field) {
1183
- const collidesWithGlobalFlag = GLOBAL_LONG_OPTION_FLAGS.has(field.optionFlag);
1184
- if (collidesWithGlobalFlag) {
1185
- if (field.shortFlag === void 0) {
1186
- throw new UserError(
1187
- `Parameter "${field.displayPath}" uses reserved CLI flag "${field.optionFlag}". Add a short flag or rename the parameter.`
1188
- );
1189
- }
1190
- return `-${field.shortFlag}`;
1191
- }
1192
- if (field.shortFlag === void 0) {
1193
- return field.optionFlag;
1194
- }
1195
- return `-${field.shortFlag}, ${field.optionFlag}`;
1196
- }
1197
- function formatPositionalToken(field) {
1198
- const optionalPositional = field.optional || field.hasDefault;
1199
- if (field.variadicPosition === true) {
1200
- return optionalPositional ? `[${field.displayPath}...]` : `<${field.displayPath}...>`;
1201
- }
1202
- return optionalPositional ? `[${field.displayPath}]` : `<${field.displayPath}>`;
1203
- }
1204
- function parseBooleanText(value, label) {
1205
- const normalized = value.trim().toLowerCase();
1206
- if (normalized === "true") {
1207
- return true;
1208
- }
1209
- if (normalized === "false") {
1210
- return false;
1211
- }
1212
- throw new InvalidArgumentError(`Invalid value for "${label}". Expected true or false.`);
1213
- }
1214
- function parseEnumValue(value, values, label) {
1215
- const match = values.find((candidate) => String(candidate) === value);
1216
- if (match === void 0) {
1217
- throw new InvalidArgumentError(
1218
- `Invalid value for "${label}". Expected one of: ${values.map((candidate) => String(candidate)).join(", ")}.`
1219
- );
1220
- }
1221
- return match;
1222
- }
1223
- function parseScalarValue(value, schema, label) {
1224
- switch (schema.kind) {
1225
- case "string":
1226
- return value;
1227
- case "number": {
1228
- const parsed = Number(value);
1229
- if (!isValidNumberSchemaValue(parsed, schema)) {
1230
- throw new InvalidArgumentError(
1231
- `Invalid value for "${label}". Expected ${getExpectedNumberDescription(schema)}.`
1232
- );
1233
- }
1234
- return parsed;
1235
- }
1236
- case "boolean":
1237
- return parseBooleanText(value, label);
1238
- case "enum":
1239
- return parseEnumValue(value, schema.values, label);
1240
- default:
1241
- throw new UserError(`Unsupported CLI schema kind "${schema.kind}".`);
1242
- }
1243
- }
1244
- function splitArrayInput(value) {
1245
- const items = [];
1246
- let current = "";
1247
- for (let index = 0; index < value.length; index += 1) {
1248
- const char = value[index] ?? "";
1249
- if (char === ",") {
1250
- const trimmed2 = current.trim();
1251
- if (trimmed2.length > 0) {
1252
- items.push(trimmed2);
1253
- }
1254
- current = "";
1255
- continue;
1256
- }
1257
- current += char;
1258
- }
1259
- const trimmed = current.trim();
1260
- if (trimmed.length > 0) {
1261
- items.push(trimmed);
1262
- }
1263
- return items;
1264
- }
1265
- function parseArrayValue(value, schema, label) {
1266
- const itemSchema = unwrapOptional(schema.item);
1267
- if (itemSchema.kind === "array" || itemSchema.kind === "object") {
1268
- throw new UserError(`Array parameter "${label}" must use scalar items.`);
1269
- }
1270
- return splitArrayInput(value).map((item) => parseScalarValue(item, itemSchema, label));
1271
- }
1272
- function createOption(field) {
1273
- const flags = formatOptionFlags(field);
1274
- const collidesWithGlobalFlag = GLOBAL_LONG_OPTION_FLAGS.has(field.optionFlag);
1275
- if (field.schema.kind === "boolean") {
1276
- if (collidesWithGlobalFlag) {
1277
- return [createCommanderOption(flags, field.description, field)];
1278
- }
1279
- const mainOption = createCommanderOption(`${flags} [value]`, field.description, field);
1280
- mainOption.preset(true);
1281
- mainOption.argParser(
1282
- (value) => typeof value === "boolean" ? value : parseBooleanText(value, field.displayPath)
1283
- );
1284
- return [
1285
- mainOption,
1286
- createCommanderOption(`--no-${field.optionFlag.slice(2)}`, field.description, field)
1287
- ];
1288
- }
1289
- if (field.schema.kind === "array") {
1290
- return [
1291
- createCommanderOption(`${flags} <value...>`, field.description, field).argParser(
1292
- (value, previous = []) => [
1293
- ...previous,
1294
- ...parseArrayValue(value, field.schema, field.displayPath)
1295
- ]
1296
- )
1297
- ];
1298
- }
1299
- const option = createCommanderOption(`${flags} <value>`, field.description, field);
1300
- if (field.schema.kind === "enum" && field.schema.values.every((value) => typeof value === "string")) {
1301
- option.choices([...field.schema.values]);
1302
- }
1303
- option.argParser((value) => parseScalarValue(value, field.schema, field.displayPath));
1304
- return [option];
1305
- }
1306
- var GLOBAL_LONG_OPTION_FLAGS = /* @__PURE__ */ new Set(["--preset", "--yes", "--output", "--verbose"]);
1307
- function createCommanderOption(flags, description, field) {
1308
- const option = new Option(flags, description);
1309
- if (field.commanderOptionAttribute !== field.optionAttribute) {
1310
- option.attributeName = () => field.commanderOptionAttribute;
1311
- }
1312
- return option;
1313
- }
1314
- function hasHelpFlag(argv) {
1315
- return argv.some((token) => HELP_FLAGS.has(token));
1316
- }
1317
- function resolveHelpOutput(argv) {
1318
- for (let index = 0; index < argv.length; index += 1) {
1319
- const token = argv[index] ?? "";
1320
- if (token === "--output") {
1321
- const value = argv[index + 1];
1322
- if (value === "rich" || value === "md" || value === "json") {
1323
- return value;
1324
- }
1325
- if (value === "markdown") {
1326
- return "md";
1327
- }
1328
- continue;
1329
- }
1330
- if (token.startsWith("--output=")) {
1331
- const value = token.slice("--output=".length);
1332
- if (value === "rich" || value === "md" || value === "json") {
1333
- return value;
1334
- }
1335
- if (value === "markdown") {
1336
- return "md";
1337
- }
1338
- }
1339
- }
1340
- return "rich";
1341
- }
1342
- function isNodeVisibleInScope(node, scope) {
1343
- if (node.kind === "command") {
1344
- return node.scope.includes(scope);
1345
- }
1346
- return getVisibleChildren(node, scope).length > 0 || Boolean(node.default && node.default.scope.includes(scope)) || node.scope === void 0 || node.scope.includes(scope);
1347
- }
1348
- function getVisibleChildren(group, scope) {
1349
- return group.children.filter((child) => isNodeVisibleInScope(child, scope));
1350
- }
1351
- function findVisibleChild(group, token, scope) {
1352
- return getVisibleChildren(group, scope).find(
1353
- (child) => child.name === token || child.aliases.includes(token)
1354
- );
1355
- }
1356
- function resolveHelpTarget(root, argv, scope, rootDisplayName) {
1357
- const breadcrumb = [rootDisplayName ?? root.name];
1358
- let current = root;
1359
- for (const token of argv.slice(2)) {
1360
- if (token.startsWith("-") || token === "help") {
1361
- break;
1362
- }
1363
- if (current.kind !== "group") {
1364
- break;
1365
- }
1366
- const child = findVisibleChild(
1367
- current,
1368
- token,
1369
- scope
1370
- );
1371
- if (child === void 0) {
1372
- break;
1373
- }
1374
- breadcrumb.push(child.name);
1375
- current = child;
1376
- }
1377
- return {
1378
- breadcrumb,
1379
- node: current
1380
- };
1381
- }
1382
- function describeSchemaType(schema) {
1383
- switch (schema.kind) {
1384
- case "string":
1385
- return "string";
1386
- case "number":
1387
- return "number";
1388
- case "boolean":
1389
- return "boolean";
1390
- case "enum":
1391
- return "value";
1392
- case "array":
1393
- return `${describeSchemaType(unwrapOptional(schema.item))}...`;
1394
- default:
1395
- throw new UserError("Unsupported CLI schema kind.");
1396
- }
1397
- }
1398
- function formatHelpFieldFlags(field) {
1399
- if (field.positionalIndex !== void 0) {
1400
- return formatPositionalToken(field);
1401
- }
1402
- if (field.schema.kind === "boolean") {
1403
- return `${formatOptionFlags(field)} [value]`;
1404
- }
1405
- return `${formatOptionFlags(field)} <${describeSchemaType(field.schema)}>`;
1406
- }
1407
- function appendHelpMetadata(description, metadata) {
1408
- if (metadata.length === 0) {
1409
- return description;
1410
- }
1411
- if (description.length === 0) {
1412
- return `(${metadata.join(", ")})`;
1413
- }
1414
- return `${description} (${metadata.join(", ")})`;
1415
- }
1416
- function formatHelpFieldDescription(field) {
1417
- const description = field.description ?? field.displayPath;
1418
- const metadata = [];
1419
- if (!field.optional && !field.hasDefault) {
1420
- metadata.push("required");
1421
- }
1422
- if (field.hasDefault) {
1423
- metadata.push(`default: ${formatResolvedValue(field.defaultValue)}`);
1424
- }
1425
- return appendHelpMetadata(description, metadata);
1426
- }
1427
- function formatSecretRows(secrets) {
1428
- return Object.values(secrets).map((secret) => ({
1429
- flags: secret.env,
1430
- description: formatSecretDescription(secret)
1431
- }));
1432
- }
1433
- function formatSecretDescription(secret) {
1434
- if (secret.description !== void 0 && secret.description.length > 0) {
1435
- return secret.description;
1436
- }
1437
- return secret.optional === true ? "Optional secret" : "Required secret";
1438
- }
1439
- function formatCommandRows(group, scope) {
1440
- return getVisibleChildren(group, scope).map((child) => ({
1441
- name: child.aliases.length === 0 ? child.name : `${child.name} (${child.aliases.join(", ")})`,
1442
- description: child.description ?? ""
1443
- }));
1444
- }
1445
- function formatGlobalOptionRows(showVersion) {
1446
- const rows = [
1447
- {
1448
- flags: "--preset <path>",
1449
- description: "Load parameter defaults from a JSON file"
1450
- },
1451
- {
1452
- flags: "--yes",
1453
- description: "Accept defaults, skip prompts"
1454
- },
1455
- {
1456
- flags: "--output <format>",
1457
- description: "Output format (rich, md, json)"
1458
- },
1459
- {
1460
- flags: "-h, --help",
1461
- description: "Show help"
1462
- }
1463
- ];
1464
- if (showVersion) {
1465
- rows.push({
1466
- flags: "--version",
1467
- description: "Show version"
1468
- });
1469
- }
1470
- return rows;
1471
- }
1472
- function renderHelpSections(sections) {
1473
- return sections.filter((section) => section.length > 0).join("\n\n");
1474
- }
1475
- function buildUsageLine(breadcrumb, rootUsageName, suffix) {
1476
- if (rootUsageName === void 0) {
1477
- return void 0;
1478
- }
1479
- const subPath = breadcrumb.slice(1).join(" ");
1480
- return subPath ? `${rootUsageName} ${subPath} ${suffix}` : `${rootUsageName} ${suffix}`;
1481
- }
1482
- function renderGroupHelp(group, breadcrumb, scope, showVersion, rootUsageName) {
1483
- const sections = [];
1484
- const commandRows = formatCommandRows(group, scope);
1485
- if (commandRows.length > 0) {
1486
- sections.push(`${text.section("Commands:")}
1487
- ${formatCommandList(commandRows)}`);
1488
- }
1489
- sections.push(`${text.section("Global options:")}
1490
- ${formatOptionList(formatGlobalOptionRows(showVersion))}`);
1491
- return renderHelpDocument({
1492
- breadcrumb,
1493
- usageLine: buildUsageLine(breadcrumb, rootUsageName, "[options] [command]"),
1494
- description: group.description,
1495
- requiresAuth: group.requires?.auth === true,
1496
- sections
1497
- });
1498
- }
1499
- function renderLeafHelp(command, breadcrumb, casing, rootUsageName) {
1500
- const sections = [];
1501
- const fields = assignPositionals(collectFields(command.params, casing), command.positional);
1502
- const optionRows = fields.map((field) => ({
1503
- flags: formatHelpFieldFlags(field),
1504
- description: formatHelpFieldDescription(field)
1505
- }));
1506
- if (optionRows.length > 0) {
1507
- sections.push(`${text.section("Options:")}
1508
- ${formatOptionList(optionRows)}`);
1509
- }
1510
- sections.push(`${text.section("Global options:")}
1511
- ${formatOptionList(formatGlobalOptionRows(false))}`);
1512
- const secretRows = formatSecretRows(command.secrets);
1513
- if (secretRows.length > 0) {
1514
- sections.push(`${text.section("Secrets (via environment):")}
1515
- ${formatOptionList(secretRows)}`);
1516
- }
1517
- const positionalFields = fields.filter((f) => f.positionalIndex !== void 0);
1518
- const usageSuffix = positionalFields.length > 0 ? `[options] ${positionalFields.map(formatPositionalToken).join(" ")}` : "[options]";
1519
- return renderHelpDocument({
1520
- breadcrumb,
1521
- usageLine: buildUsageLine(breadcrumb, rootUsageName, usageSuffix),
1522
- description: command.description,
1523
- requiresAuth: command.requires?.auth === true,
1524
- sections
1525
- });
1526
- }
1527
- function renderHelpDocument(input) {
1528
- const lines = [text.heading(input.breadcrumb.join(" ")), ""];
1529
- if (input.usageLine !== void 0) {
1530
- lines.push(`${text.section("Usage:")} ${text.usageCommand(input.usageLine)}`, "");
1531
- }
1532
- if (input.description !== void 0) {
1533
- lines.push(input.description);
1534
- }
1535
- if (input.requiresAuth) {
1536
- lines.push("Requires: authentication");
1537
- }
1538
- if (input.description !== void 0 || input.requiresAuth) {
1539
- lines.push("");
1540
- }
1541
- lines.push(renderHelpSections(input.sections));
1542
- return `${lines.join("\n").trimEnd()}
1543
- `;
1544
- }
1545
- async function renderGeneratedHelp(root, argv, options) {
1546
- const target = resolveHelpTarget(root, argv, "cli", options.rootDisplayName);
1547
- const output = resolveHelpOutput(argv);
1548
- const casing = options.casing ?? "kebab";
1549
- await withOutputFormat2(output, async () => {
1550
- const rendered = target.node.kind === "group" ? renderGroupHelp(target.node, target.breadcrumb, "cli", options.version !== void 0, options.rootUsageName) : renderLeafHelp(target.node, target.breadcrumb, casing, options.rootUsageName);
1551
- process.stdout.write(rendered);
1552
- });
1553
- }
1554
- function createNodeCommand(node, casing, execute) {
1555
- if (node.kind === "command") {
1556
- if (!node.scope.includes("cli")) {
1557
- return null;
1558
- }
1559
- const command = new CommanderCommand(node.name);
1560
- const fields = assignPositionals(collectFields(node.params, casing), node.positional);
1561
- if (node.description !== void 0) {
1562
- command.description(node.description);
1563
- }
1564
- node.aliases.forEach((alias) => command.alias(alias));
1565
- command.addHelpCommand(false);
1566
- addGlobalOptions(command);
1567
- for (const field of fields) {
1568
- if (field.positionalIndex !== void 0) {
1569
- command.argument(formatPositionalToken(field));
1570
- continue;
1571
- }
1572
- for (const option of createOption(field)) {
1573
- command.addOption(option);
1574
- }
1575
- }
1576
- command.action(async (...args) => {
1577
- const actionCommand = args[args.length - 1];
1578
- const positionalValues = args.slice(0, -2);
1579
- await execute({
1580
- command: node,
1581
- fields,
1582
- positionalValues,
1583
- actionCommand
1584
- });
1585
- });
1586
- return command;
1587
- }
1588
- if (!isNodeVisibleInScope(node, "cli")) {
1589
- return null;
1590
- }
1591
- const visibleChildren = node.children.map((child) => createNodeCommand(child, casing, execute)).filter((child) => child !== null);
1592
- const group = new CommanderCommand(node.name);
1593
- if (node.description !== void 0) {
1594
- group.description(node.description);
1595
- }
1596
- node.aliases.forEach((alias) => group.alias(alias));
1597
- group.addHelpCommand(false);
1598
- addGlobalOptions(group);
1599
- for (const child of visibleChildren) {
1600
- const isDefaultChild = node.default !== void 0 && node.default.scope.includes("cli") && (child.name() === node.default.name || child.aliases().includes(node.default.name));
1601
- group.addCommand(child, isDefaultChild ? { isDefault: true } : void 0);
1602
- }
1603
- return group;
1604
- }
1605
- function addGlobalOptions(command) {
1606
- command.option("--preset <path>", "Load parameter defaults from a JSON file.").option("--yes", "Accept defaults and skip prompts.").option("--output <format>", "Output format.", (value) => {
1607
- if (value === "rich" || value === "md" || value === "json") {
1608
- return value;
1609
- }
1610
- if (value === "markdown") {
1611
- return "md";
1612
- }
1613
- throw new InvalidArgumentError('Invalid value for "--output". Expected one of: rich, md, markdown, json.');
1614
- }).option("--verbose", "Print stack traces for unexpected errors.");
1615
- }
1616
- function setNestedValue(target, path2, value) {
1617
- let cursor = target;
1618
- for (let index = 0; index < path2.length - 1; index += 1) {
1619
- const segment = path2[index] ?? "";
1620
- const existing = cursor[segment];
1621
- if (typeof existing === "object" && existing !== null) {
1622
- cursor = existing;
1623
- continue;
1624
- }
1625
- const next = {};
1626
- cursor[segment] = next;
1627
- cursor = next;
1628
- }
1629
- const leaf = path2[path2.length - 1];
1630
- if (leaf !== void 0) {
1631
- cursor[leaf] = value;
1632
- }
1633
- }
1634
- function formatResolvedValue(value) {
1635
- if (Array.isArray(value)) {
1636
- return value.map((item) => String(item)).join(", ");
1637
- }
1638
- if (typeof value === "string") {
1639
- return value;
1640
- }
1641
- return JSON.stringify(value);
1642
- }
1643
- async function promptForField(field) {
1644
- const schema = field.schema;
1645
- if (schema.kind === "enum") {
1646
- const options = schema.loadOptions ? await schema.loadOptions() : schema.values.map((value) => ({
1647
- label: schema.labels?.[String(value)] ?? String(value),
1648
- value
1649
- }));
1650
- const selected = await select2({
1651
- message: field.description ?? field.displayPath,
1652
- options,
1653
- initialValue: field.hasDefault ? field.defaultValue : void 0
1654
- });
1655
- if (Ct(selected)) {
1656
- cancel("Operation cancelled.");
1657
- throw new UserError("Operation cancelled.");
1658
- }
1659
- return selected;
1660
- }
1661
- if (field.schema.kind === "boolean") {
1662
- const selected = await confirm2({
1663
- message: field.displayPath,
1664
- initialValue: field.hasDefault ? Boolean(field.defaultValue) : void 0
1665
- });
1666
- if (Ct(selected)) {
1667
- cancel("Operation cancelled.");
1668
- throw new UserError("Operation cancelled.");
1669
- }
1670
- return selected;
1671
- }
1672
- const entered = await text3({
1673
- message: field.displayPath,
1674
- initialValue: field.hasDefault && field.defaultValue !== void 0 ? formatResolvedValue(field.defaultValue) : void 0
1675
- });
1676
- if (Ct(entered)) {
1677
- cancel("Operation cancelled.");
1678
- throw new UserError("Operation cancelled.");
1679
- }
1680
- if (typeof entered !== "string") {
1681
- throw new UserError(`Missing required parameter "${field.displayPath}".`);
1682
- }
1683
- if (entered.trim().length === 0 && field.hasDefault) {
1684
- return field.defaultValue;
1685
- }
1686
- if (field.schema.kind === "array") {
1687
- return parseArrayValue(entered, field.schema, field.displayPath);
1688
- }
1689
- return parseScalarValue(entered, field.schema, field.displayPath);
1690
- }
1691
- function resolveOutput(resolvedFlags) {
1692
- if (resolvedFlags.json === true) {
1693
- return "json";
1694
- }
1695
- if (resolvedFlags.output !== void 0) {
1696
- return resolvedFlags.output;
1697
- }
1698
- return "rich";
1699
- }
1700
- var DESIGN_SYSTEM_OUTPUT_BY_MODE = {
1701
- rich: "terminal",
1702
- md: "markdown",
1703
- json: "json"
1704
- };
1705
- function toDesignSystemOutput(output) {
1706
- return DESIGN_SYSTEM_OUTPUT_BY_MODE[output];
1707
- }
1708
- async function withOutputFormat2(output, fn) {
1709
- const previous = process.env.OUTPUT_FORMAT;
1710
- process.env.OUTPUT_FORMAT = toDesignSystemOutput(output);
1711
- resetOutputFormatCache();
1712
- try {
1713
- return await fn();
1714
- } finally {
1715
- if (previous === void 0) {
1716
- delete process.env.OUTPUT_FORMAT;
1717
- } else {
1718
- process.env.OUTPUT_FORMAT = previous;
1719
- }
1720
- resetOutputFormatCache();
1721
- }
1722
- }
1723
- function createFs() {
1724
- return {
1725
- readFile: async (path2, encoding = "utf8") => readFile(path2, { encoding }),
1726
- writeFile: async (path2, contents) => {
1727
- await writeFile(path2, contents);
1728
- },
1729
- exists: async (path2) => {
1730
- try {
1731
- await access(path2);
1732
- return true;
1733
- } catch {
1734
- return false;
1735
- }
1736
- }
1737
- };
1738
- }
1739
- function createEnv(values = process.env) {
1740
- return {
1741
- get(key) {
1742
- return values[key];
1743
- }
1744
- };
1745
- }
1746
- function isPlainObject(value) {
1747
- return typeof value === "object" && value !== null && !Array.isArray(value);
1748
- }
1749
- function hasFieldValue(value) {
1750
- return value !== void 0;
1751
- }
1752
- function hasNestedField(fields, path2) {
1753
- return fields.some(
1754
- (field) => path2.length < field.path.length && path2.every((segment, index) => field.path[index] === segment)
1755
- );
1756
- }
1757
- function describeExpectedPresetValue(schema) {
1758
- if (schema.kind === "array") {
1759
- return "an array";
1760
- }
1761
- if (schema.kind === "enum") {
1762
- return `one of: ${schema.values.map((value) => JSON.stringify(value)).join(", ")}`;
1763
- }
1764
- return `a ${schema.kind}`;
1765
- }
1766
- function validatePresetScalarValue(value, schema, fieldPath, presetPath) {
1767
- if (value === null && schema.nullable === true) {
1768
- return null;
1769
- }
1770
- switch (schema.kind) {
1771
- case "string":
1772
- if (typeof value !== "string") {
1773
- break;
1774
- }
1775
- return value;
1776
- case "number":
1777
- if (!isValidNumberSchemaValue(value, schema)) {
1778
- break;
1779
- }
1780
- return value;
1781
- case "boolean":
1782
- if (typeof value !== "boolean") {
1783
- break;
1784
- }
1785
- return value;
1786
- case "enum": {
1787
- const match = schema.values.find((candidate) => Object.is(candidate, value));
1788
- if (match !== void 0) {
1789
- return match;
1790
- }
1791
- break;
1792
- }
1793
- default:
1794
- throw new UserError(`Unsupported CLI schema kind "${schema.kind}".`);
1795
- }
1796
- throw new UserError(
1797
- `Preset file "${presetPath}" has an invalid value for "${fieldPath}". Expected ${describeExpectedPresetValue(schema)}.`
1798
- );
1799
- }
1800
- function validatePresetFieldValue(value, field, presetPath) {
1801
- if (field.schema.kind !== "array") {
1802
- return validatePresetScalarValue(value, field.schema, field.displayPath, presetPath);
1803
- }
1804
- const itemSchema = unwrapOptional(field.schema.item);
1805
- if (itemSchema.kind === "array" || itemSchema.kind === "object") {
1806
- throw new UserError(`Array parameter "${field.displayPath}" must use scalar items.`);
1807
- }
1808
- if (!Array.isArray(value)) {
1809
- throw new UserError(
1810
- `Preset file "${presetPath}" has an invalid value for "${field.displayPath}". Expected an array.`
1811
- );
1812
- }
1813
- return value.map(
1814
- (item) => validatePresetScalarValue(item, itemSchema, field.displayPath, presetPath)
1815
- );
1816
- }
1817
- async function loadPresetValues(fields, presetPath) {
1818
- let rawPreset;
1819
- try {
1820
- rawPreset = await readFile(presetPath, {
1821
- encoding: "utf8"
1822
- });
1823
- } catch (error2) {
1824
- if (typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === "ENOENT") {
1825
- throw new UserError(`Preset file "${presetPath}" was not found.`);
1826
- }
1827
- const message2 = error2 instanceof Error && error2.message.length > 0 ? error2.message : "Unknown read error.";
1828
- throw new UserError(`Preset file "${presetPath}" could not be read: ${message2}`);
1829
- }
1830
- let parsedPreset;
1831
- try {
1832
- parsedPreset = JSON.parse(rawPreset);
1833
- } catch {
1834
- throw new UserError(`Preset file "${presetPath}" is not valid JSON.`);
1835
- }
1836
- if (!isPlainObject(parsedPreset)) {
1837
- throw new UserError(`Preset file "${presetPath}" must contain a JSON object.`);
1838
- }
1839
- const fieldByPath = new Map(fields.map((field) => [field.displayPath, field]));
1840
- const presetValues = {};
1841
- function visitObject(current, path2) {
1842
- for (const [key, value] of Object.entries(current)) {
1843
- const nextPath = [...path2, key];
1844
- const displayPath = toDisplayPath(nextPath);
1845
- const field = fieldByPath.get(displayPath);
1846
- if (field !== void 0) {
1847
- presetValues[field.optionAttribute] = validatePresetFieldValue(value, field, presetPath);
1848
- continue;
1849
- }
1850
- if (!hasNestedField(fields, nextPath)) {
1851
- throw new UserError(
1852
- `Preset file "${presetPath}" contains unknown parameter "${displayPath}".`
1853
- );
1854
- }
1855
- if (!isPlainObject(value)) {
1856
- throw new UserError(
1857
- `Preset file "${presetPath}" has an invalid value for "${displayPath}". Expected an object.`
1858
- );
1859
- }
1860
- visitObject(value, nextPath);
1861
- }
1862
- }
1863
- visitObject(parsedPreset, []);
1864
- return presetValues;
1865
- }
1866
- function isNumericFixtureSelector(value) {
1867
- if (value.length === 0) {
1868
- return false;
1869
- }
1870
- for (const char of value) {
1871
- if (char < "0" || char > "9") {
1872
- return false;
1873
- }
1874
- }
1875
- return true;
1876
- }
1877
- function normalizeHttpMethod(value) {
1878
- return (value ?? "GET").toUpperCase();
1879
- }
1880
- function isReadLikeMethod(name) {
1881
- const normalized = name.toLowerCase();
1882
- return normalized === "get" || normalized === "head" || normalized === "options" || normalized.startsWith("read") || normalized.startsWith("get") || normalized.startsWith("find") || normalized.startsWith("list") || normalized.startsWith("load") || normalized.startsWith("fetch") || normalized.startsWith("query") || normalized.startsWith("exists") || normalized.startsWith("has");
1883
- }
1884
- function isWriteLikeMethod(name) {
1885
- const normalized = name.toLowerCase();
1886
- return normalized === "post" || normalized === "put" || normalized === "patch" || normalized === "delete" || normalized.startsWith("write") || normalized.startsWith("set") || normalized.startsWith("save") || normalized.startsWith("create") || normalized.startsWith("update") || normalized.startsWith("delete") || normalized.startsWith("remove") || normalized.startsWith("insert");
1887
- }
1888
- function matchesFixtureValue(expected, actual) {
1889
- if (typeof expected === "string" && typeof actual === "string" && expected.endsWith("%")) {
1890
- return actual.startsWith(expected.slice(0, -1));
1891
- }
1892
- if (Array.isArray(expected)) {
1893
- if (!Array.isArray(actual) || expected.length !== actual.length) {
1894
- return false;
1895
- }
1896
- return expected.every((item, index) => matchesFixtureValue(item, actual[index]));
1897
- }
1898
- if (isPlainObject(expected)) {
1899
- if (!isPlainObject(actual)) {
1900
- return false;
1901
- }
1902
- return Object.entries(expected).every(([key, value]) => matchesFixtureValue(value, actual[key]));
1903
- }
1904
- return Object.is(expected, actual);
1905
- }
1906
- function getFetchUrl(input) {
1907
- if (typeof input === "string") {
1908
- return input;
1909
- }
1910
- if (input instanceof URL) {
1911
- return input.toString();
1912
- }
1913
- return input.url;
1914
- }
1915
- function createFixtureResponse(response) {
1916
- const status = response.status ?? 200;
1917
- const headers = new Headers(response.headers);
1918
- if (response.body === void 0) {
1919
- return new Response(null, {
1920
- status,
1921
- headers
1922
- });
1923
- }
1924
- if (typeof response.body === "string") {
1925
- return new Response(response.body, {
1926
- status,
1927
- headers
1928
- });
1929
- }
1930
- if (!headers.has("content-type")) {
1931
- headers.set("content-type", "application/json");
1932
- }
1933
- return new Response(JSON.stringify(response.body), {
1934
- status,
1935
- headers
1936
- });
1937
- }
1938
- function createFixtureFetch(entries) {
1939
- return async (input, init) => {
1940
- const method = normalizeHttpMethod(init?.method ?? (input instanceof Request ? input.method : void 0));
1941
- const url = getFetchUrl(input);
1942
- const match = entries?.find((entry) => {
1943
- const requestMethod = normalizeHttpMethod(entry.request.method);
1944
- return requestMethod === method && entry.request.url === url;
1945
- });
1946
- if (match !== void 0) {
1947
- return createFixtureResponse(match.response);
1948
- }
1949
- if (isReadLikeMethod(method)) {
1950
- return null;
1951
- }
1952
- return new Response(null, {
1953
- status: 204
1954
- });
1955
- };
1956
- }
1957
- function createFixtureFs(definition) {
1958
- const fsDefinition = isPlainObject(definition) ? definition : {};
1959
- const readFileEntries = isPlainObject(fsDefinition.readFile) ? fsDefinition.readFile : {};
1960
- const existsEntries = isPlainObject(fsDefinition.exists) ? fsDefinition.exists : {};
1961
- return {
1962
- readFile: async (filePath) => {
1963
- if (Object.prototype.hasOwnProperty.call(readFileEntries, filePath)) {
1964
- return String(readFileEntries[filePath]);
1965
- }
1966
- return null;
1967
- },
1968
- writeFile: async () => void 0,
1969
- exists: async (filePath) => {
1970
- if (Object.prototype.hasOwnProperty.call(existsEntries, filePath)) {
1971
- return Boolean(existsEntries[filePath]);
1972
- }
1973
- return Object.prototype.hasOwnProperty.call(readFileEntries, filePath);
1974
- }
1975
- };
1976
- }
1977
- function resolveFixtureMethodResult(methodName, definition, args) {
1978
- if (Array.isArray(definition)) {
1979
- for (const entry of definition) {
1980
- if (!isPlainObject(entry)) {
1981
- continue;
1982
- }
1983
- const explicitMatcher = isPlainObject(entry.request) ? entry.request : void 0;
1984
- const matcher = explicitMatcher ?? Object.fromEntries(
1985
- Object.entries(entry).filter(([key]) => key !== "result" && key !== "response" && key !== "error")
1986
- );
1987
- const firstArg = args[0];
1988
- let matched = false;
1989
- if (Array.isArray(matcher.args)) {
1990
- matched = matchesFixtureValue(matcher.args, args);
1991
- } else if (Object.keys(matcher).length === 0) {
1992
- matched = true;
1993
- } else if (isPlainObject(firstArg)) {
1994
- matched = matchesFixtureValue(matcher, firstArg);
1995
- } else if (args.length === 1 && Object.keys(matcher).length === 1) {
1996
- const [[, expectedValue]] = Object.entries(matcher);
1997
- matched = matchesFixtureValue(expectedValue, firstArg);
1998
- }
1999
- if (!matched) {
2000
- continue;
2001
- }
2002
- if (entry.error !== void 0) {
2003
- throw new Error(String(entry.error));
2004
- }
2005
- if (Object.prototype.hasOwnProperty.call(entry, "result")) {
2006
- return Promise.resolve(entry.result);
2007
- }
2008
- if (Object.prototype.hasOwnProperty.call(entry, "response")) {
2009
- return Promise.resolve(entry.response);
2010
- }
2011
- return Promise.resolve(null);
2012
- }
2013
- }
2014
- if (isPlainObject(definition)) {
2015
- const firstArg = args[0];
2016
- if (typeof firstArg === "string" && Object.prototype.hasOwnProperty.call(definition, firstArg)) {
2017
- return Promise.resolve(definition[firstArg]);
2018
- }
2019
- }
2020
- if (isWriteLikeMethod(methodName)) {
2021
- return Promise.resolve(void 0);
2022
- }
2023
- return Promise.resolve(null);
2024
- }
2025
- function createFixtureService(definition) {
2026
- const methods = isPlainObject(definition) ? definition : {};
2027
- return new Proxy(
2028
- {},
2029
- {
2030
- get(_target, property) {
2031
- if (property === "then") {
2032
- return void 0;
2033
- }
2034
- const methodName = String(property);
2035
- return async (...args) => resolveFixtureMethodResult(methodName, methods[methodName], args);
2036
- }
2037
- }
2038
- );
2039
- }
2040
- function resolveFixturePath(commandPath) {
2041
- const parsed = path.parse(commandPath);
2042
- return path.join(parsed.dir, `${parsed.name}.fixture.json`);
2043
- }
2044
- function selectFixtureScenario(scenarios, selector) {
2045
- if (isNumericFixtureSelector(selector)) {
2046
- const index = Number(selector) - 1;
2047
- const scenario2 = scenarios[index];
2048
- if (scenario2 === void 0) {
2049
- throw new UserError(
2050
- `Fixture scenario index ${selector} is out of range. Available scenarios: ${scenarios.length}.`
2051
- );
2052
- }
2053
- return scenario2;
2054
- }
2055
- const scenario = scenarios.find((entry) => entry.name === selector);
2056
- if (scenario === void 0) {
2057
- throw new UserError(`Fixture scenario "${selector}" was not found.`);
2058
- }
2059
- return scenario;
2060
- }
2061
- async function loadFixtureScenario(command, selector) {
2062
- const commandPath = getCommandSourcePath(command);
2063
- if (commandPath === void 0) {
2064
- throw new UserError(`Fixture mode could not determine the source file for command "${command.name}".`);
2065
- }
2066
- const fixturePath = resolveFixturePath(commandPath);
2067
- let rawFixture;
2068
- try {
2069
- rawFixture = await readFile(fixturePath, {
2070
- encoding: "utf8"
2071
- });
2072
- } catch {
2073
- throw new UserError(
2074
- `Fixture file not found for command "${command.name}". Expected ${fixturePath}.`
2075
- );
2076
- }
2077
- let parsed;
2078
- try {
2079
- parsed = JSON.parse(rawFixture);
2080
- } catch {
2081
- throw new UserError(`Fixture file ${fixturePath} is not valid JSON.`);
2082
- }
2083
- if (!Array.isArray(parsed)) {
2084
- throw new UserError(`Fixture file ${fixturePath} must contain a JSON array of scenarios.`);
2085
- }
2086
- return selectFixtureScenario(parsed, selector);
2087
- }
2088
- function resolveFixtureSecrets(command) {
2089
- return Object.fromEntries(Object.keys(command.secrets).map((name) => [name, "fixture-secret"]));
2090
- }
2091
- function createFixtureEnvValues(command) {
2092
- const values = {
2093
- ...process.env,
2094
- POE_API_KEY: process.env.POE_API_KEY ?? "fixture-secret"
2095
- };
2096
- for (const secret of Object.values(command.secrets)) {
2097
- values[secret.env] = values[secret.env] ?? "fixture-secret";
2098
- }
2099
- return values;
2100
- }
2101
- async function resolveFixtureRuntime(command, services, requirementOptions) {
2102
- const selector = process.env.CMDKIT_FIXTURE;
2103
- if (selector === void 0 || selector.length === 0) {
2104
- return {
2105
- env: createEnv(),
2106
- fetch: globalThis.fetch,
2107
- fs: createFs(),
2108
- isFixture: false,
2109
- requirementOptions,
2110
- secrets: resolveCommandSecrets(command),
2111
- services
2112
- };
2113
- }
2114
- const scenario = await loadFixtureScenario(command, selector);
2115
- const scenarioServices = isPlainObject(scenario.services) ? scenario.services : {};
2116
- const customServiceNames = /* @__PURE__ */ new Set([
2117
- ...Object.keys(services),
2118
- ...Object.keys(scenarioServices).filter((name) => !RESERVED_SERVICE_NAMES.has(name))
2119
- ]);
2120
- const fixtureServices = Object.fromEntries(
2121
- [...customServiceNames].map((name) => [name, createFixtureService(scenarioServices[name])])
2122
- );
2123
- const fixtureEnvValues = createFixtureEnvValues(command);
2124
- return {
2125
- env: createEnv(fixtureEnvValues),
2126
- fetch: createFixtureFetch(scenarioServices.fetch),
2127
- fs: createFixtureFs(scenarioServices.fs),
2128
- isFixture: true,
2129
- requirementOptions: {
2130
- ...requirementOptions,
2131
- env: fixtureEnvValues
2132
- },
2133
- secrets: resolveFixtureSecrets(command),
2134
- services: fixtureServices
2135
- };
2136
- }
2137
- function writeRichHeader(title) {
2138
- const padding = Math.max(12, 34 - title.length);
2139
- process.stdout.write(`\u2500\u2500 ${title} ${"\u2500".repeat(padding)}
2140
- `);
2141
- }
2142
- function validateServices(services) {
2143
- for (const name of Object.keys(services)) {
2144
- if (RESERVED_SERVICE_NAMES.has(name)) {
2145
- throw new Error(`Service name "${name}" is reserved. Choose a different name.`);
2146
- }
2147
- }
2148
- }
2149
- async function resolveParams(fields, positionalValues, optionValues, presetPath, shouldPrompt) {
2150
- const params = {};
2151
- const presetValues = typeof presetPath === "string" && presetPath.length > 0 ? await loadPresetValues(fields, presetPath) : {};
2152
- for (const field of fields) {
2153
- let value;
2154
- if (field.positionalIndex !== void 0) {
2155
- const positionalValue = positionalValues[field.positionalIndex];
2156
- if (field.schema.kind === "array") {
2157
- if (Array.isArray(positionalValue) && positionalValue.length > 0) {
2158
- const itemSchema = unwrapOptional(field.schema.item);
2159
- if (itemSchema.kind === "array" || itemSchema.kind === "object") {
2160
- throw new UserError(`Array parameter "${field.displayPath}" must use scalar items.`);
2161
- }
2162
- value = positionalValue.map(
2163
- (item) => parseScalarValue(String(item), itemSchema, field.displayPath)
2164
- );
2165
- }
2166
- } else if (typeof positionalValue === "string" && positionalValue.length > 0) {
2167
- value = parseScalarValue(positionalValue, field.schema, field.displayPath);
2168
- }
2169
- }
2170
- if (value === void 0 && Object.prototype.hasOwnProperty.call(optionValues, field.commanderOptionAttribute) && hasFieldValue(optionValues[field.commanderOptionAttribute])) {
2171
- value = optionValues[field.commanderOptionAttribute];
2172
- }
2173
- if (value === void 0 && field.commanderOptionAttribute === field.optionAttribute && Object.prototype.hasOwnProperty.call(optionValues, field.optionAttribute) && hasFieldValue(optionValues[field.optionAttribute])) {
2174
- value = optionValues[field.optionAttribute];
2175
- }
2176
- if (value === void 0 && Object.prototype.hasOwnProperty.call(presetValues, field.optionAttribute)) {
2177
- value = presetValues[field.optionAttribute];
2178
- }
2179
- if (value === void 0 && shouldPrompt && !field.optional) {
2180
- value = await promptForField(field);
2181
- }
2182
- if (value === void 0 && field.hasDefault) {
2183
- value = field.defaultValue;
2184
- }
2185
- if (value === void 0) {
2186
- if (field.optional) {
2187
- continue;
2188
- }
2189
- throw new UserError(`Missing required parameter "${field.displayPath}".`);
2190
- }
2191
- setNestedValue(params, field.path, value);
2192
- }
2193
- return params;
2194
- }
2195
- function getResolvedFlags(command) {
2196
- const flags = command.optsWithGlobals();
2197
- return flags;
2198
- }
2199
- async function executeCommand(state, services, requirementOptions) {
2200
- const logger2 = createLogger();
2201
- const primitives = {
2202
- logger: logger2,
2203
- renderTable,
2204
- getTheme,
2205
- note
2206
- };
2207
- const optionValues = state.actionCommand.optsWithGlobals();
2208
- const resolvedFlags = optionValues;
2209
- const output = resolveOutput(resolvedFlags);
2210
- const shouldPrompt = !resolvedFlags.yes && Boolean(process.stdin.isTTY);
2211
- const runtime = await resolveFixtureRuntime(state.command, services, requirementOptions);
2212
- const preflightContext = {
2213
- ...runtime.services,
2214
- secrets: runtime.secrets,
2215
- fetch: runtime.fetch,
2216
- fs: runtime.fs,
2217
- env: runtime.env,
2218
- progress(message2) {
2219
- logger2.info(message2);
2220
- }
2221
- };
2222
- await withOutputFormat2(output, async () => {
2223
- await assertCommandRequirements(state.command, preflightContext, runtime.requirementOptions);
2224
- const params = await resolveParams(
2225
- state.fields,
2226
- state.positionalValues,
2227
- optionValues,
2228
- resolvedFlags.preset,
2229
- shouldPrompt
2230
- );
2231
- const context = {
2232
- ...preflightContext,
2233
- params
2234
- };
2235
- if (state.command.confirm && !resolvedFlags.yes && process.stdin.isTTY) {
2236
- for (const field of state.fields) {
2237
- const value = field.path.reduce(
2238
- (current, segment) => current && typeof current === "object" ? current[segment] : void 0,
2239
- params
2240
- );
2241
- if (value !== void 0) {
2242
- logger2.resolved(field.displayPath, formatResolvedValue(value));
2243
- }
2244
- }
2245
- const proceed = await confirm2({
2246
- message: "Proceed?",
2247
- initialValue: true
2248
- });
2249
- if (Ct(proceed)) {
2250
- cancel("Operation cancelled.");
2251
- throw new UserError("Operation cancelled.");
2252
- }
2253
- if (proceed !== true) {
2254
- throw new UserError("Operation cancelled.");
2255
- }
2256
- }
2257
- const result = await state.command.handler(context);
2258
- if (output === "rich" && runtime.isFixture) {
2259
- writeRichHeader(`${state.command.name} (fixture)`);
2260
- }
2261
- renderResult(state.command, result, output, primitives);
2262
- });
2263
- }
2264
- function handleRunError(error2, verbose) {
2265
- const logger2 = createLogger();
2266
- if (error2 instanceof UserError) {
2267
- logger2.error(error2.message);
2268
- process.exitCode = 1;
2269
- return;
2270
- }
2271
- if (error2 instanceof CommanderError) {
2272
- process.exitCode = error2.exitCode;
2273
- if (error2.code === "commander.helpDisplayed" || error2.code === "commander.version") {
2274
- return;
2275
- }
2276
- return;
2277
- }
2278
- const message2 = error2 instanceof Error ? error2.message : String(error2);
2279
- logger2.error(verbose ? message2 : `${message2} Use --verbose for a stack trace.`);
2280
- if (verbose && error2 instanceof Error && error2.stack) {
2281
- process.stderr.write(`${error2.stack}
2282
- `);
2283
- }
2284
- process.exitCode = 1;
2285
- }
2286
- async function runCLI(roots, options = {}) {
2287
- const root = normalizeRoots(roots, process.argv);
2288
- const casing = options.casing ?? "kebab";
2289
- const services = options.services ?? {};
2290
- const requirementOptions = {
2291
- apiVersion: options.apiVersion
2292
- };
2293
- validateServices(services);
2294
- if (hasHelpFlag(process.argv)) {
2295
- await renderGeneratedHelp(root, process.argv, options);
2296
- return;
2297
- }
2298
- const program = new CommanderCommand();
2299
- program.name(root.name);
2300
- program.exitOverride();
2301
- program.showHelpAfterError();
2302
- program.addHelpCommand(false);
2303
- addGlobalOptions(program);
2304
- if (options.version !== void 0) {
2305
- program.version(options.version, "--version");
2306
- }
2307
- const execute = async (state) => {
2308
- try {
2309
- await executeCommand(state, services, requirementOptions);
2310
- } catch (error2) {
2311
- handleRunError(error2, Boolean(getResolvedFlags(state.actionCommand).verbose));
2312
- }
2313
- };
2314
- for (const child of root.children) {
2315
- const command = createNodeCommand(child, casing, execute);
2316
- if (command === null) {
2317
- continue;
2318
- }
2319
- const isDefaultChild = root.default !== void 0 && root.default.scope.includes("cli") && (command.name() === root.default.name || command.aliases().includes(root.default.name));
2320
- program.addCommand(command, isDefaultChild ? { isDefault: true } : void 0);
2321
- }
2322
- try {
2323
- await program.parseAsync(process.argv);
2324
- } catch (error2) {
2325
- handleRunError(error2, process.argv.includes("--verbose"));
2326
- }
2327
- }
2328
- export {
2329
- runCLI
2330
- };
2331
- //# sourceMappingURL=cli.js.map