Skip to content

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

TypeScript

refactor(cli): Phase 3 — colocate types + generate the ./api surface from JSDoc (#4512)

Joeyc5444875af90
diff --git a/.changeset/cli-blog-colocate-types.md b/.changeset/cli-blog-colocate-types.md
new file mode 100644
index 0000000000..57245618c7
--- /dev/null
+++ b/.changeset/cli-blog-colocate-types.md
@@ -0,0 +1,15 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[refactor] CLI — the public `@astryxdesign/cli/api` type surface is now generated from the runtime JSDoc, and the injectable logger is consolidated into one `Logger`.
+
+Consumer-visible changes to `@astryxdesign/cli/api` (types only — runtime imports are unchanged):
+
+- **Precise return types.** `component`, `docs`, `blog`, `discover`, `build`, `swizzle`, `upgrade`, `init`, and `themeBuild` previously resolved to `Promise<any>`; they now return their precise `{ type, data }` response unions. Code that leaned on `any` may surface new (correct) type errors.
+- **Response types are now exported by name** — e.g. `ComponentDetailResponse`, `SearchResponse`, `UpgradeRunResponse` — alongside `themeAdd`/`themeList`/`listThemes` and a new shared `logger` value + `Logger` type.
+- **Breaking:** the per-command return-union aliases `ComponentResult`, `DiscoverResult`, `DocsResult`, `HookResult`, and `TemplateResult` are no longer exported. Use `Awaited<ReturnType<typeof component>>` (still works), or import the member response types directly.
+
+Internally, the three divergent loggers (`CliLogger`, `InitLogger`, `ThemeBuildLogger`) collapse into one `Logger`; the logger was never part of the public type surface, so this is transparent to callers.
+
+@josephfarina
diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjs
new file mode 100644
index 0000000000..e30b325f25
--- /dev/null
+++ b/.github/scripts/cli-api-types-verify.mjs
@@ -0,0 +1,150 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Verify the PUBLISHED `@astryxdesign/cli/api` type surface.
+ *
+ * The `./api` declarations (`api/**\/*.d.mts`) are generated from the JSDoc in
+ * `api/**\/*.mjs` at `prepack` — they are NOT committed. This test proves the
+ * surface a consumer actually installs is correct, end to end:
+ *
+ * 1. `pnpm pack` the CLI (fires `prepack` → `sync:api-types`), producing the
+ * exact tarball that would be published.
+ * 2. Extract it into a throwaway `node_modules/@astryxdesign/cli` and assert
+ * `api/index.d.mts` is present. `@astryxdesign/core` is linked as a sibling
+ * so the packed declarations' `../../../core/src` specifiers resolve just
+ * like a real install.
+ * 3. Type-check a representative consumer import against the packed package
+ * with `skipLibCheck` OFF, so a stale, missing, malformed, or internal-
+ * `lib`-leaking surface fails here — before it can ship. The scenario's
+ * tsconfig extends the repo base so lib/target/@types/node are inherited.
+ *
+ * Usage: node .github/scripts/cli-api-types-verify.mjs
+ */
+
+import {execFileSync, spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '../..');
+const CLI_DIR = path.join(ROOT, 'packages/cli');
+const CORE_DIR = path.join(ROOT, 'packages/core');
+// Scratch area inside the repo so the repo tsconfig (lib/target/@types/node) and
+// the workspace's installed typescript are all inherited without any setup.
+const VERIFY_DIR = path.join(CLI_DIR, '.api-verify');
+
+function cleanup() {
+ fs.rmSync(VERIFY_DIR, {recursive: true, force: true});
+}
+function fail(msg, detail) {
+ console.error(`\u2717 ${msg}`);
+ if (detail) console.error(detail);
+ cleanup();
+ process.exit(1);
+}
+process.on('exit', cleanup);
+
+cleanup();
+const nm = path.join(VERIFY_DIR, 'node_modules', '@astryxdesign');
+fs.mkdirSync(nm, {recursive: true});
+
+// 1. Pack (fires prepack → sync:api-types).
+console.log('Packing @astryxdesign/cli (fires prepack \u2192 sync:api-types)...');
+let packed;
+try {
+ const out = execFileSync('pnpm', ['pack', '--pack-destination', VERIFY_DIR], {
+ cwd: CLI_DIR,
+ encoding: 'utf8',
+ });
+ packed = out.trim().split('\n').pop().trim();
+} catch (e) {
+ fail('pnpm pack failed', e.stdout || e.message);
+}
+const tarball = path.isAbsolute(packed) ? packed : path.join(VERIFY_DIR, path.basename(packed));
+if (!fs.existsSync(tarball)) fail(`packed tarball not found at ${tarball}`);
+
+// 2. Extract into node_modules/@astryxdesign/cli; link core as a sibling.
+const pkgDir = path.join(nm, 'cli');
+fs.mkdirSync(pkgDir, {recursive: true});
+execFileSync('tar', ['-xzf', tarball, '-C', pkgDir, '--strip-components=1']);
+if (!fs.existsSync(path.join(pkgDir, 'api', 'index.d.mts'))) {
+ fail('packaged tarball is missing api/index.d.mts \u2014 the ./api types did not ship');
+}
+console.log('\u2713 tarball ships api/index.d.mts');
+fs.symlinkSync(CORE_DIR, path.join(nm, 'core'), 'dir');
+
+// 3. Type-check a representative consumer against the packed types.
+const scenario = `
+import {
+ component, docs, blog, discover, template, hook, search, build, swizzle,
+ upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,
+ themeBuild, themeAdd, themeList, listThemes,
+ validateIntegration, summarizeIssues, logger, AstryxError,
+} from '@astryxdesign/cli/api';
+import type {
+ ComponentOptions, SearchOptions, UpgradeOptions,
+ ComponentDetailResponse, SearchResponse, UpgradeRunResponse, Logger,
+} from '@astryxdesign/cli/api';
+
+async function main() {
+ const r = await component('Button');
+ if (r.type === 'component.detail') { const n: string = r.data.name; void n; }
+ const s: SearchOptions = { limit: 5, type: 'component' };
+ const l: Logger = logger; l.setSilent(false); l.log('x');
+ void ({} as ComponentOptions); void ({} as UpgradeOptions);
+ void ({} as ComponentDetailResponse); void ({} as SearchResponse); void ({} as UpgradeRunResponse);
+ void [docs, blog, discover, template, hook, search, build, swizzle, upgrade, init,
+ doctor, layoutExpand, layoutCheck, layoutGrammar, themeBuild, themeAdd, themeList,
+ listThemes, validateIntegration, summarizeIssues, AstryxError, s];
+}
+void main;
+export {};
+`;
+fs.writeFileSync(path.join(VERIFY_DIR, 'scenario.ts'), scenario);
+fs.writeFileSync(
+ path.join(VERIFY_DIR, 'tsconfig.json'),
+ JSON.stringify(
+ {
+ // Inherit the repo's lib/target/@types/node. `bundler` resolution is the
+ // modern default this package targets; skipLibCheck OFF so the packed
+ // declarations are fully checked. `source` condition lets `@astryxdesign/core`
+ // subpaths (e.g. /authoring) resolve from core's src without a build — the
+ // `test` job doesn't build, and src/dist declare identical types (dist is
+ // compiled from src). A published consumer resolves the same types via dist.
+ extends: '../../../tsconfig.json',
+ compilerOptions: {
+ noEmit: true,
+ skipLibCheck: false,
+ module: 'esnext',
+ moduleResolution: 'bundler',
+ customConditions: ['source'],
+ types: ['node'],
+ },
+ files: ['scenario.ts'],
+ },
+ null,
+ 2,
+ ),
+);
+
+const tsc = path.join(ROOT, 'node_modules', '.bin', 'tsc');
+const res = spawnSync(tsc, ['--project', path.join(VERIFY_DIR, 'tsconfig.json')], {
+ cwd: ROOT,
+ encoding: 'utf8',
+});
+if (res.error) fail('failed to run tsc', String(res.error));
+const output = `${res.stdout || ''}\n${res.stderr || ''}`;
+const errors = output.split('\n').filter(line => /error TS/.test(line));
+// Fail closed: a non-zero exit with no parseable diagnostics still means the
+// packaged surface did not cleanly type-check.
+if (res.status !== 0 && errors.length === 0) {
+ fail('tsc exited non-zero while checking the packaged ./api surface', output.trim());
+}
+if (errors.length > 0) {
+ fail('a consumer of the packaged @astryxdesign/cli/api does not type-check', errors.join('\n'));
+}
+
+console.log('\u2713 packaged @astryxdesign/cli/api type-checks for a strict consumer');
+console.log('\nAll ./api type-surface checks passed.');
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b34ed4d685..e12f86f925 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -129,6 +129,10 @@ jobs:
if: needs.check-scope.outputs.docsite_only != 'true'
run: node scripts/sync-exports.js --check
+ - name: Verify the published CLI ./api type surface
+ if: needs.check-scope.outputs.docsite_only != 'true'
+ run: node .github/scripts/cli-api-types-verify.mjs
+
- name: Check token docs are in sync
if: needs.check-scope.outputs.docsite_only != 'true'
run: node scripts/generate-token-docs.mjs --check
diff --git a/eslint.config.js b/eslint.config.js
index 78728543cd..171381d4f2 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -70,6 +70,10 @@ export default defineConfig(
"!packages/cli/bin/**/*.mjs",
"**/*.test-violations.tsx",
"apps/example-nextjs/*.js",
+ // Generated declaration files (e.g. the CLI's `./api` type surface emitted
+ // from JSDoc by `sync:api-types` at prepack). Like `**/*.d.ts`, these are
+ // build artifacts — not hand-authored source to lint.
+ "**/*.d.mts",
"**/next-env.d.ts",
"**/.next/**",
"apps/example-nextjs-source/*.js",
diff --git a/package.json b/package.json
index d82e4a6dd0..0b1b059891 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"private": true,
"license": "MIT",
"scripts": {
- "build": "pnpm -F @astryxdesign/build build && pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/lab build && pnpm -F @astryxdesign/charts build && pnpm -F @astryxdesign/vega build && pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build && pnpm bundle:cli-themes",
+ "build": "pnpm -F @astryxdesign/build build && pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/lab build && pnpm -F @astryxdesign/charts build && pnpm -F @astryxdesign/vega build && pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build && pnpm bundle:cli-themes && pnpm -F @astryxdesign/cli sync:api-types",
"bundle:cli-themes": "node scripts/generate-cli-themes.mjs",
"dev": "pnpm -F @astryxdesign/storybook dev",
"test": "vitest run",
diff --git a/packages/cli/.gitignore b/packages/cli/.gitignore
new file mode 100644
index 0000000000..aa07e48713
--- /dev/null
+++ b/packages/cli/.gitignore
@@ -0,0 +1,7 @@
+# Generated ./api type declarations — emitted from the JSDoc in api/**/*.mjs by
+# scripts/sync-api-types.mjs. Not committed (like dist/ in the other packages);
+# regenerated automatically at `prepack` so the published tarball always ships
+# a fresh, in-sync type surface. Run `pnpm sync:api-types` to produce them locally.
+api/**/*.d.mts
+api/*.d.mts
+.api-verify/
diff --git a/packages/cli/CONTRIBUTING.md b/packages/cli/CONTRIBUTING.md
index 7f7e717d0b..1be2d2577f 100644
--- a/packages/cli/CONTRIBUTING.md
+++ b/packages/cli/CONTRIBUTING.md
@@ -52,13 +52,13 @@ packages/cli/
manifest.mjs # CLI-special: reflects the command tree (injects `program`)
utils/ # small pure helpers (package-manager, path-safety, ...)
schemas/ # zod/JSON schemas
- types/ # hand-written .d.ts (see Roadmap: migrating to generated)
- api.d.ts # API function signatures + AstryxError
+ types/ # public type surface
+ *.type.mjs (in api/) # source of truth — colocated JSDoc; ./api regenerates from it
base.d.ts # CLIError, CLIResult<T>, CLIResponse (structural — no central union)
- component.d.ts # ComponentListResponse, ComponentDetailResponse, ...
- build.d.ts # BuildKitResponse, BuildHelpResponse
- swizzle.d.ts # SwizzleListResponse, SwizzleCopyResponse
- ... # one .d.ts per command; index.d.ts is the barrel
+ component.d.ts # re-export barrel: ComponentListResponse, ComponentDetailResponse, ...
+ build.d.ts # re-export barrel: BuildKitResponse, BuildHelpResponse
+ swizzle.d.ts # re-export barrel: SwizzleListResponse, SwizzleCopyResponse
+ ... # one barrel per command; index.d.ts is the ./json barrel
bin/ scripts/ docs/ templates/
```
@@ -219,14 +219,13 @@ packages/cli/templates/{name}/
1. Add the option to the API function in `api/{command}/{command}.mjs`
2. Pass it through from the CLI handler in `cli/commands/{command}.mjs`
-3. Update the types in `types/api.d.ts` (add to the options interface)
-4. If it produces a new response type, add its interface to `types/{command}.d.ts` and reference it from the function's `@returns` (no central union to update)
+3. Add the option to the `{Command}Options` typedef in `api/{command}/{command}.type.mjs` — this JSDoc is the source of truth; the public `./api` type surface regenerates from it via `pnpm sync:api-types`
### Adding a new response type (e.g. `component.detail.variants`)
1. Add the logic in `api/{command}/{command}.mjs` — return `{type: 'component.detail.variants', data: ...}`
-2. Add a TypeScript interface in `types/{command}.d.ts`
-3. Reference it from the function's `@returns` (and the result union in `types/api.d.ts`) — there is no central `CLIAnyResponse` to update
+2. Add a `@typedef` for it in `api/{command}/{command}.type.mjs` (the colocated source of truth)
+3. Reference it from the function's `@returns` — there is no central union to update; the `./api` type surface regenerates from the JSDoc
4. The parity test will auto-detect the new type and verify API=CLI
### Renaming or removing a response type
diff --git a/packages/cli/api/blog/_adapter.mjs b/packages/cli/api/blog/_adapter.mjs
index e73e835fc2..6d0699283e 100644
--- a/packages/cli/api/blog/_adapter.mjs
+++ b/packages/cli/api/blog/_adapter.mjs
@@ -173,10 +173,10 @@ function slugFromLink(link) {
/**
* @param {string} xml
- * @returns {import('../../types/blog').BlogPost[]}
+ * @returns {import('./blog.type.mjs').BlogPost[]}
*/
function parseFeed(xml) {
- /** @type {import('../../types/blog').BlogPost[]} */
+ /** @type {import('./blog.type.mjs').BlogPost[]} */
const items = [];
const re = /<item>([\s\S]*?)<\/item>/g;
let m;
@@ -200,7 +200,7 @@ function parseFeed(xml) {
/**
* Fetch the canonical feed and parse it into posts. Shared by both leaves; the
* envelope's `feedUrl` lets a caller hit the RSS feed directly.
- * @returns {Promise<import('../../types/blog').BlogListData>}
+ * @returns {Promise<import('./blog.type.mjs').BlogListData>}
*/
export async function loadFeed() {
const xml = await fetchText(FEED_URL);
diff --git a/packages/cli/api/blog/blog.mjs b/packages/cli/api/blog/blog.mjs
index 5450e58c10..8340a44936 100644
--- a/packages/cli/api/blog/blog.mjs
+++ b/packages/cli/api/blog/blog.mjs
@@ -28,7 +28,7 @@ import {detail} from './detail/detail.mjs';
* The feed is always the canonical site — there is no user-supplied URL.
*
* @param {string} [slug]
- * @returns {Promise<import('../../types/blog').BlogListResponse | import('../../types/blog').BlogDetailResponse>}
+ * @returns {Promise<import('./blog.type.mjs').BlogListResponse | import('./blog.type.mjs').BlogDetailResponse>}
*/
export async function blog(slug) {
return slug ? detail(slug) : list();
diff --git a/packages/cli/api/blog/blog.type.mjs b/packages/cli/api/blog/blog.type.mjs
new file mode 100644
index 0000000000..0f85e088b4
--- /dev/null
+++ b/packages/cli/api/blog/blog.type.mjs
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `blog` command — the source of truth for its
+ * response/data shapes. The leaves' `@returns` reference these directly
+ * (functions own their types); the public `@astryxdesign/cli/api` surface
+ * re-exports them via types/blog.d.ts, so consumers see the same names.
+ *
+ * @position api — colocated typedefs for api/blog/{blog,list,detail,_adapter}
+ */
+
+/**
+ * A single post as parsed from the canonical RSS feed.
+ * @typedef {object} BlogPost
+ * @property {string} slug
+ * @property {string} title
+ * @property {string} [description]
+ * @property {string} [date]
+ * @property {string} [type]
+ * @property {string[]} [authors]
+ * @property {string} [link]
+ * @property {string | null} [textUrl]
+ */
+
+/**
+ * @typedef {object} BlogListData
+ * @property {string} feedUrl
+ * @property {BlogPost[]} posts
+ */
+
+/**
+ * @typedef {BlogPost & {feedUrl: string, text: string}} BlogDetailData
+ */
+
+/**
+ * `astryx --json blog` (no slug).
+ * @typedef {object} BlogListResponse
+ * @property {'blog.list'} type
+ * @property {BlogListData} data
+ */
+
+/**
+ * `astryx --json blog <slug>`.
+ * @typedef {object} BlogDetailResponse
+ * @property {'blog.detail'} type
+ * @property {BlogDetailData} data
+ */
+
+// Make this a module so the @typedefs above are importable as types via
+// `import('./blog.type.mjs').BlogPost` (and re-exportable from a .d.ts).
+export {};
diff --git a/packages/cli/api/blog/detail/detail.mjs b/packages/cli/api/blog/detail/detail.mjs
index f88797d51d..a1bdb52d69 100644
--- a/packages/cli/api/blog/detail/detail.mjs
+++ b/packages/cli/api/blog/detail/detail.mjs
@@ -20,7 +20,7 @@ import {loadFeed, fetchPostText} from '../_adapter.mjs';
/**
* Read one post identified by slug (case-insensitive) via its .txt alternate.
* @param {string} slug
- * @returns {Promise<import('../../../types/blog').BlogDetailResponse>}
+ * @returns {Promise<import('../blog.type.mjs').BlogDetailResponse>}
*/
export async function detail(slug) {
const {feedUrl, posts} = await loadFeed();
diff --git a/packages/cli/api/blog/list/list.mjs b/packages/cli/api/blog/list/list.mjs
index 39048f872b..76631e4a09 100644
--- a/packages/cli/api/blog/list/list.mjs
+++ b/packages/cli/api/blog/list/list.mjs
@@ -16,7 +16,7 @@ import {loadFeed} from '../_adapter.mjs';
/**
* List posts from the feed.
- * @returns {Promise<import('../../../types/blog').BlogListResponse>}
+ * @returns {Promise<import('../blog.type.mjs').BlogListResponse>}
*/
export async function list() {
const data = await loadFeed();
diff --git a/packages/cli/api/build/build.mjs b/packages/cli/api/build/build.mjs
index 8a728f879d..2f2433dfe2 100644
--- a/packages/cli/api/build/build.mjs
+++ b/packages/cli/api/build/build.mjs
@@ -25,7 +25,7 @@ export {buildHelp, buildKit};
*
* @param {string} [query] what you're building (e.g. "analytics dashboard")
* @param {{cwd?: string, type?: import('../../types/search').SearchDomain, limit?: number}} [options]
- * @returns {Promise<import('../../types/build').BuildHelpResponse | import('../../types/build').BuildKitResponse>}
+ * @returns {Promise<import('./build.type.mjs').BuildHelpResponse | import('./build.type.mjs').BuildKitResponse>}
*/
export async function build(query, options = {}) {
if (!query || !String(query).trim()) {
diff --git a/packages/cli/api/build/build.type.mjs b/packages/cli/api/build/build.type.mjs
new file mode 100644
index 0000000000..d49b40f78b
--- /dev/null
+++ b/packages/cli/api/build/build.type.mjs
@@ -0,0 +1,46 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `build` command — source of truth for the
+ * `build.help` (playbook signal) and `build.kit` (composition kit) JSON
+ * responses. Re-exported by types/build.d.ts.
+ */
+
+/**
+ * xds --json build (no query) — the "how to build a page" playbook signal.
+ *
+ * @typedef {object} BuildHelpResponse
+ * @property {'build.help'} type
+ * @property {object} data
+ * @property {true} data.playbook Always true; marks this envelope as the playbook rather than a result set.
+ */
+
+/**
+ * xds --json build "<idea>" — the composition kit for what you're building.
+ *
+ * Entries are raw `SearchResultEntry` objects (no package-manager-prefixed
+ * command strings — the CLI adds those); `frame`/`foundation` are static
+ * component-name arrays surfaced on every kit.
+ *
+ * @typedef {object} BuildKitResponse
+ * @property {'build.kit'} type
+ * @property {object} data
+ * @property {string} data.query
+ * @property {boolean} data.hasResults False when search returned nothing (renderer shows "No matches").
+ * @property {boolean} data.directMatch True when the top page template is a confident direct match.
+ * @property {import('../../types/search').SearchResultEntry[]} data.pages Closest page templates (≤3).
+ * @property {import('../../types/search').SearchResultEntry[]} data.blocks Drop-in block patterns covering parts of the idea (≤5).
+ * @property {import('../../types/search').SearchResultEntry[]} data.domain Idea-specific components/hooks (≤6), excluding frame/foundation.
+ * @property {string[]} data.frame Always-on page-shell component names.
+ * @property {string[]} data.foundation Always-on layout/typography/action component names.
+ */
+
+/**
+ * Options for `build()`.
+ * @typedef {object} BuildOptions
+ * @property {string} [cwd]
+ * @property {import('../search/search.type.mjs').SearchDomain} [type]
+ * @property {number} [limit]
+ */
+
+export {};
diff --git a/packages/cli/api/build/help/help.mjs b/packages/cli/api/build/help/help.mjs
index 5f6ff3842c..ede1494789 100644
--- a/packages/cli/api/build/help/help.mjs
+++ b/packages/cli/api/build/help/help.mjs
@@ -11,7 +11,7 @@
/**
* The page-building playbook signal (emitted when `build` runs with no query).
*
- * @returns {import('../../../types/build').BuildHelpResponse}
+ * @returns {import('../build.type.mjs').BuildHelpResponse}
*/
export function buildHelp() {
return {type: 'build.help', data: {playbook: true}};
diff --git a/packages/cli/api/build/kit/kit.mjs b/packages/cli/api/build/kit/kit.mjs
index 9880aff4f1..c7449ad8f9 100644
--- a/packages/cli/api/build/kit/kit.mjs
+++ b/packages/cli/api/build/kit/kit.mjs
@@ -40,13 +40,13 @@ const ALWAYS = new Set([...FRAME, ...FOUNDATION]);
*
* @param {string} query what you're building (e.g. "analytics dashboard")
* @param {{cwd?: string, type?: import('../../../types/search').SearchDomain, limit?: number}} [options]
- * @returns {Promise<import('../../../types/build').BuildKitResponse>}
+ * @returns {Promise<import('../build.type.mjs').BuildKitResponse>}
*/
export async function buildKit(query, options = {}) {
const {cwd = process.cwd(), type, limit = 60} = options;
// search()'s JSDoc @returns widens results to object[]; the SearchResponse
- // shape is the contract (api.d.ts). Cast locally rather than tightening the
- // search @returns (a separate follow-up).
+ // shape is the contract (api/search/search.type.mjs). Cast locally rather than
+ // tightening the search @returns (a separate follow-up).
const result = /** @type {import('../../../types/search').SearchResponse} */ (
await search(query, {cwd, type, limit})
);
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index 296dbca1e2..b7d4ee8c6a 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -357,7 +357,7 @@ export function extractProps(docs) {
* @param {{package: string, sourcePath: string|null}} owner
* @param {string} componentName
* @param {string} coreDir
- * @returns {import('../../types/component').ComponentDetailResponse['data']}
+ * @returns {import('./component.type.mjs').ComponentDetailResponse['data']}
*/
export function withOwnership(docs, owner, componentName, coreDir) {
const importSpec =
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index 8cb18fc5da..93b015cd7b 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -34,15 +34,6 @@ import {componentDetailSource} from './detail/source/source.mjs';
import {componentDetailShowcase} from './detail/showcase/showcase.mjs';
import {componentDetailBlocks} from './detail/blocks/blocks.mjs';
-export {
- componentList,
- componentDetail,
- componentDetailProps,
- componentDetailSource,
- componentDetailShowcase,
- componentDetailBlocks,
-};
-
/**
* @param {string} [name]
* @param {object} [options]
@@ -59,12 +50,12 @@ export {
* @param {boolean} [options.zh]
* @param {boolean} [options.dense]
* @returns {Promise<(
- * import('../../types/component').ComponentListResponse
- * | import('../../types/component').ComponentDetailResponse
- * | import('../../types/component').ComponentDetailPropsResponse
- * | import('../../types/component').ComponentDetailSourceResponse
- * | import('../../types/component').ComponentDetailShowcaseResponse
- * | import('../../types/component').ComponentDetailBlocksResponse
+ * import('./component.type.mjs').ComponentListResponse
+ * | import('./component.type.mjs').ComponentDetailResponse
+ * | import('./component.type.mjs').ComponentDetailPropsResponse
+ * | import('./component.type.mjs').ComponentDetailSourceResponse
+ * | import('./component.type.mjs').ComponentDetailShowcaseResponse
+ * | import('./component.type.mjs').ComponentDetailBlocksResponse
* )>}
*/
export async function component(name, options = {}) {
diff --git a/packages/cli/api/component/component.type.mjs b/packages/cli/api/component/component.type.mjs
new file mode 100644
index 0000000000..d7f06750c1
--- /dev/null
+++ b/packages/cli/api/component/component.type.mjs
@@ -0,0 +1,140 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `component` command — source of truth for the
+ * component command's JSON responses. These typedefs describe the `{type, data}`
+ * envelopes emitted by `xds --json component` and returned by the `component()`
+ * API; the `types/component.d.ts` barrel re-exports them for consumers.
+ *
+ * Detail-level contract for list views (brief < compact < full):
+ * --detail brief Names only. Smallest, most scannable. (DEFAULT for --list)
+ * --detail compact Names + 1-line description + import path.
+ * --detail full Full ComponentDoc per entry (props, theming, examples, etc.).
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json component -> component.list (data.detail='names')
+ * xds --json component --list -> component.list (data.detail='names')
+ * xds --json component --category Form -> component.list (filtered)
+ * xds --json component --list --detail compact -> component.list (data.detail='compact')
+ * xds --json component --list --detail full -> component.list (data.detail='full')
+ * xds --json component Button -> component.detail
+ * xds --json component Button --props -> component.detail.props
+ * xds --json component Button --source -> component.detail.source
+ * xds --json component Button --showcase -> component.detail.showcase
+ * xds --json component Button --blocks -> component.detail.blocks
+ * (not found) -> CLIError
+ */
+
+/**
+ * xds --json component [--list] [--category X] [--detail names|compact|full]
+ *
+ * The list view emits ONE `component.list` type across all three detail levels;
+ * the depth is carried in `data.detail` and `data.components` holds the grouped
+ * map whose entry shape depends on that level:
+ * - 'names' -> ComponentListEntry[] (name + owner package)
+ * - 'compact' -> ComponentBriefEntry[] (name + 1-line description + import)
+ * - 'full' -> ComponentDoc[] (full authored doc per entry)
+ * @typedef {object} ComponentListResponse
+ * @property {'component.list'} type
+ * @property {ComponentListData} data
+ */
+
+/**
+ * Detail-tagged payload for `component.list` (discriminated on `detail`).
+ * @typedef {(
+ * | {detail: 'names'; components: Record<string, ComponentListEntry[]>}
+ * | {detail: 'compact'; components: Record<string, ComponentBriefEntry[]>}
+ * | {detail: 'full'; components: Record<string, import('../../../core/src/docs-types').ComponentDoc[]>}
+ * )} ComponentListData
+ */
+
+/**
+ * A single entry in a `component.list` group at `detail: 'names'`. Pre-1.0 the
+ * list moved from bare strings to package-qualified objects so consumers can
+ * disambiguate ownership (core vs. an integration package).
+ * @typedef {object} ComponentListEntry
+ * @property {string} name
+ * @property {string} package - Owner package, e.g. '@astryxdesign/core' or '@acme/astryx-meta'.
+ */
+
+/**
+ * A single entry in a `component.list` group at `detail: 'compact'`.
+ * @typedef {object} ComponentBriefEntry
+ * @property {string} name
+ * @property {string} description
+ * @property {string} import
+ */
+
+/**
+ * xds --json component <name>
+ * @typedef {object} ComponentDetailResponse
+ * @property {'component.detail'} type
+ * @property {import('../../../core/src/docs-types').ComponentDoc & ComponentOwnership} data
+ */
+
+/**
+ * Ownership metadata attached to every `component.detail` payload. Exposes the
+ * owner package, the import specifier, and whether a swizzleable source file is
+ * available — the inputs the integration-component swizzle (a later PR) needs.
+ * @typedef {object} ComponentOwnership
+ * @property {string} package - Owner package, e.g. '@astryxdesign/core' or an integration package name.
+ * @property {string} import - Import specifier for the component (e.g. '@astryxdesign/core/Button').
+ * @property {boolean} sourceAvailable - Whether a component source file exists for `--source` / swizzle.
+ */
+
+/**
+ * xds --json component <name> --props
+ * @typedef {object} ComponentDetailPropsResponse
+ * @property {'component.detail.props'} type
+ * @property {import('../../../core/src/docs-types').PropDoc[]} data
+ */
+
+/**
+ * xds --json component <name> --source
+ * @typedef {object} ComponentDetailSourceResponse
+ * @property {'component.detail.source'} type
+ * @property {{component: string; source: string}} data
+ */
+
+/**
+ * xds --json component <name> --showcase
+ * @typedef {object} ComponentDetailShowcaseResponse
+ * @property {'component.detail.showcase'} type
+ * @property {{component: string; aspectRatio: number; source: string}} data
+ */
+
+/**
+ * xds --json component <name> --blocks
+ * @typedef {object} ComponentDetailBlocksResponse
+ * @property {'component.detail.blocks'} type
+ * @property {{component: string; showcase: BlockEntry | null; examples: BlockEntry[]; related: BlockEntry[]}} data
+ */
+
+/**
+ * @typedef {object} BlockEntry
+ * @property {string} name
+ * @property {string} displayName
+ * @property {string} description
+ * @property {boolean} isShowcase
+ * @property {string} category
+ */
+
+/**
+ * Options for `component()`.
+ * @typedef {object} ComponentOptions
+ * @property {string} [cwd]
+ * @property {boolean} [list]
+ * @property {string} [category]
+ * @property {string} [package] Scope lookup to a specific external package (e.g. '@acme/xds-widgets').
+ * @property {boolean} [props]
+ * @property {boolean} [source]
+ * @property {boolean} [showcase]
+ * @property {boolean} [blocks] List example blocks for the component: showcase, examples, and related.
+ * @property {'full' | 'compact' | 'brief'} [detail]
+ * @property {string} [lang]
+ * @property {boolean} [zh]
+ * @property {boolean} [dense]
+ */
+
+export {};
diff --git a/packages/cli/api/component/detail/blocks/blocks.mjs b/packages/cli/api/component/detail/blocks/blocks.mjs
index 3be14b04c2..67f050afc5 100644
--- a/packages/cli/api/component/detail/blocks/blocks.mjs
+++ b/packages/cli/api/component/detail/blocks/blocks.mjs
@@ -16,7 +16,7 @@ import {findRelatedBlocks} from '../../../template/template.mjs';
* envelope, splitting them into the hero showcase, component-specific examples,
* and broader related blocks.
* @param {string} componentName
- * @returns {Promise<import('../../../../types/component').ComponentDetailBlocksResponse>}
+ * @returns {Promise<import('../../component.type.mjs').ComponentDetailBlocksResponse>}
*/
export async function componentDetailBlocks(componentName) {
const allBlocks = await findRelatedBlocks(componentName);
diff --git a/packages/cli/api/component/detail/detail.mjs b/packages/cli/api/component/detail/detail.mjs
index a2dd34025f..3a4ec3edcb 100644
--- a/packages/cli/api/component/detail/detail.mjs
+++ b/packages/cli/api/component/detail/detail.mjs
@@ -16,7 +16,7 @@ import {withOwnership} from '../_adapter.mjs';
* @param {{package: string, sourcePath: string|null}} owner
* @param {string} componentName - name used for the import specifier
* @param {string} coreDir
- * @returns {import('../../../types/component').ComponentDetailResponse}
+ * @returns {import('../component.type.mjs').ComponentDetailResponse}
*/
export function componentDetail(docs, owner, componentName, coreDir) {
return {type: 'component.detail', data: withOwnership(docs, owner, componentName, coreDir)};
diff --git a/packages/cli/api/component/detail/props/props.mjs b/packages/cli/api/component/detail/props/props.mjs
index eae92f8c0c..817e456da1 100644
--- a/packages/cli/api/component/detail/props/props.mjs
+++ b/packages/cli/api/component/detail/props/props.mjs
@@ -13,7 +13,7 @@ import {extractProps} from '../../_adapter.mjs';
/**
* Project a resolved doc into the `component.detail.props` envelope.
* @param {import('../../_adapter.mjs').LoadedComponentDoc} docs
- * @returns {import('../../../../types/component').ComponentDetailPropsResponse}
+ * @returns {import('../../component.type.mjs').ComponentDetailPropsResponse}
*/
export function componentDetailProps(docs) {
return {type: 'component.detail.props', data: extractProps(docs)};
diff --git a/packages/cli/api/component/detail/showcase/showcase.mjs b/packages/cli/api/component/detail/showcase/showcase.mjs
index a2ecff7069..fcc3a75238 100644
--- a/packages/cli/api/component/detail/showcase/showcase.mjs
+++ b/packages/cli/api/component/detail/showcase/showcase.mjs
@@ -24,7 +24,7 @@ import {findShowcase} from '../../../template/template.mjs';
* @param {string} ctx.name - the caller's original input, used in the error message
* @param {string|null} [ctx.packageScope] - scope block discovery + the error to a package
* @param {boolean} [ctx.resolve] - when false, skip discovery and treat as not found
- * @returns {Promise<import('../../../../types/component').ComponentDetailShowcaseResponse>}
+ * @returns {Promise<import('../../component.type.mjs').ComponentDetailShowcaseResponse>}
*/
export async function componentDetailShowcase(componentName, {cwd, name, packageScope = null, resolve = true}) {
const match = resolve
diff --git a/packages/cli/api/component/detail/source/source.mjs b/packages/cli/api/component/detail/source/source.mjs
index d73348fd01..d496f43ccb 100644
--- a/packages/cli/api/component/detail/source/source.mjs
+++ b/packages/cli/api/component/detail/source/source.mjs
@@ -18,7 +18,7 @@ import {ERROR_CODES} from '../../../../lib/error-codes.mjs';
* @param {string} componentName - bare name, echoed back as `data.component`
* @param {string|null} sourcePath - the resolved source path (null → not found)
* @param {{name: string, notFoundInPackage?: string|null}} ctx - `name` is the caller's original input; `notFoundInPackage` scopes the not-found message to a package
- * @returns {import('../../../../types/component').ComponentDetailSourceResponse}
+ * @returns {import('../../component.type.mjs').ComponentDetailSourceResponse}
*/
export function componentDetailSource(componentName, sourcePath, {name, notFoundInPackage = null}) {
if (!sourcePath) {
diff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjs
index bb87f41cfc..0a79d96985 100644
--- a/packages/cli/api/component/list/list.mjs
+++ b/packages/cli/api/component/list/list.mjs
@@ -25,9 +25,9 @@ import {AstryxError} from '../../error.mjs';
import {loadComponentDoc, loadIntegrationsSafely} from '../_adapter.mjs';
/**
- * @typedef {import('../../../types/component').ComponentListResponse} ComponentListResponse
- * @typedef {import('../../../types/component').ComponentListEntry} ComponentListEntry
- * @typedef {import('../../../types/component').ComponentBriefEntry} ComponentBriefEntry
+ * @typedef {import('../component.type.mjs').ComponentListResponse} ComponentListResponse
+ * @typedef {import('../component.type.mjs').ComponentListEntry} ComponentListEntry
+ * @typedef {import('../component.type.mjs').ComponentBriefEntry} ComponentBriefEntry
*/
/**
diff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjs
index 02c13e3c4b..927e200c4d 100644
--- a/packages/cli/api/discover/_adapter.mjs
+++ b/packages/cli/api/discover/_adapter.mjs
@@ -99,7 +99,7 @@ export async function discoverPackages() {
* by the list and detail leaves so the entry keys (and their order) stay in one
* place.
* @param {ScannedPackage} pkg
- * @returns {import('../../types/discover').DiscoverListEntry}
+ * @returns {import('./discover.type.mjs').DiscoverListEntry}
*/
export function toEntry(pkg) {
return {
@@ -129,7 +129,7 @@ export function findComponent(packages, name) {
* `discover.detail.doc` envelope.
* @param {ComponentResolution} result
* @param {{lang?: string | null, zh?: boolean}} opts
- * @returns {Promise<import('../../types/discover').DiscoverDetailDocResponse['data']>}
+ * @returns {Promise<import('./discover.type.mjs').DiscoverDetailDocResponse['data']>}
*/
export async function loadValidatedDoc(result, {lang, zh}) {
let docs;
diff --git a/packages/cli/api/discover/detail/detail.mjs b/packages/cli/api/discover/detail/detail.mjs
index 8e65e99a53..10b93ca3b1 100644
--- a/packages/cli/api/discover/detail/detail.mjs
+++ b/packages/cli/api/discover/detail/detail.mjs
@@ -18,7 +18,7 @@ import {ERROR_CODES} from '../../../lib/error-codes.mjs';
*
* @param {import('../../../lib/package-scanner.mjs').ScannedPackage[]} packages
* @param {string} query scoped package name, e.g. `@scope/name`
- * @returns {import('../../../types/discover').DiscoverDetailResponse}
+ * @returns {import('../discover.type.mjs').DiscoverDetailResponse}
*/
export function detail(packages, query) {
const pkg = packages.find(p => p.name === query);
diff --git a/packages/cli/api/discover/detail/doc/doc.mjs b/packages/cli/api/discover/detail/doc/doc.mjs
index 7c23ac4b41..14ab2504ac 100644
--- a/packages/cli/api/discover/detail/doc/doc.mjs
+++ b/packages/cli/api/discover/detail/doc/doc.mjs
@@ -24,7 +24,7 @@ import {ERROR_CODES} from '../../../../lib/error-codes.mjs';
*
* @param {import('../../_adapter.mjs').ComponentResolution} result
* @param {{lang?: string | null, zh?: boolean}} opts
- * @returns {Promise<import('../../../../types/discover').DiscoverDetailDocResponse>}
+ * @returns {Promise<import('../../discover.type.mjs').DiscoverDetailDocResponse>}
*/
export async function docFromResult(result, opts) {
return {type: 'discover.detail.doc', data: await loadValidatedDoc(result, opts)};
@@ -40,7 +40,7 @@ export async function docFromResult(result, opts) {
* @param {string} pkgName
* @param {string} compName
* @param {{lang?: string | null, zh?: boolean}} opts
- * @returns {Promise<import('../../../../types/discover').DiscoverDetailDocResponse>}
+ * @returns {Promise<import('../../discover.type.mjs').DiscoverDetailDocResponse>}
*/
export async function doc(packages, pkgName, compName, {lang, zh}) {
const pkg = packages.find(p => p.name === pkgName);
diff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjs
index 53a881e54f..2e1f95640b 100644
--- a/packages/cli/api/discover/discover.mjs
+++ b/packages/cli/api/discover/discover.mjs
@@ -29,10 +29,10 @@ import {search} from './search/search.mjs';
* @param {string} [options.lang]
* @param {boolean} [options.zh]
* @returns {Promise<
- * import('../../types/discover').DiscoverListResponse |
- * import('../../types/discover').DiscoverDetailResponse |
- * import('../../types/discover').DiscoverDetailDocResponse |
- * import('../../types/discover').DiscoverSearchResponse
+ * import('./discover.type.mjs').DiscoverListResponse |
+ * import('./discover.type.mjs').DiscoverDetailResponse |
+ * import('./discover.type.mjs').DiscoverDetailDocResponse |
+ * import('./discover.type.mjs').DiscoverSearchResponse
* >}
*/
export async function discover(query, options = {}) {
diff --git a/packages/cli/api/discover/discover.type.mjs b/packages/cli/api/discover/discover.type.mjs
new file mode 100644
index 0000000000..d28203e1b8
--- /dev/null
+++ b/packages/cli/api/discover/discover.type.mjs
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `discover` command — source of truth for the
+ * discover JSON response shapes. `types/discover.d.ts` re-exports these.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json discover -> discover.list
+ * xds --json discover @scope/name -> discover.detail
+ * xds --json discover @scope/name/Component -> discover.detail.doc
+ * xds --json discover <searchterm> (1 match) -> discover.detail.doc
+ * xds --json discover <searchterm> (N matches) -> discover.search
+ * (not found) -> CLIError
+ */
+
+/**
+ * xds --json discover
+ * @typedef {object} DiscoverListResponse
+ * @property {'discover.list'} type
+ * @property {DiscoverListEntry[]} data
+ * @property {{configured: boolean}} [meta] Present when the list is empty so
+ * callers can distinguish "no packages configured" from "configured but
+ * nothing discovered".
+ */
+
+/**
+ * @typedef {object} DiscoverListEntry
+ * @property {string} name
+ * @property {string} category
+ * @property {string[]} components
+ * @property {string} [version]
+ * @property {string} [description]
+ * @property {string} [displayName]
+ */
+
+/**
+ * xds --json discover @scope/name
+ * @typedef {object} DiscoverDetailResponse
+ * @property {'discover.detail'} type
+ * @property {DiscoverListEntry} data
+ */
+
+/**
+ * xds --json discover @scope/name/Component
+ * @typedef {object} DiscoverDetailDocResponse
+ * @property {'discover.detail.doc'} type
+ * @property {import('../../../core/src/docs-types').ComponentDoc} data
+ */
+
+/**
+ * xds --json discover <searchterm> (multiple matches)
+ * @typedef {object} DiscoverSearchResponse
+ * @property {'discover.search'} type
+ * @property {{query: string, matches: DiscoverSearchEntry[]}} data
+ */
+
+/**
+ * @typedef {object} DiscoverSearchEntry
+ * @property {string} package
+ * @property {string} component
+ */
+
+/**
+ * Options for `discover()`.
+ * @typedef {object} DiscoverOptions
+ * @property {boolean} [components]
+ * @property {string} [lang]
+ * @property {boolean} [zh]
+ */
+
+export {};
diff --git a/packages/cli/api/discover/list/list.mjs b/packages/cli/api/discover/list/list.mjs
index e20ebaee19..9ae1e3d52d 100644
--- a/packages/cli/api/discover/list/list.mjs
+++ b/packages/cli/api/discover/list/list.mjs
@@ -16,7 +16,7 @@ import {toEntry} from '../_adapter.mjs';
*
* @param {import('../../../lib/package-scanner.mjs').ScannedPackage[]} packages
* @param {{configured: boolean}} meta
- * @returns {import('../../../types/discover').DiscoverListResponse}
+ * @returns {import('../discover.type.mjs').DiscoverListResponse}
*/
export function list(packages, {configured}) {
if (packages.length === 0) {
diff --git a/packages/cli/api/discover/search/search.mjs b/packages/cli/api/discover/search/search.mjs
index 27fcfc629a..1e30847274 100644
--- a/packages/cli/api/discover/search/search.mjs
+++ b/packages/cli/api/discover/search/search.mjs
@@ -34,8 +34,8 @@ import {ERROR_CODES} from '../../../lib/error-codes.mjs';
* @param {string} query
* @param {{lang?: string | null, zh?: boolean}} opts
* @returns {Promise<
- * import('../../../types/discover').DiscoverDetailDocResponse |
- * import('../../../types/discover').DiscoverSearchResponse
+ * import('../discover.type.mjs').DiscoverDetailDocResponse |
+ * import('../discover.type.mjs').DiscoverSearchResponse
* >}
*/
export async function search(packages, query, {lang, zh}) {
diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjs
index ab79705e1d..83f7fa68a5 100644
--- a/packages/cli/api/docs/_adapter.mjs
+++ b/packages/cli/api/docs/_adapter.mjs
@@ -37,7 +37,7 @@ export function discoverTopics() {
/**
* @param {string} docPath
* @param {{lang?: string|null}} [opts]
- * @returns {Promise<import('../../types/docs').DocsDetailResponse['data']>}
+ * @returns {Promise<import('./docs.type.mjs').DocsDetailResponse['data']>}
*/
export async function loadReferenceDocs(docPath, {lang} = {}) {
const mod = await import(pathToFileURL(docPath).href);
@@ -108,7 +108,7 @@ export async function loadReferenceDocs(docPath, {lang} = {}) {
* @param {boolean} [options.dense]
* @returns {Promise<{
* topics: Record<string, string>,
- * docsData: import('../../types/docs').DocsDetailResponse['data'],
+ * docsData: import('./docs.type.mjs').DocsDetailResponse['data'],
* }>}
*/
export async function resolveTopicDocs(topic, options = {}) {
diff --git a/packages/cli/api/docs/detail/detail.mjs b/packages/cli/api/docs/detail/detail.mjs
index 2bce94dc25..5836f577c8 100644
--- a/packages/cli/api/docs/detail/detail.mjs
+++ b/packages/cli/api/docs/detail/detail.mjs
@@ -17,9 +17,9 @@ import {resolveTopicDocs} from '../_adapter.mjs';
/**
* Resolve token-ref blocks by inlining the referenced section's table.
* This allows section docs to reference token tables without duplicating data.
- * @param {import('../../../types/docs').DocsDetailResponse['data']} docsData
+ * @param {import('../docs.type.mjs').DocsDetailResponse['data']} docsData
* @param {Record<string, string>} topics
- * @returns {Promise<import('../../../types/docs').DocsDetailResponse['data']>}
+ * @returns {Promise<import('../docs.type.mjs').DocsDetailResponse['data']>}
*/
async function resolveTokenRefs(docsData, topics) {
const resolved = {...docsData, sections: [...docsData.sections]};
@@ -72,7 +72,7 @@ async function resolveTokenRefs(docsData, topics) {
* @param {string} [options.lang]
* @param {boolean} [options.zh]
* @param {boolean} [options.dense]
- * @returns {Promise<import('../../../types/docs').DocsDetailResponse>}
+ * @returns {Promise<import('../docs.type.mjs').DocsDetailResponse>}
*/
export async function detail(topic, options = {}) {
const {topics, docsData} = await resolveTopicDocs(topic, options);
diff --git a/packages/cli/api/docs/detail/section/section.mjs b/packages/cli/api/docs/detail/section/section.mjs
index 3cb47684b7..1fd7120e99 100644
--- a/packages/cli/api/docs/detail/section/section.mjs
+++ b/packages/cli/api/docs/detail/section/section.mjs
@@ -24,7 +24,7 @@ import {resolveTopicDocs} from '../../_adapter.mjs';
* @param {string} [options.lang]
* @param {boolean} [options.zh]
* @param {boolean} [options.dense]
- * @returns {Promise<import('../../../../types/docs').DocsDetailSectionResponse>}
+ * @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}
*/
export async function section(topic, sectionName, options = {}) {
const {docsData} = await resolveTopicDocs(topic, options);
diff --git a/packages/cli/api/docs/docs.mjs b/packages/cli/api/docs/docs.mjs
index eb0abfb620..20606385b6 100644
--- a/packages/cli/api/docs/docs.mjs
+++ b/packages/cli/api/docs/docs.mjs
@@ -30,9 +30,9 @@ export {list, detail, sectionLeaf as section};
* @param {boolean} [options.zh]
* @param {boolean} [options.dense]
* @returns {Promise<
- * import('../../types/docs').DocsListResponse |
- * import('../../types/docs').DocsDetailResponse |
- * import('../../types/docs').DocsDetailSectionResponse
+ * import('./docs.type.mjs').DocsListResponse |
+ * import('./docs.type.mjs').DocsDetailResponse |
+ * import('./docs.type.mjs').DocsDetailSectionResponse
* >}
*/
export async function docs(topic, section, options = {}) {
diff --git a/packages/cli/api/docs/docs.type.mjs b/packages/cli/api/docs/docs.type.mjs
new file mode 100644
index 0000000000..5ef3436f73
--- /dev/null
+++ b/packages/cli/api/docs/docs.type.mjs
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `docs` command — source of truth for the docs
+ * command JSON responses. `types/docs.d.ts` re-exports these.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------
+ * xds --json docs -> docs.list
+ * xds --json docs <topic> -> docs.detail
+ * xds --json docs <topic> <section> -> docs.detail.section
+ * (unknown topic/section) -> CLIError
+ */
+
+/**
+ * xds --json docs
+ * @typedef {object} DocsListResponse
+ * @property {'docs.list'} type
+ * @property {DocsListEntry[]} data
+ */
+
+/**
+ * @typedef {object} DocsListEntry
+ * @property {string} topic
+ * @property {string} description
+ */
+
+/**
+ * xds --json docs <topic>
+ * @typedef {object} DocsDetailResponse
+ * @property {'docs.detail'} type
+ * @property {import('../../../core/src/docs-types').ReferenceDoc} data
+ */
+
+/**
+ * xds --json docs <topic> <section>
+ * @typedef {object} DocsDetailSectionResponse
+ * @property {'docs.detail.section'} type
+ * @property {import('../../../core/src/docs-types').ReferenceSection} data
+ */
+
+/**
+ * Options for `docs()`.
+ * @typedef {object} DocsOptions
+ * @property {string} [lang]
+ * @property {boolean} [zh]
+ * @property {boolean} [dense]
+ */
+
+export {};
diff --git a/packages/cli/api/docs/list/list.mjs b/packages/cli/api/docs/list/list.mjs
index d59ea34413..4728867cce 100644
--- a/packages/cli/api/docs/list/list.mjs
+++ b/packages/cli/api/docs/list/list.mjs
@@ -15,11 +15,11 @@ import {pathToFileURL} from 'node:url';
import {discoverTopics} from '../_adapter.mjs';
/**
- * @returns {Promise<import('../../../types/docs').DocsListResponse>}
+ * @returns {Promise<import('../docs.type.mjs').DocsListResponse>}
*/
export async function list() {
const topics = discoverTopics();
- /** @type {Array<import('../../../types/docs').DocsListEntry>} */
+ /** @type {Array<import('../docs.type.mjs').DocsListEntry>} */
const entries = [];
for (const [name, docPath] of Object.entries(topics)) {
try {
diff --git a/packages/cli/api/doctor/doctor.type.mjs b/packages/cli/api/doctor/doctor.type.mjs
new file mode 100644
index 0000000000..42b895d756
--- /dev/null
+++ b/packages/cli/api/doctor/doctor.type.mjs
@@ -0,0 +1,49 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `doctor` command — source of truth for the
+ * `astryx doctor` JSON response shapes. `types/doctor.d.ts` re-exports these so
+ * the public `./types/doctor` entrypoint (and the types barrel) keep working
+ * unchanged.
+ */
+
+/**
+ * Outcome of a single diagnostic check.
+ * @typedef {'pass' | 'warn' | 'fail' | 'info'} DoctorStatus
+ */
+
+/**
+ * A single diagnostic check result.
+ * @typedef {object} DoctorCheck
+ * @property {string} id - Stable machine-readable id (e.g. 'node-version').
+ * @property {string} label - Human-readable check name.
+ * @property {DoctorStatus} status
+ * @property {string} message - One-line result summary.
+ * @property {string} [fix] - Actionable remediation, present when status is not 'pass'.
+ */
+
+/**
+ * Aggregate counts per status.
+ * @typedef {object} DoctorSummary
+ * @property {number} pass
+ * @property {number} warn
+ * @property {number} fail
+ * @property {number} info
+ */
+
+/**
+ * xds --json doctor
+ * @typedef {object} DoctorResponse
+ * @property {'doctor'} type
+ * @property {object} data
+ * @property {DoctorCheck[]} data.checks
+ * @property {DoctorSummary} data.summary
+ */
+
+/**
+ * Options for `doctor()`.
+ * @typedef {object} DoctorOptions
+ * @property {string} [cwd]
+ */
+
+export {};
diff --git a/packages/cli/api/hook/_adapter.mjs b/packages/cli/api/hook/_adapter.mjs
index 731f92caec..4a650836be 100644
--- a/packages/cli/api/hook/_adapter.mjs
+++ b/packages/cli/api/hook/_adapter.mjs
@@ -42,7 +42,7 @@ export function resolveCoreDir(cwd) {
* @param {string} coreDir
* @param {string} name
* @param {{zh?: boolean, lang?: string|null}} [opts]
- * @returns {Promise<import('../../types/hook').HookDoc>}
+ * @returns {Promise<import('./hook.type.mjs').HookDoc>}
*/
export async function resolveHookDoc(coreDir, name, {zh = false, lang = null} = {}) {
const docPath = findHookDoc(coreDir, name);
diff --git a/packages/cli/api/hook/detail/detail.mjs b/packages/cli/api/hook/detail/detail.mjs
index f5cf1208bb..70be1b6420 100644
--- a/packages/cli/api/hook/detail/detail.mjs
+++ b/packages/cli/api/hook/detail/detail.mjs
@@ -17,7 +17,7 @@ import {resolveCoreDir, resolveHookDoc} from '../_adapter.mjs';
/**
* @param {string} name
* @param {{cwd?: string, zh?: boolean, lang?: string|null}} [options]
- * @returns {Promise<import('../../../types/hook').HookDetailResponse>}
+ * @returns {Promise<import('../hook.type.mjs').HookDetailResponse>}
*/
export async function detail(name, {cwd = process.cwd(), zh = false, lang = null} = {}) {
const coreDir = resolveCoreDir(cwd);
diff --git a/packages/cli/api/hook/detail/params/params.mjs b/packages/cli/api/hook/detail/params/params.mjs
index c9672d0545..6db395e146 100644
--- a/packages/cli/api/hook/detail/params/params.mjs
+++ b/packages/cli/api/hook/detail/params/params.mjs
@@ -17,7 +17,7 @@ import {resolveCoreDir, resolveHookDoc} from '../../_adapter.mjs';
/**
* @param {string} name
* @param {{cwd?: string, zh?: boolean, lang?: string|null}} [options]
- * @returns {Promise<import('../../../../types/hook').HookDetailParamsResponse>}
+ * @returns {Promise<import('../../hook.type.mjs').HookDetailParamsResponse>}
*/
export async function params(name, {cwd = process.cwd(), zh = false, lang = null} = {}) {
const coreDir = resolveCoreDir(cwd);
diff --git a/packages/cli/api/hook/hook.type.mjs b/packages/cli/api/hook/hook.type.mjs
new file mode 100644
index 0000000000..15cd29726a
--- /dev/null
+++ b/packages/cli/api/hook/hook.type.mjs
@@ -0,0 +1,84 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `hook` command — source of truth for its JSON
+ * responses (mirrored by `../../types/hook.d.ts`).
+ *
+ * Detail-level contract for list views (brief < compact < full):
+ * --detail brief Names only. Smallest, most scannable. (DEFAULT for --list)
+ * --detail compact Names + 1-line description + import path.
+ * --detail full Full HookDoc per entry (params, returns, usage, etc.).
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json hook -> hook.list (data.detail='names')
+ * xds --json hook --list -> hook.list (data.detail='names')
+ * xds --json hook --category State -> hook.list (filtered)
+ * xds --json hook --list --detail compact -> hook.list (data.detail='compact')
+ * xds --json hook --list --detail full -> hook.list (data.detail='full')
+ * xds --json hook useMediaQuery -> hook.detail
+ * xds --json hook useMediaQuery --params -> hook.detail.params
+ * (not found) -> CLIError
+ */
+
+// Re-export the authored-doc types from core so the hook leaves reference these
+// colocated aliases here (the leaf @returns reference these rather than reaching
+// into core directly).
+/** @typedef {import('../../../core/src/docs-types').HookDoc} HookDoc */
+/** @typedef {import('../../../core/src/docs-types').HookParamDoc} HookParamDoc */
+
+/**
+ * xds --json hook [--list] [--category X] [--detail names|compact|full]
+ *
+ * The list view emits ONE `hook.list` type across all three detail levels; the
+ * depth is carried in `data.detail` and `data.components` holds the grouped map
+ * whose entry shape depends on that level:
+ * - 'names' -> string[] (hook names only)
+ * - 'compact' -> HookBriefEntry[] (name + 1-line description + import)
+ * - 'full' -> HookDoc[] (full authored doc per entry)
+ *
+ * @typedef {object} HookListResponse
+ * @property {'hook.list'} type
+ * @property {HookListData} data
+ */
+
+/**
+ * Detail-tagged payload for `hook.list` (discriminated on `detail`).
+ * @typedef {{detail: 'names', components: Record<string, string[]>} | {detail: 'compact', components: Record<string, HookBriefEntry[]>} | {detail: 'full', components: Record<string, HookDoc[]>}} HookListData
+ */
+
+/**
+ * A single entry in a `hook.list` group at `detail: 'compact'`.
+ * @typedef {object} HookBriefEntry
+ * @property {string} name
+ * @property {string} description
+ * @property {string} import
+ */
+
+/**
+ * xds --json hook <name>
+ * @typedef {object} HookDetailResponse
+ * @property {'hook.detail'} type
+ * @property {HookDoc} data
+ */
+
+/**
+ * xds --json hook <name> --params
+ * @typedef {object} HookDetailParamsResponse
+ * @property {'hook.detail.params'} type
+ * @property {HookParamDoc[]} data
+ */
+
+/**
+ * Options for `hook()`.
+ * @typedef {object} HookOptions
+ * @property {string} [cwd]
+ * @property {boolean} [list]
+ * @property {string} [category]
+ * @property {boolean} [params]
+ * @property {'full' | 'compact' | 'brief'} [detail]
+ * @property {string} [lang]
+ * @property {boolean} [zh]
+ */
+
+export {};
diff --git a/packages/cli/api/hook/list/list.mjs b/packages/cli/api/hook/list/list.mjs
index f229a7b7cf..070bf0c28b 100644
--- a/packages/cli/api/hook/list/list.mjs
+++ b/packages/cli/api/hook/list/list.mjs
@@ -26,7 +26,7 @@ import {resolveCoreDir} from '../_adapter.mjs';
* @param {'full'|'compact'|'brief'|'names'} [options.detail] - Anything other than 'compact'/'full' renders names only.
* @param {boolean} [options.zh]
* @param {string|null} [options.lang]
- * @returns {Promise<import('../../../types/hook').HookListResponse>}
+ * @returns {Promise<import('../hook.type.mjs').HookListResponse>}
*/
export async function list({cwd = process.cwd(), category, detail = 'names', zh = false, lang = null} = {}) {
const coreDir = resolveCoreDir(cwd);
@@ -45,7 +45,7 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zh
}
if (detail === 'compact') {
- /** @type {import('../../../types/hook').HookBriefEntry[]} */
+ /** @type {import('../hook.type.mjs').HookBriefEntry[]} */
const entries = [];
for (const hookName of match[1]) {
const docPath = findHookDoc(coreDir, hookName);
@@ -68,7 +68,7 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zh
}
if (detail === 'full') {
- /** @type {import('../../../types/hook').HookDoc[]} */
+ /** @type {import('../hook.type.mjs').HookDoc[]} */
const entries = [];
for (const hookName of match[1]) {
const docPath = findHookDoc(coreDir, hookName);
@@ -76,10 +76,10 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zh
try {
entries.push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));
} catch {
- entries.push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));
+ entries.push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));
}
} else {
- entries.push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));
+ entries.push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));
}
}
return {type: 'hook.list', data: {detail: 'full', components: {[match[0]]: entries}}};
@@ -91,7 +91,7 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zh
// All hooks
if (detail === 'compact') {
- /** @type {Record<string, import('../../../types/hook').HookBriefEntry[]>} */
+ /** @type {Record<string, import('../hook.type.mjs').HookBriefEntry[]>} */
const result = {};
for (const [cat, hookNames] of Object.entries(hooks)) {
result[cat] = [];
@@ -117,7 +117,7 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zh
}
if (detail === 'full') {
- /** @type {Record<string, import('../../../types/hook').HookDoc[]>} */
+ /** @type {Record<string, import('../hook.type.mjs').HookDoc[]>} */
const result = {};
for (const [cat, hookNames] of Object.entries(hooks)) {
result[cat] = [];
@@ -127,10 +127,10 @@ export async function list({cwd = process.cwd(), category, detail = 'names', zh
try {
result[cat].push(await loadDocs(docPath, /** @type {{zh?: boolean, dense?: boolean, lang?: string}} */ ({zh, lang})));
} catch {
- result[cat].push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));
+ result[cat].push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));
}
} else {
- result[cat].push(/** @type {import('../../../types/hook').HookDoc} */ ({name: hookName}));
+ result[cat].push(/** @type {import('../hook.type.mjs').HookDoc} */ ({name: hookName}));
}
}
}
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index e3230cb24e..9bf93e6dc2 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -19,6 +19,7 @@
* // { type: 'hook.detail', data: { name: 'useMediaQuery', ... } }
*/
+// ── Functions (runtime) ──────────────────────────────────────────────
export {component} from './component/component.mjs';
export {docs} from './docs/docs.mjs';
export {blog} from './blog/blog.mjs';
@@ -38,3 +39,30 @@ export {
summarizeIssues,
} from './integration/validate-integration.mjs';
export {AstryxError} from './error.mjs';
+// The one shared logger: the `logger` instance side-effecting commands write
+// through, plus its generated `Logger` type. Part of the public surface so an
+// embedder can enable/inspect output.
+export {logger} from './logger.mjs';
+/**
+ * @typedef {import('./logger.mjs').Logger} Logger
+ */
+
+// ── Types (re-exported from each command's colocated `.type.mjs`) ─────
+// Runtime no-ops (the .type.mjs files are `export {}`); tsc carries these
+// through to the generated api/index.d.mts so the public type surface exposes
+// every command's Options + response types by name.
+export * from './component/component.type.mjs';
+export * from './docs/docs.type.mjs';
+export * from './blog/blog.type.mjs';
+export * from './discover/discover.type.mjs';
+export * from './template/template.type.mjs';
+export * from './theme/theme.type.mjs';
+export * from './hook/hook.type.mjs';
+export * from './search/search.type.mjs';
+export * from './build/build.type.mjs';
+export * from './swizzle/swizzle.type.mjs';
+export * from './upgrade/upgrade.type.mjs';
+export * from './init/init.type.mjs';
+export * from './doctor/doctor.type.mjs';
+export * from './layout/layout.type.mjs';
+export * from './integration/validate-integration.type.mjs';
diff --git a/packages/cli/api/init/_adapter.mjs b/packages/cli/api/init/_adapter.mjs
deleted file mode 100644
index 0005ddc131..0000000000
--- a/packages/cli/api/init/_adapter.mjs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file init shared adapter — the plain logger contract shared by init's leaves.
- *
- * Both the `init.run` (run/run.mjs) and `init.remove` (remove/remove.mjs) leaves
- * emit human progress through the SAME injectable logger and default to the SAME
- * silent no-op for programmatic callers. That contract is the only thing the two
- * leaves share — the agent-docs engine itself lives in lib/agent-docs — so it
- * lives here rather than being duplicated per-leaf or forcing a cross-leaf
- * import. The dispatcher/barrel (init.mjs) re-exports `noopInitLogger` so the
- * CLI + tests keep importing it by name.
- *
- * The logger is a PLAIN log/error pair, NOT the clack-style term-log used by
- * upgrade/theme: init's output has always been flat humanLog lines, so a
- * byte-identical CLI needs a plain passthrough, not intro/step/success framing.
- */
-
-/**
- * Plain injectable logger for init's flat output.
- * @typedef {object} InitLogger
- * @property {(m?: string) => void} log stdout line (the CLI maps this to humanLog)
- * @property {(m?: string) => void} error stderr line (the CLI maps this to console.error)
- */
-
-/** Silent logger — the default for programmatic callers. @type {InitLogger} */
-export const noopInitLogger = {log() {}, error() {}};
diff --git a/packages/cli/api/init/init.mjs b/packages/cli/api/init/init.mjs
index 545d93d4da..c18b6b993b 100644
--- a/packages/cli/api/init/init.mjs
+++ b/packages/cli/api/init/init.mjs
@@ -12,26 +12,21 @@
* - `init.remove` (remove/remove.mjs) — the `--remove-agents` path
*
* This module also re-exports the leaf symbols the CLI + tests import by name
- * (`getNextSteps`, `noopInitLogger`) so api/index.mjs, the command handler
+ * (`getNextSteps`) so api/index.mjs, the command handler
* (cli/commands/init.mjs), and the test suite stay unchanged.
*/
import {run} from './run/run.mjs';
import {remove} from './remove/remove.mjs';
-import {noopInitLogger} from './_adapter.mjs';
export {getNextSteps} from './run/run.mjs';
-export {noopInitLogger} from './_adapter.mjs';
/**
* Re-exported types so callers can keep referencing them off the init barrel
- * (e.g. cli/commands/init.mjs uses `import('../../api/init/init.mjs').InitOptions`
- * and `.InitLogger`). The canonical shapes stay central in types/api.d.ts +
- * types/init.d.ts; these aliases just preserve the barrel's original type
- * surface after the split.
- * @typedef {import('../../types/api').InitOptions} InitOptions
- * @typedef {import('./_adapter.mjs').InitLogger} InitLogger
- * @typedef {import('../../types/init').InitRunData} InitRunData
+ * (e.g. cli/commands/init.mjs uses `import('../../api/init/init.mjs').InitOptions`).
+ * The canonical shapes stay colocated in api/init/init.type.mjs.
+ * @typedef {import('./init.type.mjs').InitOptions} InitOptions
+ * @typedef {import('./init.type.mjs').InitRunData} InitRunData
*/
/**
@@ -42,12 +37,12 @@ export {noopInitLogger} from './_adapter.mjs';
* code.
*
* @param {InitOptions} [options]
- * @param {{cwd?: string, logger?: InitLogger}} [ctx]
- * @returns {Promise<import('../../types/init').InitRunResponse | import('../../types/init').InitRemoveResponse>}
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('./init.type.mjs').InitRunResponse | import('./init.type.mjs').InitRemoveResponse>}
*/
-export async function init(options = {}, {cwd = process.cwd(), logger = noopInitLogger} = {}) {
+export async function init(options = {}, {cwd = process.cwd()} = {}) {
if (options.removeAgents) {
- return remove({cwd, logger});
+ return remove({cwd});
}
- return run(options, {cwd, logger});
+ return run(options, {cwd});
}
diff --git a/packages/cli/api/init/init.test.mjs b/packages/cli/api/init/init.test.mjs
index 119dceb25c..eeb017ae5c 100644
--- a/packages/cli/api/init/init.test.mjs
+++ b/packages/cli/api/init/init.test.mjs
@@ -13,6 +13,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import {init, getNextSteps} from './init.mjs';
+import {logger} from '../logger.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
@@ -135,11 +136,19 @@ describe('init() — logger', () => {
expect(err).toEqual([]);
});
- it('emits the install line + full next-steps through the injected logger', async () => {
+ it('emits the install line + full next-steps through the shared logger', async () => {
/** @type {string[]} */
const lines = [];
- const logger = {log: m => lines.push(m ?? ''), error: m => lines.push(`ERR:${m}`)};
- await init({}, {cwd: tmpDir, logger});
+ const logSpy = vi.spyOn(console, 'log').mockImplementation((...a) => lines.push(a.join(' ')));
+ const errSpy = vi.spyOn(console, 'error').mockImplementation((...a) => lines.push(`ERR:${a.join(' ')}`));
+ logger.setSilent(false);
+ try {
+ await init({}, {cwd: tmpDir});
+ } finally {
+ logger.setSilent(true);
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ }
const text = lines.join('\n');
expect(text).toContain('✓ AI agent docs installed → AGENTS.md');
expect(text).toContain(' Next steps:');
diff --git a/packages/cli/api/init/init.type.mjs b/packages/cli/api/init/init.type.mjs
new file mode 100644
index 0000000000..272c1ee2ea
--- /dev/null
+++ b/packages/cli/api/init/init.type.mjs
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `init` command — source of truth for the init
+ * API response receipts and options. Re-exported by types/init.d.ts; the public
+ * `./api` type surface regenerates from this JSDoc.
+ */
+
+/**
+ * @typedef {object} InitRunData
+ * @property {'default' | 'features'} mode `default` (no flags) or `features` (--features/--all).
+ * @property {string[]} features Features that were run, in order.
+ * @property {string[]} docsWritten Agent-doc files written (empty if agents weren't run or install failed).
+ * @property {{kind: 'path-safety' | 'install-failed', message?: string} | null} docsError Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit.
+ * @property {boolean} theme Whether theme guidance was emitted.
+ * @property {'workflow' | 'created' | 'skipped' | null} template Template outcome (`workflow` is the CLI default; `created`/`skipped` are programmatic).
+ * @property {string | null} templatePath Relative output path when `template === 'created'`.
+ * @property {boolean} nextSteps Whether the getting-started "Next steps" were emitted (default mode).
+ */
+
+/**
+ * @typedef {object} InitRunResponse
+ * @property {'init.run'} type
+ * @property {InitRunData} data
+ */
+
+/**
+ * @typedef {object} InitRemoveResponse
+ * @property {'init.remove'} type
+ * @property {{removed: true}} data
+ */
+
+/**
+ * Options for `init()`.
+ * @typedef {object} InitOptions
+ * @property {string} [features] Comma-separated features to install (agents, theme, template).
+ * @property {boolean} [all] Install all features.
+ * @property {boolean} [removeAgents] Remove the managed agent-docs block instead of installing.
+ * @property {string} [agent] Agent preset: claude, cursor, codex, hermes, all.
+ * @property {string | string[]} [agentDocsPath] Explicit agent-docs file path(s).
+ * @property {string} [templateName] Scaffold a named page template (programmatic only; the CLI never sets it).
+ */
+
+export {};
diff --git a/packages/cli/api/init/remove/remove.mjs b/packages/cli/api/init/remove/remove.mjs
index 9d36ba5756..6ffdf0d2a4 100644
--- a/packages/cli/api/init/remove/remove.mjs
+++ b/packages/cli/api/init/remove/remove.mjs
@@ -5,7 +5,7 @@
*
* `remove(ctx)` deletes the managed agent-docs block from every agent-doc file
* and returns an `init.remove` receipt. The removal engine lives in
- * lib/agent-docs; this leaf only wires the cwd + the injected logger.
+ * lib/agent-docs; this leaf only wires the cwd.
*
* Note: removeAgentDocs() still logs its own per-file lines via humanLog
* (shared lib behavior) — so a programmatic remove is not perfectly silent yet.
@@ -13,16 +13,16 @@
*/
import {removeAgentDocs} from '../../../lib/agent-docs/agent-docs.mjs';
-import {noopInitLogger} from '../_adapter.mjs';
+import {logger} from '../../logger.mjs';
/**
* Remove the managed agent-docs block and return an `init.remove` receipt.
- * Progress is emitted through `logger` (silent by default).
+ * Progress is emitted through the shared `logger` (silent by default).
*
- * @param {{cwd?: string, logger?: import('../_adapter.mjs').InitLogger}} [ctx]
- * @returns {Promise<import('../../../types/init').InitRemoveResponse>}
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('../init.type.mjs').InitRemoveResponse>}
*/
-export async function remove({cwd = process.cwd(), logger = noopInitLogger} = {}) {
+export async function remove({cwd = process.cwd()} = {}) {
removeAgentDocs(cwd);
logger.log('✓ AI agent docs removed.');
return {type: 'init.remove', data: {removed: true}};
diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjs
index 6e858e7326..a4724285d8 100644
--- a/packages/cli/api/init/run/run.mjs
+++ b/packages/cli/api/init/run/run.mjs
@@ -9,7 +9,7 @@
* starter template — with NO prompts, so it behaves identically for humans,
* agents, CI, and piped I/O. It performs the side effects and returns an
* `init.run` receipt. Hard errors (unknown feature/template) throw AstryxError
- * with a stable code. Human output is emitted through the injected `logger`
+ * with a stable code. Human output is emitted through the shared `logger`
* (silent by default) so the CLI keeps its exact plain output and a
* programmatic caller stays quiet.
*/
@@ -23,7 +23,7 @@ import {installAgentDocs} from '../../../lib/agent-docs/agent-docs.mjs';
import {listTemplates} from '../../template/template.mjs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../lib/error-codes.mjs';
-import {noopInitLogger} from '../_adapter.mjs';
+import {logger} from '../../logger.mjs';
const VALID_FEATURES = ['agents', 'theme', 'template'];
@@ -63,12 +63,11 @@ export function getNextSteps(invocation) {
* generic retry hint and continues without changing the exit code.
*
* @param {string} cwd
- * @param {import('../../../types/api').InitOptions} options
+ * @param {import('../init.type.mjs').InitOptions} options
* @param {string} invocation
- * @param {import('../_adapter.mjs').InitLogger} logger
- * @param {import('../../../types/init').InitRunData} data
+ * @param {import('../init.type.mjs').InitRunData} data
*/
-function applyAgents(cwd, options, invocation, logger, data) {
+function applyAgents(cwd, options, invocation, data) {
try {
const paths = options.agentDocsPath
? Array.isArray(options.agentDocsPath)
@@ -102,10 +101,9 @@ function applyAgents(cwd, options, invocation, logger, data) {
* @param {string} cwd
* @param {{templateName?: string}} opts
* @param {string} invocation
- * @param {import('../_adapter.mjs').InitLogger} logger
- * @param {import('../../../types/init').InitRunData} data
+ * @param {import('../init.type.mjs').InitRunData} data
*/
-function applyTemplate(cwd, {templateName}, invocation, logger, data) {
+function applyTemplate(cwd, {templateName}, invocation, data) {
const templates = listTemplates();
if (templates.length === 0) {
data.template = 'skipped';
@@ -157,11 +155,11 @@ function applyTemplate(cwd, {templateName}, invocation, logger, data) {
* emitted through `logger` (silent by default); unknown feature or template
* names throw AstryxError with a stable code.
*
- * @param {import('../../../types/api').InitOptions} [options]
- * @param {{cwd?: string, logger?: import('../_adapter.mjs').InitLogger}} [ctx]
- * @returns {Promise<import('../../../types/init').InitRunResponse>}
+ * @param {import('../init.type.mjs').InitOptions} [options]
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('../init.type.mjs').InitRunResponse>}
*/
-export async function run(options = {}, {cwd = process.cwd(), logger = noopInitLogger} = {}) {
+export async function run(options = {}, {cwd = process.cwd()} = {}) {
const invocation = getCliInvocation();
// Non-interactive feature install: --features or --all.
@@ -181,7 +179,7 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopInitL
);
}
- /** @type {import('../../../types/init').InitRunData} */
+ /** @type {import('../init.type.mjs').InitRunData} */
const data = {
mode: 'features',
features,
@@ -193,7 +191,7 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopInitL
nextSteps: false,
};
for (const feature of features) {
- if (feature === 'agents') applyAgents(cwd, options, invocation, logger, data);
+ if (feature === 'agents') applyAgents(cwd, options, invocation, data);
if (feature === 'theme') {
logger.log(
`✓ For a custom theme, run \`${invocation} theme\` (browse) or \`${invocation} theme add <slug>\` (scaffold).`,
@@ -201,7 +199,7 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopInitL
data.theme = true;
}
if (feature === 'template') {
- applyTemplate(cwd, {templateName: options.templateName}, invocation, logger, data);
+ applyTemplate(cwd, {templateName: options.templateName}, invocation, data);
}
}
return {type: 'init.run', data};
@@ -209,7 +207,7 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopInitL
// No flags: TTY-free default — install the AI agent cheat sheet with NO
// prompts, then print the getting-started guidance.
- /** @type {import('../../../types/init').InitRunData} */
+ /** @type {import('../init.type.mjs').InitRunData} */
const data = {
mode: 'default',
features: ['agents'],
@@ -220,7 +218,7 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopInitL
templatePath: null,
nextSteps: true,
};
- applyAgents(cwd, options, invocation, logger, data);
+ applyAgents(cwd, options, invocation, data);
logger.log('');
logger.log(
` Tip: \`${invocation} init --all\` also points you to the theme and page-building workflows.`,
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index d847a0382b..a8fb82c8fa 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -94,7 +94,7 @@ function checkRoots(resolved, issues) {
* Validate the integration's codemods via the landed discovery. Discovery is
* strict (throws on bad export / duplicate id); we convert any throw into an
* `invalid_codemod` error.
- * @param {import('../../lib/integrations.mjs').LoadedIntegration} integration loaded-integration-shaped object
+ * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration loaded-integration-shaped object
* @param {Issue[]} issues
*/
async function checkCodemods(integration, issues) {
@@ -109,7 +109,7 @@ async function checkCodemods(integration, issues) {
/**
* Validate the integration's templates via the landed discovery. Per-template
* problems are reported as `invalid_template` errors.
- * @param {import('../../lib/integrations.mjs').LoadedIntegration} integration loaded-integration-shaped object
+ * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration loaded-integration-shaped object
* @param {Issue[]} issues
*/
async function checkTemplates(integration, issues) {
@@ -133,7 +133,7 @@ async function checkTemplates(integration, issues) {
* `discoverIntegrationComponents` returns ownership records and does not throw
* on a missing same-stem source — it records `sourcePath: null`. We surface
* each such record as an `invalid_component` error.
- * @param {import('../../lib/integrations.mjs').LoadedIntegration} integration loaded-integration-shaped object
+ * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration loaded-integration-shaped object
* @param {Issue[]} issues
*/
async function checkComponents(integration, issues) {
@@ -159,7 +159,7 @@ async function checkComponents(integration, issues) {
/**
* Run every contribution validator against a loaded-integration-shaped object.
- * @param {import('../../lib/integrations.mjs').LoadedIntegration} integration
+ * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration
* @param {Issue[]} issues
*/
async function runContributionChecks(integration, issues) {
@@ -182,7 +182,7 @@ async function runContributionChecks(integration, issues) {
* contribution checks (roots + codemods/templates/components) because those can
* regress independently of the manifest (a deleted directory, a broken template).
*
- * @param {import('../../lib/integrations.mjs').LoadedIntegration} loaded loaded-integration-shaped object
+ * @param {import('./validate-integration.type.mjs').LoadedIntegration} loaded loaded-integration-shaped object
* @returns {Promise<Issue[]>}
*/
export async function validateLoadedIntegration(loaded) {
@@ -362,7 +362,7 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {
*
* @param {string} [pkg] installed package name; omit to validate the cwd package
* @param {{cwd?: string}} [options]
- * @returns {Promise<import('../../types/validate-integration').ValidateIntegrationResponse>}
+ * @returns {Promise<import('./validate-integration.type.mjs').ValidateIntegrationResponse>}
*/
export async function validateIntegration(pkg, options = {}) {
const {cwd = process.cwd()} = options;
diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjs
new file mode 100644
index 0000000000..9313194cc9
--- /dev/null
+++ b/packages/cli/api/integration/validate-integration.type.mjs
@@ -0,0 +1,39 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `validate-integration` command — source of truth
+ * for its options + response. `AstryxIntegrationIssue` stays shared in
+ * types/integration.d.ts (it's not command-owned). Re-exported by
+ * types/validate-integration.d.ts so the public surface resolves the same names.
+ */
+
+/**
+ * A loaded integration manifest — the shape `validateLoadedIntegration` accepts.
+ * Colocated here (rather than referencing the internal `lib/integrations`
+ * module) so the generated public `./api` surface stays self-contained.
+ * @typedef {object} LoadedIntegration
+ * @property {string} name
+ * @property {string} [version]
+ * @property {string} [components]
+ * @property {string} [templates]
+ * @property {string} [codemods]
+ * @property {string} [issuesUrl]
+ * @property {string} __spec
+ * @property {string} __packageDir
+ * @property {string} __manifestFile
+ */
+
+/**
+ * Options for `validateIntegration()`.
+ * @typedef {object} ValidateIntegrationOptions
+ * @property {string} [cwd]
+ */
+
+/**
+ * `astryx --json validate-integration [package]`.
+ * @typedef {object} ValidateIntegrationResponse
+ * @property {'integration.validate'} type
+ * @property {{name: string | null, version: string | null, issues: import('../../types/integration').AstryxIntegrationIssue[]}} data
+ */
+
+export {};
diff --git a/packages/cli/api/layout/check/check.mjs b/packages/cli/api/layout/check/check.mjs
index 5fa0bd7133..901dec6136 100644
--- a/packages/cli/api/layout/check/check.mjs
+++ b/packages/cli/api/layout/check/check.mjs
@@ -20,7 +20,7 @@ import {analyze, formatIssue} from '../_adapter.mjs';
*
* @param {string} expression
* @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]
- * @returns {Promise<import('../../../types/layout').LayoutCheckResponse>}
+ * @returns {Promise<import('../layout.type.mjs').LayoutCheckResponse>}
*/
export async function layoutCheck(expression, options = {}) {
const {form = 'auto', loose = false, cwd = process.cwd()} = options;
diff --git a/packages/cli/api/layout/expand/expand.mjs b/packages/cli/api/layout/expand/expand.mjs
index 16d854db2f..e1bf5d32f0 100644
--- a/packages/cli/api/layout/expand/expand.mjs
+++ b/packages/cli/api/layout/expand/expand.mjs
@@ -93,7 +93,7 @@ function buildBlockModules(doc, blocks) {
* @param {boolean} [options.loose] - downgrade unknown {hints} to TODO warnings
* @param {string} [options.name] - generated component name
* @param {string} [options.cwd]
- * @returns {Promise<import('../../../types/layout').LayoutExpandResponse>}
+ * @returns {Promise<import('../layout.type.mjs').LayoutExpandResponse>}
*/
export async function layoutExpand(expression, options = {}) {
const {targetPath, form = 'auto', loose = false, name, cwd = process.cwd()} = options;
diff --git a/packages/cli/api/layout/grammar/grammar.mjs b/packages/cli/api/layout/grammar/grammar.mjs
index fe8bb17a63..b43951364f 100644
--- a/packages/cli/api/layout/grammar/grammar.mjs
+++ b/packages/cli/api/layout/grammar/grammar.mjs
@@ -9,14 +9,14 @@
* @position api — leaf over lib/xle/registry
*/
-import {buildRegistry, ALIAS_TABLE} from '../../../lib/xle/registry.mjs';
+import {buildRegistry} from '../../../lib/xle/registry.mjs';
/**
* `astryx layout grammar` — the agent cheatsheet, with the alias table
* generated from this branch's registry (never hand-maintained).
*
* @param {{cwd?: string}} [options]
- * @returns {Promise<import('../../../types/layout').LayoutGrammarResponse>}
+ * @returns {Promise<import('../layout.type.mjs').LayoutGrammarResponse>}
*/
export async function layoutGrammar(options = {}) {
const {cwd = process.cwd()} = options;
@@ -84,5 +84,3 @@ ALIASES (full component names always valid; XDS prefix optional)
return {type: 'layout.grammar', data: {text, aliases: Object.fromEntries(registry.aliases)}};
}
-
-export {ALIAS_TABLE};
diff --git a/packages/cli/api/layout/layout.mjs b/packages/cli/api/layout/layout.mjs
index cbc291cead..efcd135624 100644
--- a/packages/cli/api/layout/layout.mjs
+++ b/packages/cli/api/layout/layout.mjs
@@ -14,4 +14,4 @@
export {layoutExpand} from './expand/expand.mjs';
export {layoutCheck} from './check/check.mjs';
-export {layoutGrammar, ALIAS_TABLE} from './grammar/grammar.mjs';
+export {layoutGrammar} from './grammar/grammar.mjs';
diff --git a/packages/cli/api/layout/layout.type.mjs b/packages/cli/api/layout/layout.type.mjs
new file mode 100644
index 0000000000..5644026ec0
--- /dev/null
+++ b/packages/cli/api/layout/layout.type.mjs
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `layout` command — source of truth for its JSON
+ * responses. `astryx layout expand|check|grammar` turn compressed XLE/XLO
+ * expressions into validated XDS TSX (or echo canonical surfaces / a grammar
+ * cheatsheet). The `types/layout.d.ts` barrel re-exports from here.
+ *
+ * Invocation -> type discriminator
+ * -----------------------------------------------------------------
+ * astryx --json layout expand "<expr>" -> layout.expand
+ * astryx --json layout check "<expr>" -> layout.check
+ * astryx --json layout grammar -> layout.grammar
+ */
+
+/**
+ * The input surface an expression was parsed as.
+ * @typedef {'compact' | 'outline' | 'auto'} LayoutForm
+ */
+
+/**
+ * A validation issue with its formatted, human-readable rendering.
+ * @typedef {object} LayoutIssue
+ * @property {number} [line]
+ * @property {number} [col]
+ * @property {string} message
+ * @property {string} formatted
+ * @property {string[]} [suggestions]
+ */
+
+/**
+ * A block referenced by a layout expression and how it was spliced in.
+ * @typedef {object} LayoutBlockReference
+ * @property {string} name
+ * @property {string} mode
+ */
+
+/**
+ * astryx --json layout expand "<expr>" [path]
+ * @typedef {object} LayoutExpandResponse
+ * @property {'layout.expand'} type
+ * @property {object} data
+ * @property {LayoutForm} data.form
+ * @property {string} data.code
+ * @property {string[]} data.componentsUsed
+ * @property {number} data.states Number of useState hooks the expansion scaffolded.
+ * @property {string[]} data.todos
+ * @property {LayoutBlockReference[]} data.blocksReferenced
+ * @property {string[]} data.warnings
+ * @property {string | null} data.written
+ */
+
+/**
+ * astryx --json layout check "<expr>"
+ * @typedef {object} LayoutCheckResponse
+ * @property {'layout.check'} type
+ * @property {object} data
+ * @property {boolean} data.valid
+ * @property {LayoutForm} data.form
+ * @property {LayoutIssue[]} data.errors
+ * @property {string[]} data.warnings
+ * @property {string} data.compact
+ * @property {string} data.outline
+ */
+
+/**
+ * astryx --json layout grammar
+ * @typedef {object} LayoutGrammarResponse
+ * @property {'layout.grammar'} type
+ * @property {object} data
+ * @property {string} data.text
+ * @property {Record<string, string>} data.aliases Alias table (short name -> canonical component), from the registry.
+ */
+
+/**
+ * @typedef {LayoutExpandResponse | LayoutCheckResponse | LayoutGrammarResponse} LayoutResponse
+ */
+
+/**
+ * Options for `layoutExpand()`.
+ * @typedef {object} LayoutExpandOptions
+ * @property {string} [targetPath]
+ * @property {LayoutForm} [form]
+ * @property {boolean} [loose]
+ * @property {string} [name]
+ * @property {string} [cwd]
+ */
+
+/**
+ * Options for `layoutCheck()`.
+ * @typedef {object} LayoutCheckOptions
+ * @property {LayoutForm} [form]
+ * @property {boolean} [loose]
+ * @property {string} [cwd]
+ */
+
+/**
+ * Options for `layoutGrammar()`.
+ * @typedef {object} LayoutGrammarOptions
+ * @property {string} [cwd]
+ */
+
+export {};
diff --git a/packages/cli/api/logger.mjs b/packages/cli/api/logger.mjs
new file mode 100644
index 0000000000..773c5c1938
--- /dev/null
+++ b/packages/cli/api/logger.mjs
@@ -0,0 +1,43 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The one `Logger`. Source of truth: the `Logger` type is generated from
+ * the JSDoc here, and `logger` is the single instance every side-effecting
+ * command (`upgrade`, `init`, `themeBuild`) writes progress through.
+ *
+ * It is silent by default, so a programmatic caller (or `--json` mode) sees
+ * nothing but the returned `{type, data}`. The CLI calls `logger.setSilent(false)`
+ * in human mode to route lines to the terminal: `log` → stdout (via `humanLog`),
+ * `warn`/`error` → stderr. `humanLog` is itself a no-op in `--json` mode, so
+ * machine output can never be corrupted. Any presentation (glyphs, framing) is
+ * baked into the message by the caller — the logger is a dumb sink.
+ *
+ * @typedef {object} Logger
+ * @property {(message?: string) => void} log Progress / result line (stdout).
+ * @property {(message?: string) => void} warn Non-fatal warning line (stderr).
+ * @property {(message?: string) => void} error Failure line (stderr).
+ * @property {boolean} silent Whether output is currently suppressed.
+ * @property {(silent: boolean) => void} setSilent Enable/disable output.
+ */
+
+import {humanLog} from '../lib/json.mjs';
+
+/**
+ * The single logger instance. Silent until the CLI enables output.
+ * @type {Logger}
+ */
+export const logger = {
+ silent: true,
+ setSilent(silent) {
+ this.silent = silent;
+ },
+ log(message) {
+ if (!this.silent) humanLog(message ?? '');
+ },
+ warn(message) {
+ if (!this.silent) console.error(message ?? '');
+ },
+ error(message) {
+ if (!this.silent) console.error(message ?? '');
+ },
+};
diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjs
new file mode 100644
index 0000000000..4a07f5f056
--- /dev/null
+++ b/packages/cli/api/search/search.type.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `search` command — source of truth for the
+ * `astryx search <query>` JSON response shapes. `types/search.d.ts` re-exports
+ * these so the public `./types/search` entrypoint (and the types barrel) keep
+ * working unchanged.
+ */
+
+/**
+ * The domain a search result belongs to.
+ * @typedef {'component' | 'hook' | 'doc' | 'template'} SearchDomain
+ */
+
+/**
+ * A single ranked search result, tagged with its domain.
+ * @typedef {object} SearchResultEntry
+ * @property {SearchDomain} domain - Which content domain this result came from.
+ * @property {string} name - Primary identifier (component/hook name, doc topic, template dir).
+ * @property {number} score - Relevance score (higher is better).
+ * @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).
+ * @property {string} description - One-line description, when available.
+ * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`).
+ * @property {string} [import] - Import path — present for component and hook results.
+ * @property {string} [title] - Doc title — present for doc results.
+ * @property {string} [displayName] - Friendly display name — present for template results.
+ * @property {'page' | 'block'} [kind] - Template kind (`page` | `block`) — present for template results.
+ */
+
+/**
+ * xds --json search <query>
+ * @typedef {object} SearchResponse
+ * @property {'search'} type
+ * @property {object} data
+ * @property {string} data.query
+ * @property {SearchResultEntry[]} data.results
+ */
+
+/**
+ * Options for `search()`.
+ * @typedef {object} SearchOptions
+ * @property {string} [cwd]
+ * @property {SearchDomain} [type]
+ * @property {number} [limit]
+ */
+
+export {};
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index 43ad76ee7d..5eebb0e648 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -139,7 +139,7 @@ function isExcludedFromCopy(file) {
*
* @param {string} component bare or XDS-prefixed component name
* @param {{cwd?: string, output?: string, package?: string, overwrite?: boolean}} [options]
- * @returns {Promise<import('../../../types/swizzle').SwizzleCopyResponse>}
+ * @returns {Promise<import('../swizzle.type.mjs').SwizzleCopyResponse>}
*/
export async function swizzleCopy(component, options = {}) {
const {
@@ -258,7 +258,7 @@ export async function swizzleCopy(component, options = {}) {
);
const feedback = buildFeedback(dirName, owner.issuesUrl);
- /** @type {import('../../../types/swizzle').SwizzleCopyResponse['data']} */
+ /** @type {import('../swizzle.type.mjs').SwizzleCopyResponse['data']} */
const data = {
component: dirName,
package: owner.package,
diff --git a/packages/cli/api/swizzle/list/list.mjs b/packages/cli/api/swizzle/list/list.mjs
index e3d6716f48..d68be19004 100644
--- a/packages/cli/api/swizzle/list/list.mjs
+++ b/packages/cli/api/swizzle/list/list.mjs
@@ -13,7 +13,7 @@ import {resolveCore} from '../_adapter.mjs';
/**
* List swizzlable components discoverable from `cwd`'s @astryxdesign/core.
* @param {string} [cwd]
- * @returns {import('../../../types/swizzle').SwizzleListResponse}
+ * @returns {import('../swizzle.type.mjs').SwizzleListResponse}
*/
export function swizzleList(cwd = process.cwd()) {
const {components} = resolveCore(cwd);
diff --git a/packages/cli/api/swizzle/swizzle.mjs b/packages/cli/api/swizzle/swizzle.mjs
index fa572d8cba..2f9695ffcf 100644
--- a/packages/cli/api/swizzle/swizzle.mjs
+++ b/packages/cli/api/swizzle/swizzle.mjs
@@ -25,7 +25,7 @@ export {rewriteImports};
*
* @param {string} [component] bare or XDS-prefixed component name; omit to list
* @param {{cwd?: string, output?: string, package?: string, list?: boolean, overwrite?: boolean}} [options]
- * @returns {Promise<import('../../types/swizzle').SwizzleListResponse | import('../../types/swizzle').SwizzleCopyResponse>}
+ * @returns {Promise<import('./swizzle.type.mjs').SwizzleListResponse | import('./swizzle.type.mjs').SwizzleCopyResponse>}
*/
export async function swizzle(component, options = {}) {
const {cwd = process.cwd(), list = false} = options;
diff --git a/packages/cli/api/swizzle/swizzle.type.mjs b/packages/cli/api/swizzle/swizzle.type.mjs
new file mode 100644
index 0000000000..2488d176b8
--- /dev/null
+++ b/packages/cli/api/swizzle/swizzle.type.mjs
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `swizzle` command — source of truth for the
+ * `swizzle.list` and `swizzle.copy` JSON responses. Re-exported by
+ * types/swizzle.d.ts.
+ */
+
+/**
+ * xds --json swizzle [--list]
+ *
+ * @typedef {object} SwizzleListResponse
+ * @property {'swizzle.list'} type
+ * @property {string[]} data
+ */
+
+/**
+ * Maintainer feedback note emitted after a successful swizzle.
+ *
+ * @typedef {object} SwizzleFeedback
+ * @property {string} issuesUrl Where to report the gap that led to swizzling.
+ * @property {string} [ghCommand] Ready-to-run `gh issue create` command, when `gh` is available.
+ */
+
+/**
+ * xds --json swizzle <component>
+ *
+ * @typedef {object} SwizzleCopyResponse
+ * @property {'swizzle.copy'} type
+ * @property {object} data
+ * @property {string} data.component
+ * @property {string} data.package Owner package the component source was copied from.
+ * @property {string} data.outputDir
+ * @property {number} data.filesCopied
+ * @property {string[]} data.files
+ * @property {boolean} data.usesStyleX Whether any copied file uses StyleX (requires build-time setup).
+ * @property {SwizzleFeedback} [data.feedback]
+ */
+
+/**
+ * Options for `swizzle()`.
+ * @typedef {object} SwizzleOptions
+ * @property {string} [cwd]
+ * @property {string} [output] Output directory (must resolve inside cwd). Defaults to ./components/astryx.
+ * @property {string} [package] Scope to a specific owning package when a name is ambiguous.
+ * @property {boolean} [list] Force the list response even with a component argument.
+ * @property {boolean} [overwrite] Overwrite existing files instead of erroring.
+ */
+
+export {};
diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs
index f8d7b3e721..8ef53e12d5 100644
--- a/packages/cli/api/template/copy/copy.mjs
+++ b/packages/cli/api/template/copy/copy.mjs
@@ -25,7 +25,7 @@ import {stripTemplateAssetRefs} from '../_adapter.mjs';
* return the `template.copy` receipt.
* @param {import('../_adapter.mjs').DiscoveredTemplate} match
* @param {{targetPath: string, cwd: string}} ctx
- * @returns {import('../../../types/template').TemplateCopyResponse}
+ * @returns {import('../template.type.mjs').TemplateCopyResponse}
*/
export function templateCopy(match, {targetPath, cwd}) {
if (!fs.existsSync(match.filePath)) {
diff --git a/packages/cli/api/template/list/list.mjs b/packages/cli/api/template/list/list.mjs
index 7cfdde1c01..76c29a537e 100644
--- a/packages/cli/api/template/list/list.mjs
+++ b/packages/cli/api/template/list/list.mjs
@@ -15,7 +15,7 @@ import {pkgOf} from '../_adapter.mjs';
* Project a discovered template set into the `template.list` envelope.
* @param {import('../_adapter.mjs').DiscoveredTemplate[]} templates
* @param {{type?: 'page' | 'block', package?: string}} [options]
- * @returns {import('../../../types/template').TemplateListResponse}
+ * @returns {import('../template.type.mjs').TemplateListResponse}
*/
export function templateList(templates, options = {}) {
const {type, package: packageFilter} = options;
diff --git a/packages/cli/api/template/show/show.mjs b/packages/cli/api/template/show/show.mjs
index fcf0862599..7f807ad329 100644
--- a/packages/cli/api/template/show/show.mjs
+++ b/packages/cli/api/template/show/show.mjs
@@ -16,7 +16,7 @@ import {extractComponents} from '../_adapter.mjs';
/**
* Build the `template.show` envelope for an already-resolved template.
* @param {import('../_adapter.mjs').DiscoveredTemplate} match
- * @returns {import('../../../types/template').TemplateShowResponse}
+ * @returns {import('../template.type.mjs').TemplateShowResponse}
*/
export function templateShow(match) {
if (!fs.existsSync(match.filePath)) {
diff --git a/packages/cli/api/template/skeleton/skeleton.mjs b/packages/cli/api/template/skeleton/skeleton.mjs
index cda22739e2..fc35fd68a7 100644
--- a/packages/cli/api/template/skeleton/skeleton.mjs
+++ b/packages/cli/api/template/skeleton/skeleton.mjs
@@ -226,7 +226,7 @@ function extractSkeleton(source) {
* "specify a template name" error the dispatcher's resolution would surface.
* @param {import('../_adapter.mjs').DiscoveredTemplate | undefined} match
* @param {import('../_adapter.mjs').DiscoveredTemplate[]} templates
- * @returns {import('../../../types/template').TemplateSkeletonResponse}
+ * @returns {import('../template.type.mjs').TemplateSkeletonResponse}
*/
export function templateSkeleton(match, templates) {
if (!match) {
diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjs
new file mode 100644
index 0000000000..c417f15164
--- /dev/null
+++ b/packages/cli/api/template/template.type.mjs
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `template` command — source of truth for the
+ * template command JSON responses. Re-exported by `types/template.d.ts`.
+ *
+ * Each template is exactly two files: page.tsx (code) + template.doc.mjs (metadata).
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json template [--list] -> template.list
+ * xds --json template <name> -> template.show
+ * xds --json template <name> --skeleton -> template.skeleton
+ * xds --json template <name> [path] -> template.copy
+ * (unknown template) -> CLIError
+ */
+
+/**
+ * xds --json template [--list]
+ * @typedef {object} TemplateListResponse
+ * @property {'template.list'} type
+ * @property {TemplateListEntry[]} data
+ */
+
+/**
+ * @typedef {object} TemplateListEntry
+ * @property {string} id - Stable template id (relative path under the templates root, minus the .doc.* suffix).
+ * @property {string} name
+ * @property {string} displayName - (deprecated) Alias of `name`, retained for back-compat.
+ * @property {string} description
+ * @property {'page' | 'block'} type
+ * @property {string} package - Owning package; core (built-in) templates report '@astryxdesign/core'.
+ * @property {string} [category] - Optional grouping/category label.
+ * @property {string[]} [componentsUsed] - Component display names the template composes.
+ * @property {boolean} isReady
+ * @property {boolean} [scaffold]
+ */
+
+/**
+ * xds --json template <name>
+ * @typedef {object} TemplateShowResponse
+ * @property {'template.show'} type
+ * @property {object} data
+ * @property {string} data.template
+ * @property {string} data.description
+ * @property {'page' | 'block'} data.type
+ * @property {string[]} data.components
+ * @property {string} data.source
+ */
+
+/**
+ * xds --json template <name> --skeleton
+ * @typedef {object} TemplateSkeletonResponse
+ * @property {'template.skeleton'} type
+ * @property {object} data
+ * @property {string} data.template
+ * @property {string} data.description
+ * @property {string[]} data.components
+ * @property {string} data.skeleton
+ */
+
+/**
+ * xds --json template <name> [path]
+ * @typedef {object} TemplateCopyResponse
+ * @property {'template.copy'} type
+ * @property {object} data
+ * @property {string} data.template
+ * @property {string} data.outputDir
+ * @property {string} data.fileName
+ * @property {number} data.filesCopied
+ */
+
+/**
+ * Options for `template()`.
+ * @typedef {object} TemplateOptions
+ * @property {boolean} [list]
+ * @property {boolean} [skeleton]
+ * @property {boolean} [show]
+ * @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 {string} [cwd]
+ */
+
+export {};
diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjs
index e9ab0e690c..478a38fb60 100644
--- a/packages/cli/api/theme/add/add.mjs
+++ b/packages/cli/api/theme/add/add.mjs
@@ -44,7 +44,7 @@ function defaultTargetDir(slug) {
*
* @param {string} slug
* @param {{targetPath?: string, overwrite?: boolean, cwd?: string}} [options]
- * @returns {Promise<import('../../../types/theme').ThemeAddResponse>}
+ * @returns {Promise<import('../theme.type.mjs').ThemeAddResponse>}
*/
export async function themeAdd(slug, options = {}) {
const {targetPath, overwrite = false, cwd = process.cwd()} = options;
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 42a65da800..e532ba0972 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -13,7 +13,7 @@
*
* It performs the writes and returns a `theme.build` receipt, or `null` when
* the theme produced no CSS (nothing to build). Errors throw AstryxError (with
- * a stable code). Human progress is emitted through the injected `logger`
+ * a stable code). Human progress is emitted through the shared `logger`
* (silent by default), so the CLI keeps its exact output while a programmatic
* caller stays quiet.
*/
@@ -29,6 +29,7 @@ import {
} from '../../../utils/path-safety.mjs';
import {ERROR_CODES} from '../../../lib/error-codes.mjs';
import {AstryxError} from '../../error.mjs';
+import {logger} from '../../logger.mjs';
// Import shared theme processing from core. `astryx theme build` MUST produce the
// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -753,35 +754,19 @@ function validatePrivateVars(themeDef) {
return errors;
}
-/**
- * @typedef {object} ThemeBuildLogger
- * @property {(m?: string) => void} log - stdout (install/receipt lines)
- * @property {(m?: string) => void} warn - stderr (component-override warnings)
- * @property {(m?: string) => void} error - stderr (private-var errors)
- */
-
-/**
- * No-op logger — the default so a programmatic caller stays silent. The CLI
- * injects a real logger (humanLog / console.warn / console.error) in human
- * mode, and this same no-op shape in --json mode so human chatter never
- * corrupts the single JSON envelope.
- * @type {ThemeBuildLogger}
- */
-const noopLogger = {log() {}, warn() {}, error() {}};
-
/**
* Compile a defineTheme file to CSS + JS + .d.ts (and an optional
* `.variants.d.ts`). Performs the writes and returns a `theme.build` receipt,
* or `null` when the theme produced no CSS (nothing to build). Throws
- * AstryxError (stable code) on failure. Progress is emitted through `logger`
- * (silent by default).
+ * AstryxError (stable code) on failure. Progress is emitted through the shared
+ * `logger` (silent by default).
*
* @param {string} file - Theme file path, resolved against `cwd`.
* @param {{out?: string}} [options] - `out` overrides the output CSS path.
- * @param {{cwd?: string, logger?: ThemeBuildLogger}} [ctx]
- * @returns {Promise<import('../../../types/theme').ThemeBuildResponse | null>}
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | null>}
*/
-export async function themeBuild(file, options = {}, {cwd = process.cwd(), logger = noopLogger} = {}) {
+export async function themeBuild(file, options = {}, {cwd = process.cwd()} = {}) {
const filePath = path.resolve(cwd, file);
if (!fs.existsSync(filePath)) {
diff --git a/packages/cli/api/theme/list/list.mjs b/packages/cli/api/theme/list/list.mjs
index 9c7fa77a9a..0c5740d22f 100644
--- a/packages/cli/api/theme/list/list.mjs
+++ b/packages/cli/api/theme/list/list.mjs
@@ -10,7 +10,7 @@ import {listThemes} from '../_adapter.mjs';
/**
* List the themes bundled with this CLI build (the ones `theme add` can
* scaffold). Pure projection of the manifest; no I/O beyond the adapter read.
- * @returns {import('../../../types/theme').ThemeListResponse}
+ * @returns {import('../theme.type.mjs').ThemeListResponse}
*/
export function themeList() {
return {
diff --git a/packages/cli/api/theme/theme.type.mjs b/packages/cli/api/theme/theme.type.mjs
new file mode 100644
index 0000000000..5a079e7f81
--- /dev/null
+++ b/packages/cli/api/theme/theme.type.mjs
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `theme` command — the source of truth for its
+ * build/list/add JSON response shapes. The leaves' `@returns` reference these
+ * directly (functions own their types); the public `@astryxdesign/cli/api`
+ * surface re-exports them via types/theme.d.ts, so consumers see the same names.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json theme build <file> -> theme.build
+ * xds --json theme list -> theme.list
+ * xds --json theme add <slug> -> theme.add
+ * (file not found / parse error) -> CLIError
+ *
+ * @position api — colocated typedefs for api/theme/{theme,build,add,list,_adapter}
+ */
+
+/**
+ * xds --json theme build <file>
+ * @typedef {object} ThemeBuildResponse
+ * @property {'theme.build'} type
+ * @property {{name: string, tokenCount: number, componentCount: number, sizeKB: number, outputs: {css: string, js: string, dts: string, variantsDts?: string}, warnings: string[]}} data
+ */
+
+/**
+ * A single theme entry as surfaced by `theme list`.
+ * @typedef {object} ThemeListEntry
+ * @property {string} slug
+ * @property {string} displayName
+ * @property {string} description
+ * @property {boolean} maintained
+ */
+
+/**
+ * xds --json theme list
+ * @typedef {object} ThemeListResponse
+ * @property {'theme.list'} type
+ * @property {ThemeListEntry[]} data
+ */
+
+/**
+ * xds --json theme add <slug>
+ * @typedef {object} ThemeAddResponse
+ * @property {'theme.add'} type
+ * @property {{slug: string, displayName: string, maintained: boolean, outputDir: string, entry: string, exportName: string, files: string[]}} data
+ */
+
+// Make this a module so the @typedefs above are importable as types via
+// `import('./theme.type.mjs').ThemeBuildResponse` (and re-exportable from a .d.ts).
+export {};
diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjs
index 468a4fff08..d68ae5e874 100644
--- a/packages/cli/api/upgrade/_adapter.mjs
+++ b/packages/cli/api/upgrade/_adapter.mjs
@@ -10,7 +10,7 @@
* codemod runners. Leaves call these helpers and PROJECT the results into their
* one response type; the dispatcher (`upgrade.mjs`) routes.
*
- * Progress is emitted through an injected `logger` (silent by default), so the
+ * Progress is emitted through the shared `logger` (silent by default), so the
* CLI keeps its exact output while a programmatic caller stays quiet.
*/
@@ -31,7 +31,7 @@ import {formatCliCommand} from '../../utils/package-manager.mjs';
import {Project} from '../../lib/project.mjs';
import {loadIntegrations} from '../../lib/integrations.mjs';
import {warnOnIntegrationIssues} from '../../lib/integration-warnings.mjs';
-import {noopLogger} from '../../lib/term-log.mjs';
+import {logger} from '../logger.mjs';
const execFileAsync = promisify(execFile);
@@ -97,9 +97,8 @@ export function uniqueFiles(files) {
* Dry-run PREVIEWS (buildCommand still called, so a throw fails); apply executes.
* @param {import('../../types/config').PostCodemodHook[]} hooks
* @param {{packageDir: string, files: string[], apply: boolean}} context
- * @param {import('../../lib/term-log.mjs').CliLogger} logger
*/
-export async function runPostCodemodHooks(hooks, context, logger) {
+export async function runPostCodemodHooks(hooks, context) {
if (!hooks || hooks.length === 0) return;
const {packageDir, files, apply} = context;
@@ -114,13 +113,13 @@ export async function runPostCodemodHooks(hooks, context, logger) {
const cmd = await hook.buildCommand({packageDir, files});
if (!cmd) {
- logger.info(`Post-codemod hook ${label} produced no command; skipping.`);
+ logger.log(`Post-codemod hook ${label} produced no command; skipping.`);
continue;
}
if (!apply) {
const preview = [cmd.command, ...(cmd.args ?? [])].join(' ');
- logger.info(`Post-codemod hook ${label} (dry run): ${preview}`);
+ logger.log(`Post-codemod hook ${label} (dry run): ${preview}`);
continue;
}
@@ -136,7 +135,7 @@ export async function runPostCodemodHooks(hooks, context, logger) {
env: {...process.env, ...(cmd.options?.env ?? {})},
}),
);
- logger.success(`Post-codemod hook ${label} completed.`);
+ logger.log(`✓ Post-codemod hook ${label} completed.`);
}
}
@@ -145,12 +144,12 @@ export async function runPostCodemodHooks(hooks, context, logger) {
* bump. The block documents the INSTALLED library, so it must be re-synced on
* EVERY upgrade path, including the no-codemods short-circuits (#4168).
*
- * @param {{cwd: string, installedVersion: string, apply: boolean, logger?: import('../../lib/term-log.mjs').CliLogger}} ctx
- * @returns {import('../../types/upgrade').AgentDocsSummary}
+ * @param {{cwd: string, installedVersion: string, apply: boolean}} ctx
+ * @returns {import('./upgrade.type.mjs').AgentDocsSummary}
*/
-export function refreshAgentDocs({cwd, installedVersion, apply, logger = noopLogger}) {
+export function refreshAgentDocs({cwd, installedVersion, apply}) {
const inspection = inspectAgentDocs(cwd, installedVersion);
- /** @type {import('../../types/upgrade').AgentDocsSummary} */
+ /** @type {import('./upgrade.type.mjs').AgentDocsSummary} */
const summary = {
status: inspection.status,
installedVersion,
@@ -192,8 +191,8 @@ export function refreshAgentDocs({cwd, installedVersion, apply, logger = noopLog
summary.files = written;
if (summary.refreshed) {
summary.action = 'refreshed';
- logger.success(
- `Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,
+ logger.log(
+ `✓ Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,
);
} else {
summary.action = 'error';
@@ -242,26 +241,26 @@ export async function getCoreVersionManifests(from, to) {
/**
* Ensure jscodeshift is available before running codemods.
- * @param {{installDeps?: boolean, logger?: import('../../lib/term-log.mjs').CliLogger}} [options]
+ * @param {{installDeps?: boolean}} [options]
* @returns {Promise<boolean>}
*/
-export async function ensureCodemodDeps({installDeps, logger = noopLogger} = {}) {
- return ensureJscodeshift({installDeps, silent: logger === noopLogger});
+export async function ensureCodemodDeps({installDeps} = {}) {
+ return ensureJscodeshift({installDeps, silent: logger.silent});
}
/**
* Run the CORE registry codemods. Runs BEFORE the config is loaded so a core
* CONFIG codemod can repair a config the strict loader would otherwise reject.
* @param {CoreVersionManifest[]} versionManifests
- * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>, logger?: import('../../lib/term-log.mjs').CliLogger}} options
+ * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>}} options
*/
-export async function runCoreCodemods(versionManifests, {apply, path: srcPath, codemod, skipCodemods, logger = noopLogger}) {
+export async function runCoreCodemods(versionManifests, {apply, path: srcPath, codemod, skipCodemods}) {
return runCodemods(versionManifests, {
apply,
path: srcPath,
codemod,
skipCodemods,
- silent: logger === noopLogger,
+ silent: logger.silent,
});
}
@@ -288,12 +287,11 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {
* nudge must not fail the upgrade) and is suppressed for --json/programmatic
* callers (the silent logger).
* @param {Array<import('../../lib/integrations.mjs').LoadedIntegration>} integrations
- * @param {import('../../lib/term-log.mjs').CliLogger} [logger]
* @returns {Promise<void>}
*/
-export async function warnIntegrationIssues(integrations, logger = noopLogger) {
+export async function warnIntegrationIssues(integrations) {
try {
- await warnOnIntegrationIssues(integrations, {json: logger === noopLogger});
+ await warnOnIntegrationIssues(integrations, {json: logger.silent});
} catch {
// Never let the nudge break the upgrade.
}
@@ -333,9 +331,9 @@ export async function selectIntegrationCodemodsFor(integrations, from, to) {
/**
* Run the file-based INTEGRATION codemods (config codemods first, then code).
* @param {Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>} versionGroups
- * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>, logger?: import('../../lib/term-log.mjs').CliLogger}} options
+ * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>}} options
*/
-export async function runIntegrationCodemodsStep(versionGroups, {apply, path: srcPath, codemod, skipCodemods, logger = noopLogger}) {
+export async function runIntegrationCodemodsStep(versionGroups, {apply, path: srcPath, codemod, skipCodemods}) {
const jscodeshift = (await import('jscodeshift')).default;
return runIntegrationCodemods(versionGroups, {
apply,
@@ -343,6 +341,6 @@ export async function runIntegrationCodemodsStep(versionGroups, {apply, path: sr
codemod,
skipCodemods,
jscodeshift,
- silent: logger === noopLogger,
+ silent: logger.silent,
});
}
diff --git a/packages/cli/api/upgrade/list/list.mjs b/packages/cli/api/upgrade/list/list.mjs
index 328921d872..83520a179e 100644
--- a/packages/cli/api/upgrade/list/list.mjs
+++ b/packages/cli/api/upgrade/list/list.mjs
@@ -5,24 +5,23 @@
*
* Projects the registry walk (`_adapter.collectAllCodemods`) into the public
* list entries (name/title/version/optional) and emits the human listing
- * through the injected `logger`. No cwd, no version detection, no side effects.
+ * through the shared `logger`. No cwd, no version detection, no side effects.
*/
import {collectAllCodemods} from '../_adapter.mjs';
-import {noopLogger} from '../../../lib/term-log.mjs';
+import {logger} from '../../logger.mjs';
/**
* List every available codemod (oldest→newest).
- * @param {{logger?: import('../../../lib/term-log.mjs').CliLogger}} [ctx]
- * @returns {Promise<import('../../../types/upgrade').UpgradeListResponse>}
+ * @returns {Promise<import('../upgrade.type.mjs').UpgradeListResponse>}
*/
-export async function list({logger = noopLogger} = {}) {
+export async function list() {
const codemods = await collectAllCodemods();
- logger.step('Available codemods:');
+ logger.log('Available codemods:');
for (const {name, title, pr, optional} of codemods) {
- logger.info(` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`);
+ logger.log(` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`);
}
- logger.outro('Done');
+ logger.log('Done\n');
return {
type: 'upgrade.list',
data: codemods.map(({name, title, version, optional}) => ({name, title, version, optional})),
diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjs
index a5e04e9747..7cc166cf1d 100644
--- a/packages/cli/api/upgrade/run/run.mjs
+++ b/packages/cli/api/upgrade/run/run.mjs
@@ -14,7 +14,7 @@
* otherwise-invalid config) → load config → discover + run INTEGRATION codemods
* → post-codemod hooks. Integration DISCOVERY errors skip that integration;
* EXECUTION errors abort. Errors throw AstryxError (stable code); human progress
- * is emitted through the injected `logger` (silent by default).
+ * is emitted through the shared `logger` (silent by default).
*/
import * as path from 'node:path';
@@ -40,18 +40,18 @@ import {semverGte} from '../../../utils/semver.mjs';
import {getCliInvocation} from '../../../utils/package-manager.mjs';
import {ERROR_CODES} from '../../../lib/error-codes.mjs';
import {AstryxError} from '../../error.mjs';
-import {noopLogger} from '../../../lib/term-log.mjs';
+import {logger} from '../../logger.mjs';
/**
* Run the upgrade pipeline for a validated, non-list invocation. Returns the
* terminal run receipt, or one of the status short-circuits; throws AstryxError
- * on failure. Progress is emitted through `logger` (silent by default).
+ * on failure. Progress is emitted through the shared `logger` (silent by default).
*
* @param {import('../_adapter.mjs').UpgradeOptions} [options]
- * @param {{cwd?: string, logger?: import('../../../lib/term-log.mjs').CliLogger}} [ctx]
- * @returns {Promise<import('../../../types/upgrade').UpgradeStatusResponse | import('../../../types/upgrade').UpgradeRunResponse>}
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('../upgrade.type.mjs').UpgradeStatusResponse | import('../upgrade.type.mjs').UpgradeRunResponse>}
*/
-export async function run(options = {}, {cwd = process.cwd(), logger = noopLogger} = {}) {
+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
@@ -64,20 +64,20 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
if (!installed) {
const msg = `Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun \`${getCliInvocation()} upgrade --from <old-version>\`.`;
logger.error(msg);
- logger.outro('Aborted');
+ logger.log('Aborted\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);
}
const targetVersion = installed.version;
- logger.info(`From version: ${currentVersion}`);
- logger.info(`Installed target: ${targetVersion} (${installed.packageName})`);
+ logger.log(`From version: ${currentVersion}`);
+ logger.log(`Installed target: ${targetVersion} (${installed.packageName})`);
// Sync the managed agent-docs block FIRST — it documents the installed library
// independent of codemods, so refresh on every path (issue #4168).
- const agentDocs = refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false, logger});
+ const agentDocs = refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false});
if (!options.force && semverGte(currentVersion, targetVersion)) {
- return statusUpToDate({from: currentVersion, to: targetVersion, agentDocs}, logger);
+ return statusUpToDate({from: currentVersion, to: targetVersion, agentDocs});
}
const versionManifests = await getCoreVersionManifests(currentVersion, targetVersion);
@@ -104,10 +104,10 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
}
}
- const ready = await ensureCodemodDeps({installDeps: options.installDeps, logger});
+ const ready = await ensureCodemodDeps({installDeps: options.installDeps});
if (!ready) {
const msg = 'jscodeshift is required but could not be installed.';
- logger.outro('Aborted');
+ logger.log('Aborted\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_DEP_MISSING);
}
@@ -118,7 +118,6 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
path: path_,
codemod: options.codemod,
skipCodemods,
- logger,
});
const coreResult = codemodResult && 'totalFilesChanged' in codemodResult ? codemodResult : null;
@@ -145,22 +144,21 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
configCodemods: coreConfigCodemodNames,
agentDocs,
},
- logger,
);
}
// Genuine config error: abort.
logger.error(configErr.message);
- logger.outro('Aborted');
+ logger.log('Aborted\n');
throw new AstryxError(configErr.message, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);
}
if (integrations.length > 0) {
- logger.info(`Integrations: ${integrations.map(i => i.name ?? i.__spec).join(', ')}`);
+ logger.log(`Integrations: ${integrations.map(i => i.name ?? i.__spec).join(', ')}`);
}
// Non-blocking nudge for integration validation issues (suppressed for
// programmatic/--json callers, i.e. the silent logger).
- await warnIntegrationIssues(integrations, logger);
+ await warnIntegrationIssues(integrations);
const integrationVersionGroups = await selectIntegrationCodemodsFor(
integrations,
@@ -179,24 +177,24 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
}
if (versionManifests.length === 0 && !hasIntegrationCodemods) {
- return statusNoCodemods({from: currentVersion, to: targetVersion, agentDocs}, logger);
+ return statusNoCodemods({from: currentVersion, to: targetVersion, agentDocs});
}
if (totalTransforms === 0 && totalOptional === 0) {
const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
logger.error(msg);
- logger.outro('Aborted');
+ logger.log('Aborted\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);
}
if (totalTransforms > 0) {
- logger.step(`${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${apply ? '' : ' (dry run)'}`);
+ logger.log(`${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${apply ? '' : ' (dry run)'}`);
} else {
- logger.step('No automatic codemods to run for this version range.');
+ logger.log('No automatic codemods to run for this version range.');
}
/**
- * @type {{from: string, to: string, codemods: number, integrations: string[], agentDocsRefreshed: boolean, agentDocs: import('../../../types/upgrade').AgentDocsSummary, filesChanged?: number, transformsApplied?: number, errors?: Array<{file: string, codemod: string, error: string}>}}
+ * @type {{from: string, to: string, codemods: number, integrations: string[], agentDocsRefreshed: boolean, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, filesChanged?: number, transformsApplied?: number, errors?: Array<{file: string, codemod: string, error: string}>}}
*/
const receipt = {
from: currentVersion,
@@ -209,13 +207,12 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
let integrationResult = null;
if (hasIntegrationCodemods) {
- logger.step('Applying integration codemods...');
+ logger.log('Applying integration codemods...');
integrationResult = await runIntegrationCodemodsStep(integrationVersionGroups, {
apply,
path: path_,
codemod: options.codemod,
skipCodemods,
- logger,
});
}
@@ -227,12 +224,12 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
if (postCodemodHooks.length > 0 && mergedFilesChanged > 0) {
const files = uniqueFiles(mergedWrittenFiles).map(file => path.relative(cwd, file));
try {
- await runPostCodemodHooks(postCodemodHooks, {packageDir: cwd, files, apply: apply || false}, logger);
+ await runPostCodemodHooks(postCodemodHooks, {packageDir: cwd, files, apply: apply || false});
} catch (err) {
const hookErr = /** @type {Error} */ (err);
const msg = `Post-codemod hook failed: ${hookErr.message}`;
logger.error(msg);
- logger.outro('Upgrade failed');
+ logger.log('Upgrade failed\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
}
}
@@ -243,13 +240,13 @@ export async function run(options = {}, {cwd = process.cwd(), logger = noopLogge
if (receipt.errors?.length > 0) {
const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
- logger.outro('Upgrade failed');
+ logger.log('Upgrade failed\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
}
- logger.outro(apply ? 'Upgrade complete' : 'Dry run complete');
+ logger.log((apply ? 'Upgrade complete' : 'Dry run complete') + '\n');
return {
type: 'upgrade.run',
- data: /** @type {import('../../../types/upgrade').UpgradeRunResponse['data']} */ (/** @type {unknown} */ (receipt)),
+ data: /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ (/** @type {unknown} */ (receipt)),
};
}
diff --git a/packages/cli/api/upgrade/status/status.mjs b/packages/cli/api/upgrade/status/status.mjs
index 312d0cff0f..8796f331b3 100644
--- a/packages/cli/api/upgrade/status/status.mjs
+++ b/packages/cli/api/upgrade/status/status.mjs
@@ -11,35 +11,33 @@
* pending core CONFIG codemod would repair it; preview the fix, don't write.
*
* These builders own the exact human progress lines for their path (emitted via
- * the injected `logger`) and return the `upgrade.status` envelope; the caller
+ * the shared `logger`) and return the `upgrade.status` envelope; the caller
* just returns what they hand back.
*/
import {formatCliCommand} from '../../../utils/package-manager.mjs';
-import {noopLogger} from '../../../lib/term-log.mjs';
+import {logger} from '../../logger.mjs';
/**
* `--from` is at/after the installed target (and no `--force`): nothing to run.
- * @param {{from: string, to: string, agentDocs: import('../../../types/upgrade').AgentDocsSummary}} data
- * @param {import('../../../lib/term-log.mjs').CliLogger} [logger]
- * @returns {import('../../../types/upgrade').UpgradeStatusResponse}
+ * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary}} data
+ * @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusUpToDate({from, to, agentDocs}, logger = noopLogger) {
- logger.success('Already up to date — no codemods to run.');
- logger.info('Use --force to run codemods anyway.');
- logger.outro('Done');
+export function statusUpToDate({from, to, agentDocs}) {
+ logger.log('✓ Already up to date — no codemods to run.');
+ logger.log('Use --force to run codemods anyway.');
+ logger.log('Done\n');
return {type: 'upgrade.status', data: {status: 'up_to_date', from, to, agentDocs}};
}
/**
* No core or integration codemods apply to the requested version range.
- * @param {{from: string, to: string, agentDocs: import('../../../types/upgrade').AgentDocsSummary}} data
- * @param {import('../../../lib/term-log.mjs').CliLogger} [logger]
- * @returns {import('../../../types/upgrade').UpgradeStatusResponse}
+ * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary}} data
+ * @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusNoCodemods({from, to, agentDocs}, logger = noopLogger) {
- logger.success('No codemods available for this version range.');
- logger.outro('Done');
+export function statusNoCodemods({from, to, agentDocs}) {
+ logger.log('✓ No codemods available for this version range.');
+ logger.log('Done\n');
return {type: 'upgrade.status', data: {status: 'no_codemods', from, to, agentDocs}};
}
@@ -47,11 +45,10 @@ export function statusNoCodemods({from, to, agentDocs}, logger = noopLogger) {
* DRY-RUN only: the consumer's astryx.config fails strict validation, but a
* pending core CONFIG codemod previewed a change that would repair it. Preview
* the fix + report the exact `--apply` command; integrations are skipped here.
- * @param {{from: string, to: string, configError: string, configCodemods: string[], agentDocs: import('../../../types/upgrade').AgentDocsSummary}} data
- * @param {import('../../../lib/term-log.mjs').CliLogger} [logger]
- * @returns {import('../../../types/upgrade').UpgradeStatusResponse}
+ * @param {{from: string, to: string, configError: string, configCodemods: string[], agentDocs: import('../upgrade.type.mjs').AgentDocsSummary}} data
+ * @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusConfigFixable({from, to, configError, configCodemods, agentDocs}, logger = noopLogger) {
+export function statusConfigFixable({from, to, configError, configCodemods, agentDocs}) {
const codemodFlags = configCodemods.map(name => `--codemod ${name}`).join(' ');
const suggestedCommand = `astryx upgrade --from ${from} ${codemodFlags} --apply`;
const guidance =
@@ -60,9 +57,9 @@ export function statusConfigFixable({from, to, configError, configCodemods, agen
'writing. Re-run with --apply to apply it, or run just the config codemod(s) ' +
'now:';
logger.warn(guidance);
- logger.info(` ${formatCliCommand(suggestedCommand)}`);
- logger.info('Integrations are skipped in this preview; they will be processed on the --apply run.');
- logger.outro('Dry run complete');
+ logger.log(` ${formatCliCommand(suggestedCommand)}`);
+ logger.log('Integrations are skipped in this preview; they will be processed on the --apply run.');
+ logger.log('Dry run complete\n');
return {
type: 'upgrade.status',
data: {
diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjs
index 1b61d0b6e7..31963c57b8 100644
--- a/packages/cli/api/upgrade/upgrade.mjs
+++ b/packages/cli/api/upgrade/upgrade.mjs
@@ -14,9 +14,9 @@
*
* Shared version-detection + codemod selection/execution I/O lives in
* `_adapter.mjs` (the leaves project its results). Errors throw AstryxError
- * (stable code). Human progress is emitted through the injected `logger`
+ * (stable code). Human progress is emitted through the shared `logger`
* (silent by default), so the CLI keeps its exact output and a programmatic
- * caller stays quiet. `refreshAgentDocs` is re-exported here (unchanged surface).
+ * caller stays quiet.
*/
import {list} from './list/list.mjs';
@@ -25,43 +25,42 @@ import {isValidSemver} from '../../utils/semver.mjs';
import {getCliInvocation} from '../../utils/package-manager.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {AstryxError} from '../error.mjs';
-import {noopLogger} from '../../lib/term-log.mjs';
+import {logger} from '../logger.mjs';
-export {refreshAgentDocs} from './_adapter.mjs';
/**
- * @typedef {import('./_adapter.mjs').UpgradeOptions} UpgradeOptions
+ * @typedef {import('./upgrade.type.mjs').UpgradeOptions} UpgradeOptions
*/
/**
* Run the upgrade pipeline. Validates the invocation, then dispatches to the
* list/status/run leaves. Returns the leaf's receipt; throws AstryxError on
- * failure. Progress is emitted through `logger` (silent by default).
+ * failure. Progress is emitted through the shared `logger` (silent by default).
*
* @param {UpgradeOptions} [options]
- * @param {{cwd?: string, logger?: import('../../lib/term-log.mjs').CliLogger}} [ctx]
- * @returns {Promise<import('../../types/upgrade').UpgradeListResponse | import('../../types/upgrade').UpgradeStatusResponse | import('../../types/upgrade').UpgradeRunResponse>}
+ * @param {{cwd?: string}} [ctx]
+ * @returns {Promise<import('./upgrade.type.mjs').UpgradeListResponse | import('./upgrade.type.mjs').UpgradeStatusResponse | import('./upgrade.type.mjs').UpgradeRunResponse>}
*/
-export async function upgrade(options = {}, {cwd = process.cwd(), logger = noopLogger} = {}) {
- logger.intro('Upgrade');
+export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {
+ logger.log('\nUpgrade');
if (!options.list && !options.from) {
const msg = `Missing required --from. Install the target version first, then run \`${getCliInvocation()} upgrade --from <old-version>\`.`;
logger.error(msg);
- logger.outro('Aborted');
+ logger.log('Aborted\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);
}
if (!options.list && !isValidSemver(options.from)) {
const msg = `Invalid --from value: "${options.from}". Expected a semver string like 0.0.5.`;
logger.error(msg);
- logger.outro('Aborted');
+ logger.log('Aborted\n');
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);
}
if (options.list) {
- return list({logger});
+ return list();
}
- return run(options, {cwd, logger});
+ return run(options, {cwd});
}
diff --git a/packages/cli/api/upgrade/upgrade.test.mjs b/packages/cli/api/upgrade/upgrade.test.mjs
index 27869d6adc..5302951138 100644
--- a/packages/cli/api/upgrade/upgrade.test.mjs
+++ b/packages/cli/api/upgrade/upgrade.test.mjs
@@ -15,6 +15,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import {upgrade} from './upgrade.mjs';
+import {logger} from '../logger.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {generateCompressedIndex} from '../../lib/agent-docs/agent-docs.mjs';
@@ -33,6 +34,7 @@ afterEach(() => {
process.chdir(originalCwd);
fs.rmSync(tmpDir, {recursive: true, force: true});
vi.restoreAllMocks();
+ logger.setSilent(true);
});
function writePkg(dir, deps = {}) {
@@ -135,20 +137,17 @@ describe('upgrade() — honors cwd for codemod scanning (no chdir)', () => {
fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
fs.writeFileSync(path.join(tmpDir, 'src', 'index.ts'), 'const x = 1;\n');
- // Capture stdout: the runner logs the directory it scans. A non-noop logger
- // (distinct object from the module's noopLogger) keeps the runner non-silent.
+ // Capture stdout: the runner logs the directory it scans. Enabling the
+ // shared logger keeps the runner non-silent so its scan line is emitted.
const out = [];
vi.spyOn(console, 'log').mockImplementation((...a) => out.push(a.join(' ')));
vi.spyOn(process.stdout, 'write').mockImplementation(c => {
out.push(typeof c === 'string' ? c : c.toString());
return true;
});
- const noop = () => {};
- const logger = {
- intro: noop, step: noop, info: noop, warn: noop, success: noop, error: noop, outro: noop,
- };
+ logger.setSilent(false);
- const res = await upgrade({from: '0.0.1', apply: false, path: 'src'}, {cwd: tmpDir, logger});
+ const res = await upgrade({from: '0.0.1', apply: false, path: 'src'}, {cwd: tmpDir});
const joined = out.join('\n');
expect(res.type).toBe('upgrade.run');
diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjs
new file mode 100644
index 0000000000..8514b7b475
--- /dev/null
+++ b/packages/cli/api/upgrade/upgrade.type.mjs
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for the `upgrade` command — source of truth for the
+ * upgrade command JSON responses. Re-exported by `types/upgrade.d.ts`.
+ *
+ * Invocation -> type discriminator
+ * ------------------------------------------------------------------
+ * xds --json upgrade --list -> upgrade.list
+ * xds --json upgrade [--apply] -> upgrade.run
+ * xds --json upgrade (status short-circuit) -> upgrade.status
+ * (version detection failure) -> CLIError
+ */
+
+/**
+ * xds --json upgrade --list
+ * @typedef {object} UpgradeListResponse
+ * @property {'upgrade.list'} type
+ * @property {UpgradeListEntry[]} data
+ */
+
+/**
+ * @typedef {object} UpgradeListEntry
+ * @property {string} name
+ * @property {string} title
+ * @property {string} version
+ */
+
+/**
+ * State of the managed agent-docs block (`<!-- ASTRYX:START --> … END -->`)
+ * relative to the installed core version, plus what `upgrade` did about it.
+ * Present on every upgrade response (run, status, and the codemod/config error
+ * envelopes) because the block is refreshed independently of codemods.
+ *
+ * - `refreshed` — a stale block was rewritten (`--apply` only).
+ * - `would-refresh` — a stale block was detected in dry-run; nothing written.
+ * - `nudge-init` — no managed block exists; user should run `init`.
+ * - `error` — refresh was attempted but writing failed.
+ * - `none` — nothing to do (block already current).
+ *
+ * @typedef {object} AgentDocsSummary
+ * @property {'missing' | 'stale' | 'current'} status
+ * @property {string} installedVersion Installed core version the block should reflect.
+ * @property {string[]} fromVersions Distinct stale block versions found (the "from" side of the refresh).
+ * @property {string[]} files Files rewritten (apply) or that would be rewritten (dry-run).
+ * @property {boolean} refreshed True only when a block was actually rewritten (apply mode).
+ * @property {'refreshed' | 'would-refresh' | 'nudge-init' | 'error' | 'none'} action
+ */
+
+/**
+ * xds --json upgrade [--apply]
+ * @typedef {object} UpgradeRunResponse
+ * @property {'upgrade.run'} type
+ * @property {object} data
+ * @property {string} data.from
+ * @property {string} data.to
+ * @property {number} data.codemods
+ * @property {string[]} data.integrations Integration packages processed in this upgrade (by name/spec).
+ * @property {boolean} data.agentDocsRefreshed
+ * @property {AgentDocsSummary} data.agentDocs
+ * @property {number} [data.filesChanged] Total files changed across core + integration codemods (apply mode).
+ * @property {number} [data.transformsApplied] Total transforms that reported a change.
+ * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed.
+ */
+
+/**
+ * xds --json upgrade — short-circuit status results.
+ *
+ * - `up_to_date`: `--from` is >= installed target and `--force` was not passed.
+ * - `no_codemods`: no codemods (core or integration) apply to the range.
+ * - `config_fixable`: DRY-RUN ONLY. The consumer's astryx.config currently
+ * fails strict validation, but a pending core CONFIG codemod (in the selected
+ * range) would repair it. The dry run previews the fix without writing and
+ * reports the exact command to apply it; integrations are skipped for the
+ * preview (they will be processed on the `--apply` run).
+ *
+ * @typedef {object} UpgradeStatusResponse
+ * @property {'upgrade.status'} type
+ * @property {{status: 'up_to_date', from: string, to: string, agentDocs: AgentDocsSummary} | {status: 'no_codemods', from: string, to: string, agentDocs: AgentDocsSummary} | {status: 'config_fixable', from: string, to: string, configError: string, configCodemods: string[], suggestedCommand: string, message: string, note: string, agentDocs: AgentDocsSummary}} data
+ */
+
+/**
+ * Options for `upgrade()`.
+ * @typedef {object} UpgradeOptions
+ * @property {string} [from] Version before the dependency bump (required unless `list`).
+ * @property {boolean} [apply] Write changes to disk (default: dry-run).
+ * @property {boolean} [force] Run codemods even if `from` >= installed.
+ * @property {string} [codemod] Run a single named transform.
+ * @property {string[]} [skipCodemod] Exclude named codemods (re-run past a failure).
+ * @property {string[]} [integration] Explicit integration package names / file paths.
+ * @property {string} [path] Source directory to scan (default `./src`).
+ * @property {boolean} [installDeps] Auto-install jscodeshift without prompting.
+ * @property {boolean} [list] Return the available codemods instead of running.
+ */
+
+export {};
diff --git a/packages/cli/cli/commands/build-theme.mjs b/packages/cli/cli/commands/build-theme.mjs
index 098b62172c..8da573465f 100644
--- a/packages/cli/cli/commands/build-theme.mjs
+++ b/packages/cli/cli/commands/build-theme.mjs
@@ -21,6 +21,7 @@ import {fileURLToPath} from 'node:url';
import {spawn} from 'node:child_process';
import {getCliInvocation} from '../../utils/package-manager.mjs';
import {jsonOut, humanLog} from '../../lib/json.mjs';
+import {logger} from '../../api/logger.mjs';
import {cliError} from '../../lib/cli-error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {themeAdd} from '../../api/theme/add/add.mjs';
@@ -183,21 +184,13 @@ export function registerTheme(program) {
return;
}
- // Non-watch: delegate to the API compiler. The logger keeps human output
- // byte-identical — humanLog → stdout, console.warn/error → stderr — while
- // --json mode uses a no-op logger so only the envelope reaches stdout. The
+ // Non-watch: delegate to the API compiler. Enable human output unless in
+ // --json mode (log → stdout via humanLog, warn/error → stderr). The
// "Building theme from" line, the ✓/warning lines, and the install
- // instructions are all emitted from inside themeBuild via this logger.
- /** @type {{log: (m?: string) => void, warn: (m?: string) => void, error: (m?: string) => void}} */
- const logger = json
- ? {log() {}, warn() {}, error() {}}
- : {
- log: humanLog,
- warn: m => console.warn(m),
- error: m => console.error(m),
- };
+ // instructions are all emitted from inside themeBuild via the shared logger.
+ logger.setSilent(json);
try {
- const result = await themeBuild(file, {out: options.out}, {cwd: process.cwd(), logger});
+ const result = await themeBuild(file, {out: options.out}, {cwd: process.cwd()});
if (json && result) jsonOut(result);
} catch (e) {
const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
@@ -210,7 +203,7 @@ export function registerTheme(program) {
.description('List themes available to add')
.action(async () => {
const json = program.opts().json || false;
- /** @type {import('../../types/theme').ThemeListResponse} */
+ /** @type {import('../../api/theme/theme.type.mjs').ThemeListResponse} */
let result;
try {
result = themeList();
@@ -249,7 +242,7 @@ export function registerTheme(program) {
// Existing files require an explicit --overwrite; otherwise themeAdd's
// ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`
// with no slug) is the list affordance — route it to the list leaf.
- /** @type {import('../../types/theme').ThemeListResponse | import('../../types/theme').ThemeAddResponse} */
+ /** @type {import('../../api/theme/theme.type.mjs').ThemeListResponse | import('../../api/theme/theme.type.mjs').ThemeAddResponse} */
let result;
try {
result =
diff --git a/packages/cli/cli/commands/build.mjs b/packages/cli/cli/commands/build.mjs
index afe44c48ff..af6e09073b 100644
--- a/packages/cli/cli/commands/build.mjs
+++ b/packages/cli/cli/commands/build.mjs
@@ -84,10 +84,10 @@ export function registerBuild(program) {
limit = parsed;
}
- /** @type {import('../../types/build').BuildKitResponse} */
+ /** @type {import('../../api/build/build.type.mjs').BuildKitResponse} */
let result;
try {
- result = /** @type {import('../../types/build').BuildKitResponse} */ (
+ result = /** @type {import('../../api/build/build.type.mjs').BuildKitResponse} */ (
await buildApi(query, {cwd: process.cwd(), type: options.type, limit})
);
} catch (e) {
diff --git a/packages/cli/cli/commands/component/index.mjs b/packages/cli/cli/commands/component/index.mjs
index a61028692e..22697e125e 100644
--- a/packages/cli/cli/commands/component/index.mjs
+++ b/packages/cli/cli/commands/component/index.mjs
@@ -33,12 +33,12 @@ import {warnOnIntegrationIssues} from '../../../lib/integration-warnings.mjs';
* src/types/component to get narrowing + typed data.
*
* @typedef {(
- * | import('../../../types/component').ComponentListResponse
- * | import('../../../types/component').ComponentDetailResponse
- * | import('../../../types/component').ComponentDetailPropsResponse
- * | import('../../../types/component').ComponentDetailSourceResponse
- * | import('../../../types/component').ComponentDetailShowcaseResponse
- * | import('../../../types/component').ComponentDetailBlocksResponse
+ * | import('../../../api/component/component.type.mjs').ComponentListResponse
+ * | import('../../../api/component/component.type.mjs').ComponentDetailResponse
+ * | import('../../../api/component/component.type.mjs').ComponentDetailPropsResponse
+ * | import('../../../api/component/component.type.mjs').ComponentDetailSourceResponse
+ * | import('../../../api/component/component.type.mjs').ComponentDetailShowcaseResponse
+ * | import('../../../api/component/component.type.mjs').ComponentDetailBlocksResponse
* )} ComponentResult
*/
@@ -166,7 +166,7 @@ export function registerComponent(program) {
}
/** @param {string} n */
const isCollision = n => (nameCounts.get(n)?.size ?? 0) > 1;
- /** @param {import('../../../types/component').ComponentListEntry} item */
+ /** @param {import('../../../api/component/component.type.mjs').ComponentListEntry} item */
const pkgSuffix = item => {
if (item.package !== CORE_PKG) return ` [${item.package}]`;
if (isCollision(item.name)) return ` [${item.package}]`;
diff --git a/packages/cli/cli/commands/hook/index.mjs b/packages/cli/cli/commands/hook/index.mjs
index 31fe0d5a66..61c9235415 100644
--- a/packages/cli/cli/commands/hook/index.mjs
+++ b/packages/cli/cli/commands/hook/index.mjs
@@ -22,12 +22,12 @@ import {findRelatedBlocks} from '../../../api/template/template.mjs';
/**
* The api layer's hook() widens its return to `{type: string, data: unknown}`,
* so annotate the command-local result with the precise discriminated union from
- * src/types/hook to get narrowing + typed data.
+ * the colocated api/hook/hook.type.mjs to get narrowing + typed data.
*
* @typedef {(
- * | import('../../../types/hook').HookListResponse
- * | import('../../../types/hook').HookDetailResponse
- * | import('../../../types/hook').HookDetailParamsResponse
+ * | import('../../../api/hook/hook.type.mjs').HookListResponse
+ * | import('../../../api/hook/hook.type.mjs').HookDetailResponse
+ * | import('../../../api/hook/hook.type.mjs').HookDetailParamsResponse
* )} HookResult
*/
diff --git a/packages/cli/cli/commands/init.mjs b/packages/cli/cli/commands/init.mjs
index 9830a2755c..186deb9043 100644
--- a/packages/cli/cli/commands/init.mjs
+++ b/packages/cli/cli/commands/init.mjs
@@ -15,7 +15,7 @@
*/
import {init} from '../../api/init/init.mjs';
-import {humanLog} from '../../lib/json.mjs';
+import {logger} from '../../api/logger.mjs';
import {cliError} from '../../lib/cli-error.mjs';
/**
@@ -31,12 +31,12 @@ export function registerInit(program) {
.option('--agent <tool>', 'Target AI tool for agent docs: claude, cursor, codex, hermes, all')
.option('--agent-docs-path <path...>', 'Explicit file path(s) for agent docs')
.action(async (/** @type {import('../../api/init/init.mjs').InitOptions} */ options) => {
- // Plain logger: init's output is flat humanLog lines (stdout) + raw
- // console.error (stderr), never the clack-style term-log.
- /** @type {import('../../api/init/init.mjs').InitLogger} */
- const logger = {log: humanLog, error: m => console.error(m)};
+ // init has no --json mode: enable human output (log → stdout via humanLog,
+ // warn/error → stderr). humanLog still self-suppresses under a global
+ // --json flag, so a JSON envelope can never be corrupted.
+ logger.setSilent(false);
try {
- const receipt = await init(options, {cwd: process.cwd(), logger});
+ const receipt = await init(options, {cwd: process.cwd()});
// A path-safety failure already printed its error but the run
// continued; reflect it in the exit code (historical soft-error policy).
if (receipt.type === 'init.run' && receipt.data.docsError?.kind === 'path-safety') {
diff --git a/packages/cli/cli/commands/layout.mjs b/packages/cli/cli/commands/layout.mjs
index f9b023dccd..f590e33174 100644
--- a/packages/cli/cli/commands/layout.mjs
+++ b/packages/cli/cli/commands/layout.mjs
@@ -20,11 +20,12 @@ import {layoutExpand, layoutCheck, layoutGrammar} from '../../api/layout/layout.
/**
* The api layer's @returns for these functions widen the `type` discriminator
* to `string`, so annotate the command-local result with the precise response
- * shapes from src/types/layout so narrowing + jsonOut typecheck.
+ * shapes from the colocated api/layout/layout.type.mjs so narrowing + jsonOut
+ * typecheck.
*
- * @typedef {import('../../types/layout').LayoutExpandResponse} LayoutExpandResponse
- * @typedef {import('../../types/layout').LayoutCheckResponse} LayoutCheckResponse
- * @typedef {import('../../types/layout').LayoutGrammarResponse} LayoutGrammarResponse
+ * @typedef {import('../../api/layout/layout.type.mjs').LayoutExpandResponse} LayoutExpandResponse
+ * @typedef {import('../../api/layout/layout.type.mjs').LayoutCheckResponse} LayoutCheckResponse
+ * @typedef {import('../../api/layout/layout.type.mjs').LayoutGrammarResponse} LayoutGrammarResponse
*/
/**
diff --git a/packages/cli/cli/commands/search.mjs b/packages/cli/cli/commands/search.mjs
index a1090c337b..d215151f58 100644
--- a/packages/cli/cli/commands/search.mjs
+++ b/packages/cli/cli/commands/search.mjs
@@ -38,7 +38,7 @@ export function registerSearch(program) {
.option('--type <domain>', `Filter to one domain (${SEARCH_DOMAINS.join('|')})`)
.option('--limit <n>', 'Max number of results (default 20)')
.option('--detail', 'Verbose output (include import paths and match reason)')
- .action(async (/** @type {string} */ query, /** @type {{type?: import('../../types/search').SearchDomain, limit?: string, detail?: boolean}} */ options) => {
+ .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;
@@ -51,10 +51,10 @@ export function registerSearch(program) {
limit = parsed;
}
- /** @type {import('../../types/search').SearchResponse} */
+ /** @type {import('../../api/search/search.type.mjs').SearchResponse} */
let result;
try {
- result = /** @type {import('../../types/search').SearchResponse} */ (
+ result = /** @type {import('../../api/search/search.type.mjs').SearchResponse} */ (
await searchApi(query, {
cwd: process.cwd(),
type: options.type,
diff --git a/packages/cli/cli/commands/swizzle.mjs b/packages/cli/cli/commands/swizzle.mjs
index de11802d10..1e894eaf79 100644
--- a/packages/cli/cli/commands/swizzle.mjs
+++ b/packages/cli/cli/commands/swizzle.mjs
@@ -30,7 +30,7 @@ export function registerSwizzle(program) {
const json = program.opts().json || false;
const run = getCliInvocation();
- /** @type {import('../../types/swizzle').SwizzleListResponse | import('../../types/swizzle').SwizzleCopyResponse} */
+ /** @type {import('../../api/swizzle/swizzle.type.mjs').SwizzleListResponse | import('../../api/swizzle/swizzle.type.mjs').SwizzleCopyResponse} */
let result;
try {
result = await swizzleApi(component, {
diff --git a/packages/cli/cli/commands/template.mjs b/packages/cli/cli/commands/template.mjs
index 9faa49ffb4..7c3b41441a 100644
--- a/packages/cli/cli/commands/template.mjs
+++ b/packages/cli/cli/commands/template.mjs
@@ -34,10 +34,10 @@ export {discoverTemplates, listTemplates} from '../../api/template/template.mjs'
* precise union so the switch below type-checks. Replace with the api's own
* return type once it is tightened.
* @typedef {(
- * import('../../types/template').TemplateListResponse |
- * import('../../types/template').TemplateShowResponse |
- * import('../../types/template').TemplateSkeletonResponse |
- * import('../../types/template').TemplateCopyResponse
+ * import('../../api/template/template.type.mjs').TemplateListResponse |
+ * import('../../api/template/template.type.mjs').TemplateShowResponse |
+ * import('../../api/template/template.type.mjs').TemplateSkeletonResponse |
+ * import('../../api/template/template.type.mjs').TemplateCopyResponse
* )} TemplateResponse
*/
@@ -125,7 +125,7 @@ export function registerTemplate(program) {
case 'template.list': {
const pages = result.data.filter(t => t.type === 'page');
const blocks = result.data.filter(t => t.type === 'block');
- /** @param {import('../../types/template').TemplateListEntry} t */
+ /** @param {import('../../api/template/template.type.mjs').TemplateListEntry} t */
const renderEntry = t => {
const status = t.isReady ? '' : ' (WIP)';
const pkg =
diff --git a/packages/cli/cli/commands/upgrade.config-ordering.test.mjs b/packages/cli/cli/commands/upgrade.config-ordering.test.mjs
index 9f18854cca..67a60ff90b 100644
--- a/packages/cli/cli/commands/upgrade.config-ordering.test.mjs
+++ b/packages/cli/cli/commands/upgrade.config-ordering.test.mjs
@@ -44,7 +44,9 @@ beforeEach(() => {
stdoutCalls = [];
exitCode = undefined;
vi.spyOn(console, 'log').mockImplementation((...a) => logCalls.push(a.join(' ')));
- vi.spyOn(console, 'error').mockImplementation(() => {});
+ // Warnings/errors go to stderr (console.error) — capture them too so the
+ // human-output assertions see guidance lines regardless of channel.
+ vi.spyOn(console, 'error').mockImplementation((...a) => logCalls.push(a.join(' ')));
vi.spyOn(process.stdout, 'write').mockImplementation(chunk => {
stdoutCalls.push(typeof chunk === 'string' ? chunk : chunk.toString());
return true;
diff --git a/packages/cli/cli/commands/upgrade.mjs b/packages/cli/cli/commands/upgrade.mjs
index 4640071f7a..76c19567d6 100644
--- a/packages/cli/cli/commands/upgrade.mjs
+++ b/packages/cli/cli/commands/upgrade.mjs
@@ -13,7 +13,7 @@
*/
import {jsonOut, jsonError} from '../../lib/json.mjs';
-import {termLogger, noopLogger} from '../../lib/term-log.mjs';
+import {logger} from '../../api/logger.mjs';
import {AstryxError} from '../../api/error.mjs';
import {upgrade as upgradeApi} from '../../api/upgrade/upgrade.mjs';
@@ -41,12 +41,12 @@ export function registerUpgrade(program) {
*/
async options => {
const json = program.opts().json || false;
- const logger = json ? noopLogger : termLogger;
+ logger.setSilent(json);
- /** @type {import('../../types/upgrade').UpgradeListResponse | import('../../types/upgrade').UpgradeStatusResponse | import('../../types/upgrade').UpgradeRunResponse} */
+ /** @type {import('../../api/upgrade/upgrade.type.mjs').UpgradeListResponse | import('../../api/upgrade/upgrade.type.mjs').UpgradeStatusResponse | import('../../api/upgrade/upgrade.type.mjs').UpgradeRunResponse} */
let result;
try {
- result = await upgradeApi(options, {cwd: process.cwd(), logger});
+ result = await upgradeApi(options, {cwd: process.cwd()});
} catch (e) {
// Handled failures throw AstryxError: --json emits the structured
// envelope (byte-identical to the old inline jsonError) + exits 1;
diff --git a/packages/cli/lib/term-log.mjs b/packages/cli/lib/term-log.mjs
index 5f32bf4788..0553014d86 100644
--- a/packages/cli/lib/term-log.mjs
+++ b/packages/cli/lib/term-log.mjs
@@ -1,28 +1,19 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Minimal non-interactive terminal logger.
+ * @file Minimal non-interactive terminal output surface for codemods.
*
- * @input message strings from CLI commands/codemods
+ * @input message strings from codemod runners
* @output plain lines on stdout via humanLog (suppressed in --json mode)
- * @position src/lib — shared output helper, no side effects on import
+ * @position lib — shared output helper, no side effects on import
*
- * The CLI is fully non-interactive: it never prompts, so it only needs plain,
- * unbuffered output. This provides the *output-only* surface (`log.*`, `intro`,
- * `outro`) the CLI needs, so it has no dependency on any prompt library.
+ * Codemod runners use it as `import * as p from './term-log.mjs'` and call
+ * `p.log.step(...)`, `p.log.success(...)`, etc. All output routes through
+ * `humanLog`, the CLI's stdout-discipline primitive, which is a no-op in
+ * `--json` mode — so these human logs can never corrupt a JSON envelope.
*
- * All output is routed through `humanLog`, the CLI's stdout-discipline
- * primitive, which is a no-op in `--json` mode — so these human logs can never
- * corrupt a JSON envelope.
- *
- * Call sites use it as `import * as p from './term-log.mjs'` and call
- * `p.log.info(...)`, `p.intro(...)`, `p.outro(...)`.
- *
- * For API functions that emit progress without knowing how it's rendered, this
- * module also exports an *injectable* flat logger (`CliLogger`): the CLI passes
- * `termLogger` (routes here → stdout, suppressed in --json); programmatic
- * callers get the silent `noopLogger` default, so a scripted API call stays
- * quiet even though it isn't in --json mode.
+ * The side-effecting API commands (upgrade/init/themeBuild) do NOT use this;
+ * they write through the shared `logger` (api/logger.mjs).
*/
import {humanLog} from './json.mjs';
@@ -31,7 +22,7 @@ import {humanLog} from './json.mjs';
const toStr = (msg) => (msg === undefined || msg === null ? '' : String(msg));
/**
- * Human-facing log surface (the small `log` API the CLI uses). All lines go to
+ * Human-facing log surface (the small `log` API codemods use). All lines go to
* stdout via humanLog; the level prefixes are cosmetic. `--json` mode suppresses
* every one of these, keeping machine-readable stdout clean.
*/
@@ -49,53 +40,3 @@ export const log = {
/** @param {unknown} msg */
error: (msg) => humanLog(`✗ ${toStr(msg)}`),
};
-
-/** Banner printed at the start of a multi-step command.
- * @param {unknown} title */
-export function intro(title) {
- humanLog(`\n${toStr(title)}`);
-}
-
-/** Footer printed at the end of a multi-step command.
- * @param {unknown} message */
-export function outro(message) {
- humanLog(`${toStr(message)}\n`);
-}
-
-/**
- * Injectable flat logger for API functions (side-effecting/long-running
- * commands like upgrade). The API calls `logger.step(...)` etc. and defaults to
- * `noopLogger`; the CLI hands it `termLogger`. Purely presentation — the API
- * still returns its `{type, data}` result / throws.
- *
- * @typedef {object} CliLogger
- * @property {(m?: unknown) => void} intro
- * @property {(m?: unknown) => void} step
- * @property {(m?: unknown) => void} info
- * @property {(m?: unknown) => void} warn
- * @property {(m?: unknown) => void} success
- * @property {(m?: unknown) => void} error
- * @property {(m?: unknown) => void} outro
- */
-
-/** Silent logger — the default for programmatic API callers. @type {CliLogger} */
-export const noopLogger = {
- intro() {},
- step() {},
- info() {},
- warn() {},
- success() {},
- error() {},
- outro() {},
-};
-
-/** term-log-backed logger — used by the CLI in human (non --json) mode. @type {CliLogger} */
-export const termLogger = {
- intro: msg => intro(msg),
- step: msg => log.step(msg),
- info: msg => log.info(msg),
- warn: msg => log.warn(msg),
- success: msg => log.success(msg),
- error: msg => log.error(msg),
- outro: msg => outro(msg),
-};
diff --git a/packages/cli/package.json b/packages/cli/package.json
index e1e44b018f..8f36be160c 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -36,7 +36,7 @@
"import": "./lib/parse.mjs"
},
"./api": {
- "types": "./types/api.d.ts",
+ "types": "./api/index.d.mts",
"import": "./api/index.mjs"
},
"./config": {
@@ -83,8 +83,10 @@
"astryx": "node bin/astryx.mjs",
"postinstall": "node scripts/postinstall.mjs",
"typecheck:template-docs": "tsc --project tsconfig.template-docs.json",
- "typecheck:json-api": "tsc --project tsconfig.json-api.json && tsc --project tsconfig.api-contract.json",
- "typecheck:strict": "tsc --project tsconfig.strict.json"
+ "typecheck:json-api": "tsc --project tsconfig.json-api.json",
+ "typecheck:strict": "tsc --project tsconfig.strict.json",
+ "sync:api-types": "node scripts/sync-api-types.mjs",
+ "prepack": "pnpm sync:api-types"
},
"dependencies": {
"commander": "^12.1.0",
diff --git a/packages/cli/scripts/sync-api-types.mjs b/packages/cli/scripts/sync-api-types.mjs
new file mode 100644
index 0000000000..87a835bae8
--- /dev/null
+++ b/packages/cli/scripts/sync-api-types.mjs
@@ -0,0 +1,89 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Generate the public `./api` type surface from the JSDoc source of truth.
+ *
+ * Functions own their types: each api leaf's `@returns` + colocated
+ * `.type.mjs` typedefs ARE the contract. This script runs `tsc`
+ * (allowJs + checkJs + declaration + emitDeclarationOnly) over the api sources
+ * into a throwaway temp dir, then copies just the emitted api declaration tree
+ * (the `.d.mts` files) back alongside the sources (so their relative imports and
+ * shared `types` declarations resolve). `api/index.d.mts` is the entry that
+ * `package.json` exports["./api"].types points at.
+ *
+ * The emitted `api/**\/*.d.mts` are NOT committed (they're gitignored, like the
+ * other packages' `dist/`). This script runs automatically at `prepack`, so
+ * `pnpm pack`/`pnpm publish` always ships a freshly generated, in-sync surface.
+ * Run `pnpm sync:api-types` to produce them locally; the published surface is
+ * verified end-to-end by `.github/scripts/cli-api-types-verify.mjs`.
+ *
+ * @position packages/cli/scripts — build tooling; not shipped runtime
+ */
+
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const CLI_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const TMP = '/tmp/astryx-dts-build';
+const EMITTED_API = path.join(TMP, 'packages', 'cli', 'api');
+const DEST_API = path.join(CLI_ROOT, 'api');
+
+/**
+ * Banner prepended to every emitted declaration so it's obvious the file is
+ * generated and must not be hand-edited — edit the `.mjs` JSDoc and re-run
+ * `pnpm sync:api-types` instead. The `@generated` tag is the standard marker
+ * tooling and reviewers recognize.
+ */
+const BANNER =
+ '// @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.\n' +
+ '// DO NOT EDIT — run `pnpm sync:api-types` to regenerate.\n\n';
+
+/**
+ * Recursively copy every emitted declaration from `src` to `dest`, preserving
+ * structure and prepending the generated banner.
+ * @param {string} src
+ * @param {string} dest
+ */
+function copyDts(src, dest) {
+ for (const entry of fs.readdirSync(src, {withFileTypes: true})) {
+ const s = path.join(src, entry.name);
+ const d = path.join(dest, entry.name);
+ if (entry.isDirectory()) {
+ copyDts(s, d);
+ } else if (entry.name.endsWith('.d.mts')) {
+ fs.mkdirSync(dest, {recursive: true});
+ fs.writeFileSync(d, BANNER + fs.readFileSync(s, 'utf8'));
+ }
+ }
+}
+
+/**
+ * Recursively delete every `.d.mts` under `dir` so a regen builds from pure
+ * `.mjs` source. Committed declarations sit next to their `.mjs`, and tsc would
+ * otherwise resolve an import to the stale `.d.mts` instead of re-inferring from
+ * the (possibly edited) source — making generation non-idempotent.
+ * @param {string} dir
+ */
+function cleanDts(dir) {
+ if (!fs.existsSync(dir)) return;
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) cleanDts(p);
+ else if (entry.name.endsWith('.d.mts')) fs.rmSync(p);
+ }
+}
+
+fs.rmSync(TMP, {recursive: true, force: true});
+cleanDts(DEST_API);
+execFileSync('pnpm', ['exec', 'tsc', '--project', 'tsconfig.api-dts.json'], {
+ cwd: CLI_ROOT,
+ stdio: 'inherit',
+});
+if (!fs.existsSync(EMITTED_API)) {
+ throw new Error(`Expected emitted declarations at ${EMITTED_API} — tsc produced nothing.`);
+}
+copyDts(EMITTED_API, DEST_API);
+fs.rmSync(TMP, {recursive: true, force: true});
+console.log('Synced ./api declarations from the JSDoc source of truth.');
diff --git a/packages/cli/tsconfig.api-contract.json b/packages/cli/tsconfig.api-contract.json
deleted file mode 100644
index bf48ef8c59..0000000000
--- a/packages/cli/tsconfig.api-contract.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "extends": "../../tsconfig.json",
- "compilerOptions": {
- "rootDir": "../..",
- "allowJs": true,
- "checkJs": false,
- "noEmit": true,
- "types": ["node"]
- },
- "include": [
- "types/**/*.d.ts",
- "types/api.contract.assert.ts",
- "../core/src/docs-types.ts"
- ]
-}
diff --git a/packages/cli/tsconfig.api-dts.json b/packages/cli/tsconfig.api-dts.json
new file mode 100644
index 0000000000..a8bea96f9f
--- /dev/null
+++ b/packages/cli/tsconfig.api-dts.json
@@ -0,0 +1,14 @@
+{
+ "extends": "./tsconfig.strict.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "declarationMap": false,
+ "rootDir": "../..",
+ "outDir": "/tmp/astryx-dts-build",
+ "customConditions": ["source"]
+ },
+ "include": ["api/**/*.mjs", "types/**/*.d.ts"],
+ "exclude": ["**/*.test.mjs"]
+}
diff --git a/packages/cli/types/api.contract.assert.ts b/packages/cli/types/api.contract.assert.ts
deleted file mode 100644
index aad1a09558..0000000000
--- a/packages/cli/types/api.contract.assert.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Compile-time guard that the runtime @astryxdesign/cli/api implementation matches the
- * declared programmatic API surface in api.d.ts.
- *
- * WHY THIS FILE EXISTS
- * --------------------
- * `typecheck:json-api` historically only checked the `.d.ts` declarations plus a
- * couple of `lib/*.mjs` helpers — it never looked at `src/api/*.mjs`. So the
- * hand-written declarations in `api.d.ts` could (and did) silently drift from
- * what the runtime functions actually accept: the runtime `component()` gained
- * `package`/`blocks` options and a `component.detail.blocks` result, and
- * `template()` gained a `type` filter, none of which were reflected in
- * `api.d.ts`. CI never caught it.
- *
- * Turning on full `checkJs` over the api implementations surfaces ~140
- * pre-existing implicit-any JSDoc errors in transitively-imported `lib/*` and
- * `utils/*` files that have nothing to do with the public API contract — an
- * unmanageable cleanup for one PR (see PR body). Instead, this file pins the
- * *option surface and arity* of each runtime function against the declared
- * types. The check runs under a dedicated tsconfig with `checkJs: false`, so
- * the implementation bodies are not re-typechecked — only their JSDoc-derived
- * export signatures are read and compared.
- *
- * The JSDoc `@param` annotations on each `src/api/*.mjs` export are the source
- * TypeScript reads for the runtime side, so keeping them in sync with
- * `api.d.ts` is exactly what this guard enforces. If a runtime function adds an
- * option the `.d.ts` omits (or vice versa), the corresponding `MutuallyEqual`
- * assertion below fails and `typecheck:json-api` goes red.
- */
-
-import type * as Api from './api';
-import type {component} from '../api/component/component.mjs';
-import type {docs} from '../api/docs/docs.mjs';
-import type {discover} from '../api/discover/discover.mjs';
-import type {template} from '../api/template/template.mjs';
-
-/** Resolve to `true` only when `A` and `B` are mutually assignable. */
-type Equal<A, B> =
- (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
- ? true
- : false;
-
-/** Compile error unless `T` is exactly `true`. */
-type Expect<T extends true> = T;
-
-/** Drop `undefined` from an optional options parameter for comparison. */
-type Opt<T> = NonNullable<T>;
-
-// ── Option-bag parity: the declared options and the runtime JSDoc options
-// must describe the same set of keys/types, in both directions. ──────────────
-
-type _ComponentOptions = Expect<
- Equal<
- Opt<Parameters<typeof Api.component>[1]>,
- Opt<Parameters<typeof component>[1]>
- >
->;
-type _DocsOptions = Expect<
- Equal<Opt<Parameters<typeof Api.docs>[2]>, Opt<Parameters<typeof docs>[2]>>
->;
-type _DiscoverOptions = Expect<
- Equal<
- Opt<Parameters<typeof Api.discover>[1]>,
- Opt<Parameters<typeof discover>[1]>
- >
->;
-type _TemplateOptions = Expect<
- Equal<
- Opt<Parameters<typeof Api.template>[1]>,
- Opt<Parameters<typeof template>[1]>
- >
->;
-
-// ── Positional-argument parity: arity and positional types must match. ───────
-
-type _ComponentName = Expect<
- Equal<Parameters<typeof Api.component>[0], Parameters<typeof component>[0]>
->;
-type _DocsTopic = Expect<
- Equal<Parameters<typeof Api.docs>[0], Parameters<typeof docs>[0]>
->;
-type _DocsSection = Expect<
- Equal<Parameters<typeof Api.docs>[1], Parameters<typeof docs>[1]>
->;
-type _DiscoverQuery = Expect<
- Equal<Parameters<typeof Api.discover>[0], Parameters<typeof discover>[0]>
->;
-type _TemplateName = Expect<
- Equal<Parameters<typeof Api.template>[0], Parameters<typeof template>[0]>
->;
-
-// Surface the assertion aliases so the file has a value/type export and the
-// checks above are not tree-shaken away by `noUnusedLocals`.
-export type _ApiContractGuard = [
- _ComponentOptions,
- _DocsOptions,
- _DiscoverOptions,
- _TemplateOptions,
- _ComponentName,
- _DocsTopic,
- _DocsSection,
- _DiscoverQuery,
- _TemplateName,
-];
diff --git a/packages/cli/types/api.d.ts b/packages/cli/types/api.d.ts
deleted file mode 100644
index 0fcf1df118..0000000000
--- a/packages/cli/types/api.d.ts
+++ /dev/null
@@ -1,386 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Programmatic API types for @astryxdesign/cli/api.
- *
- * Every function returns the same { type, data } envelope as `xds --json`.
- * Errors throw AstryxError.
- */
-
-import type {
- ComponentListResponse,
- ComponentDetailResponse,
- ComponentDetailPropsResponse,
- ComponentDetailSourceResponse,
- ComponentDetailShowcaseResponse,
- ComponentDetailBlocksResponse,
-} from './component';
-import type {
- DocsListResponse,
- DocsDetailResponse,
- DocsDetailSectionResponse,
-} from './docs';
-import type {
- DiscoverListResponse,
- DiscoverDetailResponse,
- DiscoverDetailDocResponse,
- DiscoverSearchResponse,
-} from './discover';
-import type {
- TemplateListResponse,
- TemplateShowResponse,
- TemplateSkeletonResponse,
- TemplateCopyResponse,
-} from './template';
-import type {
- HookListResponse,
- HookDetailResponse,
- HookDetailParamsResponse,
-} from './hook';
-import type {SearchResponse, SearchDomain} from './search';
-import type {ErrorCode} from './error-codes';
-import type {DoctorResponse} from './doctor';
-import type {
- LayoutForm,
- LayoutExpandResponse,
- LayoutCheckResponse,
- LayoutGrammarResponse,
-} from './layout';
-import type {ValidateIntegrationResponse} from './validate-integration';
-import type {AstryxIntegrationIssue} from './integration';
-import type {BuildHelpResponse, BuildKitResponse} from './build';
-import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';
-import type {
- UpgradeListResponse,
- UpgradeStatusResponse,
- UpgradeRunResponse,
-} from './upgrade';
-import type {BlogListResponse, BlogDetailResponse} from './blog';
-import type {InitRunResponse, InitRemoveResponse} from './init';
-import type {ThemeBuildResponse} from './theme';
-import type {Suggestion} from './base';
-
-/** Structured API error with a stable machine-readable code. */
-export declare class AstryxError extends Error {
- /** Stable error code; consumers branch on this, never the message. */
- code: ErrorCode;
- suggestions?: Suggestion[];
- constructor(message: string, suggestions?: Suggestion[], code?: ErrorCode);
-}
-
-// ── Component ────────────────────────────────────────────────────────
-
-export interface ComponentOptions {
- cwd?: string;
- list?: boolean;
- category?: string;
- /** Scope lookup to a specific external package (e.g. '@acme/xds-widgets'). */
- package?: string;
- props?: boolean;
- source?: boolean;
- showcase?: boolean;
- /** List example blocks for the component: showcase, examples, and related. */
- blocks?: boolean;
- detail?: 'full' | 'compact' | 'brief';
- lang?: string;
- zh?: boolean;
- dense?: boolean;
-}
-
-type ComponentResult =
- | ComponentListResponse
- | ComponentDetailResponse
- | ComponentDetailPropsResponse
- | ComponentDetailSourceResponse
- | ComponentDetailShowcaseResponse
- | ComponentDetailBlocksResponse;
-
-export declare function component(
- name?: string,
- options?: ComponentOptions,
-): Promise<ComponentResult>;
-
-// ── Docs ─────────────────────────────────────────────────────────────
-
-export interface DocsOptions {
- lang?: string;
- zh?: boolean;
- dense?: boolean;
-}
-
-type DocsResult =
- DocsListResponse | DocsDetailResponse | DocsDetailSectionResponse;
-
-export declare function docs(
- topic?: string,
- section?: string,
- options?: DocsOptions,
-): Promise<DocsResult>;
-
-// ── Discover ─────────────────────────────────────────────────────────
-
-export interface DiscoverOptions {
- components?: boolean;
- lang?: string;
- zh?: boolean;
-}
-
-type DiscoverResult =
- | DiscoverListResponse
- | DiscoverDetailResponse
- | DiscoverDetailDocResponse
- | DiscoverSearchResponse;
-
-export declare function discover(
- query?: string,
- options?: DiscoverOptions,
-): Promise<DiscoverResult>;
-
-// ── Template ─────────────────────────────────────────────────────────
-
-export interface TemplateOptions {
- list?: boolean;
- skeleton?: boolean;
- show?: boolean;
- /** Filter templates by kind: 'page' or 'block'. Only applies to list views. */
- type?: 'page' | 'block';
- /** Narrow to templates from a specific package (id-only lookups across packages are ambiguous). */
- package?: string;
- targetPath?: string;
- cwd?: string;
-}
-
-type TemplateResult =
- | TemplateListResponse
- | TemplateShowResponse
- | TemplateSkeletonResponse
- | TemplateCopyResponse;
-
-export declare function template(
- name?: string,
- options?: TemplateOptions,
-): Promise<TemplateResult>;
-
-// ── Hook ─────────────────────────────────────────────────────────────
-
-export interface HookOptions {
- cwd?: string;
- list?: boolean;
- category?: string;
- params?: boolean;
- detail?: 'full' | 'compact' | 'brief';
- lang?: string;
- zh?: boolean;
-}
-
-type HookResult =
- HookListResponse | HookDetailResponse | HookDetailParamsResponse;
-
-export declare function hook(
- name?: string,
- options?: HookOptions,
-): Promise<HookResult>;
-
-// ── Search ───────────────────────────────────────────────────────────
-
-export interface SearchOptions {
- cwd?: string;
- type?: SearchDomain;
- limit?: number;
-}
-
-export declare function search(
- query: string,
- options?: SearchOptions,
-): Promise<SearchResponse>;
-
-// ── Build ────────────────────────────────────────────────────────────
-
-export interface BuildOptions {
- cwd?: string;
- type?: SearchDomain;
- limit?: number;
-}
-
-/**
- * Page-building assistant. No query → `build.help` (playbook signal); a query →
- * `build.kit` (grouped composition kit of raw search entries + frame/foundation).
- */
-export declare function build(
- query?: string,
- options?: BuildOptions,
-): Promise<BuildHelpResponse | BuildKitResponse>;
-
-// ── Swizzle ──────────────────────────────────────────────────────────
-
-export interface SwizzleOptions {
- cwd?: string;
- /** Output directory (must resolve inside cwd). Defaults to ./components/astryx. */
- output?: string;
- /** Scope to a specific owning package when a name is ambiguous. */
- package?: string;
- /** Force the list response even with a component argument. */
- list?: boolean;
- /** Overwrite existing files instead of erroring. */
- overwrite?: boolean;
-}
-
-/**
- * List swizzlable components (no name / `list`) or copy one component's source
- * into the project (side effect) and return a `swizzle.copy` receipt. Errors
- * throw AstryxError (ERR_UNKNOWN_COMPONENT, ERR_AMBIGUOUS_COMPONENT, …).
- */
-export declare function swizzle(
- component?: string,
- options?: SwizzleOptions,
-): Promise<SwizzleListResponse | SwizzleCopyResponse>;
-
-// ── Doctor ──────────────────────────────────
-
-export interface DoctorOptions {
- cwd?: string;
-}
-
-export declare function doctor(
- options?: DoctorOptions,
-): Promise<DoctorResponse>;
-
-// ── Layout ───────────────────────────────────────────────────────────
-
-export interface LayoutExpandOptions {
- targetPath?: string;
- form?: LayoutForm;
- loose?: boolean;
- name?: string;
- cwd?: string;
-}
-
-export declare function layoutExpand(
- expression: string,
- options?: LayoutExpandOptions,
-): Promise<LayoutExpandResponse>;
-
-export interface LayoutCheckOptions {
- form?: LayoutForm;
- loose?: boolean;
- cwd?: string;
-}
-
-export declare function layoutCheck(
- expression: string,
- options?: LayoutCheckOptions,
-): Promise<LayoutCheckResponse>;
-
-export interface LayoutGrammarOptions {
- cwd?: string;
-}
-
-export declare function layoutGrammar(
- options?: LayoutGrammarOptions,
-): Promise<LayoutGrammarResponse>;
-
-// ── Validate integration ─────────────────────────────────────────────
-
-export interface ValidateIntegrationOptions {
- cwd?: string;
-}
-
-/**
- * Validate the local integration (no `pkg`) or an installed one (`pkg` given).
- * The no-manifest local case returns `{ name: null, version: null, issues: [] }`.
- */
-export declare function validateIntegration(
- pkg?: string,
- options?: ValidateIntegrationOptions,
-): Promise<ValidateIntegrationResponse>;
-
-/** Count issues by severity. */
-export declare function summarizeIssues(issues: AstryxIntegrationIssue[]): {
- errors: number;
- warnings: number;
-};
-
-// ── Upgrade ──────────────────────────────────────────────────────────
-
-export interface UpgradeOptions {
- /** Version before the dependency bump (required unless `list`). */
- from?: string;
- /** Write changes to disk (default: dry-run). */
- apply?: boolean;
- /** Run codemods even if `from` >= installed. */
- force?: boolean;
- /** Run a single named transform. */
- codemod?: string;
- /** Exclude named codemods (re-run past a failure). */
- skipCodemod?: string[];
- /** Explicit integration package names / file paths. */
- integration?: string[];
- /** Source directory to scan (default `./src`). */
- path?: string;
- /** Auto-install jscodeshift without prompting. */
- installDeps?: boolean;
- /** Return the available codemods instead of running. */
- list?: boolean;
-}
-
-/**
- * Run the version-to-version upgrade pipeline (codemods + agent-docs refresh).
- * Performs the effect in `apply` mode and returns a receipt; throws AstryxError
- * on failure.
- */
-export declare function upgrade(
- options?: UpgradeOptions,
- ctx?: {cwd?: string},
-): Promise<UpgradeListResponse | UpgradeStatusResponse | UpgradeRunResponse>;
-
-// ── Blog ─────────────────────────────────────────────────────────────
-
-/**
- * Read the Astryx blog over the canonical RSS feed. No args lists posts; a slug
- * reads that post's plaintext. Throws AstryxError on a fetch failure or an
- * unknown slug.
- */
-export declare function blog(
- slug?: string,
-): Promise<BlogListResponse | BlogDetailResponse>;
-
-// ── Init ─────────────────────────────────────────────────────────────
-
-export interface InitOptions {
- /** Comma-separated features to install (agents, theme, template). */
- features?: string;
- /** Install all features. */
- all?: boolean;
- /** Remove the managed agent-docs block instead of installing. */
- removeAgents?: boolean;
- /** Agent preset: claude, cursor, codex, hermes, all. */
- agent?: string;
- /** Explicit agent-docs file path(s). */
- agentDocsPath?: string | string[];
- /** Scaffold a named page template (programmatic only; the CLI never sets it). */
- templateName?: string;
-}
-
-/**
- * Run the non-interactive init flow (agent-docs install, template scaffold, or
- * agent-docs removal). Performs the effect and returns a receipt; throws
- * AstryxError on an unknown feature or template name.
- */
-export declare function init(
- options?: InitOptions,
- ctx?: {cwd?: string},
-): Promise<InitRunResponse | InitRemoveResponse>;
-
-// ── Theme build ──────────────────────────────────────────────────────
-
-/**
- * Compile a defineTheme file to CSS + JS + .d.ts (and an optional
- * `.variants.d.ts`). Writes the outputs and returns a `theme.build` receipt,
- * or `null` when the theme produced no CSS (nothing to build). Throws
- * AstryxError on failure. `out` overrides the output CSS path.
- */
-export declare function themeBuild(
- file: string,
- options?: {out?: string},
- ctx?: {cwd?: string},
-): Promise<ThemeBuildResponse | null>;
diff --git a/packages/cli/types/blog.d.ts b/packages/cli/types/blog.d.ts
index 8176c94155..f75ee80574 100644
--- a/packages/cli/types/blog.d.ts
+++ b/packages/cli/types/blog.d.ts
@@ -1,35 +1,18 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Types for the `blog` API (@astryxdesign/cli/api → blog). The blog is
- * read over the canonical RSS feed; there are no options (list vs. read a post
- * is decided by the optional slug argument).
+ * @file Public re-export of the `blog` command's types.
+ *
+ * The source of truth is colocated with the API leaves in
+ * `api/blog/blog.type.mjs` (functions own their types). This file keeps the
+ * `./types/blog` consumers (and the `@astryxdesign/cli` `./json` surface)
+ * resolving the same type names without duplicating the shapes.
*/
-export interface BlogPost {
- slug: string;
- title: string;
- description?: string;
- date?: string;
- type?: string;
- authors?: string[];
- link?: string;
- textUrl?: string | null;
-}
-
-export interface BlogListData {
- feedUrl: string;
- posts: BlogPost[];
-}
-
-export type BlogDetailData = BlogPost & {feedUrl: string; text: string};
-
-export interface BlogListResponse {
- type: 'blog.list';
- data: BlogListData;
-}
-
-export interface BlogDetailResponse {
- type: 'blog.detail';
- data: BlogDetailData;
-}
+export type {
+ BlogPost,
+ BlogListData,
+ BlogDetailData,
+ BlogListResponse,
+ BlogDetailResponse,
+} from '../api/blog/blog.type.mjs';
diff --git a/packages/cli/types/build.d.ts b/packages/cli/types/build.d.ts
index dc38fee4f6..e781f4ae77 100644
--- a/packages/cli/types/build.d.ts
+++ b/packages/cli/types/build.d.ts
@@ -3,51 +3,12 @@
/**
* Build command JSON responses.
*
- * `astryx build` is the "assemble a page" verb. With no query it emits the
- * workflow playbook; with a query it delegates to the search pipeline and
- * emits a `search` response (see search.d.ts).
- *
- * Invocation -> type discriminator
- * ---------------------------------------------------
- * xds --json build -> build.help
- * xds --json build "<idea>" -> build.kit
+ * The shapes now live next to the API as the source of truth in
+ * `api/build/build.type.mjs`. This barrel re-exports them so existing
+ * `./types/build` consumers (types/index.d.ts) stay stable.
*/
-import type {SearchResultEntry} from './search';
-
-/** xds --json build (no query) — the "how to build a page" playbook signal. */
-export interface BuildHelpResponse {
- type: 'build.help';
- data: {
- /** Always true; marks this envelope as the playbook rather than a result set. */
- playbook: true;
- };
-}
-
-/**
- * xds --json build "<idea>" — the composition kit for what you're building.
- *
- * Entries are raw `SearchResultEntry` objects (no package-manager-prefixed
- * command strings — the CLI adds those); `frame`/`foundation` are static
- * component-name arrays surfaced on every kit.
- */
-export interface BuildKitResponse {
- type: 'build.kit';
- data: {
- query: string;
- /** False when search returned nothing (renderer shows "No matches"). */
- hasResults: boolean;
- /** True when the top page template is a confident direct match. */
- directMatch: boolean;
- /** Closest page templates (≤3). */
- pages: SearchResultEntry[];
- /** Drop-in block patterns covering parts of the idea (≤5). */
- blocks: SearchResultEntry[];
- /** Idea-specific components/hooks (≤6), excluding frame/foundation. */
- domain: SearchResultEntry[];
- /** Always-on page-shell component names. */
- frame: string[];
- /** Always-on layout/typography/action component names. */
- foundation: string[];
- };
-}
+export type {
+ BuildHelpResponse,
+ BuildKitResponse,
+} from '../api/build/build.type.mjs';
diff --git a/packages/cli/types/component.d.ts b/packages/cli/types/component.d.ts
index 92bcd15940..297b878f1a 100644
--- a/packages/cli/types/component.d.ts
+++ b/packages/cli/types/component.d.ts
@@ -1,122 +1,22 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Component command JSON responses.
- *
- * Detail-level contract for list views (brief < compact < full):
- * --detail brief Names only. Smallest, most scannable. (DEFAULT for --list)
- * --detail compact Names + 1-line description + import path.
- * --detail full Full ComponentDoc per entry (props, theming, examples, etc.).
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json component -> component.list (data.detail='names')
- * xds --json component --list -> component.list (data.detail='names')
- * xds --json component --category Form -> component.list (filtered)
- * xds --json component --list --detail compact -> component.list (data.detail='compact')
- * xds --json component --list --detail full -> component.list (data.detail='full')
- * xds --json component Button -> component.detail
- * xds --json component Button --props -> component.detail.props
- * xds --json component Button --source -> component.detail.source
- * xds --json component Button --showcase -> component.detail.showcase
- * xds --json component Button --blocks -> component.detail.blocks
- * (not found) -> CLIError
+ * @file Barrel for the `component` command's JSON response types. The source of
+ * truth now lives beside the API at `api/component/component.type.mjs`; this thin
+ * re-export keeps existing `./types/component` consumers (types/index.d.ts)
+ * resolving these names unchanged.
*/
-import type {ComponentDoc, PropDoc} from '../../core/src/docs-types';
-
-/**
- * xds --json component [--list] [--category X] [--detail names|compact|full]
- *
- * The list view emits ONE `component.list` type across all three detail levels;
- * the depth is carried in `data.detail` and `data.components` holds the grouped
- * map whose entry shape depends on that level:
- * - 'names' -> ComponentListEntry[] (name + owner package)
- * - 'compact' -> ComponentBriefEntry[] (name + 1-line description + import)
- * - 'full' -> ComponentDoc[] (full authored doc per entry)
- */
-export interface ComponentListResponse {
- type: 'component.list';
- data: ComponentListData;
-}
-
-/** Detail-tagged payload for `component.list` (discriminated on `detail`). */
-export type ComponentListData =
- | {detail: 'names'; components: Record<string, ComponentListEntry[]>}
- | {detail: 'compact'; components: Record<string, ComponentBriefEntry[]>}
- | {detail: 'full'; components: Record<string, ComponentDoc[]>};
-
-/**
- * A single entry in a `component.list` group at `detail: 'names'`. Pre-1.0 the
- * list moved from bare strings to package-qualified objects so consumers can
- * disambiguate ownership (core vs. an integration package).
- */
-export interface ComponentListEntry {
- name: string;
- /** Owner package, e.g. '@astryxdesign/core' or '@acme/astryx-meta'. */
- package: string;
-}
-
-/** A single entry in a `component.list` group at `detail: 'compact'`. */
-export interface ComponentBriefEntry {
- name: string;
- description: string;
- import: string;
-}
-
-/** xds --json component <name> */
-export interface ComponentDetailResponse {
- type: 'component.detail';
- data: ComponentDoc & ComponentOwnership;
-}
-
-/**
- * Ownership metadata attached to every `component.detail` payload. Exposes the
- * owner package, the import specifier, and whether a swizzleable source file is
- * available — the inputs the integration-component swizzle (a later PR) needs.
- */
-export interface ComponentOwnership {
- /** Owner package, e.g. '@astryxdesign/core' or an integration package name. */
- package: string;
- /** Import specifier for the component (e.g. '@astryxdesign/core/Button'). */
- import: string;
- /** Whether a component source file exists for `--source` / swizzle. */
- sourceAvailable: boolean;
-}
-
-/** xds --json component <name> --props */
-export interface ComponentDetailPropsResponse {
- type: 'component.detail.props';
- data: PropDoc[];
-}
-
-/** xds --json component <name> --source */
-export interface ComponentDetailSourceResponse {
- type: 'component.detail.source';
- data: {component: string; source: string};
-}
-
-/** xds --json component <name> --showcase */
-export interface ComponentDetailShowcaseResponse {
- type: 'component.detail.showcase';
- data: {component: string; aspectRatio: number; source: string};
-}
-
-/** xds --json component <name> --blocks */
-export interface ComponentDetailBlocksResponse {
- type: 'component.detail.blocks';
- data: {
- component: string;
- showcase: BlockEntry | null;
- examples: BlockEntry[];
- related: BlockEntry[];
- };
-}
-
-export interface BlockEntry {
- name: string;
- displayName: string;
- description: string;
- isShowcase: boolean;
- category: string;
-}
+export type {
+ ComponentListResponse,
+ ComponentListData,
+ ComponentListEntry,
+ ComponentBriefEntry,
+ ComponentDetailResponse,
+ ComponentOwnership,
+ ComponentDetailPropsResponse,
+ ComponentDetailSourceResponse,
+ ComponentDetailShowcaseResponse,
+ ComponentDetailBlocksResponse,
+ BlockEntry,
+} from '../api/component/component.type.mjs';
diff --git a/packages/cli/types/discover.d.ts b/packages/cli/types/discover.d.ts
index 7fa0661ac0..0dcd1e2e54 100644
--- a/packages/cli/types/discover.d.ts
+++ b/packages/cli/types/discover.d.ts
@@ -1,59 +1,18 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Discover command JSON responses.
+ * Discover command JSON response types.
*
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json discover -> discover.list
- * xds --json discover @scope/name -> discover.detail
- * xds --json discover @scope/name/Component -> discover.detail.doc
- * xds --json discover <searchterm> (1 match) -> discover.detail.doc
- * xds --json discover <searchterm> (N matches) -> discover.search
- * (not found) -> CLIError
+ * Source of truth is colocated with the command's API at
+ * `../api/discover/discover.type.mjs`; this file re-exports those types so
+ * existing `types/discover` importers keep working.
*/
-import type {ComponentDoc} from '../../core/src/docs-types';
-
-/** xds --json discover */
-export interface DiscoverListResponse {
- type: 'discover.list';
- data: DiscoverListEntry[];
- /**
- * Present when the list is empty so callers can distinguish "no packages
- * configured" from "configured but nothing discovered".
- */
- meta?: {configured: boolean};
-}
-
-export interface DiscoverListEntry {
- name: string;
- category: string;
- components: string[];
- version?: string;
- description?: string;
- displayName?: string;
-}
-
-/** xds --json discover @scope/name */
-export interface DiscoverDetailResponse {
- type: 'discover.detail';
- data: DiscoverListEntry;
-}
-
-/** xds --json discover @scope/name/Component */
-export interface DiscoverDetailDocResponse {
- type: 'discover.detail.doc';
- data: ComponentDoc;
-}
-
-/** xds --json discover <searchterm> (multiple matches) */
-export interface DiscoverSearchResponse {
- type: 'discover.search';
- data: {query: string; matches: DiscoverSearchEntry[]};
-}
-
-export interface DiscoverSearchEntry {
- package: string;
- component: string;
-}
+export type {
+ DiscoverListResponse,
+ DiscoverListEntry,
+ DiscoverDetailResponse,
+ DiscoverDetailDocResponse,
+ DiscoverSearchResponse,
+ DiscoverSearchEntry,
+} from '../api/discover/discover.type.mjs';
diff --git a/packages/cli/types/docs.d.ts b/packages/cli/types/docs.d.ts
index fdcf6d7afe..001a8f0342 100644
--- a/packages/cli/types/docs.d.ts
+++ b/packages/cli/types/docs.d.ts
@@ -1,37 +1,11 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-/**
- * Docs command JSON responses.
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json docs -> docs.list
- * xds --json docs <topic> -> docs.detail
- * xds --json docs <topic> <section> -> docs.detail.section
- * (unknown topic/section) -> CLIError
- */
-
-import type {ReferenceDoc, ReferenceSection} from '../../core/src/docs-types';
-
-/** xds --json docs */
-export interface DocsListResponse {
- type: 'docs.list';
- data: DocsListEntry[];
-}
-
-export interface DocsListEntry {
- topic: string;
- description: string;
-}
-
-/** xds --json docs <topic> */
-export interface DocsDetailResponse {
- type: 'docs.detail';
- data: ReferenceDoc;
-}
-
-/** xds --json docs <topic> <section> */
-export interface DocsDetailSectionResponse {
- type: 'docs.detail.section';
- data: ReferenceSection;
-}
+// Docs command JSON response types are colocated with the API — the source of
+// truth is `api/docs/docs.type.mjs`. This barrel re-exports them so existing
+// consumers (types/index.d.ts) keep importing from 'types/docs'.
+export type {
+ DocsListResponse,
+ DocsListEntry,
+ DocsDetailResponse,
+ DocsDetailSectionResponse,
+} from '../api/docs/docs.type.mjs';
diff --git a/packages/cli/types/doctor.d.ts b/packages/cli/types/doctor.d.ts
index e13947d00a..dc0fa0b832 100644
--- a/packages/cli/types/doctor.d.ts
+++ b/packages/cli/types/doctor.d.ts
@@ -3,40 +3,15 @@
/**
* Doctor command JSON responses.
*
- * Invocation -> type discriminator
- * --------------------------------------------------
- * xds --json doctor -> doctor
+ * NOTE: These types are colocated with the command implementation — the source
+ * of truth now lives in `../api/doctor/doctor.type.mjs` (JSDoc typedefs). This
+ * file re-exports them so the public `./types/doctor` entrypoint and the
+ * `types/index.d.ts` barrel keep working unchanged.
*/
-/** Outcome of a single diagnostic check. */
-export type DoctorStatus = 'pass' | 'warn' | 'fail' | 'info';
-
-/** A single diagnostic check result. */
-export interface DoctorCheck {
- /** Stable machine-readable id (e.g. 'node-version'). */
- id: string;
- /** Human-readable check name. */
- label: string;
- status: DoctorStatus;
- /** One-line result summary. */
- message: string;
- /** Actionable remediation, present when status is not 'pass'. */
- fix?: string;
-}
-
-/** Aggregate counts per status. */
-export interface DoctorSummary {
- pass: number;
- warn: number;
- fail: number;
- info: number;
-}
-
-/** xds --json doctor */
-export interface DoctorResponse {
- type: 'doctor';
- data: {
- checks: DoctorCheck[];
- summary: DoctorSummary;
- };
-}
+export type {
+ DoctorStatus,
+ DoctorCheck,
+ DoctorSummary,
+ DoctorResponse,
+} from '../api/doctor/doctor.type.mjs';
diff --git a/packages/cli/types/hook.d.ts b/packages/cli/types/hook.d.ts
index 41528111e5..6c24d64ad1 100644
--- a/packages/cli/types/hook.d.ts
+++ b/packages/cli/types/hook.d.ts
@@ -1,67 +1,19 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Hook command JSON responses.
+ * @file Hook command JSON response types.
*
- * Detail-level contract for list views (brief < compact < full):
- * --detail brief Names only. Smallest, most scannable. (DEFAULT for --list)
- * --detail compact Names + 1-line description + import path.
- * --detail full Full HookDoc per entry (params, returns, usage, etc.).
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json hook -> hook.list (data.detail='names')
- * xds --json hook --list -> hook.list (data.detail='names')
- * xds --json hook --category State -> hook.list (filtered)
- * xds --json hook --list --detail compact -> hook.list (data.detail='compact')
- * xds --json hook --list --detail full -> hook.list (data.detail='full')
- * xds --json hook useMediaQuery -> hook.detail
- * xds --json hook useMediaQuery --params -> hook.detail.params
- * (not found) -> CLIError
- */
-
-import type {HookDoc, HookParamDoc} from '../../core/src/docs-types';
-
-// Re-export the authored-doc types the hook leaves project so they stay central
-// here (the leaf @returns reference these rather than reaching into core).
-export type {HookDoc, HookParamDoc};
-
-/**
- * xds --json hook [--list] [--category X] [--detail names|compact|full]
- *
- * The list view emits ONE `hook.list` type across all three detail levels; the
- * depth is carried in `data.detail` and `data.components` holds the grouped map
- * whose entry shape depends on that level:
- * - 'names' -> string[] (hook names only)
- * - 'compact' -> HookBriefEntry[] (name + 1-line description + import)
- * - 'full' -> HookDoc[] (full authored doc per entry)
+ * Thin mirror that re-exports the colocated source of truth at
+ * `../api/hook/hook.type.mjs`; see that file for the detail-level contract and
+ * the invocation -> type discriminator table.
*/
-export interface HookListResponse {
- type: 'hook.list';
- data: HookListData;
-}
-
-/** Detail-tagged payload for `hook.list` (discriminated on `detail`). */
-export type HookListData =
- | {detail: 'names'; components: Record<string, string[]>}
- | {detail: 'compact'; components: Record<string, HookBriefEntry[]>}
- | {detail: 'full'; components: Record<string, HookDoc[]>};
-
-/** A single entry in a `hook.list` group at `detail: 'compact'`. */
-export interface HookBriefEntry {
- name: string;
- description: string;
- import: string;
-}
-
-/** xds --json hook <name> */
-export interface HookDetailResponse {
- type: 'hook.detail';
- data: HookDoc;
-}
-/** xds --json hook <name> --params */
-export interface HookDetailParamsResponse {
- type: 'hook.detail.params';
- data: HookParamDoc[];
-}
+export type {
+ HookDoc,
+ HookParamDoc,
+ HookListResponse,
+ HookListData,
+ HookBriefEntry,
+ HookDetailResponse,
+ HookDetailParamsResponse,
+} from '../api/hook/hook.type.mjs';
diff --git a/packages/cli/types/init.d.ts b/packages/cli/types/init.d.ts
index 45447baa09..a0d5d1e04f 100644
--- a/packages/cli/types/init.d.ts
+++ b/packages/cli/types/init.d.ts
@@ -1,35 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Response types for the `init` API (@astryxdesign/cli/api → init).
- * Options live in api.d.ts (like UpgradeOptions).
+ * @file Re-export barrel for the `init` command's response types. The source of
+ * truth now lives colocated with the API at api/init/init.type.mjs; this file
+ * keeps existing `./types/init` consumers (types/index.d.ts) resolving
+ * unchanged. Options live in api/init/init.type.mjs (like UpgradeOptions).
*/
-export interface InitRunData {
- /** `default` (no flags) or `features` (--features/--all). */
- mode: 'default' | 'features';
- /** Features that were run, in order. */
- features: string[];
- /** Agent-doc files written (empty if agents weren't run or install failed). */
- docsWritten: string[];
- /** Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit. */
- docsError: {kind: 'path-safety' | 'install-failed'; message?: string} | null;
- /** Whether theme guidance was emitted. */
- theme: boolean;
- /** Template outcome (`workflow` is the CLI default; `created`/`skipped` are programmatic). */
- template: 'workflow' | 'created' | 'skipped' | null;
- /** Relative output path when `template === 'created'`. */
- templatePath: string | null;
- /** Whether the getting-started "Next steps" were emitted (default mode). */
- nextSteps: boolean;
-}
-
-export interface InitRunResponse {
- type: 'init.run';
- data: InitRunData;
-}
-
-export interface InitRemoveResponse {
- type: 'init.remove';
- data: {removed: true};
-}
+export type {
+ InitRunData,
+ InitRunResponse,
+ InitRemoveResponse,
+} from '../api/init/init.type.mjs';
diff --git a/packages/cli/types/layout.d.ts b/packages/cli/types/layout.d.ts
index 003f626e17..0a15295f6a 100644
--- a/packages/cli/types/layout.d.ts
+++ b/packages/cli/types/layout.d.ts
@@ -1,74 +1,17 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Layout command JSON responses.
- *
- * `astryx layout expand|check|grammar` turn compressed XLE/XLO expressions into
- * validated XDS TSX (or echo canonical surfaces / a grammar cheatsheet).
- *
- * Invocation -> type discriminator
- * -----------------------------------------------------------------
- * astryx --json layout expand "<expr>" -> layout.expand
- * astryx --json layout check "<expr>" -> layout.check
- * astryx --json layout grammar -> layout.grammar
+ * Barrel for the `layout` command's JSON response types. The source of truth is
+ * now colocated next to the API at `api/layout/layout.type.mjs`; this file just
+ * re-exports it so existing `types/layout` importers keep working.
*/
-/** The input surface an expression was parsed as. */
-export type LayoutForm = 'compact' | 'outline' | 'auto';
-
-/** A validation issue with its formatted, human-readable rendering. */
-export interface LayoutIssue {
- line?: number;
- col?: number;
- message: string;
- formatted: string;
- suggestions?: string[];
-}
-
-/** A block referenced by a layout expression and how it was spliced in. */
-export interface LayoutBlockReference {
- name: string;
- mode: string;
-}
-
-/** astryx --json layout expand "<expr>" [path] */
-export interface LayoutExpandResponse {
- type: 'layout.expand';
- data: {
- form: LayoutForm;
- code: string;
- componentsUsed: string[];
- /** Number of useState hooks the expansion scaffolded. */
- states: number;
- todos: string[];
- blocksReferenced: LayoutBlockReference[];
- warnings: string[];
- written: string | null;
- };
-}
-
-/** astryx --json layout check "<expr>" */
-export interface LayoutCheckResponse {
- type: 'layout.check';
- data: {
- valid: boolean;
- form: LayoutForm;
- errors: LayoutIssue[];
- warnings: string[];
- compact: string;
- outline: string;
- };
-}
-
-/** astryx --json layout grammar */
-export interface LayoutGrammarResponse {
- type: 'layout.grammar';
- data: {
- text: string;
- /** Alias table (short name -> canonical component), from the registry. */
- aliases: Record<string, string>;
- };
-}
-
-export type LayoutResponse =
- LayoutExpandResponse | LayoutCheckResponse | LayoutGrammarResponse;
+export type {
+ LayoutForm,
+ LayoutIssue,
+ LayoutBlockReference,
+ LayoutExpandResponse,
+ LayoutCheckResponse,
+ LayoutGrammarResponse,
+ LayoutResponse,
+} from '../api/layout/layout.type.mjs';
diff --git a/packages/cli/types/search.d.ts b/packages/cli/types/search.d.ts
index 15790e565d..858276e4c4 100644
--- a/packages/cli/types/search.d.ts
+++ b/packages/cli/types/search.d.ts
@@ -3,51 +3,14 @@
/**
* Search command JSON responses.
*
- * `astryx search <query>` returns a single ranked, typed result set spanning all
- * content domains — components, hooks, docs topics, and templates. Scoring is
- * keyword + fuzzy ranking (not semantic / embeddings).
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json search button -> search
- * xds --json search modal --type component -> search (filtered)
- * xds --json search forms --limit 5 -> search (capped)
- * xds --json search zzznomatch -> search (empty results, exit 0)
- * (no query) -> CLIError
+ * NOTE: These types are colocated with the command implementation — the source
+ * of truth now lives in `../api/search/search.type.mjs` (JSDoc typedefs). This
+ * file re-exports them so the public `./types/search` entrypoint and the
+ * `types/index.d.ts` barrel keep working unchanged.
*/
-/** The domain a search result belongs to. */
-export type SearchDomain = 'component' | 'hook' | 'doc' | 'template';
-
-/** A single ranked search result, tagged with its domain. */
-export interface SearchResultEntry {
- /** Which content domain this result came from. */
- domain: SearchDomain;
- /** Primary identifier (component/hook name, doc topic, template dir). */
- name: string;
- /** Relevance score (higher is better). */
- score: number;
- /** Human-readable reason the candidate matched (e.g. `keyword "button"`). */
- reason: string;
- /** One-line description, when available. */
- description: string;
- /** Follow-up command to act on this result (e.g. `astryx component Button`). */
- command: string;
- /** Import path — present for component and hook results. */
- import?: string;
- /** Doc title — present for doc results. */
- title?: string;
- /** Friendly display name — present for template results. */
- displayName?: string;
- /** Template kind (`page` | `block`) — present for template results. */
- kind?: 'page' | 'block';
-}
-
-/** xds --json search <query> */
-export interface SearchResponse {
- type: 'search';
- data: {
- query: string;
- results: SearchResultEntry[];
- };
-}
+export type {
+ SearchDomain,
+ SearchResultEntry,
+ SearchResponse,
+} from '../api/search/search.type.mjs';
diff --git a/packages/cli/types/swizzle.d.ts b/packages/cli/types/swizzle.d.ts
index 1ed7e921d8..65ed7e7c67 100644
--- a/packages/cli/types/swizzle.d.ts
+++ b/packages/cli/types/swizzle.d.ts
@@ -3,39 +3,13 @@
/**
* Swizzle command JSON responses.
*
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json swizzle [--list] -> swizzle.list
- * xds --json swizzle <component> -> swizzle.copy
- * (not found) -> CLIError
+ * The shapes now live next to the API as the source of truth in
+ * `api/swizzle/swizzle.type.mjs`. This barrel re-exports them so existing
+ * `./types/swizzle` consumers (types/index.d.ts) stay stable.
*/
-/** xds --json swizzle [--list] */
-export interface SwizzleListResponse {
- type: 'swizzle.list';
- data: string[];
-}
-
-/** Maintainer feedback note emitted after a successful swizzle. */
-export interface SwizzleFeedback {
- /** Where to report the gap that led to swizzling. */
- issuesUrl: string;
- /** Ready-to-run `gh issue create` command, when `gh` is available. */
- ghCommand?: string;
-}
-
-/** xds --json swizzle <component> */
-export interface SwizzleCopyResponse {
- type: 'swizzle.copy';
- data: {
- component: string;
- /** Owner package the component source was copied from. */
- package: string;
- outputDir: string;
- filesCopied: number;
- files: string[];
- /** Whether any copied file uses StyleX (requires build-time setup). */
- usesStyleX: boolean;
- feedback?: SwizzleFeedback;
- };
-}
+export type {
+ SwizzleListResponse,
+ SwizzleFeedback,
+ SwizzleCopyResponse,
+} from '../api/swizzle/swizzle.type.mjs';
diff --git a/packages/cli/types/template.d.ts b/packages/cli/types/template.d.ts
index ac0e7206a7..8622cdc792 100644
--- a/packages/cli/types/template.d.ts
+++ b/packages/cli/types/template.d.ts
@@ -3,71 +3,14 @@
/**
* Template command JSON responses.
*
- * Each template is exactly two files: page.tsx (code) + template.doc.mjs (metadata).
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json template [--list] -> template.list
- * xds --json template <name> -> template.show
- * xds --json template <name> --skeleton -> template.skeleton
- * xds --json template <name> [path] -> template.copy
- * (unknown template) -> CLIError
+ * The types now live next to the `template` API as JSDoc typedefs. This file
+ * re-exports them so existing `types/template` imports keep resolving. Edit the
+ * source of truth at `../api/template/template.type.mjs`.
*/
-
-/** xds --json template [--list] */
-export interface TemplateListResponse {
- type: 'template.list';
- data: TemplateListEntry[];
-}
-
-export interface TemplateListEntry {
- /** Stable template id (relative path under the templates root, minus the .doc.* suffix). */
- id: string;
- name: string;
- /** @deprecated Alias of `name`, retained for back-compat. */
- displayName: string;
- description: string;
- type: 'page' | 'block';
- /** Owning package; core (built-in) templates report '@astryxdesign/core'. */
- package: string;
- /** Optional grouping/category label. */
- category?: string;
- /** Component display names the template composes. */
- componentsUsed?: string[];
- isReady: boolean;
- scaffold?: boolean;
-}
-
-/** xds --json template <name> */
-export interface TemplateShowResponse {
- type: 'template.show';
- data: {
- template: string;
- description: string;
- type: 'page' | 'block';
- components: string[];
- source: string;
- };
-}
-
-/** xds --json template <name> --skeleton */
-export interface TemplateSkeletonResponse {
- type: 'template.skeleton';
- data: {
- template: string;
- description: string;
- components: string[];
- skeleton: string;
- };
-}
-
-/** xds --json template <name> [path] */
-export interface TemplateCopyResponse {
- type: 'template.copy';
- data: {
- template: string;
- outputDir: string;
- fileName: string;
- filesCopied: number;
- };
-}
+export type {
+ TemplateListResponse,
+ TemplateListEntry,
+ TemplateShowResponse,
+ TemplateSkeletonResponse,
+ TemplateCopyResponse,
+} from '../api/template/template.type.mjs';
diff --git a/packages/cli/types/theme.d.ts b/packages/cli/types/theme.d.ts
index 416d976321..cdc74dd0ad 100644
--- a/packages/cli/types/theme.d.ts
+++ b/packages/cli/types/theme.d.ts
@@ -1,53 +1,17 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Theme build command JSON responses.
+ * @file Public re-export of the `theme` command's types.
*
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json theme build <file> -> theme.build
- * xds --json theme list -> theme.list
- * xds --json theme add <slug> -> theme.add
- * (file not found / parse error) -> CLIError
+ * The source of truth is colocated with the API leaves in
+ * `api/theme/theme.type.mjs` (functions own their types). This file keeps the
+ * `./types/theme` consumers (and the `@astryxdesign/cli` `./json` surface)
+ * resolving the same type names without duplicating the shapes.
*/
-/** xds --json theme build <file> */
-export interface ThemeBuildResponse {
- type: 'theme.build';
- data: {
- name: string;
- tokenCount: number;
- componentCount: number;
- sizeKB: number;
- outputs: {css: string; js: string; dts: string; variantsDts?: string};
- warnings: string[];
- };
-}
-
-/** A single theme entry as surfaced by `theme list`. */
-export interface ThemeListEntry {
- slug: string;
- displayName: string;
- description: string;
- maintained: boolean;
-}
-
-/** xds --json theme list */
-export interface ThemeListResponse {
- type: 'theme.list';
- data: ThemeListEntry[];
-}
-
-/** xds --json theme add <slug> */
-export interface ThemeAddResponse {
- type: 'theme.add';
- data: {
- slug: string;
- displayName: string;
- maintained: boolean;
- outputDir: string;
- entry: string;
- exportName: string;
- files: string[];
- };
-}
+export type {
+ ThemeBuildResponse,
+ ThemeListEntry,
+ ThemeListResponse,
+ ThemeAddResponse,
+} from '../api/theme/theme.type.mjs';
diff --git a/packages/cli/types/upgrade.d.ts b/packages/cli/types/upgrade.d.ts
index b1ba9eaf90..eba82043bc 100644
--- a/packages/cli/types/upgrade.d.ts
+++ b/packages/cli/types/upgrade.d.ts
@@ -1,108 +1,13 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-/**
- * Upgrade command JSON responses.
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json upgrade --list -> upgrade.list
- * xds --json upgrade [--apply] -> upgrade.run
- * xds --json upgrade (status short-circuit) -> upgrade.status
- * (version detection failure) -> CLIError
- */
-
-/** xds --json upgrade --list */
-export interface UpgradeListResponse {
- type: 'upgrade.list';
- data: UpgradeListEntry[];
-}
-
-export interface UpgradeListEntry {
- name: string;
- title: string;
- version: string;
-}
-
-/**
- * State of the managed agent-docs block (`<!-- ASTRYX:START --> … END -->`)
- * relative to the installed core version, plus what `upgrade` did about it.
- * Present on every upgrade response (run, status, and the codemod/config error
- * envelopes) because the block is refreshed independently of codemods.
- *
- * - `refreshed` — a stale block was rewritten (`--apply` only).
- * - `would-refresh` — a stale block was detected in dry-run; nothing written.
- * - `nudge-init` — no managed block exists; user should run `init`.
- * - `error` — refresh was attempted but writing failed.
- * - `none` — nothing to do (block already current).
- */
-export interface AgentDocsSummary {
- status: 'missing' | 'stale' | 'current';
- /** Installed core version the block should reflect. */
- installedVersion: string;
- /** Distinct stale block versions found (the "from" side of the refresh). */
- fromVersions: string[];
- /** Files rewritten (apply) or that would be rewritten (dry-run). */
- files: string[];
- /** True only when a block was actually rewritten (apply mode). */
- refreshed: boolean;
- action: 'refreshed' | 'would-refresh' | 'nudge-init' | 'error' | 'none';
-}
-
-/** xds --json upgrade [--apply] */
-export interface UpgradeRunResponse {
- type: 'upgrade.run';
- data: {
- from: string;
- to: string;
- codemods: number;
- /** Integration packages processed in this upgrade (by name/spec). */
- integrations: string[];
- agentDocsRefreshed: boolean;
- agentDocs: AgentDocsSummary;
- /** Total files changed across core + integration codemods (apply mode). */
- filesChanged?: number;
- /** Total transforms that reported a change. */
- transformsApplied?: number;
- /** Per-codemod errors, when any codemod failed. */
- errors?: Array<{file: string; codemod: string; error: string}>;
- };
-}
-
-/**
- * xds --json upgrade — short-circuit status results.
- *
- * - `up_to_date`: `--from` is >= installed target and `--force` was not passed.
- * - `no_codemods`: no codemods (core or integration) apply to the range.
- * - `config_fixable`: DRY-RUN ONLY. The consumer's astryx.config currently
- * fails strict validation, but a pending core CONFIG codemod (in the selected
- * range) would repair it. The dry run previews the fix without writing and
- * reports the exact command to apply it; integrations are skipped for the
- * preview (they will be processed on the `--apply` run).
- */
-export interface UpgradeStatusResponse {
- type: 'upgrade.status';
- data:
- | {
- status: 'up_to_date';
- from: string;
- to: string;
- agentDocs: AgentDocsSummary;
- }
- | {
- status: 'no_codemods';
- from: string;
- to: string;
- agentDocs: AgentDocsSummary;
- }
- | {
- status: 'config_fixable';
- from: string;
- to: string;
- configError: string;
- configCodemods: string[];
- suggestedCommand: string;
- message: string;
- note: string;
- agentDocs: AgentDocsSummary;
- };
-}
+// Types for the `upgrade` command now live next to their API as the source of
+// truth. This module re-exports them so `types/upgrade` stays a stable import.
+// Edit shapes/descriptions in `../api/upgrade/upgrade.type.mjs`, not here.
+
+export type {
+ UpgradeListResponse,
+ UpgradeListEntry,
+ AgentDocsSummary,
+ UpgradeRunResponse,
+ UpgradeStatusResponse,
+} from '../api/upgrade/upgrade.type.mjs';
diff --git a/packages/cli/types/validate-integration.d.ts b/packages/cli/types/validate-integration.d.ts
index 664840317b..ed6e3b69f1 100644
--- a/packages/cli/types/validate-integration.d.ts
+++ b/packages/cli/types/validate-integration.d.ts
@@ -1,24 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * validate-integration command JSON responses.
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------
- * astryx --json validate-integration -> integration.validate
- * astryx --json validate-integration <pkg> -> integration.validate
+ * @file Public re-export of the `validate-integration` command's types. Source of
+ * truth is colocated in api/integration/validate-integration.type.mjs;
+ * `AstryxIntegrationIssue` stays shared in types/integration.d.ts.
*/
-import type {AstryxIntegrationIssue} from './integration';
-
-/** astryx --json validate-integration [package] */
-export interface ValidateIntegrationResponse {
- type: 'integration.validate';
- data: {
- /** Integration package name, or null when no manifest was located. */
- name: string | null;
- /** Integration package version, or null when unavailable. */
- version: string | null;
- issues: AstryxIntegrationIssue[];
- };
-}
+export type {
+ ValidateIntegrationOptions,
+ ValidateIntegrationResponse,
+} from '../api/integration/validate-integration.type.mjs';