@cagov/ca-ds 0.0.0-stage → 1.0.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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +600 -2
  3. package/bin/ca-ds.js +5 -0
  4. package/package.json +62 -4
  5. package/src/cli/add.js +134 -0
  6. package/src/cli/build.js +15 -0
  7. package/src/cli/diff.js +39 -0
  8. package/src/cli/eject.js +112 -0
  9. package/src/cli/exit.js +22 -0
  10. package/src/cli/format.js +52 -0
  11. package/src/cli/init.js +148 -0
  12. package/src/cli/install.js +178 -0
  13. package/src/cli/items.js +10 -0
  14. package/src/cli/login.js +331 -0
  15. package/src/cli/main.js +108 -0
  16. package/src/cli/new.js +230 -0
  17. package/src/cli/outdated.js +74 -0
  18. package/src/cli/pack.js +75 -0
  19. package/src/cli/preview.js +31 -0
  20. package/src/cli/publish.js +295 -0
  21. package/src/cli/pull.js +208 -0
  22. package/src/cli/remote.js +52 -0
  23. package/src/cli/remove.js +69 -0
  24. package/src/cli/update.js +223 -0
  25. package/src/cli/validate.js +131 -0
  26. package/src/lib/browser.js +12 -0
  27. package/src/lib/build.js +249 -0
  28. package/src/lib/bundle.js +148 -0
  29. package/src/lib/catalog.js +44 -0
  30. package/src/lib/checks.js +31 -0
  31. package/src/lib/collection.js +65 -0
  32. package/src/lib/emblem.js +29 -0
  33. package/src/lib/fixtures.js +59 -0
  34. package/src/lib/floor.js +79 -0
  35. package/src/lib/glyph.js +148 -0
  36. package/src/lib/image.js +138 -0
  37. package/src/lib/json-text.js +213 -0
  38. package/src/lib/keys.js +322 -0
  39. package/src/lib/links.js +321 -0
  40. package/src/lib/markdown.js +408 -0
  41. package/src/lib/merge.js +93 -0
  42. package/src/lib/pack.js +30 -0
  43. package/src/lib/page-schema.js +368 -0
  44. package/src/lib/page.js +372 -0
  45. package/src/lib/patch.js +9 -0
  46. package/src/lib/regions.js +173 -0
  47. package/src/lib/registry.js +371 -0
  48. package/src/lib/release.js +119 -0
  49. package/src/lib/repoints.js +120 -0
  50. package/src/lib/resolve.js +32 -0
  51. package/src/lib/schema.js +28 -0
  52. package/src/lib/serial.js +4 -0
  53. package/src/lib/serialize.js +444 -0
  54. package/src/lib/structured.js +72 -0
  55. package/src/lib/system.js +13 -0
  56. package/src/lib/targets.js +85 -0
  57. package/src/lib/terms.js +11 -0
  58. package/src/lib/token-view.js +289 -0
  59. package/src/lib/tokens.js +247 -0
  60. package/src/lib/version.js +34 -0
  61. package/src/preview/frame.js +75 -0
  62. package/src/preview/pages.js +128 -0
  63. package/src/preview/preview.css +58 -0
  64. package/src/preview/screenshots.js +72 -0
  65. package/src/preview/server.js +378 -0
  66. package/src/preview/shell.js +153 -0
  67. package/src/schema/a11y.schema.json +56 -0
  68. package/src/schema/collection.lock.schema.json +58 -0
  69. package/src/schema/collection.schema.json +65 -0
  70. package/src/schema/composition.schema.json +98 -0
  71. package/src/schema/contract.schema.json +116 -0
  72. package/src/schema/interface.schema.json +257 -0
  73. package/src/schema/item.schema.json +362 -0
  74. package/src/schema/release.schema.json +39 -0
  75. package/src/schema/system.schema.json +75 -0
  76. package/src/schema/variants.schema.json +60 -0
  77. package/src/validate/collection.js +19 -0
  78. package/src/validate/collisions.js +124 -0
  79. package/src/validate/context.js +357 -0
  80. package/src/validate/facts.js +253 -0
  81. package/src/validate/files.js +103 -0
  82. package/src/validate/findings.js +19 -0
  83. package/src/validate/glyphs.js +126 -0
  84. package/src/validate/html.js +215 -0
  85. package/src/validate/imports.js +29 -0
  86. package/src/validate/index.js +75 -0
  87. package/src/validate/item.js +47 -0
  88. package/src/validate/links.js +113 -0
  89. package/src/validate/manifest.js +147 -0
  90. package/src/validate/media.js +65 -0
  91. package/src/validate/page.js +74 -0
  92. package/src/validate/prefixes.js +58 -0
  93. package/src/validate/relations.js +310 -0
  94. package/src/validate/release.js +109 -0
  95. package/src/validate/skill.js +122 -0
  96. package/src/validate/structured.js +335 -0
  97. package/src/validate/tasc.js +80 -0
  98. package/src/validate/template.js +129 -0
  99. package/src/validate/tokens.js +154 -0
  100. package/src/validate/zip.js +40 -0
@@ -0,0 +1,148 @@
1
+ // No disk I/O. dist/ matches ca-ds build's output byte for byte, so a build in the unzipped folder writes the same bytes.
2
+
3
+ import { sha256 } from './pack.js';
4
+ import { collisionMessage, keyGraph, setCollisions } from './keys.js';
5
+ import { structuredFiles } from './structured.js';
6
+ import { buildTokens, tokenLayers } from './tokens.js';
7
+ import { buildOutputs, copied, entryFiles, fontAssets } from './build.js';
8
+
9
+ export { entryFiles };
10
+
11
+ const encoder = new TextEncoder();
12
+ const decoder = new TextDecoder();
13
+
14
+ export const DIST = 'dist';
15
+
16
+ export const archivePath = (name, path) => `items/${name}/${path}`;
17
+
18
+ export function tokenSources(order, items) {
19
+ return tokenLayers(
20
+ order.map((name) => {
21
+ const { manifest, files } = items.get(name);
22
+ return { base: manifest.source ?? name, manifest, json: (path) => JSON.parse(decoder.decode(files.get(path))) };
23
+ }),
24
+ );
25
+ }
26
+
27
+ export function bundleCollision(order, items) {
28
+ const held = new Map();
29
+ for (const name of order) {
30
+ const { manifest, files } = items.get(name);
31
+ const interfaces = [];
32
+ const path = structuredFiles(manifest).interface;
33
+ const bytes = path ? files.get(path) : null;
34
+ if (bytes) {
35
+ try {
36
+ interfaces.push(JSON.parse(decoder.decode(bytes)));
37
+ } catch {
38
+ // The validator rejects it.
39
+ }
40
+ }
41
+ held.set(name, { manifest, interfaces });
42
+ }
43
+ return setCollisions(keyGraph((name) => held.get(name) ?? null), order)[0] ?? null;
44
+ }
45
+
46
+ // The registry keys a bundle's cache on it, and a draft pins its set in it.
47
+ export function lockFor({ order, manifests, release = null, requested = [], preset = null }) {
48
+ return {
49
+ release,
50
+ ...(preset ? { preset } : {}),
51
+ requested,
52
+ items: order.map((name) => ({ name, version: manifests.get(name).version })),
53
+ };
54
+ }
55
+
56
+ const sorted = (entries) => entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
57
+
58
+ export function bundleCollection({ registry = null, release = null, requested, manifests }) {
59
+ return {
60
+ ...(registry ? { registry } : {}),
61
+ namespaces: [],
62
+ ...(release ? { release } : {}),
63
+ ...(requested.length ? { items: Object.fromEntries(requested.map((name) => [name, `^${manifests.get(name).version}`])) } : {}),
64
+ };
65
+ }
66
+
67
+ export function bundleLock({ order, items, release = null, requested, foundation = [] }) {
68
+ const asked = new Set(requested);
69
+ return {
70
+ release,
71
+ ...(foundation.length ? { foundation } : {}),
72
+ items: Object.fromEntries(
73
+ [...order].sort().map((name) => {
74
+ const { manifest, files } = items.get(name);
75
+ const hashes = Object.fromEntries(sorted([...files].map(([path, bytes]) => [path, sha256(bytes)])));
76
+ return [name, { version: manifest.version, path: archivePath(name, '').slice(0, -1), requested: asked.has(name), files: hashes }];
77
+ }),
78
+ ),
79
+ };
80
+ }
81
+
82
+ export function bundleReadme({ registry = null, release = null, preset = null, requested, count }) {
83
+ const what = preset ? `the \`${preset}\` preset` : requested.length ? `${requested.length === 1 ? 'one item' : `${requested.length} items`} and their dependencies` : 'the foundation';
84
+ const from = registry ? `the registry at ${registry}` : 'a checkout of the system';
85
+ const pinned = release ? `, pinned to the release ${release}` : '';
86
+ const list = (rows) => rows.map((r) => `- ${r}`).join('\n');
87
+ return `${[
88
+ '# California Design System bundle',
89
+ `This folder holds ${what} from ${from}${pinned}: ${count} items, built. It is a collection, so the \`ca-ds\` toolbelt maintains it.`,
90
+ `## Use the built files\n\nThe built files sit in \`dist/\`. Earlier bundles held them at the folder's root.\n\n${list([
91
+ '`dist/ca-ds.css`: the tokens, then every item\'s CSS in load order. Link it from every page',
92
+ '`dist/ca-ds.js`: every item\'s scripts in load order. Load it as a module script',
93
+ '`dist/ca-ds.min.css` and `dist/ca-ds.min.js`: the same, minified',
94
+ '`dist/tokens.css`: the tokens alone',
95
+ '`dist/fonts/`: the fonts the CSS links',
96
+ ])}\n\nCopy \`dist/\` into your site whole, since the CSS links the fonts beside it.`,
97
+ `## Run the toolbelt\n\nRun each command in this folder, with Node 24 or later:\n\n${list([
98
+ '`npx @cagov/ca-ds preview`: serves every item\'s examples with live reload',
99
+ '`npx @cagov/ca-ds build`: rebuilds `dist/` after you edit an item',
100
+ '`npx @cagov/ca-ds validate`: checks every item against the system\'s rules',
101
+ '`npx @cagov/ca-ds outdated`: lists the items with newer versions',
102
+ '`npx @cagov/ca-ds update`: merges the newer versions into your edits',
103
+ '`npx @cagov/ca-ds add <scope>/<name>`: adds an item and its dependencies',
104
+ '`npx @cagov/ca-ds diff <scope>/<name>`: shows your edits to an item',
105
+ ])}\n\nThe commands that read the registry need a token. Run \`npx @cagov/ca-ds login\`, or set \`CA_DS_TOKEN\`.`,
106
+ `## What's inside\n\n${list([
107
+ '`collection.json`: the registry, the release, and the items asked for, each with a version range',
108
+ '`collection.lock.json`: every item at its exact version, with the hash of each file as it shipped',
109
+ '`items/<scope>/<name>/`: each item\'s files. Edit them freely. `update` merges a new version into your edits',
110
+ '`dist/`: the built files',
111
+ ])}`,
112
+ ].join('\n\n')}\n`;
113
+ }
114
+
115
+ // items maps scoped name to { manifest, files }, files a Map from item-relative path to bytes.
116
+ export async function buildBundle({ order, items, release = null, requested = [], preset = null, foundation = [], registry = null }) {
117
+ for (const name of order) if (!items.has(name)) throw new Error(`The set resolves to ${name}, and its files are missing.`);
118
+ const collision = bundleCollision(order, items);
119
+ if (collision) throw new Error(`${collisionMessage(collision)} A bundle holds one of them.`);
120
+ const manifests = new Map(order.map((name) => [name, items.get(name).manifest]));
121
+ const files = new Map();
122
+ for (const name of order) {
123
+ for (const [path, bytes] of items.get(name).files) files.set(archivePath(name, path), bytes);
124
+ }
125
+
126
+ const tokens = await buildTokens({ sources: tokenSources(order, items) });
127
+ const source = {
128
+ base: '/',
129
+ order,
130
+ manifests,
131
+ dirOf: (name) => `/${archivePath(name, '')}`.slice(0, -1),
132
+ read: (path) => files.get(path.slice(1)) ?? null,
133
+ };
134
+ const out = `/${DIST}`;
135
+ const built = await buildOutputs(source, { tokens, out, locate: copied(source, out) });
136
+ for (const [name, bytes] of built.files) files.set(`${DIST}/${name}`, bytes);
137
+ for (const { from, to } of [...fontAssets(source, out), ...built.assets]) {
138
+ const bytes = source.read(from);
139
+ if (bytes === null) throw new Error(`${from.slice(1)} is missing, and the CSS links it.`);
140
+ files.set(to.slice(1), bytes);
141
+ }
142
+
143
+ const json = (data) => encoder.encode(`${JSON.stringify(data, null, 2)}\n`);
144
+ files.set('collection.json', json(bundleCollection({ registry, release, requested, manifests })));
145
+ files.set('collection.lock.json', json(bundleLock({ order, items, release, requested, foundation })));
146
+ files.set('README.md', encoder.encode(bundleReadme({ registry, release, preset, requested, count: order.length })));
147
+ return { files, lock: lockFor({ order, manifests, release, requested, preset }) };
148
+ }
@@ -0,0 +1,44 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+
4
+ export const SKIP = new Set(['node_modules', 'build', '.git', '.temp', '.scratch', 'fixtures']);
5
+
6
+ // ======= is left out, since a markdown setext underline takes the same shape.
7
+ export const CONFLICT_MARKER = /^(?:<{7}|>{7}) /;
8
+
9
+ export function conflictLine(text) {
10
+ const at = text.split('\n').findIndex((line) => CONFLICT_MARKER.test(line));
11
+ return at === -1 ? null : at + 1;
12
+ }
13
+
14
+ function readManifest(path, rel) {
15
+ const text = readFileSync(path, 'utf8');
16
+ try {
17
+ return JSON.parse(text);
18
+ } catch (err) {
19
+ const line = conflictLine(text);
20
+ throw new Error(line === null ? `${rel} is not valid JSON: ${err.message}` : `${rel} holds a git conflict marker at line ${line}. Resolve the conflict and remove the markers.`);
21
+ }
22
+ }
23
+
24
+ export function loadItems(root) {
25
+ const found = [];
26
+ const walk = (dir) => {
27
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
28
+ if (!entry.isDirectory() || SKIP.has(entry.name)) {
29
+ if (entry.name === 'item.json') {
30
+ const rel = relative(root, dir).split(sep).join('/') || '.';
31
+ found.push({ dir: rel, manifest: readManifest(join(dir, entry.name), rel === '.' ? 'item.json' : `${rel}/item.json`) });
32
+ }
33
+ continue;
34
+ }
35
+ walk(join(dir, entry.name));
36
+ }
37
+ };
38
+ walk(root);
39
+ return found.sort((a, b) => a.dir.localeCompare(b.dir));
40
+ }
41
+
42
+ export function byName(items) {
43
+ return new Map(items.map(({ manifest }) => [manifest.name, manifest]));
44
+ }
@@ -0,0 +1,31 @@
1
+ import { parse, parseFragment } from 'parse5';
2
+ import { adapter } from 'parse5-htmlparser2-tree-adapter';
3
+ import { selectAll, is } from 'css-select';
4
+
5
+ export function parseHtml(html, { locations = false } = {}) {
6
+ const whole = /^\s*(<!doctype|<html)/i.test(html);
7
+ const options = { treeAdapter: adapter, sourceCodeLocationInfo: locations };
8
+ return whole ? parse(html, options) : parseFragment(html, options);
9
+ }
10
+
11
+ const describe = (el) => `<${el.name}${Object.entries(el.attribs ?? {}).map(([k, v]) => (v === '' ? ` ${k}` : ` ${k}="${v}"`)).join('')}>`;
12
+
13
+ export function runCheck(check, tree, write = describe) {
14
+ const found = 'none' in check ? selectAll(check.none, tree) : selectAll(check.each, tree).filter((el) => !is(el, check.has));
15
+ return found.map(write);
16
+ }
17
+
18
+ export function runRules(rules, html) {
19
+ const tree = typeof html === 'string' ? parseHtml(html) : html;
20
+ const out = { failed: [], passed: [], unchecked: [] };
21
+ for (const rule of rules) {
22
+ if (!rule.check) {
23
+ out.unchecked.push(rule);
24
+ continue;
25
+ }
26
+ const offenders = runCheck(rule.check, tree);
27
+ if (offenders.length) out.failed.push({ rule, offenders });
28
+ else out.passed.push(rule);
29
+ }
30
+ return out;
31
+ }
@@ -0,0 +1,65 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve as resolvePath } from 'node:path';
3
+ import { loadItems } from './catalog.js';
4
+ import { validateCollection, validateLock } from './schema.js';
5
+
6
+ export const COLLECTION = 'collection.json';
7
+ export const LOCK = 'collection.lock.json';
8
+
9
+ export const emptyLock = () => ({ release: null, items: {} });
10
+
11
+ export const DEFAULT_SKILLS = ['.agents/skills', '.claude/skills'];
12
+
13
+ export const skillFolders = (config) => (config?.skills?.length ? config.skills : DEFAULT_SKILLS).map((f) => f.replace(/\/+$/, ''));
14
+
15
+ export function findCollection(start = process.cwd()) {
16
+ let dir = resolvePath(start);
17
+ for (;;) {
18
+ if (existsSync(join(dir, COLLECTION))) return dir;
19
+ const up = dirname(dir);
20
+ if (up === dir) return null;
21
+ dir = up;
22
+ }
23
+ }
24
+
25
+ export function loadCollection(start = process.cwd()) {
26
+ const root = findCollection(start);
27
+ if (!root) throw new Error(`No ${COLLECTION} sits in ${resolvePath(start)} or any folder above it.`);
28
+ return openCollection(root);
29
+ }
30
+
31
+ function readRoot(root, file, check) {
32
+ const path = join(root, file);
33
+ if (!existsSync(path)) return null;
34
+ let data;
35
+ try {
36
+ data = JSON.parse(readFileSync(path, 'utf8'));
37
+ } catch (err) {
38
+ throw new Error(`${file} is not valid JSON: ${err.message}`);
39
+ }
40
+ if (!check(data)) {
41
+ const errors = check.errors.map((e) => `${e.instancePath || '(root)'} ${e.message}`).join('; ');
42
+ throw new Error(`${file} fails its schema: ${errors}.`);
43
+ }
44
+ return data;
45
+ }
46
+
47
+ export const foundationOf = (collection) => collection.system?.foundation ?? collection.lock?.foundation ?? [];
48
+
49
+ const scopeOf = (name) => (typeof name === 'string' && name.includes('/') ? name.slice(0, name.indexOf('/')) : null);
50
+
51
+ // No walk up. Without a collection.json, as in a temporary checkout, authored and installed are null.
52
+ export function openCollection(root) {
53
+ root = resolvePath(root);
54
+ const config = readRoot(root, COLLECTION, validateCollection);
55
+ const lock = readRoot(root, LOCK, validateLock) ?? emptyLock();
56
+ const systemPath = join(root, 'system.json');
57
+ const system = existsSync(systemPath) ? JSON.parse(readFileSync(systemPath, 'utf8')) : null;
58
+ const namespaces = new Set(config?.namespaces ?? []);
59
+ const items = loadItems(root).map((entry) => ({
60
+ ...entry,
61
+ authored: config ? namespaces.has(scopeOf(entry.manifest?.name)) : null,
62
+ installed: config ? Object.hasOwn(lock.items, entry.manifest?.name ?? '') : null,
63
+ }));
64
+ return { root, config, lock, system, items };
65
+ }
@@ -0,0 +1,29 @@
1
+ // A copy is found by its <title> and the master by its variant, so renaming the file moves nothing.
2
+
3
+ import { selectAll } from 'css-select';
4
+ import { systemItem } from './system.js';
5
+
6
+ export const EMBLEM = { item: systemItem('ca-logo'), variant: 'current-color', title: 'ca.gov', rule: { item: systemItem('org'), id: 'emblem-current-color' } };
7
+
8
+ const PATH_D = /<path\b[^>]*\bd="([^"]*)"/g;
9
+
10
+ export const masterPaths = (svg) => [...svg.matchAll(PATH_D)].map((m) => m[1]);
11
+
12
+ export const masterRendition = (manifest) => manifest?.media?.renditions?.find((r) => r.variant === EMBLEM.variant) ?? null;
13
+
14
+ export function emblemDiff(master, copy) {
15
+ if (master.length !== copy.length) return `It holds ${copy.length} paths where the master holds ${master.length}.`;
16
+ const at = master.findIndex((d, i) => d !== copy[i]);
17
+ return at === -1 ? null : `Its path ${at + 1} of ${copy.length} differs.`;
18
+ }
19
+
20
+ function titleOf(el) {
21
+ const title = (el.children ?? []).find((c) => c.name === 'title');
22
+ return (title?.children ?? []).map((c) => c.data ?? '').join('').trim().toLowerCase();
23
+ }
24
+
25
+ export function emblemCopies(tree) {
26
+ return selectAll('svg', tree)
27
+ .filter((el) => titleOf(el) === EMBLEM.title)
28
+ .map((element) => ({ element, paths: selectAll('path', element).map((p) => p.attribs?.d).filter((d) => d !== undefined) }));
29
+ }
@@ -0,0 +1,59 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { loadItems } from './catalog.js';
4
+
5
+ // No segment is . or .. and none holds a percent escape, so no resolved link leaves the member's folder.
6
+ export const MEDIA_LINK = /^\/media\/([A-Za-z0-9_-]+)\/((?!\.+$)[A-Za-z0-9_.-]+)$/;
7
+
8
+ export const ITEM_MEDIA_LINK = /^\/media\/([a-z0-9]+(?:-[a-z0-9]+)*)\/([a-z0-9]+(?:-[a-z0-9]+)*)\/((?!\.+$)[A-Za-z0-9_.-]+)$/;
9
+
10
+ // No scope holds a ~, so the shape never reads as a published leaf's.
11
+ export const DRAFT_MEDIA_LINK = /^\/media\/~draft\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/((?!\.+$)[A-Za-z0-9_.~%-]+)$/;
12
+
13
+ // Escapes everything outside letters, digits, and -._~, so the path breaks no attribute, srcset, or url().
14
+ export const draftMediaPath = ({ id, name }) => `/media/~draft/${id}/${encodeURIComponent(name).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
15
+
16
+ export function mediaTarget(url) {
17
+ const path = String(url).split(/[?#]/)[0];
18
+ let m = MEDIA_LINK.exec(path);
19
+ if (m) return { kind: 'fixture', dir: m[1], file: m[2] };
20
+ m = ITEM_MEDIA_LINK.exec(path);
21
+ if (m) return { kind: 'item', name: `${m[1]}/${m[2]}`, file: m[3] };
22
+ m = DRAFT_MEDIA_LINK.exec(path);
23
+ if (m) return { kind: 'draft', id: m[1], file: m[2] };
24
+ return null;
25
+ }
26
+
27
+ // A path opening an attribute value, a srcset candidate, or a url(). Group 1 is what precedes it, group 2 the path.
28
+ export const MEDIA_PATHS = /(["'(\s,=;])(\/media\/(?:~draft\/[0-9a-f-]{36}\/[A-Za-z0-9_.~%-]+|[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*\/[A-Za-z0-9_.-]+|[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+))/g;
29
+
30
+ export function mediaPaths(text) {
31
+ const out = new Map();
32
+ for (const m of String(text).matchAll(MEDIA_PATHS)) {
33
+ if (out.has(m[2])) continue;
34
+ const target = mediaTarget(m[2]);
35
+ if (target) out.set(m[2], target);
36
+ }
37
+ return [...out].map(([path, target]) => ({ path, target }));
38
+ }
39
+
40
+ export const linkedMediaItems = (text) => [...new Set(mediaPaths(text).filter((p) => p.target.kind === 'item').map((p) => p.target.name))].sort();
41
+
42
+ export function fixtureFolders(collection, items) {
43
+ const folders = new Map();
44
+ for (const name of collection?.members ?? []) {
45
+ const item = items.get(name);
46
+ if (!item?.manifest) continue;
47
+ const slug = item.dir.split('/').pop();
48
+ folders.set(slug, { name, item, files: new Set((item.manifest.files ?? []).map((f) => f.path)) });
49
+ }
50
+ return folders;
51
+ }
52
+
53
+ export function checkoutFixtures(root) {
54
+ const path = join(root, 'system.json');
55
+ const { fixtures = null } = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
56
+ if (fixtures === null) return { fixtures, folders: new Map() };
57
+ const items = new Map(loadItems(root).map((i) => [i.manifest.name, i]));
58
+ return { fixtures, folders: fixtureFolders(items.get(fixtures)?.manifest ?? null, items) };
59
+ }
@@ -0,0 +1,79 @@
1
+ // An item here is { manifest, files }, files a Map of path to bytes, as pack.js's itemFiles answers.
2
+
3
+ import semver from 'semver';
4
+ import { addedNames, describeName, nameId } from './keys.js';
5
+ import { structuredFiles } from './structured.js';
6
+
7
+ export const BUMPS = ['patch', 'minor', 'major'];
8
+
9
+ const rank = (bump) => BUMPS.indexOf(bump);
10
+
11
+ export const higher = (a, b) => (rank(a) >= rank(b) ? a : b);
12
+
13
+ const decoder = new TextDecoder();
14
+
15
+ function parsed(item, role) {
16
+ const path = structuredFiles(item.manifest ?? {})[role];
17
+ const bytes = path ? item.files.get(path) : null;
18
+ if (!bytes) return null;
19
+ try {
20
+ return JSON.parse(decoder.decode(bytes));
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+
26
+ const names = (iface) => new Map((iface ? addedNames([iface]) : []).map((n) => [nameId(n), n]));
27
+
28
+ const rules = (contract) => new Map((Array.isArray(contract?.rules) ? contract.rules : []).filter((r) => typeof r?.id === 'string').map((r) => [r.id, r]));
29
+
30
+ const variantIds = (variants) => new Set((Array.isArray(variants?.variants) ? variants.variants : []).map((v) => v?.id).filter((id) => typeof id === 'string'));
31
+
32
+ // A doc, an example, and an example's image may go in any version.
33
+ function looseFiles(manifest) {
34
+ const out = new Set();
35
+ for (const f of manifest?.files ?? []) {
36
+ if (f?.role === 'doc' || f?.role === 'reference-html') out.add(f.path);
37
+ for (const image of [f?.image?.light, f?.image?.dark]) if (typeof image === 'string') out.add(image);
38
+ }
39
+ return out;
40
+ }
41
+
42
+ export function floorOf(before, after) {
43
+ const major = [];
44
+ const minor = [];
45
+
46
+ const [was, now] = [names(parsed(before, 'interface')), names(parsed(after, 'interface'))];
47
+ for (const [id, n] of was) if (!now.has(id)) major.push(`the interface no longer adds ${describeName(n)}`);
48
+ for (const [id, n] of now) if (!was.has(id)) minor.push(`the interface adds ${describeName(n)}`);
49
+
50
+ const [held, holds] = [rules(parsed(before, 'contract')), rules(parsed(after, 'contract'))];
51
+ for (const [id, rule] of holds) {
52
+ const prior = held.get(id);
53
+ if (!prior) (rule.severity === 'must' ? major : minor).push(`the contract adds the ${rule.severity} rule ${id}`);
54
+ else if (rule.severity === 'must' && prior.severity !== 'must') major.push(`the contract raises ${id} to must`);
55
+ }
56
+ for (const [id, rule] of held) if (!holds.has(id)) minor.push(`the contract drops the ${rule.severity} rule ${id}`);
57
+
58
+ const variants = variantIds(parsed(before, 'variants'));
59
+ for (const id of variantIds(parsed(after, 'variants'))) if (!variants.has(id)) minor.push(`the variants add ${id}`);
60
+
61
+ const loose = looseFiles(before.manifest);
62
+ for (const path of before.files.keys()) {
63
+ if (!after.files.has(path) && !loose.has(path)) major.push(`the item no longer ships ${path}`);
64
+ }
65
+ for (const path of after.files.keys()) if (!before.files.has(path)) minor.push(`the item ships ${path}, a new file`);
66
+
67
+ if (major.length) return { bump: 'major', reasons: major };
68
+ if (minor.length) return { bump: 'minor', reasons: minor };
69
+ return { bump: 'patch', reasons: [] };
70
+ }
71
+
72
+ // Below 1.0.0 a caret range takes patches alone, so a major floor asks a minor there. A requested
73
+ // major stands, the one way to 1.0.0.
74
+ export function bumpFor(latest, requested, floor = 'patch') {
75
+ for (const b of [requested, floor]) if (!BUMPS.includes(b)) throw new TypeError(`A bump is one of ${BUMPS.join(', ')}, not ${b}.`);
76
+ return higher(requested, semver.major(latest) === 0 && floor === 'major' ? 'minor' : floor);
77
+ }
78
+
79
+ export const mint = (latest, requested, floor = 'patch') => semver.inc(latest, bumpFor(latest, requested, floor));
@@ -0,0 +1,148 @@
1
+ const NUMBER = /-?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi;
2
+ const TOKEN = /[MLHVQTCSZmlhvqtcsz]|-?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi;
3
+
4
+ function quadExtremes(p0, p1, p2) {
5
+ const den = p0 - 2 * p1 + p2;
6
+ if (!den) return [];
7
+ const t = (p0 - p1) / den;
8
+ return t > 0 && t < 1 ? [(1 - t) ** 2 * p0 + 2 * (1 - t) * t * p1 + t * t * p2] : [];
9
+ }
10
+
11
+ function cubicExtremes(p0, p1, p2, p3) {
12
+ const a = -p0 + 3 * p1 - 3 * p2 + p3;
13
+ const b = 2 * (p0 - 2 * p1 + p2);
14
+ const c = p1 - p0;
15
+ let ts;
16
+ if (a) {
17
+ const disc = b * b - 4 * a * c;
18
+ ts = disc < 0 ? [] : [(-b + Math.sqrt(disc)) / (2 * a), (-b - Math.sqrt(disc)) / (2 * a)];
19
+ } else {
20
+ ts = b ? [-c / b] : [];
21
+ }
22
+ return ts.filter((t) => t > 0 && t < 1).map((t) => (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * p1 + 3 * (1 - t) * t * t * p2 + t ** 3 * p3);
23
+ }
24
+
25
+ // Throws on a command it can't measure, such as an arc.
26
+ export function pathBounds(d) {
27
+ const tokens = d.match(TOKEN) ?? [];
28
+ const leftover = d.replace(TOKEN, '').replace(/[\s,]/g, '');
29
+ if (leftover) throw new Error(`the path command \`${leftover[0]}\` has no measure`);
30
+ const xs = [];
31
+ const ys = [];
32
+ let i = 0;
33
+ let cmd = '';
34
+ let prev = '';
35
+ let x = 0;
36
+ let y = 0;
37
+ let startX = 0;
38
+ let startY = 0;
39
+ let ctrlX = 0;
40
+ let ctrlY = 0;
41
+ const num = () => {
42
+ const n = Number(tokens[i++]);
43
+ if (Number.isNaN(n)) throw new Error(`the path command \`${cmd}\` is short of numbers`);
44
+ return n;
45
+ };
46
+ while (i < tokens.length) {
47
+ if (/[a-z]/i.test(tokens[i])) cmd = tokens[i++];
48
+ else if (!cmd) throw new Error('the path opens with a number');
49
+ const C = cmd.toUpperCase();
50
+ const ox = cmd === C ? 0 : x;
51
+ const oy = cmd === C ? 0 : y;
52
+ if (C === 'Z') {
53
+ x = startX;
54
+ y = startY;
55
+ prev = C;
56
+ continue;
57
+ }
58
+ if (C === 'M') {
59
+ x = ox + num();
60
+ y = oy + num();
61
+ startX = x;
62
+ startY = y;
63
+ // Further pairs after a moveto are linetos.
64
+ cmd = cmd === 'M' ? 'L' : 'l';
65
+ } else if (C === 'L') {
66
+ x = ox + num();
67
+ y = oy + num();
68
+ } else if (C === 'H') {
69
+ x = ox + num();
70
+ } else if (C === 'V') {
71
+ y = oy + num();
72
+ } else if (C === 'Q' || C === 'T') {
73
+ let qx = x;
74
+ let qy = y;
75
+ if (C === 'Q') {
76
+ qx = ox + num();
77
+ qy = oy + num();
78
+ } else if (prev === 'Q' || prev === 'T') {
79
+ qx = 2 * x - ctrlX;
80
+ qy = 2 * y - ctrlY;
81
+ }
82
+ const nx = ox + num();
83
+ const ny = oy + num();
84
+ xs.push(...quadExtremes(x, qx, nx));
85
+ ys.push(...quadExtremes(y, qy, ny));
86
+ [ctrlX, ctrlY, x, y] = [qx, qy, nx, ny];
87
+ } else if (C === 'C' || C === 'S') {
88
+ let c1x = x;
89
+ let c1y = y;
90
+ if (C === 'C') {
91
+ c1x = ox + num();
92
+ c1y = oy + num();
93
+ } else if (prev === 'C' || prev === 'S') {
94
+ c1x = 2 * x - ctrlX;
95
+ c1y = 2 * y - ctrlY;
96
+ }
97
+ const c2x = ox + num();
98
+ const c2y = oy + num();
99
+ const nx = ox + num();
100
+ const ny = oy + num();
101
+ xs.push(...cubicExtremes(x, c1x, c2x, nx));
102
+ ys.push(...cubicExtremes(y, c1y, c2y, ny));
103
+ [ctrlX, ctrlY, x, y] = [c2x, c2y, nx, ny];
104
+ }
105
+ xs.push(x);
106
+ ys.push(y);
107
+ prev = C === 'M' ? 'M' : C;
108
+ }
109
+ if (!xs.length) throw new Error('the path draws nothing');
110
+ return { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys) };
111
+ }
112
+
113
+ export function svgOfDataUri(uri) {
114
+ const m = /^data:image\/svg\+xml(;[^,]*)?,([\s\S]*)$/i.exec(uri.trim());
115
+ if (!m) return null;
116
+ if (/;base64/i.test(m[1] ?? '')) return Buffer.from(m[2], 'base64').toString('utf8');
117
+ try {
118
+ return decodeURIComponent(m[2]);
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ // The narrower horizontal margin over the viewBox width, floored so a trim never crops ink.
125
+ export function glyphBearing(svg) {
126
+ const viewBox = /<svg\b[^>]*\bviewBox\s*=\s*["']([^"']*)["']/i.exec(svg);
127
+ if (!viewBox) return { error: 'the SVG has no viewBox' };
128
+ const box = viewBox[1].match(NUMBER)?.map(Number) ?? [];
129
+ if (box.length !== 4 || !(box[2] > 0)) return { error: 'the viewBox is malformed' };
130
+ const [vx, , width] = box;
131
+ const shape = /<(circle|ellipse|line|polygon|polyline|rect|use|image|text)\b/i.exec(svg);
132
+ if (shape) return { error: `the SVG draws a \`<${shape[1]}>\`, and only \`<path>\` data has a measure` };
133
+ const ds = [...svg.matchAll(/<path\b[^>]*\bd\s*=\s*["']([^"']*)["']/gi)].map((m) => m[1]);
134
+ if (!ds.length) return { error: 'the SVG holds no path' };
135
+ let minX = Infinity;
136
+ let maxX = -Infinity;
137
+ try {
138
+ for (const d of ds) {
139
+ const b = pathBounds(d);
140
+ minX = Math.min(minX, b.minX);
141
+ maxX = Math.max(maxX, b.maxX);
142
+ }
143
+ } catch (err) {
144
+ return { error: err.message };
145
+ }
146
+ const side = Math.min(minX - vx, vx + width - maxX);
147
+ return { bearing: Math.max(0, Math.floor((side / width) * 1000 + 1e-9) / 1000) };
148
+ }