@popcorn245/cornfield 0.39.0 → 0.40.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/core/config.js CHANGED
@@ -28,6 +28,7 @@
28
28
  * links: [], // [{ label, href }] shown in the explorer's header
29
29
  * theme: {}, // { css, fonts, fontHosts, names, default, icons, pixelated, contrast }: a repo's own look, CSS only (docs/config.md#theme)
30
30
  * brand: {}, // { logo, wordmark, favicon, appName, color, background }: a repo's own logo and name, images from the repo (docs/config.md#brand)
31
+ * layers: {}, // { add: [{ key, label, desc?, match }], off: [keys], order: [keys] }: a repo's own layers in the Layers menu, as data (docs/config.md#layers)
31
32
  * strings: {}, // { approve: 'Ship it', … }: a repo's own words for the visible labels, plain text (core/strings.js, docs/theming.md#words)
32
33
  * proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
33
34
  * importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
@@ -46,6 +47,7 @@ import { pathToFileURL, fileURLToPath } from 'node:url';
46
47
  import { themeProblems } from './theme.js';
47
48
  import { brandProblems } from './brand.js';
48
49
  import { stringsProblems } from './strings.js';
50
+ import { layersProblems, clientLayers } from './layers.js';
49
51
  import { PROFILE_SOURCE, MAX_NUMBER, MAX_BRIEF_CHARS, RUN_KINDS, TRIGGER_EVENTS, CREDENTIAL_VALUE_SOURCE } from './agent-contract.js';
50
52
 
51
53
  export { TRIGGER_EVENTS };
@@ -173,6 +175,7 @@ export const DEFAULTS = Object.freeze({
173
175
  theme: { css: null, fonts: [], fontHosts: [], names: {}, default: null, icons: {}, pixelated: false, contrast: 'error' },
174
176
  brand: { logo: null, wordmark: null, favicon: null, appName: null, color: null, background: null },
175
177
  strings: {},
178
+ layers: { add: [], off: [], order: [] },
176
179
  proxy: {},
177
180
  importMap: {},
178
181
  dataDir: null,
@@ -365,6 +368,7 @@ export function configProblems(c) {
365
368
  out.push(...themeProblems(c.theme));
366
369
  out.push(...brandProblems(c.brand));
367
370
  out.push(...stringsProblems(c.strings));
371
+ out.push(...layersProblems(c.layers));
368
372
  if (c.proxy !== undefined) {
369
373
  if (!isObject(c.proxy)) out.push('"proxy" is { "/path/": "http://upstream" }.');
370
374
  else for (const [p, t] of Object.entries(c.proxy)) {
@@ -554,6 +558,7 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
554
558
  config.theme = { ...structuredClone(DEFAULTS.theme), ...(raw.theme || {}) };
555
559
  config.brand = { ...DEFAULTS.brand, ...(raw.brand || {}) };
556
560
  config.strings = { ...(raw.strings || {}) };
561
+ config.layers = clientLayers(raw.layers); // checked above: only the known keys, as plain data
557
562
  // `threads: false` stays false; an object is read over the default
558
563
  config.threads = raw.threads === false ? false : { ...DEFAULTS.threads, ...(raw.threads || {}) };
559
564
  // `hookPoll: false` is `{ specs: false }`; an object is read over the default
package/core/contrast.js CHANGED
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
24
24
  import { MAX_MIX_DEPTH, readColor, over, toHex, luminance, ratio, splitTop } from './color.js';
25
25
  import { MAX_THEME_BYTES, cssProblems, withoutComments } from './theme.js';
26
26
  import { NODE_THEMES } from './schema.js';
27
+ import { LAYER_KEY_RE, MAX_KEY, parseKindToken } from './layers.js';
27
28
  import { DIFF_MARK_COLORS, DIFF_LABEL_ALPHA, markOpacity } from '../explorer/diff-marks.js';
28
29
  import { lightColor } from '../explorer/theme-model.js';
29
30
 
@@ -516,7 +517,7 @@ function worstOnGrounds(c, grounds) {
516
517
  * the fill and the ground; the label colour against the ground and against its halo. Always the same findings in the same order
517
518
  * (checkSheets lines the two system settings up by position).
518
519
  */
519
- function mapFindings(props, theme, mode, grounds) {
520
+ function mapFindings(props, theme, mode, grounds, extra = []) {
520
521
  const out = [];
521
522
  if (!grounds.length) return out;
522
523
  const base = { theme, mode };
@@ -553,6 +554,23 @@ function mapFindings(props, theme, mode, grounds) {
553
554
  out.push({ ...base, fg: '--corn-map-stroke', bg: weakest.on, min: MAP_FILL_MIN, kind: 'ui', use: `the outline that carries the fill of ${anOf(label)} ${label} node, which is ${fmt(f.ratio)} on its own`, fgValue: onGround.fgValue, bgValue: weakest.value, ratio: weakest.r });
554
555
  }
555
556
  }
557
+ // The tokens a theme sets for a finer kind (`--corn-map-kind-<type>-<kind>`) and a project layer (`--corn-map-group-<key>`): the same fill
558
+ // check, for each one the theme sets (an `auto` one draws the type's own colour, which is checked above)
559
+ for (const name of extra) {
560
+ const t = mapToken(props, name);
561
+ if (t.auto) continue;
562
+ const kind = parseKindToken(name);
563
+ const what = kind ? `the fill of ${anOf(kind.type)} ${kind.type} node of the kind "${kind.kind}"` : `the fill of a node in the "${name.slice('--corn-map-group-'.length)}" layer`;
564
+ if (t.problem) { out.push({ ...base, fg: name, bg: GROUND, min: MAP_FILL_MIN, kind: 'ui', use: what, problem: t.problem }); continue; }
565
+ const f = worstOnGrounds(t.color, grounds);
566
+ const finding = { ...base, fg: name, bg: GROUND, min: MAP_FILL_MIN, kind: 'ui', use: what, fgValue: f.fgValue, bgValue: f.bgValue, ratio: f.ratio, ...(f.image ? { groundImage: true } : {}) };
567
+ if (f.ratio >= MAP_FILL_MIN) { out.push(finding); continue; }
568
+ if (!strokeOn) { out.push({ ...finding, use: `${what}; set --corn-map-stroke, an outline at ${MAP_FILL_MIN}:1 on the fill and on the ground, or a deeper fill` }); continue; }
569
+ const onGround = worstOnGrounds(stroke.color, grounds);
570
+ const onFill = ratio(luminance(over(stroke.color, over(t.color, ground))), luminance(over(t.color, ground)));
571
+ const weakest = onGround.ratio <= onFill ? { r: onGround.ratio, on: '--corn-ground', value: onGround.bgValue } : { r: onFill, on: name, value: toHex(over(t.color, ground)) };
572
+ out.push({ ...base, fg: '--corn-map-stroke', bg: weakest.on, min: MAP_FILL_MIN, kind: 'ui', use: `the outline that carries ${what}, which is ${fmt(f.ratio)} on its own`, fgValue: onGround.fgValue, bgValue: weakest.value, ratio: weakest.r });
573
+ }
556
574
  // Labels are text: the colour against the ground, and against the halo under it (the halo is the ground's own colour at `auto`)
557
575
  const label = mapToken(props, '--corn-map-label');
558
576
  const haloTok = mapToken(props, '--corn-map-label-halo');
@@ -573,7 +591,7 @@ function mapFindings(props, theme, mode, grounds) {
573
591
  }
574
592
 
575
593
  /** Pair results for one page state: one per pair, the worst over the ground and the ground image */
576
- function checkState(props, theme, mode) {
594
+ function checkState(props, theme, mode, extra = []) {
577
595
  const out = [];
578
596
  const canvas = mode === 'dark' ? [0, 0, 0, 1] : [255, 255, 255, 1];
579
597
  const cache = new Map();
@@ -601,7 +619,7 @@ function checkState(props, theme, mode) {
601
619
  const { image, ...rest } = worst;
602
620
  out.push({ ...finding, ...rest, ...(image ? { groundImage: true } : {}) });
603
621
  }
604
- out.push(...mapFindings(props, theme, mode, grounds)); // the map's node fills and labels (their block above)
622
+ out.push(...mapFindings(props, theme, mode, grounds, extra)); // the map's node fills and labels (their block above)
605
623
  out.push(...diffMapFindings(props, theme, mode, grounds, isColor(g) ? over(g, canvas) : null));
606
624
  return out;
607
625
  }
@@ -671,12 +689,14 @@ function diffMapFindings(props, theme, mode, grounds, base) {
671
689
  export function checkSheets(themes) {
672
690
  const out = [];
673
691
  for (const { theme, sheets, name } of themes) {
692
+ const extra = mapExtraTokens(sheets);
674
693
  for (const mode of ['light', 'dark']) {
675
694
  const other = mode === 'light' ? 'dark' : 'light';
676
- const same = checkState(resolveProps(sheets, { mode, system: mode, name }), theme, mode);
677
- const flipped = checkState(resolveProps(sheets, { mode, system: other, name }), theme, mode);
695
+ const same = checkState(resolveProps(sheets, { mode, system: mode, name }), theme, mode, extra);
696
+ const flipped = checkState(resolveProps(sheets, { mode, system: other, name }), theme, mode, extra);
678
697
  same.forEach((f, i) => {
679
- const g = flipped[i];
698
+ // The same findings in the same order, but for a kind or layer token that is `auto` on one system setting only: then by what it is about
699
+ const g = flipped.length === same.length ? flipped[i] : flipped.find((x) => x.fg === f.fg && x.bg === f.bg && x.use === f.use) || f;
680
700
  const worse = (f.problem === undefined && g.problem !== undefined) || (f.ratio !== undefined && g.ratio !== undefined && g.ratio < f.ratio && g.ratio < g.min && f.ratio >= f.min);
681
701
  out.push(worse ? { ...g, system: other } : f);
682
702
  });
@@ -685,6 +705,27 @@ export function checkSheets(themes) {
685
705
  return out;
686
706
  }
687
707
 
708
+ /** Every custom property a stylesheet declares, anywhere in it, once each */
709
+ export function declaredProps(sheets) {
710
+ const names = new Set();
711
+ for (const css of sheets) for (const rule of parseRules(css)) for (const d of rule.decls) names.add(d.name);
712
+ return names;
713
+ }
714
+
715
+ /** The groups the standard tokens have (a type's own, and cloud, web and the house): any other `--corn-map-group-*` is a project layer's */
716
+ const BUILTIN_GROUPS = new Set([...Object.keys(NODE_THEMES), 'cloud', 'web', 'house']);
717
+
718
+ /** A project layer's group token: `--corn-map-group-<key>` with a key that passes the layer-key pattern and is not a starting group */
719
+ export function projectGroupOf(name) {
720
+ const m = /^--corn-map-group-(.+)$/.exec(name);
721
+ return m && m[1].length <= MAX_KEY && LAYER_KEY_RE.test(m[1]) && !BUILTIN_GROUPS.has(m[1]) ? m[1] : null;
722
+ }
723
+
724
+ /** The kind and project-layer fill tokens a theme's stylesheets set (spec 0009 D6), sorted: what the contrast check reads besides the fixed list */
725
+ export function mapExtraTokens(sheets) {
726
+ return [...declaredProps(sheets)].filter((n) => parseKindToken(n) || projectGroupOf(n)).sort();
727
+ }
728
+
688
729
  /** The pairs under their minimum: { fails, unresolved } */
689
730
  export function contrastProblems(themes) {
690
731
  const all = checkSheets(themes);
package/core/layers.js ADDED
@@ -0,0 +1,412 @@
1
+ /**
2
+ * @module core/layers
3
+ *
4
+ * The Layers menu's rows as data (spec 0009): the starting layers cornfield ships, the project layers a repo adds in
5
+ * `cornfield.config.js` (`layers: { add, off, order }`), the matcher that says which layer a node is in, the checks `cornfield validate`
6
+ * and the config load make, and the letters a finer `kind` shows on the map.
7
+ *
8
+ * `match` is DATA, never code: the fixed keys `type`, `kind`, `parent` and `field`, whose values are text, numbers, true or false (or a
9
+ * short list of them), compared exactly. No pattern, no function, no template. A layer's key is checked against a strict pattern before it
10
+ * can reach a CSS custom property name or a `data-corn` value; its label and description are text, escaped wherever they reach the page.
11
+ *
12
+ * Pure, no imports but the schema's node table: the CLI, the server and the browser (core/ is served to it) all read this one file.
13
+ */
14
+
15
+ import { NODE_THEMES } from './schema.js';
16
+
17
+ /** A layer key: lower-case words joined by "-" (letters and digits), at most 32 characters. The only way in to a token name or a `data-corn` value */
18
+ export const LAYER_KEY_RE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
19
+ export const MAX_KEY = 32;
20
+ export const MAX_LAYERS = 24;
21
+ export const MAX_LABEL = 40;
22
+ export const MAX_DESC = 120;
23
+ /** The most values in a list of a match, the most field names a match tests, the longest text value */
24
+ export const MAX_LIST = 20;
25
+ export const MAX_FIELDS = 4;
26
+ export const MAX_VALUE = 80;
27
+ /** The keys of a project layer, and of its `match` */
28
+ export const LAYER_KEYS = Object.freeze(['key', 'label', 'desc', 'match']);
29
+ export const MATCH_KEYS = Object.freeze(['type', 'kind', 'parent', 'field']);
30
+ /** The keys of `layers` */
31
+ export const LAYERS_KEYS = Object.freeze(['add', 'off', 'order']);
32
+ /** A field name: letters, digits and `_`, starting with a letter */
33
+ export const FIELD_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
34
+ /** Node types a layer key may not be, though no starting layer has them as a key */
35
+ const RESERVED = Object.freeze(['root', 'external', 'floor', 'room']);
36
+
37
+ /**
38
+ * The starting layers, in the menu's usual order, each as an entry of the shape a project layer has. `match` is what puts a node in it
39
+ * (null: the layer holds no nodes of its own). `live` rows draw or place from the live layer; `overlay` rows are marks over the map, not layers.
40
+ * A node no entry takes is in a row of its own type (layers.js adds the row), and the root is in none.
41
+ */
42
+ export const STARTING_LAYERS = Object.freeze([
43
+ { key: 'app', label: 'Apps', desc: 'Subdomains', match: { type: 'app' } },
44
+ { key: 'pkg', label: 'Packages', desc: 'Libraries', match: { type: 'pkg' } },
45
+ { key: 'page', label: 'Pages & Routes', desc: 'Routes', match: { type: 'page' } },
46
+ { key: 'atom', label: 'Atoms', desc: 'Base Components', match: { type: 'atom' } },
47
+ { key: 'molecule', label: 'Molecules', desc: 'Composites', match: { type: 'molecule' } },
48
+ { key: 'token', label: 'Design Tokens', desc: 'Pollen CSS', match: { type: 'token' } },
49
+ { key: 'tool', label: 'Dev Tools', desc: 'Utilities', match: { type: 'tool' } },
50
+ { key: 'flow', label: 'Data Flow', desc: 'Tiers & sync', match: null },
51
+ { key: 'core', label: 'Core', desc: 'The shared core: what the apps and packages are built on. Shows with Packages or Atoms', match: { type: 'core' } },
52
+ { key: 'store', label: 'Stores', desc: 'Storage tiers and the ends of the data flows. Shows with Data Flow', match: { type: 'store' } },
53
+ { key: 'table', label: 'Tables', desc: 'SQLite tables, reads & writes', match: { type: 'table' } },
54
+ { key: 'rom', label: 'ROM', desc: 'Render on Mutation', match: { type: 'rom' } },
55
+ { key: 'service', label: 'Services', desc: 'API jobs, webhooks and hooks', match: { type: 'service' } },
56
+ // Cloud is every outside node that is not the public web (an external with another kind, or none, is Cloud: scene.js has always drawn it so)
57
+ { key: 'cloud', label: 'Cloud', desc: 'Services outside the house that we do not control: what runs, where software comes from, accounts (topology.cloud.json)', match: { type: 'external', kind: 'cloud' } },
58
+ { key: 'web', label: 'Public web', desc: 'Any public page or picture a person points us at: not cloud', match: { type: 'external', kind: 'web' } },
59
+ { key: 'stack', label: 'Infra', desc: 'Compose stacks and the domains they serve', match: { type: 'stack' } },
60
+ { key: 'machine', label: 'Machines', desc: 'The computers the code runs on, placed in their room from the inventory (live)', match: { type: 'machine' }, live: true },
61
+ { key: 'container', label: 'Containers', desc: 'One service of a stack, from its compose file', match: { type: 'container' } },
62
+ { key: 'device', label: 'Devices', desc: 'Cameras, and live: phones, NFC tags, Home Assistant devices', match: { type: 'device' }, live: true },
63
+ { key: 'house', label: 'House', desc: 'Floors and rooms (live)', match: { type: ['floor', 'room'] }, live: true },
64
+ { key: 'runs', label: 'Runs in flight', desc: 'A pulsing ring on the nodes an open agent run is changing; a dashed ring and a warning where two runs change the same node', match: null, overlay: true },
65
+ { key: 'persona', label: 'People', desc: 'Personas, with a live count of their accounts (never a name)', match: { type: 'persona' }, live: true },
66
+ ]);
67
+
68
+ export const STARTING_KEYS = Object.freeze(STARTING_LAYERS.map((l) => l.key));
69
+ const STARTING_SET = new Set(STARTING_KEYS);
70
+ const NODE_TYPES = Object.keys(NODE_THEMES);
71
+
72
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
73
+ /** A line break or any other control character */
74
+ const CONTROL = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]');
75
+ const show = (v) => (typeof v === 'string' ? `"${v.length > 40 ? `${v.slice(0, 40)}…` : v}"` : typeof v === 'number' || typeof v === 'boolean' ? String(v) : Array.isArray(v) ? 'a list' : v === null ? 'null' : typeof v);
76
+ const scalar = (v) => (typeof v === 'string' && v.length > 0 && v.length <= MAX_VALUE && !CONTROL.test(v)) || (typeof v === 'number' && Number.isFinite(v)) || typeof v === 'boolean';
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Names a theme can reach: the tokens and icon keys of a kind and of a project layer (D6)
80
+ // ---------------------------------------------------------------------------
81
+
82
+ /** A kind as it is written in a token name or an icon key: lower-case words and digits joined by "-", at most 32 characters. A kind that is anything else has no token of its own (it is still a kind) */
83
+ export const KIND_NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
84
+ export const MAX_KIND_NAME = 32;
85
+ const TYPE_SET = new Set(NODE_TYPES);
86
+
87
+ /** `--corn-map-kind-<type>-<kind>`, or null when the type is not a node type or the kind cannot be a part of a name (types never hold a "-", so the name reads one way) */
88
+ export const mapKindToken = (type, kind) => (TYPE_SET.has(type) && typeof kind === 'string' && kind.length <= MAX_KIND_NAME && KIND_NAME_RE.test(kind) ? `--corn-map-kind-${type}-${kind}` : null);
89
+ /** `--corn-map-group-<key>` for a layer key that passes LAYER_KEY_RE, else null */
90
+ export const mapGroupToken = (key) => (typeof key === 'string' && key.length <= MAX_KEY && LAYER_KEY_RE.test(key) ? `--corn-map-group-${key}` : null);
91
+ /** Reads a kind token's name back: `{ type, kind }`, or null (the type is the part before the first "-") */
92
+ export function parseKindToken(name) {
93
+ const m = /^--corn-map-kind-([a-z]+)-([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(String(name));
94
+ return m && TYPE_SET.has(m[1]) && m[2].length <= MAX_KIND_NAME ? { type: m[1], kind: m[2] } : null;
95
+ }
96
+
97
+ /**
98
+ * What a `theme.icons` key names: a node type (`"service"`), a finer kind of one (`"service:timer"`) or a project layer (`"layer:timers"`).
99
+ * Null when it is none of them. Whether the kind is on the map or the layer in the config is a warning, not a shape.
100
+ * @param {unknown} key
101
+ * @returns {{ type: string } | { type: string, kind: string } | { layer: string } | null}
102
+ */
103
+ export function iconKeyShape(key) {
104
+ if (typeof key !== 'string') return null;
105
+ if (TYPE_SET.has(key)) return { type: key };
106
+ const i = key.indexOf(':');
107
+ if (i < 0) return null;
108
+ const head = key.slice(0, i);
109
+ const tail = key.slice(i + 1);
110
+ if (head === 'layer') return LAYER_KEY_RE.test(tail) && tail.length <= MAX_KEY ? { layer: tail } : null;
111
+ return TYPE_SET.has(head) && KIND_NAME_RE.test(tail) && tail.length <= MAX_KIND_NAME ? { type: head, kind: tail } : null;
112
+ }
113
+
114
+ /** The icon keys to try for a node, most specific first: its kind, its project layer, its type (D6) */
115
+ export function iconKeysFor(type, kind, layer) {
116
+ const out = [];
117
+ if (typeof kind === 'string' && KIND_NAME_RE.test(kind) && kind.length <= MAX_KIND_NAME) out.push(`${type}:${kind}`);
118
+ if (layer) out.push(`layer:${layer}`);
119
+ out.push(type);
120
+ return out;
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // Which layer a node is in
125
+ // ---------------------------------------------------------------------------
126
+
127
+ /** The edges' ownership line as a map: child id to parent id (an edge with no kind that is not dashed; the first one wins, as layout.js reads it) */
128
+ const parentMemo = new WeakMap();
129
+ export function parentIndex(edges) {
130
+ const hit = parentMemo.get(edges);
131
+ if (hit && hit.length === edges.length) return hit.map;
132
+ const map = new Map();
133
+ for (const e of edges) if (e && !e.dashed && !e.kind && e.from && e.to && e.from !== e.to && !map.has(e.to)) map.set(e.to, e.from);
134
+ parentMemo.set(edges, { length: edges.length, map });
135
+ return map;
136
+ }
137
+
138
+ const oneOf = (want, got) => (Array.isArray(want) ? want.includes(got) : want === got);
139
+
140
+ /**
141
+ * Whether `node` meets `match`: within a key any value, across keys all. A node without the field does not meet it; a field that holds a
142
+ * list meets it when it holds one of the values. Pure: `parentOf(node)` says the id of its owner (only asked when the match has `parent`).
143
+ * @param {object | null | undefined} match
144
+ * @param {object} node
145
+ * @param {(node: object) => string | undefined} [parentOf]
146
+ */
147
+ export function meets(match, node, parentOf) {
148
+ if (!isObject(match)) return false;
149
+ let any = false;
150
+ if (match.type !== undefined) { any = true; if (!oneOf(match.type, node.type)) return false; }
151
+ if (match.kind !== undefined) { any = true; if (!oneOf(match.kind, node.kind)) return false; }
152
+ if (match.parent !== undefined) { any = true; if (!parentOf || !oneOf(match.parent, parentOf(node))) return false; }
153
+ if (match.field !== undefined) {
154
+ any = true;
155
+ for (const name of Object.keys(match.field)) {
156
+ if (!Object.hasOwn(node, name)) return false;
157
+ const have = node[name];
158
+ const want = match.field[name];
159
+ const ok = Array.isArray(have) ? have.some((h) => oneOf(want, h)) : oneOf(want, have);
160
+ if (!ok) return false;
161
+ }
162
+ }
163
+ return any;
164
+ }
165
+
166
+ /** The starting layers that hold nodes, the more specific (with a `kind`) first, so the public web is taken before Cloud */
167
+ const BY_SPECIFICITY = [...STARTING_LAYERS.filter((l) => l.match)].sort((a, b) => Number('kind' in b.match) - Number('kind' in a.match));
168
+
169
+ /** The key of the starting layer `node` is in: Cloud for any outside node that is not the public web, House for floors and rooms, else its type's row. The root has none (null) */
170
+ export function startingLayerOf(node) {
171
+ if (node.type === 'root') return null;
172
+ if (node.type === 'external') return node.kind === 'web' ? 'web' : 'cloud';
173
+ for (const l of BY_SPECIFICITY) if (meets(l.match, node)) return l.key;
174
+ return node.type;
175
+ }
176
+
177
+ /**
178
+ * The key of the first project layer in `add` whose match the node meets, or null (D3: a node is in exactly one layer; the first project
179
+ * layer that takes it, else its starting layer).
180
+ * @param {object[]} add the project layers
181
+ * @param {object} node
182
+ * @param {(node: object) => string | undefined} [parentOf]
183
+ */
184
+ export function projectLayerOf(add, node, parentOf) {
185
+ if (!add || !add.length || node.type === 'root') return null;
186
+ for (const l of add) if (meets(l.match, node, parentOf)) return l.key;
187
+ return null;
188
+ }
189
+
190
+ /** The row a node is under: its project layer, else its starting layer (null for the root) */
191
+ export const layerKeyOf = (add, node, parentOf) => projectLayerOf(add, node, parentOf) || startingLayerOf(node);
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // The checks (D4)
195
+ // ---------------------------------------------------------------------------
196
+
197
+ const typeHint = `${NODE_TYPES.slice(0, 5).join(', ')}, …`;
198
+ const IN_LAYER_LIST = (add) => {
199
+ const keys = (Array.isArray(add) ? add : []).map((l) => (isObject(l) && typeof l.key === 'string' ? l.key : null)).filter((k) => k && LAYER_KEY_RE.test(k));
200
+ return `${STARTING_KEYS.slice(0, 3).join(', ')}, …${keys.length ? `, ${keys[keys.length - 1]}` : ''}`;
201
+ };
202
+
203
+ function valueProblems(where, name, v, out) {
204
+ if (Array.isArray(v)) {
205
+ if (!v.length) out.push(`${where}.${name} is an empty list: give at least one value, or leave the key out.`);
206
+ else if (v.length > MAX_LIST) out.push(`${where}.${name} has ${v.length} values: at most ${MAX_LIST}.`);
207
+ return v.length <= MAX_LIST ? v : [];
208
+ }
209
+ return [v];
210
+ }
211
+
212
+ function matchProblems(w, match, out) {
213
+ if (!isObject(match)) { out.push(`${w}.match is { type, kind, parent, field }: say at least one of them.`); return; }
214
+ for (const k of Object.keys(match)) {
215
+ if (!MATCH_KEYS.includes(k)) out.push(`${w}.match has unknown key "${k}": known: ${MATCH_KEYS.join(', ')}. A match is data: no pattern, no function.`);
216
+ }
217
+ if (!Object.keys(match).some((k) => MATCH_KEYS.includes(k))) {
218
+ if (!Object.keys(match).length) out.push(`${w}.match is empty: say at least one of ${MATCH_KEYS.join(', ')}.`);
219
+ return;
220
+ }
221
+ if ('type' in match) {
222
+ for (const t of valueProblems(`${w}.match`, 'type', match.type, out)) {
223
+ if (typeof t !== 'string' || !NODE_TYPES.includes(t)) out.push(`${w}.match.type ${show(t)} is not a node type (${typeHint}).`);
224
+ }
225
+ }
226
+ if ('kind' in match) {
227
+ for (const k of valueProblems(`${w}.match`, 'kind', match.kind, out)) {
228
+ if (typeof k !== 'string' || !k || k.length > MAX_VALUE || CONTROL.test(k)) out.push(`${w}.match.kind ${show(k)}: a kind is text, one line, at most ${MAX_VALUE} characters.`);
229
+ }
230
+ }
231
+ if ('parent' in match) {
232
+ for (const p of valueProblems(`${w}.match`, 'parent', match.parent, out)) {
233
+ if (typeof p !== 'string' || !p || p.length > 200 || CONTROL.test(p)) out.push(`${w}.match.parent ${show(p)}: a parent is a node id (text), like "pkg-core".`);
234
+ }
235
+ }
236
+ if ('field' in match) {
237
+ const f = match.field;
238
+ if (!isObject(f)) { out.push(`${w}.match.field is { name: value }: a node field and the value (or list of values) it must have.`); return; }
239
+ const names = Object.keys(f);
240
+ if (!names.length) out.push(`${w}.match.field is empty: name a field, like { audience: 'household' }.`);
241
+ if (names.length > MAX_FIELDS) out.push(`${w}.match.field names ${names.length} fields: at most ${MAX_FIELDS}.`);
242
+ for (const name of names.slice(0, 20)) {
243
+ if (!FIELD_NAME_RE.test(name) || name.length > 40) { out.push(`${w}.match.field "${name.slice(0, 40)}": a field name is letters, digits and "_", starting with a letter.`); continue; }
244
+ if (['type', 'kind', 'parent'].includes(name)) { out.push(`${w}.match.field.${name}: use the match key "${name}" itself, not a field.`); continue; }
245
+ const values = Array.isArray(f[name]) ? f[name] : [f[name]];
246
+ if (Array.isArray(f[name]) && (!values.length || values.length > MAX_LIST)) out.push(`${w}.match.field.${name} is a list of ${values.length}: one to ${MAX_LIST} values.`);
247
+ else if (!values.every(scalar)) out.push(`${w}.match.field.${name}: a value is text, a number, true or false, or a list of them.`);
248
+ }
249
+ }
250
+ }
251
+
252
+ /**
253
+ * What is wrong with `layers` (as the config file wrote it), one line each, naming the key and what would be right. Pure: nothing about the map.
254
+ * @param {unknown} layers
255
+ * @returns {string[]}
256
+ */
257
+ export function layersProblems(layers) {
258
+ if (layers === undefined) return [];
259
+ if (!isObject(layers)) return ['"layers" is an object: { add: [{ key, label, match }], off: [keys], order: [keys] }.'];
260
+ const out = [];
261
+ for (const k of Object.keys(layers)) if (!LAYERS_KEYS.includes(k)) out.push(`layers has unknown key "${k}": known: ${LAYERS_KEYS.join(', ')}.`);
262
+ const add = layers.add;
263
+ if (add !== undefined && !Array.isArray(add)) out.push('layers.add is a list of project layers: [{ key, label, desc?, match }].');
264
+ const list = Array.isArray(add) ? add : [];
265
+ if (list.length > MAX_LAYERS) out.push(`layers.add has ${list.length} layers: at most ${MAX_LAYERS}.`);
266
+ const seen = new Map();
267
+ list.slice(0, 100).forEach((l, i) => {
268
+ const w = `layers.add[${i}]`;
269
+ if (!isObject(l)) { out.push(`${w} is { key, label, desc?, match }.`); return; }
270
+ for (const k of Object.keys(l)) {
271
+ if (LAYER_KEYS.includes(k)) continue;
272
+ const why = /^colou?r$|^icon$|^fill$/i.test(k) ? ' Colours and icons are the theme\'s.' : k === 'on' || k === 'hide' ? ' Whether a layer starts off is layers.off.' : '';
273
+ out.push(`${w} has unknown key "${k}": known: ${LAYER_KEYS.join(', ')}.${why}`);
274
+ }
275
+ const key = l.key;
276
+ if (typeof key !== 'string') out.push(`${w}.key is required: lower-case words joined by "-", like "edge-stack".`);
277
+ else if (STARTING_SET.has(key)) out.push(`${w}.key ${show(key)} is a starting layer: pick another key.`);
278
+ else if (RESERVED.includes(key)) out.push(`${w}.key ${show(key)} is reserved (a node type): pick another key.`);
279
+ else if (!LAYER_KEY_RE.test(key) || key.length > MAX_KEY) out.push(`${w}.key ${show(key)}: lower-case words joined by "-", like "edge-stack"${key.length > MAX_KEY ? `, at most ${MAX_KEY} characters` : ''}.`);
280
+ else if (seen.has(key)) out.push(`${w}.key ${show(key)} is also layers.add[${seen.get(key)}].key: a key is used once.`);
281
+ else seen.set(key, i);
282
+ const textProblem = (name, max, needed) => {
283
+ const v = l[name];
284
+ if (v === undefined) { if (needed) out.push(`${w}.${name} is required: plain text, one line, at most ${max} characters.`); return; }
285
+ if (typeof v !== 'string' || !v.trim()) out.push(`${w}.${name} ${show(v)}: plain text, one line, at most ${max} characters.`);
286
+ else if (CONTROL.test(v)) out.push(`${w}.${name}: one line of plain text (no line break or control character).`);
287
+ else if ([...v].length > max) out.push(`${w}.${name} is ${[...v].length} characters: at most ${max}.`);
288
+ };
289
+ textProblem('label', MAX_LABEL, true);
290
+ textProblem('desc', MAX_DESC, false);
291
+ if (l.match === undefined) out.push(`${w}.match is required: say at least one of ${MATCH_KEYS.join(', ')}.`);
292
+ else matchProblems(w, l.match, out);
293
+ });
294
+ const known = new Set([...STARTING_KEYS, ...list.map((l) => (isObject(l) && typeof l.key === 'string' ? l.key : null)).filter(Boolean)]);
295
+ for (const name of ['off', 'order']) {
296
+ const v = layers[name];
297
+ if (v === undefined) continue;
298
+ if (!Array.isArray(v)) { out.push(`layers.${name} is a list of layer keys: ['${name === 'off' ? 'timers' : 'app'}', …].`); continue; }
299
+ const dup = new Set();
300
+ v.forEach((k) => {
301
+ if (typeof k !== 'string' || !known.has(k)) out.push(`layers.${name} ${show(k)} is not a layer (${IN_LAYER_LIST(add)}).`);
302
+ else if (dup.has(k)) out.push(`layers.${name} ${show(k)} is listed twice.`);
303
+ dup.add(k);
304
+ });
305
+ }
306
+ return out;
307
+ }
308
+
309
+ /**
310
+ * The layers the browser is sent: only what passed (`layersProblems` empty, else nothing), copied to plain data of the known keys, so a hostile
311
+ * value never travels.
312
+ * @param {unknown} layers
313
+ * @returns {{ add: { key: string, label: string, desc?: string, match: object }[], off: string[], order: string[] }}
314
+ */
315
+ export function clientLayers(layers) {
316
+ const none = { add: [], off: [], order: [] };
317
+ if (!isObject(layers) || layersProblems(layers).length) return none;
318
+ const copy = (v) => (Array.isArray(v) ? v.slice(0, MAX_LIST) : v);
319
+ const add = (layers.add || []).map((l) => {
320
+ const m = l.match;
321
+ const match = {};
322
+ if (m.type !== undefined) match.type = copy(m.type);
323
+ if (m.kind !== undefined) match.kind = copy(m.kind);
324
+ if (m.parent !== undefined) match.parent = copy(m.parent);
325
+ if (m.field !== undefined) match.field = Object.fromEntries(Object.keys(m.field).map((k) => [k, copy(m.field[k])]));
326
+ const out = { key: l.key, label: l.label.trim(), match };
327
+ if (typeof l.desc === 'string' && l.desc.trim()) out.desc = l.desc.trim();
328
+ return out;
329
+ });
330
+ return { add, off: [...(layers.off || [])], order: [...(layers.order || [])] };
331
+ }
332
+
333
+ /**
334
+ * What `validate` says about the layers against the map (a warning, never a failure): a project layer that matches no node, and one whose
335
+ * every node an earlier layer took.
336
+ * @param {{ add?: object[] }} layers the client form (`clientLayers`)
337
+ * @param {{ nodes: object[], edges?: object[] }} map
338
+ * @returns {string[]}
339
+ */
340
+ export function layersMapWarnings(layers, map) {
341
+ const add = (layers && layers.add) || [];
342
+ if (!add.length) return [];
343
+ const parentOf = (n) => parentIndex(map.edges || []).get(n.id);
344
+ const out = [];
345
+ const taken = new Map(add.map((l) => [l.key, 0]));
346
+ const met = new Map(add.map((l) => [l.key, 0]));
347
+ for (const n of map.nodes) {
348
+ if (n.type === 'root') continue;
349
+ for (const l of add) if (meets(l.match, n, parentOf)) met.set(l.key, met.get(l.key) + 1);
350
+ const k = projectLayerOf(add, n, parentOf);
351
+ if (k) taken.set(k, taken.get(k) + 1);
352
+ }
353
+ add.forEach((l, i) => {
354
+ if (!met.get(l.key)) out.push(`layers.add[${i}] "${l.key}" matches no node on the map: its row will not show.`);
355
+ else if (!taken.get(l.key)) out.push(`layers.add[${i}] "${l.key}" takes no node: every node it matches is taken by an earlier layer.`);
356
+ });
357
+ return out;
358
+ }
359
+
360
+ // ---------------------------------------------------------------------------
361
+ // The order of the rows (D8)
362
+ // ---------------------------------------------------------------------------
363
+
364
+ /**
365
+ * The rows in menu order: `order` first, then the project layers in `add` order, then the starting layers in their usual order, then any
366
+ * `extra` rows (a node type none covers). The overlays are not in this list: the menu draws them under their own heading.
367
+ * @template {{ key: string }} R
368
+ * @param {R[]} project the project layers' rows
369
+ * @param {R[]} starting the starting layers' rows (no overlays)
370
+ * @param {string[]} [order]
371
+ * @returns {R[]}
372
+ */
373
+ export function orderRows(project, starting, order = []) {
374
+ const all = [...project, ...starting];
375
+ const byKey = new Map(all.map((r) => [r.key, r]));
376
+ const first = [];
377
+ for (const k of order) { const r = byKey.get(k); if (r && !first.includes(r)) first.push(r); }
378
+ return [...first, ...all.filter((r) => !first.includes(r))];
379
+ }
380
+
381
+ // ---------------------------------------------------------------------------
382
+ // Finer kinds (D5)
383
+ // ---------------------------------------------------------------------------
384
+
385
+ /**
386
+ * The letters each finer kind shows in its node's core: the shortest start of the kind's name (one or two letters) that no other kind of
387
+ * the same node type on the map shares; when two letters are still shared, the first two. A kind is any text: nothing here is an error.
388
+ * @param {{ type: string, kind?: unknown }[]} nodes
389
+ * @returns {Map<string, Map<string, string>>} node type to kind to letters
390
+ */
391
+ export function kindLetters(nodes) {
392
+ const byType = new Map();
393
+ for (const n of nodes) {
394
+ if (typeof n.kind !== 'string' || !n.kind) continue;
395
+ if (!byType.has(n.type)) byType.set(n.type, new Set());
396
+ byType.get(n.type).add(n.kind);
397
+ }
398
+ const out = new Map();
399
+ for (const [type, kinds] of byType) {
400
+ const names = [...kinds].sort();
401
+ // Only the first two characters of a name are ever compared: read those once (a kind is the map's data, and may be long)
402
+ const heads = names.map((k) => [...k.slice(0, 4).toLowerCase()].slice(0, 2));
403
+ const m = new Map();
404
+ names.forEach((k, i) => {
405
+ const one = heads[i][0];
406
+ const shared = heads.some((h, j) => j !== i && h[0] === one);
407
+ m.set(k, shared ? heads[i].join('') : one);
408
+ });
409
+ out.set(type, m);
410
+ }
411
+ return out;
412
+ }
@@ -6,7 +6,8 @@
6
6
  * says so before the theme ships, as a warning naming the token, the theme, the level and what it may hold (docs/theming.md, The map).
7
7
  */
8
8
 
9
- import { expand, resolveProps, themesToCheck } from './contrast.js';
9
+ import { declaredProps, expand, projectGroupOf, resolveProps, themesToCheck } from './contrast.js';
10
+ import { iconKeyShape, parseKindToken } from './layers.js';
10
11
  import { EDGE_WIDTH_TOKEN, FONT_TOKEN, GLOW_TOKEN, MAX_EDGE_WIDTH, MAX_GLOW, readMapTokens } from '../explorer/map-style.js';
11
12
 
12
13
  const WANTS = {
@@ -41,3 +42,46 @@ export function mapTokenWarnings(config) {
41
42
  }
42
43
  return out;
43
44
  }
45
+
46
+ /**
47
+ * Warnings about a kind or a project layer a theme names that is not there (spec 0009 D6): a typo would otherwise do nothing, silently.
48
+ * - a `--corn-map-kind-<type>-<kind>` token for a kind no node of that type has on the map, or that is not shaped like one
49
+ * - a `--corn-map-group-<key>` token for a layer the config does not have (not a starting group either)
50
+ * - a `theme.icons` key `"<type>:<kind>"` for a kind not on the map, or `"layer:<key>"` for a layer not in the config
51
+ * Each warning names the token or icon key and what is on the map. Warnings, never errors: a theme may be shared between repos.
52
+ * @param {{ root: string, theme?: object, layers?: { add?: { key: string }[] } }} config
53
+ * @param {{ nodes: { type: string, kind?: unknown }[] } | null} map the committed map
54
+ * @returns {string[]}
55
+ */
56
+ export function layerTokenWarnings(config, map) {
57
+ const out = [];
58
+ const nodes = (map && map.nodes) || [];
59
+ const kinds = new Map();
60
+ for (const n of nodes) if (typeof n.kind === 'string' && n.kind) { if (!kinds.has(n.type)) kinds.set(n.type, new Set()); kinds.get(n.type).add(n.kind); }
61
+ const layers = new Set(((config.layers && config.layers.add) || []).map((l) => l.key));
62
+ const kindsOf = (type) => (kinds.has(type) ? [...kinds.get(type)].sort().slice(0, 8).join(', ') : 'none');
63
+ const layersWord = layers.size ? [...layers].join(', ') : 'none are in the config';
64
+ const typoOfKind = (type, kind) => `${type} kinds on the map: ${kindsOf(type)}`;
65
+ const themes = themesToCheck(config);
66
+ for (const { theme, sheets } of themes || []) {
67
+ const who = theme === 'standard' ? 'the standard theme' : `named theme "${theme}"`;
68
+ for (const name of [...declaredProps(sheets)].sort()) {
69
+ if (name.startsWith('--corn-map-kind-')) {
70
+ const k = parseKindToken(name);
71
+ if (!k) out.push(`theme: ${name} in ${who} is not a kind token: write --corn-map-kind-<node type>-<kind>, like --corn-map-kind-service-timer (lower-case words joined by "-").`);
72
+ else if (!kinds.has(k.type) || !kinds.get(k.type).has(k.kind)) out.push(`theme: ${name} in ${who} names a kind no ${k.type} on the map has (${typoOfKind(k.type, k.kind)}), so it paints nothing: check the spelling.`);
73
+ } else if (name.startsWith('--corn-map-group-')) {
74
+ const key = projectGroupOf(name);
75
+ if (name.slice('--corn-map-group-'.length) && key && !layers.has(key)) out.push(`theme: ${name} in ${who} names a layer the config does not have (project layers: ${layersWord}), so it paints nothing: check the spelling.`);
76
+ }
77
+ }
78
+ }
79
+ const icons = config.theme && config.theme.icons && typeof config.theme.icons === 'object' ? Object.keys(config.theme.icons) : [];
80
+ for (const key of icons) {
81
+ const shape = iconKeyShape(key);
82
+ if (!shape) continue; // refused by the config check
83
+ if ('layer' in shape && !layers.has(shape.layer)) out.push(`theme.icons "${key}" names a layer the config does not have (project layers: ${layersWord}), so it is never drawn: check the spelling.`);
84
+ else if ('kind' in shape && (!kinds.has(shape.type) || !kinds.get(shape.type).has(shape.kind))) out.push(`theme.icons "${key}" names a kind no ${shape.type} on the map has (${typoOfKind(shape.type, shape.kind)}), so it is never drawn: check the spelling.`);
85
+ }
86
+ return out;
87
+ }
package/core/strings.js CHANGED
@@ -14,6 +14,9 @@
14
14
  export const STRINGS = Object.freeze({
15
15
  // The header
16
16
  layers: 'Layers',
17
+ layersAll: 'All',
18
+ layersNone: 'None',
19
+ overlays: 'Overlays',
17
20
  dataFlow: 'Flow',
18
21
  house: 'House',
19
22
  proposals: 'Proposals',