Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): API-layer input validation, path-safety, and codemod hardening + test backfill (#4511)

Joey57611be4071e
diff --git a/.changeset/cli-search-input-validation.md b/.changeset/cli-search-input-validation.md
new file mode 100644
index 0000000000..a0177a3e71
--- /dev/null
+++ b/.changeset/cli-search-input-validation.md
@@ -0,0 +1,64 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] cli hardening pass — validate inputs at the API layer, close path-safety gaps, and prevent agent-docs content loss. The API is a public surface (`@astryxdesign/cli/api`), so guards that lived only in the CLI wrapper are pushed into the API.
+
+Path safety (the guard the write commands all depend on):
+
+- `assertWithin` now canonicalizes symlinks (realpath of the deepest existing ancestor) — a symlink inside the project root pointing outside no longer lets a write escape. Also rejects a NUL byte in the path. This closes the escape for every command that writes through the guard (swizzle/template/upgrade/theme/layout/agent-docs).
+
+Per-command input validation + write safety:
+
+- `search()`: non-positive/non-integer `limit`, empty query, unknown `--type` → `ERR_INVALID_ARGUMENT` (previously `limit: 0` returned the full unclamped set).
+- `swizzle()`: the component name is sanitized so `..`/separators can't escape the `--output` base.
+- `swizzle()` import rewriting: dynamic `import('../Sibling/…')` is now rewritten (was left pointing at a non-existent sibling in the output dir); a two-levels-up asset import (`../../locales/x.json`) maps to the exported subpath instead of the invalid `<pkg>/..`; and `../theme/tokens.stylex` keeps its full subpath (the StyleX compiler needs the dedicated `./theme/tokens.stylex` export — collapsing it to `<pkg>/theme` broke StyleX resolution). Component-local `.stylex` files that aren't subpath exports keep the working barrel collapse.
+- `template()` copy: refuses to clobber without `overwrite: true` (`ERR_FILE_EXISTS`); adds an `overwrite` option.
+- `upgrade()`: the `--path` scan dir is confined to cwd (`--apply` rewrites files in place).
+- `init()`: template scaffold refuses to clobber an existing `page.tsx` (`ERR_FILE_EXISTS`); an unknown `--agent` now throws `ERR_UNKNOWN_AGENT` (was silently ignored).
+- `layout`: rejects an unknown `--form` (`ERR_INVALID_OPTION`) and empty expression (`ERR_INVALID_ARGUMENT`).
+- `layout expand`: text payloads containing `<`, `>`, `{`, or `}` (e.g. `Text"5 < 3"`) are emitted as JSX string-expression children so the generated TSX is valid — previously they produced syntactically-broken output.
+- `layout expand`: a top-level repeat or group that expands to multiple sibling elements (`B"x"*3`, `(B"a" + B"b")`, an outline `repeat` block) is now wrapped in a fragment — previously the generated TSX had adjacent root elements with no parent and failed to compile (the wrapper decision counted AST roots instead of expanded elements).
+- `layout` (expand/check): an empty expression now surfaces `ERR_MISSING_ARGUMENT` and a missing `--file` surfaces `ERR_FILE_NOT_FOUND` (was a generic `ERR_UNKNOWN` / a raw `ENOENT` errno, with a stack leak in human mode).
+- `layout` parser: a pathologically deep compact expression (`V > …` nested past 512 levels) is rejected with a located `ERR_LAYOUT_PARSE` instead of blowing the call stack and surfacing a raw `RangeError` (→ `ERR_UNKNOWN`).
+- `layout check --form …` printers: a string containing a quote (e.g. a Button `label="Don't panic"`) now round-trips — the printer picks a delimiter the string doesn't contain instead of always single-quoting, so the emitted compact/outline surface re-parses (was producing an unparseable token).
+- `resolveTheme`: a non-string `astryx.theme` in package.json (number/array/object/boolean) degrades to null instead of crashing `astryx component` with a raw `TypeError` (parity with the empty-string / unknown-slug paths).
+- `jsonOut`: serializes the envelope BEFORE marking the emission handled, so if a command returns unserializable `data` (circular ref / BigInt — an author bug) the bin error boundary still emits a JSON error envelope instead of leaving a `--json` consumer with empty stdout.
+- package scanner: a dependency's `astryx.docs` that is a non-string (number/array) is skipped instead of crashing the whole scan with a raw `TypeError`, and a `docs` path that escapes its own package dir is skipped rather than surfacing foreign docs; a non-string package `name` is coerced to a string.
+- `component --package <pkg> --showcase`/`--blocks`: route to the right leaf instead of falling back to `component.detail`.
+- `discover`/`docs` leaves: empty query/section errors instead of matching everything via `.includes('')`.
+- `docs()`/`discover()`: a non-string `topic`/`section`/`query` now throws a stable coded error (`ERR_UNKNOWN_TOPIC` / `ERR_UNKNOWN_SECTION` / `ERR_INVALID_ARGUMENT`) instead of a raw `TypeError` the CLI downgraded to `ERR_UNKNOWN` (parity with the `component`/`hook` non-string guards).
+- `blog()` detail: a non-string slug throws `ERR_INVALID_ARGUMENT` (was a raw `TypeError` the CLI downgraded to `ERR_UNKNOWN`), and fails fast before any network fetch.
+- `hook()`/`component()` dispatchers: a non-string `name` or `category` throws a coded error (`ERR_UNKNOWN_HOOK` / `ERR_UNKNOWN_COMPONENT` / `ERR_UNKNOWN_CATEGORY`) instead of a raw `TypeError` with no `.code` from the leaf's `.toLowerCase()`/`.replace(...)`.
+- `theme add`: a write failure where an ancestor of the target dir is a file now surfaces `ERR_WRITE_FAILED` (the `mkdir` moved inside the write try/catch) instead of leaking a raw fs errno (`EEXIST`/`ENOTDIR`) + absolute path.
+- `validate-integration`: a path-unsafe `[package]` spec (`..`/absolute) is reported as an `invalid_package_spec` diagnostic instead of crashing with a raw stack (human) / generic `ERR_UNKNOWN` (`--json`).
+- `doctor`: no longer crashes (raw stack in human mode / `ERR_UNKNOWN` in `--json`) when multiple `astryx.config.*` files coexist — it reports a `config` FAIL. Version-alignment skips (info) instead of a spurious drift WARN with a `NaN.undefined.x` fix when either version isn't comparable semver (e.g. `workspace:*`).
+- `manifest`: subcommands are sorted by name (same stability guarantee the top-level command list makes), so reordering `.command()` calls can't silently change the agent-facing manifest.
+- `build`: the CLI wrapper now propagates the API's error `code` into the `--json` envelope (bogus `--type` / non-positive / non-integer `--limit` → `ERR_INVALID_ARGUMENT` instead of a generic `ERR_UNKNOWN`), and delegates `--limit` validation to the API (parity with `search`).
+- `layout check`: exits `1` in BOTH `--json` and human mode for an invalid (but parseable) layout — the exit code no longer depends on the output mode, so it works as a CI gate / agent check without parsing stdout.
+- `upgrade` config codemods: a `findConfigPath` throw (multiple `astryx.config.*` files) is surfaced as a structured per-codemod error instead of crashing the whole upgrade run — config codemods run before the strict loader, so this restores the per-codemod isolation every other failure path honors.
+- CLI dispatch: the belt-and-suspenders postAction "completed without emitting an envelope" error carries a `code` (`ERR_UNKNOWN`) so every error envelope is branchable on `code`.
+- `toErrorEnvelope`/`AstryxError`: attach `suggestions` only when it's a real array.
+
+Agent-docs data integrity:
+
+- `injectXdsBlock`/`removeXdsBlock` no longer drop, duplicate, or orphan user content on malformed managed blocks (END-before-START, duplicate/nested blocks, or a start marker with no end). They locate a single well-formed block (END searched after START) and refuse to touch an ambiguous/half-written file instead of corrupting it.
+
+Backfills api-level tests for the zero-coverage commands (`component`, `search`, `doctor`), the `hook`/`discover`/`docs` dispatchers (incl. `hook.list --category` unknown → `ERR_UNKNOWN_CATEGORY`), the blog adapter/leaf/CLI wrapper, doctor degradation paths, manifest determinism + subcommand ordering, `build` error-code faithfulness, `layout check` exit-code parity, `layout expand` JSX-safe text payloads, `swizzle` import rewriting (dynamic import, two-levels-up assets, theme StyleX subpath, barrel collapse), config-codemod isolation, a static guard that every inline error envelope carries a `code`, `isAstryxInitialized` malformed-marker resilience, and unit tests for `levenshteinDistance`, `checkGhCli`, the error-envelope contract, path-safety symlink escapes, the agent-docs malformed-block cases, `jsonOut` serialization-failure discipline, the `print` string round-trip, the package scanner's adversarial-node_modules handling, `resolveTheme`'s malformed-`astryx.theme` degradation, and the pure `string-utils` / `config-schema` / consumer-facing `json` parser / `term-log` json-silence modules.
+
+Codemod runner + integration loading:
+
+- The codemod source scan no longer follows symlinks (a symlinked file under the scanned path could rewrite its target OUTSIDE the project) and skips generated-output dirs (dist/build/out/.next/coverage) — codemods rewrite source, not artifacts or dependencies.
+- `resolvePackageDir` rejects an integration spec that isn't a bare package name (no `..`, no absolute, must stay in node_modules) — a config spec can no longer point the loader at an arbitrary module.
+- A broken integration manifest (throws on import or fails schema validation) no longer crashes `Project.load` (and thus every command). It's recorded and surfaced via `issues()`, restoring the documented skip+warn policy; other integrations still load.
+
+Codemod transforms (token migrations):
+
+- The `--radius-*`, `--shadow-*`/`--elevation-*`, and `--color-*` token-migration codemods no longer rewrite a longer consumer-defined token that merely shares a prefix (e.g. `--radius-container-custom` → `--radius-3-custom`, `--radius-innermost` → `--radius-0most`, `var(--shadow-10)` → `--shadow-base0`, `--color-positive-custom` → `--color-success-custom`). The boundary lookahead was binding only to the last alternative in the pattern (and two codemods had no boundary at all); it now wraps the whole alternation, so only exact token names migrate.
+- `migrate-badge-children-to-label` no longer emits a duplicate `label` prop when the badge already has one (`<XDSBadge label="x">Active</XDSBadge>` produced an invalid `label="x" label="Active"`); it now skips a badge that already declares `label`.
+
+Component discovery:
+
+- `readDocMeta` no longer reads a `group:`/`hidden:` field nested inside a `propDescriptions` block (a docsZh/docsDense translation export) as the component's group — that leaked a translated prop description as a group key in the default English `component --list` (e.g. a Chinese string appeared as a group). The field regexes now match top-level fields only (<=2 spaces).
+
+@josephfarina
diff --git a/packages/cli/api/blog/_adapter.test.mjs b/packages/cli/api/blog/_adapter.test.mjs
new file mode 100644
index 0000000000..17686e6f30
--- /dev/null
+++ b/packages/cli/api/blog/_adapter.test.mjs
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the blog adapter (api/blog/_adapter.mjs) — the shared network
+ * + RSS-parsing layer behind the blog leaves. `fetch` is stubbed so nothing
+ * hits the network. Locks the SSRF/origin guard, invalid-URL handling, and the
+ * garbage-feed degradation that the leaves depend on but never test directly.
+ */
+
+import {describe, it, expect, afterEach, vi} from 'vitest';
+import {loadFeed, fetchPostText, FEED_URL} from './_adapter.mjs';
+import {AstryxError} from '../error.mjs';
+import {SITE_URL} from '../../lib/site.mjs';
+
+const FEED = `<?xml version="1.0" encoding="UTF-8"?>
+<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
+ <channel>
+ <title>Astryx Blog</title>
+ <link>${SITE_URL}/blog</link>
+ <item>
+ <title>Under the hood &amp; more</title>
+ <link>${SITE_URL}/blog/how-astryx-works</link>
+ <atom:link rel="alternate" type="text/plain" href="${SITE_URL}/blog/how-astryx-works.txt" />
+ </item>
+ </channel>
+</rss>`;
+
+/** Build a fetch stub from a url→{status,body} map. */
+function stubFetch(routes) {
+ return vi.fn(async url => {
+ const r = routes[String(url)];
+ if (!r) return {ok: false, status: 404, text: async () => 'not found'};
+ return {ok: r.status < 400, status: r.status, text: async () => r.body};
+ });
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('blog adapter — loadFeed', () => {
+ it('parses posts and reports the canonical feed URL', async () => {
+ vi.stubGlobal('fetch', stubFetch({[FEED_URL]: {status: 200, body: FEED}}));
+ const {feedUrl, posts} = await loadFeed();
+ expect(feedUrl).toBe(FEED_URL);
+ expect(posts).toHaveLength(1);
+ expect(posts[0].slug).toBe('how-astryx-works');
+ // XML entities in the title are unescaped.
+ expect(posts[0].title).toBe('Under the hood & more');
+ });
+
+ it('returns an empty post list for non-RSS / garbage feed content', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ stubFetch({[FEED_URL]: {status: 200, body: '<html>not a feed</html>'}}),
+ );
+ const {feedUrl, posts} = await loadFeed();
+ expect(feedUrl).toBe(FEED_URL);
+ expect(posts).toEqual([]);
+ });
+
+ it('throws ERR_FETCH_FAILED when the feed request is non-200', async () => {
+ vi.stubGlobal('fetch', stubFetch({[FEED_URL]: {status: 500, body: 'boom'}}));
+ await expect(loadFeed()).rejects.toMatchObject({code: 'ERR_FETCH_FAILED'});
+ });
+});
+
+describe('blog adapter — fetchPostText SSRF/origin guard', () => {
+ it('rejects a plaintext URL on a non-canonical origin (SSRF)', async () => {
+ const spy = vi.fn(async () => ({ok: true, status: 200, text: async () => 'SECRETS'}));
+ vi.stubGlobal('fetch', spy);
+ await expect(
+ fetchPostText('http://169.254.169.254/latest/meta-data'),
+ ).rejects.toBeInstanceOf(AstryxError);
+ await expect(
+ fetchPostText('http://169.254.169.254/latest/meta-data'),
+ ).rejects.toMatchObject({code: 'ERR_FETCH_FAILED'});
+ // The internal host must never be fetched.
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unparseable URL with ERR_FETCH_FAILED', async () => {
+ vi.stubGlobal('fetch', vi.fn());
+ await expect(fetchPostText('not a url')).rejects.toMatchObject({
+ code: 'ERR_FETCH_FAILED',
+ });
+ });
+
+ it('fetches a same-origin plaintext URL', async () => {
+ const url = `${SITE_URL}/blog/how-astryx-works.txt`;
+ vi.stubGlobal('fetch', stubFetch({[url]: {status: 200, body: '# body'}}));
+ await expect(fetchPostText(url)).resolves.toBe('# body');
+ });
+});
diff --git a/packages/cli/api/blog/detail/detail.mjs b/packages/cli/api/blog/detail/detail.mjs
index a1bdb52d69..e692ca9bc9 100644
--- a/packages/cli/api/blog/detail/detail.mjs
+++ b/packages/cli/api/blog/detail/detail.mjs
@@ -23,6 +23,18 @@ import {loadFeed, fetchPostText} from '../_adapter.mjs';
* @returns {Promise<import('../blog.type.mjs').BlogDetailResponse>}
*/
export async function detail(slug) {
+ // Validate the slug type before any network work — the dispatcher routes
+ // any truthy value here, and a public API caller (`@astryxdesign/cli/api`)
+ // could pass a non-string. Without this guard `slug.toLowerCase()` throws a
+ // raw TypeError with no `.code`, which the CLI downgrades to ERR_UNKNOWN.
+ if (typeof slug !== 'string') {
+ throw new AstryxError(
+ `Invalid blog slug: ${String(slug)}`,
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+
const {feedUrl, posts} = await loadFeed();
const normalized = slug.toLowerCase();
diff --git a/packages/cli/api/blog/detail/detail.test.mjs b/packages/cli/api/blog/detail/detail.test.mjs
index eb4529a03a..0ba394feb2 100644
--- a/packages/cli/api/blog/detail/detail.test.mjs
+++ b/packages/cli/api/blog/detail/detail.test.mjs
@@ -67,6 +67,23 @@ describe('blog.detail leaf', () => {
expect(res.data.slug).toBe('how-astryx-works');
});
+ it('throws a coded error (not a raw TypeError) for a non-string slug', async () => {
+ // The dispatcher routes any truthy value into detail(); a public API
+ // caller could pass a non-string. It must surface a coded AstryxError,
+ // not a raw TypeError that the CLI downgrades to ERR_UNKNOWN — and it must
+ // fail fast, before any network fetch.
+ for (const bad of [null, 42, {}, [1]]) {
+ await expect(detail(/** @type {any} */ (bad))).rejects.toBeInstanceOf(
+ AstryxError,
+ );
+ await expect(detail(/** @type {any} */ (bad))).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ }
+ // No feed fetch should have happened for the invalid inputs.
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
it('throws ERR_UNKNOWN_POST with suggestions for a bad slug', async () => {
await expect(detail('does-not-exist')).rejects.toMatchObject({
code: 'ERR_UNKNOWN_POST',
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index 93b015cd7b..09529b7238 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -83,6 +83,17 @@ export async function component(name, options = {}) {
const coreDir = requireCoreDir(cwd);
+ // A public API caller could pass a non-string category; the list leaf does
+ // `category.toLowerCase()`, so guard it up front (same class as the name
+ // guard below) instead of throwing a raw TypeError with no `.code`.
+ if (category != null && typeof category !== 'string') {
+ throw new AstryxError(
+ `Unknown category "${String(category)}"`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,
+ );
+ }
+
// ── List mode ──────────────────────────────────────────────────
if (category || list || !name) {
return componentList(coreDir, {cwd, category, detail, zh, dense, lang});
@@ -120,6 +131,20 @@ export async function component(name, options = {}) {
notFoundInPackage: scoped.kind === 'integration' ? packageScope : null,
});
}
+ // showcase/blocks were previously dropped on the scoped path — a
+ // `--package ... --showcase`/`--blocks` request silently fell through to
+ // component.detail. Route them to the same leaves the no-scope path uses.
+ // Core showcases carry no `package` field, so a core scope must NOT pass
+ // packageScope (findShowcase filters those out); integrations never carry
+ // a showcase, so skip discovery entirely.
+ if (showcase) {
+ return scoped.kind === 'core'
+ ? componentDetailShowcase(dirName, {cwd, name})
+ : componentDetailShowcase(dirName, {cwd, name, resolve: false});
+ }
+ if (blocks) {
+ return componentDetailBlocks(dirName);
+ }
const docs = await loadComponentDoc(owner.docPath, docOpts);
if (props) return componentDetailProps(docs);
return componentDetail(docs, owner, dirName, coreDir);
diff --git a/packages/cli/api/component/component.test.mjs b/packages/cli/api/component/component.test.mjs
new file mode 100644
index 0000000000..e2e3c27ed0
--- /dev/null
+++ b/packages/cli/api/component/component.test.mjs
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the `component` command dispatcher
+ * (api/component/component.mjs), run against the real @astryxdesign/core
+ * registry. `component` fans out to list/detail(+props/source/showcase/blocks)
+ * leaves; this pins the DISPATCH + precedence rules that no other suite covered
+ * (component had no api-level tests). Locks behavior so a future refactor of the
+ * router can't silently change which leaf a given arg/flag combination hits.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {component} from './component.mjs';
+import {AstryxError} from '../error.mjs';
+
+// api/component/ -> up 4 = repo root (has packages/core, which findCoreDir walks to).
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+const cwd = REPO;
+const SLOW = 30_000;
+
+describe('component dispatcher — routing', () => {
+ it('routes a bare name to component.detail', async () => {
+ const r = await component('Button', {cwd});
+ expect(r.type).toBe('component.detail');
+ expect(r.data.name).toBe('Button');
+ }, SLOW);
+
+ it('routes no-name to the list leaf (component.list, detail=names)', async () => {
+ const r = await component(undefined, {cwd});
+ expect(r.type).toBe('component.list');
+ expect(r.data.detail).toBe('names');
+ expect(Object.keys(r.data.components).length).toBeGreaterThan(0);
+ }, SLOW);
+
+ it('routes --category to the list leaf, filtered to that group', async () => {
+ const r = await component(undefined, {cwd, category: 'Layout'});
+ expect(r.type).toBe('component.list');
+ expect(Object.keys(r.data.components)).toContain('Layout');
+ }, SLOW);
+
+ it('treats an empty-string name as a list (not a not-found error)', async () => {
+ const r = await component('', {cwd});
+ expect(r.type).toBe('component.list');
+ }, SLOW);
+});
+
+describe('component dispatcher — detail levels on list', () => {
+ it('--detail compact lists with detail=compact', async () => {
+ const r = await component(undefined, {cwd, list: true, detail: 'compact'});
+ expect(r.type).toBe('component.list');
+ expect(r.data.detail).toBe('compact');
+ }, SLOW);
+
+ it('--detail full lists with detail=full', async () => {
+ const r = await component(undefined, {cwd, list: true, detail: 'full'});
+ expect(r.type).toBe('component.list');
+ expect(r.data.detail).toBe('full');
+ }, SLOW);
+});
+
+describe('component dispatcher — projection precedence (locked)', () => {
+ it('--props routes to component.detail.props', async () => {
+ const r = await component('Button', {cwd, props: true});
+ expect(r.type).toBe('component.detail.props');
+ }, SLOW);
+
+ it('--source routes to component.detail.source', async () => {
+ const r = await component('Button', {cwd, source: true});
+ expect(r.type).toBe('component.detail.source');
+ }, SLOW);
+
+ it('--source WINS over --props when both are set (precedence lock)', async () => {
+ const r = await component('Button', {cwd, props: true, source: true});
+ expect(r.type).toBe('component.detail.source');
+ }, SLOW);
+
+ it('--list WINS over a given name (list dispatch precedence lock)', async () => {
+ const r = await component('Button', {cwd, list: true});
+ expect(r.type).toBe('component.list');
+ }, SLOW);
+});
+
+describe('component dispatcher — name resolution', () => {
+ it('strips a legacy XDS prefix (XDSButton -> Button)', async () => {
+ const r = await component('XDSButton', {cwd});
+ expect(r.type).toBe('component.detail');
+ expect(r.data.name).toBe('Button');
+ }, SLOW);
+
+ it('is case-SENSITIVE: a lowercased name is unknown', async () => {
+ let err;
+ try {
+ await component('button', {cwd});
+ } catch (e) {
+ err = e;
+ }
+ expect(err).toBeDefined();
+ expect(err.code).toBe('ERR_UNKNOWN_COMPONENT');
+ }, SLOW);
+
+ it('throws ERR_UNKNOWN_COMPONENT for a genuinely unknown name', async () => {
+ let err;
+ try {
+ await component('ZzzNope99', {cwd});
+ } catch (e) {
+ err = e;
+ }
+ expect(err.code).toBe('ERR_UNKNOWN_COMPONENT');
+ }, SLOW);
+
+ it('throws ERR_UNKNOWN_PACKAGE when --package names a missing package', async () => {
+ let err;
+ try {
+ await component('Button', {cwd, package: '@nonexistent/pkg-xyz'});
+ } catch (e) {
+ err = e;
+ }
+ expect(err).toBeDefined();
+ expect(err.code).toBe('ERR_UNKNOWN_PACKAGE');
+ }, SLOW);
+});
+
+
+describe('component dispatcher — scoped --package routes all projections', () => {
+ const CORE = '@astryxdesign/core';
+
+ it('--package (core) routes --showcase like the no-scope path', async () => {
+ const ns = await component('Button', {cwd, showcase: true});
+ const sc = await component('Button', {cwd, package: CORE, showcase: true});
+ expect(sc.type).toBe(ns.type); // was silently component.detail before the fix
+ }, SLOW);
+
+ it('--package (core) routes --blocks like the no-scope path', async () => {
+ const ns = await component('Button', {cwd, blocks: true});
+ const sc = await component('Button', {cwd, package: CORE, blocks: true});
+ expect(sc.type).toBe(ns.type);
+ expect(sc.type).toBe('component.detail.blocks');
+ }, SLOW);
+
+ it('--package (core) still routes --source and --props', async () => {
+ expect((await component('Button', {cwd, package: CORE, source: true})).type).toBe(
+ 'component.detail.source',
+ );
+ expect((await component('Button', {cwd, package: CORE, props: true})).type).toBe(
+ 'component.detail.props',
+ );
+ }, SLOW);
+});
+
+describe('component dispatcher — category guard', () => {
+ it('a non-string category throws a coded error (not a raw TypeError)', async () => {
+ for (const bad of [123, {}, [1]]) {
+ const err = await component(undefined, {
+ cwd,
+ category: /** @type {any} */ (bad),
+ }).catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_CATEGORY');
+ }
+ }, SLOW);
+});
diff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjs
index 2e1f95640b..ce2df94fae 100644
--- a/packages/cli/api/discover/discover.mjs
+++ b/packages/cli/api/discover/discover.mjs
@@ -21,6 +21,8 @@ import {list} from './list/list.mjs';
import {detail} from './detail/detail.mjs';
import {doc} from './detail/doc/doc.mjs';
import {search} from './search/search.mjs';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
/**
* @param {string} [query]
@@ -47,6 +49,17 @@ export async function discover(query, options = {}) {
// No query: the full package list.
if (!query) return list(packages, {configured});
+ // A non-string (truthy) query would crash `.startsWith`/`.indexOf` below
+ // with a raw TypeError (no ERR_* code → downgrades to ERR_UNKNOWN). The CLI
+ // only ever passes a string, but the public API must fail with a code.
+ if (typeof query !== 'string') {
+ throw new AstryxError(
+ `Invalid query "${String(query)}"`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+
// Scoped package query: @scope/name or @scope/name/Component
if (query.startsWith('@')) {
const slashIdx = query.indexOf('/', query.indexOf('/') + 1);
diff --git a/packages/cli/api/discover/discover.test.mjs b/packages/cli/api/discover/discover.test.mjs
new file mode 100644
index 0000000000..65c1007057
--- /dev/null
+++ b/packages/cli/api/discover/discover.test.mjs
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dispatcher-level tests for discover() — the query-shape routing that
+ * sits above the list/detail/doc/search leaves. The leaves have their own
+ * tests; this pins the router itself, which parses the query into:
+ *
+ * (no query) -> discover.list
+ * @scope/name -> discover.detail
+ * @scope/name/Component -> discover.detail.doc
+ * free text -> discover.search
+ *
+ * `discoverPackages` is mocked so routing is exercised deterministically
+ * without a real configured project (the empty-project path returns list()
+ * before any parsing, so routing needs a non-empty package set).
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+
+vi.mock('./_adapter.mjs', async orig => {
+ const actual = /** @type {any} */ (await orig());
+ return {
+ ...actual,
+ discoverPackages: async () => ({
+ configured: true,
+ packages: [
+ {
+ name: '@acme/widgets',
+ category: '@acme/widgets',
+ version: '1.0.0',
+ components: ['Alpha', 'Beta'],
+ dir: '/virtual/widgets',
+ astryx: {},
+ docsDir: '/virtual/widgets/docs',
+ },
+ ],
+ }),
+ };
+});
+
+const {discover} = await import('./discover.mjs');
+const {AstryxError} = await import('../error.mjs');
+
+describe('discover() dispatcher routing', () => {
+ it('no query -> discover.list', async () => {
+ const r = await discover();
+ expect(r.type).toBe('discover.list');
+ });
+
+ it('empty query -> discover.list', async () => {
+ expect((await discover('')).type).toBe('discover.list');
+ });
+
+ it('@scope/name -> discover.detail (unknown package -> ERR_UNKNOWN_PACKAGE)', async () => {
+ expect((await discover('@acme/widgets')).type).toBe('discover.detail');
+ await expect(discover('@acme/nope')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_PACKAGE',
+ });
+ });
+
+ it('@scope/name/Component -> doc route (unknown component -> coded error)', async () => {
+ const err = await discover('@acme/widgets/Nope').catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toMatch(/^ERR_/);
+ expect(err.code).not.toBe('ERR_UNKNOWN');
+ });
+
+ it('free-text query with multiple matches -> discover.search envelope', async () => {
+ // 'a' is a substring of both Alpha and Beta (no exact match), so the search
+ // leaf returns the multi-match discover.search envelope. Proves free-text
+ // routing reaches the search leaf and projects its envelope.
+ const r = await discover('a');
+ expect(r.type).toBe('discover.search');
+ expect(r.data.matches.map(m => m.component).sort()).toEqual(['Alpha', 'Beta']);
+ });
+
+ it('free-text query with no match still routes to the search leaf (coded not-found)', async () => {
+ const err = await discover('zzzznope').catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toMatch(/^ERR_/);
+ expect(err.code).not.toBe('ERR_UNKNOWN');
+ });
+
+ it('non-string query -> ERR_INVALID_ARGUMENT (not a raw TypeError)', async () => {
+ for (const bad of [123, {}, ['x'], true]) {
+ const err = await discover(/** @type {any} */ (bad)).catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_INVALID_ARGUMENT');
+ }
+ });
+});
diff --git a/packages/cli/api/discover/search/search.mjs b/packages/cli/api/discover/search/search.mjs
index 1e30847274..7a5ca3e4be 100644
--- a/packages/cli/api/discover/search/search.mjs
+++ b/packages/cli/api/discover/search/search.mjs
@@ -39,6 +39,16 @@ import {ERROR_CODES} from '../../../lib/error-codes.mjs';
* >}
*/
export async function search(packages, query, {lang, zh}) {
+ // An empty query must error, not match every component via `.includes('')`
+ // (parity with the api/search leaf). The discover() dispatcher already routes
+ // an empty query to list, but the leaf must be safe on its own.
+ if (!query || !String(query).trim()) {
+ throw new AstryxError(
+ 'A search query is required',
+ [{name: 'astryx discover button', reason: 'example'}],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
const lower = query.toLowerCase();
const exact = findComponent(packages, query);
diff --git a/packages/cli/api/discover/search/search.test.mjs b/packages/cli/api/discover/search/search.test.mjs
index 1a0bb1adf2..57e68df6c7 100644
--- a/packages/cli/api/discover/search/search.test.mjs
+++ b/packages/cli/api/discover/search/search.test.mjs
@@ -102,3 +102,17 @@ describe('discover.search leaf', () => {
expect(err.suggestions).toBeUndefined();
});
});
+
+describe('discover.search leaf — empty query (parity with api/search)', () => {
+ it('throws ERR_INVALID_ARGUMENT for an empty query (does not match everything)', async () => {
+ await expect(search(packages, '', {})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ });
+
+ it('throws ERR_INVALID_ARGUMENT for a whitespace-only query', async () => {
+ await expect(search(packages, ' ', {})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ });
+});
diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjs
index 83f7fa68a5..378e37aade 100644
--- a/packages/cli/api/docs/_adapter.mjs
+++ b/packages/cli/api/docs/_adapter.mjs
@@ -116,6 +116,17 @@ export async function resolveTopicDocs(topic, options = {}) {
const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);
const topics = discoverTopics();
+ // A public API caller could pass a non-string topic; `.toLowerCase()` below
+ // would throw a raw TypeError (no ERR_* code → downgrades to ERR_UNKNOWN).
+ // Surface the same stable code the unknown-topic path uses.
+ if (typeof topic !== 'string') {
+ throw new AstryxError(
+ `Unknown topic "${String(topic)}"`,
+ Object.keys(topics).map(t => ({name: t, reason: 'available topic'})),
+ ERROR_CODES.ERR_UNKNOWN_TOPIC,
+ );
+ }
+
const normalized = topic.toLowerCase();
if (!topics[normalized]) {
throw new AstryxError(
diff --git a/packages/cli/api/docs/detail/section/section.mjs b/packages/cli/api/docs/detail/section/section.mjs
index 1fd7120e99..f7675c7db0 100644
--- a/packages/cli/api/docs/detail/section/section.mjs
+++ b/packages/cli/api/docs/detail/section/section.mjs
@@ -27,6 +27,17 @@ import {resolveTopicDocs} from '../../_adapter.mjs';
* @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}
*/
export async function section(topic, sectionName, options = {}) {
+ // An empty section name must error, not resolve to the first section via
+ // `.includes('')`. The docs() dispatcher routes a falsy section to detail, but
+ // the leaf must be safe on its own. A non-string would also throw a raw
+ // TypeError below (`.toLowerCase()`) → downgrades to ERR_UNKNOWN.
+ if (typeof sectionName !== 'string' || !sectionName.trim()) {
+ throw new AstryxError(
+ 'A section name is required',
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
+ );
+ }
const {docsData} = await resolveTopicDocs(topic, options);
const normalizedSection = sectionName.toLowerCase();
diff --git a/packages/cli/api/docs/detail/section/section.test.mjs b/packages/cli/api/docs/detail/section/section.test.mjs
new file mode 100644
index 0000000000..8d41b2a577
--- /dev/null
+++ b/packages/cli/api/docs/detail/section/section.test.mjs
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the docs.detail.section leaf. Locks the happy path,
+ * case-insensitive title match, ERR_UNKNOWN_SECTION, and the empty-section guard
+ * (regression: '' matched every title via .includes(''), silently returning the
+ * first section).
+ */
+
+import {describe, it, expect} from 'vitest';
+import {section} from './section.mjs';
+import {AstryxError} from '../../../error.mjs';
+
+const SLOW = 30_000;
+
+describe('docs.detail.section leaf', () => {
+ it('resolves a named section (case-insensitive) into a docs.detail.section envelope', async () => {
+ const res = await section('tokens', 'spacing');
+ expect(res.type).toBe('docs.detail.section');
+ expect(res.data.title.toLowerCase()).toContain('spacing');
+ }, SLOW);
+
+ it('throws ERR_UNKNOWN_SECTION for an unknown section', async () => {
+ let err;
+ try {
+ await section('tokens', 'zzzznope');
+ } catch (e) {
+ err = e;
+ }
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
+ }, SLOW);
+
+ it('does not return the first section for an empty section name', async () => {
+ await expect(section('tokens', '')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_SECTION',
+ });
+ await expect(section('tokens', ' ')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_SECTION',
+ });
+ }, SLOW);
+});
diff --git a/packages/cli/api/docs/docs.test.mjs b/packages/cli/api/docs/docs.test.mjs
new file mode 100644
index 0000000000..f564e678cf
--- /dev/null
+++ b/packages/cli/api/docs/docs.test.mjs
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dispatcher-level tests for docs() — the argument-shape routing that
+ * sits above the list/detail/section leaves. The leaves have their own tests;
+ * this pins the router: docs() -> list, docs(topic) -> detail,
+ * docs(topic, section) -> section, plus the unknown-topic/section error codes.
+ * Runs against the real CLI-bundled docs (no cwd/project needed).
+ */
+
+import {describe, it, expect} from 'vitest';
+import {docs} from './docs.mjs';
+import {AstryxError} from '../error.mjs';
+
+const SLOW = 30_000;
+
+describe('docs() dispatcher routing', () => {
+ it('no topic -> docs.list', async () => {
+ const r = await docs();
+ expect(r.type).toBe('docs.list');
+ expect(Array.isArray(r.data)).toBe(true);
+ expect(r.data.length).toBeGreaterThan(0);
+ }, SLOW);
+
+ it('empty topic -> docs.list (falsy topic routes to list)', async () => {
+ expect((await docs('')).type).toBe('docs.list');
+ }, SLOW);
+
+ it('topic only -> docs.detail', async () => {
+ const {data} = await docs();
+ const topic = data[0].topic;
+ const r = await docs(topic);
+ expect(r.type).toBe('docs.detail');
+ }, SLOW);
+
+ it('topic + section -> docs.detail.section', async () => {
+ const {data} = await docs();
+ let routed = null;
+ for (const {topic} of data) {
+ const detail = await docs(topic);
+ const sections = detail.data.sections;
+ if (Array.isArray(sections) && sections.length > 0) {
+ routed = await docs(topic, sections[0].title);
+ break;
+ }
+ }
+ expect(routed).not.toBeNull();
+ expect(routed.type).toBe('docs.detail.section');
+ }, SLOW);
+
+ it('unknown topic -> ERR_UNKNOWN_TOPIC', async () => {
+ await expect(docs('zzz-not-a-real-topic')).rejects.toBeInstanceOf(AstryxError);
+ await expect(docs('zzz-not-a-real-topic')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_TOPIC',
+ });
+ }, SLOW);
+
+ it('known topic + unknown section -> ERR_UNKNOWN_SECTION', async () => {
+ const {data} = await docs();
+ const topic = data[0].topic;
+ await expect(docs(topic, 'zzz-not-a-real-section')).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_SECTION',
+ });
+ }, SLOW);
+
+ it('non-string topic -> ERR_UNKNOWN_TOPIC (not a raw TypeError)', async () => {
+ for (const bad of [123, {}, ['tokens'], true]) {
+ const err = await docs(/** @type {any} */ (bad)).catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_TOPIC');
+ }
+ }, SLOW);
+
+ it('non-string section -> ERR_UNKNOWN_SECTION (not a raw TypeError)', async () => {
+ const {data} = await docs();
+ const topic = data[0].topic;
+ for (const bad of [456, {}, ['x']]) {
+ const err = await docs(topic, /** @type {any} */ (bad)).catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
+ }
+ }, SLOW);
+});
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index 3a53d7a132..9c86716592 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -28,7 +28,7 @@ import {MIN_NODE_VERSION, isNodeVersionSupported} from '../../lib/node-version.m
import {CLI_ROOT, findCoreDir} from '../../utils/paths.mjs';
import {detectPackageManager, getCliInvocation} from '../../utils/package-manager.mjs';
import {findConfigPath, Project} from '../../lib/project.mjs';
-import {semverCompare} from '../../utils/semver.mjs';
+import {semverCompare, isValidSemver} from '../../utils/semver.mjs';
const _require = createRequire(import.meta.url);
@@ -52,6 +52,8 @@ const _require = createRequire(import.meta.url);
* @property {string|null} coreDir - Resolved core package directory, or null.
* @property {string|null} configPath - Resolved astryx.config.mjs path, or null.
* @property {string|null} configTheme - theme value read from config, or null.
+ * @property {Error|null} [configError] - Error thrown while resolving the config
+ * path (e.g. multiple config files present), surfaced by checkConfig as a FAIL.
*/
/* ── helpers ──────────────────────────────────────────────────────────── */
@@ -213,6 +215,22 @@ export function checkVersionAlignment(ctx) {
};
}
+ // A monorepo/linked install often pins a non-semver range like `workspace:*`
+ // or `link:...`. `'workspace:*'.split('.').map(Number)` yields NaN, and
+ // `NaN !== cliMajor` is always true — that produced a spurious drift WARN
+ // with a `NaN.undefined.x` fix string. If either version isn't real semver,
+ // there's nothing to compare: skip.
+ if (!isValidSemver(coreVersion) || !isValidSemver(cliVersion)) {
+ return {
+ id: 'version-alignment',
+ label: '@astryxdesign/core <-> @astryxdesign/cli alignment',
+ status: 'info',
+ message:
+ `Skipped — @astryxdesign/core v${coreVersion} / @astryxdesign/cli ` +
+ `v${cliVersion} are not both comparable semver.`,
+ };
+ }
+
const [coreMajor, coreMinor] = coreVersion.split('.').map(Number);
const [cliMajor, cliMinor] = cliVersion.split('.').map(Number);
const drift = coreMajor !== cliMajor || coreMinor !== cliMinor;
@@ -282,6 +300,17 @@ export function checkThemes(ctx) {
* @returns {Promise<DoctorCheck>}
*/
export async function checkConfig(ctx) {
+ // A resolution error (e.g. multiple astryx.config.* files) is exactly the
+ // kind of setup problem doctor should report — not crash on.
+ if (ctx.configError) {
+ return {
+ id: 'config',
+ label: 'astryx.config.mjs',
+ status: 'fail',
+ message: ctx.configError.message,
+ fix: 'Keep exactly one astryx.config.{ts,mjs,js} at your project root.',
+ };
+ }
if (!ctx.configPath) {
return {
id: 'config',
@@ -485,7 +514,16 @@ export const SYNC_CHECKS = [
export async function runChecks(options = {}) {
const cwd = options.cwd ?? process.cwd();
const coreDir = findCoreDir(cwd);
- const configPath = findConfigPath(cwd);
+ // findConfigPath throws when multiple config files coexist. That's a
+ // misconfiguration doctor exists to report — catch it and surface it through
+ // checkConfig as a FAIL rather than crashing the whole diagnostic engine.
+ let configPath = null;
+ let configError = null;
+ try {
+ configPath = findConfigPath(cwd);
+ } catch (err) {
+ configError = /** @type {Error} */ (err);
+ }
// Resolve a possible theme key from config (best-effort; never throws).
let configTheme = null;
@@ -504,6 +542,7 @@ export async function runChecks(options = {}) {
coreDir,
configPath,
configTheme,
+ configError,
};
/** @type {DoctorCheck[]} */
diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjs
new file mode 100644
index 0000000000..1ddb1a3f66
--- /dev/null
+++ b/packages/cli/api/doctor/doctor.test.mjs
@@ -0,0 +1,151 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the `doctor` leaf (api/doctor/doctor.mjs). `doctor`
+ * had no api-level tests; this locks the envelope shape and the summary
+ * invariant (the counts must always add up to the number of checks).
+ */
+
+import {describe, it, expect, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {doctor, checkVersionAlignment} from './doctor.mjs';
+
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+const cwd = REPO;
+const SLOW = 30_000;
+
+/** Throwaway project dirs, cleaned up after each test. */
+const tmpDirs = [];
+function mkProject(files) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-doctor-'));
+ tmpDirs.push(dir);
+ for (const [rel, content] of Object.entries(files)) {
+ const abs = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(abs), {recursive: true});
+ fs.writeFileSync(abs, content);
+ }
+ return dir;
+}
+afterEach(() => {
+ while (tmpDirs.length) {
+ fs.rmSync(tmpDirs.pop(), {recursive: true, force: true});
+ }
+});
+
+describe('doctor leaf', () => {
+ it('returns a `doctor` envelope with checks + summary', async () => {
+ const r = await doctor({cwd});
+ expect(r.type).toBe('doctor');
+ expect(Array.isArray(r.data.checks)).toBe(true);
+ expect(r.data.checks.length).toBeGreaterThan(0);
+ expect(r.data.summary).toBeDefined();
+ }, SLOW);
+
+ it('every check has an id, label, and a valid status', async () => {
+ const r = await doctor({cwd});
+ for (const c of r.data.checks) {
+ expect(typeof c.id).toBe('string');
+ expect(typeof c.label).toBe('string');
+ expect(['pass', 'warn', 'fail', 'info']).toContain(c.status);
+ }
+ }, SLOW);
+
+ it('summary counts sum to the number of checks (invariant)', async () => {
+ const r = await doctor({cwd});
+ const {pass, warn, fail, info} = r.data.summary;
+ expect(pass + warn + fail + info).toBe(r.data.checks.length);
+ }, SLOW);
+
+ it('reports the core node-version and core-installed checks', async () => {
+ const r = await doctor({cwd});
+ const ids = r.data.checks.map(c => c.id);
+ expect(ids).toContain('node-version');
+ expect(ids).toContain('core-installed');
+ }, SLOW);
+});
+
+describe('doctor leaf — degradation & error paths', () => {
+ it('does not crash on multiple config files; reports a config FAIL', async () => {
+ const dir = mkProject({
+ 'package.json': '{"name":"x"}',
+ 'astryx.config.mjs': 'export default {};',
+ 'astryx.config.js': 'export default {};',
+ });
+ const r = await doctor({cwd: dir});
+ const config = r.data.checks.find(c => c.id === 'config');
+ expect(config).toBeDefined();
+ expect(config.status).toBe('fail');
+ expect(config.message).toMatch(/multiple|exactly one/i);
+ }, SLOW);
+
+ it('reports a config FAIL (not a crash) when astryx.config.mjs throws on import', async () => {
+ const dir = mkProject({
+ 'package.json': '{"name":"x"}',
+ 'astryx.config.mjs': 'throw new Error("boom");\nexport default {};',
+ });
+ const r = await doctor({cwd: dir});
+ const config = r.data.checks.find(c => c.id === 'config');
+ expect(config.status).toBe('fail');
+ expect(config.message).toMatch(/failed to load/i);
+ }, SLOW);
+
+ it('flags a non-object config default export as FAIL', async () => {
+ const dir = mkProject({
+ 'package.json': '{"name":"x"}',
+ 'astryx.config.mjs': 'export default 42;',
+ });
+ const r = await doctor({cwd: dir});
+ const config = r.data.checks.find(c => c.id === 'config');
+ expect(config.status).toBe('fail');
+ expect(config.message).toMatch(/not an object/i);
+ }, SLOW);
+
+ it('degrades gracefully on invalid package.json', async () => {
+ const dir = mkProject({'package.json': '{ not json }'});
+ const r = await doctor({cwd: dir});
+ const {pass, warn, fail, info} = r.data.summary;
+ expect(pass + warn + fail + info).toBe(r.data.checks.length);
+ }, SLOW);
+});
+
+describe('doctor — checkVersionAlignment', () => {
+ it('skips (info) when the core version is not comparable semver', () => {
+ const dir = mkProject({
+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({
+ name: '@astryxdesign/core',
+ version: 'workspace:*',
+ }),
+ });
+ const c = checkVersionAlignment({
+ cwd: dir,
+ coreDir: path.join(dir, 'node_modules/@astryxdesign/core'),
+ nodeVersion: '',
+ configPath: null,
+ configTheme: null,
+ });
+ expect(c.status).toBe('info');
+ expect(c.fix ?? '').not.toMatch(/NaN|undefined/);
+ });
+
+ it('does not leak NaN/undefined for a comparable semver core version', () => {
+ const dir = mkProject({
+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '0.0.1',
+ }),
+ });
+ const c = checkVersionAlignment({
+ cwd: dir,
+ coreDir: path.join(dir, 'node_modules/@astryxdesign/core'),
+ nodeVersion: '',
+ configPath: null,
+ configTheme: null,
+ });
+ expect(['pass', 'warn']).toContain(c.status);
+ expect(c.message).not.toMatch(/NaN|undefined/);
+ if (c.fix) expect(c.fix).not.toMatch(/NaN|undefined/);
+ });
+});
diff --git a/packages/cli/api/error.mjs b/packages/cli/api/error.mjs
index f079f1f9a8..6b3728fa52 100644
--- a/packages/cli/api/error.mjs
+++ b/packages/cli/api/error.mjs
@@ -33,6 +33,6 @@ export class AstryxError extends Error {
super(message);
this.name = 'AstryxError';
this.code = code || ERROR_CODES.ERR_UNKNOWN;
- if (suggestions?.length) this.suggestions = suggestions;
+ if (Array.isArray(suggestions) && suggestions.length) this.suggestions = suggestions;
}
}
diff --git a/packages/cli/api/hook/hook.mjs b/packages/cli/api/hook/hook.mjs
index 2c4929ff0c..65abffc51a 100644
--- a/packages/cli/api/hook/hook.mjs
+++ b/packages/cli/api/hook/hook.mjs
@@ -17,6 +17,8 @@
import {list} from './list/list.mjs';
import {detail as detailLeaf} from './detail/detail.mjs';
import {params as paramsLeaf} from './detail/params/params.mjs';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
/**
* @param {string} [name]
@@ -48,12 +50,35 @@ export async function hook(name, options = {}) {
const isListView = listFlag || category != null || !name;
const detail = detailOption ?? (isListView ? 'brief' : 'full');
+ // A public API caller could pass a non-string category; the list leaf does
+ // `category.toLowerCase()`, so guard it up front (same class as the name
+ // guard below) instead of throwing a raw TypeError with no `.code`.
+ if (category != null && typeof category !== 'string') {
+ throw new AstryxError(
+ `Unknown category "${String(category)}"`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,
+ );
+ }
+
// ── List mode ──────────────────────────────────────────────────
if (category || listFlag || !name) {
return list({cwd, category, detail, zh, lang});
}
// ── Single hook ────────────────────────────────────────────────
+ // A public API caller could pass a non-string name (the CLI only ever passes
+ // string|undefined). Guard it up front so the leaves' `name.replace(...)` /
+ // `name.toLowerCase()` don't throw a raw TypeError with no `.code` (which the
+ // CLI would downgrade to ERR_UNKNOWN). Mirrors the component() dispatcher.
+ if (typeof name !== 'string') {
+ throw new AstryxError(
+ `No hook named "${String(name)}"`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_HOOK,
+ );
+ }
+
if (paramsFlag) {
return paramsLeaf(name, {cwd, zh, lang});
}
diff --git a/packages/cli/api/hook/hook.test.mjs b/packages/cli/api/hook/hook.test.mjs
new file mode 100644
index 0000000000..9249f2d472
--- /dev/null
+++ b/packages/cli/api/hook/hook.test.mjs
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Dispatcher-level tests for hook() — the argument-shape routing above
+ * the list/detail/params leaves. The leaves have their own tests; this pins the
+ * router: no name / --list / --category -> hook.list, bare name -> hook.detail,
+ * --params -> hook.detail.params, an unknown --category -> ERR_UNKNOWN_CATEGORY,
+ * and a non-string name -> a coded ERR_UNKNOWN_HOOK (not a raw TypeError).
+ * Runs against the real @astryxdesign/core hooks.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {hook} from './hook.mjs';
+import {AstryxError} from '../error.mjs';
+
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+const cwd = REPO;
+const SLOW = 30_000;
+
+describe('hook() dispatcher routing', () => {
+ it('no name -> hook.list', async () => {
+ const r = await hook(undefined, {cwd});
+ expect(r.type).toBe('hook.list');
+ expect(r.data.components).toBeDefined();
+ }, SLOW);
+
+ it('--list -> hook.list', async () => {
+ expect((await hook(undefined, {cwd, list: true})).type).toBe('hook.list');
+ }, SLOW);
+
+ it('--category (known) -> filtered hook.list', async () => {
+ const all = await hook(undefined, {cwd});
+ const someCategory = Object.keys(all.data.components)[0];
+ const r = await hook(undefined, {cwd, category: someCategory});
+ expect(r.type).toBe('hook.list');
+ expect(Object.keys(r.data.components)).toEqual([someCategory]);
+ }, SLOW);
+
+ it('--category (unknown) -> ERR_UNKNOWN_CATEGORY', async () => {
+ await expect(
+ hook(undefined, {cwd, category: 'zzz-not-a-real-category'}),
+ ).rejects.toMatchObject({code: 'ERR_UNKNOWN_CATEGORY'});
+ }, SLOW);
+
+ it('bare name -> hook.detail', async () => {
+ expect((await hook('useMediaQuery', {cwd})).type).toBe('hook.detail');
+ }, SLOW);
+
+ it('--params -> hook.detail.params', async () => {
+ expect((await hook('useMediaQuery', {cwd, params: true})).type).toBe(
+ 'hook.detail.params',
+ );
+ }, SLOW);
+
+ it('a non-string name throws a coded error (not a raw TypeError)', async () => {
+ for (const bad of [42, {}, [1]]) {
+ const err = await hook(/** @type {any} */ (bad), {cwd}).catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_HOOK');
+ }
+ }, SLOW);
+
+ it('a non-string category throws a coded error (not a raw TypeError)', async () => {
+ for (const bad of [123, {}, [1]]) {
+ const err = await hook(undefined, {
+ cwd,
+ category: /** @type {any} */ (bad),
+ }).catch(e => e);
+ expect(err).toBeInstanceOf(AstryxError);
+ expect(err.code).toBe('ERR_UNKNOWN_CATEGORY');
+ }
+ }, SLOW);
+});
diff --git a/packages/cli/api/init/init.test.mjs b/packages/cli/api/init/init.test.mjs
index eeb017ae5c..3017319e4d 100644
--- a/packages/cli/api/init/init.test.mjs
+++ b/packages/cli/api/init/init.test.mjs
@@ -156,3 +156,28 @@ describe('init() — logger', () => {
expect(text).toContain(getNextSteps('npx astryx')[2].slice(0, 20));
});
});
+
+describe('init() — write-path safety', () => {
+ it('template scaffold refuses to clobber an existing page.tsx', async () => {
+ const dest = path.join(tmpDir, 'src', 'pages', 'blank');
+ fs.mkdirSync(dest, {recursive: true});
+ fs.writeFileSync(path.join(dest, 'page.tsx'), 'MY EXISTING FILE');
+ await expect(
+ init({features: 'template', templateName: 'blank'}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_FILE_EXISTS});
+ // user's file is untouched
+ expect(fs.readFileSync(path.join(dest, 'page.tsx'), 'utf8')).toBe('MY EXISTING FILE');
+ });
+
+ it('throws ERR_UNKNOWN_AGENT for an unknown --agent value', async () => {
+ await expect(
+ init({features: 'agents', agent: 'claud'}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_UNKNOWN_AGENT});
+ });
+
+ it('rejects a traversal templateName before any write (ERR_UNKNOWN_TEMPLATE)', async () => {
+ await expect(
+ init({features: 'template', templateName: '../../etc/evil'}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_UNKNOWN_TEMPLATE});
+ });
+});
diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjs
index a4724285d8..dc63d36193 100644
--- a/packages/cli/api/init/run/run.mjs
+++ b/packages/cli/api/init/run/run.mjs
@@ -26,6 +26,7 @@ import {ERROR_CODES} from '../../../lib/error-codes.mjs';
import {logger} from '../../logger.mjs';
const VALID_FEATURES = ['agents', 'theme', 'template'];
+const VALID_AGENTS = ['claude', 'cursor', 'codex', 'hermes', 'all'];
/**
* Build the "Next steps" lines printed at the end of `astryx init`.
@@ -68,6 +69,16 @@ export function getNextSteps(invocation) {
* @param {import('../init.type.mjs').InitRunData} data
*/
function applyAgents(cwd, options, invocation, data) {
+ // Validate --agent up front (a hard error, not a swallowed install failure).
+ // ERR_UNKNOWN_AGENT was defined but never wired — a typo like `--agent claud`
+ // otherwise silently fell back to writing AGENTS.md. Mirrors --features.
+ if (options.agent && !VALID_AGENTS.includes(options.agent)) {
+ throw new AstryxError(
+ `Unknown agent "${options.agent}". Valid agents: ${VALID_AGENTS.join(', ')}`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_AGENT,
+ );
+ }
try {
const paths = options.agentDocsPath
? Array.isArray(options.agentDocsPath)
@@ -140,8 +151,19 @@ function applyTemplate(cwd, {templateName}, invocation, data) {
const outputDir = path.resolve(cwd, `./src/pages/${templateName}`);
const srcPath = path.join(CLI_ROOT, 'templates', 'pages', templateName, 'page.tsx');
+ const destFile = path.join(outputDir, 'page.tsx');
+ // Don't clobber a user's existing page — same guard the peer template/copy and
+ // theme/add write-leaves apply (init is a public API surface too).
+ if (fs.existsSync(destFile)) {
+ const relDest = path.relative(cwd, destFile) || destFile;
+ throw new AstryxError(
+ `Refusing to overwrite existing file ${relDest}.`,
+ undefined,
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
fs.mkdirSync(outputDir, {recursive: true});
- fs.copyFileSync(srcPath, path.join(outputDir, 'page.tsx'));
+ fs.copyFileSync(srcPath, destFile);
const rel = path.relative(cwd, outputDir);
logger.log(`✓ Template created at ${rel}/page.tsx`);
data.template = 'created';
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index a8fb82c8fa..d920ec0318 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -324,7 +324,22 @@ export async function validateLocalIntegration(cwd = process.cwd()) {
* @returns {Promise<ValidateResult>}
*/
export async function validateInstalledIntegration(spec, cwd = process.cwd()) {
- const packageDir = resolvePackageDir(spec, cwd);
+ // resolvePackageDir throws (path-safety guard) on a spec with path segments,
+ // `..`, or an absolute path. Every other malformed input to this command
+ // degrades into a diagnostic — so catch it here and return an issue instead
+ // of letting the throw escape to a raw stack (human) / generic ERR_UNKNOWN
+ // (--json).
+ let packageDir;
+ try {
+ packageDir = resolvePackageDir(spec, cwd);
+ } catch (err) {
+ return {
+ found: true,
+ name: spec,
+ version: undefined,
+ issues: [error('invalid_package_spec', /** @type {any} */ (err).message)],
+ };
+ }
const pkgJsonPath = path.join(packageDir, 'package.json');
/** @type {{name?: string, version?: string}} */
diff --git a/packages/cli/api/integration/validate-integration.test.mjs b/packages/cli/api/integration/validate-integration.test.mjs
index 60bee51a92..1240055dd3 100644
--- a/packages/cli/api/integration/validate-integration.test.mjs
+++ b/packages/cli/api/integration/validate-integration.test.mjs
@@ -219,4 +219,30 @@ describe('validate-integration API', () => {
const result = await validateLocalIntegration(pkgDir);
expect(byCode(result.issues, 'invalid_component')).toHaveLength(1);
});
+
+ it('degrades a path-unsafe package spec (..) into a diagnostic instead of crashing', async () => {
+ const consumer = path.join(tmpDir, 'consumer');
+ fs.mkdirSync(consumer, {recursive: true});
+ fs.writeFileSync(
+ path.join(consumer, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ // resolvePackageDir throws on a spec with `..`; it must be caught and
+ // surfaced as an issue, not escape as a raw stack / generic ERR_UNKNOWN.
+ const result = await validateInstalledIntegration('../evil', consumer);
+ expect(result.found).toBe(true);
+ expect(byCode(result.issues, 'invalid_package_spec')).toHaveLength(1);
+ expect(summarizeIssues(result.issues).errors).toBeGreaterThan(0);
+ });
+
+ it('degrades an absolute package spec into a diagnostic', async () => {
+ const consumer = path.join(tmpDir, 'consumer');
+ fs.mkdirSync(consumer, {recursive: true});
+ fs.writeFileSync(
+ path.join(consumer, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ const result = await validateInstalledIntegration('/etc/passwd', consumer);
+ expect(byCode(result.issues, 'invalid_package_spec')).toHaveLength(1);
+ });
});
diff --git a/packages/cli/api/layout/_adapter.mjs b/packages/cli/api/layout/_adapter.mjs
index 4f670530dd..f51b838d8a 100644
--- a/packages/cli/api/layout/_adapter.mjs
+++ b/packages/cli/api/layout/_adapter.mjs
@@ -92,6 +92,22 @@ export function formatIssue(issue) {
* @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]
*/
export async function analyze(expression, {form = 'auto', loose = false, cwd = process.cwd()} = {}) {
+ // Validate inputs in the API (not just the CLI): an empty expression or an
+ // unknown --form must error, not silently parse as an empty/compact layout.
+ if (typeof expression !== 'string' || expression.trim() === '') {
+ throw new AstryxError(
+ 'Layout expression is empty.',
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (form !== 'compact' && form !== 'outline' && form !== 'auto') {
+ throw new AstryxError(
+ `Invalid form "${form}". Must be one of: compact, outline, auto.`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_OPTION,
+ );
+ }
const registry = /** @type {import('../../lib/xle/xle-ast').Registry} */ (
/** @type {unknown} */ (await buildRegistry({cwd}))
);
diff --git a/packages/cli/api/layout/layout.test.mjs b/packages/cli/api/layout/layout.test.mjs
index 4a2ab4a312..15868b9910 100644
--- a/packages/cli/api/layout/layout.test.mjs
+++ b/packages/cli/api/layout/layout.test.mjs
@@ -145,6 +145,45 @@ describe('layoutExpand', () => {
message: expect.stringMatching(/line 1/),
});
});
+
+ it('maps pathologically deep nesting to a coded parse error, not ERR_UNKNOWN', async () => {
+ await expect(layoutCheck('V > '.repeat(2000) + 'C')).rejects.toMatchObject({
+ code: 'ERR_LAYOUT_PARSE',
+ });
+ });
+
+ it('wraps top-level repeats and groups in a fragment (valid JSX)', async () => {
+ for (const expr of ['B"Sign in"*3', '(B"a" + B"b")', '(B"a" + B"b")*2']) {
+ const {data} = await layoutExpand(expr);
+ expectValidTsx(data.code);
+ expect(data.code).toContain('<>');
+ }
+ }, SLOW);
+
+ it('wraps a top-level outline repeat block in a fragment', async () => {
+ const {data} = await layoutExpand('repeat 3:\n B "x"', {form: 'outline'});
+ expectValidTsx(data.code);
+ }, SLOW);
+
+ it('emits JSX-safe TSX for text payloads containing < and >', async () => {
+ const result = await layoutExpand('Text"5 < 3 and 3 > 1"');
+ expectValidTsx(result.data.code);
+ }, SLOW);
+
+ it('emits JSX-safe TSX for text payloads containing { and }', async () => {
+ const result = await layoutExpand('Text"cost is {price}"');
+ expectValidTsx(result.data.code);
+ }, SLOW);
+
+ it('emits JSX-safe TSX when a text payload looks like a closing tag', async () => {
+ const result = await layoutExpand('Text"end</Text><img/>"');
+ expectValidTsx(result.data.code);
+ }, SLOW);
+
+ it('emits JSX-safe TSX for JSX-special chars in outline form', async () => {
+ const result = await layoutExpand('VStack\n Text "a < b"', {form: 'outline'});
+ expectValidTsx(result.data.code);
+ }, SLOW);
});
describe('layoutCheck', () => {
@@ -239,3 +278,20 @@ describe('layoutGrammar', () => {
expect(Object.values(result.data.aliases)).not.toContain(undefined);
});
});
+
+
+describe('layout — input validation (API matches CLI)', () => {
+ it('rejects an invalid --form value instead of silently parsing as compact', async () => {
+ await expect(layoutCheck('V > C', {form: /** @type {any} */ ('xml')})).rejects.toMatchObject({
+ code: 'ERR_INVALID_OPTION',
+ });
+ await expect(layoutExpand('V > C', {form: /** @type {any} */ ('nonsense')})).rejects.toMatchObject({
+ code: 'ERR_INVALID_OPTION',
+ });
+ });
+
+ it('rejects an empty expression at the API layer', async () => {
+ await expect(layoutCheck('')).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ await expect(layoutExpand(' ')).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ });
+});
diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjs
index 6915cca619..5d080602bb 100644
--- a/packages/cli/api/search/search.mjs
+++ b/packages/cli/api/search/search.mjs
@@ -43,6 +43,7 @@ import {discoverHooks, findHookDoc} from '../../lib/hook-discovery.mjs';
import {levenshteinDistance} from '../../lib/string-utils.mjs';
import {discoverTemplates, extractComponents} from '../template/template.mjs';
import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
const DOCS_DIR = path.join(CLI_ROOT, 'docs');
@@ -558,15 +559,32 @@ export async function search(query, options = {}) {
const {cwd = process.cwd(), type, limit = 20} = options;
if (!query || !String(query).trim()) {
- throw new AstryxError('A search query is required', [
- {name: 'astryx search button', reason: 'example'},
- ]);
+ throw new AstryxError(
+ 'A search query is required',
+ [{name: 'astryx search button', reason: 'example'}],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
}
if (type && !SEARCH_DOMAINS.includes(type)) {
throw new AstryxError(
`Unknown --type "${type}"`,
SEARCH_DOMAINS.map(d => ({name: d, reason: 'valid type'})),
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+
+ // Validate limit here (not just in the CLI) so direct API callers get the same
+ // contract: a non-positive or non-integer limit is an error, never a silent
+ // "return everything". (Previously `limit <= 0` fell through to the full set.)
+ if (
+ limit != null &&
+ (!Number.isInteger(limit) || limit <= 0)
+ ) {
+ throw new AstryxError(
+ `Invalid limit "${limit}". Must be a positive integer.`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
);
}
@@ -610,7 +628,7 @@ export async function search(query, options = {}) {
a.name.localeCompare(b.name),
);
- const limited = limit > 0 ? scored.slice(0, limit) : scored;
+ const limited = scored.slice(0, limit);
return {type: 'search', data: {query: String(query).trim(), results: limited}};
}
diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjs
new file mode 100644
index 0000000000..d5e8279570
--- /dev/null
+++ b/packages/cli/api/search/search.test.mjs
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the `search` leaf (api/search/search.mjs), run
+ * against the real @astryxdesign/core registry. `search` had no api-level tests;
+ * this locks the envelope, ranking invariants, the `--type`/limit handling, and
+ * the error paths.
+ *
+ * The API validates its own inputs (not just the CLI): a non-positive/non-integer
+ * `limit`, an empty query, and a bad `--type` all throw AstryxError with the
+ * ERR_INVALID_ARGUMENT code, so a direct `@astryxdesign/cli/api` caller gets the
+ * same contract as `astryx search` on the command line.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {search, SEARCH_DOMAINS} from './search.mjs';
+
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+const cwd = REPO;
+const SLOW = 30_000;
+
+describe('search leaf — envelope + ranking', () => {
+ it('returns a `search` envelope with query + results', async () => {
+ const r = await search('button', {cwd});
+ expect(r.type).toBe('search');
+ expect(r.data.query).toBe('button');
+ expect(Array.isArray(r.data.results)).toBe(true);
+ expect(r.data.results.length).toBeGreaterThan(0);
+ }, SLOW);
+
+ it('returns an empty result set (not an error) for a no-match query', async () => {
+ const r = await search('zzznomatch99', {cwd});
+ expect(r.type).toBe('search');
+ expect(r.data.results).toEqual([]);
+ }, SLOW);
+
+ it('defaults to at most 20 results', async () => {
+ const r = await search('button', {cwd});
+ expect(r.data.results.length).toBeLessThanOrEqual(20);
+ }, SLOW);
+
+ it('caps results to a positive limit', async () => {
+ const r = await search('button', {cwd, limit: 2});
+ expect(r.data.results.length).toBeLessThanOrEqual(2);
+ }, SLOW);
+});
+
+describe('search leaf — --type filter', () => {
+ it('restricts results to the requested domain', async () => {
+ const r = await search('button', {cwd, type: 'component'});
+ expect(r.data.results.every(x => x.domain === 'component')).toBe(true);
+ }, SLOW);
+
+ it('exposes the valid domain list', () => {
+ expect(SEARCH_DOMAINS).toEqual(expect.arrayContaining(['component', 'hook', 'doc', 'template']));
+ });
+});
+
+describe('search leaf — error paths (pinned)', () => {
+ it('throws ERR_INVALID_ARGUMENT when the query is empty/whitespace', async () => {
+ await expect(search(' ', {cwd})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ message: expect.stringMatching(/query is required/i),
+ });
+ }, SLOW);
+
+ it('throws ERR_INVALID_ARGUMENT for an unknown --type', async () => {
+ await expect(
+ search('button', {cwd, type: /** @type {any} */ ('bogus')}),
+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
+ }, SLOW);
+});
+
+describe('search leaf — limit validation (API matches the CLI contract)', () => {
+ it('throws ERR_INVALID_ARGUMENT for a limit of 0 (no longer returns everything)', async () => {
+ await expect(search('button', {cwd, limit: 0})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ }, SLOW);
+
+ it('throws ERR_INVALID_ARGUMENT for a negative limit', async () => {
+ await expect(search('button', {cwd, limit: -5})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ }, SLOW);
+
+ it('throws ERR_INVALID_ARGUMENT for a non-integer limit', async () => {
+ await expect(search('button', {cwd, limit: 2.5})).rejects.toMatchObject({
+ code: 'ERR_INVALID_ARGUMENT',
+ });
+ }, SLOW);
+});
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index 5eebb0e648..5f55510277 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -16,7 +16,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {resolveCore} from '../_adapter.mjs';
-import {assertWithin, PathSafetyError} from '../../../utils/path-safety.mjs';
+import {assertWithin, sanitizeName, PathSafetyError} from '../../../utils/path-safety.mjs';
import {checkGhCli} from '../../../utils/github.mjs';
import {Project} from '../../../lib/project.mjs';
import {
@@ -36,21 +36,54 @@ const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';
* left untouched.
*
* e.g. with ownerPackage '@astryxdesign/core':
- * '../theme/tokens.stylex' -> '@astryxdesign/core/theme'
+ * '../theme/tokens.stylex' -> '@astryxdesign/core/theme/tokens.stylex'
* '../utils/mergeProps' -> '@astryxdesign/core/utils'
+ * '../../locales/en.json' -> '@astryxdesign/core/locales/en.json'
+ * import('../Tooltip/Tooltip') -> import('@astryxdesign/core/Tooltip')
+ *
+ * Most sibling dirs are barrels, so the top-dir collapse (`../utils/x` ->
+ * `<pkg>/utils`) resolves. Two shapes must NOT be collapsed to the top dir:
+ * - Asset files (`.json`, `.css`): exported by full subpath (e.g.
+ * `./locales/*.json`, `./reset.css`), and collapsing a two-levels-up
+ * `../../locales/x.json` would emit the invalid `<pkg>/..`.
+ * - The theme StyleX token module (`../theme/tokens.stylex`): the StyleX
+ * compiler needs the real module, which core ships as the dedicated
+ * `./theme/tokens.stylex` export (the in-repo charts consumer imports it
+ * by that exact subpath). Other `.stylex` files (e.g. a component-local
+ * `../Layer/layerAnimations.stylex`) are NOT exported by subpath, so they
+ * keep the barrel collapse.
*
* @param {string} content
* @param {string} [ownerPackage]
*/
export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
- return content.replace(
- /(from\s+['"])(\.\.\/.+?)(['"])/g,
- (match, prefix, importPath, suffix) => {
- const parts = importPath.replace(/^\.\.\//, '').split('/');
- const topDir = parts[0];
- return `${prefix}${ownerPackage}/${topDir}${suffix}`;
- },
- );
+ /** @param {string} importPath */
+ const mapTarget = importPath => {
+ // Strip ALL leading `../` so a two-levels-up path never yields `<pkg>/..`.
+ const rest = importPath.replace(/^(?:\.\.\/)+/, '');
+ const parts = rest.split('/');
+ const last = parts[parts.length - 1];
+ // Asset files are resolved by exact export / wildcard, never a barrel.
+ if (/\.(?:json|css)$/.test(last)) {
+ return `${ownerPackage}/${rest}`;
+ }
+ // The theme token module is a dedicated deep StyleX export.
+ if (parts[0] === 'theme' && /\.stylex(?:\.[cm]?[jt]sx?)?$/.test(last)) {
+ return `${ownerPackage}/${rest}`;
+ }
+ return `${ownerPackage}/${parts[0]}`;
+ };
+ return content
+ .replace(
+ /(from\s+['"])(\.\.\/[^'"]+)(['"])/g,
+ (_m, prefix, importPath, suffix) =>
+ `${prefix}${mapTarget(importPath)}${suffix}`,
+ )
+ .replace(
+ /(import\(\s*['"])(\.\.\/[^'"]+)(['"])/g,
+ (_m, prefix, importPath, suffix) =>
+ `${prefix}${mapTarget(importPath)}${suffix}`,
+ );
}
/**
@@ -153,6 +186,19 @@ export async function swizzleCopy(component, options = {}) {
const dirName = component.replace(/^XDS/, '');
+ // The component name becomes a path segment in the output dir
+ // (path.join(outputBase, dirName)), so a name containing `..` or a separator
+ // would escape the assertWithin(output) guard. Reject it up front — a real
+ // component name is a bare identifier.
+ try {
+ sanitizeName(dirName, {label: 'component name'});
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ throw new AstryxError(err.message, [], ERROR_CODES.ERR_PATH_TRAVERSAL);
+ }
+ throw err;
+ }
+
const {loadedIntegrations, project} = await loadConfigSafely(cwd);
const coreIssuesUrl = project
? project.issuesUrl({package: CORE_PACKAGE})
diff --git a/packages/cli/api/swizzle/copy/copy.test.mjs b/packages/cli/api/swizzle/copy/copy.test.mjs
new file mode 100644
index 0000000000..f362d876a6
--- /dev/null
+++ b/packages/cli/api/swizzle/copy/copy.test.mjs
@@ -0,0 +1,60 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the swizzle.copy leaf — path-safety + overwrite.
+ * The copy leaf writes files, so the output base AND the component name (which
+ * becomes a path segment) must both be confined to cwd.
+ */
+
+import {describe, it, expect, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {swizzle} from '../swizzle.mjs';
+
+// api/swizzle/copy/ -> up 5 = repo root.
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');
+const OUT = 'tmp-swizzle-copy-test';
+const SLOW = 30_000;
+
+describe('swizzle.copy — path safety', () => {
+ afterEach(() => {
+ fs.rmSync(path.join(REPO, OUT), {recursive: true, force: true});
+ // guard against an escape landing at <repo>/src
+ if (fs.existsSync(path.join(REPO, 'src'))) {
+ // never auto-delete a real src; the test asserts it wasn't created.
+ }
+ });
+
+ it('rejects a component name that traverses out of the output base', async () => {
+ await expect(
+ swizzle('../src', {cwd: REPO, output: './' + OUT}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ }, SLOW);
+
+ it('rejects a component name containing a path separator', async () => {
+ await expect(
+ swizzle('foo/bar', {cwd: REPO, output: './' + OUT}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ }, SLOW);
+
+ it('rejects an --output that escapes cwd (relative and absolute)', async () => {
+ await expect(swizzle('Button', {cwd: REPO, output: '../evil'})).rejects.toMatchObject({
+ code: 'ERR_PATH_TRAVERSAL',
+ });
+ await expect(swizzle('Button', {cwd: REPO, output: '/tmp/evil'})).rejects.toMatchObject({
+ code: 'ERR_PATH_TRAVERSAL',
+ });
+ }, SLOW);
+
+ it('copies a real component, then refuses to clobber without overwrite', async () => {
+ const r = await swizzle('Button', {cwd: REPO, output: './' + OUT});
+ expect(r.type).toBe('swizzle.copy');
+ expect(r.data.filesCopied).toBeGreaterThan(0);
+ await expect(swizzle('Button', {cwd: REPO, output: './' + OUT})).rejects.toMatchObject({
+ code: 'ERR_FILE_EXISTS',
+ });
+ const r2 = await swizzle('Button', {cwd: REPO, output: './' + OUT, overwrite: true});
+ expect(r2.data.filesCopied).toBe(r.data.filesCopied);
+ }, SLOW);
+});
diff --git a/packages/cli/api/swizzle/swizzle.test.mjs b/packages/cli/api/swizzle/swizzle.test.mjs
index bea9cc33e6..9a741885df 100644
--- a/packages/cli/api/swizzle/swizzle.test.mjs
+++ b/packages/cli/api/swizzle/swizzle.test.mjs
@@ -9,10 +9,12 @@ import {rewriteImports, swizzle} from './swizzle.mjs';
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
describe('rewriteImports', () => {
- it('rewrites ../theme/tokens to @astryxdesign/core/theme', () => {
+ it('preserves the theme token subpath (StyleX module is a dedicated export)', () => {
const input = `import { tokens } from '../theme/tokens.stylex';`;
const result = rewriteImports(input);
- expect(result).toBe(`import { tokens } from '@astryxdesign/core/theme';`);
+ expect(result).toBe(
+ `import { tokens } from '@astryxdesign/core/theme/tokens.stylex';`,
+ );
});
it('rewrites ../utils/mergeProps to @astryxdesign/core/utils', () => {
@@ -36,7 +38,9 @@ describe('rewriteImports', () => {
it('handles double quotes', () => {
const input = `import { tokens } from "../theme/tokens.stylex";`;
const result = rewriteImports(input);
- expect(result).toBe(`import { tokens } from "@astryxdesign/core/theme";`);
+ expect(result).toBe(
+ `import { tokens } from "@astryxdesign/core/theme/tokens.stylex";`,
+ );
});
it('handles multiple imports in one file', () => {
@@ -49,12 +53,37 @@ describe('rewriteImports', () => {
const result = rewriteImports(input);
expect(result).toBe(
[
- `import { tokens } from '@astryxdesign/core/theme';`,
+ `import { tokens } from '@astryxdesign/core/theme/tokens.stylex';`,
`import { mergeProps } from '@astryxdesign/core/utils';`,
`import { helper } from './helper';`,
].join('\n'),
);
});
+
+ it('rewrites a dynamic import() of a sibling component', () => {
+ const input = `const T = lazy(() => import('../Tooltip/Tooltip'));`;
+ expect(rewriteImports(input)).toBe(
+ `const T = lazy(() => import('@astryxdesign/core/Tooltip'));`,
+ );
+ });
+
+ it('rewrites a two-levels-up asset import to a valid subpath (never /..)', () => {
+ const input = `import en from '../../locales/en.json' with {type: 'json'};`;
+ const out = rewriteImports(input);
+ expect(out).not.toContain('@astryxdesign/core/..');
+ expect(out).toBe(
+ `import en from '@astryxdesign/core/locales/en.json' with {type: 'json'};`,
+ );
+ });
+
+ it('keeps the barrel collapse for a component-local .stylex (not a subpath export)', () => {
+ // Only theme/tokens.stylex is a dedicated deep export; component-local
+ // .stylex files are re-exported through the directory barrel.
+ const input = `import { s } from '../Layer/layerAnimations.stylex';`;
+ expect(rewriteImports(input)).toBe(
+ `import { s } from '@astryxdesign/core/Layer';`,
+ );
+ });
});
describe('swizzle() API', () => {
diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs
index 8ef53e12d5..0010faf8b8 100644
--- a/packages/cli/api/template/copy/copy.mjs
+++ b/packages/cli/api/template/copy/copy.mjs
@@ -24,10 +24,10 @@ import {stripTemplateAssetRefs} from '../_adapter.mjs';
* Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and
* return the `template.copy` receipt.
* @param {import('../_adapter.mjs').DiscoveredTemplate} match
- * @param {{targetPath: string, cwd: string}} ctx
+ * @param {{targetPath: string, cwd: string, overwrite?: boolean}} ctx
* @returns {import('../template.type.mjs').TemplateCopyResponse}
*/
-export function templateCopy(match, {targetPath, cwd}) {
+export function templateCopy(match, {targetPath, cwd, overwrite = false}) {
if (!fs.existsSync(match.filePath)) {
throw new AstryxError(
`No source file found for template "${match.dirName}"`,
@@ -73,6 +73,19 @@ export function templateCopy(match, {targetPath, cwd}) {
outputFilePath = path.join(outputDir, outputFileName);
}
+ // Refuse to clobber an existing file unless the caller opts in. The CLI has
+ // its own pre-flight collision message, but the API is a public surface
+ // (@astryxdesign/cli/api) and must enforce this itself — same guard the peer
+ // theme/add write-leaf applies.
+ if (!overwrite && fs.existsSync(outputFilePath)) {
+ const rel = path.relative(cwd, outputFilePath) || outputFilePath;
+ throw new AstryxError(
+ `Refusing to overwrite existing file ${rel}. Re-run with overwrite to replace it.`,
+ undefined,
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
+
fs.mkdirSync(outputDir, {recursive: true});
// Strip demo image references so the scaffolded file renders without a
diff --git a/packages/cli/api/template/copy/copy.test.mjs b/packages/cli/api/template/copy/copy.test.mjs
new file mode 100644
index 0000000000..4a637a6eed
--- /dev/null
+++ b/packages/cli/api/template/copy/copy.test.mjs
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the template.copy leaf — overwrite safety + path
+ * traversal. `template copy` writes files; the API must guard clobber/traversal
+ * itself (it's a public surface), not rely on the CLI wrapper.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {template} from '../template.mjs';
+
+const SLOW = 30_000;
+
+describe('template.copy — overwrite + path safety', () => {
+ let dir;
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-copy-'));
+ });
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
+
+ it('copies a page template into a directory as page.tsx', async () => {
+ const res = await template('blank', {targetPath: './dest', cwd: dir});
+ expect(res.type).toBe('template.copy');
+ expect(fs.existsSync(path.join(dir, 'dest', 'page.tsx'))).toBe(true);
+ }, SLOW);
+
+ it('refuses to overwrite an existing file (ERR_FILE_EXISTS), leaving it untouched', async () => {
+ fs.writeFileSync(path.join(dir, 'mine.tsx'), 'USER CODE');
+ await expect(
+ template('blank', {targetPath: './mine.tsx', cwd: dir}),
+ ).rejects.toMatchObject({code: 'ERR_FILE_EXISTS'});
+ expect(fs.readFileSync(path.join(dir, 'mine.tsx'), 'utf-8')).toBe('USER CODE');
+ }, SLOW);
+
+ it('overwrites when overwrite:true is passed', async () => {
+ fs.writeFileSync(path.join(dir, 'mine.tsx'), 'USER CODE');
+ const res = await template('blank', {targetPath: './mine.tsx', overwrite: true, cwd: dir});
+ expect(res.type).toBe('template.copy');
+ expect(fs.readFileSync(path.join(dir, 'mine.tsx'), 'utf-8')).not.toBe('USER CODE');
+ }, SLOW);
+
+ it('rejects a traversal target and writes nothing outside cwd', async () => {
+ await expect(
+ template('blank', {targetPath: '../escape.tsx', cwd: dir}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ expect(fs.existsSync(path.join(dir, '..', 'escape.tsx'))).toBe(false);
+ }, SLOW);
+});
diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs
index 845a943a0e..9b264d4926 100644
--- a/packages/cli/api/template/template.mjs
+++ b/packages/cli/api/template/template.mjs
@@ -53,6 +53,7 @@ export {
* @param {string} [name]
* @param {object} [options]
* @param {string} [options.targetPath]
+ * @param {boolean} [options.overwrite]
* @param {boolean} [options.list]
* @param {boolean} [options.skeleton]
* @param {boolean} [options.show]
@@ -67,6 +68,7 @@ export async function template(name, options = {}) {
skeleton = false,
show = false,
targetPath,
+ overwrite = false,
type,
package: packageFilter,
cwd = process.cwd(),
@@ -111,5 +113,5 @@ export async function template(name, options = {}) {
return templateShow(match);
}
- return templateCopy(match, {targetPath, cwd});
+ return templateCopy(match, {targetPath, cwd, overwrite});
}
diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjs
index c417f15164..85899f4e9a 100644
--- a/packages/cli/api/template/template.type.mjs
+++ b/packages/cli/api/template/template.type.mjs
@@ -79,6 +79,7 @@
* @property {'page' | 'block'} [type] Filter templates by kind: 'page' or 'block'. Only applies to list views.
* @property {string} [package] Narrow to templates from a specific package (id-only lookups across packages are ambiguous).
* @property {string} [targetPath]
+ * @property {boolean} [overwrite] Overwrite an existing target file instead of erroring (ERR_FILE_EXISTS).
* @property {string} [cwd]
*/
diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjs
index 478a38fb60..3becff3a44 100644
--- a/packages/cli/api/theme/add/add.mjs
+++ b/packages/cli/api/theme/add/add.mjs
@@ -110,10 +110,12 @@ export async function themeAdd(slug, options = {}) {
}
// Stage to temp files then rename, rolling back partials on failure so a
- // failed write never leaves a half-written theme.
- fs.mkdirSync(resolvedDir, {recursive: true});
+ // failed write never leaves a half-written theme. mkdir is inside the try so
+ // a failure (e.g. an ancestor is a file → EEXIST/ENOTDIR) surfaces as a
+ // stable ERR_WRITE_FAILED rather than leaking a raw fs errno + absolute path.
const staged = [];
try {
+ fs.mkdirSync(resolvedDir, {recursive: true});
for (const w of writes) {
const tmp = `${w.dest}.${process.pid}.tmp`;
const contents = stripCopyrightHeader(fs.readFileSync(w.src, 'utf-8'));
diff --git a/packages/cli/api/theme/add/add.test.mjs b/packages/cli/api/theme/add/add.test.mjs
index f35f731a62..8c0bda27de 100644
--- a/packages/cli/api/theme/add/add.test.mjs
+++ b/packages/cli/api/theme/add/add.test.mjs
@@ -85,4 +85,25 @@ describe('themeAdd (api/theme/add)', () => {
themeAdd('neutral', {cwd: tmpDir, targetPath: '../escape'}),
).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
});
+
+ it('surfaces ERR_WRITE_FAILED (not a raw errno) when the target path is an existing file', async () => {
+ fs.writeFileSync(path.join(tmpDir, 'blocker'), 'x');
+ await expect(
+ themeAdd('neutral', {cwd: tmpDir, targetPath: 'blocker'}),
+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});
+ });
+
+ it('surfaces ERR_WRITE_FAILED when an ancestor of the default dir is a file', async () => {
+ // A file named `src` blocks mkdir of src/themes/neutral (ENOTDIR).
+ fs.writeFileSync(path.join(tmpDir, 'src'), 'x');
+ await expect(themeAdd('neutral', {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_WRITE_FAILED',
+ });
+ });
+
+ it('adds into an existing empty target directory', async () => {
+ fs.mkdirSync(path.join(tmpDir, 'mydir'));
+ const r = await themeAdd('neutral', {cwd: tmpDir, targetPath: 'mydir'});
+ expect(r.data.outputDir).toBe('mydir');
+ });
});
diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjs
index 7cc166cf1d..529a57bd51 100644
--- a/packages/cli/api/upgrade/run/run.mjs
+++ b/packages/cli/api/upgrade/run/run.mjs
@@ -41,6 +41,7 @@ import {getCliInvocation} from '../../../utils/package-manager.mjs';
import {ERROR_CODES} from '../../../lib/error-codes.mjs';
import {AstryxError} from '../../error.mjs';
import {logger} from '../../logger.mjs';
+import {assertWithin, PathSafetyError} from '../../../utils/path-safety.mjs';
/**
* Run the upgrade pipeline for a validated, non-list invocation. Returns the
@@ -53,10 +54,25 @@ import {logger} from '../../logger.mjs';
*/
export async function run(options = {}, {cwd = process.cwd()} = {}) {
// Resolve the source dir against the API's cwd (not process.cwd()) so a
- // programmatic caller in another directory scans the right tree. The runners
- // do path.resolve(srcPath); an already-absolute path is idempotent there, so
- // this is byte-identical for the CLI (where cwd === process.cwd()).
- const path_ = path.resolve(cwd, options.path ?? './src');
+ // programmatic caller in another directory scans the right tree. Confine it to
+ // cwd: --apply rewrites files in place, so a `..`-escaping or out-of-tree
+ // absolute --path must be rejected (parity with template/theme/swizzle/layout,
+ // and this is the most destructive command). allowAbsolute permits an absolute
+ // path that still resolves inside cwd.
+ let path_;
+ try {
+ path_ = assertWithin(options.path ?? './src', cwd, {
+ allowAbsolute: true,
+ label: 'source directory',
+ });
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ logger.error(err.message);
+ logger.log('Aborted\n');
+ throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
+ }
+ throw err;
+ }
const apply = options.apply ?? false;
const currentVersion = /** @type {string} */ (options.from);
diff --git a/packages/cli/api/upgrade/run/run.test.mjs b/packages/cli/api/upgrade/run/run.test.mjs
new file mode 100644
index 0000000000..c5cd018b55
--- /dev/null
+++ b/packages/cli/api/upgrade/run/run.test.mjs
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for the upgrade.run leaf — the --path scan dir must be
+ * confined to cwd (upgrade rewrites source in place with --apply, so an escaping
+ * or out-of-tree path must be rejected).
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {upgrade} from '../upgrade.mjs';
+
+const SLOW = 30_000;
+
+function seedProject(dir) {
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: 'x', version: '1.0.0', dependencies: {'@astryxdesign/core': '0.1.8'}}),
+ );
+ const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');
+ fs.mkdirSync(core, {recursive: true});
+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({name: '@astryxdesign/core', version: '0.1.8'}));
+ fs.mkdirSync(path.join(dir, 'src'), {recursive: true});
+ fs.writeFileSync(path.join(dir, 'src', 'index.ts'), 'const x = 1;\n');
+}
+
+describe('upgrade.run — --path confinement', () => {
+ let dir;
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-path-'));
+ seedProject(dir);
+ });
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
+
+ it('accepts a normal in-tree --path (dry run)', async () => {
+ const res = await upgrade({from: '0.0.1', path: 'src'}, {cwd: dir});
+ expect(res.type).toBe('upgrade.run');
+ }, SLOW);
+
+ it('rejects a ../-escaping --path with ERR_PATH_TRAVERSAL', async () => {
+ await expect(
+ upgrade({from: '0.0.1', path: '../../../../etc'}, {cwd: dir}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ }, SLOW);
+
+ it('rejects an absolute --path outside cwd with ERR_PATH_TRAVERSAL', async () => {
+ await expect(
+ upgrade({from: '0.0.1', path: os.tmpdir()}, {cwd: dir}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ }, SLOW);
+});
diff --git a/packages/cli/cli/commands/blog.test.mjs b/packages/cli/cli/commands/blog.test.mjs
index 34bf7a6d27..d0886fa1ea 100644
--- a/packages/cli/cli/commands/blog.test.mjs
+++ b/packages/cli/cli/commands/blog.test.mjs
@@ -85,4 +85,12 @@ describe('blog CLI — json-enabled', () => {
expect(stdout).toMatch(/Astryx blog · feed:/);
expect(stdout).toMatch(/how-astryx-works/);
});
+
+ it('surfaces the API error code and exits non-zero for an unknown slug (--json)', async () => {
+ const {status, stdout} = await runCli(['blog', 'no-such-post', '--json']);
+ expect(status).not.toBe(0);
+ const env = JSON.parse(stdout);
+ expect(env.error).toBeDefined();
+ expect(env.code).toBe('ERR_UNKNOWN_POST');
+ });
});
diff --git a/packages/cli/cli/commands/build.error-codes.test.mjs b/packages/cli/cli/commands/build.error-codes.test.mjs
new file mode 100644
index 0000000000..b39aa658bb
--- /dev/null
+++ b/packages/cli/cli/commands/build.error-codes.test.mjs
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CLI-level tests for `astryx build` error-envelope faithfulness.
+ *
+ * The build command delegates to search(), which validates --type and --limit
+ * and throws AstryxError with a specific code. The CLI wrapper must propagate
+ * that `code` into the --json error envelope (the field agents/CI branch on)
+ * instead of dropping it and falling through to the generic ERR_UNKNOWN.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {runCli} from '../../test-utils/run-cli.mjs';
+
+// Run against the monorepo root so @astryxdesign/core is discoverable.
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+const SLOW = 30_000;
+
+describe('build --json error envelopes carry the API error code', () => {
+ it('bogus --type -> ERR_INVALID_ARGUMENT (not ERR_UNKNOWN)', async () => {
+ const {status, stdout} = await runCli(
+ ['build', 'dashboard', '--type', 'bogus', '--json'],
+ REPO,
+ );
+ expect(status).toBe(1);
+ const env = JSON.parse(stdout);
+ expect(env.error).toMatch(/unknown --type/i);
+ expect(env.code).toBe('ERR_INVALID_ARGUMENT');
+ }, SLOW);
+
+ it('non-positive --limit -> ERR_INVALID_ARGUMENT', async () => {
+ const {status, stdout} = await runCli(
+ ['build', 'dashboard', '--limit', '0', '--json'],
+ REPO,
+ );
+ expect(status).toBe(1);
+ expect(JSON.parse(stdout).code).toBe('ERR_INVALID_ARGUMENT');
+ }, SLOW);
+
+ it('non-integer --limit -> ERR_INVALID_ARGUMENT', async () => {
+ const {status, stdout} = await runCli(
+ ['build', 'dashboard', '--limit', 'abc', '--json'],
+ REPO,
+ );
+ expect(status).toBe(1);
+ expect(JSON.parse(stdout).code).toBe('ERR_INVALID_ARGUMENT');
+ }, SLOW);
+});
diff --git a/packages/cli/cli/commands/build.mjs b/packages/cli/cli/commands/build.mjs
index af6e09073b..2057dcebbd 100644
--- a/packages/cli/cli/commands/build.mjs
+++ b/packages/cli/cli/commands/build.mjs
@@ -74,15 +74,11 @@ export function registerBuild(program) {
}
// Arg validation stays in the CLI.
- let limit = 60;
- if (options.limit != null) {
- const parsed = Number.parseInt(options.limit, 10);
- if (!Number.isFinite(parsed) || parsed <= 0) {
- cliError(`Invalid --limit value "${options.limit}". Must be a positive integer.`);
- return;
- }
- limit = parsed;
- }
+ // Parse --limit to a number; the API validates it (positive integer) and
+ // throws ERR_INVALID_ARGUMENT, so we pass NaN through rather than
+ // pre-rejecting with a generic code here (parity with `search`).
+ const limit =
+ options.limit != null ? Number.parseInt(options.limit, 10) : 60;
/** @type {import('../../api/build/build.type.mjs').BuildKitResponse} */
let result;
@@ -92,7 +88,7 @@ export function registerBuild(program) {
);
} catch (e) {
const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
- cliError(err.message, {suggestions: err.suggestions});
+ cliError(err.message, {suggestions: err.suggestions, code: err.code});
return;
}
diff --git a/packages/cli/cli/commands/layout.error-codes.test.mjs b/packages/cli/cli/commands/layout.error-codes.test.mjs
new file mode 100644
index 0000000000..4ed0ba7b1d
--- /dev/null
+++ b/packages/cli/cli/commands/layout.error-codes.test.mjs
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Error-code contract tests for the layout command wrapper. Locks the
+ * two foreseeable input errors to STABLE ERR_* codes (never ERR_UNKNOWN or a
+ * raw fs errno) and asserts --json/human exit parity:
+ * - empty expression → ERR_MISSING_ARGUMENT
+ * - --file <missing> → ERR_FILE_NOT_FOUND (not raw ENOENT), no stack leak
+ * Spawns the real binary so the bin error boundary is exercised faithfully.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_BIN = path.resolve(__dirname, '../../bin/astryx.mjs');
+
+function run(args) {
+ const res = spawnSync('node', [CLI_BIN, ...args], {
+ encoding: 'utf-8',
+ timeout: 20_000,
+ });
+ return {status: res.status, stdout: res.stdout || '', stderr: res.stderr || ''};
+}
+
+describe('layout --json error codes', () => {
+ for (const sub of ['expand', 'check']) {
+ it(`layout ${sub} "" → ERR_MISSING_ARGUMENT (not ERR_UNKNOWN)`, () => {
+ const r = run(['--json', 'layout', sub, '']);
+ expect(r.status).toBe(1);
+ const env = JSON.parse(r.stdout);
+ expect(env.code).toBe('ERR_MISSING_ARGUMENT');
+ expect(r.stderr).toBe('');
+ expect(r.stdout).not.toMatch(/\n\s+at /); // no stack frames
+ });
+
+ it(`layout ${sub} --file <missing> → ERR_FILE_NOT_FOUND (not ENOENT)`, () => {
+ const r = run([
+ '--json',
+ 'layout',
+ sub,
+ '--file',
+ '/tmp/definitely-missing-astryx-xyz.mjs',
+ ]);
+ expect(r.status).toBe(1);
+ const env = JSON.parse(r.stdout);
+ expect(env.code).toBe('ERR_FILE_NOT_FOUND');
+ expect(r.stderr).toBe('');
+ });
+
+ it(`layout ${sub}: --json and human agree on exit code (empty input)`, () => {
+ const human = run(['layout', sub, '']);
+ const json = run(['--json', 'layout', sub, '']);
+ expect(json.status).toBe(human.status);
+ expect(json.status).toBe(1);
+ });
+
+ it(`layout ${sub} --file <missing> in human mode leaks no stack trace`, () => {
+ const r = run(['layout', sub, '--file', '/tmp/definitely-missing-astryx-xyz.mjs']);
+ expect(r.status).toBe(1);
+ expect(r.stderr).not.toMatch(/\n\s+at /);
+ });
+ }
+});
diff --git a/packages/cli/cli/commands/layout.exit-parity.test.mjs b/packages/cli/cli/commands/layout.exit-parity.test.mjs
new file mode 100644
index 0000000000..b67f053344
--- /dev/null
+++ b/packages/cli/cli/commands/layout.exit-parity.test.mjs
@@ -0,0 +1,41 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CLI-level tests for `astryx layout check` exit-code parity.
+ *
+ * The exit code is the contract and must NOT depend on --json vs human mode:
+ * an invalid (but parseable) layout exits 1 in BOTH modes so `layout check`
+ * works as a CI gate / agent check without parsing stdout. Runs the real
+ * program in-process via the shared runCli harness.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {runCli} from '../../test-utils/run-cli.mjs';
+
+const SLOW = 30_000;
+// Parses fine, but references an unknown component -> data.valid: false
+// (a semantic error, surfaced as data, not a thrown ERR_LAYOUT_PARSE).
+const INVALID = 'ZzzUnknownComponent[foo=bar]';
+const VALID = 'K';
+
+describe('layout check — exit-code parity (--json vs human)', () => {
+ it('human mode exits 1 for an invalid (parseable) expression', async () => {
+ const {status} = await runCli(['layout', 'check', INVALID]);
+ expect(status).toBe(1);
+ }, SLOW);
+
+ it('--json exits 1 for the SAME invalid expression (modes agree)', async () => {
+ const {status, stdout} = await runCli(['layout', 'check', INVALID, '--json']);
+ const env = JSON.parse(stdout);
+ expect(env.type).toBe('layout.check');
+ expect(env.data.valid).toBe(false);
+ expect(status).toBe(1);
+ }, SLOW);
+
+ it('a valid expression exits 0 in both modes', async () => {
+ expect((await runCli(['layout', 'check', VALID])).status).toBe(0);
+ const {status, stdout} = await runCli(['layout', 'check', VALID, '--json']);
+ expect(JSON.parse(stdout).data.valid).toBe(true);
+ expect(status).toBe(0);
+ }, SLOW);
+});
diff --git a/packages/cli/cli/commands/layout.mjs b/packages/cli/cli/commands/layout.mjs
index f590e33174..9c4cab131d 100644
--- a/packages/cli/cli/commands/layout.mjs
+++ b/packages/cli/cli/commands/layout.mjs
@@ -15,6 +15,7 @@
import * as fs from 'node:fs';
import {jsonOut, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {layoutExpand, layoutCheck, layoutGrammar} from '../../api/layout/layout.mjs';
/**
@@ -50,7 +51,21 @@ import {layoutExpand, layoutCheck, layoutGrammar} from '../../api/layout/layout.
* @returns {Promise<string>}
*/
async function readExpression(expr, options = {}) {
- if (options.file) return fs.readFileSync(options.file, 'utf-8');
+ if (options.file) {
+ try {
+ return fs.readFileSync(options.file, 'utf-8');
+ } catch (e) {
+ const errno = /** @type {NodeJS.ErrnoException} */ (e);
+ if (errno && errno.code === 'ENOENT') {
+ // A --file pointing at a missing file is foreseeable — surface a
+ // stable code, not the raw ENOENT errno (and no stack in human mode).
+ cliError(`File not found: ${options.file}`, {
+ code: ERROR_CODES.ERR_FILE_NOT_FOUND,
+ });
+ }
+ throw e;
+ }
+ }
if (expr === '-') {
/** @type {Buffer[]} */
const chunks = [];
@@ -79,7 +94,10 @@ export function registerLayout(program) {
const json = program.opts().json || false;
const source = await readExpression(expression, options);
if (!source || source.trim() === '') {
- cliError('No layout expression given — pass it as an argument, via --file, or on stdin');
+ cliError(
+ 'No layout expression given — pass it as an argument, via --file, or on stdin',
+ {code: ERROR_CODES.ERR_MISSING_ARGUMENT},
+ );
return;
}
/** @type {LayoutExpandResponse} */
@@ -122,7 +140,10 @@ export function registerLayout(program) {
const json = program.opts().json || false;
const source = await readExpression(expression, options);
if (!source || source.trim() === '') {
- cliError('No layout expression given — pass it as an argument, via --file, or on stdin');
+ cliError(
+ 'No layout expression given — pass it as an argument, via --file, or on stdin',
+ {code: ERROR_CODES.ERR_MISSING_ARGUMENT},
+ );
return;
}
/** @type {LayoutCheckResponse} */
@@ -138,6 +159,12 @@ export function registerLayout(program) {
cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
return;
}
+ // Exit code is the contract and must NOT depend on --json vs human: an
+ // invalid (but parseable) layout exits 1 in BOTH modes so `layout check`
+ // works as a CI gate / agent check without parsing stdout. Decide it
+ // before the JSON return (parity with doctor / validate-integration).
+ if (!result.data.valid) process.exitCode = 1;
+
if (json) return jsonOut(result);
const {valid, form, errors, warnings, compact, outline} = result.data;
@@ -148,7 +175,6 @@ export function registerLayout(program) {
if (e.suggestions && e.suggestions.length > 0) humanLog(` did you mean: ${e.suggestions.join(', ')}?`);
}
humanLog('');
- process.exitCode = 1;
return;
}
humanLog(`\n✓ Valid (parsed as ${form})`);
diff --git a/packages/cli/cli/commands/search.mjs b/packages/cli/cli/commands/search.mjs
index d215151f58..2311b679af 100644
--- a/packages/cli/cli/commands/search.mjs
+++ b/packages/cli/cli/commands/search.mjs
@@ -41,15 +41,11 @@ export function registerSearch(program) {
.action(async (/** @type {string} */ query, /** @type {{type?: import('../../api/search/search.type.mjs').SearchDomain, limit?: string, detail?: boolean}} */ options) => {
const json = program.opts().json || false;
- let limit = 20;
- if (options.limit != null) {
- const parsed = Number.parseInt(options.limit, 10);
- if (!Number.isFinite(parsed) || parsed <= 0) {
- cliError(`Invalid --limit value "${options.limit}". Must be a positive integer.`);
- return;
- }
- limit = parsed;
- }
+ // Parse --limit to a number; the API validates it (positive integer) and
+ // throws ERR_INVALID_ARGUMENT, so we pass NaN through rather than
+ // pre-rejecting with a generic code here.
+ const limit =
+ options.limit != null ? Number.parseInt(options.limit, 10) : 20;
/** @type {import('../../api/search/search.type.mjs').SearchResponse} */
let result;
@@ -63,7 +59,7 @@ export function registerSearch(program) {
);
} catch (e) {
const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
- cliError(err.message, {suggestions: err.suggestions});
+ cliError(err.message, {suggestions: err.suggestions, code: err.code});
return;
}
diff --git a/packages/cli/cli/commands/swizzle.routing.test.mjs b/packages/cli/cli/commands/swizzle.routing.test.mjs
index d19eff6b4e..47b9295ab1 100644
--- a/packages/cli/cli/commands/swizzle.routing.test.mjs
+++ b/packages/cli/cli/commands/swizzle.routing.test.mjs
@@ -135,7 +135,7 @@ describe('swizzle — core feedback routing via config', () => {
path.join(project, 'components', 'astryx', 'Button', 'Button.tsx'),
'utf-8',
);
- expect(out).toContain(`from '@astryxdesign/core/theme'`);
+ expect(out).toContain(`from '@astryxdesign/core/theme/tokens.stylex'`);
expect(out).toContain(`from './helper'`);
});
@@ -252,7 +252,7 @@ describe('swizzle — ambiguous ownership', () => {
path.join(project, 'components', 'astryx', 'Button', 'Button.tsx'),
'utf-8',
);
- expect(out).toContain(`from '@astryxdesign/core/theme'`);
+ expect(out).toContain(`from '@astryxdesign/core/theme/tokens.stylex'`);
});
});
diff --git a/packages/cli/cli/commands/template.mjs b/packages/cli/cli/commands/template.mjs
index 7c3b41441a..615880fd24 100644
--- a/packages/cli/cli/commands/template.mjs
+++ b/packages/cli/cli/commands/template.mjs
@@ -108,6 +108,7 @@ export function registerTemplate(program) {
type: /** @type {'page' | 'block' | undefined} */ (options.type),
package: options.package,
targetPath,
+ overwrite: options.overwrite,
cwd: process.cwd(),
})
);
diff --git a/packages/cli/cli/error-envelope-code.test.mjs b/packages/cli/cli/error-envelope-code.test.mjs
new file mode 100644
index 0000000000..5db2216b26
--- /dev/null
+++ b/packages/cli/cli/error-envelope-code.test.mjs
@@ -0,0 +1,38 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Static regression: every inline JSON error envelope constructed in
+ * cli/index.mjs carries a `code` field.
+ *
+ * The JSON contract guarantees `code` always appears on an error envelope so
+ * consumers can branch on it unconditionally. Most error envelopes flow through
+ * `toErrorEnvelope`/`cliError` (which always set a code), but cli/index.mjs
+ * hand-builds two envelopes (the --json gate rejection and the postAction
+ * "completed without emitting an envelope" fallback). This scan catches a new
+ * hand-built envelope that forgets `code`.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+
+describe('inline JSON error envelopes carry a `code`', () => {
+ it('cli/index.mjs — no hand-built error envelope missing code', () => {
+ const file = path.resolve(HERE, 'index.mjs');
+ const lines = fs.readFileSync(file, 'utf-8').split('\n');
+ const offenders = [];
+ lines.forEach((ln, i) => {
+ if (/^\s*error:/.test(ln)) {
+ const windowText = lines.slice(Math.max(0, i - 4), i + 6).join('\n');
+ if (!/\bcode:/.test(windowText)) offenders.push(i + 1);
+ }
+ });
+ expect(
+ offenders,
+ `index.mjs error envelope(s) missing code at line(s) ${offenders.join(', ')}`,
+ ).toEqual([]);
+ });
+});
diff --git a/packages/cli/cli/index.mjs b/packages/cli/cli/index.mjs
index 13a9827592..42bb480426 100644
--- a/packages/cli/cli/index.mjs
+++ b/packages/cli/cli/index.mjs
@@ -263,6 +263,10 @@ export async function createProgram() {
console.log(JSON.stringify({
apiVersion: API_VERSION,
error: `Internal: '${fullName}' completed without emitting a JSON envelope`,
+ // `code` always appears on an error envelope so consumers can branch on
+ // it unconditionally. This belt-and-suspenders path is an internal
+ // condition, so it uses the generic ERR_UNKNOWN.
+ code: ERROR_CODES.ERR_UNKNOWN,
}, null, 2));
process.exit(1);
});
diff --git a/packages/cli/codemods/__tests__/runner.test.mjs b/packages/cli/codemods/__tests__/runner.test.mjs
index 5e8073995f..b9da59698c 100644
--- a/packages/cli/codemods/__tests__/runner.test.mjs
+++ b/packages/cli/codemods/__tests__/runner.test.mjs
@@ -70,6 +70,61 @@ describe('runCodemods — unified config codemod path', () => {
).toContain('new-theme');
});
+ it('surfaces a findConfigPath throw (multiple config files) as a structured error, not a crash', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ // Two config files → findConfigPath throws. Config codemods run before the
+ // strict project loader, so an uncaught throw here would abort the whole
+ // upgrade. It must degrade to a structured error and let the run continue.
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.ts'),
+ `export default { theme: 'x' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.js'),
+ `export default { theme: 'x' };\n`,
+ );
+ const srcDir = path.join(tmpDir, 'src');
+ fs.mkdirSync(srcDir);
+ fs.writeFileSync(path.join(srcDir, 'a.tsx'), 'const a = 1;\n');
+
+ const versionManifests = [
+ {
+ version: '0.1.3',
+ transforms: [
+ {
+ name: 'cfg',
+ meta: {title: 'cfg', codemodType: 'config'},
+ transform: () => null,
+ },
+ // A code codemod that MUST still run after the config one fails.
+ {
+ name: 'code-after',
+ meta: {title: 'code after'},
+ transform: file =>
+ file.source.includes('const a')
+ ? file.source.replace('const a', 'const b')
+ : undefined,
+ },
+ ],
+ },
+ ];
+
+ // Must NOT throw; the multi-config problem is surfaced as a structured
+ // error, and the subsequent code codemod is still reached.
+ const result = await runCodemods(versionManifests, {
+ apply: false,
+ path: './src',
+ silent: true,
+ });
+ expect(
+ result.errors.some(e => /Multiple Astryx config files/.test(e.error)),
+ ).toBe(true);
+ expect(result.totalFilesChanged).toBe(1); // code-after previewed a change
+ });
+
it('still runs core code codemods against source files', async () => {
const srcDir = path.join(tmpDir, 'src');
fs.mkdirSync(srcDir);
@@ -139,3 +194,42 @@ describe('runCodemods — unified config codemod path', () => {
);
});
});
+
+describe('findSourceFiles — scan boundaries (symlink + build dirs)', () => {
+ const manifests = [
+ {
+ version: '0.1.3',
+ transforms: [
+ {name: 'p', meta: {title: 'p'}, transform: f => f.source.replace(/foo/g, 'bar')},
+ ],
+ },
+ ];
+
+ it('does not follow a symlinked file out of the scan tree', async () => {
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
+ fs.mkdirSync(outside, {recursive: true});
+ const secret = path.join(outside, 'secret.ts');
+ fs.writeFileSync(secret, 'const foo = 1;\n');
+ fs.writeFileSync(path.join(tmpDir, 'src', 'real.ts'), 'const foo = 2;\n');
+ fs.symlinkSync(secret, path.join(tmpDir, 'src', 'link.ts'));
+
+ const r = await runCodemods(manifests, {apply: true, path: './src', silent: true});
+ // the symlink target (outside the tree) must be untouched
+ expect(fs.readFileSync(secret, 'utf-8')).toBe('const foo = 1;\n');
+ expect(r.writtenFiles.map(f => path.basename(f))).toEqual(['real.ts']);
+ });
+
+ it('does not scan generated-output dirs (dist/build/out)', async () => {
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
+ fs.mkdirSync(path.join(tmpDir, 'dist'), {recursive: true});
+ fs.mkdirSync(path.join(tmpDir, 'build'), {recursive: true});
+ fs.writeFileSync(path.join(tmpDir, 'src', 'a.ts'), 'const foo = 1;\n');
+ fs.writeFileSync(path.join(tmpDir, 'dist', 'b.js'), 'const foo = 2;\n');
+ fs.writeFileSync(path.join(tmpDir, 'build', 'c.js'), 'const foo = 3;\n');
+
+ const r = await runCodemods(manifests, {apply: true, path: '.', silent: true});
+ expect(r.writtenFiles.map(f => path.basename(f))).toEqual(['a.ts']);
+ expect(fs.readFileSync(path.join(tmpDir, 'dist', 'b.js'), 'utf-8')).toContain('foo');
+ });
+});
diff --git a/packages/cli/codemods/run-codemod.mjs b/packages/cli/codemods/run-codemod.mjs
index 0a18915d86..b052a073d5 100644
--- a/packages/cli/codemods/run-codemod.mjs
+++ b/packages/cli/codemods/run-codemod.mjs
@@ -31,7 +31,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '../lib/term-log.mjs';
import {findConfigPath} from '../lib/project.mjs';
-import {fixDirectiveCorruption, validateOutput} from './runner.mjs';
+import {fixDirectiveCorruption, validateOutput, IGNORED_DIRS} from './runner.mjs';
export const DEFAULT_CODE_EXTENSIONS = [
'.tsx',
@@ -61,8 +61,11 @@ export function findSourceFiles(dir) {
}
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
+ // Never follow symlinks — writing through one would rewrite its target
+ // outside the scan tree (e.g. into node_modules or anywhere on disk).
+ if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ if (IGNORED_DIRS.has(entry.name)) continue;
walk(fullPath);
} else {
results.push(fullPath);
@@ -94,7 +97,23 @@ export function makeLog(silent) {
export function runConfigCodemod(entry, {apply, log, jscodeshift}) {
const {codemod, id, package: pkg} = entry;
const name = `${pkg}:${id}`;
- const configPath = findConfigPath(process.cwd());
+ // findConfigPath throws when multiple astryx.config.* files coexist. Config
+ // codemods run FIRST (before the strict project loader), so an uncaught throw
+ // here aborts the entire `astryx upgrade` with an un-coded error — breaking
+ // the per-codemod isolation every other failure path honors. Degrade it to a
+ // structured error so the run continues and reports it.
+ let configPath;
+ try {
+ configPath = findConfigPath(process.cwd());
+ } catch (err) {
+ const message = /** @type {any} */ (err).message;
+ log.error(` ✗ astryx.config.* — ${message}`);
+ return {
+ filesChanged: 0,
+ writtenFiles: [],
+ errors: [{file: 'astryx.config.*', codemod: name, error: message}],
+ };
+ }
if (!configPath) {
log.info(` ${codemod.title} — no astryx.config.* found; skipping.`);
return {filesChanged: 0, writtenFiles: [], errors: []};
diff --git a/packages/cli/codemods/runner.mjs b/packages/cli/codemods/runner.mjs
index 143024d2eb..be0a8c0145 100644
--- a/packages/cli/codemods/runner.mjs
+++ b/packages/cli/codemods/runner.mjs
@@ -45,6 +45,21 @@ export function fixDirectiveCorruption(code) {
return code.replace(/^(['"]use (client|server|strict)['"]);\s*;/gm, '$1;');
}
+/**
+ * Directories a source scan must never descend into: dependencies, VCS, and
+ * generated build output (codemods rewrite source, not artifacts).
+ */
+const IGNORED_DIRS = new Set([
+ 'node_modules',
+ '.git',
+ 'dist',
+ 'build',
+ 'out',
+ '.next',
+ 'coverage',
+]);
+export {IGNORED_DIRS};
+
/**
* Recursively find all source files in a directory.
* @param {string} dir
@@ -76,8 +91,15 @@ function findSourceFiles(dir) {
}
for (const entry of entries) {
const fullPath = path.join(currentDir, entry.name);
+ // Never follow symlinks: readFileSync/writeFileSync would traverse a
+ // symlinked file and rewrite its target OUTSIDE the scan tree (e.g. into
+ // node_modules or anywhere on disk). A codemod must only edit real files
+ // it reaches directly under the scanned path.
+ if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ // Skip dependency, VCS, and generated-output dirs — codemods rewrite
+ // source, not build artifacts.
+ if (IGNORED_DIRS.has(entry.name)) continue;
walk(fullPath);
} else if (extensions.has(path.extname(entry.name))) {
results.push(fullPath);
diff --git a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-badge-children-to-label.test.mjs b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-badge-children-to-label.test.mjs
new file mode 100644
index 0000000000..e39ad9ad7f
--- /dev/null
+++ b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-badge-children-to-label.test.mjs
@@ -0,0 +1,46 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+
+async function applyTransform(source) {
+ const {default: transform} = await import(
+ '../migrate-badge-children-to-label.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+ const api = {jscodeshift, stats: () => {}, report: () => {}};
+ const file = {source, path: 'test.tsx'};
+ const result = transform(file, api);
+ return result ?? source;
+}
+
+describe('migrate-badge-children-to-label', () => {
+ it('moves text children to a label prop and self-closes', async () => {
+ const out = await applyTransform(
+ `import {XDSBadge} from '@xds/core';\nexport const A = () => <XDSBadge variant="success">Active</XDSBadge>;`,
+ );
+ expect(out).toContain("label='Active'");
+ expect(out).toContain('variant="success"');
+ expect(out).not.toMatch(/>Active</);
+ });
+
+ it('wraps a numeric/expression child in an expression container', async () => {
+ const out = await applyTransform(
+ `import {XDSBadge} from '@xds/core';\nexport const B = () => <XDSBadge>{count}</XDSBadge>;`,
+ );
+ expect(out).toContain('label={count}');
+ });
+
+ it('does not add a duplicate label when one already exists', async () => {
+ // Regression: the codemod pushed a `label` attr unconditionally, producing
+ // an invalid `<XDSBadge label="x" label="Active" />` duplicate prop.
+ const input = `import {XDSBadge} from '@xds/core';\nexport const C = () => <XDSBadge label="x">Active</XDSBadge>;`;
+ const out = await applyTransform(input);
+ expect(out).toBe(input); // unchanged — the existing label wins
+ expect(out.match(/label/g)).toHaveLength(1);
+ });
+
+ it('skips JSX element children (only text/expression migrate)', async () => {
+ const input = `import {XDSBadge} from '@xds/core';\nexport const D = () => <XDSBadge><span>x</span></XDSBadge>;`;
+ expect(await applyTransform(input)).toBe(input);
+ });
+});
diff --git a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-radius-tokens.test.mjs b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-radius-tokens.test.mjs
index 2e7e49072d..1a0df3461d 100644
--- a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-radius-tokens.test.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-radius-tokens.test.mjs
@@ -83,4 +83,16 @@ describe('migrate-radius-tokens', () => {
const result = transform({source, path: 'test.tsx'}, api);
expect(result).toBeUndefined();
});
+
+ it('does not rewrite a longer consumer token that shares a prefix', async () => {
+ // Regression: `a|b|c(?!…)` bound the boundary lookahead only to the last
+ // alternative, so `--radius-container` matched inside a consumer's
+ // `--radius-container-custom` and corrupted it to `--radius-3-custom`.
+ expect(await applyTransform(`const x = "var(--radius-container-custom)";`)).toContain(
+ '--radius-container-custom',
+ );
+ expect(await applyTransform(`const x = "--radius-innermost";`)).toContain(
+ '--radius-innermost',
+ );
+ });
});
diff --git a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-shadow-tokens.test.mjs b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-shadow-tokens.test.mjs
index 72f895b70a..1183cfe619 100644
--- a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-shadow-tokens.test.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-shadow-tokens.test.mjs
@@ -104,4 +104,14 @@ const s = stylex.create({ c: { boxShadow: elevationVars['--elevation-menu'] } })
expect(out).not.toContain('elevationVars');
expect(out).not.toContain('--elevation-menu');
});
+
+ it('does not rewrite a longer token that shares a numeric-shadow prefix', async () => {
+ // Regression: `--shadow-1` matched inside `--shadow-10` → `--shadow-base0`.
+ expect(await applyTransform(`const x = "var(--shadow-10)";`)).toContain(
+ '--shadow-10',
+ );
+ expect(await applyTransform(`const x = "--elevation-baseX";`)).toContain(
+ '--elevation-baseX',
+ );
+ });
});
diff --git a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-token-names.test.mjs b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-token-names.test.mjs
index bb19972932..d711cd3e60 100644
--- a/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-token-names.test.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/__tests__/migrate-token-names.test.mjs
@@ -264,4 +264,12 @@ describe('migrate-token-names', () => {
expect(output).toContain('--ease-standard');
expect(output).not.toContain('--easing-standard');
});
+
+ it('does not rewrite a longer consumer token that shares a prefix', async () => {
+ // Regression: the boundary lookahead only bound to the last alternative,
+ // so `--color-positive` matched inside `--color-positive-custom`.
+ expect(await applyTransform(`const x = "--color-positive-custom";`)).toContain(
+ '--color-positive-custom',
+ );
+ });
});
diff --git a/packages/cli/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs b/packages/cli/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs
index be7968cc50..bd3022d5b4 100644
--- a/packages/cli/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/migrate-badge-children-to-label.mjs
@@ -39,6 +39,14 @@ export default function transformer(file, api) {
// Skip if already self-closing or no children
if (children.length === 0) return;
+ // Skip if a `label` prop is already present — pushing another would emit
+ // a duplicate JSX attribute (invalid React). The existing label wins.
+ const hasLabel = path.node.openingElement.attributes.some(
+ (/** @type {any} */ attr) =>
+ attr.type === 'JSXAttribute' && attr.name?.name === 'label',
+ );
+ if (hasLabel) return;
+
// Filter out whitespace-only JSXText nodes
const meaningful = children.filter(
(/** @type {any} */ c) => !(c.type === 'JSXText' && !c.value.trim()),
diff --git a/packages/cli/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs b/packages/cli/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs
index 235c827724..fd1c67bd8b 100644
--- a/packages/cli/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/migrate-radius-tokens.mjs
@@ -31,11 +31,18 @@ const TOKEN_MAP = {
'--radius-page': '--radius-4',
};
-// Build a regex that matches any old token name (as a whole token, not substring)
+// Build a regex that matches any old token name as a WHOLE token, not a
+// prefix of a longer consumer-defined name. The right-boundary lookahead is
+// wrapped around the whole alternation (a bare `a|b|c(?!…)` would bind the
+// lookahead only to `c`, leaving the other tokens to match prefixes and
+// silently corrupt e.g. `--radius-container-custom`).
const OLD_TOKENS_PATTERN = new RegExp(
- Object.keys(TOKEN_MAP)
- .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
- .join('|'),
+ '(?:' +
+ Object.keys(TOKEN_MAP)
+ .sort((a, b) => b.length - a.length)
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join('|') +
+ ')(?![a-zA-Z0-9_-])',
'g',
);
diff --git a/packages/cli/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs b/packages/cli/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs
index 396fc5ae9f..8afb3d8530 100644
--- a/packages/cli/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs
@@ -59,10 +59,12 @@ const IDENTIFIER_MAP = {
};
const OLD_TOKENS_PATTERN = new RegExp(
- Object.keys(TOKEN_MAP)
- .sort((a, b) => b.length - a.length)
- .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
- .join('|'),
+ '(?:' +
+ Object.keys(TOKEN_MAP)
+ .sort((a, b) => b.length - a.length)
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join('|') +
+ ')(?![a-zA-Z0-9_-])',
'g',
);
diff --git a/packages/cli/codemods/transforms/v0.0.6/migrate-token-names.mjs b/packages/cli/codemods/transforms/v0.0.6/migrate-token-names.mjs
index 731f313bef..ba77fbc0b7 100644
--- a/packages/cli/codemods/transforms/v0.0.6/migrate-token-names.mjs
+++ b/packages/cli/codemods/transforms/v0.0.6/migrate-token-names.mjs
@@ -108,10 +108,12 @@ const TOKEN_MAP = {
// Uses negative lookahead for word-like chars to avoid partial matches
// (e.g. --color-accent must not match inside --color-accent-deemphasized).
const OLD_TOKENS_PATTERN = new RegExp(
- Object.keys(TOKEN_MAP)
- .sort((a, b) => b.length - a.length)
- .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
- .join('|') + '(?![a-zA-Z0-9_-])',
+ '(?:' +
+ Object.keys(TOKEN_MAP)
+ .sort((a, b) => b.length - a.length)
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join('|') +
+ ')(?![a-zA-Z0-9_-])',
'g',
);
diff --git a/packages/cli/codemods/transforms/v0.0.8/__tests__/migrate-token-renames.test.mjs b/packages/cli/codemods/transforms/v0.0.8/__tests__/migrate-token-renames.test.mjs
index ba7947bfdf..ad54ebdb20 100644
--- a/packages/cli/codemods/transforms/v0.0.8/__tests__/migrate-token-renames.test.mjs
+++ b/packages/cli/codemods/transforms/v0.0.8/__tests__/migrate-token-renames.test.mjs
@@ -318,4 +318,10 @@ const b = typeScaleVars;`;
// All usages should be typeScaleVars
expect((output.match(/typeScaleVars/g) || []).length).toBeGreaterThanOrEqual(2);
});
+
+ it('does not rewrite a longer consumer token that shares a prefix', async () => {
+ // Regression: the boundary lookahead only bound to the last alternative.
+ const out = await applyTransform(`const x = "--color-wash-custom";`);
+ expect(out).toContain('--color-wash-custom');
+ });
});
diff --git a/packages/cli/codemods/transforms/v0.0.8/migrate-token-renames.mjs b/packages/cli/codemods/transforms/v0.0.8/migrate-token-renames.mjs
index f7df6e11f8..ae9b83929f 100644
--- a/packages/cli/codemods/transforms/v0.0.8/migrate-token-renames.mjs
+++ b/packages/cli/codemods/transforms/v0.0.8/migrate-token-renames.mjs
@@ -208,10 +208,12 @@ const IDENTIFIER_MAP = {
// =============================================================================
const OLD_TOKENS_PATTERN = new RegExp(
- Object.keys(TOKEN_MAP)
- .sort((a, b) => b.length - a.length)
- .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
- .join('|') + '(?![a-zA-Z0-9_-])',
+ '(?:' +
+ Object.keys(TOKEN_MAP)
+ .sort((a, b) => b.length - a.length)
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join('|') +
+ ')(?![a-zA-Z0-9_-])',
'g',
);
diff --git a/packages/cli/lib/agent-docs/agent-docs.mjs b/packages/cli/lib/agent-docs/agent-docs.mjs
index 6b44e2bcd8..2dc61f1be3 100644
--- a/packages/cli/lib/agent-docs/agent-docs.mjs
+++ b/packages/cli/lib/agent-docs/agent-docs.mjs
@@ -40,6 +40,45 @@ const MARKER_END = '<!-- ASTRYX:END -->';
const LEGACY_MARKER_START = '<!-- XDS:START -->';
const LEGACY_MARKER_END = '<!-- XDS:END -->';
+/**
+ * Locate the single well-formed managed block in `content`.
+ *
+ * A naive `indexOf(START)` + `indexOf(END)` corrupts user content on malformed
+ * input: an END that appears before START makes the slice boundaries overlap
+ * (duplicating text), and a stray START with no END silently looks like "no
+ * block" so a fresh block gets appended below the broken one. This searches for
+ * END strictly *after* START (so the boundaries can never cross) and refuses to
+ * touch a file that has more than one START of the same kind — better to ask the
+ * user to fix an ambiguous file than to guess and drop their content.
+ *
+ * @param {string} content
+ * @returns {{start: number, end: number} | null} start = index of START marker;
+ * end = index just past the END marker. null when there is no block. Throws on
+ * an ambiguous file (duplicate/nested START markers).
+ */
+function findManagedBlock(content) {
+ for (const [start, end] of [
+ [MARKER_START, MARKER_END],
+ [LEGACY_MARKER_START, LEGACY_MARKER_END],
+ ]) {
+ const startIdx = content.indexOf(start);
+ if (startIdx === -1) continue;
+ // Search for END after START so end > start is guaranteed.
+ const endIdx = content.indexOf(end, startIdx + start.length);
+ if (endIdx === -1) continue; // START without a matching END → treat as no block
+ // A second START of the same kind means the file is ambiguous (duplicate or
+ // nested block). Refuse rather than orphan/mangle content.
+ if (content.indexOf(start, startIdx + start.length) !== -1) {
+ throw new Error(
+ `Malformed agent-docs block: multiple "${start}" markers found. ` +
+ `Remove the duplicate/broken block manually, then re-run.`,
+ );
+ }
+ return {start: startIdx, end: endIdx + end.length};
+ }
+ return null;
+}
+
/**
* Agent tool presets — maps tool names to their file search paths.
* Order matters: first existing file wins, last entry is the default (created if none exist).
@@ -392,21 +431,22 @@ export function injectXdsBlock(filePath, compressedIndex, {createIfMissing = fal
if (fs.existsSync(filePath)) {
content = fs.readFileSync(filePath, 'utf-8');
- // Find existing section — try new markers first, fall back to legacy XDS markers
- let startIdx = content.indexOf(MARKER_START);
- let endIdx = content.indexOf(MARKER_END);
- let markerEndLength = MARKER_END.length;
- if (startIdx === -1) {
- startIdx = content.indexOf(LEGACY_MARKER_START);
- endIdx = content.indexOf(LEGACY_MARKER_END);
- markerEndLength = LEGACY_MARKER_END.length;
- }
+ // Find existing section (new or legacy markers), well-formed only.
+ const block = findManagedBlock(content);
- if (startIdx !== -1 && endIdx !== -1) {
+ if (block) {
content =
- content.slice(0, startIdx) +
+ content.slice(0, block.start) +
compressedIndex +
- content.slice(endIdx + markerEndLength);
+ content.slice(block.end);
+ } else if (content.includes(MARKER_START) || content.includes(LEGACY_MARKER_START)) {
+ // A START with no matching END (e.g. an interrupted previous write). Don't
+ // append a second block below the broken one — that leaves two STARTs the
+ // tool can never converge. Refuse and ask the user to clean it up.
+ throw new Error(
+ `Malformed agent-docs block: found a start marker with no matching end ` +
+ `in ${filePath}. Remove the incomplete block manually, then re-run.`,
+ );
} else if (onlyReplace) {
// File exists but has no Astryx markers — skip it
return false;
@@ -471,20 +511,12 @@ export function removeXdsBlock(filePath, {deleteIfEmpty = false} = {}) {
if (!fs.existsSync(filePath)) return false;
let content = fs.readFileSync(filePath, 'utf-8');
- // Find existing section — try new markers first, fall back to legacy
- let startIdx = content.indexOf(MARKER_START);
- let endIdx = content.indexOf(MARKER_END);
- let markerEndLen = MARKER_END.length;
- if (startIdx === -1) {
- startIdx = content.indexOf(LEGACY_MARKER_START);
- endIdx = content.indexOf(LEGACY_MARKER_END);
- markerEndLen = LEGACY_MARKER_END.length;
- }
-
- if (startIdx === -1 || endIdx === -1) return false;
+ // Find existing section (new or legacy markers), well-formed only.
+ const block = findManagedBlock(content);
+ if (!block) return false;
- const before = content.slice(0, startIdx).trimEnd();
- const after = content.slice(endIdx + markerEndLen).trimStart();
+ const before = content.slice(0, block.start).trimEnd();
+ const after = content.slice(block.end).trimStart();
content = before + (after ? '\n\n' + after : '') + '\n';
if (deleteIfEmpty) {
diff --git a/packages/cli/lib/agent-docs/agent-docs.test.mjs b/packages/cli/lib/agent-docs/agent-docs.test.mjs
index 812d5981cf..9b82745667 100644
--- a/packages/cli/lib/agent-docs/agent-docs.test.mjs
+++ b/packages/cli/lib/agent-docs/agent-docs.test.mjs
@@ -18,6 +18,7 @@ import {
resolveAgentPaths,
parseBlockVersion,
inspectAgentDocs,
+ isAstryxInitialized,
} from './agent-docs.mjs';
let tmpDir;
@@ -715,3 +716,88 @@ describe('inspectAgentDocs', () => {
expect(res.status).toBe('current');
});
});
+
+describe('injectXdsBlock / removeXdsBlock — malformed managed blocks (no user-content loss)', () => {
+ const S = '<!-- ASTRYX:START -->';
+ const E = '<!-- ASTRYX:END -->';
+ const BLOCK = `${S}\nNEW\n${E}`;
+
+ it('does not duplicate user content when END precedes START', () => {
+ const f = path.join(tmpDir, 'a.md');
+ fs.writeFileSync(f, `# Doc\nUSER-A\n${E}\nUSER-B\n${S}\nUSER-C\n`);
+ removeXdsBlock(f);
+ const c = fs.readFileSync(f, 'utf-8');
+ expect((c.match(/USER-B/g) || []).length).toBeLessThanOrEqual(1);
+ });
+
+ it('refuses (throws) instead of orphaning a second block when duplicates exist', () => {
+ const f = path.join(tmpDir, 'b.md');
+ fs.writeFileSync(f, `# Doc\n${S}\nB1\n${E}\nMID\n${S}\nB2\n${E}\nTAIL\n`);
+ expect(() => injectXdsBlock(f, BLOCK)).toThrow(/multiple|malformed/i);
+ // file left untouched for the user to fix
+ expect(fs.readFileSync(f, 'utf-8')).toContain('MID');
+ expect(fs.readFileSync(f, 'utf-8')).toContain('TAIL');
+ });
+
+ it('refuses to append a second block when a START has no matching END', () => {
+ const f = path.join(tmpDir, 'c.md');
+ fs.writeFileSync(f, `# Doc\nUSER1\n${S}\nOLD (no end)\nUSER2\n`);
+ expect(() => injectXdsBlock(f, BLOCK)).toThrow(/end marker|malformed|no matching/i);
+ expect((fs.readFileSync(f, 'utf-8').match(/ASTRYX:START/g) || []).length).toBe(1);
+ });
+
+ it('replaces a single well-formed block idempotently, preserving surrounding content', () => {
+ const f = path.join(tmpDir, 'ok.md');
+ fs.writeFileSync(f, `# Doc\nUSER\n${S}\nOLD\n${E}\nTAIL\n`);
+ injectXdsBlock(f, BLOCK);
+ const c = fs.readFileSync(f, 'utf-8');
+ expect((c.match(/ASTRYX:START/g) || []).length).toBe(1);
+ expect(c).toContain('NEW');
+ expect(c).toContain('USER');
+ expect(c).toContain('TAIL');
+ expect(c).not.toContain('OLD');
+ });
+});
+
+describe('isAstryxInitialized — resilient to malformed markers (postinstall hot path)', () => {
+ // isAstryxInitialized runs on every consumer `npm install` (via postinstall).
+ // It must never throw — even on a half-written or garbage-marker file — so it
+ // uses a plain `.includes(MARKER_START)`, never the strict findManagedBlock.
+ const START = '<!-- ASTRYX:START -->';
+ const END = '<!-- ASTRYX:END -->';
+
+ it('returns true (never throws) on duplicate START markers', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ `${START}\na\n${START}\nb\n${END}\n`,
+ );
+ expect(() => isAstryxInitialized(tmpDir)).not.toThrow();
+ expect(isAstryxInitialized(tmpDir)).toBe(true);
+ });
+
+ it('returns true on an END-before-START file without throwing', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ `${END}\nuser\n${START}\nblock\n`,
+ );
+ expect(() => isAstryxInitialized(tmpDir)).not.toThrow();
+ expect(isAstryxInitialized(tmpDir)).toBe(true);
+ });
+
+ it('returns true on a START with no END (half-written block)', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ `# Doc\nuser\n${START}\ntruncated block, no end\n`,
+ );
+ expect(() => isAstryxInitialized(tmpDir)).not.toThrow();
+ expect(isAstryxInitialized(tmpDir)).toBe(true);
+ });
+
+ it('returns false for a directory with no agent docs', () => {
+ expect(isAstryxInitialized(tmpDir)).toBe(false);
+ });
+
+ it('returns false for a nonexistent directory', () => {
+ expect(isAstryxInitialized(path.join(tmpDir, 'does-not-exist'))).toBe(false);
+ });
+});
diff --git a/packages/cli/lib/component-discovery.mjs b/packages/cli/lib/component-discovery.mjs
index 5005795ce2..886c4cc79a 100644
--- a/packages/cli/lib/component-discovery.mjs
+++ b/packages/cli/lib/component-discovery.mjs
@@ -68,11 +68,13 @@ function componentNameFromFile(fileName) {
}
// Matches the top-level `group: 'GroupName'` field in a .doc.mjs file.
-// Only matches at shallow indentation (≤ 4 spaces from line start) to avoid
-// picking up nested `group:` fields inside prop descriptions.
-const GROUP_RE = /(?:^|\n) {0,4}group:\s*['"]([^'"]+)['"]/;
-const HIDDEN_COMPONENTS_RE = /(?:^|\n) {0,4}hiddenComponents:\s*\[([^\]]*)\]/;
-const HIDDEN_RE = /(?:^|\n) {0,4}hidden:\s*true/;
+// Only matches at ≤2 spaces (top-level object fields). Deeper indentation is a
+// nested field — e.g. a `group:` entry inside a `propDescriptions:` block of a
+// docsZh/docsDense translation export — which must NOT be read as the
+// component's group (that leaked a translated prop description as a group key).
+const GROUP_RE = /(?:^|\n) {0,2}group:\s*['"]([^'"]+)['"]/;
+const HIDDEN_COMPONENTS_RE = /(?:^|\n) {0,2}hiddenComponents:\s*\[([^\]]*)\]/;
+const HIDDEN_RE = /(?:^|\n) {0,2}hidden:\s*true/;
/**
* Read the `group`, `hiddenComponents`, and `hidden` fields from a
diff --git a/packages/cli/lib/component-discovery.test.mjs b/packages/cli/lib/component-discovery.test.mjs
new file mode 100644
index 0000000000..5915641c1c
--- /dev/null
+++ b/packages/cli/lib/component-discovery.test.mjs
@@ -0,0 +1,245 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for component-discovery, run against the real
+ * @astryxdesign/core source tree plus throwaway fixtures. Complements
+ * component-discovery.importpath.test.mjs (which covers the .ts-source
+ * import-path derivation) by pinning the discovery/grouping/resolution
+ * behavior and the crash-on-missing-src surface.
+ */
+
+import {describe, it, expect, afterAll} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {
+ CORE_PACKAGE,
+ discoverComponents,
+ findComponentReadme,
+ findComponentSource,
+ resolveImportPath,
+ discoverExternalComponents,
+ discoverExternalComponentsGrouped,
+ findExternalComponentDoc,
+ discoverIntegrationComponents,
+ findIntegrationComponentDoc,
+ findIntegrationComponentSource,
+ discoverOwnedComponents,
+} from './component-discovery.mjs';
+
+// packages/cli/lib/ -> up 3 = repo root (has packages/core).
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+const CORE = path.join(REPO, 'packages', 'core');
+
+const SLOW = 30_000;
+
+const tmpDirs = [];
+function mkTmp(prefix) {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ tmpDirs.push(d);
+ return d;
+}
+afterAll(() => {
+ for (const d of tmpDirs) {
+ fs.rmSync(d, {recursive: true, force: true});
+ }
+});
+
+describe('discoverComponents (real core)', () => {
+ it('discovers and groups real components', () => {
+ const comps = discoverComponents(CORE);
+ const keys = Object.keys(comps);
+ expect(keys.length).toBeGreaterThan(20);
+ for (const members of Object.values(comps)) {
+ expect(Array.isArray(members)).toBe(true);
+ expect(members.length).toBeGreaterThan(0);
+ expect([...members].sort()).toEqual(members);
+ }
+ expect([...keys].sort((a, b) => a.localeCompare(b))).toEqual(keys);
+ expect(keys).toContain('Button');
+ expect(comps.Button).toContain('Button');
+ expect(comps.Button).toContain('IconButton');
+ expect(comps.Button.length).toBeGreaterThan(1);
+ }, SLOW);
+
+ it('never emits a non-ASCII (translated) group key', () => {
+ // Regression: a `group:` prop inside a docsZh propDescriptions block leaked
+ // a Chinese string as a group key in the default (English) listing.
+ const comps = discoverComponents(CORE);
+ for (const key of Object.keys(comps)) {
+ expect([...key].every(ch => ch.charCodeAt(0) < 128)).toBe(true);
+ }
+ }, SLOW);
+
+ it('honors group, hidden, and hiddenComponents from a directory doc', () => {
+ const core = mkTmp('as-cd-group-');
+ const dir = path.join(core, 'src', 'Foo');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'XDSFoo.tsx'), 'x');
+ fs.writeFileSync(path.join(dir, 'XDSFooInternal.tsx'), 'x');
+ fs.writeFileSync(
+ path.join(dir, 'Foo.doc.mjs'),
+ "export default {\n group: 'Widgets',\n hiddenComponents: ['FooInternal'],\n};\n",
+ );
+ expect(discoverComponents(core)).toEqual({Widgets: ['Foo']});
+ });
+
+ it('does not read a group: nested in a propDescriptions block', () => {
+ // The ChatMessageBubble bug: a `group:` at 4-space indent inside
+ // propDescriptions must NOT be picked up as the component's group.
+ const core = mkTmp('as-cd-nested-');
+ const dir = path.join(core, 'src', 'Bubble');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'XDSBubble.tsx'), 'x');
+ fs.writeFileSync(
+ path.join(dir, 'Bubble.doc.mjs'),
+ 'export default {\n' +
+ " displayName: 'Bubble',\n" +
+ ' propDescriptions: {\n' +
+ " group: 'position within a multi-bubble group',\n" +
+ ' },\n' +
+ '};\n',
+ );
+ // No top-level group -> falls back to the component name, NOT the prop text.
+ expect(discoverComponents(core)).toEqual({Bubble: ['Bubble']});
+ });
+
+ it('skips an entire directory whose doc is hidden: true', () => {
+ const core = mkTmp('as-cd-hidden-');
+ const dir = path.join(core, 'src', 'Bar');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'XDSBar.tsx'), 'x');
+ fs.writeFileSync(path.join(dir, 'Bar.doc.mjs'), 'export default {\n hidden: true,\n};\n');
+ expect(discoverComponents(core)).toEqual({});
+ });
+
+ it('omits component source files that have no sibling doc file', () => {
+ const core = mkTmp('as-cd-nodoc-');
+ const dir = path.join(core, 'src', 'Naked');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'XDSNaked.tsx'), 'x');
+ expect(discoverComponents(core)).toEqual({});
+ });
+
+ it('returns {} for an empty src/ dir', () => {
+ const core = mkTmp('as-cd-emptysrc-');
+ fs.mkdirSync(path.join(core, 'src'));
+ expect(discoverComponents(core)).toEqual({});
+ });
+
+ it('throws when src/ is missing (no existsSync guard on the top readdir)', () => {
+ const core = mkTmp('as-cd-nosrc-');
+ expect(() => discoverComponents(core)).toThrow(/ENOENT/);
+ });
+});
+
+describe('findComponentReadme / findComponentSource / resolveImportPath', () => {
+ it('finds the doc + source for a top-level component', () => {
+ expect(findComponentReadme(CORE, 'Button')).toMatch(/Button\.doc\.mjs$/);
+ expect(findComponentSource(CORE, 'Button')).toMatch(/\.tsx$/);
+ expect(resolveImportPath(CORE, 'Button')).toBe('@astryxdesign/core/Button');
+ }, SLOW);
+
+ it('returns null for an unknown component (no fuzzy fallback, unlike hooks)', () => {
+ expect(findComponentReadme(CORE, 'Buton')).toBeNull();
+ expect(findComponentSource(CORE, 'Buton')).toBeNull();
+ }, SLOW);
+
+ it('falls back to the bare package root when no source is found', () => {
+ const core = mkTmp('as-rip-empty-');
+ fs.mkdirSync(path.join(core, 'src'));
+ expect(resolveImportPath(core, 'Nope')).toBe('@astryxdesign/core');
+ });
+
+ it('throws when src/ is missing', () => {
+ const core = mkTmp('as-fcr-nosrc-');
+ expect(() => findComponentReadme(core, 'Button')).toThrow(/ENOENT/);
+ expect(() => findComponentSource(core, 'Button')).toThrow(/ENOENT/);
+ expect(() => resolveImportPath(core, 'Button')).toThrow(/ENOENT/);
+ });
+});
+
+describe('external package discovery', () => {
+ function buildExternalDocs() {
+ const root = mkTmp('as-ext-');
+ const docs = path.join(root, 'docs');
+ fs.mkdirSync(path.join(docs, 'sub'), {recursive: true});
+ fs.writeFileSync(path.join(docs, 'AppShell.doc.mjs'), "export default {\n group: 'App Chrome',\n};\n");
+ fs.writeFileSync(path.join(docs, 'sub', 'SideNav.doc.mjs'), "export default {\n group: 'App Chrome',\n};\n");
+ fs.writeFileSync(path.join(docs, 'Diff.doc.mjs'), 'export default {};\n');
+ fs.writeFileSync(path.join(docs, 'Secret.doc.mjs'), 'export default {\n hidden: true,\n};\n');
+ return docs;
+ }
+
+ it('discoverExternalComponents returns a sorted flat list (deprecated)', () => {
+ expect(discoverExternalComponents(buildExternalDocs())).toEqual(['AppShell', 'Diff', 'Secret', 'SideNav']);
+ });
+
+ it('discoverExternalComponentsGrouped groups + drops hidden', () => {
+ expect(discoverExternalComponentsGrouped(buildExternalDocs())).toEqual({
+ 'App Chrome': ['AppShell', 'SideNav'],
+ Diff: ['Diff'],
+ });
+ });
+
+ it('findExternalComponentDoc locates a nested doc by name', () => {
+ const docs = buildExternalDocs();
+ expect(findExternalComponentDoc(docs, 'SideNav')).toMatch(/SideNav\.doc\.mjs$/);
+ expect(findExternalComponentDoc(docs, 'Nope')).toBeNull();
+ });
+
+ it('returns empty for a missing docs dir (guarded)', () => {
+ expect(discoverExternalComponents('/no/such/dir')).toEqual([]);
+ expect(discoverExternalComponentsGrouped('/no/such/dir')).toEqual({});
+ expect(findExternalComponentDoc('/no/such/dir', 'X')).toBeNull();
+ });
+});
+
+describe('integration component discovery (ownership-aware)', () => {
+ function buildIntegration() {
+ const root = mkTmp('as-integ-');
+ const cdir = path.join(root, 'components');
+ fs.mkdirSync(path.join(cdir, 'sub'), {recursive: true});
+ fs.writeFileSync(path.join(cdir, 'MetaAppShell.doc.mjs'), "export default {\n group: 'App Chrome',\n};\n");
+ fs.writeFileSync(path.join(cdir, 'MetaAppShell.tsx'), 'x');
+ fs.writeFileSync(path.join(cdir, 'sub', 'MetaDiff.doc.ts'), 'export default {};\n');
+ fs.writeFileSync(path.join(cdir, 'MetaSecret.doc.mjs'), 'export default {\n hidden: true,\n};\n');
+ return {name: '@acme/astryx-meta', components: cdir, issuesUrl: 'https://example.com/issues'};
+ }
+
+ it('records owner package, issuesUrl, group, and source presence; drops hidden', () => {
+ const recs = discoverIntegrationComponents(buildIntegration()).sort((a, b) => a.name.localeCompare(b.name));
+ expect(recs.map(r => r.name)).toEqual(['MetaAppShell', 'MetaDiff']);
+ const shell = recs.find(r => r.name === 'MetaAppShell');
+ expect(shell.package).toBe('@acme/astryx-meta');
+ expect(shell.issuesUrl).toBe('https://example.com/issues');
+ expect(shell.group).toBe('App Chrome');
+ expect(shell.sourcePath).toMatch(/MetaAppShell\.tsx$/);
+ expect(recs.find(r => r.name === 'MetaDiff').sourcePath).toBeNull();
+ });
+
+ it('finds an integration doc + source by name', () => {
+ const integ = buildIntegration();
+ expect(findIntegrationComponentDoc(integ, 'MetaAppShell')).toMatch(/MetaAppShell\.doc\.mjs$/);
+ expect(findIntegrationComponentSource(integ, 'MetaAppShell')).toMatch(/MetaAppShell\.tsx$/);
+ expect(findIntegrationComponentDoc(integ, 'MetaDiff')).toMatch(/MetaDiff\.doc\.ts$/);
+ expect(findIntegrationComponentSource(integ, 'MetaDiff')).toBeNull();
+ expect(findIntegrationComponentDoc(integ, 'Nope')).toBeNull();
+ });
+
+ it('gracefully handles a broken/missing integration components dir', () => {
+ expect(discoverIntegrationComponents({name: 'x'})).toEqual([]);
+ expect(discoverIntegrationComponents({name: 'x', components: '/no/such/dir'})).toEqual([]);
+ expect(findIntegrationComponentDoc({name: 'x', components: '/no/such/dir'}, 'A')).toBeNull();
+ });
+
+ it('discoverOwnedComponents merges core + integration records', () => {
+ const recs = discoverOwnedComponents(CORE, [buildIntegration()]);
+ const button = recs.find(r => r.name === 'Button');
+ expect(button).toBeDefined();
+ expect(button.package).toBe(CORE_PACKAGE);
+ expect(button.sourcePath).toMatch(/\.tsx$/);
+ expect(recs.find(r => r.name === 'MetaAppShell').package).toBe('@acme/astryx-meta');
+ }, SLOW);
+});
diff --git a/packages/cli/lib/config-schema.test.mjs b/packages/cli/lib/config-schema.test.mjs
new file mode 100644
index 0000000000..d6b61e1f13
--- /dev/null
+++ b/packages/cli/lib/config-schema.test.mjs
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for config-schema — the runtime zod schemas for
+ * astryx.config.* and integration manifests. These lock:
+ * - AstryxConfigSchema accepts an empty config and a fully-populated valid one,
+ * - it rejects non-objects (null / number / array) with a readable message,
+ * - .strict() rejects unknown top-level AND nested keys,
+ * - issuesUrl must be a URL, integrations must be string[],
+ * - postCodemod.buildCommand must be a function (the custom `Fn` schema),
+ * - AstryxIntegrationSchema is likewise strict,
+ * - formatZodError renders `label is invalid: path: message; ...`, using
+ * `(root)` for the top-level path.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ AstryxConfigSchema,
+ AstryxIntegrationSchema,
+ PostCodemodHookSchema,
+ XleComponentSchema,
+ formatZodError,
+} from './config-schema.mjs';
+
+/** Parse and, on failure, return the formatted error string. */
+function reason(schema, value, label = 'config') {
+ const res = schema.safeParse(value);
+ return res.success ? null : formatZodError(label, res.error);
+}
+
+describe('AstryxConfigSchema', () => {
+ it('accepts an empty config (every field optional)', () => {
+ expect(AstryxConfigSchema.safeParse({}).success).toBe(true);
+ });
+
+ it('accepts a fully-populated valid config', () => {
+ const cfg = {
+ integrations: ['@astryxdesign/core'],
+ issuesUrl: 'https://github.com/org/repo/issues',
+ hooks: {postCodemod: [{name: 'build', buildCommand: () => {}}]},
+ experimental: {xle: {components: {Foo: {from: 'pkg', default: true}}}},
+ };
+ expect(AstryxConfigSchema.safeParse(cfg).success).toBe(true);
+ });
+
+ it('rejects null / number / array with a readable message', () => {
+ expect(reason(AstryxConfigSchema, null)).toContain('expected object');
+ expect(reason(AstryxConfigSchema, 42)).toContain('expected object');
+ expect(reason(AstryxConfigSchema, [])).toContain('expected object');
+ });
+
+ it('rejects unknown top-level keys (.strict)', () => {
+ const msg = reason(AstryxConfigSchema, {bogus: 1});
+ expect(msg).toContain('Unrecognized key');
+ expect(msg).toContain('bogus');
+ });
+
+ it('rejects a bad issuesUrl', () => {
+ expect(reason(AstryxConfigSchema, {issuesUrl: 'not-a-url'})).toContain(
+ 'issuesUrl',
+ );
+ });
+
+ it('rejects mistyped integrations', () => {
+ expect(reason(AstryxConfigSchema, {integrations: 'nope'})).toContain(
+ 'expected array',
+ );
+ expect(reason(AstryxConfigSchema, {integrations: [1]})).toContain(
+ 'integrations.0',
+ );
+ });
+
+ it('rejects a non-function postCodemod.buildCommand', () => {
+ const msg = reason(AstryxConfigSchema, {
+ hooks: {postCodemod: [{buildCommand: 'notAFn'}]},
+ });
+ expect(msg).toContain('buildCommand');
+ expect(msg).toContain('Expected function');
+ });
+
+ it('rejects unknown nested keys inside experimental.xle.components', () => {
+ const msg = reason(AstryxConfigSchema, {
+ experimental: {xle: {components: {Foo: {from: 'pkg', bad: 1}}}},
+ });
+ expect(msg).toContain('Unrecognized key');
+ });
+});
+
+describe('PostCodemodHookSchema / XleComponentSchema', () => {
+ it('PostCodemodHookSchema accepts {buildCommand} and rejects a missing one', () => {
+ expect(PostCodemodHookSchema.safeParse({buildCommand: () => {}}).success).toBe(
+ true,
+ );
+ expect(PostCodemodHookSchema.safeParse({}).success).toBe(false);
+ });
+
+ it('XleComponentSchema requires `from` and is strict', () => {
+ expect(XleComponentSchema.safeParse({from: 'pkg'}).success).toBe(true);
+ expect(XleComponentSchema.safeParse({}).success).toBe(false);
+ expect(XleComponentSchema.safeParse({from: 'pkg', extra: 1}).success).toBe(
+ false,
+ );
+ });
+});
+
+describe('AstryxIntegrationSchema', () => {
+ it('accepts an empty manifest and a valid one', () => {
+ expect(AstryxIntegrationSchema.safeParse({}).success).toBe(true);
+ expect(
+ AstryxIntegrationSchema.safeParse({
+ components: './c',
+ issuesUrl: 'https://example.com/i',
+ }).success,
+ ).toBe(true);
+ });
+
+ it('rejects unknown keys and a bad issuesUrl', () => {
+ expect(reason(AstryxIntegrationSchema, {bogus: 1})).toContain(
+ 'Unrecognized key',
+ );
+ expect(reason(AstryxIntegrationSchema, {issuesUrl: 'x'})).toContain(
+ 'issuesUrl',
+ );
+ });
+});
+
+describe('formatZodError', () => {
+ it('renders "label is invalid: path: message"', () => {
+ const res = AstryxConfigSchema.safeParse({issuesUrl: 'bad'});
+ expect(res.success).toBe(false);
+ const msg = formatZodError('astryx.config.mjs', res.error);
+ expect(msg).toMatch(/^astryx\.config\.mjs is invalid: /);
+ expect(msg).toContain('issuesUrl: ');
+ });
+
+ it('uses "(root)" for a top-level (empty-path) issue', () => {
+ const res = AstryxConfigSchema.safeParse(null);
+ expect(formatZodError('config', res.error)).toContain('(root): ');
+ });
+
+ it('joins multiple issues with "; "', () => {
+ const res = AstryxConfigSchema.safeParse({integrations: [1, 2]});
+ const msg = formatZodError('config', res.error);
+ expect(msg).toContain('; ');
+ expect(msg).toContain('integrations.0');
+ expect(msg).toContain('integrations.1');
+ });
+});
diff --git a/packages/cli/lib/hook-discovery.test.mjs b/packages/cli/lib/hook-discovery.test.mjs
new file mode 100644
index 0000000000..8430ff4258
--- /dev/null
+++ b/packages/cli/lib/hook-discovery.test.mjs
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for hook-discovery, run against the real
+ * @astryxdesign/core source tree plus throwaway fixtures. Pins the
+ * category grouping, the missing-src guarding (which differs from
+ * component-discovery), and the Levenshtein fuzzy-fallback in findHookDoc.
+ */
+
+import {describe, it, expect, afterAll} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {discoverHooks, findHookDoc, getAllHookNames} from './hook-discovery.mjs';
+
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+const CORE = path.join(REPO, 'packages', 'core');
+const SLOW = 30_000;
+
+const tmpDirs = [];
+function mkTmp(prefix) {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ tmpDirs.push(d);
+ return d;
+}
+afterAll(() => {
+ for (const d of tmpDirs) fs.rmSync(d, {recursive: true, force: true});
+});
+
+describe('discoverHooks (real core)', () => {
+ it('discovers real hooks grouped by category', () => {
+ const hooks = discoverHooks(CORE);
+ const cats = Object.keys(hooks);
+ expect(cats.length).toBeGreaterThan(1);
+ if (cats.includes('Other')) expect(cats[cats.length - 1]).toBe('Other');
+ const nonOther = cats.filter(c => c !== 'Other');
+ expect([...nonOther].sort((a, b) => a.localeCompare(b))).toEqual(nonOther);
+ for (const members of Object.values(hooks)) {
+ expect([...members].sort()).toEqual(members);
+ }
+ const all = getAllHookNames(CORE);
+ expect(all).toContain('useMediaQuery');
+ expect(all.length).toBeGreaterThan(10);
+ }, SLOW);
+
+ it('capitalizes categories and buckets category-less docs into Other', () => {
+ const core = mkTmp('as-hd-cat-');
+ const hooksDir = path.join(core, 'src', 'hooks');
+ fs.mkdirSync(hooksDir, {recursive: true});
+ fs.writeFileSync(path.join(hooksDir, 'useThing.doc.mjs'), "export default {\n category: 'layout',\n};\n");
+ fs.writeFileSync(path.join(hooksDir, 'useOrphan.doc.mjs'), 'export default {};\n');
+ expect(discoverHooks(core)).toEqual({Layout: ['useThing'], Other: ['useOrphan']});
+ });
+
+ it('discovers use*.doc.mjs colocated in component directories', () => {
+ const core = mkTmp('as-hd-colo-');
+ const compDir = path.join(core, 'src', 'Resizable');
+ fs.mkdirSync(compDir, {recursive: true});
+ fs.writeFileSync(path.join(compDir, 'useResizable.doc.mjs'), "export default {\n category: 'interaction',\n};\n");
+ expect(discoverHooks(core)).toEqual({Interaction: ['useResizable']});
+ });
+
+ it('returns {} when src/ is missing (guarded with existsSync)', () => {
+ const core = mkTmp('as-hd-nosrc-');
+ expect(discoverHooks(core)).toEqual({});
+ expect(getAllHookNames(core)).toEqual([]);
+ });
+});
+
+describe('findHookDoc (real core)', () => {
+ it('resolves an exact hook name', () => {
+ expect(findHookDoc(CORE, 'useMediaQuery')).toMatch(/useMediaQuery\.doc\.mjs$/);
+ }, SLOW);
+
+ it('resolves a bare (use-prefix-stripped, case-insensitive) name', () => {
+ expect(findHookDoc(CORE, 'mediaquery')).toMatch(/useMediaQuery\.doc\.mjs$/);
+ }, SLOW);
+
+ it('returns null when src/ is missing (guarded)', () => {
+ const core = mkTmp('as-fhd-nosrc-');
+ expect(findHookDoc(core, 'useFoo')).toBeNull();
+ });
+});
+
+describe('findHookDoc fuzzy Levenshtein fallback (pinned current behavior)', () => {
+ it('auto-resolves a typo within edit distance 3', () => {
+ expect(getAllHookNames(CORE)).not.toContain('useLayers');
+ expect(getAllHookNames(CORE)).toContain('useLayer');
+ expect(findHookDoc(CORE, 'useLayers')).toMatch(/useLayer\.doc\.mjs$/);
+ }, SLOW);
+
+ it('returns null when the closest hook is farther than distance 3', () => {
+ expect(findHookDoc(CORE, 'useZzzzzz')).toBeNull();
+ expect(findHookDoc(CORE, 'zzzzzzzzzz')).toBeNull();
+ }, SLOW);
+});
diff --git a/packages/cli/lib/integrations.mjs b/packages/cli/lib/integrations.mjs
index dea7192128..e92d9d0557 100644
--- a/packages/cli/lib/integrations.mjs
+++ b/packages/cli/lib/integrations.mjs
@@ -30,6 +30,8 @@ import {loadModuleWithSchema, findPresentFiles} from './module-loader.mjs';
* @property {string} __spec
* @property {string} __packageDir
* @property {string} __manifestFile
+ * @property {string} [__loadError] set when the manifest failed to load/validate;
+ * such an integration contributes nothing and is surfaced via Project.issues()
*/
/** Conventional manifest basenames, in load-precedence order. */
@@ -70,7 +72,26 @@ export async function loadManifestObject(file, label = 'integration manifest') {
* @param {string} [cwd]
*/
export function resolvePackageDir(packageName, cwd = process.cwd()) {
- return path.resolve(cwd, 'node_modules', ...packageName.split('/'));
+ // An integration spec is a bare npm package name — never a path. Reject `..`,
+ // `.`, and absolute specs so a config can't point the loader (which then
+ // dynamically imports the manifest) at an arbitrary module outside
+ // node_modules.
+ if (
+ typeof packageName !== 'string' ||
+ packageName.length === 0 ||
+ path.isAbsolute(packageName) ||
+ packageName.split('/').some(seg => seg === '..' || seg === '.')
+ ) {
+ throw new Error(
+ `Invalid integration package name "${packageName}". Use a bare package name (no path segments).`,
+ );
+ }
+ const nodeModules = path.resolve(cwd, 'node_modules');
+ const dir = path.resolve(nodeModules, ...packageName.split('/'));
+ if (dir !== nodeModules && !dir.startsWith(nodeModules + path.sep)) {
+ throw new Error(`Integration "${packageName}" resolves outside node_modules.`);
+ }
+ return dir;
}
/**
@@ -125,11 +146,28 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
}
const manifestFile = resolveManifestPath(packageDir, spec);
- const manifest = await loadModuleWithSchema(
- manifestFile,
- AstryxIntegrationSchema,
- {label: `Integration ${spec}`},
- );
+ let manifest;
+ try {
+ manifest = await loadModuleWithSchema(
+ manifestFile,
+ AstryxIntegrationSchema,
+ {label: `Integration ${spec}`},
+ );
+ } catch (err) {
+ // A manifest that throws on import or fails schema validation must NOT take
+ // down every command (component/docs/theme don't need this integration).
+ // Record a load-error marker; Project surfaces it via issues() and the
+ // discovery loops naturally skip it (no components/templates/codemods).
+ integrations.push({
+ name: pkg.name ?? spec,
+ version: pkg.version,
+ __spec: spec,
+ __packageDir: packageDir,
+ __manifestFile: manifestFile,
+ __loadError: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
/** @param {string | null | undefined} value */
const resolveRoot = value =>
diff --git a/packages/cli/lib/integrations.test.mjs b/packages/cli/lib/integrations.test.mjs
index 58b2b93ba7..ef3910252c 100644
--- a/packages/cli/lib/integrations.test.mjs
+++ b/packages/cli/lib/integrations.test.mjs
@@ -4,7 +4,7 @@ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {Project} from './project.mjs';
-import {loadIntegrations} from './integrations.mjs';
+import {loadIntegrations, resolvePackageDir} from './integrations.mjs';
import {discover} from '../api/discover/discover.mjs';
let tmpDir;
@@ -133,3 +133,43 @@ describe('configured integrations', () => {
);
});
});
+
+describe('resolvePackageDir — spec must be a bare package name', () => {
+ it.each(['../../../etc', 'a/../../b', '/abs/evil', 'foo/..', '..'])(
+ 'rejects a traversal/absolute spec %s',
+ spec => {
+ expect(() => resolvePackageDir(spec, '/proj')).toThrow(/Invalid|outside node_modules/i);
+ },
+ );
+
+ it('accepts scoped and plain package names', () => {
+ expect(resolvePackageDir('@acme/x', '/proj')).toBe(
+ path.join('/proj', 'node_modules', '@acme', 'x'),
+ );
+ expect(resolvePackageDir('lodash', '/proj')).toBe(
+ path.join('/proj', 'node_modules', 'lodash'),
+ );
+ });
+});
+
+describe('a broken integration manifest degrades gracefully (skip + warn)', () => {
+ it('does not crash Project.load; other integrations still load and the error surfaces', async () => {
+ // tmpDir already has @acme/widgets wired; add a good + bad alongside it.
+ const config = `export default { integrations: ['@good/a', '@bad/b'] };\n`;
+ fs.writeFileSync(path.join(tmpDir, 'astryx.config.mjs'), config);
+ for (const [name, body] of [
+ ['@good/a', 'export default {};'],
+ ['@bad/b', 'throw new Error("boom manifest");'],
+ ]) {
+ const dir = path.join(tmpDir, 'node_modules', ...name.split('/'));
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({name, version: '1.0.0'}));
+ fs.writeFileSync(path.join(dir, 'astryx.integration.mjs'), body);
+ }
+
+ const project = await Project.load(tmpDir); // must not throw
+ expect(project.loadedIntegrations.map(i => i.name)).toContain('@good/a');
+ const issues = await project.issues();
+ expect(issues.some(i => /boom manifest/.test(i.message))).toBe(true);
+ });
+});
diff --git a/packages/cli/lib/json-contract.test.mjs b/packages/cli/lib/json-contract.test.mjs
index 9dccde9bb0..3d8dd0fa23 100644
--- a/packages/cli/lib/json-contract.test.mjs
+++ b/packages/cli/lib/json-contract.test.mjs
@@ -100,6 +100,18 @@ describe('json envelope shape', () => {
const env = toErrorEnvelope('x', [{name: 'Button', reason: 'close match'}]);
expect(env.suggestions).toEqual([{name: 'Button', reason: 'close match'}]);
});
+
+ it('toErrorEnvelope omits suggestions for an empty array', () => {
+ expect('suggestions' in toErrorEnvelope('x', [])).toBe(false);
+ });
+
+ it('toErrorEnvelope drops non-array suggestions (only a real Suggestion[] is attached)', () => {
+ // The guard is `Array.isArray(...) && .length`, not a bare `?.length` — a
+ // string ("hello".length === 5) or a `{length: n}` object must NOT slip
+ // through as `suggestions`, which is contractually a Suggestion[].
+ expect('suggestions' in toErrorEnvelope('x', /** @type {any} */ ('hello'))).toBe(false);
+ expect('suggestions' in toErrorEnvelope('x', /** @type {any} */ ({length: 3}))).toBe(false);
+ });
});
describe('stdout discipline (humanLog / humanWarn)', () => {
diff --git a/packages/cli/lib/json-serialize.test.mjs b/packages/cli/lib/json-serialize.test.mjs
new file mode 100644
index 0000000000..c803def3c6
--- /dev/null
+++ b/packages/cli/lib/json-serialize.test.mjs
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Supplemental unit tests for lib/json.mjs — serialization-failure
+ * discipline.
+ *
+ * json-contract.test.mjs already locks envelope shape, apiVersion stamping,
+ * humanLog/humanWarn suppression, and the toErrorEnvelope code/suggestions
+ * rules. This file adds the case that guards the contract when serialization
+ * itself can fail:
+ *
+ * jsonOut() must SERIALIZE before it marks the emission handled. If
+ * JSON.stringify throws (a circular reference or a BigInt in `data` — an
+ * author bug in a command's return value), the process-wide
+ * `__xdsJsonHandled` flag must remain UNSET, so the bin error boundary is
+ * still free to emit a JSON error envelope. If the flag were set first, the
+ * boundary would go silent and a --json consumer would get EMPTY stdout with
+ * exit 1 — an unparseable non-envelope.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {jsonOut} from './json.mjs';
+
+describe('jsonOut — serialization-failure discipline', () => {
+ beforeEach(() => {
+ process.__xdsJsonHandled = false;
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ process.__xdsJsonHandled = false;
+ });
+
+ it('does NOT print when data has a circular reference', () => {
+ const circular = {};
+ circular.self = circular;
+ expect(() => jsonOut({type: 'x', data: circular})).toThrow(/circular/i);
+ expect(console.log).not.toHaveBeenCalled();
+ });
+
+ it('leaves __xdsJsonHandled unset when serialization throws (boundary can still emit)', () => {
+ const circular = {};
+ circular.self = circular;
+ try {
+ jsonOut({type: 'x', data: circular});
+ } catch {
+ /* expected */
+ }
+ expect(process.__xdsJsonHandled).toBe(false);
+ });
+
+ it('leaves __xdsJsonHandled unset when data contains a BigInt', () => {
+ try {
+ jsonOut({type: 'x', data: {n: 10n}});
+ } catch {
+ /* expected: BigInt is not JSON-serializable */
+ }
+ expect(process.__xdsJsonHandled).toBe(false);
+ });
+
+ it('marks handled and prints on a successful emission', () => {
+ jsonOut({type: 'ok', data: {a: 1}});
+ expect(process.__xdsJsonHandled).toBe(true);
+ expect(console.log).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/cli/lib/json.mjs b/packages/cli/lib/json.mjs
index f5d04be04c..a3cd87bafd 100644
--- a/packages/cli/lib/json.mjs
+++ b/packages/cli/lib/json.mjs
@@ -94,11 +94,19 @@ export function humanWarn(...args) {
* @returns {void}
*/
export function jsonOut(response) {
- process.__xdsJsonHandled = true;
/** @type {any} */
const envelope = {apiVersion: API_VERSION, type: response.type, data: response.data};
if (response.meta !== undefined) envelope.meta = response.meta;
- console.log(JSON.stringify(envelope, null, 2));
+ // Serialize BEFORE marking handled. If JSON.stringify throws (a circular
+ // reference or a BigInt in `data` — an author bug in a command's return
+ // value), the `__xdsJsonHandled` flag must stay unset so the bin error
+ // boundary is still free to emit a JSON error envelope. Setting the flag
+ // first leaves a --json consumer with empty stdout + exit 1 (an unparseable
+ // non-envelope), violating the "every --json emission is a single valid
+ // envelope" contract.
+ const out = JSON.stringify(envelope, null, 2);
+ process.__xdsJsonHandled = true;
+ console.log(out);
}
/**
@@ -129,7 +137,7 @@ export function toErrorEnvelope(err, suggestions, code) {
ERROR_CODES.ERR_UNKNOWN;
/** @type {any} */
const env = {apiVersion: API_VERSION, error: message, code: resolvedCode};
- if (suggestions?.length) env.suggestions = suggestions;
+ if (Array.isArray(suggestions) && suggestions.length) env.suggestions = suggestions;
return env;
}
diff --git a/packages/cli/lib/levenshtein.test.mjs b/packages/cli/lib/levenshtein.test.mjs
new file mode 100644
index 0000000000..f2d493cbdc
--- /dev/null
+++ b/packages/cli/lib/levenshtein.test.mjs
@@ -0,0 +1,40 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for levenshteinDistance — the fuzzy-suggestion primitive
+ * behind "did you mean" errors across component/hook/discover/theme. Had no
+ * coverage; these lock the edge cases (empty strings, symmetry, unicode).
+ */
+
+import {describe, it, expect} from 'vitest';
+import {levenshteinDistance as d} from './levenshtein.mjs';
+
+describe('levenshteinDistance', () => {
+ it('is 0 for identical strings', () => {
+ expect(d('Button', 'Button')).toBe(0);
+ expect(d('', '')).toBe(0);
+ });
+
+ it('handles empty inputs (distance = other length)', () => {
+ expect(d('', 'abc')).toBe(3);
+ expect(d('abc', '')).toBe(3);
+ });
+
+ it('computes the classic kitten/sitting distance', () => {
+ expect(d('kitten', 'sitting')).toBe(3);
+ });
+
+ it('is symmetric', () => {
+ expect(d('abc', 'xyz')).toBe(d('xyz', 'abc'));
+ expect(d('Button', 'Buttonn')).toBe(d('Buttonn', 'Button'));
+ });
+
+ it('counts a single substitution/insertion for near-miss names', () => {
+ expect(d('Button', 'Buttonn')).toBe(1);
+ expect(d('useMediaQuery', 'usemediaquery')).toBe(2); // M->m and Q->q
+ });
+
+ it('handles unicode', () => {
+ expect(d('café', 'cafe')).toBe(1);
+ });
+});
diff --git a/packages/cli/lib/manifest.mjs b/packages/cli/lib/manifest.mjs
index b5ada4da6b..a571a1df63 100644
--- a/packages/cli/lib/manifest.mjs
+++ b/packages/cli/lib/manifest.mjs
@@ -209,7 +209,15 @@ function describeCommand(cmd, root, jsonSupported) {
if (EXAMPLES[name]) entry.examples = [...EXAMPLES[name]];
- if (subcommands.length > 0) entry.subcommands = subcommands;
+ // Sort subcommands by name for a stable, agent-facing contract — the same
+ // guarantee the top-level command list makes. Otherwise Commander
+ // registration order leaks into the manifest and a pure reorder of
+ // `.command()` calls silently changes the output.
+ if (subcommands.length > 0) {
+ entry.subcommands = subcommands.sort((a, b) =>
+ /** @type {any} */ (a).name.localeCompare(/** @type {any} */ (b).name),
+ );
+ }
return entry;
}
diff --git a/packages/cli/lib/manifest.test.mjs b/packages/cli/lib/manifest.test.mjs
index 488e781b25..74c79a2aad 100644
--- a/packages/cli/lib/manifest.test.mjs
+++ b/packages/cli/lib/manifest.test.mjs
@@ -85,6 +85,24 @@ describe('manifest: drift guards', () => {
}
}
});
+
+ it('sorts subcommands by name (stable, agent-facing order)', () => {
+ for (const entry of allEntries) {
+ if (!entry.subcommands) continue;
+ const names = entry.subcommands.map((s) => s.name);
+ expect(names, `subcommands of "${entry.name}" are not sorted`).toEqual(
+ [...names].sort((a, b) => a.localeCompare(b)),
+ );
+ }
+ });
+
+ it('is deterministic across builds', () => {
+ const again = buildManifest(program, {
+ jsonSupported: JSON_SUPPORTED,
+ version: '0.0.0-test',
+ });
+ expect(again).toEqual(manifest);
+ });
});
describe('manifest: shape', () => {
diff --git a/packages/cli/lib/package-scanner.mjs b/packages/cli/lib/package-scanner.mjs
index 29e89080b8..605b454bde 100644
--- a/packages/cli/lib/package-scanner.mjs
+++ b/packages/cli/lib/package-scanner.mjs
@@ -39,13 +39,22 @@ export function scanDirectory(scanDir) {
} catch {
continue;
}
- if (!pkg.astryx || !pkg.astryx.docs) continue;
+ // `astryx.docs` is third-party-controlled (a dependency's package.json).
+ // A truthy non-string (number/array) would slip past `!pkg.astryx.docs`
+ // and crash path.resolve with a raw TypeError, taking down the whole scan.
+ // Skip it — discovery must degrade, not crash.
+ if (!pkg.astryx || typeof pkg.astryx.docs !== 'string') continue;
const pkgDir = path.join(scanDir, entry.name);
const docsDir = path.resolve(pkgDir, pkg.astryx.docs);
+ // Defense-in-depth: a dependency's docs dir must stay inside its own
+ // package (a `docs: "../../x"` shouldn't let the scanner walk arbitrary
+ // sibling dirs). Skip an escaping entry rather than surfacing foreign docs.
+ const pkgDirWithSep = pkgDir.endsWith(path.sep) ? pkgDir : pkgDir + path.sep;
+ if (docsDir !== pkgDir && !docsDir.startsWith(pkgDirWithSep)) continue;
const components = discoverDocComponents(docsDir);
if (components.length === 0) continue;
packages.push({
- name: pkg.name || entry.name,
+ name: String(pkg.name || entry.name),
version: pkg.version,
description: pkg.description,
displayName: pkg.displayName,
diff --git a/packages/cli/lib/package-scanner.test.mjs b/packages/cli/lib/package-scanner.test.mjs
new file mode 100644
index 0000000000..bd79efcccb
--- /dev/null
+++ b/packages/cli/lib/package-scanner.test.mjs
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the config-based package scanner. Focuses on adversarial
+ * node_modules — a dependency's package.json is fully third-party-controlled,
+ * so a malformed `astryx.docs` (non-string, path-escaping) must degrade the
+ * scan (skip that entry) rather than crash or expose foreign docs.
+ */
+
+import {describe, it, expect, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {
+ scanDirectory,
+ scanAllPackages,
+ findComponentInPackages,
+} from './package-scanner.mjs';
+
+let tmp;
+afterEach(() => {
+ if (tmp) fs.rmSync(tmp, {recursive: true, force: true});
+ tmp = undefined;
+});
+
+/** Write a package dir with a package.json + optional docs files. */
+function writePkg(root, name, {astryx, docs} = {}) {
+ const dir = path.join(root, name);
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name, ...(astryx ? {astryx} : {})}),
+ );
+ if (docs) {
+ for (const [rel, contents] of Object.entries(docs)) {
+ const p = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(p), {recursive: true});
+ fs.writeFileSync(p, contents);
+ }
+ }
+ return dir;
+}
+
+describe('scanDirectory — adversarial node_modules', () => {
+ it('skips a package with a non-string astryx.docs instead of crashing', () => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ps-nonstr-'));
+ writePkg(tmp, 'good', {
+ astryx: {docs: 'docs'},
+ docs: {'docs/Btn.doc.mjs': 'export const docs = {};'},
+ });
+ // number, not string — must not slip past the guard and crash path.resolve.
+ writePkg(tmp, 'bad', {astryx: {docs: 123}});
+ const res = scanDirectory(tmp);
+ expect(res.map(p => p.name)).toEqual(['good']);
+ });
+
+ it('skips a docs dir that escapes its own package (../.. traversal)', () => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ps-escape-'));
+ // A sibling with real docs the escaper would try to reach.
+ writePkg(tmp, 'victim', {
+ docs: {'Secret.doc.mjs': 'export const docs = {};'},
+ });
+ writePkg(tmp, 'escaper', {astryx: {docs: '../victim'}});
+ const res = scanDirectory(tmp);
+ // escaper is skipped (docs escapes its package); victim has no astryx.docs.
+ expect(res.map(p => p.name)).toEqual([]);
+ });
+
+ it('coerces a non-string package name to a string', () => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ps-name-'));
+ const dir = path.join(tmp, 'weird');
+ fs.mkdirSync(path.join(dir, 'docs'), {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: 12345, astryx: {docs: 'docs'}}),
+ );
+ fs.writeFileSync(path.join(dir, 'docs', 'X.doc.mjs'), 'export const docs = {};');
+ const res = scanDirectory(tmp);
+ expect(res).toHaveLength(1);
+ expect(typeof res[0].name).toBe('string');
+ expect(res[0].name).toBe('12345');
+ });
+
+ it('discovers a well-formed package with nested docs (skips node_modules)', () => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ps-ok-'));
+ writePkg(tmp, 'ds', {
+ astryx: {docs: 'docs'},
+ docs: {
+ 'docs/A.doc.mjs': 'export const docs = {};',
+ 'docs/nested/B.doc.mjs': 'export const docs = {};',
+ 'docs/node_modules/Skip.doc.mjs': 'export const docs = {};',
+ },
+ });
+ const res = scanDirectory(tmp);
+ expect(res).toHaveLength(1);
+ expect(res[0].components).toEqual(['A', 'B']);
+ });
+
+ it('returns [] for a missing scan dir', () => {
+ expect(scanDirectory('/no/such/dir/anywhere')).toEqual([]);
+ });
+});
+
+describe('scanAllPackages + findComponentInPackages', () => {
+ it('dedups by name and finds a component case-insensitively', () => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ps-all-'));
+ writePkg(tmp, 'ds', {
+ astryx: {docs: 'docs'},
+ docs: {'docs/Button.doc.mjs': 'export const docs = {};'},
+ });
+ const all = scanAllPackages([tmp]);
+ expect(all.map(p => p.name)).toEqual(['ds']);
+ const found = findComponentInPackages(all, 'button');
+ expect(found).not.toBeNull();
+ expect(found.componentName).toBe('Button');
+ });
+});
diff --git a/packages/cli/lib/parse.test.mjs b/packages/cli/lib/parse.test.mjs
new file mode 100644
index 0000000000..07917f45a8
--- /dev/null
+++ b/packages/cli/lib/parse.test.mjs
@@ -0,0 +1,76 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for parse.mjs — the CONSUMER-FACING JSON helpers
+ * exported as `@astryxdesign/cli/json`. These lock the contract downstream
+ * consumers depend on:
+ * - parseResponse JSON-parses a string but passes a non-string through
+ * by reference (idempotent on already-parsed envelopes),
+ * - parseResponse propagates a SyntaxError on malformed JSON,
+ * - isError is a safe type-guard that is true only for objects carrying an
+ * `error` key (never throws on null/undefined/primitives),
+ * - assertResponse returns the envelope on a type match, throws the CLI's
+ * error string on an error envelope, and throws a descriptive message on
+ * a type mismatch.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {parseResponse, isError, assertResponse} from './parse.mjs';
+
+describe('parseResponse', () => {
+ it('parses a JSON string into an object', () => {
+ expect(parseResponse('{"type":"t","data":1}')).toEqual({
+ type: 't',
+ data: 1,
+ });
+ });
+
+ it('passes a non-string value through by reference (idempotent)', () => {
+ const already = {type: 't', data: 1};
+ expect(parseResponse(already)).toBe(already);
+ expect(parseResponse(null)).toBeNull();
+ });
+
+ it('throws a SyntaxError on malformed JSON', () => {
+ expect(() => parseResponse('{not json')).toThrow(SyntaxError);
+ });
+});
+
+describe('isError', () => {
+ it('is true only for an object with an `error` key', () => {
+ expect(isError({error: 'boom'})).toBe(true);
+ expect(isError({type: 'ok'})).toBe(false);
+ });
+
+ it('never throws on null / undefined / primitives', () => {
+ expect(isError(null)).toBe(false);
+ expect(isError(undefined)).toBe(false);
+ expect(isError('error')).toBe(false);
+ expect(isError(5)).toBe(false);
+ expect(isError(true)).toBe(false);
+ });
+});
+
+describe('assertResponse', () => {
+ it('returns the parsed envelope when the type matches', () => {
+ expect(assertResponse('{"type":"foo","data":42}', 'foo')).toEqual({
+ type: 'foo',
+ data: 42,
+ });
+ });
+
+ it('accepts an already-parsed object', () => {
+ const env = {type: 'foo', data: 1};
+ expect(assertResponse(env, 'foo')).toBe(env);
+ });
+
+ it('throws the CLI error string on an error envelope', () => {
+ expect(() => assertResponse('{"error":"boom"}', 'foo')).toThrow('boom');
+ });
+
+ it('throws a descriptive message on a type mismatch', () => {
+ expect(() => assertResponse('{"type":"bar"}', 'foo')).toThrow(
+ 'Expected type "foo", got "bar"',
+ );
+ });
+});
diff --git a/packages/cli/lib/project.mjs b/packages/cli/lib/project.mjs
index eb4d964089..5202127241 100644
--- a/packages/cli/lib/project.mjs
+++ b/packages/cli/lib/project.mjs
@@ -316,6 +316,17 @@ export class Project {
const pkg = this.#pkgLabel(integration);
if (this.#visitedIssues.has(pkg)) return;
this.#visitedIssues.add(pkg);
+ // A manifest that failed to load (throwing import / invalid shape) is
+ // recorded as a marker by loadIntegrations — surface it as an issue and
+ // skip validation (there's no manifest to validate).
+ if (integration?.__loadError) {
+ this.#pushIssue(pkg, {
+ code: 'integration_error',
+ severity: 'error',
+ message: integration.__loadError,
+ });
+ return;
+ }
try {
const found = await validateLoadedIntegration(integration);
for (const issue of found ?? []) this.#pushIssue(pkg, issue);
diff --git a/packages/cli/lib/resolve-theme.mjs b/packages/cli/lib/resolve-theme.mjs
index 7c6d6dc2d4..91c6035052 100644
--- a/packages/cli/lib/resolve-theme.mjs
+++ b/packages/cli/lib/resolve-theme.mjs
@@ -104,7 +104,11 @@ export function resolveTheme(cwd = process.cwd()) {
}
}
- if (!specifier) {
+ // `astryx.theme` (package.json) and ASTRYX_THEME are user/third-party
+ // controlled and may be any value. Anything that isn't a usable non-empty
+ // string means "no theme" — degrade to null rather than crashing on
+ // specifier.startsWith(...) below. (Subsumes the empty-string case.)
+ if (typeof specifier !== 'string' || specifier.length === 0) {
return null;
}
diff --git a/packages/cli/lib/resolve-theme.test.mjs b/packages/cli/lib/resolve-theme.test.mjs
new file mode 100644
index 0000000000..ef31235fca
--- /dev/null
+++ b/packages/cli/lib/resolve-theme.test.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for resolveTheme's handling of a malformed `astryx.theme`.
+ * The field is user/third-party-controlled config, so a non-string value must
+ * degrade to null (like an unknown slug) rather than crash `astryx component`
+ * with a raw TypeError from specifier.startsWith(...).
+ */
+
+import {describe, it, expect, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {resolveTheme} from './resolve-theme.mjs';
+
+const dirs = [];
+function fixture(pkg) {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'resolve-theme-'));
+ dirs.push(d);
+ fs.writeFileSync(path.join(d, 'package.json'), JSON.stringify(pkg));
+ return d;
+}
+afterEach(() => {
+ delete process.env.ASTRYX_THEME;
+ while (dirs.length) fs.rmSync(dirs.pop(), {recursive: true, force: true});
+});
+
+describe('resolveTheme — malformed astryx.theme degrades to null', () => {
+ it('numeric theme → null', () => {
+ expect(resolveTheme(fixture({astryx: {theme: 123}}))).toBeNull();
+ });
+ it('array theme → null', () => {
+ expect(resolveTheme(fixture({astryx: {theme: ['a']}}))).toBeNull();
+ });
+ it('object theme → null', () => {
+ expect(resolveTheme(fixture({astryx: {theme: {x: 1}}}))).toBeNull();
+ });
+ it('boolean theme → null', () => {
+ expect(resolveTheme(fixture({astryx: {theme: true}}))).toBeNull();
+ });
+ it('empty-string theme → null', () => {
+ expect(resolveTheme(fixture({astryx: {theme: ''}}))).toBeNull();
+ });
+ it('no theme field → null', () => {
+ expect(resolveTheme(fixture({name: 'p'}))).toBeNull();
+ });
+});
diff --git a/packages/cli/lib/string-utils.test.mjs b/packages/cli/lib/string-utils.test.mjs
new file mode 100644
index 0000000000..7d89981c9f
--- /dev/null
+++ b/packages/cli/lib/string-utils.test.mjs
@@ -0,0 +1,158 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for string-utils — the fuzzy-matching and semantic
+ * search surface. These lock the ROBUSTNESS and ORDERING invariants that the
+ * `component` / `search` commands rely on:
+ * - neither helper throws on empty / whitespace / unicode / very-long /
+ * regex-metacharacter input (the needle is user-controlled),
+ * - regex metacharacters in the needle are ESCAPED before being used in the
+ * description RegExp (a bare `.*` or `(` must not throw or match-all),
+ * - findClosestComponents sorts by ascending distance and honours maxDistance,
+ * - searchComponents scores an exact name match 100, dedupes by name, and
+ * sorts by score desc then name asc.
+ * The doc-file reading (Pass 2) is exercised end-to-end elsewhere; here we use
+ * a non-existent coreDir so Pass 2 is a no-op and the tests stay pure + fast.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ findClosestComponents,
+ searchComponents,
+ levenshteinDistance,
+} from './string-utils.mjs';
+
+const COMPONENTS = {group: ['Button', 'Card', 'Text', 'Badge', 'Avatar']};
+// A coreDir that does not exist -> Pass 2 (doc reads) is a no-op, so results
+// come purely from name/distance scoring. Keeps these tests pure and fast.
+const NO_CORE = '/definitely/not/a/real/dir';
+
+describe('levenshteinDistance (re-export)', () => {
+ it('is re-exported and computes classic edit distance', () => {
+ expect(levenshteinDistance('kitten', 'sitting')).toBe(3);
+ expect(levenshteinDistance('same', 'same')).toBe(0);
+ });
+});
+
+describe('findClosestComponents', () => {
+ it('returns distance 0 for an exact (case-insensitive) match', () => {
+ expect(findClosestComponents('button', COMPONENTS)).toEqual([
+ {name: 'Button', distance: 0},
+ ]);
+ });
+
+ it('finds a one-edit typo and reports distance 1', () => {
+ const matches = findClosestComponents('Buton', COMPONENTS);
+ expect(matches[0]).toEqual({name: 'Button', distance: 1});
+ });
+
+ it('sorts matches by ascending distance', () => {
+ const matches = findClosestComponents('Card', COMPONENTS);
+ const distances = matches.map(m => m.distance);
+ expect(distances).toEqual([...distances].sort((a, b) => a - b));
+ });
+
+ it('honours the maxDistance filter (default 3)', () => {
+ // "Bird" is >3 edits from every component -> filtered out.
+ expect(findClosestComponents('Bird', COMPONENTS, 1)).toEqual([]);
+ // Tightening maxDistance never returns more than the default.
+ const wide = findClosestComponents('Buton', COMPONENTS, 3).length;
+ const narrow = findClosestComponents('Buton', COMPONENTS, 1).length;
+ expect(narrow).toBeLessThanOrEqual(wide);
+ });
+
+ it('does not throw on empty / whitespace / regex-special / unicode / long input', () => {
+ expect(findClosestComponents('', COMPONENTS)).toEqual([]);
+ expect(() => findClosestComponents(' ', COMPONENTS)).not.toThrow();
+ // Regex metacharacters must be treated as literal text, never matched-all.
+ expect(findClosestComponents('.*', COMPONENTS)).toEqual([]);
+ expect(() => findClosestComponents('(', COMPONENTS)).not.toThrow();
+ expect(() =>
+ findClosestComponents('café', {g: ['café', 'cafe']}),
+ ).not.toThrow();
+ expect(() =>
+ findClosestComponents('a'.repeat(100_000), COMPONENTS),
+ ).not.toThrow();
+ });
+
+ it('handles an empty component registry', () => {
+ expect(findClosestComponents('Button', {})).toEqual([]);
+ });
+});
+
+describe('searchComponents', () => {
+ it('scores an exact name match 100', async () => {
+ const results = await searchComponents('Button', NO_CORE, COMPONENTS);
+ expect(results[0]).toEqual({
+ name: 'Button',
+ score: 100,
+ reason: 'exact name',
+ });
+ });
+
+ it('scores a distance-1 name match 80', async () => {
+ const results = await searchComponents('Buton', NO_CORE, COMPONENTS);
+ expect(results[0]).toMatchObject({name: 'Button', score: 80});
+ });
+
+ it('dedupes by name (an exact match yields a single entry)', async () => {
+ const results = await searchComponents('Button', NO_CORE, {
+ g: ['Button', 'Buttonx'],
+ });
+ const buttons = results.filter(r => r.name === 'Button');
+ expect(buttons).toHaveLength(1);
+ expect(buttons[0].score).toBe(100);
+ });
+
+ it('sorts by score desc, then name asc on ties', async () => {
+ const results = await searchComponents('Button', NO_CORE, COMPONENTS);
+ for (let i = 1; i < results.length; i++) {
+ const prev = results[i - 1];
+ const cur = results[i];
+ expect(prev.score).toBeGreaterThanOrEqual(cur.score);
+ if (prev.score === cur.score) {
+ expect(prev.name.localeCompare(cur.name)).toBeLessThanOrEqual(0);
+ }
+ }
+ });
+
+ it('breaks a score tie alphabetically', async () => {
+ // Both names are edit-distance 2 from "bcd" -> both score 40 -> alpha order.
+ const results = await searchComponents('bcd', NO_CORE, {g: ['Xbc', 'Abc']});
+ expect(results.map(r => r.name)).toEqual(['Abc', 'Xbc']);
+ expect(results.every(r => r.score === 40)).toBe(true);
+ });
+
+ it('treats regex metacharacters as literal (no throw, no match-all)', async () => {
+ // A bare `.*` would match every description if the needle were not escaped;
+ // with escaping + no doc dir it simply scores nothing.
+ await expect(
+ searchComponents('.*', NO_CORE, COMPONENTS),
+ ).resolves.toEqual([]);
+ await expect(
+ searchComponents('(', NO_CORE, COMPONENTS),
+ ).resolves.toEqual([]);
+ await expect(
+ searchComponents('[a-z]+', NO_CORE, COMPONENTS),
+ ).resolves.toEqual([]);
+ });
+
+ it('does not throw on empty / whitespace / unicode / very-long input', async () => {
+ await expect(
+ searchComponents('', NO_CORE, COMPONENTS),
+ ).resolves.toEqual([]);
+ await expect(
+ searchComponents(' ', NO_CORE, COMPONENTS),
+ ).resolves.not.toThrow();
+ await expect(
+ searchComponents('café', NO_CORE, {g: ['café', 'cafe']}),
+ ).resolves.toBeInstanceOf(Array);
+ await expect(
+ searchComponents('a'.repeat(100_000), NO_CORE, COMPONENTS),
+ ).resolves.toBeInstanceOf(Array);
+ });
+
+ it('returns an empty array for an empty registry without throwing', async () => {
+ await expect(searchComponents('Button', NO_CORE, {})).resolves.toEqual([]);
+ });
+});
diff --git a/packages/cli/lib/term-log.test.mjs b/packages/cli/lib/term-log.test.mjs
new file mode 100644
index 0000000000..1cb8416fee
--- /dev/null
+++ b/packages/cli/lib/term-log.test.mjs
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated tests for term-log.mjs — the CLI's output-only `log` surface
+ * for codemods. These lock the documented invariant that keeps the "--json is
+ * always valid JSON" contract intact: in --json mode, EVERY `log` helper
+ * (message/info/step/success/warn/error) emits ZERO stdout, so a stray codemod
+ * log can never corrupt a JSON envelope. A sanity check confirms the helpers DO
+ * emit in human mode, so the json-mode silence is meaningful (not a dead spy).
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as p from './term-log.mjs';
+import {setJsonMode} from './json.mjs';
+
+let logSpy;
+let errSpy;
+
+beforeEach(() => {
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ setJsonMode(false); // never leak json mode into other test files
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+});
+
+/** Exercise every human-facing emitter the `log` surface exposes. */
+function callAllLogHelpers() {
+ p.log.message('m');
+ p.log.info('i');
+ p.log.step('s');
+ p.log.success('ok');
+ p.log.warn('w');
+ p.log.error('e');
+}
+
+describe('term-log --json silence', () => {
+ it('emits ZERO stdout from every log helper in --json mode', () => {
+ setJsonMode(true);
+ callAllLogHelpers();
+ expect(logSpy).not.toHaveBeenCalled();
+ expect(errSpy).not.toHaveBeenCalled();
+ });
+});
+
+describe('sanity: helpers are live in human mode', () => {
+ it('log.success emits to stdout when not in --json mode', () => {
+ setJsonMode(false);
+ p.log.success('done');
+ expect(logSpy).toHaveBeenCalledTimes(1);
+ expect(logSpy).toHaveBeenCalledWith('✓ done');
+ });
+
+ it('every log helper emits exactly one stdout line in human mode', () => {
+ setJsonMode(false);
+ callAllLogHelpers(); // 6 emitters -> 6 console.log calls
+ expect(logSpy).toHaveBeenCalledTimes(6);
+ });
+});
diff --git a/packages/cli/lib/xle/expand.mjs b/packages/cli/lib/xle/expand.mjs
index 32af0c1971..9bff7b847d 100644
--- a/packages/cli/lib/xle/expand.mjs
+++ b/packages/cli/lib/xle/expand.mjs
@@ -38,6 +38,18 @@ function escapeAttr(value) {
return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
+/**
+ * JSX text nodes cannot contain raw `<`, `>`, `{`, or `}`. When a text payload
+ * contains any of them, emit it as a string-expression child so the output is
+ * valid TSX. Plain text is passed through unchanged.
+ * @param {import('./xle-ast').XLEValue} text
+ * @returns {string}
+ */
+function jsxText(text) {
+ const str = String(text);
+ return /[<>{}]/.test(str) ? `{${JSON.stringify(str)}}` : str;
+}
+
/**
* @param {import('./xle-ast').XLEItem} item
* @returns {import('./xle-ast').XLEItem}
@@ -419,13 +431,13 @@ class Emitter {
const bodyLines = [];
if (node.hint) bodyLines.push(...this.emitHint(node.hint, depth + 1));
- if (textChild != null) bodyLines.push(`${INDENT.repeat(depth + 1)}${textChild}`);
+ if (textChild != null) bodyLines.push(`${INDENT.repeat(depth + 1)}${jsxText(textChild)}`);
bodyLines.push(...this.emitItems(children, depth + 1, childContext));
// Required children with nothing to render → placeholder text.
const childrenProp = component.props.get('children');
if (bodyLines.length === 0 && childrenProp?.required) {
- bodyLines.push(`${INDENT.repeat(depth + 1)}${node.payload || component.name}`);
+ bodyLines.push(`${INDENT.repeat(depth + 1)}${jsxText(node.payload || component.name)}`);
}
const lines = this.renderTag(component, props, slotEntries, bodyLines, depth);
@@ -492,7 +504,7 @@ class Emitter {
}
if (typeof value === 'string') {
const text = this.requireComponent('Text');
- return [text ? `<${text.exportName}>${value}</${text.exportName}>` : `<>${value}</>`];
+ return [text ? `<${text.exportName}>${jsxText(value)}</${text.exportName}>` : `<>${jsxText(value)}</>`];
}
if ('hint' in value) {
return [
@@ -700,9 +712,11 @@ export function expand(doc, registry, options = {}) {
]
: [];
- const needsFragment = doc.roots.length + (doc.overlays.length > 0 ? 1 : 0) > 1
- || doc.roots.length > 1
- || (doc.overlays.length > 0);
+ // Count top-level elements *after* group/repeat expansion — a single root
+ // item can still emit multiple siblings (`B*3`, `(a + b)`), which need a
+ // fragment wrapper to be valid JSX.
+ const topLevelRoots = emitter.flattenItems(doc.roots).length;
+ const needsFragment = topLevelRoots + (doc.overlays.length > 0 ? 1 : 0) > 1;
const body = [];
if (needsFragment) {
diff --git a/packages/cli/lib/xle/parse.mjs b/packages/cli/lib/xle/parse.mjs
index 495aaecf68..68c84aa3ed 100644
--- a/packages/cli/lib/xle/parse.mjs
+++ b/packages/cli/lib/xle/parse.mjs
@@ -285,6 +285,16 @@ function parseAttrToken(token, line) {
// ─── compact (XLE) surface ─────────────────────────────────────────────────
+/**
+ * Guard against unbounded recursion in the compact parser. A layout tree this
+ * deep is never hand-authored; without the cap the recursive descent blows the
+ * JS call stack and surfaces a raw RangeError (→ ERR_UNKNOWN, no line/col)
+ * instead of a located ERR_LAYOUT_PARSE. The counter is module-level so it
+ * spans group / attribute sub-streams; each parse entry point resets it.
+ */
+const MAX_COMPACT_DEPTH = 512;
+let compactDepth = 0;
+
class CompactStream {
/**
* @param {string} src
@@ -467,23 +477,37 @@ function structuredCloneNode(node) {
* @returns {import('./xle-ast').XLEItem[]}
*/
function parseCompactSiblings(s) {
- /** @type {import('./xle-ast').XLEItem[]} */
- const terms = [];
- for (;;) {
- s.skipWs();
- if (s.eof()) break;
- if (s.peek() === '^') {
- s.error("'^' climb-up is not supported — group siblings with (...) instead");
- }
- terms.push(parseCompactTerm(s));
- s.skipWs();
- if (s.peek() === '^') {
- s.error("'^' climb-up is not supported — group siblings with (...) instead");
+ if (++compactDepth > MAX_COMPACT_DEPTH) {
+ compactDepth--;
+ s.error(
+ `Layout is nested too deeply (limit ${MAX_COMPACT_DEPTH}); ` +
+ `flatten the tree or split it into blocks`,
+ );
+ }
+ try {
+ /** @type {import('./xle-ast').XLEItem[]} */
+ const terms = [];
+ for (;;) {
+ s.skipWs();
+ if (s.eof()) break;
+ if (s.peek() === '^') {
+ s.error("'^' climb-up is not supported — group siblings with (...) instead");
+ }
+ terms.push(parseCompactTerm(s));
+ s.skipWs();
+ if (s.peek() === '^') {
+ s.error("'^' climb-up is not supported — group siblings with (...) instead");
+ }
+ if (s.peek() === '+') {
+ s.next();
+ continue;
+ }
+ break;
}
- if (s.peek() === '+') { s.next(); continue; }
- break;
+ return terms;
+ } finally {
+ compactDepth--;
}
- return terms;
}
/**
@@ -491,6 +515,7 @@ function parseCompactSiblings(s) {
* @returns {import('./xle-ast').XLEDoc}
*/
export function parseCompact(source) {
+ compactDepth = 0;
const parts = source.split(/;;/);
const main = new CompactStream(parts[0]);
const roots = parseCompactSiblings(main);
diff --git a/packages/cli/lib/xle/print.mjs b/packages/cli/lib/xle/print.mjs
index 055dea74d7..7ad3242df1 100644
--- a/packages/cli/lib/xle/print.mjs
+++ b/packages/cli/lib/xle/print.mjs
@@ -13,12 +13,28 @@
* @position lib/xle — inverse of parse.mjs
*/
+/**
+ * Quote a string for XLE/XLO output. The lexer (parse.mjs readString) has no
+ * escape mechanism — a quoted run ends at the next matching delimiter — so we
+ * pick the delimiter the string does NOT contain. This keeps the printed
+ * surface re-parseable (e.g. a Button `label="Don't panic"` must not emit
+ * `'Don't panic'`, which re-parses as a broken/unclosed token). A string
+ * containing BOTH quote kinds is unrepresentable without parser escape support
+ * and degrades to double-quotes (documented limitation).
+ * @param {string} str
+ * @returns {string}
+ */
+function quoteStr(str) {
+ return str.includes('"') && !str.includes("'") ? `'${str}'` : `"${str}"`;
+}
+
/**
* @param {import('./xle-ast').XLEValue} value
* @returns {string}
*/
function valueText(value) {
- if (typeof value === 'string') return /[\s,'"]/.test(value) ? `'${value}'` : value;
+ if (typeof value === 'string')
+ return /[\s,'"]/.test(value) ? quoteStr(value) : value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
if (value && /** @type {any} */ (value).idref) return `#${/** @type {any} */ (value).idref}`;
if (Array.isArray(value)) return `[${value.map(valueText).join(',')}]`;
@@ -56,7 +72,7 @@ function attrTokens(node) {
function slotTokensCompact(node) {
return node.slots.map(slot => {
if (slot.value == null) return `@${slot.key}`;
- if (typeof slot.value === 'string') return `@${slot.key}='${slot.value}'`;
+ if (typeof slot.value === 'string') return `@${slot.key}=${quoteStr(slot.value)}`;
if ('hint' in slot.value) return `@${slot.key}=${hintText(slot.value.hint)}`;
if (/** @type {any} */ (slot.value).idref) return `@${slot.key}=#${/** @type {any} */ (slot.value).idref}`;
if ('subexpr' in slot.value) return `@${slot.key}=(${siblingsCompact(slot.value.subexpr)})`;
@@ -72,8 +88,8 @@ function nodeCompact(node) {
let out = node.name || '';
if (node.id) out += `#${node.id}`;
for (const mod of node.enumMods) out += `.${mod}`;
- if (node.payload != null) out += `"${node.payload}"`;
- if (node.payload2 != null) out += `:"${node.payload2}"`;
+ if (node.payload != null) out += quoteStr(node.payload);
+ if (node.payload2 != null) out += `:${quoteStr(node.payload2)}`;
const attrs = [...attrTokens(node), ...slotTokensCompact(node)];
if (attrs.length > 0) out += `[${attrs.join(' ')}]`;
if (node.hint) out += hintText(node.hint);
@@ -139,8 +155,8 @@ function nodeOutlineLines(node, depth) {
let line = node.name || '';
if (node.id) line += `#${node.id}`;
for (const mod of node.enumMods) line += `.${mod}`;
- if (node.payload != null) line += ` "${node.payload}"`;
- if (node.payload2 != null) line += ` :"${node.payload2}"`;
+ if (node.payload != null) line += ` ${quoteStr(node.payload)}`;
+ if (node.payload2 != null) line += ` :${quoteStr(node.payload2)}`;
const attrs = attrTokens(node);
if (attrs.length > 0) line += ' ' + attrs.join(' ');
if (node.hint) line += ' ' + hintText(node.hint);
@@ -161,7 +177,7 @@ function nodeOutlineLines(node, depth) {
for (const sub of sv.subexpr) lines.push(...itemOutlineLines(sub, depth + 2));
}
} else if (typeof sv === 'string') {
- lines.push(`${pad} ${slot.key}: "${sv}"`);
+ lines.push(`${pad} ${slot.key}: ${quoteStr(sv)}`);
} else if (sv && typeof sv === 'object' && 'hint' in sv) {
lines.push(`${pad} ${slot.key}: ${hintText(sv.hint)}`);
} else if (sv && /** @type {any} */ (sv).idref) {
diff --git a/packages/cli/lib/xle/print.test.mjs b/packages/cli/lib/xle/print.test.mjs
new file mode 100644
index 0000000000..3b5064746e
--- /dev/null
+++ b/packages/cli/lib/xle/print.test.mjs
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Round-trip tests for the XLE printers (print.mjs). The lexer has no
+ * string-escape mechanism, so the printer must pick a delimiter the string
+ * doesn't contain — otherwise a valid expression (e.g. a Button label with an
+ * apostrophe) re-serializes into text that no longer parses. These lock that
+ * contract for both compact and outline surfaces.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {parse} from './parse.mjs';
+import {toCompact, toOutline} from './print.mjs';
+
+/** Parse an expression, print it back, re-parse, and return the KV value. */
+function kvOf(ast, key) {
+ const attr = ast.roots[0].attrs.find(a => a.kind === 'kv' && a.key === key);
+ return attr ? attr.value : undefined;
+}
+
+describe('print round-trip — strings with embedded quotes', () => {
+ it('KV value with an apostrophe re-parses identically (compact)', () => {
+ const doc = parse(`B[label="Don't panic"]`, {form: 'compact'});
+ const round = parse(toCompact(doc), {form: 'compact'});
+ expect(kvOf(round, 'label')).toBe("Don't panic");
+ });
+
+ it('KV value with an apostrophe re-parses identically (outline)', () => {
+ const doc = parse(`B[label="Don't panic"]`, {form: 'compact'});
+ const round = parse(toOutline(doc), {form: 'outline'});
+ expect(kvOf(round, 'label')).toBe("Don't panic");
+ });
+
+ it('payload with double quotes re-parses identically (compact)', () => {
+ const doc = parse(`Tx'She said "hi"'`, {form: 'compact'});
+ const round = parse(toCompact(doc), {form: 'compact'});
+ expect(round.roots[0].payload).toBe('She said "hi"');
+ });
+
+ it('payload with double quotes re-parses identically (outline)', () => {
+ const doc = parse(`Tx'She said "hi"'`, {form: 'compact'});
+ const round = parse(toOutline(doc), {form: 'outline'});
+ expect(round.roots[0].payload).toBe('She said "hi"');
+ });
+
+ it('plain values are still emitted unquoted', () => {
+ const doc = parse(`B[variant=primary]`, {form: 'compact'});
+ expect(toCompact(doc)).toContain('variant=primary');
+ });
+});
diff --git a/packages/cli/lib/xle/xle.test.mjs b/packages/cli/lib/xle/xle.test.mjs
index e09ca61dc2..ae11902344 100644
--- a/packages/cli/lib/xle/xle.test.mjs
+++ b/packages/cli/lib/xle/xle.test.mjs
@@ -331,3 +331,39 @@ describe('parseEnumValues', () => {
expect(parseEnumValues('boolean')).toBeNull();
});
});
+
+// ─── compact parser depth guard ─────────────────────────────────────────────
+
+describe('parseCompact depth guard', () => {
+ it('rejects pathologically deep child chains with a located parse error', () => {
+ let err;
+ try {
+ parseCompact('V > '.repeat(2000) + 'C');
+ } catch (e) {
+ err = e;
+ }
+ expect(err).toBeInstanceOf(XLEParseError);
+ expect(err.message).toMatch(/nested too deeply/);
+ expect(err.line).toBe(1);
+ expect(typeof err.col).toBe('number');
+ });
+
+ it('rejects deep nesting that crosses group boundaries', () => {
+ expect(() =>
+ parseCompact('(' + 'V > '.repeat(2000) + 'C' + ')'),
+ ).toThrow(XLEParseError);
+ });
+
+ it('still parses moderately deep, realistic layouts', () => {
+ expect(parseCompact('V > '.repeat(400) + 'C').roots).toHaveLength(1);
+ });
+
+ it('does not leave stale depth state after a thrown error', () => {
+ try {
+ parseCompact('V > '.repeat(2000) + 'C');
+ } catch {
+ /* expected */
+ }
+ expect(parse('V > C').roots[0].children.map(c => c.name)).toEqual(['C']);
+ });
+});
diff --git a/packages/cli/utils/github.test.mjs b/packages/cli/utils/github.test.mjs
new file mode 100644
index 0000000000..e095ab2497
--- /dev/null
+++ b/packages/cli/utils/github.test.mjs
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Unit tests for `checkGhCli()` — the only export of utils/github.mjs.
+ *
+ * `checkGhCli` shells out to `gh auth status` via `execFileSync`. These tests
+ * mock `node:child_process` so they never depend on `gh` being installed or
+ * authenticated in CI, and assert both the success and failure contracts plus
+ * the exact (non-shell, static-arg) invocation — the property that keeps this
+ * helper injection-free.
+ */
+
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import {checkGhCli} from './github.mjs';
+
+vi.mock('node:child_process', () => ({execFileSync: vi.fn()}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('checkGhCli', () => {
+ it('returns true when `gh auth status` succeeds', () => {
+ vi.mocked(execFileSync).mockReturnValue(Buffer.from(''));
+ expect(checkGhCli()).toBe(true);
+ });
+
+ it('invokes gh with a static, non-shell argument array (no injection surface)', () => {
+ vi.mocked(execFileSync).mockReturnValue(Buffer.from(''));
+ checkGhCli();
+ expect(execFileSync).toHaveBeenCalledTimes(1);
+ expect(execFileSync).toHaveBeenCalledWith('gh', ['auth', 'status'], {
+ stdio: 'ignore',
+ });
+ });
+
+ it('returns false when gh is missing or unauthenticated (throws)', () => {
+ vi.mocked(execFileSync).mockImplementation(() => {
+ throw new Error('command not found: gh');
+ });
+ expect(checkGhCli()).toBe(false);
+ });
+
+ it('swallows a non-zero exit (unauthenticated) and returns false', () => {
+ vi.mocked(execFileSync).mockImplementation(() => {
+ const err = new Error('gh: not logged in');
+ /** @type {any} */ (err).status = 1;
+ throw err;
+ });
+ expect(checkGhCli()).toBe(false);
+ });
+});
diff --git a/packages/cli/utils/path-safety.mjs b/packages/cli/utils/path-safety.mjs
index eea1afa110..eaae1a3ed7 100644
--- a/packages/cli/utils/path-safety.mjs
+++ b/packages/cli/utils/path-safety.mjs
@@ -13,6 +13,7 @@
*/
import * as path from 'node:path';
+import * as fs from 'node:fs';
/**
* Error thrown by path-safety guards. Carries a stable `code`
@@ -58,6 +59,12 @@ export function assertWithin(targetPath, rootDir, options = {}) {
throw new PathSafetyError(`Invalid ${label}: must be a non-empty string`, 'PATH_INVALID');
}
+ // A NUL byte can't be a real path; reject it up front rather than letting it
+ // reach the fs layer (defense in depth, matches sanitizeName).
+ if (targetPath.includes('\0')) {
+ throw new PathSafetyError(`Invalid ${label}: contains a NUL byte`, 'PATH_INVALID');
+ }
+
if (path.isAbsolute(targetPath) && !allowAbsolute) {
throw new PathSafetyError(
`Invalid ${label} "${targetPath}": absolute paths are not allowed. ` +
@@ -80,6 +87,35 @@ export function assertWithin(targetPath, rootDir, options = {}) {
);
}
+ // path.resolve is purely lexical — it does NOT follow symlinks, so a symlink
+ // INSIDE the root that points outside would pass the check above while the
+ // real write lands outside root. Canonicalize the deepest EXISTING ancestor
+ // (the target itself usually doesn't exist yet) and re-check against the
+ // realpath'd root. This closes the symlink-escape hole for every command that
+ // writes through this guard.
+ try {
+ const realRoot = fs.realpathSync(absRoot);
+ let existing = resolved;
+ while (!fs.existsSync(existing)) {
+ const parent = path.dirname(existing);
+ if (parent === existing) break;
+ existing = parent;
+ }
+ const realExisting = fs.realpathSync(existing);
+ const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;
+ if (realExisting !== realRoot && !realExisting.startsWith(realRootWithSep)) {
+ throw new PathSafetyError(
+ `Invalid ${label} "${targetPath}": resolves outside the project root ` +
+ `(${absRoot}) via a symlink. Path traversal is not allowed.`,
+ 'PATH_TRAVERSAL',
+ );
+ }
+ } catch (err) {
+ if (err instanceof PathSafetyError) throw err;
+ // realpath can fail if the root doesn't exist (ENOENT) or on a race; fall
+ // back to the lexical result already validated above rather than crash.
+ }
+
return resolved;
}
diff --git a/packages/cli/utils/path-safety.test.mjs b/packages/cli/utils/path-safety.test.mjs
index eccd257a97..699963f3da 100644
--- a/packages/cli/utils/path-safety.test.mjs
+++ b/packages/cli/utils/path-safety.test.mjs
@@ -135,3 +135,31 @@ describe('isFilePathArg', () => {
expect(isFilePathArg(null)).toBe(false);
});
});
+
+describe('assertWithin — symlink escape (realpath guard)', () => {
+ let root;
+ let outside;
+ beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'aw-root-'));
+ outside = fs.mkdtempSync(path.join(os.tmpdir(), 'aw-out-'));
+ });
+ afterEach(() => {
+ fs.rmSync(root, {recursive: true, force: true});
+ fs.rmSync(outside, {recursive: true, force: true});
+ });
+
+ it('rejects a path that traverses a symlink pointing outside root', () => {
+ fs.symlinkSync(outside, path.join(root, 'link'));
+ // path.resolve is lexical and would pass this; the realpath check must catch it.
+ expect(() => assertWithin('link/evil.txt', root)).toThrow(PathSafetyError);
+ expect(() => assertWithin('link/evil.txt', root)).toThrow(/outside|symlink|traversal/i);
+ });
+
+ it('still accepts a legit non-existent nested path inside root', () => {
+ expect(assertWithin('a/b/c.txt', root)).toBe(path.join(root, 'a', 'b', 'c.txt'));
+ });
+
+ it('rejects a NUL byte in the path', () => {
+ expect(() => assertWithin('a\u0000b', root)).toThrow(PathSafetyError);
+ });
+});