create-kerf-component 5.0.0-beta.13 → 5.0.0-beta.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,16 +11,28 @@ npm create kerf-component@latest my-widgets
11
11
  cd my-widgets
12
12
  npm install
13
13
  npm run build
14
+ npm run catalog:check
15
+ npm run check:styles
14
16
  ```
15
17
 
16
18
  Run it with **no argument** (`npm create kerf-component`) and it prompts for the
17
19
  directory. Pass `.` to scaffold into the current directory. The target
18
- directory's basename is used as the package name.
20
+ directory's basename is used as the package name; pass `--name` to choose
21
+ another, such as a scoped name:
22
+
23
+ ```bash
24
+ npm create kerf-component@latest widgets -- --name @acme/widgets
25
+ ```
26
+
27
+ Any other argument that starts with `-` is rejected as an unknown option.
28
+ The initializer installs nothing beyond itself: TypeScript is only an optional
29
+ peer of the `kerf-component-catalog` command, which runs inside your
30
+ TypeScript project.
19
31
 
20
32
  ## What you get
21
33
 
22
34
  A ready-to-publish component package that encodes the rules from the kerf docs
23
- (*Building reusable component packages*):
35
+ (_Building reusable component packages_):
24
36
 
25
37
  - **`kerfjs` as a `peerDependency`, `external` in the tsup build** — never
26
38
  bundled, so `isSafeHtml` brand checks and signal identity stay intact across
@@ -35,6 +47,80 @@ A ready-to-publish component package that encodes the rules from the kerf docs
35
47
  component needs:
36
48
  - **per-instance state via a factory + props** (`createCounter` → `<Counter store={…} />`), and
37
49
  - **a `wire(root)` delegation disposer** (`wireCounter`) instead of inline event handlers.
50
+ - **A stylesheet that owns only its component** (`src/counter.css`, exported as
51
+ `./counter.css`): it styles `.kerf-counter` and its own internals, writes only
52
+ `--_kerf-counter-*` private variables (the context it gives its buttons is
53
+ named after Counter), exposes a typed `size` prop and one public token
54
+ (`--kerf-counter-gap`) as its configuration, and adapts itself inside a Kerf
55
+ UI Toolbar from its own stylesheet (`.kui-toolbar .kerf-counter`). `npm run
56
+ check:styles` runs `kerf-ui-analyze` (from the `@kerfjs/ui` dev dependency)
57
+ over `src/`, so a rule that restyles another package's component, touches
58
+ its private variables, overrides a token a typed prop sets, or uses a hook
59
+ class (`KUI-L019`–`KUI-L022`) fails before `prepublishOnly` publishes.
60
+ - **Author-owned AI metadata** in `kerf.components.json`, with explicit purpose,
61
+ exports, composition, geometry, public `rootClass`, tokens, accessibility,
62
+ and source links. Run
63
+ `npm run catalog:generate` to emit the package-qualified
64
+ `component-composition.json`; `npm run catalog:check` fails on drift, deleted
65
+ sources, renamed exports, duplicate ids, an omitted author decision, or any
66
+ source/output field that violates the shipped schemas. Export verification
67
+ uses the TypeScript/TSX syntax tree, so JSX text, nested scopes, comments, and
68
+ string/template/regular-expression literals cannot masquerade as public
69
+ exports. The scaffold already declares TypeScript; run `npm install` before
70
+ invoking its copied local checker in a fresh offline directory.
71
+ - **A structured prop schema**, `component-props.json`. `npm run props:generate`
72
+ builds the package, then runs `kerf-ui-props` (from `@kerfjs/ui`) over the
73
+ built declarations, so Kerf UI view tools (the editor, `validateView`,
74
+ `kerf-ui-view`) can use the package's components. `npm run props:check` fails
75
+ when the committed file is stale; `prepublishOnly` regenerates it.
76
+ A component whose wiring helper writes runtime `data-*` state onto its DOM
77
+ can declare it under `composition.wiring.stateAttributes` — each item is
78
+ `{ name, on, helper, meaning }`, where `name` is a `data-*` name, `on` is the
79
+ element that carries it, and `helper` is one of `wiring.helpers`. Apps must
80
+ not render, remove, or treat those attributes as their own state. The field
81
+ is optional; names must be unique per component, and the checker rejects a
82
+ helper that is not listed in `wiring.helpers`.
83
+ `boundaries.placeableClasses` (optional) names the public classes an app may
84
+ write onto its own elements; every other public class is the component's
85
+ rendered anatomy, which `eslint-plugin-kerfjs` reports on an app-owned
86
+ element as `KUI-L103` with the component to render. `boundaries.rootElement`
87
+ names the element the component itself renders around its placeable classes,
88
+ so a plain element of that tag carrying them is reported too. Placeable
89
+ classes must be public; `rootElement` requires them.
90
+ A wrapper that renders a cataloged component declares it under
91
+ `composition.rendersAs` (for example
92
+ `["@kerfjs/ui:toolbar-control-group"]`), so the `ui-composition` lint treats
93
+ it as that root. Every key must resolve to an entry generated in the same run
94
+ or to an installed package's catalog.
95
+ A container that already insets its content in some form (an embedded
96
+ appearance) declares `composition.insetFreeChildren`: prop conditions such as
97
+ `[{ "prop": "appearance", "equals": "embedded" }]`. While one holds, the
98
+ `ui-composition` lint reports a direct child whose geometry is `self` on
99
+ margin, border, and padding as `KUI-L204` (a double inset). An inset-bearing
100
+ component that has an inset-free form declares `composition.insetFreeWhen`
101
+ (`[{ "prop": "flush", "equals": true }]`, where a bare boolean prop equals
102
+ `true`), which the lint accepts and names as the fix. Both fields are
103
+ optional non-empty lists of `{ prop, equals }`; `prop` is a JSX prop name and
104
+ `equals` a string, number, or boolean. The generator copies them into the
105
+ catalog entry unchanged.
106
+ A component that renders a native control, link, or label declares
107
+ `composition.content`: `{ "interactive": [{ "kind": "root" }] }` when the
108
+ control is its root, `"contains"` when it renders one inside, and
109
+ `"whenProps": ["href"]` when only those props make it so; `exports` gives
110
+ another JSX export its own rules. `@kerfjs/ui`'s view validator then reports
111
+ a control placed in a `root` component's zones as `KUI-V014`. Omitted, the
112
+ component's placements are unchecked.
113
+ Each `publicExports` item names a `package.json#exports` subpath that maps to
114
+ the `src/` file exporting it. A private, bundled application
115
+ (`package.json#private: true`) has no per-file `dist/` entries and is never
116
+ imported by package name, so its items may omit `subpath`
117
+ (`{ "name": "DemandSegmentsControl" }`); the checker then verifies the name
118
+ against the component's `source` file, which is how the UI lint resolves the
119
+ wrapper. A subpath it does declare is still checked against `exports`.
120
+ `private: true` is the only opt-in: a `.kerf-ui-profile.json` `scope` does
121
+ not change this. An application that is published to npm (an app shell), or
122
+ whose manifest omits `private`, either declares a real `subpath` for each
123
+ item or sets `"private": true`.
38
124
 
39
125
  ## Layout produced
40
126
 
@@ -43,13 +129,37 @@ my-widgets/
43
129
  ├── package.json # peerDependencies.kerfjs, exports map, publish files
44
130
  ├── tsconfig.json # jsxImportSource: "kerfjs"
45
131
  ├── tsup.config.ts # external: ['kerfjs'], format esm, dts
132
+ ├── kerf.components.json # explicit source metadata (never inferred from pixels)
133
+ ├── component-composition.json # deterministic generated AI catalog
134
+ ├── scripts/
135
+ │ ├── kerf-component-catalog.mjs # local generator + check mode
136
+ │ ├── catalog/ # the generator's modules (validation, export discovery, generation)
137
+ │ ├── component-metadata.schema.json # author-source schema used by the checker
138
+ │ ├── component-composition.schema.json # emitted-catalog schema used by the checker
139
+ │ └── component-catalog-extension.schema.json # optional selection-catalog schema
46
140
  ├── LICENSE # MIT license with the package contributor notice
47
141
  ├── .gitignore
48
142
  ├── README.md
49
143
  └── src/
50
144
  ├── index.ts # public barrel
51
- └── counter.tsx # factory + component + wire() disposer
145
+ ├── counter.tsx # factory + component + wire() disposer
146
+ └── counter.css # styles only Counter; configured by props and tokens
52
147
  ```
53
148
 
54
149
  This package is part of the kerf repository and releases in lockstep with
55
- `kerfjs`.
150
+ `kerfjs`. The 5.0.0 template targets `kerfjs` and `@kerfjs/ui` on the 5.x
151
+ line; the generated package keeps Kerf as a peer dependency and uses UI only
152
+ for its authoring checks.
153
+
154
+ The package also exposes `kerf-component-catalog`. It accepts `--write` (the
155
+ default), `--check`, and `--root <path>`. A root package with npm `workspaces`
156
+ generates every child package that declares `package.json#kerfComponentCatalog`,
157
+ in deterministic package and component order. Set
158
+ `kerfComponentCatalog.selectionOutput` and give each component a `selection`
159
+ block (`useWhen`, `avoidWhen`, …) to also generate and check the `@kerfjs/ui`
160
+ selection catalog extension from the same `kerf.components.json`.
161
+
162
+ Application projects do not need this package scaffold. `npx kerfjs setup
163
+ --ui` creates an empty, schema-valid author metadata file, wires this catalog
164
+ command, and publishes the generated app catalog through the workspace UI
165
+ profile.
@@ -0,0 +1,112 @@
1
+ // Syntax-aware discovery of a source file's named exports, using the project's
2
+ // installed TypeScript parser so JSX text, nested scopes, comments, strings,
3
+ // templates, and regex literals cannot impersonate an export.
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { join } from 'node:path';
7
+
8
+ let typescript;
9
+
10
+ function typescriptApi() {
11
+ if (typescript) return typescript;
12
+ try {
13
+ typescript = createRequire(import.meta.url)('typescript');
14
+ return typescript;
15
+ } catch {
16
+ throw new Error(
17
+ 'TypeScript is required for syntax-aware export verification; install it in this project (npm install --save-dev typescript) before catalog generation.',
18
+ );
19
+ }
20
+ }
21
+
22
+ function hasModifier(ts, node, kind) {
23
+ return Boolean(node.modifiers?.some((modifier) => modifier.kind === kind));
24
+ }
25
+
26
+ function bindingNames(ts, name, names) {
27
+ if (ts.isIdentifier(name)) names.add(name.text);
28
+ else
29
+ for (const element of name.elements ?? [])
30
+ if (!ts.isOmittedExpression(element))
31
+ bindingNames(ts, element.name, names);
32
+ }
33
+
34
+ function parseSource(ts, source, fileName) {
35
+ const sourceFile = ts.createSourceFile(
36
+ fileName,
37
+ source,
38
+ ts.ScriptTarget.Latest,
39
+ true,
40
+ fileName.endsWith('.tsx') || fileName.endsWith('.jsx')
41
+ ? ts.ScriptKind.TSX
42
+ : ts.ScriptKind.TS,
43
+ );
44
+ if (sourceFile.parseDiagnostics.length) {
45
+ const diagnostic = sourceFile.parseDiagnostics[0];
46
+ const point = sourceFile.getLineAndCharacterOfPosition(
47
+ diagnostic.start ?? 0,
48
+ );
49
+ throw new Error(
50
+ `${fileName}:${point.line + 1}:${point.character + 1}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`,
51
+ );
52
+ }
53
+ return sourceFile;
54
+ }
55
+
56
+ // The names one top-level statement exports. Default exports have no name a
57
+ // catalog can refer to, and `export *` re-exports are not followed.
58
+ function statementExports(ts, statement, names) {
59
+ if (ts.isExportDeclaration(statement)) {
60
+ if (statement.exportClause && ts.isNamedExports(statement.exportClause))
61
+ for (const element of statement.exportClause.elements)
62
+ names.add(element.name.text);
63
+ return;
64
+ }
65
+ if (
66
+ !hasModifier(ts, statement, ts.SyntaxKind.ExportKeyword) ||
67
+ hasModifier(ts, statement, ts.SyntaxKind.DefaultKeyword)
68
+ )
69
+ return;
70
+ if (ts.isVariableStatement(statement)) {
71
+ for (const declaration of statement.declarationList.declarations)
72
+ bindingNames(ts, declaration.name, names);
73
+ } else if (
74
+ (ts.isFunctionDeclaration(statement) ||
75
+ ts.isClassDeclaration(statement) ||
76
+ ts.isEnumDeclaration(statement) ||
77
+ ts.isModuleDeclaration(statement) ||
78
+ ts.isInterfaceDeclaration(statement) ||
79
+ ts.isTypeAliasDeclaration(statement)) &&
80
+ statement.name
81
+ )
82
+ names.add(statement.name.text);
83
+ }
84
+
85
+ /** The named exports of TypeScript/TSX `source`; throws on a syntax error. */
86
+ export function exportedNamesFromSource(source, fileName = 'component.tsx') {
87
+ const ts = typescriptApi();
88
+ const sourceFile = parseSource(ts, source, fileName);
89
+ const names = new Set();
90
+ for (const statement of sourceFile.statements)
91
+ statementExports(ts, statement, names);
92
+ return names;
93
+ }
94
+
95
+ export function exportedNamesFromFile(path) {
96
+ return exportedNamesFromSource(readFileSync(path, 'utf8'), path);
97
+ }
98
+
99
+ /** The `src/` file a `./dist/…` package export is built from, or null. */
100
+ export function sourceEntryForExport(packageRoot, definition) {
101
+ const target =
102
+ typeof definition === 'string'
103
+ ? definition
104
+ : (definition?.import ?? definition?.default);
105
+ if (typeof target !== 'string' || !target.startsWith('./dist/')) return null;
106
+ const stem = target.slice('./dist/'.length).replace(/\.(?:mjs|cjs|js)$/, '');
107
+ for (const extension of ['.ts', '.tsx', '.mts', '.js', '.jsx', '.mjs']) {
108
+ const candidate = join(packageRoot, 'src', `${stem}${extension}`);
109
+ if (existsSync(candidate)) return candidate;
110
+ }
111
+ return null;
112
+ }
@@ -0,0 +1,308 @@
1
+ // Catalog generation: author metadata in, deterministic composition (and
2
+ // optional selection) catalogs out, every problem collected into one
3
+ // CatalogError rather than stopping at the first.
4
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { dirname, join, relative, resolve } from 'node:path';
6
+ import process from 'node:process';
7
+
8
+ import { validateDocumentAgainstSchema } from './schema-validate.js';
9
+ import { catalogSchema, metadataSchema, selectionSchema } from './schemas.js';
10
+ import { buildSelectionCatalog, posixRelative } from './selection.js';
11
+ import { validateComponent } from './validate-component.js';
12
+ import {
13
+ CatalogError,
14
+ CONFIG_KEY,
15
+ configuredPackages,
16
+ readJson,
17
+ } from './workspace.js';
18
+
19
+ function toEntry(packageName, component) {
20
+ return {
21
+ key: `${packageName}:${component.id}`,
22
+ package: packageName,
23
+ id: component.id,
24
+ name: component.name,
25
+ kind: component.kind,
26
+ purpose: component.purpose,
27
+ publicExports: component.publicExports,
28
+ sourceLinks: component.sourceLinks,
29
+ source: component.source,
30
+ ...(component.composition.rendersAs
31
+ ? { rendersAs: component.composition.rendersAs }
32
+ : {}),
33
+ ...(component.composition.insetFreeChildren
34
+ ? { insetFreeChildren: component.composition.insetFreeChildren }
35
+ : {}),
36
+ ...(component.composition.insetFreeWhen
37
+ ? { insetFreeWhen: component.composition.insetFreeWhen }
38
+ : {}),
39
+ ...(component.composition.content
40
+ ? { content: component.composition.content }
41
+ : {}),
42
+ parents: component.composition.parents,
43
+ contexts: component.composition.contexts,
44
+ zones: component.composition.zones,
45
+ children: component.composition.children,
46
+ state: component.composition.state,
47
+ wiring: component.composition.wiring,
48
+ responsive: component.composition.responsive,
49
+ layout: component.composition.layout,
50
+ accessibility: component.accessibility,
51
+ boundaries: component.boundaries,
52
+ diagnostics: component.diagnostics,
53
+ provenance: component.provenance,
54
+ };
55
+ }
56
+
57
+ // The catalog keys a package's `rendersAs` may name: entries generated in this
58
+ // run, or those of an installed dependency's shipped catalog (its
59
+ // package.json#kerfComponentCatalog.output, or @kerfjs/ui's ai/ catalog).
60
+ function dependencyCatalogKeys(packageRoot, packageName, cache) {
61
+ const cacheKey = `${packageRoot}\0${packageName}`;
62
+ if (cache.has(cacheKey)) return cache.get(cacheKey);
63
+ let keys;
64
+ for (let dir = packageRoot; ; dir = dirname(dir)) {
65
+ const manifestPath = join(dir, 'node_modules', packageName, 'package.json');
66
+ if (existsSync(manifestPath)) {
67
+ keys = installedCatalogKeys(manifestPath);
68
+ break;
69
+ }
70
+ if (dirname(dir) === dir) break;
71
+ }
72
+ cache.set(cacheKey, keys);
73
+ return keys;
74
+ }
75
+
76
+ // The entry keys of one installed package's catalog; undefined when it has
77
+ // none that can be read.
78
+ function installedCatalogKeys(manifestPath) {
79
+ const dependencyRoot = dirname(manifestPath);
80
+ let catalogPath;
81
+ try {
82
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
83
+ if (manifest[CONFIG_KEY]?.output)
84
+ catalogPath = resolve(dependencyRoot, manifest[CONFIG_KEY].output);
85
+ } catch {
86
+ // An unreadable manifest falls back to the @kerfjs/ui catalog location.
87
+ }
88
+ catalogPath ??= join(dependencyRoot, 'ai', 'component-composition.json');
89
+ try {
90
+ const catalog = JSON.parse(readFileSync(catalogPath, 'utf8'));
91
+ return new Set(
92
+ (catalog.entries ?? []).map(
93
+ (entry) => entry.key ?? `${catalog.package}:${entry.id}`,
94
+ ),
95
+ );
96
+ } catch {
97
+ // No readable catalog: the package stays unresolved.
98
+ return undefined;
99
+ }
100
+ }
101
+
102
+ function validateRendersAs(results, diagnostics) {
103
+ const generated = new Map(
104
+ results.map(({ catalog }) => [
105
+ catalog.package,
106
+ new Set(catalog.entries.map((entry) => entry.key)),
107
+ ]),
108
+ );
109
+ const cache = new Map();
110
+ for (const { packageRoot, metadataPath, catalog } of results)
111
+ for (const entry of catalog.entries)
112
+ for (const root of entry.rendersAs ?? []) {
113
+ const at = `${metadataPath}: components.${entry.id}.composition.rendersAs`;
114
+ const rootPackage = root.slice(0, root.lastIndexOf(':'));
115
+ if (root === entry.key) {
116
+ diagnostics.push(`${at}: ${root} names the component itself`);
117
+ continue;
118
+ }
119
+ const keys =
120
+ generated.get(rootPackage) ??
121
+ dependencyCatalogKeys(packageRoot, rootPackage, cache);
122
+ if (!keys)
123
+ diagnostics.push(
124
+ `${at}: cannot resolve a component catalog for package ${rootPackage}; install it or generate its catalog`,
125
+ );
126
+ else if (!keys.has(root))
127
+ diagnostics.push(
128
+ `${at}: ${root} is not an entry in ${rootPackage}'s catalog`,
129
+ );
130
+ }
131
+ }
132
+
133
+ // A package's `kerfComponentCatalog` settings: `source` and `output` are
134
+ // required, and a `selectionOutput` must be a path distinct from `output`.
135
+ function validatePackageConfig(
136
+ packageRoot,
137
+ packagePath,
138
+ packageJson,
139
+ packageNames,
140
+ diagnostics,
141
+ ) {
142
+ const config = packageJson[CONFIG_KEY];
143
+ if (!packageJson.name)
144
+ diagnostics.push(`${packagePath}: package name is required`);
145
+ if (packageNames.has(packageJson.name))
146
+ diagnostics.push(
147
+ `${packagePath}: duplicate configured package name ${packageJson.name}`,
148
+ );
149
+ packageNames.add(packageJson.name);
150
+ for (const key of ['source', 'output'])
151
+ if (!config?.[key])
152
+ diagnostics.push(`${packagePath}#${CONFIG_KEY}.${key}: is required`);
153
+ if (
154
+ config?.selectionOutput !== undefined &&
155
+ (typeof config.selectionOutput !== 'string' ||
156
+ !config.selectionOutput ||
157
+ resolve(packageRoot, config.selectionOutput) ===
158
+ resolve(packageRoot, config.output ?? ''))
159
+ )
160
+ diagnostics.push(
161
+ `${packagePath}#${CONFIG_KEY}.selectionOutput: expected a path distinct from output`,
162
+ );
163
+ return config;
164
+ }
165
+
166
+ // Generate one configured package's catalogs; null when its metadata cannot
167
+ // be read or fails its schema (those diagnostics are already recorded).
168
+ function generatePackage(packageRoot, packageNames, diagnostics) {
169
+ const packagePath = join(packageRoot, 'package.json');
170
+ const packageJson = readJson(packagePath, packagePath, diagnostics);
171
+ if (!packageJson) return null;
172
+ const config = validatePackageConfig(
173
+ packageRoot,
174
+ packagePath,
175
+ packageJson,
176
+ packageNames,
177
+ diagnostics,
178
+ );
179
+ if (!config?.source || !config?.output) return null;
180
+ const metadataPath = resolve(packageRoot, config.source);
181
+ const metadata = readJson(metadataPath, metadataPath, diagnostics);
182
+ if (!metadata) return null;
183
+ const metadataDiagnostics = validateDocumentAgainstSchema(
184
+ metadata,
185
+ metadataSchema,
186
+ metadataPath,
187
+ );
188
+ diagnostics.push(...metadataDiagnostics);
189
+ if (metadataDiagnostics.length) return null;
190
+
191
+ const ids = new Set();
192
+ const diagnosticIds = new Set();
193
+ for (const component of metadata.components)
194
+ validateComponent(
195
+ component,
196
+ packageRoot,
197
+ packageJson,
198
+ ids,
199
+ diagnosticIds,
200
+ diagnostics,
201
+ );
202
+ const entries = [...metadata.components]
203
+ .sort((a, b) => a.id.localeCompare(b.id))
204
+ .map((component) => toEntry(packageJson.name, component));
205
+ const outputPath = resolve(packageRoot, config.output);
206
+ const selectionOutputPath =
207
+ typeof config.selectionOutput === 'string' && config.selectionOutput
208
+ ? resolve(packageRoot, config.selectionOutput)
209
+ : null;
210
+ const selection = buildSelectionCatalog({
211
+ packageRoot,
212
+ packageJson,
213
+ metadata,
214
+ metadataPath,
215
+ outputPath,
216
+ selectionOutputPath,
217
+ diagnostics,
218
+ });
219
+ const componentCatalog = selectionOutputPath
220
+ ? posixRelative(dirname(outputPath), selectionOutputPath)
221
+ : (metadata.componentCatalog ?? 'not-applicable');
222
+ const catalog = {
223
+ $schema:
224
+ 'https://raw.githubusercontent.com/brianwestphal/kerf/main/ui/ai/component-composition-extension.schema.json',
225
+ schemaVersion: 1,
226
+ package: packageJson.name,
227
+ compatibility: {
228
+ componentCatalog,
229
+ identity: 'package:id',
230
+ },
231
+ entries,
232
+ };
233
+ diagnostics.push(
234
+ ...validateDocumentAgainstSchema(catalog, catalogSchema, outputPath),
235
+ );
236
+ return {
237
+ packageRoot,
238
+ metadataPath,
239
+ outputPath,
240
+ catalog,
241
+ ...(selection ? { selectionOutputPath, selection } : {}),
242
+ };
243
+ }
244
+
245
+ /** Generate every configured package's catalogs under `root`, or throw. */
246
+ export function generateCatalogs(root = process.cwd()) {
247
+ const diagnostics = [];
248
+ const packages = configuredPackages(resolve(root), diagnostics);
249
+ if (!packages.length && !diagnostics.length)
250
+ diagnostics.push(
251
+ `${relative(process.cwd(), resolve(root)) || '.'}: no package declares package.json#${CONFIG_KEY}`,
252
+ );
253
+ const results = [];
254
+ const packageNames = new Set();
255
+ for (const packageRoot of packages) {
256
+ const result = generatePackage(packageRoot, packageNames, diagnostics);
257
+ if (result) results.push(result);
258
+ }
259
+ validateRendersAs(results, diagnostics);
260
+ if (diagnostics.length) throw new CatalogError(diagnostics.sort());
261
+ return results;
262
+ }
263
+
264
+ export function formatCatalog(catalog) {
265
+ return `${JSON.stringify(catalog, null, 2)}\n`;
266
+ }
267
+
268
+ function checkOutput(path, catalog, schema, label, diagnostics) {
269
+ if (!existsSync(path)) {
270
+ diagnostics.push(`${path}: generated ${label} is missing`);
271
+ return;
272
+ }
273
+ const actualSource = readFileSync(path, 'utf8');
274
+ const actual = readJson(path, path, diagnostics);
275
+ if (actual)
276
+ diagnostics.push(...validateDocumentAgainstSchema(actual, schema, path));
277
+ if (actualSource !== formatCatalog(catalog))
278
+ diagnostics.push(
279
+ `${path}: generated ${label} is stale; run catalog:generate`,
280
+ );
281
+ }
282
+
283
+ /** Write (or with `check`, verify) every generated catalog under `root`. */
284
+ export function runCatalogCommand({
285
+ root = process.cwd(),
286
+ check = false,
287
+ } = {}) {
288
+ const results = generateCatalogs(root);
289
+ const diagnostics = [];
290
+ for (const result of results) {
291
+ const outputs = [
292
+ [result.outputPath, result.catalog, catalogSchema, 'catalog'],
293
+ ];
294
+ if (result.selection)
295
+ outputs.push([
296
+ result.selectionOutputPath,
297
+ result.selection,
298
+ selectionSchema,
299
+ 'selection catalog',
300
+ ]);
301
+ for (const [path, catalog, schema, label] of outputs) {
302
+ if (check) checkOutput(path, catalog, schema, label, diagnostics);
303
+ else writeFileSync(path, formatCatalog(catalog));
304
+ }
305
+ }
306
+ if (diagnostics.length) throw new CatalogError(diagnostics);
307
+ return results;
308
+ }