@cagov/ca-ds 1.0.0 → 1.1.0

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.
Files changed (101) hide show
  1. package/README.md +4 -2
  2. package/THIRD-PARTY-LICENSES.txt +690 -0
  3. package/ca-ds.js +48337 -0
  4. package/package.json +5 -31
  5. package/bin/ca-ds.js +0 -5
  6. package/src/cli/add.js +0 -134
  7. package/src/cli/build.js +0 -15
  8. package/src/cli/diff.js +0 -39
  9. package/src/cli/eject.js +0 -112
  10. package/src/cli/exit.js +0 -22
  11. package/src/cli/format.js +0 -52
  12. package/src/cli/init.js +0 -148
  13. package/src/cli/install.js +0 -178
  14. package/src/cli/items.js +0 -10
  15. package/src/cli/login.js +0 -331
  16. package/src/cli/main.js +0 -108
  17. package/src/cli/new.js +0 -230
  18. package/src/cli/outdated.js +0 -74
  19. package/src/cli/pack.js +0 -75
  20. package/src/cli/preview.js +0 -31
  21. package/src/cli/publish.js +0 -295
  22. package/src/cli/pull.js +0 -208
  23. package/src/cli/remote.js +0 -52
  24. package/src/cli/remove.js +0 -69
  25. package/src/cli/update.js +0 -223
  26. package/src/cli/validate.js +0 -131
  27. package/src/lib/browser.js +0 -12
  28. package/src/lib/build.js +0 -249
  29. package/src/lib/bundle.js +0 -148
  30. package/src/lib/catalog.js +0 -44
  31. package/src/lib/checks.js +0 -31
  32. package/src/lib/collection.js +0 -65
  33. package/src/lib/emblem.js +0 -29
  34. package/src/lib/fixtures.js +0 -59
  35. package/src/lib/floor.js +0 -79
  36. package/src/lib/glyph.js +0 -148
  37. package/src/lib/image.js +0 -138
  38. package/src/lib/json-text.js +0 -213
  39. package/src/lib/keys.js +0 -322
  40. package/src/lib/links.js +0 -321
  41. package/src/lib/markdown.js +0 -408
  42. package/src/lib/merge.js +0 -93
  43. package/src/lib/pack.js +0 -30
  44. package/src/lib/page-schema.js +0 -368
  45. package/src/lib/page.js +0 -372
  46. package/src/lib/patch.js +0 -9
  47. package/src/lib/regions.js +0 -173
  48. package/src/lib/registry.js +0 -371
  49. package/src/lib/release.js +0 -119
  50. package/src/lib/repoints.js +0 -120
  51. package/src/lib/resolve.js +0 -32
  52. package/src/lib/schema.js +0 -28
  53. package/src/lib/serial.js +0 -4
  54. package/src/lib/serialize.js +0 -444
  55. package/src/lib/structured.js +0 -72
  56. package/src/lib/system.js +0 -13
  57. package/src/lib/targets.js +0 -85
  58. package/src/lib/terms.js +0 -11
  59. package/src/lib/token-view.js +0 -289
  60. package/src/lib/tokens.js +0 -247
  61. package/src/lib/version.js +0 -34
  62. package/src/preview/frame.js +0 -75
  63. package/src/preview/pages.js +0 -128
  64. package/src/preview/screenshots.js +0 -72
  65. package/src/preview/server.js +0 -378
  66. package/src/preview/shell.js +0 -153
  67. package/src/schema/a11y.schema.json +0 -56
  68. package/src/schema/collection.lock.schema.json +0 -58
  69. package/src/schema/collection.schema.json +0 -65
  70. package/src/schema/composition.schema.json +0 -98
  71. package/src/schema/contract.schema.json +0 -116
  72. package/src/schema/interface.schema.json +0 -257
  73. package/src/schema/item.schema.json +0 -362
  74. package/src/schema/release.schema.json +0 -39
  75. package/src/schema/system.schema.json +0 -75
  76. package/src/schema/variants.schema.json +0 -60
  77. package/src/validate/collection.js +0 -19
  78. package/src/validate/collisions.js +0 -124
  79. package/src/validate/context.js +0 -357
  80. package/src/validate/facts.js +0 -253
  81. package/src/validate/files.js +0 -103
  82. package/src/validate/findings.js +0 -19
  83. package/src/validate/glyphs.js +0 -126
  84. package/src/validate/html.js +0 -215
  85. package/src/validate/imports.js +0 -29
  86. package/src/validate/index.js +0 -75
  87. package/src/validate/item.js +0 -47
  88. package/src/validate/links.js +0 -113
  89. package/src/validate/manifest.js +0 -147
  90. package/src/validate/media.js +0 -65
  91. package/src/validate/page.js +0 -74
  92. package/src/validate/prefixes.js +0 -58
  93. package/src/validate/relations.js +0 -310
  94. package/src/validate/release.js +0 -109
  95. package/src/validate/skill.js +0 -122
  96. package/src/validate/structured.js +0 -335
  97. package/src/validate/tasc.js +0 -80
  98. package/src/validate/template.js +0 -129
  99. package/src/validate/tokens.js +0 -154
  100. package/src/validate/zip.js +0 -40
  101. /package/{src/preview/preview.css → preview.css} +0 -0
package/src/cli/update.js DELETED
@@ -1,223 +0,0 @@
1
- import { existsSync, mkdirSync, readdirSync, renameSync } from 'node:fs';
2
- import { basename, dirname, join } from 'node:path';
3
- import semver from 'semver';
4
- import { mergeFile } from '../lib/merge.js';
5
- import { isSystemItem } from '../lib/system.js';
6
- import { CliError, EXIT, usageError } from './exit.js';
7
- import { authoredDependencies, fetchFresh, highestIn, lockEntry, placeFresh, scriptsWarning } from './add.js';
8
- import { baselineOf, hashesOf, installedManifest, installedSkills, linkClash, linkSkill, localFiles, parseSpec, pruneEmpty, rootsOf, saveRoots, skillLinks, skillNameOf, skillPath, unlinkSkill, writeFiles } from './install.js';
9
- import { connect, TOKEN } from './remote.js';
10
- import { entriesBetween, logEntries } from './outdated.js';
11
-
12
- function moving(collection, names) {
13
- const manifests = new Map(collection.items.map((i) => [i.manifest.name, i.manifest]));
14
- const out = new Set();
15
- const visit = (name, top) => {
16
- const entry = collection.lock.items[name];
17
- if (out.has(name) || !entry || (!top && entry.requested)) return;
18
- out.add(name);
19
- for (const dep of Object.keys(manifests.get(name)?.dependencies ?? {})) visit(dep, false);
20
- };
21
- for (const name of names) visit(name, true);
22
- return out;
23
- }
24
-
25
- async function mergeItem(collection, client, name, entry, version) {
26
- const record = await client.item(name, version);
27
- if (!record) throw new CliError(`The registry at ${client.url} holds no ${name} ${version}.`, EXIT.registry);
28
- const theirs = baselineOf(record);
29
- const local = localFiles(join(collection.root, entry.path));
30
- const ours = hashesOf(local);
31
- const labels = { ours: 'local', theirs: `${name}@${version}` };
32
- const files = [];
33
- const write = new Map();
34
- const upstream = new Map();
35
- const remove = [];
36
- const paths = [...new Set([...Object.keys(entry.files), ...Object.keys(ours), ...Object.keys(theirs)])].sort();
37
- for (const path of paths) {
38
- const [o, a, b] = [entry.files[path], ours[path], theirs[path]];
39
- if (a === b || b === o) continue;
40
- const fetchAt = (v, hash) => (hash ? client.file(name, v, path, hash) : null);
41
- const sides = {
42
- base: a === o ? null : await fetchAt(entry.version, o),
43
- ours: local.get(path) ?? null,
44
- theirs: await fetchAt(version, b),
45
- };
46
- if (sides.theirs) upstream.set(path, sides.theirs);
47
- // A file untouched locally fast-forwards with no need of its base.
48
- const merged = a === o ? { outcome: 'updated', bytes: sides.theirs } : mergeFile(path, sides, labels);
49
- if (merged.outcome === 'kept') continue;
50
- files.push({ path, outcome: merged.outcome, ...(merged.conflicts ? { conflicts: merged.conflicts } : {}), ...(merged.reason ? { reason: merged.reason } : {}), ...(merged.keys ? { keys: merged.keys } : {}) });
51
- if (merged.bytes === null) remove.push(path);
52
- else if (merged.bytes) write.set(path, merged.bytes);
53
- }
54
- const status = files.some((f) => f.outcome === 'stop') ? 'stopped' : files.some((f) => f.outcome === 'conflict') ? 'conflict' : 'updated';
55
- return { status, files, write, remove, upstream, baseline: theirs, local, record };
56
- }
57
-
58
- const skipped = (config, path, links, recorded, name) =>
59
- skillLinks(config, path)
60
- .filter((l) => !links.includes(l) && !recorded.includes(l))
61
- .map((l) => ({ rule: 'skill-link', name, message: `${l} holds a folder ${name}'s lock entry never recorded, so it stays, and ${name} isn't linked there. Move it, then run ca-ds update again.` }));
62
-
63
- const decoded = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
64
-
65
- // A skill whose new frontmatter name differs moves to that name's folder, unless another holds it.
66
- function planMove(collection, config, name, entry, plan, taken) {
67
- const manifest = plan.write.has('item.json') ? decoded(plan.write.get('item.json')) : installedManifest(collection, name);
68
- plan.skill = manifest?.kind === 'skill';
69
- if (!plan.skill || plan.status === 'stopped') return;
70
- const doc = plan.write.get(manifest.doc) ?? plan.local.get(manifest.doc);
71
- // A merged doc whose frontmatter conflicted takes the new version's own name, so the folder follows the rename.
72
- const upstream = plan.upstream.get(manifest.doc);
73
- const skillName = skillNameOf(doc) ?? (upstream ? skillNameOf(upstream) : null) ?? basename(entry.path);
74
- const to = skillPath(config, skillName);
75
- // An installed skill keeps its folder when the skills folders change; an item that becomes one moves into them.
76
- if (to === entry.path || (entry.links && skillName === basename(entry.path))) return;
77
- const abs = join(collection.root, to);
78
- const link = linkClash(collection.root, config, to);
79
- const holder = taken.get(skillName);
80
- let clash = null;
81
- if (holder) clash = `${holder} already installs as the skill ${skillName}`;
82
- else if (existsSync(abs) && readdirSync(abs).length) clash = `${to} already holds files`;
83
- else if (link) clash = `${link} already holds a skill`;
84
- if (clash) {
85
- plan.status = 'stopped';
86
- plan.files.push({ path: manifest.doc, outcome: 'stop', reason: `it renames the skill ${skillName}, and ${clash}` });
87
- return;
88
- }
89
- taken.delete(basename(entry.path));
90
- taken.set(skillName, name);
91
- plan.move = to;
92
- }
93
-
94
- export const command = {
95
- synopsis: 'update [name...]',
96
- summary: 'merge newer versions, with --dry-run and --latest',
97
- usage: ['ca-ds update [<scope>/<name>...] [--dry-run] [--latest] [--token <token>]'],
98
- options: { 'dry-run': { type: 'boolean' }, latest: { type: 'boolean' }, ...TOKEN },
99
- async run({ values, positionals, io, collection, env, fetch }) {
100
- const c = collection();
101
- const { config, lock } = rootsOf(c);
102
- const dryRun = values['dry-run'] === true;
103
- const latest = values.latest === true;
104
- const names = positionals.map((arg) => {
105
- const { name, range } = parseSpec(arg);
106
- if (range !== null) throw usageError(`update takes a name, with no range: ${name}. Set a range in collection.json's items.`);
107
- if (!lock.items[name]) throw usageError(`${name} is not installed.`);
108
- return name;
109
- });
110
- const from = config.release ?? null;
111
- if (from && !latest && names.length) throw usageError(`collection.json names the release ${from}, and a release moves every item together. Drop the names, or pass --latest.`);
112
- if (!Object.keys(lock.items).length) {
113
- io.log('Nothing is installed.');
114
- return { result: { dryRun, release: null, items: [], ranges: [] } };
115
- }
116
-
117
- const client = connect(c, { values, env, fetch });
118
- let release = null;
119
- if (from && !latest) {
120
- const newest = await client.release('latest');
121
- if (!newest) throw new CliError(`collection.json names the release ${from}, and the registry at ${client.url} records none.`, EXIT.registry);
122
- release = newest.tag;
123
- }
124
- const free = names.length ? moving(c, names) : new Set(Object.keys(lock.items));
125
- const versions = Object.fromEntries(Object.entries(lock.items).filter(([name]) => !free.has(name)).map(([name, entry]) => [name, entry.version]));
126
- const asked = config.items ?? {};
127
- if (!latest) {
128
- for (const [name, range] of Object.entries(asked)) {
129
- if (free.has(name) && !(release && isSystemItem(name))) versions[name] = await highestIn(client, name, range);
130
- }
131
- }
132
- const answer = await client.resolve({ items: [...new Set([...Object.keys(asked), ...authoredDependencies(c)])], release, versions });
133
- const resolved = new Map(answer.items.map((i) => [i.name, i.version]));
134
-
135
- const authored = new Set(c.items.filter((i) => i.authored).map((i) => i.manifest.name));
136
- const items = [];
137
- const plans = [];
138
- const taken = installedSkills(c);
139
- for (const [name, entry] of Object.entries(lock.items).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
140
- const to = resolved.get(name) ?? null;
141
- if (to === null) items.push({ name, from: entry.version, to: null, status: 'orphaned', files: [] });
142
- else if (to === entry.version) items.push({ name, from: to, to, status: 'current', files: [] });
143
- else {
144
- const plan = await mergeItem(c, client, name, entry, to);
145
- planMove(c, config, name, entry, plan, taken);
146
- plan.changedScripts = plan.record.files.some((f) => f.role === 'script' && entry.files[f.path] !== plan.baseline[f.path]);
147
- plans.push({ name, entry, to, plan });
148
- items.push({ name, from: entry.version, to, status: plan.status, files: plan.files, ...(plan.move ? { moved: { from: entry.path, to: plan.move } } : {}) });
149
- }
150
- }
151
- const fresh = await fetchFresh(c, client, config, answer.items.filter((i) => !lock.items[i.name] && !authored.has(i.name)), taken);
152
- for (const f of fresh) items.push({ name: f.name, from: null, to: f.version, status: 'added', files: [] });
153
-
154
- const ranges = [];
155
- if (release || latest) {
156
- for (const [name, range] of Object.entries(asked)) {
157
- const to = resolved.get(name);
158
- if (to && !semver.satisfies(to, range)) ranges.push({ name, from: range, to: `^${to}` });
159
- }
160
- }
161
- const stopped = items.some((i) => i.status === 'stopped');
162
- if (dryRun) {
163
- for (const i of items) if (i.from && i.to && semver.gt(i.to, i.from)) i.changelog = await entriesBetween(client, i.name, i.from, i.to);
164
- }
165
-
166
- const warnings = [];
167
- for (const { name, entry, plan } of plans) {
168
- if (plan.status !== 'stopped' && plan.changedScripts) warnings.push(scriptsWarning(name, plan.move ?? entry.path));
169
- }
170
- for (const f of fresh) if (f.scripts) warnings.push(scriptsWarning(f.name, f.path));
171
- if (!dryRun) {
172
- for (const { name, entry, to, plan } of plans) {
173
- if (plan.status === 'stopped') continue;
174
- const at = join(c.root, entry.path);
175
- writeFiles(at, plan.write, plan.remove);
176
- const path = plan.move ?? entry.path;
177
- if (plan.move) {
178
- warnings.push(...unlinkSkill(c.root, entry.links, entry.path, name));
179
- mkdirSync(dirname(join(c.root, path)), { recursive: true });
180
- renameSync(at, join(c.root, path));
181
- pruneEmpty(dirname(at), c.root);
182
- }
183
- const skill = plan.skill;
184
- if (!skill && entry.links) warnings.push(...unlinkSkill(c.root, entry.links, path, name));
185
- const recorded = plan.move ? [] : (entry.links ?? []);
186
- const links = skill ? linkSkill(c.root, config, path, { recorded }) : null;
187
- if (skill && !plan.move) warnings.push(...unlinkSkill(c.root, (entry.links ?? []).filter((l) => !links.includes(l)), path, name));
188
- if (skill) warnings.push(...skipped(config, path, links, recorded, name));
189
- lock.items[name] = { version: to, path, requested: entry.requested, ...(skill ? { links } : {}), files: plan.baseline };
190
- }
191
- placeFresh(c, config, fresh);
192
- for (const f of fresh) lock.items[f.name] = lockEntry(f, Object.hasOwn(asked, f.name));
193
- if (ranges.length) config.items = { ...asked, ...Object.fromEntries(ranges.map((r) => [r.name, r.to])) };
194
- if (release) config.release = release;
195
- if (latest) delete config.release;
196
- if (!stopped) lock.release = release;
197
- if (Array.isArray(answer.foundation)) lock.foundation = answer.foundation;
198
- saveRoots(c, { config, lock });
199
- }
200
-
201
- const verb = dryRun ? 'would be' : 'is';
202
- if (items.every((i) => i.status === 'current')) io.log('Every installed item is current.');
203
- for (const i of items) {
204
- if (i.status === 'current') continue;
205
- const move = i.from && i.to ? `${i.from} to ${i.to}` : (i.to ?? i.from);
206
- const detail = i.files
207
- .filter((f) => f.outcome === 'conflict' || f.outcome === 'stop')
208
- .map((f) => (f.outcome === 'conflict' ? `${f.path} holds ${f.conflicts} conflict${f.conflicts === 1 ? '' : 's'}` : `${f.path}: ${f.reason === 'json' ? `keys changed on both sides, ${f.keys.map((k) => k || '(the document)').join(', ')}` : f.reason}`));
209
- io.log(`${i.status.padEnd(10)} ${i.name} ${move}${detail.length ? `. ${detail.join('. ')}` : ''}`);
210
- if (i.changelog) logEntries(io, i.name, i.changelog);
211
- }
212
- for (const i of items) if (i.moved) io.log(`moved ${i.name} from ${i.moved.from} to ${i.moved.to}, the folder its new skill name takes`);
213
- for (const w of warnings) io.warn(`warning: ${w.message}`);
214
- for (const r of ranges) io.log(`range ${r.name} ${r.from} to ${r.to} in collection.json`);
215
- if (release && release !== from) io.log(`release ${from} to ${release}`);
216
- if (latest && from) io.log(`release ${from} dropped from collection.json`);
217
- const conflicted = items.some((i) => i.status === 'conflict');
218
- if (conflicted) io.warn(`A file with conflict markers ${verb} left to resolve. ca-ds validate rejects it until the markers are gone.`);
219
- if (stopped) io.warn(`A stopped item ${verb} left at its version, untouched. Settle the changes it names, then run ca-ds update again.`);
220
- const result = { dryRun, release: release || (latest && from) ? { from, to: release } : null, items: items.filter((i) => i.status !== 'current'), ranges, warnings };
221
- return { exit: conflicted || stopped ? EXIT.conflict : EXIT.ok, result };
222
- },
223
- };
@@ -1,131 +0,0 @@
1
- import { statSync } from 'node:fs';
2
- import { validate, validateRepo, loadContext, loadItem, itemAt, summarize } from '../validate/index.js';
3
- import { unpack } from '../validate/zip.js';
4
- import { validateRelease, isRelease } from '../validate/release.js';
5
- import { RegistryFailure } from '../lib/registry.js';
6
- import { systemItem } from '../lib/system.js';
7
- import { handshake } from '../lib/version.js';
8
- import { EXIT, usageError } from './exit.js';
9
- import { argPath } from './items.js';
10
- import { connect, registryItems, TOKEN } from './remote.js';
11
-
12
- const NEEDS = [
13
- { check: 'html', rule: 'emblem-unchecked', item: systemItem('ca-logo') },
14
- { check: 'structured', rule: 'page-checklist-unchecked', item: systemItem('page-checklist') },
15
- ];
16
-
17
- const ONLINE_TIMEOUT = 20_000;
18
-
19
- async function check(collection, args, registry = null, purged = new Set()) {
20
- const options = { ...(registry ? { registry } : {}), ...(purged.size ? { purged } : {}) };
21
- if (args.length === 0) return { results: await validateRepo(collection, options), releases: [] };
22
- // A release is its own published state, so only an item needs the collection's context.
23
- let ctx = null;
24
- const context = async () => (ctx ??= await loadContext(collection, options));
25
- const results = [];
26
- const releases = [];
27
- for (const arg of args) {
28
- const abs = argPath(collection, arg);
29
- let stat;
30
- try {
31
- stat = statSync(abs);
32
- } catch {
33
- throw usageError(`${arg} is no item in the collection and no file or folder.`);
34
- }
35
- if (stat.isDirectory() && isRelease(abs)) {
36
- const release = await validateRelease(abs, { label: arg });
37
- releases.push(release);
38
- results.push(...release.results);
39
- } else if (stat.isDirectory()) {
40
- results.push(await validate(itemAt(await context(), abs, arg), await context()));
41
- } else {
42
- const { dir, cleanup } = unpack(abs);
43
- try {
44
- results.push(await validate(Object.assign(loadItem(dir), { label: arg }), await context()));
45
- } finally {
46
- cleanup();
47
- }
48
- }
49
- }
50
- return { results, releases };
51
- }
52
-
53
- const where = (f) => [f.file, f.line].filter((x) => x != null).join(':');
54
-
55
- const isTimeout = (err) => ['TimeoutError', 'AbortError'].includes(err?.name);
56
-
57
- async function purgesOf(client, io) {
58
- const out = { url: client.url, names: [], error: null };
59
- try {
60
- out.names = (await client.purges()).map((p) => p.name);
61
- } catch (err) {
62
- if (!(err instanceof RegistryFailure) && !isTimeout(err)) throw err;
63
- out.error = err.message;
64
- io.warn(`The registry didn't answer the read of its purges, so a link to a purged item reads as one to an item it never held. ${err.message}`);
65
- }
66
- return out;
67
- }
68
-
69
- function print(io, results, releases, summary) {
70
- const rows = [...releases.map((r) => ({ ...r, name: `release ${r.tag ?? '(no tag)'}` })), ...results];
71
- for (const [title, key] of [['Rejections', 'rejections'], ['Warnings', 'warnings']]) {
72
- const withAny = rows.filter((r) => r[key].length > 0);
73
- if (withAny.length === 0) continue;
74
- io.log(`${title}\n`);
75
- for (const r of withAny) {
76
- io.log(` ${r.name ?? '(unnamed)'} ${r.dir}`);
77
- for (const f of r[key]) io.log(` ${f.check}/${f.rule} ${where(f)} ${f.message}`);
78
- io.log('');
79
- }
80
- }
81
- const counts = (by) => Object.entries(by).map(([k, n]) => `${k} ${n}`).join(', ');
82
- const scope = summary.releases ? `${summary.releases} release${summary.releases === 1 ? '' : 's'}, ` : '';
83
- io.log(`${scope}${summary.items} items, ${summary.rejections} rejections, ${summary.warnings} warnings`);
84
- if (summary.rejections) io.log(` rejections: ${counts(summary.byRule.rejections)}`);
85
- if (summary.warnings) io.log(` warnings: ${counts(summary.byRule.warnings)}`);
86
- }
87
-
88
- export const command = {
89
- synopsis: 'validate',
90
- summary: 'run the validator over the collection',
91
- usage: ['ca-ds validate [<name, folder, ZIP, or release folder> ...] [--offline] [--token <token>]'],
92
- options: { offline: { type: 'boolean' }, ...TOKEN },
93
- async run({ values, positionals, io, collection, env, fetch }) {
94
- const c = collection();
95
- const named = !values.offline && Boolean(c.config.registry || env.CA_DS_URL);
96
- const timed = (url, init = {}) => fetch(url, { ...init, signal: AbortSignal.timeout(ONLINE_TIMEOUT) });
97
- const purges = named ? await purgesOf(connect(c, { values, env, fetch: timed }), io) : null;
98
- const purged = new Set(purges?.names ?? []);
99
- let { results, releases } = await check(c, positionals, null, purged);
100
- let online = null;
101
- const targets = [...new Set(results.flatMap((r) => r.warnings.filter((w) => w.check === 'links' && w.needs).map((w) => w.needs)))];
102
- const missing = [...new Set([...NEEDS.filter((n) => results.some((r) => r.warnings.some((w) => w.check === n.check && w.rule === n.rule))).map((n) => n.item), ...targets])];
103
- if (missing.length && named) {
104
- const client = connect(c, { values, env, fetch: timed });
105
- online = { url: client.url, items: [], handshake: null, error: null };
106
- let fetched = null;
107
- try {
108
- const health = await client.health();
109
- online.handshake = handshake(client.url, health?.package?.version ?? null);
110
- if (online.handshake.message) io.warn(online.handshake.message);
111
- fetched = await registryItems(client, missing);
112
- online.items = [...fetched.items.keys()];
113
- // Once asked, a link target the registry lacks resolves to nothing, so validate again.
114
- if (online.items.length || targets.length) ({ results, releases } = await check(c, positionals, fetched.items, purged));
115
- } catch (err) {
116
- if (!(err instanceof RegistryFailure) && !isTimeout(err)) throw err;
117
- online.error = err.message;
118
- io.warn(`The registry didn't answer the read of ${missing.join(' and ')}, so the checks that need them stay skipped. ${err.message}`);
119
- } finally {
120
- fetched?.cleanup();
121
- }
122
- }
123
- const summary = summarize(results, releases);
124
- const own = releases.map(({ results: _, ...release }) => release);
125
- if (!io.json) print(io, results, own, summary);
126
- return {
127
- exit: summary.rejections > 0 ? EXIT.rejected : EXIT.ok,
128
- result: { summary, ...(own.length > 0 ? { releases: own } : {}), items: results, ...(online ? { registry: online } : {}), ...(purges ? { purges } : {}) },
129
- };
130
- },
131
- };
@@ -1,12 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
-
3
- export function openUrl(url, platform = process.platform) {
4
- const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'start' : 'xdg-open';
5
- try {
6
- const child = spawn(cmd, [url], { stdio: 'ignore', detached: true, shell: platform === 'win32' });
7
- child.on('error', () => {});
8
- child.unref();
9
- } catch {
10
- /* best effort */
11
- }
12
- }
package/src/lib/build.js DELETED
@@ -1,249 +0,0 @@
1
- // A source is { base, order, manifests, dirOf(name), read(absolutePath) }, on disk or virtual.
2
- // No @layer, since source order alone governs precedence, and no `targets`, so modern CSS ships as authored.
3
-
4
- import './serial.js';
5
- import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';
6
- import { dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from 'node:path';
7
- import { bundleAsync, transform } from 'lightningcss';
8
- import { build } from 'esbuild';
9
- import { resolve } from './resolve.js';
10
- import { buildTokens, tokenLayers } from './tokens.js';
11
- import { foundationOf } from './collection.js';
12
-
13
- const encoder = new TextEncoder();
14
- const decoder = new TextDecoder();
15
- const text = (bytes) => (typeof bytes === 'string' ? bytes : decoder.decode(bytes));
16
- const slashes = (p) => p.split(sep).join('/');
17
-
18
- export function entryFiles(order, manifests, role) {
19
- return order.flatMap((name) =>
20
- (manifests.get(name).files ?? []).filter((f) => f.role === role).map((f) => ({ name, path: f.path })),
21
- );
22
- }
23
-
24
- function specifier(from, to) {
25
- const r = slashes(relative(from, to));
26
- return r.startsWith('.') ? r : `./${r}`;
27
- }
28
-
29
- // Without a preset, the everything preset when one is defined, and otherwise every item.
30
- export function buildSet(collection, { preset = null } = {}) {
31
- const { config, system } = collection;
32
- const found = new Map(collection.items.map((item) => [item.manifest.name, item]));
33
- const manifests = new Map([...found].map(([name, { manifest }]) => [name, manifest]));
34
- const presets = { ...(system?.presets ?? {}), ...(config?.presets ?? {}) };
35
- const foundation = foundationOf(collection);
36
- let names;
37
- let from;
38
- if (preset !== null) {
39
- if (!Object.hasOwn(presets, preset)) {
40
- const known = Object.keys(presets);
41
- throw Object.assign(new Error(`The collection has no preset ${preset}. ${known.length ? `Its presets are ${known.join(', ')}.` : 'It defines no presets.'}`), { usage: true });
42
- }
43
- names = presets[preset].items;
44
- from = `the "${preset}" preset`;
45
- } else if (Object.hasOwn(presets, 'everything')) {
46
- names = presets.everything.items;
47
- from = 'the "everything" preset';
48
- } else {
49
- const asked = Object.keys(config?.items ?? {}).filter((name) => manifests.has(name));
50
- names = [...new Set([...asked, ...manifests.keys()])];
51
- from = 'every item in the collection';
52
- }
53
- const order = resolve(names, manifests, { foundation });
54
- return { order, items: new Map(order.map((name) => [name, found.get(name)])), foundation, from };
55
- }
56
-
57
- export function diskSource(root, set) {
58
- root = resolvePath(root);
59
- return {
60
- base: root,
61
- order: set.order,
62
- manifests: new Map([...set.items].map(([name, { manifest }]) => [name, manifest])),
63
- dirOf: (name) => join(root, set.items.get(name).dir),
64
- read: (path) => {
65
- try {
66
- return readFileSync(path);
67
- } catch {
68
- return null;
69
- }
70
- },
71
- };
72
- }
73
-
74
- export function sourceTokens(source, { shared } = {}) {
75
- return tokenLayers(
76
- source.order.map((name) => ({
77
- base: slashes(relative(source.base, source.dirOf(name))) || '.',
78
- manifest: source.manifests.get(name),
79
- json: (path) => {
80
- const bytes = source.read(join(source.dirOf(name), path));
81
- return bytes === null ? null : JSON.parse(text(bytes));
82
- },
83
- })),
84
- { shared },
85
- );
86
- }
87
-
88
- // Where a file an item's CSS links lands: copied into the output, as fonts are, or in place, as in a bundle ZIP.
89
- export const copied = (source, out) => (name, path) => join(out, path);
90
- export const inPlace = (source) => (name, path) => join(source.dirOf(name), path);
91
-
92
- function owner(source, file) {
93
- for (const name of source.order) {
94
- const dir = source.dirOf(name);
95
- const r = relative(dir, file);
96
- if (r && !r.startsWith('..') && !r.startsWith(sep) && !/^[a-zA-Z]:/.test(r)) return { name, path: slashes(r) };
97
- }
98
- return null;
99
- }
100
-
101
- const relativeUrl = (url) => !/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(url);
102
-
103
- export async function buildCss(source, { out, locate }) {
104
- const entry = join(out, 'ca-ds.entry.css');
105
- const lines = entryFiles(source.order, source.manifests, 'css').map((f) => `@import "${specifier(out, join(source.dirOf(f.name), f.path))}"; /* ${f.name} */`);
106
- const css = `${lines.join('\n')}\n`;
107
- const read = (file) => {
108
- if (file === entry) return css;
109
- const bytes = source.read(file);
110
- if (bytes === null) throw new Error(`The CSS imports ${slashes(relative(source.base, file))}, which no item in the set ships.`);
111
- return text(bytes);
112
- };
113
- const { code, map, dependencies } = await bundleAsync({
114
- filename: entry,
115
- sourceMap: true,
116
- projectRoot: out,
117
- analyzeDependencies: true,
118
- resolver: { read, resolve: (spec, from) => join(dirname(from), spec) },
119
- });
120
- let output = code.toString();
121
- const assets = new Map();
122
- for (const dep of dependencies.filter((d) => d.type === 'url')) {
123
- let url = dep.url;
124
- if (relativeUrl(dep.url)) {
125
- const file = join(dirname(dep.loc.filePath), dep.url);
126
- const held = owner(source, file);
127
- const to = held ? locate(held.name, held.path) : file;
128
- if (to !== file) assets.set(to, file);
129
- url = slashes(relative(out, to));
130
- }
131
- output = output.replaceAll(`"${dep.placeholder}"`, JSON.stringify(url));
132
- }
133
- return { code: output, map: JSON.parse(map.toString()), assets: [...assets].map(([to, from]) => ({ from, to })) };
134
- }
135
-
136
- // The plugin reads every file through the source, so esbuild touches no disk.
137
- export async function buildJs(source, { out, file = 'ca-ds.js', minify = false }) {
138
- const lines = entryFiles(source.order, source.manifests, 'js').map((f) => `import "${specifier(out, join(source.dirOf(f.name), f.path))}"; /* ${f.name} */`);
139
- const plugin = {
140
- name: 'ca-ds-items',
141
- setup(b) {
142
- b.onResolve({ filter: /.*/ }, (args) => ({ path: join(args.resolveDir, args.path) }));
143
- b.onLoad({ filter: /.*/ }, (args) => {
144
- const bytes = source.read(args.path);
145
- if (bytes === null) return { errors: [{ text: `${slashes(relative(source.base, args.path))} is in no item in the set.` }] };
146
- return { contents: text(bytes), loader: 'js', resolveDir: dirname(args.path) };
147
- });
148
- },
149
- };
150
- const result = await build({
151
- stdin: { contents: `${lines.join('\n')}\n`, resolveDir: out, sourcefile: 'ca-ds.entry.js' },
152
- absWorkingDir: source.base,
153
- bundle: true,
154
- format: 'esm',
155
- minify,
156
- sourcemap: true,
157
- write: false,
158
- outfile: join(out, file),
159
- logLevel: 'silent',
160
- plugins: [plugin],
161
- });
162
- const code = result.outputFiles.find((f) => f.path.endsWith('.js'));
163
- const map = result.outputFiles.find((f) => f.path.endsWith('.map'));
164
- return { code: decoder.decode(code.contents), map: JSON.parse(decoder.decode(map.contents)) };
165
- }
166
-
167
- // Each ; in a map's mappings starts a generated line.
168
- function shifted(map, prefix) {
169
- const lines = prefix.split('\n').length - 1;
170
- return { ...map, mappings: ';'.repeat(lines) + map.mappings };
171
- }
172
-
173
- function minifyCss({ code, map }, file) {
174
- const result = transform({
175
- filename: file,
176
- code: encoder.encode(code),
177
- minify: true,
178
- sourceMap: true,
179
- inputSourceMap: JSON.stringify(map),
180
- });
181
- return { code: result.code.toString(), map: JSON.parse(result.map.toString()) };
182
- }
183
-
184
- export async function buildOutputs(source, { tokens, out, locate }) {
185
- const files = new Map();
186
- const css = await buildCss(source, { out, locate });
187
- const min = minifyCss(css, 'ca-ds.css');
188
- const minTokens = transform({ filename: 'tokens.css', code: encoder.encode(tokens), minify: true }).code.toString();
189
- const put = (name, code, map) => {
190
- files.set(name, encoder.encode(code));
191
- files.set(`${name}.map`, encoder.encode(JSON.stringify(map)));
192
- };
193
- const comment = (name) => `\n/*# sourceMappingURL=${name}.map */\n`;
194
- put('ca-ds.css', `${tokens}\n${css.code}${comment('ca-ds.css')}`, { ...shifted(css.map, `${tokens}\n`), file: 'ca-ds.css' });
195
- put('ca-ds.min.css', `${minTokens}\n${min.code}${comment('ca-ds.min.css')}`, { ...shifted(min.map, `${minTokens}\n`), file: 'ca-ds.min.css' });
196
- for (const [name, minify] of [['ca-ds.js', false], ['ca-ds.min.js', true]]) {
197
- const js = await buildJs(source, { out, file: name, minify });
198
- put(name, js.code, js.map);
199
- }
200
- files.set('tokens.css', encoder.encode(tokens));
201
- return { files, assets: css.assets };
202
- }
203
-
204
- export const hasTokens = (source) => [...source.manifests.values()].some((m) => m.kind === 'tokens');
205
-
206
- export function fontAssets(source, out) {
207
- return source.order.flatMap((name) =>
208
- (source.manifests.get(name).files ?? [])
209
- .filter((f) => f.role === 'font')
210
- .map((f) => ({ from: join(source.dirOf(name), f.path), to: join(out, f.path) })),
211
- );
212
- }
213
-
214
- export function distFolder(collection) {
215
- const named = collection.config?.dist ?? 'dist';
216
- const dir = resolvePath(collection.root, named);
217
- const r = relative(collection.root, dir);
218
- if (!r || r.startsWith('..') || isAbsolute(r)) {
219
- throw Object.assign(new Error(`collection.json's dist, ${named}, is not a folder inside the collection.`), { usage: true });
220
- }
221
- return dir;
222
- }
223
-
224
- export async function buildDist(collection, { preset = null } = {}) {
225
- const set = buildSet(collection, { preset });
226
- const source = diskSource(collection.root, set);
227
- const out = distFolder(collection);
228
- const warnings = [];
229
- if (!hasTokens(source)) {
230
- warnings.push({ rule: 'no-tokens', message: `The set, ${set.from}, holds no tokens item, so tokens.css holds only its items' own tokens and a var(--ca-*) the shared layers define resolves to nothing.` });
231
- }
232
- const tokens = await buildTokens({ sources: sourceTokens(source) });
233
- const { files, assets } = await buildOutputs(source, { tokens, out, locate: copied(source, out) });
234
- const copies = new Map([...fontAssets(source, out), ...assets].map((a) => [a.to, a.from]));
235
- mkdirSync(out, { recursive: true });
236
- const written = [];
237
- for (const [name, bytes] of files) {
238
- writeFileSync(join(out, name), bytes);
239
- written.push(name);
240
- }
241
- for (const [to, from] of copies) {
242
- const bytes = source.read(from);
243
- if (bytes === null) throw new Error(`${slashes(relative(collection.root, from))} is missing, and the CSS links it.`);
244
- mkdirSync(dirname(to), { recursive: true });
245
- writeFileSync(to, bytes);
246
- written.push(slashes(relative(out, to)));
247
- }
248
- return { dist: slashes(relative(collection.root, out)), from: set.from, order: set.order, files: written.sort(), warnings };
249
- }