@atlaskit/ads-cli 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,9 @@ var _formatToken = require("../output/format-token");
23
23
  var _parseLintRuleRecords = require("../output/parse-lint-rule-records");
24
24
  var _buildManifest = require("./build-manifest");
25
25
  var _getVersion = require("./get-version");
26
+ var _normalizeBatchRequest = require("./normalize-batch-request");
27
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
28
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
26
29
  function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
27
30
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
28
31
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /**
@@ -468,6 +471,76 @@ var resolveUnifiedSearch = function resolveUnifiedSearch(input) {
468
471
  };
469
472
  };
470
473
 
474
+ /**
475
+ * Split a batch invocation into argv groups introduced by repeated `--command` flags. Canonical
476
+ * tokenized groups remain unchanged; a complete request in the first token is safely normalized
477
+ * to argv without evaluating shell strings.
478
+ */
479
+ var resolveBatch = function resolveBatch(input) {
480
+ var _input$rawArgs;
481
+ var rawArgs = (_input$rawArgs = input.rawArgs) !== null && _input$rawArgs !== void 0 ? _input$rawArgs : [];
482
+ var batchIndex = rawArgs.indexOf('batch');
483
+ var tokens = rawArgs.slice(batchIndex + 1).filter(function (token) {
484
+ return token !== '--json';
485
+ });
486
+ if (tokens.length === 0) {
487
+ return {
488
+ error: 'At least one command request is required.'
489
+ };
490
+ }
491
+ if (tokens[0] !== '--command') {
492
+ return {
493
+ error: 'Each batch request must start with `--command`.'
494
+ };
495
+ }
496
+ var requests = [];
497
+ // The leading `--command` is validated above, so every remaining token either closes the open
498
+ // request or appends to it. Seeding the accumulator here keeps it non-nullable, which is what
499
+ // lets the loop stay free of "no request open yet" checks.
500
+ var current = [];
501
+ var _iterator = _createForOfIteratorHelper(tokens.slice(1)),
502
+ _step;
503
+ try {
504
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
505
+ var token = _step.value;
506
+ if (token === '--command') {
507
+ if (current.length === 0) {
508
+ return {
509
+ error: '`--command` must be followed by a non-empty command request.'
510
+ };
511
+ }
512
+ var _normalized = (0, _normalizeBatchRequest.normalizeBatchRequest)(current);
513
+ if ('error' in _normalized) {
514
+ return _normalized;
515
+ }
516
+ requests.push(_normalized);
517
+ current = [];
518
+ continue;
519
+ }
520
+ current.push(token);
521
+ }
522
+ } catch (err) {
523
+ _iterator.e(err);
524
+ } finally {
525
+ _iterator.f();
526
+ }
527
+ if (current.length === 0) {
528
+ return {
529
+ error: '`--command` must be followed by a non-empty command request.'
530
+ };
531
+ }
532
+ var normalized = (0, _normalizeBatchRequest.normalizeBatchRequest)(current);
533
+ if ('error' in normalized) {
534
+ return normalized;
535
+ }
536
+ requests.push(normalized);
537
+ return {
538
+ tools: [],
539
+ batch: requests,
540
+ meta: {}
541
+ };
542
+ };
543
+
471
544
  /**
472
545
  * The full set of CLI commands. Order here is the order shown by `manifest` and `--help`.
473
546
  */
@@ -531,6 +604,22 @@ var commands = exports.commands = [{
531
604
  tool: searchKindTools[searchType]
532
605
  });
533
606
  }
607
+ }, {
608
+ name: 'batch',
609
+ description: 'Run multiple ADS CLI queries in one process. Tokenized child requests are canonical; complete-request strings are also accepted.',
610
+ usage: 'batch [--json] --command <command> [args...] [--command <command> [args...]]...',
611
+ arguments: [],
612
+ flags: [{
613
+ name: 'command',
614
+ type: 'string[]',
615
+ description: 'Canonical: a tokenized child command and its arguments. A complete quoted request is also accepted. Repeat once per child command.'
616
+ }],
617
+ examples: ['batch --command search button --type icon --command token space.200', 'batch --command "search button" --type icon --command "token space.200"', 'batch --json --command component Button --command docs spacing'],
618
+ responseTypes: ['ads-cli/batch'],
619
+ envelopeType: function envelopeType() {
620
+ return 'batch';
621
+ },
622
+ resolve: resolveBatch
534
623
  }, makeItemCommand({
535
624
  kind: 'components',
536
625
  name: 'component',
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.normalizeBatchRequest = void 0;
8
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
9
+ var _toArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toArray"));
10
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
11
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
12
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
13
+ /**
14
+ * Normalise one batch child request without involving a shell.
15
+ *
16
+ * The canonical form is already-tokenized argv, for example
17
+ * `['search', 'Grid', '--type', 'component']`. For compatibility with agent-generated commands,
18
+ * the first token may instead contain a complete request, for example `['search Grid', '--type',
19
+ * 'component']`. Only that first token is split; trailing tokens have already been tokenized by the
20
+ * caller and must remain unchanged so multi-word arguments keep their boundaries.
21
+ */
22
+
23
+ var shellSyntaxError = function shellSyntaxError(syntax) {
24
+ return {
25
+ error: "Shell syntax ".concat(syntax, " is not supported in batch requests. Pass child commands as argv only; pipes, redirects, expansion, and command substitution are not allowed.")
26
+ };
27
+ };
28
+
29
+ /**
30
+ * Reject syntax that would have special meaning to a shell even though this parser never invokes
31
+ * one. Failing closed gives callers an actionable error instead of accepting input that only looks
32
+ * safe because it currently remains an argv array.
33
+ */
34
+ var findShellSyntax = function findShellSyntax(value) {
35
+ var _value$match;
36
+ if (value.includes('$(')) {
37
+ return 'command substitution (`$(...)`)';
38
+ }
39
+ if (value.includes('`')) {
40
+ return 'command substitution (backticks)';
41
+ }
42
+ if (value.includes('$')) {
43
+ return 'environment expansion (`$`)';
44
+ }
45
+ if (/\r|\n/.test(value)) {
46
+ return 'a command separator (line break)';
47
+ }
48
+ if (value.includes('&&')) {
49
+ return 'the `&&` operator';
50
+ }
51
+ if (value.includes('||')) {
52
+ return 'the `||` operator';
53
+ }
54
+ var operator = (_value$match = value.match(/[|&;<>()]/)) === null || _value$match === void 0 ? void 0 : _value$match[0];
55
+ return operator ? "the `".concat(operator, "` operator") : null;
56
+ };
57
+
58
+ /**
59
+ * Split a complete child request into argv using quoting and escaping rules only. This is
60
+ * intentionally not a shell grammar: it performs no expansion, substitution, redirection, or
61
+ * operator evaluation.
62
+ */
63
+ var tokenizeCompleteRequest = function tokenizeCompleteRequest(value) {
64
+ var argv = [];
65
+ var current = '';
66
+ var quote = null;
67
+ var escaped = false;
68
+ var tokenStarted = false;
69
+ var _iterator = _createForOfIteratorHelper(value),
70
+ _step;
71
+ try {
72
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
73
+ var character = _step.value;
74
+ if (escaped) {
75
+ current += character;
76
+ escaped = false;
77
+ tokenStarted = true;
78
+ continue;
79
+ }
80
+ if (character === '\\') {
81
+ escaped = true;
82
+ tokenStarted = true;
83
+ continue;
84
+ }
85
+ if (quote !== null) {
86
+ if (character === quote) {
87
+ quote = null;
88
+ } else {
89
+ current += character;
90
+ }
91
+ continue;
92
+ }
93
+ if (character === "'" || character === '"') {
94
+ quote = character;
95
+ tokenStarted = true;
96
+ continue;
97
+ }
98
+ if (/\s/.test(character)) {
99
+ if (tokenStarted) {
100
+ argv.push(current);
101
+ current = '';
102
+ tokenStarted = false;
103
+ }
104
+ continue;
105
+ }
106
+ current += character;
107
+ tokenStarted = true;
108
+ }
109
+ } catch (err) {
110
+ _iterator.e(err);
111
+ } finally {
112
+ _iterator.f();
113
+ }
114
+ if (escaped) {
115
+ return {
116
+ error: 'Invalid complete batch request: it ends with an escape character.'
117
+ };
118
+ }
119
+ if (quote !== null) {
120
+ return {
121
+ error: "Invalid complete batch request: unterminated ".concat(quote, " quote.")
122
+ };
123
+ }
124
+ if (tokenStarted) {
125
+ argv.push(current);
126
+ }
127
+ if (argv.length === 0) {
128
+ return {
129
+ error: 'Invalid complete batch request: a command name is required.'
130
+ };
131
+ }
132
+ return {
133
+ argv: argv
134
+ };
135
+ };
136
+ var normalizeBatchRequest = exports.normalizeBatchRequest = function normalizeBatchRequest(argv) {
137
+ var _iterator2 = _createForOfIteratorHelper(argv),
138
+ _step2;
139
+ try {
140
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
141
+ var token = _step2.value;
142
+ var syntax = findShellSyntax(token);
143
+ if (syntax !== null) {
144
+ return shellSyntaxError(syntax);
145
+ }
146
+ }
147
+ } catch (err) {
148
+ _iterator2.e(err);
149
+ } finally {
150
+ _iterator2.f();
151
+ }
152
+ var _argv = (0, _toArray2.default)(argv),
153
+ first = _argv[0],
154
+ trailing = _arrayLikeToArray(_argv).slice(1);
155
+ if (first === undefined) {
156
+ return {
157
+ error: '`--command` must be followed by a non-empty command request.'
158
+ };
159
+ }
160
+
161
+ // A normal command name cannot contain whitespace, quotes, or escapes. Their presence in the
162
+ // first argv entry therefore identifies the complete-string compatibility form. Tokenized
163
+ // trailing entries are never re-split.
164
+ if (!/[\s'"\\]/.test(first)) {
165
+ return {
166
+ argv: (0, _toConsumableArray2.default)(argv)
167
+ };
168
+ }
169
+ var normalized = tokenizeCompleteRequest(first);
170
+ if ('error' in normalized) {
171
+ return normalized;
172
+ }
173
+ return {
174
+ argv: [].concat((0, _toConsumableArray2.default)(normalized.argv), (0, _toConsumableArray2.default)(trailing))
175
+ };
176
+ };
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.formatHumanResult = void 0;
8
+ var _chalk = _interopRequireDefault(require("chalk"));
9
+ /**
10
+ * Generic last-resort human formatting for a successful command result.
11
+ */
12
+
13
+ /**
14
+ * Render a successful result with the generic last-resort formatting, used when a command
15
+ * declares neither a compact result kind nor its own `formatHuman`.
16
+ *
17
+ * Structured data is pretty-printed as JSON (the underlying tools already return rich objects),
18
+ * while plain-string payloads such as guideline markdown are returned verbatim.
19
+ *
20
+ * Kept separate from the writer so callers that compose text rather than write it — notably
21
+ * `batch`, which concatenates one section per child — produce byte-identical output without
22
+ * duplicating these rules.
23
+ */
24
+ var formatHumanResult = exports.formatHumanResult = function formatHumanResult(_ref) {
25
+ var data = _ref.data;
26
+ if (typeof data === 'string') {
27
+ return data;
28
+ }
29
+ if (data === null || data === undefined) {
30
+ return _chalk.default.yellow('No results.');
31
+ }
32
+ return JSON.stringify(data, null, 2);
33
+ };
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
3
  Object.defineProperty(exports, "__esModule", {
5
4
  value: true
6
5
  });
7
6
  exports.writeHumanResult = void 0;
8
- var _chalk = _interopRequireDefault(require("chalk"));
7
+ var _formatHumanResult = require("./format-human-result");
9
8
  /**
10
9
  * Human-readable rendering of a successful command result.
11
10
  */
@@ -13,19 +12,18 @@ var _chalk = _interopRequireDefault(require("chalk"));
13
12
  /**
14
13
  * Emit a human-readable rendering of a successful result to stdout.
15
14
  *
16
- * Structured data is pretty-printed as JSON (the underlying tools already return rich
17
- * objects), while plain-string payloads such as guideline markdown are printed verbatim.
15
+ * An absent payload is a diagnostic rather than data, so it goes to stderr to keep stdout clean
16
+ * for piping.
18
17
  */
19
18
  var writeHumanResult = exports.writeHumanResult = function writeHumanResult(_ref) {
20
19
  var data = _ref.data,
21
20
  writer = _ref.writer;
22
- if (typeof data === 'string') {
23
- writer.out(data);
24
- return;
25
- }
21
+ var text = (0, _formatHumanResult.formatHumanResult)({
22
+ data: data
23
+ });
26
24
  if (data === null || data === undefined) {
27
- writer.err(_chalk.default.yellow('No results.'));
25
+ writer.err(text);
28
26
  return;
29
27
  }
30
- writer.out(JSON.stringify(data, null, 2));
28
+ writer.out(text);
31
29
  };
@@ -18,7 +18,9 @@ import { runTool } from './commands/run-tool';
18
18
  import { createErrorEnvelope } from './envelope/create-error-envelope';
19
19
  import { createSuccessEnvelope } from './envelope/create-success-envelope';
20
20
  import { createDocSearchResults } from './output/create-doc-search-results';
21
+ import { isDisambiguation } from './output/disambiguation';
21
22
  import { formatGroupedResults } from './output/format-grouped-results';
23
+ import { formatHumanResult } from './output/format-human-result';
22
24
  import { formatCompactResults } from './output/format-results';
23
25
  import { writeHumanError } from './output/write-human-error';
24
26
  import { writeHumanResult } from './output/write-human-result';
@@ -52,6 +54,12 @@ const buildHelpText = invocation => {
52
54
  const examples = [{
53
55
  command: 'search contrast',
54
56
  comment: 'unified: components, tokens, icons & docs'
57
+ }, {
58
+ command: 'batch --command search button --type icon --command token space.200',
59
+ comment: 'canonical tokenized batch form'
60
+ }, {
61
+ command: 'batch --command "search button" --type icon --command "token space.200"',
62
+ comment: 'complete-string compatibility form'
55
63
  }, {
56
64
  command: 'search button --type component'
57
65
  }, {
@@ -144,6 +152,18 @@ const runRegistryCommand = async ({
144
152
  });
145
153
  }
146
154
 
155
+ // Batch requests re-enter the same command registry in-process. Dynamic imports stay cached,
156
+ // requests run concurrently, and each child retains its normal envelope semantics.
157
+ if (resolved.batch) {
158
+ return runBatchRequests({
159
+ command,
160
+ requests: resolved.batch,
161
+ json,
162
+ writer,
163
+ invocation
164
+ });
165
+ }
166
+
147
167
  // Run every tool call the command resolved to. Single-tool commands have one; unified
148
168
  // commands (e.g. `search` with no `--type`) have several that run in parallel.
149
169
  const results = await Promise.all(resolved.tools.map(async tool => {
@@ -182,6 +202,36 @@ const runRegistryCommand = async ({
182
202
  });
183
203
  };
184
204
 
205
+ /**
206
+ * Render a command's already-transformed payload as human-readable text.
207
+ *
208
+ * Tried in order:
209
+ * 1. Compact per-row view when the command declares a result kind (search/list).
210
+ * 2. The command's own `formatHuman` renderer for rich single-object payloads
211
+ * (component docs, a11y/migration guides, lint-rule markdown).
212
+ *
213
+ * Returns `null` when neither step applies, leaving the caller to choose its own last-resort
214
+ * fallback. Shared by the single-command path and `batch` so the two cannot drift apart.
215
+ */
216
+ const formatCommandHuman = ({
217
+ command,
218
+ input,
219
+ data,
220
+ invocation
221
+ }) => {
222
+ var _command$resultKind, _ref, _command$formatHuman;
223
+ const resultKind = (_command$resultKind = command.resultKind) === null || _command$resultKind === void 0 ? void 0 : _command$resultKind.call(command, input);
224
+ const compact = resultKind ? formatCompactResults({
225
+ kind: resultKind,
226
+ data,
227
+ showFollowUp: command.name === 'search',
228
+ invocation
229
+ }) : null;
230
+ return (_ref = compact !== null && compact !== void 0 ? compact : (_command$formatHuman = command.formatHuman) === null || _command$formatHuman === void 0 ? void 0 : _command$formatHuman.call(command, data, {
231
+ invocation
232
+ })) !== null && _ref !== void 0 ? _ref : null;
233
+ };
234
+
185
235
  /**
186
236
  * Render a single-tool command result (the common case).
187
237
  */
@@ -194,7 +244,6 @@ const renderSingleResult = ({
194
244
  writer,
195
245
  invocation
196
246
  }) => {
197
- var _command$resultKind, _ref, _command$formatHuman;
198
247
  const {
199
248
  isError
200
249
  } = result;
@@ -262,22 +311,14 @@ const renderSingleResult = ({
262
311
  return ExitCode.Ok;
263
312
  }
264
313
 
265
- // Default (human) output, tried in order:
266
- // 1. Compact per-row view when the command declares a result kind (search/list).
267
- // 2. The command's own `formatHuman` renderer for rich single-object payloads
268
- // (component docs, a11y/migration guides, lint-rule markdown).
269
- // 3. The generic fallback: verbatim strings (e.g. foundations markdown) or pretty JSON.
270
- // Each step returns `null` to defer to the next, so a raw JSON dump is only ever a last resort.
271
- const resultKind = (_command$resultKind = command.resultKind) === null || _command$resultKind === void 0 ? void 0 : _command$resultKind.call(command, input);
272
- const compact = resultKind ? formatCompactResults({
273
- kind: resultKind,
314
+ // Default (human) output: the shared renderer, falling back to verbatim strings (e.g.
315
+ // foundations markdown) or pretty JSON so a raw dump is only ever a last resort.
316
+ const human = formatCommandHuman({
317
+ command,
318
+ input,
274
319
  data,
275
- showFollowUp: command.name === 'search',
276
- invocation
277
- }) : null;
278
- const human = (_ref = compact !== null && compact !== void 0 ? compact : (_command$formatHuman = command.formatHuman) === null || _command$formatHuman === void 0 ? void 0 : _command$formatHuman.call(command, data, {
279
320
  invocation
280
- })) !== null && _ref !== void 0 ? _ref : null;
321
+ });
281
322
  if (human !== null) {
282
323
  writer.out(human);
283
324
  } else {
@@ -288,6 +329,159 @@ const renderSingleResult = ({
288
329
  }
289
330
  return ExitCode.Ok;
290
331
  };
332
+ const classifyBatchResponse = response => {
333
+ if (!response.ok) {
334
+ return 'failure';
335
+ }
336
+ return isDisambiguation(response.data) ? 'ambiguous' : 'success';
337
+ };
338
+ const createCapturedWriter = () => {
339
+ const stdout = [];
340
+ const stderr = [];
341
+ return {
342
+ stdout,
343
+ stderr,
344
+ out: line => stdout.push(line),
345
+ err: line => stderr.push(line)
346
+ };
347
+ };
348
+
349
+ /**
350
+ * Execute one child argv through the normal CLI pipeline, forcing JSON so the parent can preserve
351
+ * the child's stable envelope without scraping human-readable output.
352
+ *
353
+ * There is deliberately no `--help`/`--version` guard here. Every child token is also a top-level
354
+ * token, so {@link run} already short-circuits the whole invocation to help/version text before a
355
+ * batch is ever resolved — a guard at this level would be unreachable.
356
+ */
357
+ const runBatchChild = async ({
358
+ request,
359
+ invocation
360
+ }) => {
361
+ const parsed = parseArgs(request.argv);
362
+ let response;
363
+ if (!parsed.command) {
364
+ response = createErrorEnvelope({
365
+ command: 'batch',
366
+ code: 'USAGE_ERROR',
367
+ message: 'A batch request must start with a command name.'
368
+ });
369
+ } else if (parsed.command === 'batch') {
370
+ response = createErrorEnvelope({
371
+ command: 'batch',
372
+ code: 'USAGE_ERROR',
373
+ message: 'Nested batch requests are not supported.'
374
+ });
375
+ } else {
376
+ const captured = createCapturedWriter();
377
+ await run([...request.argv, '--json'], captured, {
378
+ invocation
379
+ });
380
+ try {
381
+ response = JSON.parse(captured.stdout.join('\n'));
382
+ } catch {
383
+ response = createErrorEnvelope({
384
+ command: parsed.command,
385
+ code: 'RUNTIME_ERROR',
386
+ message: 'The child command did not produce a valid JSON envelope.'
387
+ });
388
+ }
389
+ }
390
+ return {
391
+ request: request.argv,
392
+ status: classifyBatchResponse(response),
393
+ response
394
+ };
395
+ };
396
+
397
+ /**
398
+ * Render an already-transformed child success envelope with the same human format as its command.
399
+ */
400
+ const formatBatchChildHuman = ({
401
+ item,
402
+ invocation
403
+ }) => {
404
+ if (!item.response.ok) {
405
+ return `Error: ${item.response.error.message}`;
406
+ }
407
+ const parsed = parseArgs(item.request);
408
+ const definition = parsed.command ? getCommand(parsed.command) : undefined;
409
+ if (!definition) {
410
+ return formatHumanResult({
411
+ data: item.response.data
412
+ });
413
+ }
414
+
415
+ // A unified search spans every kind, so it has no single result kind and needs the grouped
416
+ // formatter instead. This is the same condition `search`'s own resolver uses to choose the
417
+ // grouped path, so the two cannot disagree.
418
+ if (definition.name === 'search' && parsed.flags.type === undefined && typeof item.response.data === 'object' && item.response.data !== null) {
419
+ var _item$response$meta$c;
420
+ return formatGroupedResults({
421
+ groups: item.response.data,
422
+ totalCount: Number((_item$response$meta$c = item.response.meta.count) !== null && _item$response$meta$c !== void 0 ? _item$response$meta$c : 0),
423
+ invocation
424
+ });
425
+ }
426
+ const human = formatCommandHuman({
427
+ command: definition,
428
+ input: {
429
+ positionals: parsed.positionals,
430
+ flags: parsed.flags
431
+ },
432
+ data: item.response.data,
433
+ invocation
434
+ });
435
+ return human !== null && human !== void 0 ? human : formatHumanResult({
436
+ data: item.response.data
437
+ });
438
+ };
439
+
440
+ /**
441
+ * Execute heterogeneous registered commands concurrently in the current process and aggregate
442
+ * their existing envelopes. A valid batch exits zero even when individual child commands fail.
443
+ */
444
+ const runBatchRequests = async ({
445
+ command,
446
+ requests,
447
+ json,
448
+ writer,
449
+ invocation
450
+ }) => {
451
+ const items = await Promise.all(requests.map(request => runBatchChild({
452
+ request,
453
+ invocation
454
+ })));
455
+ const succeeded = items.filter(item => item.status === 'success').length;
456
+ const ambiguous = items.filter(item => item.status === 'ambiguous').length;
457
+ const failed = items.length - succeeded - ambiguous;
458
+ if (json) {
459
+ writeJsonEnvelope({
460
+ envelope: createSuccessEnvelope({
461
+ envelopeType: command.envelopeType({
462
+ positionals: [],
463
+ flags: {}
464
+ }),
465
+ command: command.name,
466
+ data: items,
467
+ meta: {
468
+ succeeded,
469
+ ambiguous,
470
+ failed
471
+ }
472
+ }),
473
+ writer
474
+ });
475
+ return ExitCode.Ok;
476
+ }
477
+ const summary = `Batch results: ${succeeded} succeeded, ${ambiguous} ambiguous, ${failed} failed`;
478
+ const sections = items.map(item => `Request: ${item.request.join(' ')}\n${formatBatchChildHuman({
479
+ item,
480
+ invocation
481
+ })}`);
482
+ writer.out([summary, ...sections].join('\n\n'));
483
+ return ExitCode.Ok;
484
+ };
291
485
 
292
486
  /**
293
487
  * Render a grouped (multi-tool) command result, e.g. unified `search`.
@@ -422,7 +616,8 @@ export const run = async (argv = process.argv.slice(2), writer = defaultWriter,
422
616
  command: definition,
423
617
  input: {
424
618
  positionals,
425
- flags
619
+ flags,
620
+ rawArgs: argv
426
621
  },
427
622
  json,
428
623
  writer,