@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,253 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { extname, join } from 'node:path';
3
+ import { transform, transformStyleAttribute } from 'lightningcss';
4
+ import { parseFragment } from 'parse5';
5
+ import { build, transform as transformJs } from 'esbuild';
6
+ import { lineAt } from './findings.js';
7
+ import { declaredFiles } from './item.js';
8
+
9
+ export function* components(selector) {
10
+ for (const c of selector) {
11
+ yield c;
12
+ if (Array.isArray(c.selectors)) for (const s of c.selectors) yield* components(s);
13
+ if (c.type === 'pseudo-element' && Array.isArray(c.selector)) yield* components(c.selector);
14
+ }
15
+ }
16
+
17
+ export function cssFacts(text, { filename = 'style.css', offsetLine = 0, attribute = false } = {}) {
18
+ // Comments blanked, newlines kept, so a name a comment mentions never takes the code's line.
19
+ const code = text.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' '));
20
+ const facts = { rules: [], varRefs: [], customDecls: [], classes: new Set(), elements: new Set(), errors: [], warnings: [], code, offsetLine };
21
+ const lineOf = (...needles) => {
22
+ for (const n of needles) {
23
+ const i = code.indexOf(n);
24
+ if (i >= 0) return lineAt(code, i) + offsetLine;
25
+ }
26
+ return null;
27
+ };
28
+ const visitor = {
29
+ Rule: {
30
+ style(rule) {
31
+ const { selectors, loc, declarations } = rule.value;
32
+ // LightningCSS reports 0-based lines.
33
+ const line = loc.line + 1 + offsetLine;
34
+ const important = (declarations?.importantDeclarations ?? []).map((d) =>
35
+ d.property === 'custom' ? d.value.name : d.property,
36
+ );
37
+ facts.rules.push({ selectors, line, prelude: preludeAt(text, loc), important });
38
+ for (const s of selectors) {
39
+ for (const c of components(s)) {
40
+ if (c.type === 'class') facts.classes.add(c.name);
41
+ if (c.type === 'type' && c.name.includes('-')) facts.elements.add(c.name);
42
+ }
43
+ }
44
+ },
45
+ },
46
+ Variable(v) {
47
+ facts.varRefs.push({ name: v.name.ident, fallback: Boolean(v.fallback), line: lineOf(`var(${v.name.ident}`, v.name.ident) });
48
+ },
49
+ Declaration: {
50
+ // LightningCSS routes every property it doesn't model here, so only a dashed name is custom.
51
+ custom(d) {
52
+ if (d.name.startsWith('--')) facts.customDecls.push({ name: d.name, line: lineOf(`${d.name}:`, d.name) });
53
+ },
54
+ },
55
+ };
56
+ try {
57
+ const options = { filename, code: Buffer.from(text), errorRecovery: true, visitor };
58
+ const result = attribute ? transformStyleAttribute(options) : transform(options);
59
+ for (const w of result.warnings ?? []) facts.warnings.push({ message: w.message, line: w.loc ? w.loc.line + offsetLine : null });
60
+ } catch (err) {
61
+ facts.errors.push({ message: err.message, line: err.loc ? err.loc.line + offsetLine : null });
62
+ }
63
+ return facts;
64
+ }
65
+
66
+ const CUSTOM_VALUE = /(--[A-Za-z0-9_-]+)\s*:|var\(\s*(--[A-Za-z0-9_-]+)\s*(,)?/g;
67
+
68
+ // Each declaration's value and each var() fallback, untrimmed, in source order. Takes cssFacts' blanked code.
69
+ export function customValues(css) {
70
+ const { code, offsetLine = 0 } = css;
71
+ const out = [];
72
+ for (const m of code.matchAll(CUSTOM_VALUE)) {
73
+ const fallback = !m[1];
74
+ if (fallback && !m[3]) continue;
75
+ // A declaration's name opens its block or follows a declaration's end.
76
+ if (!fallback) {
77
+ let i = m.index - 1;
78
+ while (i >= 0 && /\s/.test(code[i])) i--;
79
+ if (i >= 0 && !'{;}'.includes(code[i])) continue;
80
+ }
81
+ const start = m.index + m[0].length;
82
+ let depth = 0;
83
+ let end = start;
84
+ for (; end < code.length; end++) {
85
+ const c = code[end];
86
+ if (c === '(') depth++;
87
+ else if (c === ')' && depth === 0 && fallback) break;
88
+ else if (c === ')') depth--;
89
+ else if ((c === ';' || c === '}') && depth === 0 && !fallback) break;
90
+ }
91
+ const value = fallback ? code.slice(start, end) : code.slice(start, end).replace(/\s*!important\s*$/i, '');
92
+ out.push({ name: m[1] ?? m[2], value, line: lineAt(code, m.index) + offsetLine, fallback });
93
+ }
94
+ return out;
95
+ }
96
+
97
+ const propertyOf = (d) => (d.property === 'custom' ? d.value.name : d.property === 'unparsed' ? d.value.propertyId.property : d.property);
98
+
99
+ // Nesting resolved, & as :is() of the parent. An at-rule's condition drops, since a rule under one still meets the rules outside it.
100
+ export function styleRules(text) {
101
+ const out = [];
102
+ const resolve = (selector, parent) =>
103
+ parent ? selector.map((c) => (c.type === 'nesting' ? { type: 'pseudo-class', kind: 'is', selectors: parent } : c)) : selector.filter((c) => c.type !== 'nesting');
104
+ const record = (selectors, declarations, loc, prelude) => {
105
+ const properties = [...(declarations?.declarations ?? []), ...(declarations?.importantDeclarations ?? [])].map(propertyOf);
106
+ out.push({ selectors, properties, line: loc.line + 1, prelude });
107
+ };
108
+ const walk = (rules, parent) => {
109
+ for (const rule of rules ?? []) {
110
+ if (rule.type === 'style') {
111
+ const selectors = rule.value.selectors.map((s) => resolve(s, parent?.selectors));
112
+ const prelude = preludeAt(text, rule.value.loc);
113
+ record(selectors, rule.value.declarations, rule.value.loc, prelude);
114
+ walk(rule.value.rules, { selectors, prelude });
115
+ } else if (rule.type === 'nested-declarations') {
116
+ if (parent) record(parent.selectors, rule.value.declarations, rule.value.loc, parent.prelude);
117
+ } else if (Array.isArray(rule.value?.rules)) {
118
+ walk(rule.value.rules, parent);
119
+ }
120
+ }
121
+ };
122
+ try {
123
+ transform({ filename: 'style.css', code: Buffer.from(text), errorRecovery: true, visitor: { StyleSheet: (sheet) => walk(sheet.rules, null) } });
124
+ } catch {
125
+ // cssFacts reports it.
126
+ }
127
+ return out;
128
+ }
129
+
130
+ function preludeAt(text, loc) {
131
+ const lines = text.split('\n');
132
+ let i = 0;
133
+ for (let k = 0; k < loc.line; k++) i += lines[k].length + 1;
134
+ i += loc.column - 1;
135
+ const end = text.indexOf('{', i);
136
+ return text.slice(i, end < 0 ? undefined : end).replace(/\s+/g, ' ').trim();
137
+ }
138
+
139
+ export function htmlFacts(text) {
140
+ const errors = [];
141
+ const tree = parseFragment(text, {
142
+ sourceCodeLocationInfo: true,
143
+ onParseError: (e) => errors.push({ code: e.code, line: e.startLine }),
144
+ });
145
+ errors.push(...balance(text, tree));
146
+ const styles = [];
147
+ for (const { node } of walkHtml(tree)) {
148
+ const line = node.sourceCodeLocation?.startLine ?? null;
149
+ if (node.nodeName === 'style') {
150
+ const css = node.childNodes.map((n) => n.value ?? '').join('');
151
+ const start = node.childNodes[0]?.sourceCodeLocation?.startLine ?? line;
152
+ styles.push({ ...cssFacts(css, { offsetLine: (start ?? 1) - 1 }), attribute: false });
153
+ }
154
+ const style = node.attrs?.find((a) => a.name === 'style');
155
+ if (style) {
156
+ const facts = cssFacts(style.value, { attribute: true, offsetLine: (line ?? 1) - 1 });
157
+ for (const r of facts.varRefs) r.line = line;
158
+ for (const d of facts.customDecls) d.line = line;
159
+ styles.push({ ...facts, attribute: true });
160
+ }
161
+ }
162
+ return { tree, errors, styles };
163
+ }
164
+
165
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
166
+ const OPTIONAL_END = new Set(['html', 'head', 'body', 'p', 'li', 'dt', 'dd', 'option', 'optgroup', 'rb', 'rp', 'rt', 'rtc', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'colgroup', 'caption']);
167
+
168
+ // parse5 repairs unbalanced tags silently, so this finds stray end tags and unclosed elements.
169
+ function balance(text, tree) {
170
+ const errors = [];
171
+ const ends = new Set();
172
+ let blank = text;
173
+ const blankRange = (from, to) => {
174
+ blank = blank.slice(0, from) + blank.slice(from, to).replace(/[^\n]/g, ' ') + blank.slice(to);
175
+ };
176
+ for (const { node } of walkHtml(tree)) {
177
+ const loc = node.sourceCodeLocation;
178
+ if (!loc) continue;
179
+ if (node.nodeName === '#comment') blankRange(loc.startOffset, loc.endOffset);
180
+ if (!node.tagName) continue;
181
+ if (loc.endTag) ends.add(loc.endTag.startOffset);
182
+ if (['script', 'style'].includes(node.tagName) && loc.startTag && loc.endTag) blankRange(loc.startTag.endOffset, loc.endTag.startOffset);
183
+ // SVG and MathML children may self-close.
184
+ const foreign = node.namespaceURI !== 'http://www.w3.org/1999/xhtml';
185
+ if (loc.startTag && !loc.endTag && !foreign && !VOID.has(node.tagName) && !OPTIONAL_END.has(node.tagName)) {
186
+ errors.push({ code: `unclosed <${node.tagName}>`, line: loc.startLine });
187
+ }
188
+ }
189
+ for (const m of blank.matchAll(/<\/([A-Za-z][\w-]*)\s*>/g)) {
190
+ if (!ends.has(m.index)) errors.push({ code: `stray </${m[1].toLowerCase()}>`, line: lineAt(text, m.index) });
191
+ }
192
+ return errors;
193
+ }
194
+
195
+ // Enters <template> content. ancestors holds elements, nearest last.
196
+ export function* walkHtml(node, ancestors = []) {
197
+ const children = node.content ? [...node.childNodes, ...node.content.childNodes] : node.childNodes ?? [];
198
+ for (const child of children) {
199
+ yield { node: child, ancestors };
200
+ if (child.childNodes || child.content) yield* walkHtml(child, child.tagName ? [...ancestors, child] : ancestors);
201
+ }
202
+ }
203
+
204
+ export async function jsFacts(abs, text) {
205
+ const imports = [];
206
+ let error = null;
207
+ let code = text;
208
+ try {
209
+ ({ code } = await transformJs(text, { loader: 'js', legalComments: 'none', format: 'esm' }));
210
+ await build({
211
+ entryPoints: [abs],
212
+ bundle: true,
213
+ write: false,
214
+ format: 'esm',
215
+ platform: 'browser',
216
+ logLevel: 'silent',
217
+ plugins: [
218
+ {
219
+ name: 'record-imports',
220
+ setup(b) {
221
+ b.onResolve({ filter: /.*/ }, (args) => {
222
+ if (args.kind === 'entry-point') return undefined;
223
+ imports.push({ specifier: args.path, kind: args.kind, line: lineAt(text, text.indexOf(args.path)) });
224
+ return { path: args.path, external: true };
225
+ });
226
+ },
227
+ },
228
+ ],
229
+ });
230
+ } catch (err) {
231
+ const first = err.errors?.[0];
232
+ error = { message: first?.text ?? err.message, line: first?.location?.line ?? null };
233
+ }
234
+ return { imports, code, error };
235
+ }
236
+
237
+ export async function itemFacts(item) {
238
+ const css = new Map();
239
+ const html = new Map();
240
+ const js = new Map();
241
+ for (const path of item.checks ?? []) {
242
+ if (extname(path).toLowerCase() === '.html') html.set(path, htmlFacts(readFileSync(join(item.dir, path), 'utf8')));
243
+ }
244
+ for (const { path } of declaredFiles(item.manifest)) {
245
+ if (!item.present.has(path)) continue;
246
+ const abs = join(item.dir, path);
247
+ const ext = extname(path).toLowerCase();
248
+ if (ext === '.css') css.set(path, cssFacts(readFileSync(abs, 'utf8'), { filename: path }));
249
+ if (ext === '.html') html.set(path, htmlFacts(readFileSync(abs, 'utf8')));
250
+ if (ext === '.js') js.set(path, await jsFacts(abs, readFileSync(abs, 'utf8')));
251
+ }
252
+ return { css, html, js };
253
+ }
@@ -0,0 +1,103 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { extname, join } from 'node:path';
3
+ import { declaredFiles, conflictLine } from './item.js';
4
+ import { roundTrip } from '../lib/markdown.js';
5
+ import { SITE_NAMESPACE, isSystemItem } from '../lib/system.js';
6
+
7
+ export const check = 'files';
8
+
9
+ const IMAGES = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.avif', '.ico'];
10
+ const FONTS = ['.woff', '.woff2', '.ttf', '.otf'];
11
+ export const ALLOWED = new Set(['.md', '.html', '.css', '.js', '.json', '.txt', ...IMAGES, ...FONTS]);
12
+
13
+ export const NAMED = new Map([
14
+ ['.jsx', 'React'],
15
+ ['.tsx', 'React with TypeScript'],
16
+ ['.vue', 'Vue'],
17
+ ['.svelte', 'Svelte'],
18
+ ['.razor', 'Blazor'],
19
+ ['.cshtml', 'Razor'],
20
+ ['.php', 'PHP'],
21
+ ]);
22
+
23
+ const TEXT = new Set(['.md', '.html', '.css', '.js', '.json', '.txt', '.svg']);
24
+
25
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
26
+ const isText = (bytes) => {
27
+ if (bytes.includes(0)) return false;
28
+ try {
29
+ utf8.decode(bytes);
30
+ return true;
31
+ } catch {
32
+ return false;
33
+ }
34
+ };
35
+
36
+ const QUOTE = 160;
37
+ const quote = (line) => {
38
+ if (line === null) return 'nothing';
39
+ if (line === '') return 'a blank line';
40
+ return JSON.stringify(line.length > QUOTE ? `${line.slice(0, QUOTE)}…` : line);
41
+ };
42
+
43
+ export function markdownFinding(path, text) {
44
+ const { difference, error } = roundTrip(text);
45
+ if (error) return { message: `\`${path}\` doesn't parse as the docs' markdown: ${error}`, line: null };
46
+ if (!difference) return null;
47
+ const { line, expected, actual } = difference;
48
+ return {
49
+ message: `\`${path}\` doesn't round-trip through the markdown serializer. Line ${line} holds ${quote(expected)}, where the serializer writes ${quote(actual)}. \`ca-ds format\` rewrites it.`,
50
+ line,
51
+ };
52
+ }
53
+
54
+ export async function run(item, ctx, { reject, warn }) {
55
+ const declared = new Set(declaredFiles(item.manifest).map((f) => f.path));
56
+
57
+ const scripts = new Set(item.manifest.kind === 'skill' ? declaredFiles(item.manifest).filter((f) => f.role === 'script').map((f) => f.path) : []);
58
+ for (const path of new Set([...declared, ...item.present])) {
59
+ const ext = extname(path).toLowerCase();
60
+ if (scripts.has(path)) {
61
+ if (item.present.has(path) && !isText(readFileSync(join(item.dir, path)))) reject('extension', `\`${path}\` is a script that isn't UTF-8 text, and a skill's script is a text file.`, { file: path });
62
+ } else if (NAMED.has(ext)) {
63
+ reject('extension', `\`${path}\` is a ${NAMED.get(ext)} source file. An item ships the reference implementation as HTML, CSS, and JS.`, { file: path });
64
+ } else if (!ALLOWED.has(ext)) {
65
+ reject('extension', `\`${path}\` has the extension \`${ext || '(none)'}\`, which an item may not ship.`, { file: path });
66
+ }
67
+ }
68
+
69
+ for (const path of item.present) {
70
+ if (!declared.has(path)) warn('undeclared', `\`${path}\` is in the folder and not in the manifest's \`files\`.`, { file: path });
71
+ }
72
+
73
+ for (const path of [...item.present, ...item.checks].sort()) {
74
+ if (!TEXT.has(extname(path).toLowerCase()) && !scripts.has(path)) continue;
75
+ const line = conflictLine(readFileSync(join(item.dir, path), 'utf8'));
76
+ if (line !== null) reject('conflict-markers', `\`${path}\` holds a git conflict marker at line ${line}. Resolve the conflict and remove the markers.`, { file: path, line });
77
+ }
78
+
79
+ for (const path of declared) {
80
+ if (!item.present.has(path) || extname(path).toLowerCase() !== '.json') continue;
81
+ try {
82
+ JSON.parse(readFileSync(join(item.dir, path), 'utf8'));
83
+ } catch (err) {
84
+ reject('parse', `\`${path}\` is not valid JSON: ${err.message}`, { file: path });
85
+ }
86
+ }
87
+
88
+ const name = item.manifest.name;
89
+ const record = isSystemItem(name) || (typeof name === 'string' && name.startsWith(`${SITE_NAMESPACE}/`)) ? reject : warn;
90
+ for (const path of [...declared].sort()) {
91
+ if (!item.present.has(path) || extname(path).toLowerCase() !== '.md') continue;
92
+ const text = readFileSync(join(item.dir, path), 'utf8');
93
+ if (conflictLine(text) !== null) continue;
94
+ const finding = markdownFinding(path, text);
95
+ if (finding) record('markdown', finding.message, { file: path, line: finding.line });
96
+ }
97
+
98
+ const facts = await ctx.facts(item);
99
+ for (const [path, css] of facts.css) {
100
+ for (const e of css.errors) reject('parse', `The CSS fails to parse: ${e.message}`, { file: path, line: e.line });
101
+ for (const w of css.warnings) warn('css', w.message, { file: path, line: w.line });
102
+ }
103
+ }
@@ -0,0 +1,19 @@
1
+ // needs names an item the state lacks, which an online run fetches from the registry.
2
+ export function recorder(findings, check) {
3
+ const add = (severity) => (rule, message, { file, line, needs } = {}) =>
4
+ findings.push({ severity, check, rule, file: file ?? null, line: line ?? null, message, ...(needs ? { needs } : {}) });
5
+ return { reject: add('reject'), warn: add('warn') };
6
+ }
7
+
8
+ // 1-based.
9
+ export function lineAt(text, i) {
10
+ if (i < 0) return null;
11
+ let line = 1;
12
+ for (let k = 0; k < i; k++) if (text.charCodeAt(k) === 10) line++;
13
+ return line;
14
+ }
15
+
16
+ // A message names an attribute, never its value.
17
+ export function elideValues(text) {
18
+ return text.replace(/(=\s*)("[^"]*"|'[^']*'|[^\]\s>]+)/g, '$1…');
19
+ }
@@ -0,0 +1,126 @@
1
+ import { lineAt } from './findings.js';
2
+ import { svgOfDataUri, glyphBearing } from '../lib/glyph.js';
3
+
4
+ export const check = 'glyphs';
5
+
6
+ const REGISTRY = /^--ca-icon-([a-z0-9_]+)$/;
7
+ const BEARING = /^--ca-icon-([a-z0-9_]+)-bearing$/;
8
+ const URL = /^url\(\s*(["']?)([\s\S]*)\1\s*\)$/i;
9
+ const REGISTRY_VAR = /^var\(\s*--ca-icon-([a-z0-9_]+)\s*\)$/;
10
+ const BEARING_VAR = /^var\(\s*--ca-icon-([a-z0-9_]+)-bearing\s*\)$/;
11
+ const NAME_RULE = /\bca-icon\[\s*name\b/;
12
+
13
+ function* blocks(code) {
14
+ for (const m of code.matchAll(/([^{}]*)\{([^{}]*)\}/g)) {
15
+ const prelude = m[1].slice(m[1].lastIndexOf(';') + 1).trim();
16
+ const start = m.index + m[1].length + 1;
17
+ const decls = new Map();
18
+ for (const { text, at } of split(m[2])) {
19
+ const colon = text.indexOf(':');
20
+ if (colon < 0) continue;
21
+ const name = text.slice(0, colon).trim();
22
+ if (name) decls.set(name, { value: text.slice(colon + 1).trim(), at: start + at });
23
+ }
24
+ yield { prelude, decls };
25
+ }
26
+ }
27
+
28
+ function split(body) {
29
+ const parts = [];
30
+ let depth = 0;
31
+ let quote = null;
32
+ let from = 0;
33
+ for (let i = 0; i <= body.length; i++) {
34
+ const c = body[i];
35
+ if (quote) {
36
+ if (c === '\\') i++;
37
+ else if (c === quote) quote = null;
38
+ } else if (c === '"' || c === "'") quote = c;
39
+ else if (c === '(') depth++;
40
+ else if (c === ')') depth--;
41
+ else if ((c === ';' && depth === 0) || i === body.length) {
42
+ const text = body.slice(from, i);
43
+ parts.push({ text, at: from + text.search(/\S|$/) });
44
+ from = i + 1;
45
+ }
46
+ }
47
+ return parts;
48
+ }
49
+
50
+ function measure(value) {
51
+ const url = URL.exec(value);
52
+ const svg = url && svgOfDataUri(url[2]);
53
+ return svg === null || svg === undefined ? null : glyphBearing(svg);
54
+ }
55
+
56
+ const places = (n) => n.toFixed(3);
57
+
58
+ export async function run(item, ctx, { reject, warn }) {
59
+ if (!item.manifest) return;
60
+ const facts = await ctx.facts(item);
61
+ const sheets = [...facts.css].map(([path, css]) => ({ path, css }));
62
+ for (const [path, html] of facts.html) {
63
+ // A style attribute's single-use glyph is exempt.
64
+ for (const css of html.styles) if (!css.attribute) sheets.push({ path, css });
65
+ }
66
+
67
+ for (const { path, css } of sheets) {
68
+ const where = (at) => ({ file: path, line: lineAt(css.code, at) + css.offsetLine });
69
+ const glyphs = new Map();
70
+ const bearings = new Map();
71
+
72
+ const hold = (glyph, measured, declared, name) => {
73
+ if (!/^\d*\.?\d+$/.test(declared.value)) {
74
+ reject('bearing-value', `\`${name}\` declares \`${declared.value}\`, and a bearing is a plain number. \`${glyph}\` measures ${places(measured)}.`, where(declared.at));
75
+ } else if (Math.round(Number(declared.value) * 1000) !== Math.round(measured * 1000)) {
76
+ reject('bearing-value', `\`${name}\` declares ${declared.value}, and \`${glyph}\`'s path data measures ${places(measured)}.`, where(declared.at));
77
+ }
78
+ };
79
+
80
+ for (const { prelude, decls } of blocks(css.code)) {
81
+ for (const [name, decl] of decls) {
82
+ const id = REGISTRY.exec(name)?.[1];
83
+ const bearingId = BEARING.exec(name)?.[1];
84
+ if (bearingId) bearings.set(bearingId, decl);
85
+ else if (id) {
86
+ const measured = measure(decl.value);
87
+ if (measured) glyphs.set(id, { ...measured, at: decl.at });
88
+ }
89
+ }
90
+
91
+ const icon = decls.get('--ca-icon');
92
+ const bearing = decls.get('--ca-icon-bearing');
93
+ if (!icon) continue;
94
+ const measured = measure(icon.value);
95
+ if (measured?.error) {
96
+ warn('unmeasured', `The glyph \`--ca-icon\` sets goes unchecked, since ${measured.error}.`, where(icon.at));
97
+ } else if (measured && !bearing) {
98
+ reject('missing-bearing', `A rule sets \`--ca-icon\` to a glyph and no \`--ca-icon-bearing\` beside it. The glyph's side bearing measures ${places(measured.bearing)}.`, where(icon.at));
99
+ } else if (measured) {
100
+ hold('--ca-icon', measured.bearing, bearing, '--ca-icon-bearing');
101
+ }
102
+
103
+ const from = REGISTRY_VAR.exec(icon.value)?.[1];
104
+ if (!from) continue;
105
+ const to = bearing && BEARING_VAR.exec(bearing.value)?.[1];
106
+ if (bearing && to && to !== from) {
107
+ reject('bearing-pair', `A rule sets \`--ca-icon\` from \`--ca-icon-${from}\` and \`--ca-icon-bearing\` from \`--ca-icon-${to}-bearing\`, another glyph's.`, where(bearing.at));
108
+ } else if (bearing && !to) {
109
+ reject('bearing-pair', `A rule sets \`--ca-icon\` from \`--ca-icon-${from}\`, and its \`--ca-icon-bearing\` takes \`var(--ca-icon-${from}-bearing)\`.`, where(bearing.at));
110
+ } else if (!bearing && NAME_RULE.test(prelude)) {
111
+ reject('missing-bearing', `A \`ca-icon[name]\` rule sets \`--ca-icon\` from \`--ca-icon-${from}\` and no \`--ca-icon-bearing\`. It takes \`var(--ca-icon-${from}-bearing)\`.`, where(icon.at));
112
+ }
113
+ }
114
+
115
+ for (const [id, glyph] of glyphs) {
116
+ const name = `--ca-icon-${id}`;
117
+ if (glyph.error) {
118
+ warn('unmeasured', `The glyph \`${name}\` goes unchecked, since ${glyph.error}.`, where(glyph.at));
119
+ } else if (!bearings.has(id)) {
120
+ reject('missing-bearing', `The glyph \`${name}\` has no \`${name}-bearing\` in its stylesheet. Its side bearing measures ${places(glyph.bearing)}.`, where(glyph.at));
121
+ } else {
122
+ hold(name, glyph.bearing, bearings.get(id), `${name}-bearing`);
123
+ }
124
+ }
125
+ }
126
+ }