Skip to content

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

TypeScript

Astryx config + integration API (#3280)

EJ Hammond39ed50d2dcaa
diff --git a/.changeset/component-ownership.md b/.changeset/component-ownership.md
new file mode 100644
index 0000000000..4b693e48a9
--- /dev/null
+++ b/.changeset/component-ownership.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Component discovery is now package-ownership aware: --package scoping, source resolution for integration components, and package-qualified JSON listings.
+
+@ejhammond
diff --git a/.changeset/config-integration-foundation.md b/.changeset/config-integration-foundation.md
new file mode 100644
index 0000000000..0f5032bad1
--- /dev/null
+++ b/.changeset/config-integration-foundation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Strict config + integration v1 schema (integrations, issuesUrl, hooks.postCodemod) and new @astryxdesign/cli/integration export.
+
+@ejhammond
diff --git a/.changeset/dedupe-jiti-loaders.md b/.changeset/dedupe-jiti-loaders.md
new file mode 100644
index 0000000000..828f9f6410
--- /dev/null
+++ b/.changeset/dedupe-jiti-loaders.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[chore] Integration codemod and template-doc loading now use the shared module-loader util instead of duplicating the jiti/import logic.
+
+@ejhammond
diff --git a/.changeset/error-codes-drift.md b/.changeset/error-codes-drift.md
new file mode 100644
index 0000000000..4d8aedba8b
--- /dev/null
+++ b/.changeset/error-codes-drift.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Align the CLI error-code type declarations with the runtime error codes (add the missing ERR_AMBIGUOUS_TEMPLATE declaration).
+
+@ejhammond
diff --git a/.changeset/file-based-codemods.md b/.changeset/file-based-codemods.md
new file mode 100644
index 0000000000..954cd0931f
--- /dev/null
+++ b/.changeset/file-based-codemods.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] File-based codemod API (createCodemod/createConfigCodemod) with the @astryxdesign/cli/codemod export and integration codemod discovery in upgrade.
+
+@ejhammond
diff --git a/.changeset/fix-parity-harness-component-shape.md b/.changeset/fix-parity-harness-component-shape.md
new file mode 100644
index 0000000000..b053f8e0a4
--- /dev/null
+++ b/.changeset/fix-parity-harness-component-shape.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Update the API/CLI parity harness for the package-qualified `component --list` shape, and make the component API reject a non-string name with a clean error instead of throwing.
+
+@ejhammond
diff --git a/.changeset/integration-issue-warning.md b/.changeset/integration-issue-warning.md
new file mode 100644
index 0000000000..a6a707b385
--- /dev/null
+++ b/.changeset/integration-issue-warning.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] component, template, and upgrade now print a one-line non-blocking warning when a configured integration has validation issues, pointing to validate-integration.
+
+@ejhammond
diff --git a/.changeset/migrate-layout-components.md b/.changeset/migrate-layout-components.md
new file mode 100644
index 0000000000..1ae7b164a9
--- /dev/null
+++ b/.changeset/migrate-layout-components.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Add a v0.1.3 config codemod that migrates astryx.config layout.components to experimental.xle.components.
+
+@ejhammond
diff --git a/.changeset/module-loader-extract.md b/.changeset/module-loader-extract.md
new file mode 100644
index 0000000000..0b189377b4
--- /dev/null
+++ b/.changeset/module-loader-extract.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[chore] Extract the shared module-loading + conventional-file-discovery helpers used by config and integration loading into one internal util (no behavior change).
+
+@ejhammond
diff --git a/.changeset/project-config-api.md b/.changeset/project-config-api.md
new file mode 100644
index 0000000000..0eeb326485
--- /dev/null
+++ b/.changeset/project-config-api.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Introduce the Project configuration API as the single entry point for reading resolved project config, components, templates, codemods, and issue routing, replacing loadConfig. Misconfigured integrations are now skipped with a warning during upgrade instead of hard-failing, and a new --skip-codemod flag lets you re-run past a failed codemod.
+
+@ejhammond
diff --git a/.changeset/remove-gap-report.md b/.changeset/remove-gap-report.md
new file mode 100644
index 0000000000..1f5ef821c5
--- /dev/null
+++ b/.changeset/remove-gap-report.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[chore] Remove the standalone gap-report command. Swizzle now prints a short maintainer feedback link instead of filing issues.
+
+@ejhammond
diff --git a/.changeset/static-template-api.md b/.changeset/static-template-api.md
new file mode 100644
index 0000000000..672ceb255b
--- /dev/null
+++ b/.changeset/static-template-api.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Static template authoring API (createPageTemplate/createBlockTemplate) with the @astryxdesign/cli/template export and type-driven, package-scoped template discovery.
+
+@ejhammond
diff --git a/.changeset/swizzle-integration-routing.md b/.changeset/swizzle-integration-routing.md
new file mode 100644
index 0000000000..ca2c405e44
--- /dev/null
+++ b/.changeset/swizzle-integration-routing.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Swizzle can now copy integration-owned components, rewrites escaping imports to the owning package, and routes maintainer feedback through config and integration issue URLs.
+
+@ejhammond
diff --git a/.changeset/unified-module-loading.md b/.changeset/unified-module-loading.md
new file mode 100644
index 0000000000..1a53cd341f
--- /dev/null
+++ b/.changeset/unified-module-loading.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[refactor] Load and validate user-authored config, integration, codemod, and template modules through one shared module loader; create\* factories are now type-only and validation happens at load.
+
+@ejhammond
diff --git a/.changeset/unify-config-codemod-runner.md b/.changeset/unify-config-codemod-runner.md
new file mode 100644
index 0000000000..4540f7eddd
--- /dev/null
+++ b/.changeset/unify-config-codemod-runner.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[chore] Remove the obsolete xds config-surface migration codemod and unify config codemod execution on the shared (file, api) runner used by integration codemods.
+
+@ejhammond
diff --git a/.changeset/upgrade-config-codemod-ordering.md b/.changeset/upgrade-config-codemod-ordering.md
new file mode 100644
index 0000000000..e1ceef7eb8
--- /dev/null
+++ b/.changeset/upgrade-config-codemod-ordering.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] upgrade now runs core codemods before loading config, so a config codemod can repair an otherwise-invalid config; dry-run reports a fixable config and suggests the command to apply it.
+
+@ejhammond
diff --git a/.changeset/validate-integration.md b/.changeset/validate-integration.md
new file mode 100644
index 0000000000..335826c16e
--- /dev/null
+++ b/.changeset/validate-integration.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Add the validate-integration command and integration issue model for checking an Astryx integration package's manifest and contributions.
+
+@ejhammond
diff --git a/.changeset/xle-experimental-components.md b/.changeset/xle-experimental-components.md
new file mode 100644
index 0000000000..5a0dee0cc3
--- /dev/null
+++ b/.changeset/xle-experimental-components.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] XLE app-component registration moved into validated config under experimental.xle.components (object form), replacing the unvalidated layout.components read.
+
+@ejhammond
diff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjs
index f1fbe5c8f5..e4f8bc0a18 100644
--- a/.github/scripts/api-cli-parity-test.mjs
+++ b/.github/scripts/api-cli-parity-test.mjs
@@ -76,8 +76,13 @@ console.log('Discovering...');
const api = await import('../../packages/cli/src/api/index.mjs');
const componentList = cliJson(['component', '--list']);
+// `component --list` data is package-qualified: each group value is an array
+// of { name, package } objects. Map to bare names for the per-component cases.
+// (Tolerate plain strings too, in case the shape is ever simplified.)
const allComponents = componentList.data && !componentList.error
- ? Object.values(componentList.data).flat()
+ ? Object.values(componentList.data)
+ .flat()
+ .map(c => (typeof c === 'string' ? c : c.name))
: [];
const docsList = cliJson(['docs']);
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 4c7d184e5b..ae073e8f6d 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -43,6 +43,18 @@
"types": "./src/types/config.d.ts",
"import": "./src/config.mjs"
},
+ "./integration": {
+ "types": "./src/types/integration.d.ts",
+ "import": "./src/integration.mjs"
+ },
+ "./template": {
+ "types": "./src/types/template-api.d.ts",
+ "import": "./src/template.mjs"
+ },
+ "./codemod": {
+ "types": "./src/types/codemod.d.ts",
+ "import": "./src/codemod.mjs"
+ },
"./xle": {
"types": "./src/lib/xle/browser.d.ts",
"import": "./src/lib/xle/browser.mjs"
diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjs
index a31ab438a6..c6560ea444 100644
--- a/packages/cli/src/api/component.mjs
+++ b/packages/cli/src/api/component.mjs
@@ -11,18 +11,48 @@ import * as fs from 'node:fs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
import {findCoreDir, discoverExternalPackages} from '../utils/paths.mjs';
import {
+ CORE_PACKAGE,
discoverComponents,
discoverExternalComponentsGrouped,
+ discoverIntegrationComponents,
findComponentReadme,
findComponentSource,
findExternalComponentDoc,
+ findIntegrationComponentDoc,
+ findIntegrationComponentSource,
resolveImportPath,
} from '../lib/component-discovery.mjs';
+import {Project} from '../lib/project.mjs';
import {loadDocs} from '../lib/component-loader.mjs';
import {searchComponents} from '../lib/string-utils.mjs';
import {AstryxError} from './error.mjs';
import {findShowcase, findRelatedBlocks} from './template.mjs';
+/**
+ * Load the configured integrations for `cwd`, swallowing any config errors so
+ * component discovery never hard-fails on a malformed/absent integration. An
+ * empty list means "core only".
+ * @param {string} cwd
+ * @returns {Promise<Array<{name: string, components?: string, issuesUrl?: string}>>}
+ */
+async function loadIntegrationsSafely(cwd) {
+ try {
+ const project = await Project.load(cwd);
+ return project.loadedIntegrations;
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Resolve a loaded integration by package name.
+ * @param {Array<{name: string}>} loadedIntegrations
+ * @param {string} packageName
+ */
+function findLoadedIntegration(loadedIntegrations, packageName) {
+ return loadedIntegrations.find(i => i.name === packageName) ?? null;
+}
+
/**
* Resolve an external package by name from the discovered externals list.
* @param {string} packageName - e.g. '@acme/xds-widgets'
@@ -131,8 +161,13 @@ export async function component(name, options = {}) {
return {type: 'component.full', data: {[match[0]]: entries}};
}
- // Default: brief — names only
- return {type: 'component.list', data: {[match[0]]: match[1]}};
+ // Default: brief — package-qualified object list for the category.
+ // Pre-1.0 JSON contract: members are {name, package} objects, not bare
+ // strings, so consumers can disambiguate ownership.
+ return {
+ type: 'component.list',
+ data: {[match[0]]: match[1].map(n => ({name: n, package: CORE_PACKAGE}))},
+ };
}
// All components — merge core + external packages with grouped subcategories
@@ -179,43 +214,189 @@ export async function component(name, options = {}) {
return {type: 'component.full', data: result};
}
- // Default: brief — names only (with externals merged in)
+ // Default: brief — package-qualified object list (core + integrations).
+ // Pre-1.0 JSON contract: each group's members are {name, package} objects.
+ /** @type {Record<string, Array<{name: string, package: string}>>} */
+ const listData = {};
+ for (const [cat, comps] of Object.entries(components)) {
+ listData[cat] = comps.map(n => ({name: n, package: CORE_PACKAGE}));
+ }
+
+ // Integration components (authoritative source: loadedIntegrations).
+ const loadedIntegrations = await loadIntegrationsSafely(cwd);
+ const seenIntegration = new Set();
+ for (const integration of loadedIntegrations) {
+ seenIntegration.add(integration.name);
+ const owned = discoverIntegrationComponents(integration);
+ // Group integration components by their doc `group`, falling back to the
+ // package name. Keys are package-qualified so they never collide with
+ // core groups or each other.
+ /** @type {Map<string, Array<{name: string, package: string}>>} */
+ const byGroup = new Map();
+ for (const rec of owned) {
+ const groupLabel = rec.group ?? integration.name;
+ const key = `${groupLabel} (${integration.name})`;
+ if (!byGroup.has(key)) byGroup.set(key, []);
+ byGroup.get(key).push({name: rec.name, package: integration.name});
+ }
+ for (const [key, members] of byGroup) {
+ members.sort((a, b) => a.name.localeCompare(b.name));
+ listData[key] = members;
+ }
+ }
+
+ // Back-compat: node_modules-scanned external packages (pkg.astryx.docs)
+ // that are NOT configured integrations. Preserves existing discovery for
+ // consumers that haven't adopted the config-integration flow.
const externals = discoverExternalPackages(cwd);
for (const ext of externals) {
+ if (seenIntegration.has(ext.name)) continue;
const grouped = discoverExternalComponentsGrouped(ext.docsDir);
const groupKeys = Object.keys(grouped);
if (groupKeys.length === 0) continue;
- // If the package has subcategories (groups), emit each as a separate key.
- // If no groups exist, fall back to the flat list under one key.
const hasGroups = groupKeys.some(
k => grouped[k].length > 1 || grouped[k][0] !== k,
);
if (hasGroups) {
for (const [group, members] of Object.entries(grouped)) {
- components[`${group} (${ext.name})`] = members;
+ listData[`${group} (${ext.name})`] = members.map(n => ({
+ name: n,
+ package: ext.name,
+ }));
}
} else {
- // All ungrouped — single flat list under the package category
const allComps = Object.values(grouped).flat().sort();
if (allComps.length > 0) {
- components[`${ext.category} (${ext.name})`] = allComps;
+ listData[`${ext.category} (${ext.name})`] = allComps.map(n => ({
+ name: n,
+ package: ext.name,
+ }));
}
}
}
- return {type: 'component.list', data: components};
+ return {type: 'component.list', data: listData};
}
// ── Single component ───────────────────────────────────────────
+ if (typeof name !== 'string') {
+ throw new AstryxError(
+ `No component named "${String(name)}"`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+
const dirName = name.replace(/^XDS/, '');
+ // Ownership-aware resolution. Build the set of OWNER packages that provide a
+ // component with this name across core + every loaded integration. This is
+ // what lets the CLI disambiguate by package and expose the owner's source +
+ // issuesUrl (the inputs the future integration-component swizzle needs).
+ const loadedIntegrations = await loadIntegrationsSafely(cwd);
+ const coreDocPath = findComponentReadme(coreDir, dirName);
+ /**
+ * @type {Array<{
+ * package: string,
+ * docPath: string,
+ * sourcePath: string|null,
+ * issuesUrl: string|undefined,
+ * integration: object|null,
+ * }>}
+ */
+ const owners = [];
+ if (coreDocPath) {
+ owners.push({
+ package: CORE_PACKAGE,
+ docPath: coreDocPath,
+ sourcePath: findComponentSource(coreDir, dirName),
+ issuesUrl: undefined,
+ integration: null,
+ });
+ }
+ for (const integration of loadedIntegrations) {
+ const docPath = findIntegrationComponentDoc(integration, dirName);
+ if (!docPath) continue;
+ owners.push({
+ package: integration.name,
+ docPath,
+ sourcePath: findIntegrationComponentSource(integration, dirName),
+ issuesUrl: integration.issuesUrl,
+ integration,
+ });
+ }
+
+ /**
+ * Augment a loaded `component.detail` doc with ownership metadata. Adds
+ * `package`, the resolved `import` specifier, and `sourceAvailable` (whether
+ * a swizzleable source file exists for the owner). Existing doc fields
+ * (name, usage, props, …) are preserved.
+ * @param {object} docs
+ * @param {{package: string, sourcePath: string|null}} owner
+ * @param {string} componentName
+ */
+ function withOwnership(docs, owner, componentName) {
+ const importSpec =
+ owner.package === CORE_PACKAGE
+ ? resolveImportPath(coreDir, componentName)
+ : `${owner.package}/${componentName}`;
+ return {
+ ...docs,
+ package: owner.package,
+ import: importSpec,
+ sourceAvailable: owner.sourcePath != null,
+ };
+ }
+
// When scoped to a specific package, search that package first.
// This is critical for components that exist in both core and an external
// package (e.g. AppShell, Button, SideNav) — the package scope ensures
// the external package's docs are returned, not core's.
if (packageScope) {
+ // Core scope: resolve from core directly.
+ if (packageScope === CORE_PACKAGE) {
+ const owner = owners.find(o => o.package === CORE_PACKAGE);
+ if (!owner) {
+ throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
+ }
+ if (source) {
+ if (!owner.sourcePath) {
+ throw new AstryxError(`Source for "${name}" not found`, undefined, ERROR_CODES.ERR_NO_SOURCE);
+ }
+ return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};
+ }
+ const docs = await loadDocs(owner.docPath, {zh, dense, lang});
+ if (props) {
+ const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
+ return {type: 'component.detail.props', data: p};
+ }
+ return {type: 'component.detail', data: withOwnership(docs, owner, dirName)};
+ }
+
+ // Integration scope (authoritative): resolve from the loaded integration.
+ const integration = findLoadedIntegration(loadedIntegrations, packageScope);
+ if (integration) {
+ const owner = owners.find(o => o.package === packageScope);
+ if (!owner) {
+ throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
+ }
+ if (source) {
+ if (!owner.sourcePath) {
+ throw new AstryxError(`Source for "${name}" not found in package "${packageScope}"`, undefined, ERROR_CODES.ERR_NO_SOURCE);
+ }
+ return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};
+ }
+ const docs = await loadDocs(owner.docPath, {zh, dense, lang});
+ if (props) {
+ const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
+ return {type: 'component.detail.props', data: p};
+ }
+ return {type: 'component.detail', data: withOwnership(docs, owner, dirName)};
+ }
+
+ // Legacy fallback: node_modules `pkg.astryx.docs` external package.
const ext = resolveExternalPackage(packageScope, cwd);
if (!ext) {
throw new AstryxError(`External package "${packageScope}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);
@@ -244,11 +425,49 @@ export async function component(name, options = {}) {
const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
return {type: 'component.detail.props', data: p};
}
- return {type: 'component.detail', data: docs};
+ return {
+ type: 'component.detail',
+ data: withOwnership(docs, {package: ext.name, sourcePath: null}, dirName),
+ };
}
throw new AstryxError(`No component "${name}" in package "${packageScope}"`, undefined, ERROR_CODES.ERR_UNKNOWN_COMPONENT);
}
+ // Ambiguity: when the name is owned by MORE THAN ONE package (core and/or
+ // integrations) and the caller did not scope with --package, refuse to guess.
+ // NOTE: legacy `pkg.astryx.docs` externals are intentionally NOT part of this
+ // ambiguity set — they retain their historical core-first fallback below so
+ // existing consumers (and tests) keep working. Only config-driven integration
+ // ownership participates here.
+ if (owners.length > 1) {
+ throw new AstryxError(
+ `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
+ owners.map(o => ({name: o.package, reason: 'provides this component'})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+
+ // Single non-core owner (an integration provides it, core does not) — resolve
+ // from that integration so the integration component is authoritative.
+ if (owners.length === 1 && owners[0].package !== CORE_PACKAGE) {
+ const owner = owners[0];
+ if (source) {
+ if (!owner.sourcePath) {
+ throw new AstryxError(`Source for "${name}" not found`, undefined, ERROR_CODES.ERR_NO_SOURCE);
+ }
+ return {type: 'component.detail.source', data: {component: dirName, source: fs.readFileSync(owner.sourcePath, 'utf-8')}};
+ }
+ if (showcase) {
+ throw new AstryxError(`No showcase found for "${name}"`, undefined, ERROR_CODES.ERR_NO_SHOWCASE);
+ }
+ const docs = await loadDocs(owner.docPath, {zh, dense, lang});
+ if (props) {
+ const p = docs.props || (docs.components ? docs.components.flatMap(c => c.props || []) : []);
+ return {type: 'component.detail.props', data: p};
+ }
+ return {type: 'component.detail', data: withOwnership(docs, owner, dirName)};
+ }
+
if (source) {
const sourcePath = findComponentSource(coreDir, dirName);
if (!sourcePath) {
@@ -274,6 +493,10 @@ export async function component(name, options = {}) {
let readmePath = findComponentReadme(coreDir, dirName);
let resolvedName = dirName;
+ // Track the resolving owner so the detail payload can carry ownership info.
+ // Defaults to core; the legacy-external fallback below may reassign it.
+ let resolvedOwnerPackage = CORE_PACKAGE;
+ let resolvedSourcePath = readmePath ? findComponentSource(coreDir, dirName) : null;
if (!readmePath) {
const externals = discoverExternalPackages(cwd);
@@ -281,6 +504,8 @@ export async function component(name, options = {}) {
const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);
if (extDocPath) {
readmePath = extDocPath;
+ resolvedOwnerPackage = ext.name;
+ resolvedSourcePath = null;
break;
}
}
@@ -299,6 +524,8 @@ export async function component(name, options = {}) {
if (topScore >= 90 && topTied.length === 1 && gap >= 20) {
resolvedName = topTied[0].name;
readmePath = findComponentReadme(coreDir, resolvedName);
+ resolvedOwnerPackage = CORE_PACKAGE;
+ resolvedSourcePath = findComponentSource(coreDir, resolvedName);
} else {
const threshold = Math.max(topScore - 20, 1);
const candidates = results.filter(r => r.score >= threshold).slice(0, 5);
@@ -382,7 +609,14 @@ export async function component(name, options = {}) {
if (props) {
return {type: 'component.detail.props', data: matchingComponent.props || []};
}
- return {type: 'component.detail', data: scoped};
+ return {
+ type: 'component.detail',
+ data: withOwnership(
+ scoped,
+ {package: resolvedOwnerPackage, sourcePath: resolvedSourcePath},
+ dirName,
+ ),
+ };
}
if (props) {
@@ -390,5 +624,12 @@ export async function component(name, options = {}) {
return {type: 'component.detail.props', data: p};
}
- return {type: 'component.detail', data: docs};
+ return {
+ type: 'component.detail',
+ data: withOwnership(
+ docs,
+ {package: resolvedOwnerPackage, sourcePath: resolvedSourcePath},
+ resolvedName,
+ ),
+ };
}
diff --git a/packages/cli/src/api/discover.mjs b/packages/cli/src/api/discover.mjs
index 65ccbace15..70399b1326 100644
--- a/packages/cli/src/api/discover.mjs
+++ b/packages/cli/src/api/discover.mjs
@@ -4,7 +4,7 @@
* @file Programmatic API for the discover command.
*/
-import {loadConfig} from '../lib/config.mjs';
+import {Project} from '../lib/project.mjs';
import {
scanAllPackages,
findComponentInPackages,
@@ -40,7 +40,7 @@ function validateDocs(docs) {
*/
export async function discover(query, options = {}) {
const {lang = null, zh = false} = options;
- const config = await loadConfig();
+ const project = await Project.load();
const toEntry = pkg => ({
name: pkg.name,
category: pkg.category,
@@ -50,14 +50,21 @@ export async function discover(query, options = {}) {
displayName: pkg.displayName,
});
- const explicitPackages = (config.loadedIntegrations ?? [])
- .map(integration => integration.package)
- .filter(Boolean);
- if (config.packages.length === 0 && explicitPackages.length === 0) {
+ // External packages come from configured integrations that declare a
+ // components root. Each becomes a scannable package keyed by its docsDir.
+ const explicitPackages = project.loadedIntegrations
+ .filter(integration => integration.components)
+ .map(integration => ({
+ name: integration.name,
+ version: integration.version,
+ category: integration.name,
+ docsDir: integration.components,
+ }));
+ if (explicitPackages.length === 0) {
return {type: 'discover.list', data: [], meta: {configured: false}};
}
- const packages = scanAllPackages(config.packages, explicitPackages);
+ const packages = scanAllPackages([], explicitPackages);
if (packages.length === 0) {
return {type: 'discover.list', data: [], meta: {configured: true}};
diff --git a/packages/cli/src/api/doctor.mjs b/packages/cli/src/api/doctor.mjs
index daa61e104b..687a4e77cc 100644
--- a/packages/cli/src/api/doctor.mjs
+++ b/packages/cli/src/api/doctor.mjs
@@ -27,7 +27,7 @@ import {createRequire} from 'node:module';
import {MIN_NODE_VERSION, isNodeVersionSupported} from '../lib/node-version.mjs';
import {CLI_ROOT, findCoreDir} from '../utils/paths.mjs';
import {detectPackageManager} from '../utils/package-manager.mjs';
-import {findConfigPath, loadConfig} from '../lib/config.mjs';
+import {findConfigPath, Project} from '../lib/project.mjs';
import {semverCompare} from '../utils/semver.mjs';
const _require = createRequire(import.meta.url);
@@ -279,8 +279,9 @@ export async function checkConfig(ctx) {
};
}
- // loadConfig swallows errors and returns defaults, so re-import directly to
- // surface a genuine load failure as a FAIL.
+ // Project.load swallows nothing — it surfaces a genuine load failure — but
+ // the config check wants to report a bad default export precisely, so we
+ // re-import directly to surface a genuine load failure as a FAIL.
try {
const {pathToFileURL} = await import('node:url');
const mod = await import(pathToFileURL(ctx.configPath).href);
@@ -291,25 +292,9 @@ export async function checkConfig(ctx) {
label: 'astryx.config.mjs',
status: 'fail',
message: `astryx.config.mjs default export is not an object (got ${typeof config}).`,
- fix: 'Export a default object from astryx.config.mjs, e.g. `export default { theme: "default" };`.',
+ fix: 'Export a default object from astryx.config.mjs, e.g. `export default { integrations: [] };`.',
};
}
- // Validate that `packages`, if present, is a string or array of strings.
- if (config?.packages !== undefined) {
- const arr = Array.isArray(config.packages)
- ? config.packages
- : [config.packages];
- const bad = arr.some(p => typeof p !== 'string');
- if (bad) {
- return {
- id: 'config',
- label: 'astryx.config.mjs',
- status: 'fail',
- message: 'astryx.config.mjs `packages` must be a string or array of strings.',
- fix: 'Set `packages` to a path string or array of path strings.',
- };
- }
- }
return {
id: 'config',
label: 'astryx.config.mjs',
@@ -493,8 +478,8 @@ export async function runChecks(options = {}) {
// Resolve a possible theme key from config (best-effort; never throws).
let configTheme = null;
try {
- const loaded = await loadConfig(cwd);
- configTheme = loaded?.theme ?? null;
+ const project = await Project.load(cwd);
+ configTheme = project.config?.theme ?? null;
} catch {
// Best-effort: a missing/invalid config leaves configTheme null.
}
diff --git a/packages/cli/src/api/layout.mjs b/packages/cli/src/api/layout.mjs
index aeed02d61a..5a29f7c952 100644
--- a/packages/cli/src/api/layout.mjs
+++ b/packages/cli/src/api/layout.mjs
@@ -25,13 +25,14 @@ import {expand} from '../lib/xle/expand.mjs';
import {toCompact, toOutline} from '../lib/xle/print.mjs';
import {buildRegistry, ALIAS_TABLE} from '../lib/xle/registry.mjs';
import {discoverTemplates, stripTemplateAssetRefs} from './template.mjs';
-import {loadConfig} from '../lib/config.mjs';
+import {Project} from '../lib/project.mjs';
/**
* The catalog a `{hint}` can resolve to: template blocks (spliced inline) plus
- * any app-registered local components from astryx.config.mjs `layout.components`
- * (imported by name). App components are how XLE reaches domain pieces — the
- * KpiCard/chart/drawer set that the @astryxdesign/core registry can't see.
+ * any app-registered local components from astryx.config.mjs
+ * `experimental.xle.components` (imported by name). App components are how XLE
+ * reaches domain pieces — the KpiCard/chart/drawer set that the
+ * @astryxdesign/core registry can't see.
*/
async function loadBlocks(cwd) {
const blocks = [];
@@ -42,20 +43,20 @@ async function loadBlocks(cwd) {
// discovery is best-effort
}
try {
- const config = await loadConfig(cwd);
- const components = config.layout?.components || {};
+ const project = await Project.load(cwd);
+ const components = project.config.experimental?.xle?.components ?? {};
for (const [name, spec] of Object.entries(components)) {
- const importPath = typeof spec === 'string' ? spec : spec.from;
+ const importPath = spec.from;
if (!importPath) continue;
blocks.push({
type: 'block',
kind: 'component',
dirName: name,
name,
- description: typeof spec === 'object' ? spec.description || '' : '',
+ description: spec.description ?? '',
category: 'app',
importPath,
- isDefault: typeof spec === 'object' ? Boolean(spec.default) : false,
+ isDefault: Boolean(spec.default),
});
}
} catch {
@@ -281,7 +282,7 @@ TEMPLATE REFERENCING ({hint} pulls in real content — this is how XLE reaches
{kpi-card} standalone reference (no wrapper element) — place a component directly
{kpi-card}*4 repeat a reference; the definition/import is emitted once
app components register local ones in astryx.config.mjs to import them by name:
- export default {layout: {components: {KpiCard: '@/components/KpiCard'}}}
+ export default {experimental: {xle: {components: {KpiCard: {from: '@/components/KpiCard'}}}}}
then {kpi-card} → import {KpiCard} + <KpiCard /> (kebab ↔ Pascal)
STRUCTURE THE EXPANDER HANDLES
diff --git a/packages/cli/src/api/layout.test.mjs b/packages/cli/src/api/layout.test.mjs
index 81d900a75c..297dca5689 100644
--- a/packages/cli/src/api/layout.test.mjs
+++ b/packages/cli/src/api/layout.test.mjs
@@ -196,11 +196,14 @@ describe('template referencing', () => {
it('imports app-registered local components (the local-component bridge)', async () => {
// Inside the workspace so @astryxdesign/core resolves; cleaned up after.
+ // A package.json beside the config makes Project.load resolve it as the
+ // sibling-of-nearest-package.json (the standard config resolution).
const cwd = mkdtempSync(join(process.cwd(), '.xle-imp-test-'));
try {
+ writeFileSync(join(cwd, 'package.json'), '{"name": "xle-imp-fixture"}\n');
writeFileSync(
join(cwd, 'astryx.config.mjs'),
- `export default {layout: {components: {KpiCard: '@/components/KpiCard', TimeRangePicker: {from: '@/components/TimeRangePicker'}}}};\n`,
+ `export default {experimental: {xle: {components: {KpiCard: {from: '@/components/KpiCard'}, TimeRangePicker: {from: '@/components/TimeRangePicker'}}}}};\n`,
);
const result = await layoutExpand('S[p6] > (G[c4 g4] > {kpi-card}*4) + {time-range-picker}', {
name: 'Demo',
diff --git a/packages/cli/src/api/template-integration.test.mjs b/packages/cli/src/api/template-integration.test.mjs
new file mode 100644
index 0000000000..bc51024ee6
--- /dev/null
+++ b/packages/cli/src/api/template-integration.test.mjs
@@ -0,0 +1,225 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration-provided template discovery (same-stem + type-driven).
+ *
+ * These tests stand up a temp consumer project with an astryx.config and an
+ * installed integration package that contributes templates, then exercise the
+ * public `template()` API to verify discovery, package/type scoping, ambiguity
+ * errors, and copy-to-dir naming.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {template} from './template.mjs';
+
+let tmpDir;
+let originalCwd;
+
+/** Absolute path to the CLI package so integrations can import /template. */
+const CLI_PKG = path.resolve(import.meta.dirname, '..', '..');
+
+function makeConsumer() {
+ const dir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-template-it-'),
+ );
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(dir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets'] };\n`,
+ );
+ return dir;
+}
+
+/**
+ * Install an @acme/widgets integration package that declares a templates root.
+ * @returns the package dir.
+ */
+function installWidgets(consumerDir) {
+ const pkgDir = path.join(consumerDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '2.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default { templates: './templates' };\n`,
+ );
+ fs.mkdirSync(path.join(pkgDir, 'templates'));
+ return pkgDir;
+}
+
+/** Write a template doc + same-stem source under the templates root. */
+function writeTemplate(pkgDir, id, {kind, body, withSource = true}) {
+ const docPath = path.join(pkgDir, 'templates', `${id}.doc.mjs`);
+ fs.mkdirSync(path.dirname(docPath), {recursive: true});
+ const create = kind === 'page' ? 'createPageTemplate' : 'createBlockTemplate';
+ fs.writeFileSync(
+ docPath,
+ body ??
+ `import {${create}} from '${CLI_PKG}/src/template.mjs';\n` +
+ `export default ${create}({name: '${id} name', description: '${id} desc'});\n`,
+ );
+ if (withSource) {
+ fs.writeFileSync(
+ path.join(pkgDir, 'templates', `${id}.tsx`),
+ `export default function ${id.replace(/[^a-zA-Z0-9]/g, '')}() { return null; }\n`,
+ );
+ }
+}
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = makeConsumer();
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('integration template discovery', () => {
+ it('discovers and lists an integration template with package + type', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'pricing', {kind: 'page'});
+
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ expect(result.type).toBe('template.list');
+ const entry = result.data.find(t => t.id === 'pricing');
+ expect(entry).toBeTruthy();
+ expect(entry.type).toBe('page');
+ expect(entry.package).toBe('@acme/widgets');
+ expect(entry.name).toBe('pricing name');
+ expect(entry.description).toBe('pricing desc');
+ });
+
+ it('lists nested-id templates (kebab path under root)', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'marketing/hero', {kind: 'block'});
+
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ const entry = result.data.find(t => t.id === 'marketing/hero');
+ expect(entry).toBeTruthy();
+ expect(entry.type).toBe('block');
+ expect(entry.package).toBe('@acme/widgets');
+ });
+
+ it('always reports core templates under @astryxdesign/core', async () => {
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ const core = result.data.filter(t => t.package === '@astryxdesign/core');
+ expect(core.length).toBeGreaterThan(0);
+ });
+
+ it('--package narrows the listing', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'pricing', {kind: 'page'});
+
+ const result = await template(undefined, {
+ list: true,
+ package: '@acme/widgets',
+ cwd: tmpDir,
+ });
+ expect(result.data.length).toBe(1);
+ expect(result.data[0].id).toBe('pricing');
+ });
+
+ it('skips a template whose same-stem source is missing', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'orphan', {kind: 'page', withSource: false});
+
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ expect(result.data.find(t => t.id === 'orphan')).toBeUndefined();
+ });
+
+ it('skips a raw doc that is missing a type', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'untyped', {
+ kind: 'page',
+ body: `export default {name: 'Untyped', description: 'no type'};\n`,
+ });
+
+ const result = await template(undefined, {list: true, cwd: tmpDir});
+ expect(result.data.find(t => t.id === 'untyped')).toBeUndefined();
+ });
+
+ it('errors with candidates when an id is ambiguous across type/package', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ // Same id "hero" as both a page and a block within the integration.
+ writeTemplate(pkgDir, 'hero', {kind: 'page'});
+ // Add a sibling block doc with the same stem in a different file is not
+ // possible (same file). Instead install a second package with a "hero".
+ const pkg2 = path.join(tmpDir, 'node_modules', '@acme', 'extra');
+ fs.mkdirSync(path.join(pkg2, 'templates'), {recursive: true});
+ fs.writeFileSync(
+ path.join(pkg2, 'package.json'),
+ JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkg2, 'astryx.integration.mjs'),
+ `export default { templates: './templates' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkg2, 'templates', 'hero.doc.mjs'),
+ `import {createBlockTemplate} from '${CLI_PKG}/src/template.mjs';\n` +
+ `export default createBlockTemplate({name: 'Hero block', description: 'b'});\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkg2, 'templates', 'hero.tsx'),
+ `export default function Hero() { return null; }\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
+ );
+
+ await expect(
+ template('hero', {targetPath: './out', cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_AMBIGUOUS_TEMPLATE'});
+ });
+
+ it('--type and --package narrow an ambiguous id to a single match', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'pricing', {kind: 'page'});
+
+ const result = await template('pricing', {
+ type: 'page',
+ package: '@acme/widgets',
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(result.type).toBe('template.show');
+ expect(result.data.type).toBe('page');
+ });
+
+ it('copies a page template into a directory as page.tsx', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'pricing', {kind: 'page'});
+
+ const result = await template('pricing', {
+ targetPath: './dest',
+ cwd: tmpDir,
+ });
+ expect(result.type).toBe('template.copy');
+ expect(result.data.fileName).toBe('page.tsx');
+ expect(fs.existsSync(path.join(tmpDir, 'dest', 'page.tsx'))).toBe(true);
+ });
+
+ it('copies a block template into a directory as <id-basename>.tsx', async () => {
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, 'marketing/hero', {kind: 'block'});
+
+ const result = await template('marketing/hero', {
+ targetPath: './dest',
+ cwd: tmpDir,
+ });
+ expect(result.type).toBe('template.copy');
+ expect(result.data.fileName).toBe('hero.tsx');
+ expect(fs.existsSync(path.join(tmpDir, 'dest', 'hero.tsx'))).toBe(true);
+ });
+});
diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjs
index 69bbc48a5c..fb259bafd7 100644
--- a/packages/cli/src/api/template.mjs
+++ b/packages/cli/src/api/template.mjs
@@ -6,6 +6,8 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {loadModuleWithSchema} from '../lib/module-loader.mjs';
+import {TemplateEnvelopeSchema} from '../template.mjs';
import {CLI_ROOT, discoverExternalPackages} from '../utils/paths.mjs';
import {
assertWithin,
@@ -14,7 +16,28 @@ import {
} from '../utils/path-safety.mjs';
import {AstryxError} from './error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
-import {loadConfig} from '../lib/config.mjs';
+import {Project} from '../lib/project.mjs';
+
+/** Identity used for core (built-in) templates in package-scoped listings. */
+const CORE_PACKAGE = '@astryxdesign/core';
+
+/** Doc-file basename suffixes for integration templates, in precedence order. */
+const DOC_SUFFIXES = ['.doc.ts', '.doc.mjs', '.doc.js'];
+
+/**
+ * Load an integration template doc module and validate it against the template
+ * envelope at the load boundary. Default export only — `.ts` via jiti,
+ * `.mjs`/`.js` via dynamic import. Throws (caught by discovery) if the default
+ * export is missing or fails {@link TemplateEnvelopeSchema}. NOTE: the built-in
+ * core templates use `export const doc = {...}` and are loaded by a different
+ * function ({@link loadDocModule}) — this path is for INTEGRATION templates.
+ *
+ * @param {string} file
+ * @param {string} [label]
+ */
+async function loadIntegrationDoc(file, label) {
+ return loadModuleWithSchema(file, TemplateEnvelopeSchema, {label});
+}
const TEMPLATES_DIR = path.join(CLI_ROOT, 'templates');
const PAGES_DIR = path.join(TEMPLATES_DIR, 'pages');
@@ -140,17 +163,13 @@ async function discoverBlocks() {
}
/**
- * Discover blocks from external packages that declare `xds.blocks`.
- * Same shape as discoverBlocks() output.
+ * Discover blocks from external packages that declare `astryx.blocks` in
+ * their package.json. Same shape as discoverBlocks() output.
*
* @param {string} [cwd]
*/
async function discoverExternalBlocks(cwd = process.cwd()) {
- const config = await loadConfig(cwd);
- const integrationPackages = (config.loadedIntegrations ?? [])
- .map(integration => integration.package)
- .filter(Boolean);
- const externals = [...discoverExternalPackages(cwd), ...integrationPackages];
+ const externals = discoverExternalPackages(cwd);
const blocks = [];
for (const ext of externals) {
@@ -194,12 +213,184 @@ async function discoverAllBlocks(cwd = process.cwd()) {
return [...core, ...external];
}
-async function discoverAll() {
- const [pages, blocks] = await Promise.all([
+async function discoverAll(cwd = process.cwd()) {
+ const [pages, blocks, integration] = await Promise.all([
+ discoverPages(),
+ discoverAllBlocks(cwd),
+ discoverIntegrationTemplates(cwd),
+ ]);
+ return [...pages, ...blocks, ...integration.templates].sort((a, b) =>
+ a.name.localeCompare(b.name),
+ );
+}
+
+/**
+ * Like {@link discoverAll} but also returns integration-template discovery
+ * errors (missing same-stem source, missing `type`, load failure). Use this
+ * when the caller wants to warn about malformed integration templates.
+ *
+ * @param {string} [cwd]
+ * @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}
+ */
+async function discoverAllWithErrors(cwd = process.cwd()) {
+ const [pages, blocks, integration] = await Promise.all([
discoverPages(),
- discoverAllBlocks(),
+ discoverAllBlocks(cwd),
+ discoverIntegrationTemplates(cwd),
]);
- return [...pages, ...blocks].sort((a, b) => a.name.localeCompare(b.name));
+ const templates = [...pages, ...blocks, ...integration.templates].sort(
+ (a, b) => a.name.localeCompare(b.name),
+ );
+ return {templates, errors: integration.errors};
+}
+
+export {discoverAllWithErrors};
+
+/**
+ * Recursively collect integration template doc files under `root`.
+ * Returns absolute paths to files ending in one of DOC_SUFFIXES.
+ *
+ * @param {string} root
+ * @returns {string[]}
+ */
+function findIntegrationDocFiles(root) {
+ const results = [];
+ if (!fs.existsSync(root)) return results;
+ const walk = dir => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full);
+ } else if (DOC_SUFFIXES.some(suffix => entry.name.endsWith(suffix))) {
+ results.push(full);
+ }
+ }
+ };
+ walk(root);
+ return results;
+}
+
+/**
+ * The doc-file suffix present on `file`, or null if none matches.
+ * @param {string} file
+ */
+function matchedDocSuffix(file) {
+ return DOC_SUFFIXES.find(suffix => file.endsWith(suffix)) ?? null;
+}
+
+/**
+ * Discover templates contributed by configured integrations.
+ *
+ * For each integration with a resolved `templates` root, every
+ * `<id>.doc.{ts,mjs,js}` file is a template whose id is its path relative to
+ * the templates root with the `.doc.*` suffix stripped (kebab-case, may be
+ * nested). The doc's `type` (page|block) decides scaffolding — there is no
+ * `/pages` vs `/blocks` requirement. A same-stem sibling source file
+ * (`<id>.tsx`) is required; a doc missing its source, or missing `type`, is
+ * an integration error and that template is skipped (recorded in `errors`).
+ *
+ * @param {string} [cwd]
+ * @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}
+ */
+async function discoverIntegrationTemplates(cwd = process.cwd()) {
+ const templates = [];
+ const errors = [];
+
+ let loadedIntegrations;
+ try {
+ const project = await Project.load(cwd);
+ loadedIntegrations = project.loadedIntegrations;
+ } catch {
+ // Config load failures are surfaced elsewhere (discover/doctor); here we
+ // simply contribute no integration templates.
+ return {templates, errors};
+ }
+
+ for (const integration of loadedIntegrations) {
+ const result = await discoverIntegrationTemplatesForOne(integration);
+ templates.push(...result.templates);
+ errors.push(...result.errors);
+ }
+
+ return {templates, errors};
+}
+
+/**
+ * Discover the templates contributed by a SINGLE integration. Same per-template
+ * rules as {@link discoverIntegrationTemplates} (same-stem source required,
+ * page|block type required); broken templates are recorded in `errors` rather
+ * than thrown. Exposed for `validate-integration`.
+ *
+ * @param {{name?: string, __spec?: string, templates?: string}} integration
+ * @returns {Promise<{templates: object[], errors: {package: string, template?: string, message: string}[]}>}
+ */
+export async function discoverIntegrationTemplatesForOne(integration) {
+ const templates = [];
+ const errors = [];
+
+ const root = integration?.templates;
+ const pkgLabel = integration?.name ?? integration?.__spec ?? 'integration';
+ if (!root || !fs.existsSync(root)) return {templates, errors};
+
+ for (const docPath of findIntegrationDocFiles(root)) {
+ const suffix = matchedDocSuffix(docPath);
+ const id = path
+ .relative(root, docPath)
+ .slice(0, -suffix.length)
+ .split(path.sep)
+ .join('/');
+
+ const sourcePath = docPath.slice(0, -suffix.length) + '.tsx';
+ if (!fs.existsSync(sourcePath)) {
+ errors.push({
+ package: pkgLabel,
+ template: id,
+ message: `Template "${id}" is missing its same-stem source file ${path.basename(sourcePath)}.`,
+ });
+ continue;
+ }
+
+ let doc;
+ try {
+ doc = await loadIntegrationDoc(docPath, `Template "${id}"`);
+ } catch (err) {
+ errors.push({
+ package: pkgLabel,
+ template: id,
+ message: `Template "${id}" failed to load: ${err.message}`,
+ });
+ continue;
+ }
+
+ // loadIntegrationDoc validates against the envelope (incl. a 'page'|'block'
+ // type) at the load boundary, so a valid doc always has a type. This guard
+ // stays as defense-in-depth.
+ const type = doc?.type;
+ if (type !== 'page' && type !== 'block') {
+ errors.push({
+ package: pkgLabel,
+ template: id,
+ message: `Template "${id}" is missing a "type" of "page" or "block". Author it with createPageTemplate/createBlockTemplate.`,
+ });
+ continue;
+ }
+
+ templates.push({
+ type,
+ dirName: id,
+ name: doc?.name || id,
+ description: doc?.description || '',
+ category: doc?.category || '',
+ isReady: true,
+ scaffold: false,
+ componentsUsed: doc?.componentsUsed ?? [],
+ filePath: sourcePath,
+ docPath,
+ package: pkgLabel,
+ });
+ }
+
+ return {templates, errors};
}
export async function findRelatedBlocks(componentName, cwd) {
@@ -491,71 +682,6 @@ function extractSkeleton(source) {
return out.filter(l => l.trim()).join('\n');
}
-/**
- * Fetch a template by ID using the `template.get` hook in astryx.config.mjs.
- * @param {string} id
- * @param {object} [options]
- * @param {string} [options.cwd]
- * @returns {Promise<{type: 'template.get', data: {id: string, source: string}}>}
- */
-export async function getTemplateById(id, options = {}) {
- const {cwd = process.cwd()} = options;
- const config = await loadConfig(cwd);
-
- const getter = config.template?.get;
- if (typeof getter !== 'function') {
- throw new AstryxError(
- 'Template fetching by ID is not configured.\n' +
- 'Add a template.get function to astryx.config.mjs:\n\n' +
- ' export default {\n' +
- ' template: {\n' +
- ' get: async (id) => { /* return template source string */ },\n' +
- ' },\n' +
- ' };',
- undefined,
- ERROR_CODES.ERR_TEMPLATE_CONFIG,
- );
- }
-
- let source;
- try {
- source = await getter(id);
- } catch (err) {
- const detail = err instanceof Error ? err.message : String(err);
- throw new AstryxError(
- `template.get("${id}") threw an error: ${detail}`,
- undefined,
- ERROR_CODES.ERR_TEMPLATE_GET,
- );
- }
-
- if (source == null) {
- throw new AstryxError(
- `template.get("${id}") returned ${source} — no template found for that ID`,
- undefined,
- ERROR_CODES.ERR_TEMPLATE_GET,
- );
- }
-
- if (typeof source !== 'string') {
- throw new AstryxError(
- `template.get("${id}") must return a string, got ${typeof source}`,
- undefined,
- ERROR_CODES.ERR_TEMPLATE_GET,
- );
- }
-
- if (source.trim() === '') {
- throw new AstryxError(
- `template.get("${id}") returned an empty string`,
- undefined,
- ERROR_CODES.ERR_TEMPLATE_GET,
- );
- }
-
- return {type: 'template.get', data: {id, source}};
-}
-
/**
* @param {string} [name]
* @param {object} [options]
@@ -563,7 +689,8 @@ export async function getTemplateById(id, options = {}) {
* @param {boolean} [options.list]
* @param {boolean} [options.skeleton]
* @param {boolean} [options.show]
- * @param {'page'|'block'} [options.type] - Filter list views by template kind.
+ * @param {'page'|'block'} [options.type] - Filter list views / narrow lookups by template kind.
+ * @param {string} [options.package] - Narrow lookups to a specific package (id-only matches across packages are ambiguous).
* @param {string} [options.cwd]
* @returns {Promise<{type: string, data: unknown}>}
*/
@@ -574,34 +701,65 @@ export async function template(name, options = {}) {
show = false,
targetPath,
type,
+ package: packageFilter,
cwd = process.cwd(),
} = options;
- const templates = await discoverAll();
+ const templates = await discoverAll(cwd);
+
+ /**
+ * Identity for a template in package-scoped views. Core (built-in)
+ * templates have no `package` field; report them under @astryxdesign/core.
+ * @param {{package?: string}} t
+ */
+ const pkgOf = t => t.package ?? CORE_PACKAGE;
if (list || (!name && !skeleton)) {
let filtered = templates;
- if (type) filtered = templates.filter(t => t.type === type);
+ if (type) filtered = filtered.filter(t => t.type === type);
+ if (packageFilter) filtered = filtered.filter(t => pkgOf(t) === packageFilter);
return {
type: 'template.list',
data: filtered.map(t => ({
- name: t.dirName,
+ id: t.dirName,
+ name: t.name,
+ // `displayName` retained for back-compat with existing consumers.
displayName: t.name,
description: t.description,
+ type: t.type,
+ package: pkgOf(t),
+ category: t.category || undefined,
+ componentsUsed: t.componentsUsed ?? undefined,
isReady: t.isReady,
scaffold: t.scaffold ?? false,
- type: t.type,
})),
};
}
- const match = templates.find(t => t.dirName === name);
- if (name && !match) {
+ // Resolve `name` to a single template. The same id can appear across types
+ // and/or packages (e.g. a core "hero" page and an integration "hero"
+ // block); narrow with --type / --package.
+ let candidates = templates.filter(t => t.dirName === name);
+ if (type) candidates = candidates.filter(t => t.type === type);
+ if (packageFilter) candidates = candidates.filter(t => pkgOf(t) === packageFilter);
+
+ if (name && candidates.length === 0) {
throw new AstryxError(
`Unknown template "${name}"`,
templates.map(t => ({name: t.dirName, reason: `${t.type} template`})),
ERROR_CODES.ERR_UNKNOWN_TEMPLATE,
);
}
+ if (name && candidates.length > 1) {
+ throw new AstryxError(
+ `Template "${name}" is ambiguous — narrow it with --type and/or --package.`,
+ candidates.map(t => ({
+ name: t.dirName,
+ reason: `${t.type} template in ${pkgOf(t)}`,
+ })),
+ ERROR_CODES.ERR_AMBIGUOUS_TEMPLATE,
+ );
+ }
+ const match = candidates[0];
if (skeleton) {
if (!match) {
diff --git a/packages/cli/src/api/validate-integration.mjs b/packages/cli/src/api/validate-integration.mjs
new file mode 100644
index 0000000000..d45b31848d
--- /dev/null
+++ b/packages/cli/src/api/validate-integration.mjs
@@ -0,0 +1,370 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Programmatic API for `astryx validate-integration`.
+ *
+ * Validates exactly ONE integration package at a time and reports findings
+ * using the AstryxIntegrationIssue model
+ * ({ code, severity: 'warning'|'error', message }; see
+ * types/integration.d.ts). Two entry points:
+ *
+ * - validateLocalIntegration(cwd) — the package rooted at `cwd` (nearest
+ * package.json + sibling astryx.integration.{ts,mjs,js}).
+ * - validateInstalledIntegration(spec, cwd) — an installed package resolved
+ * from `cwd`/node_modules.
+ *
+ * Both return a { found, name, version, manifestFile, issues } result. `found`
+ * is false only for the no-manifest local case, which is guidance (not an
+ * error) so `validate-integration` can stay exit-0 in a non-integration dir.
+ *
+ * Validators are intentionally small and independent so more checks can be
+ * appended without reshaping the result. Issue `code`s are stable public
+ * strings.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {
+ findManifestPaths,
+ loadManifestObject,
+ resolvePackageDir,
+} from '../lib/integrations.mjs';
+import {discoverIntegrationCodemods} from '../codemods/integration-discovery.mjs';
+import {discoverIntegrationTemplatesForOne} from './template.mjs';
+import * as componentDiscovery from '../lib/component-discovery.mjs';
+
+/**
+ * @typedef {import('../types/integration').AstryxIntegrationIssue} Issue
+ */
+
+/**
+ * @typedef {Object} ValidateResult
+ * @property {boolean} found Whether an integration manifest was located.
+ * @property {string} [name] Integration package name (from package.json).
+ * @property {string} [version] Integration package version.
+ * @property {string} [manifestFile] Absolute path to the loaded manifest.
+ * @property {Issue[]} issues
+ */
+
+/**
+ * Find the nearest package.json starting from `cwd` and walking up.
+ * @param {string} cwd
+ * @returns {string | null} absolute path to the package.json, or null.
+ */
+function findNearestPackageJson(cwd) {
+ let dir = path.resolve(cwd);
+ for (;;) {
+ const candidate = path.join(dir, 'package.json');
+ if (fs.existsSync(candidate)) return candidate;
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+/** @param {string} code @param {string} message @returns {Issue} */
+function error(code, message) {
+ return {code, severity: 'error', message};
+}
+
+/** @param {string} code @param {string} message @returns {Issue} */
+function warning(code, message) {
+ return {code, severity: 'warning', message};
+}
+
+/**
+ * Verify each declared contribution root exists on disk. A declared-but-missing
+ * root is a `missing_root` error.
+ * @param {{components?: string, templates?: string, codemods?: string}} resolved
+ * absolute resolved roots (undefined when not declared)
+ * @param {Issue[]} issues
+ */
+function checkRoots(resolved, issues) {
+ for (const kind of ['components', 'templates', 'codemods']) {
+ const root = resolved[kind];
+ if (root == null) continue;
+ if (!fs.existsSync(root)) {
+ issues.push(
+ error(
+ 'missing_root',
+ `Declared ${kind} root does not exist on disk: ${root}`,
+ ),
+ );
+ }
+ }
+}
+
+/**
+ * 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 {object} integration loaded-integration-shaped object
+ * @param {Issue[]} issues
+ */
+async function checkCodemods(integration, issues) {
+ if (!integration.codemods || !fs.existsSync(integration.codemods)) return;
+ try {
+ await discoverIntegrationCodemods([integration]);
+ } catch (err) {
+ issues.push(error('invalid_codemod', err.message));
+ }
+}
+
+/**
+ * Validate the integration's templates via the landed discovery. Per-template
+ * problems are reported as `invalid_template` errors.
+ * @param {object} integration loaded-integration-shaped object
+ * @param {Issue[]} issues
+ */
+async function checkTemplates(integration, issues) {
+ if (!integration.templates || !fs.existsSync(integration.templates)) return;
+ try {
+ const {errors} = await discoverIntegrationTemplatesForOne(integration);
+ for (const e of errors) {
+ issues.push(error('invalid_template', e.message));
+ }
+ } catch (err) {
+ issues.push(error('invalid_template', err.message));
+ }
+}
+
+/**
+ * Validate the integration's components via the landed ownership discovery.
+ * Feature-detected: if the component-ownership export isn't present in this
+ * build (sibling PR not yet merged), component validation is skipped rather
+ * than hard-failing.
+ *
+ * `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 {object} integration loaded-integration-shaped object
+ * @param {Issue[]} issues
+ */
+async function checkComponents(integration, issues) {
+ if (!integration.components || !fs.existsSync(integration.components)) return;
+ const discover = componentDiscovery.discoverIntegrationComponents;
+ if (typeof discover !== 'function') return; // feature not present yet
+ try {
+ const records = (await discover(integration)) ?? [];
+ for (const record of records) {
+ if (record?.sourcePath == null) {
+ issues.push(
+ error(
+ 'invalid_component',
+ `Component "${record?.name}" is missing its same-stem source file ${record?.name}.tsx.`,
+ ),
+ );
+ }
+ }
+ } catch (err) {
+ issues.push(error('invalid_component', err.message));
+ }
+}
+
+/**
+ * Run every contribution validator against a loaded-integration-shaped object.
+ * @param {object} integration
+ * @param {Issue[]} issues
+ */
+async function runContributionChecks(integration, issues) {
+ await checkCodemods(integration, issues);
+ await checkTemplates(integration, issues);
+ await checkComponents(integration, issues);
+}
+
+/**
+ * Validate an already-LOADED integration (as produced by
+ * `loadIntegrations` in lib/integrations.mjs — absolute contribution roots
+ * plus identity) and return its issues. This is the reuse seam for everyday
+ * commands that have already loaded the configured integrations and want the
+ * SAME validators that `validate-integration` runs, without re-resolving the
+ * manifest from disk.
+ *
+ * The manifest schema is intentionally NOT re-validated here: `loadIntegrations`
+ * already validated it (and throws otherwise), so by the time a command holds a
+ * loaded integration the manifest is known-good. We re-run the on-disk
+ * contribution checks (roots + codemods/templates/components) because those can
+ * regress independently of the manifest (a deleted directory, a broken template).
+ *
+ * @param {object} loaded loaded-integration-shaped object
+ * @returns {Promise<Issue[]>}
+ */
+export async function validateLoadedIntegration(loaded) {
+ /** @type {Issue[]} */
+ const issues = [];
+ if (!loaded || typeof loaded !== 'object') return issues;
+ checkRoots(
+ {
+ components: loaded.components,
+ templates: loaded.templates,
+ codemods: loaded.codemods,
+ },
+ issues,
+ );
+ await runContributionChecks(loaded, issues);
+ return issues;
+}
+
+/**
+ * Validate a single integration given its package directory and identity.
+ * Shared core for the local and installed entry points.
+ * @param {string} packageDir
+ * @param {{name: string, version?: string}} identity
+ * @returns {Promise<ValidateResult>}
+ */
+async function validateAtPackageDir(packageDir, identity) {
+ /** @type {Issue[]} */
+ const issues = [];
+ const result = {
+ found: true,
+ name: identity.name,
+ version: identity.version,
+ manifestFile: undefined,
+ issues,
+ };
+
+ const manifests = findManifestPaths(packageDir);
+ if (manifests.length === 0) {
+ issues.push(
+ error(
+ 'missing_manifest',
+ `No astryx.integration.{ts,mjs,js} found next to package.json in ${packageDir}.`,
+ ),
+ );
+ return result;
+ }
+ if (manifests.length > 1) {
+ issues.push(
+ error(
+ 'multiple_manifests',
+ `Multiple root manifests present (${manifests
+ .map(m => path.basename(m))
+ .join(', ')}). Keep exactly one.`,
+ ),
+ );
+ return result;
+ }
+
+ const manifestFile = manifests[0];
+ result.manifestFile = manifestFile;
+
+ // loadManifestObject loads the default export and validates it against the
+ // integration schema (the shared load boundary). A missing default export or
+ // a schema failure throws; we convert either into a single invalid_manifest
+ // error issue so validate-integration stays exit-1-but-not-crash.
+ let manifest;
+ try {
+ manifest = await loadManifestObject(
+ manifestFile,
+ `Integration manifest (${path.basename(manifestFile)})`,
+ );
+ } catch (err) {
+ issues.push(error('invalid_manifest', err.message));
+ return result;
+ }
+
+ const resolveRoot = value =>
+ value == null ? undefined : path.resolve(packageDir, value);
+
+ const loaded = {
+ name: identity.name,
+ version: identity.version,
+ components: resolveRoot(manifest.components),
+ templates: resolveRoot(manifest.templates),
+ codemods: resolveRoot(manifest.codemods),
+ issuesUrl: manifest.issuesUrl,
+ __spec: identity.name,
+ __packageDir: packageDir,
+ __manifestFile: manifestFile,
+ };
+
+ // Roots + contribution checks are shared with validateLoadedIntegration so
+ // the everyday-command nudge runs the exact same validators.
+ issues.push(...(await validateLoadedIntegration(loaded)));
+
+ return result;
+}
+
+/**
+ * Validate the LOCAL integration package rooted at `cwd`: nearest package.json
+ * + a single sibling astryx.integration.{ts,mjs,js}. A missing manifest yields
+ * `found: false` (guidance, not an error) so callers stay exit-0.
+ * @param {string} [cwd]
+ * @returns {Promise<ValidateResult>}
+ */
+export async function validateLocalIntegration(cwd = process.cwd()) {
+ const pkgJsonPath = findNearestPackageJson(cwd);
+ if (!pkgJsonPath) {
+ return {found: false, issues: []};
+ }
+ const packageDir = path.dirname(pkgJsonPath);
+
+ const manifests = findManifestPaths(packageDir);
+ if (manifests.length === 0) {
+ // No manifest next to package.json — guidance, not an error.
+ return {found: false, issues: []};
+ }
+
+ let pkg = {};
+ try {
+ pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
+ } catch {
+ // Identity falls back to undefined; the manifest checks still run.
+ }
+
+ return validateAtPackageDir(packageDir, {
+ name: pkg.name ?? '(local package)',
+ version: pkg.version,
+ });
+}
+
+/**
+ * Validate an INSTALLED integration package resolved from `cwd`/node_modules.
+ * @param {string} spec package name
+ * @param {string} [cwd]
+ * @returns {Promise<ValidateResult>}
+ */
+export async function validateInstalledIntegration(spec, cwd = process.cwd()) {
+ const packageDir = resolvePackageDir(spec, cwd);
+ const pkgJsonPath = path.join(packageDir, 'package.json');
+
+ let pkg;
+ try {
+ pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
+ } catch {
+ return {
+ found: true,
+ name: spec,
+ version: undefined,
+ issues: [
+ error(
+ 'package_not_found',
+ `Could not find installed integration package "${spec}" at ${pkgJsonPath}. Install it first.`,
+ ),
+ ],
+ };
+ }
+
+ return validateAtPackageDir(packageDir, {
+ name: pkg.name ?? spec,
+ version: pkg.version,
+ });
+}
+
+/**
+ * Summarize issues by severity.
+ * @param {Issue[]} issues
+ * @returns {{errors: number, warnings: number}}
+ */
+export function summarizeIssues(issues) {
+ let errors = 0;
+ let warnings = 0;
+ for (const issue of issues) {
+ if (issue.severity === 'error') errors += 1;
+ else if (issue.severity === 'warning') warnings += 1;
+ }
+ return {errors, warnings};
+}
+
+// Re-export issue constructors for callers/tests that want them.
+export {error as integrationError, warning as integrationWarning};
diff --git a/packages/cli/src/api/validate-integration.test.mjs b/packages/cli/src/api/validate-integration.test.mjs
new file mode 100644
index 0000000000..a84580248f
--- /dev/null
+++ b/packages/cli/src/api/validate-integration.test.mjs
@@ -0,0 +1,222 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Hermetic tests for the validate-integration API.
+ *
+ * Each test stands up a temp integration package and exercises the public
+ * validate API directly. Temp dirs live UNDER the repo root (process.cwd())
+ * so node_modules-style paths are within Vite's allowed fs roots; we never
+ * load configs from /tmp.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {
+ validateLocalIntegration,
+ validateInstalledIntegration,
+ summarizeIssues,
+} from './validate-integration.mjs';
+
+let tmpDir;
+
+// Absolute file:// URL to the codemod helper so codemod modules in the temp
+// package can import createCodemod without node_modules wiring.
+const codemodModuleUrl = pathToFileURL(
+ path.resolve(process.cwd(), 'packages/cli/src/codemod.mjs'),
+).href;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-validate-it-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * Create an integration package directory with a package.json + manifest.
+ * @param {string} dir
+ * @param {{name?: string, version?: string, manifest: string, manifestExt?: string}} opts
+ */
+function writePackage(dir, {name = '@acme/widgets', version = '1.0.0', manifest, manifestExt = 'mjs'}) {
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name, version}),
+ );
+ fs.writeFileSync(path.join(dir, `astryx.integration.${manifestExt}`), manifest);
+}
+
+/** Find issues by code. */
+function byCode(issues, code) {
+ return issues.filter(i => i.code === code);
+}
+
+describe('validate-integration API', () => {
+ it('reports no errors for a valid integration with a codemod', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { codemods: './codemods' };\n`,
+ });
+ const cmDir = path.join(pkgDir, 'codemods', '0.2.0');
+ fs.mkdirSync(cmDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(cmDir, 'drop-foo.mjs'),
+ `import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};\n` +
+ `export default createCodemod({ title: 'Drop foo', transform: (file) => file.source });\n`,
+ );
+
+ const result = await validateLocalIntegration(pkgDir);
+ expect(result.found).toBe(true);
+ expect(result.name).toBe('@acme/widgets');
+ expect(result.version).toBe('1.0.0');
+ const {errors} = summarizeIssues(result.issues);
+ expect(errors).toBe(0);
+ });
+
+ it('flags an unknown manifest key as invalid_manifest error', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { components: './c', bogus: true };\n`,
+ });
+ const result = await validateLocalIntegration(pkgDir);
+ const manifestIssues = byCode(result.issues, 'invalid_manifest');
+ expect(manifestIssues).toHaveLength(1);
+ expect(manifestIssues[0].severity).toBe('error');
+ });
+
+ it('flags a declared-but-missing root as missing_root error', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { templates: './nope' };\n`,
+ });
+ const result = await validateLocalIntegration(pkgDir);
+ const rootIssues = byCode(result.issues, 'missing_root');
+ expect(rootIssues).toHaveLength(1);
+ expect(rootIssues[0].severity).toBe('error');
+ expect(summarizeIssues(result.issues).errors).toBeGreaterThan(0);
+ });
+
+ it('flags multiple manifests as multiple_manifests error', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {manifest: `export default {};\n`});
+ fs.writeFileSync(path.join(pkgDir, 'astryx.integration.js'), 'export default {};\n');
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'multiple_manifests')).toHaveLength(1);
+ });
+
+ it('returns found:false (guidance) when no manifest is present', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: 'plain'}),
+ );
+ const result = await validateLocalIntegration(pkgDir);
+ expect(result.found).toBe(false);
+ expect(result.issues).toEqual([]);
+ });
+
+ it('flags a broken codemod as invalid_codemod error', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { codemods: './codemods' };\n`,
+ });
+ const cmDir = path.join(pkgDir, 'codemods', '0.2.0');
+ fs.mkdirSync(cmDir, {recursive: true});
+ // Missing default export → discovery throws → invalid_codemod.
+ fs.writeFileSync(path.join(cmDir, 'broken.mjs'), `export const nope = 1;\n`);
+
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'invalid_codemod')).toHaveLength(1);
+ });
+
+ it('flags a broken template as invalid_template error', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { templates: './templates' };\n`,
+ });
+ const tplDir = path.join(pkgDir, 'templates');
+ fs.mkdirSync(tplDir, {recursive: true});
+ // Doc with no same-stem source file.
+ fs.writeFileSync(
+ path.join(tplDir, 'dash.doc.mjs'),
+ `export default { type: 'page', name: 'Dash' };\n`,
+ );
+
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'invalid_template')).toHaveLength(1);
+ });
+
+ it('validates an installed package resolved from node_modules', async () => {
+ const consumer = path.join(tmpDir, 'consumer');
+ fs.mkdirSync(consumer, {recursive: true});
+ fs.writeFileSync(
+ path.join(consumer, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ const pkgDir = path.join(consumer, 'node_modules', '@acme', 'widgets');
+ writePackage(pkgDir, {
+ name: '@acme/widgets',
+ version: '2.0.0',
+ manifest: `export default { templates: './gone' };\n`,
+ });
+
+ const result = await validateInstalledIntegration('@acme/widgets', consumer);
+ expect(result.found).toBe(true);
+ expect(result.name).toBe('@acme/widgets');
+ expect(result.version).toBe('2.0.0');
+ expect(byCode(result.issues, 'missing_root')).toHaveLength(1);
+ });
+
+ it('flags a non-installed package as package_not_found error', async () => {
+ const consumer = path.join(tmpDir, 'consumer');
+ fs.mkdirSync(consumer, {recursive: true});
+ fs.writeFileSync(
+ path.join(consumer, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ const result = await validateInstalledIntegration('@acme/nope', consumer);
+ expect(byCode(result.issues, 'package_not_found')).toHaveLength(1);
+ });
+
+ it('reports no errors for a valid component (doc + same-stem source)', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { components: './components' };\n`,
+ });
+ const cDir = path.join(pkgDir, 'components');
+ fs.mkdirSync(cDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(cDir, 'Widget.doc.mjs'),
+ `export default { name: 'Widget' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(cDir, 'Widget.tsx'),
+ `export function Widget() { return null; }\n`,
+ );
+
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'invalid_component')).toHaveLength(0);
+ expect(summarizeIssues(result.issues).errors).toBe(0);
+ });
+
+ it('flags a component doc missing its same-stem source as invalid_component', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default { components: './components' };\n`,
+ });
+ const cDir = path.join(pkgDir, 'components');
+ fs.mkdirSync(cDir, {recursive: true});
+ // Doc with no sibling Widget.tsx.
+ fs.writeFileSync(
+ path.join(cDir, 'Widget.doc.mjs'),
+ `export default { name: 'Widget' };\n`,
+ );
+
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'invalid_component')).toHaveLength(1);
+ });
+});
diff --git a/packages/cli/src/codemod.mjs b/packages/cli/src/codemod.mjs
new file mode 100644
index 0000000000..cd5fde4369
--- /dev/null
+++ b/packages/cli/src/codemod.mjs
@@ -0,0 +1,93 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Public file-based codemod-authoring API.
+ *
+ * Integrations (and core) author codemods as standalone modules that
+ * default-export a `createCodemod(...)` or `createConfigCodemod(...)` result.
+ * These helpers are intentionally tiny: they stamp a `type` discriminator
+ * (`'code'` | `'config'`) consumed by integration codemod discovery during
+ * `astryx upgrade`, and otherwise return the definition unchanged. They do NOT
+ * validate — validation happens at the load boundary, where discovery runs the
+ * module's default export through {@link CodemodEnvelopeSchema} (see
+ * `loadModuleWithSchema`). The exported schemas below ARE that contract.
+ */
+
+import {z} from 'zod';
+
+const Fn = z.custom(value => typeof value === 'function', {
+ message: 'Expected a function',
+});
+
+/**
+ * Authoring shape for a file-transforming codemod (the `def` an author passes
+ * to {@link createCodemod}), before the `type` discriminator is stamped on.
+ * Exported so discovery can validate the stamped result against the envelope.
+ */
+export const CodemodSchema = z
+ .object({
+ title: z.string(),
+ description: z.string().optional(),
+ isOptional: z.boolean().optional().default(false),
+ fileExtensions: z.array(z.string()).optional(),
+ transform: Fn,
+ })
+ .strict();
+
+/**
+ * Authoring shape for a config-targeting codemod (the `def` an author passes to
+ * {@link createConfigCodemod}). Like {@link CodemodSchema} but without
+ * `fileExtensions`, which is only meaningful for code codemods.
+ */
+export const ConfigCodemodSchema = z
+ .object({
+ title: z.string(),
+ description: z.string().optional(),
+ isOptional: z.boolean().optional().default(false),
+ transform: Fn,
+ })
+ .strict();
+
+/**
+ * The metadata envelope discovery validates: a stamped codemod result. This is
+ * the LOAD-boundary contract — a hand-written plain object that matches this
+ * shape is accepted (discovery does not check "was it made by the factory",
+ * only the shape). A single discriminated union over the stamped `type`:
+ * - `type: 'code'` → may carry `fileExtensions`
+ * - `type: 'config'` → no `fileExtensions`
+ */
+export const CodemodEnvelopeSchema = z.discriminatedUnion('type', [
+ CodemodSchema.extend({type: z.literal('code')}),
+ ConfigCodemodSchema.extend({type: z.literal('config')}),
+]);
+
+/**
+ * Define a file-transforming codemod. Stamp-only: returns the definition with
+ * `type: 'code'` injected. Validation happens at the load boundary.
+ *
+ * @template {import('./types/codemod').AstryxCodemodDef} T
+ * @param {T} def
+ * @returns {import('./types/codemod').AstryxCodemod}
+ */
+export function createCodemod(def) {
+ return /** @type {import('./types/codemod').AstryxCodemod} */ ({
+ ...def,
+ type: 'code',
+ });
+}
+
+/**
+ * Define a codemod that targets the consumer's astryx.config.* file. Stamp-only:
+ * returns the definition with `type: 'config'` injected. Validation happens at
+ * the load boundary.
+ *
+ * @template {import('./types/codemod').AstryxConfigCodemodDef} T
+ * @param {T} def
+ * @returns {import('./types/codemod').AstryxConfigCodemod}
+ */
+export function createConfigCodemod(def) {
+ return /** @type {import('./types/codemod').AstryxConfigCodemod} */ ({
+ ...def,
+ type: 'config',
+ });
+}
diff --git a/packages/cli/src/codemod.test.mjs b/packages/cli/src/codemod.test.mjs
new file mode 100644
index 0000000000..196c7983b3
--- /dev/null
+++ b/packages/cli/src/codemod.test.mjs
@@ -0,0 +1,134 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {
+ createCodemod,
+ createConfigCodemod,
+ CodemodEnvelopeSchema,
+} from './codemod.mjs';
+
+// createCodemod/createConfigCodemod are now stamp-only: they inject the `type`
+// discriminator and return the definition otherwise unchanged, performing NO
+// runtime validation. Validation happens at the LOAD boundary (discovery runs
+// the default export through CodemodEnvelopeSchema), so the rejection cases
+// that used to assert factory throws now assert the envelope schema rejects.
+
+describe('createCodemod (stamp-only)', () => {
+ it('stamps type: code and returns the def otherwise unchanged', () => {
+ const transform = file => file.source;
+ const result = createCodemod({title: 'Drop foo', transform});
+ expect(result.type).toBe('code');
+ expect(result.title).toBe('Drop foo');
+ expect(result.transform).toBe(transform);
+ // Stamp-only: it does NOT apply schema defaults (e.g. isOptional).
+ expect(result.isOptional).toBeUndefined();
+ });
+
+ it('preserves description, fileExtensions, and explicit isOptional', () => {
+ const result = createCodemod({
+ title: 'Rename',
+ description: 'renames things',
+ isOptional: true,
+ fileExtensions: ['.tsx'],
+ transform: () => null,
+ });
+ expect(result.description).toBe('renames things');
+ expect(result.isOptional).toBe(true);
+ expect(result.fileExtensions).toEqual(['.tsx']);
+ expect(result.type).toBe('code');
+ });
+
+ it('does NOT validate — returns an invalid def stamped, unchanged', () => {
+ const result = createCodemod({transform: () => null});
+ expect(result.type).toBe('code');
+ expect(result.title).toBeUndefined();
+ });
+});
+
+describe('createConfigCodemod (stamp-only)', () => {
+ it('stamps type: config', () => {
+ const transform = file => file.source;
+ const result = createConfigCodemod({title: 'Config bump', transform});
+ expect(result.type).toBe('config');
+ expect(result.transform).toBe(transform);
+ });
+});
+
+describe('CodemodEnvelopeSchema (load-boundary validation)', () => {
+ it('accepts a stamped code codemod (incl. defaults)', () => {
+ const parsed = CodemodEnvelopeSchema.parse(
+ createCodemod({title: 'Drop foo', transform: () => null}),
+ );
+ expect(parsed.type).toBe('code');
+ expect(parsed.isOptional).toBe(false); // schema default applied at load
+ });
+
+ it('accepts a PLAIN OBJECT envelope (no factory required)', () => {
+ const parsed = CodemodEnvelopeSchema.parse({
+ type: 'code',
+ title: 'Hand-written',
+ transform: () => null,
+ });
+ expect(parsed.title).toBe('Hand-written');
+ });
+
+ it('accepts a stamped config codemod', () => {
+ const parsed = CodemodEnvelopeSchema.parse(
+ createConfigCodemod({title: 'Bump', transform: () => null}),
+ );
+ expect(parsed.type).toBe('config');
+ });
+
+ it('rejects a missing title', () => {
+ expect(() =>
+ CodemodEnvelopeSchema.parse({type: 'code', transform: () => null}),
+ ).toThrow(/title/i);
+ });
+
+ it('rejects a missing transform', () => {
+ expect(() =>
+ CodemodEnvelopeSchema.parse({type: 'code', title: 'x'}),
+ ).toThrow(/transform/i);
+ });
+
+ it('rejects a non-function transform', () => {
+ expect(() =>
+ CodemodEnvelopeSchema.parse({type: 'code', title: 'x', transform: 'nope'}),
+ ).toThrow(/transform/i);
+ });
+
+ it('rejects a missing/invalid type discriminator', () => {
+ expect(() =>
+ CodemodEnvelopeSchema.parse({title: 'x', transform: () => null}),
+ ).toThrow();
+ expect(() =>
+ CodemodEnvelopeSchema.parse({
+ type: 'bogus',
+ title: 'x',
+ transform: () => null,
+ }),
+ ).toThrow();
+ });
+
+ it('rejects unknown keys (strict)', () => {
+ expect(() =>
+ CodemodEnvelopeSchema.parse({
+ type: 'code',
+ title: 'x',
+ transform: () => null,
+ bogus: true,
+ }),
+ ).toThrow();
+ });
+
+ it('rejects fileExtensions on a config codemod', () => {
+ expect(() =>
+ CodemodEnvelopeSchema.parse({
+ type: 'config',
+ title: 'x',
+ transform: () => null,
+ fileExtensions: ['.ts'],
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/cli/src/codemods/__tests__/registry.test.mjs b/packages/cli/src/codemods/__tests__/registry.test.mjs
index 817d9c09a7..485f1dccb2 100644
--- a/packages/cli/src/codemods/__tests__/registry.test.mjs
+++ b/packages/cli/src/codemods/__tests__/registry.test.mjs
@@ -18,6 +18,7 @@ describe('registry', () => {
'0.0.15',
'0.1.0',
'0.1.2',
+ '0.1.3',
]);
});
});
diff --git a/packages/cli/src/codemods/__tests__/runner.test.mjs b/packages/cli/src/codemods/__tests__/runner.test.mjs
new file mode 100644
index 0000000000..73466408ac
--- /dev/null
+++ b/packages/cli/src/codemods/__tests__/runner.test.mjs
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {runCodemods} from '../runner.mjs';
+
+let tmpDir;
+let originalCwd;
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ // Repo-local temp dir (not /tmp) to mirror the integration-runner tests and
+ // avoid any Vite dynamic-import quirks with absolute /tmp paths.
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-runner-test-'));
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('runCodemods — unified config codemod path', () => {
+ it('routes a core config codemod through the (file, api) runner to edit astryx.config.*', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { theme: 'old-theme' };\n`,
+ );
+
+ // A synthetic CORE registry transform marked as a config codemod via
+ // meta.codemodType === 'config'. It authors against the unified
+ // (file, api) => string contract, just like createConfigCodemod results.
+ const versionManifests = [
+ {
+ version: '0.1.3',
+ transforms: [
+ {
+ name: 'synthetic-config-codemod',
+ meta: {
+ title: 'Synthetic config codemod',
+ codemodType: 'config',
+ },
+ transform: (file, api) => {
+ // Exercise the unified (file, api) contract: api carries a
+ // configured jscodeshift instance, and the transform returns the
+ // rewritten source string (or null/undefined for no-op).
+ expect(typeof api.jscodeshift).toBe('function');
+ return file.source.replace('old-theme', 'new-theme');
+ },
+ },
+ ],
+ },
+ ];
+
+ const result = await runCodemods(versionManifests, {
+ apply: true,
+ path: './src',
+ silent: true,
+ });
+
+ expect(result.errors).toHaveLength(0);
+ expect(result.totalFilesChanged).toBe(1);
+ expect(
+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),
+ ).toContain('new-theme');
+ });
+
+ it('still runs core code codemods against source files', async () => {
+ const srcDir = path.join(tmpDir, 'src');
+ fs.mkdirSync(srcDir);
+ fs.writeFileSync(path.join(srcDir, 'a.ts'), 'const foo = 1;\n');
+
+ const versionManifests = [
+ {
+ version: '0.1.3',
+ transforms: [
+ {
+ name: 'synthetic-code-codemod',
+ meta: {title: 'Synthetic code codemod'},
+ transform: file => file.source.replace(/foo/g, 'bar'),
+ },
+ ],
+ },
+ ];
+
+ const result = await runCodemods(versionManifests, {
+ apply: true,
+ path: './src',
+ silent: true,
+ });
+
+ expect(result.errors).toHaveLength(0);
+ expect(result.totalFilesChanged).toBe(1);
+ expect(fs.readFileSync(path.join(srcDir, 'a.ts'), 'utf-8')).toContain(
+ 'const bar = 1',
+ );
+ });
+});
diff --git a/packages/cli/src/codemods/integration-discovery.mjs b/packages/cli/src/codemods/integration-discovery.mjs
new file mode 100644
index 0000000000..b5d6864e07
--- /dev/null
+++ b/packages/cli/src/codemods/integration-discovery.mjs
@@ -0,0 +1,168 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration codemod discovery.
+ *
+ * Integrations may declare a `codemods` directory in their manifest. The
+ * directory layout is version-folder-first:
+ *
+ * <codemodsRoot>/<version>/<id>.<ext>
+ *
+ * where `<version>` is the immediate folder name (e.g. "0.2.0") and `<id>` is
+ * the codemod module's relative path under that version folder WITHOUT its
+ * extension (kebab-case; may include nested segments like "config/rename").
+ * Each module DEFAULT-EXPORTS a codemod envelope — typically a `createCodemod`
+ * / `createConfigCodemod` result, though any plain object matching
+ * {@link CodemodEnvelopeSchema} is accepted. Validation happens here at the
+ * load boundary via `loadModuleWithSchema`, not in the factories.
+ *
+ * Version selection mirrors the core registry's getTransformsBetween(from,to):
+ * a codemod under folder X runs when upgrading to include X.
+ *
+ * Strictness: any broken discovery (bad/missing default export, schema
+ * invalid, duplicate id) is a hard error so the upgrade fails loudly rather
+ * than silently skipping migrations.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {loadModuleWithSchema} from '../lib/module-loader.mjs';
+import {CodemodEnvelopeSchema} from '../codemod.mjs';
+import {semverCompare} from '../utils/semver.mjs';
+
+/** File extensions recognized as codemod modules. */
+const CODEMOD_EXTENSIONS = ['.ts', '.mjs', '.js'];
+
+/**
+ * Recursively collect codemod module files under a version folder. Returns
+ * entries of {id, file} where id is the extension-less relative path
+ * (POSIX-style) under `versionDir`.
+ * @param {string} versionDir
+ * @returns {Array<{id: string, file: string}>}
+ */
+function collectCodemodFiles(versionDir) {
+ const out = [];
+
+ /** @param {string} dir */
+ function walk(dir) {
+ const entries = fs.readdirSync(dir, {withFileTypes: true});
+ for (const entry of entries) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ walk(full);
+ continue;
+ }
+ const ext = path.extname(entry.name);
+ if (!CODEMOD_EXTENSIONS.includes(ext)) continue;
+ const rel = path.relative(versionDir, full);
+ const id = rel.slice(0, rel.length - ext.length).split(path.sep).join('/');
+ out.push({id, file: full});
+ }
+ }
+
+ walk(versionDir);
+ return out.sort((a, b) => a.id.localeCompare(b.id));
+}
+
+/**
+ * Discover file-based codemods contributed by configured integrations.
+ *
+ * @param {Array<{name?: string, codemods?: string, __spec?: string}>} loadedIntegrations
+ * @returns {Promise<Map<string, Array<{id: string, type: 'code'|'config', codemod: object, package: string}>>>}
+ * Map keyed by version string; each value is the list of discovered codemods
+ * for that version (across all integrations).
+ */
+export async function discoverIntegrationCodemods(loadedIntegrations = []) {
+ /** @type {Map<string, Array<{id: string, type: string, codemod: object, package: string}>>} */
+ const byVersion = new Map();
+
+ for (const integration of loadedIntegrations ?? []) {
+ const root = integration?.codemods;
+ if (!root) continue;
+
+ const pkgLabel = integration.name ?? integration.__spec ?? 'integration';
+
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
+ throw new Error(
+ `Integration "${pkgLabel}" declares a codemods directory that does not exist: ${root}`,
+ );
+ }
+
+ const versionFolders = fs
+ .readdirSync(root, {withFileTypes: true})
+ .filter(entry => entry.isDirectory())
+ .map(entry => entry.name);
+
+ // Track ids seen ACROSS versions within this package — duplicate id across
+ // versions within a package is a hard error (locked decision).
+ /** @type {Map<string, string>} id -> version */
+ const idToVersion = new Map();
+
+ for (const version of versionFolders) {
+ const versionDir = path.join(root, version);
+ const files = collectCodemodFiles(versionDir);
+
+ // Track ids within this package+version to catch same-version dupes.
+ const seenInVersion = new Set();
+
+ for (const {id, file} of files) {
+ const label = `Integration "${pkgLabel}" codemod ${version}/${id} (${file})`;
+
+ if (seenInVersion.has(id)) {
+ throw new Error(
+ `Integration "${pkgLabel}" has a duplicate codemod id "${id}" within version ${version}.`,
+ );
+ }
+ seenInVersion.add(id);
+
+ const priorVersion = idToVersion.get(id);
+ if (priorVersion != null && priorVersion !== version) {
+ throw new Error(
+ `Integration "${pkgLabel}" reuses codemod id "${id}" across versions ${priorVersion} and ${version}. Codemod ids must be unique within a package.`,
+ );
+ }
+ idToVersion.set(id, version);
+
+ const codemod = await loadModuleWithSchema(file, CodemodEnvelopeSchema, {
+ label,
+ });
+
+ const entry = {
+ id,
+ type: codemod.type,
+ codemod,
+ package: pkgLabel,
+ };
+ const list = byVersion.get(version);
+ if (list) {
+ list.push(entry);
+ } else {
+ byVersion.set(version, [entry]);
+ }
+ }
+ }
+ }
+
+ return byVersion;
+}
+
+/**
+ * Select discovered integration codemods that apply when upgrading from
+ * `from` (exclusive) to `to` (inclusive), ordered ascending by version.
+ *
+ * @param {Map<string, Array<object>>} byVersion
+ * @param {string} from
+ * @param {string} to
+ * @returns {Array<{version: string, codemods: Array<object>}>}
+ */
+export function selectIntegrationCodemods(byVersion, from, to) {
+ const versions = [...byVersion.keys()].sort(semverCompare);
+ const results = [];
+ for (const version of versions) {
+ if (semverCompare(version, from) > 0 && semverCompare(version, to) <= 0) {
+ results.push({version, codemods: byVersion.get(version)});
+ }
+ }
+ return results;
+}
diff --git a/packages/cli/src/codemods/integration-discovery.test.mjs b/packages/cli/src/codemods/integration-discovery.test.mjs
new file mode 100644
index 0000000000..fe26f0a7f9
--- /dev/null
+++ b/packages/cli/src/codemods/integration-discovery.test.mjs
@@ -0,0 +1,234 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {Project} from '../lib/project.mjs';
+import {
+ discoverIntegrationCodemods,
+ selectIntegrationCodemods,
+} from './integration-discovery.mjs';
+import {runIntegrationCodemods} from './integration-runner.mjs';
+
+let tmpDir;
+let originalCwd;
+
+/**
+ * Build a consumer project with an astryx.config.mjs that loads a single
+ * integration package, and the integration package itself (manifest +
+ * codemods dir). `codemodFiles` maps "<version>/<id>.mjs" -> file body.
+ */
+function scaffold(codemodFiles) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets'] };\n`,
+ );
+
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default { codemods: './codemods' };\n`,
+ );
+
+ for (const [rel, body] of Object.entries(codemodFiles)) {
+ const full = path.join(pkgDir, 'codemods', rel);
+ fs.mkdirSync(path.dirname(full), {recursive: true});
+ fs.writeFileSync(full, body);
+ }
+ return pkgDir;
+}
+
+// Resolve the codemod helper module to an absolute file:// URL so codemod
+// modules in the temp package can import it without node_modules wiring.
+// vitest reports import.meta.url as an http:// URL, so derive the on-disk path
+// from the vitest cwd (the repo root) instead.
+const codemodModulePath = path.resolve(
+ process.cwd(),
+ 'packages/cli/src/codemod.mjs',
+);
+const codemodModuleUrl = pathToFileURL(codemodModulePath).href;
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-codemod-test-'));
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('integration codemod discovery', () => {
+ it('discovers a code codemod and runs it for an applicable --from', async () => {
+ scaffold({
+ '0.2.0/drop-foo.mjs': `
+ import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};
+ export default createCodemod({
+ title: 'Drop foo',
+ transform: (file) => file.source.replace(/foo/g, 'bar'),
+ });
+ `,
+ });
+
+ const project = await Project.load(tmpDir);
+ expect(project.loadedIntegrations).toHaveLength(1);
+
+ const byVersion = await discoverIntegrationCodemods(
+ project.loadedIntegrations,
+ );
+ expect([...byVersion.keys()]).toEqual(['0.2.0']);
+ const entry = byVersion.get('0.2.0')[0];
+ expect(entry.id).toBe('drop-foo');
+ expect(entry.type).toBe('code');
+ expect(entry.package).toBe('@acme/widgets');
+
+ // Selection: applies upgrading from 0.1.0 -> 0.2.0, not from 0.2.0 -> 0.2.0
+ expect(selectIntegrationCodemods(byVersion, '0.1.0', '0.2.0')).toHaveLength(
+ 1,
+ );
+ expect(selectIntegrationCodemods(byVersion, '0.2.0', '0.2.0')).toHaveLength(
+ 0,
+ );
+
+ // Run it against a source file.
+ const srcDir = path.join(tmpDir, 'src');
+ fs.mkdirSync(srcDir);
+ fs.writeFileSync(path.join(srcDir, 'a.ts'), 'const foo = 1;\n');
+
+ const jscodeshift = (await import('jscodeshift')).default;
+ const groups = selectIntegrationCodemods(byVersion, '0.1.0', '0.2.0');
+ const result = runIntegrationCodemods(groups, {
+ apply: true,
+ path: './src',
+ jscodeshift,
+ silent: true,
+ });
+ expect(result.errors).toHaveLength(0);
+ expect(result.totalFilesChanged).toBe(1);
+ expect(fs.readFileSync(path.join(srcDir, 'a.ts'), 'utf-8')).toContain(
+ 'const bar = 1',
+ );
+ });
+
+ it('discovers and runs a config codemod against astryx.config.*', async () => {
+ scaffold({
+ '0.2.0/bump-config.mjs': `
+ import {createConfigCodemod} from ${JSON.stringify(codemodModuleUrl)};
+ export default createConfigCodemod({
+ title: 'Bump config',
+ transform: (file) => file.source.replace('consumer-old', 'consumer-new'),
+ });
+ `,
+ });
+ // Make the config file a transform target. (Project.load only needs a valid
+ // default export; the marker string lives in a comment.)
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `// consumer-old\nexport default { integrations: ['@acme/widgets'] };\n`,
+ );
+
+ const project = await Project.load(tmpDir);
+ const byVersion = await discoverIntegrationCodemods(
+ project.loadedIntegrations,
+ );
+ expect(byVersion.get('0.2.0')[0].type).toBe('config');
+
+ const jscodeshift = (await import('jscodeshift')).default;
+ const groups = selectIntegrationCodemods(byVersion, '0.1.0', '0.2.0');
+ const result = runIntegrationCodemods(groups, {
+ apply: true,
+ path: './src',
+ jscodeshift,
+ silent: true,
+ });
+ expect(result.errors).toHaveLength(0);
+ expect(result.totalFilesChanged).toBe(1);
+ expect(
+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),
+ ).toContain('consumer-new');
+ });
+
+ it('fails discovery when a codemod has no default export', async () => {
+ scaffold({
+ '0.2.0/broken.mjs': `export const notDefault = 1;\n`,
+ });
+ const project = await Project.load(tmpDir);
+ // Validation now happens at the LOAD boundary (loadModuleWithSchema against
+ // CodemodEnvelopeSchema); a missing default export is a schema-invalid
+ // failure rather than the old bespoke "must default-export" message.
+ await expect(
+ discoverIntegrationCodemods(project.loadedIntegrations),
+ ).rejects.toThrow(/is invalid/i);
+ });
+
+ it('fails discovery when default export is not a codemod envelope', async () => {
+ scaffold({
+ '0.2.0/bad.mjs': `export default { title: 'x', transform: () => null };\n`,
+ });
+ const project = await Project.load(tmpDir);
+ // No `type` discriminator -> fails the envelope schema at load.
+ await expect(
+ discoverIntegrationCodemods(project.loadedIntegrations),
+ ).rejects.toThrow(/is invalid/i);
+ });
+
+ it('accepts a PLAIN OBJECT codemod envelope (no factory required)', async () => {
+ // Proves we dropped factory-identity coupling: a hand-written object that
+ // matches the envelope schema is accepted by discovery.
+ scaffold({
+ '0.2.0/hand-written.mjs': `
+ export default {
+ type: 'code',
+ title: 'Hand written',
+ transform: (file) => file.source,
+ };
+ `,
+ });
+ const project = await Project.load(tmpDir);
+ const byVersion = await discoverIntegrationCodemods(
+ project.loadedIntegrations,
+ );
+ const entry = byVersion.get('0.2.0')[0];
+ expect(entry.id).toBe('hand-written');
+ expect(entry.type).toBe('code');
+ expect(entry.codemod.isOptional).toBe(false); // schema default applied
+ });
+
+ it('rejects a malformed codemod envelope at load (missing transform)', async () => {
+ scaffold({
+ '0.2.0/no-transform.mjs': `export default { type: 'code', title: 'x' };\n`,
+ });
+ const project = await Project.load(tmpDir);
+ await expect(
+ discoverIntegrationCodemods(project.loadedIntegrations),
+ ).rejects.toThrow(/transform/i);
+ });
+
+ it('fails discovery on a duplicate id across versions within a package', async () => {
+ scaffold({
+ '0.2.0/dup.mjs': `
+ import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};
+ export default createCodemod({title: 'a', transform: () => null});
+ `,
+ '0.3.0/dup.mjs': `
+ import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};
+ export default createCodemod({title: 'b', transform: () => null});
+ `,
+ });
+ const project = await Project.load(tmpDir);
+ await expect(
+ discoverIntegrationCodemods(project.loadedIntegrations),
+ ).rejects.toThrow(/across versions/i);
+ });
+});
diff --git a/packages/cli/src/codemods/integration-runner.mjs b/packages/cli/src/codemods/integration-runner.mjs
new file mode 100644
index 0000000000..6cb2820820
--- /dev/null
+++ b/packages/cli/src/codemods/integration-runner.mjs
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Runner for file-based integration codemods.
+ *
+ * Integration codemods authored with `createCodemod` / `createConfigCodemod`
+ * use the file-based contract `(file, api) => string | null | undefined`.
+ * Config codemods target the consumer's astryx.config.* file; code codemods
+ * are applied to source files discovered under `--path`, filtered by each
+ * codemod's `fileExtensions`.
+ *
+ * Execution is delegated to the shared primitives in `run-codemod.mjs`, which
+ * the core registry runner (`runner.mjs`) reuses too — there is a single
+ * implementation of "run a config codemod against astryx.config.*" and "run a
+ * code codemod against source files".
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {
+ findSourceFiles,
+ makeLog,
+ runCodeCodemod,
+ runConfigCodemod,
+} from './run-codemod.mjs';
+
+/**
+ * Run file-based integration codemods, version-ordered. Config codemods run
+ * first (targeting astryx.config.*), then code codemods (source globbing).
+ *
+ * Optional codemods (isOptional) are skipped unless explicitly requested via
+ * `codemod` (matched against the codemod id).
+ *
+ * @param {Array<{version: string, codemods: Array<object>}>} versionGroups
+ * @param {object} options
+ * @param {boolean} options.apply
+ * @param {string} options.path source directory to scan
+ * @param {string} [options.codemod] run only this codemod id
+ * @param {Set<string>} [options.skipCodemods] codemod ids to exclude
+ * @param {Function} options.jscodeshift
+ * @param {boolean} [options.silent]
+ * @returns {{totalFilesChanged: number, totalTransformsApplied: number, writtenFiles: string[], errors: Array, skippedOptional: Array}}
+ */
+export function runIntegrationCodemods(
+ versionGroups,
+ {apply, path: srcPath, codemod, skipCodemods, jscodeshift, silent = false},
+) {
+ const log = makeLog(silent);
+
+ let totalFilesChanged = 0;
+ let totalTransformsApplied = 0;
+ const writtenFiles = [];
+ const errors = [];
+ const skippedOptional = [];
+
+ // Flatten and split by type, preserving version ordering.
+ const configEntries = [];
+ const codeEntries = [];
+ for (const {version, codemods} of versionGroups) {
+ for (const entry of codemods) {
+ const withVersion = {...entry, version};
+ // Exclude explicitly skipped codemods (by codemod id).
+ if (skipCodemods?.has(entry.id)) continue;
+ if (entry.codemod.isOptional && !codemod) {
+ skippedOptional.push(withVersion);
+ continue;
+ }
+ if (codemod && entry.id !== codemod) continue;
+ if (entry.type === 'config') configEntries.push(withVersion);
+ else codeEntries.push(withVersion);
+ }
+ }
+
+ // Config codemods first.
+ for (const entry of configEntries) {
+ log.info(` ${entry.codemod.title} (v${entry.version}, ${entry.package})`);
+ const r = runConfigCodemod(entry, {apply, log, jscodeshift});
+ totalFilesChanged += r.filesChanged;
+ totalTransformsApplied += r.filesChanged;
+ writtenFiles.push(...r.writtenFiles);
+ errors.push(...r.errors);
+ }
+
+ // Then code codemods (only scan the tree if there are any).
+ if (codeEntries.length > 0) {
+ const resolvedPath = path.resolve(srcPath);
+ const files = fs.existsSync(resolvedPath)
+ ? findSourceFiles(resolvedPath)
+ : [];
+ for (const entry of codeEntries) {
+ log.info(
+ ` ${entry.codemod.title} (v${entry.version}, ${entry.package})`,
+ );
+ const r = runCodeCodemod(entry, files, {apply, log, jscodeshift});
+ totalFilesChanged += r.filesChanged;
+ totalTransformsApplied += r.filesChanged;
+ writtenFiles.push(...r.writtenFiles);
+ errors.push(...r.errors);
+ }
+ }
+
+ return {
+ totalFilesChanged,
+ totalTransformsApplied,
+ writtenFiles,
+ errors,
+ skippedOptional,
+ };
+}
diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjs
index 0648686c28..ffc143751a 100644
--- a/packages/cli/src/codemods/registry.mjs
+++ b/packages/cli/src/codemods/registry.mjs
@@ -19,6 +19,7 @@ const registry = new Map([
['0.0.15', () => import('./transforms/v0.0.15/index.mjs')],
['0.1.0', () => import('./transforms/v0.1.0/index.mjs')],
['0.1.2', () => import('./transforms/v0.1.2/index.mjs')],
+ ['0.1.3', () => import('./transforms/v0.1.3/index.mjs')],
]);
// Re-export from the shared utility so registry callers and other consumers
diff --git a/packages/cli/src/codemods/run-codemod.mjs b/packages/cli/src/codemods/run-codemod.mjs
new file mode 100644
index 0000000000..d8e82997bf
--- /dev/null
+++ b/packages/cli/src/codemods/run-codemod.mjs
@@ -0,0 +1,207 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared codemod execution primitives.
+ *
+ * Both the core registry runner (`runner.mjs` / `upgrade.mjs`) and the
+ * integration runner (`integration-runner.mjs`) execute codemods that follow
+ * the unified file-based contract:
+ *
+ * (file, api) => string | null | undefined
+ *
+ * where `file` is `{path, source}` and `api` is
+ * `{jscodeshift, stats, report}`. Config codemods target the consumer's
+ * astryx.config.* file; code codemods are applied to source files discovered
+ * under `--path`, filtered by each codemod's `fileExtensions`.
+ *
+ * A codemod ENTRY is normalized to a single shape across both callers:
+ *
+ * {id, type: 'code' | 'config', codemod: {title, transform, fileExtensions?,
+ * isOptional?}, package, version}
+ *
+ * Integration discovery emits this shape directly. The core registry stores
+ * entries as `{name, transform, meta}`; `runner.mjs` normalizes those to this
+ * shape at the boundary (see `runner.mjs`).
+ *
+ * Both kinds reuse the shared output validation from runner.mjs and surface a
+ * transform throw as an error (strictness contract).
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as p from '@clack/prompts';
+import {findConfigPath} from '../lib/project.mjs';
+import {fixDirectiveCorruption, validateOutput} from './runner.mjs';
+
+export const DEFAULT_CODE_EXTENSIONS = [
+ '.tsx',
+ '.ts',
+ '.jsx',
+ '.js',
+ '.mjs',
+ '.cjs',
+];
+const PARSEABLE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs'];
+
+/**
+ * Recursively find candidate source files in a directory.
+ * @param {string} dir
+ * @returns {string[]}
+ */
+export function findSourceFiles(dir) {
+ const results = [];
+ function walk(currentDir) {
+ let entries;
+ try {
+ entries = fs.readdirSync(currentDir, {withFileTypes: true});
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const fullPath = path.join(currentDir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ walk(fullPath);
+ } else {
+ results.push(fullPath);
+ }
+ }
+ }
+ walk(dir);
+ return results.sort();
+}
+
+/**
+ * No-op log surface for silent (`--json`) mode.
+ * @param {boolean} silent
+ */
+export function makeLog(silent) {
+ return silent
+ ? {step() {}, info() {}, success() {}, warn() {}, error() {}, message() {}}
+ : p.log;
+}
+
+/**
+ * Apply a config codemod to the consumer's astryx.config.* file.
+ *
+ * @param {object} entry normalized codemod entry {id, codemod, package}
+ * @param {{apply: boolean, log: object, jscodeshift: Function}} ctx
+ * @returns {{filesChanged: number, writtenFiles: string[], errors: Array}}
+ */
+export function runConfigCodemod(entry, {apply, log, jscodeshift}) {
+ const {codemod, id, package: pkg} = entry;
+ const name = `${pkg}:${id}`;
+ const configPath = findConfigPath(process.cwd());
+ if (!configPath) {
+ log.info(` ${codemod.title} — no astryx.config.* found; skipping.`);
+ return {filesChanged: 0, writtenFiles: [], errors: []};
+ }
+
+ const relativePath = path.relative(process.cwd(), configPath);
+ try {
+ const source = fs.readFileSync(configPath, 'utf-8');
+ const ext = path.extname(configPath);
+ const parser = ext === '.tsx' || ext === '.ts' ? 'tsx' : 'babel';
+ const j = jscodeshift.withParser(parser);
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
+ let result = codemod.transform({source, path: configPath}, api);
+
+ if (result == null || result === source) {
+ return {filesChanged: 0, writtenFiles: [], errors: []};
+ }
+
+ result = fixDirectiveCorruption(result);
+ const validation = validateOutput(result, source, j, {
+ parse: PARSEABLE_EXTENSIONS.includes(ext),
+ });
+ if (!validation.valid) {
+ log.error(` ✗ ${relativePath} — ${validation.reason}`);
+ return {
+ filesChanged: 0,
+ writtenFiles: [],
+ errors: [{file: relativePath, codemod: name, error: validation.reason}],
+ };
+ }
+
+ if (apply) {
+ fs.writeFileSync(configPath, result, 'utf-8');
+ log.success(` ✓ ${relativePath}`);
+ } else {
+ log.warn(` ~ ${relativePath} (would change)`);
+ }
+ return {
+ filesChanged: 1,
+ writtenFiles: apply ? [configPath] : [],
+ errors: [],
+ };
+ } catch (err) {
+ log.error(` ✗ ${relativePath} — ${err.message}`);
+ return {
+ filesChanged: 0,
+ writtenFiles: [],
+ errors: [{file: relativePath, codemod: name, error: err.message}],
+ };
+ }
+}
+
+/**
+ * Apply a code codemod to discovered source files.
+ *
+ * @param {object} entry normalized codemod entry {id, codemod, package}
+ * @param {string[]} files
+ * @param {{apply: boolean, log: object, jscodeshift: Function}} ctx
+ * @returns {{filesChanged: number, writtenFiles: string[], errors: Array}}
+ */
+export function runCodeCodemod(entry, files, {apply, log, jscodeshift}) {
+ const {codemod, id, package: pkg} = entry;
+ const name = `${pkg}:${id}`;
+ const extensions = new Set(codemod.fileExtensions ?? DEFAULT_CODE_EXTENSIONS);
+
+ let filesChanged = 0;
+ const writtenFiles = [];
+ const errors = [];
+
+ for (const filePath of files) {
+ const ext = path.extname(filePath);
+ if (!extensions.has(ext)) continue;
+
+ const relativePath = path.relative(process.cwd(), filePath);
+ try {
+ const source = fs.readFileSync(filePath, 'utf-8');
+ const parser = ext === '.tsx' || ext === '.ts' ? 'tsx' : 'babel';
+ const j = jscodeshift.withParser(parser);
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
+ let result = codemod.transform({source, path: filePath}, api);
+
+ if (result == null || result === source) continue;
+
+ result = fixDirectiveCorruption(result);
+ const validation = validateOutput(result, source, j, {
+ parse: PARSEABLE_EXTENSIONS.includes(ext),
+ });
+ if (!validation.valid) {
+ log.error(` ✗ ${relativePath} — ${validation.reason}`);
+ errors.push({
+ file: relativePath,
+ codemod: name,
+ error: validation.reason,
+ });
+ continue;
+ }
+
+ filesChanged++;
+ if (apply) {
+ fs.writeFileSync(filePath, result, 'utf-8');
+ writtenFiles.push(filePath);
+ log.success(` ✓ ${relativePath}`);
+ } else {
+ log.warn(` ~ ${relativePath} (would change)`);
+ }
+ } catch (err) {
+ log.error(` ✗ ${relativePath} — ${err.message}`);
+ errors.push({file: relativePath, codemod: name, error: err.message});
+ }
+ }
+
+ return {filesChanged, writtenFiles, errors};
+}
diff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjs
index caa6d06641..3eddc26868 100644
--- a/packages/cli/src/codemods/runner.mjs
+++ b/packages/cli/src/codemods/runner.mjs
@@ -12,6 +12,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '@clack/prompts';
import {humanLog} from '../lib/json.mjs';
+import {runConfigCodemod} from './run-codemod.mjs';
// Known corruption patterns that indicate a broken transform.
// Each entry: [regex, human-readable description]
@@ -128,83 +129,42 @@ export function validateOutput(result, source, j, {parse = true} = {}) {
return {valid: true};
}
-function isConfigCodemod(transformEntry) {
- return transformEntry.meta?.codemodType === 'config';
-}
-
-const CONFIG_CODEMOD_PATHS = new Set([
- 'package.json',
- 'astryx.config.mjs',
- 'xds.config.mjs',
-]);
-
-function resolveConfigPath(relativePath) {
- if (!CONFIG_CODEMOD_PATHS.has(relativePath)) {
- throw new Error(`unsupported config codemod path: ${relativePath}`);
- }
- return path.resolve(process.cwd(), relativePath);
-}
-
-function readOptionalConfigFile(relativePath) {
- const fullPath = resolveConfigPath(relativePath);
- if (!fs.existsSync(fullPath)) return null;
- return {path: relativePath, source: fs.readFileSync(fullPath, 'utf-8')};
-}
-
-function getConfigCodemodContext() {
- return {
- packageJson: readOptionalConfigFile('package.json'),
- astryxConfig: readOptionalConfigFile('astryx.config.mjs'),
- xdsConfig: readOptionalConfigFile('xds.config.mjs'),
- };
-}
-
-async function runConfigCodemod(transformEntry, {apply, log}) {
- const {transform} = transformEntry;
- const api = {config: getConfigCodemodContext()};
- const result = await transform({path: process.cwd(), source: ''}, api);
- const errors = result?.errors ?? [];
- if (errors.length > 0) {
- for (const error of errors) {
- log.error(` ✗ ${error.file ?? 'config'} — ${error.error}`);
- }
- return {filesChanged: 0, errors};
- }
-
- const changes = result?.changes ?? [];
- if (changes.length === 0) return {filesChanged: 0, errors: []};
-
- for (const change of changes) {
- const fullPath = resolveConfigPath(change.path);
- if (change.delete) {
- if (apply) fs.rmSync(fullPath, {force: true});
- log[apply ? 'success' : 'warn'](
- ` ${apply ? '✓' : '~'} ${change.path} (delete${apply ? '' : ', dry run'})`,
- );
- continue;
- }
-
- if (apply) {
- fs.writeFileSync(fullPath, change.source, 'utf-8');
- }
- log[apply ? 'success' : 'warn'](
- ` ${apply ? '✓' : '~'} ${change.path}${apply ? '' : ' (would change)'}`,
- );
- }
-
- if (changes.length > 0) {
- const verb = apply ? 'Updated' : 'Would update';
- log.info(
- ` ${verb} ${changes.length} config file${changes.length === 1 ? '' : 's'}`,
- );
- }
-
+/**
+ * Normalize a core registry transform entry to the unified codemod entry shape
+ * consumed by the shared runner (`run-codemod.mjs`).
+ *
+ * Core registry entries are stored as `{name, transform, meta, optional}`.
+ * The shared runner — the same one integration codemods use — operates on
+ * `{id, type, codemod: {title, transform, fileExtensions?, isOptional?},
+ * package, version}`.
+ *
+ * CONVENTION — how a core registry entry signals it is a CONFIG codemod:
+ * set `meta.codemodType === 'config'` on the entry (the default is a 'code'
+ * codemod). A config codemod runs against the consumer's astryx.config.* file
+ * via the unified `(file, api)`/jscodeshift contract; a code codemod runs
+ * against discovered source files. Any future core config codemod (e.g. a
+ * v0.1.3 one) must set `meta.codemodType = 'config'` and author its transform
+ * with the same `(file, api) => string | null | undefined` contract used by
+ * `createConfigCodemod`.
+ *
+ * @param {{name: string, transform: Function, meta: object, optional?: boolean}} transformEntry
+ * @param {string} version
+ * @returns {{id: string, type: 'code'|'config', codemod: object, package: string, version: string}}
+ */
+function toUnifiedEntry(transformEntry, version) {
+ const {name, transform, meta, optional} = transformEntry;
+ const type = meta?.codemodType === 'config' ? 'config' : 'code';
return {
- filesChanged: changes.length,
- writtenFiles: changes
- .filter(change => !change.delete && path.extname(change.path) !== '.json')
- .map(change => resolveConfigPath(change.path)),
- errors: [],
+ id: name,
+ type,
+ codemod: {
+ title: meta.title,
+ transform,
+ fileExtensions: meta.fileExtensions,
+ isOptional: !!optional,
+ },
+ package: 'core',
+ version,
};
}
@@ -216,11 +176,12 @@ async function runConfigCodemod(transformEntry, {apply, log}) {
* @param {boolean} options.apply - Write changes to disk
* @param {string} options.path - Source directory to scan
* @param {string|undefined} options.codemod - Run only this specific transform
+ * @param {Set<string>} [options.skipCodemods] - Transform names to exclude
* @param {boolean} [options.silent] - Suppress all human-facing output (for --json)
*/
export async function runCodemods(
versionManifests,
- {apply, path: srcPath, codemod, silent = false},
+ {apply, path: srcPath, codemod, skipCodemods, silent = false},
) {
// No-op stub object so silent mode skips clack stdout entirely without
// littering the body with `if (!silent)` guards.
@@ -233,20 +194,31 @@ export async function runCodemods(
const resolvedPath = path.resolve(srcPath);
- if (!fs.existsSync(resolvedPath)) {
+ // Config codemods target the consumer's astryx.config.* and never read
+ // source files, so a missing --path should not block them. Only hard-fail
+ // on a missing source path when there is at least one CODE codemod to run.
+ const hasCodeCodemod = versionManifests.some(({transforms}) =>
+ transforms.some(t => t.meta?.codemodType !== 'config'),
+ );
+ const sourcePathExists = fs.existsSync(resolvedPath);
+
+ if (!sourcePathExists && hasCodeCodemod) {
log.error(`Source path not found: ${resolvedPath}`);
return {ok: false, reason: 'source_path_missing', resolvedPath};
}
- log.step(`Scanning ${resolvedPath} for source files...`);
- const files = findSourceFiles(resolvedPath);
+ let files = [];
+ if (sourcePathExists) {
+ log.step(`Scanning ${resolvedPath} for source files...`);
+ files = findSourceFiles(resolvedPath);
- if (files.length === 0) {
- log.warn('No source files found.');
- } else {
- log.info(
- `Found ${files.length} source file${files.length === 1 ? '' : 's'}`,
- );
+ if (files.length === 0) {
+ log.warn('No source files found.');
+ } else {
+ log.info(
+ `Found ${files.length} source file${files.length === 1 ? '' : 's'}`,
+ );
+ }
}
// Dynamically import jscodeshift
@@ -265,6 +237,8 @@ export async function runCodemods(
for (const transformEntry of transforms) {
// Filter by codemod name if specified
if (codemod && transformEntry.name !== codemod) continue;
+ // Exclude explicitly skipped codemods (by transform name).
+ if (skipCodemods?.has(transformEntry.name)) continue;
const {name, transform, meta, optional} = transformEntry;
const transformExtensions = new Set(
@@ -279,20 +253,23 @@ export async function runCodemods(
log.info(` ${meta.title}`);
- if (isConfigCodemod(transformEntry)) {
- const result = await runConfigCodemod(transformEntry, {apply, log});
+ // Config codemods are routed through the SAME shared runner that
+ // integration config codemods use: the transform follows the unified
+ // `(file, api)` contract and targets the consumer's astryx.config.*.
+ // A core entry signals "config" via `meta.codemodType === 'config'`
+ // (see toUnifiedEntry).
+ if (meta?.codemodType === 'config') {
+ const result = runConfigCodemod(toUnifiedEntry(transformEntry, version), {
+ apply,
+ log,
+ jscodeshift,
+ });
if (result.errors.length > 0) {
- for (const error of result.errors) {
- errors.push({
- file: error.file ?? 'config',
- codemod: name,
- error: error.error,
- });
- }
+ errors.push(...result.errors);
} else if (result.filesChanged > 0) {
totalFilesChanged += result.filesChanged;
totalTransformsApplied += result.filesChanged;
- writtenFiles.push(...(result.writtenFiles ?? []));
+ writtenFiles.push(...result.writtenFiles);
}
continue;
}
diff --git a/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-config-surfaces.test.mjs b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-config-surfaces.test.mjs
deleted file mode 100644
index 3639309281..0000000000
--- a/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-config-surfaces.test.mjs
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import {describe, it, expect} from 'vitest';
-
-async function applyConfigCodemod(files) {
- const {default: transform} =
- await import('../migrate-xds-config-surfaces.mjs');
- const config = {
- packageJson: files['package.json']
- ? {path: 'package.json', source: files['package.json']}
- : null,
- astryxConfig: files['astryx.config.mjs']
- ? {path: 'astryx.config.mjs', source: files['astryx.config.mjs']}
- : null,
- xdsConfig: files['xds.config.mjs']
- ? {path: 'xds.config.mjs', source: files['xds.config.mjs']}
- : null,
- };
- return transform({path: process.cwd(), source: ''}, {config});
-}
-
-describe('migrate-xds-config-surfaces', () => {
- it('extracts package.json xds config into astryx.config.mjs and removes the package key in place', async () => {
- const input = `{
- "dependencies": {"@xds/core":"^0.0.15"},
- "xds" : {"theme":"neutral","docs":"./src"}
-}
-`;
-
- const result = await applyConfigCodemod({'package.json': input});
- expect(result.errors ?? []).toEqual([]);
- expect(result.changes).toEqual([
- {
- path: 'package.json',
- source: `{
- "dependencies": {"@xds/core":"^0.0.15"}
-}
-`,
- },
- {
- path: 'astryx.config.mjs',
- source: `export default {
- "theme": "neutral",
- "docs": "./src"
-};
-`,
- },
- ]);
- });
-
- it('extracts package.json astryx config into astryx.config.mjs too', async () => {
- const result = await applyConfigCodemod({
- 'package.json': `{"astryx":{"theme":"neutral"}}\n`,
- });
- expect(result.changes).toEqual([
- {path: 'package.json', source: `{}\n`},
- {
- path: 'astryx.config.mjs',
- source: `export default {
- "theme": "neutral"
-};
-`,
- },
- ]);
- });
-
- it('bails when package.json contains both xds and astryx config keys', async () => {
- const result = await applyConfigCodemod({
- 'package.json': `{"xds":{"theme":"default"},"astryx":{"theme":"neutral"}}\n`,
- });
- expect(result.errors?.[0]?.error).toMatch(/both xds and astryx/);
- });
-
- it('does not rewrite dependency keys in package.json', async () => {
- const input = `{"dependencies":{"@xds/core":"^0.0.15"}}\n`;
- const result = await applyConfigCodemod({'package.json': input});
- expect(result.changes).toEqual([]);
- });
-
- it('bails when package config and astryx.config.mjs both exist', async () => {
- const result = await applyConfigCodemod({
- 'package.json': `{"xds":{"theme":"neutral"}}\n`,
- 'astryx.config.mjs': `export default {};\n`,
- });
- expect(result.errors?.[0]?.error).toMatch(/migrate the config manually/);
- });
-
- it('bails when package config and xds.config.mjs both exist', async () => {
- const result = await applyConfigCodemod({
- 'package.json': `{"xds":{"theme":"neutral"}}\n`,
- 'xds.config.mjs': `export default {};\n`,
- });
- expect(result.errors?.[0]?.error).toMatch(/migrate the config manually/);
- });
-
- it('renames xds.config.mjs to astryx.config.mjs when no package config exists', async () => {
- const result = await applyConfigCodemod({
- 'xds.config.mjs': "export default { theme: 'neutral' };\n",
- });
- expect(result.changes).toEqual([
- {
- path: 'astryx.config.mjs',
- source: "export default { theme: 'neutral' };\n",
- },
- {path: 'xds.config.mjs', delete: true},
- ]);
- });
-
- it('bails when xds.config.mjs and astryx.config.mjs both exist', async () => {
- const result = await applyConfigCodemod({
- 'xds.config.mjs': `export default {};\n`,
- 'astryx.config.mjs': `export default {};\n`,
- });
- expect(result.errors?.[0]?.error).toMatch(/migrate the config manually/);
- });
-});
diff --git a/packages/cli/src/codemods/transforms/v0.1.0/index.mjs b/packages/cli/src/codemods/transforms/v0.1.0/index.mjs
index d944b49dc4..37e594bf76 100644
--- a/packages/cli/src/codemods/transforms/v0.1.0/index.mjs
+++ b/packages/cli/src/codemods/transforms/v0.1.0/index.mjs
@@ -6,20 +6,11 @@
* Lists all codemods for the v0.1.0 release in the order they should run.
*/
-import migrateXdsConfigSurfaces, {
- meta as migrateXdsConfigSurfacesMeta,
-} from './migrate-xds-config-surfaces.mjs';
-
import migrateXdsModuleSpecifiers, {
meta as migrateXdsModuleSpecifiersMeta,
} from './migrate-xds-module-specifiers.mjs';
export default [
- {
- name: 'migrate-xds-config-surfaces',
- transform: migrateXdsConfigSurfaces,
- meta: migrateXdsConfigSurfacesMeta,
- },
{
name: 'migrate-xds-module-specifiers',
transform: migrateXdsModuleSpecifiers,
diff --git a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-config-surfaces.mjs b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-config-surfaces.mjs
deleted file mode 100644
index d83410cae7..0000000000
--- a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-config-surfaces.mjs
+++ /dev/null
@@ -1,230 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Codemod: migrate XDS config surfaces to Astryx v0.1.0
- *
- * The v0.1.0 CLI reads astryx.config.mjs. This config codemod migrates
- * legacy xds.config.mjs and package.json's top-level `xds` config without
- * changing dependency names or versions.
- */
-
-export const meta = {
- title: 'Migrate xds config surfaces to astryx',
- description:
- 'Moves legacy package.json xds config into astryx.config.mjs, or renames ' +
- 'xds.config.mjs when no package.json config exists. Bails out if both exist.',
- pr: '#3092',
- codemodType: 'config',
-};
-
-function findTopLevelKey(source, targetKey) {
- let depth = 0;
- let inString = false;
- let escaped = false;
- let stringStart = -1;
-
- for (let i = 0; i < source.length; i++) {
- const ch = source[i];
-
- if (inString) {
- if (escaped) {
- escaped = false;
- continue;
- }
- if (ch === '\\') {
- escaped = true;
- continue;
- }
- if (ch !== '"') continue;
-
- inString = false;
- const rawKey = source.slice(stringStart + 1, i);
- if (depth !== 1 || rawKey !== targetKey) continue;
-
- let j = i + 1;
- while (/\s/.test(source[j] ?? '')) j++;
- if (source[j] !== ':') continue;
-
- const valueStart = j + 1;
- const value = readJsonValue(source, valueStart);
- if (!value) return null;
- return {keyStart: stringStart, keyEnd: i + 1, colon: j, ...value};
- }
-
- if (ch === '"') {
- inString = true;
- stringStart = i;
- continue;
- }
- if (ch === '{' || ch === '[') depth++;
- else if (ch === '}' || ch === ']') depth--;
- }
- return null;
-}
-
-function readJsonValue(source, start) {
- let i = start;
- while (/\s/.test(source[i] ?? '')) i++;
- const valueStart = i;
- let inString = false;
- let escaped = false;
- let depth = 0;
-
- for (; i < source.length; i++) {
- const ch = source[i];
- if (inString) {
- if (escaped) {
- escaped = false;
- continue;
- }
- if (ch === '\\') {
- escaped = true;
- continue;
- }
- if (ch === '"') inString = false;
- continue;
- }
- if (ch === '"') {
- inString = true;
- continue;
- }
- if (ch === '{' || ch === '[') {
- depth++;
- continue;
- }
- if (ch === '}' || ch === ']') {
- if (depth === 0) break;
- depth--;
- continue;
- }
- if (depth === 0 && ch === ',') break;
- }
-
- const valueEnd = i;
- const rawValue = source.slice(valueStart, valueEnd).trim();
- try {
- JSON.parse(rawValue);
- } catch {
- return null;
- }
- return {valueStart, valueEnd, rawValue, terminator: source[i]};
-}
-
-function removeTopLevelProperty(source, property) {
- let removeStart = property.keyStart;
- let removeEnd = property.valueEnd;
-
- if (source[removeEnd] === ',') {
- removeEnd++;
- if (source[removeEnd] === '\n') removeEnd++;
- return source.slice(0, removeStart) + source.slice(removeEnd);
- }
-
- let i = removeStart - 1;
- while (/\s/.test(source[i] ?? '')) i--;
- if (source[i] === ',') {
- const whitespaceBetweenCommaAndKey = source.slice(i + 1, removeStart);
- const preservedWhitespace = whitespaceBetweenCommaAndKey.includes('\n')
- ? '\n'
- : '';
- return source.slice(0, i) + preservedWhitespace + source.slice(removeEnd);
- }
-
- return source.slice(0, removeStart) + source.slice(removeEnd);
-}
-
-function formatConfigSource(rawConfig) {
- const parsed = JSON.parse(rawConfig);
- return `export default ${JSON.stringify(parsed, null, 2)};\n`;
-}
-
-function migratePackageJsonConfig(config) {
- if (!config.packageJson) return {changes: []};
-
- const packageJson = config.packageJson.source;
- const xdsConfig = findTopLevelKey(packageJson, 'xds');
- const astryxConfig = findTopLevelKey(packageJson, 'astryx');
- if (!xdsConfig && !astryxConfig) return {changes: []};
-
- if (config.astryxConfig) {
- return {
- errors: [
- {
- file: 'package.json',
- error:
- 'package.json contains xds/astryx config and astryx.config.mjs already exists; migrate the config manually.',
- },
- ],
- };
- }
-
- if (xdsConfig && astryxConfig) {
- return {
- errors: [
- {
- file: 'package.json',
- error:
- 'package.json contains both xds and astryx config keys; migrate the config manually.',
- },
- ],
- };
- }
-
- const configProperty = astryxConfig ?? xdsConfig;
- const packageJsonWithoutConfig = removeTopLevelProperty(
- packageJson,
- configProperty,
- );
- return {
- changes: [
- {path: 'package.json', source: packageJsonWithoutConfig},
- {
- path: 'astryx.config.mjs',
- source: formatConfigSource(configProperty.rawValue),
- },
- ],
- };
-}
-
-function migrateXdsConfigFile(config) {
- if (!config.xdsConfig) return {changes: []};
- if (config.astryxConfig) {
- return {
- errors: [
- {
- file: 'xds.config.mjs',
- error:
- 'xds.config.mjs and astryx.config.mjs both exist; migrate the config manually.',
- },
- ],
- };
- }
- return {
- changes: [
- {path: 'astryx.config.mjs', source: config.xdsConfig.source},
- {path: 'xds.config.mjs', delete: true},
- ],
- };
-}
-
-export default function transformer(_file, api) {
- const config = api.config ?? {};
- const packageResult = migratePackageJsonConfig(config);
- if (packageResult.errors?.length) return packageResult;
- if (packageResult.changes?.length) {
- if (config.xdsConfig) {
- return {
- errors: [
- {
- file: 'package.json',
- error:
- 'package.json contains xds/astryx config and xds.config.mjs exists; migrate the config manually.',
- },
- ],
- };
- }
- return packageResult;
- }
-
- return migrateXdsConfigFile(config);
-}
diff --git a/packages/cli/src/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs b/packages/cli/src/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs
new file mode 100644
index 0000000000..5d10e7570d
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs
@@ -0,0 +1,360 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/**
+ * Invoke the transform directly with a configured jscodeshift api, mirroring
+ * how other transform tests (and `runConfigCodemod`) drive transforms via the
+ * unified `(file, api) => string | null | undefined` contract.
+ *
+ * @param {string} source
+ * @param {string} [filePath]
+ * @returns {Promise<string|null>} the rewritten source, or null for no-op
+ */
+async function applyTransform(source, filePath = 'astryx.config.mjs') {
+ const {default: transform} = await import(
+ '../migrate-layout-components-to-experimental.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+ const j = jscodeshift.withParser('babel');
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
+ return transform({source, path: filePath}, api);
+}
+
+describe('migrate-layout-components-to-experimental — meta', () => {
+ it('declares itself as a config codemod', async () => {
+ const {meta} = await import(
+ '../migrate-layout-components-to-experimental.mjs'
+ );
+ expect(meta.codemodType).toBe('config');
+ expect(meta.title).toMatch(/layout\.components/);
+ expect(typeof meta.description).toBe('string');
+ });
+});
+
+describe('migrate-layout-components-to-experimental — string → {from}', () => {
+ it('normalizes a string entry to { from } (named import semantics)', async () => {
+ const input = `export default {
+ layout: {
+ components: {
+ KpiCard: '@/components/KpiCard',
+ },
+ },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).not.toBeNull();
+ // No longer under layout.
+ expect(output).not.toMatch(/layout\s*:/);
+ // Relocated under experimental.xle.components as { from }.
+ expect(output).toContain('experimental');
+ expect(output).toContain('xle');
+ expect(output).toMatch(/KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);
+ });
+
+ it('normalizes multiple string entries', async () => {
+ const input = `export default {
+ layout: {
+ components: {
+ KpiCard: '@/components/KpiCard',
+ Banner: '@/components/Banner',
+ },
+ },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toMatch(/KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);
+ expect(output).toMatch(/Banner:\s*\{\s*from:\s*['"]@\/components\/Banner['"]/);
+ });
+});
+
+describe('migrate-layout-components-to-experimental — object entries carried unchanged', () => {
+ it('preserves default: true (default import semantics)', async () => {
+ const input = `export default {
+ layout: {
+ components: {
+ Chart: { from: '@/c/Chart', default: true },
+ },
+ },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toContain("from: '@/c/Chart'");
+ expect(output).toContain('default: true');
+ expect(output).toContain('experimental');
+ expect(output).toContain('xle');
+ });
+
+ it('preserves description', async () => {
+ const input = `export default {
+ layout: {
+ components: {
+ Chart: { from: '@/c/Chart', description: 'A chart' },
+ },
+ },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toContain("from: '@/c/Chart'");
+ expect(output).toContain("description: 'A chart'");
+ });
+
+ it('preserves from/description/default and key order', async () => {
+ const input = `export default {
+ layout: {
+ components: {
+ Chart: { from: '@/c/Chart', description: 'A chart', default: true },
+ },
+ },
+};
+`;
+ const output = await applyTransform(input);
+ // Order: from, then description, then default.
+ expect(output).toMatch(
+ /from:\s*'@\/c\/Chart',\s*description:\s*'A chart',\s*default:\s*true/,
+ );
+ });
+
+ it('migrates a mix of string and object entries', async () => {
+ const input = `export default {
+ layout: {
+ components: {
+ KpiCard: '@/components/KpiCard',
+ Chart: { from: '@/c/Chart', default: true },
+ },
+ },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toMatch(/KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);
+ expect(output).toContain("from: '@/c/Chart'");
+ expect(output).toContain('default: true');
+ });
+});
+
+describe('migrate-layout-components-to-experimental — wrapper forms', () => {
+ it('handles bare object literal default export', async () => {
+ const input = `export default {
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toContain('experimental');
+ expect(output).toContain('xle');
+ });
+
+ it('handles createConfig({ ... }) wrapper', async () => {
+ const input = `import { createConfig } from '@astryxdesign/cli';
+
+export default createConfig({
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
+});
+`;
+ const output = await applyTransform(input);
+ expect(output).not.toBeNull();
+ expect(output).toContain('createConfig(');
+ expect(output).toContain('experimental');
+ expect(output).toContain('xle');
+ expect(output).toMatch(/KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);
+ expect(output).not.toMatch(/layout\s*:/);
+ });
+});
+
+describe('migrate-layout-components-to-experimental — placement', () => {
+ it('adds xle to a pre-existing experimental (no xle)', async () => {
+ const input = `export default {
+ experimental: { foo: true },
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toContain('foo: true');
+ expect(output).toContain('xle');
+ expect(output).toMatch(/KpiCard:\s*\{\s*from:/);
+ });
+});
+
+describe('migrate-layout-components-to-experimental — no-op cases', () => {
+ it('returns null when there is no layout', async () => {
+ const input = `export default { theme: 'dark' };\n`;
+ const output = await applyTransform(input);
+ expect(output).toBeNull();
+ });
+
+ it('returns null when layout has no components', async () => {
+ const input = `export default { layout: { foo: 1 } };\n`;
+ // layout exists but has no components → no-op (return null) BEFORE the
+ // "extra key" check, because there is nothing to migrate.
+ const output = await applyTransform(input);
+ expect(output).toBeNull();
+ });
+
+ it('returns null on an already-migrated config (idempotence-ish)', async () => {
+ const input = `export default {
+ experimental: { xle: { components: { KpiCard: { from: '@/components/KpiCard' } } } },
+};
+`;
+ const output = await applyTransform(input);
+ expect(output).toBeNull();
+ });
+});
+
+describe('migrate-layout-components-to-experimental — bail (throw) cases', () => {
+ it('throws when experimental.xle already exists', async () => {
+ const input = `export default {
+ experimental: { xle: { components: {} } },
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
+};
+`;
+ await expect(applyTransform(input)).rejects.toThrow(/experimental\.xle/);
+ });
+
+ it('throws when layout has an extra key besides components', async () => {
+ const input = `export default {
+ layout: {
+ components: { KpiCard: '@/components/KpiCard' },
+ spacing: 8,
+ },
+};
+`;
+ await expect(applyTransform(input)).rejects.toThrow(/other than/);
+ });
+
+ it('throws when an entry value is an identifier', async () => {
+ const input = `const Kpi = '@/components/KpiCard';
+export default {
+ layout: { components: { KpiCard: Kpi } },
+};
+`;
+ await expect(applyTransform(input)).rejects.toThrow(/cannot be safely migrated/);
+ });
+
+ it('throws when an entry value is a call expression', async () => {
+ const input = `export default {
+ layout: { components: { KpiCard: resolve('@/components/KpiCard') } },
+};
+`;
+ await expect(applyTransform(input)).rejects.toThrow(/cannot be safely migrated/);
+ });
+
+ it('throws on a non-object default export (variable reference)', async () => {
+ const input = `const config = { layout: { components: {} } };
+export default config;
+`;
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
+ });
+});
+
+describe('migrate-layout-components-to-experimental — end-to-end via runConfigCodemod', () => {
+ it('rewrites astryx.config.mjs on disk through the unified runner', async () => {
+ const {runConfigCodemod} = await import('../../../run-codemod.mjs');
+ const {default: transform, meta} = await import(
+ '../migrate-layout-components-to-experimental.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+
+ const originalCwd = process.cwd();
+ const tmpDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-v013-codemod-test-'),
+ );
+ try {
+ process.chdir(tmpDir);
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default {
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
+};
+`,
+ );
+
+ const entry = {
+ id: 'migrate-layout-components-to-experimental',
+ type: 'config',
+ codemod: {title: meta.title, transform},
+ package: 'core',
+ version: '0.1.3',
+ };
+ const log = {
+ step() {},
+ info() {},
+ success() {},
+ warn() {},
+ error() {},
+ message() {},
+ };
+ const result = runConfigCodemod(entry, {apply: true, log, jscodeshift});
+
+ expect(result.errors).toHaveLength(0);
+ expect(result.filesChanged).toBe(1);
+ const rewritten = fs.readFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ 'utf-8',
+ );
+ expect(rewritten).toContain('experimental');
+ expect(rewritten).toContain('xle');
+ expect(rewritten).toMatch(/KpiCard:\s*\{\s*from:/);
+ expect(rewritten).not.toMatch(/layout\s*:/);
+ } finally {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ }
+ });
+
+ it('surfaces a thrown bail as a structured error through runConfigCodemod', async () => {
+ const {runConfigCodemod} = await import('../../../run-codemod.mjs');
+ const {default: transform, meta} = await import(
+ '../migrate-layout-components-to-experimental.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+
+ const originalCwd = process.cwd();
+ const tmpDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-v013-codemod-test-'),
+ );
+ try {
+ process.chdir(tmpDir);
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default {
+ experimental: { xle: { components: {} } },
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
+};
+`,
+ );
+
+ const entry = {
+ id: 'migrate-layout-components-to-experimental',
+ type: 'config',
+ codemod: {title: meta.title, transform},
+ package: 'core',
+ version: '0.1.3',
+ };
+ const log = {
+ step() {},
+ info() {},
+ success() {},
+ warn() {},
+ error() {},
+ message() {},
+ };
+ const result = runConfigCodemod(entry, {apply: true, log, jscodeshift});
+
+ expect(result.filesChanged).toBe(0);
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0].error).toMatch(/experimental\.xle/);
+ } finally {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ }
+ });
+});
diff --git a/packages/cli/src/codemods/transforms/v0.1.3/index.mjs b/packages/cli/src/codemods/transforms/v0.1.3/index.mjs
new file mode 100644
index 0000000000..6f67a755c8
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.1.3/index.mjs
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file v0.1.3 transform manifest
+ *
+ * Lists all codemods for the v0.1.3 release in the order they should run.
+ */
+
+import migrateLayoutComponentsToExperimental, {
+ meta as migrateLayoutComponentsToExperimentalMeta,
+} from './migrate-layout-components-to-experimental.mjs';
+
+export default [
+ {
+ name: 'migrate-layout-components-to-experimental',
+ transform: migrateLayoutComponentsToExperimental,
+ meta: migrateLayoutComponentsToExperimentalMeta,
+ },
+];
diff --git a/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs b/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs
new file mode 100644
index 0000000000..fc14026a8c
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs
@@ -0,0 +1,260 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Codemod: migrate astryx.config `layout.components` to
+ * `experimental.xle.components`.
+ *
+ * The published 0.1.2 CLI read XLE app-component registration from
+ * `astryx.config.*` under `layout.components`. The next release relocates this
+ * to `experimental.xle.components`, validated by a strict schema that REJECTS
+ * unknown keys — so any consumer that still has `layout.components` would
+ * hard-error on upgrade. This codemod performs the straight relocation.
+ *
+ * The semantics are IDENTICAL between the old and new shapes; this is purely a
+ * MOVE plus a string→object normalization. No meaning is changed:
+ *
+ * OLD `layout.components` entry forms (from the 0.1.2 shim):
+ * - string `'X'` → a NAMED import; the KEY is both the local name and the
+ * export name.
+ * - object `{ from, description?, default? }` → `default: true` means a
+ * default import; otherwise a named import (key = export name).
+ *
+ * NEW `experimental.xle.components` entry shape (already shipped on the
+ * branch; unchanged here): `{ from, description?, default? }`, with the same
+ * semantics.
+ *
+ * So the migration is:
+ * - string `'X'` → `{ from: 'X' }`
+ * - object `{ from, description?, default? }` → carried over UNCHANGED
+ * (from/description/default preserved, key order preserved).
+ *
+ * The transform recognizes the config default export as EITHER a bare object
+ * literal (`export default { ... }`) or a `createConfig({ ... })` call wrapping
+ * an object literal (`export default createConfig({ ... })`). Anything else is
+ * not statically analyzable and the transform THROWS with a clear
+ * migrate-manually message (the unified config-codemod contract has no
+ * structured-error return — `runConfigCodemod` surfaces a thrown `err.message`
+ * as `{file, codemod, error}`).
+ */
+
+export const meta = {
+ title: 'Migrate astryx.config layout.components to experimental.xle.components',
+ description:
+ 'Relocates XLE app-component registration from the legacy ' +
+ '`layout.components` config key to `experimental.xle.components`. String ' +
+ 'entries (`Name: "@/path"`) are normalized to `{ from: "@/path" }` ' +
+ '(named import, key = export name); object entries are carried over ' +
+ 'unchanged (from/description/default preserved). Bails with a clear ' +
+ 'migrate-manually error when the config cannot be statically analyzed or ' +
+ 'when merging would be unsafe.',
+ codemodType: 'config',
+};
+
+const MANUAL =
+ 'migrate layout.components to experimental.xle.components manually';
+
+/**
+ * @param {{source: string, path: string}} file
+ * @param {{jscodeshift: Function}} api
+ * @returns {string|null}
+ */
+export default function transformer(file, api) {
+ const j = api.jscodeshift;
+ const root = j(file.source);
+
+ const defaultExports = root.find(j.ExportDefaultDeclaration);
+ if (defaultExports.size() === 0) {
+ throw new Error(
+ `could not statically analyze astryx config (no default export); ${MANUAL}`,
+ );
+ }
+
+ const declaration = defaultExports.paths()[0].node.declaration;
+
+ // Resolve the config object literal from either form:
+ // export default { ... }
+ // export default createConfig({ ... })
+ const configObject = resolveConfigObject(j, declaration);
+ if (!configObject) {
+ throw new Error(
+ `could not statically analyze astryx config; ${MANUAL}`,
+ );
+ }
+
+ // Locate the top-level `layout` property and its `components` value.
+ const layoutProp = findObjectProperty(j, configObject, 'layout');
+ if (!layoutProp) {
+ return null; // no layout → nothing to migrate
+ }
+ if (!j.ObjectExpression.check(layoutProp.value)) {
+ throw new Error(
+ `astryx config \`layout\` is not an object literal; ${MANUAL}`,
+ );
+ }
+
+ const componentsProp = findObjectProperty(j, layoutProp.value, 'components');
+ if (!componentsProp) {
+ return null; // no layout.components → nothing to migrate
+ }
+ if (!j.ObjectExpression.check(componentsProp.value)) {
+ throw new Error(
+ `astryx config \`layout.components\` is not an object literal; ${MANUAL}`,
+ );
+ }
+
+ // `components` was the only documented `layout` key. Anything else is
+ // unexpected and we cannot safely guess intent.
+ const otherLayoutKeys = layoutProp.value.properties.filter(
+ p => p !== componentsProp,
+ );
+ if (otherLayoutKeys.length > 0) {
+ throw new Error(
+ `astryx config \`layout\` has keys other than \`components\`; ${MANUAL}`,
+ );
+ }
+
+ // Build the migrated `components` object literal entry by entry.
+ const migratedComponents = buildMigratedComponents(j, componentsProp.value);
+
+ // Placement into `experimental.xle.components`.
+ const experimentalProp = findObjectProperty(j, configObject, 'experimental');
+ if (experimentalProp) {
+ if (!j.ObjectExpression.check(experimentalProp.value)) {
+ throw new Error(
+ `astryx config \`experimental\` is not an object literal; ${MANUAL}`,
+ );
+ }
+ const xleProp = findObjectProperty(j, experimentalProp.value, 'xle');
+ if (xleProp) {
+ // Can't safely merge into a pre-existing experimental.xle.
+ throw new Error(
+ `astryx config already defines \`experimental.xle\`; ${MANUAL}`,
+ );
+ }
+ experimentalProp.value.properties.push(
+ j.objectProperty(j.identifier('xle'), buildXleObject(j, migratedComponents)),
+ );
+ } else {
+ configObject.properties.push(
+ j.objectProperty(
+ j.identifier('experimental'),
+ j.objectExpression([
+ j.objectProperty(j.identifier('xle'), buildXleObject(j, migratedComponents)),
+ ]),
+ ),
+ );
+ }
+
+ // Remove the migrated data from `layout`. Since `components` was the only
+ // key (asserted above), remove the entire `layout` property.
+ configObject.properties = configObject.properties.filter(
+ p => p !== layoutProp,
+ );
+
+ return root.toSource();
+}
+
+/**
+ * Resolve the wrapped config object literal from a default-export declaration.
+ * Handles `{ ... }` and `createConfig({ ... })`.
+ * @returns {object|null} the ObjectExpression node, or null if not analyzable
+ */
+function resolveConfigObject(j, declaration) {
+ if (!declaration) return null;
+ if (j.ObjectExpression.check(declaration)) {
+ return declaration;
+ }
+ if (
+ j.CallExpression.check(declaration) &&
+ declaration.arguments.length >= 1 &&
+ j.ObjectExpression.check(declaration.arguments[0])
+ ) {
+ return declaration.arguments[0];
+ }
+ return null;
+}
+
+/**
+ * Find a (non-computed, non-spread) property on an object literal by key name.
+ * Supports Identifier and string-literal keys.
+ * @returns {object|undefined} the property node
+ */
+function findObjectProperty(j, objectExpression, name) {
+ return objectExpression.properties.find(prop => {
+ if (
+ !j.ObjectProperty.check(prop) &&
+ !j.Property.check(prop)
+ ) {
+ return false;
+ }
+ if (prop.computed) return false;
+ const key = prop.key;
+ if (j.Identifier.check(key)) return key.name === name;
+ if (j.StringLiteral.check(key)) return key.value === name;
+ if (j.Literal.check(key)) return key.value === name;
+ return false;
+ });
+}
+
+/**
+ * Build the migrated `components` ObjectExpression from the old one.
+ * @returns {object} ObjectExpression
+ */
+function buildMigratedComponents(j, oldComponents) {
+ const newProps = oldComponents.properties.map(prop => {
+ if (
+ (!j.ObjectProperty.check(prop) && !j.Property.check(prop)) ||
+ prop.computed
+ ) {
+ throw new Error(
+ `astryx config \`layout.components\` has a non-literal entry; ${MANUAL}`,
+ );
+ }
+
+ const value = prop.value;
+
+ // string `'X'` → `{ from: 'X' }`
+ if (j.StringLiteral.check(value) || (j.Literal.check(value) && typeof value.value === 'string')) {
+ return j.objectProperty(
+ cloneKey(j, prop.key),
+ j.objectExpression([
+ j.objectProperty(j.identifier('from'), cloneStringLiteral(j, value)),
+ ]),
+ );
+ }
+
+ // object `{ from, description?, default? }` → carried over UNCHANGED
+ if (j.ObjectExpression.check(value)) {
+ return j.objectProperty(cloneKey(j, prop.key), value);
+ }
+
+ // anything else (identifier, call, ternary, etc.) → cannot safely migrate
+ throw new Error(
+ `astryx config \`layout.components\` entry is neither a string nor an ` +
+ `object literal and cannot be safely migrated; ${MANUAL}`,
+ );
+ });
+
+ return j.objectExpression(newProps);
+}
+
+/** Build `{ components: <obj> }` for `experimental.xle`. */
+function buildXleObject(j, migratedComponents) {
+ return j.objectExpression([
+ j.objectProperty(j.identifier('components'), migratedComponents),
+ ]);
+}
+
+/** Clone a property key node so we don't reuse a node across the tree. */
+function cloneKey(j, key) {
+ if (j.Identifier.check(key)) return j.identifier(key.name);
+ if (j.StringLiteral.check(key)) return j.stringLiteral(key.value);
+ if (j.Literal.check(key)) return j.literal(key.value);
+ return key;
+}
+
+/** Build a fresh string literal preserving the original raw quoting if possible. */
+function cloneStringLiteral(j, value) {
+ if (j.StringLiteral.check(value)) return j.stringLiteral(value.value);
+ return j.literal(value.value);
+}
diff --git a/packages/cli/src/commands/component-ownership.test.mjs b/packages/cli/src/commands/component-ownership.test.mjs
new file mode 100644
index 0000000000..2902a187f7
--- /dev/null
+++ b/packages/cli/src/commands/component-ownership.test.mjs
@@ -0,0 +1,227 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ discoverIntegrationComponents,
+ discoverOwnedComponents,
+ findIntegrationComponentDoc,
+ findIntegrationComponentSource,
+ CORE_PACKAGE,
+} from '../lib/component-discovery.mjs';
+
+// The api `component()` reads integrations via Project.load(). In the vitest
+// environment, Vite's `server.fs.allow` only permits loading modules from
+// under `node_modules`, so a real astryx.config.mjs at a tmp root cannot be
+// imported. We therefore mock Project.load to return a project whose
+// `loadedIntegrations` are resolved (exactly the shape lib/integrations.mjs
+// produces) while keeping the integration's `components` dir on disk under
+// node_modules so its `.doc.mjs` files load normally.
+const projectLoadMock = vi.fn();
+vi.mock('../lib/project.mjs', () => ({
+ Project: {load: (...args) => projectLoadMock(...args)},
+}));
+
+// Import the api AFTER the mock is registered.
+const {component} = await import('../api/component.mjs');
+
+let tmpDir;
+
+const INTEGRATION_NAME = '@test/meta';
+const INTEGRATION_ISSUES = 'https://example.com/meta/issues';
+
+/**
+ * Build a consumer fixture:
+ * - packages/core symlinked to the real @astryxdesign/core (loadDocs source)
+ * - node_modules/@test/meta with a `components` dir using the same-stem
+ * source/doc convention (MetaAppShell.tsx + MetaAppShell.doc.mjs)
+ * Returns the absolute `components` dir so the Project.load mock can hand back a
+ * resolved integration entry.
+ */
+function createFixture({withSource = true, extraComponent = null} = {}) {
+ const realCoreDir = path.resolve(import.meta.dirname, '..', '..', '..', 'core');
+ const coreDir = path.join(tmpDir, 'packages', 'core');
+ fs.mkdirSync(path.dirname(coreDir), {recursive: true});
+ fs.symlinkSync(realCoreDir, coreDir);
+
+ const intDir = path.join(tmpDir, 'node_modules', '@test', 'meta');
+ const compDir = path.join(intDir, 'components');
+ fs.mkdirSync(compDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(intDir, 'package.json'),
+ JSON.stringify({name: INTEGRATION_NAME, version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(compDir, 'MetaAppShell.doc.mjs'),
+ `export const docs = {\n name: 'MetaAppShell',\n usage: { description: 'Meta-flavored app shell.' },\n props: [{ name: 'title', type: 'string', description: 'Header title' }],\n};\n`,
+ );
+ if (withSource) {
+ fs.writeFileSync(
+ path.join(compDir, 'MetaAppShell.tsx'),
+ "'use client';\nexport function MetaAppShell() { return null; }\n",
+ );
+ }
+ if (extraComponent) {
+ fs.writeFileSync(
+ path.join(compDir, `${extraComponent}.doc.mjs`),
+ `export const docs = {\n name: '${extraComponent}',\n usage: { description: '${extraComponent} from meta.' },\n};\n`,
+ );
+ fs.writeFileSync(
+ path.join(compDir, `${extraComponent}.tsx`),
+ `export function ${extraComponent}() { return null; }\n`,
+ );
+ }
+
+ const integration = {
+ name: INTEGRATION_NAME,
+ version: '1.2.3',
+ components: compDir,
+ templates: undefined,
+ codemods: undefined,
+ issuesUrl: INTEGRATION_ISSUES,
+ };
+ projectLoadMock.mockResolvedValue({
+ integrations: [INTEGRATION_NAME],
+ loadedIntegrations: [integration],
+ });
+ return {coreDir, intDir, compDir, integration};
+}
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-ownership-'));
+ projectLoadMock.mockReset();
+ // Default: no integrations (core only).
+ projectLoadMock.mockResolvedValue({integrations: [], loadedIntegrations: []});
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('discoverIntegrationComponents (ownership records)', () => {
+ it('records name, package, sourcePath, and issuesUrl for same-stem components', () => {
+ const {integration, compDir} = createFixture();
+ const records = discoverIntegrationComponents(integration);
+ expect(records).toHaveLength(1);
+ const rec = records[0];
+ expect(rec.name).toBe('MetaAppShell');
+ expect(rec.package).toBe(INTEGRATION_NAME);
+ expect(rec.issuesUrl).toBe(INTEGRATION_ISSUES);
+ expect(rec.sourcePath).toBe(path.join(compDir, 'MetaAppShell.tsx'));
+ expect(fs.existsSync(rec.sourcePath)).toBe(true);
+ });
+
+ it('records sourcePath: null when the integration ships docs without source', () => {
+ const {integration} = createFixture({withSource: false});
+ const [rec] = discoverIntegrationComponents(integration);
+ expect(rec.sourcePath).toBeNull();
+ });
+});
+
+describe('discoverOwnedComponents (core + integrations)', () => {
+ it('marks core components with the core package and integration components with their owner', () => {
+ const {coreDir, integration} = createFixture();
+ const records = discoverOwnedComponents(coreDir, [integration]);
+ const core = records.find(r => r.package === CORE_PACKAGE);
+ expect(core).toBeTruthy();
+ expect(core.issuesUrl).toBeUndefined();
+ const meta = records.find(r => r.name === 'MetaAppShell');
+ expect(meta.package).toBe(INTEGRATION_NAME);
+ expect(meta.issuesUrl).toBe(INTEGRATION_ISSUES);
+ expect(meta.sourcePath).toContain('MetaAppShell.tsx');
+ });
+});
+
+describe('findIntegrationComponentDoc / Source', () => {
+ it('finds doc + source by name', () => {
+ const {integration} = createFixture();
+ expect(findIntegrationComponentDoc(integration, 'MetaAppShell')).toContain('MetaAppShell.doc.mjs');
+ expect(findIntegrationComponentSource(integration, 'MetaAppShell')).toContain('MetaAppShell.tsx');
+ });
+
+ it('returns null source when none present', () => {
+ const {integration} = createFixture({withSource: false});
+ expect(findIntegrationComponentSource(integration, 'MetaAppShell')).toBeNull();
+ });
+});
+
+describe('component() — integration ownership via config', () => {
+ it('discovers a config integration component by package ownership (detail)', async () => {
+ createFixture();
+ const result = await component('MetaAppShell', {cwd: tmpDir});
+ expect(result.type).toBe('component.detail');
+ expect(result.data.name).toBe('MetaAppShell');
+ expect(result.data.package).toBe(INTEGRATION_NAME);
+ expect(result.data.sourceAvailable).toBe(true);
+ expect(result.data.import).toBe(`${INTEGRATION_NAME}/MetaAppShell`);
+ });
+
+ it('--package resolves the integration component', async () => {
+ createFixture();
+ const result = await component('MetaAppShell', {cwd: tmpDir, package: INTEGRATION_NAME});
+ expect(result.type).toBe('component.detail');
+ expect(result.data.package).toBe(INTEGRATION_NAME);
+ });
+
+ it('--source returns the integration source when available', async () => {
+ createFixture();
+ const result = await component('MetaAppShell', {cwd: tmpDir, source: true});
+ expect(result.type).toBe('component.detail.source');
+ expect(result.data.component).toBe('MetaAppShell');
+ expect(result.data.source).toContain('MetaAppShell');
+ });
+
+ it('--source throws ERR_NO_SOURCE when the integration ships no source', async () => {
+ createFixture({withSource: false});
+ await expect(
+ component('MetaAppShell', {cwd: tmpDir, source: true}),
+ ).rejects.toMatchObject({code: 'ERR_NO_SOURCE'});
+ });
+
+ it('errors with candidate packages when a name is ambiguous (core + integration)', async () => {
+ // 'AppShell' exists in core; add a same-named integration component.
+ createFixture({extraComponent: 'AppShell'});
+ let caught;
+ try {
+ await component('AppShell', {cwd: tmpDir});
+ } catch (e) {
+ caught = e;
+ }
+ expect(caught).toBeTruthy();
+ expect(caught.code).toBe('ERR_UNKNOWN_COMPONENT');
+ const pkgs = (caught.suggestions ?? []).map(s => s.name);
+ expect(pkgs).toContain(CORE_PACKAGE);
+ expect(pkgs).toContain(INTEGRATION_NAME);
+ });
+
+ it('--package disambiguates an ambiguous name to core', async () => {
+ createFixture({extraComponent: 'AppShell'});
+ const result = await component('AppShell', {cwd: tmpDir, package: CORE_PACKAGE});
+ expect(result.type).toBe('component.detail');
+ expect(result.data.package).toBe(CORE_PACKAGE);
+ });
+
+ it('--package disambiguates an ambiguous name to the integration', async () => {
+ createFixture({extraComponent: 'AppShell'});
+ const result = await component('AppShell', {cwd: tmpDir, package: INTEGRATION_NAME});
+ expect(result.type).toBe('component.detail');
+ expect(result.data.package).toBe(INTEGRATION_NAME);
+ });
+
+ it('JSON list includes integration components as {name, package} objects', async () => {
+ createFixture();
+ const result = await component(undefined, {cwd: tmpDir, list: true});
+ expect(result.type).toBe('component.list');
+ const allEntries = Object.values(result.data).flat();
+ for (const entry of allEntries) {
+ expect(typeof entry.name).toBe('string');
+ expect(typeof entry.package).toBe('string');
+ }
+ const meta = allEntries.find(e => e.name === 'MetaAppShell');
+ expect(meta).toBeTruthy();
+ expect(meta.package).toBe(INTEGRATION_NAME);
+ expect(allEntries.some(e => e.package === CORE_PACKAGE)).toBe(true);
+ });
+});
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index 1321ebf880..4b9ecc7640 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -24,6 +24,8 @@ import {cliError} from '../../lib/cli-error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {component as componentApi} from '../../api/component.mjs';
import {findRelatedBlocks} from '../../api/template.mjs';
+import {Project} from '../../lib/project.mjs';
+import {warnOnIntegrationIssues} from '../../lib/integration-warnings.mjs';
export function registerComponent(program) {
program
@@ -55,6 +57,16 @@ export function registerComponent(program) {
return;
}
+ // Non-blocking nudge: if any configured integration has validation
+ // issues, print one compact line to stderr pointing at
+ // validate-integration. Best-effort; suppressed in --json mode.
+ try {
+ const project = await Project.load(process.cwd());
+ await warnOnIntegrationIssues(project.loadedIntegrations, {json});
+ } catch {
+ // Never let the nudge break the command.
+ }
+
let result;
try {
result = await componentApi(name, {
@@ -82,27 +94,49 @@ export function registerComponent(program) {
switch (result.type) {
case 'component.list': {
- // --detail brief (default for list views) — names with import paths.
+ // --detail brief (default for list views). The API now returns
+ // package-qualified entries ({name, package}); the human view omits
+ // the core package label for readability but ALWAYS shows the package
+ // for integration components (and whenever names collide).
+ const CORE_PKG = '@astryxdesign/core';
+ // Names that appear under more than one package across the whole
+ // listing — these must always be package-qualified to disambiguate.
+ const nameCounts = new Map();
+ for (const items of Object.values(result.data)) {
+ for (const item of items) {
+ const set = nameCounts.get(item.name) ?? new Set();
+ set.add(item.package);
+ nameCounts.set(item.name, set);
+ }
+ }
+ const isCollision = n => (nameCounts.get(n)?.size ?? 0) > 1;
+ const pkgSuffix = item => {
+ if (item.package !== CORE_PKG) return ` [${item.package}]`;
+ if (isCollision(item.name)) return ` [${item.package}]`;
+ return '';
+ };
+
if (options.category) {
const [cat, comps] = Object.entries(result.data)[0];
humanLog(`\n${cat}:`);
- for (const comp of comps) {
- const importPath = resolveImportPath(coreDir, comp);
- humanLog(` ${comp} ← ${importPath}`);
+ for (const item of comps) {
+ const importPath = resolveImportPath(coreDir, item.name);
+ humanLog(` ${item.name} ← ${importPath}${pkgSuffix(item)}`);
}
humanLog('');
} else {
humanLog('');
for (const [key, comps] of Object.entries(result.data)) {
- const isUngrouped = comps.length === 1 && comps[0] === key;
+ const isUngrouped = comps.length === 1 && comps[0]?.name === key;
if (isUngrouped) {
- const importPath = resolveImportPath(coreDir, key);
- humanLog(`${key} ← ${importPath}`);
+ const item = comps[0];
+ const importPath = resolveImportPath(coreDir, item.name);
+ humanLog(`${item.name} ← ${importPath}${pkgSuffix(item)}`);
} else {
humanLog(`${key} (group)`);
- for (const comp of comps) {
- const importPath = resolveImportPath(coreDir, comp);
- humanLog(` ${comp} ← ${importPath}`);
+ for (const item of comps) {
+ const importPath = resolveImportPath(coreDir, item.name);
+ humanLog(` ${item.name} ← ${importPath}${pkgSuffix(item)}`);
}
}
}
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
index 88d9def659..21451079a5 100644
--- a/packages/cli/src/commands/discover.mjs
+++ b/packages/cli/src/commands/discover.mjs
@@ -10,7 +10,6 @@
* astryx discover searchterm Search across all packages
*/
-import {loadConfig} from '../lib/config.mjs';
import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
@@ -45,27 +44,17 @@ export function registerDiscover(program) {
switch (result.type) {
case 'discover.list': {
if (result.data.length === 0) {
- const config = await loadConfig();
humanLog('');
- if (config.packages.length === 0) {
- humanLog('No package directories configured.');
+ if (result.meta && result.meta.configured === false) {
+ humanLog('No integrations configured.');
humanLog('');
- humanLog('Add a packages field to astryx.config.mjs:');
+ humanLog('Add integration package names to astryx.config.mjs:');
humanLog('');
humanLog(' export default {');
- humanLog(" packages: ['/path/to/your/libs'],");
+ humanLog(" integrations: ['@scope/your-integration'],");
humanLog(' };');
} else {
- humanLog('No external packages found.');
- humanLog('');
- humanLog('Packages opt in by adding an "astryx" field to package.json:');
- humanLog('');
- humanLog(' {');
- humanLog(' "astryx": {');
- humanLog(' "docs": "./src",');
- humanLog(' "category": "Common"');
- humanLog(' }');
- humanLog(' }');
+ humanLog('No external components found in configured integrations.');
}
humanLog('');
} else {
diff --git a/packages/cli/src/commands/doctor.test.mjs b/packages/cli/src/commands/doctor.test.mjs
index 9b1bc06ec2..5797e84b49 100644
--- a/packages/cli/src/commands/doctor.test.mjs
+++ b/packages/cli/src/commands/doctor.test.mjs
@@ -132,7 +132,7 @@ describe('doctor — individual checks', () => {
);
const configPath = path.join(fixtureDir, 'astryx.config.mjs');
try {
- fs.writeFileSync(configPath, 'export default { theme: "default" };');
+ fs.writeFileSync(configPath, 'export default { integrations: [] };');
const res = await checkConfig({cwd: fixtureDir, configPath});
if (res.status !== 'pass') {
throw new Error(`expected pass, got ${res.status}: ${res.message}`);
@@ -158,13 +158,13 @@ describe('doctor — individual checks', () => {
}
});
- it('config: FAIL when packages is the wrong shape', async () => {
+ it('config: FAIL when default export is not an object', async () => {
const fixtureDir = fs.mkdtempSync(
path.join(path.dirname(new URL(import.meta.url).pathname), '__doctor_cfg_'),
);
const configPath = path.join(fixtureDir, 'astryx.config.mjs');
try {
- fs.writeFileSync(configPath, 'export default { packages: [123] };');
+ fs.writeFileSync(configPath, 'export default 123;');
const res = await checkConfig({cwd: fixtureDir, configPath});
expect(res.status).toBe('fail');
} finally {
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
deleted file mode 100644
index f054cad9b1..0000000000
--- a/packages/cli/src/commands/gap-report.mjs
+++ /dev/null
@@ -1,464 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file gap-report command — File a gap report for missing Astryx capabilities
- *
- * Interactive and non-interactive modes for reporting gaps in the design system.
- * Creates GitHub issues with the `gap-report` label.
- *
- * Includes `gap-report setup` subcommand for configuring gap report delivery.
- */
-
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import * as p from '@clack/prompts';
-import {
- buildGapReportPreview,
- checkGhCli,
- createGapReport,
- loadGapReportConfig,
- GAP_CATEGORIES,
-} from '../utils/github.mjs';
-import {getRunPrefix} from '../utils/package-manager.mjs';
-import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
-import {cliError} from '../lib/cli-error.mjs';
-import {ERROR_CODES} from '../lib/error-codes.mjs';
-
-/**
- * Decide whether we're in a context safe to actually file a report.
- *
- * Returns true ONLY when the user has explicitly opted in via --commit, OR
- * we're in an interactive TTY session AND --dry-run was not requested.
- *
- * Defaults are intentionally conservative: in CI, when piped, when --json is
- * set, or when neither --commit nor a TTY is present, we dry-run.
- */
-export function shouldActuallyFile({
- commit = false,
- dryRun = false,
- json = false,
- isTTY = process.stdout.isTTY,
-} = {}) {
- if (dryRun) return false;
- if (commit) return true;
- if (json) return false;
- if (!isTTY) return false;
- // Interactive TTY without --commit: caller must show a confirmation prompt.
- return true;
-}
-
-/**
- * Render a human-readable preview of the gap report that would be filed.
- */
-export function formatPreview(preview) {
- const lines = [];
- if (preview.mode === 'github') {
- lines.push(`Would file GitHub issue on ${preview.repo}:`);
- } else if (preview.mode === 'custom') {
- lines.push(`Would invoke custom command: ${preview.command}`);
- } else {
- lines.push('Gap reporting is disabled (no action would be taken).');
- return lines.join('\n');
- }
- lines.push('');
- lines.push(` Title: ${preview.title}`);
- lines.push('');
- lines.push(' Body:');
- for (const ln of preview.body.split('\n')) {
- lines.push(` ${ln}`);
- }
- lines.push('');
- lines.push(' Labels: gap-report');
- return lines.join('\n');
-}
-
-function isCancel(value) {
- if (p.isCancel(value)) {
- p.cancel('Gap report cancelled.');
- process.exit(0);
- }
- return value;
-}
-
-/**
- * Update or insert the gapReport key in astryx.config.mjs.
- * Preserves existing keys (e.g. theme).
- */
-function writeGapReportConfig(targetDir, gapReportValue) {
- const configPath = path.join(targetDir, 'astryx.config.mjs');
-
- if (fs.existsSync(configPath)) {
- let content = fs.readFileSync(configPath, 'utf-8');
-
- // Replace existing gapReport key (handles both `false` and `{ command: '...' }`)
- if (/gapReport\s*:/.test(content)) {
- content = content.replace(
- /gapReport\s*:\s*(?:\{[^}]*\}|false|true)\s*,?/s,
- `gapReport: ${gapReportValue},`,
- );
- } else {
- // Insert before the closing `};`
- content = content.replace(
- /(\n};?\s*)$/,
- `\n gapReport: ${gapReportValue},$1`,
- );
- }
-
- fs.writeFileSync(configPath, content);
- } else {
- const content = `/**
- * Astryx Configuration
- * Generated by \`astryx gap-report setup\`
- */
-export default {
- gapReport: ${gapReportValue},
-};
-`;
- fs.writeFileSync(configPath, content);
- }
-
- return configPath;
-}
-
-export function registerGapReport(program) {
- const gapCmd = program
- .command('gap-report')
- .description('Report a gap in the design system');
-
- // --- setup subcommand ---
- gapCmd
- .command('setup')
- .description('Configure where gap reports are sent')
- .action(async () => {
- p.intro('Gap report setup');
-
- const config = await loadGapReportConfig();
- const currentMode = !config.enabled
- ? 'disabled'
- : config.command
- ? 'custom'
- : 'github';
-
- const mode = isCancel(
- await p.select({
- message: `How should gap reports be delivered? (current: ${currentMode})`,
- options: [
- {
- value: 'github',
- label: 'GitHub Issues',
- hint: 'Creates issues on facebookexperimental/xds (requires gh CLI)',
- },
- {
- value: 'custom',
- label: 'Custom command',
- hint: 'Run a script that receives the report as JSON on stdin',
- },
- {
- value: 'disabled',
- label: 'Disabled',
- hint: 'Turn off gap reporting entirely',
- },
- ],
- }),
- );
-
- let configValue;
- const targetDir = process.cwd();
-
- if (mode === 'disabled') {
- configValue = 'false';
- writeGapReportConfig(targetDir, configValue);
- p.log.success('Gap reporting disabled.');
- } else if (mode === 'custom') {
- const command = isCancel(
- await p.text({
- message: 'Path to script:',
- placeholder: './scripts/report-gap.sh',
- validate: val => {
- if (!val.trim()) return 'Script path is required';
- },
- }),
- );
-
- configValue = `{ command: '${command.trim()}' }`;
- writeGapReportConfig(targetDir, configValue);
-
- p.log.success(`Gap reports will be sent to: ${command.trim()}`);
- p.note(
- 'Your script receives JSON on stdin with these fields:\n' +
- ' component, category, categoryLabel, intention,\n' +
- ' detail, source, timestamp\n\n' +
- 'Anything printed to stdout is shown to the user.',
- 'Script contract',
- );
- } else {
- // GitHub mode — remove gapReport key or set to default
- const configPath = path.join(targetDir, 'astryx.config.mjs');
- if (fs.existsSync(configPath)) {
- let content = fs.readFileSync(configPath, 'utf-8');
- // Remove the gapReport line entirely to use default
- content = content.replace(
- /\s*gapReport\s*:\s*(?:\{[^}]*\}|false|true)\s*,?/s,
- '',
- );
- fs.writeFileSync(configPath, content);
- }
-
- if (!checkGhCli()) {
- p.log.warning(
- 'gh CLI is not installed or not authenticated.\n' +
- 'Install from https://cli.github.com and run `gh auth login`.',
- );
- } else {
- p.log.success(
- 'Gap reports will create GitHub issues on facebookexperimental/xds.',
- );
- }
- }
-
- p.outro('Configuration saved to astryx.config.mjs');
- });
-
- // --- main gap-report command ---
- gapCmd
- .option('--component <name>', 'Component name')
- .option('--category <category>', 'Gap category')
- .option('--reason <reason>', 'What capability was missing')
- .option('--list-categories', 'List valid gap categories')
- .option(
- '--dry-run',
- 'Print the issue that would be filed without contacting GitHub. Default in CI / non-TTY / --json mode.',
- )
- .option(
- '--commit',
- 'Actually file the issue. Required in non-interactive mode (CI, piped, --json).',
- )
- .addHelpText(
- 'after',
- '\nSafety:\n' +
- ' Set ASTRYX_GAP_REPORT=off to disable gap reporting entirely.\n' +
- ' In non-interactive mode (CI, piped stdout, --json), gap-report is\n' +
- ' dry-run by default. Pass --commit to actually file an issue.\n' +
- ' In interactive mode, you will always be shown a confirmation prompt.\n',
- )
- .action(async options => {
- const json = program.opts().json || false;
-
- if (options.listCategories) {
- if (json) return jsonOut('gap-report.categories', GAP_CATEGORIES);
- for (const cat of GAP_CATEGORIES) {
- humanLog(` ${cat.value.padEnd(20)} ${cat.label}`);
- }
- return;
- }
-
- const config = await loadGapReportConfig();
- if (!config.enabled) {
- if (json)
- return jsonError(
- 'Gap reporting is disabled',
- undefined,
- ERROR_CODES.ERR_GAP_REPORT_FAILED,
- );
- humanLog(
- `Gap reporting is disabled (ASTRYX_GAP_REPORT=off or astryx.config.mjs).\n` +
- `Run \`${getRunPrefix()} astryx gap-report setup\` to configure.`,
- );
- return;
- }
-
- // We only need gh available when we'd actually file. For dry-run, skip
- // the gh check so users can preview output in CI without `gh` installed.
- const willFile = shouldActuallyFile({
- commit: options.commit,
- dryRun: options.dryRun,
- json,
- });
-
- if (willFile && !config.command && !checkGhCli()) {
- const msg =
- 'GitHub CLI (gh) is not installed or not authenticated. ' +
- 'Install it from https://cli.github.com and run `gh auth login`. ' +
- `Or run \`${getRunPrefix()} astryx gap-report setup\` to configure a custom command.`;
- cliError(msg, {code: ERROR_CODES.ERR_GH_CLI});
- return;
- }
-
- const isNonInteractive =
- options.component && options.category && options.reason;
-
- if (isNonInteractive) {
- // Non-interactive mode for LLM/script use
- const validCategory = GAP_CATEGORIES.find(
- c => c.value === options.category,
- );
- if (!validCategory) {
- cliError(
- `Invalid category "${options.category}". Valid: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
- {code: ERROR_CODES.ERR_UNKNOWN_CATEGORY},
- );
- return;
- }
-
- const preview = await buildGapReportPreview({
- component: options.component,
- category: options.category,
- intention: options.reason,
- source: 'cli',
- });
-
- if (!willFile) {
- // DRY-RUN: print what would be filed and exit cleanly.
- if (json) {
- return jsonOut('gap-report.dryRun', {
- dryRun: true,
- wouldFile: preview.mode !== 'disabled',
- mode: preview.mode,
- title: preview.title,
- body: preview.body,
- repo: preview.repo,
- command: preview.command || null,
- hint:
- 'Re-run with --commit to actually file. ' +
- 'Default is dry-run in non-interactive contexts.',
- });
- }
- humanLog(formatPreview(preview));
- humanLog(
- '\n[dry-run] Nothing was filed. Re-run with --commit to file this report.',
- );
- return;
- }
-
- try {
- const url = await createGapReport({
- component: options.component,
- category: options.category,
- intention: options.reason,
- source: 'cli',
- });
- if (json)
- return jsonOut('gap-report.file', {
- filed: !!url,
- url: url || null,
- });
- if (url) {
- humanLog(`\n✓ Gap report filed: ${url}\n`);
- } else {
- humanLog('\nGap reporting is disabled via configuration.\n');
- }
- } catch (err) {
- cliError(`Filing gap report failed: ${err.message}`, {
- code: ERROR_CODES.ERR_GAP_REPORT_FAILED,
- });
- return;
- }
- return;
- }
-
- // --json without --component/--category/--reason can't go interactive —
- // emit a structured error explaining the required flags.
- if (json) {
- return jsonError(
- 'gap-report --json requires --component, --category, and --reason. ' +
- 'Run with --list-categories to see valid categories.',
- undefined,
- ERROR_CODES.ERR_INVALID_ARGUMENT,
- );
- }
-
- // Interactive mode
- p.intro('Report a gap');
-
- const component = isCancel(
- await p.text({
- message: 'Which component is this about?',
- placeholder: 'e.g. Button, Table, or "general"',
- validate: val => {
- if (!val.trim()) return 'Component name is required';
- },
- }),
- );
-
- const category = isCancel(
- await p.select({
- message: 'What kind of gap is this?',
- options: GAP_CATEGORIES,
- }),
- );
-
- const intention = isCancel(
- await p.text({
- message: 'What were you trying to achieve?',
- placeholder:
- 'e.g. "Need a compact variant for use in dense data tables"',
- validate: val => {
- if (!val.trim())
- return 'Please describe what you were trying to do';
- },
- }),
- );
-
- const detail = isCancel(
- await p.text({
- message: 'Any additional context? (optional)',
- placeholder: 'Press Enter to skip',
- }),
- );
-
- const previewArgs = {
- component: component.trim(),
- category,
- intention: intention.trim(),
- detail: detail?.trim() || undefined,
- source: 'interactive',
- };
-
- const preview = await buildGapReportPreview(previewArgs);
-
- // Always show the user exactly what would be filed before sending.
- p.note(
- `${preview.mode === 'github' ? `Repo: ${preview.repo}` : `Custom command: ${preview.command}`}\n\n` +
- `Title:\n ${preview.title}\n\n` +
- `Body:\n${preview.body
- .split('\n')
- .map(l => ` ${l}`)
- .join('\n')}`,
- 'Preview — this is exactly what will be filed',
- );
-
- if (options.dryRun) {
- p.outro('[dry-run] Nothing filed.');
- return;
- }
-
- const confirm = isCancel(
- await p.confirm({
- message: 'File this gap report now?',
- initialValue: false,
- }),
- );
-
- if (!confirm) {
- p.outro('Cancelled — nothing was filed.');
- return;
- }
-
- const s = p.spinner();
- s.start('Filing gap report');
-
- try {
- const url = await createGapReport(previewArgs);
- s.stop(url ? 'Gap report filed' : 'Gap reporting is disabled');
- if (url) {
- p.log.success(url);
- }
- } catch (err) {
- s.stop('Failed to file gap report');
- p.log.error(err.message);
- process.exit(1);
- }
-
- p.outro('Thanks for the feedback!');
- });
-}
diff --git a/packages/cli/src/commands/gap-report.test.mjs b/packages/cli/src/commands/gap-report.test.mjs
deleted file mode 100644
index 46200d4f16..0000000000
--- a/packages/cli/src/commands/gap-report.test.mjs
+++ /dev/null
@@ -1,168 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Tests for gap-report safety gates: dry-run-by-default in non-interactive
- * mode, --commit required to actually file, --no-report suppression in swizzle,
- * and ASTRYX_GAP_REPORT=off honored everywhere.
- *
- * Regression cases for issues #2370 and #2371: real gap-report issues filed
- * unintentionally in CI/non-TTY runs.
- */
-
-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {shouldActuallyFile, formatPreview} from './gap-report.mjs';
-
-describe('shouldActuallyFile', () => {
- it('returns false in non-TTY mode by default (dry-run by default in CI)', () => {
- expect(shouldActuallyFile({isTTY: false})).toBe(false);
- });
-
- it('returns false when --json is set, even with TTY', () => {
- expect(shouldActuallyFile({isTTY: true, json: true})).toBe(false);
- });
-
- it('returns false when --dry-run is explicitly set', () => {
- expect(shouldActuallyFile({isTTY: true, dryRun: true})).toBe(false);
- });
-
- it('returns true in TTY mode without dry-run/json (interactive prompts will gate)', () => {
- expect(shouldActuallyFile({isTTY: true})).toBe(true);
- });
-
- it('returns true with --commit even in non-TTY mode', () => {
- expect(shouldActuallyFile({isTTY: false, commit: true})).toBe(true);
- });
-
- it('--commit overrides --json being set', () => {
- expect(shouldActuallyFile({isTTY: false, commit: true, json: true})).toBe(
- true,
- );
- });
-
- it('--dry-run wins over --commit (safety)', () => {
- expect(shouldActuallyFile({isTTY: true, commit: true, dryRun: true})).toBe(
- false,
- );
- });
-});
-
-describe('formatPreview', () => {
- it('renders a github-mode preview with title, body, and repo', () => {
- const out = formatPreview({
- mode: 'github',
- repo: 'facebookexperimental/xds',
- title: '[gap] Button: missing compact variant',
- body: '## User Intention\n\nNeed a compact variant',
- });
- expect(out).toContain(
- 'Would file GitHub issue on facebookexperimental/xds',
- );
- expect(out).toContain('[gap] Button');
- expect(out).toContain('Need a compact variant');
- expect(out).toContain('Labels: gap-report');
- });
-
- it('renders disabled mode without filing instructions', () => {
- const out = formatPreview({mode: 'disabled'});
- expect(out).toContain('Gap reporting is disabled');
- expect(out).not.toContain('Would file');
- });
-
- it('renders custom-command mode', () => {
- const out = formatPreview({
- mode: 'custom',
- command: './scripts/report.sh',
- title: 't',
- body: 'b',
- });
- expect(out).toContain('Would invoke custom command: ./scripts/report.sh');
- });
-});
-
-describe('ASTRYX_GAP_REPORT=off env var', () => {
- let originalEnv;
- beforeEach(() => {
- originalEnv = process.env.ASTRYX_GAP_REPORT;
- });
- afterEach(() => {
- if (originalEnv === undefined) delete process.env.ASTRYX_GAP_REPORT;
- else process.env.ASTRYX_GAP_REPORT = originalEnv;
- vi.resetModules();
- });
-
- it('disables gap reporting when set to "off"', async () => {
- process.env.ASTRYX_GAP_REPORT = 'off';
- vi.resetModules();
- const {loadGapReportConfig, createGapReport} =
- await import('../utils/github.mjs');
- await expect(loadGapReportConfig()).resolves.toMatchObject({
- enabled: false,
- });
-
- // createGapReport must return null and never invoke gh.
- const result = await createGapReport({
- component: 'Button',
- category: 'other',
- intention: 'test',
- });
- expect(result).toBeNull();
- });
-
- it('also accepts "false" and "0" as disable values', async () => {
- process.env.ASTRYX_GAP_REPORT = 'false';
- vi.resetModules();
- let mod = await import('../utils/github.mjs');
- await expect(mod.loadGapReportConfig()).resolves.toMatchObject({
- enabled: false,
- });
-
- process.env.ASTRYX_GAP_REPORT = '0';
- vi.resetModules();
- mod = await import('../utils/github.mjs');
- await expect(mod.loadGapReportConfig()).resolves.toMatchObject({
- enabled: false,
- });
- });
-});
-
-describe('buildGapReportPreview', () => {
- let originalEnv;
- beforeEach(() => {
- originalEnv = process.env.ASTRYX_GAP_REPORT;
- // Force github mode (default) for these tests.
- delete process.env.ASTRYX_GAP_REPORT;
- });
- afterEach(() => {
- if (originalEnv === undefined) delete process.env.ASTRYX_GAP_REPORT;
- else process.env.ASTRYX_GAP_REPORT = originalEnv;
- });
-
- it('renders title and body without invoking gh', async () => {
- vi.resetModules();
- const {buildGapReportPreview} = await import('../utils/github.mjs');
- const preview = await buildGapReportPreview({
- component: 'Button',
- category: 'missing_variant',
- intention: 'Need compact variant for tables',
- });
- expect(preview.mode).toBe('github');
- expect(preview.enabled).toBe(true);
- expect(preview.title).toBe('[gap] Button: Need compact variant for tables');
- expect(preview.body).toContain('| **Component** | Button |');
- expect(preview.body).toContain('Need compact variant for tables');
- expect(preview.repo).toBe('facebookexperimental/xds');
- });
-
- it('reports disabled mode when env var is off', async () => {
- process.env.ASTRYX_GAP_REPORT = 'off';
- vi.resetModules();
- const {buildGapReportPreview} = await import('../utils/github.mjs');
- const preview = await buildGapReportPreview({
- component: 'Button',
- category: 'other',
- intention: 'x',
- });
- expect(preview.mode).toBe('disabled');
- expect(preview.enabled).toBe(false);
- });
-});
diff --git a/packages/cli/src/commands/json-contract.test.mjs b/packages/cli/src/commands/json-contract.test.mjs
index b786178cdc..361a412de9 100644
--- a/packages/cli/src/commands/json-contract.test.mjs
+++ b/packages/cli/src/commands/json-contract.test.mjs
@@ -91,15 +91,6 @@ describe('--json contract: rejects before side effects', () => {
expect(fs.readdirSync(tmpDir)).toEqual([]);
});
- it('astryx gap-report setup --json rejects before prompting', () => {
- const {status, stdout} = runCli(['gap-report', 'setup', '--json'], {cwd: tmpDir});
- expect(status).toBe(1);
- const parsed = parseJson(stdout);
- expect(parsed.error).toMatch(/gap-report setup/);
- // No astryx.config.mjs written.
- expect(fs.existsSync(path.join(tmpDir, 'astryx.config.mjs'))).toBe(false);
- });
-
it('astryx theme --json (parent, no subcommand) rejects without printing help', () => {
const {status, stdout, stderr} = runCli(['theme', '--json'], {cwd: tmpDir});
expect(status).toBe(1);
@@ -145,29 +136,6 @@ describe('--json contract: supported commands emit valid envelopes', () => {
expect(Array.isArray(parsed.data.jsonSupported)).toBe(true);
});
- it('astryx gap-report --json --list-categories returns a typed envelope', () => {
- const {status, stdout} = runCli(['gap-report', '--json', '--list-categories'], {cwd: tmpDir});
- expect(status).toBe(0);
- const parsed = parseJson(stdout);
- expect(parsed.type).toBe('gap-report.categories');
- expect(Array.isArray(parsed.data)).toBe(true);
- });
-
- it('astryx gap-report --json without required flags emits a structured error (no clack)', () => {
- // Configure gap-report so it doesn't error on "disabled" — we want to
- // hit the "interactive prompt would start" branch.
- fs.writeFileSync(
- path.join(tmpDir, 'astryx.config.mjs'),
- 'export default { gapReport: { command: "true" } };\n',
- );
- const {status, stdout} = runCli(['gap-report', '--json'], {cwd: tmpDir});
- expect(status).toBe(1);
- const parsed = parseJson(stdout);
- expect(parsed.error).toMatch(/component/i);
- // Must not contain clack-rendered prompt characters.
- expect(stdout).not.toMatch(/Which component/);
- });
-
it('astryx upgrade --json --list returns the codemod list', () => {
const {status, stdout} = runCli(['upgrade', '--json', '--list'], {cwd: tmpDir});
expect(status).toBe(0);
diff --git a/packages/cli/src/commands/swizzle-gap-safety.test.mjs b/packages/cli/src/commands/swizzle-gap-safety.test.mjs
deleted file mode 100644
index 5e19a678ef..0000000000
--- a/packages/cli/src/commands/swizzle-gap-safety.test.mjs
+++ /dev/null
@@ -1,273 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * End-to-end safety tests for `astryx swizzle --gap` and `xds gap-report`.
- *
- * Critical: these tests must NEVER actually invoke `gh issue create`. We
- * defend in depth:
- *
- * 1. We spawn the CLI in a non-TTY pipe → triggers the dry-run gate.
- * 2. We set ASTRYX_GAP_REPORT=off as an extra belt-and-suspenders for tests
- * that would otherwise risk filing.
- * 3. We unset GH_TOKEN so that any unexpected `gh` invocation fails fast.
- * 4. We put a sabotaged `gh` shim earlier on PATH that blocks real
- * `gh issue create` calls and writes a marker file. Any successful
- * "filing" path leaves a marker we can assert against — so a regression
- * is detected even if the gate silently breaks.
- *
- * Regression cases for issues #2370 and #2371: real gap-report issues filed
- * unintentionally during a verification run because the non-interactive path
- * called `gh issue create` with no confirmation.
- */
-
-import {describe, it, expect, beforeAll, afterAll, beforeEach, afterEach} from 'vitest';
-import {spawnSync} from 'node:child_process';
-import * as fs from 'node:fs';
-import * as os from 'node:os';
-import * as path from 'node:path';
-import {fileURLToPath} from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const cliBin = path.resolve(__dirname, '../../bin/astryx.mjs');
-const repoRoot = path.resolve(__dirname, '../../../..');
-
-let shimDir;
-let markerFile;
-let baseEnv;
-
-beforeAll(() => {
- shimDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gh-shim-'));
- markerFile = path.join(shimDir, 'gh-issue-create-was-called.marker');
-
- // Sabotaged `gh` shim. Records ONLY `gh issue create` invocations to the
- // marker file, since that's the only command we want to detect as a
- // "would-have-filed" event. Other subcommands (auth status, label create)
- // succeed silently so they don't break the gh availability check or the
- // label-ensure path.
- const shim = `#!/usr/bin/env node
-import * as fs from 'node:fs';
-const args = process.argv.slice(2);
-const isIssueCreate = args[0] === 'issue' && args[1] === 'create';
-if (isIssueCreate) {
- fs.appendFileSync(${JSON.stringify(markerFile)}, JSON.stringify(args) + '\\n');
- process.stderr.write('TEST GUARD: real gh issue create blocked\\n');
- process.exit(1);
-}
-// Other commands (auth status, label create) succeed silently.
-process.exit(0);
-`;
- fs.writeFileSync(path.join(shimDir, 'gh'), shim);
- fs.chmodSync(path.join(shimDir, 'gh'), 0o755);
-
- baseEnv = {
- ...process.env,
- PATH: `${shimDir}:${process.env.PATH}`,
- // Belt-and-suspenders: even if a gate breaks, this disables the feature.
- // For tests that need the feature on, individual cases override this.
- GH_TOKEN: '',
- };
-});
-
-afterAll(() => {
- fs.rmSync(shimDir, {recursive: true, force: true});
-});
-
-function runXds(args, {env = {}, cwd = repoRoot} = {}) {
- // Reset marker for each run.
- if (fs.existsSync(markerFile)) fs.unlinkSync(markerFile);
- const result = spawnSync('node', [cliBin, ...args], {
- cwd,
- env: {...baseEnv, ...env},
- encoding: 'utf-8',
- });
- return {
- ...result,
- // True iff the CLI tried to call `gh issue create` — the actual filing
- // operation. Other gh subcommands (auth status, label create) are
- // ignored as benign.
- ghWasCalled: fs.existsSync(markerFile),
- ghCallArgs: fs.existsSync(markerFile)
- ? fs.readFileSync(markerFile, 'utf-8')
- : null,
- };
-}
-
-describe('gap-report: dry-run by default in non-interactive mode', () => {
- it('non-TTY pipe with all required flags → dry-run, exit 0, no gh call', () => {
- const r = runXds([
- 'gap-report',
- '--component',
- 'Button',
- '--category',
- 'missing_variant',
- '--reason',
- 'Test that we never file in non-interactive mode',
- ]);
- expect(r.status).toBe(0);
- expect(r.ghWasCalled).toBe(false);
- expect(r.stdout).toMatch(/dry-run/i);
- expect(r.stdout).toMatch(/Re-run with --commit/i);
- // Preview should include the title we'd file.
- expect(r.stdout).toContain('Button');
- });
-
- it('--json mode in non-TTY → structured dry-run JSON, no gh call', () => {
- const r = runXds([
- '--json',
- 'gap-report',
- '--component',
- 'Button',
- '--category',
- 'missing_variant',
- '--reason',
- 'JSON dry-run',
- ]);
- expect(r.status).toBe(0);
- expect(r.ghWasCalled).toBe(false);
- // jsonOut pretty-prints across multiple lines; parse the whole stdout
- // as JSON (after stripping any trailing whitespace).
- const parsed = JSON.parse(r.stdout.trim());
- expect(parsed.type).toBe('gap-report.dryRun');
- expect(parsed.data.dryRun).toBe(true);
- expect(parsed.data.title).toContain('Button');
- expect(parsed.data.wouldFile).toBe(true);
- });
-
- it('ASTRYX_GAP_REPORT=off → no gh call, even with --commit flag', () => {
- const r = runXds(
- [
- 'gap-report',
- '--component',
- 'Button',
- '--category',
- 'other',
- '--reason',
- 'should be disabled',
- '--commit',
- ],
- {env: {ASTRYX_GAP_REPORT: 'off'}},
- );
- // Should exit 0 with a "disabled" message; never calls gh.
- expect(r.ghWasCalled).toBe(false);
- expect(r.status).toBe(0);
- expect(r.stdout + r.stderr).toMatch(/disabled/i);
- });
-
- it('--commit in non-TTY mode WOULD invoke gh (verified via shim)', () => {
- // This proves --commit actually engages the file path. Our shim exits 1
- // so the CLI will report failure, but the marker proves gh was invoked
- // with the expected args.
- const r = runXds(
- [
- 'gap-report',
- '--component',
- 'Button',
- '--category',
- 'other',
- '--reason',
- 'commit flag should engage filing',
- '--commit',
- ],
- {env: {ASTRYX_GAP_REPORT: ''}}, // re-enable feature; shim will block real call
- );
- expect(r.ghWasCalled).toBe(true);
- expect(r.ghCallArgs).toContain('issue');
- expect(r.ghCallArgs).toContain('create');
- expect(r.ghCallArgs).toContain('facebookexperimental/xds');
- });
-});
-
-describe('swizzle --gap respects safety gates', () => {
- // swizzle's --output is path-safety guarded: absolute paths and `..`
- // traversal are rejected (see swizzle.path-safety.test.mjs). These gap
- // tests only care about the gh-call / status gates, so they write into a
- // *relative* output dir created under the repo root (a valid, in-root
- // target) and clean it up afterward. The CLI still resolves @astryxdesign/core via
- // findCoreDir walking up from the cwd.
- let swizzleOutDir;
- beforeEach(() => {
- swizzleOutDir = fs.mkdtempSync(path.join(repoRoot, '.xds-swizzle-gap-test-'));
- });
- afterEach(() => {
- if (swizzleOutDir) fs.rmSync(swizzleOutDir, {recursive: true, force: true});
- });
- // Relative path into the temp dir, so it passes the path-safety guard
- // (cwd === repoRoot for runXds by default).
- const relOut = () => path.relative(repoRoot, swizzleOutDir);
-
- it('swizzle --gap in non-TTY → dry-run, no gh call', () => {
- const r = runXds([
- 'swizzle',
- 'Button',
- '--output',
- relOut(),
- '--gap',
- 'Need a compact variant',
- '--gap-category',
- 'missing_variant',
- ]);
- expect(r.ghWasCalled).toBe(false);
- expect(r.status).toBe(0);
- expect(r.stdout).toMatch(/dry-run/i);
- });
-
- it('swizzle --gap --no-report → never engages gap reporting at all', () => {
- const r = runXds([
- 'swizzle',
- 'Button',
- '--output',
- relOut(),
- '--gap',
- 'Should be suppressed entirely',
- '--gap-category',
- 'missing_variant',
- '--no-report',
- ]);
- expect(r.ghWasCalled).toBe(false);
- expect(r.status).toBe(0);
- // Should not even show a dry-run preview — reporting is suppressed.
- expect(r.stdout).toMatch(/suppressed/i);
- expect(r.stdout).not.toMatch(/Would file GitHub issue/i);
- });
-
- it('swizzle --gap --no-report --commit → STILL no gh call (no-report wins)', () => {
- // Critical regression test: --no-report must beat --commit for the
- // --gap auto-file path. Otherwise CI scripts could file issues.
- const r = runXds(
- [
- 'swizzle',
- 'Button',
- '--output',
- relOut(),
- '--gap',
- 'should never file',
- '--gap-category',
- 'other',
- '--no-report',
- '--commit',
- ],
- {env: {ASTRYX_GAP_REPORT: ''}},
- );
- expect(r.ghWasCalled).toBe(false);
- expect(r.status).toBe(0);
- });
-
- it('swizzle --gap with ASTRYX_GAP_REPORT=off → no gh call', () => {
- const r = runXds(
- [
- 'swizzle',
- 'Button',
- '--output',
- relOut(),
- '--gap',
- 'should be disabled by env',
- '--gap-category',
- 'other',
- '--commit',
- ],
- {env: {ASTRYX_GAP_REPORT: 'off'}},
- );
- expect(r.ghWasCalled).toBe(false);
- expect(r.status).toBe(0);
- });
-});
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 1552875e2d..f089e2e572 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -3,12 +3,14 @@
/**
* @file swizzle command — Copy component source for customization
*
- * Resolves component source from packages/core/src/{Component}/,
- * copies non-test files to the output directory, and rewrites
- * relative imports to use '@astryxdesign/core' package paths.
+ * Resolves a component's owning package (core or a configured integration),
+ * copies its non-test/non-doc source files to the output directory, and
+ * rewrites escaping relative imports to use the OWNER package's subpaths.
*
- * After swizzling, optionally prompts the user to file a gap report
- * explaining why they needed to customize the component.
+ * After swizzling, prints a short maintainer feedback note pointing users at
+ * the owner's issue tracker so they can let the team know what gap led them to
+ * customize the component. The core feedback URL is routed through app config
+ * (`config.issuesUrl`); integration components use their manifest `issuesUrl`.
*/
import * as fs from 'node:fs';
@@ -20,27 +22,36 @@ import {
PathSafetyError,
isNonInteractive,
} from '../utils/path-safety.mjs';
-import {isInteractive} from '../utils/interactive.mjs';
import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
+import {checkGhCli} from '../utils/github.mjs';
+import {Project} from '../lib/project.mjs';
import {
- buildGapReportPreview,
- checkGhCli,
- createGapReport,
- loadGapReportConfig,
- GAP_CATEGORIES,
-} from '../utils/github.mjs';
-import {shouldActuallyFile, formatPreview} from './gap-report.mjs';
+ CORE_PACKAGE,
+ findIntegrationComponentDoc,
+ findIntegrationComponentSource,
+} from '../lib/component-discovery.mjs';
+
+/** Default issue tracker for maintainer feedback after swizzling. */
+const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';
/**
- * Rewrite relative imports that point outside the component directory
- * to use @astryxdesign/core package paths.
+ * Rewrite relative imports that point outside the component directory to use
+ * the OWNER package's subpaths. Imports within the copied directory (./x) are
+ * left untouched.
*
- * e.g. '../theme/tokens.stylex' -> '@astryxdesign/core/theme'
+ * e.g. with ownerPackage '@astryxdesign/core':
+ * '../theme/tokens.stylex' -> '@astryxdesign/core/theme'
* '../utils/mergeProps' -> '@astryxdesign/core/utils'
+ *
+ * `ownerPackage` defaults to '@astryxdesign/core' so existing core behavior is
+ * unchanged; integration components pass their own owning package.
+ *
+ * @param {string} content
+ * @param {string} [ownerPackage]
*/
-export function rewriteImports(content) {
+export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
// Match import/export from statements with relative paths going up
return content.replace(
/(from\s+['"])(\.\.\/.+?)(['"])/g,
@@ -51,12 +62,42 @@ export function rewriteImports(content) {
const parts = importPath.replace(/^\.\.\//, '').split('/');
const topDir = parts[0];
- // Map to @astryxdesign/core subpath
- return `${prefix}@astryxdesign/core/${topDir}${suffix}`;
+ // Map to the owner package subpath
+ return `${prefix}${ownerPackage}/${topDir}${suffix}`;
},
);
}
+/**
+ * Build the maintainer feedback note for a swizzled component.
+ *
+ * Returns { issuesUrl, ghCommand? } or null when no issues URL is available
+ * (an integration that ships no `issuesUrl`). When the issues URL is a GitHub
+ * issues URL and the `gh` CLI is available, a ready-to-run `gh issue create`
+ * command is included so the user can file feedback without leaving the
+ * terminal.
+ *
+ * @param {string} component bare component name (used in the issue title)
+ * @param {string|undefined} issuesUrl owner's issue tracker URL
+ * @returns {{issuesUrl: string, ghCommand?: string} | null}
+ */
+function buildFeedback(component, issuesUrl) {
+ if (!issuesUrl) return null;
+
+ const feedback = {issuesUrl};
+
+ // Accept any github.com/<owner>/<repo>/issues(/new)? form.
+ const match = issuesUrl.match(
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues(?:\/new)?\/?$/,
+ );
+ if (match && checkGhCli()) {
+ const [, owner, repo] = match;
+ feedback.ghCommand = `gh issue create --repo ${owner}/${repo} --title "[${component}] Swizzle feedback"`;
+ }
+
+ return feedback;
+}
+
function isCancel(value) {
if (p.isCancel(value)) {
p.cancel('Cancelled.');
@@ -65,26 +106,85 @@ function isCancel(value) {
return value;
}
+/**
+ * Load the configured integrations + core issues URL for `cwd`, swallowing any
+ * config errors so swizzle never hard-fails on a malformed/absent config. An
+ * empty list means "core only". The core issues URL is routed through the
+ * Project (config.issuesUrl, falling back to the default core tracker).
+ * @param {string} cwd
+ * @returns {Promise<{loadedIntegrations: Array<object>, issuesUrl: string|undefined, project: Project|null}>}
+ */
+async function loadConfigSafely(cwd) {
+ try {
+ const project = await Project.load(cwd);
+ return {
+ loadedIntegrations: project.loadedIntegrations,
+ issuesUrl: project.config.issuesUrl,
+ project,
+ };
+ } catch {
+ return {loadedIntegrations: [], issuesUrl: undefined, project: null};
+ }
+}
+
+/**
+ * Build the set of OWNER packages that provide a component with `name` across
+ * core + every loaded integration.
+ *
+ * Core ownership is determined by the source directory existing on disk
+ * (`coreDir/src/<name>`) so plain core components without a `.doc.mjs` still
+ * resolve as today. Integration ownership is determined by a same-stem doc file
+ * (`<name>.doc.{ts,mjs,js}`) via findIntegrationComponentDoc.
+ *
+ * @param {string} coreDir
+ * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations
+ * @param {string} name bare component name (no XDS/Astryx prefix)
+ * @param {string|undefined} coreIssuesUrl
+ * @returns {Array<{package: string, sourceDir: string|null, ownerPackage: string, issuesUrl: string|undefined}>}
+ */
+function resolveOwners(coreDir, loadedIntegrations, name, coreIssuesUrl) {
+ const owners = [];
+
+ const coreComponentDir = path.join(coreDir, 'src', name);
+ if (fs.existsSync(coreComponentDir)) {
+ owners.push({
+ package: CORE_PACKAGE,
+ sourceDir: coreComponentDir,
+ ownerPackage: CORE_PACKAGE,
+ issuesUrl: coreIssuesUrl || DEFAULT_ISSUES_URL,
+ });
+ }
+
+ for (const integration of loadedIntegrations) {
+ const docPath = findIntegrationComponentDoc(integration, name);
+ if (!docPath) continue;
+ const sourcePath = findIntegrationComponentSource(integration, name);
+ owners.push({
+ package: integration.name,
+ // The component's own folder — the directory containing its source.
+ sourceDir: sourcePath ? path.dirname(sourcePath) : null,
+ ownerPackage: integration.name,
+ issuesUrl: integration.issuesUrl,
+ });
+ }
+
+ return owners;
+}
+
+/** Whether a filename should be excluded from the swizzle copy. */
+function isExcludedFromCopy(file) {
+ return (
+ file.includes('.test.') || file.includes('.doc.') || file === 'README.md'
+ );
+}
+
export function registerSwizzle(program) {
program
.command('swizzle [component]')
.description('Copy component source for customization')
.option('--output <dir>', 'Output directory', './components/astryx')
+ .option('--package <pkg>', 'Scope to a specific owning package')
.option('--list', 'List available components')
- .option('--gap <reason>', 'File a gap report explaining why you swizzled')
- .option('--gap-category <category>', 'Gap category (for --gap mode)')
- .option(
- '--no-report',
- 'Suppress all gap reporting (interactive prompt AND --gap auto-filing)',
- )
- .option(
- '--dry-run',
- 'For --gap: print the issue that would be filed without contacting GitHub. Default in non-TTY / --json mode.',
- )
- .option(
- '--commit',
- 'For --gap: actually file the issue. Required in non-interactive mode.',
- )
.option('-f, --overwrite', 'Overwrite existing files without prompting')
.action(async (component, options) => {
const coreDir = findCoreDir(process.cwd());
@@ -115,9 +215,25 @@ export function registerSwizzle(program) {
}
const dirName = component.replace(/^XDS/, '');
- const componentDir = path.join(coreDir, 'src', dirName);
- if (!fs.existsSync(componentDir)) {
+ // Resolve the component's owning package(s) across core + integrations.
+ const {loadedIntegrations, project} = await loadConfigSafely(
+ process.cwd(),
+ );
+ // Core feedback URL is routed through the Project (config.issuesUrl,
+ // falling back to the default core tracker). When config load failed,
+ // resolveOwners applies the same default fallback.
+ const coreIssuesUrl = project
+ ? project.issuesUrl({package: CORE_PACKAGE})
+ : undefined;
+ const allOwners = resolveOwners(
+ coreDir,
+ loadedIntegrations,
+ dirName,
+ coreIssuesUrl,
+ );
+
+ if (allOwners.length === 0) {
cliError(`Component "${component}" not found.`, {
suggestions: components.slice(0, 10).map(n => ({name: n})),
code: ERROR_CODES.ERR_UNKNOWN_COMPONENT,
@@ -125,6 +241,48 @@ export function registerSwizzle(program) {
return;
}
+ let owner;
+ if (options.package) {
+ owner = allOwners.find(o => o.package === options.package);
+ if (!owner) {
+ cliError(
+ `Component "${dirName}" is not provided by package "${options.package}".`,
+ {
+ suggestions: allOwners.map(o => ({
+ name: o.package,
+ reason: 'provides this component',
+ })),
+ code: ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ },
+ );
+ return;
+ }
+ } else if (allOwners.length > 1) {
+ cliError(
+ `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
+ {
+ suggestions: allOwners.map(o => ({
+ name: o.package,
+ reason: 'provides this component',
+ })),
+ code: ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,
+ },
+ );
+ return;
+ } else {
+ owner = allOwners[0];
+ }
+
+ if (!owner.sourceDir || !fs.existsSync(owner.sourceDir)) {
+ cliError(
+ `No source found for "${dirName}" in package "${owner.package}".`,
+ {code: ERROR_CODES.ERR_NO_SOURCE},
+ );
+ return;
+ }
+
+ const componentDir = owner.sourceDir;
+
// Path-safety: --output must resolve inside cwd. Reject absolute
// paths and `..` traversal up front, before any directory is created.
let outputBase;
@@ -144,7 +302,7 @@ export function registerSwizzle(program) {
// Pre-flight overwrite check: collect files we'd write and detect
// collisions before mkdir/writeFile so we never half-clobber.
const sourceFiles = fs.readdirSync(componentDir).filter(file => {
- if (file.includes('.test.') || file === 'README.md') return false;
+ if (isExcludedFromCopy(file)) return false;
const stat = fs.statSync(path.join(componentDir, file));
return stat.isFile();
});
@@ -178,13 +336,13 @@ export function registerSwizzle(program) {
fs.mkdirSync(outputDir, {recursive: true});
- // Copy all non-test, non-README files
+ // Copy all non-test, non-doc, non-README files
const files = fs.readdirSync(componentDir);
let copied = 0;
for (const file of files) {
- // Skip test files and README
- if (file.includes('.test.') || file === 'README.md') continue;
+ // Skip test files, doc files, and README
+ if (isExcludedFromCopy(file)) continue;
const srcPath = path.join(componentDir, file);
const stat = fs.statSync(srcPath);
@@ -192,9 +350,9 @@ export function registerSwizzle(program) {
let content = fs.readFileSync(srcPath, 'utf-8');
- // Rewrite imports for .ts/.tsx files
+ // Rewrite escaping imports for .ts/.tsx files to the owner package.
if (file.endsWith('.ts') || file.endsWith('.tsx')) {
- content = rewriteImports(content);
+ content = rewriteImports(content, owner.ownerPackage);
}
fs.writeFileSync(path.join(outputDir, file), content);
@@ -204,214 +362,45 @@ export function registerSwizzle(program) {
const relOutput = path.relative(process.cwd(), outputDir);
const copiedFiles = files.filter(
f =>
- !f.includes('.test.') &&
- f !== 'README.md' &&
+ !isExcludedFromCopy(f) &&
fs.statSync(path.join(componentDir, f)).isFile(),
);
- // --- Gap reporting ---
-
- const gapConfig = await loadGapReportConfig();
- let gapReportUrl = null;
- let gapDryRunPreview = null;
+ const feedback = buildFeedback(dirName, owner.issuesUrl);
- // CRITICAL: --no-report must suppress BOTH the interactive prompt AND
- // the --gap auto-file path. Previously --gap bypassed --no-report.
- // commander sets options.report to false for `--no-report`.
- const reportingSuppressed = options.report === false;
-
- if (options.gap && !reportingSuppressed && gapConfig.enabled) {
- const category = options.gapCategory || 'other';
- const previewArgs = {
- component: dirName,
- category,
- intention: options.gap,
- source: 'llm-auto',
- };
-
- const willFile = shouldActuallyFile({
- commit: options.commit,
- dryRun: options.dryRun,
- json,
- });
-
- const preview = await buildGapReportPreview(previewArgs);
-
- if (!willFile) {
- // Dry-run: do NOT call gh. Surface what would have been filed.
- gapDryRunPreview = {
- dryRun: true,
- wouldFile: preview.mode !== 'disabled',
- mode: preview.mode,
- title: preview.title,
- body: preview.body,
- repo: preview.repo,
- command: preview.command || null,
- };
- } else if (gapConfig.command || checkGhCli()) {
- try {
- gapReportUrl = await createGapReport(previewArgs);
- } catch (err) {
- if (!json)
- console.error(
- `Warning: Could not file gap report: ${err.message}`,
- );
- }
- }
- }
-
- if (options.gap) {
- if (json)
- return jsonOut('swizzle.copy', {
- component: dirName,
- outputDir: relOutput,
- filesCopied: copied,
- files: copiedFiles.map(f => f),
- gapReport: gapReportUrl,
- gapReportDryRun: gapDryRunPreview,
- gapReportSuppressed: reportingSuppressed || !gapConfig.enabled,
- });
- humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
- humanLog(
- 'Relative imports have been rewritten to use @astryxdesign/core.',
- );
- humanLog('You can now customize the component source freely.\n');
- if (gapReportUrl) {
- humanLog(`✓ Gap report filed: ${gapReportUrl}\n`);
- } else if (gapDryRunPreview) {
- humanLog(
- formatPreview(
- await buildGapReportPreview({
- component: dirName,
- category: options.gapCategory || 'other',
- intention: options.gap,
- source: 'llm-auto',
- }),
- ),
- );
- humanLog(
- '\n[dry-run] No gap report was filed. Re-run with --commit to file.',
- );
- } else if (reportingSuppressed) {
- humanLog('Gap reporting suppressed by --no-report.');
- } else if (!gapConfig.enabled) {
- humanLog('Gap reporting is disabled via configuration.');
- } else if (!gapConfig.command && !checkGhCli()) {
- humanLog('Skipping gap report: gh CLI not available.');
- }
- return;
- }
-
- if (json)
- return jsonOut('swizzle.copy', {
+ if (json) {
+ /** @type {Record<string, unknown>} */
+ const payload = {
component: dirName,
+ package: owner.package,
outputDir: relOutput,
filesCopied: copied,
files: copiedFiles.map(f => f),
- });
+ };
+ if (feedback) payload.feedback = feedback;
+ return jsonOut('swizzle.copy', payload);
+ }
humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
humanLog(
- 'Relative imports have been rewritten to use @astryxdesign/core.',
+ `Relative imports have been rewritten to use ${owner.ownerPackage}.`,
);
humanLog('You can now customize the component source freely.\n');
- if (reportingSuppressed || !gapConfig.enabled) {
- return;
- }
-
- // Interactive gap report prompt
- //
- // This prompt is OPTIONAL — the swizzle copy already succeeded above.
- // In a non-interactive context (CI, piped I/O, no TTY) we must not
- // block on it; skip gracefully rather than hang. Use --gap with
- // explicit flags for non-interactive gap reporting.
- if (!isInteractive()) {
- return;
- }
-
- if (!gapConfig.command && !checkGhCli()) {
- // Silently skip if gh isn't available and no custom command configured
- return;
- }
-
- const shouldReport = isCancel(
- await p.confirm({
- message: 'Would you like to report why you swizzled this component?',
- initialValue: false,
- }),
- );
-
- if (!shouldReport) return;
-
- const category = isCancel(
- await p.select({
- message: 'What kind of gap is this?',
- options: GAP_CATEGORIES,
- }),
- );
-
- const intention = isCancel(
- await p.text({
- message: 'What were you trying to achieve?',
- placeholder:
- 'e.g. "Need a compact variant for use in dense data tables"',
- validate: val => {
- if (!val.trim())
- return 'Please describe what you were trying to do';
- },
- }),
- );
-
- const detail = isCancel(
- await p.text({
- message: 'Any additional context? (optional)',
- placeholder: 'Press Enter to skip',
- }),
- );
-
- const previewArgs = {
- component: dirName,
- category,
- intention: intention.trim(),
- detail: detail?.trim() || undefined,
- source: 'interactive',
- };
-
- const preview = await buildGapReportPreview(previewArgs);
-
- p.note(
- `${preview.mode === 'github' ? `Repo: ${preview.repo}` : `Custom command: ${preview.command}`}\n\n` +
- `Title:\n ${preview.title}\n\n` +
- `Body:\n${preview.body
- .split('\n')
- .map(l => ` ${l}`)
- .join('\n')}`,
- 'Preview — this is exactly what will be filed',
- );
-
- const confirmFile = isCancel(
- await p.confirm({
- message: 'File this gap report now?',
- initialValue: false,
- }),
- );
-
- if (!confirmFile) {
- humanLog('Cancelled — nothing was filed.');
- return;
- }
-
- const s = p.spinner();
- s.start('Filing gap report');
-
- try {
- const url = await createGapReport(previewArgs);
- s.stop('Gap report filed');
- humanLog(`✓ ${url}\n`);
- } catch (err) {
- s.stop('Failed to file gap report');
- console.error(`Warning: Could not file gap report: ${err.message}`);
+ // Maintainer feedback note. If we couldn't swizzle cleanly, the team
+ // wants to know — point users at the issue tracker. Skipped when the
+ // owning package ships no issues URL.
+ if (feedback) {
+ humanLog(
+ 'Customizing a component often signals a gap in the design system.',
+ );
+ humanLog('Let the maintainers know what you needed:');
+ if (feedback.ghCommand) {
+ humanLog(` ${feedback.ghCommand}`);
+ } else {
+ humanLog(` ${feedback.issuesUrl}`);
+ }
+ humanLog('');
}
});
}
diff --git a/packages/cli/src/commands/swizzle.path-safety.test.mjs b/packages/cli/src/commands/swizzle.path-safety.test.mjs
index 91d118180e..d9d6b97374 100644
--- a/packages/cli/src/commands/swizzle.path-safety.test.mjs
+++ b/packages/cli/src/commands/swizzle.path-safety.test.mjs
@@ -69,7 +69,7 @@ describe('swizzle path safety', () => {
const {project, outside} = buildFakeRepo(tmpDir);
const result = runCli(
- ['swizzle', 'Button', '--output', '../outside-project', '--no-report'],
+ ['swizzle', 'Button', '--output', '../outside-project'],
project,
);
@@ -87,7 +87,7 @@ describe('swizzle path safety', () => {
const absTarget = path.join(tmpDir, 'absolute-target');
const result = runCli(
- ['swizzle', 'Button', '--output', absTarget, '--no-report'],
+ ['swizzle', 'Button', '--output', absTarget],
project,
);
@@ -105,7 +105,7 @@ describe('swizzle path safety', () => {
// Use --json to force non-interactive mode.
const result = runCli(
- ['--json', 'swizzle', 'Button', '--no-report'],
+ ['--json', 'swizzle', 'Button'],
project,
);
diff --git a/packages/cli/src/commands/swizzle.routing.test.mjs b/packages/cli/src/commands/swizzle.routing.test.mjs
new file mode 100644
index 0000000000..aab347097d
--- /dev/null
+++ b/packages/cli/src/commands/swizzle.routing.test.mjs
@@ -0,0 +1,279 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration-routing tests for `astryx swizzle`.
+ *
+ * `rewriteImports` is unit-tested in swizzle.test.mjs. These tests exercise the
+ * end-to-end command behavior by spawning the CLI bin against hermetic
+ * fixtures: a fake @astryxdesign/core under node_modules plus, for the
+ * integration cases, a configured integration package (astryx.config.mjs +
+ * astryx.integration.mjs + a `components` dir) — all under node_modules so the
+ * config/manifest loaders resolve normally.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_BIN = path.resolve(__dirname, '../../bin/astryx.mjs');
+
+/**
+ * Build a fake @astryxdesign/core under <project>/node_modules with a single
+ * swizzleable Button component (bare `Button.tsx`, no doc).
+ */
+function buildFakeCore(project) {
+ const core = path.join(project, 'node_modules', '@astryxdesign', 'core');
+ const buttonDir = path.join(core, 'src', 'Button');
+ fs.mkdirSync(buttonDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(core, 'package.json'),
+ '{"name":"@astryxdesign/core","version":"0.0.13"}',
+ );
+ fs.writeFileSync(
+ path.join(buttonDir, 'Button.tsx'),
+ [
+ `import {tokens} from '../theme/tokens.stylex';`,
+ `import {helper} from './helper';`,
+ `export const Button = () => null;`,
+ '',
+ ].join('\n'),
+ );
+ fs.writeFileSync(
+ path.join(buttonDir, 'helper.ts'),
+ `export const helper = 1;\n`,
+ );
+ return core;
+}
+
+/**
+ * Build a configured integration package `@test/meta` under
+ * <project>/node_modules with a same-stem component (source + doc) and an
+ * escaping import, plus a colocated test file. Writes astryx.config.mjs at the
+ * project root listing the integration.
+ *
+ * @param {string} project
+ * @param {{issuesUrl?: string|null, componentName?: string}} [opts]
+ */
+function buildIntegration(project, {issuesUrl, componentName = 'MetaAppShell'} = {}) {
+ const intDir = path.join(project, 'node_modules', '@test', 'meta');
+ const compRoot = path.join(intDir, 'components');
+ const compDir = path.join(compRoot, componentName);
+ fs.mkdirSync(compDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(intDir, 'package.json'),
+ JSON.stringify({name: '@test/meta', version: '1.2.3'}),
+ );
+ const manifest = {components: './components'};
+ if (issuesUrl) manifest.issuesUrl = issuesUrl;
+ fs.writeFileSync(
+ path.join(intDir, 'astryx.integration.mjs'),
+ `export default ${JSON.stringify(manifest)};\n`,
+ );
+ fs.writeFileSync(
+ path.join(compDir, `${componentName}.tsx`),
+ [
+ `import x from '../utils/foo';`,
+ `import {sib} from './sibling';`,
+ `export function ${componentName}() { return x; }`,
+ '',
+ ].join('\n'),
+ );
+ fs.writeFileSync(
+ path.join(compDir, 'sibling.ts'),
+ `export const sib = 1;\n`,
+ );
+ fs.writeFileSync(
+ path.join(compDir, `${componentName}.doc.mjs`),
+ `export const docs = {name: '${componentName}', usage: {description: 'x'}};\n`,
+ );
+ fs.writeFileSync(
+ path.join(compDir, `${componentName}.test.tsx`),
+ `it('noop', () => {});\n`,
+ );
+ fs.writeFileSync(
+ path.join(project, 'astryx.config.mjs'),
+ `export default {integrations: ['@test/meta']};\n`,
+ );
+ return {intDir, compDir};
+}
+
+function writeProjectPackageJson(project, extra = {}) {
+ fs.writeFileSync(
+ path.join(project, 'package.json'),
+ JSON.stringify({name: 'consumer', version: '1.0.0', ...extra}),
+ );
+}
+
+function runCli(args, cwd) {
+ try {
+ const out = execFileSync('node', [CLI_BIN, ...args], {
+ cwd,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {...process.env, FORCE_COLOR: '0'},
+ });
+ return {code: 0, stdout: out, stderr: ''};
+ } catch (e) {
+ return {
+ code: e.status ?? 1,
+ stdout: e.stdout?.toString() ?? '',
+ stderr: e.stderr?.toString() ?? '',
+ };
+ }
+}
+
+let tmpDir;
+let project;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-swizzle-routing-'));
+ project = path.join(tmpDir, 'project');
+ fs.mkdirSync(project, {recursive: true});
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('swizzle — core feedback routing via config', () => {
+ it('routes core feedback to config.issuesUrl when set', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ fs.writeFileSync(
+ path.join(project, 'astryx.config.mjs'),
+ `export default {issuesUrl: 'https://github.com/acme/ds/issues'};\n`,
+ );
+
+ const result = runCli(['--json', 'swizzle', 'Button', '-f'], project);
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.type).toBe('swizzle.copy');
+ expect(env.data.package).toBe('@astryxdesign/core');
+ expect(env.data.feedback.issuesUrl).toBe('https://github.com/acme/ds/issues');
+ // Escaping import rewritten to core; sibling import preserved.
+ const out = fs.readFileSync(
+ path.join(project, 'components', 'astryx', 'Button', 'Button.tsx'),
+ 'utf-8',
+ );
+ expect(out).toContain(`from '@astryxdesign/core/theme'`);
+ expect(out).toContain(`from './helper'`);
+ });
+
+ it('falls back to the default issues URL when config has none', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+
+ const result = runCli(['--json', 'swizzle', 'Button', '-f'], project);
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.data.feedback.issuesUrl).toBe(
+ 'https://github.com/facebook/astryx/issues/new',
+ );
+ });
+});
+
+describe('swizzle — integration-owned components', () => {
+ it('copies the component dir (excluding test/doc), rewrites escaping imports to the owner package, routes feedback to the integration issuesUrl', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ buildIntegration(project, {issuesUrl: 'https://example.com/meta/issues'});
+
+ const result = runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.type).toBe('swizzle.copy');
+ expect(env.data.package).toBe('@test/meta');
+ // Doc + test excluded from the copy.
+ expect(env.data.files).toContain('MetaAppShell.tsx');
+ expect(env.data.files).toContain('sibling.ts');
+ expect(env.data.files).not.toContain('MetaAppShell.doc.mjs');
+ expect(env.data.files.some(f => f.includes('.test.'))).toBe(false);
+ // Feedback routed to the integration's issues URL.
+ expect(env.data.feedback.issuesUrl).toBe('https://example.com/meta/issues');
+
+ const outDir = path.join(project, 'components', 'astryx', 'MetaAppShell');
+ expect(fs.existsSync(path.join(outDir, 'MetaAppShell.doc.mjs'))).toBe(false);
+ const out = fs.readFileSync(path.join(outDir, 'MetaAppShell.tsx'), 'utf-8');
+ expect(out).toContain(`from '@test/meta/utils'`);
+ expect(out).toContain(`from './sibling'`);
+ });
+
+ it('omits the feedback note when the integration ships no issuesUrl', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ buildIntegration(project, {issuesUrl: null});
+
+ const result = runCli(['--json', 'swizzle', 'MetaAppShell', '-f'], project);
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.type).toBe('swizzle.copy');
+ expect(env.data.package).toBe('@test/meta');
+ expect(env.data.feedback).toBeUndefined();
+ });
+});
+
+describe('swizzle — ambiguous ownership', () => {
+ it('errors when a name is owned by core + an integration and no --package is given', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ // Integration also provides "Button" (collides with core).
+ buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ componentName: 'Button',
+ });
+
+ const result = runCli(['--json', 'swizzle', 'Button', '-f'], project);
+ expect(result.code).not.toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.code).toBe('ERR_AMBIGUOUS_COMPONENT');
+ const pkgs = (env.suggestions ?? []).map(s => s.name);
+ expect(pkgs).toContain('@astryxdesign/core');
+ expect(pkgs).toContain('@test/meta');
+ });
+
+ it('--package resolves an ambiguous name to the integration', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ componentName: 'Button',
+ });
+
+ const result = runCli(
+ ['--json', 'swizzle', 'Button', '--package', '@test/meta', '-f'],
+ project,
+ );
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.data.package).toBe('@test/meta');
+ const out = fs.readFileSync(
+ path.join(project, 'components', 'astryx', 'Button', 'Button.tsx'),
+ 'utf-8',
+ );
+ expect(out).toContain(`from '@test/meta/utils'`);
+ });
+
+ it('--package resolves an ambiguous name to core', () => {
+ buildFakeCore(project);
+ writeProjectPackageJson(project);
+ buildIntegration(project, {
+ issuesUrl: 'https://example.com/meta/issues',
+ componentName: 'Button',
+ });
+
+ const result = runCli(
+ ['--json', 'swizzle', 'Button', '--package', '@astryxdesign/core', '-f'],
+ project,
+ );
+ expect(result.code).toBe(0);
+ const env = JSON.parse(result.stdout);
+ expect(env.data.package).toBe('@astryxdesign/core');
+ const out = fs.readFileSync(
+ path.join(project, 'components', 'astryx', 'Button', 'Button.tsx'),
+ 'utf-8',
+ );
+ expect(out).toContain(`from '@astryxdesign/core/theme'`);
+ });
+});
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 6f192c4a33..c90400d911 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -11,9 +11,11 @@ import {isNonInteractive} from '../utils/path-safety.mjs';
import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
-import {template as templateApi, getTemplateById} from '../api/template.mjs';
+import {template as templateApi} from '../api/template.mjs';
+import {Project} from '../lib/project.mjs';
+import {warnOnIntegrationIssues} from '../lib/integration-warnings.mjs';
-export {discoverTemplates, listTemplates, getTemplateById} from '../api/template.mjs';
+export {discoverTemplates, listTemplates} from '../api/template.mjs';
function isCancel(value) {
if (p.isCancel(value)) {
@@ -24,16 +26,27 @@ function isCancel(value) {
}
export function registerTemplate(program) {
- const templateCmd = program
+ program
.command('template [name] [path]')
.description('Inject a page or block template')
.option('--list', 'List available templates')
.option('--type <type>', 'Filter by template type: page or block')
+ .option('--package <pkg>', 'Narrow to templates from a specific package')
.option('--skeleton', 'Show layout skeleton with spatial annotations (padding, gap, nesting)')
.option('-f, --overwrite', 'Overwrite existing files without prompting')
.action(async (name, targetPath, options) => {
const json = program.opts().json || false;
+ // Non-blocking nudge: if any configured integration has validation
+ // issues, print one compact line to stderr pointing at
+ // validate-integration. Best-effort; suppressed in --json mode.
+ try {
+ const project = await Project.load(process.cwd());
+ await warnOnIntegrationIssues(project.loadedIntegrations, {json});
+ } catch {
+ // Never let the nudge break the command.
+ }
+
// Pre-flight overwrite check (only when we'd actually copy a file).
// The API resolves the destination; we need to mirror its logic
// narrowly enough to detect collisions before invoking it.
@@ -72,6 +85,7 @@ export function registerTemplate(program) {
list: options.list,
skeleton: options.skeleton,
type: options.type,
+ package: options.package,
targetPath,
cwd: process.cwd(),
});
@@ -88,26 +102,28 @@ 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');
+ const renderEntry = t => {
+ const status = t.isReady ? '' : ' (WIP)';
+ const pkg =
+ t.package && t.package !== '@astryxdesign/core'
+ ? ` [${t.package}]`
+ : '';
+ humanLog(` ${t.name}${status}${pkg}`);
+ if (t.description) humanLog(` ${t.description}`);
+ };
if (pages.length > 0) {
humanLog('\nPage Templates:\n');
- for (const t of pages) {
- const status = t.isReady ? '' : ' (WIP)';
- humanLog(` ${t.name}${status}`);
- if (t.description) humanLog(` ${t.description}`);
- }
+ for (const t of pages) renderEntry(t);
}
if (blocks.length > 0) {
humanLog('\nBlock Templates:\n');
- for (const t of blocks) {
- const status = t.isReady ? '' : ' (WIP)';
- humanLog(` ${t.name}${status}`);
- if (t.description) humanLog(` ${t.description}`);
- }
+ for (const t of blocks) renderEntry(t);
}
humanLog('\nUsage:');
- humanLog(' astryx template <name> [target-path] Scaffold page or block');
- humanLog(' astryx template <name> --skeleton Layout reference');
- humanLog(' astryx template --list --type block List only blocks\n');
+ humanLog(' astryx template <id> [target-path] Scaffold page or block');
+ humanLog(' astryx template <id> --skeleton Layout reference');
+ humanLog(' astryx template --list --type block List only blocks');
+ humanLog(' astryx template --list --package <pkg> List from one package\n');
break;
}
@@ -131,26 +147,6 @@ export function registerTemplate(program) {
}
}
});
-
- templateCmd
- .command('get')
- .description('Fetch a template by ID via the astryx.config.mjs hook')
- .requiredOption('--id <id>', 'Template identifier to fetch')
- .action(async (options) => {
- const json = program.opts().json || false;
-
- let result;
- try {
- result = await getTemplateById(options.id, {cwd: process.cwd()});
- } catch (e) {
- cliError(e.message, {suggestions: e.suggestions, code: e.code});
- return;
- }
-
- if (json) return jsonOut(result.type, result.data);
-
- humanLog(result.data.source);
- });
}
/**
@@ -168,7 +164,7 @@ async function detectTemplateCollision(name, targetPath) {
const {discoverTemplates} = await import('../api/template.mjs');
let templates;
try {
- templates = await discoverTemplates();
+ templates = await discoverTemplates(process.cwd());
} catch {
return null;
}
diff --git a/packages/cli/src/commands/upgrade.config-ordering.test.mjs b/packages/cli/src/commands/upgrade.config-ordering.test.mjs
new file mode 100644
index 0000000000..9f18854cca
--- /dev/null
+++ b/packages/cli/src/commands/upgrade.config-ordering.test.mjs
@@ -0,0 +1,273 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Upgrade config-codemod-ordering tests.
+ *
+ * Verifies that CORE codemods run BEFORE the consumer's config is loaded, so a
+ * config codemod (v0.1.3 migrate-layout-components, meta.codemodType==='config')
+ * can repair an otherwise-invalid config that strict `Project.load` would reject.
+ *
+ * Like the integration-policy tests, these scaffold a real consumer project
+ * (package.json + astryx.config.mjs) under a REPO-LOCAL temp dir (so Vite
+ * permits dynamic import of the config module — it blocks /tmp) and chdir in.
+ *
+ * Cases:
+ * 1. dry-run, legacy layout.components, v0.1.3 config codemod in range →
+ * does NOT abort; reports "fixable, re-run with --apply" + the suggested
+ * `--codemod ... --apply` command; exit 0; integrations skipped.
+ * 2. --apply, same config → core config codemod writes the repaired config,
+ * then config loads strictly OK and the upgrade completes; on-disk config
+ * is migrated to experimental.xle.components.
+ * 3. dry-run, config genuinely invalid (integrations: 5) with NO pending
+ * config codemod → still ABORTS (exit nonzero).
+ * 4. happy path (valid config, no config codemod) → unchanged behavior.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {Command} from 'commander';
+import {registerUpgrade} from './upgrade.mjs';
+
+let tmpDir;
+let originalCwd;
+let logCalls;
+let stdoutCalls;
+let exitCode;
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ // Repo-local temp dir: under cwd so Vite allows the astryx.config import.
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-upgrade-order-'));
+ process.chdir(tmpDir);
+ logCalls = [];
+ stdoutCalls = [];
+ exitCode = undefined;
+ vi.spyOn(console, 'log').mockImplementation((...a) => logCalls.push(a.join(' ')));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(process.stdout, 'write').mockImplementation(chunk => {
+ stdoutCalls.push(typeof chunk === 'string' ? chunk : chunk.toString());
+ return true;
+ });
+ vi.spyOn(process, 'exit').mockImplementation(code => {
+ exitCode = code;
+ throw new Error(`__exit ${code}`);
+ });
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+});
+
+function writePkg() {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+}
+
+function writeInstalledCore(version) {
+ const dir = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version}),
+ );
+}
+
+function writeConfig(body) {
+ fs.writeFileSync(path.join(tmpDir, 'astryx.config.mjs'), body);
+}
+
+function writeSource() {
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
+ fs.writeFileSync(path.join(tmpDir, 'src', 'index.ts'), 'const foo = 1;\n');
+}
+
+const LEGACY_CONFIG = `export default {
+ layout: {
+ components: {
+ KpiCard: '@/components/KpiCard',
+ },
+ },
+};
+`;
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ program.option('--json', 'Output as typed JSON');
+ registerUpgrade(program);
+ return program;
+}
+
+async function runJson(args) {
+ const program = createProgram();
+ try {
+ await program.parseAsync(['node', 'astryx', ...args]);
+ } catch (err) {
+ if (!String(err?.message || '').startsWith('__exit')) throw err;
+ }
+ for (let i = logCalls.length - 1; i >= 0; i--) {
+ const line = logCalls[i];
+ if (line.startsWith('{')) {
+ try {
+ return JSON.parse(line);
+ } catch {
+ // keep looking
+ }
+ }
+ }
+ return null;
+}
+
+async function runHuman(args) {
+ const program = createProgram();
+ try {
+ await program.parseAsync(['node', 'astryx', ...args]);
+ } catch (err) {
+ if (!String(err?.message || '').startsWith('__exit')) throw err;
+ }
+ return stdoutCalls.join('') + '\n' + logCalls.join('\n');
+}
+
+describe('upgrade — core codemods run before config load', () => {
+ it('dry-run: legacy layout.components is reported as fixable, not an abort', async () => {
+ // 0.1.2 -> 0.1.3 brings the migrate-layout-components config codemod.
+ writePkg();
+ writeInstalledCore('0.1.3');
+ writeConfig(LEGACY_CONFIG);
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.2',
+ '--path',
+ 'src',
+ ]);
+
+ expect(result).not.toBeNull();
+ // Did NOT abort with a config-validation error.
+ expect(result.error).toBeUndefined();
+ expect(exitCode).not.toBe(1);
+ // Reported as the fixable case with the suggested apply command.
+ expect(result.type).toBe('upgrade.status');
+ expect(result.data.status).toBe('config_fixable');
+ expect(result.data.configCodemods).toContain(
+ 'migrate-layout-components-to-experimental',
+ );
+ expect(result.data.suggestedCommand).toBe(
+ 'astryx upgrade --from 0.1.2 --codemod migrate-layout-components-to-experimental --apply',
+ );
+ expect(result.data.message).toMatch(/--apply/);
+ // Integrations skipped for the preview.
+ expect(result.data.note).toMatch(/--apply run/i);
+ // Dry-run did not write the config.
+ const onDisk = fs.readFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ 'utf-8',
+ );
+ expect(onDisk).toContain('layout');
+ expect(onDisk).not.toContain('experimental');
+ });
+
+ it('human dry-run prints the fixable guidance + suggested command', async () => {
+ writePkg();
+ writeInstalledCore('0.1.3');
+ writeConfig(LEGACY_CONFIG);
+ writeSource();
+
+ const out = await runHuman(['upgrade', '--from', '0.1.2', '--path', 'src']);
+ expect(out).toMatch(/fails strict validation/i);
+ expect(out).toContain(
+ 'astryx upgrade --from 0.1.2 --codemod migrate-layout-components-to-experimental --apply',
+ );
+ expect(exitCode).not.toBe(1);
+ });
+
+ it('--apply: core config codemod repairs the config, then the upgrade completes', async () => {
+ writePkg();
+ writeInstalledCore('0.1.3');
+ writeConfig(LEGACY_CONFIG);
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.2',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+
+ expect(result).not.toBeNull();
+ expect(result.error).toBeUndefined();
+ expect(exitCode).not.toBe(1);
+ expect(result.type).toBe('upgrade.run');
+ expect(result.data.filesChanged).toBeGreaterThan(0);
+
+ // The on-disk config was migrated to experimental.xle.components.
+ const onDisk = fs.readFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ 'utf-8',
+ );
+ expect(onDisk).toContain('experimental');
+ expect(onDisk).toContain('xle');
+ expect(onDisk).toMatch(
+ /KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/,
+ );
+ expect(onDisk).not.toMatch(/layout\s*:/);
+ });
+
+ it('dry-run: a genuinely invalid config with NO fixing codemod still aborts', async () => {
+ writePkg();
+ writeInstalledCore('0.1.3');
+ // `integrations: 5` is invalid AND no config codemod in 0.1.2->0.1.3 fixes it.
+ writeConfig(`export default { integrations: 5 };\n`);
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.2',
+ '--path',
+ 'src',
+ ]);
+
+ expect(result).not.toBeNull();
+ // Aborts with a config-validation error (not the fixable status).
+ expect(result.error).toBeTruthy();
+ expect(result.type).not.toBe('upgrade.status');
+ expect(exitCode).toBe(1);
+ });
+
+ it('happy path: valid config with no config codemod behaves normally', async () => {
+ writePkg();
+ writeInstalledCore('0.1.3');
+ // A valid, already-migrated config; no relocation needed.
+ writeConfig(`export default { integrations: [] };\n`);
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.2',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+
+ expect(result).not.toBeNull();
+ expect(result.error).toBeUndefined();
+ expect(exitCode).not.toBe(1);
+ // Completed as a run (the config codemod is a no-op on an already-migrated config).
+ expect(result.type).toBe('upgrade.run');
+ });
+});
diff --git a/packages/cli/src/commands/upgrade.integration-policy.test.mjs b/packages/cli/src/commands/upgrade.integration-policy.test.mjs
new file mode 100644
index 0000000000..11cc6bb3d6
--- /dev/null
+++ b/packages/cli/src/commands/upgrade.integration-policy.test.mjs
@@ -0,0 +1,204 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Upgrade integration error-policy + --skip-codemod tests.
+ *
+ * These scaffold a real consumer project (astryx.config.mjs + an installed
+ * integration package with codemods) under a REPO-LOCAL temp dir so Vite
+ * permits dynamic import of the config/integration modules (it blocks /tmp).
+ * They assert:
+ * - a broken integration codemod definition is SKIPPED (warned), not a hard
+ * fail of the upgrade (reverses the previous policy);
+ * - --skip-codemod excludes a named integration codemod.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {Command} from 'commander';
+import {registerUpgrade} from './upgrade.mjs';
+
+let tmpDir;
+let originalCwd;
+let logCalls;
+let errCalls;
+let exitCode;
+
+const codemodModuleUrl = pathToFileURL(
+ path.resolve(process.cwd(), 'packages/cli/src/codemod.mjs'),
+).href;
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ // Repo-local temp dir: under cwd so Vite allows config/integration imports.
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-upgrade-policy-'));
+ process.chdir(tmpDir);
+ logCalls = [];
+ errCalls = [];
+ exitCode = undefined;
+ vi.spyOn(console, 'log').mockImplementation((...a) => logCalls.push(a.join(' ')));
+ vi.spyOn(console, 'error').mockImplementation((...a) => errCalls.push(a.join(' ')));
+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ vi.spyOn(process, 'exit').mockImplementation(code => {
+ exitCode = code;
+ throw new Error(`__exit ${code}`);
+ });
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+});
+
+function writeInstalledCore(version) {
+ const dir = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version}),
+ );
+}
+
+function writeSource() {
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
+ fs.writeFileSync(path.join(tmpDir, 'src', 'index.ts'), 'const foo = 1;\n');
+}
+
+/**
+ * Scaffold a consumer + an installed integration package with codemods.
+ * @param {Object<string,string>} codemodFiles "<version>/<id>.mjs" -> body
+ */
+function scaffoldIntegration(codemodFiles) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets'] };\n`,
+ );
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default { codemods: './codemods' };\n`,
+ );
+ for (const [rel, body] of Object.entries(codemodFiles)) {
+ const full = path.join(pkgDir, 'codemods', rel);
+ fs.mkdirSync(path.dirname(full), {recursive: true});
+ fs.writeFileSync(full, body);
+ }
+}
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ program.option('--json', 'Output as typed JSON');
+ registerUpgrade(program);
+ return program;
+}
+
+async function runJson(args) {
+ const program = createProgram();
+ try {
+ await program.parseAsync(['node', 'astryx', ...args]);
+ } catch (err) {
+ if (!String(err?.message || '').startsWith('__exit')) throw err;
+ }
+ for (let i = logCalls.length - 1; i >= 0; i--) {
+ const line = logCalls[i];
+ if (line.startsWith('{')) {
+ try {
+ return JSON.parse(line);
+ } catch {
+ // keep looking
+ }
+ }
+ }
+ return null;
+}
+
+describe('upgrade integration error policy (skip + warn)', () => {
+ it('SKIPS a broken integration codemod instead of hard-failing the upgrade', async () => {
+ // A codemod module whose default export is not a valid codemod result —
+ // a DEFINITION error. The upgrade must NOT abort; it skips the broken
+ // integration's codemods and completes.
+ scaffoldIntegration({
+ '0.2.0/bad.mjs': `export default { not: 'a codemod' };\n`,
+ });
+ writeInstalledCore('0.2.0');
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.0',
+ '--path',
+ 'src',
+ ]);
+
+ // Did NOT hard-fail: no error envelope, and it ran to a status/run result.
+ expect(result).not.toBeNull();
+ expect(result.error).toBeUndefined();
+ expect(exitCode).not.toBe(1);
+ });
+
+ it('runs a healthy integration codemod for an applicable range', async () => {
+ scaffoldIntegration({
+ '0.2.0/drop-foo.mjs':
+ `import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};\n` +
+ `export default createCodemod({ title: 'Drop foo', transform: (file) => file.source.replace(/foo/g, 'bar') });\n`,
+ });
+ writeInstalledCore('0.2.0');
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.0',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+ expect(result).not.toBeNull();
+ expect(result.error).toBeUndefined();
+ // The codemod rewrote foo -> bar.
+ const out = fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8');
+ expect(out).toContain('bar');
+ });
+
+ it('--skip-codemod excludes a named integration codemod', async () => {
+ scaffoldIntegration({
+ '0.2.0/drop-foo.mjs':
+ `import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};\n` +
+ `export default createCodemod({ title: 'Drop foo', transform: (file) => file.source.replace(/foo/g, 'bar') });\n`,
+ });
+ writeInstalledCore('0.2.0');
+ writeSource();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.0',
+ '--path',
+ 'src',
+ '--apply',
+ '--skip-codemod',
+ 'drop-foo',
+ ]);
+ expect(result).not.toBeNull();
+ // Skipped: the source is unchanged (foo not rewritten to bar).
+ const out = fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8');
+ expect(out).toContain('foo');
+ expect(out).not.toContain('bar');
+ });
+});
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 0bc2e7a24b..2228a82b33 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -15,13 +15,22 @@
* 3. Refresh agent docs (AGENTS.md / CLAUDE.md) if present
*
* Options:
- * --from <version> Previous version before the dependency upgrade
- * --apply Write changes to disk (default: dry-run)
- * --force Run codemods even when from >= installed version
- * --codemod <name> Run a specific transform only
- * --integration <spec> Load an explicit integration package or file
- * --path <dir> Source directory (default: ./src)
- * --install-deps Auto-install jscodeshift without prompting (for CI/LLM)
+ * --from <version> Previous version before the dependency upgrade
+ * --apply Write changes to disk (default: dry-run)
+ * --force Run codemods even when from >= installed version
+ * --codemod <name> Run a specific transform only
+ * --skip-codemod <name…> Exclude named codemods (variadic). Use this to
+ * re-run past a codemod that failed at execution time.
+ * --integration <spec> Load an explicit integration package or file
+ * --path <dir> Source directory (default: ./src)
+ * --install-deps Auto-install jscodeshift without prompting (for CI/LLM)
+ *
+ * Integration error policy:
+ * - A DISCOVERY/definition error for an integration (bad manifest/export,
+ * duplicate ids, missing root) SKIPS that integration's codemods and warns
+ * (via the integration-issue nudge) — it does NOT hard-fail the upgrade.
+ * - An EXECUTION-time failure (a transform THROWS while rewriting files)
+ * ABORTS the upgrade (nonzero exit) so a partial write never proceeds.
*/
import * as fs from 'node:fs';
@@ -32,12 +41,18 @@ import * as p from '@clack/prompts';
import {ensureJscodeshift} from '../codemods/ensure-jscodeshift.mjs';
import {getTransformsBetween, latestVersion} from '../codemods/registry.mjs';
import {runCodemods} from '../codemods/runner.mjs';
+import {
+ discoverIntegrationCodemods,
+ selectIntegrationCodemods,
+} from '../codemods/integration-discovery.mjs';
+import {runIntegrationCodemods} from '../codemods/integration-runner.mjs';
import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
-import {isValidSemver, semverGte, semverGt} from '../utils/semver.mjs';
+import {isValidSemver, semverGte} from '../utils/semver.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
-import {loadConfig} from '../lib/config.mjs';
+import {Project} from '../lib/project.mjs';
import {loadIntegrations} from '../lib/integrations.mjs';
+import {warnOnIntegrationIssues} from '../lib/integration-warnings.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
const execFileAsync = promisify(execFile);
@@ -64,90 +79,59 @@ function detectInstalledTargetVersion() {
return null;
}
-function normalizeIntegrationTransforms(integration, from, to) {
- const transforms = [];
- for (const entry of integration.codemods ?? []) {
- const entryFrom = entry.from ?? '0.0.0';
- const entryTo = entry.to ?? to;
- if (semverGte(from, entryTo) || semverGt(entryFrom, to)) continue;
- if (!entry.name)
- throw new Error(
- `Integration ${integration.name ?? integration.__spec} has a codemod without a name.`,
- );
- if (!entry.transform)
- throw new Error(
- `Integration codemod ${entry.name} is missing transform.`,
- );
- const directTransform =
- typeof entry.transform === 'function' ? entry.transform : null;
- if (!directTransform)
- throw new Error(
- `Integration codemod ${entry.name} did not resolve to a function.`,
- );
- transforms.push({
- name: entry.name,
- meta: {
- title:
- entry.title ??
- `${integration.name ?? integration.__spec}: ${entry.name}`,
- description: entry.description ?? '',
- pr: entry.pr,
- fileExtensions: entry.fileExtensions,
- },
- optional: !!entry.optional,
- transform: directTransform,
- });
- }
- return transforms.length ? [{version: to, transforms}] : [];
-}
-
function uniqueFiles(files) {
return [...new Set((files ?? []).filter(Boolean))];
}
-async function runPostCodemodHooks(integrations, context, silent) {
- const hooks = integrations.flatMap(integration =>
- (integration.postCodemod ?? []).map(hook => ({integration, hook})),
- );
- if (hooks.length === 0) return;
+/**
+ * Run the app config's post-codemod hooks (config.hooks.postCodemod).
+ *
+ * Each hook's `buildCommand({packageDir, files})` returns a command to run
+ * (or a nullish value to skip). In dry-run mode we only PREVIEW — buildCommand
+ * is called (so a throw still fails the run) but the command is never executed.
+ * In apply mode the commands run in order via execFile; a nonzero exit (or a
+ * buildCommand throw) fails the upgrade.
+ *
+ * @param {import('../types/config').PostCodemodHook[]} hooks
+ * @param {{packageDir: string, files: string[], apply: boolean}} context
+ * @param {boolean} silent
+ */
+async function runPostCodemodHooks(hooks, context, silent) {
+ if (!hooks || hooks.length === 0) return;
const log = silent ? {info() {}, warn() {}, success() {}, error() {}} : p.log;
+ const {packageDir, files, apply} = context;
- const run = async (command, args, options = {}) => {
- await execFileAsync(command, args, {
- cwd: options.cwd ?? context.packageDir,
- timeout: options.timeoutMs ?? 300_000,
+ for (let i = 0; i < hooks.length; i++) {
+ const hook = hooks[i];
+ const label = hook.name ?? `postCodemod[${i}]`;
+ if (typeof hook.buildCommand !== 'function') {
+ throw new Error(
+ `Post-codemod hook ${label} is missing a buildCommand function.`,
+ );
+ }
+
+ const cmd = await hook.buildCommand({packageDir, files});
+ if (!cmd) {
+ log.info(`Post-codemod hook ${label} produced no command; skipping.`);
+ continue;
+ }
+
+ if (!apply) {
+ const preview = [cmd.command, ...(cmd.args ?? [])].join(' ');
+ log.info(`Post-codemod hook ${label} (dry run): ${preview}`);
+ continue;
+ }
+
+ await execFileAsync(cmd.command, cmd.args ?? [], {
+ cwd: cmd.options?.cwd ?? packageDir,
+ timeout: cmd.options?.timeout ?? 300_000,
stdio: 'pipe',
encoding: 'utf-8',
- env: {...process.env, ...(options.env ?? {})},
+ ...cmd.options,
+ env: {...process.env, ...(cmd.options?.env ?? {})},
});
- };
-
- const ctx = {...context, run};
- for (const {integration, hook} of hooks) {
- const label = `${integration.name ?? integration.__spec}:${hook.name ?? 'postCodemod'}`;
- try {
- if (typeof hook.run === 'function') {
- await hook.run(ctx);
- } else if (typeof hook.command === 'function') {
- const cmd = await hook.command(ctx);
- if (cmd) {
- await run(cmd.command, cmd.args ?? [], {
- cwd: cmd.cwd,
- timeoutMs: cmd.timeoutMs,
- env: cmd.env,
- });
- }
- } else {
- log.warn(
- `Integration hook ${label} has no run() or command() function; skipping.`,
- );
- continue;
- }
- log.success(`Post-codemod hook ${label} completed.`);
- } catch (err) {
- log.warn(`Post-codemod hook ${label} failed: ${err.message}`);
- }
+ log.success(`Post-codemod hook ${label} completed.`);
}
}
@@ -169,6 +153,10 @@ export function registerUpgrade(program) {
false,
)
.option('--codemod <name>', 'Run a specific transform only')
+ .option(
+ '--skip-codemod <name...>',
+ 'Exclude named codemods (repeatable). Re-run past a failed codemod by skipping it.',
+ )
.option(
'--integration <package-or-file>',
'Explicit integration package name or integration file path (repeatable)',
@@ -266,15 +254,170 @@ export function registerUpgrade(program) {
);
}
+ // ───────────────────────────────────────────────────────────────────
+ // PIPELINE ORDERING
+ //
+ // CORE codemods run BEFORE the consumer's config is loaded. `Project.load`
+ // STRICT-validates astryx.config.* and THROWS on unknown keys — but a core
+ // CONFIG codemod (e.g. v0.1.3 migrate-layout-components, signalled by
+ // `meta.codemodType === 'config'`) is precisely what repairs an otherwise
+ // -invalid config. Loading first created a chicken-and-egg: the config was
+ // rejected before the codemod that would fix it ever ran. Core codemods
+ // read files directly (config codemods via runConfigCodemod read
+ // astryx.config.*; code codemods scan --path), so they do NOT need the
+ // loaded config. We run them here, then load config, then sequence the
+ // integration codemods (which DO require a valid loaded config).
+ // ───────────────────────────────────────────────────────────────────
+
+ if (!options.force && semverGte(currentVersion, targetVersion)) {
+ if (json) {
+ return jsonOut('upgrade.status', {
+ status: 'up_to_date',
+ from: currentVersion,
+ to: targetVersion,
+ });
+ }
+ p.log.success('Already up to date — no codemods to run.');
+ p.log.info('Use --force to run codemods anyway.');
+ p.outro('Done');
+ return;
+ }
+
+ // Resolve CORE transforms from the registry. These do not need the loaded
+ // config. Integration codemods are discovered later, AFTER the config
+ // loads successfully (they require a valid config to resolve).
+ const versionManifests = [
+ ...(await getTransformsBetween(currentVersion, targetVersion)),
+ ];
+
+ // Does the selected core set include >=1 CONFIG codemod? A config codemod
+ // is the established convention `meta.codemodType === 'config'` (see
+ // `toUnifiedEntry` in runner.mjs). This drives the graceful dry-run catch
+ // around `Project.load` below: a fixable config error is only "expected"
+ // when a pending core config codemod would repair it.
+ const coreConfigCodemodNames = [];
+ for (const {transforms} of versionManifests) {
+ for (const t of transforms) {
+ if (options.codemod && t.name !== options.codemod) continue;
+ if (t.meta?.codemodType === 'config') {
+ coreConfigCodemodNames.push(t.name);
+ }
+ }
+ }
+ const hasCoreConfigCodemod = coreConfigCodemodNames.length > 0;
+
+ // Codemods explicitly excluded via --skip-codemod, matched by the same
+ // identifier the run loop uses (core transform `t.name`, integration
+ // codemod `c.id`). Lets a user re-run past a codemod that failed at
+ // execution time.
+ const skipCodemods = new Set(options.skipCodemod ?? []);
+
+ // Count CORE transforms (optional codemods only count when explicitly
+ // requested). Integration counts are added after discovery below.
+ let totalTransforms = 0;
+ let totalOptional = 0;
+ for (const {transforms} of versionManifests) {
+ for (const t of transforms) {
+ if (options.codemod && t.name !== options.codemod) continue;
+ if (skipCodemods.has(t.name)) continue;
+ if (t.optional && !options.codemod) {
+ totalOptional++;
+ } else {
+ totalTransforms++;
+ }
+ }
+ }
+
+ // Ensure jscodeshift is available before running any codemod.
+ const ready = await ensureJscodeshift({
+ installDeps: options.installDeps,
+ silent: json,
+ });
+ if (!ready) {
+ if (json)
+ return jsonError(
+ 'jscodeshift is required but could not be installed.',
+ undefined,
+ ERROR_CODES.ERR_DEP_MISSING,
+ );
+ p.outro('Aborted');
+ process.exitCode = 1;
+ return;
+ }
+
+ // STEP 3 — Run CORE codemods FIRST (before loading config). In --apply,
+ // core config codemods WRITE the repaired config to disk; in dry-run they
+ // only PREVIEW. This is what makes the v0.1.3 config codemod reachable on
+ // a config that the strict loader would otherwise reject.
+ const codemodResult = await runCodemods(versionManifests, {
+ apply: options.apply,
+ path: options.path,
+ codemod: options.codemod,
+ skipCodemods,
+ silent: json,
+ });
+
+ // STEP 4 — Load the consumer's config (STRICT validation; unchanged). On
+ // --apply this now sees the repaired config the core codemod just wrote.
+ // We need `hooks.postCodemod` and the configured integration specs from
+ // here. Wrap in a graceful dry-run catch (see below).
+ // Assigned inside the try below; every catch branch returns, so these
+ // are always set before any later read.
let integrations;
+ let postCodemodHooks;
+ let integrationVersionGroups;
try {
- const config = await loadConfig(process.cwd());
+ const project = await Project.load(process.cwd());
+ postCodemodHooks = project.config.hooks?.postCodemod ?? [];
const integrationSpecs = uniqueFiles([
- ...(config.integrations ?? []),
+ ...(project.integrations ?? []),
...(options.integration ?? []),
]);
integrations = await loadIntegrations(integrationSpecs);
} catch (err) {
+ // GRACEFUL DRY-RUN CATCH. A config that fails strict validation is the
+ // EXPECTED, fixable case ONLY when we are in dry-run AND a pending core
+ // config codemod just PREVIEWED a change to the config — i.e. the very
+ // codemod that would repair it. (Merely having a config codemod in the
+ // range is not enough: it may be a no-op on this config, in which case
+ // the validation error is genuine and we must abort. A config codemod
+ // that THREW reports zero would-change files, so it also fails this
+ // gate and aborts below — preserving the strictness contract.) This is
+ // the reason this PR reorders the pipeline.
+ const codemodWouldFixConfig =
+ hasCoreConfigCodemod && (codemodResult?.totalFilesChanged ?? 0) > 0;
+ if (!options.apply && codemodWouldFixConfig) {
+ const codemodFlags = coreConfigCodemodNames
+ .map(name => `--codemod ${name}`)
+ .join(' ');
+ const suggestedCommand = `astryx upgrade --from ${currentVersion} ${codemodFlags} --apply`;
+ const guidance =
+ 'Your astryx.config currently fails strict validation, but a pending ' +
+ 'config codemod would repair it. This dry run previewed the fix without ' +
+ 'writing. Re-run with --apply to apply it, or run just the config codemod(s) ' +
+ 'now:';
+ if (json) {
+ return jsonOut('upgrade.status', {
+ status: 'config_fixable',
+ from: currentVersion,
+ to: targetVersion,
+ configError: err.message,
+ configCodemods: coreConfigCodemodNames,
+ suggestedCommand,
+ message: guidance,
+ note: 'Integrations are skipped in this preview; they will be processed on the --apply run.',
+ });
+ }
+ p.log.warn(guidance);
+ p.log.info(` ${suggestedCommand}`);
+ p.log.info(
+ 'Integrations are skipped in this preview; they will be processed on the --apply run.',
+ );
+ p.outro('Dry run complete');
+ return;
+ }
+ // Genuine config error (apply mode, OR dry-run with no pending core
+ // config codemod that would fix it): abort as before.
if (json)
return jsonError(
err.message,
@@ -286,39 +429,71 @@ export function registerUpgrade(program) {
process.exitCode = 1;
return;
}
+
if (!json && integrations.length > 0) {
p.log.info(
`Integrations: ${integrations.map(i => i.name ?? i.__spec).join(', ')}`,
);
}
- if (!options.force && semverGte(currentVersion, targetVersion)) {
- if (json) {
- return jsonOut('upgrade.status', {
- status: 'up_to_date',
- from: currentVersion,
- to: targetVersion,
- });
+ // Non-blocking nudge: if any configured integration has validation
+ // issues, print one compact line to stderr pointing at
+ // validate-integration. Best-effort; suppressed in --json mode. This
+ // depends on integrations being loaded, so it lives after the successful
+ // config load (it is skipped on the graceful dry-run path above, where
+ // integrations were never loaded).
+ try {
+ await warnOnIntegrationIssues(integrations, {json});
+ } catch {
+ // Never let the nudge break the upgrade.
+ }
+
+ // STEP 5 — Discover + run INTEGRATION codemods (only reached on a
+ // successful config load). A broken integration (bad export, invalid
+ // schema, duplicate id, missing root) is a DEFINITION error: skip that
+ // integration's codemods and warn (via the nudge above), rather than
+ // hard-failing the upgrade. An EXECUTION-time failure (a transform
+ // throwing) is handled later by the codemod-error gate, which still
+ // aborts the upgrade.
+ const integrationCodemodsByVersion = new Map();
+ for (const integration of integrations) {
+ if (!integration?.codemods) continue;
+ try {
+ const byVersion = await discoverIntegrationCodemods([integration]);
+ for (const [version, list] of byVersion) {
+ const existing = integrationCodemodsByVersion.get(version);
+ if (existing) existing.push(...list);
+ else integrationCodemodsByVersion.set(version, [...list]);
+ }
+ } catch {
+ // Skip this integration's codemods; the validate-integration nudge
+ // above surfaces the underlying issue. Best-effort, non-blocking.
}
- p.log.success('Already up to date — no codemods to run.');
- p.log.info('Use --force to run codemods anyway.');
- p.outro('Done');
- return;
}
+ integrationVersionGroups = selectIntegrationCodemods(
+ integrationCodemodsByVersion,
+ currentVersion,
+ targetVersion,
+ );
+ const hasIntegrationCodemods = integrationVersionGroups.some(
+ g => g.codemods.length > 0,
+ );
- // Resolve transforms
- const versionManifests = [
- ...(await getTransformsBetween(currentVersion, targetVersion)),
- ...integrations.flatMap(integration =>
- normalizeIntegrationTransforms(
- integration,
- currentVersion,
- targetVersion,
- ),
- ),
- ];
+ // Add integration transforms to the run counts.
+ for (const {codemods} of integrationVersionGroups) {
+ for (const c of codemods) {
+ if (options.codemod && c.id !== options.codemod) continue;
+ if (skipCodemods.has(c.id)) continue;
+ if (c.codemod.isOptional && !options.codemod) {
+ totalOptional++;
+ } else {
+ totalTransforms++;
+ }
+ }
+ }
- if (versionManifests.length === 0) {
+ // No codemods at all for this range (neither core nor integration).
+ if (versionManifests.length === 0 && !hasIntegrationCodemods) {
if (json) {
return jsonOut('upgrade.status', {
status: 'no_codemods',
@@ -331,20 +506,7 @@ export function registerUpgrade(program) {
return;
}
- // Count transforms (optional codemods only count when explicitly requested)
- let totalTransforms = 0;
- let totalOptional = 0;
- for (const {transforms} of versionManifests) {
- for (const t of transforms) {
- if (options.codemod && t.name !== options.codemod) continue;
- if (t.optional && !options.codemod) {
- totalOptional++;
- } else {
- totalTransforms++;
- }
- }
- }
-
+ // A named `--codemod` that matched nothing (across core + integration).
if (totalTransforms === 0 && totalOptional === 0) {
const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
if (json)
@@ -373,54 +535,73 @@ export function registerUpgrade(program) {
agentDocsRefreshed: false,
};
- // Ensure jscodeshift is available
- const ready = await ensureJscodeshift({
- installDeps: options.installDeps,
- silent: json,
- });
- if (!ready) {
- if (json)
- return jsonError(
- 'jscodeshift is required but could not be installed.',
- undefined,
- ERROR_CODES.ERR_DEP_MISSING,
- );
- p.outro('Aborted');
- process.exitCode = 1;
- return;
+ // Run file-based integration codemods alongside the core registry
+ // codemods (config codemods first, then code codemods), ordered by
+ // version. Their results are merged into the receipt below.
+ let integrationResult = null;
+ if (hasIntegrationCodemods) {
+ if (!json) p.log.step('Applying integration codemods...');
+ const jscodeshift = (await import('jscodeshift')).default;
+ integrationResult = runIntegrationCodemods(integrationVersionGroups, {
+ apply: options.apply,
+ path: options.path,
+ codemod: options.codemod,
+ skipCodemods,
+ jscodeshift,
+ silent: json,
+ });
}
- // Run codemods
- const codemodResult = await runCodemods(versionManifests, {
- apply: options.apply,
- path: options.path,
- codemod: options.codemod,
- silent: json,
- });
- if (options.apply && integrations.length > 0) {
- const codemodDir = path.resolve(options.path);
- const absoluteChangedFiles = uniqueFiles(
- codemodResult?.writtenFiles ?? [],
- );
- const changedFiles = absoluteChangedFiles.map(file =>
+ // Merge core + integration codemod results into a single accounting so
+ // hooks, receipts, and error gating see both.
+ const mergedFilesChanged =
+ (codemodResult?.totalFilesChanged ?? 0) +
+ (integrationResult?.totalFilesChanged ?? 0);
+ const mergedTransformsApplied =
+ (codemodResult?.totalTransformsApplied ?? 0) +
+ (integrationResult?.totalTransformsApplied ?? 0);
+ const mergedWrittenFiles = [
+ ...(codemodResult?.writtenFiles ?? []),
+ ...(integrationResult?.writtenFiles ?? []),
+ ];
+ const mergedErrors = [
+ ...(codemodResult?.errors ?? []),
+ ...(integrationResult?.errors ?? []),
+ ];
+
+ // Post-codemod hooks come from the app config (config.hooks.postCodemod).
+ // They run only when codemods actually changed files. In apply mode the
+ // commands execute (nonzero exit fails the upgrade); in dry-run mode we
+ // only preview the resolved command (a buildCommand throw still fails).
+ const changedFileCount = mergedFilesChanged;
+ if (postCodemodHooks.length > 0 && changedFileCount > 0) {
+ const absoluteChangedFiles = uniqueFiles(mergedWrittenFiles);
+ const files = absoluteChangedFiles.map(file =>
path.relative(process.cwd(), file),
);
- const packageChangedFiles = absoluteChangedFiles
- .filter(file => file.startsWith(process.cwd() + path.sep))
- .map(file => path.relative(process.cwd(), file));
- await runPostCodemodHooks(
- integrations,
- {
- packageDir: process.cwd(),
- codemodDir,
- changedFiles,
- absoluteChangedFiles,
- packageChangedFiles,
- apply: options.apply,
- },
- json,
- );
+ try {
+ await runPostCodemodHooks(
+ postCodemodHooks,
+ {
+ packageDir: process.cwd(),
+ files,
+ apply: options.apply,
+ },
+ json,
+ );
+ } catch (err) {
+ if (json)
+ return jsonError(
+ `Post-codemod hook failed: ${err.message}`,
+ {receipt},
+ ERROR_CODES.ERR_CODEMOD_FAILED,
+ );
+ p.log.error(`Post-codemod hook failed: ${err.message}`);
+ p.outro('Upgrade failed');
+ process.exitCode = 1;
+ return;
+ }
}
// Refresh agent docs if any exist (AGENTS.md, CLAUDE.md, .claude/CLAUDE.md, etc.)
@@ -444,11 +625,9 @@ export function registerUpgrade(program) {
}
}
- if (codemodResult && typeof codemodResult === 'object') {
- receipt.filesChanged = codemodResult.totalFilesChanged ?? 0;
- receipt.transformsApplied = codemodResult.totalTransformsApplied ?? 0;
- receipt.errors = codemodResult.errors ?? [];
- }
+ receipt.filesChanged = mergedFilesChanged;
+ receipt.transformsApplied = mergedTransformsApplied;
+ receipt.errors = mergedErrors;
if (receipt.errors?.length > 0) {
const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
diff --git a/packages/cli/src/commands/validate-integration.mjs b/packages/cli/src/commands/validate-integration.mjs
new file mode 100644
index 0000000000..2bbbf665ef
--- /dev/null
+++ b/packages/cli/src/commands/validate-integration.mjs
@@ -0,0 +1,110 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx validate-integration` command — validate ONE integration
+ * package's manifest and contributions and report findings using the
+ * AstryxIntegrationIssue model.
+ *
+ * astryx validate-integration validate the local package (cwd)
+ * astryx validate-integration <pkg> validate an installed package
+ *
+ * Exit code is the contract: 0 when there are no severity:'error' issues
+ * (warnings are fine), 1 when any error issue is present — so it works as a CI
+ * gate. The no-arg + no-local-manifest case prints guidance and exits 0 (not
+ * an integration package is not a failure).
+ */
+
+import {jsonOut, humanLog} from '../lib/json.mjs';
+import {
+ validateLocalIntegration,
+ validateInstalledIntegration,
+ summarizeIssues,
+} from '../api/validate-integration.mjs';
+
+/**
+ * Render a validation result for humans.
+ * @param {import('../api/validate-integration.mjs').ValidateResult} result
+ */
+function printHuman(result) {
+ const label =
+ result.version != null
+ ? `${result.name}@${result.version}`
+ : result.name;
+ humanLog(`Validating integration: ${label}`);
+
+ if (result.issues.length === 0) {
+ humanLog('\n\u2713 No issues found.');
+ return;
+ }
+
+ humanLog('');
+ for (const issue of result.issues) {
+ humanLog(` ${issue.severity} ${issue.code}: ${issue.message}`);
+ }
+
+ const {errors, warnings} = summarizeIssues(result.issues);
+ humanLog(
+ `\n${result.issues.length} issue(s): ${errors} error(s), ${warnings} warning(s)`,
+ );
+}
+
+const NO_MANIFEST_GUIDANCE =
+ 'No astryx.integration.* found next to package.json. ' +
+ 'To validate an installed integration: astryx validate-integration <package>';
+
+/**
+ * Register the `astryx validate-integration` command.
+ * @param {import('commander').Command} program
+ */
+export function registerValidateIntegration(program) {
+ program
+ .command('validate-integration [package]')
+ .description(
+ 'Validate an Astryx integration package (manifest + contributions)',
+ )
+ .addHelpText(
+ 'after',
+ '\nWith no argument, validates the integration package rooted at the\n' +
+ 'current directory. Pass a package name to validate an installed\n' +
+ 'integration resolved from ./node_modules.\n\n' +
+ 'Exit code:\n' +
+ ' 0 no error issues (warnings are allowed) — safe as a CI gate\n' +
+ ' 1 one or more error issues\n',
+ )
+ .action(async pkg => {
+ const json = program.opts().json || false;
+
+ const result = pkg
+ ? await validateInstalledIntegration(pkg)
+ : await validateLocalIntegration();
+
+ // No-arg + no local manifest: guidance, not an error.
+ if (!result.found) {
+ if (json) {
+ jsonOut('integration.validate', {
+ name: null,
+ version: null,
+ issues: [],
+ });
+ } else {
+ humanLog(NO_MANIFEST_GUIDANCE);
+ }
+ return;
+ }
+
+ if (json) {
+ jsonOut('integration.validate', {
+ name: result.name ?? null,
+ version: result.version ?? null,
+ issues: result.issues,
+ });
+ } else {
+ printHuman(result);
+ }
+
+ const {errors} = summarizeIssues(result.issues);
+ if (errors > 0) {
+ process.exitCode = 1;
+ }
+ });
+}
diff --git a/packages/cli/src/commands/validate-integration.test.mjs b/packages/cli/src/commands/validate-integration.test.mjs
new file mode 100644
index 0000000000..d51d6b55d4
--- /dev/null
+++ b/packages/cli/src/commands/validate-integration.test.mjs
@@ -0,0 +1,124 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Command-level tests for `astryx validate-integration` — envelope shape
+ * and the no-manifest guidance path.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {Command} from 'commander';
+
+import {registerValidateIntegration} from './validate-integration.mjs';
+
+let tmpDir;
+let logCalls;
+let prevCwd;
+let prevExit;
+
+beforeEach(() => {
+ // Temp dir under the repo root so manifest/node_modules paths are within
+ // Vite's allowed fs roots.
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-validate-cmd-'));
+ logCalls = [];
+ vi.spyOn(console, 'log').mockImplementation((...args) => {
+ logCalls.push(args.join(' '));
+ });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ prevCwd = process.cwd();
+ prevExit = process.exitCode;
+ process.exitCode = undefined;
+});
+
+afterEach(() => {
+ process.chdir(prevCwd);
+ process.exitCode = prevExit;
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+});
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ program.option('--json', 'Output as typed JSON');
+ registerValidateIntegration(program);
+ return program;
+}
+
+describe('validate-integration — command', () => {
+ it('--json emits an integration.validate envelope for a valid package', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ 'export default {};\n',
+ );
+ process.chdir(tmpDir);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'astryx', '--json', 'validate-integration']);
+
+ const parsed = JSON.parse(logCalls.join('\n'));
+ expect(parsed.apiVersion).toBe(1);
+ expect(parsed.type).toBe('integration.validate');
+ expect(parsed.data.name).toBe('@acme/widgets');
+ expect(parsed.data.version).toBe('1.2.3');
+ expect(Array.isArray(parsed.data.issues)).toBe(true);
+ expect(parsed.data.issues).toHaveLength(0);
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('--json envelope carries issues and sets exit 1 on errors', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: '@acme/bad', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.integration.mjs'),
+ 'export default { templates: "./gone" };\n',
+ );
+ process.chdir(tmpDir);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'astryx', '--json', 'validate-integration']);
+
+ const parsed = JSON.parse(logCalls.join('\n'));
+ expect(parsed.type).toBe('integration.validate');
+ expect(parsed.data.issues.some(i => i.code === 'missing_root')).toBe(true);
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('no-arg + no manifest prints guidance and stays exit 0', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'plain'}),
+ );
+ process.chdir(tmpDir);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'astryx', 'validate-integration']);
+
+ const out = logCalls.join('\n');
+ expect(out).toContain('No astryx.integration.* found next to package.json');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('--json with no manifest yields a null-identity envelope', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'plain'}),
+ );
+ process.chdir(tmpDir);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'astryx', '--json', 'validate-integration']);
+
+ const parsed = JSON.parse(logCalls.join('\n'));
+ expect(parsed.type).toBe('integration.validate');
+ expect(parsed.data.name).toBeNull();
+ expect(parsed.data.issues).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/config.mjs b/packages/cli/src/config.mjs
index 2e661aead4..4e7074d5a3 100644
--- a/packages/cli/src/config.mjs
+++ b/packages/cli/src/config.mjs
@@ -1,31 +1,18 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {validateConfig, validateIntegration} from './lib/config-schema.mjs';
-
/**
- * Type-preserving helpers for Astryx config and integration manifests.
+ * Type-preserving helper for the Astryx config file.
+ *
+ * This is an intentionally tiny runtime identity function: it returns its
+ * argument unchanged. Its value is the exported TypeScript surface from
+ * `@astryxdesign/cli/config`, so config files get editor/type feedback without
+ * coupling to CLI internals. Validation is NOT performed here — it happens at
+ * the load boundary (see `loadModuleWithSchema` + `AstryxConfigSchema`).
*
- * These are intentionally tiny runtime identity functions. Their value is the
- * exported TypeScript surface from `@astryxdesign/cli/config`, so config files
- * can get editor/type feedback without coupling to CLI internals.
- */
-
-/**
* @template {import('./types/config').AstryxConfig} T
* @param {T} config
* @returns {T}
*/
export function createConfig(config) {
- validateConfig(config);
return config;
}
-
-/**
- * @template {import('./types/config').AstryxIntegration} T
- * @param {T} integration
- * @returns {T}
- */
-export function createIntegration(integration) {
- validateIntegration(integration);
- return integration;
-}
diff --git a/packages/cli/src/config.test.mjs b/packages/cli/src/config.test.mjs
index a40fdc1f4d..053c3b745e 100644
--- a/packages/cli/src/config.test.mjs
+++ b/packages/cli/src/config.test.mjs
@@ -1,24 +1,100 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, expect, it} from 'vitest';
-import {createConfig, createIntegration} from './config.mjs';
+import {createConfig} from './config.mjs';
+import {createIntegration} from './integration.mjs';
+import {
+ AstryxConfigSchema,
+ AstryxIntegrationSchema,
+} from './lib/config-schema.mjs';
-describe('config helpers', () => {
- it('return config and integration objects unchanged', () => {
+// createConfig/createIntegration are now pure typed-identity helpers: they
+// return their argument unchanged and perform NO runtime validation. Validation
+// happens at the LOAD boundary (loadModuleWithSchema against the schemas below),
+// so the rejection cases that used to assert factory throws now assert the
+// schema rejects the same shapes.
+
+describe('createConfig (typed identity)', () => {
+ it('returns the config unchanged', () => {
const config = {integrations: ['@acme/widgets']};
- const integration = {name: '@acme/widgets', docs: './docs'};
expect(createConfig(config)).toBe(config);
- expect(createIntegration(integration)).toBe(integration);
+ expect(createConfig({})).toEqual({});
+ });
+
+ it('does NOT validate — returns invalid shapes unchanged', () => {
+ const bogus = {packages: ['./libs']};
+ expect(createConfig(bogus)).toBe(bogus);
+ const badIntegrations = {integrations: '@acme/widgets'};
+ expect(createConfig(badIntegrations)).toBe(badIntegrations);
+ });
+});
+
+describe('AstryxConfigSchema (load-boundary validation)', () => {
+ it('accepts a valid minimal config', () => {
+ expect(AstryxConfigSchema.parse({})).toEqual({});
+ expect(
+ AstryxConfigSchema.parse({integrations: ['@acme/widgets']}),
+ ).toEqual({integrations: ['@acme/widgets']});
});
- it('validates config and integration shapes', () => {
- expect(() => createConfig({integrations: [42]})).toThrow(/integrations/);
- expect(() => createIntegration({docs: './docs'})).toThrow(/name/);
+ it('accepts hooks.postCodemod with a buildCommand function', () => {
+ const config = {
+ hooks: {postCodemod: [{name: 'format', buildCommand: () => null}]},
+ };
+ expect(() => AstryxConfigSchema.parse(config)).not.toThrow();
+ });
+
+ it('rejects unknown keys (strict)', () => {
+ expect(() => AstryxConfigSchema.parse({packages: ['./libs']})).toThrow(
+ /packages|Unrecognized/,
+ );
+ });
+
+ it('rejects a non-array integrations field', () => {
expect(() =>
- createIntegration({
- name: '@acme/widgets',
- postCodemod: [{name: 'empty'}],
- }),
- ).toThrow(/postCodemod/);
+ AstryxConfigSchema.parse({integrations: '@acme/widgets'}),
+ ).toThrow();
+ });
+
+ it('rejects a non-URL issuesUrl', () => {
+ expect(() => AstryxConfigSchema.parse({issuesUrl: 'not-a-url'})).toThrow();
+ });
+
+ it('rejects a postCodemod hook without buildCommand', () => {
+ expect(() =>
+ AstryxConfigSchema.parse({hooks: {postCodemod: [{name: 'empty'}]}}),
+ ).toThrow();
+ });
+});
+
+describe('createIntegration (typed identity)', () => {
+ it('returns the integration unchanged', () => {
+ const integration = {components: './src'};
+ expect(createIntegration(integration)).toBe(integration);
+ expect(createIntegration({})).toEqual({});
+ });
+
+ it('does NOT validate — returns invalid shapes unchanged', () => {
+ const bogus = {name: '@acme/widgets'};
+ expect(createIntegration(bogus)).toBe(bogus);
+ });
+});
+
+describe('AstryxIntegrationSchema (load-boundary validation)', () => {
+ it('accepts a valid minimal integration', () => {
+ expect(AstryxIntegrationSchema.parse({components: './src'})).toEqual({
+ components: './src',
+ });
+ expect(AstryxIntegrationSchema.parse({})).toEqual({});
+ });
+
+ it('rejects unknown keys (strict)', () => {
+ expect(() => AstryxIntegrationSchema.parse({name: '@acme/widgets'})).toThrow(
+ /name|Unrecognized/,
+ );
+ });
+
+ it('rejects a non-URL issuesUrl', () => {
+ expect(() => AstryxIntegrationSchema.parse({issuesUrl: 'nope'})).toThrow();
});
});
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index 7334504b35..c64ea8b885 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -61,10 +61,10 @@ export const JSON_SUPPORTED = new Set([
'theme build',
'theme list',
'theme add',
- 'gap-report',
'upgrade',
'manifest',
'doctor',
+ 'validate-integration',
'layout expand',
'layout check',
'layout grammar',
@@ -155,7 +155,7 @@ program
});
/**
- * Compute the fully qualified command name, e.g. "theme build" or "gap-report".
+ * Compute the fully qualified command name, e.g. "theme build" or "swizzle".
* @param {import('commander').Command} actionCommand
* @returns {string}
*/
@@ -249,7 +249,6 @@ const commands = [
// agent-docs folded into init — functions still importable from agent-docs.mjs
{name: 'template', path: './commands/template.mjs', register: 'registerTemplate'},
{name: 'layout', path: './commands/layout.mjs', register: 'registerLayout'},
- {name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},
{name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},
{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},
{name: 'hook', path: './commands/hook/index.mjs', register: 'registerHook'},
@@ -257,6 +256,11 @@ const commands = [
{name: 'search', path: './commands/search.mjs', register: 'registerSearch'},
{name: 'build', path: './commands/build.mjs', register: 'registerBuild'},
{name: 'doctor', path: './commands/doctor.mjs', register: 'registerDoctor'},
+ {
+ name: 'validate-integration',
+ path: './commands/validate-integration.mjs',
+ register: 'registerValidateIntegration',
+ },
];
for (const cmd of commands) {
diff --git a/packages/cli/src/integration.mjs b/packages/cli/src/integration.mjs
new file mode 100644
index 0000000000..a5761c6c99
--- /dev/null
+++ b/packages/cli/src/integration.mjs
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Type-preserving helper for an Astryx integration manifest.
+ *
+ * This is an intentionally tiny runtime identity function: it returns its
+ * argument unchanged. Its value is the exported TypeScript surface from
+ * `@astryxdesign/cli/integration`, so manifests get editor/type feedback
+ * without coupling to CLI internals. Validation is NOT performed here — it
+ * happens at the load boundary (see `loadModuleWithSchema` +
+ * `AstryxIntegrationSchema`).
+ *
+ * @template {import('./types/integration').AstryxIntegration} T
+ * @param {T} integration
+ * @returns {T}
+ */
+export function createIntegration(integration) {
+ return integration;
+}
diff --git a/packages/cli/src/lib/component-discovery.mjs b/packages/cli/src/lib/component-discovery.mjs
index a7c15327ff..d2bf242d85 100644
--- a/packages/cli/src/lib/component-discovery.mjs
+++ b/packages/cli/src/lib/component-discovery.mjs
@@ -9,6 +9,12 @@ import * as path from 'node:path';
const SKIP_DIRS = new Set(['hooks', 'utils', '__tests__', 'node_modules']);
+/** The owner package name for built-in (core) components. */
+export const CORE_PACKAGE = '@astryxdesign/core';
+
+/** Conventional doc-file suffixes for integration components (same-stem). */
+const INTEGRATION_DOC_SUFFIXES = ['.doc.ts', '.doc.mjs', '.doc.js'];
+
// Component source files are named `XDS{Name}.tsx` today. The XDS-prefix
// migration (P2380608025, P4) renames them to the bare `{Name}.tsx` form, so
// discovery must recognize BOTH. The `XDS` prefix has historically doubled as
@@ -475,6 +481,177 @@ export function findExternalComponentDoc(docsDir, name) {
return scanDir(docsDir);
}
+// ── Integration component discovery (ownership-aware) ────────────────
+//
+// Integration packages contribute a `components` root (resolved absolute path
+// in `loadedIntegrations`, see lib/integrations.mjs). Each component uses a
+// same-stem source/doc convention — e.g. `MetaAppShell.tsx` next to
+// `MetaAppShell.doc.{ts,mjs,js}`. The doc file is authoritative for discovery;
+// the sibling `.tsx` (if present) is the swizzleable source.
+//
+// Each discovered component is recorded with its OWNER package (the
+// integration's package name) and the owner's `issuesUrl` so downstream
+// commands — and the future integration-component swizzle — can disambiguate
+// by package and route source/issues correctly.
+
+/**
+ * Given an integration component doc path, return the sibling component source
+ * (`{Name}.tsx`) if one exists, else null.
+ *
+ * @param {string} docPath absolute path to a `{Name}.doc.{ts,mjs,js}` file
+ * @returns {string|null}
+ */
+function integrationSourceForDoc(docPath) {
+ const dir = path.dirname(docPath);
+ const base = path.basename(docPath).replace(/\.doc\.(ts|mjs|js)$/, '');
+ const candidate = path.join(dir, `${base}.tsx`);
+ return fs.existsSync(candidate) ? candidate : null;
+}
+
+/**
+ * Discover ownership records for the components contributed by a single loaded
+ * integration. Scans the integration's resolved `components` dir for same-stem
+ * doc files and records each with owner package + issuesUrl + sourcePath.
+ *
+ * @param {{name: string, components?: string, issuesUrl?: string}} integration
+ * a single entry from `loadedIntegrations` (lib/integrations.mjs)
+ * @returns {Array<{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>}
+ */
+export function discoverIntegrationComponents(integration) {
+ const componentsDir = integration?.components;
+ if (!componentsDir || !fs.existsSync(componentsDir)) return [];
+
+ /** @type {Map<string, {name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>} */
+ const byName = new Map();
+
+ function scanDir(dirPath) {
+ const entries = fs.readdirSync(dirPath, {withFileTypes: true});
+ for (const entry of entries) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ const fullPath = path.join(dirPath, entry.name);
+ if (entry.isDirectory()) {
+ scanDir(fullPath);
+ continue;
+ }
+ const suffix = INTEGRATION_DOC_SUFFIXES.find(s => entry.name.endsWith(s));
+ if (!suffix) continue;
+ const name = entry.name.slice(0, -suffix.length);
+ const {group, hidden} = readDocMeta(fullPath);
+ if (hidden) continue;
+ // First doc wins per name (precedence matches INTEGRATION_DOC_SUFFIXES).
+ if (byName.has(name)) continue;
+ byName.set(name, {
+ name,
+ package: integration.name,
+ docPath: fullPath,
+ sourcePath: integrationSourceForDoc(fullPath),
+ issuesUrl: integration.issuesUrl,
+ group: group ?? null,
+ });
+ }
+ }
+
+ scanDir(componentsDir);
+ return [...byName.values()];
+}
+
+/**
+ * Find an integration component's doc file by name within a loaded
+ * integration's resolved `components` dir. Honors the same-stem convention
+ * (`{Name}.doc.{ts,mjs,js}`), preferring `.ts` → `.mjs` → `.js`.
+ *
+ * @param {{components?: string}} integration
+ * @param {string} name bare component name (no `XDS`/`Astryx` prefix)
+ * @returns {string|null}
+ */
+export function findIntegrationComponentDoc(integration, name) {
+ const componentsDir = integration?.components;
+ if (!componentsDir || !fs.existsSync(componentsDir)) return null;
+
+ function scanDir(dirPath) {
+ const entries = fs.readdirSync(dirPath, {withFileTypes: true});
+ // Exact same-stem match (precedence order) first in this dir.
+ for (const suffix of INTEGRATION_DOC_SUFFIXES) {
+ const candidate = path.join(dirPath, `${name}${suffix}`);
+ if (fs.existsSync(candidate)) return candidate;
+ }
+ for (const entry of entries) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ if (entry.isDirectory()) {
+ const found = scanDir(path.join(dirPath, entry.name));
+ if (found) return found;
+ }
+ }
+ return null;
+ }
+
+ return scanDir(componentsDir);
+}
+
+/**
+ * Find an integration component's swizzleable source file (`{Name}.tsx`) by
+ * name within a loaded integration's resolved `components` dir. Returns null
+ * when the integration ships docs without source.
+ *
+ * @param {{components?: string}} integration
+ * @param {string} name bare component name
+ * @returns {string|null}
+ */
+export function findIntegrationComponentSource(integration, name) {
+ const docPath = findIntegrationComponentDoc(integration, name);
+ if (!docPath) return null;
+ return integrationSourceForDoc(docPath);
+}
+
+/**
+ * Build a flat list of ownership records for ALL discoverable components —
+ * core (built-in) plus every loaded integration. This is the authoritative
+ * source for package-aware listing and disambiguation.
+ *
+ * Core records carry `package: '@astryxdesign/core'`, `issuesUrl: undefined`
+ * (the default core issues URL), and the resolved `.tsx` source via
+ * findComponentSource(). Integration records carry their owner package name,
+ * the manifest `issuesUrl`, and the same-stem `.tsx` source if present.
+ *
+ * @param {string} coreDir
+ * @param {Array<{name: string, components?: string, issuesUrl?: string}>} [loadedIntegrations]
+ * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
+ */
+export function discoverOwnedComponents(coreDir, loadedIntegrations = []) {
+ /** @type {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>} */
+ const records = [];
+
+ // Core components — derive group from discoverComponents (grouped record).
+ const grouped = discoverComponents(coreDir);
+ /** @type {Map<string, string|null>} name → group */
+ const coreGroup = new Map();
+ for (const [key, members] of Object.entries(grouped)) {
+ const isUngrouped = members.length === 1 && members[0] === key;
+ for (const name of members) {
+ coreGroup.set(name, isUngrouped ? null : key);
+ }
+ }
+ for (const [name, group] of coreGroup) {
+ records.push({
+ name,
+ package: CORE_PACKAGE,
+ group,
+ docPath: findComponentReadme(coreDir, name),
+ sourcePath: findComponentSource(coreDir, name),
+ issuesUrl: undefined,
+ });
+ }
+
+ // Integration components.
+ for (const integration of loadedIntegrations) {
+ for (const rec of discoverIntegrationComponents(integration)) {
+ records.push(rec);
+ }
+ }
+
+ return records;
+}
+
// ── Legacy markdown-parsing functions ────────────────────────────────
// These are kept for backward compatibility with existing tests.
// The CLI action handler uses the new format functions below instead.
diff --git a/packages/cli/src/lib/config-cache.mjs b/packages/cli/src/lib/config-cache.mjs
new file mode 100644
index 0000000000..66b493176e
--- /dev/null
+++ b/packages/cli/src/lib/config-cache.mjs
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Pluggable config/discovery cache for the Project API.
+ *
+ * The Project class memoizes resolved discovery (components, templates,
+ * codemods, config) behind a small key/value cache so the same work is never
+ * repeated within a single Project instance. The cache interface is
+ * intentionally tiny — `get(key)` / `set(key, value)` — so a future
+ * file-backed, cross-process cache can drop in with NO API change.
+ *
+ * Cache keys are derived from a CONTENT HASH of the project's config file
+ * (see {@link configContentHash}) combined with the cwd and the
+ * discovery-kind (+ args). The in-memory implementation never busts on a
+ * content change, but the hash is computed regardless so a hash-busting,
+ * file-backed cache works against the exact same key path.
+ *
+ * @typedef {Object} ConfigCache
+ * @property {(key: string) => unknown} get
+ * @property {(key: string, value: unknown) => void} set
+ */
+
+import * as fs from 'node:fs';
+import * as crypto from 'node:crypto';
+
+/**
+ * Stable sentinel hash used when there is no config file (or it can't be
+ * read). Keeps key derivation total — every cwd still produces a key.
+ */
+export const NO_CONFIG_HASH = 'no-config';
+
+/**
+ * Compute a stable content hash for a config file. Reads the file bytes and
+ * returns their sha256 hex digest; a missing/unreadable file yields
+ * {@link NO_CONFIG_HASH}. The hash is the bust signal a future file-backed
+ * cache would key on.
+ *
+ * @param {string | null | undefined} configPath absolute config path, or null
+ * @returns {string}
+ */
+export function configContentHash(configPath) {
+ if (!configPath) return NO_CONFIG_HASH;
+ try {
+ const bytes = fs.readFileSync(configPath);
+ return crypto.createHash('sha256').update(bytes).digest('hex');
+ } catch {
+ return NO_CONFIG_HASH;
+ }
+}
+
+/**
+ * Build a cache key from a config content hash, a cwd, and a discovery kind
+ * (already including any args, e.g. `codemods:0.1.0..0.2.0`). The shape is
+ * stable so the same inputs always map to the same key.
+ *
+ * @param {string} hash config content hash
+ * @param {string} cwd
+ * @param {string} kind discovery kind (+args)
+ * @returns {string}
+ */
+export function cacheKey(hash, cwd, kind) {
+ return `${hash}\u0000${cwd}\u0000${kind}`;
+}
+
+/**
+ * Default in-memory cache. Per-instance by default (the Project creates one in
+ * {@link Project.load} when none is supplied), so it behaves like simple
+ * memoization. A shared instance can be passed to reuse results across
+ * Projects. Never busts — a content change produces a different KEY (via the
+ * hash), not an eviction, which is exactly the behavior a future file-backed
+ * cache also relies on.
+ *
+ * @implements {ConfigCache}
+ */
+export class InMemoryConfigCache {
+ /** @type {Map<string, unknown>} */
+ #m = new Map();
+
+ /** @param {string} key */
+ get(key) {
+ return this.#m.get(key);
+ }
+
+ /**
+ * @param {string} key
+ * @param {unknown} value
+ */
+ set(key, value) {
+ this.#m.set(key, value);
+ }
+}
diff --git a/packages/cli/src/lib/config-cache.test.mjs b/packages/cli/src/lib/config-cache.test.mjs
new file mode 100644
index 0000000000..619657f99f
--- /dev/null
+++ b/packages/cli/src/lib/config-cache.test.mjs
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {
+ InMemoryConfigCache,
+ cacheKey,
+ configContentHash,
+ NO_CONFIG_HASH,
+} from './config-cache.mjs';
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-cache-test-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('InMemoryConfigCache', () => {
+ it('stores and returns values by key', () => {
+ const cache = new InMemoryConfigCache();
+ expect(cache.get('a')).toBeUndefined();
+ cache.set('a', 42);
+ expect(cache.get('a')).toBe(42);
+ });
+
+ it('can store falsy values distinctly from a miss', () => {
+ const cache = new InMemoryConfigCache();
+ cache.set('zero', {value: 0});
+ expect(cache.get('zero')).toEqual({value: 0});
+ expect(cache.get('missing')).toBeUndefined();
+ });
+});
+
+describe('configContentHash', () => {
+ it('returns the sentinel when there is no config path', () => {
+ expect(configContentHash(null)).toBe(NO_CONFIG_HASH);
+ expect(configContentHash(undefined)).toBe(NO_CONFIG_HASH);
+ });
+
+ it('returns the sentinel for a missing file', () => {
+ expect(configContentHash(path.join(tmpDir, 'nope.mjs'))).toBe(
+ NO_CONFIG_HASH,
+ );
+ });
+
+ it('is stable for the same bytes', () => {
+ const file = path.join(tmpDir, 'astryx.config.mjs');
+ fs.writeFileSync(file, 'export default { integrations: [] };\n');
+ const a = configContentHash(file);
+ const b = configContentHash(file);
+ expect(a).toBe(b);
+ expect(a).not.toBe(NO_CONFIG_HASH);
+ });
+
+ it('differs when the config content changes', () => {
+ const file = path.join(tmpDir, 'astryx.config.mjs');
+ fs.writeFileSync(file, 'export default { integrations: [] };\n');
+ const before = configContentHash(file);
+ fs.writeFileSync(file, 'export default { integrations: ["@x/y"] };\n');
+ const after = configContentHash(file);
+ expect(before).not.toBe(after);
+ });
+});
+
+describe('cacheKey', () => {
+ it('is stable for identical inputs and varies by kind', () => {
+ const k1 = cacheKey('hash', '/cwd', 'components');
+ const k2 = cacheKey('hash', '/cwd', 'components');
+ const k3 = cacheKey('hash', '/cwd', 'templates');
+ expect(k1).toBe(k2);
+ expect(k1).not.toBe(k3);
+ });
+
+ it('varies by hash and cwd', () => {
+ expect(cacheKey('h1', '/cwd', 'k')).not.toBe(cacheKey('h2', '/cwd', 'k'));
+ expect(cacheKey('h', '/a', 'k')).not.toBe(cacheKey('h', '/b', 'k'));
+ });
+});
diff --git a/packages/cli/src/lib/config-schema.mjs b/packages/cli/src/lib/config-schema.mjs
index f1b302725b..c81429f543 100644
--- a/packages/cli/src/lib/config-schema.mjs
+++ b/packages/cli/src/lib/config-schema.mjs
@@ -8,77 +8,63 @@ const Fn = z.custom(value => typeof value === 'function', {
message: 'Expected function',
});
-const StringOrStringArray = z.union([z.string(), z.array(z.string())]);
-const GapReportSchema = z.union([
- z.literal(false),
- z.object({command: z.string()}).passthrough(),
-]);
-
-export const AstryxConfigSchema = z
+export const PostCodemodHookSchema = z
.object({
- packages: StringOrStringArray.optional(),
- integrations: StringOrStringArray.optional(),
- gapReport: GapReportSchema.optional(),
- template: z
- .object({
- get: Fn.optional(),
- })
- .passthrough()
- .optional(),
+ name: z.string().optional(),
+ buildCommand: Fn,
})
- .passthrough();
+ .strict();
-export const AstryxIntegrationCodemodSchema = z
+export const XleComponentSchema = z
.object({
- name: z.string(),
- from: z.string().optional(),
- to: z.string().optional(),
- title: z.string().optional(),
+ from: z.string(),
description: z.string().optional(),
- pr: z.string().optional(),
- optional: z.boolean().optional(),
- fileExtensions: z.array(z.string()).optional(),
- transform: z.union([z.string(), Fn]),
+ default: z.boolean().optional(),
})
- .passthrough();
+ .strict();
-export const AstryxPostCodemodHookSchema = z
+export const AstryxConfigSchema = z
.object({
- name: z.string().optional(),
- run: Fn.optional(),
- command: Fn.optional(),
+ integrations: z.array(z.string()).optional(),
+ issuesUrl: z.string().url().optional(),
+ hooks: z
+ .object({
+ postCodemod: z.array(PostCodemodHookSchema).optional(),
+ })
+ .strict()
+ .optional(),
+ experimental: z
+ .object({
+ xle: z
+ .object({
+ components: z.record(z.string(), XleComponentSchema).optional(),
+ })
+ .strict()
+ .optional(),
+ })
+ .strict()
+ .optional(),
})
- .passthrough()
- .refine(value => value.run || value.command, {
- message: 'postCodemod hook must define run() or command()',
- });
+ .strict();
export const AstryxIntegrationSchema = z
.object({
- name: z.string(),
- version: z.string().optional(),
- displayName: z.string().optional(),
- description: z.string().optional(),
- docs: z.string().optional(),
- category: z.string().optional(),
- blocks: z.string().optional(),
- gapReport: GapReportSchema.optional(),
- template: z
- .object({
- get: z.union([z.string(), Fn]).optional(),
- })
- .passthrough()
- .optional(),
- codemods: z.array(AstryxIntegrationCodemodSchema).optional(),
- postCodemod: z.array(AstryxPostCodemodHookSchema).optional(),
+ components: z.string().optional(),
+ templates: z.string().optional(),
+ codemods: z.string().optional(),
+ issuesUrl: z.string().url().optional(),
})
- .passthrough();
+ .strict();
/**
+ * Format a zod error into a single readable line, mirroring the issue-joining
+ * convention used across the CLI (path: message; path: message). Exported so
+ * the shared module loader and other validators stay in lockstep.
* @param {string} label
* @param {import('zod').ZodError} error
+ * @returns {string}
*/
-function formatZodError(label, error) {
+export function formatZodError(label, error) {
const issues = error.issues
.map(issue => {
const path = issue.path.length ? issue.path.join('.') : '(root)';
@@ -96,7 +82,7 @@ export function validateConfig(config) {
const result = AstryxConfigSchema.safeParse(config);
if (!result.success) {
throw new Error(
- formatZodError('astryx.config.mjs default export', result.error),
+ formatZodError('astryx.config default export', result.error),
);
}
return result.data;
@@ -105,7 +91,7 @@ export function validateConfig(config) {
/**
* @param {unknown} integration
* @param {string} [label]
- * @returns {import('../types/config').AstryxIntegration}
+ * @returns {import('../types/integration').AstryxIntegration}
*/
export function validateIntegration(
integration,
diff --git a/packages/cli/src/lib/config.mjs b/packages/cli/src/lib/config.mjs
deleted file mode 100644
index 0b531ce24d..0000000000
--- a/packages/cli/src/lib/config.mjs
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Config loader — reads astryx.config.mjs from project root
- *
- * Walks up from cwd looking for astryx.config.mjs.
- * Returns the config object or defaults if not found.
- */
-
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {pathToFileURL} from 'node:url';
-import {loadIntegrations} from './integrations.mjs';
-import {validateConfig} from './config-schema.mjs';
-
-const DEFAULTS = {
- packages: [],
- integrations: [],
-};
-
-/**
- * Find astryx.config.mjs by walking up from startDir.
- * Returns the absolute path or null.
- */
-export function findConfigPath(startDir = process.cwd()) {
- let dir = startDir;
- for (let i = 0; i < 10; i++) {
- const candidate = path.join(dir, 'astryx.config.mjs');
- if (fs.existsSync(candidate)) return candidate;
- const parent = path.dirname(dir);
- if (parent === dir) break;
- dir = parent;
- }
- return null;
-}
-
-/**
- * Load and return the config from astryx.config.mjs.
- * Returns defaults if no config file is found.
- */
-export async function loadConfig(startDir = process.cwd()) {
- const configPath = findConfigPath(startDir);
- if (!configPath) return {...DEFAULTS};
-
- let rawConfig;
- try {
- const mod = await import(pathToFileURL(configPath).href);
- rawConfig = mod.default || {};
- } catch {
- return {...DEFAULTS};
- }
-
- const config = validateConfig(rawConfig);
- const configDir = path.dirname(configPath);
- const integrationSpecs = normalizeIntegrations(config.integrations);
- const loadedIntegrations = await loadIntegrations(integrationSpecs, {
- cwd: configDir,
- });
- return {
- ...DEFAULTS,
- ...config,
- packages: normalizePackages(config.packages, configDir),
- integrations: integrationSpecs,
- loadedIntegrations,
- gapReport:
- config.gapReport ?? firstDefined(loadedIntegrations, 'gapReport'),
- template: mergeTemplateConfig(config.template, loadedIntegrations),
- };
-}
-
-/**
- * Normalize packages to an array of unique absolute paths.
- * Filters out empty strings and non-string values.
- * Relative paths resolved from config file directory.
- * Deduplicates by resolved path.
- */
-function normalizePackages(packages, configDir) {
- if (!packages) return [];
- const arr = Array.isArray(packages) ? packages : [packages];
- const seen = new Set();
- const result = [];
- for (const p of arr) {
- if (typeof p !== 'string' || p === '') continue;
- const resolved = path.isAbsolute(p) ? p : path.resolve(configDir, p);
- if (seen.has(resolved)) continue;
- seen.add(resolved);
- result.push(resolved);
- }
- return result;
-}
-
-/**
- * Normalize integration specs to a string array. Integrations are package names
- * or manifest paths consumed by `astryx upgrade --integration`.
- */
-function normalizeIntegrations(integrations) {
- if (!integrations) return [];
- const arr = Array.isArray(integrations) ? integrations : [integrations];
- return arr.filter(value => typeof value === 'string' && value !== '');
-}
-
-function firstDefined(integrations, key) {
- for (const integration of integrations) {
- if (integration[key] !== undefined) return integration[key];
- }
- return undefined;
-}
-
-function mergeTemplateConfig(template, integrations) {
- if (template?.get) return template;
- const integrationTemplate = firstDefined(integrations, 'template');
- return integrationTemplate ?? template;
-}
diff --git a/packages/cli/src/lib/config.test.mjs b/packages/cli/src/lib/config.test.mjs
deleted file mode 100644
index 566764f62b..0000000000
--- a/packages/cli/src/lib/config.test.mjs
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {loadConfig} from './config.mjs';
-
-let tmpDir;
-
-beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-config-test-'));
-});
-
-afterEach(() => {
- fs.rmSync(tmpDir, {recursive: true, force: true});
-});
-
-function installIntegrationPackage(dir, name = '@nest/xds-meta') {
- const packageDir = path.join(dir, 'node_modules', ...name.split('/'));
- fs.mkdirSync(packageDir, {recursive: true});
- fs.writeFileSync(
- path.join(packageDir, 'package.json'),
- JSON.stringify({name, astryx: {integration: './astryx.integration.mjs'}}),
- );
- fs.writeFileSync(
- path.join(packageDir, 'astryx.integration.mjs'),
- `export default { name: '${name}' };
-`,
- );
-}
-
-describe('loadConfig', () => {
- it('normalizes integrations from astryx.config.mjs', async () => {
- const dir = path.join(tmpDir, 'one');
- fs.mkdirSync(dir);
- installIntegrationPackage(dir);
- fs.writeFileSync(
- path.join(dir, 'astryx.config.mjs'),
- `export default { integrations: '@nest/xds-meta' };\n`,
- );
- await expect(loadConfig(dir)).resolves.toMatchObject({
- integrations: ['@nest/xds-meta'],
- });
- });
-
- it('rejects invalid integration package manifests', async () => {
- const dir = path.join(tmpDir, 'bad');
- fs.mkdirSync(dir);
- const packageDir = path.join(dir, 'node_modules', '@bad', 'widgets');
- fs.mkdirSync(packageDir, {recursive: true});
- fs.writeFileSync(
- path.join(dir, 'astryx.config.mjs'),
- `export default { integrations: '@bad/widgets' };\n`,
- );
- fs.writeFileSync(
- path.join(packageDir, 'package.json'),
- JSON.stringify({
- name: '@bad/widgets',
- astryx: {integration: './astryx.integration.mjs'},
- }),
- );
- fs.writeFileSync(
- path.join(packageDir, 'astryx.integration.mjs'),
- `export default { docs: './docs' };\n`,
- );
- await expect(loadConfig(dir)).rejects.toThrow(/name/);
- });
-
- it('normalizes integration arrays', async () => {
- const dir = path.join(tmpDir, 'two');
- fs.mkdirSync(dir);
- installIntegrationPackage(dir);
- fs.writeFileSync(
- path.join(dir, 'astryx.config.mjs'),
- `export default { integrations: ['@nest/xds-meta', ''] };\n`,
- );
- await expect(loadConfig(dir)).resolves.toMatchObject({
- integrations: ['@nest/xds-meta'],
- });
- });
-
- it('rejects invalid config shapes', async () => {
- const dir = path.join(tmpDir, 'invalid');
- fs.mkdirSync(dir);
- fs.writeFileSync(
- path.join(dir, 'astryx.config.mjs'),
- `export default { integrations: [42] };\n`,
- );
- await expect(loadConfig(dir)).rejects.toThrow(/integrations/);
- });
-});
diff --git a/packages/cli/src/lib/error-codes.mjs b/packages/cli/src/lib/error-codes.mjs
index e884a1d84b..541a58975e 100644
--- a/packages/cli/src/lib/error-codes.mjs
+++ b/packages/cli/src/lib/error-codes.mjs
@@ -52,6 +52,8 @@
* | 'ERR_UNKNOWN_SECTION'
* | 'ERR_UNKNOWN_CATEGORY'
* | 'ERR_UNKNOWN_TEMPLATE'
+ * | 'ERR_AMBIGUOUS_TEMPLATE'
+ * | 'ERR_AMBIGUOUS_COMPONENT'
* | 'ERR_UNKNOWN_THEME'
* | 'ERR_UNKNOWN_PACKAGE'
* | 'ERR_UNKNOWN_AGENT'
@@ -69,13 +71,10 @@
* | 'ERR_WRITE_FAILED'
* | 'ERR_THEME_INVALID'
* | 'ERR_THEME_LOAD'
- * | 'ERR_TEMPLATE_CONFIG'
- * | 'ERR_TEMPLATE_GET'
* | 'ERR_VERSION_DETECT'
* | 'ERR_INVALID_VERSION'
* | 'ERR_DEP_MISSING'
* | 'ERR_GH_CLI'
- * | 'ERR_GAP_REPORT_FAILED'
* | 'ERR_LAYOUT_PARSE'
* | 'ERR_LAYOUT_INVALID'
* )} ErrorCode
@@ -125,6 +124,10 @@ export const ERROR_CODES = Object.freeze({
ERR_UNKNOWN_CATEGORY: 'ERR_UNKNOWN_CATEGORY',
/** No template matched the requested name. */
ERR_UNKNOWN_TEMPLATE: 'ERR_UNKNOWN_TEMPLATE',
+ /** A template id matched more than one template (narrow with --type/--package). */
+ ERR_AMBIGUOUS_TEMPLATE: 'ERR_AMBIGUOUS_TEMPLATE',
+ /** A component name is owned by more than one package (narrow with --package). */
+ ERR_AMBIGUOUS_COMPONENT: 'ERR_AMBIGUOUS_COMPONENT',
/** No theme matched the requested slug (theme add). */
ERR_UNKNOWN_THEME: 'ERR_UNKNOWN_THEME',
/** No package matched the requested name (discover). */
@@ -166,12 +169,6 @@ export const ERROR_CODES = Object.freeze({
/** A theme file could not be loaded / parsed into a defineTheme result. */
ERR_THEME_LOAD: 'ERR_THEME_LOAD',
- // ── Template config ──────────────────────────────────────────────
- /** `template.get` is not configured in astryx.config.mjs (fetch-by-id). */
- ERR_TEMPLATE_CONFIG: 'ERR_TEMPLATE_CONFIG',
- /** A configured `template.get` threw or returned an invalid value. */
- ERR_TEMPLATE_GET: 'ERR_TEMPLATE_GET',
-
// ── Upgrade ──────────────────────────────────────────────────────
/** The current `@astryxdesign/core` version could not be detected. */
ERR_VERSION_DETECT: 'ERR_VERSION_DETECT',
@@ -180,11 +177,9 @@ export const ERROR_CODES = Object.freeze({
/** A required external dependency (e.g. jscodeshift) is missing. */
ERR_DEP_MISSING: 'ERR_DEP_MISSING',
- // ── Gap report ───────────────────────────────────────────────────
+ // ── GitHub CLI ───────────────────────────────────────────────────
/** GitHub CLI (`gh`) is not installed or not authenticated. */
ERR_GH_CLI: 'ERR_GH_CLI',
- /** Filing a gap report failed at the command/integration boundary. */
- ERR_GAP_REPORT_FAILED: 'ERR_GAP_REPORT_FAILED',
// ── Layout expressions (XLE/XLO) ─────────────────────────────────
/** A layout expression failed to parse (syntax error, with line/col). */
diff --git a/packages/cli/src/lib/integration-warnings.mjs b/packages/cli/src/lib/integration-warnings.mjs
new file mode 100644
index 0000000000..fb93b15f87
--- /dev/null
+++ b/packages/cli/src/lib/integration-warnings.mjs
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Compact, non-blocking integration-issue nudge for everyday commands.
+ *
+ * When a CONFIGURED integration (from the Project's `loadedIntegrations`) has
+ * validation issues, the everyday commands (component / template / upgrade)
+ * should print ONE compact, non-blocking line per integration telling the user
+ * to run `validate-integration` — instead of silently skipping broken
+ * contributions or spamming per-contribution diagnostics.
+ *
+ * Design constraints (all enforced here):
+ * - Reuses the validate-integration validators (validateLoadedIntegration);
+ * no validation logic is duplicated.
+ * - Writes to STDERR only, so it never corrupts a --json stdout envelope.
+ * - Suppressed entirely in --json mode.
+ * - Best-effort: never throws, never changes the exit code. Broken
+ * contributions are still skipped downstream exactly as before; this only
+ * ADDS a one-line nudge.
+ */
+
+import {validateLoadedIntegration} from '../api/validate-integration.mjs';
+
+/**
+ * For each configured (already-loaded) integration, compute its issues using
+ * the shared validate-integration validators and, if any exist, print exactly
+ * ONE line per integration to stderr:
+ *
+ * Warning: <pkg> has N integration issue(s). Run: astryx validate-integration <pkg>
+ *
+ * @param {Array<object>} loadedIntegrations the Project's loaded integrations
+ * @param {{json?: boolean}} [options]
+ * @returns {Promise<void>}
+ */
+export async function warnOnIntegrationIssues(loadedIntegrations, {json = false} = {}) {
+ try {
+ // Cheap guard: only do work when integrations are actually configured.
+ if (json) return;
+ if (!Array.isArray(loadedIntegrations) || loadedIntegrations.length === 0) {
+ return;
+ }
+ for (const integration of loadedIntegrations) {
+ if (!integration || typeof integration !== 'object') continue;
+ let issues;
+ try {
+ issues = await validateLoadedIntegration(integration);
+ } catch {
+ // Best-effort: a validator throwing must not break the host command.
+ continue;
+ }
+ if (!Array.isArray(issues) || issues.length === 0) continue;
+ const pkg = integration.name ?? integration.__spec ?? '(integration)';
+ // Stderr only — keeps stdout (and any --json envelope) clean.
+ console.error(
+ `Warning: ${pkg} has ${issues.length} integration issue(s). ` +
+ `Run: astryx validate-integration ${pkg}`,
+ );
+ }
+ } catch {
+ // Never throw, never change the exit code.
+ }
+}
diff --git a/packages/cli/src/lib/integration-warnings.test.mjs b/packages/cli/src/lib/integration-warnings.test.mjs
new file mode 100644
index 0000000000..39d378f5af
--- /dev/null
+++ b/packages/cli/src/lib/integration-warnings.test.mjs
@@ -0,0 +1,102 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Hermetic tests for the compact integration-issue nudge.
+ *
+ * Builds loaded-integration-shaped objects (as produced by
+ * lib/integrations.mjs) with absolute contribution roots under the repo root
+ * (process.cwd()) so any node_modules-style path stays within Vite's allowed
+ * fs roots. We never load configs from /tmp. The helper is exercised directly;
+ * stderr is captured to assert exactly one warning line per broken integration
+ * and zero output in --json mode / for clean integrations.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {warnOnIntegrationIssues} from './integration-warnings.mjs';
+
+let tmpDir;
+let errSpy;
+let errLines;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-warn-it-'));
+ errLines = [];
+ errSpy = vi.spyOn(console, 'error').mockImplementation((...args) => {
+ errLines.push(args.join(' '));
+ });
+});
+
+afterEach(() => {
+ errSpy.mockRestore();
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * Build a loaded-integration-shaped object. Roots are absolute (mirrors
+ * loadIntegrations' resolveRoot).
+ */
+function loaded({name = '@acme/widgets', components, templates, codemods} = {}) {
+ return {
+ name,
+ version: '1.0.0',
+ components: components == null ? undefined : path.join(tmpDir, components),
+ templates: templates == null ? undefined : path.join(tmpDir, templates),
+ codemods: codemods == null ? undefined : path.join(tmpDir, codemods),
+ __spec: name,
+ __packageDir: tmpDir,
+ };
+}
+
+describe('warnOnIntegrationIssues', () => {
+ it('emits exactly one stderr line for an integration with issues', async () => {
+ // Declared components root that does not exist on disk → missing_root.
+ const integration = loaded({components: 'does-not-exist'});
+ await warnOnIntegrationIssues([integration], {json: false});
+
+ expect(errLines).toHaveLength(1);
+ expect(errLines[0]).toBe(
+ 'Warning: @acme/widgets has 1 integration issue(s). ' +
+ 'Run: astryx validate-integration @acme/widgets',
+ );
+ });
+
+ it('emits nothing in --json mode (keeps stdout/JSON clean)', async () => {
+ const integration = loaded({components: 'does-not-exist'});
+ await warnOnIntegrationIssues([integration], {json: true});
+ expect(errLines).toHaveLength(0);
+ });
+
+ it('emits nothing for an integration with no issues', async () => {
+ // Existing components root with no broken contributions → no issues.
+ const componentsRoot = path.join(tmpDir, 'components');
+ fs.mkdirSync(componentsRoot, {recursive: true});
+ const integration = loaded({components: 'components'});
+ await warnOnIntegrationIssues([integration], {json: false});
+ expect(errLines).toHaveLength(0);
+ });
+
+ it('emits nothing when there are no configured integrations', async () => {
+ await warnOnIntegrationIssues([], {json: false});
+ await warnOnIntegrationIssues(undefined, {json: false});
+ expect(errLines).toHaveLength(0);
+ });
+
+ it('emits one line per broken integration', async () => {
+ const a = loaded({name: '@acme/a', components: 'missing-a'});
+ const b = loaded({name: '@acme/b', templates: 'missing-b'});
+ await warnOnIntegrationIssues([a, b], {json: false});
+ expect(errLines).toHaveLength(2);
+ expect(errLines[0]).toContain('@acme/a');
+ expect(errLines[1]).toContain('@acme/b');
+ });
+
+ it('never throws and never emits when a validator misbehaves', async () => {
+ // A non-object entry must be skipped silently.
+ await expect(
+ warnOnIntegrationIssues([null, 'nope', 42], {json: false}),
+ ).resolves.toBeUndefined();
+ expect(errLines).toHaveLength(0);
+ });
+});
diff --git a/packages/cli/src/lib/integrations.mjs b/packages/cli/src/lib/integrations.mjs
index 5da50d02b7..031b608159 100644
--- a/packages/cli/src/lib/integrations.mjs
+++ b/packages/cli/src/lib/integrations.mjs
@@ -3,95 +3,89 @@
/**
* @file Integration manifest loading for Astryx config.
*
- * Integrations are package names or direct manifest paths listed in
- * astryx.config.mjs. A manifest can contribute docs/discovery metadata,
- * gap-report/template hooks, upgrade codemods, and post-codemod hooks.
+ * Integrations are PACKAGE NAMES listed in astryx.config.{ts,mjs,js}. Each
+ * package declares a single conventional root manifest sibling to its
+ * package.json — astryx.integration.{ts,mjs,js} — which contributes
+ * components/templates/codemods roots and an optional issuesUrl. Identity
+ * (name, version) comes from the package's package.json, not the manifest.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {pathToFileURL} from 'node:url';
-import {validateIntegration} from './config-schema.mjs';
+import {AstryxIntegrationSchema} from './config-schema.mjs';
+import {loadModuleWithSchema, findPresentFiles} from './module-loader.mjs';
-export function isPathSpec(spec) {
- return (
- spec.startsWith('.') ||
- spec.startsWith('/') ||
- spec.endsWith('.mjs') ||
- spec.endsWith('.js')
- );
+/** Conventional manifest basenames, in load-precedence order. */
+export const MANIFEST_BASENAMES = [
+ 'astryx.integration.ts',
+ 'astryx.integration.mjs',
+ 'astryx.integration.js',
+];
+
+/**
+ * Return the conventional root manifest paths present in `dir`, in
+ * load-precedence order. Unlike {@link resolveManifestPath} this never throws —
+ * callers (e.g. validate-integration) decide how to treat zero / multiple.
+ * @param {string} dir
+ * @returns {string[]} absolute manifest paths
+ */
+export function findManifestPaths(dir) {
+ return findPresentFiles(dir, MANIFEST_BASENAMES);
}
+/**
+ * Load and validate a manifest module's default export against the integration
+ * schema. Default export only — `.ts` is loaded via jiti; `.mjs`/`.js` via
+ * dynamic import. Throws if the default export is missing or invalid. Exposed
+ * for validate-integration.
+ * @param {string} file absolute manifest path
+ * @param {string} [label] used in error messages
+ * @returns {Promise<import('../types/integration').AstryxIntegration>}
+ */
+export async function loadManifestObject(file, label = 'integration manifest') {
+ return loadModuleWithSchema(file, AstryxIntegrationSchema, {label});
+}
+
+/**
+ * Resolve the directory of an installed integration package from the consumer's
+ * node_modules.
+ * @param {string} packageName
+ * @param {string} [cwd]
+ */
export function resolvePackageDir(packageName, cwd = process.cwd()) {
return path.resolve(cwd, 'node_modules', ...packageName.split('/'));
}
-export function resolveIntegrationFile(spec, cwd = process.cwd()) {
- if (isPathSpec(spec)) {
- return path.resolve(cwd, spec);
- }
-
- const packageDir = resolvePackageDir(spec, cwd);
- const pkgPath = path.join(packageDir, 'package.json');
- let pkg;
- try {
- pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
- } catch {
+/**
+ * Find the single conventional root manifest sibling of the package's
+ * package.json. Multiple present is a hard error; missing is a hard error.
+ * @param {string} packageDir
+ * @param {string} spec
+ * @returns {string} absolute manifest path
+ */
+function resolveManifestPath(packageDir, spec) {
+ const present = findPresentFiles(packageDir, MANIFEST_BASENAMES);
+ if (present.length === 0) {
throw new Error(
- `Could not find installed integration package "${spec}" at ${pkgPath}. Install it first or pass a direct integration file path.`,
+ `Integration package "${spec}" has no conventional root manifest. Add one of: ${MANIFEST_BASENAMES.join(', ')} next to its package.json.`,
);
}
-
- const manifestPath = pkg.astryx?.integration ?? pkg.xds?.integration;
- if (!manifestPath) {
+ if (present.length > 1) {
throw new Error(
- `Package "${spec}" does not declare astryx.integration (or legacy xds.integration) in package.json.`,
+ `Integration package "${spec}" has multiple root manifests (${present
+ .map(file => path.basename(file))
+ .join(', ')}). Keep exactly one.`,
);
}
- return path.resolve(packageDir, manifestPath);
-}
-
-function normalizePackageContribution(integration) {
- const docs = integration.docs;
- if (!docs) return null;
- const packageDir = integration.__packageDir ?? integration.__dir;
- const docsDir = path.resolve(packageDir, docs);
- return {
- name: integration.name ?? integration.__spec,
- version: integration.version,
- description: integration.description,
- displayName: integration.displayName,
- dir: packageDir,
- astryx: {
- docs,
- category: integration.category,
- blocks: integration.blocks,
- },
- category: integration.category ?? integration.name ?? integration.__spec,
- docsDir,
- };
-}
-
-function resolveHookFunction(hook, integration) {
- if (typeof hook === 'function') return hook;
- if (typeof hook !== 'string') return hook;
- const [moduleSpec, exportName = 'default'] = hook.split('#');
- return async (...args) => {
- const mod = isPathSpec(moduleSpec)
- ? await import(
- pathToFileURL(path.resolve(integration.__dir, moduleSpec)).href
- )
- : await import(moduleSpec);
- const fn = exportName === 'default' ? mod.default : mod[exportName];
- if (typeof fn !== 'function') {
- throw new Error(
- `Integration hook ${hook} did not resolve to a function.`,
- );
- }
- return fn(...args);
- };
+ return present[0];
}
+/**
+ * Load configured integrations.
+ *
+ * @param {string[]} [specs] package names
+ * @param {{cwd?: string}} [options]
+ */
export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
const integrations = [];
const seen = new Set();
@@ -100,55 +94,38 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
if (!spec || seen.has(spec)) continue;
seen.add(spec);
- const file = resolveIntegrationFile(spec, cwd);
- const mod = await import(pathToFileURL(file).href);
- const exported = mod.default ?? mod.integration ?? mod;
- if (!exported || typeof exported !== 'object') {
- throw new Error(`Integration ${spec} did not export an object.`);
+ const packageDir = resolvePackageDir(spec, cwd);
+ const pkgPath = path.join(packageDir, 'package.json');
+ let pkg;
+ try {
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ } catch {
+ throw new Error(
+ `Could not find installed integration package "${spec}" at ${pkgPath}. Install it first.`,
+ );
}
- const integration = validateIntegration(exported, `Integration ${spec}`);
- const integrationDir = path.dirname(file);
- const packageDir = isPathSpec(spec)
- ? integrationDir
- : resolvePackageDir(spec, cwd);
- const normalized = {
- ...integration,
- __file: file,
- __dir: integrationDir,
- __packageDir: packageDir,
- __spec: spec,
- };
-
- if (Array.isArray(normalized.codemods)) {
- for (const codemod of normalized.codemods) {
- if (typeof codemod.transform === 'string') {
- const transformPath = path.resolve(integrationDir, codemod.transform);
- const transformMod = await import(pathToFileURL(transformPath).href);
- codemod.transform =
- transformMod.default ?? transformMod.transform ?? transformMod;
- }
- }
- }
+ const manifestFile = resolveManifestPath(packageDir, spec);
+ const manifest = await loadModuleWithSchema(
+ manifestFile,
+ AstryxIntegrationSchema,
+ {label: `Integration ${spec}`},
+ );
- normalized.package = normalizePackageContribution(normalized);
- if (
- normalized.gapReport?.command &&
- isPathSpec(normalized.gapReport.command)
- ) {
- normalized.gapReport = {
- ...normalized.gapReport,
- command: path.resolve(packageDir, normalized.gapReport.command),
- };
- }
- if (normalized.template?.get) {
- normalized.template = {
- ...normalized.template,
- get: resolveHookFunction(normalized.template.get, normalized),
- };
- }
+ const resolveRoot = value =>
+ value == null ? undefined : path.resolve(packageDir, value);
- integrations.push(normalized);
+ integrations.push({
+ name: pkg.name ?? spec,
+ version: pkg.version,
+ components: resolveRoot(manifest.components),
+ templates: resolveRoot(manifest.templates),
+ codemods: resolveRoot(manifest.codemods),
+ issuesUrl: manifest.issuesUrl,
+ __spec: spec,
+ __packageDir: packageDir,
+ __manifestFile: manifestFile,
+ });
}
return integrations;
diff --git a/packages/cli/src/lib/integrations.test.mjs b/packages/cli/src/lib/integrations.test.mjs
index 28d9b3171d..0d110b36af 100644
--- a/packages/cli/src/lib/integrations.test.mjs
+++ b/packages/cli/src/lib/integrations.test.mjs
@@ -3,91 +3,39 @@
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {loadConfig} from './config.mjs';
+import {Project} from './project.mjs';
+import {loadIntegrations} from './integrations.mjs';
import {discover} from '../api/discover.mjs';
-import {loadGapReportConfig} from '../utils/github.mjs';
-import {getTemplateById} from '../api/template.mjs';
let tmpDir;
let originalCwd;
-beforeEach(() => {
- originalCwd = process.cwd();
- tmpDir = fs.mkdtempSync(
- path.join(process.cwd(), '.astryx-integration-test-'),
- );
- fs.mkdirSync(path.join(tmpDir, 'node_modules', '@acme', 'widgets'), {
- recursive: true,
- });
+function writeManifestPackage(dir, {basename = 'astryx.integration.mjs', body}) {
+ const pkgDir = path.join(dir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
fs.writeFileSync(
- path.join(tmpDir, 'astryx.config.mjs'),
- `export default { integrations: '@acme/widgets' };\n`,
- );
- fs.writeFileSync(
- path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'package.json'),
+ path.join(pkgDir, 'package.json'),
JSON.stringify({
name: '@acme/widgets',
version: '1.2.3',
- displayName: 'Acme Widgets',
- astryx: {integration: './astryx.integration.mjs'},
}),
);
- fs.writeFileSync(
- path.join(
- tmpDir,
- 'node_modules',
- '@acme',
- 'widgets',
- 'astryx.integration.mjs',
- ),
- `export default {
- name: '@acme/widgets',
- version: '1.2.3',
- displayName: 'Acme Widgets',
- docs: './docs',
- category: 'Acme',
- gapReport: {command: './scripts/report-gap.sh'},
- template: {get: './template.mjs#getTemplate'},
- codemods: [{name: 'noop', from: '0.0.0', to: '9.0.0', transform: './codemod.mjs'}],
- };\n`,
- );
- fs.mkdirSync(path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'docs'));
- fs.writeFileSync(
- path.join(
- tmpDir,
- 'node_modules',
- '@acme',
- 'widgets',
- 'docs',
- 'Widget.doc.mjs',
- ),
- `export const doc = {
- name: 'Widget',
- usage: {description: 'Acme widget'},
- props: [],
- };\n`,
- );
- fs.mkdirSync(
- path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'scripts'),
- );
- fs.writeFileSync(
- path.join(
- tmpDir,
- 'node_modules',
- '@acme',
- 'widgets',
- 'scripts',
- 'report-gap.sh',
- ),
- '#!/bin/sh\ncat >/dev/null\necho ok\n',
+ fs.writeFileSync(path.join(pkgDir, basename), body);
+ return pkgDir;
+}
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-integration-test-'),
);
fs.writeFileSync(
- path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'template.mjs'),
- `export async function getTemplate(id) { return 'template:' + id; }\n`,
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
);
fs.writeFileSync(
- path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'codemod.mjs'),
- `export default function transform() { return undefined; }\n`,
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: ['@acme/widgets'] };\n`,
);
process.chdir(tmpDir);
});
@@ -98,57 +46,90 @@ afterEach(() => {
});
describe('configured integrations', () => {
- it('load docs/gap/template/codemod metadata from integration manifests', async () => {
- const config = await loadConfig(tmpDir);
- expect(config.integrations).toEqual(['@acme/widgets']);
- expect(config.loadedIntegrations[0].name).toBe('@acme/widgets');
- expect(config.loadedIntegrations[0].package).toMatchObject({
- name: '@acme/widgets',
- category: 'Acme',
+ it('resolves identity from package.json and contribution roots to absolute paths', async () => {
+ const pkgDir = writeManifestPackage(tmpDir, {
+ body: `export default {
+ components: './docs',
+ templates: './blocks',
+ codemods: './codemods',
+ issuesUrl: 'https://example.com/issues',
+ };\n`,
});
- expect(config.loadedIntegrations[0].codemods[0].transform).toEqual(
- expect.any(Function),
- );
- expect(config.gapReport.command).toBe(
- path.join(
- tmpDir,
- 'node_modules',
- '@acme',
- 'widgets',
- 'scripts',
- 'report-gap.sh',
- ),
+ fs.mkdirSync(path.join(pkgDir, 'docs'));
+ fs.writeFileSync(
+ path.join(pkgDir, 'docs', 'Widget.doc.mjs'),
+ `export const doc = {
+ name: 'Widget',
+ usage: {description: 'Acme widget'},
+ props: [],
+ };\n`,
);
- await expect(config.template.get('P123')).resolves.toBe('template:P123');
+
+ const project = await Project.load(tmpDir);
+ expect(project.integrations).toEqual(['@acme/widgets']);
+ const loaded = project.loadedIntegrations[0];
+ // Identity comes from package.json, not the manifest.
+ expect(loaded.name).toBe('@acme/widgets');
+ expect(loaded.version).toBe('1.2.3');
+ expect(loaded.components).toBe(path.join(pkgDir, 'docs'));
+ expect(loaded.templates).toBe(path.join(pkgDir, 'blocks'));
+ expect(loaded.codemods).toBe(path.join(pkgDir, 'codemods'));
+ expect(loaded.issuesUrl).toBe('https://example.com/issues');
});
- it('makes integration docs discoverable without packages config', async () => {
+ it('makes integration components discoverable', async () => {
+ const pkgDir = writeManifestPackage(tmpDir, {
+ body: `export default { components: './docs' };\n`,
+ });
+ fs.mkdirSync(path.join(pkgDir, 'docs'));
+ fs.writeFileSync(
+ path.join(pkgDir, 'docs', 'Widget.doc.mjs'),
+ `export const doc = {
+ name: 'Widget',
+ usage: {description: 'Acme widget'},
+ props: [],
+ };\n`,
+ );
+
const result = await discover(undefined, {});
expect(result.type).toBe('discover.list');
expect(result.data).toEqual([
expect.objectContaining({
name: '@acme/widgets',
- category: 'Acme',
+ category: '@acme/widgets',
components: ['Widget'],
}),
]);
});
- it('uses integration gap-report and template hooks', async () => {
- await expect(loadGapReportConfig()).resolves.toMatchObject({
- enabled: true,
- command: path.join(
- tmpDir,
- 'node_modules',
- '@acme',
- 'widgets',
- 'scripts',
- 'report-gap.sh',
- ),
- });
- await expect(getTemplateById('P123', {cwd: tmpDir})).resolves.toEqual({
- type: 'template.get',
- data: {id: 'P123', source: 'template:P123'},
+ it('errors when the package has no conventional root manifest', async () => {
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets'}),
+ );
+ await expect(loadIntegrations(['@acme/widgets'], {cwd: tmpDir})).rejects.toThrow(
+ /no conventional root manifest/,
+ );
+ });
+
+ it('errors when the package has multiple root manifests', async () => {
+ const pkgDir = writeManifestPackage(tmpDir, {
+ body: `export default {};\n`,
});
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.js'),
+ `module.exports = {};\n`,
+ );
+ await expect(loadIntegrations(['@acme/widgets'], {cwd: tmpDir})).rejects.toThrow(
+ /multiple root manifests/,
+ );
+ });
+
+ it('errors when the package is not installed', async () => {
+ await expect(loadIntegrations(['@acme/missing'], {cwd: tmpDir})).rejects.toThrow(
+ /Could not find installed integration package/,
+ );
});
});
diff --git a/packages/cli/src/lib/manifest.mjs b/packages/cli/src/lib/manifest.mjs
index 3f20411a53..88f9e94ca7 100644
--- a/packages/cli/src/lib/manifest.mjs
+++ b/packages/cli/src/lib/manifest.mjs
@@ -56,16 +56,15 @@ export const RESPONSE_TYPES = {
'template.show',
'template.skeleton',
'template.copy',
- 'template.get',
],
hook: ['hook.list', 'hook.brief', 'hook.full', 'hook.detail', 'hook.detail.params'],
'theme build': ['theme.build'],
'theme list': ['theme.list'],
'theme add': ['theme.list', 'theme.add'],
upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],
- 'gap-report': ['gap-report.categories', 'gap-report.dryRun', 'gap-report.file'],
manifest: ['manifest'],
doctor: ['doctor'],
+ 'validate-integration': ['integration.validate'],
'layout expand': ['layout.expand'],
'layout check': ['layout.check'],
'layout grammar': ['layout.grammar'],
@@ -89,6 +88,10 @@ const EXAMPLES = {
upgrade: ['astryx upgrade --json'],
manifest: ['astryx manifest --json', 'astryx --json'],
doctor: ['astryx doctor', 'astryx doctor --json'],
+ 'validate-integration': [
+ 'astryx validate-integration',
+ 'astryx validate-integration @acme/widgets --json',
+ ],
init: ['astryx init'],
'layout expand': [`astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx`],
'layout check': [`astryx layout check 'A[cp6] > L > LC > S[p6]' --json`],
diff --git a/packages/cli/src/lib/module-loader.mjs b/packages/cli/src/lib/module-loader.mjs
new file mode 100644
index 0000000000..7a72f783de
--- /dev/null
+++ b/packages/cli/src/lib/module-loader.mjs
@@ -0,0 +1,80 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared module-loading + conventional-file-discovery primitives.
+ *
+ * Both config loading and integration loading need to (a) import a
+ * user-authored module (`.ts` via jiti, `.mjs`/`.js` via native dynamic
+ * import) and (b) find conventional files by basename in a fixed
+ * load-precedence order. These helpers centralize that so the two callers stay
+ * in lockstep.
+ *
+ * `loadModuleWithSchema` builds on these primitives to provide the single
+ * load/validation boundary shared by config, integration, codemod, and
+ * template discovery: import the module, take its default export, and validate
+ * it against the expected zod schema.
+ */
+
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import * as fs from 'node:fs';
+import {createJiti} from 'jiti';
+import {formatZodError} from './config-schema.mjs';
+
+let jitiInstance;
+function getJiti() {
+ if (!jitiInstance) {
+ jitiInstance = createJiti(import.meta.url);
+ }
+ return jitiInstance;
+}
+
+/**
+ * Import a user-authored module. `.ts` is loaded via jiti; `.mjs`/`.js` via
+ * native dynamic import (file:// URL). Returns the full module namespace.
+ * @param {string} file absolute path
+ * @returns {Promise<Record<string, unknown>>}
+ */
+export async function importUserModule(file) {
+ if (file.endsWith('.ts')) {
+ return await getJiti().import(file);
+ }
+ return await import(pathToFileURL(file).href);
+}
+
+/**
+ * Return the conventional files (by basename, in the given precedence order)
+ * that exist directly in `dir`, as absolute paths. Never throws.
+ * @param {string} dir
+ * @param {string[]} basenames precedence-ordered
+ * @returns {string[]} absolute paths of present files, in basenames order
+ */
+export function findPresentFiles(dir, basenames) {
+ return basenames
+ .filter(name => fs.existsSync(path.join(dir, name)))
+ .map(name => path.join(dir, name));
+}
+
+/**
+ * Import a user-authored module, take its default export, and validate it
+ * against a zod schema. This is the single load/validation boundary for all
+ * user-authored modules (config, integration, codemod, template): execute the
+ * module, take the default export, validate it against the expected schema.
+ * Throws a clear, readable error if the default export is missing or fails
+ * validation.
+ *
+ * @template {import('zod').ZodType} S
+ * @param {string} file absolute path
+ * @param {S} schema
+ * @param {{label?: string}} [opts] label used in error messages
+ * @returns {Promise<import('zod').infer<S>>} parsed + typed value
+ */
+export async function loadModuleWithSchema(file, schema, {label} = {}) {
+ const mod = await importUserModule(file);
+ const exported = mod?.default;
+ const result = schema.safeParse(exported);
+ if (!result.success) {
+ throw new Error(formatZodError(label ?? file, result.error));
+ }
+ return result.data;
+}
diff --git a/packages/cli/src/lib/module-loader.test.mjs b/packages/cli/src/lib/module-loader.test.mjs
new file mode 100644
index 0000000000..0c73007f5a
--- /dev/null
+++ b/packages/cli/src/lib/module-loader.test.mjs
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {z} from 'zod';
+import {
+ findPresentFiles,
+ importUserModule,
+ loadModuleWithSchema,
+} from './module-loader.mjs';
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-module-loader-test-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('findPresentFiles', () => {
+ const basenames = ['a.ts', 'b.mjs', 'c.js'];
+
+ it('returns [] when none of the basenames are present', () => {
+ expect(findPresentFiles(tmpDir, basenames)).toEqual([]);
+ });
+
+ it('returns only the present files, in basenames precedence order', () => {
+ // Create out of order to prove the result follows `basenames`, not disk order.
+ fs.writeFileSync(path.join(tmpDir, 'c.js'), '');
+ fs.writeFileSync(path.join(tmpDir, 'a.ts'), '');
+ const present = findPresentFiles(tmpDir, basenames);
+ expect(present.map(p => path.basename(p))).toEqual(['a.ts', 'c.js']);
+ });
+
+ it('returns absolute paths joined to the given directory', () => {
+ fs.writeFileSync(path.join(tmpDir, 'b.mjs'), '');
+ const present = findPresentFiles(tmpDir, basenames);
+ expect(present).toEqual([path.join(tmpDir, 'b.mjs')]);
+ expect(path.isAbsolute(present[0])).toBe(true);
+ });
+
+ it('does not match files in nested subdirectories', () => {
+ const nested = path.join(tmpDir, 'nested');
+ fs.mkdirSync(nested);
+ fs.writeFileSync(path.join(nested, 'a.ts'), '');
+ expect(findPresentFiles(tmpDir, basenames)).toEqual([]);
+ });
+});
+
+describe('importUserModule', () => {
+ it('imports a .mjs file and returns its module namespace', async () => {
+ const file = path.join(tmpDir, 'mod.mjs');
+ fs.writeFileSync(
+ file,
+ `export default {answer: 42};\nexport const named = 'hi';\n`,
+ );
+ const mod = await importUserModule(file);
+ expect(mod.default).toEqual({answer: 42});
+ expect(mod.named).toBe('hi');
+ });
+});
+
+describe('loadModuleWithSchema', () => {
+ // Temp module files live under a repo-local dir (not /tmp): Vite's dynamic
+ // import blocks /tmp, so we mirror the existing repo-local temp pattern.
+ const schema = z
+ .object({
+ name: z.string(),
+ count: z.number().optional(),
+ })
+ .strict();
+
+ it('returns the parsed default export when it satisfies the schema', async () => {
+ const file = path.join(tmpDir, 'valid.mjs');
+ fs.writeFileSync(file, `export default {name: 'ok', count: 3};\n`);
+ const value = await loadModuleWithSchema(file, schema, {label: 'thing'});
+ expect(value).toEqual({name: 'ok', count: 3});
+ });
+
+ it('throws a readable error when there is no default export', async () => {
+ const file = path.join(tmpDir, 'no-default.mjs');
+ fs.writeFileSync(file, `export const named = {name: 'x'};\n`);
+ await expect(
+ loadModuleWithSchema(file, schema, {label: 'thing'}),
+ ).rejects.toThrow(/thing is invalid/i);
+ });
+
+ it('throws a readable error when the default export fails the schema', async () => {
+ const file = path.join(tmpDir, 'invalid.mjs');
+ fs.writeFileSync(file, `export default {count: 'not-a-number'};\n`);
+ await expect(
+ loadModuleWithSchema(file, schema, {label: 'thing'}),
+ ).rejects.toThrow(/thing is invalid:.*name/i);
+ });
+
+ it('falls back to the file path in the message when no label is given', async () => {
+ const file = path.join(tmpDir, 'unlabeled.mjs');
+ fs.writeFileSync(file, `export default {bogus: true};\n`);
+ await expect(loadModuleWithSchema(file, schema)).rejects.toThrow(
+ new RegExp(`${path.basename(file)} is invalid`),
+ );
+ });
+});
diff --git a/packages/cli/src/lib/project.mjs b/packages/cli/src/lib/project.mjs
new file mode 100644
index 0000000000..6b7d2f0532
--- /dev/null
+++ b/packages/cli/src/lib/project.mjs
@@ -0,0 +1,502 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Project — the single API for reading resolved project configuration.
+ *
+ * `Project` is the one entry point a command uses to read everything it needs
+ * about a consumer's project: the validated config surface, the configured
+ * integrations, and the resolved discovery sets (components, templates,
+ * codemods) — plus issue routing (issuesUrl) and the accumulated integration
+ * issues. It replaces the old `loadConfig(cwd)` plain-object loader and the
+ * per-command fan-out into the various discovery helpers.
+ *
+ * Design:
+ * - `Project.load(cwd, {cache})` is the async factory (constructors can't be
+ * async). It does what loadConfig did — find the config sibling-of
+ * package.json, import + validate it, load the configured integrations —
+ * and nothing more. Discovery is LAZY.
+ * - Discovery methods (components/templates/codemods) are MEMOIZED per
+ * instance (via the pluggable cache) and orchestrate the EXISTING discovery
+ * functions — Project never reimplements discovery.
+ * - SKIP + WARN policy: as a discovery method runs, per-integration work is
+ * guarded so one broken integration never throws out of discovery. Any
+ * AstryxIntegrationIssue encountered is collected into a private set and
+ * that integration's contributions are skipped.
+ * - `issues()` returns the deduped accumulated set, and (when called
+ * directly) fills in validation for any configured integration not yet
+ * visited by a discovery call, so it is always complete on demand.
+ *
+ * @position lib — orchestration over config-schema / integrations /
+ * component-discovery / template / codemod discovery; commands consume it.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {findPresentFiles, loadModuleWithSchema} from './module-loader.mjs';
+import {AstryxConfigSchema} from './config-schema.mjs';
+import {loadIntegrations} from './integrations.mjs';
+import {
+ CORE_PACKAGE,
+ discoverOwnedComponents,
+ discoverIntegrationComponents,
+} from './component-discovery.mjs';
+import {findCoreDir} from '../utils/paths.mjs';
+import {
+ discoverTemplates,
+ discoverIntegrationTemplatesForOne,
+} from '../api/template.mjs';
+import {getTransformsBetween} from '../codemods/registry.mjs';
+import {
+ discoverIntegrationCodemods,
+ selectIntegrationCodemods,
+} from '../codemods/integration-discovery.mjs';
+import {validateLoadedIntegration} from '../api/validate-integration.mjs';
+import {
+ InMemoryConfigCache,
+ cacheKey,
+ configContentHash,
+} from './config-cache.mjs';
+
+/** Conventional config basenames, in load-precedence order. */
+export const CONFIG_BASENAMES = [
+ 'astryx.config.ts',
+ 'astryx.config.mjs',
+ 'astryx.config.js',
+];
+
+/** Default issue tracker used when neither config nor integration routes one. */
+export const DEFAULT_ISSUES_URL =
+ 'https://github.com/facebook/astryx/issues/new';
+
+/**
+ * Find the directory of the nearest package.json walking up from startDir.
+ * @param {string} startDir
+ * @returns {string|null}
+ */
+function findPackageRoot(startDir) {
+ let dir = startDir;
+ for (let i = 0; i < 50; i++) {
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return null;
+}
+
+/**
+ * Find astryx.config.{ts,mjs,js} as a sibling of the nearest package.json.
+ * Returns the absolute path, or null if none is present. Throws if multiple
+ * config files exist at that root.
+ * @param {string} [startDir]
+ * @returns {string|null}
+ */
+export function findConfigPath(startDir = process.cwd()) {
+ const root = findPackageRoot(startDir) ?? startDir;
+ const present = findPresentFiles(root, CONFIG_BASENAMES);
+ if (present.length > 1) {
+ throw new Error(
+ `Multiple Astryx config files found in ${root} (${present
+ .map(p => path.basename(p))
+ .join(', ')}). Keep exactly one.`,
+ );
+ }
+ return present.length === 1 ? present[0] : null;
+}
+
+/**
+ * The single API for reading resolved project configuration. Construct via the
+ * async {@link Project.load} factory.
+ */
+export class Project {
+ /** @type {string} */
+ #cwd;
+ /** @type {string|null} */
+ #configPath;
+ /** @type {import('../types/config').AstryxConfig} */
+ #config;
+ /** @type {string[]} */
+ #integrations;
+ /** @type {Array<object>} */
+ #loadedIntegrations;
+ /** @type {import('./config-cache.mjs').ConfigCache} */
+ #cache;
+ /** @type {string} */
+ #hash;
+ /** @type {import('../types/integration').AstryxIntegrationIssue[]} */
+ #issues = [];
+ /**
+ * Package names of integrations whose issues have already been collected
+ * (via a discovery method or a direct issues() validation), so issues() can
+ * fill in only the ones not yet visited and never double-collect.
+ * @type {Set<string>}
+ */
+ #visitedIssues = new Set();
+
+ /**
+ * @param {object} init
+ * @param {string} init.cwd
+ * @param {string|null} init.configPath
+ * @param {object} init.config validated AstryxConfig surface
+ * @param {string[]} init.integrations
+ * @param {Array<object>} init.loadedIntegrations
+ * @param {import('./config-cache.mjs').ConfigCache} init.cache
+ * @param {string} init.hash config content hash
+ */
+ constructor({
+ cwd,
+ configPath,
+ config,
+ integrations,
+ loadedIntegrations,
+ cache,
+ hash,
+ }) {
+ this.#cwd = cwd;
+ this.#configPath = configPath;
+ this.#config = config;
+ this.#integrations = integrations;
+ this.#loadedIntegrations = loadedIntegrations;
+ this.#cache = cache;
+ this.#hash = hash;
+ }
+
+ /**
+ * Async factory. Finds + validates the config (the same work loadConfig did)
+ * and loads the configured integrations. Discovery is NOT run here — it is
+ * lazy and memoized on the returned instance.
+ *
+ * @param {string} [cwd]
+ * @param {{cache?: import('./config-cache.mjs').ConfigCache}} [options]
+ * @returns {Promise<Project>}
+ */
+ static async load(cwd = process.cwd(), {cache} = {}) {
+ const resolvedCache = cache ?? new InMemoryConfigCache();
+ const configPath = findConfigPath(cwd);
+ const hash = configContentHash(configPath);
+
+ let config = {integrations: []};
+ let integrations = [];
+ let loadedIntegrations = [];
+
+ if (configPath) {
+ config = await loadModuleWithSchema(configPath, AstryxConfigSchema, {
+ label: 'astryx.config',
+ });
+ const configDir = path.dirname(configPath);
+ integrations = config.integrations ?? [];
+ loadedIntegrations = await loadIntegrations(integrations, {
+ cwd: configDir,
+ });
+ }
+
+ return new Project({
+ cwd,
+ configPath,
+ config,
+ integrations,
+ loadedIntegrations,
+ cache: resolvedCache,
+ hash,
+ });
+ }
+
+ /**
+ * The validated config surface (same data loadConfig returned, minus the
+ * resolved `loadedIntegrations` which is exposed separately).
+ * @returns {{integrations?: string[], issuesUrl?: string, hooks?: object, experimental?: object}}
+ */
+ get config() {
+ return this.#config;
+ }
+
+ /** Configured integration package names. @returns {string[]} */
+ get integrations() {
+ return this.#integrations;
+ }
+
+ /** Resolved loaded integrations (lib/integrations.mjs shape). @returns {Array<object>} */
+ get loadedIntegrations() {
+ return this.#loadedIntegrations;
+ }
+
+ /** @returns {string} */
+ get cwd() {
+ return this.#cwd;
+ }
+
+ /**
+ * Absolute path to the resolved config file, or null when the project has
+ * no config (defaults-only).
+ * @returns {string|null}
+ */
+ get configPath() {
+ return this.#configPath;
+ }
+
+ /**
+ * Memoize an async producer behind the pluggable cache, keyed by the config
+ * content hash + cwd + discovery kind. A sentinel wrapper distinguishes a
+ * cached `undefined`/falsy value from a cache miss.
+ * @template T
+ * @param {string} kind
+ * @param {() => Promise<T>} produce
+ * @returns {Promise<T>}
+ */
+ async #memo(kind, produce) {
+ const key = cacheKey(this.#hash, this.#cwd, kind);
+ const hit = this.#cache.get(key);
+ if (hit !== undefined) return hit.value;
+ const value = await produce();
+ this.#cache.set(key, {value});
+ return value;
+ }
+
+ /**
+ * Record a single integration issue, deduped by (package, code, message).
+ * @param {string} pkg
+ * @param {import('../types/integration').AstryxIntegrationIssue} issue
+ */
+ #pushIssue(pkg, issue) {
+ const code = issue?.code ?? 'unknown';
+ const message = issue?.message ?? '';
+ const exists = this.#issues.some(
+ e => e.package === pkg && e.code === code && e.message === message,
+ );
+ if (exists) return;
+ this.#issues.push({
+ package: pkg,
+ code,
+ severity: issue?.severity ?? 'error',
+ message,
+ });
+ }
+
+ /** Package label for a loaded integration. */
+ #pkgLabel(integration) {
+ return integration?.name ?? integration?.__spec ?? '(integration)';
+ }
+
+ /**
+ * Validate one loaded integration and collect any issues. Marks the
+ * integration visited so issues() won't redo the work. Best-effort: a
+ * validator throwing is itself recorded as an issue, never propagated.
+ * @param {object} integration
+ */
+ async #collectIssues(integration) {
+ const pkg = this.#pkgLabel(integration);
+ if (this.#visitedIssues.has(pkg)) return;
+ this.#visitedIssues.add(pkg);
+ try {
+ const found = await validateLoadedIntegration(integration);
+ for (const issue of found ?? []) this.#pushIssue(pkg, issue);
+ } catch (err) {
+ this.#pushIssue(pkg, {
+ code: 'integration_error',
+ severity: 'error',
+ message: err?.message ?? String(err),
+ });
+ }
+ }
+
+ /**
+ * Core + integration component ownership records. Wraps
+ * discoverOwnedComponents for core and discoverIntegrationComponents (via
+ * discoverOwnedComponents) for integrations, but applies the skip+warn
+ * policy per integration: a broken integration's components are skipped and
+ * its issues collected, never thrown. Memoized per instance.
+ *
+ * @returns {Promise<Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>>}
+ */
+ async components() {
+ return this.#memo('components', async () => {
+ const coreDir = findCoreDir(this.#cwd);
+ /** @type {Array<object>} */
+ const records = [];
+
+ // Core records (no integrations) — never integration-broken.
+ if (coreDir) {
+ try {
+ records.push(...discoverOwnedComponents(coreDir, []));
+ } catch {
+ // Core discovery failure is not an integration issue; surface
+ // nothing here (core problems show up via doctor/other paths).
+ }
+ }
+
+ // Each integration in isolation so one broken integration is skipped.
+ for (const integration of this.#loadedIntegrations) {
+ await this.#collectIssues(integration);
+ const pkg = this.#pkgLabel(integration);
+ const hadError = this.#issues.some(
+ i => i.package === pkg && i.severity === 'error',
+ );
+ if (hadError) continue;
+ try {
+ // discoverOwnedComponents owns the core+integration record shape;
+ // here we add only this integration's records (core is handled
+ // above) so a single broken integration can be skipped in isolation.
+ for (const rec of discoverIntegrationComponents(integration)) {
+ records.push(rec);
+ }
+ } catch (err) {
+ this.#pushIssue(pkg, {
+ code: 'invalid_component',
+ severity: 'error',
+ message: err?.message ?? String(err),
+ });
+ }
+ }
+
+ return records;
+ });
+ }
+
+ /**
+ * Core + integration templates, type-tagged. Wraps discoverTemplates (core +
+ * external blocks) and discoverIntegrationTemplatesForOne per integration so
+ * a broken integration's templates are skipped and its issues collected.
+ * Memoized per instance.
+ *
+ * @returns {Promise<Array<object>>}
+ */
+ async templates() {
+ return this.#memo('templates', async () => {
+ /** @type {Array<object>} */
+ const templates = [];
+
+ // Core + external-package templates (discoverTemplates internally also
+ // loads integration templates via loadConfig today; we intentionally
+ // re-collect integration templates below through the per-integration
+ // path so the skip+warn policy and issue collection apply, then dedupe).
+ try {
+ const core = await discoverTemplates(this.#cwd);
+ for (const t of core) {
+ // Skip integration-owned templates here; they are re-added (and
+ // issue-collected) per integration below to honor skip+warn.
+ if (t.package && t.package !== CORE_PACKAGE) continue;
+ templates.push(t);
+ }
+ } catch {
+ // Core/template discovery failure contributes no templates.
+ }
+
+ for (const integration of this.#loadedIntegrations) {
+ await this.#collectIssues(integration);
+ const pkg = this.#pkgLabel(integration);
+ const hadError = this.#issues.some(
+ i => i.package === pkg && i.severity === 'error',
+ );
+ if (hadError) continue;
+ try {
+ const {templates: ts, errors} =
+ await discoverIntegrationTemplatesForOne(integration);
+ for (const e of errors) {
+ this.#pushIssue(pkg, {
+ code: 'invalid_template',
+ severity: 'error',
+ message: e.message,
+ });
+ }
+ // Only contribute templates when the integration had no per-template
+ // errors (skip the whole integration's templates on any error).
+ if (errors.length === 0) templates.push(...ts);
+ } catch (err) {
+ this.#pushIssue(pkg, {
+ code: 'invalid_template',
+ severity: 'error',
+ message: err?.message ?? String(err),
+ });
+ }
+ }
+
+ return templates.sort((a, b) => a.name.localeCompare(b.name));
+ });
+ }
+
+ /**
+ * Core registry transforms + integration codemods for an upgrade range.
+ * Wraps getTransformsBetween (core) and discoverIntegrationCodemods /
+ * selectIntegrationCodemods (integrations). A broken integration's codemods
+ * are skipped (issue collected) rather than failing the whole resolution.
+ * Memoized per (from, to) key.
+ *
+ * @param {string} fromVersion exclusive lower bound
+ * @param {string} toVersion inclusive upper bound
+ * @returns {Promise<{core: Array<{version: string, transforms: Array<object>}>, integration: Array<{version: string, codemods: Array<object>}>}>}
+ */
+ async codemods(fromVersion, toVersion) {
+ return this.#memo(`codemods:${fromVersion}..${toVersion}`, async () => {
+ const core = await getTransformsBetween(fromVersion, toVersion);
+
+ // Discover integration codemods per integration so a single broken
+ // integration is skipped (issue collected) without losing the others.
+ const good = [];
+ for (const integration of this.#loadedIntegrations) {
+ await this.#collectIssues(integration);
+ const pkg = this.#pkgLabel(integration);
+ const hadError = this.#issues.some(
+ i => i.package === pkg && i.severity === 'error',
+ );
+ if (hadError) continue;
+ if (!integration?.codemods) continue;
+ try {
+ // Validate this integration's codemods discover cleanly in
+ // isolation; if so it is safe to include.
+ await discoverIntegrationCodemods([integration]);
+ good.push(integration);
+ } catch (err) {
+ this.#pushIssue(pkg, {
+ code: 'invalid_codemod',
+ severity: 'error',
+ message: err?.message ?? String(err),
+ });
+ }
+ }
+
+ const byVersion = await discoverIntegrationCodemods(good);
+ const integration = selectIntegrationCodemods(
+ byVersion,
+ fromVersion,
+ toVersion,
+ );
+
+ return {core, integration};
+ });
+ }
+
+ /**
+ * Route an issues URL for a component/source reference.
+ *
+ * - `package === CORE_PACKAGE` or omitted => this.config.issuesUrl or the
+ * default core issues URL.
+ * - an integration package => that loaded integration's manifest issuesUrl
+ * (which may be undefined when the integration ships none).
+ *
+ * @param {{package?: string}} [ref]
+ * @returns {string|undefined}
+ */
+ issuesUrl(ref = {}) {
+ const pkg = ref?.package;
+ if (!pkg || pkg === CORE_PACKAGE) {
+ return this.#config.issuesUrl ?? DEFAULT_ISSUES_URL;
+ }
+ const integration = this.#loadedIntegrations.find(i => i.name === pkg);
+ return integration?.issuesUrl;
+ }
+
+ /**
+ * The accumulated integration issues (deduped by package, code, message).
+ * When called directly, also validates any configured integration not yet
+ * visited by a discovery call, so the returned set is complete on demand.
+ *
+ * @returns {Promise<import('../types/integration').AstryxIntegrationIssue[]>}
+ */
+ async issues() {
+ for (const integration of this.#loadedIntegrations) {
+ await this.#collectIssues(integration);
+ }
+ // Return a stable copy so callers can't mutate internal state.
+ return this.#issues.map(i => ({...i}));
+ }
+}
diff --git a/packages/cli/src/lib/project.test.mjs b/packages/cli/src/lib/project.test.mjs
new file mode 100644
index 0000000000..7a103ef327
--- /dev/null
+++ b/packages/cli/src/lib/project.test.mjs
@@ -0,0 +1,308 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {Project, DEFAULT_ISSUES_URL, findConfigPath} from './project.mjs';
+import {InMemoryConfigCache} from './config-cache.mjs';
+import * as componentDiscovery from './component-discovery.mjs';
+
+let tmpDir;
+let originalCwd;
+
+const codemodModulePath = path.resolve(
+ process.cwd(),
+ 'packages/cli/src/codemod.mjs',
+);
+const codemodModuleUrl = pathToFileURL(codemodModulePath).href;
+
+/**
+ * Scaffold a consumer project (package.json + astryx.config.mjs) under a
+ * repo-local temp dir, plus an installed integration package under
+ * node_modules. The repo-local location is required so Vite permits dynamic
+ * import of the config/integration modules (it blocks /tmp).
+ */
+function scaffold({
+ integrations = ['@acme/widgets'],
+ issuesUrl,
+ withComponents = true,
+ withTemplates = true,
+ withCodemods = true,
+ brokenComponent = false,
+ brokenCodemod = false,
+ integrationIssuesUrl = 'https://example.com/widgets/issues',
+} = {}) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ const config = {integrations};
+ if (issuesUrl) config.issuesUrl = issuesUrl;
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default ${JSON.stringify(config)};\n`,
+ );
+
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+
+ const manifest = {};
+ if (withComponents) manifest.components = './components';
+ if (withTemplates) manifest.templates = './templates';
+ if (withCodemods) manifest.codemods = './codemods';
+ if (integrationIssuesUrl) manifest.issuesUrl = integrationIssuesUrl;
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default ${JSON.stringify(manifest)};\n`,
+ );
+
+ if (withComponents) {
+ const compDir = path.join(pkgDir, 'components');
+ fs.mkdirSync(compDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(compDir, 'Widget.doc.mjs'),
+ `export const docs = { name: 'Widget', usage: {description: 'A widget'} };\n`,
+ );
+ if (!brokenComponent) {
+ fs.writeFileSync(
+ path.join(compDir, 'Widget.tsx'),
+ `export function Widget() { return null; }\n`,
+ );
+ }
+ // brokenComponent => doc with no sibling .tsx (invalid_component issue).
+ }
+
+ if (withTemplates) {
+ const tDir = path.join(pkgDir, 'templates');
+ fs.mkdirSync(tDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(tDir, 'hero.doc.mjs'),
+ `export default { type: 'block', name: 'Hero', description: 'A hero' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(tDir, 'hero.tsx'),
+ `export default function Hero() { return null; }\n`,
+ );
+ }
+
+ if (withCodemods) {
+ const cmDir = path.join(pkgDir, 'codemods', '0.2.0');
+ fs.mkdirSync(cmDir, {recursive: true});
+ if (brokenCodemod) {
+ fs.writeFileSync(
+ path.join(cmDir, 'bad.mjs'),
+ `export default { not: 'a codemod' };\n`,
+ );
+ } else {
+ fs.writeFileSync(
+ path.join(cmDir, 'drop-foo.mjs'),
+ `import {createCodemod} from ${JSON.stringify(codemodModuleUrl)};\n` +
+ `export default createCodemod({ title: 'Drop foo', transform: (file) => file.source });\n`,
+ );
+ }
+ }
+
+ return pkgDir;
+}
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-project-test-'));
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+});
+
+describe('Project.load', () => {
+ it('returns an empty config + no integrations when no config file exists', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ const project = await Project.load(tmpDir);
+ expect(project.config).toEqual({integrations: []});
+ expect(project.integrations).toEqual([]);
+ expect(project.loadedIntegrations).toEqual([]);
+ expect(project.cwd).toBe(tmpDir);
+ });
+
+ it('exposes the validated config surface and loaded integrations', async () => {
+ scaffold({issuesUrl: 'https://example.com/issues'});
+ const project = await Project.load(tmpDir);
+ expect(project.config.issuesUrl).toBe('https://example.com/issues');
+ expect(project.integrations).toEqual(['@acme/widgets']);
+ expect(project.loadedIntegrations).toHaveLength(1);
+ expect(project.loadedIntegrations[0].name).toBe('@acme/widgets');
+ });
+
+ it('rejects an invalid config shape (strict validation)', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: [42] };\n`,
+ );
+ await expect(Project.load(tmpDir)).rejects.toThrow(/integrations/);
+ });
+});
+
+describe('findConfigPath', () => {
+ it('rejects multiple config files at the same root', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default {};\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.js'),
+ `module.exports = {};\n`,
+ );
+ expect(() => findConfigPath(tmpDir)).toThrow(/Multiple Astryx config files/);
+ });
+});
+
+describe('Project discovery', () => {
+ it('components() returns integration ownership records', async () => {
+ scaffold();
+ const project = await Project.load(tmpDir);
+ const comps = await project.components();
+ const widget = comps.find(
+ c => c.name === 'Widget' && c.package === '@acme/widgets',
+ );
+ expect(widget).toBeTruthy();
+ expect(widget.sourcePath).toMatch(/Widget\.tsx$/);
+ });
+
+ it('templates() returns integration templates type-tagged', async () => {
+ scaffold();
+ const project = await Project.load(tmpDir);
+ const templates = await project.templates();
+ const hero = templates.find(t => t.package === '@acme/widgets');
+ expect(hero).toBeTruthy();
+ expect(hero.type).toBe('block');
+ });
+
+ it('codemods() returns core registry groups + integration groups', async () => {
+ scaffold();
+ const project = await Project.load(tmpDir);
+ const {core, integration} = await project.codemods('0.1.0', '0.2.0');
+ expect(Array.isArray(core)).toBe(true);
+ expect(integration).toHaveLength(1);
+ expect(integration[0].version).toBe('0.2.0');
+ expect(integration[0].codemods[0].id).toBe('drop-foo');
+ });
+
+ it('memoizes components() — the second call does not re-walk', async () => {
+ scaffold();
+ const project = await Project.load(tmpDir);
+ const spy = vi.spyOn(componentDiscovery, 'discoverIntegrationComponents');
+ const first = await project.components();
+ const callsAfterFirst = spy.mock.calls.length;
+ const second = await project.components();
+ // Same identity (cached value) and no additional discovery walk.
+ expect(second).toBe(first);
+ expect(spy.mock.calls.length).toBe(callsAfterFirst);
+ });
+});
+
+describe('Project issues (skip + warn)', () => {
+ it('collects issues for a broken integration and skips its contributions', async () => {
+ scaffold({brokenComponent: true});
+ const project = await Project.load(tmpDir);
+ const comps = await project.components();
+ // Widget is skipped because its source is missing.
+ expect(comps.find(c => c.package === '@acme/widgets')).toBeUndefined();
+ const issues = await project.issues();
+ expect(issues.length).toBeGreaterThan(0);
+ expect(issues.some(i => i.package === '@acme/widgets')).toBe(true);
+ });
+
+ it('does not throw when an integration codemod is broken', async () => {
+ scaffold({brokenCodemod: true});
+ const project = await Project.load(tmpDir);
+ const {integration} = await project.codemods('0.1.0', '0.2.0');
+ // Broken integration is skipped, not thrown.
+ expect(integration).toHaveLength(0);
+ const issues = await project.issues();
+ expect(issues.some(i => i.code === 'invalid_codemod')).toBe(true);
+ });
+
+ it('issues() dedupes and is complete on demand', async () => {
+ scaffold({brokenComponent: true});
+ const project = await Project.load(tmpDir);
+ // Call a discovery method first (collects some), then issues().
+ await project.components();
+ const a = await project.issues();
+ const b = await project.issues();
+ expect(a).toEqual(b);
+ // No duplicate (package, code, message) tuples.
+ const seen = new Set(a.map(i => `${i.package}\u0000${i.code}\u0000${i.message}`));
+ expect(seen.size).toBe(a.length);
+ });
+
+ it('issues() validates integrations not yet visited by a discovery call', async () => {
+ scaffold({brokenComponent: true});
+ const project = await Project.load(tmpDir);
+ // No discovery call at all — issues() must still surface the broken one.
+ const issues = await project.issues();
+ expect(issues.some(i => i.package === '@acme/widgets')).toBe(true);
+ });
+});
+
+describe('Project.issuesUrl routing', () => {
+ it('routes core to config.issuesUrl, falling back to the default', async () => {
+ scaffold({issuesUrl: 'https://example.com/core'});
+ const project = await Project.load(tmpDir);
+ expect(project.issuesUrl()).toBe('https://example.com/core');
+ expect(project.issuesUrl({package: '@astryxdesign/core'})).toBe(
+ 'https://example.com/core',
+ );
+ });
+
+ it('falls back to the default core URL when config has none', async () => {
+ scaffold();
+ const project = await Project.load(tmpDir);
+ expect(project.issuesUrl()).toBe(DEFAULT_ISSUES_URL);
+ });
+
+ it('routes an integration package to its manifest issuesUrl', async () => {
+ scaffold({integrationIssuesUrl: 'https://example.com/widgets/issues'});
+ const project = await Project.load(tmpDir);
+ expect(project.issuesUrl({package: '@acme/widgets'})).toBe(
+ 'https://example.com/widgets/issues',
+ );
+ });
+
+ it('returns undefined for an integration that ships no issuesUrl', async () => {
+ scaffold({integrationIssuesUrl: null});
+ const project = await Project.load(tmpDir);
+ expect(project.issuesUrl({package: '@acme/widgets'})).toBeUndefined();
+ });
+});
+
+describe('Project caching', () => {
+ it('reuses a shared cache across instances for the same config bytes', async () => {
+ scaffold();
+ const cache = new InMemoryConfigCache();
+ const p1 = await Project.load(tmpDir, {cache});
+ const comps1 = await p1.components();
+ const p2 = await Project.load(tmpDir, {cache});
+ const comps2 = await p2.components();
+ // Same cached value across Project instances (same key path).
+ expect(comps2).toBe(comps1);
+ });
+});
diff --git a/packages/cli/src/template.mjs b/packages/cli/src/template.mjs
new file mode 100644
index 0000000000..f9d726369a
--- /dev/null
+++ b/packages/cli/src/template.mjs
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Static template authoring API.
+ *
+ * Helpers for authoring Astryx page/block template docs. Like
+ * `createConfig`/`createIntegration`, these are tiny runtime identity helpers
+ * whose real value is the exported TypeScript surface from
+ * `@astryxdesign/cli/template`. They inject the discriminant `type` so a
+ * discovered doc always knows whether it is a page or a block. They do NOT
+ * validate — validation happens at the load boundary, where integration
+ * template discovery runs the module's default export through
+ * {@link TemplateEnvelopeSchema} (see `loadModuleWithSchema`).
+ */
+
+import {z} from 'zod';
+
+const PreviewSchema = z
+ .object({
+ image: z.string().optional(),
+ aspectRatio: z.string().optional(),
+ })
+ .strict();
+
+/**
+ * Shared authored-template shape. `type` is injected by the create* helpers,
+ * so authors never write it. Inline source/sourceFile are intentionally NOT
+ * part of v1 — a template's source is the required same-stem sibling file.
+ * Exported so integration template discovery can validate the stamped result.
+ */
+export const BaseTemplateSchema = z
+ .object({
+ name: z.string().min(1, 'name is required'),
+ description: z.string().min(1, 'description is required'),
+ category: z.string().optional(),
+ componentsUsed: z.array(z.string()).optional(),
+ preview: PreviewSchema.optional(),
+ })
+ .strict();
+
+/**
+ * The metadata envelope integration template discovery validates: a stamped
+ * template doc. This is the LOAD-boundary contract — a hand-written plain
+ * object that matches this shape is accepted (discovery does not check "was it
+ * made by the factory", only the shape).
+ */
+export const TemplateEnvelopeSchema = BaseTemplateSchema.extend({
+ type: z.enum(['page', 'block']),
+});
+
+/**
+ * Author an Astryx page template doc. Stamp-only: returns the def with
+ * `type: 'page'` injected. Validation happens at the load boundary.
+ *
+ * @template {import('./types/template-api').AstryxPageTemplateInput} T
+ * @param {T} def
+ * @returns {T & {type: 'page'}}
+ */
+export function createPageTemplate(def) {
+ return /** @type {T & {type: 'page'}} */ ({...def, type: 'page'});
+}
+
+/**
+ * Author an Astryx block template doc. Stamp-only: returns the def with
+ * `type: 'block'` injected. Validation happens at the load boundary.
+ *
+ * @template {import('./types/template-api').AstryxBlockTemplateInput} T
+ * @param {T} def
+ * @returns {T & {type: 'block'}}
+ */
+export function createBlockTemplate(def) {
+ return /** @type {T & {type: 'block'}} */ ({...def, type: 'block'});
+}
diff --git a/packages/cli/src/template.test.mjs b/packages/cli/src/template.test.mjs
new file mode 100644
index 0000000000..4a46192b3c
--- /dev/null
+++ b/packages/cli/src/template.test.mjs
@@ -0,0 +1,127 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {
+ createPageTemplate,
+ createBlockTemplate,
+ TemplateEnvelopeSchema,
+} from './template.mjs';
+
+// createPageTemplate/createBlockTemplate are now stamp-only: they inject the
+// `type` discriminant and return the def otherwise unchanged, with NO runtime
+// validation. Validation happens at the LOAD boundary (integration template
+// discovery runs the default export through TemplateEnvelopeSchema), so the
+// rejection cases that used to assert factory throws now assert the envelope
+// schema rejects the same shapes.
+
+describe('createPageTemplate (stamp-only)', () => {
+ it('returns the def with type "page" injected', () => {
+ const t = createPageTemplate({
+ name: 'Landing',
+ description: 'A landing page.',
+ });
+ expect(t).toEqual({
+ name: 'Landing',
+ description: 'A landing page.',
+ type: 'page',
+ });
+ });
+
+ it('preserves optional fields', () => {
+ const t = createPageTemplate({
+ name: 'Landing',
+ description: 'A landing page.',
+ category: 'Marketing',
+ componentsUsed: ['Button', 'Card'],
+ preview: {image: './preview.png', aspectRatio: '16 / 9'},
+ });
+ expect(t.category).toBe('Marketing');
+ expect(t.componentsUsed).toEqual(['Button', 'Card']);
+ expect(t.preview).toEqual({image: './preview.png', aspectRatio: '16 / 9'});
+ expect(t.type).toBe('page');
+ });
+
+ it('does NOT validate — returns an invalid def stamped, unchanged', () => {
+ const t = createPageTemplate({description: 'x'});
+ expect(t.type).toBe('page');
+ expect(t.name).toBeUndefined();
+ });
+});
+
+describe('createBlockTemplate (stamp-only)', () => {
+ it('returns the def with type "block" injected', () => {
+ const t = createBlockTemplate({
+ name: 'Hero',
+ description: 'A hero block.',
+ });
+ expect(t.type).toBe('block');
+ expect(t.name).toBe('Hero');
+ });
+});
+
+describe('TemplateEnvelopeSchema (load-boundary validation)', () => {
+ it('accepts a stamped page template', () => {
+ const parsed = TemplateEnvelopeSchema.parse(
+ createPageTemplate({name: 'Landing', description: 'A landing page.'}),
+ );
+ expect(parsed.type).toBe('page');
+ });
+
+ it('accepts a PLAIN OBJECT envelope (no factory required)', () => {
+ const parsed = TemplateEnvelopeSchema.parse({
+ type: 'block',
+ name: 'Hero',
+ description: 'A hero block.',
+ });
+ expect(parsed.name).toBe('Hero');
+ });
+
+ it('rejects a missing name', () => {
+ expect(() =>
+ TemplateEnvelopeSchema.parse({type: 'page', description: 'x'}),
+ ).toThrow(/name/);
+ });
+
+ it('rejects a missing description', () => {
+ expect(() =>
+ TemplateEnvelopeSchema.parse({type: 'page', name: 'x'}),
+ ).toThrow(/description/);
+ });
+
+ it('rejects an empty-string name', () => {
+ expect(() =>
+ TemplateEnvelopeSchema.parse({type: 'page', name: '', description: 'x'}),
+ ).toThrow(/name/);
+ });
+
+ it('rejects a missing/invalid type', () => {
+ expect(() =>
+ TemplateEnvelopeSchema.parse({name: 'x', description: 'y'}),
+ ).toThrow();
+ expect(() =>
+ TemplateEnvelopeSchema.parse({type: 'bogus', name: 'x', description: 'y'}),
+ ).toThrow();
+ });
+
+ it('rejects unknown keys (strict)', () => {
+ expect(() =>
+ TemplateEnvelopeSchema.parse({
+ type: 'page',
+ name: 'x',
+ description: 'y',
+ source: './x.tsx',
+ }),
+ ).toThrow();
+ });
+
+ it('rejects inline sourceFile (not supported in v1)', () => {
+ expect(() =>
+ TemplateEnvelopeSchema.parse({
+ type: 'page',
+ name: 'x',
+ description: 'y',
+ sourceFile: './x.tsx',
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/cli/src/types/api.d.ts b/packages/cli/src/types/api.d.ts
index 488b926fb4..e4b04cfb26 100644
--- a/packages/cli/src/types/api.d.ts
+++ b/packages/cli/src/types/api.d.ts
@@ -33,7 +33,6 @@ import type {
TemplateShowResponse,
TemplateSkeletonResponse,
TemplateCopyResponse,
- TemplateGetResponse,
} from './template';
import type {
HookListResponse,
@@ -138,6 +137,8 @@ export interface TemplateOptions {
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;
}
@@ -153,11 +154,6 @@ export declare function template(
options?: TemplateOptions,
): Promise<TemplateResult>;
-export declare function getTemplateById(
- id: string,
- options?: {cwd?: string},
-): Promise<TemplateGetResponse>;
-
// ── Hook ─────────────────────────────────────────────────────────────
export interface HookOptions {
diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.ts
index 8e43918ffb..d48c3e912c 100644
--- a/packages/cli/src/types/base.d.ts
+++ b/packages/cli/src/types/base.d.ts
@@ -32,7 +32,6 @@ import type {
TemplateShowResponse,
TemplateSkeletonResponse,
TemplateCopyResponse,
- TemplateGetResponse,
} from './template';
import type {
HookListResponse,
@@ -44,14 +43,11 @@ import type {
import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';
import type {ThemeBuildResponse} from './theme';
import type {UpgradeListResponse, UpgradeRunResponse} from './upgrade';
-import type {
- GapReportCategoriesResponse,
- GapReportFileResponse,
-} from './gap-report';
import type {SearchResponse} from './search';
import type {ErrorCode} from './error-codes';
import type {ManifestResponse} from './manifest';
import type {DoctorResponse} from './doctor';
+import type {ValidateIntegrationResponse} from './validate-integration';
/**
* Structured error. Check `'error' in result` to discriminate.
@@ -93,7 +89,6 @@ export type CLIAnyResponse =
| TemplateShowResponse
| TemplateSkeletonResponse
| TemplateCopyResponse
- | TemplateGetResponse
| HookListResponse
| HookBriefResponse
| HookFullResponse
@@ -104,11 +99,10 @@ export type CLIAnyResponse =
| ThemeBuildResponse
| UpgradeListResponse
| UpgradeRunResponse
- | GapReportCategoriesResponse
- | GapReportFileResponse
| SearchResponse
| ManifestResponse
- | DoctorResponse;
+ | DoctorResponse
+ | ValidateIntegrationResponse;
/** Union of all type discriminator string literals. */
export type CLIResponseType = CLIAnyResponse['type'];
diff --git a/packages/cli/src/types/codemod.d.ts b/packages/cli/src/types/codemod.d.ts
new file mode 100644
index 0000000000..4a9e0ff6f8
--- /dev/null
+++ b/packages/cli/src/types/codemod.d.ts
@@ -0,0 +1,81 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Public type surface for the file-based codemod-authoring API exported from
+ * `@astryxdesign/cli/codemod`.
+ */
+
+/** A single source file presented to a codemod's transform. */
+export interface AstryxCodemodFile {
+ /** Absolute path to the file being transformed. */
+ path: string;
+ /** The current source contents of the file. */
+ source: string;
+}
+
+/** Helpers and context passed to a codemod's transform as the second argument. */
+export interface AstryxCodemodApi {
+ /** A jscodeshift instance configured with a parser for the file. */
+ jscodeshift: unknown;
+ /** Report a statistic (no-op-friendly; provided for jscodeshift parity). */
+ stats: (...args: unknown[]) => void;
+ /** Report progress (no-op-friendly; provided for jscodeshift parity). */
+ report: (...args: unknown[]) => void;
+}
+
+/**
+ * A codemod's transform. Return the new source to rewrite the file, or
+ * `null`/`undefined` to leave the file unchanged.
+ */
+export type AstryxCodemodTransform = (
+ file: AstryxCodemodFile,
+ api: AstryxCodemodApi,
+) => string | null | undefined;
+
+/** Definition accepted by {@link createCodemod}. */
+export interface AstryxCodemodDef {
+ /** Short, human-readable title shown in upgrade output. */
+ title: string;
+ /** Optional longer description. */
+ description?: string;
+ /** When true, the codemod runs only when explicitly requested. */
+ isOptional?: boolean;
+ /** File extensions this codemod applies to (e.g. ['.tsx', '.ts']). */
+ fileExtensions?: string[];
+ /** The transform function. */
+ transform: AstryxCodemodTransform;
+}
+
+/** Result of {@link createCodemod}. */
+export interface AstryxCodemod extends AstryxCodemodDef {
+ isOptional: boolean;
+ type: 'code';
+}
+
+/** Definition accepted by {@link createConfigCodemod}. */
+export interface AstryxConfigCodemodDef {
+ /** Short, human-readable title shown in upgrade output. */
+ title: string;
+ /** Optional longer description. */
+ description?: string;
+ /** When true, the codemod runs only when explicitly requested. */
+ isOptional?: boolean;
+ /** The transform function applied to the astryx.config.* file. */
+ transform: AstryxCodemodTransform;
+}
+
+/** Result of {@link createConfigCodemod}. */
+export interface AstryxConfigCodemod extends AstryxConfigCodemodDef {
+ isOptional: boolean;
+ type: 'config';
+}
+
+/** Define a file-transforming codemod. */
+export declare function createCodemod<T extends AstryxCodemodDef>(
+ def: T,
+): AstryxCodemod;
+
+/** Define a codemod that targets the consumer's astryx.config.* file. */
+export declare function createConfigCodemod<T extends AstryxConfigCodemodDef>(
+ def: T,
+): AstryxConfigCodemod;
diff --git a/packages/cli/src/types/component.d.ts b/packages/cli/src/types/component.d.ts
index 722d47ae57..b91a23281f 100644
--- a/packages/cli/src/types/component.d.ts
+++ b/packages/cli/src/types/component.d.ts
@@ -28,7 +28,18 @@ import type {ComponentDoc, PropDoc} from '../../../core/src/docs-types';
/** xds --json component [--list] [--category X] [--detail brief] */
export interface ComponentListResponse {
type: 'component.list';
- data: Record<string, string[]>;
+ data: Record<string, ComponentListEntry[]>;
+}
+
+/**
+ * A single entry in a `component.list` group. 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;
}
/** xds --json component --list --detail compact */
@@ -52,7 +63,21 @@ export interface ComponentFullResponse {
/** xds --json component <name> */
export interface ComponentDetailResponse {
type: 'component.detail';
- data: ComponentDoc;
+ 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 */
diff --git a/packages/cli/src/types/config.d.ts b/packages/cli/src/types/config.d.ts
index 175f7fb732..9618248582 100644
--- a/packages/cli/src/types/config.d.ts
+++ b/packages/cli/src/types/config.d.ts
@@ -1,99 +1,70 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-/** User config exported from astryx.config.mjs. */
-export interface AstryxConfig {
- /** External package directories to scan for package.json astryx.docs metadata. */
- packages?: string | string[];
- /** Integration package names or manifest paths. */
- integrations?: string | string[];
- /** Gap report delivery override. Omit for default GitHub issue filing. */
- gapReport?: false | {command: string};
- /** Template hooks. */
- template?: {
- get?: (id: string) => string | Promise<string>;
+/**
+ * A command to run as part of a post-codemod hook. Returned by a hook's
+ * `buildCommand` and executed via `execFile` after codemods write files.
+ */
+export interface PostCodemodCommand {
+ command: string;
+ args?: string[];
+ options?: {
+ cwd?: string;
+ env?: NodeJS.ProcessEnv;
+ timeout?: number;
};
- [key: string]: unknown;
-}
-
-export interface AstryxIntegrationCodemod {
- name: string;
- from?: string;
- to?: string;
- title?: string;
- description?: string;
- pr?: string;
- optional?: boolean;
- fileExtensions?: string[];
- transform:
- | string
- | ((file: unknown, api: unknown) => string | undefined | null);
-}
-
-export interface AstryxPostCodemodContext {
- packageDir: string;
- codemodDir: string;
- changedFiles: string[];
- absoluteChangedFiles: string[];
- packageChangedFiles: string[];
- apply: boolean;
- run: (
- command: string,
- args?: string[],
- options?: {
- cwd?: string;
- timeoutMs?: number;
- env?: Record<string, string>;
- },
- ) => Promise<void>;
}
-export interface AstryxPostCodemodHook {
+/**
+ * A post-codemod hook. `buildCommand` receives the package directory and the
+ * list of files changed by codemods, and returns the command to run (or a
+ * nullish value to skip).
+ */
+export type PostCodemodHook = {
name?: string;
- run?: (context: AstryxPostCodemodContext) => void | Promise<void>;
- command?: (context: AstryxPostCodemodContext) =>
- | {
- command: string;
- args?: string[];
- cwd?: string;
- timeoutMs?: number;
- env?: Record<string, string>;
- }
+ buildCommand: (ctx: {
+ packageDir: string;
+ files: string[];
+ }) =>
+ | PostCodemodCommand
| null
| undefined
- | Promise<
- | {
- command: string;
- args?: string[];
- cwd?: string;
- timeoutMs?: number;
- env?: Record<string, string>;
- }
- | null
- | undefined
- >;
-}
+ | Promise<PostCodemodCommand | null | undefined>;
+};
-/** Integration manifest exported from an astryx.integration.mjs file. */
-export interface AstryxIntegration {
- name: string;
- version?: string;
- displayName?: string;
+/** A component XLE layout expressions can reference by name via `{hint}`. */
+export interface XleComponent {
+ /** Import specifier the component is imported from, e.g. '@/components/KpiCard'. */
+ from: string;
+ /** Optional human description shown in tooling. */
description?: string;
- /** Relative docs root containing *.doc.mjs files. */
- docs?: string;
- category?: string;
- /** Relative block-template root. */
- blocks?: string;
- gapReport?: false | {command: string};
- template?: {
- get?: string | ((id: string) => string | Promise<string>);
+ /** Import as the module's default export instead of a named export. Defaults to false. */
+ default?: boolean;
+}
+
+/** User config exported from astryx.config.{ts,mjs,js}. */
+export interface AstryxConfig {
+ /** Integration package names to load. */
+ integrations?: string[];
+ /** Where to file issues/feedback for this project. */
+ issuesUrl?: string;
+ /** Lifecycle hooks. */
+ hooks?: {
+ postCodemod?: PostCodemodHook[];
+ };
+ /**
+ * EXPERIMENTAL — shape may change and is not part of the stable config
+ * contract. Provisional home for features still being proven out.
+ */
+ experimental?: {
+ /** Experimental XLE (layout expression) configuration. */
+ xle?: {
+ /**
+ * Register app-local components so XLE layout expressions can
+ * reference them by name via {hint}. Keyed by component name.
+ */
+ components?: Record<string, XleComponent>;
+ };
};
- codemods?: AstryxIntegrationCodemod[];
- postCodemod?: AstryxPostCodemodHook[];
- [key: string]: unknown;
}
export declare function createConfig<T extends AstryxConfig>(config: T): T;
-export declare function createIntegration<T extends AstryxIntegration>(
- integration: T,
-): T;
diff --git a/packages/cli/src/types/error-codes.d.ts b/packages/cli/src/types/error-codes.d.ts
index e2ea48b50b..f2aec8735e 100644
--- a/packages/cli/src/types/error-codes.d.ts
+++ b/packages/cli/src/types/error-codes.d.ts
@@ -25,6 +25,9 @@ export type ErrorCode =
| 'ERR_UNKNOWN_SECTION'
| 'ERR_UNKNOWN_CATEGORY'
| 'ERR_UNKNOWN_TEMPLATE'
+ | 'ERR_AMBIGUOUS_TEMPLATE'
+ | 'ERR_AMBIGUOUS_COMPONENT'
+ | 'ERR_UNKNOWN_THEME'
| 'ERR_UNKNOWN_PACKAGE'
| 'ERR_UNKNOWN_AGENT'
| 'ERR_UNKNOWN_FEATURE'
@@ -41,13 +44,12 @@ export type ErrorCode =
| 'ERR_WRITE_FAILED'
| 'ERR_THEME_INVALID'
| 'ERR_THEME_LOAD'
- | 'ERR_TEMPLATE_CONFIG'
- | 'ERR_TEMPLATE_GET'
| 'ERR_VERSION_DETECT'
| 'ERR_INVALID_VERSION'
| 'ERR_DEP_MISSING'
| 'ERR_GH_CLI'
- | 'ERR_GAP_REPORT_FAILED';
+ | 'ERR_LAYOUT_PARSE'
+ | 'ERR_LAYOUT_INVALID';
/** The frozen runtime map of all error codes (keys === values). */
export declare const ERROR_CODES: Readonly<Record<ErrorCode, ErrorCode>>;
diff --git a/packages/cli/src/types/gap-report.d.ts b/packages/cli/src/types/gap-report.d.ts
deleted file mode 100644
index f9438ce4d6..0000000000
--- a/packages/cli/src/types/gap-report.d.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * Gap-report command JSON responses.
- *
- * Invocation -> type discriminator
- * ------------------------------------------------------------------
- * xds --json gap-report --list-categories -> gap-report.categories
- * xds --json gap-report --component X --category Y --reason Z -> gap-report.file
- * (invalid category) -> CLIError
- * (interactive mode) -> CLIUnsupportedError (fallback)
- */
-
-/** xds --json gap-report --list-categories */
-export interface GapReportCategoriesResponse {
- type: 'gap-report.categories';
- data: GapReportCategoryEntry[];
-}
-
-export interface GapReportCategoryEntry {
- value: string;
- label: string;
-}
-
-/** xds --json gap-report --component X --category Y --reason Z */
-export interface GapReportFileResponse {
- type: 'gap-report.file';
- data: {filed: boolean; url: string | null};
-}
diff --git a/packages/cli/src/types/index.d.ts b/packages/cli/src/types/index.d.ts
index c87a09dc33..ac1ae61472 100644
--- a/packages/cli/src/types/index.d.ts
+++ b/packages/cli/src/types/index.d.ts
@@ -8,7 +8,6 @@ export * from './template';
export * from './hook';
export * from './swizzle';
export * from './theme';
-export * from './gap-report';
export * from './upgrade';
export * from './search';
export * from './error-codes';
diff --git a/packages/cli/src/types/integration.d.ts b/packages/cli/src/types/integration.d.ts
new file mode 100644
index 0000000000..ec1d61b60c
--- /dev/null
+++ b/packages/cli/src/types/integration.d.ts
@@ -0,0 +1,29 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Integration manifest exported from a conventional root manifest file
+ * (astryx.integration.{ts,mjs,js}) sibling to the integration package's
+ * package.json. Identity (name/version) comes from the package's
+ * package.json, not from the manifest.
+ */
+export interface AstryxIntegration {
+ /** Relative path to the components/docs root (resolved to absolute). */
+ components?: string;
+ /** Relative path to the templates root (resolved to absolute). */
+ templates?: string;
+ /** Relative path to the codemods root (resolved to absolute). */
+ codemods?: string;
+ /** Where to file issues/feedback for this integration. */
+ issuesUrl?: string;
+}
+
+/** An issue surfaced by an integration. */
+export interface AstryxIntegrationIssue {
+ code: string;
+ severity: 'warning' | 'error';
+ message: string;
+}
+
+export declare function createIntegration<T extends AstryxIntegration>(
+ integration: T,
+): T;
diff --git a/packages/cli/src/types/swizzle.d.ts b/packages/cli/src/types/swizzle.d.ts
index abe701ddc7..172605ef8f 100644
--- a/packages/cli/src/types/swizzle.d.ts
+++ b/packages/cli/src/types/swizzle.d.ts
@@ -7,7 +7,6 @@
* ------------------------------------------------------------------
* xds --json swizzle [--list] -> swizzle.list
* xds --json swizzle <component> -> swizzle.copy
- * xds --json swizzle <component> --gap "x" -> swizzle.copy (with gapReport)
* (not found) -> CLIError
*/
@@ -17,6 +16,14 @@ export interface SwizzleListResponse {
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';
@@ -25,6 +32,6 @@ export interface SwizzleCopyResponse {
outputDir: string;
filesCopied: number;
files: string[];
- gapReport?: string | null;
+ feedback?: SwizzleFeedback;
};
}
diff --git a/packages/cli/src/types/template-api.d.ts b/packages/cli/src/types/template-api.d.ts
new file mode 100644
index 0000000000..0cb83d1a4d
--- /dev/null
+++ b/packages/cli/src/types/template-api.d.ts
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Authoring surface for Astryx static templates, exported from
+ * `@astryxdesign/cli/template`.
+ *
+ * A template doc lives in a `<id>.doc.{ts,mjs,js}` file with a required
+ * same-stem sibling source file (`<id>.tsx`). The doc's `type` (page or
+ * block) — injected by the create* helpers — decides how the template is
+ * scaffolded; there is no `/pages` vs `/blocks` directory requirement.
+ */
+
+/** Optional preview metadata for a template (used by docs surfaces). */
+export interface AstryxTemplatePreview {
+ /** Path or URL to a preview image. */
+ image?: string;
+ /** CSS aspect-ratio hint for the preview, e.g. "16 / 9". */
+ aspectRatio?: string;
+}
+
+/** Fields common to page and block template docs (without the `type` tag). */
+export interface AstryxTemplateInput {
+ /** Human-readable template name. Required. */
+ name: string;
+ /** One-line description of what the template provides. Required. */
+ description: string;
+ /** Optional grouping/category label. */
+ category?: string;
+ /** Component display names the template composes. */
+ componentsUsed?: string[];
+ /** Optional preview metadata. */
+ preview?: AstryxTemplatePreview;
+}
+
+/** Input accepted by {@link createPageTemplate} (no `type` field). */
+export type AstryxPageTemplateInput = AstryxTemplateInput;
+/** Input accepted by {@link createBlockTemplate} (no `type` field). */
+export type AstryxBlockTemplateInput = AstryxTemplateInput;
+
+/** A validated page template doc. */
+export type AstryxPageTemplate = AstryxTemplateInput & {type: 'page'};
+/** A validated block template doc. */
+export type AstryxBlockTemplate = AstryxTemplateInput & {type: 'block'};
+
+/** A validated template doc (page or block). */
+export type AstryxTemplate = AstryxPageTemplate | AstryxBlockTemplate;
+
+export declare function createPageTemplate<T extends AstryxPageTemplateInput>(
+ def: T,
+): T & {type: 'page'};
+
+export declare function createBlockTemplate<T extends AstryxBlockTemplateInput>(
+ def: T,
+): T & {type: 'block'};
diff --git a/packages/cli/src/types/template.d.ts b/packages/cli/src/types/template.d.ts
index a8bcfd3ae2..ac0e7206a7 100644
--- a/packages/cli/src/types/template.d.ts
+++ b/packages/cli/src/types/template.d.ts
@@ -21,12 +21,21 @@ export interface TemplateListResponse {
}
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;
- type: 'page' | 'block';
}
/** xds --json template <name> */
@@ -62,9 +71,3 @@ export interface TemplateCopyResponse {
filesCopied: number;
};
}
-
-/** xds --json template get --id <id> */
-export interface TemplateGetResponse {
- type: 'template.get';
- data: {id: string; source: string};
-}
diff --git a/packages/cli/src/types/upgrade.d.ts b/packages/cli/src/types/upgrade.d.ts
index 97e8ddd7db..1f910756c0 100644
--- a/packages/cli/src/types/upgrade.d.ts
+++ b/packages/cli/src/types/upgrade.d.ts
@@ -7,6 +7,7 @@
* ------------------------------------------------------------------
* xds --json upgrade --list -> upgrade.list
* xds --json upgrade [--apply] -> upgrade.run
+ * xds --json upgrade (status short-circuit) -> upgrade.status
* (version detection failure) -> CLIError
*/
@@ -33,3 +34,31 @@ export interface UpgradeRunResponse {
agentDocsRefreshed: boolean;
};
}
+
+/**
+ * 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}
+ | {status: 'no_codemods'; from: string; to: string}
+ | {
+ status: 'config_fixable';
+ from: string;
+ to: string;
+ configError: string;
+ configCodemods: string[];
+ suggestedCommand: string;
+ message: string;
+ note: string;
+ };
+}
diff --git a/packages/cli/src/types/validate-integration.d.ts b/packages/cli/src/types/validate-integration.d.ts
new file mode 100644
index 0000000000..664840317b
--- /dev/null
+++ b/packages/cli/src/types/validate-integration.d.ts
@@ -0,0 +1,24 @@
+// 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
+ */
+
+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[];
+ };
+}
diff --git a/packages/cli/src/utils/github.mjs b/packages/cli/src/utils/github.mjs
index f49965511a..f54a939e16 100644
--- a/packages/cli/src/utils/github.mjs
+++ b/packages/cli/src/utils/github.mjs
@@ -4,69 +4,9 @@
* @file GitHub utilities for Astryx CLI
*
* Shared helpers for interacting with the GitHub CLI (`gh`).
- * Used by gap-report and swizzle commands.
- *
- * Gap reporting can be configured via astryx.config.mjs:
- * gapReport: false — disable entirely
- * gapReport: { command: './scripts/report-gap.sh' } — run custom script (receives JSON on stdin)
- *
- * Or via environment variable:
- * ASTRYX_GAP_REPORT=off — disable entirely
- * ASTRYX_GAP_REPORT=./scripts/report-gap.sh — run custom script
*/
import {execFileSync} from 'node:child_process';
-import * as path from 'node:path';
-import {loadConfig} from '../lib/config.mjs';
-
-/** Default target repository for gap report issues. */
-const DEFAULT_REPO = 'facebookexperimental/xds';
-
-/** Gap report category options. */
-export const GAP_CATEGORIES = [
- {value: 'missing_component', label: 'Missing component'},
- {value: 'missing_variant', label: 'Missing variant or prop'},
- {value: 'layout_gap', label: 'Layout gap'},
- {value: 'styling_gap', label: 'Styling gap'},
- {value: 'a11y_gap', label: 'Accessibility gap'},
- {value: 'api_friction', label: 'API friction'},
- {value: 'docs_gap', label: 'Documentation gap'},
- {value: 'other', label: 'Other'},
-];
-
-/**
- * Load gap report configuration.
- *
- * Priority: env var > astryx.config.mjs > default (GitHub issue)
- *
- * Returns { enabled: boolean, command?: string }
- * - enabled: false → gap reporting disabled
- * - command: string → run this script instead of creating a GitHub issue
- * - neither → default behavior (GitHub issue to facebookexperimental/xds)
- */
-export async function loadGapReportConfig() {
- // 1. Check environment variable
- const envVar = process.env.ASTRYX_GAP_REPORT;
- if (envVar) {
- if (envVar === 'off' || envVar === 'false' || envVar === '0') {
- return {enabled: false};
- }
- // Treat as custom command
- return {enabled: true, command: envVar};
- }
-
- // 2. Check astryx.config.mjs + integration manifests
- const config = await loadConfig(process.cwd());
- if (config.gapReport !== undefined) {
- if (config.gapReport === false) return {enabled: false};
- if (config.gapReport?.command) {
- return {enabled: true, command: config.gapReport.command};
- }
- }
-
- // 3. Default
- return {enabled: true};
-}
/**
* Check if `gh` CLI is installed and authenticated.
@@ -80,180 +20,3 @@ export function checkGhCli() {
return false;
}
}
-
-/**
- * Idempotently create the `gap-report` and `gap-analysis` labels.
- * Uses `--force` to avoid errors if labels already exist.
- */
-function ensureGapReportLabel() {
- try {
- execFileSync(
- 'gh',
- [
- 'label',
- 'create',
- 'gap-report',
- '--repo',
- DEFAULT_REPO,
- '--color',
- 'D4C5F9',
- '--description',
- 'Auto-filed gap report from swizzle/gap-report CLI',
- '--force',
- ],
- {stdio: 'ignore'},
- );
- execFileSync(
- 'gh',
- [
- 'label',
- 'create',
- 'gap-analysis',
- '--repo',
- DEFAULT_REPO,
- '--color',
- '0E8A16',
- '--description',
- 'Curated gap analysis summary',
- '--force',
- ],
- {stdio: 'ignore'},
- );
- } catch {
- // Best-effort — labels may already exist or user may lack permissions
- }
-}
-
-/**
- * Run a custom gap report command, piping report data as JSON to stdin.
- *
- * @param {string} command Script path to execute
- * @param {object} report Report data (component, category, intention, detail, source)
- * @returns {string} stdout from the command
- */
-function runCustomCommand(command, report) {
- const resolved = path.resolve(process.cwd(), command);
- const json = JSON.stringify(report, null, 2);
-
- const result = execFileSync(resolved, [], {
- input: json,
- encoding: 'utf-8',
- });
-
- return result.trim();
-}
-
-/**
- * Build the report payload + rendered title/body for a gap report.
- * Pure function — no side effects, never calls `gh` or external scripts.
- *
- * @returns {{
- * enabled: boolean,
- * mode: 'disabled' | 'custom' | 'github',
- * command?: string,
- * report: object,
- * title: string,
- * body: string,
- * repo: string,
- * }}
- */
-export async function buildGapReportPreview({
- component,
- category,
- intention,
- detail,
- source = 'cli',
-}) {
- const config = await loadGapReportConfig();
- const categoryLabel =
- GAP_CATEGORIES.find(c => c.value === category)?.label ?? category;
-
- const report = {
- component,
- category,
- categoryLabel,
- intention,
- detail: detail || null,
- source,
- timestamp: new Date().toISOString(),
- };
-
- const title = `[gap] ${component}: ${intention.slice(0, 70)}`;
- const body = [
- '| Field | Value |',
- '|-------|-------|',
- `| **Component** | ${component} |`,
- `| **Category** | ${categoryLabel} |`,
- `| **Source** | ${source} |`,
- `| **Timestamp** | ${report.timestamp} |`,
- '',
- '## User Intention',
- '',
- intention,
- ...(detail ? ['', '## Additional Context', '', detail] : []),
- ].join('\n');
-
- let mode = 'github';
- if (!config.enabled) mode = 'disabled';
- else if (config.command) mode = 'custom';
-
- return {
- enabled: config.enabled,
- mode,
- command: config.command,
- report,
- title,
- body,
- repo: DEFAULT_REPO,
- };
-}
-
-/**
- * Create a gap report — either via GitHub issue or custom command.
- *
- * SAFETY: This actually invokes `gh issue create` (or runs the custom command).
- * Callers MUST gate this behind explicit user confirmation or a `--commit`-style
- * flag in non-interactive contexts. Use `buildGapReportPreview` for dry-run.
- *
- * @param {object} opts
- * @param {string} opts.component Component name (e.g. "Button")
- * @param {string} opts.category One of GAP_CATEGORIES values
- * @param {string} opts.intention What the user was trying to achieve
- * @param {string} [opts.detail] Additional context
- * @param {string} [opts.source] Who filed it: "interactive", "llm-auto", "cli"
- * @returns {string|null} URL of the created issue (or custom command output), null if disabled
- */
-export async function createGapReport(opts) {
- const preview = await buildGapReportPreview(opts);
-
- if (!preview.enabled) {
- return null;
- }
-
- // Custom command mode — pipe JSON to the script
- if (preview.mode === 'custom') {
- return runCustomCommand(preview.command, preview.report);
- }
-
- // Default mode — create GitHub issue
- ensureGapReportLabel();
-
- const result = execFileSync(
- 'gh',
- [
- 'issue',
- 'create',
- '--repo',
- preview.repo,
- '--title',
- preview.title,
- '--body',
- preview.body,
- '--label',
- 'gap-report',
- ],
- {encoding: 'utf-8'},
- );
-
- return result.trim();
-}
diff --git a/packages/cli/src/utils/interactive.mjs b/packages/cli/src/utils/interactive.mjs
index f970ff18f4..5a3eab74ae 100644
--- a/packages/cli/src/utils/interactive.mjs
+++ b/packages/cli/src/utils/interactive.mjs
@@ -18,8 +18,8 @@
* fail fast (exit 1) with actionable, non-interactive guidance.
*
* - `isInteractive()` — for commands with an OPTIONAL secondary prompt
- * (e.g. swizzle's post-copy "report a gap?"). The primary work already
- * succeeded; callers use this to skip the prompt gracefully.
+ * that runs after the primary work has already succeeded; callers use
+ * this to skip the prompt gracefully in non-interactive contexts.
*/
/**