@easysociable/cli 0.1.1 → 0.1.3

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 (116) hide show
  1. package/README.md +29 -18
  2. package/content-engine/fixtures/golden-run-en/draft.md +13 -0
  3. package/content-engine/fixtures/golden-run-en/idea.md +26 -0
  4. package/content-engine/fixtures/golden-run-en/pack-tiktok.json +11 -0
  5. package/content-engine/scripts/contracts.mjs +183 -0
  6. package/content-engine/scripts/export-contracts.mjs +76 -0
  7. package/content-engine/scripts/fixture.test.mjs +24 -0
  8. package/content-engine/scripts/starter.mjs +55 -0
  9. package/content-engine/scripts/validate-export.mjs +42 -0
  10. package/content-engine/scripts/validate-pack.mjs +48 -0
  11. package/content-engine/scripts/validate-run.mjs +100 -0
  12. package/content-engine/scripts/validate.test.mjs +101 -0
  13. package/content-engine/scripts/workbench.mjs +135 -0
  14. package/content-engine/starter/CLAUDE.md +756 -0
  15. package/content-engine/starter/accounts/README.md +9 -0
  16. package/content-engine/starter/accounts/_index.md +31 -0
  17. package/content-engine/starter/accounts/overrides/README.md +3 -0
  18. package/content-engine/starter/discovery/README.md +18 -0
  19. package/content-engine/starter/discovery/_index.md +27 -0
  20. package/content-engine/starter/discovery/_template.md +41 -0
  21. package/content-engine/starter/engine.json +19 -0
  22. package/content-engine/starter/exports/README.md +28 -0
  23. package/content-engine/starter/inbox/README.md +9 -0
  24. package/content-engine/starter/inbox/_index.md +24 -0
  25. package/content-engine/starter/inbox/entries/README.md +3 -0
  26. package/content-engine/starter/platforms/README.md +19 -0
  27. package/content-engine/starter/platforms/ig.md +69 -0
  28. package/content-engine/starter/platforms/instagram.md +5 -0
  29. package/content-engine/starter/platforms/linkedin.md +72 -0
  30. package/content-engine/starter/platforms/threads.md +69 -0
  31. package/content-engine/starter/platforms/tiktok.md +71 -0
  32. package/content-engine/starter/platforms/x.md +78 -0
  33. package/content-engine/starter/platforms/xiaohongshu.md +19 -0
  34. package/content-engine/starter/profiles/_index.md +13 -0
  35. package/content-engine/starter/profiles/default/README.md +11 -0
  36. package/content-engine/starter/profiles/default/audience.md +38 -0
  37. package/content-engine/starter/profiles/default/pillars.md +33 -0
  38. package/content-engine/starter/profiles/default/voice.md +24 -0
  39. package/content-engine/starter/published/_index.md +20 -0
  40. package/content-engine/starter/raw/README.md +4 -0
  41. package/content-engine/starter/raw/_index.md +12 -0
  42. package/content-engine/starter/runs/README.md +22 -0
  43. package/content-engine/starter/runs/_index.md +41 -0
  44. package/content-engine/starter/runs/_template/brief.md +66 -0
  45. package/content-engine/starter/runs/_template/draft.md +11 -0
  46. package/content-engine/starter/runs/_template/editor.md +18 -0
  47. package/content-engine/starter/runs/_template/feedback.md +15 -0
  48. package/content-engine/starter/runs/_template/idea.md +27 -0
  49. package/content-engine/starter/runs/_template/pack.md +47 -0
  50. package/content-engine/starter/runs/_template/packet.md +25 -0
  51. package/content-engine/starter/runs/_template/rubric.md +19 -0
  52. package/content-engine/starter/swipe/_index.md +27 -0
  53. package/content-engine/starter/swipe/_template.md +34 -0
  54. package/content-engine/starter/topics/README.md +25 -0
  55. package/content-engine/starter/topics/WATCHLIST.md +65 -0
  56. package/content-engine/starter/topics/_index.md +44 -0
  57. package/content-engine/starter/topics/_template-item.md +90 -0
  58. package/content-engine/starter/topics/items/README.md +4 -0
  59. package/content-engine/starter/topics/scoring.md +201 -0
  60. package/content-engine/starter/topics/watchlists/README.md +10 -0
  61. package/content-engine/starter/topics/watchlists/_shared.md +14 -0
  62. package/content-engine/starter/topics/watchlists/default.md +6 -0
  63. package/content-engine/starter/wiki/README.md +13 -0
  64. package/content-engine/starter/wiki/atoms/_index.md +23 -0
  65. package/content-engine/starter/wiki/atoms/_template.md +31 -0
  66. package/content-engine/starter/wiki/claims/_index.md +26 -0
  67. package/content-engine/starter/wiki/claims/_template.md +38 -0
  68. package/content-engine/starter/workbench/README.md +17 -0
  69. package/content-engine/workbench/build.py +1074 -0
  70. package/content-engine/workbench/serve.py +53 -0
  71. package/content-engine/workbench/template.html +2119 -0
  72. package/dist/easysociable.js +804 -2903
  73. package/dist/easysociable.js.map +1 -1
  74. package/package.json +19 -13
  75. package/skills/ONBOARDING.md +20 -14
  76. package/skills/easysociable-content/SKILL.md +38 -102
  77. package/skills/easysociable-slideshow/SKILL.md +24 -16
  78. package/skills/easysociable-slideshow/references/VAULT.md +13 -11
  79. package/skills/easysociable-template/SKILL.md +26 -24
  80. package/skills/easysociable-template/references/CATALOG_METADATA.md +2 -2
  81. package/skills/easysociable-template/references/DESIGN_V2_1.md +53 -2
  82. package/skills/easysociable-template/references/GATEWAY.md +7 -2
  83. package/skills/easysociable-template/references/PLATFORM_SPECS.md +11 -3
  84. package/skills/easysociable-template/references/THEME_TOKENS.md +1 -1
  85. package/skills/easysociable-template/references/fixtures/image-reference.design-plan.json +74 -0
  86. package/skills/easysociable-template/references/fixtures/image-reference.visual-qa.json +28 -0
  87. package/skills/easysociable-template/scripts/generate-theme-from-hex.mjs +0 -0
  88. package/skills/easysociable-template/scripts/validate-design-v2.mjs +97 -0
  89. package/skills/easysociable-template/workflows/ASSET_PLAN.md +2 -1
  90. package/skills/easysociable-template/workflows/AUTHORING_FROM_BRIEF.md +4 -4
  91. package/skills/easysociable-template/workflows/AUTHORING_FROM_IMAGE.md +66 -16
  92. package/skills/easysociable-template/workflows/AUTHORING_STUDIO.md +28 -15
  93. package/skills/easysociable-template/workflows/DESIGN_BRIEF.md +4 -3
  94. package/skills/easysociable-template/workflows/MULTI_PLATFORM_FAMILY.md +81 -0
  95. package/skills/easysociable-template/workflows/PUBLISH_FROM_DRAFT.md +1 -1
  96. package/skills/easysociable-template/workflows/VISUAL_QA.md +10 -0
  97. package/skills/easysociable-content/platforms/claude.md +0 -5
  98. package/skills/easysociable-content/platforms/codex.md +0 -5
  99. package/skills/easysociable-content/platforms/hermes.md +0 -5
  100. package/skills/easysociable-content/platforms/openclaw.md +0 -5
  101. package/skills/easysociable-content/references/CLI.md +0 -27
  102. package/skills/easysociable-content/references/MCP.md +0 -20
  103. package/skills/easysociable-content/references/PAGE_PACK.md +0 -6
  104. package/skills/easysociable-content/references/TROUBLESHOOTING.md +0 -11
  105. package/skills/easysociable-content/references/VAULT.md +0 -20
  106. package/skills/easysociable-content/scripts/setup.mjs +0 -156
  107. package/skills/easysociable-content/scripts/setup.test.mjs +0 -71
  108. package/skills/easysociable-content/scripts/starter.mjs +0 -53
  109. package/skills/easysociable-content/workflows/ANALYSIS_AND_COVERAGE.md +0 -8
  110. package/skills/easysociable-content/workflows/CONTENT_EXPORT.md +0 -19
  111. package/skills/easysociable-content/workflows/DEVICE_TASKS.md +0 -5
  112. package/skills/easysociable-content/workflows/EXPERIMENTS.md +0 -6
  113. package/skills/easysociable-content/workflows/MCP_FIRST.md +0 -10
  114. package/skills/easysociable-content/workflows/PUBLICATION.md +0 -5
  115. package/skills/easysociable-content/workflows/TOPIC_DRAFT.md +0 -5
  116. package/skills/easysociable-content/workflows/WORKING_DRAFT.md +0 -10
@@ -4,2783 +4,32 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
- var __esm = (fn, res) => function __init() {
14
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
- };
16
- var __commonJS = (cb, mod) => function __require2() {
17
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
- };
19
- var __export = (target, all) => {
20
- for (var name in all)
21
- __defProp(target, name, { get: all[name], enumerable: true });
22
- };
23
- var __copyProps = (to, from, except, desc) => {
24
- if (from && typeof from === "object" || typeof from === "function") {
25
- for (let key of __getOwnPropNames(from))
26
- if (!__hasOwnProp.call(to, key) && key !== except)
27
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
- }
29
- return to;
30
- };
31
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
- // If the importer is in node compatibility mode or this is not an ESM
33
- // file that has been converted to a CommonJS file using a Babel-
34
- // compatible transform (i.e. "__esModule" has not been set), then set
35
- // "default" to the CommonJS "module.exports" for node compatibility.
36
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
- mod
38
- ));
39
-
40
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/error.js
41
- var require_error = __commonJS({
42
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/error.js"(exports) {
43
- "use strict";
44
- var CommanderError2 = class extends Error {
45
- /**
46
- * Constructs the CommanderError class
47
- * @param {number} exitCode suggested exit code which could be used with process.exit
48
- * @param {string} code an id string representing the error
49
- * @param {string} message human-readable description of the error
50
- * @constructor
51
- */
52
- constructor(exitCode2, code, message) {
53
- super(message);
54
- Error.captureStackTrace(this, this.constructor);
55
- this.name = this.constructor.name;
56
- this.code = code;
57
- this.exitCode = exitCode2;
58
- this.nestedError = void 0;
59
- }
60
- };
61
- var InvalidArgumentError2 = class extends CommanderError2 {
62
- /**
63
- * Constructs the InvalidArgumentError class
64
- * @param {string} [message] explanation of why argument is invalid
65
- * @constructor
66
- */
67
- constructor(message) {
68
- super(1, "commander.invalidArgument", message);
69
- Error.captureStackTrace(this, this.constructor);
70
- this.name = this.constructor.name;
71
- }
72
- };
73
- exports.CommanderError = CommanderError2;
74
- exports.InvalidArgumentError = InvalidArgumentError2;
75
- }
76
- });
77
-
78
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/argument.js
79
- var require_argument = __commonJS({
80
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/argument.js"(exports) {
81
- "use strict";
82
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
83
- var Argument2 = class {
84
- /**
85
- * Initialize a new command argument with the given name and description.
86
- * The default is that the argument is required, and you can explicitly
87
- * indicate this with <> around the name. Put [] around the name for an optional argument.
88
- *
89
- * @param {string} name
90
- * @param {string} [description]
91
- */
92
- constructor(name, description) {
93
- this.description = description || "";
94
- this.variadic = false;
95
- this.parseArg = void 0;
96
- this.defaultValue = void 0;
97
- this.defaultValueDescription = void 0;
98
- this.argChoices = void 0;
99
- switch (name[0]) {
100
- case "<":
101
- this.required = true;
102
- this._name = name.slice(1, -1);
103
- break;
104
- case "[":
105
- this.required = false;
106
- this._name = name.slice(1, -1);
107
- break;
108
- default:
109
- this.required = true;
110
- this._name = name;
111
- break;
112
- }
113
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
114
- this.variadic = true;
115
- this._name = this._name.slice(0, -3);
116
- }
117
- }
118
- /**
119
- * Return argument name.
120
- *
121
- * @return {string}
122
- */
123
- name() {
124
- return this._name;
125
- }
126
- /**
127
- * @api private
128
- */
129
- _concatValue(value, previous) {
130
- if (previous === this.defaultValue || !Array.isArray(previous)) {
131
- return [value];
132
- }
133
- return previous.concat(value);
134
- }
135
- /**
136
- * Set the default value, and optionally supply the description to be displayed in the help.
137
- *
138
- * @param {*} value
139
- * @param {string} [description]
140
- * @return {Argument}
141
- */
142
- default(value, description) {
143
- this.defaultValue = value;
144
- this.defaultValueDescription = description;
145
- return this;
146
- }
147
- /**
148
- * Set the custom handler for processing CLI command arguments into argument values.
149
- *
150
- * @param {Function} [fn]
151
- * @return {Argument}
152
- */
153
- argParser(fn) {
154
- this.parseArg = fn;
155
- return this;
156
- }
157
- /**
158
- * Only allow argument value to be one of choices.
159
- *
160
- * @param {string[]} values
161
- * @return {Argument}
162
- */
163
- choices(values) {
164
- this.argChoices = values.slice();
165
- this.parseArg = (arg, previous) => {
166
- if (!this.argChoices.includes(arg)) {
167
- throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
168
- }
169
- if (this.variadic) {
170
- return this._concatValue(arg, previous);
171
- }
172
- return arg;
173
- };
174
- return this;
175
- }
176
- /**
177
- * Make argument required.
178
- */
179
- argRequired() {
180
- this.required = true;
181
- return this;
182
- }
183
- /**
184
- * Make argument optional.
185
- */
186
- argOptional() {
187
- this.required = false;
188
- return this;
189
- }
190
- };
191
- function humanReadableArgName(arg) {
192
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
193
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
194
- }
195
- exports.Argument = Argument2;
196
- exports.humanReadableArgName = humanReadableArgName;
197
- }
198
- });
199
-
200
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/help.js
201
- var require_help = __commonJS({
202
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/help.js"(exports) {
203
- "use strict";
204
- var { humanReadableArgName } = require_argument();
205
- var Help2 = class {
206
- constructor() {
207
- this.helpWidth = void 0;
208
- this.sortSubcommands = false;
209
- this.sortOptions = false;
210
- this.showGlobalOptions = false;
211
- }
212
- /**
213
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
214
- *
215
- * @param {Command} cmd
216
- * @returns {Command[]}
217
- */
218
- visibleCommands(cmd) {
219
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
220
- if (cmd._hasImplicitHelpCommand()) {
221
- const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
222
- const helpCommand = cmd.createCommand(helpName).helpOption(false);
223
- helpCommand.description(cmd._helpCommandDescription);
224
- if (helpArgs) helpCommand.arguments(helpArgs);
225
- visibleCommands.push(helpCommand);
226
- }
227
- if (this.sortSubcommands) {
228
- visibleCommands.sort((a, b) => {
229
- return a.name().localeCompare(b.name());
230
- });
231
- }
232
- return visibleCommands;
233
- }
234
- /**
235
- * Compare options for sort.
236
- *
237
- * @param {Option} a
238
- * @param {Option} b
239
- * @returns number
240
- */
241
- compareOptions(a, b) {
242
- const getSortKey = (option) => {
243
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
244
- };
245
- return getSortKey(a).localeCompare(getSortKey(b));
246
- }
247
- /**
248
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
249
- *
250
- * @param {Command} cmd
251
- * @returns {Option[]}
252
- */
253
- visibleOptions(cmd) {
254
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
255
- const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
256
- const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
257
- if (showShortHelpFlag || showLongHelpFlag) {
258
- let helpOption;
259
- if (!showShortHelpFlag) {
260
- helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
261
- } else if (!showLongHelpFlag) {
262
- helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
263
- } else {
264
- helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
265
- }
266
- visibleOptions.push(helpOption);
267
- }
268
- if (this.sortOptions) {
269
- visibleOptions.sort(this.compareOptions);
270
- }
271
- return visibleOptions;
272
- }
273
- /**
274
- * Get an array of the visible global options. (Not including help.)
275
- *
276
- * @param {Command} cmd
277
- * @returns {Option[]}
278
- */
279
- visibleGlobalOptions(cmd) {
280
- if (!this.showGlobalOptions) return [];
281
- const globalOptions = [];
282
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
283
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
284
- globalOptions.push(...visibleOptions);
285
- }
286
- if (this.sortOptions) {
287
- globalOptions.sort(this.compareOptions);
288
- }
289
- return globalOptions;
290
- }
291
- /**
292
- * Get an array of the arguments if any have a description.
293
- *
294
- * @param {Command} cmd
295
- * @returns {Argument[]}
296
- */
297
- visibleArguments(cmd) {
298
- if (cmd._argsDescription) {
299
- cmd.registeredArguments.forEach((argument) => {
300
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
301
- });
302
- }
303
- if (cmd.registeredArguments.find((argument) => argument.description)) {
304
- return cmd.registeredArguments;
305
- }
306
- return [];
307
- }
308
- /**
309
- * Get the command term to show in the list of subcommands.
310
- *
311
- * @param {Command} cmd
312
- * @returns {string}
313
- */
314
- subcommandTerm(cmd) {
315
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
316
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
317
- (args ? " " + args : "");
318
- }
319
- /**
320
- * Get the option term to show in the list of options.
321
- *
322
- * @param {Option} option
323
- * @returns {string}
324
- */
325
- optionTerm(option) {
326
- return option.flags;
327
- }
328
- /**
329
- * Get the argument term to show in the list of arguments.
330
- *
331
- * @param {Argument} argument
332
- * @returns {string}
333
- */
334
- argumentTerm(argument) {
335
- return argument.name();
336
- }
337
- /**
338
- * Get the longest command term length.
339
- *
340
- * @param {Command} cmd
341
- * @param {Help} helper
342
- * @returns {number}
343
- */
344
- longestSubcommandTermLength(cmd, helper) {
345
- return helper.visibleCommands(cmd).reduce((max, command) => {
346
- return Math.max(max, helper.subcommandTerm(command).length);
347
- }, 0);
348
- }
349
- /**
350
- * Get the longest option term length.
351
- *
352
- * @param {Command} cmd
353
- * @param {Help} helper
354
- * @returns {number}
355
- */
356
- longestOptionTermLength(cmd, helper) {
357
- return helper.visibleOptions(cmd).reduce((max, option) => {
358
- return Math.max(max, helper.optionTerm(option).length);
359
- }, 0);
360
- }
361
- /**
362
- * Get the longest global option term length.
363
- *
364
- * @param {Command} cmd
365
- * @param {Help} helper
366
- * @returns {number}
367
- */
368
- longestGlobalOptionTermLength(cmd, helper) {
369
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
370
- return Math.max(max, helper.optionTerm(option).length);
371
- }, 0);
372
- }
373
- /**
374
- * Get the longest argument term length.
375
- *
376
- * @param {Command} cmd
377
- * @param {Help} helper
378
- * @returns {number}
379
- */
380
- longestArgumentTermLength(cmd, helper) {
381
- return helper.visibleArguments(cmd).reduce((max, argument) => {
382
- return Math.max(max, helper.argumentTerm(argument).length);
383
- }, 0);
384
- }
385
- /**
386
- * Get the command usage to be displayed at the top of the built-in help.
387
- *
388
- * @param {Command} cmd
389
- * @returns {string}
390
- */
391
- commandUsage(cmd) {
392
- let cmdName = cmd._name;
393
- if (cmd._aliases[0]) {
394
- cmdName = cmdName + "|" + cmd._aliases[0];
395
- }
396
- let ancestorCmdNames = "";
397
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
398
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
399
- }
400
- return ancestorCmdNames + cmdName + " " + cmd.usage();
401
- }
402
- /**
403
- * Get the description for the command.
404
- *
405
- * @param {Command} cmd
406
- * @returns {string}
407
- */
408
- commandDescription(cmd) {
409
- return cmd.description();
410
- }
411
- /**
412
- * Get the subcommand summary to show in the list of subcommands.
413
- * (Fallback to description for backwards compatibility.)
414
- *
415
- * @param {Command} cmd
416
- * @returns {string}
417
- */
418
- subcommandDescription(cmd) {
419
- return cmd.summary() || cmd.description();
420
- }
421
- /**
422
- * Get the option description to show in the list of options.
423
- *
424
- * @param {Option} option
425
- * @return {string}
426
- */
427
- optionDescription(option) {
428
- const extraInfo = [];
429
- if (option.argChoices) {
430
- extraInfo.push(
431
- // use stringify to match the display of the default value
432
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
433
- );
434
- }
435
- if (option.defaultValue !== void 0) {
436
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
437
- if (showDefault) {
438
- extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
439
- }
440
- }
441
- if (option.presetArg !== void 0 && option.optional) {
442
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
443
- }
444
- if (option.envVar !== void 0) {
445
- extraInfo.push(`env: ${option.envVar}`);
446
- }
447
- if (extraInfo.length > 0) {
448
- return `${option.description} (${extraInfo.join(", ")})`;
449
- }
450
- return option.description;
451
- }
452
- /**
453
- * Get the argument description to show in the list of arguments.
454
- *
455
- * @param {Argument} argument
456
- * @return {string}
457
- */
458
- argumentDescription(argument) {
459
- const extraInfo = [];
460
- if (argument.argChoices) {
461
- extraInfo.push(
462
- // use stringify to match the display of the default value
463
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
464
- );
465
- }
466
- if (argument.defaultValue !== void 0) {
467
- extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
468
- }
469
- if (extraInfo.length > 0) {
470
- const extraDescripton = `(${extraInfo.join(", ")})`;
471
- if (argument.description) {
472
- return `${argument.description} ${extraDescripton}`;
473
- }
474
- return extraDescripton;
475
- }
476
- return argument.description;
477
- }
478
- /**
479
- * Generate the built-in help text.
480
- *
481
- * @param {Command} cmd
482
- * @param {Help} helper
483
- * @returns {string}
484
- */
485
- formatHelp(cmd, helper) {
486
- const termWidth = helper.padWidth(cmd, helper);
487
- const helpWidth = helper.helpWidth || 80;
488
- const itemIndentWidth = 2;
489
- const itemSeparatorWidth = 2;
490
- function formatItem(term, description) {
491
- if (description) {
492
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
493
- return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
494
- }
495
- return term;
496
- }
497
- function formatList(textArray) {
498
- return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
499
- }
500
- let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
501
- const commandDescription = helper.commandDescription(cmd);
502
- if (commandDescription.length > 0) {
503
- output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
504
- }
505
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
506
- return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
507
- });
508
- if (argumentList.length > 0) {
509
- output = output.concat(["Arguments:", formatList(argumentList), ""]);
510
- }
511
- const optionList = helper.visibleOptions(cmd).map((option) => {
512
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
513
- });
514
- if (optionList.length > 0) {
515
- output = output.concat(["Options:", formatList(optionList), ""]);
516
- }
517
- if (this.showGlobalOptions) {
518
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
519
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
520
- });
521
- if (globalOptionList.length > 0) {
522
- output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
523
- }
524
- }
525
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
526
- return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
527
- });
528
- if (commandList.length > 0) {
529
- output = output.concat(["Commands:", formatList(commandList), ""]);
530
- }
531
- return output.join("\n");
532
- }
533
- /**
534
- * Calculate the pad width from the maximum term length.
535
- *
536
- * @param {Command} cmd
537
- * @param {Help} helper
538
- * @returns {number}
539
- */
540
- padWidth(cmd, helper) {
541
- return Math.max(
542
- helper.longestOptionTermLength(cmd, helper),
543
- helper.longestGlobalOptionTermLength(cmd, helper),
544
- helper.longestSubcommandTermLength(cmd, helper),
545
- helper.longestArgumentTermLength(cmd, helper)
546
- );
547
- }
548
- /**
549
- * Wrap the given string to width characters per line, with lines after the first indented.
550
- * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
551
- *
552
- * @param {string} str
553
- * @param {number} width
554
- * @param {number} indent
555
- * @param {number} [minColumnWidth=40]
556
- * @return {string}
557
- *
558
- */
559
- wrap(str, width, indent, minColumnWidth = 40) {
560
- const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
561
- const manualIndent = new RegExp(`[\\n][${indents}]+`);
562
- if (str.match(manualIndent)) return str;
563
- const columnWidth = width - indent;
564
- if (columnWidth < minColumnWidth) return str;
565
- const leadingStr = str.slice(0, indent);
566
- const columnText = str.slice(indent).replace("\r\n", "\n");
567
- const indentString = " ".repeat(indent);
568
- const zeroWidthSpace = "\u200B";
569
- const breaks = `\\s${zeroWidthSpace}`;
570
- const regex = new RegExp(`
571
- |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
572
- const lines = columnText.match(regex) || [];
573
- return leadingStr + lines.map((line, i) => {
574
- if (line === "\n") return "";
575
- return (i > 0 ? indentString : "") + line.trimEnd();
576
- }).join("\n");
577
- }
578
- };
579
- exports.Help = Help2;
580
- }
581
- });
582
-
583
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/option.js
584
- var require_option = __commonJS({
585
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/option.js"(exports) {
586
- "use strict";
587
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
588
- var Option2 = class {
589
- /**
590
- * Initialize a new `Option` with the given `flags` and `description`.
591
- *
592
- * @param {string} flags
593
- * @param {string} [description]
594
- */
595
- constructor(flags, description) {
596
- this.flags = flags;
597
- this.description = description || "";
598
- this.required = flags.includes("<");
599
- this.optional = flags.includes("[");
600
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
601
- this.mandatory = false;
602
- const optionFlags = splitOptionFlags(flags);
603
- this.short = optionFlags.shortFlag;
604
- this.long = optionFlags.longFlag;
605
- this.negate = false;
606
- if (this.long) {
607
- this.negate = this.long.startsWith("--no-");
608
- }
609
- this.defaultValue = void 0;
610
- this.defaultValueDescription = void 0;
611
- this.presetArg = void 0;
612
- this.envVar = void 0;
613
- this.parseArg = void 0;
614
- this.hidden = false;
615
- this.argChoices = void 0;
616
- this.conflictsWith = [];
617
- this.implied = void 0;
618
- }
619
- /**
620
- * Set the default value, and optionally supply the description to be displayed in the help.
621
- *
622
- * @param {*} value
623
- * @param {string} [description]
624
- * @return {Option}
625
- */
626
- default(value, description) {
627
- this.defaultValue = value;
628
- this.defaultValueDescription = description;
629
- return this;
630
- }
631
- /**
632
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
633
- * The custom processing (parseArg) is called.
634
- *
635
- * @example
636
- * new Option('--color').default('GREYSCALE').preset('RGB');
637
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
638
- *
639
- * @param {*} arg
640
- * @return {Option}
641
- */
642
- preset(arg) {
643
- this.presetArg = arg;
644
- return this;
645
- }
646
- /**
647
- * Add option name(s) that conflict with this option.
648
- * An error will be displayed if conflicting options are found during parsing.
649
- *
650
- * @example
651
- * new Option('--rgb').conflicts('cmyk');
652
- * new Option('--js').conflicts(['ts', 'jsx']);
653
- *
654
- * @param {string | string[]} names
655
- * @return {Option}
656
- */
657
- conflicts(names) {
658
- this.conflictsWith = this.conflictsWith.concat(names);
659
- return this;
660
- }
661
- /**
662
- * Specify implied option values for when this option is set and the implied options are not.
663
- *
664
- * The custom processing (parseArg) is not called on the implied values.
665
- *
666
- * @example
667
- * program
668
- * .addOption(new Option('--log', 'write logging information to file'))
669
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
670
- *
671
- * @param {Object} impliedOptionValues
672
- * @return {Option}
673
- */
674
- implies(impliedOptionValues) {
675
- let newImplied = impliedOptionValues;
676
- if (typeof impliedOptionValues === "string") {
677
- newImplied = { [impliedOptionValues]: true };
678
- }
679
- this.implied = Object.assign(this.implied || {}, newImplied);
680
- return this;
681
- }
682
- /**
683
- * Set environment variable to check for option value.
684
- *
685
- * An environment variable is only used if when processed the current option value is
686
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
687
- *
688
- * @param {string} name
689
- * @return {Option}
690
- */
691
- env(name) {
692
- this.envVar = name;
693
- return this;
694
- }
695
- /**
696
- * Set the custom handler for processing CLI option arguments into option values.
697
- *
698
- * @param {Function} [fn]
699
- * @return {Option}
700
- */
701
- argParser(fn) {
702
- this.parseArg = fn;
703
- return this;
704
- }
705
- /**
706
- * Whether the option is mandatory and must have a value after parsing.
707
- *
708
- * @param {boolean} [mandatory=true]
709
- * @return {Option}
710
- */
711
- makeOptionMandatory(mandatory = true) {
712
- this.mandatory = !!mandatory;
713
- return this;
714
- }
715
- /**
716
- * Hide option in help.
717
- *
718
- * @param {boolean} [hide=true]
719
- * @return {Option}
720
- */
721
- hideHelp(hide = true) {
722
- this.hidden = !!hide;
723
- return this;
724
- }
725
- /**
726
- * @api private
727
- */
728
- _concatValue(value, previous) {
729
- if (previous === this.defaultValue || !Array.isArray(previous)) {
730
- return [value];
731
- }
732
- return previous.concat(value);
733
- }
734
- /**
735
- * Only allow option value to be one of choices.
736
- *
737
- * @param {string[]} values
738
- * @return {Option}
739
- */
740
- choices(values) {
741
- this.argChoices = values.slice();
742
- this.parseArg = (arg, previous) => {
743
- if (!this.argChoices.includes(arg)) {
744
- throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
745
- }
746
- if (this.variadic) {
747
- return this._concatValue(arg, previous);
748
- }
749
- return arg;
750
- };
751
- return this;
752
- }
753
- /**
754
- * Return option name.
755
- *
756
- * @return {string}
757
- */
758
- name() {
759
- if (this.long) {
760
- return this.long.replace(/^--/, "");
761
- }
762
- return this.short.replace(/^-/, "");
763
- }
764
- /**
765
- * Return option name, in a camelcase format that can be used
766
- * as a object attribute key.
767
- *
768
- * @return {string}
769
- * @api private
770
- */
771
- attributeName() {
772
- return camelcase(this.name().replace(/^no-/, ""));
773
- }
774
- /**
775
- * Check if `arg` matches the short or long flag.
776
- *
777
- * @param {string} arg
778
- * @return {boolean}
779
- * @api private
780
- */
781
- is(arg) {
782
- return this.short === arg || this.long === arg;
783
- }
784
- /**
785
- * Return whether a boolean option.
786
- *
787
- * Options are one of boolean, negated, required argument, or optional argument.
788
- *
789
- * @return {boolean}
790
- * @api private
791
- */
792
- isBoolean() {
793
- return !this.required && !this.optional && !this.negate;
794
- }
795
- };
796
- var DualOptions = class {
797
- /**
798
- * @param {Option[]} options
799
- */
800
- constructor(options) {
801
- this.positiveOptions = /* @__PURE__ */ new Map();
802
- this.negativeOptions = /* @__PURE__ */ new Map();
803
- this.dualOptions = /* @__PURE__ */ new Set();
804
- options.forEach((option) => {
805
- if (option.negate) {
806
- this.negativeOptions.set(option.attributeName(), option);
807
- } else {
808
- this.positiveOptions.set(option.attributeName(), option);
809
- }
810
- });
811
- this.negativeOptions.forEach((value, key) => {
812
- if (this.positiveOptions.has(key)) {
813
- this.dualOptions.add(key);
814
- }
815
- });
816
- }
817
- /**
818
- * Did the value come from the option, and not from possible matching dual option?
819
- *
820
- * @param {*} value
821
- * @param {Option} option
822
- * @returns {boolean}
823
- */
824
- valueFromOption(value, option) {
825
- const optionKey = option.attributeName();
826
- if (!this.dualOptions.has(optionKey)) return true;
827
- const preset = this.negativeOptions.get(optionKey).presetArg;
828
- const negativeValue = preset !== void 0 ? preset : false;
829
- return option.negate === (negativeValue === value);
830
- }
831
- };
832
- function camelcase(str) {
833
- return str.split("-").reduce((str2, word) => {
834
- return str2 + word[0].toUpperCase() + word.slice(1);
835
- });
836
- }
837
- function splitOptionFlags(flags) {
838
- let shortFlag;
839
- let longFlag;
840
- const flagParts = flags.split(/[ |,]+/);
841
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
842
- longFlag = flagParts.shift();
843
- if (!shortFlag && /^-[^-]$/.test(longFlag)) {
844
- shortFlag = longFlag;
845
- longFlag = void 0;
846
- }
847
- return { shortFlag, longFlag };
848
- }
849
- exports.Option = Option2;
850
- exports.splitOptionFlags = splitOptionFlags;
851
- exports.DualOptions = DualOptions;
852
- }
853
- });
854
-
855
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/suggestSimilar.js
856
- var require_suggestSimilar = __commonJS({
857
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
858
- "use strict";
859
- var maxDistance = 3;
860
- function editDistance(a, b) {
861
- if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
862
- const d = [];
863
- for (let i = 0; i <= a.length; i++) {
864
- d[i] = [i];
865
- }
866
- for (let j = 0; j <= b.length; j++) {
867
- d[0][j] = j;
868
- }
869
- for (let j = 1; j <= b.length; j++) {
870
- for (let i = 1; i <= a.length; i++) {
871
- let cost = 1;
872
- if (a[i - 1] === b[j - 1]) {
873
- cost = 0;
874
- } else {
875
- cost = 1;
876
- }
877
- d[i][j] = Math.min(
878
- d[i - 1][j] + 1,
879
- // deletion
880
- d[i][j - 1] + 1,
881
- // insertion
882
- d[i - 1][j - 1] + cost
883
- // substitution
884
- );
885
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
886
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
887
- }
888
- }
889
- }
890
- return d[a.length][b.length];
891
- }
892
- function suggestSimilar(word, candidates) {
893
- if (!candidates || candidates.length === 0) return "";
894
- candidates = Array.from(new Set(candidates));
895
- const searchingOptions = word.startsWith("--");
896
- if (searchingOptions) {
897
- word = word.slice(2);
898
- candidates = candidates.map((candidate) => candidate.slice(2));
899
- }
900
- let similar = [];
901
- let bestDistance = maxDistance;
902
- const minSimilarity = 0.4;
903
- candidates.forEach((candidate) => {
904
- if (candidate.length <= 1) return;
905
- const distance = editDistance(word, candidate);
906
- const length = Math.max(word.length, candidate.length);
907
- const similarity = (length - distance) / length;
908
- if (similarity > minSimilarity) {
909
- if (distance < bestDistance) {
910
- bestDistance = distance;
911
- similar = [candidate];
912
- } else if (distance === bestDistance) {
913
- similar.push(candidate);
914
- }
915
- }
916
- });
917
- similar.sort((a, b) => a.localeCompare(b));
918
- if (searchingOptions) {
919
- similar = similar.map((candidate) => `--${candidate}`);
920
- }
921
- if (similar.length > 1) {
922
- return `
923
- (Did you mean one of ${similar.join(", ")}?)`;
924
- }
925
- if (similar.length === 1) {
926
- return `
927
- (Did you mean ${similar[0]}?)`;
928
- }
929
- return "";
930
- }
931
- exports.suggestSimilar = suggestSimilar;
932
- }
933
- });
934
-
935
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/command.js
936
- var require_command = __commonJS({
937
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/command.js"(exports) {
938
- "use strict";
939
- var EventEmitter = __require("events").EventEmitter;
940
- var childProcess = __require("child_process");
941
- var path = __require("path");
942
- var fs = __require("fs");
943
- var process4 = __require("process");
944
- var { Argument: Argument2, humanReadableArgName } = require_argument();
945
- var { CommanderError: CommanderError2 } = require_error();
946
- var { Help: Help2 } = require_help();
947
- var { Option: Option2, splitOptionFlags, DualOptions } = require_option();
948
- var { suggestSimilar } = require_suggestSimilar();
949
- var Command2 = class _Command extends EventEmitter {
950
- /**
951
- * Initialize a new `Command`.
952
- *
953
- * @param {string} [name]
954
- */
955
- constructor(name) {
956
- super();
957
- this.commands = [];
958
- this.options = [];
959
- this.parent = null;
960
- this._allowUnknownOption = false;
961
- this._allowExcessArguments = true;
962
- this.registeredArguments = [];
963
- this._args = this.registeredArguments;
964
- this.args = [];
965
- this.rawArgs = [];
966
- this.processedArgs = [];
967
- this._scriptPath = null;
968
- this._name = name || "";
969
- this._optionValues = {};
970
- this._optionValueSources = {};
971
- this._storeOptionsAsProperties = false;
972
- this._actionHandler = null;
973
- this._executableHandler = false;
974
- this._executableFile = null;
975
- this._executableDir = null;
976
- this._defaultCommandName = null;
977
- this._exitCallback = null;
978
- this._aliases = [];
979
- this._combineFlagAndOptionalValue = true;
980
- this._description = "";
981
- this._summary = "";
982
- this._argsDescription = void 0;
983
- this._enablePositionalOptions = false;
984
- this._passThroughOptions = false;
985
- this._lifeCycleHooks = {};
986
- this._showHelpAfterError = false;
987
- this._showSuggestionAfterError = true;
988
- this._outputConfiguration = {
989
- writeOut: (str) => process4.stdout.write(str),
990
- writeErr: (str) => process4.stderr.write(str),
991
- getOutHelpWidth: () => process4.stdout.isTTY ? process4.stdout.columns : void 0,
992
- getErrHelpWidth: () => process4.stderr.isTTY ? process4.stderr.columns : void 0,
993
- outputError: (str, write) => write(str)
994
- };
995
- this._hidden = false;
996
- this._hasHelpOption = true;
997
- this._helpFlags = "-h, --help";
998
- this._helpDescription = "display help for command";
999
- this._helpShortFlag = "-h";
1000
- this._helpLongFlag = "--help";
1001
- this._addImplicitHelpCommand = void 0;
1002
- this._helpCommandName = "help";
1003
- this._helpCommandnameAndArgs = "help [command]";
1004
- this._helpCommandDescription = "display help for command";
1005
- this._helpConfiguration = {};
1006
- }
1007
- /**
1008
- * Copy settings that are useful to have in common across root command and subcommands.
1009
- *
1010
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1011
- *
1012
- * @param {Command} sourceCommand
1013
- * @return {Command} `this` command for chaining
1014
- */
1015
- copyInheritedSettings(sourceCommand) {
1016
- this._outputConfiguration = sourceCommand._outputConfiguration;
1017
- this._hasHelpOption = sourceCommand._hasHelpOption;
1018
- this._helpFlags = sourceCommand._helpFlags;
1019
- this._helpDescription = sourceCommand._helpDescription;
1020
- this._helpShortFlag = sourceCommand._helpShortFlag;
1021
- this._helpLongFlag = sourceCommand._helpLongFlag;
1022
- this._helpCommandName = sourceCommand._helpCommandName;
1023
- this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
1024
- this._helpCommandDescription = sourceCommand._helpCommandDescription;
1025
- this._helpConfiguration = sourceCommand._helpConfiguration;
1026
- this._exitCallback = sourceCommand._exitCallback;
1027
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1028
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1029
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1030
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1031
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1032
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1033
- return this;
1034
- }
1035
- /**
1036
- * @returns {Command[]}
1037
- * @api private
1038
- */
1039
- _getCommandAndAncestors() {
1040
- const result = [];
1041
- for (let command = this; command; command = command.parent) {
1042
- result.push(command);
1043
- }
1044
- return result;
1045
- }
1046
- /**
1047
- * Define a command.
1048
- *
1049
- * There are two styles of command: pay attention to where to put the description.
1050
- *
1051
- * @example
1052
- * // Command implemented using action handler (description is supplied separately to `.command`)
1053
- * program
1054
- * .command('clone <source> [destination]')
1055
- * .description('clone a repository into a newly created directory')
1056
- * .action((source, destination) => {
1057
- * console.log('clone command called');
1058
- * });
1059
- *
1060
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1061
- * program
1062
- * .command('start <service>', 'start named service')
1063
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1064
- *
1065
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1066
- * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1067
- * @param {Object} [execOpts] - configuration options (for executable)
1068
- * @return {Command} returns new command for action handler, or `this` for executable command
1069
- */
1070
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1071
- let desc = actionOptsOrExecDesc;
1072
- let opts = execOpts;
1073
- if (typeof desc === "object" && desc !== null) {
1074
- opts = desc;
1075
- desc = null;
1076
- }
1077
- opts = opts || {};
1078
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1079
- const cmd = this.createCommand(name);
1080
- if (desc) {
1081
- cmd.description(desc);
1082
- cmd._executableHandler = true;
1083
- }
1084
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1085
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1086
- cmd._executableFile = opts.executableFile || null;
1087
- if (args) cmd.arguments(args);
1088
- this.commands.push(cmd);
1089
- cmd.parent = this;
1090
- cmd.copyInheritedSettings(this);
1091
- if (desc) return this;
1092
- return cmd;
1093
- }
1094
- /**
1095
- * Factory routine to create a new unattached command.
1096
- *
1097
- * See .command() for creating an attached subcommand, which uses this routine to
1098
- * create the command. You can override createCommand to customise subcommands.
1099
- *
1100
- * @param {string} [name]
1101
- * @return {Command} new command
1102
- */
1103
- createCommand(name) {
1104
- return new _Command(name);
1105
- }
1106
- /**
1107
- * You can customise the help with a subclass of Help by overriding createHelp,
1108
- * or by overriding Help properties using configureHelp().
1109
- *
1110
- * @return {Help}
1111
- */
1112
- createHelp() {
1113
- return Object.assign(new Help2(), this.configureHelp());
1114
- }
1115
- /**
1116
- * You can customise the help by overriding Help properties using configureHelp(),
1117
- * or with a subclass of Help by overriding createHelp().
1118
- *
1119
- * @param {Object} [configuration] - configuration options
1120
- * @return {Command|Object} `this` command for chaining, or stored configuration
1121
- */
1122
- configureHelp(configuration) {
1123
- if (configuration === void 0) return this._helpConfiguration;
1124
- this._helpConfiguration = configuration;
1125
- return this;
1126
- }
1127
- /**
1128
- * The default output goes to stdout and stderr. You can customise this for special
1129
- * applications. You can also customise the display of errors by overriding outputError.
1130
- *
1131
- * The configuration properties are all functions:
1132
- *
1133
- * // functions to change where being written, stdout and stderr
1134
- * writeOut(str)
1135
- * writeErr(str)
1136
- * // matching functions to specify width for wrapping help
1137
- * getOutHelpWidth()
1138
- * getErrHelpWidth()
1139
- * // functions based on what is being written out
1140
- * outputError(str, write) // used for displaying errors, and not used for displaying help
1141
- *
1142
- * @param {Object} [configuration] - configuration options
1143
- * @return {Command|Object} `this` command for chaining, or stored configuration
1144
- */
1145
- configureOutput(configuration) {
1146
- if (configuration === void 0) return this._outputConfiguration;
1147
- Object.assign(this._outputConfiguration, configuration);
1148
- return this;
1149
- }
1150
- /**
1151
- * Display the help or a custom message after an error occurs.
1152
- *
1153
- * @param {boolean|string} [displayHelp]
1154
- * @return {Command} `this` command for chaining
1155
- */
1156
- showHelpAfterError(displayHelp = true) {
1157
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1158
- this._showHelpAfterError = displayHelp;
1159
- return this;
1160
- }
1161
- /**
1162
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1163
- *
1164
- * @param {boolean} [displaySuggestion]
1165
- * @return {Command} `this` command for chaining
1166
- */
1167
- showSuggestionAfterError(displaySuggestion = true) {
1168
- this._showSuggestionAfterError = !!displaySuggestion;
1169
- return this;
1170
- }
1171
- /**
1172
- * Add a prepared subcommand.
1173
- *
1174
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1175
- *
1176
- * @param {Command} cmd - new subcommand
1177
- * @param {Object} [opts] - configuration options
1178
- * @return {Command} `this` command for chaining
1179
- */
1180
- addCommand(cmd, opts) {
1181
- if (!cmd._name) {
1182
- throw new Error(`Command passed to .addCommand() must have a name
1183
- - specify the name in Command constructor or using .name()`);
1184
- }
1185
- opts = opts || {};
1186
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1187
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1188
- this.commands.push(cmd);
1189
- cmd.parent = this;
1190
- return this;
1191
- }
1192
- /**
1193
- * Factory routine to create a new unattached argument.
1194
- *
1195
- * See .argument() for creating an attached argument, which uses this routine to
1196
- * create the argument. You can override createArgument to return a custom argument.
1197
- *
1198
- * @param {string} name
1199
- * @param {string} [description]
1200
- * @return {Argument} new argument
1201
- */
1202
- createArgument(name, description) {
1203
- return new Argument2(name, description);
1204
- }
1205
- /**
1206
- * Define argument syntax for command.
1207
- *
1208
- * The default is that the argument is required, and you can explicitly
1209
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1210
- *
1211
- * @example
1212
- * program.argument('<input-file>');
1213
- * program.argument('[output-file]');
1214
- *
1215
- * @param {string} name
1216
- * @param {string} [description]
1217
- * @param {Function|*} [fn] - custom argument processing function
1218
- * @param {*} [defaultValue]
1219
- * @return {Command} `this` command for chaining
1220
- */
1221
- argument(name, description, fn, defaultValue) {
1222
- const argument = this.createArgument(name, description);
1223
- if (typeof fn === "function") {
1224
- argument.default(defaultValue).argParser(fn);
1225
- } else {
1226
- argument.default(fn);
1227
- }
1228
- this.addArgument(argument);
1229
- return this;
1230
- }
1231
- /**
1232
- * Define argument syntax for command, adding multiple at once (without descriptions).
1233
- *
1234
- * See also .argument().
1235
- *
1236
- * @example
1237
- * program.arguments('<cmd> [env]');
1238
- *
1239
- * @param {string} names
1240
- * @return {Command} `this` command for chaining
1241
- */
1242
- arguments(names) {
1243
- names.trim().split(/ +/).forEach((detail) => {
1244
- this.argument(detail);
1245
- });
1246
- return this;
1247
- }
1248
- /**
1249
- * Define argument syntax for command, adding a prepared argument.
1250
- *
1251
- * @param {Argument} argument
1252
- * @return {Command} `this` command for chaining
1253
- */
1254
- addArgument(argument) {
1255
- const previousArgument = this.registeredArguments.slice(-1)[0];
1256
- if (previousArgument && previousArgument.variadic) {
1257
- throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1258
- }
1259
- if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1260
- throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1261
- }
1262
- this.registeredArguments.push(argument);
1263
- return this;
1264
- }
1265
- /**
1266
- * Override default decision whether to add implicit help command.
1267
- *
1268
- * addHelpCommand() // force on
1269
- * addHelpCommand(false); // force off
1270
- * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1271
- *
1272
- * @return {Command} `this` command for chaining
1273
- */
1274
- addHelpCommand(enableOrNameAndArgs, description) {
1275
- if (enableOrNameAndArgs === false) {
1276
- this._addImplicitHelpCommand = false;
1277
- } else {
1278
- this._addImplicitHelpCommand = true;
1279
- if (typeof enableOrNameAndArgs === "string") {
1280
- this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
1281
- this._helpCommandnameAndArgs = enableOrNameAndArgs;
1282
- }
1283
- this._helpCommandDescription = description || this._helpCommandDescription;
1284
- }
1285
- return this;
1286
- }
1287
- /**
1288
- * @return {boolean}
1289
- * @api private
1290
- */
1291
- _hasImplicitHelpCommand() {
1292
- if (this._addImplicitHelpCommand === void 0) {
1293
- return this.commands.length && !this._actionHandler && !this._findCommand("help");
1294
- }
1295
- return this._addImplicitHelpCommand;
1296
- }
1297
- /**
1298
- * Add hook for life cycle event.
1299
- *
1300
- * @param {string} event
1301
- * @param {Function} listener
1302
- * @return {Command} `this` command for chaining
1303
- */
1304
- hook(event, listener) {
1305
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
1306
- if (!allowedValues.includes(event)) {
1307
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1308
- Expecting one of '${allowedValues.join("', '")}'`);
1309
- }
1310
- if (this._lifeCycleHooks[event]) {
1311
- this._lifeCycleHooks[event].push(listener);
1312
- } else {
1313
- this._lifeCycleHooks[event] = [listener];
1314
- }
1315
- return this;
1316
- }
1317
- /**
1318
- * Register callback to use as replacement for calling process.exit.
1319
- *
1320
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1321
- * @return {Command} `this` command for chaining
1322
- */
1323
- exitOverride(fn) {
1324
- if (fn) {
1325
- this._exitCallback = fn;
1326
- } else {
1327
- this._exitCallback = (err) => {
1328
- if (err.code !== "commander.executeSubCommandAsync") {
1329
- throw err;
1330
- } else {
1331
- }
1332
- };
1333
- }
1334
- return this;
1335
- }
1336
- /**
1337
- * Call process.exit, and _exitCallback if defined.
1338
- *
1339
- * @param {number} exitCode exit code for using with process.exit
1340
- * @param {string} code an id string representing the error
1341
- * @param {string} message human-readable description of the error
1342
- * @return never
1343
- * @api private
1344
- */
1345
- _exit(exitCode2, code, message) {
1346
- if (this._exitCallback) {
1347
- this._exitCallback(new CommanderError2(exitCode2, code, message));
1348
- }
1349
- process4.exit(exitCode2);
1350
- }
1351
- /**
1352
- * Register callback `fn` for the command.
1353
- *
1354
- * @example
1355
- * program
1356
- * .command('serve')
1357
- * .description('start service')
1358
- * .action(function() {
1359
- * // do work here
1360
- * });
1361
- *
1362
- * @param {Function} fn
1363
- * @return {Command} `this` command for chaining
1364
- */
1365
- action(fn) {
1366
- const listener = (args) => {
1367
- const expectedArgsCount = this.registeredArguments.length;
1368
- const actionArgs = args.slice(0, expectedArgsCount);
1369
- if (this._storeOptionsAsProperties) {
1370
- actionArgs[expectedArgsCount] = this;
1371
- } else {
1372
- actionArgs[expectedArgsCount] = this.opts();
1373
- }
1374
- actionArgs.push(this);
1375
- return fn.apply(this, actionArgs);
1376
- };
1377
- this._actionHandler = listener;
1378
- return this;
1379
- }
1380
- /**
1381
- * Factory routine to create a new unattached option.
1382
- *
1383
- * See .option() for creating an attached option, which uses this routine to
1384
- * create the option. You can override createOption to return a custom option.
1385
- *
1386
- * @param {string} flags
1387
- * @param {string} [description]
1388
- * @return {Option} new option
1389
- */
1390
- createOption(flags, description) {
1391
- return new Option2(flags, description);
1392
- }
1393
- /**
1394
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1395
- *
1396
- * @param {Option | Argument} target
1397
- * @param {string} value
1398
- * @param {*} previous
1399
- * @param {string} invalidArgumentMessage
1400
- * @api private
1401
- */
1402
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1403
- try {
1404
- return target.parseArg(value, previous);
1405
- } catch (err) {
1406
- if (err.code === "commander.invalidArgument") {
1407
- const message = `${invalidArgumentMessage} ${err.message}`;
1408
- this.error(message, { exitCode: err.exitCode, code: err.code });
1409
- }
1410
- throw err;
1411
- }
1412
- }
1413
- /**
1414
- * Add an option.
1415
- *
1416
- * @param {Option} option
1417
- * @return {Command} `this` command for chaining
1418
- */
1419
- addOption(option) {
1420
- const oname = option.name();
1421
- const name = option.attributeName();
1422
- if (option.negate) {
1423
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1424
- if (!this._findOption(positiveLongFlag)) {
1425
- this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1426
- }
1427
- } else if (option.defaultValue !== void 0) {
1428
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1429
- }
1430
- this.options.push(option);
1431
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1432
- if (val == null && option.presetArg !== void 0) {
1433
- val = option.presetArg;
1434
- }
1435
- const oldValue = this.getOptionValue(name);
1436
- if (val !== null && option.parseArg) {
1437
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1438
- } else if (val !== null && option.variadic) {
1439
- val = option._concatValue(val, oldValue);
1440
- }
1441
- if (val == null) {
1442
- if (option.negate) {
1443
- val = false;
1444
- } else if (option.isBoolean() || option.optional) {
1445
- val = true;
1446
- } else {
1447
- val = "";
1448
- }
1449
- }
1450
- this.setOptionValueWithSource(name, val, valueSource);
1451
- };
1452
- this.on("option:" + oname, (val) => {
1453
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1454
- handleOptionValue(val, invalidValueMessage, "cli");
1455
- });
1456
- if (option.envVar) {
1457
- this.on("optionEnv:" + oname, (val) => {
1458
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1459
- handleOptionValue(val, invalidValueMessage, "env");
1460
- });
1461
- }
1462
- return this;
1463
- }
1464
- /**
1465
- * Internal implementation shared by .option() and .requiredOption()
1466
- *
1467
- * @api private
1468
- */
1469
- _optionEx(config3, flags, description, fn, defaultValue) {
1470
- if (typeof flags === "object" && flags instanceof Option2) {
1471
- throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1472
- }
1473
- const option = this.createOption(flags, description);
1474
- option.makeOptionMandatory(!!config3.mandatory);
1475
- if (typeof fn === "function") {
1476
- option.default(defaultValue).argParser(fn);
1477
- } else if (fn instanceof RegExp) {
1478
- const regex = fn;
1479
- fn = (val, def) => {
1480
- const m = regex.exec(val);
1481
- return m ? m[0] : def;
1482
- };
1483
- option.default(defaultValue).argParser(fn);
1484
- } else {
1485
- option.default(fn);
1486
- }
1487
- return this.addOption(option);
1488
- }
1489
- /**
1490
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1491
- *
1492
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1493
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1494
- *
1495
- * See the README for more details, and see also addOption() and requiredOption().
1496
- *
1497
- * @example
1498
- * program
1499
- * .option('-p, --pepper', 'add pepper')
1500
- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1501
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1502
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1503
- *
1504
- * @param {string} flags
1505
- * @param {string} [description]
1506
- * @param {Function|*} [parseArg] - custom option processing function or default value
1507
- * @param {*} [defaultValue]
1508
- * @return {Command} `this` command for chaining
1509
- */
1510
- option(flags, description, parseArg, defaultValue) {
1511
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1512
- }
1513
- /**
1514
- * Add a required option which must have a value after parsing. This usually means
1515
- * the option must be specified on the command line. (Otherwise the same as .option().)
1516
- *
1517
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1518
- *
1519
- * @param {string} flags
1520
- * @param {string} [description]
1521
- * @param {Function|*} [parseArg] - custom option processing function or default value
1522
- * @param {*} [defaultValue]
1523
- * @return {Command} `this` command for chaining
1524
- */
1525
- requiredOption(flags, description, parseArg, defaultValue) {
1526
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1527
- }
1528
- /**
1529
- * Alter parsing of short flags with optional values.
1530
- *
1531
- * @example
1532
- * // for `.option('-f,--flag [value]'):
1533
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1534
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1535
- *
1536
- * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1537
- */
1538
- combineFlagAndOptionalValue(combine = true) {
1539
- this._combineFlagAndOptionalValue = !!combine;
1540
- return this;
1541
- }
1542
- /**
1543
- * Allow unknown options on the command line.
1544
- *
1545
- * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1546
- * for unknown options.
1547
- */
1548
- allowUnknownOption(allowUnknown = true) {
1549
- this._allowUnknownOption = !!allowUnknown;
1550
- return this;
1551
- }
1552
- /**
1553
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1554
- *
1555
- * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1556
- * for excess arguments.
1557
- */
1558
- allowExcessArguments(allowExcess = true) {
1559
- this._allowExcessArguments = !!allowExcess;
1560
- return this;
1561
- }
1562
- /**
1563
- * Enable positional options. Positional means global options are specified before subcommands which lets
1564
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1565
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1566
- *
1567
- * @param {Boolean} [positional=true]
1568
- */
1569
- enablePositionalOptions(positional = true) {
1570
- this._enablePositionalOptions = !!positional;
1571
- return this;
1572
- }
1573
- /**
1574
- * Pass through options that come after command-arguments rather than treat them as command-options,
1575
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1576
- * positional options to have been enabled on the program (parent commands).
1577
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1578
- *
1579
- * @param {Boolean} [passThrough=true]
1580
- * for unknown options.
1581
- */
1582
- passThroughOptions(passThrough = true) {
1583
- this._passThroughOptions = !!passThrough;
1584
- if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1585
- throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
1586
- }
1587
- return this;
1588
- }
1589
- /**
1590
- * Whether to store option values as properties on command object,
1591
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1592
- *
1593
- * @param {boolean} [storeAsProperties=true]
1594
- * @return {Command} `this` command for chaining
1595
- */
1596
- storeOptionsAsProperties(storeAsProperties = true) {
1597
- if (this.options.length) {
1598
- throw new Error("call .storeOptionsAsProperties() before adding options");
1599
- }
1600
- this._storeOptionsAsProperties = !!storeAsProperties;
1601
- return this;
1602
- }
1603
- /**
1604
- * Retrieve option value.
1605
- *
1606
- * @param {string} key
1607
- * @return {Object} value
1608
- */
1609
- getOptionValue(key) {
1610
- if (this._storeOptionsAsProperties) {
1611
- return this[key];
1612
- }
1613
- return this._optionValues[key];
1614
- }
1615
- /**
1616
- * Store option value.
1617
- *
1618
- * @param {string} key
1619
- * @param {Object} value
1620
- * @return {Command} `this` command for chaining
1621
- */
1622
- setOptionValue(key, value) {
1623
- return this.setOptionValueWithSource(key, value, void 0);
1624
- }
1625
- /**
1626
- * Store option value and where the value came from.
1627
- *
1628
- * @param {string} key
1629
- * @param {Object} value
1630
- * @param {string} source - expected values are default/config/env/cli/implied
1631
- * @return {Command} `this` command for chaining
1632
- */
1633
- setOptionValueWithSource(key, value, source) {
1634
- if (this._storeOptionsAsProperties) {
1635
- this[key] = value;
1636
- } else {
1637
- this._optionValues[key] = value;
1638
- }
1639
- this._optionValueSources[key] = source;
1640
- return this;
1641
- }
1642
- /**
1643
- * Get source of option value.
1644
- * Expected values are default | config | env | cli | implied
1645
- *
1646
- * @param {string} key
1647
- * @return {string}
1648
- */
1649
- getOptionValueSource(key) {
1650
- return this._optionValueSources[key];
1651
- }
1652
- /**
1653
- * Get source of option value. See also .optsWithGlobals().
1654
- * Expected values are default | config | env | cli | implied
1655
- *
1656
- * @param {string} key
1657
- * @return {string}
1658
- */
1659
- getOptionValueSourceWithGlobals(key) {
1660
- let source;
1661
- this._getCommandAndAncestors().forEach((cmd) => {
1662
- if (cmd.getOptionValueSource(key) !== void 0) {
1663
- source = cmd.getOptionValueSource(key);
1664
- }
1665
- });
1666
- return source;
1667
- }
1668
- /**
1669
- * Get user arguments from implied or explicit arguments.
1670
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1671
- *
1672
- * @api private
1673
- */
1674
- _prepareUserArgs(argv, parseOptions) {
1675
- if (argv !== void 0 && !Array.isArray(argv)) {
1676
- throw new Error("first parameter to parse must be array or undefined");
1677
- }
1678
- parseOptions = parseOptions || {};
1679
- if (argv === void 0) {
1680
- argv = process4.argv;
1681
- if (process4.versions && process4.versions.electron) {
1682
- parseOptions.from = "electron";
1683
- }
1684
- }
1685
- this.rawArgs = argv.slice();
1686
- let userArgs;
1687
- switch (parseOptions.from) {
1688
- case void 0:
1689
- case "node":
1690
- this._scriptPath = argv[1];
1691
- userArgs = argv.slice(2);
1692
- break;
1693
- case "electron":
1694
- if (process4.defaultApp) {
1695
- this._scriptPath = argv[1];
1696
- userArgs = argv.slice(2);
1697
- } else {
1698
- userArgs = argv.slice(1);
1699
- }
1700
- break;
1701
- case "user":
1702
- userArgs = argv.slice(0);
1703
- break;
1704
- default:
1705
- throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1706
- }
1707
- if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1708
- this._name = this._name || "program";
1709
- return userArgs;
1710
- }
1711
- /**
1712
- * Parse `argv`, setting options and invoking commands when defined.
1713
- *
1714
- * The default expectation is that the arguments are from node and have the application as argv[0]
1715
- * and the script being run in argv[1], with user parameters after that.
1716
- *
1717
- * @example
1718
- * program.parse(process.argv);
1719
- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1720
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1721
- *
1722
- * @param {string[]} [argv] - optional, defaults to process.argv
1723
- * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1724
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1725
- * @return {Command} `this` command for chaining
1726
- */
1727
- parse(argv, parseOptions) {
1728
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1729
- this._parseCommand([], userArgs);
1730
- return this;
1731
- }
1732
- /**
1733
- * Parse `argv`, setting options and invoking commands when defined.
1734
- *
1735
- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1736
- *
1737
- * The default expectation is that the arguments are from node and have the application as argv[0]
1738
- * and the script being run in argv[1], with user parameters after that.
1739
- *
1740
- * @example
1741
- * await program.parseAsync(process.argv);
1742
- * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1743
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1744
- *
1745
- * @param {string[]} [argv]
1746
- * @param {Object} [parseOptions]
1747
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1748
- * @return {Promise}
1749
- */
1750
- async parseAsync(argv, parseOptions) {
1751
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1752
- await this._parseCommand([], userArgs);
1753
- return this;
1754
- }
1755
- /**
1756
- * Execute a sub-command executable.
1757
- *
1758
- * @api private
1759
- */
1760
- _executeSubCommand(subcommand, args) {
1761
- args = args.slice();
1762
- let launchWithNode = false;
1763
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1764
- function findFile(baseDir, baseName) {
1765
- const localBin = path.resolve(baseDir, baseName);
1766
- if (fs.existsSync(localBin)) return localBin;
1767
- if (sourceExt.includes(path.extname(baseName))) return void 0;
1768
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1769
- if (foundExt) return `${localBin}${foundExt}`;
1770
- return void 0;
1771
- }
1772
- this._checkForMissingMandatoryOptions();
1773
- this._checkForConflictingOptions();
1774
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1775
- let executableDir = this._executableDir || "";
1776
- if (this._scriptPath) {
1777
- let resolvedScriptPath;
1778
- try {
1779
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
1780
- } catch (err) {
1781
- resolvedScriptPath = this._scriptPath;
1782
- }
1783
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1784
- }
1785
- if (executableDir) {
1786
- let localFile = findFile(executableDir, executableFile);
1787
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
1788
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1789
- if (legacyName !== this._name) {
1790
- localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1791
- }
1792
- }
1793
- executableFile = localFile || executableFile;
1794
- }
1795
- launchWithNode = sourceExt.includes(path.extname(executableFile));
1796
- let proc;
1797
- if (process4.platform !== "win32") {
1798
- if (launchWithNode) {
1799
- args.unshift(executableFile);
1800
- args = incrementNodeInspectorPort(process4.execArgv).concat(args);
1801
- proc = childProcess.spawn(process4.argv[0], args, { stdio: "inherit" });
1802
- } else {
1803
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1804
- }
1805
- } else {
1806
- args.unshift(executableFile);
1807
- args = incrementNodeInspectorPort(process4.execArgv).concat(args);
1808
- proc = childProcess.spawn(process4.execPath, args, { stdio: "inherit" });
1809
- }
1810
- if (!proc.killed) {
1811
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1812
- signals.forEach((signal) => {
1813
- process4.on(signal, () => {
1814
- if (proc.killed === false && proc.exitCode === null) {
1815
- proc.kill(signal);
1816
- }
1817
- });
1818
- });
1819
- }
1820
- const exitCallback = this._exitCallback;
1821
- if (!exitCallback) {
1822
- proc.on("close", process4.exit.bind(process4));
1823
- } else {
1824
- proc.on("close", () => {
1825
- exitCallback(new CommanderError2(process4.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1826
- });
1827
- }
1828
- proc.on("error", (err) => {
1829
- if (err.code === "ENOENT") {
1830
- 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";
1831
- const executableMissing = `'${executableFile}' does not exist
1832
- - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1833
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1834
- - ${executableDirMessage}`;
1835
- throw new Error(executableMissing);
1836
- } else if (err.code === "EACCES") {
1837
- throw new Error(`'${executableFile}' not executable`);
1838
- }
1839
- if (!exitCallback) {
1840
- process4.exit(1);
1841
- } else {
1842
- const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
1843
- wrappedError.nestedError = err;
1844
- exitCallback(wrappedError);
1845
- }
1846
- });
1847
- this.runningCommand = proc;
1848
- }
1849
- /**
1850
- * @api private
1851
- */
1852
- _dispatchSubcommand(commandName, operands, unknown3) {
1853
- const subCommand = this._findCommand(commandName);
1854
- if (!subCommand) this.help({ error: true });
1855
- let promiseChain;
1856
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1857
- promiseChain = this._chainOrCall(promiseChain, () => {
1858
- if (subCommand._executableHandler) {
1859
- this._executeSubCommand(subCommand, operands.concat(unknown3));
1860
- } else {
1861
- return subCommand._parseCommand(operands, unknown3);
1862
- }
1863
- });
1864
- return promiseChain;
1865
- }
1866
- /**
1867
- * Invoke help directly if possible, or dispatch if necessary.
1868
- * e.g. help foo
1869
- *
1870
- * @api private
1871
- */
1872
- _dispatchHelpCommand(subcommandName) {
1873
- if (!subcommandName) {
1874
- this.help();
1875
- }
1876
- const subCommand = this._findCommand(subcommandName);
1877
- if (subCommand && !subCommand._executableHandler) {
1878
- subCommand.help();
1879
- }
1880
- return this._dispatchSubcommand(subcommandName, [], [
1881
- this._helpLongFlag || this._helpShortFlag
1882
- ]);
1883
- }
1884
- /**
1885
- * Check this.args against expected this.registeredArguments.
1886
- *
1887
- * @api private
1888
- */
1889
- _checkNumberOfArguments() {
1890
- this.registeredArguments.forEach((arg, i) => {
1891
- if (arg.required && this.args[i] == null) {
1892
- this.missingArgument(arg.name());
1893
- }
1894
- });
1895
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1896
- return;
1897
- }
1898
- if (this.args.length > this.registeredArguments.length) {
1899
- this._excessArguments(this.args);
1900
- }
1901
- }
1902
- /**
1903
- * Process this.args using this.registeredArguments and save as this.processedArgs!
1904
- *
1905
- * @api private
1906
- */
1907
- _processArguments() {
1908
- const myParseArg = (argument, value, previous) => {
1909
- let parsedValue = value;
1910
- if (value !== null && argument.parseArg) {
1911
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1912
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1913
- }
1914
- return parsedValue;
1915
- };
1916
- this._checkNumberOfArguments();
1917
- const processedArgs = [];
1918
- this.registeredArguments.forEach((declaredArg, index) => {
1919
- let value = declaredArg.defaultValue;
1920
- if (declaredArg.variadic) {
1921
- if (index < this.args.length) {
1922
- value = this.args.slice(index);
1923
- if (declaredArg.parseArg) {
1924
- value = value.reduce((processed, v) => {
1925
- return myParseArg(declaredArg, v, processed);
1926
- }, declaredArg.defaultValue);
1927
- }
1928
- } else if (value === void 0) {
1929
- value = [];
1930
- }
1931
- } else if (index < this.args.length) {
1932
- value = this.args[index];
1933
- if (declaredArg.parseArg) {
1934
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1935
- }
1936
- }
1937
- processedArgs[index] = value;
1938
- });
1939
- this.processedArgs = processedArgs;
1940
- }
1941
- /**
1942
- * Once we have a promise we chain, but call synchronously until then.
1943
- *
1944
- * @param {Promise|undefined} promise
1945
- * @param {Function} fn
1946
- * @return {Promise|undefined}
1947
- * @api private
1948
- */
1949
- _chainOrCall(promise2, fn) {
1950
- if (promise2 && promise2.then && typeof promise2.then === "function") {
1951
- return promise2.then(() => fn());
1952
- }
1953
- return fn();
1954
- }
1955
- /**
1956
- *
1957
- * @param {Promise|undefined} promise
1958
- * @param {string} event
1959
- * @return {Promise|undefined}
1960
- * @api private
1961
- */
1962
- _chainOrCallHooks(promise2, event) {
1963
- let result = promise2;
1964
- const hooks = [];
1965
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
1966
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1967
- hooks.push({ hookedCommand, callback });
1968
- });
1969
- });
1970
- if (event === "postAction") {
1971
- hooks.reverse();
1972
- }
1973
- hooks.forEach((hookDetail) => {
1974
- result = this._chainOrCall(result, () => {
1975
- return hookDetail.callback(hookDetail.hookedCommand, this);
1976
- });
1977
- });
1978
- return result;
1979
- }
1980
- /**
1981
- *
1982
- * @param {Promise|undefined} promise
1983
- * @param {Command} subCommand
1984
- * @param {string} event
1985
- * @return {Promise|undefined}
1986
- * @api private
1987
- */
1988
- _chainOrCallSubCommandHook(promise2, subCommand, event) {
1989
- let result = promise2;
1990
- if (this._lifeCycleHooks[event] !== void 0) {
1991
- this._lifeCycleHooks[event].forEach((hook) => {
1992
- result = this._chainOrCall(result, () => {
1993
- return hook(this, subCommand);
1994
- });
1995
- });
1996
- }
1997
- return result;
1998
- }
1999
- /**
2000
- * Process arguments in context of this command.
2001
- * Returns action result, in case it is a promise.
2002
- *
2003
- * @api private
2004
- */
2005
- _parseCommand(operands, unknown3) {
2006
- const parsed = this.parseOptions(unknown3);
2007
- this._parseOptionsEnv();
2008
- this._parseOptionsImplied();
2009
- operands = operands.concat(parsed.operands);
2010
- unknown3 = parsed.unknown;
2011
- this.args = operands.concat(unknown3);
2012
- if (operands && this._findCommand(operands[0])) {
2013
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown3);
2014
- }
2015
- if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2016
- return this._dispatchHelpCommand(operands[1]);
2017
- }
2018
- if (this._defaultCommandName) {
2019
- outputHelpIfRequested(this, unknown3);
2020
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown3);
2021
- }
2022
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2023
- this.help({ error: true });
2024
- }
2025
- outputHelpIfRequested(this, parsed.unknown);
2026
- this._checkForMissingMandatoryOptions();
2027
- this._checkForConflictingOptions();
2028
- const checkForUnknownOptions = () => {
2029
- if (parsed.unknown.length > 0) {
2030
- this.unknownOption(parsed.unknown[0]);
2031
- }
2032
- };
2033
- const commandEvent = `command:${this.name()}`;
2034
- if (this._actionHandler) {
2035
- checkForUnknownOptions();
2036
- this._processArguments();
2037
- let promiseChain;
2038
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2039
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2040
- if (this.parent) {
2041
- promiseChain = this._chainOrCall(promiseChain, () => {
2042
- this.parent.emit(commandEvent, operands, unknown3);
2043
- });
2044
- }
2045
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2046
- return promiseChain;
2047
- }
2048
- if (this.parent && this.parent.listenerCount(commandEvent)) {
2049
- checkForUnknownOptions();
2050
- this._processArguments();
2051
- this.parent.emit(commandEvent, operands, unknown3);
2052
- } else if (operands.length) {
2053
- if (this._findCommand("*")) {
2054
- return this._dispatchSubcommand("*", operands, unknown3);
2055
- }
2056
- if (this.listenerCount("command:*")) {
2057
- this.emit("command:*", operands, unknown3);
2058
- } else if (this.commands.length) {
2059
- this.unknownCommand();
2060
- } else {
2061
- checkForUnknownOptions();
2062
- this._processArguments();
2063
- }
2064
- } else if (this.commands.length) {
2065
- checkForUnknownOptions();
2066
- this.help({ error: true });
2067
- } else {
2068
- checkForUnknownOptions();
2069
- this._processArguments();
2070
- }
2071
- }
2072
- /**
2073
- * Find matching command.
2074
- *
2075
- * @api private
2076
- */
2077
- _findCommand(name) {
2078
- if (!name) return void 0;
2079
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2080
- }
2081
- /**
2082
- * Return an option matching `arg` if any.
2083
- *
2084
- * @param {string} arg
2085
- * @return {Option}
2086
- * @api private
2087
- */
2088
- _findOption(arg) {
2089
- return this.options.find((option) => option.is(arg));
2090
- }
2091
- /**
2092
- * Display an error message if a mandatory option does not have a value.
2093
- * Called after checking for help flags in leaf subcommand.
2094
- *
2095
- * @api private
2096
- */
2097
- _checkForMissingMandatoryOptions() {
2098
- this._getCommandAndAncestors().forEach((cmd) => {
2099
- cmd.options.forEach((anOption) => {
2100
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2101
- cmd.missingMandatoryOptionValue(anOption);
2102
- }
2103
- });
2104
- });
2105
- }
2106
- /**
2107
- * Display an error message if conflicting options are used together in this.
2108
- *
2109
- * @api private
2110
- */
2111
- _checkForConflictingLocalOptions() {
2112
- const definedNonDefaultOptions = this.options.filter(
2113
- (option) => {
2114
- const optionKey = option.attributeName();
2115
- if (this.getOptionValue(optionKey) === void 0) {
2116
- return false;
2117
- }
2118
- return this.getOptionValueSource(optionKey) !== "default";
2119
- }
2120
- );
2121
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2122
- (option) => option.conflictsWith.length > 0
2123
- );
2124
- optionsWithConflicting.forEach((option) => {
2125
- const conflictingAndDefined = definedNonDefaultOptions.find(
2126
- (defined) => option.conflictsWith.includes(defined.attributeName())
2127
- );
2128
- if (conflictingAndDefined) {
2129
- this._conflictingOption(option, conflictingAndDefined);
2130
- }
2131
- });
2132
- }
2133
- /**
2134
- * Display an error message if conflicting options are used together.
2135
- * Called after checking for help flags in leaf subcommand.
2136
- *
2137
- * @api private
2138
- */
2139
- _checkForConflictingOptions() {
2140
- this._getCommandAndAncestors().forEach((cmd) => {
2141
- cmd._checkForConflictingLocalOptions();
2142
- });
2143
- }
2144
- /**
2145
- * Parse options from `argv` removing known options,
2146
- * and return argv split into operands and unknown arguments.
2147
- *
2148
- * Examples:
2149
- *
2150
- * argv => operands, unknown
2151
- * --known kkk op => [op], []
2152
- * op --known kkk => [op], []
2153
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2154
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2155
- *
2156
- * @param {String[]} argv
2157
- * @return {{operands: String[], unknown: String[]}}
2158
- */
2159
- parseOptions(argv) {
2160
- const operands = [];
2161
- const unknown3 = [];
2162
- let dest = operands;
2163
- const args = argv.slice();
2164
- function maybeOption(arg) {
2165
- return arg.length > 1 && arg[0] === "-";
2166
- }
2167
- let activeVariadicOption = null;
2168
- while (args.length) {
2169
- const arg = args.shift();
2170
- if (arg === "--") {
2171
- if (dest === unknown3) dest.push(arg);
2172
- dest.push(...args);
2173
- break;
2174
- }
2175
- if (activeVariadicOption && !maybeOption(arg)) {
2176
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2177
- continue;
2178
- }
2179
- activeVariadicOption = null;
2180
- if (maybeOption(arg)) {
2181
- const option = this._findOption(arg);
2182
- if (option) {
2183
- if (option.required) {
2184
- const value = args.shift();
2185
- if (value === void 0) this.optionMissingArgument(option);
2186
- this.emit(`option:${option.name()}`, value);
2187
- } else if (option.optional) {
2188
- let value = null;
2189
- if (args.length > 0 && !maybeOption(args[0])) {
2190
- value = args.shift();
2191
- }
2192
- this.emit(`option:${option.name()}`, value);
2193
- } else {
2194
- this.emit(`option:${option.name()}`);
2195
- }
2196
- activeVariadicOption = option.variadic ? option : null;
2197
- continue;
2198
- }
2199
- }
2200
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2201
- const option = this._findOption(`-${arg[1]}`);
2202
- if (option) {
2203
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2204
- this.emit(`option:${option.name()}`, arg.slice(2));
2205
- } else {
2206
- this.emit(`option:${option.name()}`);
2207
- args.unshift(`-${arg.slice(2)}`);
2208
- }
2209
- continue;
2210
- }
2211
- }
2212
- if (/^--[^=]+=/.test(arg)) {
2213
- const index = arg.indexOf("=");
2214
- const option = this._findOption(arg.slice(0, index));
2215
- if (option && (option.required || option.optional)) {
2216
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2217
- continue;
2218
- }
2219
- }
2220
- if (maybeOption(arg)) {
2221
- dest = unknown3;
2222
- }
2223
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown3.length === 0) {
2224
- if (this._findCommand(arg)) {
2225
- operands.push(arg);
2226
- if (args.length > 0) unknown3.push(...args);
2227
- break;
2228
- } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2229
- operands.push(arg);
2230
- if (args.length > 0) operands.push(...args);
2231
- break;
2232
- } else if (this._defaultCommandName) {
2233
- unknown3.push(arg);
2234
- if (args.length > 0) unknown3.push(...args);
2235
- break;
2236
- }
2237
- }
2238
- if (this._passThroughOptions) {
2239
- dest.push(arg);
2240
- if (args.length > 0) dest.push(...args);
2241
- break;
2242
- }
2243
- dest.push(arg);
2244
- }
2245
- return { operands, unknown: unknown3 };
2246
- }
2247
- /**
2248
- * Return an object containing local option values as key-value pairs.
2249
- *
2250
- * @return {Object}
2251
- */
2252
- opts() {
2253
- if (this._storeOptionsAsProperties) {
2254
- const result = {};
2255
- const len = this.options.length;
2256
- for (let i = 0; i < len; i++) {
2257
- const key = this.options[i].attributeName();
2258
- result[key] = key === this._versionOptionName ? this._version : this[key];
2259
- }
2260
- return result;
2261
- }
2262
- return this._optionValues;
2263
- }
2264
- /**
2265
- * Return an object containing merged local and global option values as key-value pairs.
2266
- *
2267
- * @return {Object}
2268
- */
2269
- optsWithGlobals() {
2270
- return this._getCommandAndAncestors().reduce(
2271
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2272
- {}
2273
- );
2274
- }
2275
- /**
2276
- * Display error message and exit (or call exitOverride).
2277
- *
2278
- * @param {string} message
2279
- * @param {Object} [errorOptions]
2280
- * @param {string} [errorOptions.code] - an id string representing the error
2281
- * @param {number} [errorOptions.exitCode] - used with process.exit
2282
- */
2283
- error(message, errorOptions) {
2284
- this._outputConfiguration.outputError(`${message}
2285
- `, this._outputConfiguration.writeErr);
2286
- if (typeof this._showHelpAfterError === "string") {
2287
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2288
- `);
2289
- } else if (this._showHelpAfterError) {
2290
- this._outputConfiguration.writeErr("\n");
2291
- this.outputHelp({ error: true });
2292
- }
2293
- const config3 = errorOptions || {};
2294
- const exitCode2 = config3.exitCode || 1;
2295
- const code = config3.code || "commander.error";
2296
- this._exit(exitCode2, code, message);
2297
- }
2298
- /**
2299
- * Apply any option related environment variables, if option does
2300
- * not have a value from cli or client code.
2301
- *
2302
- * @api private
2303
- */
2304
- _parseOptionsEnv() {
2305
- this.options.forEach((option) => {
2306
- if (option.envVar && option.envVar in process4.env) {
2307
- const optionKey = option.attributeName();
2308
- if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2309
- if (option.required || option.optional) {
2310
- this.emit(`optionEnv:${option.name()}`, process4.env[option.envVar]);
2311
- } else {
2312
- this.emit(`optionEnv:${option.name()}`);
2313
- }
2314
- }
2315
- }
2316
- });
2317
- }
2318
- /**
2319
- * Apply any implied option values, if option is undefined or default value.
2320
- *
2321
- * @api private
2322
- */
2323
- _parseOptionsImplied() {
2324
- const dualHelper = new DualOptions(this.options);
2325
- const hasCustomOptionValue = (optionKey) => {
2326
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2327
- };
2328
- this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2329
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2330
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2331
- });
2332
- });
2333
- }
2334
- /**
2335
- * Argument `name` is missing.
2336
- *
2337
- * @param {string} name
2338
- * @api private
2339
- */
2340
- missingArgument(name) {
2341
- const message = `error: missing required argument '${name}'`;
2342
- this.error(message, { code: "commander.missingArgument" });
2343
- }
2344
- /**
2345
- * `Option` is missing an argument.
2346
- *
2347
- * @param {Option} option
2348
- * @api private
2349
- */
2350
- optionMissingArgument(option) {
2351
- const message = `error: option '${option.flags}' argument missing`;
2352
- this.error(message, { code: "commander.optionMissingArgument" });
2353
- }
2354
- /**
2355
- * `Option` does not have a value, and is a mandatory option.
2356
- *
2357
- * @param {Option} option
2358
- * @api private
2359
- */
2360
- missingMandatoryOptionValue(option) {
2361
- const message = `error: required option '${option.flags}' not specified`;
2362
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2363
- }
2364
- /**
2365
- * `Option` conflicts with another option.
2366
- *
2367
- * @param {Option} option
2368
- * @param {Option} conflictingOption
2369
- * @api private
2370
- */
2371
- _conflictingOption(option, conflictingOption) {
2372
- const findBestOptionFromValue = (option2) => {
2373
- const optionKey = option2.attributeName();
2374
- const optionValue = this.getOptionValue(optionKey);
2375
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2376
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2377
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2378
- return negativeOption;
2379
- }
2380
- return positiveOption || option2;
2381
- };
2382
- const getErrorMessage = (option2) => {
2383
- const bestOption = findBestOptionFromValue(option2);
2384
- const optionKey = bestOption.attributeName();
2385
- const source = this.getOptionValueSource(optionKey);
2386
- if (source === "env") {
2387
- return `environment variable '${bestOption.envVar}'`;
2388
- }
2389
- return `option '${bestOption.flags}'`;
2390
- };
2391
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2392
- this.error(message, { code: "commander.conflictingOption" });
2393
- }
2394
- /**
2395
- * Unknown option `flag`.
2396
- *
2397
- * @param {string} flag
2398
- * @api private
2399
- */
2400
- unknownOption(flag) {
2401
- if (this._allowUnknownOption) return;
2402
- let suggestion = "";
2403
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2404
- let candidateFlags = [];
2405
- let command = this;
2406
- do {
2407
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2408
- candidateFlags = candidateFlags.concat(moreFlags);
2409
- command = command.parent;
2410
- } while (command && !command._enablePositionalOptions);
2411
- suggestion = suggestSimilar(flag, candidateFlags);
2412
- }
2413
- const message = `error: unknown option '${flag}'${suggestion}`;
2414
- this.error(message, { code: "commander.unknownOption" });
2415
- }
2416
- /**
2417
- * Excess arguments, more than expected.
2418
- *
2419
- * @param {string[]} receivedArgs
2420
- * @api private
2421
- */
2422
- _excessArguments(receivedArgs) {
2423
- if (this._allowExcessArguments) return;
2424
- const expected = this.registeredArguments.length;
2425
- const s = expected === 1 ? "" : "s";
2426
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2427
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2428
- this.error(message, { code: "commander.excessArguments" });
2429
- }
2430
- /**
2431
- * Unknown command.
2432
- *
2433
- * @api private
2434
- */
2435
- unknownCommand() {
2436
- const unknownName = this.args[0];
2437
- let suggestion = "";
2438
- if (this._showSuggestionAfterError) {
2439
- const candidateNames = [];
2440
- this.createHelp().visibleCommands(this).forEach((command) => {
2441
- candidateNames.push(command.name());
2442
- if (command.alias()) candidateNames.push(command.alias());
2443
- });
2444
- suggestion = suggestSimilar(unknownName, candidateNames);
2445
- }
2446
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2447
- this.error(message, { code: "commander.unknownCommand" });
2448
- }
2449
- /**
2450
- * Get or set the program version.
2451
- *
2452
- * This method auto-registers the "-V, --version" option which will print the version number.
2453
- *
2454
- * You can optionally supply the flags and description to override the defaults.
2455
- *
2456
- * @param {string} [str]
2457
- * @param {string} [flags]
2458
- * @param {string} [description]
2459
- * @return {this | string | undefined} `this` command for chaining, or version string if no arguments
2460
- */
2461
- version(str, flags, description) {
2462
- if (str === void 0) return this._version;
2463
- this._version = str;
2464
- flags = flags || "-V, --version";
2465
- description = description || "output the version number";
2466
- const versionOption = this.createOption(flags, description);
2467
- this._versionOptionName = versionOption.attributeName();
2468
- this.options.push(versionOption);
2469
- this.on("option:" + versionOption.name(), () => {
2470
- this._outputConfiguration.writeOut(`${str}
2471
- `);
2472
- this._exit(0, "commander.version", str);
2473
- });
2474
- return this;
2475
- }
2476
- /**
2477
- * Set the description.
2478
- *
2479
- * @param {string} [str]
2480
- * @param {Object} [argsDescription]
2481
- * @return {string|Command}
2482
- */
2483
- description(str, argsDescription) {
2484
- if (str === void 0 && argsDescription === void 0) return this._description;
2485
- this._description = str;
2486
- if (argsDescription) {
2487
- this._argsDescription = argsDescription;
2488
- }
2489
- return this;
2490
- }
2491
- /**
2492
- * Set the summary. Used when listed as subcommand of parent.
2493
- *
2494
- * @param {string} [str]
2495
- * @return {string|Command}
2496
- */
2497
- summary(str) {
2498
- if (str === void 0) return this._summary;
2499
- this._summary = str;
2500
- return this;
2501
- }
2502
- /**
2503
- * Set an alias for the command.
2504
- *
2505
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2506
- *
2507
- * @param {string} [alias]
2508
- * @return {string|Command}
2509
- */
2510
- alias(alias) {
2511
- if (alias === void 0) return this._aliases[0];
2512
- let command = this;
2513
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2514
- command = this.commands[this.commands.length - 1];
2515
- }
2516
- if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2517
- command._aliases.push(alias);
2518
- return this;
2519
- }
2520
- /**
2521
- * Set aliases for the command.
2522
- *
2523
- * Only the first alias is shown in the auto-generated help.
2524
- *
2525
- * @param {string[]} [aliases]
2526
- * @return {string[]|Command}
2527
- */
2528
- aliases(aliases) {
2529
- if (aliases === void 0) return this._aliases;
2530
- aliases.forEach((alias) => this.alias(alias));
2531
- return this;
2532
- }
2533
- /**
2534
- * Set / get the command usage `str`.
2535
- *
2536
- * @param {string} [str]
2537
- * @return {String|Command}
2538
- */
2539
- usage(str) {
2540
- if (str === void 0) {
2541
- if (this._usage) return this._usage;
2542
- const args = this.registeredArguments.map((arg) => {
2543
- return humanReadableArgName(arg);
2544
- });
2545
- return [].concat(
2546
- this.options.length || this._hasHelpOption ? "[options]" : [],
2547
- this.commands.length ? "[command]" : [],
2548
- this.registeredArguments.length ? args : []
2549
- ).join(" ");
2550
- }
2551
- this._usage = str;
2552
- return this;
2553
- }
2554
- /**
2555
- * Get or set the name of the command.
2556
- *
2557
- * @param {string} [str]
2558
- * @return {string|Command}
2559
- */
2560
- name(str) {
2561
- if (str === void 0) return this._name;
2562
- this._name = str;
2563
- return this;
2564
- }
2565
- /**
2566
- * Set the name of the command from script filename, such as process.argv[1],
2567
- * or require.main.filename, or __filename.
2568
- *
2569
- * (Used internally and public although not documented in README.)
2570
- *
2571
- * @example
2572
- * program.nameFromFilename(require.main.filename);
2573
- *
2574
- * @param {string} filename
2575
- * @return {Command}
2576
- */
2577
- nameFromFilename(filename) {
2578
- this._name = path.basename(filename, path.extname(filename));
2579
- return this;
2580
- }
2581
- /**
2582
- * Get or set the directory for searching for executable subcommands of this command.
2583
- *
2584
- * @example
2585
- * program.executableDir(__dirname);
2586
- * // or
2587
- * program.executableDir('subcommands');
2588
- *
2589
- * @param {string} [path]
2590
- * @return {string|null|Command}
2591
- */
2592
- executableDir(path2) {
2593
- if (path2 === void 0) return this._executableDir;
2594
- this._executableDir = path2;
2595
- return this;
2596
- }
2597
- /**
2598
- * Return program help documentation.
2599
- *
2600
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2601
- * @return {string}
2602
- */
2603
- helpInformation(contextOptions) {
2604
- const helper = this.createHelp();
2605
- if (helper.helpWidth === void 0) {
2606
- helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2607
- }
2608
- return helper.formatHelp(this, helper);
2609
- }
2610
- /**
2611
- * @api private
2612
- */
2613
- _getHelpContext(contextOptions) {
2614
- contextOptions = contextOptions || {};
2615
- const context = { error: !!contextOptions.error };
2616
- let write;
2617
- if (context.error) {
2618
- write = (arg) => this._outputConfiguration.writeErr(arg);
2619
- } else {
2620
- write = (arg) => this._outputConfiguration.writeOut(arg);
2621
- }
2622
- context.write = contextOptions.write || write;
2623
- context.command = this;
2624
- return context;
2625
- }
2626
- /**
2627
- * Output help information for this command.
2628
- *
2629
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2630
- *
2631
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2632
- */
2633
- outputHelp(contextOptions) {
2634
- let deprecatedCallback;
2635
- if (typeof contextOptions === "function") {
2636
- deprecatedCallback = contextOptions;
2637
- contextOptions = void 0;
2638
- }
2639
- const context = this._getHelpContext(contextOptions);
2640
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2641
- this.emit("beforeHelp", context);
2642
- let helpInformation = this.helpInformation(context);
2643
- if (deprecatedCallback) {
2644
- helpInformation = deprecatedCallback(helpInformation);
2645
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2646
- throw new Error("outputHelp callback must return a string or a Buffer");
2647
- }
2648
- }
2649
- context.write(helpInformation);
2650
- if (this._helpLongFlag) {
2651
- this.emit(this._helpLongFlag);
2652
- }
2653
- this.emit("afterHelp", context);
2654
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
2655
- }
2656
- /**
2657
- * You can pass in flags and a description to override the help
2658
- * flags and help description for your command. Pass in false to
2659
- * disable the built-in help option.
2660
- *
2661
- * @param {string | boolean} [flags]
2662
- * @param {string} [description]
2663
- * @return {Command} `this` command for chaining
2664
- */
2665
- helpOption(flags, description) {
2666
- if (typeof flags === "boolean") {
2667
- this._hasHelpOption = flags;
2668
- return this;
2669
- }
2670
- this._helpFlags = flags || this._helpFlags;
2671
- this._helpDescription = description || this._helpDescription;
2672
- const helpFlags = splitOptionFlags(this._helpFlags);
2673
- this._helpShortFlag = helpFlags.shortFlag;
2674
- this._helpLongFlag = helpFlags.longFlag;
2675
- return this;
2676
- }
2677
- /**
2678
- * Output help information and exit.
2679
- *
2680
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2681
- *
2682
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2683
- */
2684
- help(contextOptions) {
2685
- this.outputHelp(contextOptions);
2686
- let exitCode2 = process4.exitCode || 0;
2687
- if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2688
- exitCode2 = 1;
2689
- }
2690
- this._exit(exitCode2, "commander.help", "(outputHelp)");
2691
- }
2692
- /**
2693
- * Add additional text to be displayed with the built-in help.
2694
- *
2695
- * Position is 'before' or 'after' to affect just this command,
2696
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2697
- *
2698
- * @param {string} position - before or after built-in help
2699
- * @param {string | Function} text - string to add, or a function returning a string
2700
- * @return {Command} `this` command for chaining
2701
- */
2702
- addHelpText(position, text) {
2703
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2704
- if (!allowedValues.includes(position)) {
2705
- throw new Error(`Unexpected value for position to addHelpText.
2706
- Expecting one of '${allowedValues.join("', '")}'`);
2707
- }
2708
- const helpEvent = `${position}Help`;
2709
- this.on(helpEvent, (context) => {
2710
- let helpStr;
2711
- if (typeof text === "function") {
2712
- helpStr = text({ error: context.error, command: context.command });
2713
- } else {
2714
- helpStr = text;
2715
- }
2716
- if (helpStr) {
2717
- context.write(`${helpStr}
2718
- `);
2719
- }
2720
- });
2721
- return this;
2722
- }
2723
- };
2724
- function outputHelpIfRequested(cmd, args) {
2725
- const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2726
- if (helpOption) {
2727
- cmd.outputHelp();
2728
- cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
2729
- }
2730
- }
2731
- function incrementNodeInspectorPort(args) {
2732
- return args.map((arg) => {
2733
- if (!arg.startsWith("--inspect")) {
2734
- return arg;
2735
- }
2736
- let debugOption;
2737
- let debugHost = "127.0.0.1";
2738
- let debugPort = "9229";
2739
- let match;
2740
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2741
- debugOption = match[1];
2742
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2743
- debugOption = match[1];
2744
- if (/^\d+$/.test(match[3])) {
2745
- debugPort = match[3];
2746
- } else {
2747
- debugHost = match[3];
2748
- }
2749
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2750
- debugOption = match[1];
2751
- debugHost = match[3];
2752
- debugPort = match[4];
2753
- }
2754
- if (debugOption && debugPort !== "0") {
2755
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2756
- }
2757
- return arg;
2758
- });
2759
- }
2760
- exports.Command = Command2;
2761
- }
2762
- });
2763
-
2764
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/index.js
2765
- var require_commander = __commonJS({
2766
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/index.js"(exports, module) {
2767
- "use strict";
2768
- var { Argument: Argument2 } = require_argument();
2769
- var { Command: Command2 } = require_command();
2770
- var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
2771
- var { Help: Help2 } = require_help();
2772
- var { Option: Option2 } = require_option();
2773
- exports = module.exports = new Command2();
2774
- exports.program = exports;
2775
- exports.Command = Command2;
2776
- exports.Option = Option2;
2777
- exports.Argument = Argument2;
2778
- exports.Help = Help2;
2779
- exports.CommanderError = CommanderError2;
2780
- exports.InvalidArgumentError = InvalidArgumentError2;
2781
- exports.InvalidOptionArgumentError = InvalidArgumentError2;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __commonJS = (cb, mod) => function __require() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2782
22
  }
2783
- });
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
2784
33
 
2785
34
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js
2786
35
  // @__NO_SIDE_EFFECTS__
@@ -18098,13 +15347,17 @@ function parseSlideshowRun(payload) {
18098
15347
  assertNoPrivateTemplateFields(payload);
18099
15348
  return parseDataEnvelope(payload, slideshowRunSchema);
18100
15349
  }
18101
- function parseBrandProfile(payload) {
18102
- return parseDataEnvelope(payload, brandProfileSchema);
15350
+ function parseSlideshowRunSummaryList(payload) {
15351
+ assertNoPrivateTemplateFields(payload);
15352
+ return parseDataEnvelope(payload, external_exports.array(slideshowRunSummarySchema));
15353
+ }
15354
+ function parseBrand(payload) {
15355
+ return parseDataEnvelope(payload, brandSchema);
18103
15356
  }
18104
- function parseBrandProfileList(payload) {
18105
- return parseDataEnvelope(payload, external_exports.array(brandProfileSchema));
15357
+ function parseBrandList(payload) {
15358
+ return parseDataEnvelope(payload, external_exports.array(brandSchema));
18106
15359
  }
18107
- var FORBIDDEN_PUBLIC_KEYS, templatePlatformSchema, canvasPresetSchema, pageRoleSchema, contentFamilySchema, contentArchetypeSchema, densityLevelSchema, visualStyleSchema, imageRoleSchema, slotSummarySchema, selectionMetadataSchema, selectionMetadataDraftSchema, listTemplatesQuerySchema, templateSummarySchema, publicTemplateSlotTypeSchema, publicTemplateSlotSchema, templateDetailSchema, templateSelectionSchema, presentationIntentSchema, renderSlotValueSchema, renderJobRequestSchema, legacyRenderJobRequestSchema, renderJobStatusSchema, renderCaptureHintSchema, renderJobViewSchema, renderPreviewMaterializationSchema, renderSelectionSummarySchema, renderManifestSchema, templateAuthoringCanvasSchema, templateAuthoringProvenanceSchema, templateImageModeSchema, templateImageNodeSchema, authoringImageNodeSchema, authoringIconNodeSchema, templateAuthoringSourceSchema, themeContrastEntrySchema, themePaletteSchema, themeTokensSchema, themeSummarySchema, themeDetailSchema, gradientTextSafeZoneSchema, gradientStopSchema, gradientSummarySchema, gradientDetailSchema, listGradientsQuerySchema, templateSurfaceKindSchema, templateSurfacePreviewSchema, templateImageProviderSchema, templateImageRightsStatusSchema, templateImageProvenanceSchema, importTemplateImageFileSchema, importTemplateImageInputSchema, importTemplateImageBodySchema, createRenderAssetInputSchema, renderAssetReferenceSchema, iconStyleSchema, templateIconLicenseSchema, searchTemplateIconsRequestSchema, templateIconCandidateSchema, getTemplateIconRequestSchema, templateIconProvenanceSchema, templateIconAssetReferenceSchema, templateIconErrorCodeSchema, templateImageReferenceSchema, themeCreateInputSchema, draftThemeInputSchema, createTemplateDraftInputSchema, updateTemplateDraftInputSchema, templateAuthoringDraftSchema, DEFAULT_AUTHORING_STUDIO_BASE_URL, templatePrincipalErrorSchema, slideshowPlatformCaps, slideshowPlatformSchema, slideshowRunStatusSchema, publicSlotValueSchema, contentPackPageSchema, contentPackSchema, slideshowRunPageSchema, brandProfilePreferenceSchema, brandProfileSchema, createBrandProfileInputSchema, updateBrandProfileInputSchema, slideshowRunSchema, createSlideshowRunInputSchema, updateSlideshowRunInputSchema, renderSlideshowRunInputSchema;
15360
+ var FORBIDDEN_PUBLIC_KEYS, templatePlatformSchema, canvasPresetSchema, pageRoleSchema, contentFamilySchema, contentArchetypeSchema, densityLevelSchema, visualStyleSchema, imageRoleSchema, slotSummarySchema, selectionMetadataSchema, selectionMetadataDraftSchema, listTemplatesQuerySchema, templateSummarySchema, publicTemplateSlotTypeSchema, publicTemplateSlotSchema, templateDetailSchema, templateSelectionSchema, presentationIntentSchema, renderSlotValueSchema, renderJobRequestSchema, legacyRenderJobRequestSchema, renderJobStatusSchema, renderCaptureHintSchema, renderJobViewSchema, renderPreviewMaterializationSchema, renderSelectionSummarySchema, renderManifestSchema, templateAuthoringCanvasSchema, templateAuthoringProvenanceSchema, templateImageModeSchema, templateImageNodeSchema, authoringImageNodeSchema, authoringIconNodeSchema, templateAuthoringSourceSchema, themeContrastEntrySchema, themePaletteSchema, themeTokensSchema, themeSummarySchema, themeDetailSchema, gradientTextSafeZoneSchema, gradientStopSchema, gradientSummarySchema, gradientDetailSchema, listGradientsQuerySchema, templateSurfaceKindSchema, templateSurfacePreviewSchema, templateImageProviderSchema, templateImageRightsStatusSchema, templateImageProvenanceSchema, importTemplateImageFileSchema, importTemplateImageInputSchema, importTemplateImageBodySchema, createRenderAssetInputSchema, renderAssetReferenceSchema, iconStyleSchema, templateIconLicenseSchema, searchTemplateIconsRequestSchema, templateIconCandidateSchema, getTemplateIconRequestSchema, templateIconProvenanceSchema, templateIconAssetReferenceSchema, templateIconErrorCodeSchema, templateImageReferenceSchema, themeCreateInputSchema, draftThemeInputSchema, createTemplateDraftInputSchema, updateTemplateDraftInputSchema, authoringDraftVariantSchema, templateAuthoringDraftSchema, DEFAULT_AUTHORING_STUDIO_BASE_URL, templatePrincipalErrorSchema, slideshowPlatformCaps, slideshowPlatformSchema, slideshowRunStatusSchema, publicSlotValueSchema, contentPackPageSchema, contentPackSchema, slideshowRunPageSchema, brandProfilePreferenceSchema, brandProfileSchema, createBrandProfileInputSchema, updateBrandProfileInputSchema, brandTypographySchema, brandColorsSchema, brandSchema, createBrandInputSchema, updateBrandInputSchema, slideshowRunSummarySchema, slideshowRunSchema, createSlideshowRunInputSchema, updateSlideshowRunInputSchema, renderSlideshowRunInputSchema, listSlideshowRunsQuerySchema;
18108
15361
  var init_src = __esm({
18109
15362
  "../../packages/template-public-contracts/src/index.ts"() {
18110
15363
  "use strict";
@@ -18234,8 +15487,8 @@ var init_src = __esm({
18234
15487
  notFor: external_exports.array(external_exports.string()).min(1).max(3).optional(),
18235
15488
  selectionHints: external_exports.string().optional(),
18236
15489
  visualStyle: visualStyleSchema.optional(),
18237
- defaultThemeId: external_exports.string().optional(),
18238
- compatibleThemeIds: external_exports.array(external_exports.string()).optional(),
15490
+ // ADR-0033: published selection metadata must not bind a Theme.
15491
+ // Runtime appearance comes from Brand themeSnapshot at fill/render.
18239
15492
  locale: external_exports.enum(["zh-CN", "en", "bilingual"]).optional(),
18240
15493
  exampleFilledPreviewUrl: external_exports.string().url().optional(),
18241
15494
  // P2
@@ -18377,7 +15630,11 @@ var init_src = __esm({
18377
15630
  }).strict();
18378
15631
  renderSelectionSummarySchema = external_exports.object({
18379
15632
  templateId: external_exports.string().min(1),
18380
- themeId: external_exports.string().min(1),
15633
+ /**
15634
+ * Optional audit id for the tokens used (Brand snapshot / preview fallback).
15635
+ * Not a Template→Theme publish binding (ADR-0033).
15636
+ */
15637
+ themeId: external_exports.string().min(1).optional(),
18381
15638
  role: external_exports.string().min(1),
18382
15639
  canvas: external_exports.object({
18383
15640
  width: external_exports.number().int().positive(),
@@ -18746,23 +16003,18 @@ var init_src = __esm({
18746
16003
  tokens: themeTokensSchema
18747
16004
  }).strict();
18748
16005
  draftThemeInputSchema = external_exports.object({
16006
+ /** @deprecated TemplateTheme retired — ignored; use create.tokens or tokens. */
18749
16007
  themeId: external_exports.string().min(1).optional(),
18750
- /** With themeId: fork a new Theme when tokens differ (never mutate shared themes). */
16008
+ /** Preferred: write these onto LayoutFamily.preview_tokens. */
18751
16009
  tokens: themeTokensSchema.optional(),
18752
16010
  create: themeCreateInputSchema.optional()
18753
16011
  }).strict().refine(
18754
16012
  (value) => {
18755
- const hasId = Boolean(value.themeId);
18756
16013
  const hasCreate = Boolean(value.create);
18757
- if (hasId && hasCreate)
18758
- return false;
18759
- if (!hasId && !hasCreate)
18760
- return false;
18761
- if (value.tokens && !hasId)
18762
- return false;
18763
- return true;
16014
+ const hasTokens = Boolean(value.tokens);
16015
+ return hasCreate || hasTokens;
18764
16016
  },
18765
- { message: "theme must provide themeId (optionally with tokens) or create" }
16017
+ { message: "theme must provide create.tokens or tokens for Family.preview_tokens" }
18766
16018
  );
18767
16019
  createTemplateDraftInputSchema = external_exports.object({
18768
16020
  name: external_exports.string().min(1),
@@ -18782,12 +16034,28 @@ var init_src = __esm({
18782
16034
  theme: draftThemeInputSchema.optional(),
18783
16035
  selectionMetadata: selectionMetadataDraftSchema.optional()
18784
16036
  }).strict();
16037
+ authoringDraftVariantSchema = external_exports.object({
16038
+ pageId: external_exports.string(),
16039
+ familyRole: external_exports.enum(["master", "variant"]),
16040
+ canvasPreset: external_exports.string().nullable().optional(),
16041
+ canvas: external_exports.object({
16042
+ width: external_exports.number(),
16043
+ height: external_exports.number()
16044
+ }),
16045
+ platforms: external_exports.array(external_exports.string())
16046
+ }).strict();
18785
16047
  templateAuthoringDraftSchema = external_exports.object({
18786
16048
  id: external_exports.string(),
18787
16049
  /** Equals draft id — drafts are folded into TemplatePage. */
18788
16050
  templateId: external_exports.string().optional(),
18789
16051
  /** Soft theme preview reference; tokens are not stored on the draft. */
18790
16052
  themeId: external_exports.string().optional(),
16053
+ /** Alias of themeId after Layout Family / Theme unbind. */
16054
+ previewThemeId: external_exports.string().nullable().optional(),
16055
+ familyId: external_exports.string().optional(),
16056
+ familyRole: external_exports.enum(["master", "variant"]).optional(),
16057
+ variants: external_exports.array(authoringDraftVariantSchema).optional(),
16058
+ intendedPlatforms: external_exports.array(external_exports.string()).optional(),
18791
16059
  name: external_exports.string(),
18792
16060
  status: external_exports.enum(["draft", "validated", "published", "archived", "trashed"]),
18793
16061
  revision: external_exports.number().int().positive().optional(),
@@ -18830,10 +16098,13 @@ var init_src = __esm({
18830
16098
  ]);
18831
16099
  slideshowRunStatusSchema = external_exports.enum([
18832
16100
  "draft",
16101
+ "ready",
18833
16102
  "rendering",
18834
16103
  "completed",
18835
16104
  "failed",
18836
- "expired"
16105
+ "expired",
16106
+ "archived",
16107
+ "trashed"
18837
16108
  ]);
18838
16109
  publicSlotValueSchema = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]);
18839
16110
  contentPackPageSchema = external_exports.object({
@@ -18845,6 +16116,7 @@ var init_src = __esm({
18845
16116
  schemaVersion: external_exports.literal("content-pack.v1"),
18846
16117
  platform: slideshowPlatformSchema,
18847
16118
  title: external_exports.string().optional(),
16119
+ contentSlug: external_exports.string().optional(),
18848
16120
  pages: external_exports.array(contentPackPageSchema).min(1)
18849
16121
  }).strict().superRefine((value, ctx) => {
18850
16122
  const forbidden = JSON.stringify(value).toLowerCase();
@@ -18891,11 +16163,63 @@ var init_src = __esm({
18891
16163
  preference: brandProfilePreferenceSchema.default({})
18892
16164
  }).strict();
18893
16165
  updateBrandProfileInputSchema = createBrandProfileInputSchema.partial().strict();
16166
+ brandTypographySchema = external_exports.object({
16167
+ headingFontId: external_exports.string(),
16168
+ bodyFontId: external_exports.string()
16169
+ }).strict();
16170
+ brandColorsSchema = external_exports.object({
16171
+ canvas: external_exports.string(),
16172
+ surface: external_exports.string(),
16173
+ text: external_exports.string(),
16174
+ textMuted: external_exports.string(),
16175
+ primary: external_exports.string(),
16176
+ accent: external_exports.string()
16177
+ }).strict();
16178
+ brandSchema = external_exports.object({
16179
+ id: external_exports.string(),
16180
+ brandId: external_exports.string().optional(),
16181
+ name: external_exports.string(),
16182
+ displayName: external_exports.string().optional(),
16183
+ handle: external_exports.string().optional(),
16184
+ typography: brandTypographySchema.optional(),
16185
+ colors: brandColorsSchema.partial().optional(),
16186
+ logoAssetId: external_exports.string().nullable().optional(),
16187
+ revision: external_exports.number().int().positive().optional(),
16188
+ status: external_exports.string(),
16189
+ createdAt: external_exports.string().optional(),
16190
+ updatedAt: external_exports.string().optional()
16191
+ }).strict();
16192
+ createBrandInputSchema = external_exports.object({
16193
+ name: external_exports.string().min(1),
16194
+ displayName: external_exports.string().optional(),
16195
+ handle: external_exports.string().optional(),
16196
+ typography: brandTypographySchema.partial().optional(),
16197
+ colors: brandColorsSchema.partial().optional(),
16198
+ logoAssetId: external_exports.string().nullable().optional()
16199
+ }).strict();
16200
+ updateBrandInputSchema = createBrandInputSchema.partial().extend({
16201
+ baseRevision: external_exports.number().int().positive()
16202
+ }).strict();
16203
+ slideshowRunSummarySchema = external_exports.object({
16204
+ id: external_exports.string(),
16205
+ platform: slideshowPlatformSchema,
16206
+ title: external_exports.string().optional(),
16207
+ contentSlug: external_exports.string().optional(),
16208
+ status: slideshowRunStatusSchema,
16209
+ revision: external_exports.number().int().positive(),
16210
+ pageCount: external_exports.number().int().nonnegative(),
16211
+ brandProfileId: external_exports.string().optional(),
16212
+ studioUrl: external_exports.string().url().optional(),
16213
+ lastActivityAt: external_exports.string().optional(),
16214
+ createdAt: external_exports.string(),
16215
+ updatedAt: external_exports.string()
16216
+ }).strict();
18894
16217
  slideshowRunSchema = external_exports.object({
18895
16218
  id: external_exports.string(),
18896
16219
  ownerId: external_exports.string().optional(),
18897
16220
  platform: slideshowPlatformSchema,
18898
16221
  title: external_exports.string().optional(),
16222
+ contentSlug: external_exports.string().optional(),
18899
16223
  status: slideshowRunStatusSchema,
18900
16224
  revision: external_exports.number().int().positive().optional(),
18901
16225
  packSnapshot: contentPackSchema,
@@ -18903,18 +16227,23 @@ var init_src = __esm({
18903
16227
  pages: external_exports.array(slideshowRunPageSchema),
18904
16228
  brandProfileId: external_exports.string().optional(),
18905
16229
  studioUrl: external_exports.string().url().optional(),
16230
+ lastActivityAt: external_exports.string().optional(),
18906
16231
  updatedAt: external_exports.string(),
18907
16232
  createdAt: external_exports.string()
18908
16233
  }).strict();
18909
16234
  createSlideshowRunInputSchema = external_exports.object({
18910
16235
  pack: contentPackSchema,
16236
+ brandId: external_exports.string().optional(),
18911
16237
  brandProfileId: external_exports.string().optional(),
18912
- themeSnapshot: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
16238
+ themeSnapshot: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
16239
+ contentSlug: external_exports.string().optional()
18913
16240
  }).strict();
18914
16241
  updateSlideshowRunInputSchema = external_exports.object({
18915
16242
  pack: contentPackSchema.optional(),
16243
+ brandId: external_exports.string().optional(),
18916
16244
  brandProfileId: external_exports.string().optional(),
18917
16245
  themeSnapshot: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
16246
+ contentSlug: external_exports.string().optional(),
18918
16247
  baseRevision: external_exports.number().int().positive().optional(),
18919
16248
  pageIndex: external_exports.number().int().nonnegative().optional(),
18920
16249
  slots: external_exports.record(external_exports.string(), publicSlotValueSchema).optional(),
@@ -18926,6 +16255,14 @@ var init_src = __esm({
18926
16255
  outputFormats: external_exports.array(external_exports.literal("png")).length(1).default(["png"]),
18927
16256
  idempotencyKey: external_exports.string().min(1).max(128)
18928
16257
  }).strict();
16258
+ listSlideshowRunsQuerySchema = external_exports.object({
16259
+ q: external_exports.string().optional(),
16260
+ platform: slideshowPlatformSchema.optional(),
16261
+ profileId: external_exports.string().optional(),
16262
+ brandProfileId: external_exports.string().optional(),
16263
+ contentSlug: external_exports.string().optional(),
16264
+ status: slideshowRunStatusSchema.optional()
16265
+ }).strict();
18929
16266
  }
18930
16267
  });
18931
16268
 
@@ -18951,7 +16288,7 @@ function isRetryableStatus(status) {
18951
16288
  return status === 429 || status === 502 || status === 503 || status === 504;
18952
16289
  }
18953
16290
  function sleep(ms) {
18954
- return new Promise((resolve) => setTimeout(resolve, ms));
16291
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
18955
16292
  }
18956
16293
  var TemplateGatewayError, TemplateGatewayClient;
18957
16294
  var init_client = __esm({
@@ -19127,6 +16464,25 @@ var init_client = __esm({
19127
16464
  this.options.authoringStudioBaseUrl
19128
16465
  );
19129
16466
  }
16467
+ async getTemplateFamily(familyId) {
16468
+ const response = await this.request("GET", `/v1/template-families/${encodeURIComponent(familyId)}`);
16469
+ this.throwIfError(response.status, response.json);
16470
+ return response.json.data ?? response.json;
16471
+ }
16472
+ async deriveTemplateFamily(familyId, body = {}) {
16473
+ const response = await this.request(
16474
+ "POST",
16475
+ `/v1/template-families/${encodeURIComponent(familyId)}/derive`,
16476
+ body
16477
+ );
16478
+ this.throwIfError(response.status, response.json);
16479
+ return response.json.data ?? response.json;
16480
+ }
16481
+ async migrateLegacyTemplateFamilies() {
16482
+ const response = await this.request("POST", "/v1/template-families/migrate-legacy", {});
16483
+ this.throwIfError(response.status, response.json);
16484
+ return response.json.data;
16485
+ }
19130
16486
  async updateDraft(draftId, body) {
19131
16487
  const input = parseUpdateTemplateDraftInput(body);
19132
16488
  const response = await this.request("PUT", `/v1/template-drafts/${encodeURIComponent(draftId)}`, input);
@@ -19180,6 +16536,18 @@ var init_client = __esm({
19180
16536
  this.throwIfError(response.status, response.json);
19181
16537
  return parseSlideshowRun(response.json);
19182
16538
  }
16539
+ async listSlideshowRuns(query = {}) {
16540
+ const input = listSlideshowRunsQuerySchema.parse(query);
16541
+ const params = new URLSearchParams();
16542
+ for (const [key, value] of Object.entries(input)) {
16543
+ if (value !== void 0 && value !== "")
16544
+ params.set(key, String(value));
16545
+ }
16546
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
16547
+ const response = await this.request("GET", `/v1/slideshow/runs${suffix}`);
16548
+ this.throwIfError(response.status, response.json);
16549
+ return parseSlideshowRunSummaryList(response.json);
16550
+ }
19183
16551
  async getSlideshowRun(runId) {
19184
16552
  const response = await this.request("GET", `/v1/slideshow/runs/${encodeURIComponent(runId)}`);
19185
16553
  this.throwIfError(response.status, response.json);
@@ -19191,6 +16559,22 @@ var init_client = __esm({
19191
16559
  this.throwIfError(response.status, response.json);
19192
16560
  return parseSlideshowRun(response.json);
19193
16561
  }
16562
+ async archiveSlideshowRun(runId) {
16563
+ const response = await this.request("POST", `/v1/slideshow/runs/${encodeURIComponent(runId)}/archive`);
16564
+ this.throwIfError(response.status, response.json);
16565
+ return parseSlideshowRun(response.json);
16566
+ }
16567
+ async restoreSlideshowRun(runId) {
16568
+ const response = await this.request("POST", `/v1/slideshow/runs/${encodeURIComponent(runId)}/restore`);
16569
+ this.throwIfError(response.status, response.json);
16570
+ return parseSlideshowRun(response.json);
16571
+ }
16572
+ async trashSlideshowRun(runId) {
16573
+ const response = await this.request("DELETE", `/v1/slideshow/runs/${encodeURIComponent(runId)}`);
16574
+ this.throwIfError(response.status, response.json);
16575
+ const rows = parseSlideshowRunSummaryList(response.json);
16576
+ return rows[0];
16577
+ }
19194
16578
  async renderSlideshowRun(runId, body) {
19195
16579
  const input = renderSlideshowRunInputSchema.parse(body ?? {});
19196
16580
  const response = await this.request("POST", `/v1/slideshow/runs/${encodeURIComponent(runId)}/render`, input, { idempotencyKey: input.idempotencyKey });
@@ -19231,22 +16615,83 @@ var init_client = __esm({
19231
16615
  throw new Error(`Artifact download failed (${response.status})`);
19232
16616
  return new Uint8Array(await response.arrayBuffer());
19233
16617
  }
19234
- async listBrandProfiles() {
19235
- const response = await this.request("GET", "/v1/slideshow/brand-profiles");
16618
+ async listBrands() {
16619
+ const response = await this.request("GET", "/v1/brands");
19236
16620
  this.throwIfError(response.status, response.json);
19237
- return parseBrandProfileList(response.json);
16621
+ return parseBrandList(response.json);
19238
16622
  }
19239
- async createBrandProfile(body) {
19240
- const input = createBrandProfileInputSchema.parse(body);
19241
- const response = await this.request("POST", "/v1/slideshow/brand-profiles", input);
16623
+ async getBrand(brandId) {
16624
+ const response = await this.request("GET", `/v1/brands/${encodeURIComponent(brandId)}`);
19242
16625
  this.throwIfError(response.status, response.json);
19243
- return parseBrandProfile(response.json);
16626
+ return parseBrand(response.json);
19244
16627
  }
19245
- async updateBrandProfile(id, body) {
19246
- const input = updateBrandProfileInputSchema.parse(body);
19247
- const response = await this.request("PATCH", `/v1/slideshow/brand-profiles/${encodeURIComponent(id)}`, input);
16628
+ async createBrand(body) {
16629
+ const input = createBrandInputSchema.parse(body);
16630
+ const response = await this.request("POST", "/v1/brands", input);
16631
+ this.throwIfError(response.status, response.json);
16632
+ return parseBrand(response.json);
16633
+ }
16634
+ async updateBrand(brandId, body) {
16635
+ const input = updateBrandInputSchema.parse(body);
16636
+ const response = await this.request("PATCH", `/v1/brands/${encodeURIComponent(brandId)}`, input);
16637
+ this.throwIfError(response.status, response.json);
16638
+ return parseBrand(response.json);
16639
+ }
16640
+ async archiveBrand(brandId) {
16641
+ const response = await this.request("POST", `/v1/brands/${encodeURIComponent(brandId)}/archive`);
19248
16642
  this.throwIfError(response.status, response.json);
19249
- return parseBrandProfile(response.json);
16643
+ return parseBrand(response.json);
16644
+ }
16645
+ async restoreBrand(brandId) {
16646
+ const response = await this.request("POST", `/v1/brands/${encodeURIComponent(brandId)}/restore`);
16647
+ this.throwIfError(response.status, response.json);
16648
+ return parseBrand(response.json);
16649
+ }
16650
+ async trashBrand(brandId) {
16651
+ const response = await this.request("DELETE", `/v1/brands/${encodeURIComponent(brandId)}`);
16652
+ this.throwIfError(response.status, response.json);
16653
+ return parseBrand(response.json);
16654
+ }
16655
+ /** @deprecated Use listBrands */
16656
+ async listBrandProfiles() {
16657
+ const brands = await this.listBrands();
16658
+ return brands.map((brand) => ({
16659
+ id: brand.id,
16660
+ name: brand.name,
16661
+ preference: {
16662
+ themeId: void 0,
16663
+ fonts: brand.typography ? { heading: brand.typography.headingFontId, body: brand.typography.bodyFontId } : void 0,
16664
+ brandHex: brand.colors?.primary
16665
+ },
16666
+ createdAt: brand.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
16667
+ updatedAt: brand.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
16668
+ }));
16669
+ }
16670
+ /** @deprecated Use createBrand */
16671
+ async createBrandProfile(body) {
16672
+ const brand = await this.createBrand({ name: body.name });
16673
+ return (await this.listBrandProfiles()).find((item) => item.id === brand.id) ?? {
16674
+ id: brand.id,
16675
+ name: brand.name,
16676
+ preference: body.preference,
16677
+ createdAt: brand.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
16678
+ updatedAt: brand.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
16679
+ };
16680
+ }
16681
+ /** @deprecated Use updateBrand */
16682
+ async updateBrandProfile(id, body) {
16683
+ const current = await this.getBrand(id);
16684
+ await this.updateBrand(id, {
16685
+ baseRevision: current.revision ?? 1,
16686
+ name: body.name
16687
+ });
16688
+ return (await this.listBrandProfiles()).find((item) => item.id === id) ?? {
16689
+ id,
16690
+ name: body.name ?? current.name,
16691
+ preference: body.preference ?? {},
16692
+ createdAt: current.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
16693
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
16694
+ };
19250
16695
  }
19251
16696
  /**
19252
16697
  * Materialize a confirmed external/upload image into R2 + Directus Image.
@@ -26007,7 +23452,7 @@ var init_protocol = __esm({
26007
23452
  return;
26008
23453
  }
26009
23454
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
26010
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
23455
+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
26011
23456
  options?.signal?.throwIfAborted();
26012
23457
  }
26013
23458
  } catch (error52) {
@@ -26024,7 +23469,7 @@ var init_protocol = __esm({
26024
23469
  */
26025
23470
  request(request, resultSchema, options) {
26026
23471
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
26027
- return new Promise((resolve, reject) => {
23472
+ return new Promise((resolve2, reject) => {
26028
23473
  const earlyReject = (error52) => {
26029
23474
  reject(error52);
26030
23475
  };
@@ -26102,7 +23547,7 @@ var init_protocol = __esm({
26102
23547
  if (!parseResult.success) {
26103
23548
  reject(parseResult.error);
26104
23549
  } else {
26105
- resolve(parseResult.data);
23550
+ resolve2(parseResult.data);
26106
23551
  }
26107
23552
  } catch (error52) {
26108
23553
  reject(error52);
@@ -26363,12 +23808,12 @@ var init_protocol = __esm({
26363
23808
  }
26364
23809
  } catch {
26365
23810
  }
26366
- return new Promise((resolve, reject) => {
23811
+ return new Promise((resolve2, reject) => {
26367
23812
  if (signal.aborted) {
26368
23813
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
26369
23814
  return;
26370
23815
  }
26371
- const timeoutId = setTimeout(resolve, interval);
23816
+ const timeoutId = setTimeout(resolve2, interval);
26372
23817
  signal.addEventListener("abort", () => {
26373
23818
  clearTimeout(timeoutId);
26374
23819
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -29395,7 +26840,7 @@ var require_compile = __commonJS({
29395
26840
  const schOrFunc = root.refs[ref];
29396
26841
  if (schOrFunc)
29397
26842
  return schOrFunc;
29398
- let _sch = resolve.call(this, root, ref);
26843
+ let _sch = resolve2.call(this, root, ref);
29399
26844
  if (_sch === void 0) {
29400
26845
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
29401
26846
  const { schemaId } = this.opts;
@@ -29422,7 +26867,7 @@ var require_compile = __commonJS({
29422
26867
  function sameSchemaEnv(s1, s2) {
29423
26868
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
29424
26869
  }
29425
- function resolve(root, ref) {
26870
+ function resolve2(root, ref) {
29426
26871
  let sch;
29427
26872
  while (typeof (sch = this.refs[ref]) == "string")
29428
26873
  ref = sch;
@@ -29997,7 +27442,7 @@ var require_fast_uri = __commonJS({
29997
27442
  }
29998
27443
  return uri;
29999
27444
  }
30000
- function resolve(baseURI, relativeURI, options) {
27445
+ function resolve2(baseURI, relativeURI, options) {
30001
27446
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
30002
27447
  const resolved = resolveComponent(parse5(baseURI, schemelessOptions), parse5(relativeURI, schemelessOptions), schemelessOptions, true);
30003
27448
  schemelessOptions.skipEscape = true;
@@ -30224,7 +27669,7 @@ var require_fast_uri = __commonJS({
30224
27669
  var fastUri = {
30225
27670
  SCHEMES,
30226
27671
  normalize,
30227
- resolve,
27672
+ resolve: resolve2,
30228
27673
  resolveComponent,
30229
27674
  equal,
30230
27675
  serialize,
@@ -34123,12 +31568,12 @@ var init_stdio2 = __esm({
34123
31568
  this.onclose?.();
34124
31569
  }
34125
31570
  send(message) {
34126
- return new Promise((resolve) => {
31571
+ return new Promise((resolve2) => {
34127
31572
  const json2 = serializeMessage(message);
34128
31573
  if (this._stdout.write(json2)) {
34129
- resolve();
31574
+ resolve2();
34130
31575
  } else {
34131
- this._stdout.once("drain", resolve);
31576
+ this._stdout.once("drain", resolve2);
34132
31577
  }
34133
31578
  });
34134
31579
  }
@@ -34199,8 +31644,8 @@ async function serveStdioMcp(options) {
34199
31644
  await waitForStdioServerClose(server, process.stdin);
34200
31645
  }
34201
31646
  async function waitForStdioServerClose(server, stdin = process.stdin) {
34202
- await new Promise((resolve) => {
34203
- server.onclose = () => resolve();
31647
+ await new Promise((resolve2) => {
31648
+ server.onclose = () => resolve2();
34204
31649
  if (stdin.readableEnded || stdin.destroyed) {
34205
31650
  void server.close().catch(() => void 0);
34206
31651
  return;
@@ -34824,13 +32269,14 @@ var init_src5 = __esm({
34824
32269
  init_src2();
34825
32270
  objectSchema = { type: "object", properties: {}, additionalProperties: true };
34826
32271
  slideshowToolRegistry = [
34827
- { name: "create_run", title: "Create slideshow run", description: "Create an ADR-0026 Slideshow Run from a ContentPack.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { pack: { type: "object" }, brandProfileId: { type: "string" } }, required: ["pack"] }, outputSchema: objectSchema },
32272
+ { name: "list_runs", title: "List slideshow runs", description: "List owner-scoped Slideshow Runs with optional filters.", effect: "read-only", inputSchema: { ...objectSchema, properties: { q: { type: "string" }, platform: { type: "string" }, profileId: { type: "string" }, brandProfileId: { type: "string" }, contentSlug: { type: "string" }, status: { type: "string" } } }, outputSchema: objectSchema },
32273
+ { name: "create_run", title: "Create slideshow run", description: "Create an ADR-0026 Slideshow Run from a ContentPack.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { pack: { type: "object" }, brandId: { type: "string" }, brandProfileId: { type: "string" }, contentSlug: { type: "string" } }, required: ["pack"] }, outputSchema: objectSchema },
34828
32274
  { name: "get_run", title: "Get slideshow run", description: "Get an owner-scoped Slideshow Run.", effect: "read-only", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
34829
- { name: "update_run", title: "Update slideshow run", description: "Edit page-instance slots/layout/style/decorations or presentation preference with optimistic revision.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, pack: { type: "object" }, brandProfileId: { type: "string" }, baseRevision: { type: "integer", minimum: 1 }, pageIndex: { type: "integer", minimum: 0 }, slots: { type: "object" }, layout: { type: "object" }, style: { type: "object" }, decorations: { type: "array" } }, required: ["runId"] }, outputSchema: objectSchema },
34830
- { name: "render_run", title: "Render slideshow run", description: "Render a topology-locked Run as an atomic PNG set.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, idempotencyKey: { type: "string", minLength: 1, maxLength: 128 } }, required: ["runId", "idempotencyKey"] }, outputSchema: objectSchema },
34831
- { name: "list_brand_profiles", title: "List brand profiles", description: "List owner-scoped Brand Profiles.", effect: "read-only", inputSchema: { ...objectSchema, properties: {} }, outputSchema: objectSchema },
34832
- { name: "create_brand_profile", title: "Create brand profile", description: "Create a Brand Profile; Free workspaces are limited to one.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { name: { type: "string" }, preference: { type: "object" } }, required: ["name"] }, outputSchema: objectSchema },
34833
- { name: "update_brand_profile", title: "Update brand profile", description: "Update a Brand Profile preference.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { profileId: { type: "string" }, name: { type: "string" }, preference: { type: "object" } }, required: ["profileId"] }, outputSchema: objectSchema }
32275
+ { name: "update_run", title: "Update slideshow run", description: "Edit page-instance slots/layout/style/decorations or presentation preference with optimistic revision.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, pack: { type: "object" }, brandId: { type: "string" }, brandProfileId: { type: "string" }, contentSlug: { type: "string" }, baseRevision: { type: "integer", minimum: 1 }, pageIndex: { type: "integer", minimum: 0 }, slots: { type: "object" }, layout: { type: "object" }, style: { type: "object" }, decorations: { type: "array" } }, required: ["runId"] }, outputSchema: objectSchema },
32276
+ { name: "archive_run", title: "Archive slideshow run", description: "Hide a Run from default lists without deleting it.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
32277
+ { name: "restore_run", title: "Restore slideshow run", description: "Restore an archived or trashed Run.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
32278
+ { name: "trash_run", title: "Trash slideshow run", description: "Move a Run to trash (recoverable for 30 days).", effect: "explicit-approval", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
32279
+ { name: "render_run", title: "Render slideshow run", description: "Render a topology-locked Run as an atomic PNG set.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, idempotencyKey: { type: "string", minLength: 1, maxLength: 128 } }, required: ["runId", "idempotencyKey"] }, outputSchema: objectSchema }
34834
32280
  ];
34835
32281
  slideshowResourceTemplates = [
34836
32282
  { uriTemplate: "slideshow://runs/{runId}", name: "Slideshow Run", description: "Owner-scoped Run JSON snapshot", mimeType: "application/json" }
@@ -34843,20 +32289,29 @@ var init_src5 = __esm({
34843
32289
  const m = meta3();
34844
32290
  try {
34845
32291
  switch (toolName) {
32292
+ case "list_runs":
32293
+ return { ok: true, data: await this.client.listSlideshowRuns({
32294
+ q: args.q,
32295
+ platform: args.platform,
32296
+ profileId: args.profileId,
32297
+ brandProfileId: args.brandProfileId,
32298
+ contentSlug: args.contentSlug,
32299
+ status: args.status
32300
+ }), meta: m };
34846
32301
  case "create_run":
34847
- return { ok: true, data: await this.client.createSlideshowRun({ pack: args.pack, brandProfileId: args.brandProfileId }), meta: m };
32302
+ return { ok: true, data: await this.client.createSlideshowRun({ pack: args.pack, brandId: args.brandId, brandProfileId: args.brandProfileId, contentSlug: args.contentSlug }), meta: m };
34848
32303
  case "get_run":
34849
32304
  return { ok: true, data: await this.client.getSlideshowRun(String(args.runId)), meta: m };
34850
32305
  case "update_run":
34851
- return { ok: true, data: await this.client.updateSlideshowRun(String(args.runId), { pack: args.pack, brandProfileId: args.brandProfileId, baseRevision: args.baseRevision, pageIndex: args.pageIndex, slots: args.slots, layout: args.layout, style: args.style, decorations: args.decorations }), meta: m };
32306
+ return { ok: true, data: await this.client.updateSlideshowRun(String(args.runId), { pack: args.pack, brandId: args.brandId, brandProfileId: args.brandProfileId, contentSlug: args.contentSlug, baseRevision: args.baseRevision, pageIndex: args.pageIndex, slots: args.slots, layout: args.layout, style: args.style, decorations: args.decorations }), meta: m };
32307
+ case "archive_run":
32308
+ return { ok: true, data: await this.client.archiveSlideshowRun(String(args.runId)), meta: m };
32309
+ case "restore_run":
32310
+ return { ok: true, data: await this.client.restoreSlideshowRun(String(args.runId)), meta: m };
32311
+ case "trash_run":
32312
+ return { ok: true, data: await this.client.trashSlideshowRun(String(args.runId)), meta: m };
34852
32313
  case "render_run":
34853
32314
  return { ok: true, data: await this.client.renderSlideshowRun(String(args.runId), { outputFormats: args.outputFormats ?? ["png"], idempotencyKey: String(args.idempotencyKey) }), meta: m };
34854
- case "list_brand_profiles":
34855
- return { ok: true, data: await this.client.listBrandProfiles(), meta: m };
34856
- case "create_brand_profile":
34857
- return { ok: true, data: await this.client.createBrandProfile({ name: String(args.name), preference: args.preference ?? {} }), meta: m };
34858
- case "update_brand_profile":
34859
- return { ok: true, data: await this.client.updateBrandProfile(String(args.profileId), { name: args.name, preference: args.preference }), meta: m };
34860
32315
  default:
34861
32316
  return { ok: false, error: { code: "UNKNOWN_TOOL", message: `Unknown tool: ${toolName}`, retryable: false }, meta: m };
34862
32317
  }
@@ -34888,7 +32343,7 @@ async function serveUnifiedStdioMcp(client) {
34888
32343
  resourceTemplates: unifiedResourceTemplates
34889
32344
  }, { backendName: "gateway" });
34890
32345
  }
34891
- var removedTools, templateNames, slideshowNames, rename, templateTools, slideshowTools, imageTools, unifiedToolRegistry, unifiedResourceTemplates, UnifiedMcpBackend;
32346
+ var removedTools, templateNames, slideshowNames, brandTools, rename, templateTools, slideshowTools, imageTools, unifiedToolRegistry, unifiedResourceTemplates, UnifiedMcpBackend;
34892
32347
  var init_src6 = __esm({
34893
32348
  "../../packages/mcp-server/src/index.ts"() {
34894
32349
  "use strict";
@@ -34906,14 +32361,24 @@ var init_src6 = __esm({
34906
32361
  get_render_job: "get_template_render_job"
34907
32362
  };
34908
32363
  slideshowNames = {
32364
+ list_runs: "list_slideshow_runs",
34909
32365
  create_run: "create_slideshow_run",
34910
32366
  get_run: "get_slideshow_run",
34911
32367
  update_run: "update_slideshow_run",
34912
- render_run: "render_slideshow_run",
34913
- list_brand_profiles: "list_profiles",
34914
- create_brand_profile: "create_profile",
34915
- update_brand_profile: "update_profile"
34916
- };
32368
+ archive_run: "archive_slideshow_run",
32369
+ restore_run: "restore_slideshow_run",
32370
+ trash_run: "trash_slideshow_run",
32371
+ render_run: "render_slideshow_run"
32372
+ };
32373
+ brandTools = [
32374
+ { name: "list_brands", title: "List brands", description: "List owner-scoped Brands (identity + fonts + colors + logo).", effect: "read-only", inputSchema: { type: "object", properties: {}, additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32375
+ { name: "get_brand", title: "Get brand", description: "Get one Brand by id.", effect: "read-only", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32376
+ { name: "create_brand", title: "Create brand", description: "Create a Brand with optional fonts, colors and logoAssetId.", effect: "local-write-job", inputSchema: { type: "object", properties: { name: { type: "string" }, displayName: { type: "string" }, handle: { type: "string" }, typography: { type: "object" }, colors: { type: "object" }, logoAssetId: { type: "string" } }, required: ["name"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32377
+ { name: "update_brand", title: "Update brand", description: "Patch Brand appearance with optimistic baseRevision.", effect: "local-write-job", inputSchema: { type: "object", properties: { brandId: { type: "string" }, baseRevision: { type: "integer", minimum: 1 }, name: { type: "string" }, displayName: { type: "string" }, handle: { type: "string" }, typography: { type: "object" }, colors: { type: "object" }, logoAssetId: { type: "string" } }, required: ["brandId", "baseRevision"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32378
+ { name: "archive_brand", title: "Archive brand", description: "Archive a Brand.", effect: "local-write-job", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32379
+ { name: "restore_brand", title: "Restore brand", description: "Restore an archived Brand.", effect: "local-write-job", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32380
+ { name: "trash_brand", title: "Trash brand", description: "Move a Brand to trash.", effect: "explicit-approval", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } }
32381
+ ];
34917
32382
  rename = (tool, names) => ({ ...tool, name: names[tool.name] ?? tool.name });
34918
32383
  templateTools = templateToolRegistry.map((tool) => rename(tool, templateNames));
34919
32384
  slideshowTools = slideshowToolRegistry.filter((tool) => !removedTools.has(tool.name)).map((tool) => rename(tool, slideshowNames));
@@ -34926,7 +32391,7 @@ var init_src6 = __esm({
34926
32391
  { name: "restore_image", title: "Restore image", description: "Restore an image asset.", effect: "local-write-job", inputSchema: { type: "object", properties: { imageId: { type: "string" } }, required: ["imageId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
34927
32392
  { name: "delete_image", title: "Trash image", description: "Move an image asset to trash.", effect: "explicit-approval", inputSchema: { type: "object", properties: { imageId: { type: "string" } }, required: ["imageId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } }
34928
32393
  ];
34929
- unifiedToolRegistry = [...templateTools, ...slideshowTools, ...imageTools];
32394
+ unifiedToolRegistry = [...templateTools, ...slideshowTools, ...brandTools, ...imageTools];
34930
32395
  unifiedResourceTemplates = slideshowResourceTemplates;
34931
32396
  UnifiedMcpBackend = class {
34932
32397
  client;
@@ -34942,6 +32407,47 @@ var init_src6 = __esm({
34942
32407
  if (templateTool) return this.template.invoke(Object.entries(templateNames).find(([, name]) => name === toolName)?.[0] ?? toolName, args);
34943
32408
  const slideshowTool = slideshowTools.find((tool) => tool.name === toolName);
34944
32409
  if (slideshowTool) return this.slideshow.invoke(Object.entries(slideshowNames).find(([, name]) => name === toolName)?.[0] ?? toolName, args);
32410
+ const brandTool = brandTools.find((tool) => tool.name === toolName);
32411
+ if (brandTool) {
32412
+ const meta4 = { requestId: `mcp_${Date.now().toString(36)}`, runtimeVersion: "0.0.0", schemaVersion: 1, toolContractVersion: "2026-08-28" };
32413
+ const brandId = typeof args.brandId === "string" ? args.brandId : "";
32414
+ const run = async () => {
32415
+ switch (toolName) {
32416
+ case "list_brands":
32417
+ return this.client.listBrands();
32418
+ case "get_brand":
32419
+ return this.client.getBrand(brandId);
32420
+ case "create_brand":
32421
+ return this.client.createBrand({
32422
+ name: String(args.name),
32423
+ displayName: args.displayName,
32424
+ handle: args.handle,
32425
+ typography: args.typography,
32426
+ colors: args.colors,
32427
+ logoAssetId: args.logoAssetId
32428
+ });
32429
+ case "update_brand":
32430
+ return this.client.updateBrand(brandId, {
32431
+ baseRevision: Number(args.baseRevision),
32432
+ name: args.name,
32433
+ displayName: args.displayName,
32434
+ handle: args.handle,
32435
+ typography: args.typography,
32436
+ colors: args.colors,
32437
+ logoAssetId: args.logoAssetId
32438
+ });
32439
+ case "archive_brand":
32440
+ return this.client.archiveBrand(brandId);
32441
+ case "restore_brand":
32442
+ return this.client.restoreBrand(brandId);
32443
+ case "trash_brand":
32444
+ return this.client.trashBrand(brandId);
32445
+ default:
32446
+ throw new Error(`Unknown brand tool: ${toolName}`);
32447
+ }
32448
+ };
32449
+ return run().then((data) => ({ ok: true, data, meta: meta4 })).catch((e) => ({ ok: false, error: { code: e?.code ?? "GATEWAY_ERROR", message: e?.message ?? "Gateway request failed", retryable: Boolean(e?.retryable) }, meta: meta4 }));
32450
+ }
34945
32451
  const imageTool = imageTools.find((tool) => tool.name === toolName);
34946
32452
  if (imageTool) {
34947
32453
  const imageId = typeof args.imageId === "string" ? encodeURIComponent(args.imageId) : "";
@@ -34979,32 +32485,13 @@ var init_v1_mcp = __esm({
34979
32485
  });
34980
32486
 
34981
32487
  // src/v1-cli.ts
32488
+ init_src2();
34982
32489
  import { cp, mkdtemp, readFile, rename as rename2, rm, writeFile, mkdir, chmod, copyFile } from "fs/promises";
34983
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
32490
+ import { existsSync as existsSync4, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
34984
32491
  import { createHash } from "crypto";
34985
- import { homedir as homedir2, tmpdir } from "os";
34986
- import { join as join3 } from "path";
34987
- import { fileURLToPath as fileURLToPath2 } from "url";
34988
-
34989
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/esm.mjs
34990
- var import_index = __toESM(require_commander(), 1);
34991
- var {
34992
- program,
34993
- createCommand,
34994
- createArgument,
34995
- createOption,
34996
- CommanderError,
34997
- InvalidArgumentError,
34998
- InvalidOptionArgumentError,
34999
- // deprecated old name
35000
- Command,
35001
- Argument,
35002
- Option,
35003
- Help
35004
- } = import_index.default;
35005
-
35006
- // src/v1-cli.ts
35007
- init_src2();
32492
+ import { homedir as homedir3, tmpdir } from "os";
32493
+ import { join as join4 } from "path";
32494
+ import { Command } from "commander";
35008
32495
 
35009
32496
  // src/runtime/mcp-hosts.ts
35010
32497
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
@@ -35128,16 +32615,330 @@ function resolveDefaultSkillsSource(moduleUrl) {
35128
32615
  return bundled;
35129
32616
  }
35130
32617
 
32618
+ // src/engine.ts
32619
+ import { spawn, spawnSync } from "child_process";
32620
+ import {
32621
+ copyFileSync,
32622
+ existsSync as existsSync3,
32623
+ mkdirSync as mkdirSync2,
32624
+ readdirSync,
32625
+ readFileSync as readFileSync2,
32626
+ statSync,
32627
+ writeFileSync as writeFileSync2
32628
+ } from "fs";
32629
+ import net from "net";
32630
+ import { homedir as homedir2 } from "os";
32631
+ import { basename, dirname as dirname3, join as join3, resolve } from "path";
32632
+ var ENGINE_ROOT_NAME = "Content Engine";
32633
+ var WORKBENCH_PORT = 8765;
32634
+ var WORKBENCH_URL = `http://127.0.0.1:${WORKBENCH_PORT}/workbench/`;
32635
+ var WORKBENCH_FILES = ["template.html", "build.py", "serve.py"];
32636
+ function contentEnginePackageRoot(moduleUrl) {
32637
+ const pkg = cliPackageRoot(moduleUrl);
32638
+ const bundled = join3(pkg, "content-engine");
32639
+ if (existsSync3(join3(bundled, "starter")))
32640
+ return bundled;
32641
+ const sibling = join3(pkg, "content-engine");
32642
+ if (existsSync3(join3(sibling, "starter")))
32643
+ return sibling;
32644
+ return bundled;
32645
+ }
32646
+ function starterDir(moduleUrl) {
32647
+ return join3(contentEnginePackageRoot(moduleUrl), "starter");
32648
+ }
32649
+ function workbenchSrc(moduleUrl) {
32650
+ return join3(contentEnginePackageRoot(moduleUrl), "workbench");
32651
+ }
32652
+ function scriptsDir(moduleUrl) {
32653
+ return join3(contentEnginePackageRoot(moduleUrl), "scripts");
32654
+ }
32655
+ function isDir(path) {
32656
+ return existsSync3(path) && statSync(path).isDirectory();
32657
+ }
32658
+ function isEngine(path) {
32659
+ return isDir(path) && existsSync3(join3(path, "CLAUDE.md")) && isDir(join3(path, "runs"));
32660
+ }
32661
+ function resolveEngine(rootOrEngine) {
32662
+ const absolute = resolve(rootOrEngine);
32663
+ if (isEngine(absolute) || basename(absolute) === ENGINE_ROOT_NAME)
32664
+ return absolute;
32665
+ return join3(absolute, ENGINE_ROOT_NAME);
32666
+ }
32667
+ function walkFiles(dir) {
32668
+ const out = [];
32669
+ if (!existsSync3(dir))
32670
+ return out;
32671
+ for (const name of readdirSync(dir)) {
32672
+ if (name === ".DS_Store")
32673
+ continue;
32674
+ const path = join3(dir, name);
32675
+ if (statSync(path).isDirectory())
32676
+ out.push(...walkFiles(path));
32677
+ else
32678
+ out.push(path);
32679
+ }
32680
+ return out;
32681
+ }
32682
+ function engineJson() {
32683
+ return `${JSON.stringify({
32684
+ schemaVersion: "content-engine.v1",
32685
+ locale: "en",
32686
+ root: ENGINE_ROOT_NAME,
32687
+ paths: {
32688
+ runs: "runs",
32689
+ exports: "exports",
32690
+ topics: "topics",
32691
+ discovery: "discovery",
32692
+ swipe: "swipe",
32693
+ profiles: "profiles",
32694
+ inbox: "inbox",
32695
+ accounts: "accounts",
32696
+ raw: "raw",
32697
+ published: "published",
32698
+ wiki: "wiki",
32699
+ platforms: "platforms",
32700
+ workbench: "workbench"
32701
+ }
32702
+ }, null, 2)}
32703
+ `;
32704
+ }
32705
+ function starterFiles(moduleUrl) {
32706
+ const root = starterDir(moduleUrl);
32707
+ const files = {};
32708
+ for (const path of walkFiles(root)) {
32709
+ const relativePath = path.slice(root.length + 1).split("\\").join("/");
32710
+ files[relativePath] = readFileSync2(path, "utf8");
32711
+ }
32712
+ files["engine.json"] = engineJson();
32713
+ return files;
32714
+ }
32715
+ function inventory(engine, moduleUrl) {
32716
+ const files = starterFiles(moduleUrl);
32717
+ const missing = [];
32718
+ const existing = [];
32719
+ for (const relative of Object.keys(files)) {
32720
+ const path = join3(engine, relative);
32721
+ (existsSync3(path) ? existing : missing).push(relative);
32722
+ }
32723
+ return {
32724
+ engine,
32725
+ engineExists: isDir(engine),
32726
+ rootName: ENGINE_ROOT_NAME,
32727
+ missing,
32728
+ existing,
32729
+ starterComplete: missing.length === 0
32730
+ };
32731
+ }
32732
+ function validateEngine(rootOrEngine, moduleUrl, { strict = false } = {}) {
32733
+ const engine = resolveEngine(rootOrEngine);
32734
+ const parent = resolve(engine, "..");
32735
+ const errors = [];
32736
+ if (!existsSync3(parent) || !statSync(parent).isDirectory()) {
32737
+ errors.push("Parent directory does not exist");
32738
+ return { ...inventory(engine, moduleUrl), valid: false, errors, created: [] };
32739
+ }
32740
+ const result = inventory(engine, moduleUrl);
32741
+ if (existsSync3(engine) && !isDir(engine))
32742
+ errors.push("Content Engine exists but is not a directory");
32743
+ if (strict) {
32744
+ if (!result.engineExists)
32745
+ errors.push("Content Engine/ folder does not exist");
32746
+ else if (result.missing.length > 0)
32747
+ errors.push(`Starter incomplete: ${result.missing.length} file(s) missing (use engine init --yes to add only missing files)`);
32748
+ }
32749
+ return { ...result, valid: errors.length === 0, errors, created: [] };
32750
+ }
32751
+ function python3Bin() {
32752
+ const result = spawnSync("python3", ["--version"], { encoding: "utf8" });
32753
+ return result.status === 0 ? "python3" : "";
32754
+ }
32755
+ function ensureWorkbench(engine, moduleUrl) {
32756
+ const destDir = join3(engine, "workbench");
32757
+ mkdirSync2(destDir, { recursive: true });
32758
+ const copied = [];
32759
+ const skipped = [];
32760
+ const src = workbenchSrc(moduleUrl);
32761
+ for (const name of WORKBENCH_FILES) {
32762
+ const dest = join3(destDir, name);
32763
+ if (existsSync3(dest)) {
32764
+ skipped.push(name);
32765
+ continue;
32766
+ }
32767
+ copyFileSync(join3(src, name), dest);
32768
+ copied.push(name);
32769
+ }
32770
+ return { destDir, copied, skipped };
32771
+ }
32772
+ function buildWorkbench(engine) {
32773
+ const python = python3Bin();
32774
+ if (!python)
32775
+ return { ok: false, code: "PYTHON3_REQUIRED", message: "python3 is required for the workbench. Install Python 3 and retry." };
32776
+ const script = join3(engine, "workbench", "build.py");
32777
+ if (!existsSync3(script))
32778
+ return { ok: false, code: "WORKBENCH_MISSING", message: "workbench/build.py is missing. Re-run easysociable engine init --yes." };
32779
+ const result = spawnSync(python, [script], { encoding: "utf8", cwd: engine });
32780
+ if (result.status !== 0)
32781
+ return { ok: false, code: "WORKBENCH_BUILD_FAILED", message: result.stderr.trim() || result.stdout.trim() || "workbench build failed" };
32782
+ return { ok: true, message: result.stdout.trim() };
32783
+ }
32784
+ function portInUse(port = WORKBENCH_PORT) {
32785
+ return new Promise((resolvePort) => {
32786
+ const socket = net.connect({ port, host: "127.0.0.1" }, () => {
32787
+ socket.end();
32788
+ resolvePort(true);
32789
+ });
32790
+ socket.on("error", () => resolvePort(false));
32791
+ });
32792
+ }
32793
+ function openUrl(url2) {
32794
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
32795
+ const args = process.platform === "win32" ? ["/c", "start", url2] : [url2];
32796
+ spawn(command, args, { stdio: "ignore", detached: true }).unref();
32797
+ }
32798
+ async function startWorkbench(engine, moduleUrl, { noOpen = false } = {}) {
32799
+ const python = python3Bin();
32800
+ if (!python)
32801
+ return { ok: false, code: "PYTHON3_REQUIRED", message: "python3 is required for the workbench. Install Python 3 and retry." };
32802
+ ensureWorkbench(engine, moduleUrl);
32803
+ const built = buildWorkbench(engine);
32804
+ if (!built.ok)
32805
+ return built;
32806
+ const url2 = WORKBENCH_URL;
32807
+ if (await portInUse()) {
32808
+ if (!noOpen && process.env.EASYSOCIABLE_NO_OPEN !== "true")
32809
+ openUrl(url2);
32810
+ return { ok: true, alreadyRunning: true, url: url2, build: built.message };
32811
+ }
32812
+ const args = [join3(engine, "workbench", "serve.py")];
32813
+ if (noOpen)
32814
+ args.push("--no-open");
32815
+ const child = spawn(python, args, { cwd: engine, detached: true, stdio: "ignore" });
32816
+ child.unref();
32817
+ return { ok: true, alreadyRunning: false, url: url2, pid: child.pid, build: built.message };
32818
+ }
32819
+ async function initEngine(rootOrEngine, moduleUrl, {
32820
+ yes = false,
32821
+ noOpen = false,
32822
+ serve = false
32823
+ } = {}) {
32824
+ const engine = resolveEngine(rootOrEngine);
32825
+ if (!yes) {
32826
+ const preview = validateEngine(engine, moduleUrl);
32827
+ return {
32828
+ ...preview,
32829
+ action: "preview",
32830
+ next: "Review missing files and re-run with --yes"
32831
+ };
32832
+ }
32833
+ const parent = resolve(engine, "..");
32834
+ if (!existsSync3(parent) || !statSync(parent).isDirectory()) {
32835
+ return {
32836
+ engine,
32837
+ action: "applied",
32838
+ valid: false,
32839
+ code: "PARENT_MISSING",
32840
+ errors: ["Parent directory does not exist"],
32841
+ created: []
32842
+ };
32843
+ }
32844
+ mkdirSync2(engine, { recursive: true });
32845
+ const report = inventory(engine, moduleUrl);
32846
+ const created = [];
32847
+ const files = starterFiles(moduleUrl);
32848
+ for (const relative of report.missing) {
32849
+ const path = join3(engine, relative);
32850
+ mkdirSync2(dirname3(path), { recursive: true });
32851
+ writeFileSync2(path, files[relative], { encoding: "utf8", flag: "wx" });
32852
+ created.push(relative);
32853
+ }
32854
+ const workbench = ensureWorkbench(engine, moduleUrl);
32855
+ const python = python3Bin();
32856
+ if (!python) {
32857
+ return {
32858
+ ...validateEngine(engine, moduleUrl),
32859
+ created,
32860
+ workbench,
32861
+ action: "applied",
32862
+ valid: false,
32863
+ code: "PYTHON3_REQUIRED",
32864
+ errors: ["python3 is required for the workbench. Install Python 3 and retry. Starter files were written; workbench was not started."]
32865
+ };
32866
+ }
32867
+ const built = buildWorkbench(engine);
32868
+ const started = serve ? await startWorkbench(engine, moduleUrl, { noOpen }) : { skipped: true, build: built };
32869
+ return {
32870
+ ...validateEngine(engine, moduleUrl),
32871
+ created,
32872
+ workbench,
32873
+ workbenchBuild: built,
32874
+ workbenchStart: started,
32875
+ action: "applied"
32876
+ };
32877
+ }
32878
+ function detectEngines() {
32879
+ const extra = (process.env.EASYSOCIABLE_ENGINE_SEARCH_ROOTS || "").split(process.platform === "win32" ? ";" : ":").map((item) => item.trim()).filter(Boolean);
32880
+ const home = homedir2();
32881
+ const roots = [...extra, join3(home, "Documents"), home];
32882
+ const found = [];
32883
+ for (const root of roots) {
32884
+ if (!isDir(root))
32885
+ continue;
32886
+ const direct = join3(root, ENGINE_ROOT_NAME);
32887
+ if (isEngine(direct) || isDir(direct))
32888
+ found.push(direct);
32889
+ try {
32890
+ for (const name of readdirSync(root)) {
32891
+ const child = join3(root, name, ENGINE_ROOT_NAME);
32892
+ if (isDir(child))
32893
+ found.push(child);
32894
+ }
32895
+ } catch {
32896
+ continue;
32897
+ }
32898
+ }
32899
+ return [...new Set(found)];
32900
+ }
32901
+ function validateRun(moduleUrl, args) {
32902
+ const script = join3(scriptsDir(moduleUrl), "validate-run.mjs");
32903
+ if (!existsSync3(script))
32904
+ throw new Error(`Missing validate-run script at ${script}`);
32905
+ const argv = ["--run", args.run];
32906
+ if (args.requirePack)
32907
+ argv.push("--require-pack");
32908
+ if (args.requireExport)
32909
+ argv.push("--require-export");
32910
+ if (args.exportDir)
32911
+ argv.push("--export", args.exportDir);
32912
+ if (args.requirePageTemplateId)
32913
+ argv.push("--require-page-template-id");
32914
+ if (args.json !== false)
32915
+ argv.push("--json");
32916
+ const result = spawnSync(process.execPath, [script, ...argv], { encoding: "utf8" });
32917
+ return {
32918
+ status: result.status ?? 1,
32919
+ stdout: result.stdout,
32920
+ stderr: result.stderr
32921
+ };
32922
+ }
32923
+
35131
32924
  // src/v1-cli.ts
35132
- var CLI_MODULE_URL = fileURLToPath2(import.meta.url);
35133
- var credentialPath = join3(homedir2(), ".config", "easysociable", "credentials.json");
32925
+ var CLI_MODULE_URL = import.meta.url;
32926
+ function readCliVersion() {
32927
+ try {
32928
+ const pkg = JSON.parse(readFileSync3(join4(cliPackageRoot(CLI_MODULE_URL), "package.json"), "utf8"));
32929
+ return typeof pkg.version === "string" && pkg.version ? pkg.version : "0.0.0";
32930
+ } catch {
32931
+ return "0.0.0";
32932
+ }
32933
+ }
32934
+ var credentialPath = join4(homedir3(), ".config", "easysociable", "credentials.json");
35134
32935
  function resolveInstallSkillIds(options) {
35135
32936
  return parseInstallSkills(typeof options.skills === "string" ? options.skills : void 0);
35136
32937
  }
35137
32938
  function readStoredCredentials() {
35138
32939
  try {
35139
- if (!existsSync3(credentialPath)) return null;
35140
- const parsed = JSON.parse(readFileSync2(credentialPath, "utf8"));
32940
+ if (!existsSync4(credentialPath)) return null;
32941
+ const parsed = JSON.parse(readFileSync3(credentialPath, "utf8"));
35141
32942
  if (typeof parsed.apiKey !== "string" || typeof parsed.baseUrl !== "string") return null;
35142
32943
  return { apiKey: parsed.apiKey, baseUrl: parsed.baseUrl };
35143
32944
  } catch {
@@ -35145,7 +32946,7 @@ function readStoredCredentials() {
35145
32946
  }
35146
32947
  }
35147
32948
  async function writeStoredCredentials(credentials) {
35148
- await mkdir(join3(homedir2(), ".config", "easysociable"), { recursive: true, mode: 448 });
32949
+ await mkdir(join4(homedir3(), ".config", "easysociable"), { recursive: true, mode: 448 });
35149
32950
  await writeFile(credentialPath, `${JSON.stringify(credentials, null, 2)}
35150
32951
  `, { mode: 384 });
35151
32952
  await chmod(credentialPath, 384);
@@ -35161,6 +32962,13 @@ function print(value, json2) {
35161
32962
  else process.stdout.write(`${JSON.stringify(value, null, 2)}
35162
32963
  `);
35163
32964
  }
32965
+ function commandWantsJson(command) {
32966
+ const local = command.opts();
32967
+ if (local.json === true)
32968
+ return true;
32969
+ const withGlobals = typeof command.optsWithGlobals === "function" ? command.optsWithGlobals() : {};
32970
+ return withGlobals.json === true;
32971
+ }
35164
32972
  function clientFromEnv() {
35165
32973
  const stored = readStoredCredentials();
35166
32974
  const allowEnv = process.env.EASYSOCIABLE_ALLOW_ENV_CREDENTIALS === "true";
@@ -35177,8 +32985,16 @@ function clientFromEnv() {
35177
32985
  function jsonOption(command) {
35178
32986
  return command.option("--json", "Emit a JSON envelope");
35179
32987
  }
32988
+ function defaultEngineRoot() {
32989
+ try {
32990
+ if (existsSync4("/workspace") && statSync2("/workspace").isDirectory())
32991
+ return "/workspace";
32992
+ } catch {
32993
+ }
32994
+ return process.cwd();
32995
+ }
35180
32996
  function installHome(options) {
35181
- return typeof options.home === "string" && options.home ? String(options.home) : homedir2();
32997
+ return typeof options.home === "string" && options.home ? String(options.home) : homedir3();
35182
32998
  }
35183
32999
  function installSource(options) {
35184
33000
  if (typeof options.source === "string" && options.source)
@@ -35189,17 +33005,17 @@ function installSource(options) {
35189
33005
  }
35190
33006
  function detectedHosts(home) {
35191
33007
  const candidates = [
35192
- { host: "codex", dir: join3(home, ".codex") },
35193
- { host: "claude", dir: join3(home, ".claude") }
33008
+ { host: "codex", dir: join4(home, ".codex") },
33009
+ { host: "claude", dir: join4(home, ".claude") }
35194
33010
  ];
35195
- return candidates.filter((item) => existsSync3(item.dir)).map((item) => ({ host: item.host, configPath: join3(item.dir, "mcp.json"), skillsPath: join3(item.dir, "skills") }));
33011
+ return candidates.filter((item) => existsSync4(item.dir)).map((item) => ({ host: item.host, configPath: join4(item.dir, "mcp.json"), skillsPath: join4(item.dir, "skills") }));
35196
33012
  }
35197
33013
  async function planInstallation(options) {
35198
33014
  const home = installHome(options);
35199
33015
  const source = installSource(options);
35200
33016
  const hosts = detectedHosts(home);
35201
33017
  const skillNames = resolveInstallSkillIds(options);
35202
- const missingSkills = skillNames.filter((name) => !existsSync3(join3(source, name)));
33018
+ const missingSkills = skillNames.filter((name) => !existsSync4(join4(source, name)));
35203
33019
  return {
35204
33020
  source,
35205
33021
  home,
@@ -35208,7 +33024,7 @@ async function planInstallation(options) {
35208
33024
  missingSkills,
35209
33025
  changes: hosts.flatMap((host) => [
35210
33026
  `merge ${host.configPath} with one easysociable MCP registration`,
35211
- ...skillNames.map((name) => `install ${join3(host.skillsPath, name)}`)
33027
+ ...skillNames.map((name) => `install ${join4(host.skillsPath, name)}`)
35212
33028
  ])
35213
33029
  };
35214
33030
  }
@@ -35224,7 +33040,7 @@ async function applyInstallation(options) {
35224
33040
  const backupSuffix = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
35225
33041
  const backups = [];
35226
33042
  for (const host of detectedHosts(String(plan.home))) {
35227
- if (existsSync3(host.configPath)) {
33043
+ if (existsSync4(host.configPath)) {
35228
33044
  const backupPath = `${host.configPath}.bak.${backupSuffix}`;
35229
33045
  await copyFile(host.configPath, backupPath);
35230
33046
  backups.push(backupPath);
@@ -35232,12 +33048,12 @@ async function applyInstallation(options) {
35232
33048
  await installHostConfig({ host: host.host, dataDir: "", configPath: host.configPath });
35233
33049
  await mkdir(host.skillsPath, { recursive: true, mode: 448 });
35234
33050
  for (const skill of resolveInstallSkillIds(options))
35235
- await cp(join3(String(plan.source), skill), join3(host.skillsPath, skill), { recursive: true, force: false, errorOnExist: false });
33051
+ await cp(join4(String(plan.source), skill), join4(host.skillsPath, skill), { recursive: true, force: false, errorOnExist: false });
35236
33052
  }
35237
33053
  return { ...plan, applied: true, backups };
35238
33054
  }
35239
33055
  async function readJsonArgument(value) {
35240
- if (existsSync3(value))
33056
+ if (existsSync4(value))
35241
33057
  return JSON.parse(await readFile(value, "utf8"));
35242
33058
  return JSON.parse(value);
35243
33059
  }
@@ -35275,7 +33091,7 @@ async function exportManifest(client, jobId, output) {
35275
33091
  const job = await client.getRenderJob(jobId);
35276
33092
  if (job.status !== "completed" || !job.manifest)
35277
33093
  throw new Error(`Render job ${jobId} is not completed or has no manifest`);
35278
- const staging = await mkdtemp(join3(tmpdir(), "easysociable-export-"));
33094
+ const staging = await mkdtemp(join4(tmpdir(), "easysociable-export-"));
35279
33095
  try {
35280
33096
  for (const [index, artifact] of job.manifest.artifacts.entries()) {
35281
33097
  const response = await fetch(artifact.url);
@@ -35283,9 +33099,9 @@ async function exportManifest(client, jobId, output) {
35283
33099
  const bytes = Buffer.from(await response.arrayBuffer());
35284
33100
  const checksum = createHash("sha256").update(bytes).digest("hex");
35285
33101
  if (checksum !== artifact.sha256) throw new Error(`Artifact checksum mismatch for page ${index + 1}`);
35286
- await writeFile(join3(staging, `${String(index + 1).padStart(2, "0")}.png`), bytes);
33102
+ await writeFile(join4(staging, `${String(index + 1).padStart(2, "0")}.png`), bytes);
35287
33103
  }
35288
- await writeFile(join3(staging, "manifest.json"), `${JSON.stringify(job.manifest, null, 2)}
33104
+ await writeFile(join4(staging, "manifest.json"), `${JSON.stringify(job.manifest, null, 2)}
35289
33105
  `);
35290
33106
  await rm(output, { recursive: true, force: true });
35291
33107
  await rename2(staging, output);
@@ -35297,7 +33113,7 @@ async function exportManifest(client, jobId, output) {
35297
33113
  }
35298
33114
  async function exportSlideshowRun(client, runId, output) {
35299
33115
  const manifest = await client.getSlideshowRunManifest(runId);
35300
- const staging = await mkdtemp(join3(tmpdir(), "easysociable-slideshow-export-"));
33116
+ const staging = await mkdtemp(join4(tmpdir(), "easysociable-slideshow-export-"));
35301
33117
  try {
35302
33118
  const pages = [];
35303
33119
  for (const artifact of manifest.artifacts) {
@@ -35307,7 +33123,7 @@ async function exportSlideshowRun(client, runId, output) {
35307
33123
  throw new Error(`Artifact checksum mismatch for page ${artifact.pageIndex + 1}`);
35308
33124
  const role = artifact.role || `page${artifact.pageIndex}`;
35309
33125
  const fileName = `${String(artifact.pageIndex + 1).padStart(2, "0")}-${role}.png`;
35310
- await writeFile(join3(staging, fileName), bytes);
33126
+ await writeFile(join4(staging, fileName), bytes);
35311
33127
  pages.push({
35312
33128
  pageIndex: artifact.pageIndex,
35313
33129
  role,
@@ -35324,7 +33140,7 @@ async function exportSlideshowRun(client, runId, output) {
35324
33140
  deckJobId: manifest.deckJobId,
35325
33141
  pages
35326
33142
  };
35327
- await writeFile(join3(staging, "manifest.json"), `${JSON.stringify(localManifest, null, 2)}
33143
+ await writeFile(join4(staging, "manifest.json"), `${JSON.stringify(localManifest, null, 2)}
35328
33144
  `);
35329
33145
  await rm(output, { recursive: true, force: true });
35330
33146
  await rename2(staging, output);
@@ -35345,22 +33161,89 @@ function addCrudCommands(parent, resource, routes) {
35345
33161
  }
35346
33162
  }
35347
33163
  function buildV1Cli() {
35348
- const program2 = new Command().name("easysociable").description("EasySociable Gateway CLI for Template and Slideshow V1").version("0.0.0").option("--json", "Emit a JSON envelope");
35349
- jsonOption(program2.command("install").description("Install Skills and one MCP registration for detected Codex/Claude hosts").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
33164
+ const program = new Command().name("easysociable").description("EasySociable Gateway CLI for Template and Slideshow V1").version(readCliVersion()).option("--json", "Emit a JSON envelope");
33165
+ jsonOption(program.command("install").description("Install Skills and one MCP registration for detected Codex/Claude hosts").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
35350
33166
  const command = args.at(-1);
35351
33167
  const opts = command.opts();
35352
33168
  const plan = await planInstallation(opts);
35353
33169
  const result = opts.yes === true ? await applyInstallation(opts) : { ...plan, applied: false, next: "Review changes and re-run with --yes" };
35354
33170
  print(result, Boolean(opts.json));
35355
33171
  });
35356
- jsonOption(program2.command("update").description("Update installed Skills and MCP registration with backup").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
33172
+ jsonOption(program.command("update").description("Update installed Skills and MCP registration with backup").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
35357
33173
  const command = args.at(-1);
35358
33174
  const opts = command.opts();
35359
33175
  const plan = await planInstallation(opts);
35360
33176
  const result = opts.yes === true ? await applyInstallation(opts) : { ...plan, applied: false, next: "Review changes and re-run with --yes" };
35361
33177
  print(result, Boolean(opts.json));
35362
33178
  });
35363
- const auth = program2.command("auth").description("Manage the shared EasySociable credential");
33179
+ const engine = program.command("engine").description("Create and operate a local Content Engine + workbench");
33180
+ jsonOption(engine.command("detect").description("Find Content Engine folders under search roots")).action((...args) => {
33181
+ const command = args.at(-1);
33182
+ print({ action: "detect", engines: detectEngines() }, commandWantsJson(command));
33183
+ });
33184
+ jsonOption(engine.command("init").description("Scaffold Content Engine starter files (never overwrites existing)").option("--root <path>", "Parent directory or Content Engine path", defaultEngineRoot()).option("--yes", "Write missing starter files").option("--serve", "Also start the workbench server").option("--no-open", "Do not open a browser when starting the workbench")).action(async (...args) => {
33185
+ const command = args.at(-1);
33186
+ const opts = command.opts();
33187
+ const result = await initEngine(String(opts.root), CLI_MODULE_URL, {
33188
+ yes: opts.yes === true,
33189
+ noOpen: opts.noOpen === true,
33190
+ serve: opts.serve === true
33191
+ });
33192
+ print(result, commandWantsJson(command));
33193
+ if (opts.yes === true && (result.valid === false || result.code)) {
33194
+ const errors = result.errors;
33195
+ throw new Error(errors?.[0] ?? result.code ?? "engine init failed");
33196
+ }
33197
+ });
33198
+ jsonOption(engine.command("validate").description("Validate engine starter completeness or a run folder").option("--root <path>", "Parent directory or Content Engine path").option("--run <path>", "Run directory to validate").option("--require-pack", "Require pack-*.json on the run").option("--require-export", "Require export directory").option("--export <path>", "Export directory for --require-export")).action((...args) => {
33199
+ const command = args.at(-1);
33200
+ const opts = command.opts();
33201
+ if (opts.run) {
33202
+ const result = validateRun(CLI_MODULE_URL, {
33203
+ run: String(opts.run),
33204
+ requirePack: opts.requirePack === true,
33205
+ requireExport: opts.requireExport === true,
33206
+ exportDir: opts.export ? String(opts.export) : void 0,
33207
+ json: true
33208
+ });
33209
+ if (result.stdout)
33210
+ process.stdout.write(result.stdout.endsWith("\n") ? result.stdout : `${result.stdout}
33211
+ `);
33212
+ if (result.status !== 0)
33213
+ throw new Error(result.stderr.trim() || "engine validate --run failed");
33214
+ return;
33215
+ }
33216
+ if (!opts.root)
33217
+ throw new Error("Pass --root <path> or --run <path>.");
33218
+ const report = validateEngine(String(opts.root), CLI_MODULE_URL, { strict: true });
33219
+ print({ ...report, action: "validated" }, commandWantsJson(command));
33220
+ if (!report.valid)
33221
+ throw new Error(report.errors[0] ?? "engine validate failed");
33222
+ });
33223
+ jsonOption(engine.command("serve").description("Build and start the workbench on :8765").option("--engine <path>", "Content Engine path or parent", defaultEngineRoot()).option("--no-open", "Do not open a browser")).action(async (...args) => {
33224
+ const command = args.at(-1);
33225
+ const opts = command.opts();
33226
+ const enginePath = resolveEngine(String(opts.engine));
33227
+ ensureWorkbench(enginePath, CLI_MODULE_URL);
33228
+ const built = buildWorkbench(enginePath);
33229
+ if (!built.ok)
33230
+ throw new Error(built.message);
33231
+ const started = await startWorkbench(enginePath, CLI_MODULE_URL, { noOpen: opts.noOpen === true });
33232
+ print({ action: "serve", engine: enginePath, ...started }, commandWantsJson(command));
33233
+ if (!started.ok)
33234
+ throw new Error("message" in started ? String(started.message) : "engine serve failed");
33235
+ });
33236
+ jsonOption(engine.command("build").description("Rebuild workbench/index.html from markdown indexes").option("--engine <path>", "Content Engine path or parent", defaultEngineRoot())).action((...args) => {
33237
+ const command = args.at(-1);
33238
+ const opts = command.opts();
33239
+ const enginePath = resolveEngine(String(opts.engine));
33240
+ ensureWorkbench(enginePath, CLI_MODULE_URL);
33241
+ const built = buildWorkbench(enginePath);
33242
+ print({ action: "build", engine: enginePath, ...built }, commandWantsJson(command));
33243
+ if (!built.ok)
33244
+ throw new Error(built.message);
33245
+ });
33246
+ const auth = program.command("auth").description("Manage the shared EasySociable credential");
35364
33247
  jsonOption(auth.command("status").description("Show authentication status")).action(async (...args) => {
35365
33248
  const command = args.at(-1);
35366
33249
  const stored = readStoredCredentials();
@@ -35377,17 +33260,18 @@ function buildV1Cli() {
35377
33260
  await rm(credentialPath, { force: true });
35378
33261
  process.stdout.write("Removed the stored EasySociable credential.\n");
35379
33262
  });
35380
- addCrudCommands(program2.command("profiles"), "profiles", { list: "/v1/profiles", get: "/v1/profiles/:id", create: "/v1/profiles", update: "/v1/profiles/:id", archive: "/v1/profiles/:id/archive", restore: "/v1/profiles/:id/restore", delete: "/v1/profiles/:id" });
35381
- const themes = program2.command("themes").description("Manage Profile-owned Themes");
33263
+ addCrudCommands(program.command("brands").description("Manage workspace Brands (identity, fonts, colors, logo)"), "brands", { list: "/v1/brands", get: "/v1/brands/:id", create: "/v1/brands", update: "/v1/brands/:id", archive: "/v1/brands/:id/archive", restore: "/v1/brands/:id/restore", delete: "/v1/brands/:id" });
33264
+ addCrudCommands(program.command("profiles").description("Deprecated \u2014 use brands"), "profiles", { list: "/v1/profiles", get: "/v1/profiles/:id", create: "/v1/profiles", update: "/v1/profiles/:id", archive: "/v1/profiles/:id/archive", restore: "/v1/profiles/:id/restore", delete: "/v1/profiles/:id" });
33265
+ const themes = program.command("themes").description("Deprecated \u2014 use brands");
35382
33266
  addCrudCommands(themes, "themes", { list: "/v1/themes", get: "/v1/themes/:id", create: "/v1/themes", update: "/v1/themes/:id", archive: "/v1/themes/:id/archive", restore: "/v1/themes/:id/restore", delete: "/v1/themes/:id" });
35383
33267
  jsonOption(themes.command("set-default").requiredOption("--profile-id <profileId>").requiredOption("--theme-id <themeId>")).action(withClient(async (client, opts) => client.requestJson("POST", `/v1/profiles/${opts.profileId}/default-theme`, { themeId: opts.themeId })));
35384
- const images = program2.command("images").description("Manage account image assets");
33268
+ const images = program.command("images").description("Manage account image assets");
35385
33269
  addCrudCommands(images, "images", { list: "/v1/images", get: "/v1/images/:id", create: "/v1/images/imports", update: "/v1/images/:id", archive: "/v1/images/:id/archive", restore: "/v1/images/:id/restore", delete: "/v1/images/:id" });
35386
33270
  jsonOption(images.command("upload").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.requestJson("POST", "/v1/images/imports", JSON.parse(await readFile(String(opts.file), "utf8")))));
35387
33271
  jsonOption(images.command("import-url").requiredOption("--url <url>").option("--name <name>")).action(withClient(async (client, opts) => client.requestJson("POST", "/v1/images/imports", { sourceUrl: String(opts.url), ...opts.name ? { name: String(opts.name) } : {} })));
35388
33272
  jsonOption(images.command("search").requiredOption("--q <query>")).action(withClient(async (client, opts) => client.requestJson("GET", `/v1/images?q=${encodeURIComponent(String(opts.q))}`)));
35389
33273
  jsonOption(images.command("attest").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.requestJson("POST", `/v1/images/${opts.id}/attest`, { accepted: true })));
35390
- const templates = program2.command("templates").description("Create and manage Page Template drafts");
33274
+ const templates = program.command("templates").description("Create and manage Page Template drafts");
35391
33275
  jsonOption(templates.command("list")).action(withClient(async (client) => client.listTemplates()));
35392
33276
  jsonOption(templates.command("get").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getTemplate(String(opts.id))));
35393
33277
  jsonOption(templates.command("create-draft").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.createDraft(JSON.parse(await readFile(String(opts.file), "utf8")))));
@@ -35398,16 +33282,33 @@ function buildV1Cli() {
35398
33282
  jsonOption(templates.command("archive").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.archiveDraft(String(opts.id))));
35399
33283
  jsonOption(templates.command("restore").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.restoreDraft(String(opts.id))));
35400
33284
  jsonOption(templates.command("delete").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.deleteDraft(String(opts.id))));
35401
- const icons = program2.command("icons").description("Search the internal safe icon catalog");
33285
+ const families = templates.command("families").description("Layout Family (multi-platform template identity)");
33286
+ jsonOption(families.command("get").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getTemplateFamily(String(opts.id))));
33287
+ jsonOption(families.command("derive").requiredOption("--id <id>").option("--presets <list>", "Comma-separated presets e.g. 4:5,9:16")).action(withClient(async (client, opts) => {
33288
+ const presets = typeof opts.presets === "string" && opts.presets.trim() ? String(opts.presets).split(",").map((item) => item.trim()).filter(Boolean) : void 0;
33289
+ return client.deriveTemplateFamily(String(opts.id), { presets });
33290
+ }));
33291
+ jsonOption(families.command("migrate-legacy").description("Wrap pages missing familyId into single-variant families")).action(withClient(async (client) => client.migrateLegacyTemplateFamilies()));
33292
+ const icons = program.command("icons").description("Search the internal safe icon catalog");
35402
33293
  jsonOption(icons.command("search").requiredOption("--query <query>")).action(withClient(async (client, opts) => client.searchIcons({ query: String(opts.query) })));
35403
33294
  jsonOption(icons.command("get").requiredOption("--id <id>").requiredOption("--idempotency-key <key>")).action(withClient(async (client, opts) => client.getIcon({ iconId: String(opts.id), idempotencyKey: String(opts.idempotencyKey) })));
35404
- const slideshows = program2.command("slideshows").description("Create and render temporary Slideshow Runs");
35405
- jsonOption(slideshows.command("create").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.createSlideshowRun(JSON.parse(await readFile(String(opts.file), "utf8")))));
33295
+ const slideshows = program.command("slideshows").description("List, create, update and render Slideshow Runs");
33296
+ jsonOption(slideshows.command("list").option("--q <text>").option("--platform <platform>").option("--profile-id <id>").option("--content-slug <slug>").option("--status <status>")).action(withClient(async (client, opts) => client.listSlideshowRuns({
33297
+ q: opts.q ? String(opts.q) : void 0,
33298
+ platform: opts.platform ? String(opts.platform) : void 0,
33299
+ profileId: opts.profileId ? String(opts.profileId) : void 0,
33300
+ contentSlug: opts.contentSlug ? String(opts.contentSlug) : void 0,
33301
+ status: opts.status ? String(opts.status) : void 0
33302
+ })));
33303
+ jsonOption(slideshows.command("create").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.createSlideshowRun({ pack: JSON.parse(await readFile(String(opts.file), "utf8")) })));
35406
33304
  jsonOption(slideshows.command("get").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getSlideshowRun(String(opts.id))));
35407
33305
  jsonOption(slideshows.command("update").requiredOption("--id <id>").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.updateSlideshowRun(String(opts.id), JSON.parse(await readFile(String(opts.file), "utf8")))));
33306
+ jsonOption(slideshows.command("archive").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.archiveSlideshowRun(String(opts.id))));
33307
+ jsonOption(slideshows.command("restore").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.restoreSlideshowRun(String(opts.id))));
33308
+ jsonOption(slideshows.command("delete").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.trashSlideshowRun(String(opts.id))));
35408
33309
  jsonOption(slideshows.command("render").requiredOption("--id <id>").requiredOption("--idempotency-key <key>")).action(withClient(async (client, opts) => client.renderSlideshowRun(String(opts.id), { outputFormats: ["png"], idempotencyKey: String(opts.idempotencyKey) })));
35409
33310
  jsonOption(slideshows.command("export").requiredOption("--id <id>").requiredOption("--output <path>")).action(withClient(async (client, opts) => exportSlideshowRun(client, String(opts.id), String(opts.output))));
35410
- const renders = program2.command("renders").description("Inspect final render jobs");
33311
+ const renders = program.command("renders").description("Inspect final render jobs");
35411
33312
  jsonOption(renders.command("create-asset").requiredOption("--file <path>").requiredOption("--idempotency-key <key>")).action(withClient(async (client, opts) => {
35412
33313
  const fileName = String(opts.file);
35413
33314
  const bytes = await readFile(fileName);
@@ -35431,7 +33332,7 @@ function buildV1Cli() {
35431
33332
  jsonOption(renders.command("manifest").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getRenderManifest(String(opts.id))));
35432
33333
  jsonOption(renders.command("wait").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.pollRenderJob(String(opts.id))));
35433
33334
  jsonOption(renders.command("export").requiredOption("--id <id>").requiredOption("--output <path>")).action(withClient(async (client, opts) => exportManifest(client, String(opts.id), String(opts.output))));
35434
- const mcp = program2.command("mcp").description("Install and run the unified EasySociable MCP server");
33335
+ const mcp = program.command("mcp").description("Install and run the unified EasySociable MCP server");
35435
33336
  jsonOption(mcp.command("install").requiredOption("--host <host>", "codex, claude, hermes, or openclaw").option("--config-path <path>")).action((...args) => {
35436
33337
  const command = args.at(-1);
35437
33338
  const opts = command.opts();
@@ -35444,12 +33345,12 @@ function buildV1Cli() {
35444
33345
  const { serveUnifiedStdioMcp: serveUnifiedStdioMcp2 } = await Promise.resolve().then(() => (init_v1_mcp(), v1_mcp_exports));
35445
33346
  await serveUnifiedStdioMcp2(clientFromEnv());
35446
33347
  });
35447
- return program2;
33348
+ return program;
35448
33349
  }
35449
33350
  async function runV1Cli(argv = process.argv) {
35450
- const program2 = buildV1Cli();
33351
+ const program = buildV1Cli();
35451
33352
  try {
35452
- await program2.parseAsync(argv);
33353
+ await program.parseAsync(argv);
35453
33354
  return 0;
35454
33355
  } catch (error52) {
35455
33356
  process.stderr.write(`${error52 instanceof Error ? error52.message : String(error52)}