@atlaskit/ads-cli 0.8.1 → 0.9.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.
@@ -0,0 +1,303 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { lstatSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createErrorEnvelope } from '../envelope/create-error-envelope';
5
+ import { createSuccessEnvelope } from '../envelope/create-success-envelope';
6
+ import { writeHumanError } from '../output/write-human-error';
7
+ import { writeJsonEnvelope } from '../output/write-json-envelope';
8
+ import { ExitCode } from '../types';
9
+ import { CLI_ATLAS_INVOCATION } from './cli-metadata';
10
+ const SKILL_ENTRYPOINT = 'SKILL.md';
11
+ const SKILLS = [{
12
+ name: 'atlassian-design-system',
13
+ displayName: 'ADS',
14
+ relativePath: '.agents/skills/atlassian-design-system',
15
+ requiredFiles: [SKILL_ENTRYPOINT]
16
+ }, {
17
+ name: 'ui-styling-standard',
18
+ displayName: 'UI Styling Standard',
19
+ relativePath: '.agents/skills/ui-styling-standard',
20
+ requiredFiles: [SKILL_ENTRYPOINT]
21
+ }, {
22
+ name: 'a11y-foundation',
23
+ displayName: 'Accessibility Foundation',
24
+ relativePath: '.agents/skills/a11y-foundation',
25
+ requiredFiles: [SKILL_ENTRYPOINT]
26
+ }];
27
+ const GIT_MARKER = '.git';
28
+ const SKILLS_INSTALLER_PACKAGE = '@atlassian/skills';
29
+ const SKILLS_INSTALLER_UNAVAILABLE_REASON = 'skills-installer-unavailable';
30
+ const SKILLS_INSTALLER_UNAVAILABLE_ERROR_CODES = new Set(['EACCES', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ENOENT', 'ENOTFOUND', 'ETIMEDOUT']);
31
+ const defaultPathExists = target => {
32
+ try {
33
+ lstatSync(target);
34
+ return true;
35
+ } catch (error) {
36
+ if (error.code === 'ENOENT') {
37
+ return false;
38
+ }
39
+ throw error;
40
+ }
41
+ };
42
+ const defaultRunProcess = ({
43
+ command,
44
+ args,
45
+ cwd,
46
+ capture
47
+ }) => {
48
+ const result = spawnSync(command, args, {
49
+ cwd,
50
+ encoding: 'utf8',
51
+ stdio: capture ? 'pipe' : 'inherit'
52
+ });
53
+ return {
54
+ status: result.status,
55
+ stdout: typeof result.stdout === 'string' ? result.stdout : '',
56
+ stderr: typeof result.stderr === 'string' ? result.stderr : '',
57
+ error: result.error
58
+ };
59
+ };
60
+ const processFailureMessage = (result, fallback) => {
61
+ var _result$error;
62
+ const details = result.stderr.trim() || ((_result$error = result.error) === null || _result$error === void 0 ? void 0 : _result$error.message);
63
+ return details ? `${fallback}: ${details}` : fallback;
64
+ };
65
+ const isSkillsInstallerUnavailableFailure = result => {
66
+ var _result$error2, _result$error$message, _result$error3;
67
+ if (result.status === null || (_result$error2 = result.error) !== null && _result$error2 !== void 0 && _result$error2.code && SKILLS_INSTALLER_UNAVAILABLE_ERROR_CODES.has(result.error.code)) {
68
+ return true;
69
+ }
70
+ const details = `${result.stdout}\n${result.stderr}\n${(_result$error$message = (_result$error3 = result.error) === null || _result$error3 === void 0 ? void 0 : _result$error3.message) !== null && _result$error$message !== void 0 ? _result$error$message : ''}`.toLowerCase();
71
+ if (!details.trim()) {
72
+ return true;
73
+ }
74
+ return ['401 unauthorized', '403 forbidden', '404 not found', 'authentication required', 'could not resolve', 'e401', 'e403', 'e404', 'eneedauth', 'failed to fetch', 'network error', 'not in this registry', 'registry unavailable', 'unable to authenticate', 'unable to resolve'].some(message => details.includes(message));
75
+ };
76
+ const createNotInstalledSkillResults = reason => SKILLS.map(skillDefinition => ({
77
+ name: skillDefinition.name,
78
+ status: 'not-installed',
79
+ path: skillDefinition.relativePath,
80
+ reason
81
+ }));
82
+ const findRepositoryRoot = cwd => {
83
+ let current = path.resolve(cwd);
84
+ while (true) {
85
+ if (defaultPathExists(path.join(current, GIT_MARKER))) {
86
+ return current;
87
+ }
88
+ const parent = path.dirname(current);
89
+ if (parent === current) {
90
+ return undefined;
91
+ }
92
+ current = parent;
93
+ }
94
+ };
95
+ const writeUsageError = ({
96
+ message,
97
+ json,
98
+ writer
99
+ }) => {
100
+ if (json) {
101
+ writeJsonEnvelope({
102
+ envelope: createErrorEnvelope({
103
+ command: 'init',
104
+ code: 'USAGE_ERROR',
105
+ message
106
+ }),
107
+ writer
108
+ });
109
+ } else {
110
+ writeHumanError({
111
+ message,
112
+ writer
113
+ });
114
+ writer.err('Usage: init');
115
+ }
116
+ return ExitCode.UsageError;
117
+ };
118
+ const validateInput = input => {
119
+ if (input.positionals.length > 0) {
120
+ return '`init` does not accept positional arguments.';
121
+ }
122
+ const allowedFlags = new Set(['json']);
123
+ const unknownFlag = Object.keys(input.flags).find(flag => !allowedFlags.has(flag));
124
+ if (unknownFlag) {
125
+ return `Unknown flag "--${unknownFlag}".`;
126
+ }
127
+ return undefined;
128
+ };
129
+ export const runInitCommand = async ({
130
+ input,
131
+ json,
132
+ writer,
133
+ invocation,
134
+ cwd
135
+ }) => {
136
+ const usageError = validateInput(input);
137
+ if (usageError) {
138
+ return writeUsageError({
139
+ message: usageError,
140
+ json,
141
+ writer
142
+ });
143
+ }
144
+ const projectRoot = findRepositoryRoot(cwd);
145
+ const skills = [];
146
+ const repositorySetupErrors = [];
147
+ if (!projectRoot) {
148
+ skills.push(...createNotInstalledSkillResults('not-in-git-repository'));
149
+ if (!json) {
150
+ writer.out('– Repository-local skills not installed because the current directory is not in a Git repository');
151
+ }
152
+ } else {
153
+ const npxCommand = process.platform === 'win32' ? 'npx.cmd' : 'npx';
154
+ let skillsInstallerUnavailable = false;
155
+ const skillHumanOutput = [];
156
+ for (const skillDefinition of SKILLS) {
157
+ try {
158
+ const skillPath = path.join(projectRoot, skillDefinition.relativePath);
159
+ const skillEntrypoint = path.join(skillPath, SKILL_ENTRYPOINT);
160
+ const skillPathExists = defaultPathExists(skillPath);
161
+ const skillEntrypointExists = defaultPathExists(skillEntrypoint);
162
+ const isCurrent = skillDefinition.requiredFiles.every(requiredFile => defaultPathExists(path.join(skillPath, requiredFile)));
163
+ if (skillPathExists && !skillEntrypointExists) {
164
+ throw new Error(`Cannot install the ${skillDefinition.displayName} skill because ${skillDefinition.relativePath} already exists without a ${SKILL_ENTRYPOINT}. Move or remove it, then run init again.`);
165
+ }
166
+ let skillResult;
167
+ if (isCurrent) {
168
+ skillResult = {
169
+ name: skillDefinition.name,
170
+ status: 'already-installed',
171
+ path: skillDefinition.relativePath
172
+ };
173
+ } else {
174
+ const result = defaultRunProcess({
175
+ command: npxCommand,
176
+ args: ['--yes', SKILLS_INSTALLER_PACKAGE, 'add', skillDefinition.name, '--universal', '--yes'],
177
+ cwd: projectRoot,
178
+ capture: true
179
+ });
180
+ if (result.status !== 0) {
181
+ if (isSkillsInstallerUnavailableFailure(result)) {
182
+ skillsInstallerUnavailable = true;
183
+ break;
184
+ }
185
+ throw new Error(processFailureMessage(result, `Failed to install the ${skillDefinition.displayName} skill`));
186
+ }
187
+ const missingRequiredFile = skillDefinition.requiredFiles.find(requiredFile => !defaultPathExists(path.join(skillPath, requiredFile)));
188
+ if (missingRequiredFile) {
189
+ const missingRelativePath = `${skillDefinition.relativePath}/${missingRequiredFile}`;
190
+ throw new Error(`The skill installer completed without creating ${missingRelativePath}.`);
191
+ }
192
+ skillResult = {
193
+ name: skillDefinition.name,
194
+ status: skillEntrypointExists ? 'updated' : 'installed',
195
+ path: skillDefinition.relativePath
196
+ };
197
+ }
198
+ skills.push(skillResult);
199
+ if (!json) {
200
+ const statusMessage = skillResult.status === 'already-installed' ? 'already set up' : skillResult.status;
201
+ skillHumanOutput.push(`✓ ${skillDefinition.displayName} skill ${statusMessage} at ${skillDefinition.relativePath}`);
202
+ }
203
+ } catch (error) {
204
+ repositorySetupErrors.push(error instanceof Error ? error : new Error(`Failed to set up the ${skillDefinition.displayName} skill.`));
205
+ }
206
+ }
207
+ if (skillsInstallerUnavailable) {
208
+ const skillResultsByName = new Map(skills.map(skill => [skill.name, skill]));
209
+ skills.splice(0, skills.length, ...SKILLS.map(skillDefinition => {
210
+ var _skillResultsByName$g;
211
+ return (_skillResultsByName$g = skillResultsByName.get(skillDefinition.name)) !== null && _skillResultsByName$g !== void 0 ? _skillResultsByName$g : {
212
+ name: skillDefinition.name,
213
+ status: 'not-installed',
214
+ path: skillDefinition.relativePath,
215
+ reason: SKILLS_INSTALLER_UNAVAILABLE_REASON
216
+ };
217
+ }));
218
+ }
219
+ if (!json) {
220
+ for (const line of skillHumanOutput) {
221
+ writer.out(line);
222
+ }
223
+ if (skillsInstallerUnavailable) {
224
+ writer.out(skillHumanOutput.length > 0 ? '– Remaining repository-local skills skipped because @atlassian/skills is unavailable; npx @atlaskit/ads-cli remains available' : '– Repository-local skills skipped because @atlassian/skills is unavailable; npx @atlaskit/ads-cli remains available');
225
+ }
226
+ }
227
+ }
228
+ const atlasCwd = projectRoot !== null && projectRoot !== void 0 ? projectRoot : path.resolve(cwd);
229
+ let atlasPluginStatus;
230
+ if (invocation === CLI_ATLAS_INVOCATION) {
231
+ atlasPluginStatus = 'already-installed';
232
+ if (!json) {
233
+ writer.out('✓ Atlas CLI ADS plugin already available');
234
+ }
235
+ } else {
236
+ var _atlasCheck$error;
237
+ const atlasCheck = defaultRunProcess({
238
+ command: 'atlas',
239
+ args: ['ads', '--help'],
240
+ cwd: atlasCwd,
241
+ capture: true
242
+ });
243
+ if (atlasCheck.status === 0) {
244
+ atlasPluginStatus = 'already-installed';
245
+ if (!json) {
246
+ writer.out('✓ Atlas CLI ADS plugin already available');
247
+ }
248
+ } else if (((_atlasCheck$error = atlasCheck.error) === null || _atlasCheck$error === void 0 ? void 0 : _atlasCheck$error.code) === 'ENOENT') {
249
+ atlasPluginStatus = 'atlas-cli-unavailable';
250
+ if (!json) {
251
+ writer.out('– Atlas CLI is unavailable; use npx @atlaskit/ads-cli for ADS commands');
252
+ }
253
+ } else {
254
+ const installResult = defaultRunProcess({
255
+ command: 'atlas',
256
+ args: ['plugin', 'install', '--name', 'ads'],
257
+ cwd: atlasCwd,
258
+ capture: json
259
+ });
260
+ if (installResult.status !== 0) {
261
+ throw new Error(processFailureMessage(installResult, 'Failed to install the Atlas CLI ADS plugin. npx @atlaskit/ads-cli remains available'));
262
+ }
263
+ const verification = defaultRunProcess({
264
+ command: 'atlas',
265
+ args: ['ads', '--help'],
266
+ cwd: atlasCwd,
267
+ capture: true
268
+ });
269
+ if (verification.status !== 0) {
270
+ throw new Error('The Atlas CLI ADS plugin was installed but `atlas ads --help` did not succeed. npx @atlaskit/ads-cli remains available.');
271
+ }
272
+ atlasPluginStatus = 'installed';
273
+ if (!json) {
274
+ writer.out('✓ Atlas CLI ADS plugin installed');
275
+ }
276
+ }
277
+ }
278
+ if (repositorySetupErrors.length > 0) {
279
+ throw new Error(repositorySetupErrors.map(error => error.message).join('\n'));
280
+ }
281
+ if (skills.length !== SKILLS.length) {
282
+ throw new Error('Failed to determine the ADS repository setup result.');
283
+ }
284
+ const data = {
285
+ projectRoot: projectRoot !== null && projectRoot !== void 0 ? projectRoot : null,
286
+ skills,
287
+ atlas: {
288
+ status: atlasPluginStatus
289
+ }
290
+ };
291
+ if (json) {
292
+ writeJsonEnvelope({
293
+ envelope: createSuccessEnvelope({
294
+ envelopeType: 'init',
295
+ command: 'init',
296
+ data,
297
+ meta: {}
298
+ }),
299
+ writer
300
+ });
301
+ }
302
+ return ExitCode.Ok;
303
+ };
package/dist/esm/cli.js CHANGED
@@ -24,6 +24,7 @@ import { commands } from './commands/definitions';
24
24
  import { getCommand } from './commands/get-command';
25
25
  import { getVersion } from './commands/get-version';
26
26
  import { importToolHandler } from './commands/import-tool-handler';
27
+ import { runInitCommand } from './commands/init';
27
28
  import { runTool } from './commands/run-tool';
28
29
  import { createErrorEnvelope } from './envelope/create-error-envelope';
29
30
  import { createSuccessEnvelope } from './envelope/create-success-envelope';
@@ -65,6 +66,9 @@ var buildHelpText = function buildHelpText(invocation) {
65
66
  return " --".concat(flag.name).concat(aliases).padEnd(18) + flag.description;
66
67
  }).join('\n');
67
68
  var examples = [{
69
+ command: 'init',
70
+ comment: 'set up repository-local frontend skills and the Atlas plugin'
71
+ }, {
68
72
  command: 'search contrast',
69
73
  comment: 'unified: components, tokens, icons & docs'
70
74
  }, {
@@ -125,9 +129,21 @@ var runRegistryCommand = /*#__PURE__*/function () {
125
129
  while (1) switch (_context2.prev = _context2.next) {
126
130
  case 0:
127
131
  command = _ref3.command, input = _ref3.input, json = _ref3.json, writer = _ref3.writer, invocation = _ref3.invocation;
132
+ if (!(command.action === 'init')) {
133
+ _context2.next = 1;
134
+ break;
135
+ }
136
+ return _context2.abrupt("return", runInitCommand({
137
+ input: input,
138
+ json: json,
139
+ writer: writer,
140
+ invocation: invocation,
141
+ cwd: process.cwd()
142
+ }));
143
+ case 1:
128
144
  resolved = command.resolve(input); // A resolver returning `{ error }` indicates invalid input (a usage error).
129
145
  if (!('error' in resolved)) {
130
- _context2.next = 1;
146
+ _context2.next = 2;
131
147
  break;
132
148
  }
133
149
  if (json) {
@@ -147,9 +163,9 @@ var runRegistryCommand = /*#__PURE__*/function () {
147
163
  writer.err("Usage: ".concat(command.usage));
148
164
  }
149
165
  return _context2.abrupt("return", ExitCode.UsageError);
150
- case 1:
166
+ case 2:
151
167
  if (!('data' in resolved)) {
152
- _context2.next = 2;
168
+ _context2.next = 3;
153
169
  break;
154
170
  }
155
171
  return _context2.abrupt("return", renderSingleResult({
@@ -164,9 +180,9 @@ var runRegistryCommand = /*#__PURE__*/function () {
164
180
  writer: writer,
165
181
  invocation: invocation
166
182
  }));
167
- case 2:
183
+ case 3:
168
184
  if (!resolved.batch) {
169
- _context2.next = 3;
185
+ _context2.next = 4;
170
186
  break;
171
187
  }
172
188
  return _context2.abrupt("return", runBatchRequests({
@@ -176,8 +192,8 @@ var runRegistryCommand = /*#__PURE__*/function () {
176
192
  writer: writer,
177
193
  invocation: invocation
178
194
  }));
179
- case 3:
180
- _context2.next = 4;
195
+ case 4:
196
+ _context2.next = 5;
181
197
  return Promise.all(resolved.tools.map( /*#__PURE__*/function () {
182
198
  var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(tool) {
183
199
  var handler, _t, _t2;
@@ -212,10 +228,10 @@ var runRegistryCommand = /*#__PURE__*/function () {
212
228
  return _ref5.apply(this, arguments);
213
229
  };
214
230
  }()));
215
- case 4:
231
+ case 5:
216
232
  results = _context2.sent;
217
233
  if (!resolved.grouped) {
218
- _context2.next = 5;
234
+ _context2.next = 6;
219
235
  break;
220
236
  }
221
237
  return _context2.abrupt("return", renderGroupedResult({
@@ -227,7 +243,7 @@ var runRegistryCommand = /*#__PURE__*/function () {
227
243
  writer: writer,
228
244
  invocation: invocation
229
245
  }));
230
- case 5:
246
+ case 6:
231
247
  return _context2.abrupt("return", renderSingleResult({
232
248
  command: command,
233
249
  input: input,
@@ -237,7 +253,7 @@ var runRegistryCommand = /*#__PURE__*/function () {
237
253
  writer: writer,
238
254
  invocation: invocation
239
255
  }));
240
- case 6:
256
+ case 7:
241
257
  case "end":
242
258
  return _context2.stop();
243
259
  }
@@ -409,6 +425,7 @@ var createCapturedWriter = function createCapturedWriter() {
409
425
  */
410
426
  var runBatchChild = /*#__PURE__*/function () {
411
427
  var _ref0 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref9) {
428
+ var _getCommand;
412
429
  var request, invocation, parsed, response, captured;
413
430
  return _regeneratorRuntime.wrap(function (_context3) {
414
431
  while (1) switch (_context3.prev = _context3.next) {
@@ -424,7 +441,7 @@ var runBatchChild = /*#__PURE__*/function () {
424
441
  code: 'USAGE_ERROR',
425
442
  message: 'A batch request must start with a command name.'
426
443
  });
427
- _context3.next = 4;
444
+ _context3.next = 5;
428
445
  break;
429
446
  case 1:
430
447
  if (!(parsed.command === 'batch')) {
@@ -436,15 +453,27 @@ var runBatchChild = /*#__PURE__*/function () {
436
453
  code: 'USAGE_ERROR',
437
454
  message: 'Nested batch requests are not supported.'
438
455
  });
439
- _context3.next = 4;
456
+ _context3.next = 5;
440
457
  break;
441
458
  case 2:
459
+ if (!((_getCommand = getCommand(parsed.command)) !== null && _getCommand !== void 0 && _getCommand.action)) {
460
+ _context3.next = 3;
461
+ break;
462
+ }
463
+ response = createErrorEnvelope({
464
+ command: parsed.command,
465
+ code: 'USAGE_ERROR',
466
+ message: "Action command \"".concat(parsed.command, "\" cannot run inside batch.")
467
+ });
468
+ _context3.next = 5;
469
+ break;
470
+ case 3:
442
471
  captured = createCapturedWriter();
443
- _context3.next = 3;
472
+ _context3.next = 4;
444
473
  return run([].concat(_toConsumableArray(request.argv), ['--json']), captured, {
445
474
  invocation: invocation
446
475
  });
447
- case 3:
476
+ case 4:
448
477
  try {
449
478
  response = JSON.parse(captured.stdout.join('\n'));
450
479
  } catch (_unused) {
@@ -454,13 +483,13 @@ var runBatchChild = /*#__PURE__*/function () {
454
483
  message: 'The child command did not produce a valid JSON envelope.'
455
484
  });
456
485
  }
457
- case 4:
486
+ case 5:
458
487
  return _context3.abrupt("return", {
459
488
  request: request.argv,
460
489
  status: classifyBatchResponse(response),
461
490
  response: response
462
491
  });
463
- case 5:
492
+ case 6:
464
493
  case "end":
465
494
  return _context3.stop();
466
495
  }
@@ -47,6 +47,10 @@ var limitFlag = {
47
47
  alias: 'l',
48
48
  description: 'Maximum matches per term.'
49
49
  };
50
+ var searchLimitFlag = _objectSpread(_objectSpread({}, limitFlag), {}, {
51
+ default: 2,
52
+ description: 'Maximum matches per term, per result type (default: 2).'
53
+ });
50
54
 
51
55
  /**
52
56
  * Parse and validate the `--limit` flag.
@@ -566,8 +570,20 @@ var resolveBatch = function resolveBatch(input) {
566
570
  * The full set of CLI commands. Order here is the order shown by `manifest` and `--help`.
567
571
  */
568
572
  export var commands = [{
573
+ name: 'init',
574
+ action: 'init',
575
+ description: 'Set up the ADS, UI Styling Standard, and Accessibility Foundation skills at the Git repository root and install the Atlas CLI ADS plugin.',
576
+ usage: 'init',
577
+ arguments: [],
578
+ flags: [],
579
+ examples: ['init'],
580
+ responseTypes: ['ads-cli/init'],
581
+ envelopeType: function envelopeType() {
582
+ return 'init';
583
+ }
584
+ }, {
569
585
  name: 'search',
570
- description: 'Fuzzy-search ADS components, tokens, icons, and docs together (or narrow results with --type).',
586
+ description: 'Fuzzy-search ADS components, tokens, icons, and docs together (or narrow results with --type). Returns up to 2 matches per term, per result type by default; override with --limit.',
571
587
  usage: "search <query...> [--type ".concat(Object.keys(SEARCH_TYPE_VALUES).join('|'), "] [--limit N]"),
572
588
  arguments: [{
573
589
  name: 'query',
@@ -582,7 +598,7 @@ export var commands = [{
582
598
  alias: 't',
583
599
  choices: Object.keys(SEARCH_TYPE_VALUES),
584
600
  description: "Narrow the search to a single kind: ".concat(Object.keys(SEARCH_TYPE_VALUES).join(', '), ".")
585
- }, limitFlag],
601
+ }, searchLimitFlag],
586
602
  examples: ['search button', 'search space color --type token', 'search add --type icon --limit 5', 'search contrast --type docs'],
587
603
  responseTypes: ['ads-cli/search'].concat(_toConsumableArray(Object.values(searchKindTools).map(function (tool) {
588
604
  return "ads-cli/".concat(tool.envelopeType);