@cagov/ca-ds 1.0.0 → 1.2.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 +43 -26
  2. package/THIRD-PARTY-LICENSES.txt +690 -0
  3. package/ca-ds.js +48390 -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
@@ -1,295 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { join, relative, resolve as resolvePath, sep } from 'node:path';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import { unzipSync } from 'fflate';
5
- import { loadContext } from '../validate/index.js';
6
- import { itemFiles, zip } from '../lib/pack.js';
7
- import { packRelease, publishOrder, readRelease, ReleaseError } from '../lib/release.js';
8
- import { SYSTEM_NAMESPACE, isSystemItem } from '../lib/system.js';
9
- import { handshake } from '../lib/version.js';
10
- import { CliError, EXIT, usageError } from './exit.js';
11
- import { argPath } from './items.js';
12
- import { connect, heldAs, TOKEN } from './remote.js';
13
-
14
- const where = (f) => [f.file, f.line].filter((x) => x != null).join(':');
15
- const rel = (root, p) => {
16
- const r = relative(root, p);
17
- return r.startsWith('..') ? p : r.split(sep).join('/');
18
- };
19
-
20
- function printFindings(io, what, findings) {
21
- io.warn(what);
22
- for (const f of findings) io.warn(` ${f.check}/${f.rule} ${where(f)} ${f.message}`);
23
- }
24
-
25
- async function shake(client, io, dryRun) {
26
- const health = await client.health();
27
- const result = handshake(client.url, health?.package?.version ?? null);
28
- if (result.outcome === 'major' && dryRun) return result;
29
- if (result.outcome === 'major') throw new CliError(`${result.message} ca-ds publish refuses.`, EXIT.rejected);
30
- if (result.message) io.warn(result.message);
31
- return result;
32
- }
33
-
34
- function targets(c, ctx, args) {
35
- const order = publishOrder(ctx.catalog, ctx.foundation);
36
- const authored = order.filter((n) => ctx.catalog.get(n).authored !== false);
37
- if (args.length === 0) return authored;
38
- const named = new Set();
39
- for (const arg of args) {
40
- const abs = argPath(c, arg);
41
- const item = [...ctx.catalog.values()].find((i) => join(c.root, i.rel) === abs);
42
- if (!item) throw usageError(`${arg} is no item in the collection.`);
43
- if (item.authored === false) throw usageError(`${item.manifest.name} is installed, not authored, so it isn't the collection's to publish.`);
44
- named.add(item.manifest.name);
45
- }
46
- return authored.filter((n) => named.has(n));
47
- }
48
-
49
- const BUMPS = ['patch', 'minor', 'major'];
50
-
51
- const conflictLines = (conflicts) =>
52
- conflicts.map((f) => ` ${f.path}: ${f.reason === 'json' ? `keys changed on both sides, ${(f.keys ?? []).map((k) => k || '(the document)').join(', ')}` : f.reason === 'text' ? 'lines changed on both sides' : f.reason}`);
53
-
54
- function sentLine(name, body) {
55
- const from = body.base ? ` (from ${body.base}${body.merged ? `, merged onto ${body.previous ?? body.latest}` : ''})` : '';
56
- return `${name} ${body.version}${from}`;
57
- }
58
-
59
- // A dry run publishes nothing, so an item that needs another the run sends ahead of it, a dependency, a
60
- // member, or the foundation, meets a registry without that change, and its rejections may be that alone.
61
- function waitsOnRun(manifest, foundation, ahead) {
62
- return [...Object.keys(manifest.dependencies ?? {}), ...(manifest.members ?? []), ...foundation].some((n) => n !== manifest.name && ahead.has(n));
63
- }
64
-
65
- // Sends each changed item, and never writes the working copy: ca-ds pull brings the minted versions back.
66
- async function items(c, client, values, args, io, shook) {
67
- const ctx = await loadContext(c);
68
- const dryRun = values['dry-run'] === true;
69
- const options = { bump: values.bump ?? null, summary: values.summary ?? null };
70
- const result = { registry: client.url, handshake: shook, dryRun, published: [], current: [], behind: [], conflicts: [], pending: [], purged: [], rejected: null };
71
- const ahead = new Set();
72
- const purged = new Set((await client.purges()).map((p) => p.name));
73
- for (const name of targets(c, ctx, args)) {
74
- const item = ctx.catalog.get(name);
75
- const { version } = item.manifest;
76
- if (purged.has(name)) {
77
- result.purged.push({ name, version });
78
- io.log(`purged ${name} ${version}, which the registry takes no more and ca-ds pull removes`);
79
- continue;
80
- }
81
- const files = itemFiles(item);
82
- const held = await heldAs(client, name, version, files);
83
- if (held.state === 'same') {
84
- if (held.latest !== null && held.latest !== version) {
85
- result.behind.push({ name, version, latest: held.latest });
86
- io.log(`behind ${name} ${version}, the registry's latest is ${held.latest}. Run ca-ds pull.`);
87
- } else result.current.push(name);
88
- continue;
89
- }
90
- const bytes = zip(files);
91
- const sent = dryRun ? await client.dryRun(bytes, `the dry run of ${name}`, options) : await client.upload(bytes, `${name}`, options);
92
- const { body } = sent;
93
- if (sent.status === 409 && (body.error === 'conflict' || body.error === 'unknown-base')) {
94
- result.conflicts.push({ name, version, error: body.error, latest: body.latest ?? null, conflicts: body.conflicts ?? [] });
95
- io.log(`${body.error === 'conflict' ? 'conflict ' : 'unknown '} ${name} ${version}: ${body.message}`);
96
- if (body.conflicts?.length) for (const line of conflictLines(body.conflicts)) io.log(line);
97
- continue;
98
- }
99
- if (dryRun && sent.status === 200 && (body.state === 'conflict' || body.state === 'unknown-base')) {
100
- result.conflicts.push({ name, version, error: body.state, latest: body.latest ?? null, conflicts: body.conflicts ?? [] });
101
- io.log(`${body.state === 'conflict' ? 'conflict ' : 'unknown '} ${name} ${version}, against the registry's ${body.latest}`);
102
- if (body.conflicts?.length) for (const line of conflictLines(body.conflicts)) io.log(line);
103
- continue;
104
- }
105
- const rejections = (sent.status === 422 && body.rejections) || (dryRun && sent.status === 200 && body.rejections?.length ? body.rejections : null);
106
- if (rejections && dryRun && waitsOnRun(item.manifest, ctx.foundation, ahead)) {
107
- result.pending.push({ name, version });
108
- ahead.add(name);
109
- io.log(`pending ${name} ${version}, with ${rejections.length} findings that may wait on an item the run sends before it`);
110
- continue;
111
- }
112
- if (rejections) {
113
- printFindings(io, `rejected ${name} ${version}${dryRun ? ", by the registry's dry run" : ''}`, rejections);
114
- result.rejected ??= { name, version, rejections, warnings: body.warnings ?? [] };
115
- if (dryRun) {
116
- ahead.add(name);
117
- continue;
118
- }
119
- return { exit: EXIT.rejected, result };
120
- }
121
- if (sent.status === 200 && (body.state === 'current' || !dryRun)) {
122
- if (body.version && body.version !== version) {
123
- result.behind.push({ name, version, latest: body.version });
124
- io.log(`behind ${name} ${version}, whose changes the registry's ${body.version} already holds. Run ca-ds pull.`);
125
- } else result.current.push(name);
126
- continue;
127
- }
128
- if (dryRun && sent.status === 200) {
129
- ahead.add(name);
130
- result.published.push({ name, version: body.version, base: body.base, merged: body.merged, bump: body.bump, floor: body.floor, warnings: body.warnings?.length ?? 0 });
131
- const floor = body.floor && body.floor !== 'patch' ? `, at least ${body.floor}: ${body.reasons.join('; ')}` : '';
132
- io.log(body.state === 'new' ? `would add ${name} ${body.version}, a first publish` : `would mint ${sentLine(name, { ...body, previous: body.latest })}, a ${body.bump}${floor}`);
133
- continue;
134
- }
135
- if (sent.status !== 201) throw new CliError(`The registry at ${client.url} refused ${name} ${version}, ${sent.status}. ${body.message ?? ''}`.trim(), EXIT.registry);
136
- result.published.push({ name, version: body.version, base: body.base, merged: body.merged, bump: body.bump, floor: body.floor, warnings: body.warnings?.length ?? 0 });
137
- io.log(`published ${sentLine(name, body)}`);
138
- }
139
- const verb = dryRun ? 'would publish' : 'published';
140
- const pending = result.pending.length ? `, ${result.pending.length} pending` : '';
141
- io.log(`${result.published.length} ${verb}, ${result.current.length} current, ${result.behind.length} behind, ${result.conflicts.length} conflicting${pending}${result.purged.length ? `, ${result.purged.length} purged` : ''}`);
142
- if (!dryRun && result.published.length) io.warn('The registry minted the versions above. Run ca-ds pull to bring them into the collection.');
143
- if (result.rejected) return { exit: EXIT.rejected, result };
144
- if (result.conflicts.length === 0) return { result };
145
- io.warn('A conflicting item published nothing. Run ca-ds pull, settle each conflict, then publish again.');
146
- return { exit: EXIT.conflict, result };
147
- }
148
-
149
- // A first publish stands, and a version the registry holds with the same files is already published.
150
- async function fromFolder(client, zips, io, out) {
151
- for (const { entry, bytes } of zips) {
152
- const files = new Map(Object.entries(unzipSync(bytes)).filter(([path]) => !path.endsWith('/')));
153
- const held = await heldAs(client, entry.name, entry.version, files);
154
- if (held.state === 'same') {
155
- out.existing.push(entry.name);
156
- io.log(`exists ${entry.name} ${entry.version}`);
157
- continue;
158
- }
159
- if (held.state !== 'new') {
160
- const why = held.state === 'changed' ? 'with other files' : `at other versions, its latest ${held.latest}`;
161
- throw new CliError(`The registry at ${client.url} holds ${entry.name} ${why}, so the release folder's ${entry.version} can't publish. Pack the release from a checkout ca-ds pull brought current.`, EXIT.rejected);
162
- }
163
- const sent = await client.upload(bytes, `${entry.name} ${entry.version}`);
164
- if (sent.status === 201) {
165
- out.published.push(entry.name);
166
- io.log(`published ${entry.name} ${entry.version}`);
167
- } else if (sent.status === 422 && sent.body.rejections) {
168
- printFindings(io, `rejected ${entry.name} ${entry.version}`, sent.body.rejections);
169
- return { exit: EXIT.rejected, result: { ...out, rejected: [{ name: entry.name, version: entry.version, rejections: sent.body.rejections, warnings: sent.body.warnings ?? [] }] } };
170
- } else {
171
- throw new CliError(`The registry at ${client.url} refused ${entry.name} ${entry.version}, ${sent.status}. ${sent.body.message ?? ''}`.trim(), EXIT.registry);
172
- }
173
- }
174
- return null;
175
- }
176
-
177
- // A release records the registry's versions, so every standard item must be current first.
178
- async function notCurrent(c, client) {
179
- const ctx = await loadContext(c);
180
- const out = [];
181
- for (const [name, item] of ctx.catalog) {
182
- if (!isSystemItem(name) || item.authored === false) continue;
183
- const held = await heldAs(client, name, item.manifest.version, itemFiles(item));
184
- if (held.state !== 'same' || held.latest !== item.manifest.version) out.push({ name, version: item.manifest.version, state: held.state, latest: held.latest });
185
- }
186
- return out;
187
- }
188
-
189
- async function release(c, client, values, io, shook) {
190
- if (!(c.config.namespaces ?? []).includes(SYSTEM_NAMESPACE)) {
191
- throw usageError(`Only the ${SYSTEM_NAMESPACE} namespace records releases, and collection.json doesn't author it.`);
192
- }
193
- const tag = values.release;
194
- const out = { registry: client.url, handshake: shook, tag, dir: null, published: [], existing: [], release: null, warmed: [], rejected: [], behind: [] };
195
- let dir;
196
- let release;
197
- let zips;
198
- try {
199
- if (values.from !== undefined) {
200
- dir = resolvePath(values.from);
201
- if (!existsSync(dir)) throw usageError(`${values.from} is no folder.`);
202
- } else {
203
- out.behind = await notCurrent(c, client);
204
- if (out.behind.length) {
205
- for (const b of out.behind) {
206
- io.log(`${b.state === 'changed' || b.state === 'new' ? 'changed ' : 'behind '} ${b.name} ${b.version}${b.latest ? `, the registry's latest is ${b.latest}` : ''}`);
207
- }
208
- io.warn(`A release records the registry's versions, and ${out.behind.length} ${SYSTEM_NAMESPACE} items differ from them. Run ca-ds publish, then ca-ds pull, then release again.`);
209
- return { exit: EXIT.rejected, result: out };
210
- }
211
- const packed = await packRelease({ root: c.root, tag, out: values.out === undefined ? null : resolvePath(values.out) });
212
- if (!packed.dir) {
213
- for (const r of packed.rejected) printFindings(io, `rejected ${r.name ?? '(unnamed)'} ${r.dir}`, r.rejections);
214
- io.warn(`published nothing: ${packed.rejected.length} items rejected`);
215
- return { exit: EXIT.rejected, result: { ...out, rejected: packed.rejected } };
216
- }
217
- dir = packed.dir;
218
- io.log(`packed ${tag} ${rel(c.root, dir)}`);
219
- }
220
- ({ release, zips } = readRelease(dir));
221
- } catch (err) {
222
- if (err instanceof ReleaseError) throw new CliError(err.message, EXIT.rejected);
223
- throw err;
224
- }
225
- out.dir = rel(c.root, dir);
226
- if (release.tag !== tag) throw usageError(`${out.dir}/release.json is the release ${release.tag}, and --release names ${tag}.`);
227
-
228
- if (values.from !== undefined) {
229
- const refused = await fromFolder(client, zips, io, out);
230
- if (refused) return refused;
231
- } else {
232
- for (const { entry } of zips) out.existing.push(entry.name);
233
- }
234
-
235
- const recorded = await client.recordRelease(release);
236
- if (recorded.status === 409 && recorded.body.error === 'release-exists') {
237
- const { createdAt, ...held } = (await client.release(release.tag)) ?? {};
238
- if (!isDeepStrictEqual(held, release)) throw new CliError(`The registry at ${client.url} already holds ${release.tag}, with other content than this release.json.`, EXIT.rejected);
239
- out.release = 'existing';
240
- } else if (recorded.status === 201) {
241
- out.release = 'created';
242
- } else {
243
- if (recorded.body.rejections) printFindings(io, `rejected the release ${release.tag}`, recorded.body.rejections);
244
- throw new CliError(`The registry at ${client.url} refused the release ${release.tag}, ${recorded.status}. ${recorded.body.message ?? ''}`.trim(), recorded.status === 422 ? EXIT.rejected : EXIT.registry);
245
- }
246
- io.log(`${out.release === 'created' ? 'released' : 'exists'} ${release.tag}, ${release.items.length} items`);
247
-
248
- if (!values['no-warm']) {
249
- for (const preset of Object.keys(release.presets)) {
250
- const location = await client.warm(preset, release.tag);
251
- out.warmed.push(preset);
252
- io.log(`warmed ${preset} ${location}`);
253
- }
254
- }
255
- io.log(`${out.published.length} published, ${out.existing.length} already published, release ${out.release}, ${out.warmed.length} presets warmed`);
256
- return { result: out };
257
- }
258
-
259
- export const command = {
260
- synopsis: 'publish [name...]',
261
- summary: 'publish changed authored items, with --release',
262
- usage: [
263
- 'ca-ds publish [<name or folder> ...] [--bump patch|minor|major] [--summary <text>] [--dry-run] [--token <token>]',
264
- 'ca-ds publish --release <tag> [--from <release folder> | --out <folder>] [--no-warm] [--token <token>]',
265
- ],
266
- options: {
267
- ...TOKEN,
268
- bump: { type: 'string' },
269
- summary: { type: 'string' },
270
- 'dry-run': { type: 'boolean' },
271
- release: { type: 'string' },
272
- from: { type: 'string' },
273
- out: { type: 'string' },
274
- 'no-warm': { type: 'boolean' },
275
- },
276
- async run({ values, positionals, io, collection, env, fetch }) {
277
- if (values.bump !== undefined && !BUMPS.includes(values.bump)) throw usageError(`--bump is one of ${BUMPS.join(', ')}, not ${values.bump}.`);
278
- if (values.release === undefined) {
279
- for (const flag of ['from', 'out', 'no-warm']) if (values[flag] !== undefined) throw usageError(`--${flag} takes --release.`);
280
- } else {
281
- for (const flag of ['bump', 'summary', 'dry-run']) if (values[flag] !== undefined) throw usageError(`--${flag} publishes items, and --release records a release. Pass one.`);
282
- if (positionals.length) throw usageError('--release publishes every item. Name no item with it.');
283
- if (values.from !== undefined && values.out !== undefined) throw usageError('--out names where the pack goes, and --from publishes a folder already packed. Pass one.');
284
- }
285
- const c = collection();
286
- const client = connect(c, { values, env, fetch });
287
- const shook = await shake(client, io, values['dry-run'] === true);
288
- // A dry run sends nothing, so a registry it can't speak to skips it rather than fail.
289
- if (shook.outcome === 'major') {
290
- io.warn(`${shook.message} The dry run skips.`);
291
- return { result: { registry: client.url, handshake: shook, dryRun: true, skipped: true } };
292
- }
293
- return values.release === undefined ? items(c, client, values, positionals, io, shook) : release(c, client, values, io, shook);
294
- },
295
- };
package/src/cli/pull.js DELETED
@@ -1,208 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import semver from 'semver';
5
- import { SKIP } from '../lib/catalog.js';
6
- import { withVersion } from '../lib/json-text.js';
7
- import { mergeFile } from '../lib/merge.js';
8
- import { repoFolder } from '../lib/system.js';
9
- import { safeSource } from '../validate/release.js';
10
- import { loadItem } from '../validate/item.js';
11
- import { EXIT, usageError } from './exit.js';
12
- import { baselineOf, hashesOf, installPath, localFiles, pruneEmpty, safePath, scopeOf, writeFiles } from './install.js';
13
- import { connect, TOKEN } from './remote.js';
14
-
15
- const sorted = (list) => [...list].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
16
-
17
- function unsafe(collection, scope, source) {
18
- if (!safeSource(source)) return `its source, ${JSON.stringify(source ?? null)}, names no folder inside the collection`;
19
- const folder = repoFolder(scope);
20
- if (folder && !source.startsWith(folder)) return `its source, \`${source}\`, sits outside \`${folder}\`, the folder a ${scope} item is written to`;
21
- const install = installPath(collection.config, '').replace(/\/+$/, '');
22
- if (source === install || source.startsWith(`${install}/`)) return `its source, \`${source}\`, sits in the install folder, \`${install}/\``;
23
- if (source.split('/').some((s) => SKIP.has(s))) return `its source, \`${source}\`, sits in a folder the catalog skips`;
24
- return null;
25
- }
26
-
27
- // Nesting alone is fine; overlapping another item's files, its notes and check pages included, isn't.
28
- function nested(collection, name, source, shipped) {
29
- const inside = (path, folder) => path.startsWith(`${folder}/`);
30
- for (const other of collection.items) {
31
- if (other.manifest?.name === name) continue;
32
- if (inside(source, other.dir)) {
33
- const held = loadItem(join(collection.root, other.dir));
34
- const files = [...held.present, ...held.checks, ...held.notes].map((f) => `${other.dir}/${f}`);
35
- if (files.some((f) => inside(f, source))) return `${other.manifest?.name ?? 'another item'} has files inside \`${source}\`, which its item.json would cut off from it`;
36
- }
37
- if (inside(other.dir, source) && shipped.some((f) => inside(`${source}/${f}`, other.dir))) {
38
- return `${other.manifest?.name ?? 'another item'} sits at \`${other.dir}\`, over files it ships`;
39
- }
40
- }
41
- return null;
42
- }
43
-
44
- const decoder = new TextDecoder();
45
- const encoder = new TextEncoder();
46
- const stamp = (bytes, version) => (bytes ? encoder.encode(withVersion(decoder.decode(bytes), version)) : bytes);
47
-
48
- // Base B, the collection's version; theirs L, the registry's latest; ours the local files. A file
49
- // untouched locally fast-forwards, and item.json's version is L on every side, so it never conflicts.
50
- async function mergeLocal(client, name, { from, to, baseRecord, record, local }) {
51
- const labels = { ours: 'local', theirs: `${name}@${to}` };
52
- const base = baseRecord ? baselineOf(baseRecord) : {};
53
- const theirs = baselineOf(record);
54
- const ours = hashesOf(local);
55
- const fetchAt = (version, path, hash) => (hash ? client.file(name, version, path, hash) : null);
56
- const files = [];
57
- const write = new Map();
58
- const remove = [];
59
- const paths = [...new Set([...Object.keys(base), ...Object.keys(ours), ...Object.keys(theirs)])].sort();
60
- for (const path of paths) {
61
- const [o, a, b] = [base[path], ours[path], theirs[path]];
62
- let merged;
63
- if (path === 'item.json') {
64
- const sides = {
65
- base: stamp(await fetchAt(from, path, o), to),
66
- ours: stamp(local.get(path) ?? null, to),
67
- theirs: await fetchAt(to, path, b),
68
- };
69
- merged = mergeFile(path, sides, labels);
70
- if (merged.outcome === 'kept' && !Buffer.from(merged.bytes ?? []).equals(Buffer.from(local.get(path) ?? []))) merged = { ...merged, outcome: 'merged' };
71
- } else {
72
- if (a === b || (baseRecord && b === o)) continue;
73
- if (baseRecord && a === o) merged = { outcome: 'updated', bytes: await fetchAt(to, path, b) };
74
- else merged = mergeFile(path, { base: await fetchAt(from, path, o), ours: local.get(path) ?? null, theirs: await fetchAt(to, path, b) }, labels);
75
- }
76
- if (merged.outcome === 'kept') continue;
77
- files.push({ path, outcome: merged.outcome, ...(merged.conflicts ? { conflicts: merged.conflicts } : {}), ...(merged.reason ? { reason: merged.reason } : {}), ...(merged.keys ? { keys: merged.keys } : {}) });
78
- if (merged.outcome === 'stop') continue;
79
- if (merged.bytes === null) remove.push(path);
80
- else write.set(path, merged.bytes);
81
- }
82
- const status = files.some((f) => f.outcome === 'stop') ? 'stopped' : files.some((f) => f.outcome === 'conflict') ? 'conflict' : 'merged';
83
- return { status, files, write, remove };
84
- }
85
-
86
- async function planOf(collection, client, hit, mine) {
87
- const { name } = hit;
88
- const from = mine?.manifest.version ?? null;
89
- const out = { name, from, to: hit.version, versions: [], path: null, status: mine ? 'updated' : 'added', written: [], removed: [], files: [] };
90
- const stop = (reason) => ({ ...out, status: 'stopped', reason });
91
-
92
- const record = await client.item(name, hit.version);
93
- if (!record) return stop(`the registry listed ${hit.version} and then answered no such version`);
94
- const live = record.versions.filter((v) => !v.yankedAt && semver.valid(v.version) && semver.lte(v.version, hit.version) && (from === null || !semver.valid(from) || semver.gt(v.version, from)));
95
- out.versions = live.map((v) => v.version).sort(semver.compare);
96
- const source = record.manifest?.source;
97
- const refused = unsafe(collection, scopeOf(name), source);
98
- if (refused) return stop(refused);
99
- out.path = source;
100
- const shipped = record.files.map((f) => f.path);
101
- const outside = shipped.filter((p) => !safePath(p));
102
- if (outside.length) return stop(`its latest version lists files outside its folder: ${outside.join(', ')}`);
103
- const other = collection.items.find((i) => i.dir === source && i.manifest?.name !== name);
104
- if (other) return stop(`${other.manifest?.name ?? 'another item'} already sits at \`${source}\``);
105
- const nest = nested(collection, name, source, shipped);
106
- if (nest) return stop(nest);
107
-
108
- const abs = join(collection.root, source);
109
- if (!mine) {
110
- const taken = shipped.filter((p) => existsSync(join(abs, p)));
111
- if (taken.length) return stop(`files already sit where it would be written, at \`${source}\`: ${taken.join(', ')}`);
112
- const { files } = await client.files(name, hit.version);
113
- return { ...out, written: sorted(files.keys()), write: files, remove: [] };
114
- }
115
- if (mine.dir !== source) return stop(`its latest version moves it from \`${mine.dir}\` to \`${source}\`. Move the folder there whole, with git mv, so its notes.md and check pages go with it, then pull again`);
116
-
117
- const local = localFiles(abs);
118
- const baseRecord = typeof from === 'string' ? await client.item(name, from) : null;
119
- if (baseRecord && isDeepStrictEqual(hashesOf(local), baselineOf(baseRecord))) {
120
- const { files } = await client.files(name, hit.version);
121
- const next = new Set(shipped);
122
- const removed = sorted(baseRecord.files.map((f) => f.path).filter((p) => !next.has(p)));
123
- const changed = new Map([...files].filter(([path, bytes]) => !existsSync(join(abs, path)) || !Buffer.from(bytes).equals(readFileSync(join(abs, path)))));
124
- return { ...out, written: sorted(changed.keys()), removed, write: changed, remove: removed };
125
- }
126
- const merged = await mergeLocal(client, name, { from, to: hit.version, baseRecord, record, local });
127
- return {
128
- ...out,
129
- status: merged.status,
130
- files: merged.files,
131
- ...(merged.status === 'stopped' ? { reason: 'files changed on both sides that no line merge settles' } : {}),
132
- written: sorted(merged.write.keys()),
133
- removed: sorted(merged.remove),
134
- write: merged.write,
135
- remove: merged.remove,
136
- };
137
- }
138
-
139
- function removalOf(purge, mine) {
140
- const from = mine.manifest.version;
141
- const out = { name: purge.name, from, to: null, versions: [...purge.versions], path: mine.dir, status: 'removed', written: [], removed: [], files: [] };
142
- if (!purge.versions.includes(from)) return { ...out, status: 'stopped', reason: `the registry purged it, and never published ${from}, the collection's version, so ca-ds pull deletes nothing. Delete the folder by hand, or publish the work under another name` };
143
- const removed = sorted(localFiles(mine.abs).keys());
144
- return { ...out, removed, write: new Map(), remove: removed };
145
- }
146
-
147
- const describe = (f) =>
148
- f.outcome === 'conflict'
149
- ? `${f.path} holds ${f.conflicts} conflict${f.conflicts === 1 ? '' : 's'}`
150
- : `${f.path}: ${f.reason === 'json' ? `keys changed on both sides, ${f.keys.map((k) => k || '(the document)').join(', ')}` : f.reason === 'binary' ? 'a binary file changed on both sides' : f.reason === 'deleted' ? 'deleted on one side and changed on the other' : f.reason}`;
151
-
152
- export const command = {
153
- synopsis: 'pull',
154
- summary: "write the registry's newer versions into the collection, merging local edits",
155
- usage: ['ca-ds pull [--dry-run] [--token <token>]'],
156
- options: { ...TOKEN, 'dry-run': { type: 'boolean' } },
157
- async run({ values, positionals, io, collection, env, fetch }) {
158
- if (positionals.length) throw usageError('pull reads every authored item. Name none.');
159
- const c = collection();
160
- const namespaces = c.config?.namespaces ?? [];
161
- if (namespaces.length === 0) throw usageError("collection.json's namespaces names none, so the collection authors no item to pull.");
162
- const dryRun = values['dry-run'] === true;
163
- const client = connect(c, { values, env, fetch });
164
-
165
- const local = new Map(c.items.filter((i) => i.manifest && i.authored).map((i) => [i.manifest.name, i]));
166
- const plans = [];
167
- let current = 0;
168
- for (const hit of await client.list()) {
169
- if (!namespaces.includes(scopeOf(hit.name))) continue;
170
- const mine = local.get(hit.name) ?? null;
171
- if (mine && mine.manifest.version === hit.version) {
172
- current += 1;
173
- continue;
174
- }
175
- plans.push(await planOf(c, client, hit, mine));
176
- }
177
- for (const purge of await client.purges()) {
178
- const mine = local.get(purge.name);
179
- if (mine && namespaces.includes(scopeOf(purge.name))) plans.push(removalOf(purge, { ...mine, abs: join(c.root, mine.dir) }));
180
- }
181
- plans.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
182
-
183
- if (!dryRun) {
184
- for (const p of plans) {
185
- if (p.status === 'stopped') continue;
186
- writeFiles(join(c.root, p.path), p.write, p.remove);
187
- if (p.status === 'removed') pruneEmpty(join(c.root, p.path), c.root);
188
- }
189
- }
190
-
191
- const items = plans.map(({ write, remove, ...p }) => p);
192
- for (const p of items) {
193
- const detail = p.files.filter((f) => f.outcome === 'conflict' || f.outcome === 'stop').map(describe);
194
- const more = detail.length ? `. ${detail.join('. ')}` : '';
195
- if (p.status === 'stopped') io.log(`stopped ${p.name}: ${p.reason}${more}.`);
196
- else if (p.status === 'removed') io.log(`removed ${p.name} ${p.from}, purged ${p.path}`);
197
- else io.log(`${p.status.padEnd(8)} ${p.name} ${p.from === null ? p.to : `${p.from} to ${p.to}`} ${p.path}${more}`);
198
- }
199
- const count = (status) => items.filter((p) => p.status === status).length;
200
- const verb = dryRun ? 'would be' : 'is';
201
- io.log(`${count('updated')} updated, ${count('merged')} merged, ${count('conflict')} conflicting, ${count('added')} added, ${count('removed')} removed, ${count('stopped')} stopped, ${current} current${dryRun ? ', nothing written' : ''}`);
202
- if (count('conflict')) io.warn(`A file with conflict markers ${verb} left to resolve. ca-ds validate rejects it until the markers are gone.`);
203
- if (count('stopped')) io.warn(`A stopped item ${verb} left as it was. Settle what it names by hand, then pull again.`);
204
- if (count('removed')) io.warn("A removed item's folder keeps every file it never shipped, such as its notes.md. Delete them by hand.");
205
- if (count('added')) io.warn("An added item arrives without a notes.md, since no version ships one. Write one by hand for each item whose decisions need their reasons.");
206
- return { exit: count('stopped') || count('conflict') ? EXIT.conflict : EXIT.ok, result: { registry: client.url, dryRun, current, items } };
207
- },
208
- };
package/src/cli/remote.js DELETED
@@ -1,52 +0,0 @@
1
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { dirname, join } from 'node:path';
4
- import { isDeepStrictEqual } from 'node:util';
5
- import { authFor, credentialsFile, registryClient, registryUrl, RegistryFailure } from '../lib/registry.js';
6
- import { loadItem } from '../validate/item.js';
7
- import { baselineOf, hashesOf } from './install.js';
8
-
9
- export const TOKEN = { token: { type: 'string' } };
10
-
11
- export function connect(collection, { values, env, fetch }) {
12
- const url = registryUrl(collection.config, env);
13
- return registryClient({ url, ...authFor(url, { token: values.token ?? null, env, file: credentialsFile(env) }), fetch });
14
- }
15
-
16
- // new: the registry holds no such item. unknown: it holds the item but not the version. same and changed
17
- // compare the files with the version's.
18
- export async function heldAs(client, name, version, files) {
19
- const record = await client.item(name, version);
20
- if (!record) {
21
- const latest = await client.item(name);
22
- return { state: latest ? 'unknown' : 'new', latest: latest?.version ?? null, record: null };
23
- }
24
- const same = isDeepStrictEqual(hashesOf(files), baselineOf(record));
25
- return { state: same ? 'same' : 'changed', latest: record.latest, record };
26
- }
27
-
28
- export async function registryItems(client, names) {
29
- const base = mkdtempSync(join(tmpdir(), 'ca-ds-registry-'));
30
- const cleanup = () => rmSync(base, { recursive: true, force: true });
31
- const items = new Map();
32
- try {
33
- for (const name of names) {
34
- const record = await client.item(name);
35
- if (!record) continue;
36
- const { files } = await client.files(name, record.version);
37
- const dir = join(base, ...name.split('/'));
38
- for (const [path, bytes] of files) {
39
- if (path.startsWith('/') || path.split('/').some((seg) => seg === '..' || seg === '')) {
40
- throw new RegistryFailure(`The registry at ${client.url} lists ${name}'s file ${path}, a path outside the item's folder.`);
41
- }
42
- mkdirSync(dirname(join(dir, path)), { recursive: true });
43
- writeFileSync(join(dir, path), bytes);
44
- }
45
- items.set(name, loadItem(dir));
46
- }
47
- } catch (err) {
48
- cleanup();
49
- throw err;
50
- }
51
- return { items, cleanup };
52
- }
package/src/cli/remove.js DELETED
@@ -1,69 +0,0 @@
1
- import { CliError, EXIT, usageError } from './exit.js';
2
- import { deleteItem, dependentsOf, parseSpec, rootsOf, saveRoots, unlinkSkill } from './install.js';
3
-
4
- // Installed dependencies no remaining root reaches. The foundation counts only while another root remains.
5
- export function orphans(manifests, { config, lock, authored }) {
6
- const roots = [...Object.keys(config.items ?? {}), ...authored].filter((n) => manifests.has(n));
7
- const reached = new Set();
8
- const reach = (name) => {
9
- if (reached.has(name) || !manifests.has(name)) return;
10
- reached.add(name);
11
- for (const dep of Object.keys(manifests.get(name).dependencies ?? {})) reach(dep);
12
- };
13
- const foundation = lock.foundation ?? [];
14
- const others = roots.filter((n) => !foundation.includes(n));
15
- if (others.length) for (const name of foundation) reach(name);
16
- for (const name of roots) reach(name);
17
- return Object.keys(lock.items).filter((name) => !lock.items[name].requested && !reached.has(name)).sort();
18
- }
19
-
20
- export const command = {
21
- synopsis: 'remove <name>...',
22
- summary: 'remove items, with --prune',
23
- usage: ['ca-ds remove <scope>/<name>... [--prune]', 'ca-ds remove --prune'],
24
- options: { prune: { type: 'boolean' } },
25
- async run({ values, positionals, io, collection }) {
26
- if (!positionals.length && !values.prune) throw usageError('Name an item to remove, or pass --prune.');
27
- const c = collection();
28
- const { config, lock } = rootsOf(c);
29
- const names = positionals.map((arg) => {
30
- const { name, range } = parseSpec(arg);
31
- if (range !== null) throw usageError(`remove takes a name, with no range: ${name}.`);
32
- if (lock.items[name]) return name;
33
- const authored = c.items.some((i) => i.authored && i.manifest.name === name);
34
- throw usageError(authored ? `${name} is authored here, not installed. Delete its folder to remove it.` : `${name} is not installed.`);
35
- });
36
- const removing = new Set(names);
37
- const held = names.map((name) => [name, dependentsOf(c, name, removing)]).filter(([, by]) => by.length);
38
- if (held.length) {
39
- const lines = held.map(([name, by]) => `${name} is a dependency of ${by.join(', ')}`);
40
- throw new CliError(`${lines.join('. ')}. Remove ${held.length === 1 && held[0][1].length === 1 ? 'that' : 'those'} too, or keep it.`, EXIT.conflict);
41
- }
42
-
43
- if (values.prune) {
44
- const manifests = new Map(c.items.filter((i) => i.manifest && !removing.has(i.manifest.name)).map((i) => [i.manifest.name, i.manifest]));
45
- const remaining = { config: { ...config, items: Object.fromEntries(Object.entries(config.items ?? {}).filter(([n]) => !removing.has(n))) }, lock };
46
- const authored = c.items.filter((i) => i.authored).map((i) => i.manifest.name);
47
- for (const name of orphans(manifests, { ...remaining, authored })) removing.add(name);
48
- }
49
-
50
- const removed = [];
51
- const warnings = [];
52
- for (const name of [...removing].sort()) {
53
- const entry = lock.items[name];
54
- warnings.push(...unlinkSkill(c.root, entry.links, entry.path, name));
55
- deleteItem(c.root, entry.path);
56
- removed.push({ name, version: entry.version, path: entry.path, requested: entry.requested });
57
- delete lock.items[name];
58
- if (config.items) delete config.items[name];
59
- }
60
- if (lock.foundation) lock.foundation = lock.foundation.filter((n) => !removing.has(n));
61
- if (Object.keys(lock.items).length === 0) delete lock.foundation;
62
- saveRoots(c, { config, lock });
63
-
64
- for (const r of removed) io.log(`removed ${r.name} ${r.version} from ${r.path}${r.requested ? '' : ', a dependency'}`);
65
- io.log(`${removed.length} removed`);
66
- for (const w of warnings) io.warn(`warning: ${w.message}`);
67
- return { result: { removed, warnings } };
68
- },
69
- };