An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): let integration components replace Core identities (#6266)
Joeybd969de04eb3
diff --git a/.changeset/integration-component-replacements.md b/.changeset/integration-component-replacements.mdnew file mode 100644index 0000000000..765d72381c--- /dev/null+++ b/.changeset/integration-component-replacements.md@@ -0,0 +1,10 @@+---+'@astryxdesign/cli': patch+---++[feat] An integration component can replace a Core component, once its package opts in++A component whose doc sets `replaces: 'SideNav'` takes over `SideNav` for unqualified component detail, batch selectors, every `component --list` detail level, `search`, `swizzle`, and gap-report routing, when its package declares `"@astryxdesign/cli": ">=0.6.7"` in `peerDependencies` (optional in `peerDependenciesMeta`). The replacement keeps answering to its own name, every result names its package, and `--package @astryxdesign/core` still selects the original Core component.++Any `@astryxdesign/cli` range that starts at 0.6.7 or later is the opt-in, including the `>=0.7.0` that `integration add doc --parent` wrote in 0.6.4 and 0.6.5, and `integration add theme` in 0.6.5. A package whose range admits an earlier CLI keeps its component under its own name and Core stays selected, and an app that loads it sees no new output; its author gets warnings naming the range to add, from `astryx doctor integration components` and `integration pack --check`. `component SideNav --package <that package>` also selects the replacement. For a package that declares the range, `astryx doctor integration components` reports a missing Core target, an invalid value, a component named after a different Core component, or two replacements for one target in the package as errors and exits 1. When several packages replace one target, an explicitly configured package beats an autolinked one, the later configured package wins, and Doctor warns.+@josephfarinadiff --git a/docs/specs/AST-035/spec.md b/docs/specs/AST-035/spec.mdindex 0273355aca..a1dc5331c6 100644--- a/docs/specs/AST-035/spec.md+++ b/docs/specs/AST-035/spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: josephfarina-approved_at: 2026-09-29+approved_at: 2026-10-07phase: acceptedowners: [josephfarina, cixzhang]affects_architecture: [architecture:cli-surface]@@ -16,20 +16,20 @@ affects_contributing: [contributing:templates, contributing:api-conventions]affects_consumer_docs: [cli/integrations]----# Integration template replacement system spec+# Integration template and component replacement system spec## IntentLet an installed integration provide the project-specific implementation of a Core-template without making the common lookup ambiguous or removing access to the Core-original.+template or a Core component without making the common lookup ambiguous or removing+access to the Core original.## Non-goals-- Replacing integration components or reference-doc topics. Those surfaces own their- own contracts.-- Rewriting template source that a consumer already copied into an app.-- Making an integration template available when its source or metadata is invalid.+- Replacing reference-doc topics. That surface owns its own contract.+- Rewriting template or component source that a consumer already copied into an app.+- Making an integration template or component available when its source or metadata+ is invalid.- Selecting an integration that the project neither configures nor autolinks.## Requirements@@ -87,6 +87,46 @@ original.MUST NOT remove valid siblings. Other kinds keep their existing per-kind atomicity. Amanifest load failure still withdraws the integration because no contribution rootsare trustworthy. This rule applies whether or not any template declares `replaces`.+- **FR10 — A component declares its own replacement, and the CLI floor turns it on.**+ An integration component MAY set `replaces` in its own ComponentDoc to the exact+ `name` of a component in the Core component catalog. The replacement applies only+ when the component's package declares a `@astryxdesign/cli` peer range whose lowest+ admitted version is at least the first stable CLI release that applies component+ replacement (`COMPONENT_REPLACES_CLI`). That range is the package's opt-in. Stable+ CLIs before that release accept the field and keep the component under its own name.+- **FR11 — An applied component replacement owns unqualified component lookup.** The+ replacing component answers to the Core component's name in component detail and+ batch selectors, takes the Core component's slot at every component-list detail+ level, is the component search result for that name, is the component an unqualified+ `swizzle <Name>` copies, and is where gap-report routing sends a report for that name. It+ remains addressable by its own name. Every one of those results names the replacing+ component's own package (`architecture:cli-surface` INV28).+- **FR12 — Explicit Core selection preserves the original component.** Selecting+ `@astryxdesign/core` in component detail, batch selectors, and swizzle MUST address+ the original Core component. `swizzle --list` lists Core's components, a replaced one+ included.+- **FR13 — Invalid component declarations fail closed for packages that opt in.** For a+ package with the FR10 range, a `replaces` that names no Core catalog component, a+ value that is not a non-empty string, a component whose own name is a different Core+ component, and more than one declaration for one target inside the package MUST each+ be an error in `astryx doctor integration components`, which then exits 1. An invalid+ set MUST NOT replace Core. Valid components remain available by their own names+ (FR9).+- **FR14 — Component precedence is deterministic.** When several packages with the+ FR10 range validly replace one Core component, the FR5 order decides the winner: an+ explicitly configured package wins over an autolinked one, the package configured+ later wins among configured packages, and the dependency listed later wins among+ autolinked packages. Doctor warns whenever more than one package contends. An invalid+ autolinked declaration MUST NOT disable a valid explicit replacement. An integration+ component from another package whose own name is the replaced Core name is shadowed+ for unqualified lookup, stays addressable through its package, and Doctor warns.+- **FR15 — A package without the floor keeps its released behavior.** Its component+ `replaces` declarations never apply, and an app that loads the package sees no new+ output from them. Every finding about them, including the one that names the FR10+ range, is a warning reported to the package's author by+ `astryx doctor integration components`, so no command's result or exit code changes+ because of them. `integration pack --check` warns, and never fails, when a component+ sets `replaces` and the package's range admits an earlier stable CLI.### Platform support@@ -99,15 +139,18 @@ original.field. Stable 0.6.x conflict responses retain their warning-only shape. Thereplacement-specific conflict schema becomes eligible for an explicit, completeprojection update at 0.7.0; version alone does not activate it.+- Component replacement: `@astryxdesign/cli >=0.6.7` is both the minimum supported CLI+ and the opt-in (FR10). Earlier stable CLIs accept a component's `replaces` and keep+ the component under its own name, with the Core component still selected.- Browser evidence: not applicable to catalog selection. A generated consumer appMUST still build or run when its selected template renders integration-ownednavigation.## Current-state impact-The template metadata type and parser gain one optional field, `replaces`. Shared template-resolution becomes the owner for replacement validation, precedence, aliases, and the-default discovery view. Template commands, search/build, Project, layout, Doctor,+The template metadata type and parser accept one optional field, `replaces`. Shared+template resolution owns replacement validation, precedence, aliases, and the default+discovery view. Template commands, search/build, Project, layout, Doctor,response documentation, and the integration-authoring guide project that result.Project reports invalid contributions while retaining other valid contribution kindsand valid template or component siblings.@@ -127,16 +170,33 @@ become supported. A package-version bump alone leaves the warning-only projectioplace. Under `spec:AST-017/FR1`, FR2, FR5, FR7, and FR9–FR13, this pre-publicationcapability plus the compatibility gate is a `[feat]` patch, not a breaking minor.+Component discovery reads `replaces` from each valid component doc, and one resolver+decides component replacement, precedence, and findings. Component detail, batch+selectors, every list detail level, search, swizzle copy, gap-report routing, Project+issues, and `astryx doctor integration components` read its result. Stable CLI+releases before `COMPONENT_REPLACES_CLI` accept a component `replaces` and ignore it. A+package whose range admits one of them keeps its components' names, the Core+components stay selected, an app that loads it sees no new output, and its author sees+warnings in the package checks. A package whose range already starts later, such as+the `>=0.7.0` that earlier `integration add theme` and `integration add doc --parent`+wrote, opts in unchanged; its range excludes every CLI that ignores the field, so no+supported combination changes. Under `spec:AST-017/FR1`, FR5, and FR12, component+replacement is a `[feat]` patch.+## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |-| FR1, FR6 | Template parser and discovery tests plus a released-CLI consumer run | field present, field absent, 0.6.3 CLI | a replacement is honored from anywhere but the template's own metadata |-| FR2, FR3 | Template API/CLI and real consumer-app tests | target id, own id, Core package, integration package | lookup becomes ambiguous or the Core original is unreachable |-| FR4, FR7 | Doctor and discovery tests plus a 0.6.x response-shape fixture | missing local/source, missing target, wrong kind, duplicate, same-id rejection, pre-publication replacement | invalid metadata activates a replacement, Doctor reports success, or a 0.6.x conflict gains staged fields |-| FR5 | Multi-integration and autolink tests | configured order, explicit versus autolinked, invalid loser | file/display order chooses the winner or invalid autolinking disables explicit intent |-| FR2, FR8 | List, search/build, Project, layout, response, and generated-doc checks | alias plus undeclared exact-id collision, page and block, explicit 0.7 schema projection | two projections disagree, a public field is undocumented, or version alone expands the conflict schema |-| FR9 | Project discovery and issue-order tests | invalid component/template siblings, valid contribution kinds and siblings | one bad contribution removes unrelated valid output |+| Contract | Verification | Representative states | Mutation or failure expectation |+| ---------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |+| FR1, FR6 | Template parser and discovery tests plus a released-CLI consumer run | field present, field absent, 0.6.3 CLI | a replacement is honored from anywhere but the template's own metadata |+| FR2, FR3 | Template API/CLI and real consumer-app tests | target id, own id, Core package, integration package | lookup becomes ambiguous or the Core original is unreachable |+| FR4, FR7 | Doctor and discovery tests plus a 0.6.x response-shape fixture | missing local/source, missing target, wrong kind, duplicate, same-id rejection, pre-publication replacement | invalid metadata activates a replacement, Doctor reports success, or a 0.6.x conflict gains staged fields |+| FR5 | Multi-integration and autolink tests | configured order, explicit versus autolinked, invalid loser | file/display order chooses the winner or invalid autolinking disables explicit intent |+| FR2, FR8 | List, search/build, Project, layout, response, and generated-doc checks | alias plus undeclared exact-id collision, page and block, explicit 0.7 schema projection | two projections disagree, a public field is undocumented, or version alone expands the conflict schema |+| FR9 | Project discovery and issue-order tests | invalid component/template siblings, valid contribution kinds and siblings | one bad contribution removes unrelated valid output |+| FR10, FR15 | Floor-table test, resolver tests, and a published-CLI consumer run | range at the floor, no range, lower range; latest stable CLI with the field | a package without the range gets a replacement, an error, or a changed exit code |+| FR11, FR12 | Component, batch, list, search, swizzle, and gap-report tests plus a packed consumer run | target name, own name, Core package selector, every list detail level | a surface selects a different owner than component detail, a result omits the owner package, or Core is unreachable |+| FR13 | Resolver and `doctor integration components` tests | missing target, invalid value, own name is another Core component, two declarations in one package | invalid metadata replaces Core, or Doctor exits 0 with an error finding |+| FR14 | Multi-integration resolver tests | configured order, explicit versus autolinked, autolinked only, invalid autolinked loser, shadowed same-name component | file or display order chooses the winner, or an invalid autolinked declaration disables explicit intent |## Decision log@@ -211,7 +271,36 @@ future schema differs; exposing the expanded conflict schema in 0.6.x; or gatingreplacement implementation when the supported package boundary and stable-schemaadapter already protect released consumers.+### DEC-5 — A component declares its own replacement, and the CLI floor is the opt-in++**Reference:** `spec:AST-035/DEC-5`+**Decider:** `josephfarina`, `2026-10-07`++A component's `replaces` lives in its own ComponentDoc, as a template's does (DEC-3).+Stable releases before the floor accept the field and document replacement without+applying it, so applying every declaration at once would change selection for packages+whose range admits those releases. The CLI applies a package's component replacements+only when its `@astryxdesign/cli` peer range starts at the first release that applies+them. A package whose range admits an earlier CLI keeps its behavior; a range that+already starts later, such as `>=0.7.0`, excludes every CLI that ignores the field, so+no supported combination changes. New packages get one documented switch they already+manage for other features.++Rejected: applying every declared `replaces` immediately — it changes released selection without the package asking.+Rejected: an app configuration key — the package already states its intent, and `spec:AST-017/FR19` admits configuration only on evidence.++### DEC-6 — Component replacement uses template replacement's precedence and failure rules++**Reference:** `spec:AST-035/DEC-6`+**Decider:** `josephfarina`, `2026-10-07`++One resolver applies FR4, FR5, and FR9 to components with the component-specific+checks of FR13, and every component surface reads its result. An integration author+learns one set of rules for both kinds, and no two component surfaces can disagree+about the winner.++Rejected: per-surface resolution — component, search, and swizzle would drift apart.+## Open questions-None. The CLI owner accepted the contract on 2026-09-23 and moved FR1 to-per-template `replaces` on 2026-09-24 (DEC-3).+None.diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjsindex 09d6ff119f..075435b935 100644--- a/packages/cli/api/component/_adapter.mjs+++ b/packages/cli/api/component/_adapter.mjs@@ -38,6 +38,7 @@ import {} from '../../foundation/discovery/component-discovery.mjs';import {Project} from '../../foundation/config/project.mjs';import {loadComponentDoc as loadValidatedComponentDoc} from '../../foundation/discovery/component-loader.mjs';+import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';import {searchComponents} from '../../foundation/text/string-utils.mjs';import {AstryxError} from '../error.mjs';@@ -138,6 +139,38 @@ export async function loadIntegrationsSafely(cwd) {}}+/**+ * Every component replacement the loaded integrations declare+ * (spec:AST-035 FR10–FR15): the active one for each replaced Core component,+ * and the findings Doctor reports. With no Core directory, only the opt-in+ * and value findings are computed.+ * @param {string|null} coreDir+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations+ * @returns {Promise<import('../../foundation/discovery/component-replacement.mjs').ComponentReplacements>}+ */+export function loadComponentReplacements(coreDir, loadedIntegrations) {+ return resolveComponentReplacements(coreDir, loadedIntegrations);+}++/**+ * The integration component that answers to the Core component name+ * `dirName` for unqualified lookup, or undefined when none replaces it.+ * @param {string} coreDir+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations+ * @param {string} dirName+ * @returns {Promise<import('../../foundation/discovery/component-replacement.mjs').ActiveComponentReplacement | undefined>}+ */+export async function resolveComponentReplacement(+ coreDir,+ loadedIntegrations,+ dirName,+) {+ if (loadedIntegrations.length === 0) return undefined;+ return (+ await resolveComponentReplacements(coreDir, loadedIntegrations)+ ).forTarget(dirName);+}+/*** Resolve a loaded integration by package name.* @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrationsdiff --git a/packages/cli/api/component/component-replacement.test.mjs b/packages/cli/api/component/component-replacement.test.mjsnew file mode 100644index 0000000000..1dc0e9f006--- /dev/null+++ b/packages/cli/api/component/component-replacement.test.mjs@@ -0,0 +1,603 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Component replacement end to end (spec:AST-035 FR10–FR15): a consumer+ * project with real integration packages on disk, loaded through the real+ * Project, read through every component surface.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {component} from './component.mjs';+import {componentKeywords, search} from '../search/search.mjs';+import {swizzleCopy} from '../swizzle/copy/copy.mjs';+import {integrationComponentConflicts} from '../integration/authoring-checks.mjs';+import {GAP_REPORT_CATEGORIES, gapReport} from '../gap-report/gap-report.mjs';+import {Project} from '../../foundation/config/project.mjs';+import {COMPONENT_REPLACES_CLI} from '../../foundation/integrations/cli-requirement.mjs';++const SLOW = 60_000;+const FLOOR = {'@astryxdesign/cli': `>=${COMPONENT_REPLACES_CLI}`};++let tmpDir;++beforeEach(() => {+ // Under the repository so the project resolves the workspace's Core.+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-component-replacement-'),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * An integration package in the consumer's node_modules.+ * @param {string} name+ * @param {Array<{name: string, replaces?: string}>} components+ * @param {Record<string, string>} [peers]+ */+function writeIntegration(name, components, peers) {+ const pkgDir = path.join(tmpDir, 'node_modules', ...name.split('/'));+ const componentsDir = path.join(pkgDir, 'components');+ fs.mkdirSync(componentsDir, {recursive: true});+ fs.writeFileSync(+ path.join(pkgDir, 'package.json'),+ JSON.stringify({+ name,+ version: '1.0.0',+ exports: {'./components/*': './components/*.tsx'},+ ...(peers ? {peerDependencies: peers} : {}),+ }),+ );+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ "export default {components: './components'};\n",+ );+ for (const {name: componentName, replaces} of components) {+ fs.writeFileSync(+ path.join(componentsDir, `${componentName}.doc.mjs`),+ `export default ${JSON.stringify({+ type: 'component',+ name: componentName,+ displayName: componentName,+ ...(replaces ? {replaces} : {}),+ keywords: ['acme'],+ usage: {description: `${componentName} for Acme apps.`},+ props: [],+ })};\n`,+ );+ fs.writeFileSync(+ path.join(componentsDir, `${componentName}.tsx`),+ `export function ${componentName}() { return null; }\n`,+ );+ }+}++/**+ * The consumer: its dependencies autolink every integration; `configured`+ * names the ones astryx.config lists, in order.+ * @param {string[]} dependencies+ * @param {string[]} [configured]+ */+function writeConsumer(dependencies, configured) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ version: '1.0.0',+ dependencies: Object.fromEntries(dependencies.map(dep => [dep, '1.0.0'])),+ }),+ );+ if (configured) {+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ `export default {integrations: ${JSON.stringify(configured)}};\n`,+ );+ }+}++/** Every entry of a component.list payload, flattened. */+function listEntries(result) {+ return Object.values(result.data.components).flat();+}++describe('a package that declares the CLI floor', () => {+ beforeEach(() => {+ writeIntegration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeConsumer(['@acme/nav']);+ });++ it(+ 'answers to the Core name in component detail, naming its own package',+ async () => {+ const detail = await component('SideNav', {cwd: tmpDir});+ expect(detail.type).toBe('component.detail');+ expect(detail.package).toBe('@acme/nav');+ expect(detail.data).toMatchObject({+ name: 'AcmeSideNav',+ package: '@acme/nav',+ });++ const own = await component('AcmeSideNav', {cwd: tmpDir});+ expect(own.data).toEqual(detail.data);++ const props = await component('SideNav', {cwd: tmpDir, props: true});+ expect(props.package).toBe('@acme/nav');+ },+ SLOW,+ );++ it(+ 'keeps the Core original behind an explicit Core selection',+ async () => {+ const core = await component('SideNav', {+ cwd: tmpDir,+ package: '@astryxdesign/core',+ });+ expect(core.package).toBe('@astryxdesign/core');+ expect(core.data.name).toBe('SideNav');++ const qualified = await component('@astryxdesign/core/SideNav', {+ cwd: tmpDir,+ });+ expect(qualified.package).toBe('@astryxdesign/core');++ const batch = await component(['SideNav', '@astryxdesign/core/SideNav'], {+ cwd: tmpDir,+ });+ expect(batch.data.results.map(result => result.result.package)).toEqual([+ '@acme/nav',+ '@astryxdesign/core',+ ]);+ },+ SLOW,+ );++ it(+ 'takes the Core slot at every list detail level, once',+ async () => {+ for (const detail of /** @type {const} */ ([+ 'brief',+ 'compact',+ 'full',+ ])) {+ const entries = listEntries(+ await component(undefined, {cwd: tmpDir, list: true, detail}),+ );+ const named = entries.filter(+ entry =>+ /SideNav$/.test(entry.name) && !/SideNav[A-Z]/.test(entry.name),+ );+ expect(named, detail).toHaveLength(1);+ expect(named[0], detail).toMatchObject({+ name: 'AcmeSideNav',+ package: '@acme/nav',+ });+ }+ const navigation = await component(undefined, {+ cwd: tmpDir,+ category: 'Navigation',+ });+ expect(navigation.data.components.Navigation).toContainEqual(+ expect.objectContaining({name: 'AcmeSideNav', package: '@acme/nav'}),+ );+ expect(+ navigation.data.components.Navigation.map(entry => entry.name),+ ).not.toContain('SideNav');+ },+ SLOW,+ );++ it(+ 'is the component search returns for the Core name',+ async () => {+ const found = await search('SideNav', {cwd: tmpDir, type: 'component'});+ const results = found.data.results ?? Object.values(found.data).flat();+ const components = results.filter(+ result => result.domain === 'component',+ );+ expect(components[0]).toMatchObject({+ name: 'AcmeSideNav',+ package: '@acme/nav',+ score: 100,+ });+ expect(+ components.some(+ result =>+ result.name === 'SideNav' &&+ result.package === '@astryxdesign/core',+ ),+ ).toBe(false);+ },+ SLOW,+ );++ it(+ 'is what an unqualified swizzle copies; Core stays one selection away',+ async () => {+ const copied = await swizzleCopy('SideNav', {+ cwd: tmpDir,+ output: './out',+ });+ expect(copied.package).toBe('@acme/nav');+ expect(copied.data).toMatchObject({+ component: 'AcmeSideNav',+ package: '@acme/nav',+ });+ expect(+ fs.existsSync(+ path.join(tmpDir, 'out', 'AcmeSideNav', 'AcmeSideNav.tsx'),+ ),+ ).toBe(true);++ const core = await swizzleCopy('SideNav', {+ cwd: tmpDir,+ output: './core',+ package: '@astryxdesign/core',+ });+ expect(core.data.package).toBe('@astryxdesign/core');+ expect(fs.existsSync(path.join(tmpDir, 'core', 'SideNav'))).toBe(true);+ },+ SLOW,+ );++ it(+ 'routes issues and reports no findings for a valid replacement',+ async () => {+ const project = await Project.load(tmpDir);+ expect(+ (await project.componentReplacements()).forTarget('SideNav')?.package,+ ).toBe('@acme/nav');+ expect(+ (await project.issues()).filter(issue => /component/.test(issue.code)),+ ).toEqual([]);+ const checked = await integrationComponentConflicts('@acme/nav', {+ cwd: tmpDir,+ });+ expect(checked.data.issues).toEqual([]);+ expect(checked.data.conflicts).toEqual([]);+ },+ SLOW,+ );+});++describe('every surface reads the same replacement', () => {+ beforeEach(() => {+ writeIntegration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeConsumer(['@acme/nav']);+ });++ it(+ 'routes a gap report to the replacing package, and to Core when asked',+ async () => {+ fs.writeFileSync(+ path.join(+ tmpDir,+ 'node_modules',+ '@acme',+ 'nav',+ 'astryx.integration.mjs',+ ),+ "export default {components: './components', issuesUrl: 'https://example.com/acme/nav/issues'};\n",+ );+ const category = GAP_REPORT_CATEGORIES[0].value;+ const routed = await gapReport('SideNav', {+ cwd: tmpDir,+ category,+ reason: 'Needs a compact variant',+ });+ expect(routed.data.package).toBe('@acme/nav');+ const core = await gapReport('SideNav', {+ cwd: tmpDir,+ category,+ reason: 'Needs a compact variant',+ package: '@astryxdesign/core',+ });+ expect(core.data.package).toBe('@astryxdesign/core');+ },+ SLOW,+ );++ it.each(/** @type {const} */ (['compact', 'full']))(+ 'takes the Core slot in a category list at %s detail',+ async detail => {+ const listed = await component(undefined, {+ cwd: tmpDir,+ category: 'Navigation',+ detail,+ });+ const entries = listed.data.components.Navigation;+ expect(entries).toContainEqual(+ expect.objectContaining({name: 'AcmeSideNav', package: '@acme/nav'}),+ );+ expect(entries.map(entry => entry.name)).not.toContain('SideNav');+ },+ SLOW,+ );++ it(+ 'gives build the replacement keywords, not the Core original',+ async () => {+ const coreDir = path.resolve(+ import.meta.dirname,+ '..',+ '..',+ '..',+ 'core',+ );+ const names = (await componentKeywords(coreDir, tmpDir)).map(+ entry => entry.name,+ );+ expect(names).toContain('AcmeSideNav');+ expect(names).not.toContain('SideNav');+ },+ SLOW,+ );++ it(+ 'answers to the Core name qualified by its own package',+ async () => {+ const scoped = await component('SideNav', {+ cwd: tmpDir,+ package: '@acme/nav',+ });+ expect(scoped.package).toBe('@acme/nav');+ expect(scoped.data.name).toBe('AcmeSideNav');+ const copied = await swizzleCopy('SideNav', {+ cwd: tmpDir,+ output: './scoped',+ package: '@acme/nav',+ });+ expect(copied.data).toMatchObject({+ component: 'AcmeSideNav',+ package: '@acme/nav',+ });+ },+ SLOW,+ );++ it(+ 'matches the Core name exactly, as Core lookups do',+ async () => {+ await expect(component('sidenav', {cwd: tmpDir})).rejects.toMatchObject({+ code: 'ERR_UNKNOWN_COMPONENT',+ });+ },+ SLOW,+ );+});++describe('a replacement that keeps the Core name', () => {+ it(+ 'is intentional, so it is not a conflict, and it wins the bare name',+ async () => {+ writeIntegration(+ '@acme/nav',+ [{name: 'SideNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeConsumer(['@acme/nav']);+ const checked = await integrationComponentConflicts('@acme/nav', {+ cwd: tmpDir,+ });+ expect(checked.data.conflicts).toEqual([]);+ expect(checked.data.issues).toEqual([]);+ const detail = await component('SideNav', {cwd: tmpDir});+ expect(detail.package).toBe('@acme/nav');+ },+ SLOW,+ );++ it(+ 'stays a conflict when the package has not opted in',+ async () => {+ writeIntegration('@acme/nav', [{name: 'SideNav', replaces: 'SideNav'}]);+ writeConsumer(['@acme/nav']);+ const checked = await integrationComponentConflicts('@acme/nav', {+ cwd: tmpDir,+ });+ expect(checked.data.conflicts.map(conflict => conflict.name)).toEqual([+ 'SideNav',+ ]);+ },+ SLOW,+ );+});++describe('a component the replacement shadows', () => {+ it(+ 'keeps a search hit whose command names its own package',+ async () => {+ writeIntegration('@acme/native', [{name: 'SideNav'}]);+ writeIntegration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeConsumer(['@acme/native', '@acme/nav']);+ const found = await search('SideNav', {cwd: tmpDir, type: 'component'});+ const results = found.data.results ?? Object.values(found.data).flat();+ const shadowed = results.find(+ result =>+ result.name === 'SideNav' && result.package === '@acme/native',+ );+ expect(shadowed?.command).toBe(+ 'astryx component SideNav --package @acme/native',+ );+ const native = await component('SideNav', {+ cwd: tmpDir,+ package: '@acme/native',+ });+ expect(native.package).toBe('@acme/native');+ },+ SLOW,+ );+});++describe('a package published without the CLI floor', () => {+ beforeEach(() => {+ writeIntegration('@acme/old', [+ {name: 'OldTopNav', replaces: 'TopNav'},+ {name: 'Missing', replaces: 'NoSuchComponent'},+ ]);+ writeConsumer(['@acme/old']);+ });++ it(+ 'keeps the component under its own name and Core selected',+ async () => {+ const topNav = await component('TopNav', {cwd: tmpDir});+ expect(topNav.package).toBe('@astryxdesign/core');+ expect(topNav.data.name).toBe('TopNav');++ const own = await component('OldTopNav', {cwd: tmpDir});+ expect(own.package).toBe('@acme/old');++ const entries = listEntries(+ await component(undefined, {cwd: tmpDir, list: true}),+ );+ expect(entries).toContainEqual({+ name: 'TopNav',+ package: '@astryxdesign/core',+ });+ expect(entries).toContainEqual(+ expect.objectContaining({name: 'OldTopNav', package: '@acme/old'}),+ );++ const found = await search('TopNav', {cwd: tmpDir, type: 'component'});+ const results = found.data.results ?? Object.values(found.data).flat();+ expect(results[0]).toMatchObject({+ name: 'TopNav',+ package: '@astryxdesign/core',+ });+ },+ SLOW,+ );++ it(+ 'reports every finding to its author as a warning, and nothing to the app',+ async () => {+ const checked = await integrationComponentConflicts('@acme/old', {+ cwd: tmpDir,+ });+ expect(+ checked.data.issues+ .map(issue => `${issue.severity}:${issue.code}`)+ .sort(),+ ).toEqual(+ [+ 'warning:inactive_component_replacement',+ 'warning:inactive_component_replacement',+ 'warning:missing_component_replacement_target',+ ].sort(),+ );+ // Project issues feed project Doctor and the everyday-command nudge: an+ // app that loads a package without the floor sees nothing new.+ const project = await Project.load(tmpDir);+ expect(+ (await project.issues()).filter(issue =>+ /replacement/.test(issue.code),+ ),+ ).toEqual([]);+ },+ SLOW,+ );+});++describe('an opted-in package with an invalid declaration', () => {+ it(+ 'is an error and never replaces Core',+ async () => {+ writeIntegration(+ '@acme/bad',+ [+ {name: 'BadThing', replaces: 'NoSuchComponent'},+ {name: 'Button', replaces: 'Card'},+ ],+ FLOOR,+ );+ writeConsumer(['@acme/bad']);+ const checked = await integrationComponentConflicts('@acme/bad', {+ cwd: tmpDir,+ });+ expect(+ checked.data.issues+ .map(issue => `${issue.severity}:${issue.code}`)+ .sort(),+ ).toEqual(+ [+ 'error:invalid_component_replacement',+ 'error:missing_component_replacement_target',+ ].sort(),+ );+ const card = await component('Card', {cwd: tmpDir});+ expect(card.package).toBe('@astryxdesign/core');+ },+ SLOW,+ );+});++describe('several packages replacing one Core component', () => {+ it(+ 'lets the later configured package win, and Doctor warns',+ async () => {+ writeIntegration(+ '@acme/first',+ [{name: 'FirstNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeIntegration(+ '@acme/second',+ [{name: 'SecondNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeConsumer(+ ['@acme/first', '@acme/second'],+ ['@acme/first', '@acme/second'],+ );+ const detail = await component('SideNav', {cwd: tmpDir});+ expect(detail.package).toBe('@acme/second');+ const project = await Project.load(tmpDir);+ const issues = (await project.issues()).filter(+ issue => issue.code === 'ambiguous_component_replacement',+ );+ expect(issues).toHaveLength(1);+ expect(issues[0]).toMatchObject({+ package: '@acme/second',+ severity: 'warning',+ });+ },+ SLOW,+ );++ it(+ 'lets an explicitly configured package beat an autolinked one',+ async () => {+ writeIntegration(+ '@acme/explicit',+ [{name: 'ExplicitNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeIntegration(+ '@acme/auto',+ [{name: 'AutoNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeConsumer(['@acme/explicit', '@acme/auto'], ['@acme/explicit']);+ const detail = await component('SideNav', {cwd: tmpDir});+ expect(detail.package).toBe('@acme/explicit');+ },+ SLOW,+ );+});diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjsindex e833c2265d..f0c938bc14 100644--- a/packages/cli/api/component/component.mjs+++ b/packages/cli/api/component/component.mjs@@ -28,6 +28,7 @@ import {scopeSubComponent,ComponentAmbiguityError,installedComponentPackageVersion,+ resolveComponentReplacement,} from './_adapter.mjs';import {componentList} from './list/list.mjs';import {componentDetail} from './detail/detail.mjs';@@ -380,6 +381,21 @@ export async function component(name, options = {}) {// Searches that package first — critical for names that exist in both core// and an external package (AppShell, Button, SideNav).if (packageScope) {+ // The package whose component replaces a Core component answers to that+ // Core name too, as the bare name does (spec:AST-035 FR11).+ if (+ packageScope !== CORE_PACKAGE &&+ !owners.some(owner => owner.package === packageScope)+ ) {+ const replacement = await resolveComponentReplacement(+ coreDir,+ loadedIntegrations,+ dirName,+ );+ if (replacement?.package === packageScope) {+ return component(replacement.name, {...options, package: packageScope});+ }+ }const scoped = classifyScope(packageScope, {owners,loadedIntegrations,@@ -449,6 +465,22 @@ export async function component(name, options = {}) {);}+ // ── Replaced Core component (spec:AST-035 FR11) ────────────────+ // An active integration replacement answers to the Core name it replaces,+ // bare or qualified by its own package (above). The original stays+ // reachable with `--package @astryxdesign/core`.+ const replacement = await resolveComponentReplacement(+ coreDir,+ loadedIntegrations,+ dirName,+ );+ if (replacement) {+ return component(replacement.name, {+ ...options,+ package: replacement.package,+ });+ }+// Invalid integration metadata does not create ambiguity against a valid// owner. Keep raw owners only when no doc owner is valid, so an integration-// only component still exposes its source and returns ERR_INVALID_DOC fordiff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjsindex 9b1ea4e6e1..bfabf5d618 100644--- a/packages/cli/api/component/list/list.mjs+++ b/packages/cli/api/component/list/list.mjs@@ -24,7 +24,12 @@ import {import {discoverExternalPackages} from '../../../foundation/fs/paths.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {AstryxError} from '../../error.mjs';-import {loadComponentDoc, loadIntegrationsSafely, withOwnership} from '../_adapter.mjs';+import {+ loadComponentDoc,+ loadComponentReplacements,+ loadIntegrationsSafely,+ withOwnership,+} from '../_adapter.mjs';/*** @typedef {import('../component.type.mjs').ComponentListResponse} ComponentListResponse@@ -61,6 +66,60 @@ async function legacyImport(ext, name, coreDir, docOpts) {*/const coreEntry = doc => ({name: doc.name, package: CORE_PACKAGE, ...doc});+/**+ * The entry for a Core slot an integration component replaces+ * (spec:AST-035 FR11), at the list's detail level: the replacement's own name,+ * its package, and the import `component <Name>` reports for it.+ * @param {import('../../../foundation/discovery/component-replacement.mjs').ActiveComponentReplacement} replacement+ * @param {'names'|'compact'|'full'} detail+ * @param {{zh: boolean, dense: boolean, lang: string|null}} docOpts+ * @returns {Promise<any>}+ */+async function replacementEntry(replacement, detail, {zh, dense, lang}) {+ const {integration} = replacement;+ /** @type {any} */+ let docs = null;+ try {+ docs = await loadComponentDoc(+ replacement.docPath,+ detail === 'full' ? {zh, lang, dense} : {zh, lang},+ );+ } catch {+ // Keep list resilient; validation owns malformed integration docs.+ }+ const importPath = resolveIntegrationImportPath(+ {+ exportsMap: integration.__packageExports,+ packageDir: integration.__packageDir,+ docPath: replacement.docPath,+ packageName: replacement.package,+ },+ replacement.name,+ docs?.import,+ );+ if (detail === 'names') {+ return {name: replacement.name, package: replacement.package, import: importPath};+ }+ if (detail === 'compact') {+ return {+ name: replacement.name,+ package: replacement.package,+ description: docs?.usage?.description || docs?.description || '',+ import: importPath,+ };+ }+ if (docs == null) {+ return {name: replacement.name, package: replacement.package, description: ''};+ }+ const {package: _owner, ...doc} = docs;+ return {+ name: doc.name ?? replacement.name,+ package: replacement.package,+ ...doc,+ import: importPath,+ };+}+/*** Build the `component.list` envelope. The list taxonomy is collapsed: all* three detail levels emit ONE `component.list` type; the depth rides in@@ -80,6 +139,15 @@ export async function componentList({cwd, category, detail, zh, dense, lang},) {const components = discoverComponents(coreDir);+ // An active integration replacement takes its Core component's slot in+ // every list view (spec:AST-035 FR11); the Core original stays reachable+ // with `component <Name> --package @astryxdesign/core`.+ const loadedIntegrations = await loadIntegrationsSafely(cwd);+ const replacements = await loadComponentReplacements(+ coreDir,+ loadedIntegrations,+ );+ const docOpts = {zh, dense, lang};if (category) {const match = Object.entries(components).find(@@ -97,6 +165,11 @@ export async function componentList(/** @type {ComponentBriefEntry[]} */const entries = [];for (const comp of match[1]) {+ const replacement = replacements.forTarget(comp);+ if (replacement) {+ entries.push(await replacementEntry(replacement, 'compact', docOpts));+ continue;+ }const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {@@ -134,6 +207,11 @@ export async function componentList(/** @type {any[]} */const entries = [];for (const comp of match[1]) {+ const replacement = replacements.forTarget(comp);+ if (replacement) {+ entries.push(await replacementEntry(replacement, 'full', docOpts));+ continue;+ }const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {@@ -159,7 +237,14 @@ export async function componentList(data: {detail: 'names',components: {- [match[0]]: match[1].map(n => ({name: n, package: CORE_PACKAGE})),+ [match[0]]: await Promise.all(+ match[1].map(n => {+ const replacement = replacements.forTarget(n);+ return replacement+ ? replacementEntry(replacement, 'names', docOpts)+ : {name: n, package: CORE_PACKAGE};+ }),+ ),},},};@@ -172,6 +257,11 @@ export async function componentList(for (const [cat, comps] of Object.entries(components)) {result[cat] = [];for (const comp of comps) {+ const replacement = replacements.forTarget(comp);+ if (replacement) {+ result[cat].push(await replacementEntry(replacement, 'compact', docOpts));+ continue;+ }const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {@@ -212,6 +302,11 @@ export async function componentList(for (const [cat, comps] of Object.entries(components)) {result[cat] = [];for (const comp of comps) {+ const replacement = replacements.forTarget(comp);+ if (replacement) {+ result[cat].push(await replacementEntry(replacement, 'full', docOpts));+ continue;+ }const readme = findComponentReadme(coreDir, comp);if (readme && readme.endsWith('.doc.mjs')) {try {@@ -232,11 +327,21 @@ export async function componentList(/** @type {Record<string, ComponentListEntry[]>} */const listData = {};for (const [cat, comps] of Object.entries(components)) {- listData[cat] = comps.map(n => ({name: n, package: CORE_PACKAGE}));+ listData[cat] = await Promise.all(+ comps.map(n => {+ const replacement = replacements.forTarget(n);+ return replacement+ ? replacementEntry(replacement, 'names', docOpts)+ : {name: n, package: CORE_PACKAGE};+ }),+ );}+ // A replacement is listed once, in the Core slot it took.+ const listedReplacements = new Set(+ replacements.active.map(active => `${active.package}\0${active.name}`),+ );// Integration components (authoritative source: loadedIntegrations).- const loadedIntegrations = await loadIntegrationsSafely(cwd);const seenIntegration = new Set();for (const integration of loadedIntegrations) {seenIntegration.add(integration.name);@@ -248,6 +353,7 @@ export async function componentList(/** @type {Map<string, Array<{name: string, package: string, import?: string}>>} */const byGroup = new Map();for (const rec of owned) {+ if (listedReplacements.has(`${integration.name}\0${rec.name}`)) continue;const groupLabel = rec.group ?? integration.name;const key = `${groupLabel} (${integration.name})`;if (!byGroup.has(key)) byGroup.set(key, []);diff --git a/packages/cli/api/gap-report/gap-report.mjs b/packages/cli/api/gap-report/gap-report.mjsindex a2b45589d5..e38908ca34 100644--- a/packages/cli/api/gap-report/gap-report.mjs+++ b/packages/cli/api/gap-report/gap-report.mjs@@ -164,9 +164,23 @@ async function selectTarget(project, component, packageName) {const bareComponent = component.startsWith('XDS')? component.slice(3): component;+ const records = await project.components();+ // A replaced Core component routes to the package that replaces it+ // (spec:AST-035 FR11). Owners below match without case, so the Core name+ // does too.+ const coreName =+ records.find(+ record =>+ record.package === CORE_PACKAGE &&+ record.name.toLowerCase() === bareComponent.toLowerCase(),+ )?.name ?? bareComponent;+ const replacement = (await project.componentReplacements()).forTarget(+ coreName,+ );+ if (replacement) return targetForPackage(project, replacement.package);const owners = [...new Set(- (await project.components())+ records.filter(record => record.name.toLowerCase() === bareComponent.toLowerCase(),)diff --git a/packages/cli/api/integration/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjsindex e4e6a4efd4..66a1222ca5 100644--- a/packages/cli/api/integration/authoring-checks.mjs+++ b/packages/cli/api/integration/authoring-checks.mjs@@ -24,6 +24,7 @@ import {discoverIntegrationComponents,discoverOwnedComponents,} from '../../foundation/discovery/component-discovery.mjs';+import {loadComponentReplacements} from '../component/_adapter.mjs';import {discoverBuiltinTopics,discoverIntegrationDocs,@@ -260,9 +261,28 @@ export async function integrationComponentConflicts(pkg, options = {}) {.filter(record => record.package === '@astryxdesign/core').map(record => record.name),);+ // Component replacements (spec:AST-035 FR10-FR15). A package without the+ // CLI floor gets only warnings, so its exit code is what it was before the+ // floor existed. An active replacement named after its own target is+ // intentional, not a conflict.+ const replacements = await loadComponentReplacements(coreDir, [+ resolved.integration,+ ]);+ addErrors(issues, replacements.findings, 'invalid_component_replacement');+ const intentional = new Set(+ replacements.active+ .filter(+ active => active.package === name && active.name === active.target,+ )+ .map(active => active.name),+ );+const run = getCliInvocation(cwd);const conflicts = discoverIntegrationComponents(resolved.integration)- .filter(component => coreNames.has(component.name))+ .filter(+ component =>+ coreNames.has(component.name) && !intentional.has(component.name),+ ).map(component => ({name: component.name,severity: /** @type {const} */ ('warning'),diff --git a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs b/packages/cli/api/integration/integrationComponentConflicts.doc.mjsindex f2bfc8e707..c8f7beb824 100644--- a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs+++ b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs@@ -9,11 +9,14 @@ export const doc = {name: 'integrationComponentConflicts',namespace: 'cli/api',displayName: 'integrationComponentConflicts()',- summary: 'Find integration component names that also exist in Core.',+ summary:+ 'Check integration component names and replaces declarations against Core.',description:'Loads one local or installed integration, compares its component names with ' +'Core, and returns non-blocking conflicts with the exact package-qualified ' +- 'component command required to keep an intentional overlap.',+ "component command required to keep an intentional overlap. Each component's " ++ 'replaces is checked too: its findings are issues, errors for a package that ' ++ 'declares the CLI range that turns replacement on and warnings otherwise.',importPath: '@astryxdesign/cli/api',signature:'integrationComponentConflicts(pkg?: string, options?: IntegrationAuthoringOptions): Promise<IntegrationComponentConflictResponse>',@@ -26,7 +29,7 @@ export const doc = {{type: 'integration.component-conflicts',description:- '`validated` (false when no integration manifest was found, so nothing was inspected), integration identity, structural issues, and Core component-name conflicts with package-qualified commands.',+ '`validated` (false when no integration manifest was found, so nothing was inspected), integration identity, structural and replaces issues, and Core component-name conflicts with package-qualified commands. An active replacement that keeps the Core name it replaces is not a conflict.',},],examples: [diff --git a/packages/cli/api/integration/pack-check.component-replaces.test.mjs b/packages/cli/api/integration/pack-check.component-replaces.test.mjsnew file mode 100644index 0000000000..3c6c7803bb--- /dev/null+++ b/packages/cli/api/integration/pack-check.component-replaces.test.mjs@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * The pack check on a component that sets `replaces` (spec:AST-035 FR15): a+ * package without the CLI floor gets one warning and stays packable, and+ * `integration verify` still exits 0; a package with the floor gets nothing.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {spawnSync} from 'node:child_process';+import {integrationPackCheck} from './pack-check.mjs';+import {COMPONENT_REPLACES_CLI} from '../../foundation/integrations/cli-requirement.mjs';++const SLOW = 120_000;++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-pack-check-component-replaces-'),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/** @param {Record<string, string>} [peers] */+function writePackage(peers) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: '@acme/nav',+ version: '1.0.0',+ files: ['astryx.integration.mjs', 'components'],+ exports: {'./components/AcmeSideNav': './components/AcmeSideNav.tsx'},+ ...(peers ? {peerDependencies: peers} : {}),+ }),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ "export default {components: './components'};\n",+ );+ const components = path.join(tmpDir, 'components');+ fs.mkdirSync(components, {recursive: true});+ fs.writeFileSync(+ path.join(components, 'AcmeSideNav.doc.mjs'),+ `export default ${JSON.stringify({+ type: 'component',+ name: 'AcmeSideNav',+ displayName: 'Acme Side Nav',+ replaces: 'SideNav',+ import: '@acme/nav/components/AcmeSideNav',+ usage: {description: 'Product navigation for Acme apps.'},+ props: [],+ })};\n`,+ );+ fs.writeFileSync(+ path.join(components, 'AcmeSideNav.tsx'),+ 'export function AcmeSideNav() { return null; }\n',+ );+}++/** @param {{code: string}[]} issues */+const codesOf = issues => issues.map(issue => issue.code);++describe('integrationPackCheck with a component that sets replaces', () => {+ it(+ 'warns, and stays packable, when the package has no CLI floor',+ async () => {+ writePackage();+ const result = await integrationPackCheck({cwd: tmpDir});+ const issue = result.data.issues.find(+ entry => entry.code === 'component_replaces_needs_cli',+ );+ expect(issue, JSON.stringify(result.data.issues, null, 2)).toMatchObject({+ severity: 'warning',+ });+ expect(issue?.message).toContain(`>=${COMPONENT_REPLACES_CLI}`);+ expect(result.data.packable, JSON.stringify(result.data.issues)).toBe(+ true,+ );+ },+ SLOW,+ );++ it(+ 'says nothing when the package declares the floor',+ async () => {+ writePackage({'@astryxdesign/cli': `>=${COMPONENT_REPLACES_CLI}`});+ const result = await integrationPackCheck({cwd: tmpDir});+ expect(codesOf(result.data.issues)).not.toContain(+ 'component_replaces_needs_cli',+ );+ expect(result.data.packable, JSON.stringify(result.data.issues)).toBe(+ true,+ );+ },+ SLOW,+ );++ it(+ 'leaves integration verify at exit 0 without the floor',+ () => {+ writePackage();+ const run = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'integration',+ 'verify',+ '--json',+ ],+ {cwd: tmpDir, encoding: 'utf-8', timeout: SLOW},+ );+ expect(run.status, run.stderr).toBe(0);+ const receipt = JSON.parse(run.stdout);+ expect(codesOf(receipt.data.issues)).toContain(+ 'component_replaces_needs_cli',+ );+ },+ SLOW,+ );+});diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex e86a13364e..861bad7886 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -28,6 +28,7 @@ import jscodeshift from 'jscodeshift';import {assertWithin} from '../../foundation/fs/path-safety.mjs';import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';import {+ componentReplacesCliProblem,docsTreeCliProblem,keywordsCliProblem,replacesCliProblem,@@ -52,6 +53,7 @@ import {discoverIntegrationComponents,resolveIntegrationImportPath,} from '../../foundation/discovery/component-discovery.mjs';+import {loadComponentReplacements} from '../component/_adapter.mjs';import {loadComponentDoc} from '../../foundation/discovery/component-loader.mjs';import {discoverIntegrationTemplatesForOne} from '../../foundation/discovery/template-adapter.mjs';import {@@ -1150,6 +1152,24 @@ export async function integrationPackCheck(options = {}) {issues.push(error('keywords_needs_cli', keywordsProblem));}}+ // A component that sets `replaces` (spec:AST-035 FR10) is applied only when+ // the package's CLI range starts at the release that applies it. Without+ // that range the component keeps its own name and Core stays selected, so+ // this warns and never fails the check.+ if (loaded.components) {+ const found = await loadComponentReplacements(null, [loaded]).catch(() => ({+ findings: [],+ }));+ // Every declaration from a package without the range is reported as+ // inactive, whatever else is wrong with it.+ const setsReplaces = found.findings.some(+ finding => finding.code === 'inactive_component_replacement',+ );+ const problem = setsReplaces ? componentReplacesCliProblem(pkg) : null;+ if (problem != null) {+ issues.push(warning('component_replaces_needs_cli', problem));+ }+ }// A theme needs a CLI that reads typed theme descriptors: an older CLI// rejects the themes root and withholds the package's themes and docs.if (localIdentities.themes.length > 0) {diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 9ad7fb3d91..3e46d0d664 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -86,7 +86,10 @@ import {discoverHooks,findHookDoc,} from '../../foundation/discovery/hook-discovery.mjs';-import {loadIntegrationsSafely} from '../component/_adapter.mjs';+import {+ loadComponentReplacements,+ loadIntegrationsSafely,+} from '../component/_adapter.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {discoverTemplates, extractComponents} from '../template/template.mjs';import {templateLookupIds} from '../../foundation/discovery/template-adapter.mjs';@@ -982,11 +985,10 @@ async function gatherCoreComponents(coreDir) {* this, an integration component is invisible to `search`/`build` even* though `component --list`/`component <Name>` already resolve it — the two* discovery paths silently disagreed.- * @param {string} cwd+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations* @returns {Promise<Candidate[]>}*/-async function gatherIntegrationComponents(cwd) {- const loadedIntegrations = await loadIntegrationsSafely(cwd);+async function gatherIntegrationComponents(loadedIntegrations) {/** @type {Candidate[]} */const candidates = [];for (const integration of loadedIntegrations) {@@ -1031,11 +1033,40 @@ async function gatherIntegrationComponents(cwd) {* @returns {Promise<Candidate[]>}*/async function gatherComponents(coreDir, cwd) {- const [core, integrations] = await Promise.all([+ const loadedIntegrations = await loadIntegrationsSafely(cwd);+ const [core, integrations, replacements] = await Promise.all([gatherCoreComponents(coreDir),- gatherIntegrationComponents(cwd),+ gatherIntegrationComponents(loadedIntegrations),+ loadComponentReplacements(coreDir, loadedIntegrations),]);- return [...core, ...integrations];+ // An active replacement answers to the Core name it replaces, so a search+ // for that name finds the replacement and not the Core original+ // (spec:AST-035 FR11).+ /** @type {Map<string, string>} */+ const targetOf = new Map(+ replacements.active.map(active => [+ `${active.package}\0${active.name}`,+ active.target,+ ]),+ );+ return [+ ...core.filter(candidate => !replacements.forTarget(candidate.name)),+ ...integrations.map(candidate => {+ const target = targetOf.get(`${candidate._package}\0${candidate.name}`);+ if (target != null) {+ return {...candidate, aliases: [...(candidate.aliases ?? []), target]};+ }+ // Another package's component named after a replaced Core component is+ // shadowed for the bare name (FR14): its command names its package.+ const shadowedBy = replacements.forTarget(candidate.name);+ return shadowedBy && shadowedBy.package !== candidate._package+ ? {+ ...candidate,+ _command: `astryx component ${candidate.name} --package ${candidate._package}`,+ }+ : candidate;+ }),+ ];}/**@@ -1079,7 +1110,12 @@ export async function componentKeywords(coreDir, cwd) {: null;return {name, keywords: keywordsOf(doc)};});- const integrations = (await loadIntegrationsSafely(cwd)).map(+ const loadedIntegrations = await loadIntegrationsSafely(cwd);+ const replacements = await loadComponentReplacements(+ coreDir,+ loadedIntegrations,+ );+ const integrations = loadedIntegrations.map(async integration => {const {components} = await discoverValidIntegrationComponents(integration);return Promise.all(@@ -1091,7 +1127,9 @@ export async function componentKeywords(coreDir, cwd) {},);return [- ...(await Promise.all(core)),+ ...(await Promise.all(core)).filter(+ component => !replacements.forTarget(component.name),+ ),...(await Promise.all(integrations)).flat(),];}@@ -1552,7 +1590,7 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {result = {...base,import: c._import,- command: `astryx component ${c.name}`,+ command: c._command ?? `astryx component ${c.name}`,};break;case 'hook':diff --git a/packages/cli/api/swizzle/_adapter.mjs b/packages/cli/api/swizzle/_adapter.mjsindex abb2753c23..7e96b779d5 100644--- a/packages/cli/api/swizzle/_adapter.mjs+++ b/packages/cli/api/swizzle/_adapter.mjs@@ -12,12 +12,32 @@*/import {findCoreDir, listComponents} from '../../foundation/fs/paths.mjs';+import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {AstryxError} from '../error.mjs';/** The package that owns Core's components, hooks, and codemods. */export {CORE_PROVIDER_ID as CORE_PACKAGE} from '../../foundation/identity/providers.mjs';+/**+ * The integration component that replaces the Core component `name`+ * (spec:AST-035 FR11), or undefined when none does.+ * @param {string} coreDir+ * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations+ * @param {string} name+ * @returns {Promise<import('../../foundation/discovery/component-replacement.mjs').ActiveComponentReplacement | undefined>}+ */+export async function resolveComponentReplacement(+ coreDir,+ loadedIntegrations,+ name,+) {+ if (loadedIntegrations.length === 0) return undefined;+ return (+ await resolveComponentReplacements(coreDir, loadedIntegrations)+ ).forTarget(name);+}+/*** Locate @astryxdesign/core for `cwd` and list its swizzlable components.* @param {string} cwddiff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjsindex ccdeb2b0f7..fd958f89c5 100644--- a/packages/cli/api/swizzle/copy/copy.mjs+++ b/packages/cli/api/swizzle/copy/copy.mjs@@ -15,7 +15,7 @@import * as fs from 'node:fs';import * as path from 'node:path';-import {resolveCore} from '../_adapter.mjs';+import {resolveComponentReplacement, resolveCore} from '../_adapter.mjs';import {assertWithin, sanitizeName, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';import {checkGhCli} from '../_github.mjs';import {Project} from '../../../foundation/config/project.mjs';@@ -221,6 +221,26 @@ export async function swizzleCopy(component, options = {}) {const coreIssuesUrl = project? project.issuesUrl({package: CORE_PACKAGE}): undefined;+ // An active integration replacement answers to the Core name it replaces,+ // bare or qualified by its own package (spec:AST-035 FR11): copy it under its+ // own name. `--package @astryxdesign/core` still copies the Core original.+ if (pkg !== CORE_PACKAGE) {+ const replacement = await resolveComponentReplacement(+ coreDir,+ loadedIntegrations,+ dirName,+ );+ if (+ replacement &&+ (!pkg || (pkg === replacement.package && replacement.name !== dirName))+ ) {+ return swizzleCopy(replacement.name, {+ ...options,+ package: replacement.package,+ });+ }+ }+const allOwners = resolveOwners(coreDir, loadedIntegrations, dirName, coreIssuesUrl);if (allOwners.length === 0) {diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjsindex f89d88718f..00f25b87d2 100644--- a/packages/cli/assets/docs/tree/checks.doc.mjs+++ b/packages/cli/assets/docs/tree/checks.doc.mjs@@ -36,9 +36,9 @@ export const docs = {],['`npx astryx doctor integration components`',- 'No component name clashes with a Core component',- 'Core is not installed (`core_not_found`)',- 'A name clashes with Core',+ 'No component name clashes with a Core component, and each `replaces` names one Core component',+ 'Core is not installed (`core_not_found`). In a package that declares the CLI range that turns replacement on, a `replaces` target is missing (`missing_component_replacement_target`) or invalid (`invalid_component_replacement`), or two components replace one Core component (`ambiguous_component_replacement`)',+ 'A name clashes with Core, or a component sets `replaces` in a package without that range (`inactive_component_replacement`, plus any missing, invalid, or duplicate `replaces` reported as a warning)',],['`npx astryx doctor integration templates`',@@ -56,7 +56,7 @@ export const docs = {'`npx astryx integration verify`','The packed package holds every file, shows the same contributions, resolves every public import, and declares the CLI it needs','Anything `validate` fails on, no manifest, a file left out of the `.tgz` file, an import that does not resolve, or a missing CLI peer',- 'Anything `validate` warns about',+ 'Anything `validate` warns about, or a component sets `replaces` and the package does not declare the CLI range that turns it on (`component_replaces_needs_cli`)',],],},diff --git a/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjs b/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjsindex 77e2386bea..dc72f07b98 100644--- a/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjs+++ b/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjs@@ -29,7 +29,7 @@ export const docs = {style: 'unordered',items: ['Your component intentionally serves the same role as one specific Core component.',- 'Every app that loads the integration should get your component from unqualified component detail, lists, search, swizzle, and issue routing.',+ 'Every app that loads the integration should get your component from unqualified component detail, `component --list`, search, `swizzle <Name>`, and issue routing.','You have tested both the replacement and explicit access to the original Core component.',],},@@ -70,13 +70,30 @@ export default {projection: {fields: ['replaces']},presentation: 'full',},+ {+ type: 'prose',+ text: 'The replacement turns on only when your package declares the first CLI release that applies it. Add this to its `package.json`:',+ },+ {+ type: 'code',+ lang: 'json',+ label: 'package.json',+ code: `{+ "peerDependencies": {"@astryxdesign/cli": ">=0.6.7"},+ "peerDependenciesMeta": {"@astryxdesign/cli": {"optional": true}}+}`,+ },{type: 'list',style: 'unordered',items: [+ 'Any `@astryxdesign/cli` range that starts at that release or later turns it on, including the `>=0.7.0` that earlier `integration add theme` and `integration add doc --parent` wrote.',+ 'Without such a range, the component keeps its own name, the Core component stays selected (a component named like its target stays ambiguous by that bare name, as before), and `doctor integration components` warns with the range to add. Apps that load such a package see no change.','`replaces` names the Core `ComponentDoc` identity, not its display label, import path, or a standalone hook.','Your component may keep a distinct name or use the same name as the target. A distinct name remains directly addressable on older CLIs that ignore `replaces`.',- '`--package @astryxdesign/core` always selects the original Core component.',+ '`--package @astryxdesign/core` always selects the original Core component, and `--package` with your package selects your component by either name.',+ 'Replacing `SideNav` replaces only that name. `SideNavItem` and the other SideNav parts stay Core components; document any parts your package provides under their own names.',+ '`swizzle --list` lists Core components, including the one you replace. `swizzle SideNav` copies your component, and `swizzle SideNav --package @astryxdesign/core` copies the original.',],},],@@ -94,8 +111,8 @@ export default {type: 'list',style: 'unordered',items: [- 'A missing target, invalid value, second replacement for one target in the same package, or a replacement named after a different Core component is an error.',- 'When several integrations replace one target, explicit configuration beats the automatic pick. Among explicitly configured integrations, the later package wins and Doctor warns.',+ 'Once the package declares the range, a missing target, invalid value, second replacement for one target in the same package, or a replacement named after a different Core component is an error. Without the range, `doctor integration components` reports each of these as a warning.',+ 'When several integrations replace one target, explicit configuration beats the automatic pick. Among explicitly configured integrations, the later package wins and Doctor warns. Among autolinked integrations alone, the dependency listed later in `package.json` wins and Doctor warns.',],},],diff --git a/packages/cli/assets/docs/tree/troubleshooting.doc.mjs b/packages/cli/assets/docs/tree/troubleshooting.doc.mjsindex 1da491e53d..fa625fd49c 100644--- a/packages/cli/assets/docs/tree/troubleshooting.doc.mjs+++ b/packages/cli/assets/docs/tree/troubleshooting.doc.mjs@@ -93,6 +93,10 @@ export const docs = {'`replaces_needs_cli`: The package has a template that sets `replaces` but declares no @astryxdesign/cli peer.',"Run `npm pkg set 'peerDependencies.@astryxdesign/cli=>=0.7.0'` and `npm pkg set 'peerDependenciesMeta.@astryxdesign/cli.optional=true' --json`. A stable CLI before 0.7.0 rejects `replaces`, drops that template, and hides your doc topics.",],+ [+ '`component_replaces_needs_cli` (a warning): The package has a component that sets `replaces` but declares no @astryxdesign/cli peer, or a peer range that admits an earlier CLI.',+ "Run `npm pkg set 'peerDependencies.@astryxdesign/cli=>=0.6.7'` and `npm pkg set 'peerDependenciesMeta.@astryxdesign/cli.optional=true' --json` to turn the replacement on. Until then the component keeps its own name and the Core component stays selected; a component named like its target stays ambiguous by that bare name.",+ ],['`keywords_needs_cli`: The package has a template that sets `keywords` but declares no @astryxdesign/cli peer.','The same fix as `replaces_needs_cli`: a stable CLI before 0.7.0 rejects `keywords`, drops that template, and hides your doc topics.',diff --git a/packages/cli/authoring/doctypes/component/component.doc.mjs b/packages/cli/authoring/doctypes/component/component.doc.mjsindex 472113bb46..efbe9f57a4 100644--- a/packages/cli/authoring/doctypes/component/component.doc.mjs+++ b/packages/cli/authoring/doctypes/component/component.doc.mjs@@ -56,7 +56,7 @@ export const doc = {name: 'replaces',type: 'string',description:- "Integration components only: the exact `name` of the Core ComponentDoc this component takes over for unqualified lookup, so every app that loads the integration gets it from component detail, lists, search, swizzle, and issue routing. The Core original stays reachable with `--package @astryxdesign/core`. Set it only to intentionally own a Core identity; give an alternative or variant its own name instead.",+ "Integration components only: the exact `name` of the Core ComponentDoc this component takes over for unqualified lookup, so every app that loads the integration gets it from component detail, component lists, search, `swizzle <Name>`, and issue routing; `swizzle --list` keeps listing Core names. The Core original stays reachable with `--package @astryxdesign/core`. It takes effect only when the package's peer range starts at the release that applies it, `\"@astryxdesign/cli\": \">=0.6.7\"` or later; without such a range the component keeps its own name and `doctor integration components` warns. Set it only to intentionally own a Core identity; give an alternative or variant its own name instead.",},{name: 'keywords',diff --git a/packages/cli/authoring/doctypes/component/type.ts b/packages/cli/authoring/doctypes/component/type.tsindex 7ce8fd9831..e99d63a115 100644--- a/packages/cli/authoring/doctypes/component/type.ts+++ b/packages/cli/authoring/doctypes/component/type.ts@@ -50,11 +50,15 @@ export interface ComponentBaseDoc extends AuthoredDocGraphFields {import?: string;/** Integration components only: the exact `name` of the Core ComponentDoc* this component takes over for unqualified lookup, so every app that loads- * the integration gets this component from component detail, lists, search,- * swizzle, and issue routing. The Core original stays reachable with+ * the integration gets this component from component detail, component+ * lists, search, `swizzle <Name>`, and issue routing; `swizzle --list` keeps+ * listing Core names. The Core original stays reachable with* `--package @astryxdesign/core`. Set it only to intentionally own a Core- * identity; give an alternative or variant its own name instead. Older CLIs- * that do not read `replaces` keep the component under its own name. */+ * identity; give an alternative or variant its own name instead. It takes+ * effect only when the package's peer range starts at the release that+ * applies it, `"@astryxdesign/cli": ">=0.6.7"` or later; without such a+ * range, and on older CLIs that do not read `replaces`, the component keeps+ * its own name. */replaces?: string;/** Search keywords for CLI discovery. Terms a developer might type when* looking for this component: synonyms, related UI concepts, and commondiff --git a/packages/cli/clients/cli/commands/component-replacement.text.test.mjs b/packages/cli/clients/cli/commands/component-replacement.text.test.mjsnew file mode 100644index 0000000000..5338853c81--- /dev/null+++ b/packages/cli/clients/cli/commands/component-replacement.text.test.mjs@@ -0,0 +1,271 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Component replacement in text mode (spec:AST-035 FR11, FR13, FR15;+ * architecture:cli-surface INV28): what a person sees from the real CLI for a+ * replaced Core component, at every detail level, single, batch, and list,+ * plus the help that documents it.+ */++import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {COMPONENT_REPLACES_CLI} from '../../../foundation/integrations/cli-requirement.mjs';++vi.setConfig({testTimeout: 60_000, hookTimeout: 60_000});++const FLOOR = {'@astryxdesign/cli': `>=${COMPONENT_REPLACES_CLI}`};++let tmpDir;++/**+ * @param {string} name+ * @param {Array<{name: string, replaces?: string}>} components+ * @param {Record<string, string>} [peers]+ */+function writeIntegration(name, components, peers) {+ const pkgDir = path.join(tmpDir, 'node_modules', ...name.split('/'));+ const componentsDir = path.join(pkgDir, 'components');+ fs.mkdirSync(componentsDir, {recursive: true});+ fs.writeFileSync(+ path.join(pkgDir, 'package.json'),+ JSON.stringify({+ name,+ version: '1.0.0',+ ...(peers ? {peerDependencies: peers} : {}),+ }),+ );+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ "export default {components: './components'};\n",+ );+ for (const component of components) {+ fs.writeFileSync(+ path.join(componentsDir, `${component.name}.doc.mjs`),+ `export default ${JSON.stringify({+ type: 'component',+ name: component.name,+ displayName: component.name,+ ...(component.replaces ? {replaces: component.replaces} : {}),+ import: `${name}/components/${component.name}`,+ usage: {description: `${component.name} for Acme apps.`},+ props: [],+ })};\n`,+ );+ fs.writeFileSync(+ path.join(componentsDir, `${component.name}.tsx`),+ `export function ${component.name}() { return null; }\n`,+ );+ }+}++beforeAll(() => {+ // Under the repository so the project resolves the workspace's Core.+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-component-replacement-text-'),+ );+ writeIntegration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ FLOOR,+ );+ writeIntegration('@acme/old', [{name: 'OldTopNav', replaces: 'TopNav'}]);+ writeIntegration(+ '@acme/bad',+ [{name: 'BadThing', replaces: 'NoSuchComponent'}],+ FLOOR,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ version: '1.0.0',+ dependencies: {+ '@acme/nav': '1.0.0',+ '@acme/old': '1.0.0',+ '@acme/bad': '1.0.0',+ },+ }),+ );+});++afterAll(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++const IMPORT =+ "import { AcmeSideNav } from '@acme/nav/components/AcmeSideNav';";++describe('component detail text', () => {+ it('prints the replacement at full detail, naming its package', async () => {+ const run = await runCli(['component', 'SideNav'], {cwd: tmpDir});+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain('package: @acme/nav');+ expect(run.stdout).toContain('# AcmeSideNav');+ });++ it('imports the export the package has at compact detail', async () => {+ const run = await runCli(['component', 'SideNav', '--detail', 'compact'], {+ cwd: tmpDir,+ });+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain(IMPORT);+ expect(run.stdout).not.toContain('import { SideNav }');+ });++ it('names the export the package has at brief detail', async () => {+ const run = await runCli(['component', 'SideNav', '--detail', 'brief'], {+ cwd: tmpDir,+ });+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toMatch(+ /^AcmeSideNav {2}<- from '@acme\/nav\/components\/AcmeSideNav'/m,+ );+ expect(run.stdout).not.toMatch(/^SideNav {2}<- from '@acme/m);+ });++ it('answers to the Core name qualified by the replacing package', async () => {+ const run = await runCli(+ ['component', '@acme/nav/SideNav', '--detail', 'compact'],+ {+ cwd: tmpDir,+ },+ );+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain(IMPORT);+ });++ it('keeps the Core original behind --package @astryxdesign/core', async () => {+ const run = await runCli(+ [+ 'component',+ 'SideNav',+ '--package',+ '@astryxdesign/core',+ '--detail',+ 'compact',+ ],+ {cwd: tmpDir},+ );+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain('package: @astryxdesign/core');+ expect(run.stdout).toContain("from '@astryxdesign/core/SideNav'");+ });+});++describe('component batch text', () => {+ it.each(['compact', 'brief'])(+ 'uses the replacement export at %s detail',+ async detail => {+ const run = await runCli(+ ['component', 'SideNav', 'Button', '--detail', detail],+ {+ cwd: tmpDir,+ },+ );+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain('AcmeSideNav');+ expect(run.stdout).toContain("'@acme/nav/components/AcmeSideNav'");+ expect(run.stdout).not.toContain('import { SideNav }');+ expect(run.stdout).not.toMatch(/^SideNav {2}<- from '@acme/m);+ },+ );+});++describe('component list text', () => {+ it('lists the replacement once, with its package, at brief detail', async () => {+ const run = await runCli(['component', '--list'], {cwd: tmpDir});+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain('name: AcmeSideNav');+ expect(run.stdout).toContain(+ '@acme/nav/components/AcmeSideNav [@acme/nav]',+ );+ expect(run.stdout.match(/name: {3}AcmeSideNav\n/g)).toHaveLength(1);+ expect(run.stdout).not.toMatch(/name: {3}SideNav\n/);+ });++ it('names the replacement package at compact detail', async () => {+ const run = await runCli(['component', '--list', '--detail', 'compact'], {+ cwd: tmpDir,+ });+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain(+ '@acme/nav/components/AcmeSideNav [@acme/nav]',+ );+ expect(run.stdout).not.toMatch(/name: +SideNav\n/);+ });++ it('prints the replacement in the Core slot at full detail', async () => {+ const run = await runCli(['component', '--list', '--detail', 'full'], {+ cwd: tmpDir,+ });+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toMatch(+ /^AcmeSideNav {2}<- from '@acme\/nav\/components\/AcmeSideNav' {2}\[@acme\/nav\]$/m,+ );+ expect(run.stdout).not.toMatch(/^SideNav[( ]/m);+ });++ it.each(['brief', 'compact', 'full'])(+ 'keeps the replacement in its category at %s detail',+ async detail => {+ const run = await runCli(+ ['component', '--category', 'Navigation', '--detail', detail],+ {cwd: tmpDir},+ );+ expect(run.status, run.stderr).toBe(0);+ expect(run.stdout).toContain('AcmeSideNav');+ },+ );+});++describe('help documents the replacement', () => {+ it.each([+ [+ ['component', '--help'],+ ['replaced by an integration component', '--package @astryxdesign/core'],+ ],+ [+ ['swizzle', '--help'],+ ['replaces', '--package @astryxdesign/core', '--list'],+ ],+ [+ ['gap-report', '--help'],+ ['the integration whose component replaces the named Core component'],+ ],+ [+ ['doctor', 'integration', 'components', '--help'],+ ['replaces', 'an invalid replaces'],+ ],+ ])('%s', async (args, needles) => {+ const run = await runCli(/** @type {string[]} */ (args), {cwd: tmpDir});+ const help = run.stdout + run.stderr;+ for (const needle of needles) expect(help).toContain(needle);+ });+});++describe('doctor integration components text and exit codes', () => {+ it('exits 1 for an invalid replaces in a package with the floor', async () => {+ const run = await runCli(+ ['doctor', 'integration', 'components', '@acme/bad'],+ {+ cwd: tmpDir,+ },+ );+ expect(run.status).toBe(1);+ expect(run.stdout).toContain('missing_component_replacement_target');+ });++ it('warns and exits 0 for a package without the floor', async () => {+ const run = await runCli(+ ['doctor', 'integration', 'components', '@acme/old'],+ {+ cwd: tmpDir,+ },+ );+ expect(run.status, run.stdout).toBe(0);+ expect(run.stdout).toContain('inactive_component_replacement');+ expect(run.stdout).toContain(`">=${COMPONENT_REPLACES_CLI}"`);+ });+});diff --git a/packages/cli/clients/cli/commands/component.doc.mjs b/packages/cli/clients/cli/commands/component.doc.mjsindex 2352004877..1b70f4eec8 100644--- a/packages/cli/clients/cli/commands/component.doc.mjs+++ b/packages/cli/clients/cli/commands/component.doc.mjs@@ -21,7 +21,10 @@ export const doc = {"Use 'Button', 'widgets/Button', '@acme/widgets/Button', or " +"'@acme/[email protected]/Button'. A version applies to the package and must match the " +'installed version. Boolean flags narrow every resolved component to just its props, ' +- 'source, showcase, or example blocks.',+ 'source, showcase, or example blocks. An integration component that replaces a Core ' ++ 'component (its doc sets replaces, and its package declares the CLI range that turns ' ++ 'replacement on) answers to the Core name in detail, batch, and list views; use ' ++ '--package @astryxdesign/core for the original.',fn: 'component',args: [{@@ -69,7 +72,7 @@ export const doc = {flag: '--package <name>',param: 'options.package',description:- 'Scope lookup to an external package (e.g. @acme/xds-widgets)',+ 'Scope lookup to an external package (e.g. @acme/xds-widgets). Use @astryxdesign/core to select an original replaced by an integration component.',},],examples: [@@ -82,6 +85,10 @@ export const doc = {label: 'Props table as JSON',cli: 'astryx component Button --props --json',},+ {+ label: 'Select a replaced Core original',+ cli: 'astryx component SideNav --package @astryxdesign/core',+ },],exitCodes: [{code: 0, when: 'success'},diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjsindex 81f9814878..5b865552cc 100644--- a/packages/cli/clients/cli/commands/component/index.mjs+++ b/packages/cli/clients/cli/commands/component/index.mjs@@ -97,10 +97,18 @@ function summarize(result) {* @returns {import('../../formatters/index.mjs').Block[]}*/function componentDetailBlocks(result, requestedName, detail, themeData) {- const resolvedName = (requestedName.split('/').pop() ?? requestedName).replace(+ const requested = (requestedName.split('/').pop() ?? requestedName).replace(/^XDS/,'',);+ // A replacement answers to the Core name it replaces (spec:AST-035 FR11),+ // but its package exports it under its own name: print that one.+ const resolvedName =+ result.type === 'component.detail' &&+ typeof result.data.name === 'string' &&+ result.data.replaces === requested+ ? result.data.name+ : requested;switch (result.type) {case 'component.detail': {/** @type {import('../../formatters/index.mjs').Block[]} */@@ -282,8 +290,31 @@ export function registerComponent(program) {// in result.data.detail and the grouped map in result.data.components.if (result.data.detail === 'full') {// --detail full — dense per-component docs (signature, props, theming,- // examples). Verbatim doc block from the shared formatter.- emit(code(await formatBriefAll(coreDir, {zh, lang, themeData})));+ // examples). Verbatim doc block from the shared formatter. A Core slot+ // an integration component replaces prints that component, from the+ // list result (spec:AST-035 FR11).+ /** @type {Map<string, any>} */+ const replacements = new Map();+ for (const items of Object.values(result.data.components)) {+ for (const item of /** @type {any[]} */ (items)) {+ if (+ item.package !== '@astryxdesign/core' &&+ typeof item.replaces === 'string'+ ) {+ replacements.set(item.replaces, item);+ }+ }+ }+ emit(+ code(+ await formatBriefAll(coreDir, {+ zh,+ lang,+ themeData,+ replacements,+ }),+ ),+ );break;}@@ -299,7 +330,13 @@ export function registerComponent(program) {const isUngrouped =entries.length === 1 && items.length === 1 && items[0]?.name === cat;if (!isUngrouped) out.push(section(cat));- out.push(records(items, {fields: ['name', 'import', 'description']}));+ // An entry from another package says which one (cli-surface INV28).+ const named = items.map(item =>+ item.package === '@astryxdesign/core'+ ? item+ : {...item, import: `${item.import} [${item.package}]`},+ );+ out.push(records(named, {fields: ['name', 'import', 'description']}));}out.push(listFooter);emit(...out);diff --git a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjsindex 5da6624615..a8c95b3fcc 100644--- a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs@@ -8,11 +8,16 @@ export const doc = {name: 'doctor integration components',displayName: 'astryx doctor integration components',namespace: 'cli/commands',- summary: 'Warn when integration component names conflict with Core',+ summary: 'Check integration component names and replacements against Core',description:'Compares one local or installed integration with Core component names. A ' +'conflict is allowed and exits successfully, but the report recommends ' +- 'renaming and gives the exact --package command for an intentional overlap.',+ 'renaming and gives the exact --package command for an intentional overlap. ' ++ "It also checks each component's replaces: in a package that declares the CLI " ++ 'range that turns replacement on, a missing Core target, an invalid value, a ' ++ 'component named after a different Core component, or two replacements for one ' ++ 'Core component is an error. In a package without that range they are warnings, ' ++ 'with one more warning naming the range to declare.',fn: 'integrationComponentConflicts',args: [{@@ -31,8 +36,14 @@ export const doc = {},],exitCodes: [- {code: 0, when: 'the check completed; component conflicts are warnings'},- {code: 1, when: 'the integration is invalid or Core cannot be resolved'},+ {+ code: 0,+ when: 'the check completed; component name conflicts, and replaces findings for a package without the CLI range, are warnings',+ },+ {+ code: 1,+ when: 'the integration is invalid, Core cannot be resolved, or a package that declares the CLI range has an invalid replaces',+ },],related: ['doctor integration templates', 'component'],};diff --git a/packages/cli/clients/cli/commands/gap-report.doc.mjs b/packages/cli/clients/cli/commands/gap-report.doc.mjsindex d9fc6ef2b0..6fccbe0eef 100644--- a/packages/cli/clients/cli/commands/gap-report.doc.mjs+++ b/packages/cli/clients/cli/commands/gap-report.doc.mjs@@ -13,7 +13,7 @@ export const doc = {namespace: 'cli/commands',summary: 'Report a missing component or feature to the package that owns it',description:- 'Reports a missing component, variant, layout, styling, accessibility, API, or documentation capability to the package that owns it: the --package you name, else the one package that provides the component, else Core. ' ++ 'Reports a missing component, variant, layout, styling, accessibility, API, or documentation capability to the package that owns it: the --package you name, else the integration whose component replaces it, else the one package that provides the component, else Core. ' +'Every configured handler receives the report: the project config handler first, then each integration handler in config order. Public handlers run only with --confirm-public; internal handlers always run. A failing handler does not stop the others. ' +"With no handler it files a GitHub issue for the owning package, only with --confirm-public (without it nothing is sent), or returns the package's issues URL when that is not on GitHub. " +'The report records whether an agent or a person ran it.',@@ -49,7 +49,7 @@ export const doc = {flag: '--package <pkg>',param: 'options.package',description:- 'Package that owns the gap: @astryxdesign/core or a loaded integration. Overrides automatic routing; needed when more than one package provides the component',+ 'Package that owns the gap: @astryxdesign/core or a loaded integration. Overrides automatic routing, which picks the integration whose component replaces the named Core component, else the one package that provides it, else Core; needed when more than one package provides the component',},{flag: '--confirm-public',diff --git a/packages/cli/clients/cli/commands/swizzle.doc.mjs b/packages/cli/clients/cli/commands/swizzle.doc.mjsindex 72fa1391b6..38ddf9d6e0 100644--- a/packages/cli/clients/cli/commands/swizzle.doc.mjs+++ b/packages/cli/clients/cli/commands/swizzle.doc.mjs@@ -17,7 +17,10 @@ export const doc = {description:"Ejects a component's source from the resolved @astryxdesign/core (or its owning " +'integration) into your project for deep customization, rewriting imports that ' +- 'escape the component directory. With no name it lists the swizzlable components.',+ 'escape the component directory. With no name it lists the swizzlable components. ' ++ 'An integration component that replaces a Core component is what that Core name ' ++ 'copies; --package @astryxdesign/core copies the original. --list lists Core ' ++ 'components, including one an integration replaces.',fn: 'swizzle',args: [{name: 'component', param: 'component', required: false}],options: [@@ -30,12 +33,14 @@ export const doc = {{flag: '--package <pkg>',param: 'options.package',- description: 'Scope to a specific owning package',+ description:+ 'Scope to a specific owning package. Use @astryxdesign/core to copy an original replaced by an integration component',},{flag: '--list',param: 'options.list',- description: 'List available components',+ description:+ 'List the swizzlable Core components, including any that an integration component replaces',},{flag: '-f, --overwrite',@@ -47,6 +52,10 @@ export const doc = {examples: [{label: 'List swizzlable components', cli: 'astryx swizzle --list'},{label: 'Eject a component', cli: 'astryx swizzle Button'},+ {+ label: 'Copy a replaced Core original',+ cli: 'astryx swizzle SideNav --package @astryxdesign/core',+ },],exitCodes: [{code: 0, when: 'success'},diff --git a/packages/cli/clients/cli/lib/component-format.mjs b/packages/cli/clients/cli/lib/component-format.mjsindex dc0855237f..daff80ef0a 100644--- a/packages/cli/clients/cli/lib/component-format.mjs+++ b/packages/cli/clients/cli/lib/component-format.mjs@@ -636,11 +636,17 @@ export function formatProps(docs, componentName) {/*** Format brief summaries for ALL components in one output.+ * `replacements` maps a replaced Core name to the full list entry of the+ * integration component that takes its slot; that entry is printed in its+ * place, naming its package.* @param {string} coreDir- * @param {{zh?: boolean, lang?: string, themeData?: any}} [options]+ * @param {{zh?: boolean, lang?: string, themeData?: any, replacements?: Map<string, any>}} [options]* @returns {Promise<string>}*/-export async function formatBriefAll(coreDir, {zh = false, lang, themeData = null} = {}) {+export async function formatBriefAll(+ coreDir,+ {zh = false, lang, themeData = null, replacements = new Map()} = {},+) {const components = discoverComponents(coreDir);/** @type {string[]} */const output = [];@@ -651,6 +657,17 @@ export async function formatBriefAll(coreDir, {zh = false, lang, themeData = nuloutput.push(`## ${key}\n`);}for (const comp of comps) {+ const replacement = replacements.get(comp);+ if (replacement) {+ const [first, ...rest] = formatBrief(+ replacement,+ replacement.name,+ replacement.import,+ {themeData},+ ).split('\n');+ output.push([`${first} [${replacement.package}]`, ...rest].join('\n'));+ continue;+ }const readmePath = findComponentReadme(coreDir, comp);if (readmePath && readmePath.endsWith('.doc.mjs')) {const docs = await loadDocs(readmePath, {zh, lang});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 2ce91daa4f..5d29d31348 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -54,6 +54,7 @@ import {discoverOwnedComponents,discoverValidIntegrationComponents,} from '../discovery/component-discovery.mjs';+import {resolveComponentReplacements} from '../discovery/component-replacement.mjs';import {findCoreDir} from '../fs/paths.mjs';import {applyTemplateReplacements,@@ -681,6 +682,34 @@ export class Project {});}+ /**+ * Integration component replacements (spec:AST-035 FR10–FR15): the active+ * replacement for each replaced Core component. A finding about a package+ * that declares the CLI floor joins the project's integration issues under+ * that package. A package without the floor adds nothing to an app's+ * output (FR15); its author sees the findings in `doctor integration+ * components`. Memoized per instance.+ *+ * @returns {Promise<import('../discovery/component-replacement.mjs').ComponentReplacements>}+ */+ async componentReplacements() {+ return this.#memo('componentReplacements', async () => {+ const replacements = await resolveComponentReplacements(+ findCoreDir(this.#cwd),+ this.#loadedIntegrations,+ );+ for (const finding of replacements.findings) {+ if (!finding.optedIn) continue;+ this.#pushIssue(finding.package, {+ code: finding.code,+ severity: finding.severity,+ message: finding.message,+ });+ }+ return replacements;+ });+ }+/*** Core + integration templates, type-tagged, with valid integration* replacements projected over their Core targets. Wraps raw template discovery@@ -937,6 +966,9 @@ export class Project {// catalog. Resolve it first so issue results never depend on which discovery// method the caller happened to invoke earlier.await this.templates();+ // Component replacement validity likewise depends on Core plus every+ // integration's components.+ await this.componentReplacements();for (const integration of this.#loadedIntegrations) {await this.#collectIssues(integration);}diff --git a/packages/cli/foundation/discovery/component-discovery.mjs b/packages/cli/foundation/discovery/component-discovery.mjsindex 0e9f9c511e..fd8237e69f 100644--- a/packages/cli/foundation/discovery/component-discovery.mjs+++ b/packages/cli/foundation/discovery/component-discovery.mjs@@ -696,18 +696,20 @@ export function discoverIntegrationComponents(integration) {/*** Load and validate every discovered integration component independently.* Invalid metadata or a missing same-stem source removes only that component;- * callers can report the returned errors while retaining valid siblings.+ * callers can report the returned errors while retaining valid siblings. A+ * component whose doc sets `replaces` carries the value as written; the+ * component replacement resolver decides what it means.** @param {{name: string, components?: string, issuesUrl?: string}} integration* @returns {Promise<{- * components: Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}>,+ * components: Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null, replaces?: unknown}>,* discovered: Array<{name: string, package: string, docPath: string, sourcePath: string|null, issuesUrl: string|undefined, group: string|null}>,* errors: Array<{name: string, message: string}>,* }>}*/export async function discoverValidIntegrationComponents(integration) {const discovered = discoverIntegrationComponents(integration);- /** @type {Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}>} */+ /** @type {Array<{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null, replaces?: unknown}>} */const components = [];/** @type {Array<{name: string, message: string}>} */const errors = [];@@ -721,11 +723,15 @@ export async function discoverValidIntegrationComponents(integration) {continue;}try {- await loadComponentDoc(record.docPath);- components.push(+ const doc = await loadComponentDoc(record.docPath);+ const valid =/** @type {{name: string, package: string, docPath: string, sourcePath: string, issuesUrl: string|undefined, group: string|null}} */ (record- ),+ );+ components.push(+ doc != null && typeof doc === 'object' && doc.replaces !== undefined+ ? {...valid, replaces: doc.replaces}+ : valid,);} catch (err) {errors.push({diff --git a/packages/cli/foundation/discovery/component-replacement.mjs b/packages/cli/foundation/discovery/component-replacement.mjsnew file mode 100644index 0000000000..20de30ff52--- /dev/null+++ b/packages/cli/foundation/discovery/component-replacement.mjs@@ -0,0 +1,417 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Integration component replacement (spec:AST-035 FR10–FR15).+ *+ * @input Core's component catalog and the loaded integrations, in precedence+ * order (configured, then autolinked, then the package being authored).+ * @output The active replacement for each replaced Core component, and the+ * findings Doctor reports.+ * @position foundation/discovery — the one place component replacement is+ * decided. Component detail, list, search, swizzle, gap-report routing,+ * Project, and `doctor integration components` read the result instead of+ * deciding it again.+ *+ * A component opts in by setting `replaces` in its own doc. The replacement+ * applies only when the component's package also declares a+ * `@astryxdesign/cli` peer range that starts at COMPONENT_REPLACES_CLI: a+ * package published for an earlier CLI keeps the behavior it shipped with,+ * and every finding about it is a warning.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ discoverComponents,+ discoverValidIntegrationComponents,+} from './component-discovery.mjs';+import {+ CLI_PACKAGE,+ COMPONENT_REPLACES_CLI,+ componentReplacesCliProblem,+} from '../integrations/cli-requirement.mjs';++/**+ * @typedef {import('../integrations/integrations.mjs').LoadedIntegration} LoadedIntegration+ */++/**+ * One Doctor finding about a component replacement.+ * @typedef {object} ComponentReplacementFinding+ * @property {string} package the package that declares the replacement+ * @property {string} component the declaring component's own name+ * @property {'missing_component_replacement_target' | 'invalid_component_replacement' | 'ambiguous_component_replacement' | 'inactive_component_replacement' | 'shadowed_component_name'} code+ * @property {'warning' | 'error'} severity+ * @property {string} message+ * @property {boolean} optedIn whether the finding is about a package that+ * declares the CLI floor. Project issues and the everyday-command nudge+ * carry only these; a package without the floor is reported to its author+ * through `doctor integration components` and the pack check alone.+ */++/**+ * The integration component that answers to a Core component's name.+ * @typedef {object} ActiveComponentReplacement+ * @property {string} target the replaced Core component's name+ * @property {string} name the replacement's own name+ * @property {string} package+ * @property {string} docPath+ * @property {string|null} sourcePath+ * @property {string|undefined} issuesUrl+ * @property {LoadedIntegration} integration+ */++/**+ * @typedef {object} ComponentReplacements+ * @property {ActiveComponentReplacement[]} active in Core catalog order+ * @property {ComponentReplacementFinding[]} findings+ * @property {(name: unknown) => ActiveComponentReplacement | undefined} forTarget+ * the active replacement for a Core component name, matched exactly, as+ * Core component lookups are+ */++/**+ * @typedef {object} Declaration+ * @property {string} name+ * @property {string} package+ * @property {string} docPath+ * @property {string|null} sourcePath+ * @property {string|undefined} issuesUrl+ * @property {unknown} replaces+ * @property {LoadedIntegration} integration+ * @property {boolean} autolinked+ * @property {boolean} optedIn+ */++/** @param {string} value @returns {string} */+const keyOf = value => value.toLowerCase();++/**+ * The package.json beside an integration, or an empty object when it cannot+ * be read: a package with no readable manifest declares no CLI range.+ * @param {LoadedIntegration} integration+ * @returns {any}+ */+function packageJsonOf(integration) {+ const dir = integration.__packageDir;+ if (typeof dir !== 'string') return {};+ try {+ return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));+ } catch {+ return {};+ }+}++/**+ * Whether a package's declared CLI range turns its component replacements on.+ * @param {any} pkg package.json+ * @returns {boolean}+ */+export function componentReplacementsEnabled(pkg) {+ return componentReplacesCliProblem(pkg) == null;+}++/**+ * The sentence a finding about a package without the floor ends with.+ * @param {string} name+ * @param {string} target+ * @returns {string}+ */+function inactiveTail(name, target) {+ const until =+ name === target+ ? `Until then the bare name "${name}" stays ambiguous between Core and this package; select either one with --package.`+ : `Until then "${name}" keeps its own name and "${target}" stays Core.`;+ return (+ `This CLI applies the replacement only when the package declares "${CLI_PACKAGE}": ">=${COMPONENT_REPLACES_CLI}" ` ++ `in peerDependencies (optional in peerDependenciesMeta). ${until}`+ );+}++/**+ * Decide every component replacement for one project.+ *+ * Each integration's valid components are read once. A declaration on a+ * package without the CLI floor never applies, and its findings are warnings.+ * For packages with the floor: a missing Core target, an invalid value, a+ * component named after a different Core component, or two declarations for+ * one target in one package are errors, and an invalid declaration never+ * replaces Core. When several packages validly replace one target, an+ * explicitly configured package beats an autolinked one, and among the+ * remaining contenders the later package wins with a warning.+ *+ * @param {string|null} coreDir+ * @param {readonly LoadedIntegration[]} loadedIntegrations+ * @returns {Promise<ComponentReplacements>}+ */+export async function resolveComponentReplacements(+ coreDir,+ loadedIntegrations,+) {+ /** @type {ComponentReplacementFinding[]} */+ const findings = [];+ /** @type {Map<string, ActiveComponentReplacement>} */+ const byTarget = new Map();+ const result = {+ /** @type {ActiveComponentReplacement[]} */+ active: [],+ findings,+ /** @param {unknown} name */+ forTarget: name =>+ typeof name === 'string' ? byTarget.get(name) : undefined,+ };++ /** @type {Declaration[]} */+ const declarations = [];+ /** @type {Array<{name: string, package: string}>} */+ const nativeComponents = [];+ for (const integration of loadedIntegrations) {+ if (+ integration == null ||+ integration.__loadError ||+ !integration.components+ ) {+ continue;+ }+ /** @type {Awaited<ReturnType<typeof discoverValidIntegrationComponents>>['components']} */+ let components;+ try {+ // Every valid component, with the `replaces` its loaded doc sets: a+ // doc may spread, re-export, compute, or build the field, so only the+ // loaded value says whether it declares a replacement.+ ({components} = await discoverValidIntegrationComponents(integration));+ } catch {+ // Project and Doctor report a component root that cannot be read.+ continue;+ }+ /** @type {boolean | null} */+ let optedIn = null;+ for (const record of components) {+ if (record.replaces === undefined) {+ nativeComponents.push({name: record.name, package: record.package});+ continue;+ }+ optedIn ??= componentReplacementsEnabled(packageJsonOf(integration));+ declarations.push({+ name: record.name,+ package: record.package,+ docPath: record.docPath,+ sourcePath: record.sourcePath,+ issuesUrl: record.issuesUrl,+ replaces: record.replaces,+ integration,+ autolinked: integration.__autolinked === true,+ optedIn,+ });+ }+ }+ if (declarations.length === 0) return result;++ /** @type {string[]} */+ let coreNames = [];+ if (coreDir) {+ try {+ coreNames = Object.values(discoverComponents(coreDir)).flat();+ } catch {+ coreNames = [];+ }+ }+ /** @type {Map<string, string>} */+ const coreByKey = new Map(coreNames.map(name => [keyOf(name), name]));+ const coreSet = new Set(coreNames);++ /**+ * @param {Declaration} declaration+ * @param {ComponentReplacementFinding['code']} code+ * @param {string} message+ */+ const report = (declaration, code, message) => {+ findings.push({+ package: declaration.package,+ component: declaration.name,+ code,+ severity: declaration.optedIn ? 'error' : 'warning',+ message,+ optedIn: declaration.optedIn,+ });+ };++ /**+ * Valid declarations per canonical Core target, in precedence order.+ * @type {Map<string, Declaration[]>}+ */+ const validByTarget = new Map();+ /** @type {Set<string>} targets an opted-in error makes invalid */+ const invalidTargets = new Set();+ /** @type {Map<string, Declaration[]>} errors per target, for precedence */+ const failedByTarget = new Map();++ for (const declaration of declarations) {+ const {name, replaces} = declaration;+ const shown = typeof replaces === 'string' ? replaces : String(replaces);+ if (!declaration.optedIn) {+ findings.push({+ package: declaration.package,+ component: name,+ code: 'inactive_component_replacement',+ severity: 'warning',+ message: `Component "${name}" sets \`replaces: ${JSON.stringify(shown)}\`. ${inactiveTail(name, shown)}`,+ optedIn: false,+ });+ }+ if (typeof replaces !== 'string' || replaces.trim() === '') {+ report(+ declaration,+ 'invalid_component_replacement',+ `Component "${name}" sets \`replaces\` to ${JSON.stringify(replaces) ?? String(replaces)}. Set it to the exact name of one Core component, such as "SideNav".`,+ );+ continue;+ }+ if (!coreSet.has(replaces)) {+ const differentCase = coreByKey.get(keyOf(replaces));+ report(+ declaration,+ 'missing_component_replacement_target',+ differentCase+ ? `Component "${name}" replaces "${replaces}", which is not a Core component name. Core names it "${differentCase}".`+ : `Component "${name}" replaces "${replaces}", which is not a Core component. Run \`astryx component --list\` for Core component names.`,+ );+ if (declaration.optedIn) {+ const key = differentCase ?? replaces;+ const failed = failedByTarget.get(key) ?? [];+ failed.push(declaration);+ failedByTarget.set(key, failed);+ }+ continue;+ }+ const ownCore = coreSet.has(name) ? name : null;+ if (ownCore != null && ownCore !== replaces) {+ report(+ declaration,+ 'invalid_component_replacement',+ `Component "${name}" replaces "${replaces}", but its own name is the Core component "${ownCore}". Rename it, or replace "${ownCore}" instead.`,+ );+ if (declaration.optedIn) {+ const failed = failedByTarget.get(replaces) ?? [];+ failed.push(declaration);+ failedByTarget.set(replaces, failed);+ }+ continue;+ }+ const valid = validByTarget.get(replaces) ?? [];+ valid.push(declaration);+ validByTarget.set(replaces, valid);+ }++ // Two components in one package replacing one target: neither applies. A+ // package without the floor gets the same finding, as a warning.+ for (const [target, valid] of validByTarget) {+ /** @type {Map<string, Declaration[]>} */+ const byPackage = new Map();+ for (const declaration of valid) {+ const group = byPackage.get(declaration.package) ?? [];+ group.push(declaration);+ byPackage.set(declaration.package, group);+ }+ for (const [pkg, group] of byPackage) {+ if (group.length < 2) continue;+ const names = group+ .map(declaration => `"${declaration.name}"`)+ .join(', ');+ for (const declaration of group) {+ report(+ declaration,+ 'ambiguous_component_replacement',+ `${pkg} declares ${group.length} components as replacements for Core component "${target}" (${names}). One package declares at most one replacement for a Core component.`,+ );+ }+ if (group[0].optedIn) {+ const failed = failedByTarget.get(target) ?? [];+ failed.push(...group);+ failedByTarget.set(target, failed);+ }+ validByTarget.set(+ target,+ (validByTarget.get(target) ?? []).filter(d => d.package !== pkg),+ );+ }+ }++ // Only declarations from packages with the floor contend for a target.+ /** @param {string} target */+ const contendersFor = target =>+ (validByTarget.get(target) ?? []).filter(+ declaration => declaration.optedIn,+ );++ for (const [target, failed] of failedByTarget) {+ const valid = contendersFor(target);+ const hasExplicitIntent =+ valid.some(declaration => !declaration.autolinked) ||+ failed.some(declaration => !declaration.autolinked);+ // An invalid autolinked declaration never disables explicit intent.+ if (+ failed.some(declaration => !hasExplicitIntent || !declaration.autolinked)+ ) {+ invalidTargets.add(target);+ }+ }++ for (const target of coreNames) {+ const valid = contendersFor(target);+ if (valid.length === 0 || invalidTargets.has(target)) continue;+ const hasExplicitIntent = valid.some(+ declaration => !declaration.autolinked,+ );+ const contenders = hasExplicitIntent+ ? valid.filter(declaration => !declaration.autolinked)+ : valid;+ const winner = contenders[contenders.length - 1];+ if (valid.length > 1) {+ const packages = valid.map(declaration => declaration.package).join(', ');+ const reason =+ hasExplicitIntent && valid.some(declaration => declaration.autolinked)+ ? `${winner.package} is explicitly configured, so it wins over autolinked integrations.`+ : hasExplicitIntent+ ? `${winner.package} is configured later, so it wins.`+ : `${winner.package} is listed later in package.json dependencies, so it wins. Add the intended package to astryx.config integrations to make precedence explicit.`;+ findings.push({+ package: winner.package,+ component: winner.name,+ code: 'ambiguous_component_replacement',+ severity: 'warning',+ message: `Core component "${target}" is replaced by ${packages}. ${reason}`,+ optedIn: true,+ });+ }+ const active = {+ target,+ name: winner.name,+ package: winner.package,+ docPath: winner.docPath,+ sourcePath: winner.sourcePath,+ issuesUrl: winner.issuesUrl,+ integration: winner.integration,+ };+ byTarget.set(target, active);+ result.active.push(active);++ // An integration component named after the target, from another+ // package, is no longer what the bare name selects.+ for (const native of nativeComponents) {+ if (native.package === winner.package || native.name !== target) {+ continue;+ }+ findings.push({+ package: native.package,+ component: native.name,+ code: 'shadowed_component_name',+ severity: 'warning',+ message: `Component "${native.name}" from ${native.package} is shadowed by "${winner.name}" from ${winner.package}, which replaces Core "${target}". Select it with --package ${native.package}.`,+ optedIn: true,+ });+ }+ }++ return result;+}diff --git a/packages/cli/foundation/discovery/component-replacement.test.mjs b/packages/cli/foundation/discovery/component-replacement.test.mjsnew file mode 100644index 0000000000..269bed5811--- /dev/null+++ b/packages/cli/foundation/discovery/component-replacement.test.mjs@@ -0,0 +1,480 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {resolveComponentReplacements} from './component-replacement.mjs';+import {COMPONENT_REPLACES_CLI} from '../integrations/cli-requirement.mjs';++// Real Core: replacement targets are names in Core's component catalog.+const CORE_DIR = path.resolve(import.meta.dirname, '..', '..', '..', 'core');+const FLOOR = {'@astryxdesign/cli': `>=${COMPONENT_REPLACES_CLI}`};++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-component-replacement-'),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * One integration package on disk, shaped like a loaded integration.+ * @param {string} name+ * @param {Array<{name: string, replaces?: unknown, legacy?: boolean}>} components+ * @param {{peers?: Record<string, string>, autolinked?: boolean}} [options]+ */+function integration(name, components, {peers, autolinked = false} = {}) {+ const dir = path.join(tmpDir, name.replace('/', '__'));+ const componentsDir = path.join(dir, 'components');+ fs.mkdirSync(componentsDir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name,+ version: '1.0.0',+ ...(peers ? {peerDependencies: peers} : {}),+ }),+ );+ for (const component of components) {+ const doc = {+ ...(component.legacy ? {} : {type: 'component'}),+ name: component.name,+ displayName: component.name,+ ...('replaces' in component ? {replaces: component.replaces} : {}),+ usage: {description: `${component.name} from ${name}.`},+ props: [],+ };+ fs.writeFileSync(+ path.join(componentsDir, `${component.name}.doc.mjs`),+ component.legacy+ ? `export const docs = ${JSON.stringify(doc)};\n`+ : `export default ${JSON.stringify(doc)};\n`,+ );+ fs.writeFileSync(+ path.join(componentsDir, `${component.name}.tsx`),+ `export function ${component.name}() { return null; }\n`,+ );+ }+ return {+ name,+ version: '1.0.0',+ components: componentsDir,+ __spec: name,+ __packageDir: dir,+ __manifestFile: path.join(dir, 'astryx.integration.mjs'),+ ...(autolinked ? {__autolinked: true} : {}),+ };+}++/** @param {Awaited<ReturnType<typeof resolveComponentReplacements>>} result */+const codes = result =>+ result.findings.map(+ finding => `${finding.severity}:${finding.code}:${finding.component}`,+ );++/**+ * An opted-in integration whose one component doc is the given module source,+ * with shared modules beside the components root under `lib/`.+ * @param {string} name+ * @param {string} component+ * @param {string} docSource+ * @param {Record<string, string>} [lib]+ */+function integrationWithDocSource(name, component, docSource, lib = {}) {+ const loaded = integration(name, [], {peers: FLOOR});+ const libDir = path.join(loaded.__packageDir, 'lib');+ fs.mkdirSync(libDir, {recursive: true});+ for (const [file, source] of Object.entries(lib)) {+ fs.writeFileSync(path.join(libDir, file), source);+ }+ fs.writeFileSync(+ path.join(loaded.components, `${component}.doc.mjs`),+ docSource,+ );+ fs.writeFileSync(+ path.join(loaded.components, `${component}.tsx`),+ `export function ${component}() { return null; }\n`,+ );+ return loaded;+}++const BASE_DOC = `export default {type: 'component', name: 'AcmeNav', displayName: 'Acme Nav', replaces: 'SideNav', usage: {description: 'Acme nav.'}, props: []};\n`;++describe('resolveComponentReplacements', () => {+ it('applies a replacement from a package that declares the CLI floor', async () => {+ const acme = integration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const result = await resolveComponentReplacements(CORE_DIR, [acme]);+ expect(result.findings).toEqual([]);+ expect(result.active).toHaveLength(1);+ expect(result.forTarget('SideNav')).toMatchObject({+ target: 'SideNav',+ name: 'AcmeSideNav',+ package: '@acme/nav',+ });+ // The name matches exactly, as Core component lookups do.+ expect(result.forTarget('sidenav')).toBeUndefined();+ expect(result.forTarget('TopNav')).toBeUndefined();+ });++ it.each([+ ['no CLI peer', undefined],+ [+ 'a range that admits an earlier stable CLI',+ {'@astryxdesign/cli': '>=0.6.4'},+ ],+ ['a caret range on an earlier minor', {'@astryxdesign/cli': '^0.6.0'}],+ ])(+ 'keeps the released behavior for a package with %s',+ async (_label, peers) => {+ const old = integration(+ '@acme/old',+ [{name: 'OldTopNav', replaces: 'TopNav'}],+ {peers},+ );+ const result = await resolveComponentReplacements(CORE_DIR, [old]);+ expect(result.active).toEqual([]);+ expect(result.forTarget('TopNav')).toBeUndefined();+ expect(codes(result)).toEqual([+ 'warning:inactive_component_replacement:OldTopNav',+ ]);+ expect(result.findings[0].optedIn).toBe(false);+ expect(result.findings[0].message).toContain(+ `">=${COMPONENT_REPLACES_CLI}"`,+ );+ expect(result.findings[0].message).toContain('"TopNav" stays Core');+ },+ );++ it('reports a package without the floor with warnings only, even for invalid declarations', async () => {+ const old = integration('@acme/old', [+ {name: 'Missing', replaces: 'NoSuchComponent'},+ {name: 'Button', replaces: 'Card'},+ {name: 'NavA', replaces: 'SideNav'},+ {name: 'NavB', replaces: 'SideNav'},+ ]);+ const result = await resolveComponentReplacements(CORE_DIR, [old]);+ expect(result.active).toEqual([]);+ expect(+ result.findings.every(finding => finding.severity === 'warning'),+ ).toBe(true);+ expect(result.findings.every(finding => finding.optedIn === false)).toBe(+ true,+ );+ expect(codes(result)).toEqual(+ expect.arrayContaining([+ 'warning:missing_component_replacement_target:Missing',+ 'warning:invalid_component_replacement:Button',+ ]),+ );+ });++ it('reports duplicate declarations in a package without the floor as warnings', async () => {+ const old = integration('@acme/old', [+ {name: 'NavA', replaces: 'SideNav'},+ {name: 'NavB', replaces: 'SideNav'},+ ]);+ const result = await resolveComponentReplacements(CORE_DIR, [old]);+ expect(result.active).toEqual([]);+ expect(codes(result)).toEqual(+ expect.arrayContaining([+ 'warning:ambiguous_component_replacement:NavA',+ 'warning:ambiguous_component_replacement:NavB',+ ]),+ );+ });++ it('says a same-name declaration without the floor leaves the bare name ambiguous', async () => {+ const old = integration('@acme/old', [+ {name: 'SideNav', replaces: 'SideNav'},+ ]);+ const result = await resolveComponentReplacements(CORE_DIR, [old]);+ expect(codes(result)).toEqual([+ 'warning:inactive_component_replacement:SideNav',+ ]);+ expect(result.findings[0].message).toContain(+ 'the bare name "SideNav" stays ambiguous',+ );+ expect(result.findings[0].message).not.toContain('stays Core');+ });++ it('fails closed on invalid declarations from a package with the floor', async () => {+ const bad = integration(+ '@acme/bad',+ [+ {name: 'Missing', replaces: 'NoSuchComponent'},+ {name: 'WrongCase', replaces: 'sidenav'},+ {name: 'Button', replaces: 'Card'},+ {name: 'NavA', replaces: 'TopNav'},+ {name: 'NavB', replaces: 'TopNav'},+ ],+ {peers: FLOOR},+ );+ const result = await resolveComponentReplacements(CORE_DIR, [bad]);+ expect(codes(result).sort()).toEqual(+ [+ 'error:missing_component_replacement_target:Missing',+ 'error:missing_component_replacement_target:WrongCase',+ 'error:invalid_component_replacement:Button',+ 'error:ambiguous_component_replacement:NavA',+ 'error:ambiguous_component_replacement:NavB',+ ].sort(),+ );+ expect(+ result.findings.find(f => f.component === 'WrongCase')?.message,+ ).toContain('Core names it "SideNav"');+ expect(result.findings.every(finding => finding.optedIn === true)).toBe(+ true,+ );+ // Nothing replaces Core: neither the duplicated target nor the target of a+ // component named after another Core component.+ expect(result.active).toEqual([]);+ expect(result.forTarget('TopNav')).toBeUndefined();+ expect(result.forTarget('Card')).toBeUndefined();+ });++ it('rejects a value that is not a non-empty string', async () => {+ const bad = integration(+ '@acme/bad',+ [{name: 'AcmeNav', replaces: 42, legacy: true}],+ {+ peers: FLOOR,+ },+ );+ const result = await resolveComponentReplacements(CORE_DIR, [bad]);+ expect(result.active).toEqual([]);+ expect(codes(result)).toEqual([+ 'error:invalid_component_replacement:AcmeNav',+ ]);+ });++ it('lets a replacement keep the Core name it replaces', async () => {+ const acme = integration(+ '@acme/nav',+ [{name: 'SideNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const result = await resolveComponentReplacements(CORE_DIR, [acme]);+ expect(result.findings).toEqual([]);+ expect(result.forTarget('SideNav')).toMatchObject({+ name: 'SideNav',+ package: '@acme/nav',+ });+ });++ it('lets the later configured package win, with a warning', async () => {+ const first = integration(+ '@acme/first',+ [{name: 'FirstNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const second = integration(+ '@acme/second',+ [{name: 'SecondNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const result = await resolveComponentReplacements(CORE_DIR, [+ first,+ second,+ ]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/second');+ expect(codes(result)).toEqual([+ 'warning:ambiguous_component_replacement:SecondNav',+ ]);+ expect(result.findings[0].message).toContain('configured later');+ });++ it('lets an explicitly configured package beat an autolinked one', async () => {+ const explicit = integration(+ '@acme/explicit',+ [{name: 'ExplicitNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const autolinked = integration(+ '@acme/auto',+ [{name: 'AutoNav', replaces: 'SideNav'}],+ {peers: FLOOR, autolinked: true},+ );+ const result = await resolveComponentReplacements(CORE_DIR, [+ explicit,+ autolinked,+ ]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/explicit');+ expect(result.findings[0].message).toContain('explicitly configured');+ });++ it('lets the later autolinked dependency win when nothing is configured', async () => {+ const a = integration('@acme/a', [{name: 'ANav', replaces: 'SideNav'}], {+ peers: FLOOR,+ autolinked: true,+ });+ const b = integration('@acme/b', [{name: 'BNav', replaces: 'SideNav'}], {+ peers: FLOOR,+ autolinked: true,+ });+ const result = await resolveComponentReplacements(CORE_DIR, [a, b]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/b');+ expect(result.findings[0].message).toContain(+ 'listed later in package.json',+ );+ });++ it('never lets an invalid autolinked declaration disable an explicit replacement', async () => {+ const explicit = integration(+ '@acme/explicit',+ [{name: 'ExplicitNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const broken = integration(+ '@acme/broken',+ [+ {name: 'NavA', replaces: 'SideNav'},+ {name: 'NavB', replaces: 'SideNav'},+ ],+ {peers: FLOOR, autolinked: true},+ );+ const result = await resolveComponentReplacements(CORE_DIR, [+ explicit,+ broken,+ ]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/explicit');+ expect(codes(result)).toEqual(+ expect.arrayContaining([+ 'error:ambiguous_component_replacement:NavA',+ 'error:ambiguous_component_replacement:NavB',+ ]),+ );+ });++ it('ignores a package without the floor when another package replaces the same target', async () => {+ const old = integration('@acme/old', [+ {name: 'OldNav', replaces: 'SideNav'},+ ]);+ const acme = integration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const result = await resolveComponentReplacements(CORE_DIR, [acme, old]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/nav');+ expect(codes(result)).toEqual([+ 'warning:inactive_component_replacement:OldNav',+ ]);+ });++ it('warns about a component from another package that the replacement shadows', async () => {+ const native = integration('@acme/native', [{name: 'SideNav'}]);+ const acme = integration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ {+ peers: FLOOR,+ },+ );+ const result = await resolveComponentReplacements(CORE_DIR, [native, acme]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/nav');+ expect(codes(result)).toEqual(['warning:shadowed_component_name:SideNav']);+ expect(result.findings[0].message).toContain('--package @acme/native');+ });++ it.each([+ [+ 'a re-exported doc',+ "export {default} from '../lib/base.mjs';\n",+ {'base.mjs': BASE_DOC},+ ],+ [+ 'an imported default',+ "import base from '../lib/base.mjs';\nexport default base;\n",+ {'base.mjs': BASE_DOC},+ ],+ [+ 'a factory call',+ "import {navDoc} from '../lib/factory.mjs';\nexport default navDoc('AcmeNav', 'SideNav');\n",+ {+ 'factory.mjs':+ "export const navDoc = (name, target) => ({type: 'component', name, displayName: name, replaces: target, usage: {description: name}, props: []});\n",+ },+ ],+ [+ 'Object.assign over a shared base',+ "import {shared} from '../lib/shared.mjs';\nexport default Object.assign({}, shared, {name: 'AcmeNav', displayName: 'Acme Nav'});\n",+ {+ 'shared.mjs':+ "export const shared = {type: 'component', replaces: 'SideNav', usage: {description: 'Acme nav.'}, props: []};\n",+ },+ ],+ [+ 'a computed key',+ "const key = 'rep' + 'laces';\nexport default {type: 'component', name: 'AcmeNav', displayName: 'Acme Nav', [key]: 'SideNav', usage: {description: 'Acme nav.'}, props: []};\n",+ {},+ ],+ ])(+ 'reads a replacement declared through %s',+ async (_form, docSource, lib) => {+ const acme = integrationWithDocSource(+ '@acme/nav',+ 'AcmeNav',+ docSource,+ lib,+ );+ const result = await resolveComponentReplacements(CORE_DIR, [acme]);+ expect(result.findings).toEqual([]);+ expect(result.forTarget('SideNav')).toMatchObject({+ name: 'AcmeNav',+ package: '@acme/nav',+ });+ },+ );++ it('never reports an invalid component as shadowed', async () => {+ const broken = integration('@acme/broken', []);+ fs.writeFileSync(+ path.join(broken.components, 'SideNav.doc.mjs'),+ "export default {type: 'component', name: 'SideNav', props: 'not a list'};\n",+ );+ fs.writeFileSync(+ path.join(broken.components, 'SideNav.tsx'),+ 'export function SideNav() { return null; }\n',+ );+ const acme = integration(+ '@acme/nav',+ [{name: 'AcmeSideNav', replaces: 'SideNav'}],+ {peers: FLOOR},+ );+ const result = await resolveComponentReplacements(CORE_DIR, [broken, acme]);+ expect(result.forTarget('SideNav')?.package).toBe('@acme/nav');+ expect(result.findings).toEqual([]);+ });++ it('decides nothing when no component declares a replacement', async () => {+ const plain = integration('@acme/plain', [{name: 'AcmeCard'}], {+ peers: FLOOR,+ });+ const result = await resolveComponentReplacements(CORE_DIR, [plain]);+ expect(result).toMatchObject({active: [], findings: []});+ });+});diff --git a/packages/cli/foundation/integrations/cli-requirement.mjs b/packages/cli/foundation/integrations/cli-requirement.mjsindex 88b195a58f..33787d51dc 100644--- a/packages/cli/foundation/integrations/cli-requirement.mjs+++ b/packages/cli/foundation/integrations/cli-requirement.mjs@@ -32,6 +32,20 @@ export const NAMESPACE_DOCS_CLI = '0.6.4';*/export const REPLACES_CLI = '0.7.0';+/**+ * The first stable CLI release that applies a component's `replaces`+ * (spec:AST-035 FR10). It is also the opt-in: a CLI applies a package's+ * component replacements only when the package's `@astryxdesign/cli` peer+ * range starts here, so a package published for an earlier CLI keeps the+ * behavior it shipped with. Earlier stable CLIs accept the field and keep the+ * component under its own name.+ *+ * Tied to the next patch slot: it must equal the first stable release that+ * ships component replacement. If that slot moves, change this constant and+ * its row in the floor table test together.+ */+export const COMPONENT_REPLACES_CLI = '0.6.7';+/*** The first stable CLI release that reads typed theme descriptors, the theme* folder `integration add theme` writes. Published 0.6.3 rejects a themes root@@ -167,6 +181,23 @@ export function replacesCliProblem(pkg) {);}+/**+ * Why a package with a component that sets `replaces` would not get the+ * replacement (spec:AST-035 FR10), or null when its declared CLI range starts+ * at the release that applies it. That range is the package's opt-in: without+ * it the component keeps its own name and the Core component stays selected.+ * @param {any} pkg package.json+ * @returns {string | null}+ */+export function componentReplacesCliProblem(pkg) {+ return cliRangeProblem(+ pkg,+ 'has a component that sets `replaces`',+ 'ignores the field and keeps the component under its own name, and a later CLI applies the replacement only for a package whose range starts at that release',+ COMPONENT_REPLACES_CLI,+ );+}+/*** Why a package with a doc section that sets `id` would lose its doc topics on* an older CLI, or null when its declared CLI range admits only CLIs that readdiff --git a/packages/cli/foundation/integrations/cli-requirement.test.mjs b/packages/cli/foundation/integrations/cli-requirement.test.mjsindex 5518279809..92dcfe7c8d 100644--- a/packages/cli/foundation/integrations/cli-requirement.test.mjs+++ b/packages/cli/foundation/integrations/cli-requirement.test.mjs@@ -5,10 +5,12 @@ import {describe, expect, it} from 'vitest';import {semverCompare} from '../env/semver.mjs';import * as requirement from './cli-requirement.mjs';import {+ COMPONENT_REPLACES_CLI,NAMESPACE_DOCS_CLI,REPLACES_CLI,SECTION_IDS_CLI,cliRangeProblem,+ componentReplacesCliProblem,THEMES_CLI,lowestAdmitted,docsTreeCliProblem,@@ -106,6 +108,70 @@ describe('replacesCliProblem', () => {});});+describe('componentReplacesCliProblem', () => {+ // The floor is also the opt-in (spec:AST-035 FR10): a component's `replaces`+ // applies only for a package whose CLI range starts at it. Earlier stable+ // CLIs accept the field and keep the component under its own name.+ it('asks a package whose component sets replaces for the release that applies it', () => {+ expect(componentReplacesCliProblem({name: '@acme/kit'})).toContain(+ 'has a component that sets `replaces`',+ );+ expect(componentReplacesCliProblem({name: '@acme/kit'})).toContain(+ 'keeps the component under its own name',+ );+ for (const range of ['>=0.6.4', '^0.6.0', '>=0.6.5', '*']) {+ expect(+ componentReplacesCliProblem({+ peerDependencies: {'@astryxdesign/cli': range},+ }),+ ).toContain(`admits a stable CLI before ${COMPONENT_REPLACES_CLI}`);+ }+ for (const range of [+ `>=${COMPONENT_REPLACES_CLI}`,+ `^${COMPONENT_REPLACES_CLI}`,+ '>=0.7.0',+ ]) {+ expect(+ componentReplacesCliProblem({+ peerDependencies: {'@astryxdesign/cli': range},+ }),+ ).toBeNull();+ }+ });++ it('is the range every shipped doc tells an author to declare', () => {+ // The floor is tied to the next patch slot. If the slot moves, these docs+ // move with the constant and its row in the floor table below.+ for (const file of [+ '../../assets/docs/tree/replace-a-core-component.doc.mjs',+ '../../authoring/doctypes/component/component.doc.mjs',+ '../../authoring/doctypes/component/type.ts',+ ]) {+ const text = fs.readFileSync(new URL(file, import.meta.url), 'utf-8');+ const named = [+ ...text.matchAll(/"@astryxdesign\/cli\\?":\s*\\?">=(\d+\.\d+\.\d+)/g),+ ].map(match => match[1]);+ expect(named.length, file).toBeGreaterThan(0);+ expect(new Set(named), file).toEqual(new Set([COMPONENT_REPLACES_CLI]));+ }+ const troubleshooting = fs.readFileSync(+ new URL(+ '../../assets/docs/tree/troubleshooting.doc.mjs',+ import.meta.url,+ ),+ 'utf-8',+ );+ const row = troubleshooting+ .split('],')+ .find(part => part.includes('`component_replaces_needs_cli`'));+ expect(row).toContain(`@astryxdesign/cli=>=${COMPONENT_REPLACES_CLI}'`);+ // Every version that row names is the floor.+ expect(new Set(row?.match(/\d+\.\d+\.\d+/g))).toEqual(+ new Set([COMPONENT_REPLACES_CLI]),+ );+ });+});+describe('themesCliProblem and sectionIdsCliProblem', () => {// Published 0.6.4 reads typed theme descriptors and section ids. Published// 0.6.3 rejects both and hides the package's doc topics.@@ -184,6 +250,7 @@ describe('every feature check names its CLI floor', () => {// check whose floor changes, fails here until this table says so on// purpose, so a floor never moves as a side effect of another change.const FLOORS = {+ componentReplacesCliProblem: COMPONENT_REPLACES_CLI,docsTreeCliProblem: '0.6.4',replacesCliProblem: REPLACES_CLI,keywordsCliProblem: REPLACES_CLI,@@ -209,6 +276,9 @@ describe('every feature check names its CLI floor', () => {);expect(named).toEqual({...FLOORS,+ // Tied to the next patch slot: the first stable release that ships+ // component replacement.+ componentReplacesCliProblem: '0.6.7',replacesCliProblem: '0.7.0',keywordsCliProblem: '0.7.0',});