@astryxdesign/cli 0.6.4-canary.f0355e3 → 0.6.5

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 (59) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +10 -6
  3. package/api/index.d.mts +2 -0
  4. package/api/index.mjs +2 -0
  5. package/api/json/index.ts +1 -0
  6. package/api/layout/_adapter.d.mts +34 -0
  7. package/api/layout/_adapter.mjs +148 -0
  8. package/api/layout/check/check.d.mts +16 -0
  9. package/api/layout/check/check.mjs +40 -0
  10. package/api/layout/expand/expand.d.mts +22 -0
  11. package/api/layout/expand/expand.mjs +155 -0
  12. package/api/layout/expand/expand.path-safety.test.mjs +53 -0
  13. package/api/layout/grammar/grammar.d.mts +13 -0
  14. package/api/layout/grammar/grammar.mjs +87 -0
  15. package/api/layout/layout.d.mts +6 -0
  16. package/api/layout/layout.mjs +17 -0
  17. package/api/layout/layout.test.mjs +297 -0
  18. package/api/layout/layout.type.d.mts +89 -0
  19. package/api/layout/layout.type.mjs +103 -0
  20. package/api/layout/layoutCheck.doc.d.mts +11 -0
  21. package/api/layout/layoutCheck.doc.mjs +85 -0
  22. package/api/layout/layoutExpand.doc.d.mts +11 -0
  23. package/api/layout/layoutExpand.doc.mjs +107 -0
  24. package/api/layout/layoutGrammar.doc.d.mts +11 -0
  25. package/api/layout/layoutGrammar.doc.mjs +57 -0
  26. package/api/template/template-integration.test.mjs +65 -1
  27. package/api/template/template.mjs +1 -1
  28. package/api/upgrade/run/run.mjs +1 -1
  29. package/authoring/config/config.doc.mjs +1 -1
  30. package/authoring/config/type.ts +2 -2
  31. package/authoring/doctypes/command/command.doc.mjs +1 -1
  32. package/authoring/doctypes/command/type.ts +1 -1
  33. package/clients/cli/command-result-coverage.test.mjs +7 -7
  34. package/clients/cli/commands/debug-result-summary.test.mjs +2 -2
  35. package/clients/cli/commands/layout-check.doc.mjs +65 -0
  36. package/clients/cli/commands/layout-expand.doc.mjs +83 -0
  37. package/clients/cli/commands/layout-grammar.doc.mjs +30 -0
  38. package/clients/cli/commands/layout.doc.mjs +34 -0
  39. package/clients/cli/commands/layout.error-codes.test.mjs +66 -0
  40. package/clients/cli/commands/layout.exit-parity.test.mjs +41 -0
  41. package/clients/cli/commands/layout.mjs +275 -0
  42. package/clients/cli/commands/layout.path-help.test.mjs +33 -0
  43. package/clients/cli/commands/layout.stdin-cap.test.mjs +47 -0
  44. package/clients/cli/commands/layout.text-fields.test.mjs +39 -0
  45. package/clients/cli/commands/text-json-parity.test.mjs +17 -0
  46. package/clients/cli/index.mjs +4 -0
  47. package/clients/cli/lib/exit-codes.test.mjs +8 -1
  48. package/clients/cli/lib/json-shim.test.mjs +20 -6
  49. package/clients/cli/lib/manifest.mjs +8 -0
  50. package/foundation/discovery/template-adapter.mjs +1 -1
  51. package/foundation/doc-compiler/doc-loads.test.mjs +12 -0
  52. package/foundation/response/response-types.doc.mjs +17 -0
  53. package/foundation/xle/browser.d.mts +3 -3
  54. package/foundation/xle/browser.mjs +3 -3
  55. package/foundation/xle/expand.mjs +2 -2
  56. package/foundation/xle/parse.mjs +1 -1
  57. package/foundation/xle/print.mjs +2 -2
  58. package/foundation/xle/splice.mjs +1 -1
  59. package/package.json +9 -9
@@ -0,0 +1,34 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file CommandDoc for the `astryx layout` command group. A parent group with no
5
+ * behavior of its own; it dispatches to the expand/check/grammar subcommands,
6
+ * which carry the actual args, flags, and wrapped functions.
7
+ * @position packages/cli/clients/cli/commands — command documentation
8
+ */
9
+
10
+ /** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
11
+ export const doc = {
12
+ type: 'command',
13
+ name: 'layout',
14
+ displayName: 'astryx layout',
15
+ namespace: 'cli/commands',
16
+ summary: 'Generate XDS layouts from compressed expressions (XLE/XLO)',
17
+ description:
18
+ 'The layout command group. Running astryx layout with no subcommand prints the ' +
19
+ 'subcommand list; the work happens in the subcommands: expand an expression into ' +
20
+ 'TSX (expand), validate one (check), or print the grammar cheatsheet (grammar).',
21
+ subcommands: ['expand', 'check', 'grammar'],
22
+ examples: [
23
+ {label: 'Print the grammar', cli: 'astryx layout grammar'},
24
+ {
25
+ label: 'Expand to TSX',
26
+ cli: "astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx",
27
+ },
28
+ ],
29
+ exitCodes: [
30
+ {code: 0, when: 'a subcommand succeeded, or --help'},
31
+ {code: 1, when: 'no subcommand (help is printed) or an unknown subcommand'},
32
+ ],
33
+ related: ['template', 'build'],
34
+ };
@@ -0,0 +1,66 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Error-code contract tests for the layout command wrapper. Locks the
5
+ * two foreseeable input errors to STABLE ERR_* codes (never ERR_UNKNOWN or a
6
+ * raw fs errno) and asserts --json/human exit parity:
7
+ * - empty expression → ERR_MISSING_ARGUMENT
8
+ * - --file <missing> → ERR_FILE_NOT_FOUND (not raw ENOENT), no stack leak
9
+ * Spawns the real binary so the bin error boundary is exercised faithfully.
10
+ */
11
+
12
+ import {describe, it, expect} from 'vitest';
13
+ import {spawnSync} from 'node:child_process';
14
+ import * as path from 'node:path';
15
+ import {fileURLToPath} from 'node:url';
16
+
17
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
+ const CLI_BIN = path.resolve(__dirname, '../bin/astryx.mjs');
19
+
20
+ function run(args) {
21
+ const res = spawnSync('node', [CLI_BIN, ...args], {
22
+ encoding: 'utf-8',
23
+ timeout: 20_000,
24
+ });
25
+ return {status: res.status, stdout: res.stdout || '', stderr: res.stderr || ''};
26
+ }
27
+
28
+ describe('layout --json error codes', () => {
29
+ for (const sub of ['expand', 'check']) {
30
+ it(`layout ${sub} "" → ERR_MISSING_ARGUMENT (not ERR_UNKNOWN)`, () => {
31
+ const r = run(['--json', 'layout', sub, '']);
32
+ expect(r.status).toBe(1);
33
+ const env = JSON.parse(r.stdout);
34
+ expect(env.code).toBe('ERR_MISSING_ARGUMENT');
35
+ expect(r.stderr).toBe('');
36
+ expect(r.stdout).not.toMatch(/\n\s+at /); // no stack frames
37
+ });
38
+
39
+ it(`layout ${sub} --file <missing> → ERR_FILE_NOT_FOUND (not ENOENT)`, () => {
40
+ const r = run([
41
+ '--json',
42
+ 'layout',
43
+ sub,
44
+ '--file',
45
+ '/tmp/definitely-missing-astryx-xyz.mjs',
46
+ ]);
47
+ expect(r.status).toBe(1);
48
+ const env = JSON.parse(r.stdout);
49
+ expect(env.code).toBe('ERR_FILE_NOT_FOUND');
50
+ expect(r.stderr).toBe('');
51
+ });
52
+
53
+ it(`layout ${sub}: --json and human agree on exit code (empty input)`, () => {
54
+ const human = run(['layout', sub, '']);
55
+ const json = run(['--json', 'layout', sub, '']);
56
+ expect(json.status).toBe(human.status);
57
+ expect(json.status).toBe(1);
58
+ });
59
+
60
+ it(`layout ${sub} --file <missing> in human mode leaks no stack trace`, () => {
61
+ const r = run(['layout', sub, '--file', '/tmp/definitely-missing-astryx-xyz.mjs']);
62
+ expect(r.status).toBe(1);
63
+ expect(r.stderr).not.toMatch(/\n\s+at /);
64
+ });
65
+ }
66
+ });
@@ -0,0 +1,41 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file CLI-level tests for `astryx layout check` exit-code parity.
5
+ *
6
+ * The exit code is the contract and must NOT depend on --json vs human mode:
7
+ * an invalid (but parseable) layout exits 1 in BOTH modes so `layout check`
8
+ * works as a CI gate / agent check without parsing stdout. Runs the real
9
+ * program in-process via the shared runCli harness.
10
+ */
11
+
12
+ import {describe, it, expect} from 'vitest';
13
+ import {runCli} from '../../../test-utils/run-cli.mjs';
14
+
15
+ const SLOW = 30_000;
16
+ // Parses fine, but references an unknown component -> data.valid: false
17
+ // (a semantic error, surfaced as data, not a thrown ERR_LAYOUT_PARSE).
18
+ const INVALID = 'ZzzUnknownComponent[foo=bar]';
19
+ const VALID = 'K';
20
+
21
+ describe('layout check — exit-code parity (--json vs human)', () => {
22
+ it('human mode exits 1 for an invalid (parseable) expression', async () => {
23
+ const {status} = await runCli(['layout', 'check', INVALID]);
24
+ expect(status).toBe(1);
25
+ }, SLOW);
26
+
27
+ it('--json exits 1 for the SAME invalid expression (modes agree)', async () => {
28
+ const {status, stdout} = await runCli(['layout', 'check', INVALID, '--json']);
29
+ const env = JSON.parse(stdout);
30
+ expect(env.type).toBe('layout.check');
31
+ expect(env.data.valid).toBe(false);
32
+ expect(status).toBe(1);
33
+ }, SLOW);
34
+
35
+ it('a valid expression exits 0 in both modes', async () => {
36
+ expect((await runCli(['layout', 'check', VALID])).status).toBe(0);
37
+ const {status, stdout} = await runCli(['layout', 'check', VALID, '--json']);
38
+ expect(JSON.parse(stdout).data.valid).toBe(true);
39
+ expect(status).toBe(0);
40
+ }, SLOW);
41
+ });
@@ -0,0 +1,275 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file layout command — thin CLI wrapper around api/layout.mjs.
5
+ *
6
+ * Subcommands:
7
+ * astryx layout expand "<expr>" [path] compressed expression → validated TSX
8
+ * astryx layout check "<expr>" validate + echo both canonical surfaces
9
+ * astryx layout grammar agent cheatsheet (alias table is branch-generated)
10
+ *
11
+ * The expression argument may also come from --file or stdin (`-`),
12
+ * which is how multi-line outline (XLO) input usually arrives.
13
+ *
14
+ * The command surface (group + subcommand descriptions, args, flags) is sourced
15
+ * from the colocated CommandDocs via `defineCommand`; this file supplies only the
16
+ * actions.
17
+ */
18
+
19
+ import * as fs from 'node:fs';
20
+ import * as path from 'node:path';
21
+ import {jsonOut} from '../../../foundation/response/json.mjs';
22
+ import {emit, section, text, list, record, code, WARN} from '../formatters/index.mjs';
23
+ import {cliError} from '../lib/cli-error.mjs';
24
+ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
25
+ import {layoutExpand, layoutCheck, layoutGrammar} from '../../../api/layout/layout.mjs';
26
+ import {defineCommand} from '../lib/define-command.mjs';
27
+ import {doc as layoutGroup} from './layout.doc.mjs';
28
+ import {doc as layoutExpandCommand} from './layout-expand.doc.mjs';
29
+ import {doc as layoutCheckCommand} from './layout-check.doc.mjs';
30
+ import {doc as layoutGrammarCommand} from './layout-grammar.doc.mjs';
31
+ import {doc as layoutExpandFn} from '../../../api/layout/layoutExpand.doc.mjs';
32
+ import {doc as layoutCheckFn} from '../../../api/layout/layoutCheck.doc.mjs';
33
+ import {doc as layoutGrammarFn} from '../../../api/layout/layoutGrammar.doc.mjs';
34
+ import {NO_RESULT_SET, resultSet} from '../../../foundation/debug/index.mjs';
35
+
36
+ /**
37
+ * The api layer's @returns for these functions widen the `type` discriminator
38
+ * to `string`, so annotate the command-local result with the precise response
39
+ * shapes from the colocated api/layout/layout.type.mjs so narrowing + jsonOut
40
+ * typecheck.
41
+ *
42
+ * @typedef {import('../../../api/layout/layout.type.mjs').LayoutExpandResponse} LayoutExpandResponse
43
+ * @typedef {import('../../../api/layout/layout.type.mjs').LayoutCheckResponse} LayoutCheckResponse
44
+ * @typedef {import('../../../api/layout/layout.type.mjs').LayoutGrammarResponse} LayoutGrammarResponse
45
+ */
46
+
47
+ /**
48
+ * @typedef {object} LayoutExpandOptions
49
+ * @property {string} [file]
50
+ * @property {'compact'|'outline'|'auto'} [form]
51
+ * @property {string} [name]
52
+ * @property {boolean} [loose]
53
+ */
54
+
55
+ /**
56
+ * @typedef {object} LayoutCheckOptions
57
+ * @property {string} [file]
58
+ * @property {'compact'|'outline'|'auto'} [form]
59
+ * @property {boolean} [loose]
60
+ */
61
+
62
+ /** The largest layout expression read from --file or stdin. */
63
+ const MAX_EXPRESSION_BYTES = 5 * 1024 * 1024; // 5 MB
64
+
65
+ /**
66
+ * Resolve the expression from arg, --file, or stdin ('-').
67
+ * @param {string} [expr]
68
+ * @param {{file?: string}} [options]
69
+ * @returns {Promise<string>}
70
+ */
71
+ async function readExpression(expr, options = {}) {
72
+ if (options.file) {
73
+ // Validate the file exists + is a regular file + is reasonably sized.
74
+ // We intentionally do NOT confine the read path (the user running the CLI
75
+ // controls --file; this is a read, not a write). The size cap prevents OOM
76
+ // from infinite streams like /dev/zero.
77
+ const filePath = path.resolve(process.cwd(), options.file);
78
+ const stat = fs.statSync(filePath, {throwIfNoEntry: false});
79
+ if (!stat || !stat.isFile()) {
80
+ cliError(`File not found: ${options.file}`, {
81
+ code: ERROR_CODES.ERR_FILE_NOT_FOUND,
82
+ });
83
+ }
84
+ if (stat.size > MAX_EXPRESSION_BYTES) {
85
+ cliError(
86
+ `File "${options.file}" is too large (${(stat.size / 1024 / 1024).toFixed(1)} MB, max 5 MB)`,
87
+ {code: ERROR_CODES.ERR_FILE_NOT_FOUND},
88
+ );
89
+ }
90
+ try {
91
+ return fs.readFileSync(filePath, 'utf-8');
92
+ } catch (e) {
93
+ const errno = /** @type {NodeJS.ErrnoException} */ (e);
94
+ if (errno && errno.code === 'ENOENT') {
95
+ // A --file pointing at a missing file is foreseeable — surface a
96
+ // stable code, not the raw ENOENT errno (and no stack in human mode).
97
+ cliError(`File not found: ${options.file}`, {
98
+ code: ERROR_CODES.ERR_FILE_NOT_FOUND,
99
+ });
100
+ }
101
+ throw e;
102
+ }
103
+ }
104
+ if (expr === '-') {
105
+ // Capped like --file: an endless stream must not be buffered whole.
106
+ /** @type {Buffer[]} */
107
+ const chunks = [];
108
+ let size = 0;
109
+ for await (const chunk of process.stdin) {
110
+ size += /** @type {Buffer} */ (chunk).length;
111
+ if (size > MAX_EXPRESSION_BYTES) {
112
+ cliError('The layout expression on stdin is too large (max 5 MB)', {
113
+ code: ERROR_CODES.ERR_INVALID_ARGUMENT,
114
+ });
115
+ }
116
+ chunks.push(/** @type {Buffer} */ (chunk));
117
+ }
118
+ return Buffer.concat(chunks).toString('utf-8');
119
+ }
120
+ return expr ?? '';
121
+ }
122
+
123
+ /**
124
+ * @param {import('commander').Command} program
125
+ */
126
+ export function registerLayout(program) {
127
+ const layoutCmd = defineCommand(program, layoutGroup);
128
+
129
+ defineCommand(layoutCmd, layoutExpandCommand, {
130
+ fn: layoutExpandFn,
131
+ action: async (/** @type {string} */ expression, /** @type {string} */ targetPath, /** @type {LayoutExpandOptions} */ options) => {
132
+ const json = program.opts().json || false;
133
+ const source = await readExpression(expression, options);
134
+ if (!source || source.trim() === '') {
135
+ return cliError(
136
+ 'No layout expression given — pass it as an argument, via --file, or on stdin',
137
+ {code: ERROR_CODES.ERR_MISSING_ARGUMENT},
138
+ );
139
+ }
140
+ /** @type {LayoutExpandResponse} */
141
+ let result;
142
+ try {
143
+ result = /** @type {LayoutExpandResponse} */ (await layoutExpand(source, {
144
+ targetPath,
145
+ form: options.form,
146
+ loose: options.loose || false,
147
+ name: options.name,
148
+ cwd: process.cwd(),
149
+ }));
150
+ } catch (e) {
151
+ const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
152
+ return cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
153
+ }
154
+ // Expanding turns an expression into TSX — a transformation, not a
155
+ // lookup. What it produced is in the output; there is no set to count.
156
+ if (json) {
157
+ jsonOut(result);
158
+ return NO_RESULT_SET;
159
+ }
160
+
161
+ /** @type {import('../formatters/index.mjs').Block[]} */
162
+ const out = [];
163
+ if (result.data.warnings.length > 0) {
164
+ out.push(text(result.data.warnings.map(w => `${WARN} ${w}`).join('\n')));
165
+ }
166
+ if (result.data.written) {
167
+ out.push(
168
+ text(`[ok] Expanded to ${result.data.written}`),
169
+ // Field names are the JSON keys; todos are summarised, not listed.
170
+ record(
171
+ {componentsUsed: result.data.componentsUsed, todos: result.data.todos},
172
+ {
173
+ format: {
174
+ todos: (/** @type {string[]} */ todos) =>
175
+ `${todos.length} (search for "TODO(xle)")`,
176
+ },
177
+ },
178
+ ),
179
+ );
180
+ } else {
181
+ // Raw expanded TSX (no target path) — preformatted, emitted verbatim.
182
+ out.push(code(result.data.code));
183
+ }
184
+ emit(...out);
185
+ return NO_RESULT_SET;
186
+ },
187
+ });
188
+
189
+ defineCommand(layoutCmd, layoutCheckCommand, {
190
+ fn: layoutCheckFn,
191
+ action: async (/** @type {string} */ expression, /** @type {LayoutCheckOptions} */ options) => {
192
+ const json = program.opts().json || false;
193
+ const source = await readExpression(expression, options);
194
+ if (!source || source.trim() === '') {
195
+ return cliError(
196
+ 'No layout expression given — pass it as an argument, via --file, or on stdin',
197
+ {code: ERROR_CODES.ERR_MISSING_ARGUMENT},
198
+ );
199
+ }
200
+ /** @type {LayoutCheckResponse} */
201
+ let result;
202
+ try {
203
+ result = /** @type {LayoutCheckResponse} */ (await layoutCheck(source, {
204
+ form: options.form,
205
+ loose: options.loose || false,
206
+ cwd: process.cwd(),
207
+ }));
208
+ } catch (e) {
209
+ const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
210
+ return cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
211
+ }
212
+ // Exit code is the contract and must NOT depend on --json vs human: an
213
+ // invalid (but parseable) layout exits 1 in BOTH modes so `layout check`
214
+ // works as a CI gate / agent check without parsing stdout. Decide it
215
+ // before the JSON return (parity with doctor integration validate).
216
+ if (!result.data.valid) process.exitCode = 1;
217
+
218
+ // A verdict on one expression: valid or not, with the errors that made
219
+ // it so. Nothing was looked up.
220
+ if (json) {
221
+ jsonOut(result);
222
+ return NO_RESULT_SET;
223
+ }
224
+
225
+ const {valid, form, errors, warnings, compact, outline} = result.data;
226
+ if (!valid) {
227
+ // Each error: the formatted issue, with a hanging "did you mean" line.
228
+ const items = errors.map(e =>
229
+ e.suggestions && e.suggestions.length > 0
230
+ ? [e.formatted, `did you mean: ${e.suggestions.join(', ')}?`]
231
+ : [e.formatted],
232
+ );
233
+ emit(
234
+ text(`[fail] Invalid (${errors.length} error${errors.length === 1 ? '' : 's'}):`),
235
+ list(items),
236
+ );
237
+ return NO_RESULT_SET;
238
+ }
239
+
240
+ /** @type {import('../formatters/index.mjs').Block[]} */
241
+ const out = [text(`[ok] Valid (parsed as ${form})`)];
242
+ if (warnings.length > 0) {
243
+ out.push(text(warnings.map(w => `${WARN} ${w}`).join('\n')));
244
+ }
245
+ // The canonical compact/outline surfaces are preformatted — emit verbatim.
246
+ out.push(section('compact'), code(compact), section('outline'), code(outline));
247
+ emit(...out);
248
+ return NO_RESULT_SET;
249
+ },
250
+ });
251
+
252
+ defineCommand(layoutCmd, layoutGrammarCommand, {
253
+ fn: layoutGrammarFn,
254
+ action: async () => {
255
+ const json = program.opts().json || false;
256
+ /** @type {LayoutGrammarResponse} */
257
+ let result;
258
+ try {
259
+ result = /** @type {LayoutGrammarResponse} */ (await layoutGrammar({cwd: process.cwd()}));
260
+ } catch (e) {
261
+ const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
262
+ return cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
263
+ }
264
+ // One document, the same one every time: the grammar cheatsheet.
265
+ const answered = resultSet({count: 1, resultKind: 'doc'});
266
+ if (json) {
267
+ jsonOut(result);
268
+ return answered;
269
+ }
270
+ // The cheatsheet is a preformatted document — emit verbatim.
271
+ emit(code(result.data.text));
272
+ return answered;
273
+ },
274
+ });
275
+ }
@@ -0,0 +1,33 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `layout expand` and `layout check` document their input modes (the
5
+ * argument, `-` for stdin, --file) and where `layout expand` writes.
6
+ */
7
+
8
+ import {describe, it, expect} from 'vitest';
9
+ import {runCli} from '../../../test-utils/run-cli.mjs';
10
+ import {isFilePathArg} from '../../../foundation/fs/path-safety.mjs';
11
+
12
+ const SLOW = 30_000;
13
+
14
+ describe('layout argument behavior is documented', () => {
15
+ it('layout expand help covers stdin, --file precedence and the output path rule', async () => {
16
+ const {status, stdout} = await runCli(['layout', 'expand', '--help']);
17
+ expect(status).toBe(0);
18
+ expect(stdout).toMatch(/Pass - to read it from stdin/);
19
+ expect(stdout).toMatch(/instead of the argument/);
20
+ expect(stdout).toContain('<Name>.tsx');
21
+ expect(stdout).toMatch(/existing file there is replaced/);
22
+ const exts = [...(stdout.match(/ends in ([.\w, ]+ or \.\w+)/)?.[1] ?? '').matchAll(/\.\w+/g)];
23
+ expect(exts.length).toBeGreaterThan(0);
24
+ for (const [ext] of exts) expect(isFilePathArg(`src/Page${ext}`)).toBe(true);
25
+ }, SLOW);
26
+
27
+ it('layout check help covers stdin and --file precedence', async () => {
28
+ const {status, stdout} = await runCli(['layout', 'check', '--help']);
29
+ expect(status).toBe(0);
30
+ expect(stdout).toMatch(/Pass - to read it from stdin/);
31
+ expect(stdout).toMatch(/instead of the argument/);
32
+ }, SLOW);
33
+ });
@@ -0,0 +1,47 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `layout check -` reads the expression from stdin under the same 5 MB
5
+ * cap as --file, instead of buffering whatever the pipe delivers. Spawns the
6
+ * real bin, since the in-process harness has no stdin.
7
+ */
8
+
9
+ import {describe, it, expect} from 'vitest';
10
+ import {spawnSync} from 'node:child_process';
11
+ import * as path from 'node:path';
12
+ import {fileURLToPath} from 'node:url';
13
+
14
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
15
+ const BIN = path.resolve(HERE, '../bin/astryx.mjs');
16
+ // Run against the monorepo root so @astryxdesign/core is discoverable.
17
+ const REPO = path.resolve(HERE, '../../../..');
18
+ const SLOW = 60_000;
19
+
20
+ /** @param {string} input @param {string[]} [extra] */
21
+ function checkFromStdin(input, extra = []) {
22
+ return spawnSync(process.execPath, [BIN, 'layout', 'check', '-', ...extra], {
23
+ cwd: REPO,
24
+ input,
25
+ encoding: 'utf-8',
26
+ maxBuffer: 16 * 1024 * 1024,
27
+ });
28
+ }
29
+
30
+ describe('layout check - (stdin)', () => {
31
+ it('refuses more than 5 MB with ERR_INVALID_ARGUMENT, in both modes', () => {
32
+ // Valid once trimmed, so only the cap can reject it.
33
+ const big = ' '.repeat(5 * 1024 * 1024 + 1) + 'V';
34
+ const json = checkFromStdin(big, ['--json']);
35
+ expect(json.status).toBe(1);
36
+ expect(JSON.parse(json.stdout).code).toBe('ERR_INVALID_ARGUMENT');
37
+ const human = checkFromStdin(big);
38
+ expect(human.status).toBe(1);
39
+ expect(human.stderr + human.stdout).toMatch(/too large/);
40
+ }, SLOW);
41
+
42
+ it('still reads a normal expression', () => {
43
+ const r = checkFromStdin('V > B', ['--json']);
44
+ expect(r.status).toBe(0);
45
+ expect(JSON.parse(r.stdout).data.valid).toBe(true);
46
+ }, SLOW);
47
+ });
@@ -0,0 +1,39 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `layout expand` text output names its fields after the JSON keys, so
5
+ * the two views stay greppable against each other.
6
+ */
7
+
8
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
9
+ import * as fs from 'node:fs';
10
+ import * as path from 'node:path';
11
+ import {runCli} from '../../../test-utils/run-cli.mjs';
12
+
13
+ const SLOW = 60_000;
14
+
15
+ describe('layout expand text fields mirror the JSON keys', () => {
16
+ let cwd;
17
+ beforeEach(() => {
18
+ // Inside the workspace so @astryxdesign/core resolves.
19
+ cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-text-fields-'));
20
+ });
21
+ afterEach(() => fs.rmSync(cwd, {recursive: true, force: true}));
22
+
23
+ it('labels every record field with a key of the layout.expand data', async () => {
24
+ const expr = 'V > B + {not-a-real-block}';
25
+ const json = await runCli(['layout', 'expand', expr, './a', '--loose', '--json'], cwd);
26
+ expect(json.status).toBe(0);
27
+ const {data} = JSON.parse(json.stdout);
28
+ expect(data.todos.length).toBeGreaterThan(0);
29
+
30
+ const human = await runCli(['layout', 'expand', expr, './b', '--loose'], cwd);
31
+ expect(human.status).toBe(0);
32
+ const fields = human.stdout
33
+ .split('\n')
34
+ .map(line => /^([A-Za-z]+):\s/.exec(line)?.[1])
35
+ .filter(Boolean);
36
+ expect(fields).toEqual(['componentsUsed', 'todos']);
37
+ for (const field of fields) expect(Object.keys(data)).toContain(field);
38
+ }, SLOW);
39
+ });
@@ -383,6 +383,23 @@ const CASES = [
383
383
  args: ['integration', 'pack', '--check'],
384
384
  skipFieldChecks: true,
385
385
  },
386
+ // ── Layout command: remove these cases when the layout command is deleted ──
387
+ {
388
+ name: 'layout check',
389
+ args: ['layout', 'check', 'Button'],
390
+ skipFieldChecks: true,
391
+ },
392
+ {
393
+ name: 'layout expand',
394
+ args: ['layout', 'expand', 'Button'],
395
+ skipFieldChecks: true,
396
+ },
397
+ {
398
+ name: 'layout grammar',
399
+ args: ['layout', 'grammar'],
400
+ skipFieldChecks: true,
401
+ },
402
+ // ── End layout cases ──
386
403
  {
387
404
  name: 'manifest',
388
405
  args: ['manifest'],
@@ -104,6 +104,9 @@ export const JSON_SUPPORTED = new Set([
104
104
  'doctor integration templates',
105
105
  'doctor integration components',
106
106
  'doctor integration docs',
107
+ 'layout expand',
108
+ 'layout check',
109
+ 'layout grammar',
107
110
  ]);
108
111
 
109
112
  /**
@@ -262,6 +265,7 @@ const commands = [
262
265
  {name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},
263
266
  // agent-docs folded into init — functions still importable from agent-docs.mjs
264
267
  {name: 'template', path: './commands/template.mjs', register: 'registerTemplate'},
268
+ {name: 'layout', path: './commands/layout.mjs', register: 'registerLayout'},
265
269
  {name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},
266
270
  {name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},
267
271
  {name: 'integration', path: './commands/integration.mjs', register: 'registerIntegration'},
@@ -34,7 +34,7 @@ manifest.commands.forEach(walk);
34
34
 
35
35
  describe('command exit codes', () => {
36
36
  it('every CommandDoc documents its exit codes', () => {
37
- expect(commandDocs.length).toBeGreaterThan(25);
37
+ expect(commandDocs.length).toBeGreaterThan(30);
38
38
  for (const doc of commandDocs) {
39
39
  expect(doc.exitCodes?.length, doc.name).toBeGreaterThan(0);
40
40
  }
@@ -70,6 +70,13 @@ describe('command exit codes', () => {
70
70
  },
71
71
  );
72
72
 
73
+ it('bare `astryx layout` exits 1 in both modes, as documented', async () => {
74
+ const doc = commandDocs.find((d) => d.name === 'layout');
75
+ expect(doc.exitCodes.find((e) => e.code === 1)?.when).toMatch(/^no subcommand/);
76
+ expect((await runCli(['layout'])).status).toBe(1);
77
+ expect((await runCli(['layout', '--json'])).status).toBe(1);
78
+ });
79
+
73
80
  it('`astryx discover` with a blank query exits 1 only when packages are discovered', async () => {
74
81
  const doc = commandDocs.find((d) => d.name === 'discover');
75
82
  expect(doc.exitCodes.find((e) => e.code === 1)?.when).toMatch(/blank query when packages are discovered/);
@@ -225,6 +225,23 @@ describe('--json shim: help shown for a failed invocation is an error envelope',
225
225
  expect(parsed.error).toMatch(/bogus/);
226
226
  });
227
227
 
228
+ it('astryx layout --json (group, no subcommand) emits ERR_MISSING_ARGUMENT, exit 1', async () => {
229
+ const {status, stdout, stderr} = await runCli(['layout', '--json']);
230
+ expect(status).toBe(1);
231
+ expect(stderr).toBe('');
232
+ const parsed = parseJson(stdout);
233
+ expect(parsed).not.toHaveProperty('type');
234
+ expect(parsed.code).toBe('ERR_MISSING_ARGUMENT');
235
+ expect(parsed.suggestions.map((s) => s.name)).toContain('layout expand');
236
+ });
237
+
238
+ it('astryx layout (no --json) still prints help to stderr, exit 1', async () => {
239
+ const {status, stdout, stderr} = await runCli(['layout']);
240
+ expect(status).toBe(1);
241
+ expect(stdout).toBe('');
242
+ expect(stderr).toMatch(/Usage: astryx layout/);
243
+ });
244
+
228
245
  it('the real binary emits the same envelope for help bogus --json', () => {
229
246
  // One program per process, so the root's own outputHelp patch is used here.
230
247
  const bin = fileURLToPath(new URL('../bin/astryx.mjs', import.meta.url));
@@ -240,9 +257,6 @@ describe('--json shim: help shown for a failed invocation is an error envelope',
240
257
  });
241
258
 
242
259
  it('a group added after install gets the same error envelope', () => {
243
- // This is the only coverage of the no-subcommand path: every group the CLI
244
- // ships has an action of its own (see command-result-coverage.test.mjs), so
245
- // a group without one has to be built here.
246
260
  const program = new Command('astryx');
247
261
  installJsonShim(program);
248
262
  // Added later, so only the prototype-level patch covers its outputHelp.
@@ -268,11 +282,11 @@ describe('--json shim: help shown for a failed invocation is an error envelope',
268
282
  expect(parsed.suggestions).toEqual([{name: 'late child', reason: 'available subcommand'}]);
269
283
  });
270
284
 
271
- it('astryx help theme --json still emits the help envelope, exit 0', async () => {
272
- const {status, stdout} = await runCli(['help', 'theme', '--json']);
285
+ it('astryx help layout --json still emits the help envelope, exit 0', async () => {
286
+ const {status, stdout} = await runCli(['help', 'layout', '--json']);
273
287
  expect(status).toBe(0);
274
288
  const parsed = parseJson(stdout);
275
289
  expect(parsed.type).toBe('help');
276
- expect(parsed.data.command).toBe('astryx theme');
290
+ expect(parsed.data.command).toBe('astryx layout');
277
291
  });
278
292
  });