create-kerf-component 5.0.0-beta.125 → 5.0.0-beta.127
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 +12 -1
- package/catalog/export-discovery.js +112 -0
- package/catalog/generate.js +308 -0
- package/catalog/schema-validate.js +140 -0
- package/catalog/schemas.js +19 -0
- package/catalog/selection.js +243 -0
- package/catalog/validate-component.js +524 -0
- package/catalog/workspace.js +62 -0
- package/catalog.js +21 -1183
- package/index.js +85 -16
- package/package.json +15 -2
- package/template/package.json +2 -2
package/README.md
CHANGED
|
@@ -17,7 +17,17 @@ npm run check:styles
|
|
|
17
17
|
|
|
18
18
|
Run it with **no argument** (`npm create kerf-component`) and it prompts for the
|
|
19
19
|
directory. Pass `.` to scaffold into the current directory. The target
|
|
20
|
-
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.
|
|
21
31
|
|
|
22
32
|
## What you get
|
|
23
33
|
|
|
@@ -123,6 +133,7 @@ my-widgets/
|
|
|
123
133
|
├── component-composition.json # deterministic generated AI catalog
|
|
124
134
|
├── scripts/
|
|
125
135
|
│ ├── kerf-component-catalog.mjs # local generator + check mode
|
|
136
|
+
│ ├── catalog/ # the generator's modules (validation, export discovery, generation)
|
|
126
137
|
│ ├── component-metadata.schema.json # author-source schema used by the checker
|
|
127
138
|
│ ├── component-composition.schema.json # emitted-catalog schema used by the checker
|
|
128
139
|
│ └── component-catalog-extension.schema.json # optional selection-catalog schema
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// The JSON-schema subset kerf's catalog schemas use, validated without a
|
|
2
|
+
// third-party dependency: `$ref` (local `#/` pointers), `allOf`, `anyOf`,
|
|
3
|
+
// `const`, `enum`, `type`, string `minLength`/`pattern`, number `minimum`,
|
|
4
|
+
// array `minItems`/`uniqueItems`/`items`, and object `required`/`properties`/
|
|
5
|
+
// `additionalProperties: false`. Each failure is reported at its exact JSON
|
|
6
|
+
// path.
|
|
7
|
+
|
|
8
|
+
function schemaReference(rootSchema, reference) {
|
|
9
|
+
if (!reference.startsWith('#/'))
|
|
10
|
+
throw new Error(`unsupported schema reference ${reference}`);
|
|
11
|
+
return reference
|
|
12
|
+
.slice(2)
|
|
13
|
+
.split('/')
|
|
14
|
+
.map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'))
|
|
15
|
+
.reduce((value, part) => value?.[part], rootSchema);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function schemaTypeMatches(value, type) {
|
|
19
|
+
if (type === 'array') return Array.isArray(value);
|
|
20
|
+
if (type === 'object')
|
|
21
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
22
|
+
if (type === 'integer') return Number.isInteger(value);
|
|
23
|
+
return typeof value === type;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// `anyOf` passes when one alternative passes. A union of bare types (a prop
|
|
27
|
+
// condition's `equals`) names the types in its failure.
|
|
28
|
+
function validateAnyOf(value, alternatives, path, rootSchema, diagnostics) {
|
|
29
|
+
const failures = alternatives.map((candidate) => {
|
|
30
|
+
const candidateFailures = [];
|
|
31
|
+
validateSchemaValue(value, candidate, path, rootSchema, candidateFailures);
|
|
32
|
+
return candidateFailures;
|
|
33
|
+
});
|
|
34
|
+
if (!failures.every((candidateFailures) => candidateFailures.length)) return;
|
|
35
|
+
const types = alternatives.every(
|
|
36
|
+
(candidate) =>
|
|
37
|
+
Object.keys(candidate).length === 1 && typeof candidate.type === 'string',
|
|
38
|
+
)
|
|
39
|
+
? alternatives.map((candidate) => candidate.type)
|
|
40
|
+
: null;
|
|
41
|
+
diagnostics.push(
|
|
42
|
+
types
|
|
43
|
+
? `${path}: expected ${types.join(' or ')}`
|
|
44
|
+
: `${path}: does not match any allowed schema variant`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function validateString(value, rule, path, diagnostics) {
|
|
49
|
+
if (rule.minLength !== undefined && value.length < rule.minLength)
|
|
50
|
+
diagnostics.push(
|
|
51
|
+
`${path}: expected at least ${rule.minLength} character(s)`,
|
|
52
|
+
);
|
|
53
|
+
if (rule.pattern && !new RegExp(rule.pattern).test(value))
|
|
54
|
+
diagnostics.push(`${path}: must match ${rule.pattern}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function validateArray(value, rule, path, rootSchema, diagnostics) {
|
|
58
|
+
if (rule.minItems !== undefined && value.length < rule.minItems)
|
|
59
|
+
diagnostics.push(`${path}: expected at least ${rule.minItems} item(s)`);
|
|
60
|
+
if (rule.uniqueItems) {
|
|
61
|
+
const serialized = value.map((item) => JSON.stringify(item));
|
|
62
|
+
if (new Set(serialized).size !== serialized.length)
|
|
63
|
+
diagnostics.push(`${path}: expected unique items`);
|
|
64
|
+
}
|
|
65
|
+
if (rule.items)
|
|
66
|
+
value.forEach((item, index) =>
|
|
67
|
+
validateSchemaValue(
|
|
68
|
+
item,
|
|
69
|
+
rule.items,
|
|
70
|
+
`${path}[${index}]`,
|
|
71
|
+
rootSchema,
|
|
72
|
+
diagnostics,
|
|
73
|
+
),
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function validateObject(value, rule, path, rootSchema, diagnostics) {
|
|
78
|
+
for (const key of rule.required ?? [])
|
|
79
|
+
if (!(key in value)) diagnostics.push(`${path}.${key}: is required`);
|
|
80
|
+
const properties = rule.properties ?? {};
|
|
81
|
+
for (const [key, item] of Object.entries(value)) {
|
|
82
|
+
if (key in properties)
|
|
83
|
+
validateSchemaValue(
|
|
84
|
+
item,
|
|
85
|
+
properties[key],
|
|
86
|
+
`${path}.${key}`,
|
|
87
|
+
rootSchema,
|
|
88
|
+
diagnostics,
|
|
89
|
+
);
|
|
90
|
+
else if (rule.additionalProperties === false)
|
|
91
|
+
diagnostics.push(`${path}.${key}: additional property is not allowed`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function validateSchemaValue(value, rule, path, rootSchema, diagnostics) {
|
|
96
|
+
if (rule.$ref) {
|
|
97
|
+
const referenced = schemaReference(rootSchema, rule.$ref);
|
|
98
|
+
if (!referenced) {
|
|
99
|
+
diagnostics.push(`${path}: schema reference ${rule.$ref} does not exist`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
validateSchemaValue(value, referenced, path, rootSchema, diagnostics);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (rule.allOf)
|
|
106
|
+
for (const candidate of rule.allOf)
|
|
107
|
+
validateSchemaValue(value, candidate, path, rootSchema, diagnostics);
|
|
108
|
+
if (rule.anyOf) {
|
|
109
|
+
validateAnyOf(value, rule.anyOf, path, rootSchema, diagnostics);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (rule.const !== undefined && value !== rule.const)
|
|
113
|
+
diagnostics.push(`${path}: expected ${JSON.stringify(rule.const)}`);
|
|
114
|
+
if (rule.enum && !rule.enum.includes(value))
|
|
115
|
+
diagnostics.push(
|
|
116
|
+
`${path}: expected one of ${rule.enum.map((item) => JSON.stringify(item)).join(', ')}`,
|
|
117
|
+
);
|
|
118
|
+
if (rule.type && !schemaTypeMatches(value, rule.type)) {
|
|
119
|
+
diagnostics.push(`${path}: expected ${rule.type}`);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (typeof value === 'string') validateString(value, rule, path, diagnostics);
|
|
123
|
+
if (
|
|
124
|
+
typeof value === 'number' &&
|
|
125
|
+
rule.minimum !== undefined &&
|
|
126
|
+
value < rule.minimum
|
|
127
|
+
)
|
|
128
|
+
diagnostics.push(`${path}: expected a value >= ${rule.minimum}`);
|
|
129
|
+
if (Array.isArray(value))
|
|
130
|
+
validateArray(value, rule, path, rootSchema, diagnostics);
|
|
131
|
+
else if (value !== null && typeof value === 'object')
|
|
132
|
+
validateObject(value, rule, path, rootSchema, diagnostics);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Validate `value` against `schema`; returns the diagnostics, each at `path`. */
|
|
136
|
+
export function validateDocumentAgainstSchema(value, schema, path) {
|
|
137
|
+
const diagnostics = [];
|
|
138
|
+
validateSchemaValue(value, schema, path, schema, diagnostics);
|
|
139
|
+
return diagnostics;
|
|
140
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The three JSON schemas the catalog command validates against. They ship
|
|
2
|
+
// beside the command's entry file — the package root here, `scripts/` in a
|
|
3
|
+
// scaffolded package — one directory above these modules.
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const schemaRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
9
|
+
const readSchema = (name) =>
|
|
10
|
+
JSON.parse(readFileSync(join(schemaRoot, name), 'utf8'));
|
|
11
|
+
|
|
12
|
+
/** The author metadata (`kerf.components.json`) schema. */
|
|
13
|
+
export const metadataSchema = readSchema('component-metadata.schema.json');
|
|
14
|
+
/** The generated composition catalog schema. */
|
|
15
|
+
export const catalogSchema = readSchema('component-composition.schema.json');
|
|
16
|
+
/** The generated selection-catalog extension schema. */
|
|
17
|
+
export const selectionSchema = readSchema(
|
|
18
|
+
'component-catalog-extension.schema.json',
|
|
19
|
+
);
|