@luhtech/site-template 0.24.1 → 0.25.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/README.md CHANGED
@@ -425,6 +425,52 @@ Two bins go with it:
425
425
  install chromium`. `SiteLayout` emits the web-app meta for an installable
426
426
  site.
427
427
 
428
+ ## The sites stand on the brand's ground, and draw the mark set and boards (0.25.0)
429
+
430
+ d-2026-12-04-lb-site-ground-and-marks (LuhTech-Business). Dark only: there
431
+ is no light variant, no `prefers-color-scheme` branch and no toggle.
432
+
433
+ - **The ground.** `luhtech-tokens` writes the brand's `color.dark` set into
434
+ the same `@theme` block under the same role names -- `--color-canvas` is
435
+ `color.dark.canvas`, `--color-ink` `color.dark.ink`, both accents
436
+ `color.dark.accent` -- plus `--color-surface`, `--color-muted` and
437
+ `--color-rule`, and sets `color-scheme: dark` on `:root`. Each value names
438
+ its record and JSON pointer. A brand with no `color.dark` names the record
439
+ it stands on: `luhtech-tokens <brand.json> <out.css> --ground <brand.json>`;
440
+ it keeps its own accent only where that passes 4.5:1 on the ground, else
441
+ the ground's accent. With neither, the generator fails naming the brandId.
442
+ The text pairs (ink, muted and accent on canvas and surface; canvas on each
443
+ accent) are held to WCAG 2.2 AA 4.5:1 with `@luhtech/figures` `contrast()`,
444
+ so every site's prebuild checks them.
445
+ - **Every element on the ground.** `SiteLayout`'s header and footer are
446
+ `bg-canvas text-ink`, divided by `border-rule`; inputs and panels take
447
+ `bg-surface`, their borders `border-rule`; the photo heroes stay, their
448
+ text `text-ink`. `theme-color` and `luhtech-sync-icons`' manifest and
449
+ apple-touch background read the ground (`SiteLayout` and
450
+ `luhtech-sync-icons` take the same `ground` / `--ground` record).
451
+ `configureFigures` refuses a figure theme not built with
452
+ `buildTheme(brand, families, cells, 'dark')`.
453
+ - **`luhtech-sync-mark-set <mark-set.json> <asset-bank records>... [--out] [--bytes]`**
454
+ fetches each member's bytes from its asset-bank record's own uri, refuses
455
+ any whose sha256 differs, and writes the bytes unaltered and a manifest
456
+ into `src/generated/mark-set`. A draft member, a missing record, a
457
+ mismatch, a wrong viewBox, or a mark carrying a `<style>`, `<script>`, a
458
+ style or `on*` attribute fails the build naming the markId.
459
+ **`<Mark markId="..." class? label? />`** inlines it (re-hashed at build;
460
+ an unknown markId fails the build) with `role="img"` and the member's line
461
+ as its name. `inlinedMarkProblems(html, loadMarkSet())`
462
+ (`@luhtech/site-template/lib/markSet`) hashes a built page's inlined marks
463
+ against the manifest.
464
+ - **`luhtech-sync-boards <channel-renders.json> <asset-bank records>... --board <assetId>...`**
465
+ reads the board rule from schema-registry channel-renders deck-react
466
+ `meta.boardLayout`, verifies each board's sha256, size and aspect, and
467
+ writes it to `public/boards` with a manifest. **`<Board assetId alt text
468
+ minTextScale />`** draws it at its own aspect, no narrower than the width
469
+ at which its smallest type meets the legibility floor (scrolling sideways
470
+ inside its figure where the column is narrower), with its words as data
471
+ in a `<details>`. `boardDrawnProblems` (`@luhtech/site-template/lib/boards`)
472
+ judges a board as a page check measures it.
473
+
428
474
  ## A content-security policy arrives as a response header (0.24.0)
429
475
 
430
476
  Astro renders a hash-based policy as a `<meta>` element at the end of `<head>`, so anything earlier in `<head>` is not covered by it. That includes SiteLayout's no-js script, the fonts stylesheet and a page's head slot. A header comes before the document, so it covers all of it.
@@ -0,0 +1,74 @@
1
+ // Asset-bank records and their bytes, for the sync tools that draw banked assets on a site (0.25.0,
2
+ // d-2026-12-04-lb-site-ground-and-marks OUT-3, OUT-8): luhtech-sync-mark-set and luhtech-sync-boards.
3
+ //
4
+ // A record (schema-registry portfolio/asset-bank) names its bytes by uri and their sha256. The bytes are fetched
5
+ // from that uri -- never from a URL built here -- and refused unless they hash to the record. --bytes DIR reads
6
+ // DIR/<uri basename> instead, as schema-registry tools/check_mark_set.py does, for a local mirror or a test.
7
+ import { createHash } from 'node:crypto';
8
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
+ import { basename, join } from 'node:path';
10
+
11
+ export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
12
+
13
+ function recordsIn(doc) {
14
+ if (Array.isArray(doc)) return doc;
15
+ if (doc && Array.isArray(doc.records)) return doc.records;
16
+ if (doc && typeof doc.assetId === 'string') return [doc];
17
+ return [];
18
+ }
19
+
20
+ /**
21
+ * assetId -> record, over each path: a file holding one record, an array of records or { records: [...] } (the
22
+ * site's content/assets/.../asset-bank.*.json), or a directory of such files. An assetId listed twice fails.
23
+ */
24
+ export function loadAssetRecords(paths) {
25
+ const out = new Map();
26
+ const files = [];
27
+ for (const p of paths) {
28
+ if (!existsSync(p)) throw new Error(`no asset-bank records at ${p}`);
29
+ if (statSync(p).isDirectory()) {
30
+ for (const f of readdirSync(p).filter((n) => n.endsWith('.json')).sort()) files.push(join(p, f));
31
+ } else {
32
+ files.push(p);
33
+ }
34
+ }
35
+ for (const f of files) {
36
+ for (const rec of recordsIn(JSON.parse(readFileSync(f, 'utf-8')))) {
37
+ if (typeof rec?.assetId !== 'string') continue;
38
+ if (out.has(rec.assetId)) throw new Error(`assetId ${rec.assetId} appears twice (${out.get(rec.assetId).file}, ${f})`);
39
+ out.set(rec.assetId, { record: rec, file: f });
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** A reader of a record's bytes: from its uri over https, or from bytesDir/<uri basename> when given. */
46
+ export function byteReader(bytesDir) {
47
+ if (bytesDir) {
48
+ return async (uri) => readFileSync(join(bytesDir, basename(new URL(uri).pathname)));
49
+ }
50
+ return async (uri) => {
51
+ if (!uri.startsWith('https://')) throw new Error(`not an https uri: ${uri}`);
52
+ const res = await fetch(uri);
53
+ if (!res.ok) throw new Error(`${uri}: HTTP ${res.status}`);
54
+ return Buffer.from(await res.arrayBuffer());
55
+ };
56
+ }
57
+
58
+ /**
59
+ * The record's verified bytes: read through `read` and refused unless they hash to record.sha256. Throws a
60
+ * message beginning with `who` (the markId or board id the site names).
61
+ */
62
+ export async function verifiedBytes(who, record, read) {
63
+ let bytes;
64
+ try {
65
+ bytes = await read(record.uri);
66
+ } catch (err) {
67
+ throw new Error(`${who}: ${record.assetId} bytes unreadable at ${record.uri} (${err.message})`);
68
+ }
69
+ const got = sha256(bytes);
70
+ if (got !== record.sha256) {
71
+ throw new Error(`${who}: ${record.assetId} bytes hash to ${got}, its asset-bank record says ${record.sha256} -- refused`);
72
+ }
73
+ return bytes;
74
+ }
@@ -0,0 +1,99 @@
1
+ // The ground every site stands on (0.25.0, d-2026-12-04-lb-site-ground-and-marks OUT-1, OUT-2, OUT-6).
2
+ //
3
+ // Dark only: a site's colours are its brand-identity record's color.dark set, or -- for a brand that carries
4
+ // none -- the color.dark set of the ground record it names (luhtech-tokens --ground). There is no light
5
+ // rendering to fall back to: a brand with neither fails, naming its brandId.
6
+ //
7
+ // Every value carries the record it came from and its JSON pointer, so the generated CSS, the theme-color and
8
+ // the web manifest each say where their colour is read from. The contrast check (WCAG 2.2 AA, 4.5:1 for text,
9
+ // SC 1.4.3) uses @luhtech/figures' contrast() -- the same arithmetic the figure kit and schema-registry's
10
+ // tools/figure_palette.py use -- over the pairs brand-identity holds to 4.5:1: ink, muted and accent on canvas
11
+ // and on surface, and canvas text on each accent (the button).
12
+ import { contrast } from '@luhtech/figures';
13
+
14
+ /** WCAG 2.2 SC 1.4.3 (Contrast, Minimum), level AA: normal text. */
15
+ export const WCAG_AA_TEXT = 4.5;
16
+
17
+ const DARK_ROLES = ['canvas', 'surface', 'ink', 'muted', 'rule', 'accent'];
18
+
19
+ function darkSet(record, label) {
20
+ const dark = record?.color?.dark;
21
+ if (!dark) return null;
22
+ for (const role of DARK_ROLES) {
23
+ if (!dark[role]?.oklch || !dark[role]?.hex) {
24
+ throw new Error(`${label} (${record.brandId}) color.dark.${role} has no oklch and hex value`);
25
+ }
26
+ }
27
+ return dark;
28
+ }
29
+
30
+ const at = (record, file, pointer, value) => ({ oklch: value.oklch, hex: value.hex.toUpperCase(), brandId: record.brandId, file, pointer });
31
+
32
+ /**
33
+ * The site's colour roles on the ground.
34
+ * brand, brandFile -- the site's brand-identity record and the path it was read from
35
+ * ground, groundFile -- optional: the record whose color.dark the site stands on when its brand has none
36
+ * Returns { canvas, surface, ink, muted, rule, accentPrimary, accentSecondary, groundBrandId }, each value
37
+ * { oklch, hex, brandId, file, pointer }.
38
+ */
39
+ export function resolveGround(brand, brandFile, ground, groundFile) {
40
+ if (!brand?.brandId) throw new Error(`${brandFile} is not a brand-identity record (no brandId)`);
41
+ const own = darkSet(brand, brandFile);
42
+ if (own) {
43
+ const v = (role) => at(brand, brandFile, `#/color/dark/${role}`, own[role]);
44
+ return {
45
+ groundBrandId: brand.brandId,
46
+ canvas: v('canvas'), surface: v('surface'), ink: v('ink'), muted: v('muted'), rule: v('rule'),
47
+ accentPrimary: v('accent'), accentSecondary: v('accent'),
48
+ };
49
+ }
50
+ if (!ground) {
51
+ throw new Error(`brand ${brand.brandId} carries no color.dark and names no ground record (--ground <brand-identity file>); the light rendering is closed`);
52
+ }
53
+ const gd = darkSet(ground, groundFile);
54
+ if (!gd) throw new Error(`ground record ${groundFile} (${ground.brandId}) carries no color.dark`);
55
+ const g = (role) => at(ground, groundFile, `#/color/dark/${role}`, gd[role]);
56
+ const canvas = g('canvas');
57
+ const surface = g('surface');
58
+ // L4 2026-12-04 (#618 Q2): a site keeps its own accent only where it passes contrast on the ground, and uses
59
+ // the ground record's accent elsewhere.
60
+ const accent = (slot) => {
61
+ const mine = brand.color?.accent?.[slot];
62
+ if (mine?.hex && mine?.oklch && contrast(mine.hex, canvas.hex) >= WCAG_AA_TEXT && contrast(mine.hex, surface.hex) >= WCAG_AA_TEXT
63
+ && contrast(canvas.hex, mine.hex) >= WCAG_AA_TEXT) {
64
+ return at(brand, brandFile, `#/color/accent/${slot}`, mine);
65
+ }
66
+ return g('accent');
67
+ };
68
+ return {
69
+ groundBrandId: ground.brandId,
70
+ canvas, surface, ink: g('ink'), muted: g('muted'), rule: g('rule'),
71
+ accentPrimary: accent('primary'), accentSecondary: accent('secondary'),
72
+ };
73
+ }
74
+
75
+ /** The text pairs held to 4.5:1, each { fg, bg, ratio } with the role names. */
76
+ export function contrastPairs(roles) {
77
+ const pairs = [];
78
+ for (const fg of ['ink', 'muted', 'accentPrimary', 'accentSecondary']) {
79
+ for (const bg of ['canvas', 'surface']) pairs.push([fg, bg]);
80
+ }
81
+ pairs.push(['canvas', 'accentPrimary'], ['canvas', 'accentSecondary']);
82
+ const seen = new Set();
83
+ const out = [];
84
+ for (const [fg, bg] of pairs) {
85
+ // accent-primary and accent-secondary are often one value; the pair is checked once.
86
+ const key = `${roles[fg].hex}/${roles[bg].hex}`;
87
+ if (seen.has(key)) continue;
88
+ seen.add(key);
89
+ out.push({ fg, bg, fgHex: roles[fg].hex, bgHex: roles[bg].hex, ratio: contrast(roles[fg].hex, roles[bg].hex) });
90
+ }
91
+ return out;
92
+ }
93
+
94
+ /** The pairs below WCAG 2.2 AA, as messages; empty when every pair passes. */
95
+ export function contrastFailures(roles) {
96
+ return contrastPairs(roles)
97
+ .filter((p) => p.ratio < WCAG_AA_TEXT)
98
+ .map((p) => `${p.fg} ${p.fgHex} on ${p.bg} ${p.bgHex} is ${p.ratio.toFixed(2)}:1, below WCAG 2.2 AA ${WCAG_AA_TEXT}:1`);
99
+ }
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Pulls the banked boards a site draws from the published asset bank into the
4
+ * site, verified (0.25.0, d-2026-12-04-lb-site-ground-and-marks OUT-8), the
5
+ * same shape as luhtech-sync-mark-set. Board.astro draws what this writes.
6
+ *
7
+ * Reads the board rule from schema-registry's channel-renders record (the
8
+ * site's mirrored copy of schemas/content/channel-renders.json: renderId
9
+ * deck-react, meta.boardLayout -- the fit, the aspect tolerance, the
10
+ * legibility floor and the word budget), never restating it. For each board
11
+ * the site names (--board <assetId>, repeatable) it reads the asset-bank
12
+ * record, fetches the bytes from the record's own uri, refuses any whose
13
+ * sha256 differs, reads the drawing's own size from the bytes (PNG IHDR, or
14
+ * an SVG root's viewBox) and refuses one whose size differs from the record's
15
+ * dimensions or whose aspect is off the board fit's by more than the
16
+ * tolerance -- a board is never stretched or cropped to fit. It writes the
17
+ * verified bytes unaltered to <out>/<assetId>.<ext> and a manifest carrying
18
+ * the rule (with the record and pointer it was read from) and each board.
19
+ *
20
+ * Every failure names the board and is listed before the tool exits 1;
21
+ * nothing is written then.
22
+ *
23
+ * Usage:
24
+ * luhtech-sync-boards <channel-renders.json> <asset-bank records file|dir>... --board <assetId>...
25
+ * [--out public/boards] [--base /boards] [--manifest src/generated/boards/manifest.json]
26
+ * [--bytes <dir>]
27
+ */
28
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
29
+ import { dirname, join, resolve } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
31
+ import { byteReader, loadAssetRecords, sha256, verifiedBytes } from './lib/assetBank.mjs';
32
+
33
+ export const DEFAULTS = { out: 'public/boards', base: '/boards', manifest: 'src/generated/boards/manifest.json' };
34
+ const EXT = { 'image/png': 'png', 'image/svg+xml': 'svg' };
35
+
36
+ /** deck-react's board rule, read from a channel-renders record; the fit's W x H parsed from its own words. */
37
+ export function boardRule(renders, file) {
38
+ const list = Array.isArray(renders) ? renders : [];
39
+ const render = list.find((r) => r?.renderId === 'deck-react');
40
+ const rule = render?.meta?.boardLayout;
41
+ if (!rule) throw new Error(`deck-react in ${file} states no boardLayout`);
42
+ const m = /(\d+)\s*x\s*(\d+) at 1x/.exec(rule.fit || '');
43
+ if (!m) throw new Error(`deck-react boardLayout.fit in ${file} names no WxH at 1x`);
44
+ const floor = rule.legibilityFloor?.minTextScale;
45
+ if (typeof rule.aspectTolerance !== 'number' || typeof floor !== 'number' || typeof rule.contentBudget !== 'number') {
46
+ throw new Error(`deck-react boardLayout in ${file} lacks aspectTolerance, legibilityFloor.minTextScale or contentBudget`);
47
+ }
48
+ return {
49
+ source: `${file}#deck-react/meta/boardLayout`,
50
+ fitWidth: Number(m[1]),
51
+ fitHeight: Number(m[2]),
52
+ aspectTolerance: rule.aspectTolerance,
53
+ minTextScaleFloor: floor,
54
+ contentBudget: rule.contentBudget,
55
+ };
56
+ }
57
+
58
+ /** The drawing's own size from its bytes: a PNG's IHDR, or an SVG root's viewBox. null when unreadable. */
59
+ export function intrinsicSize(bytes, mimeType) {
60
+ if (mimeType === 'image/png') {
61
+ const sig = '89504e470d0a1a0a';
62
+ if (bytes.length < 24 || bytes.subarray(0, 8).toString('hex') !== sig || bytes.subarray(12, 16).toString('ascii') !== 'IHDR') return null;
63
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
64
+ }
65
+ if (mimeType === 'image/svg+xml') {
66
+ const root = /^\s*(?:<\?xml[^>]*>\s*)?<svg\b([^>]*)>/.exec(bytes.toString('utf-8'));
67
+ const vb = root && /\sviewBox="\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*"/.exec(root[1]);
68
+ return vb ? { width: Number(vb[1]), height: Number(vb[2]) } : null;
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** Verifies every named board. Returns { boards: [...], problems: [] }. */
74
+ export async function verifyBoards(ids, records, rule, read) {
75
+ const problems = [];
76
+ const boards = [];
77
+ const fitAspect = rule.fitWidth / rule.fitHeight;
78
+ for (const id of [...new Set(ids)]) {
79
+ const entry = records.get(id);
80
+ if (!entry) { problems.push(`${id}: no asset-bank record`); continue; }
81
+ const rec = entry.record;
82
+ if (rec.bankType !== 'diagram') { problems.push(`${id}: bankType ${rec.bankType}, not diagram`); continue; }
83
+ const ext = EXT[rec.mimeType];
84
+ if (!ext) { problems.push(`${id}: mimeType ${rec.mimeType} is not one a board is drawn from (${Object.keys(EXT).join(', ')})`); continue; }
85
+ let bytes;
86
+ try {
87
+ bytes = await verifiedBytes(id, rec, read);
88
+ } catch (err) {
89
+ problems.push(err.message);
90
+ continue;
91
+ }
92
+ const size = intrinsicSize(bytes, rec.mimeType);
93
+ if (!size) { problems.push(`${id}: its size cannot be read from its ${rec.mimeType} bytes`); continue; }
94
+ const d = rec.dimensions;
95
+ if (d && (d.width !== size.width || d.height !== size.height)) {
96
+ problems.push(`${id}: bytes are ${size.width} x ${size.height}, its record says ${d.width} x ${d.height}`);
97
+ continue;
98
+ }
99
+ const aspect = size.width / size.height;
100
+ if (Math.abs(aspect - fitAspect) / fitAspect > rule.aspectTolerance) {
101
+ problems.push(`${id}: aspect ${aspect.toFixed(4)} differs from the board fit's ${fitAspect.toFixed(4)} by more than ${rule.aspectTolerance} -- refused, never stretched or cropped`);
102
+ continue;
103
+ }
104
+ boards.push({ assetId: id, sha256: sha256(bytes), mimeType: rec.mimeType, width: size.width, height: size.height, file: `${id}.${ext}`, bytes });
105
+ }
106
+ return { boards, problems };
107
+ }
108
+
109
+ export function buildManifest(rule, boards, base, out) {
110
+ return {
111
+ generatedBy: 'luhtech-sync-boards (@luhtech/site-template) -- DO NOT HAND-EDIT',
112
+ rule,
113
+ /** Where the bytes are, relative to the site root: Board.astro re-hashes them there at build. */
114
+ out,
115
+ boards: Object.fromEntries(boards.map((b) => [b.assetId, {
116
+ sha256: b.sha256, mimeType: b.mimeType, width: b.width, height: b.height, file: b.file, src: `${base.replace(/\/$/, '')}/${b.file}`,
117
+ }])),
118
+ };
119
+ }
120
+
121
+ export function parseArgs(argv) {
122
+ const args = [...argv];
123
+ const take = (flag) => {
124
+ const i = args.indexOf(flag);
125
+ if (i < 0) return null;
126
+ const v = args[i + 1];
127
+ if (!v || v.startsWith('--')) throw new Error(`${flag} needs a value`);
128
+ args.splice(i, 2);
129
+ return v;
130
+ };
131
+ const boards = [];
132
+ for (let b = take('--board'); b !== null; b = take('--board')) boards.push(b);
133
+ const out = take('--out') ?? DEFAULTS.out;
134
+ const base = take('--base') ?? DEFAULTS.base;
135
+ const manifest = take('--manifest') ?? DEFAULTS.manifest;
136
+ const bytes = take('--bytes');
137
+ const [renders, ...records] = args;
138
+ return { renders, records, boards, out, base, manifest, bytes };
139
+ }
140
+
141
+ export async function run(argv, cwd = process.cwd()) {
142
+ const o = parseArgs(argv);
143
+ if (!o.renders || o.records.length === 0 || o.boards.length === 0) {
144
+ throw new Error('Usage: luhtech-sync-boards <channel-renders.json> <asset-bank records file|dir>... --board <assetId>... [--out <dir>] [--base <url path>] [--manifest <file>] [--bytes <dir>]');
145
+ }
146
+ const rule = boardRule(JSON.parse(readFileSync(resolve(cwd, o.renders), 'utf-8')), o.renders);
147
+ const records = loadAssetRecords(o.records.map((p) => resolve(cwd, p)));
148
+ const { boards, problems } = await verifyBoards(o.boards, records, rule, byteReader(o.bytes ? resolve(cwd, o.bytes) : null));
149
+ if (problems.length) throw new Error(`boards refused:\n - ${problems.join('\n - ')}`);
150
+ const outDir = resolve(cwd, o.out);
151
+ mkdirSync(outDir, { recursive: true });
152
+ const keep = new Set(boards.map((b) => b.file));
153
+ for (const f of readdirSync(outDir)) if (/\.(png|svg)$/.test(f) && !keep.has(f)) rmSync(join(outDir, f));
154
+ for (const b of boards) writeFileSync(join(outDir, b.file), b.bytes);
155
+ const manifestPath = resolve(cwd, o.manifest);
156
+ mkdirSync(dirname(manifestPath), { recursive: true });
157
+ writeFileSync(manifestPath, JSON.stringify(buildManifest(rule, boards, o.base, o.out), null, 2) + '\n');
158
+ return { count: boards.length, out: outDir, manifest: manifestPath };
159
+ }
160
+
161
+ // Run as a CLI (including through node_modules/.bin's symlink), not on import from tests.
162
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
163
+ run(process.argv.slice(2)).then(
164
+ ({ count, out, manifest }) => console.log(`${count} board(s) verified against their asset-bank records, written to ${out}; manifest ${manifest}`),
165
+ (err) => {
166
+ console.error(`luhtech-sync-boards failed: ${err.message}`);
167
+ process.exit(1);
168
+ },
169
+ );
170
+ }
@@ -3,11 +3,12 @@
3
3
  * Generates a site's raster icons and web manifest from its own
4
4
  * public/favicon.svg and brand-identity instance, into public/:
5
5
  *
6
- * apple-touch-icon.png 180x180, mark on the brand canvas colour
6
+ * apple-touch-icon.png 180x180, mark on the ground (color.dark.canvas)
7
7
  * (iOS fills transparency with black otherwise)
8
8
  * icon-192.png 192x192, transparent
9
9
  * icon-512.png 512x512, transparent
10
10
  * site.webmanifest name, short_name, icons, theme/background colour
11
+ * -- both the ground (0.25.0)
11
12
  * favicon.ico 16, 32 and 48px, transparent -- browsers and crawlers
12
13
  * request /favicon.ico whatever the page links
13
14
  *
@@ -15,8 +16,13 @@
15
16
  * this is what turns them on for a site. Re-run when favicon.svg or the
16
17
  * brand's name/colours change; output is deterministic for the same inputs.
17
18
  *
19
+ * 0.25.0 (d-2026-12-04-lb-site-ground-and-marks OUT-2): the colours are the
20
+ * ground -- the brand's color.dark.canvas, or, for a brand with no color.dark,
21
+ * the --ground record's (the file luhtech-tokens --ground reads). A brand with
22
+ * neither fails, naming its brandId; the light rendering is closed.
23
+ *
18
24
  * Usage:
19
- * luhtech-sync-icons <path-to-brand-identity.json> [--public <dir>] [--check]
25
+ * luhtech-sync-icons <path-to-brand-identity.json> [--ground <brand-identity.json>] [--public <dir>] [--check]
20
26
  * luhtech-sync-icons content/brand/hilja.json
21
27
  *
22
28
  * --check writes nothing and exits 1 if any output is missing or stale.
@@ -27,11 +33,19 @@ import { fileURLToPath } from 'node:url';
27
33
 
28
34
  export const APPLE_PADDING = 0.125; // fraction of the canvas left clear on each side
29
35
 
30
- export function buildManifest(brand) {
36
+ /** The ground's hex: the brand's color.dark.canvas, else the ground record's; neither fails naming the brand. */
37
+ export function groundHex(brand, ground) {
38
+ const hex = brand?.color?.dark?.canvas?.hex ?? ground?.color?.dark?.canvas?.hex;
39
+ if (!hex) {
40
+ throw new Error(`brand ${brand?.brandId} carries no color.dark and names no ground record (--ground <brand-identity file>)`);
41
+ }
42
+ return hex;
43
+ }
44
+
45
+ export function buildManifest(brand, ground) {
31
46
  const name = brand?.identity?.name;
32
47
  if (!name) throw new Error('brand identity.name is required');
33
- const ink = brand?.color?.foundation?.ink?.hex;
34
- const canvas = brand?.color?.foundation?.canvas?.hex;
48
+ const canvas = groundHex(brand, ground);
35
49
  const manifest = {
36
50
  name,
37
51
  short_name: name,
@@ -42,8 +56,9 @@ export function buildManifest(brand) {
42
56
  start_url: '/',
43
57
  display: 'browser',
44
58
  };
45
- if (ink) manifest.theme_color = ink;
46
- if (canvas) manifest.background_color = canvas;
59
+ // The header stands on the ground, so the browser chrome and the splash both read it.
60
+ manifest.theme_color = canvas;
61
+ manifest.background_color = canvas;
47
62
  return JSON.stringify(manifest, null, 2) + '\n';
48
63
  }
49
64
 
@@ -96,12 +111,14 @@ async function render(svg, size) {
96
111
 
97
112
  async function main() {
98
113
  const args = process.argv.slice(2);
99
- const brandPath = args.find((a) => !a.startsWith('--') && args[args.indexOf(a) - 1] !== '--public');
114
+ const brandPath = args.find((a, i) => !a.startsWith('--') && args[i - 1] !== '--public' && args[i - 1] !== '--ground');
115
+ const groundIdx = args.indexOf('--ground');
116
+ const ground = groundIdx >= 0 ? JSON.parse(readFileSync(args[groundIdx + 1], 'utf-8')) : undefined;
100
117
  const publicIdx = args.indexOf('--public');
101
118
  const publicDir = resolve(process.cwd(), publicIdx >= 0 ? args[publicIdx + 1] : 'public');
102
119
  const check = args.includes('--check');
103
120
  if (!brandPath) {
104
- console.error('Usage: luhtech-sync-icons <path-to-brand-identity.json> [--public <dir>] [--check]');
121
+ console.error('Usage: luhtech-sync-icons <path-to-brand-identity.json> [--ground <brand-identity.json>] [--public <dir>] [--check]');
105
122
  process.exit(1);
106
123
  }
107
124
  const brand = JSON.parse(readFileSync(brandPath, 'utf-8'));
@@ -111,13 +128,13 @@ async function main() {
111
128
  process.exit(1);
112
129
  }
113
130
  const svg = readFileSync(svgPath, 'utf-8');
114
- const canvas = brand?.color?.foundation?.canvas?.hex ?? '#FFFFFF';
131
+ const canvas = groundHex(brand, ground);
115
132
 
116
133
  const outputs = [
117
134
  ['apple-touch-icon.png', await render(paddedSvg(svg, canvas), 180)],
118
135
  ['icon-192.png', await render(svg, 192)],
119
136
  ['icon-512.png', await render(svg, 512)],
120
- ['site.webmanifest', Buffer.from(buildManifest(brand))],
137
+ ['site.webmanifest', Buffer.from(buildManifest(brand, ground))],
121
138
  ['favicon.ico', buildIco(await Promise.all(ICO_SIZES.map(async (size) => ({ size, data: await render(svg, size) }))))],
122
139
  ];
123
140
 
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Pulls a site's mark set from the published asset bank into the site, verified
4
+ * (0.25.0, d-2026-12-04-lb-site-ground-and-marks OUT-3). Mark.astro inlines
5
+ * what this writes.
6
+ *
7
+ * Reads the site's mark-set record (schema-registry portfolio/mark-set, the
8
+ * site's mirrored copy) and the members' asset-bank records (the site's
9
+ * mirrored content/assets/.../asset-bank.*.json). For every member it fetches
10
+ * the bytes from the asset-bank record's own uri -- the URL is read, never
11
+ * built -- and refuses any whose sha256 differs from the record. It writes the
12
+ * verified bytes unaltered, one <markId>.svg each, and manifest.json:
13
+ * markId -> assetId, sha256, viewBox, line.
14
+ *
15
+ * The build fails, naming the markId, on:
16
+ * - a draft member (only status approved is drawn on a site)
17
+ * - a member whose assetId has no asset-bank record, or a record that is not
18
+ * bankType icon, mimeType image/svg+xml
19
+ * - bytes that cannot be read, or that do not hash to the record's sha256
20
+ * - bytes that are not one <svg> root in the set's grammar.viewBox
21
+ * - bytes carrying a <style> or <script> element, a style or on* attribute,
22
+ * a javascript: link or a <foreignObject> -- a mark inlines with nothing a
23
+ * site's content-security policy would need a new hash or unsafe-inline for
24
+ * Every failure is listed before the tool exits 1; nothing is written then.
25
+ *
26
+ * Usage:
27
+ * luhtech-sync-mark-set <mark-set.json> <asset-bank records file|dir>... [--out <dir>] [--bytes <dir>]
28
+ * luhtech-sync-mark-set content/marks/luhtech-marks.json content/assets/marks/asset-bank.marks.json
29
+ *
30
+ * --out defaults to src/generated/mark-set (where Mark.astro reads it).
31
+ * --bytes reads each record's bytes from <dir>/<uri basename> instead of its uri.
32
+ */
33
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
34
+ import { join, resolve } from 'node:path';
35
+ import { fileURLToPath } from 'node:url';
36
+ import { byteReader, loadAssetRecords, sha256, verifiedBytes } from './lib/assetBank.mjs';
37
+
38
+ export const DEFAULT_OUT = 'src/generated/mark-set';
39
+ export const MANIFEST = 'manifest.json';
40
+
41
+ /** What in a mark's bytes a hash-based content-security policy would refuse, or would need a new hash for. */
42
+ const CSP_UNSAFE = [
43
+ [/<style\b/i, 'a <style> element'],
44
+ [/<script\b/i, 'a <script> element'],
45
+ [/\sstyle\s*=/i, 'a style attribute'],
46
+ [/\son[a-z]+\s*=/i, 'an on* event attribute'],
47
+ [/javascript:/i, 'a javascript: link'],
48
+ [/<foreignObject\b/i, 'a <foreignObject>'],
49
+ ];
50
+
51
+ /** The problems with one mark's markup, as phrases; empty when it inlines with nothing a CSP needs. */
52
+ export function cspProblems(markup) {
53
+ return CSP_UNSAFE.filter(([re]) => re.test(markup)).map(([, what]) => what);
54
+ }
55
+
56
+ /** The root <svg>'s viewBox, or null when the bytes are not one <svg> root. */
57
+ export function rootViewBox(markup) {
58
+ const m = /^\s*<svg\b([^>]*)>[\s\S]*<\/svg>\s*$/.exec(markup);
59
+ if (!m) return null;
60
+ return /\sviewBox="([^"]+)"/.exec(m[1])?.[1] ?? null;
61
+ }
62
+
63
+ /**
64
+ * Verifies every member. Returns { marks: [{ markId, assetId, sha256, viewBox, line, bytes }], problems: [] }.
65
+ * read(uri) -> bytes (byteReader).
66
+ */
67
+ export async function verifyMarkSet(markSet, records, read) {
68
+ const problems = [];
69
+ const marks = [];
70
+ const viewBox = markSet?.grammar?.viewBox;
71
+ if (!Array.isArray(markSet?.members) || !viewBox) {
72
+ return { marks, problems: ['the mark-set record has no members or no grammar.viewBox'] };
73
+ }
74
+ const seen = new Set();
75
+ for (const m of markSet.members) {
76
+ const who = m.markId;
77
+ if (seen.has(who)) { problems.push(`${who}: listed twice`); continue; }
78
+ seen.add(who);
79
+ if (m.status !== 'approved') { problems.push(`${who}: status ${m.status} -- only an approved member is drawn on a site`); continue; }
80
+ const entry = records.get(m.assetId);
81
+ if (!entry) { problems.push(`${who}: assetId ${m.assetId} has no asset-bank record`); continue; }
82
+ const rec = entry.record;
83
+ if (rec.bankType !== 'icon' || rec.mimeType !== 'image/svg+xml') {
84
+ problems.push(`${who}: ${m.assetId} is ${rec.bankType} ${rec.mimeType}, not icon image/svg+xml`);
85
+ continue;
86
+ }
87
+ let bytes;
88
+ try {
89
+ bytes = await verifiedBytes(who, rec, read);
90
+ } catch (err) {
91
+ problems.push(err.message);
92
+ continue;
93
+ }
94
+ const markup = bytes.toString('utf-8');
95
+ const vb = rootViewBox(markup);
96
+ if (vb === null) { problems.push(`${who}: ${m.assetId} bytes are not one <svg> root with a viewBox`); continue; }
97
+ if (vb !== viewBox) { problems.push(`${who}: ${m.assetId} viewBox "${vb}" is not the set's grammar.viewBox "${viewBox}"`); continue; }
98
+ const unsafe = cspProblems(markup);
99
+ if (unsafe.length) { problems.push(`${who}: ${m.assetId} carries ${unsafe.join(', ')} -- refused, a mark inlines with no style and no script`); continue; }
100
+ marks.push({ markId: who, assetId: m.assetId, sha256: sha256(bytes), viewBox: vb, line: m.line, bytes });
101
+ }
102
+ return { marks, problems };
103
+ }
104
+
105
+ /** The manifest Mark.astro reads: the set it came from, and markId -> assetId, sha256, viewBox, line, file. */
106
+ export function buildManifest(markSet, markSetFile, marks) {
107
+ return {
108
+ generatedBy: 'luhtech-sync-mark-set (@luhtech/site-template) -- DO NOT HAND-EDIT',
109
+ markSet: { id: markSet.$id, version: markSet.version, brandId: markSet.brandId, file: markSetFile },
110
+ marks: Object.fromEntries(marks.map((k) => [k.markId, {
111
+ assetId: k.assetId, sha256: k.sha256, viewBox: k.viewBox, line: k.line, file: `${k.markId}.svg`,
112
+ }])),
113
+ };
114
+ }
115
+
116
+ /** Writes the verified bytes and the manifest into outDir, removing any .svg a previous run left there. */
117
+ export function writeMarkSet(outDir, manifest, marks) {
118
+ mkdirSync(outDir, { recursive: true });
119
+ const keep = new Set(marks.map((k) => `${k.markId}.svg`));
120
+ for (const f of readdirSync(outDir)) if (f.endsWith('.svg') && !keep.has(f)) rmSync(join(outDir, f));
121
+ for (const k of marks) writeFileSync(join(outDir, `${k.markId}.svg`), k.bytes);
122
+ writeFileSync(join(outDir, MANIFEST), JSON.stringify(manifest, null, 2) + '\n');
123
+ }
124
+
125
+ export function parseArgs(argv) {
126
+ const args = [...argv];
127
+ const take = (flag) => {
128
+ const i = args.indexOf(flag);
129
+ if (i < 0) return null;
130
+ const v = args[i + 1];
131
+ if (!v || v.startsWith('--')) throw new Error(`${flag} needs a directory`);
132
+ args.splice(i, 2);
133
+ return v;
134
+ };
135
+ const out = take('--out') ?? DEFAULT_OUT;
136
+ const bytes = take('--bytes');
137
+ const [markSet, ...records] = args;
138
+ return { markSet, records, out, bytes };
139
+ }
140
+
141
+ export async function run(argv, cwd = process.cwd()) {
142
+ const opts = parseArgs(argv);
143
+ if (!opts.markSet || opts.records.length === 0) {
144
+ throw new Error('Usage: luhtech-sync-mark-set <mark-set.json> <asset-bank records file|dir>... [--out <dir>] [--bytes <dir>]');
145
+ }
146
+ const markSet = JSON.parse(readFileSync(resolve(cwd, opts.markSet), 'utf-8'));
147
+ const records = loadAssetRecords(opts.records.map((p) => resolve(cwd, p)));
148
+ const read = byteReader(opts.bytes ? resolve(cwd, opts.bytes) : null);
149
+ const { marks, problems } = await verifyMarkSet(markSet, records, read);
150
+ if (problems.length) {
151
+ throw new Error(`mark set ${markSet.$id} refused:\n - ${problems.join('\n - ')}`);
152
+ }
153
+ writeMarkSet(resolve(cwd, opts.out), buildManifest(markSet, opts.markSet, marks), marks);
154
+ return { count: marks.length, out: resolve(cwd, opts.out) };
155
+ }
156
+
157
+ // Run as a CLI (including through node_modules/.bin's symlink), not on import from tests.
158
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
159
+ run(process.argv.slice(2)).then(
160
+ ({ count, out }) => console.log(`${count} mark(s) verified against their asset-bank records, written to ${out}`),
161
+ (err) => {
162
+ console.error(`luhtech-sync-mark-set failed: ${err.message}`);
163
+ process.exit(1);
164
+ },
165
+ );
166
+ }