@domandigital/craft 0.19.2 → 0.20.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@domandigital/craft",
3
- "version": "0.19.2",
3
+ "version": "0.20.0",
4
4
  "private": false,
5
5
  "description": "The Doman Digital house craft standard as numbers: OKLCh colour ramps that snap to existing anchors, derived semantic tokens with measured WCAG and APCA contrast, one shared motion vocabulary for CSS and JS, and a base stylesheet. Zero dependencies.",
6
6
  "license": "Apache-2.0",
@@ -1,249 +0,0 @@
1
- import {
2
- SOURCE_FILE,
3
- readPaths
4
- } from "./chunk-D2PEKYKH.js";
5
- import {
6
- toJson
7
- } from "./chunk-QIEDBL4J.js";
8
- import "./chunk-WK2WMWTH.js";
9
- import "./chunk-CZ7KT452.js";
10
- import "./chunk-QYBAVU3P.js";
11
-
12
- // src/phone/cli.ts
13
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "fs";
14
- import { join, resolve } from "path";
15
-
16
- // src/phone/judge.ts
17
- var EMPTY_BASELINE = { static: [], measured: [] };
18
- var MEDIA = /@(?:custom-)?media\b([^{;]*)/g;
19
- var CAPS_WIDTH = /\bmax-(?:device-)?width\s*:|\bwidth\s*<|>=?\s*(?:device-)?width\b/i;
20
- var VARIANT = /(?<![\w@-])max-(\[[^\]\s]+\]|[a-z0-9]+):/g;
21
- var NOT_VARIANTS = /* @__PURE__ */ new Set(["width", "height", "lines", "resolution", "zoom", "inline-size", "block-size"]);
22
- var OK = /mobile-first-ok\b:?(.*)/;
23
- function reasonOf(line) {
24
- const m = line?.match(OK);
25
- return m ? m[1].replace(/\*\/|-->|[{}]/g, "").trim() : null;
26
- }
27
- function scanPhoneFirst(files, exceptions = []) {
28
- const excusedFiles = new Set(exceptions.filter((e) => e.reason?.trim()).map((e) => e.file));
29
- const findings = [];
30
- let excused = 0;
31
- for (const { path, text } of files) {
32
- if (excusedFiles.has(path)) continue;
33
- const lines = text.split("\n");
34
- const lineOf = (index) => text.slice(0, index).split("\n").length;
35
- const found = [];
36
- for (const m of text.matchAll(MEDIA)) {
37
- if (CAPS_WIDTH.test(m[1])) found.push({ line: lineOf(m.index), what: `${m[0].slice(0, m[0].length - m[1].length)}${m[1].replace(/\s+/g, " ").trimEnd()}` });
38
- }
39
- for (const m of text.matchAll(VARIANT)) {
40
- if (!NOT_VARIANTS.has(m[1])) found.push({ line: lineOf(m.index), what: m[0] });
41
- }
42
- for (const { line, what } of found.sort((a, b) => a.line - b.line)) {
43
- const here = reasonOf(lines[line - 1]);
44
- const above = reasonOf(lines[line - 2]);
45
- if (here || above) {
46
- excused++;
47
- continue;
48
- }
49
- findings.push({ file: path, line, what: here === "" || above === "" ? `${what} (mobile-first-ok with no reason)` : what });
50
- }
51
- }
52
- return { findings, excused };
53
- }
54
- function checkExceptions(exceptions, exists) {
55
- const problems = [];
56
- exceptions.forEach((e, i) => {
57
- const at = `exceptions[${i}]`;
58
- const x = e;
59
- if (typeof x?.file !== "string" || !x.file.trim()) problems.push(`${at}: names no file`);
60
- else if (typeof x.reason !== "string" || !x.reason.trim()) problems.push(`${at} (${x.file}): no reason. Say why this file needs a max-width query, or remove the exception.`);
61
- else if (!exists(x.file)) problems.push(`${at}: ${x.file} is not there. Remove the exception.`);
62
- });
63
- return problems;
64
- }
65
- var normaliseElement = (element) => element.replace(/\d+/g, "#");
66
- var tally = (items, key) => {
67
- const m = /* @__PURE__ */ new Map();
68
- for (const item of items) {
69
- const k = key(item);
70
- const had = m.get(k);
71
- if (had) had.count++;
72
- else m.set(k, { item, count: 1 });
73
- }
74
- return m;
75
- };
76
- function judgeStatic(findings, baseline) {
77
- const byFile = tally(findings, (f) => f.file);
78
- const allowed = new Map(baseline.static.map((b) => [b.file, b.count]));
79
- const fresh = [];
80
- const stale = [];
81
- let known = 0;
82
- for (const [file, { count }] of byFile) {
83
- const allow = allowed.get(file) ?? 0;
84
- known += Math.min(count, allow);
85
- if (count > allow) {
86
- const here = findings.filter((f) => f.file === file);
87
- const lead = allow ? `${file}: ${count} desktop-first rules, the baseline allows ${allow}. One of these is new:` : `${file}:`;
88
- fresh.push(`${lead}
89
- ${here.map((f) => ` line ${f.line}: ${f.what}`).join("\n")}`);
90
- }
91
- }
92
- for (const { file, count } of baseline.static) {
93
- const now = byFile.get(file)?.count ?? 0;
94
- if (now < count) stale.push(`${file}: the baseline allows ${count}, there ${now === 1 ? "is" : "are"} ${now} now. Lower it to ${now}${now ? "" : " (remove the line)"}.`);
95
- }
96
- return { fresh, stale, known };
97
- }
98
- var measuredKey = (route, check, element) => `${route}\0${check}\0${element}`;
99
- function judgeMeasured(routes, baseline) {
100
- const fresh = [];
101
- const stale = [];
102
- let known = 0;
103
- const allowed = new Map(baseline.measured.map((b) => [measuredKey(b.route, b.check, b.element), b.count]));
104
- const seen = /* @__PURE__ */ new Map();
105
- const measured = new Set(routes.map((r) => r.route));
106
- for (const { route, findings } of routes) {
107
- const counted = tally(findings, (f) => measuredKey(route, f.check, normaliseElement(f.element)));
108
- for (const [key, { item, count }] of counted) {
109
- seen.set(key, count);
110
- const allow = allowed.get(key) ?? 0;
111
- known += Math.min(count, allow);
112
- if (count > allow) {
113
- const times = count - allow > 1 ? ` (${count - allow} more than the baseline's ${allow})` : allow ? ` (the baseline allows ${allow})` : "";
114
- fresh.push(`${route}: ${LABEL[item.check]} ${item.element}: ${item.detail}${times}`);
115
- }
116
- }
117
- }
118
- const missing = /* @__PURE__ */ new Set();
119
- for (const b of baseline.measured) {
120
- const key = measuredKey(b.route, b.check, b.element);
121
- if (!measured.has(b.route)) {
122
- if (!missing.has(b.route)) stale.push(`${b.route}: in the baseline but not measured this run. Measure it, or remove its lines.`);
123
- missing.add(b.route);
124
- continue;
125
- }
126
- const now = seen.get(key) ?? 0;
127
- if (now < b.count) stale.push(`${b.route}: ${LABEL[b.check]} ${b.element}: the baseline allows ${b.count}, ${now} found. Lower it to ${now}${now ? "" : " (remove the line)"}.`);
128
- }
129
- return { fresh, stale, known };
130
- }
131
- var LABEL = {
132
- scroll: "scrolls sideways",
133
- target: "small target",
134
- field: "small field",
135
- text: "small text",
136
- title: "title cut off"
137
- };
138
- function writeBaseline(findings, routes, note) {
139
- const byFile = tally(findings, (f) => f.file);
140
- const measured = routes.flatMap(
141
- ({ route, findings: findings2 }) => [...tally(findings2, (f) => measuredKey(route, f.check, normaliseElement(f.element))).values()].map(({ item, count }) => ({ route, check: item.check, element: normaliseElement(item.element), count }))
142
- );
143
- return {
144
- ...note ? { note } : {},
145
- static: [...byFile.values()].map(({ item, count }) => ({ file: item.file, count, found: findings.filter((f) => f.file === item.file).map((f) => f.what) })).sort((a, b) => a.file.localeCompare(b.file)),
146
- measured: measured.sort((a, b) => a.route.localeCompare(b.route) || a.check.localeCompare(b.check) || a.element.localeCompare(b.element))
147
- };
148
- }
149
-
150
- // src/phone/cli.ts
151
- var USAGE = "usage: craft phone-first [--config phone-first.json] [--measured <dir>] [--update-baseline] [--json]";
152
- function parse(args) {
153
- const flags = { config: "phone-first.json", update: false, json: false };
154
- for (let i = 0; i < args.length; i++) {
155
- const a = args[i];
156
- if (a === "--update-baseline") flags.update = true;
157
- else if (a === "--json") flags.json = true;
158
- else if (a === "--config" || a === "--measured") {
159
- const v = args[++i];
160
- if (!v || v.startsWith("--")) return `${a} needs a value`;
161
- if (a === "--config") flags.config = v;
162
- else flags.measured = v;
163
- } else return `unknown argument ${a}`;
164
- }
165
- return flags;
166
- }
167
- function loadConfig(path) {
168
- if (!existsSync(path)) throw new Error(`no ${path}. Write one: { "source": ["<dirs with styles and components>"], "baseline": "phone-first.baseline.json" }`);
169
- const c = JSON.parse(readFileSync(path, "utf8"));
170
- if (!Array.isArray(c.source) || c.source.length === 0 || c.source.some((s) => typeof s !== "string")) throw new Error(`${path}: "source" should list the folders to scan`);
171
- if (c.ignore !== void 0 && (!Array.isArray(c.ignore) || c.ignore.some((s) => typeof s !== "string"))) throw new Error(`${path}: "ignore" should be a list of globs`);
172
- if (c.exceptions !== void 0 && !Array.isArray(c.exceptions)) throw new Error(`${path}: "exceptions" should be a list of { "file", "reason" }`);
173
- return { source: c.source, ignore: c.ignore ?? [], exceptions: c.exceptions ?? [], baseline: c.baseline ?? "phone-first.baseline.json" };
174
- }
175
- function loadBaseline(path) {
176
- if (!existsSync(path)) return EMPTY_BASELINE;
177
- const b = JSON.parse(readFileSync(path, "utf8"));
178
- return { ...b.note ? { note: b.note } : {}, static: b.static ?? [], measured: b.measured ?? [] };
179
- }
180
- function loadMeasured(dir) {
181
- if (!existsSync(dir)) throw new Error(`--measured ${dir}: no such folder. Run the portal's phone-first specs first; they write it.`);
182
- const routes = readdirSync(dir).filter((f) => f.endsWith(".json")).sort().map((f) => JSON.parse(readFileSync(join(dir, f), "utf8")));
183
- if (routes.length === 0) throw new Error(`--measured ${dir}: no measured routes in it. Did the phone-first specs run?`);
184
- return routes;
185
- }
186
- function runPhoneFirst(args, io) {
187
- const flags = parse(args);
188
- if (typeof flags === "string") {
189
- io.err(`craft phone-first: ${flags}
190
- ${USAGE}`);
191
- return 2;
192
- }
193
- try {
194
- const config = loadConfig(resolve(io.cwd, flags.config));
195
- const baselinePath = resolve(io.cwd, config.baseline);
196
- const baseline = loadBaseline(baselinePath);
197
- const exceptionProblems = checkExceptions(config.exceptions, (f) => existsSync(resolve(io.cwd, f)));
198
- const sources = config.source.filter((s2) => existsSync(resolve(io.cwd, s2)));
199
- const missing = config.source.filter((s2) => !sources.includes(s2));
200
- if (missing.length) throw new Error(`${flags.config}: source ${missing.join(", ")} not found`);
201
- const files = readPaths(sources, io.cwd, SOURCE_FILE, void 0, config.ignore);
202
- const { findings, excused } = scanPhoneFirst(files, config.exceptions);
203
- const routes = flags.measured ? loadMeasured(resolve(io.cwd, flags.measured)) : null;
204
- if (flags.update) {
205
- const next = writeBaseline(findings, routes ?? [], baseline.note);
206
- if (!routes) next.measured = baseline.measured;
207
- writeFileSync(baselinePath, `${JSON.stringify(next, null, 2)}
208
- `);
209
- io.out(`craft phone-first: wrote ${config.baseline} (${next.static.reduce((n, s2) => n + s2.count, 0)} static, ${next.measured.reduce((n, m2) => n + m2.count, 0)} measured)`);
210
- return exceptionProblems.length ? 1 : 0;
211
- }
212
- const s = judgeStatic(findings, baseline);
213
- const m = routes ? judgeMeasured(routes, baseline) : { fresh: [], stale: [], known: 0 };
214
- const failed = exceptionProblems.length + s.fresh.length + s.stale.length + m.fresh.length + m.stale.length > 0;
215
- if (flags.json) {
216
- io.out(toJson({ pass: !failed, files: files.length, excused, routes: routes?.map((r) => r.route) ?? null, exceptionProblems, static: s, measured: m }));
217
- return failed ? 1 : 0;
218
- }
219
- const section = (title, lines) => lines.length ? `
220
- ${title}
221
- ${lines.map((l) => ` ${l}`).join("\n")}` : "";
222
- const known = s.known + m.known;
223
- const summary = [
224
- `${files.length} files${routes ? ` and ${routes.length} route${routes.length === 1 ? "" : "s"} at 375px` : ""}`,
225
- excused ? `${excused} recorded exception${excused === 1 ? "" : "s"}` : null,
226
- known ? `${known} known breach${known === 1 ? "" : "es"} in ${config.baseline}` : null
227
- ].filter(Boolean).join(", ");
228
- if (!failed) {
229
- io.out(`craft phone-first: pass. ${summary}.`);
230
- return 0;
231
- }
232
- io.err(
233
- [
234
- `craft phone-first: fail. ${summary}.`,
235
- section("The exceptions:", exceptionProblems),
236
- section("Built desktop first (write the phone as the base styles and widen with min-width; a genuine exception takes `mobile-first-ok: <reason>` on its line):", s.fresh),
237
- section("Measured at 375px:", m.fresh),
238
- section("The baseline claims more than is there (good: lower it, so the fix stays fixed):", [...s.stale, ...m.stale])
239
- ].join("")
240
- );
241
- return 1;
242
- } catch (error) {
243
- io.err(`craft phone-first: ${error.message}`);
244
- return 2;
245
- }
246
- }
247
- export {
248
- runPhoneFirst
249
- };