Skip to content

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

TypeScript

fix(cli): generate the ./authoring declarations + make foundation the bottom layer (#4736)

Joey6afcfb73fd3c
diff --git a/.changeset/cli-foundation-layering.md b/.changeset/cli-foundation-layering.md
new file mode 100644
index 0000000000..c7b64eee2c
--- /dev/null
+++ b/.changeset/cli-foundation-layering.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Make `foundation/` a true bottom layer: it no longer imports `api/`, and ESLint now enforces that direction alongside the existing `authoring/` and `api/` rules.
+
+Two things were reaching upward. `Project` pulled template discovery out of `api/template`, whose adapter imported `Project` straight back — so the module cycle ran across the layer boundary. And both `Project` and `integration-warnings` imported `validateLoadedIntegration` from the `validate-integration` command.
+
+Neither was really misplaced logic, just misplaced files: the template adapter had no `api/` imports at all, and the contribution validators are shared infra that foundation itself runs. The adapter now lives at `foundation/discovery/template-adapter.mjs` and the validators at `foundation/integrations/validate-contributions.mjs`, so both sit with their callers.
+
+To be precise about what did and did not change: `Project` and the template adapter still import each other, so the module cycle itself remains — it is simply contained within foundation now instead of spanning two layers. The redundant nested `Project.load()` inside integration-template discovery, and `Project.templates()` filtering those integration templates back out, are also untouched. Both are worth cleaning up, but doing so would change behavior, and this change is deliberately behavior-preserving.
+
+Internal only — no public API change, and no behavior change: the CLI's observable surface (help, command output, error paths, exit codes) is byte-identical across 84 invocations.
+@josephfarina
diff --git a/.changeset/cli-generated-authoring-types.md b/.changeset/cli-generated-authoring-types.md
new file mode 100644
index 0000000000..8a4de37443
--- /dev/null
+++ b/.changeset/cli-generated-authoring-types.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Generate the published `./authoring` type declarations from their JSDoc instead of hand-writing them, the same way `./api` already works. The 13 hand-maintained `.d.mts` files are gone; `scripts/sync-api-types.mjs` now emits both trees at `prepack`, stamped `@generated`.
+
+A hand-written declaration shadows the JSDoc in its `.mjs`, so it could disagree with the implementation and still compile. Both failure modes had shipped: a missing declaration made a strict consumer resolve that parser as `any`, and a stale `parseDoc` return union silently dropped `SchemaDoc`, `CommandDoc`, and `EnumDoc` — so consumers could not narrow a parsed doc to those kinds. Generation makes both impossible: `tsc` now rejects a `@returns` that disagrees with the code before a declaration can even be emitted.
+
+Also fixes `parseFunction`, which was a bare re-export of `parseHook` and therefore published `HookDoc` as its return type instead of the general `FunctionDoc`. It is now a thin typed wrapper; runtime behavior (including error message prefixes) is unchanged.
+
+The published `./authoring` surface is now covered by the same end-to-end pack-and-typecheck CI gate as `./api`.
+@josephfarina
diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjs
index e30b325f25..d581e15696 100644
--- a/.github/scripts/cli-api-types-verify.mjs
+++ b/.github/scripts/cli-api-types-verify.mjs
@@ -2,11 +2,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Verify the PUBLISHED `@astryxdesign/cli/api` type surface.
+ * Verify the PUBLISHED `@astryxdesign/cli/api` and `/authoring` type surfaces.
*
- * The `./api` declarations (`api/**\/*.d.mts`) are generated from the JSDoc in
- * `api/**\/*.mjs` at `prepack` — they are NOT committed. This test proves the
- * surface a consumer actually installs is correct, end to end:
+ * Both sets of declarations (`api/**\/*.d.mts`, `authoring/**\/*.d.mts`) are
+ * generated from the JSDoc in their `.mjs` at `prepack` — they are NOT
+ * committed. This test proves the surface a consumer actually installs is
+ * correct, end to end:
*
* 1. `pnpm pack` the CLI (fires `prepack` → `sync:api-types`), producing the
* exact tarball that would be published.
@@ -73,6 +74,23 @@ if (!fs.existsSync(path.join(pkgDir, 'api', 'index.d.mts'))) {
fail('packaged tarball is missing api/index.d.mts \u2014 the ./api types did not ship');
}
console.log('\u2713 tarball ships api/index.d.mts');
+// The authoring parser declarations are generated too, so the same "did it
+// actually ship" question applies to them.
+if (!fs.existsSync(path.join(pkgDir, 'authoring', 'doctypes', 'parse.d.mts'))) {
+ fail(
+ 'packaged tarball is missing authoring/doctypes/parse.d.mts \u2014 the generated ./authoring types did not ship',
+ );
+}
+console.log('\u2713 tarball ships the generated ./authoring declarations');
+// The api declarations re-export from foundation (e.g. api/template re-exports
+// the template adapter), so foundation's declarations have to ship too or those
+// re-exports resolve to `any` for a strict consumer.
+if (!fs.existsSync(path.join(pkgDir, 'foundation', 'discovery', 'template-adapter.d.mts'))) {
+ fail(
+ 'packaged tarball is missing foundation/discovery/template-adapter.d.mts \u2014 the api declarations re-export from foundation, so its declarations must ship too',
+ );
+}
+console.log('\u2713 tarball ships the generated foundation declarations');
fs.symlinkSync(CORE_DIR, path.join(nm, 'core'), 'dir');
// 3. Type-check a representative consumer against the packed types.
@@ -100,6 +118,32 @@ async function main() {
listThemes, validateIntegration, summarizeIssues, AstryxError, s];
}
void main;
+
+// ── ./authoring ─────────────────────────────────────────────────────────
+// These declarations are generated from JSDoc too. The narrowing below is the
+// regression test for a stale parseDoc return union: when three doc kinds were
+// missing from it, \`doc.type === 'schema'\` was a no-overlap error and \`fields\`
+// was inaccessible — while everything still compiled inside the repo.
+import {
+ parseDoc, parseComponent, parseHook, parseFunction, parseReference,
+ parseTemplate, parseSchema, parseCommand, parseEnum,
+} from '@astryxdesign/cli/authoring';
+import type {SchemaDoc, CommandDoc, EnumDoc, FunctionDoc} from '@astryxdesign/cli/authoring';
+
+function authoringSurface(raw: unknown) {
+ const doc = parseDoc(raw);
+ if (doc.type === 'schema') { const f = doc.fields; void f; }
+ if (doc.type === 'command') { const su: string = doc.summary; void su; }
+ if (doc.type === 'enum') { const m = doc.members; void m; }
+
+ const schema: SchemaDoc = parseSchema(raw);
+ const command: CommandDoc = parseCommand(raw);
+ const enumDoc: EnumDoc = parseEnum(raw);
+ const fn: FunctionDoc = parseFunction(raw);
+ void [schema, command, enumDoc, fn];
+ void [parseComponent, parseHook, parseReference, parseTemplate];
+}
+void authoringSurface;
export {};
`;
fs.writeFileSync(path.join(VERIFY_DIR, 'scenario.ts'), scenario);
@@ -146,5 +190,7 @@ if (errors.length > 0) {
fail('a consumer of the packaged @astryxdesign/cli/api does not type-check', errors.join('\n'));
}
-console.log('\u2713 packaged @astryxdesign/cli/api type-checks for a strict consumer');
-console.log('\nAll ./api type-surface checks passed.');
+console.log(
+ '\u2713 packaged @astryxdesign/cli/api + /authoring type-check for a strict consumer',
+);
+console.log('\nAll published type-surface checks passed.');
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0eefb3ebc6..e82ec9d2ba 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -324,7 +324,7 @@ The CLI (`packages/cli/`) is layered so behavior, presentation, and contracts st
- **`clients/cli/`** — the Commander program and per-command handlers. A handler is a _thin wrapper_: parse flags → call the matching `api/` function → render (JSON via `jsonOut`, or text via the formatter kit in `clients/cli/formatters/`).
- **`api/`** — the programmatic API (`@astryxdesign/cli/api`). Each command maps to `api/<name>/`, whose functions return a typed `{ type, data }` envelope. This is the behavior source of truth, so `astryx --json` and the imported function return identical data.
- **`authoring/`** — the pure data contracts (`@astryxdesign/cli/authoring`): the TypeScript types you author objects against (config, integration, codemod, and the doc-types) plus the sealed zod parsers the CLI runs at the load boundary.
-- **`foundation/`** — cross-cutting infra: the `{ type, data }` JSON contract, the stable `ERROR_CODES`, discovery, and path-safety.
+- **`foundation/`** — the bottom layer: cross-cutting infra that everything above builds on — the `{ type, data }` JSON contract, the stable `ERROR_CODES`, discovery (components, templates), integration contribution validators, and path-safety. It never imports `api/` or `clients/`; if foundation needs something, that something belongs in foundation.
### The CLI documents itself
@@ -344,16 +344,18 @@ These are not free-form. `parseDoc` validates each at load, and a **drift harnes
Most of the conventions above are mechanical, so they're checked rather than reviewed:
-| Rule | Enforced by |
-| ------------------------------------------------------------------------------------------------------------- | -------------------------------- |
-| `authoring/` imports no other layer; `api/` never imports `clients/` | ESLint (`no-restricted-imports`) |
-| zod stays sealed behind the `authoring/` parsers | ESLint (`no-restricted-imports`) |
-| commands register via `defineCommand`, never straight onto Commander | ESLint (`no-restricted-syntax`) |
-| each doc-type ships `type.ts` + `parse.mjs` + `parse.d.mts` + `<kind>.doc.mjs`, and its parser is re-exported | `pnpm check:cli-structure` |
-| each `api/<name>/` ships its typedefs, a `FunctionDoc`, and a test | `pnpm check:cli-structure` |
-| every `CommandDoc`/`EnumDoc` matches the live CLI | the drift harness |
+| Rule | Enforced by |
+| ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
+| the layer directions hold: `authoring/` imports no other layer, `foundation/` never imports `api/` or `clients/`, `api/` never imports `clients/` | ESLint (`no-restricted-imports`) |
+| zod stays sealed behind the `authoring/` parsers | ESLint (`no-restricted-imports`) |
+| commands register via `defineCommand`, never straight onto Commander | ESLint (`no-restricted-syntax`) |
+| each doc-type ships `type.ts` + `parse.mjs` + `<kind>.doc.mjs`, re-exports its parser, and appears in `parseDoc`'s `@returns` | `pnpm check:cli-structure` |
+| each `api/<name>/` ships its typedefs, a `FunctionDoc`, and a test | `pnpm check:cli-structure` |
+| every `CommandDoc`/`EnumDoc` matches the live CLI | the drift harness |
-The declaration file (`parse.d.mts`) is the easiest one to forget and the most expensive to miss: `authoring/index.d.ts` re-exports each parser, so without it a strict consumer of the published package resolves that parser as `any` — and local typechecks won't catch it, because they run with `checkJs` and never exercise the packed `./api` surface. A hand-written declaration shadows the JSDoc in its `.mjs`, so it can also go stale while still compiling; `check:cli-structure` therefore asserts that every doc kind appears in the `parseDoc` return union too.
+You never hand-write the `.d.mts` declarations. `scripts/sync-api-types.mjs` emits them for both `api/` and `authoring/` from the `.mjs` JSDoc — gitignored, regenerated at `prepack`, and stamped `@generated`. Edit the JSDoc and run `pnpm -F @astryxdesign/cli sync:api-types`.
+
+That matters because a hand-written declaration _shadows_ the JSDoc in its `.mjs`, and both ways it can lie shipped once: a missing declaration made a strict consumer resolve the parser as `any` (surfacing only at pack time as TS7016, since local typechecks run with `checkJs` and never exercise the packed surface), and a stale `parseDoc` union silently dropped three doc kinds from the published type while still compiling. Generation removes both. The one declaration still written by hand is `authoring/index.d.ts`, the curated public barrel.
### Adding a command
diff --git a/eslint.config.js b/eslint.config.js
index a14dab4c7c..2ff50e4a76 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -450,7 +450,7 @@ export default defineConfig(
},
// Everything above the contracts consumes already-parsed, typed data.
{
- files: ["packages/cli/clients/**/*.mjs", "packages/cli/foundation/**/*.mjs"],
+ files: ["packages/cli/clients/**/*.mjs"],
rules: {
"no-restricted-imports": ["error", {
paths: [{
@@ -461,6 +461,28 @@ export default defineConfig(
}],
},
},
+ // foundation/ is the bottom layer: cross-cutting infra that the layers above
+ // build on. It must not reach back up into api/ or clients/. (It briefly did:
+ // Project pulled template discovery out of api/template, whose adapter then
+ // imported Project back — a cycle across the layer boundary. The adapter and
+ // the contribution validators now live in foundation, where their callers are.)
+ {
+ files: ["packages/cli/foundation/**/*.mjs"],
+ rules: {
+ "no-restricted-imports": ["error", {
+ patterns: [{
+ group: ["**/api/**", "**/clients/**"],
+ message:
+ "foundation/ is the bottom layer and must not import api/ or clients/. If foundation needs it, it belongs in foundation — move it down rather than reaching up.",
+ }],
+ paths: [{
+ name: "zod",
+ message:
+ "zod is sealed behind the authoring/ parsers. Validate at the load boundary (parseDoc/parseConfig/parseIntegration) and pass typed data inward.",
+ }],
+ }],
+ },
+ },
// A command's --help and its manifest entry are generated from its colocated
// CommandDoc via defineCommand. Registering straight onto Commander bypasses
// the doc, so the docs silently stop describing the real CLI.
diff --git a/packages/cli/.gitignore b/packages/cli/.gitignore
index af858921cf..52144a61c4 100644
--- a/packages/cli/.gitignore
+++ b/packages/cli/.gitignore
@@ -1,9 +1,17 @@
-# Generated ./api type declarations — emitted from the JSDoc in api/**/*.mjs by
-# scripts/sync-api-types.mjs. Not committed (like dist/ in the other packages);
-# regenerated automatically at `prepack` so the published tarball always ships
-# a fresh, in-sync type surface. Run `pnpm sync:api-types` to produce them locally.
+# Generated ./api and ./authoring type declarations — emitted from the JSDoc in
+# api/**/*.mjs and authoring/**/*.mjs by scripts/sync-api-types.mjs. Not committed
+# (like dist/ in the other packages); regenerated automatically at `prepack` so the
+# published tarball always ships a fresh, in-sync type surface. Run
+# `pnpm sync:api-types` to produce them locally.
+#
+# authoring/index.d.ts is deliberately NOT here: it is the hand-curated public
+# barrel (grouped + commented), not an emitted artifact.
api/**/*.d.mts
api/*.d.mts
+authoring/**/*.d.mts
+authoring/*.d.mts
+foundation/**/*.d.mts
+foundation/*.d.mts
.api-verify/
# Transient fixture dir written by authoring-migration.tsc.test.mjs (runs the
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index dc73046892..971892936a 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -270,6 +270,9 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {
let resolvedName = dirName;
// Track the resolving owner so the detail payload can carry ownership info.
// Defaults to core; the legacy-external fallback below may reassign it.
+ // Annotated because CORE_PACKAGE's generated declaration carries the literal
+ // type, which (unlike a fresh literal) does not widen on assignment.
+ /** @type {string} */
let resolvedOwnerPackage = CORE_PACKAGE;
let resolvedSourcePath = readmePath ? findComponentSource(coreDir, dirName) : null;
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index 05b5fb63d2..fce44436c2 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -17,6 +17,14 @@
* is false only for the no-manifest local case, which is guidance (not an
* error) so `validate-integration` can stay exit-0 in a non-integration dir.
*
+ * The on-disk contribution validators themselves (roots + codemods/templates/
+ * components, behind `validateLoadedIntegration`) live in
+ * `foundation/integrations/validate-contributions.mjs`, because foundation also
+ * runs them: `Project` collects integration issues and `integration-warnings`
+ * nudges about them on ordinary commands. This file re-exports
+ * `validateLoadedIntegration` so existing importers are unaffected, and keeps
+ * the command-level entry points that resolve a manifest from disk.
+ *
* Validators are intentionally small and independent so more checks can be
* appended without reshaping the result. Issue `code`s are stable public
* strings.
@@ -30,9 +38,14 @@ import {
loadManifestObject,
resolvePackageDir,
} from '../../foundation/integrations/integrations.mjs';
-import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';
-import {discoverIntegrationTemplatesForOne} from '../template/template.mjs';
-import * as componentDiscovery from '../../foundation/discovery/component-discovery.mjs';
+// The on-disk contribution validators live in foundation: Project and
+// integration-warnings need them too, and foundation must not depend on api.
+import {
+ validateLoadedIntegration,
+ issueError as error,
+} from '../../foundation/integrations/validate-contributions.mjs';
+
+export {validateLoadedIntegration};
/**
* @typedef {import('../../foundation/integrations/issue').AstryxIntegrationIssue} Issue
@@ -63,144 +76,6 @@ function findNearestPackageJson(cwd) {
}
}
-/** @param {string} code @param {string} message @returns {Issue} */
-function error(code, message) {
- return {code, severity: 'error', message};
-}
-
-/**
- * Verify each declared contribution root exists on disk. A declared-but-missing
- * root is a `missing_root` error.
- * @param {{components?: string, templates?: string, codemods?: string}} resolved
- * absolute resolved roots (undefined when not declared)
- * @param {Issue[]} issues
- */
-function checkRoots(resolved, issues) {
- const kinds = /** @type {const} */ (['components', 'templates', 'codemods']);
- for (const kind of kinds) {
- const root = resolved[kind];
- if (root == null) continue;
- if (!fs.existsSync(root)) {
- issues.push(
- error(
- 'missing_root',
- `Declared ${kind} root does not exist on disk: ${root}`,
- ),
- );
- }
- }
-}
-
-/**
- * Validate the integration's codemods via the landed discovery. Discovery is
- * strict (throws on bad export / duplicate id); we convert any throw into an
- * `invalid_codemod` error.
- * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration loaded-integration-shaped object
- * @param {Issue[]} issues
- */
-async function checkCodemods(integration, issues) {
- if (!integration.codemods || !fs.existsSync(integration.codemods)) return;
- try {
- await discoverIntegrationCodemods([integration]);
- } catch (err) {
- issues.push(error('invalid_codemod', /** @type {any} */ (err).message));
- }
-}
-
-/**
- * Validate the integration's templates via the landed discovery. Per-template
- * problems are reported as `invalid_template` errors.
- * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration loaded-integration-shaped object
- * @param {Issue[]} issues
- */
-async function checkTemplates(integration, issues) {
- if (!integration.templates || !fs.existsSync(integration.templates)) return;
- try {
- const {errors} = await discoverIntegrationTemplatesForOne(integration);
- for (const e of errors) {
- issues.push(error('invalid_template', e.message));
- }
- } catch (err) {
- issues.push(error('invalid_template', /** @type {any} */ (err).message));
- }
-}
-
-/**
- * Validate the integration's components via the landed ownership discovery.
- * Feature-detected: if the component-ownership export isn't present in this
- * build (sibling PR not yet merged), component validation is skipped rather
- * than hard-failing.
- *
- * `discoverIntegrationComponents` returns ownership records and does not throw
- * on a missing same-stem source — it records `sourcePath: null`. We surface
- * each such record as an `invalid_component` error.
- * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration loaded-integration-shaped object
- * @param {Issue[]} issues
- */
-async function checkComponents(integration, issues) {
- if (!integration.components || !fs.existsSync(integration.components)) return;
- const discover = componentDiscovery.discoverIntegrationComponents;
- if (typeof discover !== 'function') return; // feature not present yet
- try {
- const records = (await discover(integration)) ?? [];
- for (const record of records) {
- if (record?.sourcePath == null) {
- issues.push(
- error(
- 'invalid_component',
- `Component "${record?.name}" is missing its same-stem source file ${record?.name}.tsx.`,
- ),
- );
- }
- }
- } catch (err) {
- issues.push(error('invalid_component', /** @type {any} */ (err).message));
- }
-}
-
-/**
- * Run every contribution validator against a loaded-integration-shaped object.
- * @param {import('./validate-integration.type.mjs').LoadedIntegration} integration
- * @param {Issue[]} issues
- */
-async function runContributionChecks(integration, issues) {
- await checkCodemods(integration, issues);
- await checkTemplates(integration, issues);
- await checkComponents(integration, issues);
-}
-
-/**
- * Validate an already-LOADED integration (as produced by
- * `loadIntegrations` in lib/integrations.mjs — absolute contribution roots
- * plus identity) and return its issues. This is the reuse seam for everyday
- * commands that have already loaded the configured integrations and want the
- * SAME validators that `validate-integration` runs, without re-resolving the
- * manifest from disk.
- *
- * The manifest schema is intentionally NOT re-validated here: `loadIntegrations`
- * already validated it (and throws otherwise), so by the time a command holds a
- * loaded integration the manifest is known-good. We re-run the on-disk
- * contribution checks (roots + codemods/templates/components) because those can
- * regress independently of the manifest (a deleted directory, a broken template).
- *
- * @param {import('./validate-integration.type.mjs').LoadedIntegration} loaded loaded-integration-shaped object
- * @returns {Promise<Issue[]>}
- */
-export async function validateLoadedIntegration(loaded) {
- /** @type {Issue[]} */
- const issues = [];
- if (!loaded || typeof loaded !== 'object') return issues;
- checkRoots(
- {
- components: loaded.components,
- templates: loaded.templates,
- codemods: loaded.codemods,
- },
- issues,
- );
- await runContributionChecks(loaded, issues);
- return issues;
-}
/**
* Validate a single integration given its package directory and identity.
diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs
index c77fa49db0..82113d08e2 100644
--- a/packages/cli/api/template/copy/copy.mjs
+++ b/packages/cli/api/template/copy/copy.mjs
@@ -18,12 +18,12 @@ import {
} from '../../../foundation/fs/path-safety.mjs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {stripTemplateAssetRefs} from '../_adapter.mjs';
+import {stripTemplateAssetRefs} from '../../../foundation/discovery/template-adapter.mjs';
/**
* Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and
* return the `template.copy` receipt.
- * @param {import('../_adapter.mjs').DiscoveredTemplate} match
+ * @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} match
* @param {{targetPath: string, cwd: string, overwrite?: boolean}} ctx
* @returns {import('../template.type.mjs').TemplateCopyResponse}
*/
diff --git a/packages/cli/api/template/list/list.mjs b/packages/cli/api/template/list/list.mjs
index 35d050c73a..689a8eb881 100644
--- a/packages/cli/api/template/list/list.mjs
+++ b/packages/cli/api/template/list/list.mjs
@@ -9,11 +9,11 @@
* no-skeleton default) here.
*/
-import {pkgOf} from '../_adapter.mjs';
+import {pkgOf} from '../../../foundation/discovery/template-adapter.mjs';
/**
* Project a discovered template set into the `template.list` envelope.
- * @param {import('../_adapter.mjs').DiscoveredTemplate[]} templates
+ * @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate[]} templates
* @param {{type?: 'page' | 'block', package?: string}} [options]
* @returns {import('../template.type.mjs').TemplateListResponse}
*/
diff --git a/packages/cli/api/template/show/show.mjs b/packages/cli/api/template/show/show.mjs
index 546077e482..86a4ab6201 100644
--- a/packages/cli/api/template/show/show.mjs
+++ b/packages/cli/api/template/show/show.mjs
@@ -11,11 +11,11 @@
import * as fs from 'node:fs';
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {extractComponents} from '../_adapter.mjs';
+import {extractComponents} from '../../../foundation/discovery/template-adapter.mjs';
/**
* Build the `template.show` envelope for an already-resolved template.
- * @param {import('../_adapter.mjs').DiscoveredTemplate} match
+ * @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} match
* @returns {import('../template.type.mjs').TemplateShowResponse}
*/
export function templateShow(match) {
diff --git a/packages/cli/api/template/skeleton/skeleton.mjs b/packages/cli/api/template/skeleton/skeleton.mjs
index 6eed027c75..682e6e7661 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 '../_adapter.mjs';
+import {extractComponents} from '../../../foundation/discovery/template-adapter.mjs';
const STRUCTURAL = new Set([
'AppShell',
@@ -223,8 +223,8 @@ function extractSkeleton(source) {
* Build the `template.skeleton` envelope for an already-resolved template.
* `match` may be undefined when `--skeleton` is run without a name — the same
* "specify a template name" error the dispatcher's resolution would surface.
- * @param {import('../_adapter.mjs').DiscoveredTemplate | undefined} match
- * @param {import('../_adapter.mjs').DiscoveredTemplate[]} templates
+ * @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate | undefined} match
+ * @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate[]} templates
* @returns {import('../template.type.mjs').TemplateSkeletonResponse}
*/
export function templateSkeleton(match, templates) {
diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs
index a3aca951fa..469c94b956 100644
--- a/packages/cli/api/template/template.mjs
+++ b/packages/cli/api/template/template.mjs
@@ -6,16 +6,16 @@
* This module is BOTH the template dispatcher and the stable import surface for
* the template family. `template()` discovers the available templates, resolves
* the requested one, and routes to a leaf (list/show/skeleton/copy). The shared
- * discovery/IO + cross-command helpers live in `./_adapter.mjs` and are
+ * discovery/IO + cross-command helpers live in `foundation/discovery/template-adapter.mjs` and are
* RE-EXPORTED here so external import paths (`api/template/template.mjs`) —
* used by component, layout, search, init, discover, validate-integration, and
* lib/project — keep resolving unchanged.
*
* @position api/template — the template dispatcher + barrel; leaves live under
- * ./list, ./show, ./skeleton, ./copy and shared discovery under ./_adapter.
+ * ./list, ./show, ./skeleton, ./copy and shared discovery in foundation/discovery.
*/
-import {discoverAll, pkgOf} from './_adapter.mjs';
+import {discoverAll, pkgOf} from '../../foundation/discovery/template-adapter.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {templateList} from './list/list.mjs';
@@ -37,16 +37,16 @@ export {
findRelatedBlocks,
findShowcase,
extractComponents,
-} from './_adapter.mjs';
+} from '../../foundation/discovery/template-adapter.mjs';
/**
- * @typedef {import('./_adapter.mjs').DiscoveredTemplate} DiscoveredTemplate
+ * @typedef {import('../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} DiscoveredTemplate
*/
/**
- * @typedef {import('./_adapter.mjs').TemplateDiscoveryError} TemplateDiscoveryError
+ * @typedef {import('../../foundation/discovery/template-adapter.mjs').TemplateDiscoveryError} TemplateDiscoveryError
*/
/**
- * @typedef {import('./_adapter.mjs').TemplateDocModule} TemplateDocModule
+ * @typedef {import('../../foundation/discovery/template-adapter.mjs').TemplateDocModule} TemplateDocModule
*/
/**
diff --git a/packages/cli/authoring/codemod/parse.d.mts b/packages/cli/authoring/codemod/parse.d.mts
deleted file mode 100644
index 26f50bd935..0000000000
--- a/packages/cli/authoring/codemod/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {AstryxCodemod, AstryxConfigCodemod} from './type';
-export function parseCodemod(input: unknown, label?: string): AstryxCodemod | AstryxConfigCodemod;
diff --git a/packages/cli/authoring/config/parse.d.mts b/packages/cli/authoring/config/parse.d.mts
deleted file mode 100644
index 6fa8523abe..0000000000
--- a/packages/cli/authoring/config/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {AstryxConfig} from './type';
-export function parseConfig(input: unknown, label?: string): AstryxConfig;
diff --git a/packages/cli/authoring/doctypes/command/parse.d.mts b/packages/cli/authoring/doctypes/command/parse.d.mts
deleted file mode 100644
index 866d67283c..0000000000
--- a/packages/cli/authoring/doctypes/command/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {CommandDoc} from '../types';
-export function parseCommand(input: unknown, label?: string): CommandDoc;
diff --git a/packages/cli/authoring/doctypes/component/parse.d.mts b/packages/cli/authoring/doctypes/component/parse.d.mts
deleted file mode 100644
index 3289534b5a..0000000000
--- a/packages/cli/authoring/doctypes/component/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {ComponentDoc} from '../types';
-export function parseComponent(input: unknown, label?: string): ComponentDoc;
diff --git a/packages/cli/authoring/doctypes/enum/parse.d.mts b/packages/cli/authoring/doctypes/enum/parse.d.mts
deleted file mode 100644
index 99bc85aa20..0000000000
--- a/packages/cli/authoring/doctypes/enum/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {EnumDoc} from '../types';
-export function parseEnum(input: unknown, label?: string): EnumDoc;
diff --git a/packages/cli/authoring/doctypes/function/parse.d.mts b/packages/cli/authoring/doctypes/function/parse.d.mts
deleted file mode 100644
index d65e0149a8..0000000000
--- a/packages/cli/authoring/doctypes/function/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {FunctionDoc} from '../types';
-export function parseFunction(input: unknown, label?: string): FunctionDoc;
diff --git a/packages/cli/authoring/doctypes/function/parse.mjs b/packages/cli/authoring/doctypes/function/parse.mjs
index aec4faf77b..81e404ac7c 100644
--- a/packages/cli/authoring/doctypes/function/parse.mjs
+++ b/packages/cli/authoring/doctypes/function/parse.mjs
@@ -2,9 +2,29 @@
/**
* @file Function doc parser (stamped `type: 'function'`). Hooks and CLI/API
- * functions share the discriminant and the sealed schema, so this is the same
- * validator as `parseHook`, exported under the general name. Consumers call
- * `parseFunction` or use `parseDoc`.
+ * functions share the discriminant and the sealed schema, so this delegates to
+ * the same validator as `parseHook`. Consumers call `parseFunction` or use
+ * `parseDoc`.
+ *
+ * This is a wrapper rather than `export {parseHook as parseFunction}` on
+ * purpose: a bare re-export publishes `parseHook`'s narrower `HookDoc` return
+ * type under the general name. `label` is forwarded untouched so `parseHook`'s
+ * own default still supplies the message prefix.
*/
-export {parseHook as parseFunction} from '../hook/parse.mjs';
+import {parseHook} from '../hook/parse.mjs';
+
+/** @typedef {import('../types').FunctionDoc} FunctionDoc */
+
+/**
+ * Validate an unknown value as a stamped function doc, or throw.
+ *
+ * @param {unknown} input
+ * @param {string} [label]
+ * @returns {FunctionDoc}
+ */
+export function parseFunction(input, label) {
+ return /** @type {FunctionDoc} */ (
+ /** @type {unknown} */ (parseHook(input, label))
+ );
+}
diff --git a/packages/cli/authoring/doctypes/hook/parse.d.mts b/packages/cli/authoring/doctypes/hook/parse.d.mts
deleted file mode 100644
index 80f0bec52b..0000000000
--- a/packages/cli/authoring/doctypes/hook/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {HookDoc} from '../types';
-export function parseHook(input: unknown, label?: string): HookDoc;
diff --git a/packages/cli/authoring/doctypes/legacy.d.mts b/packages/cli/authoring/doctypes/legacy.d.mts
deleted file mode 100644
index bc0b6d6836..0000000000
--- a/packages/cli/authoring/doctypes/legacy.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {ComponentDoc, HookDoc} from './types';
-export function parseLegacyDoc(input: unknown, label?: string): ComponentDoc | HookDoc;
diff --git a/packages/cli/authoring/doctypes/parse.d.mts b/packages/cli/authoring/doctypes/parse.d.mts
deleted file mode 100644
index bcea907a99..0000000000
--- a/packages/cli/authoring/doctypes/parse.d.mts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {
- ComponentDoc,
- HookDoc,
- FunctionDoc,
- ReferenceDoc,
- TemplateDoc,
- SchemaDoc,
- CommandDoc,
- EnumDoc,
-} from './types';
-
-// Must stay in step with the @returns of parseDoc in ./parse.mjs — one entry per
-// doc kind it dispatches to. This declaration shadows the implementation for
-// published consumers, so a missing member silently makes that kind unnarrowable.
-// check:cli-structure enforces the coverage.
-export function parseDoc(
- input: unknown,
- label?: string,
-): ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc;
diff --git a/packages/cli/authoring/doctypes/reference/parse.d.mts b/packages/cli/authoring/doctypes/reference/parse.d.mts
deleted file mode 100644
index c5c519c2a7..0000000000
--- a/packages/cli/authoring/doctypes/reference/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {ReferenceDoc} from '../types';
-export function parseReference(input: unknown, label?: string): ReferenceDoc;
diff --git a/packages/cli/authoring/doctypes/schema/parse.d.mts b/packages/cli/authoring/doctypes/schema/parse.d.mts
deleted file mode 100644
index 50550ae09f..0000000000
--- a/packages/cli/authoring/doctypes/schema/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {SchemaDoc} from '../types';
-export function parseSchema(input: unknown, label?: string): SchemaDoc;
diff --git a/packages/cli/authoring/doctypes/template/parse.d.mts b/packages/cli/authoring/doctypes/template/parse.d.mts
deleted file mode 100644
index 01947e6101..0000000000
--- a/packages/cli/authoring/doctypes/template/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {TemplateDoc} from '../types';
-export function parseTemplate(input: unknown, label?: string): TemplateDoc;
diff --git a/packages/cli/authoring/integration/parse.d.mts b/packages/cli/authoring/integration/parse.d.mts
deleted file mode 100644
index e04b4aa60a..0000000000
--- a/packages/cli/authoring/integration/parse.d.mts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import type {AstryxIntegration} from './type';
-export function parseIntegration(input: unknown, label?: string): AstryxIntegration;
diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjs
index 6103f1ba91..348eea374e 100644
--- a/packages/cli/foundation/config/project.mjs
+++ b/packages/cli/foundation/config/project.mjs
@@ -42,15 +42,15 @@ import {
} from '../discovery/component-discovery.mjs';
import {findCoreDir} from '../fs/paths.mjs';
import {
- discoverTemplates,
+ discoverAll as discoverTemplates,
discoverIntegrationTemplatesForOne,
-} from '../../api/template/template.mjs';
+} from '../discovery/template-adapter.mjs';
import {getTransformsBetween} from '../../assets/codemods/registry.mjs';
import {
discoverIntegrationCodemods,
selectIntegrationCodemods,
} from '../../assets/codemods/integration-discovery.mjs';
-import {validateLoadedIntegration} from '../../api/integration/validate-integration.mjs';
+import {validateLoadedIntegration} from '../integrations/validate-contributions.mjs';
import {
InMemoryConfigCache,
cacheKey,
diff --git a/packages/cli/api/template/_adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjs
similarity index 94%
rename from packages/cli/api/template/_adapter.mjs
rename to packages/cli/foundation/discovery/template-adapter.mjs
index fce74b0c44..87f327d5a6 100644
--- a/packages/cli/api/template/_adapter.mjs
+++ b/packages/cli/foundation/discovery/template-adapter.mjs
@@ -1,28 +1,33 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Shared discovery + IO for the template command family.
+ * @file Shared template discovery + IO.
*
- * This adapter owns everything the template leaves (list/show/skeleton/copy)
- * AND other commands (component, layout, search, init, discover,
- * validate-integration) share: template discovery across core/external/
- * integration sources, the template-spec loaders, and the cross-command
- * helpers (stripTemplateAssetRefs, findShowcase, findRelatedBlocks,
- * extractComponents, listTemplates). The `template.mjs` barrel re-exports the
- * public helpers so external import paths (`api/template/template.mjs`) keep
- * working unchanged.
+ * Owns everything the template leaves (list/show/skeleton/copy) AND other
+ * commands (component, layout, search, init, discover, validate-integration)
+ * share: template discovery across core/external/integration sources, the
+ * template-spec loaders, and the cross-command helpers (stripTemplateAssetRefs,
+ * findShowcase, findRelatedBlocks, extractComponents, listTemplates). The
+ * `api/template/template.mjs` barrel re-exports the public helpers so external
+ * import paths keep working unchanged.
*
- * @position api/template — shared discovery/IO under the template leaves;
- * consumed by the leaves and re-exported by the template barrel.
+ * Lives in foundation rather than under api/template because foundation itself
+ * needs it: `Project` assembles templates from it. While this sat in api/, that
+ * made a cycle across the layer boundary — Project reached up for discovery and
+ * this module imported Project back. Nothing here depends on api/; every import
+ * is node:*, jiti, foundation/*, or authoring/*.
+ *
+ * @position packages/cli/foundation/discovery — shared template discovery/IO;
+ * consumed by Project and by the api/template leaves.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import {createJiti} from 'jiti';
-import {loadModuleWithParser} from '../../foundation/fs/module-loader.mjs';
+import {loadModuleWithParser} from '../fs/module-loader.mjs';
import {parseTemplate} from '../../authoring/doctypes/template/parse.mjs';
-import {CLI_ROOT, discoverExternalPackages} from '../../foundation/fs/paths.mjs';
-import {Project} from '../../foundation/config/project.mjs';
+import {CLI_ROOT, discoverExternalPackages} from '../fs/paths.mjs';
+import {Project} from '../config/project.mjs';
/** Identity used for core (built-in) templates in package-scoped listings. */
const CORE_PACKAGE = '@astryxdesign/core';
@@ -458,7 +463,7 @@ async function discoverIntegrationTemplates(cwd = process.cwd()) {
try {
const project = await Project.load(cwd);
loadedIntegrations =
- /** @type {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} */ (
+ /** @type {import('../integrations/integrations.mjs').LoadedIntegration[]} */ (
project.loadedIntegrations
);
} catch (err) {
diff --git a/packages/cli/foundation/integrations/integration-warnings.mjs b/packages/cli/foundation/integrations/integration-warnings.mjs
index 3ac201151a..945fe88935 100644
--- a/packages/cli/foundation/integrations/integration-warnings.mjs
+++ b/packages/cli/foundation/integrations/integration-warnings.mjs
@@ -19,7 +19,7 @@
* ADDS a one-line nudge.
*/
-import {validateLoadedIntegration} from '../../api/integration/validate-integration.mjs';
+import {validateLoadedIntegration} from './validate-contributions.mjs';
/**
* For each configured (already-loaded) integration, compute its issues using
diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjs
new file mode 100644
index 0000000000..7522e8a4b1
--- /dev/null
+++ b/packages/cli/foundation/integrations/validate-contributions.mjs
@@ -0,0 +1,162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file On-disk contribution checks for a LOADED integration.
+ *
+ * These validators live in foundation rather than beside the
+ * `validate-integration` command because foundation itself needs them:
+ * `Project` collects integration issues while assembling components/templates,
+ * and `integration-warnings` nudges about them on ordinary commands. Keeping
+ * them here means those callers no longer reach up into `api/`.
+ *
+ * The manifest schema is NOT re-validated here — `loadIntegrations` already did
+ * that and throws otherwise. What is re-checked is the on-disk contributions
+ * (roots + codemods/templates/components), because those regress independently
+ * of the manifest: a deleted directory, a template that lost its source file.
+ *
+ * @input a loaded-integration-shaped object (absolute contribution roots + identity)
+ * @output AstryxIntegrationIssue[]
+ * @position packages/cli/foundation/integrations — shared contribution validators
+ */
+
+import * as fs from 'node:fs';
+import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';
+import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';
+import * as componentDiscovery from '../discovery/component-discovery.mjs';
+
+/**
+ * @typedef {import('./issue').AstryxIntegrationIssue} Issue
+ * @typedef {import('./integrations.mjs').LoadedIntegration} LoadedIntegration
+ */
+
+/** @param {string} code @param {string} message @returns {Issue} */
+export function issueError(code, message) {
+ return {code, severity: 'error', message};
+}
+
+/**
+ * Verify each declared contribution root exists on disk. A declared-but-missing
+ * root is a `missing_root` error.
+ * @param {{components?: string, templates?: string, codemods?: string}} resolved
+ * absolute resolved roots (undefined when not declared)
+ * @param {Issue[]} issues
+ */
+function checkRoots(resolved, issues) {
+ const kinds = /** @type {const} */ (['components', 'templates', 'codemods']);
+ for (const kind of kinds) {
+ const root = resolved[kind];
+ if (root == null) continue;
+ if (!fs.existsSync(root)) {
+ issues.push(
+ issueError(
+ 'missing_root',
+ `Declared ${kind} root does not exist on disk: ${root}`,
+ ),
+ );
+ }
+ }
+}
+
+/**
+ * Validate the integration's codemods via the landed discovery. Discovery is
+ * strict (throws on bad export / duplicate id); we convert any throw into an
+ * `invalid_codemod` error.
+ * @param {LoadedIntegration} integration loaded-integration-shaped object
+ * @param {Issue[]} issues
+ */
+async function checkCodemods(integration, issues) {
+ if (!integration.codemods || !fs.existsSync(integration.codemods)) return;
+ try {
+ await discoverIntegrationCodemods([integration]);
+ } catch (err) {
+ issues.push(issueError('invalid_codemod', /** @type {any} */ (err).message));
+ }
+}
+
+/**
+ * Validate the integration's templates via the landed discovery. Per-template
+ * problems are reported as `invalid_template` errors.
+ * @param {LoadedIntegration} integration loaded-integration-shaped object
+ * @param {Issue[]} issues
+ */
+async function checkTemplates(integration, issues) {
+ if (!integration.templates || !fs.existsSync(integration.templates)) return;
+ try {
+ const {errors} = await discoverIntegrationTemplatesForOne(integration);
+ for (const e of errors) {
+ issues.push(issueError('invalid_template', e.message));
+ }
+ } catch (err) {
+ issues.push(issueError('invalid_template', /** @type {any} */ (err).message));
+ }
+}
+
+/**
+ * Validate the integration's components via the landed ownership discovery.
+ * Feature-detected: if the component-ownership export isn't present in this
+ * build (sibling PR not yet merged), component validation is skipped rather
+ * than hard-failing.
+ *
+ * `discoverIntegrationComponents` returns ownership records and does not throw
+ * on a missing same-stem source — it records `sourcePath: null`. We surface
+ * each such record as an `invalid_component` error.
+ * @param {LoadedIntegration} integration loaded-integration-shaped object
+ * @param {Issue[]} issues
+ */
+async function checkComponents(integration, issues) {
+ if (!integration.components || !fs.existsSync(integration.components)) return;
+ const discover = componentDiscovery.discoverIntegrationComponents;
+ if (typeof discover !== 'function') return; // feature not present yet
+ try {
+ const records = (await discover(integration)) ?? [];
+ for (const record of records) {
+ if (record?.sourcePath == null) {
+ issues.push(
+ issueError(
+ 'invalid_component',
+ `Component "${record?.name}" is missing its same-stem source file ${record?.name}.tsx.`,
+ ),
+ );
+ }
+ }
+ } catch (err) {
+ issues.push(issueError('invalid_component', /** @type {any} */ (err).message));
+ }
+}
+
+/**
+ * Run every contribution validator against a loaded-integration-shaped object.
+ * @param {LoadedIntegration} integration
+ * @param {Issue[]} issues
+ */
+async function runContributionChecks(integration, issues) {
+ await checkCodemods(integration, issues);
+ await checkTemplates(integration, issues);
+ await checkComponents(integration, issues);
+}
+
+/**
+ * Validate an already-LOADED integration (as produced by `loadIntegrations` —
+ * absolute contribution roots plus identity) and return its issues. This is the
+ * reuse seam for everyday commands that have already loaded the configured
+ * integrations and want the SAME validators that `validate-integration` runs,
+ * without re-resolving the manifest from disk.
+ *
+ * @param {LoadedIntegration} loaded loaded-integration-shaped object
+ * @returns {Promise<Issue[]>}
+ */
+export async function validateLoadedIntegration(loaded) {
+ /** @type {Issue[]} */
+ const issues = [];
+ if (!loaded || typeof loaded !== 'object') return issues;
+ checkRoots(
+ {
+ components: loaded.components,
+ templates: loaded.templates,
+ codemods: loaded.codemods,
+ },
+ issues,
+ );
+ await runContributionChecks(loaded, issues);
+ return issues;
+}
diff --git a/packages/cli/scripts/sync-api-types.mjs b/packages/cli/scripts/sync-api-types.mjs
index 87a835bae8..089a9756e8 100644
--- a/packages/cli/scripts/sync-api-types.mjs
+++ b/packages/cli/scripts/sync-api-types.mjs
@@ -1,18 +1,23 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Generate the public `./api` type surface from the JSDoc source of truth.
+ * @file Generate the published type surface from the JSDoc source of truth.
*
- * Functions own their types: each api leaf's `@returns` + colocated
- * `.type.mjs` typedefs ARE the contract. This script runs `tsc`
- * (allowJs + checkJs + declaration + emitDeclarationOnly) over the api sources
- * into a throwaway temp dir, then copies just the emitted api declaration tree
- * (the `.d.mts` files) back alongside the sources (so their relative imports and
- * shared `types` declarations resolve). `api/index.d.mts` is the entry that
- * `package.json` exports["./api"].types points at.
+ * Functions own their types: a leaf's `@returns` + its colocated `.type.mjs`
+ * typedefs ARE the contract. This script runs `tsc` (allowJs + checkJs +
+ * declaration + emitDeclarationOnly) over the source trees into a throwaway
+ * temp dir, then copies the emitted declaration trees (the `.d.mts` files) back
+ * alongside their sources (so relative imports and shared `types` declarations
+ * resolve). `api/index.d.mts` is the entry `package.json` exports["./api"].types
+ * points at.
*
- * The emitted `api/**\/*.d.mts` are NOT committed (they're gitignored, like the
- * other packages' `dist/`). This script runs automatically at `prepack`, so
+ * Three trees are emitted (see TREES): `api` and `authoring` are published
+ * entry points, and `foundation` is included because the `api` declarations
+ * re-export from it — without it a consumer resolving those re-exports hits
+ * TS7016 on the packed surface.
+ *
+ * The emitted `.d.mts` are NOT committed (they're gitignored, like the other
+ * packages' `dist/`). This script runs automatically at `prepack`, so
* `pnpm pack`/`pnpm publish` always ships a freshly generated, in-sync surface.
* Run `pnpm sync:api-types` to produce them locally; the published surface is
* verified end-to-end by `.github/scripts/cli-api-types-verify.mjs`.
@@ -27,17 +32,27 @@ import {fileURLToPath} from 'node:url';
const CLI_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const TMP = '/tmp/astryx-dts-build';
-const EMITTED_API = path.join(TMP, 'packages', 'cli', 'api');
-const DEST_API = path.join(CLI_ROOT, 'api');
+
+/**
+ * The source trees whose `.mjs` JSDoc is the contract. Emitted in one tsc pass
+ * (they share types), then copied back beside their sources.
+ *
+ * `foundation` is here because the published `./api` declarations re-export
+ * from it (e.g. api/template re-exports the template adapter): a consumer
+ * resolving those re-exports needs foundation's declarations too, or it hits
+ * TS7016 on the packed surface.
+ */
+const TREES = ['api', 'authoring', 'foundation'];
/**
* Banner prepended to every emitted declaration so it's obvious the file is
* generated and must not be hand-edited — edit the `.mjs` JSDoc and re-run
* `pnpm sync:api-types` instead. The `@generated` tag is the standard marker
* tooling and reviewers recognize.
+ * @param {string} tree
*/
-const BANNER =
- '// @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.\n' +
+const banner = tree =>
+ `// @generated by scripts/sync-api-types.mjs from the JSDoc in ${tree}/**/*.mjs.\n` +
'// DO NOT EDIT — run `pnpm sync:api-types` to regenerate.\n\n';
/**
@@ -45,16 +60,17 @@ const BANNER =
* structure and prepending the generated banner.
* @param {string} src
* @param {string} dest
+ * @param {string} tree
*/
-function copyDts(src, dest) {
+function copyDts(src, dest, tree) {
for (const entry of fs.readdirSync(src, {withFileTypes: true})) {
const s = path.join(src, entry.name);
const d = path.join(dest, entry.name);
if (entry.isDirectory()) {
- copyDts(s, d);
+ copyDts(s, d, tree);
} else if (entry.name.endsWith('.d.mts')) {
fs.mkdirSync(dest, {recursive: true});
- fs.writeFileSync(d, BANNER + fs.readFileSync(s, 'utf8'));
+ fs.writeFileSync(d, banner(tree) + fs.readFileSync(s, 'utf8'));
}
}
}
@@ -76,14 +92,17 @@ function cleanDts(dir) {
}
fs.rmSync(TMP, {recursive: true, force: true});
-cleanDts(DEST_API);
+for (const tree of TREES) cleanDts(path.join(CLI_ROOT, tree));
execFileSync('pnpm', ['exec', 'tsc', '--project', 'tsconfig.api-dts.json'], {
cwd: CLI_ROOT,
stdio: 'inherit',
});
-if (!fs.existsSync(EMITTED_API)) {
- throw new Error(`Expected emitted declarations at ${EMITTED_API} — tsc produced nothing.`);
+for (const tree of TREES) {
+ const emitted = path.join(TMP, 'packages', 'cli', tree);
+ if (!fs.existsSync(emitted)) {
+ throw new Error(`Expected emitted declarations at ${emitted} — tsc produced nothing.`);
+ }
+ copyDts(emitted, path.join(CLI_ROOT, tree), tree);
}
-copyDts(EMITTED_API, DEST_API);
fs.rmSync(TMP, {recursive: true, force: true});
-console.log('Synced ./api declarations from the JSDoc source of truth.');
+console.log(`Synced ${TREES.join(' + ')} declarations from the JSDoc source of truth.`);
diff --git a/packages/cli/tsconfig.api-dts.json b/packages/cli/tsconfig.api-dts.json
index 3d8b1d0e05..93e299c704 100644
--- a/packages/cli/tsconfig.api-dts.json
+++ b/packages/cli/tsconfig.api-dts.json
@@ -12,8 +12,10 @@
"include": [
"api/**/*.mjs",
"api/**/*.d.ts",
- "foundation/**/*.d.ts",
- "authoring/**/*.d.ts",
+ "authoring/**/*.mjs",
+ "authoring/**/*.ts",
+ "foundation/**/*.mjs",
+ "foundation/**/*.ts",
"clients/cli/lib/*.d.ts",
"assets/codemods/*.d.ts"
],
diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjs
index 0ecd83ab8a..4e98633129 100644
--- a/scripts/check-cli-structure.mjs
+++ b/scripts/check-cli-structure.mjs
@@ -9,16 +9,16 @@
* precisely what typechecking and unit tests cannot see — every individual file
* is valid, the set is incomplete.
*
- * 1. Every doc-type ships a complete quartet:
+ * 1. Every doc-type ships a complete trio, and re-exports its parser from the
+ * authoring barrel:
* type.ts the authored shape
* parse.mjs the sealed parser (the CLI's load boundary)
- * parse.d.mts the parser's declaration
* <kind>.doc.mjs the doc-type documenting itself
- * The declaration is not optional: `authoring/index.d.ts` re-exports each
- * parser, so a missing parse.d.mts makes a strict consumer of the published
- * package resolve it as `any`. That shipped once and only surfaced at pack
- * time in CI (TS7016) — long after local typechecks passed clean, because
- * they run with checkJs and never exercise the packed ./api type surface.
+ * The parser's `.d.mts` declaration is deliberately NOT checked here: it is
+ * generated from the `.mjs` JSDoc by scripts/sync-api-types.mjs, so it can
+ * neither go missing nor drift. (Both failure modes shipped once while those
+ * declarations were hand-written — a missing file surfaced as TS7016 at pack
+ * time, and a stale parseDoc union silently dropped three doc kinds.)
*
* 2. Every api/<name>/ leaf carries its colocated contract and proof:
* *.type.mjs the Options + { type, data } response typedefs, or a
@@ -73,17 +73,26 @@ let apiCount = 0;
// ── 1. doc-type quartets ────────────────────────────────────────────────
const authoringIndexTypes = fs.readFileSync(path.join(CLI, 'authoring/index.d.ts'), 'utf8');
const authoringIndexImpl = fs.readFileSync(path.join(CLI, 'authoring/index.mjs'), 'utf8');
-const aggregateParseDecl = fs.readFileSync(
- path.join(DOCTYPES, 'parse.d.mts'),
- 'utf8',
-);
+/**
+ * parseDoc's own `@returns {...}` union — the source the emitted declaration
+ * derives from. Scoped to the JSDoc block immediately above `export function
+ * parseDoc`: the file also carries a `@typedef` line per kind, so matching the
+ * whole file would find every kind name and never fail.
+ */
+const parseSrc = fs.readFileSync(path.join(DOCTYPES, 'parse.mjs'), 'utf8');
+const parseDocJsdoc = parseSrc.slice(0, parseSrc.indexOf('export function parseDoc'));
+const returnsMatches = parseDocJsdoc.match(/@returns\s*\{[^}]*\}/g) ?? [];
+const aggregateParserReturns = returnsMatches[returnsMatches.length - 1] ?? '';
+if (!aggregateParserReturns) {
+ errors.push('could not find a @returns union on parseDoc in authoring/doctypes/parse.mjs');
+}
for (const kind of dirsIn(DOCTYPES)) {
if (DOCTYPE_EXEMPT.has(kind)) continue;
doctypeCount++;
const dir = path.join(DOCTYPES, kind);
- for (const required of ['type.ts', 'parse.mjs', 'parse.d.mts', `${kind}.doc.mjs`]) {
+ for (const required of ['type.ts', 'parse.mjs', `${kind}.doc.mjs`]) {
if (!fs.existsSync(path.join(dir, required))) {
errors.push(
`doc-type "${kind}" is missing authoring/doctypes/${kind}/${required}`,
@@ -100,14 +109,14 @@ for (const kind of dirsIn(DOCTYPES)) {
errors.push(`doc-type "${kind}" parser is not re-exported from authoring/index.mjs`);
}
- // The aggregate parseDoc declaration shadows its implementation for published
- // consumers, so a kind missing from that union is silently unnarrowable —
- // `type === 'schema'` reads as a no-overlap comparison and `fields` is
- // inaccessible. Existence of parse.d.mts is not enough; it must cover the kind.
+ // parseDoc's own `@returns` is what the generated declaration derives its
+ // return union from, so a kind missing there is silently unnarrowable for
+ // consumers (`type === 'schema'` reads as a no-overlap comparison). Checking
+ // the JSDoc catches it at the source rather than in the emitted artifact.
const docType = `${kind[0].toUpperCase()}${kind.slice(1)}Doc`;
- if (!aggregateParseDecl.includes(docType)) {
+ if (!aggregateParserReturns.includes(docType)) {
errors.push(
- `doc-type "${kind}" is missing from the parseDoc return union in authoring/doctypes/parse.d.mts (expected ${docType})`,
+ `doc-type "${kind}" is missing from the @returns union of authoring/doctypes/parse.mjs (expected ${docType})`,
);
}
}