Repository navigation
Expand file tree
/
Copy pathcatalog.js
More file actions
291 lines (276 loc) · 11.8 KB
/
Copy pathcatalog.js
File metadata and controls
291 lines (276 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// @cosyte/script-utils/catalog
//
// THE CATALOG OF COSYTE'S LIBRARIES (ST13, ST14). One record per library, generated from that
// library's own package.json, with the tier it belongs to; and one for Pathways, our integration
// engine. The tiers, Pathways' status, and which packages are on npm come from a small hand-kept
// file in cosyte/config (`catalog/tiers.json`); everything else is read out of each package.json by
// `scripts/catalog.mjs` there, and written beside this module as `catalog.json`. A record carries
// `onNpm`, and its npm URL only when it is on npm.
// A site, the org profile, a deck or a knowledgebase page reads that one list instead of keeping
// its own roster.
//
// IT ALSO CARRIES THE CHECK A LIBRARY CAN RUN, AND THAT CHECK IS ADVISORY. Each package.json
// description is that library's one canonical line (ST14). Keeping the catalog fresh is cosyte/config's
// job: `scripts/catalog.mjs check --npm` compares the catalog with every library's latest npm release,
// nightly and before each config release. So a library that changes its description is not held red
// until the next script-utils release: this check prints both values as a note and exits 0. `--strict`
// makes a disagreement exit 1 and an unlisted package exit 2, for a caller that wants the old gate.
//
// node node_modules/@cosyte/script-utils/catalog.js # the package in this directory
// node node_modules/@cosyte/script-utils/catalog.js --dir <path> # another package directory
// node node_modules/@cosyte/script-utils/catalog.js --strict # a disagreement fails
//
// EXIT CODES: 0 the description agrees, or (advisory) it does not and a note says so; 1 it does not,
// with --strict; 2 the check could not run (no package.json, a bad argument, or, with --strict, a
// package the catalog does not list).
//
// ZERO DEPENDENCIES AND NO BUILD STEP, like the rest of this package.
import { readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { isCliEntrypoint } from "./index.js";
/** The three tiers, in the order ST13 names them. */
export const TIERS = Object.freeze(["standard", "built-on", "engine"]);
/** Deep-freeze a parsed JSON value, so no consumer can edit the shared catalog in place. */
function freeze(value) {
if (value !== null && typeof value === "object") {
for (const child of Object.values(value)) freeze(child);
Object.freeze(value);
}
return value;
}
/** The catalog, as `catalog.json` beside this module carries it. */
export const CATALOG = freeze(
JSON.parse(readFileSync(new URL("./catalog.json", import.meta.url), "utf8")),
);
/**
* The release line a version is on: `0.<minor>` below 1.0.0, where a minor may break, and the
* major from 1.0.0 on. `0.1.2` is the 0.1 line (ST16).
*
* @param {string} version A `major.minor.patch` version.
* @returns {string} The line, for example `0.1`.
*/
export function releaseLine(version) {
const match = /^(\d+)\.(\d+)\.\d+(?:[-+].*)?$/.exec(String(version));
if (match === null) throw new TypeError(`${JSON.stringify(version)} is not a semver version.`);
return match[1] === "0" ? `0.${match[2]}` : match[1];
}
/** The `https://github.com/cosyte/<repo>` a package.json's repository names, or `null`. */
function repositoryUrl(manifest) {
const raw =
typeof manifest.repository === "string" ? manifest.repository : manifest.repository?.url;
if (typeof raw !== "string") return null;
const match = /github\.com[/:]cosyte\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(raw);
return match === null ? null : `https://github.com/cosyte/${match[1]}`;
}
/** The slug a `@cosyte/<slug>` name carries. */
function slugOf(name) {
const match = /^@cosyte\/([a-z0-9][a-z0-9.-]*)$/.exec(String(name));
if (match === null)
throw new TypeError(`${JSON.stringify(name)} is not a @cosyte/<name> package.`);
return match[1];
}
/** The fields every record takes from its package.json, refusing a manifest that lacks one. */
function fromManifest(name, manifest) {
if (manifest === undefined || manifest === null || typeof manifest !== "object") {
throw new TypeError(`no package.json was read for ${name}.`);
}
if (manifest.name !== name) {
throw new TypeError(
`the package.json read for ${name} names ${JSON.stringify(manifest.name)}.`,
);
}
const slug = slugOf(name);
const problems = [];
if (typeof manifest.description !== "string" || manifest.description.trim() === "") {
problems.push("no description");
}
if (typeof manifest.version !== "string") problems.push("no version");
if (typeof manifest.engines?.node !== "string") problems.push("no engines.node");
const repository = repositoryUrl(manifest);
if (repository === null) problems.push("no github.com/cosyte repository");
if (problems.length > 0)
throw new TypeError(`${name}'s package.json has ${problems.join(", ")}.`);
return {
name,
slug,
description: manifest.description,
line: releaseLine(manifest.version),
engines: { node: manifest.engines.node },
repository,
docs: `https://docs.cosyte.com/${slug}`,
};
}
/** The npm URL of a package on npm, as a record's `npm` field, or no field at all. */
function npmField(name, onNpm) {
return onNpm ? { npm: `https://www.npmjs.com/package/${name}` } : {};
}
/**
* Build the catalog from the hand-kept tiers file and each package's package.json. Pure: it reads
* nothing, so the generator decides where the manifests come from. A standard whose tiers entry
* says `onNpm: false` is not on npm; every other library is.
*
* @param {{ standards: { package: string, standard: string, onNpm?: boolean }[],
* builtOn: string[],
* engine: { package: string, name: string, status: string, onNpm: boolean } }} tiers
* @param {Map<string, Record<string, any>> | Record<string, Record<string, any>>} manifests
* Each package's parsed package.json, keyed by package name.
* @returns {{ libraries: object[], engine: object }} The catalog.
* @throws {TypeError} When a tier names a package with no usable manifest, or names one twice.
*/
export function buildCatalog(tiers, manifests) {
const get = (name) => (manifests instanceof Map ? manifests.get(name) : manifests[name]);
const seen = new Set();
const claim = (name) => {
if (seen.has(name)) throw new TypeError(`${name} is listed twice in the tiers.`);
seen.add(name);
};
const libraries = [];
for (const { package: name, standard, onNpm = true } of tiers.standards) {
claim(name);
libraries.push({
...fromManifest(name, get(name)),
...npmField(name, onNpm),
onNpm,
tier: "standard",
standard,
});
}
for (const name of tiers.builtOn) {
claim(name);
libraries.push({
...fromManifest(name, get(name)),
...npmField(name, true),
onNpm: true,
tier: "built-on",
});
}
const { package: enginePackage, name: engineName, status, onNpm } = tiers.engine;
claim(enginePackage);
const engine = {
...fromManifest(enginePackage, get(enginePackage)),
...npmField(enginePackage, onNpm),
tier: "engine",
displayName: engineName,
status,
onNpm,
};
return { libraries, engine };
}
/**
* The catalog record for a package name: a library or the engine, or `undefined`.
*
* @param {string} name A package name, for example `@cosyte/hl7`.
* @param {{ libraries: object[], engine: object }} [catalog] Defaults to `CATALOG`.
*/
export function catalogEntry(name, catalog = CATALOG) {
if (catalog.engine?.name === name) return catalog.engine;
return catalog.libraries.find((entry) => entry.name === name);
}
/**
* Compare a package.json with its catalog record. Only the description is compared: it is the line
* ST14 makes canonical, and the other generated fields move with a release (the version line) or
* cannot drift without the package moving (the name and repository).
*
* @param {Record<string, any>} manifest The package's parsed package.json.
* @param {{ libraries: object[], engine: object }} [catalog] Defaults to `CATALOG`.
* @returns {{ field: string, catalog: string, packageJson: string }[]} The disagreements.
* @throws {TypeError} When the catalog does not list the package.
*/
export function compareWithCatalog(manifest, catalog = CATALOG) {
const entry = catalogEntry(manifest?.name, catalog);
if (entry === undefined) {
throw new TypeError(`the catalog does not list ${JSON.stringify(manifest?.name ?? null)}.`);
}
if (manifest.description === entry.description) return [];
return [
{
field: "description",
catalog: entry.description,
packageJson: String(manifest.description ?? ""),
},
];
}
/**
* Run the check over one package directory and return the exit code. It never exits the process.
*
* ADVISORY BY DEFAULT: a disagreement or an unlisted package is printed as a note and exits 0,
* because keeping the catalog fresh is cosyte/config's job (`scripts/catalog.mjs check --npm`).
* `strict` (or `--strict`) restores the gate: 1 for a disagreement, 2 for an unlisted package.
*
* @param {{ dir?: string, argv?: string[], strict?: boolean }} [options] `dir` is the package
* directory (default: the working directory). `argv` is the CLI arguments, read for
* `--dir <path>` and `--strict`.
* @returns {0 | 1 | 2} 0 agree (or advisory), 1 disagree under strict, 2 the check could not run.
*/
export function runCatalogCheck(options = {}) {
let dir = options.dir ?? process.cwd();
let strict = options.strict === true;
const argv = options.argv ?? [];
for (let i = 0; i < argv.length; i += 1) {
if (argv[i] === "--dir" && typeof argv[i + 1] === "string") {
dir = argv[i + 1];
i += 1;
} else if (argv[i] === "--strict") {
strict = true;
} else if (argv[i] !== "--") {
process.stderr.write(
`catalog check: ${JSON.stringify(argv[i])} is not an argument this check accepts (only ` +
`--dir <package directory> and --strict). Nothing was checked.\n`,
);
return 2;
}
}
dir = resolve(dir);
let manifest;
try {
manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
} catch (err) {
process.stderr.write(`catalog check: could not read package.json in ${dir}: ${err.message}\n`);
return 2;
}
let differences;
try {
differences = compareWithCatalog(manifest);
} catch (err) {
if (strict) {
process.stderr.write(`catalog check: ${err.message} Nothing was checked.\n`);
return 2;
}
process.stderr.write(
`catalog check: note: ${err.message} The catalog is cosyte/config's to keep fresh; this ` +
`check is advisory, so it exits 0.\n`,
);
return 0;
}
if (differences.length === 0) {
process.stdout.write(`catalog check: ${manifest.name}'s description is the catalog's.\n`);
return 0;
}
const report = differences
.map(
(d) =>
` ${d.field}\n package.json: ${JSON.stringify(d.packageJson)}\n` +
` catalog: ${JSON.stringify(d.catalog)}`,
)
.join("\n");
if (!strict) {
process.stderr.write(
`catalog check: note: ${manifest.name}'s package.json and the catalog this release of ` +
`@cosyte/script-utils carries disagree.\n${report}\n` +
`This is advisory and exits 0. Once this package is released with the new description, ` +
`cosyte/config's nightly check against npm (scripts/catalog.mjs check --npm) flags the ` +
`catalog, and the next script-utils release carries it.\n`,
);
return 0;
}
process.stderr.write(
`catalog check: ${manifest.name}'s package.json and the catalog disagree.\n${report}\n` +
`The catalog is generated in cosyte/config (scripts/catalog.mjs) and ships in ` +
`@cosyte/script-utils. Regenerate it there, release script-utils, then move this package to ` +
`that release.\n`,
);
return 1;
}
if (isCliEntrypoint(import.meta.url)) {
process.exitCode = runCatalogCheck({ argv: process.argv.slice(2) });
}