Skip to content

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

TypeScript

feat: every CLI result names its source package (#6968)

Joey84535e7fdba3
diff --git a/.changeset/cli-provenance-surfaces.md b/.changeset/cli-provenance-surfaces.md
new file mode 100644
index 0000000000..dc79cf3ca8
--- /dev/null
+++ b/.changeset/cli-provenance-surfaces.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Every result now names the package it comes from. A `--json` result about one artifact (a component and each of its projections, a doc topic, index, section, or docs-tree node, a template, a hook, and `swizzle`) carries `package` in its envelope, directly after `type`. A result that lists artifacts gives each item its own `package`: every `search` hit, `build`'s start, alternatives, blocks, and components, a doc's sections, a docs-tree node's children, `--blocks` entries, and the `component --list` and `upgrade --list` entries. Text names the same package; `--source`, `--showcase`, and a template's source still print only the source on stdout and name the package on stderr. Existing fields are unchanged.
+
+@josephfarina
diff --git a/.github/scripts/cli-json-smoke-test.mjs b/.github/scripts/cli-json-smoke-test.mjs
index 904a6b2aec..37e503aaee 100644
--- a/.github/scripts/cli-json-smoke-test.mjs
+++ b/.github/scripts/cli-json-smoke-test.mjs
@@ -143,9 +143,10 @@ function checkJson(label, args, {expectError = false, expectType = null} = {}) {
}
// Envelope success keys are limited to the contract's fields: the
- // apiVersion stamp, the type discriminator, the data payload, and an
- // optional sidecar `meta` (emitted as a sibling of data, never merged in).
- const allowedKeys = new Set(['apiVersion', 'type', 'data', 'meta']);
+ // apiVersion stamp, the type discriminator, the optional `package` that
+ // owns what the result is about (cli-surface INV28), the data payload, and
+ // an optional sidecar `meta` (emitted as a sibling of data, never merged in).
+ const allowedKeys = new Set(['apiVersion', 'type', 'package', 'data', 'meta']);
const extraKeys = Object.keys(parsed).filter(k => !allowedKeys.has(k));
if (extraKeys.length > 0) {
console.log(` FAIL ${label} (extra fields in envelope: ${extraKeys.join(', ')})`);
@@ -154,6 +155,13 @@ function checkJson(label, args, {expectError = false, expectType = null} = {}) {
return;
}
+ if ('package' in parsed && (typeof parsed.package !== 'string' || !parsed.package)) {
+ console.log(` FAIL ${label} (envelope package is not a package name)`);
+ failures.push({label, reason: 'envelope package is not a package name'});
+ failed++;
+ return;
+ }
+
if (expectType && parsed.type !== expectType) {
console.log(` FAIL ${label} (expected type "${expectType}", got "${parsed.type}")`);
failures.push({label, reason: `expected type "${expectType}"`});
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 4a406754fc..1f198ae49b 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -1819,6 +1819,8 @@ export interface DocSection {
/** Stable key readers address the section by: astryx docs <topic> <id>. */
id?: string;
title: string;
+ /** The npm package that wrote the section, as the CLI's docs read names it. */
+ package?: string;
content: ContentBlock[];
previewType?: string;
category?: string;
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 9155797c39..006b5b2b80 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -104,7 +104,7 @@ Options:
`--json` works with every command listed in `jsonSupported` (`astryx manifest --json`), which is every command except the bare groups such as `astryx theme`. The other four change only the reads named here; other commands ignore them:
-- `--json`: Output as typed JSON envelope: `{ apiVersion, type, data, meta? }` (errors: `{ apiVersion, error, code, suggestions? }`)
+- `--json`: Output as typed JSON envelope: `{ apiVersion, type, package?, data, meta? }` (errors: `{ apiVersion, error, code, suggestions? }`)
- `--detail <level>`: Detail level for `component`, `hook`, and docs tree reads (such as `astryx docs cli/commands/build`), increasing in size: `brief` (names only, default for lists) < `compact` (names + 1-line descriptions) < `full` (full docs per entry). Single-item views default to `full`.
- `--zh`: Simplified Chinese for component reads and for docs topics that have a translation (English otherwise)
- `--dense`: Token-efficient dense text for `astryx component <Name>` and `astryx docs <topic>`
@@ -424,18 +424,18 @@ Every response has a `type` discriminant. The full set is below (generated from
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |
| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |
-| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry. |
+| `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. |
| `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). |
-| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). |
-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |
-| `component.detail.source` | One component's source file, as {component, source}. |
-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |
-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |
+| `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |
+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component. |
+| `component.detail.source` | One component's source file, as {component, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component. |
+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner. |
| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order; meta.namespaces lists the docs tree's top-level namespaces, and meta.notLoaded each package whose docs did not load. |
-| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, summary} (pass the id as the section argument; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
-| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). |
-| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
+| `docs.detail` | One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.index` | One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there). |
+| `docs.detail.section` | One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope's package names the npm package that wrote the section. |
+| `docs.node` | One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names). |
| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |
| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
| `discover.list` | The integrations the project loads (name, category, components, version, a list per other kind they add, and latest when a source knows it); with a discover source, meta.available lists what the project could add and meta.sources reports each source; when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |
@@ -443,21 +443,21 @@ Every response has a `type` discriminant. The full set is below (generated from
| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. |
| `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. |
| `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |
-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), and, for a hit on one section, section (docs), or displayName and kind (templates). |
+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). |
| `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
-| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, command, basis, reason, alternatives, ...}, pages (search's closest templates), blocks and domain as SearchResultEntry[], frame, foundation, and hint {reason, commands} when thin. |
-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |
-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. |
+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
| `gap-report.categories` | The fixed gap category values and human-readable labels. |
| `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals. |
| `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
| `template.show` | The resolved template's source, exactly as a copy writes it, plus its description, kind, the component names it composes, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
-| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
-| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). |
+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). The envelope's package names the npm package that owns the template. |
| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |
-| `hook.detail` | One hook's full authored HookDoc. |
-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |
+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope's package is @astryxdesign/core, the only package that ships hooks. |
+| `hook.detail` | One hook's full authored HookDoc. The envelope's package is @astryxdesign/core. |
+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core. |
| `theme.build` | A theme build receipt: name, tokenCount and componentCount (override counts), sizeKB, the written outputs {css, js, dts, and variantsDts when applicable}, warnings (defects to fix), and notices (advisories about a correct theme, such as a named font it does not load). |
| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |
@@ -466,7 +466,7 @@ Every response has a `type` discriminant. The full set is below (generated from
| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |
| `theme.targets` | The whole themeable surface: the echoed filter, componentCount, and targets, one per theming target — {key, className, component, props, states, deprecatedFor?}, where props and states are its legal override keys and deprecatedFor names the canonical replacement key. |
| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
-| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
+| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
diff --git a/packages/cli/api/build/_adapter.mjs b/packages/cli/api/build/_adapter.mjs
index 5988308b4f..ce1e5ae265 100644
--- a/packages/cli/api/build/_adapter.mjs
+++ b/packages/cli/api/build/_adapter.mjs
@@ -29,6 +29,7 @@ import {findCoreDir} from '../../foundation/fs/paths.mjs';
* @property {string} command `astryx template <id> --type page`, the command that selects exactly this template: an integration replacement is selected by the Core id it replaces, and `--type page` keeps a block with the same id from making it ambiguous. Search prints template commands the same way.
* @property {string} displayName Human-facing name.
* @property {string} description What the page is and how it is laid out.
+ * @property {string} package The npm package that owns this template.
* @property {string} category The template's own `Family - Variant` label; empty when it declares none.
* @property {string[]} keywords The ideas the page serves, as its own descriptor names them; empty when it declares none.
*/
@@ -65,6 +66,7 @@ export async function loadPageTemplates(cwd) {
name: t.dirName,
displayName: t.displayName || t.name,
description: t.description || '',
+ package: t.package ?? '@astryxdesign/core',
category: t.category || '',
keywords: t.keywords ?? [],
// The id `template()` resolves back to this entry: an active replacement
diff --git a/packages/cli/api/build/build.type.mjs b/packages/cli/api/build/build.type.mjs
index 110561fc5c..273a613c71 100644
--- a/packages/cli/api/build/build.type.mjs
+++ b/packages/cli/api/build/build.type.mjs
@@ -42,6 +42,7 @@
* @property {string} name Template id, as `astryx template <name>` takes it.
* @property {string} displayName Human-facing template name.
* @property {string} description What the page is: its layout and the ideas it serves.
+ * @property {string} package The npm package that owns this template.
* @property {string} command The scaffold command that selects exactly this template, `astryx template <id> --type page <path>`: `<id>` is the Core id an integration replacement stands in for, else the template's own id, `<path>` is a placeholder for the file or folder to write the template to, and the `astryx` prefix is for the caller to replace with its own invocation.
* @property {'direct' | 'closest' | 'fallback'} basis Why this template. The page ranker picks every start: it weighs each matched word by how rare it is among page templates, favors the family the idea's head names and the container it names ("in a modal"), and discounts words that only modify another. `direct` when its pick is also search's direct match (`directMatch`); `closest` when it is not; `fallback` when no template has the evidence to lead and the page starts from the app shell.
* @property {string} reason One sentence saying the same as `basis`, for a reader.
@@ -55,6 +56,7 @@
* @property {string} name Template id, as `astryx template <name>` takes it.
* @property {string} displayName Human-facing template name.
* @property {string} description What the page is: its layout and the ideas it serves.
+ * @property {string} package The npm package that owns this template.
* @property {string} command The scaffold command, in the same form as the start's.
*/
diff --git a/packages/cli/api/build/kit/kit.mjs b/packages/cli/api/build/kit/kit.mjs
index a3e7e66f8c..93ffc22426 100644
--- a/packages/cli/api/build/kit/kit.mjs
+++ b/packages/cli/api/build/kit/kit.mjs
@@ -120,6 +120,7 @@ const ALWAYS = new Set([...FRAME, ...FOUNDATION]);
*/
const asTemplate = t => ({
name: t.name,
+ package: t.package,
displayName: t.displayName,
description: t.description,
command: `${t.command} <path>`,
diff --git a/packages/cli/api/component/component.mjs b/packages/cli/api/component/component.mjs
index e8c867b6bf..e833c2265d 100644
--- a/packages/cli/api/component/component.mjs
+++ b/packages/cli/api/component/component.mjs
@@ -394,6 +394,7 @@ export async function component(name, options = {}) {
name,
notFoundInPackage:
scoped.kind === 'integration' ? packageScope : null,
+ ownerPackage: owner.package,
});
}
// showcase/blocks were previously dropped on the scoped path — a
@@ -404,20 +405,20 @@ export async function component(name, options = {}) {
// a showcase, so skip discovery entirely.
if (showcase) {
return scoped.kind === 'core'
- ? componentDetailShowcase(dirName, {cwd, name})
- : componentDetailShowcase(dirName, {cwd, name, resolve: false});
+ ? componentDetailShowcase(dirName, {cwd, name, ownerPackage: owner.package})
+ : componentDetailShowcase(dirName, {cwd, name, resolve: false, ownerPackage: owner.package});
}
if (blocks) {
- return componentDetailBlocks(dirName, cwd);
+ return componentDetailBlocks(dirName, cwd, owner.package);
}
const docs = await loadComponentDoc(owner.docPath, docOpts);
- if (props) return componentDetailProps(docs);
+ if (props) return componentDetailProps(docs, owner.package);
return componentDetail(docs, owner, dirName, coreDir);
}
// Legacy `pkg.astryx.docs` external package.
if (showcase) {
- return componentDetailShowcase(dirName, {cwd, name, packageScope});
+ return componentDetailShowcase(dirName, {cwd, name, packageScope, ownerPackage: packageScope});
}
const extDocPath = resolveLegacyExternalDoc(scoped.ext, dirName);
if (extDocPath) {
@@ -426,13 +427,14 @@ export async function component(name, options = {}) {
return componentDetailSource(dirName, null, {
name,
notFoundInPackage: packageScope,
+ ownerPackage: scoped.ext.name,
});
}
if (blocks) {
- return componentDetailBlocks(dirName, cwd);
+ return componentDetailBlocks(dirName, cwd, scoped.ext.name);
}
const docs = await loadComponentDoc(extDocPath, docOpts);
- if (props) return componentDetailProps(docs);
+ if (props) return componentDetailProps(docs, scoped.ext.name);
return componentDetail(
docs,
{package: scoped.ext.name, sourcePath: null},
@@ -476,14 +478,14 @@ export async function component(name, options = {}) {
) {
const owner = effectiveOwners[0];
if (source) {
- return componentDetailSource(dirName, owner.sourcePath, {name});
+ return componentDetailSource(dirName, owner.sourcePath, {name, ownerPackage: owner.package});
}
if (showcase) {
// Integration components don't carry showcases — fail without scanning.
- return componentDetailShowcase(dirName, {cwd, name, resolve: false});
+ return componentDetailShowcase(dirName, {cwd, name, resolve: false, ownerPackage: owner.package});
}
const docs = await loadComponentDoc(owner.docPath, docOpts);
- if (props) return componentDetailProps(docs);
+ if (props) return componentDetailProps(docs, owner.package);
return componentDetail(docs, owner, dirName, coreDir);
}
@@ -493,11 +495,11 @@ export async function component(name, options = {}) {
return componentDetailSource(
dirName,
resolveCoreSourcePath(coreDir, dirName),
- {name},
+ {name, ownerPackage: CORE_PACKAGE},
);
}
if (showcase) {
- return componentDetailShowcase(dirName, {cwd, name});
+ return componentDetailShowcase(dirName, {cwd, name, ownerPackage: CORE_PACKAGE});
}
const resolved = await resolveUnscopedDoc(dirName, {coreDir, cwd, name});
@@ -505,7 +507,7 @@ export async function component(name, options = {}) {
// ── Blocks mode ──────────────────────────────────────────────
if (blocks) {
- return componentDetailBlocks(dirName, cwd);
+ return componentDetailBlocks(dirName, cwd, resolved.resolvedOwnerPackage);
}
// ── Sub-component scoping ────────────────────────────────────
@@ -514,7 +516,7 @@ export async function component(name, options = {}) {
const sub = scopeSubComponent(docs, dirName, coreDir);
if (sub) {
if (props)
- return componentDetailProps({props: sub.matchingComponent.props});
+ return componentDetailProps({props: sub.matchingComponent.props}, resolved.resolvedOwnerPackage);
return componentDetail(
sub.scoped,
{
@@ -526,7 +528,7 @@ export async function component(name, options = {}) {
);
}
- if (props) return componentDetailProps(docs);
+ if (props) return componentDetailProps(docs, resolved.resolvedOwnerPackage);
return componentDetail(
docs,
{
diff --git a/packages/cli/api/component/component.type.mjs b/packages/cli/api/component/component.type.mjs
index 7246154d21..cb19495d2d 100644
--- a/packages/cli/api/component/component.type.mjs
+++ b/packages/cli/api/component/component.type.mjs
@@ -36,8 +36,8 @@
* the depth is carried in `data.detail` and `data.components` holds the grouped
* map whose entry shape depends on that level:
* - 'names' -> ComponentListEntry[] (name + owner package + optional import)
- * - 'compact' -> ComponentBriefEntry[] (name + 1-line description + import)
- * - 'full' -> ComponentDoc[] (full authored doc per entry)
+ * - 'compact' -> ComponentBriefEntry[] (name + owner package + 1-line description + import)
+ * - 'full' -> ComponentDoc[] (full authored doc per entry, plus its owner package)
* @typedef {object} ComponentListResponse
* @property {'component.list'} type
* @property {ComponentListData} data
@@ -48,7 +48,7 @@
* @typedef {(
* | {detail: 'names'; components: Record<string, ComponentListEntry[]>}
* | {detail: 'compact'; components: Record<string, ComponentBriefEntry[]>}
- * | {detail: 'full'; components: Record<string, import('@astryxdesign/cli/authoring').ComponentDoc[]>}
+ * | {detail: 'full'; components: Record<string, Array<import('@astryxdesign/cli/authoring').ComponentDoc & {package: string}>>}
* )} ComponentListData
*/
@@ -110,6 +110,7 @@
* A single entry in a `component.list` group at `detail: 'compact'`.
* @typedef {object} ComponentBriefEntry
* @property {string} name
+ * @property {string} package - Owner package; '@astryxdesign/core' for a Core component.
* @property {string} description
* @property {string} import
*/
@@ -118,6 +119,7 @@
* astryx --json component <name>
* @typedef {object} ComponentDetailResponse
* @property {'component.detail'} type
+ * @property {string} package The npm package that owns the component.
* @property {import('@astryxdesign/cli/authoring').ComponentDoc & ComponentOwnership & ComponentDetailScope} data
*/
@@ -142,6 +144,7 @@
* astryx --json component <name> --props
* @typedef {object} ComponentDetailPropsResponse
* @property {'component.detail.props'} type
+ * @property {string} package The npm package that owns the component.
* @property {import('@astryxdesign/cli/authoring').ComponentPropDoc[]} data
*/
@@ -149,6 +152,7 @@
* astryx --json component <name> --source
* @typedef {object} ComponentDetailSourceResponse
* @property {'component.detail.source'} type
+ * @property {string} package The npm package that owns the component.
* @property {{component: string; source: string}} data
*/
@@ -156,6 +160,7 @@
* astryx --json component <name> --showcase
* @typedef {object} ComponentDetailShowcaseResponse
* @property {'component.detail.showcase'} type
+ * @property {string} package The npm package that owns the component.
* @property {{component: string; aspectRatio: number; source: string}} data
*/
@@ -163,12 +168,14 @@
* astryx --json component <name> --blocks
* @typedef {object} ComponentDetailBlocksResponse
* @property {'component.detail.blocks'} type
+ * @property {string} package The npm package that owns the component.
* @property {{component: string; showcase: BlockEntry | null; examples: BlockEntry[]; related: BlockEntry[]}} data
*/
/**
* @typedef {object} BlockEntry
* @property {string} name
+ * @property {string} package The npm package that owns the block template.
* @property {string} displayName
* @property {string} description
* @property {boolean} isShowcase
diff --git a/packages/cli/api/component/detail/blocks/blocks.mjs b/packages/cli/api/component/detail/blocks/blocks.mjs
index 4eb856d1e3..6846d1beb0 100644
--- a/packages/cli/api/component/detail/blocks/blocks.mjs
+++ b/packages/cli/api/component/detail/blocks/blocks.mjs
@@ -9,7 +9,7 @@
*/
import * as path from 'node:path';
-import {findRelatedBlocks} from '../../../template/template.mjs';
+import {findRelatedBlocks, pkgOf} from '../../../template/template.mjs';
/**
* Project a component's related blocks into the `component.detail.blocks`
@@ -17,12 +17,14 @@ import {findRelatedBlocks} from '../../../template/template.mjs';
* and broader related blocks.
* @param {string} componentName
* @param {string} cwd - project to discover blocks from; never the process cwd
+ * @param {string} ownerPackage - the npm package that owns the component
* @returns {Promise<import('../../component.type.mjs').ComponentDetailBlocksResponse>}
*/
-export async function componentDetailBlocks(componentName, cwd) {
+export async function componentDetailBlocks(componentName, cwd, ownerPackage) {
const allBlocks = await findRelatedBlocks(componentName, cwd);
const toEntry = (/** @type {any} */ b) => ({
name: b.dirName,
+ package: pkgOf(b),
displayName: b.name,
description: b.description,
isShowcase: b.isShowcase ?? false,
@@ -46,6 +48,7 @@ export async function componentDetailBlocks(componentName, cwd) {
return {
type: 'component.detail.blocks',
+ package: ownerPackage,
data: {
component: componentName,
showcase: showcaseBlock ? toEntry(showcaseBlock) : null,
diff --git a/packages/cli/api/component/detail/detail.mjs b/packages/cli/api/component/detail/detail.mjs
index 3a4ec3edcb..78c3132a35 100644
--- a/packages/cli/api/component/detail/detail.mjs
+++ b/packages/cli/api/component/detail/detail.mjs
@@ -19,5 +19,9 @@ import {withOwnership} from '../_adapter.mjs';
* @returns {import('../component.type.mjs').ComponentDetailResponse}
*/
export function componentDetail(docs, owner, componentName, coreDir) {
- return {type: 'component.detail', data: withOwnership(docs, owner, componentName, coreDir)};
+ return {
+ type: 'component.detail',
+ package: owner.package,
+ data: withOwnership(docs, owner, componentName, coreDir),
+ };
}
diff --git a/packages/cli/api/component/detail/props/props.mjs b/packages/cli/api/component/detail/props/props.mjs
index 817e456da1..5ec34a270f 100644
--- a/packages/cli/api/component/detail/props/props.mjs
+++ b/packages/cli/api/component/detail/props/props.mjs
@@ -13,8 +13,9 @@ import {extractProps} from '../../_adapter.mjs';
/**
* Project a resolved doc into the `component.detail.props` envelope.
* @param {import('../../_adapter.mjs').LoadedComponentDoc} docs
+ * @param {string} ownerPackage - the npm package that owns the component
* @returns {import('../../component.type.mjs').ComponentDetailPropsResponse}
*/
-export function componentDetailProps(docs) {
- return {type: 'component.detail.props', data: extractProps(docs)};
+export function componentDetailProps(docs, ownerPackage) {
+ return {type: 'component.detail.props', package: ownerPackage, data: extractProps(docs)};
}
diff --git a/packages/cli/api/component/detail/showcase/showcase.mjs b/packages/cli/api/component/detail/showcase/showcase.mjs
index 69eb15de61..1a05c3dd74 100644
--- a/packages/cli/api/component/detail/showcase/showcase.mjs
+++ b/packages/cli/api/component/detail/showcase/showcase.mjs
@@ -24,9 +24,10 @@ import {findShowcase} from '../../../template/template.mjs';
* @param {string} ctx.name - the caller's original input, used in the error message
* @param {string|null} [ctx.packageScope] - scope block discovery + the error to a package
* @param {boolean} [ctx.resolve] - when false, skip discovery and treat as not found
+ * @param {string} ctx.ownerPackage - the npm package that owns the component
* @returns {Promise<import('../../component.type.mjs').ComponentDetailShowcaseResponse>}
*/
-export async function componentDetailShowcase(componentName, {cwd, name, packageScope = null, resolve = true}) {
+export async function componentDetailShowcase(componentName, {cwd, name, packageScope = null, resolve = true, ownerPackage}) {
const match = resolve
? await findShowcase(componentName, cwd, packageScope ? {package: packageScope} : undefined)
: null;
@@ -36,6 +37,7 @@ export async function componentDetailShowcase(componentName, {cwd, name, package
}
return {
type: 'component.detail.showcase',
+ package: ownerPackage,
data: {
component: componentName,
aspectRatio: /** @type {number} */ (match.aspectRatio),
diff --git a/packages/cli/api/component/detail/source/source.mjs b/packages/cli/api/component/detail/source/source.mjs
index 07ea97c6d2..8d95311916 100644
--- a/packages/cli/api/component/detail/source/source.mjs
+++ b/packages/cli/api/component/detail/source/source.mjs
@@ -17,13 +17,17 @@ import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
* envelope. Throws ERR_NO_SOURCE when the owner ships no source file.
* @param {string} componentName - bare name, echoed back as `data.component`
* @param {string|null} sourcePath - the resolved source path (null → not found)
- * @param {{name: string, notFoundInPackage?: string|null}} ctx - `name` is the caller's original input; `notFoundInPackage` scopes the not-found message to a package
+ * @param {{name: string, notFoundInPackage?: string|null, ownerPackage: string}} ctx - `name` is the caller's original input; `notFoundInPackage` scopes the not-found message to a package; `ownerPackage` is the npm package that owns the component
* @returns {import('../../component.type.mjs').ComponentDetailSourceResponse}
*/
-export function componentDetailSource(componentName, sourcePath, {name, notFoundInPackage = null}) {
+export function componentDetailSource(componentName, sourcePath, {name, notFoundInPackage = null, ownerPackage}) {
if (!sourcePath) {
const suffix = notFoundInPackage ? ` in package "${notFoundInPackage}"` : '';
throw new AstryxError(`Source for "${name}" not found${suffix}`, undefined, ERROR_CODES.ERR_NO_SOURCE);
}
- return {type: 'component.detail.source', data: {component: componentName, source: fs.readFileSync(sourcePath, 'utf-8')}};
+ return {
+ type: 'component.detail.source',
+ package: ownerPackage,
+ data: {component: componentName, source: fs.readFileSync(sourcePath, 'utf-8')},
+ };
}
diff --git a/packages/cli/api/component/list/list.mjs b/packages/cli/api/component/list/list.mjs
index 217ad77894..9b1ea4e6e1 100644
--- a/packages/cli/api/component/list/list.mjs
+++ b/packages/cli/api/component/list/list.mjs
@@ -55,6 +55,12 @@ async function legacyImport(ext, name, coreDir, docOpts) {
return withOwnership(docs, {package: ext.name, sourcePath: null}, name, coreDir).import;
}
+/**
+ * A full Core ComponentDoc list entry, naming the package that owns it.
+ * @param {any} doc
+ */
+const coreEntry = doc => ({name: doc.name, package: CORE_PACKAGE, ...doc});
+
/**
* Build the `component.list` envelope. The list taxonomy is collapsed: all
* three detail levels emit ONE `component.list` type; the depth rides in
@@ -97,12 +103,14 @@ export async function componentList(
const docs = await loadComponentDoc(readme, {zh, lang});
entries.push({
name: comp,
+ package: CORE_PACKAGE,
description: docs.usage?.description || docs.description || '',
import: resolveImportPath(coreDir, comp),
});
} catch {
entries.push({
name: comp,
+ package: CORE_PACKAGE,
description: '',
import: resolveImportPath(coreDir, comp),
});
@@ -110,6 +118,7 @@ export async function componentList(
} else {
entries.push({
name: comp,
+ package: CORE_PACKAGE,
description: '',
import: resolveImportPath(coreDir, comp),
});
@@ -128,12 +137,12 @@ export async function componentList(
const readme = findComponentReadme(coreDir, comp);
if (readme && readme.endsWith('.doc.mjs')) {
try {
- entries.push(await loadComponentDoc(readme, {zh, lang, dense}));
+ entries.push(coreEntry(await loadComponentDoc(readme, {zh, lang, dense})));
} catch {
- entries.push({name: `XDS${comp}`, description: ''});
+ entries.push({name: `XDS${comp}`, package: CORE_PACKAGE, description: ''});
}
} else {
- entries.push({name: `XDS${comp}`, description: ''});
+ entries.push({name: `XDS${comp}`, package: CORE_PACKAGE, description: ''});
}
}
return {
@@ -169,12 +178,14 @@ export async function componentList(
const docs = await loadComponentDoc(readme, {zh, lang});
result[cat].push({
name: comp,
+ package: CORE_PACKAGE,
description: docs.usage?.description || docs.description || '',
import: resolveImportPath(coreDir, comp),
});
} catch {
result[cat].push({
name: comp,
+ package: CORE_PACKAGE,
description: '',
import: resolveImportPath(coreDir, comp),
});
@@ -182,6 +193,7 @@ export async function componentList(
} else {
result[cat].push({
name: comp,
+ package: CORE_PACKAGE,
description: '',
import: resolveImportPath(coreDir, comp),
});
@@ -203,12 +215,12 @@ export async function componentList(
const readme = findComponentReadme(coreDir, comp);
if (readme && readme.endsWith('.doc.mjs')) {
try {
- result[cat].push(await loadComponentDoc(readme, {zh, lang, dense}));
+ result[cat].push(coreEntry(await loadComponentDoc(readme, {zh, lang, dense})));
} catch {
- result[cat].push({name: `XDS${comp}`, description: ''});
+ result[cat].push({name: `XDS${comp}`, package: CORE_PACKAGE, description: ''});
}
} else {
- result[cat].push({name: `XDS${comp}`, description: ''});
+ result[cat].push({name: `XDS${comp}`, package: CORE_PACKAGE, description: ''});
}
}
}
diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjs
index c0846b638a..8f75f37061 100644
--- a/packages/cli/api/docs/_adapter.mjs
+++ b/packages/cli/api/docs/_adapter.mjs
@@ -150,6 +150,31 @@ function providerOf(entry) {
return normalizeProviderId(entry.providerId ?? entry.package);
}
+/**
+ * The npm package that wrote each section of a lowered topic: the topic's own
+ * package, or the package of the extension that contributed the section
+ * (spec cli-surface INV28).
+ * @param {DocsTopicEntry} entry
+ * @param {{sectionProviders?: Record<string, string>}} node the lowered topic
+ * @returns {(sectionId: string | undefined) => string}
+ */
+export function sectionPackageOf(entry, node) {
+ /** @type {Map<string, string>} */
+ const byProvider = new Map([[providerOf(entry), entry.package]]);
+ for (const extension of entry.extensions ?? []) {
+ byProvider.set(providerOf(extension), extension.package);
+ }
+ return sectionId => {
+ const provider =
+ sectionId == null ? undefined : node.sectionProviders?.[sectionId];
+ return (
+ (provider == null
+ ? undefined
+ : byProvider.get(normalizeProviderId(provider))) ?? entry.package
+ );
+ };
+}
+
/**
* One topic, lowered for `lang` with every link between docs resolved
* (spec:AST-047 FR9): an inline `{@link <target>}` reads as the command that
diff --git a/packages/cli/api/docs/detail/detail.mjs b/packages/cli/api/docs/detail/detail.mjs
index d665550b39..e384b33869 100644
--- a/packages/cli/api/docs/detail/detail.mjs
+++ b/packages/cli/api/docs/detail/detail.mjs
@@ -5,7 +5,7 @@
*
* @input A topic name plus optional {lang, zh, dense, cwd}. Resolves the topic
* via the shared adapter and compiles it with its token references linked.
- * @output { type: 'docs.detail', data: ReferenceDoc } — the full doc with
+ * @output { type: 'docs.detail', package, data: ReferenceDoc } — the full doc with
* token-refs inlined, matching `astryx --json docs <topic>`.
* @position Leaf under api/docs. Reads the compiled node through the detail
* lens; resolution, overlays and extensions happen in the compiler.
@@ -13,7 +13,12 @@
import {linkReferenceTopic} from '../../../foundation/doc-compiler/compile.mjs';
import {detailView} from '../../../foundation/doc-compiler/lenses.mjs';
-import {referenceTargets, resolveTopicDocs, topicLinks} from '../_adapter.mjs';
+import {
+ referenceTargets,
+ resolveTopicDocs,
+ sectionPackageOf,
+ topicLinks,
+} from '../_adapter.mjs';
/**
* @param {string} topic
@@ -30,10 +35,21 @@ export async function detail(topic, options = {}) {
node,
referenceTargets(catalog, lang),
);
+ const view = detailView(linked);
+ const sectionPackage = sectionPackageOf(entry, node);
return {
type: 'docs.detail',
+ package: entry.package,
data: {
- ...detailView(linked),
+ ...view,
+ // Each section names the package that wrote it: the topic's own, or an
+ // extension's.
+ sections: view.sections.map(
+ (/** @type {import('../docs.type.mjs').DocsReadSection} */ section) => {
+ const {id, title, ...rest} = section;
+ return {id, title, package: sectionPackage(id), ...rest};
+ },
+ ),
// A guide the docs tree places is read by its route, not its doc name.
...(entry.tree ? {name: entry.name} : {}),
links: await topicLinks(catalog, entry),
diff --git a/packages/cli/api/docs/detail/section/section.mjs b/packages/cli/api/docs/detail/section/section.mjs
index 4a640726fd..c4968525fe 100644
--- a/packages/cli/api/docs/detail/section/section.mjs
+++ b/packages/cli/api/docs/detail/section/section.mjs
@@ -26,7 +26,11 @@ import {
readerSections,
sectionView,
} from '../../../../foundation/doc-compiler/lenses.mjs';
-import {referenceTargets, resolveTopicDocs} from '../../_adapter.mjs';
+import {
+ referenceTargets,
+ resolveTopicDocs,
+ sectionPackageOf,
+} from '../../_adapter.mjs';
/**
* @param {string} topic
@@ -84,6 +88,8 @@ export async function section(topic, sectionName, options = {}) {
}
return {
type: 'docs.detail.section',
+ // The package that wrote this section: the topic's own, or an extension's.
+ package: sectionPackageOf(entry, node)(match.id),
data: {...sectionView(node, linked), links},
};
}
diff --git a/packages/cli/api/docs/docs.depth.test.mjs b/packages/cli/api/docs/docs.depth.test.mjs
index 8e261d3ea1..d04c20ff1b 100644
--- a/packages/cli/api/docs/docs.depth.test.mjs
+++ b/packages/cli/api/docs/docs.depth.test.mjs
@@ -41,6 +41,7 @@ describe('docs() depth', () => {
expect(Object.keys(child).sort()).toEqual([
'kind',
'name',
+ 'package',
'route',
'summary',
'title',
@@ -60,6 +61,7 @@ describe('docs() depth', () => {
expect(findRoute(result.data, 'cli/api/functions/search')).toEqual({
route: 'cli/api/functions/search',
name: 'search',
+ package: '@astryxdesign/cli',
kind: 'function',
title: 'search()',
summary: expect.any(String),
diff --git a/packages/cli/api/docs/docs.mjs b/packages/cli/api/docs/docs.mjs
index e065be9240..4b8fe12dcd 100644
--- a/packages/cli/api/docs/docs.mjs
+++ b/packages/cli/api/docs/docs.mjs
@@ -120,6 +120,8 @@ export async function docs(topic, section, options = {}) {
}
return {
type: 'docs.node',
+ // The docs tree names each node's npm package as its provider.
+ package: found.node.provider,
data: await nodeView(found.catalog, found.tree, found.node, read),
};
}
diff --git a/packages/cli/api/docs/docs.type.mjs b/packages/cli/api/docs/docs.type.mjs
index 1eabba1a0d..8038edb790 100644
--- a/packages/cli/api/docs/docs.type.mjs
+++ b/packages/cli/api/docs/docs.type.mjs
@@ -49,6 +49,7 @@
* astryx --json docs <topic> --index
* @typedef {object} DocsIndexResponse
* @property {'docs.index'} type
+ * @property {string} package the npm package that owns the topic
* @property {DocsIndex} data
*/
@@ -56,8 +57,10 @@
* astryx --json docs <topic>
* @typedef {object} DocsDetailResponse
* @property {'docs.detail'} type
- * @property {DocsReadDoc & {links: DocsLinks}} data
- * the whole doc, and the moves from it
+ * @property {string} package the npm package that owns the topic
+ * @property {Omit<DocsReadDoc, 'sections'> & {sections: DocsDetailSection[], links: DocsLinks}} data
+ * the whole doc, each section naming the package that wrote it, and the
+ * moves from it
*/
/**
@@ -68,6 +71,12 @@
* & {content: import('@astryxdesign/cli/authoring').ReferenceContentBlock[]}} DocsReadSection
*/
+/**
+ * A section of a whole-topic read: the read section, naming the package that
+ * wrote it.
+ * @typedef {DocsReadSection & {package: string}} DocsDetailSection
+ */
+
/**
* A topic as a read returns it: every section a {@link DocsReadSection}.
* @typedef {Omit<import('@astryxdesign/cli/authoring').ReferenceDoc, 'sections'>
@@ -115,17 +124,26 @@
*/
/**
- * @typedef {object} DocsIndexSection
+ * One section of a topic's index, before it names its package.
+ * @typedef {object} DocsIndexEntry
* @property {string} id stable key; pass it as the section argument
* @property {string} title
* @property {string} summary the section's first line of text, at most 240
* characters
*/
+/**
+ * One section of a topic's index, naming the package that wrote it: the
+ * topic's own, or the extension's that contributed it.
+ * @typedef {DocsIndexEntry & {package: string}} DocsIndexSection
+ */
+
/**
* astryx --json docs <topic> <section>
* @typedef {object} DocsDetailSectionResponse
* @property {'docs.detail.section'} type
+ * @property {string} package the npm package that wrote the section: the
+ * topic's own, or the extension's that contributed it
* @property {DocsReadSection & {links: DocsLinks}} data
* the section, and the moves from it: up to its topic's index, and across to
* the sections before and after it
@@ -135,6 +153,7 @@
* astryx --json docs <route>, for a namespace or a typed doc in the docs tree
* @typedef {object} DocsNodeResponse
* @property {'docs.node'} type
+ * @property {string} package the package that owns the node
* @property {DocsNode} data
*/
@@ -180,6 +199,7 @@
* @typedef {object} DocsNodeChild
* @property {string} route pass it to `astryx docs` to go one level down
* @property {string} name the last segment of its route
+ * @property {string} package the package that owns the child
* @property {string} kind
* @property {string} title
* @property {string} summary
diff --git a/packages/cli/api/docs/index/index.mjs b/packages/cli/api/docs/index/index.mjs
index 26b6a407f8..9595d20686 100644
--- a/packages/cli/api/docs/index/index.mjs
+++ b/packages/cli/api/docs/index/index.mjs
@@ -15,7 +15,7 @@
*/
import {indexView} from '../../../foundation/doc-compiler/lenses.mjs';
-import {resolveTopicDocs, topicLinks} from '../_adapter.mjs';
+import {resolveTopicDocs, sectionPackageOf, topicLinks} from '../_adapter.mjs';
/**
* @param {string} topic
@@ -29,12 +29,21 @@ import {resolveTopicDocs, topicLinks} from '../_adapter.mjs';
export async function index(topic, options = {}) {
const {node, entry, catalog} = await resolveTopicDocs(topic, options);
const view = indexView(node);
+ const sectionPackage = sectionPackageOf(entry, node);
/** @type {import('../docs.type.mjs').DocsIndex} */
const data = {
...view,
// A guide the docs tree places is read by its route, not its doc name.
name: entry.tree ? entry.name : view.name,
+ // Each section names the package that wrote it: the topic's own, or an
+ // extension's.
+ sections: view.sections.map(s => ({
+ id: s.id,
+ title: s.title,
+ package: sectionPackage(s.id),
+ summary: s.summary,
+ })),
links: await topicLinks(catalog, entry),
};
- return {type: 'docs.index', data};
+ return {type: 'docs.index', package: entry.package, data};
}
diff --git a/packages/cli/api/docs/index/index.test.mjs b/packages/cli/api/docs/index/index.test.mjs
index dcc17be134..104d4fd732 100644
--- a/packages/cli/api/docs/index/index.test.mjs
+++ b/packages/cli/api/docs/index/index.test.mjs
@@ -15,7 +15,8 @@ describe('docs.index leaf', () => {
const keys = res.data.sections.map(s => s.id);
expect(new Set(keys).size).toBe(keys.length);
for (const entry of res.data.sections) {
- expect(Object.keys(entry)).toEqual(['id', 'title', 'summary']);
+ expect(Object.keys(entry)).toEqual(['id', 'title', 'package', 'summary']);
+ expect(entry.package).toBe(res.package);
expect(entry.summary.length).toBeLessThanOrEqual(240);
}
}, SLOW);
diff --git a/packages/cli/api/docs/node/node.mjs b/packages/cli/api/docs/node/node.mjs
index 72cf3cb648..3c4219e77f 100644
--- a/packages/cli/api/docs/node/node.mjs
+++ b/packages/cli/api/docs/node/node.mjs
@@ -94,6 +94,7 @@ function childIdentity(child) {
return {
route: child.route,
name: child.route.slice(child.route.lastIndexOf('/') + 1),
+ package: child.provider,
kind: child.kind,
title: child.title,
summary: child.summary,
@@ -310,6 +311,8 @@ export async function node(route, options = {}) {
throw await unknownTopicError(route, found.catalog);
return {
type: 'docs.node',
+ // The docs tree names each node's npm package as its provider.
+ package: found.node.provider,
data: await nodeView(found.catalog, found.tree, found.node),
};
}
diff --git a/packages/cli/api/hook/_adapter.mjs b/packages/cli/api/hook/_adapter.mjs
index 859a00c12f..e8a2bde137 100644
--- a/packages/cli/api/hook/_adapter.mjs
+++ b/packages/cli/api/hook/_adapter.mjs
@@ -24,6 +24,9 @@ import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
+/** The package that owns Core's components, hooks, and codemods. */
+export {CORE_PROVIDER_ID as CORE_PACKAGE} from '../../foundation/identity/providers.mjs';
+
/**
* Locate the @astryxdesign/core package directory, or throw the same
* ERR_CORE_NOT_FOUND envelope the flat command threw. Shared by every hook leaf.
diff --git a/packages/cli/api/hook/detail/detail.mjs b/packages/cli/api/hook/detail/detail.mjs
index 70be1b6420..a812ebbac8 100644
--- a/packages/cli/api/hook/detail/detail.mjs
+++ b/packages/cli/api/hook/detail/detail.mjs
@@ -12,7 +12,7 @@
* @position api/hook/detail/detail.mjs — dispatched from ../hook.mjs
*/
-import {resolveCoreDir, resolveHookDoc} from '../_adapter.mjs';
+import {CORE_PACKAGE, resolveCoreDir, resolveHookDoc} from '../_adapter.mjs';
/**
* @param {string} name
@@ -22,5 +22,5 @@ import {resolveCoreDir, resolveHookDoc} from '../_adapter.mjs';
export async function detail(name, {cwd = process.cwd(), zh = false, lang = null} = {}) {
const coreDir = resolveCoreDir(cwd);
const docs = await resolveHookDoc(coreDir, name, {zh, lang});
- return {type: 'hook.detail', data: docs};
+ return {type: 'hook.detail', package: CORE_PACKAGE, data: docs};
}
diff --git a/packages/cli/api/hook/detail/params/params.mjs b/packages/cli/api/hook/detail/params/params.mjs
index 6db395e146..58d597aece 100644
--- a/packages/cli/api/hook/detail/params/params.mjs
+++ b/packages/cli/api/hook/detail/params/params.mjs
@@ -12,7 +12,7 @@
* @position api/hook/detail/params/params.mjs — dispatched from ../../hook.mjs
*/
-import {resolveCoreDir, resolveHookDoc} from '../../_adapter.mjs';
+import {CORE_PACKAGE, resolveCoreDir, resolveHookDoc} from '../../_adapter.mjs';
/**
* @param {string} name
@@ -22,5 +22,5 @@ import {resolveCoreDir, resolveHookDoc} from '../../_adapter.mjs';
export async function params(name, {cwd = process.cwd(), zh = false, lang = null} = {}) {
const coreDir = resolveCoreDir(cwd);
const docs = await resolveHookDoc(coreDir, name, {zh, lang});
- return {type: 'hook.detail.params', data: docs.params || []};
+ return {type: 'hook.detail.params', package: CORE_PACKAGE, data: docs.params || []};
}
diff --git a/packages/cli/api/hook/hook.type.mjs b/packages/cli/api/hook/hook.type.mjs
index 5d1b285831..03e164825f 100644
--- a/packages/cli/api/hook/hook.type.mjs
+++ b/packages/cli/api/hook/hook.type.mjs
@@ -39,6 +39,7 @@
*
* @typedef {object} HookListResponse
* @property {'hook.list'} type
+ * @property {string} package `@astryxdesign/core`, the only package that ships hooks.
* @property {HookListData} data
*/
@@ -59,6 +60,7 @@
* astryx --json hook <name>
* @typedef {object} HookDetailResponse
* @property {'hook.detail'} type
+ * @property {string} package `@astryxdesign/core`, the only package that ships hooks.
* @property {HookDoc} data
*/
@@ -66,6 +68,7 @@
* astryx --json hook <name> --params
* @typedef {object} HookDetailParamsResponse
* @property {'hook.detail.params'} type
+ * @property {string} package `@astryxdesign/core`, the only package that ships hooks.
* @property {HookParamDoc[]} data
*/
diff --git a/packages/cli/api/hook/list/list.mjs b/packages/cli/api/hook/list/list.mjs
index e2fe7ad03c..f4f5a936f8 100644
--- a/packages/cli/api/hook/list/list.mjs
+++ b/packages/cli/api/hook/list/list.mjs
@@ -9,7 +9,7 @@
* identical to the flat command's list branch.
*
* @input { cwd, category?, detail, zh, lang }
- * @output HookListResponse ({ type: 'hook.list', data: { detail, components } })
+ * @output HookListResponse ({ type: 'hook.list', package: CORE_PACKAGE, data: { detail, components } })
* @position api/hook/list/list.mjs — dispatched from ../hook.mjs
*/
@@ -20,7 +20,7 @@ import {
import {loadDocs} from '../../../foundation/discovery/component-loader.mjs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {resolveCoreDir} from '../_adapter.mjs';
+import {CORE_PACKAGE, resolveCoreDir} from '../_adapter.mjs';
/**
* @param {object} [options]
@@ -82,7 +82,7 @@ export async function list({
}
}
return {
- type: 'hook.list',
+ type: 'hook.list', package: CORE_PACKAGE,
data: {detail: 'compact', components: {[match[0]]: entries}},
};
}
@@ -111,14 +111,14 @@ export async function list({
}
}
return {
- type: 'hook.list',
+ type: 'hook.list', package: CORE_PACKAGE,
data: {detail: 'full', components: {[match[0]]: entries}},
};
}
// Default: names only
return {
- type: 'hook.list',
+ type: 'hook.list', package: CORE_PACKAGE,
data: {detail: 'names', components: {[match[0]]: match[1]}},
};
}
@@ -155,7 +155,7 @@ export async function list({
}
}
}
- return {type: 'hook.list', data: {detail: 'compact', components: result}};
+ return {type: 'hook.list', package: CORE_PACKAGE, data: {detail: 'compact', components: result}};
}
if (detail === 'full') {
@@ -186,9 +186,9 @@ export async function list({
}
}
}
- return {type: 'hook.list', data: {detail: 'full', components: result}};
+ return {type: 'hook.list', package: CORE_PACKAGE, data: {detail: 'full', components: result}};
}
// Default: names only
- return {type: 'hook.list', data: {detail: 'names', components: hooks}};
+ return {type: 'hook.list', package: CORE_PACKAGE, data: {detail: 'names', components: hooks}};
}
diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjs
index 50b7d88cc8..c3d0db34f5 100644
--- a/packages/cli/api/search/search.mjs
+++ b/packages/cli/api/search/search.mjs
@@ -80,6 +80,7 @@ import {
findComponentReadme,
resolveImportPath,
resolveIntegrationImportPath,
+ CORE_PACKAGE,
} from '../../foundation/discovery/component-discovery.mjs';
import {
discoverHooks,
@@ -130,9 +131,9 @@ import {setResultCoverage} from './coverage.mjs';
* @property {string} [_command] - The command that reads exactly this doc part.
* @property {string} [_parent] - The command that opens the level above a doc
* part: its topic's section list, or the docs-tree namespace it sits in.
- * @property {string} [_package] - The npm package that authored a docs-tree
- * doc part. Flat topics carry none: an extension's sections can come from
- * another package.
+ * @property {string} [_package] - The npm package that owns the candidate:
+ * Core's package for its components, hooks, and templates, the integration's
+ * for what it contributed, and for a doc part the package that wrote it.
* @property {string} [_displayName]
* @property {'page'|'block'} [_kind]
* @property {string} [_resultName]
@@ -967,6 +968,7 @@ async function gatherCoreComponents(coreDir) {
keywords,
description,
guidance,
+ _package: CORE_PACKAGE,
_import: resolveImportPath(coreDir, comp),
});
}
@@ -997,6 +999,7 @@ async function gatherIntegrationComponents(cwd) {
keywords: doc && Array.isArray(doc.keywords) ? doc.keywords : [],
description: doc ? doc.usage?.description || doc.description || '' : '',
guidance: guidanceFrom(doc),
+ _package: rec.package ?? integration.name,
// Exactly what `component` reports: a doc may state its own specifier
// (one entry point exporting several components), and only when it
// does not do we resolve the subpath against the owning package's
@@ -1123,6 +1126,7 @@ async function gatherHooks(coreDir) {
name: hookName,
keywords,
description,
+ _package: CORE_PACKAGE,
_import: importPath,
});
}
@@ -1484,6 +1488,7 @@ async function gatherTemplates(cwd) {
// short idea is not a direct match.
prose: t.keywords ?? [],
_displayName: t.name,
+ _package: t.package ?? CORE_PACKAGE,
_kind: t.type, // 'page' | 'block'
_resultName: t.dirName,
_commandName: commandName,
@@ -1536,6 +1541,7 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
const base = {
domain: c.domain,
name: c._resultName ?? c.name,
+ package: c._package,
score,
reason,
description: c.description || '',
@@ -1566,7 +1572,6 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
title: c._title,
command: c._command ?? `astryx docs ${c.name}`,
...(c._parent ? {parent: c._parent} : {}),
- ...(c._package ? {package: c._package} : {}),
};
break;
case 'template':
@@ -1582,7 +1587,6 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
...base,
displayName: c._displayName,
command: `astryx theme add ${c.name}`,
- ...(c._package ? {package: c._package} : {}),
};
break;
default:
diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjs
index 6fd6b2afb9..481723e13d 100644
--- a/packages/cli/api/search/search.type.mjs
+++ b/packages/cli/api/search/search.type.mjs
@@ -24,7 +24,7 @@
* @property {string} [import] - Import path — present for component and hook results.
* @property {string} [title] - Doc title — present for doc results.
* @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.
- * @property {string} [package] - The npm package that authored a doc result (for a section, the package whose file the section came from), or that ships a theme result.
+ * @property {string} package - The npm package that owns the result: `@astryxdesign/core` for a Core component, hook, or template, `@astryxdesign/cli` for a doc the CLI ships, or the integration package that contributed it. For a doc section, the package whose file the section came from.
* @property {string} [parent] - Command that opens the level above a doc result — its topic's section list for a section, the docs-tree namespace it sits in for a tree node — so a reader can see the siblings and open another.
* @property {string} [displayName] - Friendly display name — present for template and theme results.
* @property {'page' | 'block'} [kind] - Template kind (`page` | `block`) — present for template results.
diff --git a/packages/cli/api/swizzle/_adapter.mjs b/packages/cli/api/swizzle/_adapter.mjs
index b460a81388..abb2753c23 100644
--- a/packages/cli/api/swizzle/_adapter.mjs
+++ b/packages/cli/api/swizzle/_adapter.mjs
@@ -15,6 +15,9 @@ import {findCoreDir, listComponents} from '../../foundation/fs/paths.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';
+
/**
* Locate @astryxdesign/core for `cwd` and list its swizzlable components.
* @param {string} cwd
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index 49b7f1c101..ccdeb2b0f7 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -359,7 +359,7 @@ export async function swizzleCopy(component, options = {}) {
usesStyleX,
};
if (feedback) data.feedback = feedback;
- return {type: 'swizzle.copy', data};
+ return {type: 'swizzle.copy', package: data.package, data};
}
/**
diff --git a/packages/cli/api/swizzle/list/list.mjs b/packages/cli/api/swizzle/list/list.mjs
index d68be19004..23b879e472 100644
--- a/packages/cli/api/swizzle/list/list.mjs
+++ b/packages/cli/api/swizzle/list/list.mjs
@@ -8,7 +8,7 @@
* shared seam. All human prose / usage hints live in the CLI renderer.
*/
-import {resolveCore} from '../_adapter.mjs';
+import {CORE_PACKAGE, resolveCore} from '../_adapter.mjs';
/**
* List swizzlable components discoverable from `cwd`'s @astryxdesign/core.
@@ -17,5 +17,5 @@ import {resolveCore} from '../_adapter.mjs';
*/
export function swizzleList(cwd = process.cwd()) {
const {components} = resolveCore(cwd);
- return {type: 'swizzle.list', data: components};
+ return {type: 'swizzle.list', package: CORE_PACKAGE, data: components};
}
diff --git a/packages/cli/api/swizzle/swizzle.type.mjs b/packages/cli/api/swizzle/swizzle.type.mjs
index fa0a1cc4e2..74082cadc4 100644
--- a/packages/cli/api/swizzle/swizzle.type.mjs
+++ b/packages/cli/api/swizzle/swizzle.type.mjs
@@ -11,6 +11,7 @@
*
* @typedef {object} SwizzleListResponse
* @property {'swizzle.list'} type
+ * @property {string} package `@astryxdesign/core`, the package the listed components come from.
* @property {string[]} data
*/
@@ -27,6 +28,7 @@
*
* @typedef {object} SwizzleCopyResponse
* @property {'swizzle.copy'} type
+ * @property {string} package Owner package the component source was copied from (as `data.package`).
* @property {object} data
* @property {string} data.component
* @property {string} data.package Owner package the component source was copied from.
diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs
index 86d98d864f..a21990247d 100644
--- a/packages/cli/api/template/copy/copy.mjs
+++ b/packages/cli/api/template/copy/copy.mjs
@@ -18,7 +18,7 @@ import {
} from '../../../foundation/fs/path-safety.mjs';
import {AstryxError, writeFailed} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {replaceDemoMedia} from '../../../foundation/discovery/template-adapter.mjs';
+import {pkgOf, replaceDemoMedia} from '../../../foundation/discovery/template-adapter.mjs';
/**
* Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and
@@ -96,6 +96,7 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {
const relOutput = path.relative(cwd, outputDir) || '.';
return {
type: 'template.copy',
+ package: pkgOf(match),
data: {
template: match.dirName,
outputDir: relOutput,
diff --git a/packages/cli/api/template/show/show.mjs b/packages/cli/api/template/show/show.mjs
index 94dd41c24a..f18fd319a3 100644
--- a/packages/cli/api/template/show/show.mjs
+++ b/packages/cli/api/template/show/show.mjs
@@ -13,6 +13,7 @@ import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {
extractComponents,
+ pkgOf,
replaceDemoMedia,
} from '../../../foundation/discovery/template-adapter.mjs';
@@ -39,6 +40,7 @@ export function templateShow(match) {
return {
type: 'template.show',
+ package: pkgOf(match),
data: {
template: match.dirName,
description: match.description,
diff --git a/packages/cli/api/template/skeleton/skeleton.mjs b/packages/cli/api/template/skeleton/skeleton.mjs
index 682e6e7661..26461a7530 100644
--- a/packages/cli/api/template/skeleton/skeleton.mjs
+++ b/packages/cli/api/template/skeleton/skeleton.mjs
@@ -11,7 +11,7 @@
import * as fs from 'node:fs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {extractComponents} from '../../../foundation/discovery/template-adapter.mjs';
+import {extractComponents, pkgOf} from '../../../foundation/discovery/template-adapter.mjs';
const STRUCTURAL = new Set([
'AppShell',
@@ -245,6 +245,7 @@ export function templateSkeleton(match, templates) {
const src = fs.readFileSync(match.filePath, 'utf-8');
return {
type: 'template.skeleton',
+ package: pkgOf(match),
data: {
template: match.dirName,
description: match.description,
diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs
index 3c06aff992..0058b9f521 100644
--- a/packages/cli/api/template/template.mjs
+++ b/packages/cli/api/template/template.mjs
@@ -46,6 +46,7 @@ export {
findRelatedBlocks,
findShowcase,
extractComponents,
+ pkgOf,
} from '../../foundation/discovery/template-adapter.mjs';
/**
diff --git a/packages/cli/api/template/template.type.mjs b/packages/cli/api/template/template.type.mjs
index a6405f6f62..8f0d1973b2 100644
--- a/packages/cli/api/template/template.type.mjs
+++ b/packages/cli/api/template/template.type.mjs
@@ -47,6 +47,7 @@
* astryx --json template <name>
* @typedef {object} TemplateShowResponse
* @property {'template.show'} type
+ * @property {string} package The npm package that owns the template.
* @property {object} data
* @property {string} data.template
* @property {string} data.description
@@ -60,6 +61,7 @@
* astryx --json template <name> --skeleton
* @typedef {object} TemplateSkeletonResponse
* @property {'template.skeleton'} type
+ * @property {string} package The npm package that owns the template.
* @property {object} data
* @property {string} data.template
* @property {string} data.description
@@ -71,6 +73,7 @@
* astryx --json template <name> [path]
* @typedef {object} TemplateCopyResponse
* @property {'template.copy'} type
+ * @property {string} package The npm package that owns the template.
* @property {object} data
* @property {string} data.template
* @property {string} data.outputDir
diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjs
index abd92ebafe..e894559775 100644
--- a/packages/cli/api/upgrade/_adapter.mjs
+++ b/packages/cli/api/upgrade/_adapter.mjs
@@ -41,6 +41,9 @@ import {resolveProviders} from '../../foundation/integrations/provider-resolutio
import {warnOnIntegrationIssues} from '../../foundation/integrations/integration-warnings.mjs';
import {logger} from '../logger.mjs';
+/** The package that owns Core's components, hooks, and codemods. */
+export {CORE_PROVIDER_ID as CORE_PACKAGE} from '../../foundation/identity/providers.mjs';
+
// Re-exported for the run leaf's lightweight agent-docs inspection path
// (config_fixable short-circuit, where the full render cannot load config).
export {inspectAgentDocs};
diff --git a/packages/cli/api/upgrade/list/list.mjs b/packages/cli/api/upgrade/list/list.mjs
index 8dad65bb62..717759815b 100644
--- a/packages/cli/api/upgrade/list/list.mjs
+++ b/packages/cli/api/upgrade/list/list.mjs
@@ -8,7 +8,7 @@
* through the shared `logger`. No cwd, no version detection, no side effects.
*/
-import {collectAllCodemods} from '../_adapter.mjs';
+import {CORE_PACKAGE, collectAllCodemods} from '../_adapter.mjs';
import {logger} from '../../logger.mjs';
import {toAscii} from '../../../assets/codemods/term-log.mjs';
@@ -18,13 +18,19 @@ import {toAscii} from '../../../assets/codemods/term-log.mjs';
*/
export async function list() {
const codemods = await collectAllCodemods();
- logger.log('Available codemods:');
+ logger.log(`Available codemods from ${CORE_PACKAGE}:`);
for (const {name, title, pr, optional} of codemods) {
logger.log(` ${name} - ${toAscii(title)}${optional ? ' (optional)' : ''} (${pr})`);
}
logger.log('Done\n');
return {
type: 'upgrade.list',
- data: codemods.map(({name, title, version, optional}) => ({name, title, version, optional})),
+ data: codemods.map(({name, title, version, optional}) => ({
+ name,
+ package: CORE_PACKAGE,
+ title,
+ version,
+ optional,
+ })),
};
}
diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjs
index 0f7a6419ae..40f26f47b5 100644
--- a/packages/cli/api/upgrade/upgrade.type.mjs
+++ b/packages/cli/api/upgrade/upgrade.type.mjs
@@ -23,6 +23,7 @@
/**
* @typedef {object} UpgradeListEntry
* @property {string} name
+ * @property {string} package The npm package that ships the codemod.
* @property {string} title
* @property {string} version
* @property {boolean} optional True when the codemod runs only if named with `--codemod`.
diff --git a/packages/cli/clients/cli/commands/build.mjs b/packages/cli/clients/cli/commands/build.mjs
index 99252eca90..4321c12afa 100644
--- a/packages/cli/clients/cli/commands/build.mjs
+++ b/packages/cli/clients/cli/commands/build.mjs
@@ -169,6 +169,7 @@ export function registerBuild(program) {
const full = {
fields: [
'name',
+ 'package',
'domain',
'displayName',
'score',
@@ -220,10 +221,10 @@ export function registerBuild(program) {
start,
verbose
? {
- fields: ['name', 'displayName', 'description', 'command'],
+ fields: ['name', 'package', 'displayName', 'description', 'command'],
format: {command: formatCliCommand},
}
- : brief(['name', 'description', 'command']),
+ : brief(['name', 'package', 'description', 'command']),
),
);
if (start.alternatives.length) {
@@ -234,7 +235,7 @@ export function registerBuild(program) {
),
records(
start.alternatives,
- verbose ? full : brief(['name', 'description', 'command']),
+ verbose ? full : brief(['name', 'package', 'description', 'command']),
),
);
}
@@ -249,7 +250,7 @@ export function registerBuild(program) {
'Page templates keyword search matched, best first.',
)
: text(
- `Keyword search matched these page templates: ${pages.map(p => p.name).join(', ')}.`,
+ `Keyword search matched these page templates: ${pages.map(p => `${p.name} (${p.package})`).join(', ')}.`,
),
);
if (verbose) out.push(records(pages, full));
@@ -262,7 +263,7 @@ export function registerBuild(program) {
),
records(
shown(blocks),
- verbose ? full : brief(['name', 'description']),
+ verbose ? full : brief(['name', 'package', 'description']),
),
);
}
@@ -275,7 +276,7 @@ export function registerBuild(program) {
? [
records(
shown(domain),
- verbose ? full : brief(['name', 'description']),
+ verbose ? full : brief(['name', 'package', 'description']),
),
]
: []),
diff --git a/packages/cli/clients/cli/commands/build.text-fields.test.mjs b/packages/cli/clients/cli/commands/build.text-fields.test.mjs
index 79f71f01c4..dbdea3f528 100644
--- a/packages/cli/clients/cli/commands/build.text-fields.test.mjs
+++ b/packages/cli/clients/cli/commands/build.text-fields.test.mjs
@@ -75,7 +75,7 @@ describe('build kit text fields mirror the JSON keys', () => {
expect(data.pages.length).toBeGreaterThan(0);
const human = await runCli(['build', 'contact form'], REPO);
expect(human.stdout).toContain(
- `Keyword search matched these page templates: ${data.pages.map(p => p.name).join(', ')}.`,
+ `Keyword search matched these page templates: ${data.pages.map(p => `${p.name} (${p.package})`).join(', ')}.`,
);
}, SLOW);
});
diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjs
index a649703809..193c7c0e60 100644
--- a/packages/cli/clients/cli/commands/component/index.mjs
+++ b/packages/cli/clients/cli/commands/component/index.mjs
@@ -104,7 +104,7 @@ function componentDetailBlocks(result, requestedName, detail, themeData) {
switch (result.type) {
case 'component.detail': {
/** @type {import('../../formatters/index.mjs').Block[]} */
- const out = [];
+ const out = [record({package: result.package})];
if (result.data.parentDoc) {
out.push(record(result.data, {fields: ['parentDoc']}));
}
@@ -129,24 +129,37 @@ function componentDetailBlocks(result, requestedName, detail, themeData) {
return out;
}
case 'component.detail.props':
- return [code(formatProps({props: result.data}, resolvedName))];
+ return [
+ record({package: result.package}),
+ code(formatProps({props: result.data}, resolvedName)),
+ ];
case 'component.detail.source':
case 'component.detail.showcase':
return [code(result.data.source)];
case 'component.detail.blocks': {
const {showcase, examples, related} = result.data;
+ // A block another package owns says which one.
+ /** @param {{package: string}} block @param {string} label */
+ const owned = (block, label) =>
+ block.package === result.package ? label : `${label} (${block.package})`;
/** @type {import('../../formatters/index.mjs').Block[]} */
- const out = [];
+ const out = [record({package: result.package})];
if (showcase) {
out.push(
section('Showcase'),
- record(showcase, {fields: ['displayName', 'description']}),
+ record(
+ {...showcase, displayName: owned(showcase, showcase.displayName)},
+ {fields: ['displayName', 'description']},
+ ),
);
}
if (examples.length > 0) {
out.push(
section('Examples'),
- records(examples, {fields: ['name', 'description']}),
+ records(
+ examples.map(block => ({...block, name: owned(block, block.name)})),
+ {fields: ['name', 'description']},
+ ),
);
}
if (related.length > 0) {
@@ -154,7 +167,7 @@ function componentDetailBlocks(result, requestedName, detail, themeData) {
section(
`Related: ${related.length} blocks that use ${result.data.component}`,
),
- list(related.map(block => block.name)),
+ list(related.map(block => owned(block, block.name))),
);
}
if (!showcase && examples.length === 0 && related.length === 0) {
@@ -340,6 +353,12 @@ export function registerComponent(program) {
out.push(
record(row, {fields: ['selector', 'status']}),
section('Result'),
+ // A batch is not piped as one file, so a source row names its
+ // package here; the other rows name it themselves.
+ ...(row.result.type === 'component.detail.source' ||
+ row.result.type === 'component.detail.showcase'
+ ? [record({package: row.result.package})]
+ : []),
...componentDetailBlocks(
row.result,
row.selector,
@@ -377,6 +396,15 @@ export function registerComponent(program) {
case 'component.detail.source':
case 'component.detail.showcase':
case 'component.detail.blocks':
+ // Source and showcase print the file alone so it pipes byte for
+ // byte; the package they come from goes to stderr (cli-surface
+ // INV28).
+ if (
+ result.type === 'component.detail.source' ||
+ result.type === 'component.detail.showcase'
+ ) {
+ console.error(`package: ${result.package}`);
+ }
emit(
...componentDetailBlocks(
result,
diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjs
index 556be9be7e..d7367809fd 100644
--- a/packages/cli/clients/cli/commands/docs.mjs
+++ b/packages/cli/clients/cli/commands/docs.mjs
@@ -34,6 +34,7 @@ import {
text,
code,
wrapText,
+ record,
} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
@@ -247,17 +248,22 @@ function docsBelow(count) {
* it sits below the read's namespace.
* @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild[]} children
* @param {string} root
+ * @param {string} owner the package that owns the read's namespace
* @returns {{name: string, summary: string}[]}
*/
-function treeRows(children, root) {
+function treeRows(children, root, owner) {
return children.flatMap(child => [
{
- name: belowRoot(child.route, root),
+ // A child another package owns says which one.
+ name:
+ child.package === owner
+ ? belowRoot(child.route, root)
+ : `${belowRoot(child.route, root)} (${child.package})`,
summary: child.childCount
- ? `${childRow(child).summary} (${docsBelow(child.childCount)})`
- : childRow(child).summary,
+ ? `${childRow(child, owner).summary} (${docsBelow(child.childCount)})`
+ : childRow(child, owner).summary,
},
- ...(child.slots ?? []).flatMap(slot => treeRows(slot.children, root)),
+ ...(child.slots ?? []).flatMap(slot => treeRows(slot.children, root, owner)),
]);
}
@@ -269,12 +275,16 @@ function treeRows(children, root) {
* @param {number} level
* @param {string} root
* @param {string} run
+ * @param {string} owner the package that owns the read's namespace
* @returns {string}
*/
-function formatTreeChild(child, detail, level, root, run) {
- const parts = [
- `${treeHeading(child.title, level)} (${belowRoot(child.route, root)})`,
- ];
+function formatTreeChild(child, detail, level, root, run, owner) {
+ // A child another package owns says which one.
+ const place =
+ child.package === owner
+ ? belowRoot(child.route, root)
+ : `${belowRoot(child.route, root)}, ${child.package}`;
+ const parts = [`${treeHeading(child.title, level)} (${place})`];
if (
child.summary &&
(child.kind === 'namespace' || child.kind === 'generic')
@@ -296,7 +306,7 @@ function formatTreeChild(child, detail, level, root, run) {
for (const slot of child.slots ?? []) {
parts.push(
...slot.children.map(each =>
- formatTreeChild(each, detail, level + 1, root, run),
+ formatTreeChild(each, detail, level + 1, root, run, owner),
),
);
}
@@ -332,6 +342,7 @@ function emitTree(node, detail, childDetail, run) {
const root = allBelow ? node.route : '';
emit(
section(node.title, wrapText(node.summary)),
+ record({package: node.package}),
...(node.content?.length
? [
text(
@@ -354,13 +365,15 @@ function emitTree(node, detail, childDetail, run) {
? []
: [section(slot.title)]),
childDetail === 'brief'
- ? records(treeRows(slot.children, root), {
+ ? records(treeRows(slot.children, root, node.package), {
fields: ['name', 'summary'],
layout: 'inline',
})
: code(
slot.children
- .map(child => formatTreeChild(child, childDetail, 2, root, run))
+ .map(child =>
+ formatTreeChild(child, childDetail, 2, root, run, node.package),
+ )
.join('\n\n'),
),
]),
@@ -401,20 +414,27 @@ function linkLines(links) {
* A topic's section index: what the topic is, one line per section with the
* key to read it by, and how to read further.
* @param {import('../../../api/docs/docs.type.mjs').DocsIndex} index
+ * @param {string} owner the package that owns the topic
* @param {string} run
*/
-function emitIndex(index, run) {
+function emitIndex(index, owner, run) {
emit(
section(
index.title,
index.description ? wrapText(index.description) : undefined,
),
+ record({package: owner}),
// Summaries wrap rather than being cut: the summary is how a reader picks
- // the one section to open.
- records(index.sections, {
- fields: ['id', 'title', 'summary'],
- layout: 'inline',
- }),
+ // the one section to open. A section another package wrote says which one.
+ records(
+ index.sections.map(s =>
+ s.package === owner ? s : {...s, title: `${s.title} (${s.package})`},
+ ),
+ {
+ fields: ['id', 'title', 'summary'],
+ layout: 'inline',
+ },
+ ),
text(
[
`Read one section: ${run} docs ${index.name} <section>`,
@@ -431,15 +451,17 @@ function emitIndex(index, run) {
* template`). Typed docs keep a distinct title when it carries the real symbol
* name (`assert-response assertResponse()`).
* @param {import('../../../api/docs/docs.type.mjs').DocsNodeChild} child
+ * @param {string} owner the package that owns the namespace
* @returns {{name: string, summary: string}}
*/
-function childRow(child) {
+function childRow(child, owner) {
const titleAddsIdentity =
child.kind !== 'namespace' &&
child.kind !== 'generic' &&
child.title !== child.name;
return {
- name: child.name,
+ // A child another package owns says which one.
+ name: child.package === owner ? child.name : `${child.name} (${child.package})`,
summary: titleAddsIdentity
? `${child.title}: ${child.summary}`
: child.summary,
@@ -458,6 +480,7 @@ function emitNode(node, detail, run) {
if (node.kind === 'namespace') {
emit(
section(node.title, wrapText(node.summary)),
+ record({package: node.package}),
// A namespace may author intro `blocks`; they render above its children.
...(node.content?.length
? [
@@ -474,7 +497,7 @@ function emitNode(node, detail, run) {
...(node.slots.length === 1 && slot.title === node.title
? []
: [section(slot.title)]),
- records(slot.children.map(childRow), {
+ records(slot.children.map(child => childRow(child, node.package)), {
fields: ['name', 'summary'],
layout: 'inline',
}),
@@ -495,6 +518,7 @@ function emitNode(node, detail, run) {
return;
}
emit(
+ record({package: node.package}),
code(formatSection({title: node.title, content: node.content}, detail)),
text(linkLines(node.links).join('\n')),
);
@@ -655,13 +679,28 @@ export function registerDocs(program) {
}
case 'docs.index': {
- emitIndex(result.data, run);
+ emitIndex(result.data, result.package, run);
break;
}
case 'docs.detail': {
+ const owner = result.package;
emit(
- code(formatReferenceFull(result.data, detail)),
+ record({package: owner}),
+ code(
+ formatReferenceFull(
+ {
+ ...result.data,
+ // A section another package wrote says which one.
+ sections: result.data.sections.map(s =>
+ s.package === owner
+ ? s
+ : {...s, title: `${s.title} (${s.package})`},
+ ),
+ },
+ detail,
+ ),
+ ),
text(linkLines(result.data.links).join('\n')),
);
break;
@@ -671,6 +710,7 @@ export function registerDocs(program) {
// One section ends with its moves: up to its topic's index, and to
// the sections before and after it.
emit(
+ record({package: result.package}),
code(formatSection(result.data, detail)),
text(linkLines(result.data.links).join('\n')),
);
diff --git a/packages/cli/clients/cli/commands/hook/index.mjs b/packages/cli/clients/cli/commands/hook/index.mjs
index 8fc7f65eb8..41613d93f6 100644
--- a/packages/cli/clients/cli/commands/hook/index.mjs
+++ b/packages/cli/clients/cli/commands/hook/index.mjs
@@ -14,7 +14,7 @@ import {
} from '../../lib/hook-format.mjs';
import {getCliInvocation} from '../../../../foundation/env/package-manager.mjs';
import {jsonOut} from '../../../../foundation/response/json.mjs';
-import {emit, section, text, list, records, code} from '../../formatters/index.mjs';
+import {emit, section, text, list, records, code, record} from '../../formatters/index.mjs';
import {cliError} from '../../lib/cli-error.mjs';
import {defineCommand} from '../../lib/define-command.mjs';
import {resultSet} from '../../../../foundation/debug/index.mjs';
@@ -103,6 +103,7 @@ export function registerHook(program) {
// ── Text output ────────────────────────────────────────────
switch (result.type) {
case 'hook.list': {
+ emit(record({package: result.package}));
// One list type across all three detail levels; the depth is carried
// in result.data.detail and the grouped map in result.data.components.
if (result.data.detail === 'full') {
@@ -172,6 +173,7 @@ export function registerHook(program) {
// under `component <name> --blocks`.
const related = result.data.relatedComponents ?? [];
emit(
+ record({package: result.package}),
code(doc),
related.length > 0 &&
text(
@@ -182,7 +184,10 @@ export function registerHook(program) {
}
case 'hook.detail.params': {
- emit(code(formatHookParams({params: result.data, name})));
+ emit(
+ record({package: result.package}),
+ code(formatHookParams({params: result.data, name})),
+ );
break;
}
}
diff --git a/packages/cli/clients/cli/commands/swizzle.mjs b/packages/cli/clients/cli/commands/swizzle.mjs
index b4ba0bc519..075c992668 100644
--- a/packages/cli/clients/cli/commands/swizzle.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.mjs
@@ -11,7 +11,7 @@
*/
import {jsonOut} from '../../../foundation/response/json.mjs';
-import {emit, section, list, text, WARN} from '../formatters/index.mjs';
+import {emit, section, list, text, WARN, record} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
import {swizzle as swizzleApi} from '../../../api/swizzle/swizzle.mjs';
@@ -60,6 +60,7 @@ export function registerSwizzle(program) {
if (result.type === 'swizzle.list') {
const components = result.data;
emit(
+ record({package: result.package}),
section('Available components'),
list(components),
text(`Usage: ${run} swizzle <component>`),
diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjs
index af3f233df0..b058d3ab76 100644
--- a/packages/cli/clients/cli/commands/template.mjs
+++ b/packages/cli/clients/cli/commands/template.mjs
@@ -5,7 +5,7 @@
*/
import {jsonOut} from '../../../foundation/response/json.mjs';
-import {emit, section, text, records, code} from '../formatters/index.mjs';
+import {emit, section, text, records, code, record} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {template as templateApi} from '../../../api/template/template.mjs';
import {Project} from '../../../foundation/config/project.mjs';
@@ -146,6 +146,7 @@ export function registerTemplate(program) {
case 'template.skeleton': {
const {template: tName, description, components, skeleton} = result.data;
emit(
+ record({package: result.package}),
text(
`# ${tName}${description ? ' — ' + description : ''}\n` +
`# Components: ${components.join(', ')}`,
@@ -156,10 +157,12 @@ export function registerTemplate(program) {
}
case 'template.show': {
- // Source must survive piping byte-for-byte, so the note about
- // replaced demo media goes to stderr, in the copy receipt's words.
- // (Text mode only: --json returned above with the count in data.)
+ // Source must survive piping byte-for-byte, so the package it comes
+ // from (cli-surface INV28) and the note about replaced demo media go
+ // to stderr, the note in the copy receipt's words. (Text mode only:
+ // --json returned above with both in the envelope.)
const {source, demoMediaReplaced} = result.data;
+ console.error(`package: ${result.package}`);
emit(code(source));
if (demoMediaReplaced > 0) {
console.error(
@@ -175,6 +178,7 @@ export function registerTemplate(program) {
const file = `${outputDir}/${fileName}`;
emit(
text(`Copied template to ${file}`),
+ record({package: result.package}),
demoMediaReplaced > 0 &&
text(
`Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${file}: ` +
diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
index 6b0215e8cf..6bd9358e66 100644
--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs
+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
@@ -35,6 +35,17 @@ import {runCli} from '../../../test-utils/run-cli.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, '../../../../..');
+/**
+ * Response types whose text output is the artifact's source, printed byte for
+ * byte so it can be piped (spec cli-surface INV28). Their JSON still names the
+ * package; their text does not.
+ */
+const VERBATIM_TYPES = new Set([
+ 'component.detail.source',
+ 'component.detail.showcase',
+ 'template.show',
+]);
+
// ─── Helpers ────────────────────────────────────────────────────────────────
/**
@@ -561,6 +572,15 @@ describe('text-json-parity', () => {
expect(run.textStatus).toBe(run.jsonStatus);
});
+ // spec cli-surface INV28: text names the package the envelope names.
+ // Verbatim source output prints only the source, so a pipe gets the
+ // file byte for byte.
+ it('text names the package the JSON envelope names', () => {
+ if (run.json?.package === undefined) return;
+ if (VERBATIM_TYPES.has(run.json.type)) return;
+ expect(run.text).toContain(run.json.package);
+ });
+
if (!tc.skipFieldChecks && !tc.errorExpected) {
it('every text record key exists in the JSON data', () => {
if (!run.json?.data) return;
@@ -569,6 +589,8 @@ describe('text-json-parity', () => {
if (run.json.meta) {
for (const k of jsonLeafKeys(run.json.meta)) jsonKeys.add(k);
}
+ // The envelope's own `package` (spec cli-surface INV28) is JSON too.
+ if (run.json.package !== undefined) jsonKeys.add('package');
const violations = [];
for (const key of textKeys.keys()) {
if (!jsonKeys.has(key)) {
diff --git a/packages/cli/clients/cli/commands/upgrade.mjs b/packages/cli/clients/cli/commands/upgrade.mjs
index 2e2ea0092f..54d1a15bce 100644
--- a/packages/cli/clients/cli/commands/upgrade.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.mjs
@@ -69,7 +69,7 @@ export function registerUpgrade(program) {
emit(
section('Available codemods'),
records(result.data, {
- fields: ['name', 'title', 'version', 'optional'],
+ fields: ['name', 'package', 'title', 'version', 'optional'],
}),
);
}
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index a1442822a1..4e3fbcf597 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -366,7 +366,7 @@ export async function createProgram() {
)
.option(
'--json',
- 'Output as typed JSON. Success envelope: { apiVersion, type, data, meta? }. Error envelope: { apiVersion, error, code, suggestions? }.',
+ 'Output as typed JSON. Success envelope: { apiVersion, type, package?, data, meta? }. Error envelope: { apiVersion, error, code, suggestions? }.',
)
.addHelpCommand('help', 'Show all commands')
.action((options, cmd) => {
diff --git a/packages/cli/foundation/discovery/docs-output-budget.mjs b/packages/cli/foundation/discovery/docs-output-budget.mjs
index 53f40f50fb..7d1a953ea8 100644
--- a/packages/cli/foundation/discovery/docs-output-budget.mjs
+++ b/packages/cli/foundation/discovery/docs-output-budget.mjs
@@ -26,7 +26,8 @@ export function docPayloadBytes(payload) {
}
/**
- * @param {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links'> | import('../../api/docs/docs.type.mjs').DocsIndex} index
+ * @param {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links' | 'sections'> & {sections: import('../../api/docs/docs.type.mjs').DocsIndexEntry[], links?: import('../../api/docs/docs.type.mjs').DocsLinks}} index
+ * an index, with or without its links; its sections may or may not name their package
* @returns {number}
*/
export function docsIndexBytes(index) {
diff --git a/packages/cli/foundation/discovery/docs-section-key.mjs b/packages/cli/foundation/discovery/docs-section-key.mjs
index 77a396a58a..1dc4670cb8 100644
--- a/packages/cli/foundation/discovery/docs-section-key.mjs
+++ b/packages/cli/foundation/discovery/docs-section-key.mjs
@@ -306,7 +306,7 @@ export function sectionSummary(section, max = SECTION_SUMMARY_MAX) {
* The index a topic-only read returns: what the topic is, and one entry per
* section with the key to read it by.
* @param {{name: string, title: string, description: string, sections: any[]}} doc
- * @returns {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links'>}
+ * @returns {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links' | 'sections'> & {sections: import('../../api/docs/docs.type.mjs').DocsIndexEntry[]}}
*/
export function buildDocsIndexData(doc) {
return {
diff --git a/packages/cli/foundation/doc-compiler/lenses.mjs b/packages/cli/foundation/doc-compiler/lenses.mjs
index 6597807450..7345b95caf 100644
--- a/packages/cli/foundation/doc-compiler/lenses.mjs
+++ b/packages/cli/foundation/doc-compiler/lenses.mjs
@@ -64,7 +64,7 @@ export function detailView(node) {
* `docs.index`: what the topic is, and each section's key, title and summary.
* The index leaf adds the moves.
* @param {import('./compile.mjs').CompiledReferenceNode} node
- * @returns {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links'>}
+ * @returns {Omit<import('../../api/docs/docs.type.mjs').DocsIndex, 'links' | 'sections'> & {sections: import('../../api/docs/docs.type.mjs').DocsIndexEntry[]}}
*/
export function indexView(node) {
return buildDocsIndexData(node.doc);
diff --git a/packages/cli/foundation/response/base.d.ts b/packages/cli/foundation/response/base.d.ts
index 9d26b40008..eafaf16282 100644
--- a/packages/cli/foundation/response/base.d.ts
+++ b/packages/cli/foundation/response/base.d.ts
@@ -44,15 +44,21 @@ export interface CLIUnsupportedError {
}
/**
- * A success response: a `type` discriminator, its `data` payload, and an
- * optional `meta` sidecar (emitted as a sibling of `data`, never merged in).
- * `--json` prints it with `apiVersion` added (see `parseResponse`).
+ * A success response: a `type` discriminator, the `package` that owns what the
+ * response is about, its `data` payload, and an optional `meta` sidecar
+ * (emitted as a sibling of `data`, never merged in). `--json` prints it with
+ * `apiVersion` added (see `parseResponse`).
+ *
+ * `package` is present when the response is about one thing: one component,
+ * one doc, one template. A response that lists things from more than one
+ * package leaves it out, and each listed item names its own `package`.
*
* Structural by design — there is no central union of every response `type`.
* A specific command narrows `data` via its own return type.
*/
export interface CLIResponse {
type: string;
+ package?: string;
data: unknown;
meta?: Record<string, unknown>;
}
diff --git a/packages/cli/foundation/response/json.mjs b/packages/cli/foundation/response/json.mjs
index 9424d453ea..47f74f20b0 100644
--- a/packages/cli/foundation/response/json.mjs
+++ b/packages/cli/foundation/response/json.mjs
@@ -7,7 +7,7 @@
* The contract has four guarantees, enforced here and in index.mjs:
*
* 1. EVERY emission in --json mode is a single valid JSON envelope.
- * Success: { apiVersion, type, data }
+ * Success: { apiVersion, type, package?, data, meta? }
* Error: { apiVersion, error, code, suggestions? }
* The `code` is a stable, machine-readable identifier (see
* error-codes.mjs). Consumers should branch on `code`, never on the
@@ -87,16 +87,20 @@ export function humanWarn(...args) {
* Output a JSON response envelope and mark it handled.
*
* Structural serializer: pass a command/API result straight through as
- * `{type, data, meta?}`. There is no central response union — the correctness
- * of the `type` discriminator is guaranteed at each API function's `@returns`
- * (that's the fractal source-of-truth point), not by a map in this file.
+ * `{type, package?, data, meta?}`. There is no central response union — the
+ * correctness of the `type` discriminator is guaranteed at each API function's
+ * `@returns` (that's the fractal source-of-truth point), not by a map in this
+ * file. `package` names the npm package that owns the one thing the result is
+ * about (spec cli-surface INV28); it is written directly after `type`.
*
- * @param {{type: string, data: unknown, meta?: Record<string, unknown>}} response
+ * @param {{type: string, package?: string, data: unknown, meta?: Record<string, unknown>}} response
* @returns {void}
*/
export function jsonOut(response) {
/** @type {any} */
- const envelope = {apiVersion: API_VERSION, type: response.type, data: response.data};
+ const envelope = {apiVersion: API_VERSION, type: response.type};
+ if (response.package !== undefined) envelope.package = response.package;
+ envelope.data = response.data;
if (response.meta !== undefined) envelope.meta = response.meta;
// Serialize BEFORE marking handled. If JSON.stringify throws (a circular
// reference or a BigInt in `data` — an author bug in a command's return
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 92dd6c7396..a5813ba9e6 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -36,7 +36,7 @@ export const doc = {
{
value: 'component.list',
description:
- "The component catalog grouped by component group (each component's group field): `detail` (the level: names | compact | full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries, or a full ComponentDoc per entry.",
+ "The component catalog grouped by component group (each component's group field): `detail` (the level: names | compact | full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package.",
},
{
value: 'component.batch',
@@ -46,25 +46,25 @@ export const doc = {
{
value: 'component.detail',
description:
- "One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc).",
+ "One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner.",
},
{
value: 'component.detail.props',
- description: "Just one component's props table (ComponentPropDoc[]).",
+ description: "Just one component's props table (ComponentPropDoc[]). The envelope's package names the npm package that owns the component.",
},
{
value: 'component.detail.source',
- description: "One component's source file, as {component, source}.",
+ description: "One component's source file, as {component, source}. The envelope's package names the npm package that owns the component.",
},
{
value: 'component.detail.showcase',
description:
- "One component's showcase example, as {component, aspectRatio, source}.",
+ "One component's showcase example, as {component, aspectRatio, source}. The envelope's package names the npm package that owns the component.",
},
{
value: 'component.detail.blocks',
description:
- "One component's example blocks, as {component, showcase, examples, related} of BlockEntry.",
+ "One component's example blocks, as {component, showcase, examples, related} of BlockEntry ({name, package, displayName, description, isShowcase, category}); each block names the package that owns it, and the envelope's package names the component's owner.",
},
// docs
@@ -76,22 +76,22 @@ export const doc = {
{
value: 'docs.detail',
description:
- "One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there).",
+ "One topic's full ReferenceDoc (the JSON read of a topic, --full, --dense, or a topic with one section), with token-ref blocks inlined and each section naming the package that wrote it, plus links ({up, previous, next}: the commands that open the level it sits in and its neighbors there).",
},
{
value: 'docs.index',
description:
- "One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, summary} (pass the id as the section argument; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there).",
+ "One topic's section index, the text read of a topic with more than one section (and --index): the topic's name, title, and description, plus sections, each {id, title, package, summary} (pass the id as the section argument; package is the npm package that wrote the section; summary is the section's one-line summary), and links ({up, previous, next}: the commands that open the level it sits in and its neighbors there).",
},
{
value: 'docs.detail.section',
description:
- 'One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it).',
+ 'One ReferenceSection of a topic, found by key or title, with token-ref blocks inlined, plus links ({up, previous, next}: the commands that open its topic index and the sections before and after it). The envelope\'s package names the npm package that wrote the section.',
},
{
value: 'docs.node',
description:
- "One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names).",
+ "One node of the docs tree, read by its route: its id, kind, package, title, summary, and breadcrumb, plus a namespace's slots with their children (one level down, each naming its package) or a typed doc's content, and links ({up, previous, next, related}: the commands that open its parent, its neighbors, and the docs it names).",
},
// blog (read from the published RSS feed)
@@ -137,7 +137,7 @@ export const doc = {
{
value: 'search',
description:
- 'The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), and, for a hit on one section, section (docs), or displayName and kind (templates).',
+ 'The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates).',
},
// build
@@ -149,19 +149,19 @@ export const doc = {
{
value: 'build.kit',
description:
- "The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, command, basis, reason, alternatives, ...}, pages (search's closest templates), blocks and domain as SearchResultEntry[], frame, foundation, and hint {reason, commands} when thin.",
+ "The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin.",
},
// swizzle
{
value: 'swizzle.list',
description:
- "The names of swizzlable components discoverable from cwd's @astryxdesign/core.",
+ "The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core.",
},
{
value: 'swizzle.copy',
description:
- 'An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling.',
+ 'An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope\'s package names the same owning package.',
},
// gap reports
@@ -189,12 +189,12 @@ export const doc = {
{
value: 'template.skeleton',
description:
- "A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes.",
+ "A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. The envelope's package names the npm package that owns the template.",
},
{
value: 'template.copy',
description:
- 'A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media).',
+ 'A scaffold receipt: template id, output directory, written file name, file count, and demoMediaReplaced (how many Astryx demo media references were replaced with placeholders for you to swap for your own media). The envelope\'s package names the npm package that owns the template.',
},
{
@@ -207,12 +207,17 @@ export const doc = {
{
value: 'hook.list',
description:
- 'The hook catalog grouped by category: `detail` (the level: names | compact | full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry.',
+ 'The hook catalog grouped by category: `detail` (the level: names | compact | full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. The envelope\'s package is @astryxdesign/core, the only package that ships hooks.',
+ },
+ {
+ value: 'hook.detail',
+ description:
+ "One hook's full authored HookDoc. The envelope's package is @astryxdesign/core.",
},
- {value: 'hook.detail', description: "One hook's full authored HookDoc."},
{
value: 'hook.detail.params',
- description: "Just one hook's parameters table (HookParamDoc[]).",
+ description:
+ "Just one hook's parameters table (HookParamDoc[]). The envelope's package is @astryxdesign/core.",
},
// theme
@@ -261,7 +266,7 @@ export const doc = {
{
value: 'upgrade.list',
description:
- 'Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything.',
+ 'Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything.',
},
{
value: 'upgrade.registry',
diff --git a/packages/cli/foundation/response/response.doc.mjs b/packages/cli/foundation/response/response.doc.mjs
index a985216196..b5321ada66 100644
--- a/packages/cli/foundation/response/response.doc.mjs
+++ b/packages/cli/foundation/response/response.doc.mjs
@@ -15,16 +15,17 @@ export const doc = {
namespace: 'cli/api',
description:
'The single JSON envelope every command emits under --json. Success is ' +
- '{ apiVersion, type, data, meta? }; failure is { apiVersion, error, code, ' +
+ '{ apiVersion, type, package?, data, meta? }; failure is { apiVersion, error, code, ' +
'suggestions? }. Discriminate by checking whether `error` is present.',
appliesTo: 'astryx --json',
fields: [
{
name: 'Success envelope',
- type: '{ apiVersion: number; type: string; data: unknown; meta?: Record<string, unknown> }',
+ type: '{ apiVersion: number; type: string; package?: string; data: unknown; meta?: Record<string, unknown> }',
description:
'Emitted for every successful command in --json mode: a type ' +
- 'discriminator, its data payload, and an optional meta sidecar.',
+ 'discriminator, the package that owns what the response is about, ' +
+ 'its data payload, and an optional meta sidecar.',
fields: [
{
name: 'apiVersion',
@@ -42,6 +43,18 @@ export const doc = {
'Names the payload shape. Every value is listed in the response-types enum.',
required: true,
},
+ {
+ name: 'package',
+ type: 'string',
+ description:
+ 'The npm package that owns the one thing the response is about: ' +
+ '`@astryxdesign/core` for a Core component, hook, or template, ' +
+ '`@astryxdesign/cli` for a doc the CLI ships, or the integration ' +
+ 'package that contributed it. Absent when the response lists ' +
+ 'things from more than one package; each listed item then names ' +
+ 'its own `package`.',
+ example: "'@astryxdesign/core'",
+ },
{
name: 'data',
type: 'unknown',
@@ -119,6 +132,7 @@ export const doc = {
code: `{
"apiVersion": 1,
"type": "component.detail",
+ "package": "@astryxdesign/core",
"data": { "name": "Button" }
}`,
},
diff --git a/packages/cli/test/__golden__/component-props.json b/packages/cli/test/__golden__/component-props.json
index 7fa9b2bd8f..a8b6954338 100644
--- a/packages/cli/test/__golden__/component-props.json
+++ b/packages/cli/test/__golden__/component-props.json
@@ -1,6 +1,7 @@
{
"apiVersion": 1,
"type": "component.detail.props",
+ "package": "@acme/kit",
"data": [
{
"name": "title",
diff --git a/packages/cli/test/__golden__/component-text.txt b/packages/cli/test/__golden__/component-text.txt
index 159e7d4456..15460e241c 100644
--- a/packages/cli/test/__golden__/component-text.txt
+++ b/packages/cli/test/__golden__/component-text.txt
@@ -1,3 +1,5 @@
+package: @acme/kit
+
# AcmeCard
A zorblax card that groups one topic.
diff --git a/packages/cli/test/__golden__/component-zh.json b/packages/cli/test/__golden__/component-zh.json
index 94109b7f43..c36f8e1fa3 100644
--- a/packages/cli/test/__golden__/component-zh.json
+++ b/packages/cli/test/__golden__/component-zh.json
@@ -1,6 +1,7 @@
{
"apiVersion": 1,
"type": "component.detail",
+ "package": "@acme/kit",
"data": {
"type": "component",
"name": "AcmeCard",
diff --git a/packages/cli/test/__golden__/component.json b/packages/cli/test/__golden__/component.json
index f67cf3981b..138836a42d 100644
--- a/packages/cli/test/__golden__/component.json
+++ b/packages/cli/test/__golden__/component.json
@@ -1,6 +1,7 @@
{
"apiVersion": 1,
"type": "component.detail",
+ "package": "@acme/kit",
"data": {
"type": "component",
"name": "AcmeCard",
diff --git a/packages/cli/test/__golden__/docs-index.txt b/packages/cli/test/__golden__/docs-index.txt
index d716252435..73ac4e25cc 100644
--- a/packages/cli/test/__golden__/docs-index.txt
+++ b/packages/cli/test/__golden__/docs-index.txt
@@ -1,6 +1,8 @@
Acme guide
How zorblax cards fit together.
+package: @acme/kit
+
start Start - Install the kit.
colors Colors - Cards use the core tokens.
diff --git a/packages/cli/test/__golden__/docs-section.json b/packages/cli/test/__golden__/docs-section.json
index 88ed522b83..63179d4a88 100644
--- a/packages/cli/test/__golden__/docs-section.json
+++ b/packages/cli/test/__golden__/docs-section.json
@@ -1,6 +1,7 @@
{
"apiVersion": 1,
"type": "docs.detail.section",
+ "package": "@acme/kit",
"data": {
"title": "Colors",
"content": [
diff --git a/packages/cli/test/__golden__/docs-topic-text.txt b/packages/cli/test/__golden__/docs-topic-text.txt
index 3439206e3c..24e35e83ba 100644
--- a/packages/cli/test/__golden__/docs-topic-text.txt
+++ b/packages/cli/test/__golden__/docs-topic-text.txt
@@ -1,3 +1,5 @@
+package: @acme/kit
+
# Acme guide
How zorblax cards fit together.
diff --git a/packages/cli/test/__golden__/docs-topic.json b/packages/cli/test/__golden__/docs-topic.json
index bee517996f..ca6d994b4e 100644
--- a/packages/cli/test/__golden__/docs-topic.json
+++ b/packages/cli/test/__golden__/docs-topic.json
@@ -1,6 +1,7 @@
{
"apiVersion": 1,
"type": "docs.detail",
+ "package": "@acme/kit",
"data": {
"name": "acme-guide",
"description": "How zorblax cards fit together.",
@@ -8,17 +9,20 @@
"title": "Acme guide",
"sections": [
{
+ "id": "start",
"title": "Start",
+ "package": "@acme/kit",
"content": [
{
"type": "prose",
"text": "Install the kit."
}
- ],
- "id": "start"
+ ]
},
{
+ "id": "colors",
"title": "Colors",
+ "package": "@acme/kit",
"content": [
{
"type": "prose",
@@ -28,8 +32,7 @@
"type": "prose",
"text": "[token-ref: unknown topic \"no-such-topic\"]"
}
- ],
- "id": "colors"
+ ]
}
],
"links": {
diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.json
index 5786d4935d..4dda24f4ce 100644
--- a/packages/cli/test/__golden__/search.json
+++ b/packages/cli/test/__golden__/search.json
@@ -8,6 +8,7 @@
{
"domain": "component",
"name": "AcmeCard",
+ "package": "@acme/kit",
"score": 90,
"reason": "keyword \"zorblax\"",
"description": "A zorblax card that groups one topic.",
@@ -17,17 +18,18 @@
{
"domain": "doc",
"name": "acme-guide",
+ "package": "@acme/kit",
"score": 50,
"reason": "description mentions \"zorblax\"",
"description": "How zorblax cards fit together.",
"title": "Unorganized › Acme guide",
"command": "astryx docs acme-guide --index",
- "parent": "astryx docs unorganized",
- "package": "@acme/kit"
+ "parent": "astryx docs unorganized"
},
{
"domain": "template",
"name": "hero",
+ "package": "@acme/kit",
"score": 50,
"reason": "description mentions \"zorblax\"",
"description": "A zorblax hero block.",
@@ -38,12 +40,12 @@
{
"domain": "theme",
"name": "ocean",
+ "package": "@acme/kit",
"score": 50,
"reason": "description mentions \"zorblax\"",
"description": "A zorblax blue.",
"displayName": "Ocean",
- "command": "astryx theme add ocean",
- "package": "@acme/kit"
+ "command": "astryx theme add ocean"
}
]
}
diff --git a/packages/cli/test/__golden__/template.json b/packages/cli/test/__golden__/template.json
index 4f8c24bc8f..be09ccf6cb 100644
--- a/packages/cli/test/__golden__/template.json
+++ b/packages/cli/test/__golden__/template.json
@@ -1,6 +1,7 @@
{
"apiVersion": 1,
"type": "template.show",
+ "package": "@acme/kit",
"data": {
"template": "hero",
"description": "A zorblax hero block.",
diff --git a/packages/cli/test/inv28-package-provenance.test.mjs b/packages/cli/test/inv28-package-provenance.test.mjs
new file mode 100644
index 0000000000..655baf9b00
--- /dev/null
+++ b/packages/cli/test/inv28-package-provenance.test.mjs
@@ -0,0 +1,275 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file spec cli-surface INV28: every result names the package each artifact
+ * comes from. A result about one artifact carries `package` in its envelope,
+ * directly after `type`. A result that lists artifacts gives each one its own
+ * `package`. Text names the same package; verbatim source output (`--source`,
+ * `--showcase`, a template's source) prints only the source.
+ *
+ * The CLI cases run the real binary over this repository's Core. The
+ * integration cases call the API with a project whose one integration
+ * contributes a component, and show that the integration's package reaches
+ * every projection and search with nothing written for it by its author.
+ *
+ * @position packages/cli/test — INV28 enforcement
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {runCli} from '../test-utils/run-cli.mjs';
+
+const CORE = '@astryxdesign/core';
+const CLI = '@astryxdesign/cli';
+const ACME = '@acme/widgets';
+
+// The API reads integrations through Project.load(). Vitest cannot import an
+// astryx.config.mjs from a temporary root, so the project is mocked the way
+// component-ownership.test.mjs mocks it, with the integration's files on disk.
+// The CLI cases run in a child process and are not affected.
+const projectLoadMock = vi.fn();
+vi.mock('../foundation/config/project.mjs', async importOriginal => ({
+ ...(await importOriginal()),
+ Project: {load: (/** @type {unknown[]} */ ...args) => projectLoadMock(...args)},
+}));
+const {component} = await import('../api/component/component.mjs');
+const {search} = await import('../api/search/search.mjs');
+
+// Each case scans the whole Core library; size the budget to the work.
+vi.setConfig({testTimeout: 60_000, hookTimeout: 60_000});
+
+/** @param {string[]} args */
+async function json(args) {
+ const {status, stdout} = await runCli(['--json', ...args]);
+ expect(status, stdout).toBe(0);
+ return JSON.parse(stdout);
+}
+
+/** @param {string[]} args */
+async function stderrOf(args) {
+ const {status, stdout, stderr} = await runCli(args);
+ expect(status, stdout).toBe(0);
+ return stderr;
+}
+
+/** @param {string[]} args */
+async function text(args) {
+ const {status, stdout} = await runCli(args);
+ expect(status, stdout).toBe(0);
+ return stdout;
+}
+
+/** @param {unknown} item @param {string} label */
+function expectPackage(item, label) {
+ expect(/** @type {any} */ (item)?.package, label).toEqual(expect.any(String));
+}
+
+describe('INV28: a result about one artifact names its package after `type`', () => {
+ /** @type {Array<[string, string[], string]>} */
+ const cases = [
+ ['component.detail', ['component', 'Button'], CORE],
+ ['component.detail.props', ['component', 'Button', '--props'], CORE],
+ ['component.detail.source', ['component', 'Button', '--source'], CORE],
+ ['component.detail.showcase', ['component', 'Button', '--showcase'], CORE],
+ ['component.detail.blocks', ['component', 'Button', '--blocks'], CORE],
+ ['docs.detail', ['docs', 'theme'], CLI],
+ ['docs.index', ['docs', 'theme', '--index'], CLI],
+ ['docs.detail.section', ['docs', 'theme', 'quick-start'], CLI],
+ ['docs.node', ['docs', 'cli'], CLI],
+ ['template.show', ['template', 'dashboard'], CORE],
+ ['template.skeleton', ['template', 'dashboard', '--skeleton'], CORE],
+ ['hook.detail', ['hook', 'useCollapsible'], CORE],
+ ['hook.detail.params', ['hook', 'useCollapsible', '--params'], CORE],
+ ['hook.list', ['hook', '--list'], CORE],
+ ['swizzle.list', ['swizzle', '--list'], CORE],
+ ];
+ for (const [type, args, owner] of cases) {
+ it(`${type} names ${owner}, directly after type`, async () => {
+ const res = await json(args);
+ expect(res.type).toBe(type);
+ expect(res.package).toBe(owner);
+ expect(Object.keys(res).slice(0, 4)).toEqual([
+ 'apiVersion',
+ 'type',
+ 'package',
+ 'data',
+ ]);
+ });
+ }
+});
+
+describe('INV28: a result that lists artifacts names each one', () => {
+ it('search: every result, whatever its domain', async () => {
+ const res = await json(['search', 'button']);
+ expect(res.package).toBeUndefined();
+ expect(res.data.results.length).toBeGreaterThan(0);
+ for (const r of res.data.results) expectPackage(r, `${r.domain} ${r.name}`);
+ const button = res.data.results.find(
+ (/** @type {any} */ r) => r.domain === 'component' && r.name === 'Button',
+ );
+ expect(button?.package).toBe(CORE);
+ });
+
+ it('build.kit: the start, its alternatives, pages, blocks, and components', async () => {
+ const res = await json(['build', 'user settings']);
+ expect(res.package).toBeUndefined();
+ const {start, pages, blocks, domain} = res.data;
+ expect(start.package).toBe(CORE);
+ for (const item of [...start.alternatives, ...pages, ...blocks, ...domain]) {
+ expectPackage(item, item.name);
+ }
+ });
+
+ it('component.detail.blocks: each block', async () => {
+ const {data} = await json(['component', 'Button', '--blocks']);
+ for (const block of [data.showcase, ...data.examples, ...data.related]) {
+ expectPackage(block, block.name);
+ }
+ });
+
+ it('docs.index and docs.detail: each section', async () => {
+ const index = await json(['docs', 'theme', '--index']);
+ for (const s of index.data.sections) expect(s.package, s.id).toBe(CLI);
+ const detail = await json(['docs', 'theme']);
+ for (const s of detail.data.sections) expect(s.package, s.id).toBe(CLI);
+ });
+
+ it('docs.node: each child', async () => {
+ const {data} = await json(['docs', 'cli']);
+ const children = data.slots.flatMap((/** @type {any} */ s) => s.children);
+ expect(children.length).toBeGreaterThan(0);
+ for (const child of children) expectPackage(child, child.route);
+ });
+
+ it('upgrade.list: each codemod', async () => {
+ const {data} = await json(['upgrade', '--list']);
+ expect(data.length).toBeGreaterThan(0);
+ for (const codemod of data) expect(codemod.package, codemod.name).toBe(CORE);
+ });
+
+ it('component.list: each entry, at every detail level', async () => {
+ for (const args of [
+ ['component', '--list'],
+ ['component', '--list', '--detail', 'compact'],
+ ['component', '--list', '--detail', 'full'],
+ ]) {
+ const {data} = await json(args);
+ for (const [group, entries] of Object.entries(data.components)) {
+ for (const entry of /** @type {any[]} */ (entries)) {
+ expectPackage(entry, `${args.join(' ')}: ${group}/${entry.name}`);
+ }
+ }
+ }
+ });
+
+ it('template.list and theme.list: each entry', async () => {
+ const templates = await json(['template', '--list']);
+ for (const t of templates.data) expectPackage(t, t.id);
+ const themes = await json(['theme', 'list']);
+ for (const t of themes.data) expectPackage(t, t.slug);
+ });
+});
+
+describe('INV28: text names the same package', () => {
+ it('a read of one artifact names its package', async () => {
+ expect(await text(['component', 'Button'])).toContain(`package: ${CORE}`);
+ expect(await text(['component', 'Button', '--props'])).toContain(`package: ${CORE}`);
+ expect(await text(['docs', 'theme', '--index'])).toContain(`package: ${CLI}`);
+ expect(await text(['docs', 'theme', 'quick-start'])).toContain(`package: ${CLI}`);
+ expect(await text(['template', 'dashboard', '--skeleton'])).toContain(`package: ${CORE}`);
+ expect(await text(['hook', 'useCollapsible'])).toContain(`package: ${CORE}`);
+ });
+
+ it('verbatim source output keeps stdout to the source and names the package on stderr', async () => {
+ const source = await text(['component', 'Button', '--source']);
+ expect(source).not.toContain('package:');
+ expect(source.trimStart().startsWith('// Copyright')).toBe(true);
+ for (const args of [
+ ['component', 'Button', '--source'],
+ ['component', 'Button', '--showcase'],
+ ['template', 'dashboard'],
+ ]) {
+ expect(await stderrOf(args), args.join(' ')).toContain(`package: ${CORE}`);
+ }
+ });
+
+ it('a batch names the package of each source row', async () => {
+ const out = await text(['component', 'Button', 'Badge', '--source']);
+ expect(out.match(/package:\s+@astryxdesign\/core/g)?.length).toBe(2);
+ });
+
+ it('build names the package of each template, block, and component', async () => {
+ expect(await text(['build', 'user settings'])).toMatch(/package:\s+@astryxdesign\/core/);
+ });
+});
+
+describe('INV28: an integration names its own package, with nothing written for it', () => {
+ /** @type {string} */
+ let tmp;
+
+ beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-inv28-'));
+ const realCore = path.resolve(import.meta.dirname, '..', '..', 'core');
+ fs.mkdirSync(path.join(tmp, 'packages'), {recursive: true});
+ fs.symlinkSync(realCore, path.join(tmp, 'packages', 'core'));
+ const intDir = path.join(tmp, 'node_modules', '@acme', 'widgets');
+ const compDir = path.join(intDir, 'components');
+ fs.mkdirSync(compDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(intDir, 'package.json'),
+ JSON.stringify({name: ACME, version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(compDir, 'SuperButton.doc.mjs'),
+ "export default {\n type: 'component',\n name: 'SuperButton',\n keywords: ['superbutton'],\n" +
+ " usage: {description: 'A button from the widgets integration.'},\n" +
+ " props: [{name: 'power', type: \"'low' | 'high'\", description: 'Power level.'}],\n};\n",
+ );
+ fs.writeFileSync(
+ path.join(compDir, 'SuperButton.tsx'),
+ 'export function SuperButton() { return null; }\n',
+ );
+ projectLoadMock.mockReset();
+ projectLoadMock.mockResolvedValue({
+ integrations: [ACME],
+ loadedIntegrations: [
+ {
+ name: ACME,
+ version: '1.0.0',
+ components: compDir,
+ templates: undefined,
+ codemods: undefined,
+ __packageDir: intDir,
+ },
+ ],
+ });
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmp, {recursive: true, force: true});
+ });
+
+ it('component detail, props, and source name the integration', async () => {
+ const detail = /** @type {any} */ (await component('SuperButton', {cwd: tmp}));
+ expect(detail.type).toBe('component.detail');
+ expect(detail.package).toBe(ACME);
+ expect(detail.data.package).toBe(ACME);
+ const props = /** @type {any} */ (await component('SuperButton', {cwd: tmp, props: true}));
+ expect(props.package).toBe(ACME);
+ const source = /** @type {any} */ (await component('SuperButton', {cwd: tmp, source: true}));
+ expect(source.package).toBe(ACME);
+ });
+
+ it('a Core component in the same project still names Core', async () => {
+ const props = /** @type {any} */ (await component('Button', {cwd: tmp, props: true}));
+ expect(props.package).toBe(CORE);
+ });
+
+ it('search names the integration on its component', async () => {
+ const res = await search('superbutton', {cwd: tmp});
+ const hit = res.data.results.find(r => r.name === 'SuperButton');
+ expect(hit?.package).toBe(ACME);
+ });
+});
diff --git a/packages/cli/test/readme-prose.test.mjs b/packages/cli/test/readme-prose.test.mjs
index d9cb1ec9c5..4715d228b9 100644
--- a/packages/cli/test/readme-prose.test.mjs
+++ b/packages/cli/test/readme-prose.test.mjs
@@ -18,9 +18,13 @@ const README = fs
.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '../README.md'), 'utf8')
.replace(/<!-- BEGIN GENERATED: (\S+) -->[\s\S]*?<!-- END GENERATED: \1 -->/g, '');
-/** INV2: success is {apiVersion, type, data} + meta?; failure is {apiVersion, error, code} + suggestions?. */
+/**
+ * INV2: success is {apiVersion, type, data} + package?, meta? (INV28 adds
+ * `package` for a result about one artifact); failure is
+ * {apiVersion, error, code} + suggestions?.
+ */
const SHAPES = {
- success: {required: ['apiVersion', 'type', 'data'], optional: ['meta']},
+ success: {required: ['apiVersion', 'type', 'data'], optional: ['package', 'meta']},
failure: {required: ['apiVersion', 'error', 'code'], optional: ['suggestions']},
};