@tanrei/mcp 0.0.0-stage → 0.1.0-next.1
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/LICENSE +202 -0
- package/NOTICE +57 -0
- package/README.md +150 -2
- package/bin/tanrei-mcp.js +15 -0
- package/dist/server.js +4515 -0
- package/dist/vocabulary/docs/governance/mimicry-gaps.json +666 -0
- package/dist/vocabulary/packages/tokens-build/generated/component-catalog.json +1825 -0
- package/dist/vocabulary/specs/accordion.spec.json +1 -0
- package/dist/vocabulary/specs/app-bar.spec.json +1 -0
- package/dist/vocabulary/specs/app-shell.spec.json +1 -0
- package/dist/vocabulary/specs/avatar.spec.json +1 -0
- package/dist/vocabulary/specs/badge.spec.json +1 -0
- package/dist/vocabulary/specs/bottom-sheet.spec.json +1 -0
- package/dist/vocabulary/specs/breadcrumbs.spec.json +1 -0
- package/dist/vocabulary/specs/button-group.spec.json +1 -0
- package/dist/vocabulary/specs/button-with-menu.spec.json +1 -0
- package/dist/vocabulary/specs/button.spec.json +1 -0
- package/dist/vocabulary/specs/calendar.spec.json +1 -0
- package/dist/vocabulary/specs/callout.spec.json +1 -0
- package/dist/vocabulary/specs/card.spec.json +1 -0
- package/dist/vocabulary/specs/carousel.spec.json +1 -0
- package/dist/vocabulary/specs/chat-composer.spec.json +1 -0
- package/dist/vocabulary/specs/checkbox-group.spec.json +1 -0
- package/dist/vocabulary/specs/checkbox.spec.json +1 -0
- package/dist/vocabulary/specs/chip-field.spec.json +1 -0
- package/dist/vocabulary/specs/chip.spec.json +1 -0
- package/dist/vocabulary/specs/code-block.spec.json +1 -0
- package/dist/vocabulary/specs/color-field.spec.json +1 -0
- package/dist/vocabulary/specs/color-input.spec.json +1 -0
- package/dist/vocabulary/specs/combobox-field.spec.json +1 -0
- package/dist/vocabulary/specs/combobox.spec.json +1 -0
- package/dist/vocabulary/specs/component.schema.json +1 -0
- package/dist/vocabulary/specs/copy-button.spec.json +1 -0
- package/dist/vocabulary/specs/date-time-picker.spec.json +1 -0
- package/dist/vocabulary/specs/description-list.spec.json +1 -0
- package/dist/vocabulary/specs/dialog.spec.json +1 -0
- package/dist/vocabulary/specs/divider.spec.json +1 -0
- package/dist/vocabulary/specs/drop-zone.spec.json +1 -0
- package/dist/vocabulary/specs/embedded-text-input.spec.json +1 -0
- package/dist/vocabulary/specs/empty-state.spec.json +1 -0
- package/dist/vocabulary/specs/fab-menu.spec.json +1 -0
- package/dist/vocabulary/specs/field-group.spec.json +1 -0
- package/dist/vocabulary/specs/field.spec.json +1 -0
- package/dist/vocabulary/specs/figure.spec.json +1 -0
- package/dist/vocabulary/specs/file-item.spec.json +1 -0
- package/dist/vocabulary/specs/file-picker.spec.json +1 -0
- package/dist/vocabulary/specs/file-upload.spec.json +1 -0
- package/dist/vocabulary/specs/handle.spec.json +1 -0
- package/dist/vocabulary/specs/image-preview.spec.json +1 -0
- package/dist/vocabulary/specs/inline-code.spec.json +1 -0
- package/dist/vocabulary/specs/inventory.json +1 -0
- package/dist/vocabulary/specs/keyboard-shortcut.spec.json +1 -0
- package/dist/vocabulary/specs/link-card.spec.json +1 -0
- package/dist/vocabulary/specs/link.spec.json +1 -0
- package/dist/vocabulary/specs/list-row.spec.json +1 -0
- package/dist/vocabulary/specs/list.spec.json +1 -0
- package/dist/vocabulary/specs/loading-indicator.spec.json +1 -0
- package/dist/vocabulary/specs/main-action-button.spec.json +1 -0
- package/dist/vocabulary/specs/marquee-text.spec.json +1 -0
- package/dist/vocabulary/specs/menu.spec.json +1 -0
- package/dist/vocabulary/specs/menubar.spec.json +1 -0
- package/dist/vocabulary/specs/meter.spec.json +1 -0
- package/dist/vocabulary/specs/modal-layer.spec.json +1 -0
- package/dist/vocabulary/specs/navigation-bar.spec.json +1 -0
- package/dist/vocabulary/specs/navigation-drawer.spec.json +1 -0
- package/dist/vocabulary/specs/number-field.spec.json +1 -0
- package/dist/vocabulary/specs/number-input.spec.json +1 -0
- package/dist/vocabulary/specs/number-ticker.spec.json +1 -0
- package/dist/vocabulary/specs/one-time-code-field.spec.json +1 -0
- package/dist/vocabulary/specs/one-time-code-input.spec.json +1 -0
- package/dist/vocabulary/specs/page-header.spec.json +1 -0
- package/dist/vocabulary/specs/pagination.spec.json +1 -0
- package/dist/vocabulary/specs/popover.spec.json +1 -0
- package/dist/vocabulary/specs/previous-next-links.spec.json +1 -0
- package/dist/vocabulary/specs/progress-indicator.spec.json +1 -0
- package/dist/vocabulary/specs/prose.spec.json +1 -0
- package/dist/vocabulary/specs/radio-button.spec.json +1 -0
- package/dist/vocabulary/specs/radio-group.spec.json +1 -0
- package/dist/vocabulary/specs/rating.spec.json +1 -0
- package/dist/vocabulary/specs/resizable-frame.spec.json +1 -0
- package/dist/vocabulary/specs/scroll-area.spec.json +1 -0
- package/dist/vocabulary/specs/search.spec.json +1 -0
- package/dist/vocabulary/specs/segmented-button.spec.json +1 -0
- package/dist/vocabulary/specs/select-field.spec.json +1 -0
- package/dist/vocabulary/specs/select.spec.json +1 -0
- package/dist/vocabulary/specs/side-sheet.spec.json +1 -0
- package/dist/vocabulary/specs/size-transition.spec.json +1 -0
- package/dist/vocabulary/specs/skeleton.spec.json +1 -0
- package/dist/vocabulary/specs/slider-field.spec.json +1 -0
- package/dist/vocabulary/specs/slider.spec.json +1 -0
- package/dist/vocabulary/specs/snackbar.spec.json +1 -0
- package/dist/vocabulary/specs/split-view.spec.json +1 -0
- package/dist/vocabulary/specs/stepper.spec.json +1 -0
- package/dist/vocabulary/specs/steps.spec.json +1 -0
- package/dist/vocabulary/specs/swatch.spec.json +1 -0
- package/dist/vocabulary/specs/switch.spec.json +1 -0
- package/dist/vocabulary/specs/tab-view.spec.json +1 -0
- package/dist/vocabulary/specs/table-of-contents.spec.json +1 -0
- package/dist/vocabulary/specs/table.spec.json +1 -0
- package/dist/vocabulary/specs/tabs.spec.json +1 -0
- package/dist/vocabulary/specs/tag-group.spec.json +1 -0
- package/dist/vocabulary/specs/tag.spec.json +1 -0
- package/dist/vocabulary/specs/text-field.spec.json +1 -0
- package/dist/vocabulary/specs/text-input.spec.json +1 -0
- package/dist/vocabulary/specs/timeline.spec.json +1 -0
- package/dist/vocabulary/specs/toolbar.spec.json +1 -0
- package/dist/vocabulary/specs/tooltip.spec.json +1 -0
- package/dist/vocabulary/specs/tree-view.spec.json +1 -0
- package/dist/vocabulary/tanrei.config.json +24 -0
- package/dist/vocabulary/tokens/comp/accordion.tokens.json +459 -0
- package/dist/vocabulary/tokens/comp/app-bar.tokens.json +308 -0
- package/dist/vocabulary/tokens/comp/app-shell.tokens.json +248 -0
- package/dist/vocabulary/tokens/comp/avatar.tokens.json +199 -0
- package/dist/vocabulary/tokens/comp/badge.tokens.json +101 -0
- package/dist/vocabulary/tokens/comp/bottom-sheet.tokens.json +326 -0
- package/dist/vocabulary/tokens/comp/breadcrumbs.tokens.json +253 -0
- package/dist/vocabulary/tokens/comp/button-group.tokens.json +140 -0
- package/dist/vocabulary/tokens/comp/button-with-menu.tokens.json +810 -0
- package/dist/vocabulary/tokens/comp/button.tokens.json +1355 -0
- package/dist/vocabulary/tokens/comp/calendar.tokens.json +500 -0
- package/dist/vocabulary/tokens/comp/callout.tokens.json +510 -0
- package/dist/vocabulary/tokens/comp/card.tokens.json +204 -0
- package/dist/vocabulary/tokens/comp/carousel.tokens.json +469 -0
- package/dist/vocabulary/tokens/comp/chat-composer.tokens.json +343 -0
- package/dist/vocabulary/tokens/comp/checkbox.tokens.json +587 -0
- package/dist/vocabulary/tokens/comp/chip.tokens.json +716 -0
- package/dist/vocabulary/tokens/comp/code-block.tokens.json +473 -0
- package/dist/vocabulary/tokens/comp/color-input.tokens.json +49 -0
- package/dist/vocabulary/tokens/comp/combobox.tokens.json +756 -0
- package/dist/vocabulary/tokens/comp/copy-button.tokens.json +56 -0
- package/dist/vocabulary/tokens/comp/date-time-picker.tokens.json +797 -0
- package/dist/vocabulary/tokens/comp/description-list.tokens.json +203 -0
- package/dist/vocabulary/tokens/comp/dialog.tokens.json +340 -0
- package/dist/vocabulary/tokens/comp/divider.tokens.json +139 -0
- package/dist/vocabulary/tokens/comp/drop-zone.tokens.json +151 -0
- package/dist/vocabulary/tokens/comp/embedded-text-input.tokens.json +103 -0
- package/dist/vocabulary/tokens/comp/empty-state.tokens.json +154 -0
- package/dist/vocabulary/tokens/comp/field-group.tokens.json +211 -0
- package/dist/vocabulary/tokens/comp/field.tokens.json +308 -0
- package/dist/vocabulary/tokens/comp/figure.tokens.json +269 -0
- package/dist/vocabulary/tokens/comp/file-item.tokens.json +445 -0
- package/dist/vocabulary/tokens/comp/file-picker.tokens.json +282 -0
- package/dist/vocabulary/tokens/comp/file-upload.tokens.json +30 -0
- package/dist/vocabulary/tokens/comp/handle.tokens.json +343 -0
- package/dist/vocabulary/tokens/comp/image-preview.tokens.json +327 -0
- package/dist/vocabulary/tokens/comp/inline-code.tokens.json +86 -0
- package/dist/vocabulary/tokens/comp/input-box.tokens.json +1073 -0
- package/dist/vocabulary/tokens/comp/keyboard-shortcut.tokens.json +194 -0
- package/dist/vocabulary/tokens/comp/link-card.tokens.json +321 -0
- package/dist/vocabulary/tokens/comp/link.tokens.json +321 -0
- package/dist/vocabulary/tokens/comp/list-row.tokens.json +249 -0
- package/dist/vocabulary/tokens/comp/list.tokens.json +328 -0
- package/dist/vocabulary/tokens/comp/loading-indicator.tokens.json +218 -0
- package/dist/vocabulary/tokens/comp/main-action-button.tokens.json +418 -0
- package/dist/vocabulary/tokens/comp/marquee-text.tokens.json +110 -0
- package/dist/vocabulary/tokens/comp/menu.tokens.json +1124 -0
- package/dist/vocabulary/tokens/comp/menubar.tokens.json +279 -0
- package/dist/vocabulary/tokens/comp/meter.tokens.json +173 -0
- package/dist/vocabulary/tokens/comp/modal-layer.tokens.json +69 -0
- package/dist/vocabulary/tokens/comp/navigation-bar.tokens.json +448 -0
- package/dist/vocabulary/tokens/comp/navigation-drawer.tokens.json +1126 -0
- package/dist/vocabulary/tokens/comp/number-input.tokens.json +75 -0
- package/dist/vocabulary/tokens/comp/number-ticker.tokens.json +77 -0
- package/dist/vocabulary/tokens/comp/one-time-code-input.tokens.json +246 -0
- package/dist/vocabulary/tokens/comp/page-header.tokens.json +247 -0
- package/dist/vocabulary/tokens/comp/pagination.tokens.json +233 -0
- package/dist/vocabulary/tokens/comp/popover.tokens.json +363 -0
- package/dist/vocabulary/tokens/comp/previous-next-links.tokens.json +194 -0
- package/dist/vocabulary/tokens/comp/progress-indicator.tokens.json +218 -0
- package/dist/vocabulary/tokens/comp/prose.tokens.json +283 -0
- package/dist/vocabulary/tokens/comp/radio-button.tokens.json +413 -0
- package/dist/vocabulary/tokens/comp/rating.tokens.json +230 -0
- package/dist/vocabulary/tokens/comp/resizable-frame.tokens.json +166 -0
- package/dist/vocabulary/tokens/comp/scroll-area.tokens.json +99 -0
- package/dist/vocabulary/tokens/comp/search.tokens.json +761 -0
- package/dist/vocabulary/tokens/comp/segmented-button.tokens.json +414 -0
- package/dist/vocabulary/tokens/comp/select.tokens.json +687 -0
- package/dist/vocabulary/tokens/comp/side-sheet.tokens.json +332 -0
- package/dist/vocabulary/tokens/comp/size-transition.tokens.json +49 -0
- package/dist/vocabulary/tokens/comp/skeleton.tokens.json +114 -0
- package/dist/vocabulary/tokens/comp/slider.tokens.json +436 -0
- package/dist/vocabulary/tokens/comp/snackbar.tokens.json +1160 -0
- package/dist/vocabulary/tokens/comp/split-view.tokens.json +52 -0
- package/dist/vocabulary/tokens/comp/stepper.tokens.json +538 -0
- package/dist/vocabulary/tokens/comp/steps.tokens.json +190 -0
- package/dist/vocabulary/tokens/comp/swatch.tokens.json +208 -0
- package/dist/vocabulary/tokens/comp/switch.tokens.json +350 -0
- package/dist/vocabulary/tokens/comp/tab-view.tokens.json +142 -0
- package/dist/vocabulary/tokens/comp/table-of-contents.tokens.json +429 -0
- package/dist/vocabulary/tokens/comp/table.tokens.json +553 -0
- package/dist/vocabulary/tokens/comp/tabs.tokens.json +1058 -0
- package/dist/vocabulary/tokens/comp/tag-group.tokens.json +68 -0
- package/dist/vocabulary/tokens/comp/tag.tokens.json +551 -0
- package/dist/vocabulary/tokens/comp/text-input.tokens.json +96 -0
- package/dist/vocabulary/tokens/comp/timeline.tokens.json +239 -0
- package/dist/vocabulary/tokens/comp/toolbar.tokens.json +270 -0
- package/dist/vocabulary/tokens/comp/tooltip.tokens.json +391 -0
- package/dist/vocabulary/tokens/comp/tree-view.tokens.json +478 -0
- package/dist/vocabulary/tokens/dial/dial.tokens.json +137 -0
- package/dist/vocabulary/tokens/fidelity/cupertino.fidelity.json +165 -0
- package/dist/vocabulary/tokens/fidelity/m3-like.fidelity.json +388 -0
- package/dist/vocabulary/tokens/fidelity/reference/androidx-material3.json +144 -0
- package/dist/vocabulary/tokens/fidelity/reference/apple-hig.json +196 -0
- package/dist/vocabulary/tokens/fidelity/reference/material-web.json +802 -0
- package/dist/vocabulary/tokens/generated/cupertino/components.json +1749 -0
- package/dist/vocabulary/tokens/generated/cupertino/fidelity.json +162 -0
- package/dist/vocabulary/tokens/generated/m3-like/components.json +1761 -0
- package/dist/vocabulary/tokens/generated/m3-like/fidelity.json +194 -0
- package/dist/vocabulary/tokens/generated/tanrei/components.json +1764 -0
- package/dist/vocabulary/tokens/icon-sets/material-symbols.icon-set.json +279 -0
- package/dist/vocabulary/tokens/ref/typeface.tokens.json +116 -0
- package/dist/vocabulary/tokens/schema/icon-set.schema.json +82 -0
- package/dist/vocabulary/tokens/schema/system.schema.json +859 -0
- package/dist/vocabulary/tokens/sys/behavior.tokens.json +184 -0
- package/dist/vocabulary/tokens/sys/color.vocabulary.json +58 -0
- package/dist/vocabulary/tokens/sys/elevation.tokens.json +362 -0
- package/dist/vocabulary/tokens/sys/measure.tokens.json +442 -0
- package/dist/vocabulary/tokens/sys/motion.tokens.json +1421 -0
- package/dist/vocabulary/tokens/sys/scroll-edge.tokens.json +50 -0
- package/dist/vocabulary/tokens/sys/shape.tokens.json +169 -0
- package/dist/vocabulary/tokens/sys/space.tokens.json +256 -0
- package/dist/vocabulary/tokens/sys/state.tokens.json +83 -0
- package/dist/vocabulary/tokens/sys/typescale.tokens.json +551 -0
- package/dist/vocabulary/tokens/systems/core.system.json +1889 -0
- package/dist/vocabulary/tokens/systems/cupertino.system.json +859 -0
- package/dist/vocabulary/tokens/systems/m3-like/comp/fab-menu.tokens.json +499 -0
- package/dist/vocabulary/tokens/systems/m3-like.system.json +1181 -0
- package/dist/vocabulary/tokens/systems/tanrei.system.json +707 -0
- package/dist/vocabulary/tokens/tanrei.resolver.json +400 -0
- package/package.json +52 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,4515 @@
|
|
|
1
|
+
// Bundled from the Tanrei monorepo (packages/mcp, packages/tokens-build, packages/token-engine).
|
|
2
|
+
|
|
3
|
+
// src/server.js
|
|
4
|
+
import fs10 from "node:fs";
|
|
5
|
+
import Ajv20202 from "ajv/dist/2020.js";
|
|
6
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
7
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
8
|
+
import { CallToolRequestSchema, ErrorCode, ListResourceTemplatesRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
9
|
+
|
|
10
|
+
// src/resources.js
|
|
11
|
+
import fs8 from "node:fs";
|
|
12
|
+
import path9 from "node:path";
|
|
13
|
+
|
|
14
|
+
// src/components.js
|
|
15
|
+
import fs7 from "node:fs";
|
|
16
|
+
import path8 from "node:path";
|
|
17
|
+
|
|
18
|
+
// ../tokens-build/src/bundle.js
|
|
19
|
+
import fs2 from "node:fs";
|
|
20
|
+
import path3 from "node:path";
|
|
21
|
+
import Ajv2020 from "ajv/dist/2020.js";
|
|
22
|
+
|
|
23
|
+
// ../token-engine/src/contexts.js
|
|
24
|
+
var SCHEMES = ["light", "light-medium", "light-high", "dark", "dark-medium", "dark-high"];
|
|
25
|
+
var CONTRAST_INDEX = { standard: 0, medium: 1, high: 2 };
|
|
26
|
+
function parseScheme(scheme) {
|
|
27
|
+
const [theme, contrast2 = "standard"] = scheme.split("-");
|
|
28
|
+
return { theme, contrast: contrast2 };
|
|
29
|
+
}
|
|
30
|
+
function pick(list, contrast2) {
|
|
31
|
+
return list[Math.min(CONTRAST_INDEX[contrast2], list.length - 1)];
|
|
32
|
+
}
|
|
33
|
+
function inContext(value, scheme) {
|
|
34
|
+
const { theme, contrast: contrast2 } = parseScheme(scheme);
|
|
35
|
+
let v = value;
|
|
36
|
+
if (v !== null && typeof v === "object" && !Array.isArray(v)) {
|
|
37
|
+
if (!(theme in v)) throw new Error(`context map has no "${theme}" entry: ${JSON.stringify(value)}`);
|
|
38
|
+
v = v[theme];
|
|
39
|
+
}
|
|
40
|
+
return Array.isArray(v) ? pick(v, contrast2) : v;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ../token-engine/src/errors.js
|
|
44
|
+
var SystemError = class extends Error {
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// ../token-engine/src/rules.js
|
|
48
|
+
var DERIVE = "dev.tanrei.derive";
|
|
49
|
+
var VOCABULARY = "dev.tanrei.vocabulary";
|
|
50
|
+
var ENUM = "dev.tanrei.enum";
|
|
51
|
+
var REFERENCE = "dev.tanrei.reference";
|
|
52
|
+
var enumName = (token) => token?.$extensions?.[ENUM]?.values?.[token.$value];
|
|
53
|
+
var ROUND = { dimension: 0.25, duration: 1, number: 1e-4, tracking: 1e-4 };
|
|
54
|
+
function roundTo(value, step) {
|
|
55
|
+
const inverse = 1 / step;
|
|
56
|
+
return Math.round(value * inverse) / inverse;
|
|
57
|
+
}
|
|
58
|
+
var isRef = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
59
|
+
var refId = (v) => v.slice(1, -1);
|
|
60
|
+
function roundToStep(value, step) {
|
|
61
|
+
const n = Math.round(Number((value / step).toFixed(9)));
|
|
62
|
+
return Number((n * step).toFixed(9));
|
|
63
|
+
}
|
|
64
|
+
function ruleDependencies(rule) {
|
|
65
|
+
if (!rule || typeof rule !== "object" || "fixed" in rule) return [];
|
|
66
|
+
if (!("fn" in rule)) return Object.values(rule).flatMap(ruleDependencies);
|
|
67
|
+
const picked = rule.fn === "pick" && rule.values && typeof rule.values === "object" ? Object.values(rule.values) : [];
|
|
68
|
+
return [rule.of, rule.base, rule.exp, rule.by, rule.round, rule.min, rule.height, rule.with, rule.amount, rule.on, ...Array.isArray(rule.from) ? rule.from : [], ...picked].filter(isRef).map(refId);
|
|
69
|
+
}
|
|
70
|
+
var sameUnit = (fn, field, rule, term, of) => {
|
|
71
|
+
if ((term.unit ?? null) !== (of.unit ?? null)) throw new Error(`"${fn}" ${field} ${rule[field]} (${term.unit ?? "no unit"}) is not in the unit of ${rule.of} (${of.unit ?? "no unit"})`);
|
|
72
|
+
};
|
|
73
|
+
function mulTerms(rule, of, lookup, ctx) {
|
|
74
|
+
if ("times" in rule) throw new Error('"mul" has no "times": a height that moves with another is a step of the control height ladder, or an "add"');
|
|
75
|
+
for (const field of ["round", "min"]) if (rule[field] !== void 0 && !isRef(rule[field])) throw new Error(`"mul" ${field} must be a token, as "{id}"`);
|
|
76
|
+
let step;
|
|
77
|
+
if (rule.round !== void 0) {
|
|
78
|
+
const grid = lookup(refId(rule.round));
|
|
79
|
+
sameUnit("mul", "round", rule, grid, of);
|
|
80
|
+
if (!(grid.value > 0)) throw new Error(`"mul" round ${rule.round} must be above zero; it is ${grid.value}`);
|
|
81
|
+
step = grid.value;
|
|
82
|
+
}
|
|
83
|
+
let min;
|
|
84
|
+
if (rule.min !== void 0 && !ctx.unscaling) {
|
|
85
|
+
const floor = lookup(refId(rule.min));
|
|
86
|
+
sameUnit("mul", "min", rule, floor, of);
|
|
87
|
+
min = floor.value;
|
|
88
|
+
}
|
|
89
|
+
return [step, min];
|
|
90
|
+
}
|
|
91
|
+
function evaluateNumeric(rule, lookup, ctx) {
|
|
92
|
+
const num = (v) => isRef(v) ? lookup(refId(v)).value : v;
|
|
93
|
+
switch (rule.fn) {
|
|
94
|
+
case "mul": {
|
|
95
|
+
const of = lookup(refId(rule.of));
|
|
96
|
+
const exp = rule.exp === void 0 ? 1 : num(rule.exp);
|
|
97
|
+
const coefficient = exp === 1 ? rule.by : rule.by ** exp;
|
|
98
|
+
const [step, min] = mulTerms(rule, of, lookup, ctx);
|
|
99
|
+
const product = of.value * coefficient;
|
|
100
|
+
const rounded = step === void 0 ? roundTo(product, ROUND[ctx.type] ?? ROUND.number) : roundToStep(product, step);
|
|
101
|
+
return { value: min === void 0 ? rounded : Math.max(min, rounded), unit: of.unit };
|
|
102
|
+
}
|
|
103
|
+
case "add": {
|
|
104
|
+
if (!isRef(rule.of) || !isRef(rule.by)) throw new Error('"add" needs "of" and "by", each a token as "{id}"');
|
|
105
|
+
if (rule.times !== void 0 && !(typeof rule.times === "number" && Number.isFinite(rule.times))) throw new Error(`"add" times must be a number; it is ${JSON.stringify(rule.times)}`);
|
|
106
|
+
if (rule.min !== void 0 && !isRef(rule.min)) throw new Error('"add" min must be a token, as "{id}"');
|
|
107
|
+
const [of, by] = [lookup(refId(rule.of)), lookup(refId(rule.by))];
|
|
108
|
+
sameUnit("add", "by", rule, by, of);
|
|
109
|
+
const sum = roundTo(of.value + by.value * (rule.times ?? 1), ROUND[ctx.type] ?? ROUND.number);
|
|
110
|
+
if (rule.min === void 0 || ctx.unscaling) return { value: sum, unit: of.unit };
|
|
111
|
+
const floor = lookup(refId(rule.min));
|
|
112
|
+
sameUnit("add", "min", rule, floor, of);
|
|
113
|
+
return { value: Math.max(floor.value, sum), unit: of.unit };
|
|
114
|
+
}
|
|
115
|
+
case "pad": {
|
|
116
|
+
if (!isRef(rule.of) || !isRef(rule.height)) throw new Error('"pad" needs "of" and "height", each a token as "{id}"');
|
|
117
|
+
const of = lookup(refId(rule.of));
|
|
118
|
+
if (rule.by !== void 0 && !(typeof rule.by === "number" && rule.by >= 0)) throw new Error(`"pad" by must be a number of zero or more; it is ${JSON.stringify(rule.by)}`);
|
|
119
|
+
const base = rule.by === void 0 ? of.value : roundTo(of.value * rule.by, ROUND[ctx.type] ?? ROUND.number);
|
|
120
|
+
if (ctx.unscaling) return { value: base, unit: of.unit };
|
|
121
|
+
if (typeof ctx.unscaled !== "function") throw new Error('"pad" needs the height its rule gives with no "min" (ctx.unscaled; see unscaledLookup)');
|
|
122
|
+
const [height, height1] = [lookup(refId(rule.height)), ctx.unscaled(refId(rule.height))];
|
|
123
|
+
sameUnit("pad", "height", rule, height, of);
|
|
124
|
+
return { value: Math.max(0, roundTo(base + (height.value - height1.value) / 2, ROUND[ctx.type] ?? ROUND.number)), unit: of.unit };
|
|
125
|
+
}
|
|
126
|
+
case "scale": {
|
|
127
|
+
const base = lookup(refId(rule.base));
|
|
128
|
+
return { value: roundTo(base.value * rule.ratio ** rule.step, ROUND[ctx.type] ?? ROUND.number), unit: base.unit };
|
|
129
|
+
}
|
|
130
|
+
case "clamp": {
|
|
131
|
+
const of = lookup(refId(rule.of));
|
|
132
|
+
return { value: Math.min(rule.max, Math.max(rule.min, of.value)), unit: of.unit };
|
|
133
|
+
}
|
|
134
|
+
case "sub": {
|
|
135
|
+
if (!isRef(rule.of) || !isRef(rule.by)) throw new Error('"sub" needs "of" and "by", each a token as "{id}"');
|
|
136
|
+
const [of, by] = [lookup(refId(rule.of)), lookup(refId(rule.by))];
|
|
137
|
+
if ((of.unit ?? null) !== (by.unit ?? null)) throw new Error(`"sub" takes ${rule.by} (${by.unit ?? "no unit"}) from ${rule.of} (${of.unit ?? "no unit"}): both need one unit`);
|
|
138
|
+
return { value: roundTo(Math.max(0, of.value - by.value), ROUND[ctx.type] ?? ROUND.number), unit: of.unit };
|
|
139
|
+
}
|
|
140
|
+
case "em":
|
|
141
|
+
if (ctx.fontSize === void 0) throw new Error('"em" is only valid for typography.letterSpacing');
|
|
142
|
+
return { value: roundTo(ctx.fontSize * rule.by, ROUND.tracking), unit: "px" };
|
|
143
|
+
case "pick": {
|
|
144
|
+
if (!isRef(rule.by)) throw new Error('"pick" needs "by": the choice of kind it follows, as "{id}"');
|
|
145
|
+
const choice = lookup(refId(rule.by));
|
|
146
|
+
const names = choice.names;
|
|
147
|
+
if (!Array.isArray(names)) throw new Error(`"pick" follows ${rule.by}, which is not a choice of kind (it has no ${ENUM}.values)`);
|
|
148
|
+
const values = rule.values ?? {};
|
|
149
|
+
const missing = names.filter((name) => !(name in values));
|
|
150
|
+
const unknown = Object.keys(values).filter((name) => !names.includes(name));
|
|
151
|
+
if (missing.length || unknown.length) throw new Error(`"pick" must give one value for each name of ${rule.by} (${names.join(", ")})${missing.length ? `; it gives none for ${missing.join(", ")}` : ""}${unknown.length ? `; ${unknown.join(", ")} is not one of them` : ""}`);
|
|
152
|
+
const chosen = values[names[choice.value]];
|
|
153
|
+
if (isRef(chosen)) return lookup(refId(chosen));
|
|
154
|
+
return typeof chosen === "number" ? { value: chosen } : { ...chosen };
|
|
155
|
+
}
|
|
156
|
+
default:
|
|
157
|
+
throw new Error(`unknown rule function "${rule.fn}"`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function unscaledLookup(describe) {
|
|
161
|
+
const memo = /* @__PURE__ */ new Map();
|
|
162
|
+
const unscaled = (id) => {
|
|
163
|
+
if (memo.has(id)) {
|
|
164
|
+
if (memo.get(id) === null) throw new Error(`cycle through {${id}}`);
|
|
165
|
+
return memo.get(id);
|
|
166
|
+
}
|
|
167
|
+
memo.set(id, null);
|
|
168
|
+
try {
|
|
169
|
+
const { alias, rule, type, value, reference } = describe(id);
|
|
170
|
+
const result = reference ? value && value.value > reference.value ? value : { ...reference } : alias ? unscaled(alias) : rule && typeof rule.fn === "string" ? evaluateNumeric(rule, unscaled, { type, unscaling: true, unscaled }) : value;
|
|
171
|
+
memo.set(id, result);
|
|
172
|
+
return result;
|
|
173
|
+
} catch (error) {
|
|
174
|
+
memo.delete(id);
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
return unscaled;
|
|
179
|
+
}
|
|
180
|
+
function* walkTokens(node, path11 = [], inherited = {}) {
|
|
181
|
+
const here = {
|
|
182
|
+
type: node.$type ?? inherited.type,
|
|
183
|
+
rationale: node.$extensions?.[VOCABULARY]?.rationale ?? inherited.rationale
|
|
184
|
+
};
|
|
185
|
+
if ("$value" in node) {
|
|
186
|
+
yield { id: path11.join("."), token: node, type: here.type, rationale: here.rationale };
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
for (const [key, child] of Object.entries(node)) {
|
|
190
|
+
if (key.startsWith("$") || child === null || typeof child !== "object") continue;
|
|
191
|
+
yield* walkTokens(child, [...path11, key], here);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ../token-engine/src/states.js
|
|
196
|
+
var STATES = "dev.tanrei.states";
|
|
197
|
+
var COLOR_RULES = /* @__PURE__ */ new Set(["mix", "alpha", "tone", "contrast-pick"]);
|
|
198
|
+
var isColorRule = (op) => Boolean(op && !("$value" in op) && COLOR_RULES.has(op.derive?.fn));
|
|
199
|
+
var isRef2 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
200
|
+
var hasContextAmount = (rule) => (rule.fn === "mix" || rule.fn === "alpha") && rule.amount !== null && typeof rule.amount === "object";
|
|
201
|
+
var refId2 = (v) => v.slice(1, -1);
|
|
202
|
+
var clone = (v) => JSON.parse(JSON.stringify(v));
|
|
203
|
+
function expandStateVocabulary(compDocuments) {
|
|
204
|
+
const out = [];
|
|
205
|
+
const visit = (node, path11) => {
|
|
206
|
+
const decl = node.$extensions?.[STATES];
|
|
207
|
+
if (decl) {
|
|
208
|
+
const component = path11.join(".");
|
|
209
|
+
const rationale = node.$extensions?.[VOCABULARY]?.rationale;
|
|
210
|
+
for (const state of decl.states) {
|
|
211
|
+
for (const variant of decl.variants ?? []) {
|
|
212
|
+
for (const [part, type] of Object.entries(decl.perVariant ?? {})) out.push({ id: `${component}.${variant}.${state}.${part}`, type, component, variant, state, part, enabled: `${component}.${variant}.${part}`, rationale });
|
|
213
|
+
}
|
|
214
|
+
for (const [part, type] of Object.entries(decl.perComponent ?? {})) out.push({ id: `${component}.${state}.${part}`, type, component, state, part, rationale });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) visit(child, [...path11, key]);
|
|
218
|
+
};
|
|
219
|
+
for (const doc of compDocuments) visit(doc, []);
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
222
|
+
var patternSegments = /* @__PURE__ */ new Map();
|
|
223
|
+
function matchPattern(pattern, id, s = id.split(".")) {
|
|
224
|
+
let p = patternSegments.get(pattern);
|
|
225
|
+
if (!p) patternSegments.set(pattern, p = pattern.split("."));
|
|
226
|
+
if (p.length !== s.length) return null;
|
|
227
|
+
const captures = [];
|
|
228
|
+
for (let i = 0; i < p.length; i++) {
|
|
229
|
+
if (p[i] === "*") captures.push(s[i]);
|
|
230
|
+
else if (p[i] !== s[i]) return null;
|
|
231
|
+
}
|
|
232
|
+
return captures;
|
|
233
|
+
}
|
|
234
|
+
var substitute = (value, captures) => typeof value === "string" ? value.replace(/\$(\d)/g, (_, n) => captures[n - 1] ?? `$${n}`) : Array.isArray(value) ? value.map((v) => substitute(v, captures)) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, captures)])) : value;
|
|
235
|
+
var ruleIndexes = /* @__PURE__ */ new WeakMap();
|
|
236
|
+
function ruleIndex(rules) {
|
|
237
|
+
let index2 = ruleIndexes.get(rules);
|
|
238
|
+
if (!index2 || index2.count !== rules.length) {
|
|
239
|
+
const byLength = /* @__PURE__ */ new Map();
|
|
240
|
+
for (const rule of rules) {
|
|
241
|
+
const p = rule.match.split(".");
|
|
242
|
+
if (!byLength.has(p.length)) byLength.set(p.length, []);
|
|
243
|
+
byLength.get(p.length).push({ rule, p });
|
|
244
|
+
}
|
|
245
|
+
index2 = { count: rules.length, byLength, chosen: /* @__PURE__ */ new Map() };
|
|
246
|
+
ruleIndexes.set(rules, index2);
|
|
247
|
+
}
|
|
248
|
+
return index2;
|
|
249
|
+
}
|
|
250
|
+
function operationFor(id, system) {
|
|
251
|
+
if (system.tokens[id]) return system.tokens[id];
|
|
252
|
+
if (!system.rules?.length) return null;
|
|
253
|
+
const index2 = ruleIndex(system.rules);
|
|
254
|
+
let best = index2.chosen.get(id);
|
|
255
|
+
if (best === void 0) {
|
|
256
|
+
best = null;
|
|
257
|
+
const s = id.split(".");
|
|
258
|
+
for (const { rule, p } of index2.byLength.get(s.length) ?? []) {
|
|
259
|
+
const captures = [];
|
|
260
|
+
let hit = true;
|
|
261
|
+
for (let i = 0; i < p.length && hit; i++) {
|
|
262
|
+
if (p[i] === "*") captures.push(s[i]);
|
|
263
|
+
else hit = p[i] === s[i];
|
|
264
|
+
}
|
|
265
|
+
if (hit && (!best || captures.length <= best.captures.length)) best = { rule, captures };
|
|
266
|
+
}
|
|
267
|
+
index2.chosen.set(id, best);
|
|
268
|
+
}
|
|
269
|
+
if (!best) return null;
|
|
270
|
+
const { match, ...operation } = best.rule;
|
|
271
|
+
return substitute(clone(operation), best.captures);
|
|
272
|
+
}
|
|
273
|
+
function matchingRules(id, layers) {
|
|
274
|
+
const hits = [];
|
|
275
|
+
for (const layer of layers) {
|
|
276
|
+
(layer.rules ?? []).forEach((rule, index2) => {
|
|
277
|
+
const captures = matchPattern(rule.match, id);
|
|
278
|
+
if (captures) hits.push({ layer: layer.id, index: index2, match: rule.match, wildcards: captures.length });
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
const explicit = [...layers].reverse().find((layer) => layer.tokens?.[id]);
|
|
282
|
+
const fewest = Math.min(...hits.map((h) => h.wildcards));
|
|
283
|
+
const winner = explicit ? null : hits.filter((h) => h.wildcards === fewest).at(-1);
|
|
284
|
+
const rules = hits.map((hit) => {
|
|
285
|
+
if (explicit) return { ...hit, wins: false, because: `an explicit entry under "tokens" (layer "${explicit.id}") beats every pattern` };
|
|
286
|
+
if (hit === winner) {
|
|
287
|
+
const tied = hits.filter((h) => h !== hit && h.wildcards === fewest);
|
|
288
|
+
const why = hits.length === 1 ? "the only pattern that matches" : !tied.length ? `fewest wildcards (${hit.wildcards})` : `${hits.some((h) => h.wildcards > fewest) ? `fewest wildcards (${hit.wildcards}), and ` : ""}written after ${tied.map((h) => `"${h.layer}" rules[${h.index}]`).join(", ")}, which ${tied.length === 1 ? "is" : "are"} equally specific \u2014 the later one wins a tie`;
|
|
289
|
+
return { ...hit, wins: true, because: why };
|
|
290
|
+
}
|
|
291
|
+
return { ...hit, wins: false, because: hit.wildcards > fewest ? `more wildcards (${hit.wildcards}) than "${winner.layer}" rules[${winner.index}] (${winner.wildcards})` : `equally specific, but "${winner.layer}" rules[${winner.index}] was written later` };
|
|
292
|
+
});
|
|
293
|
+
return { explicit: explicit ? { layer: explicit.id } : null, rules };
|
|
294
|
+
}
|
|
295
|
+
function mixColors(base, over2, amount) {
|
|
296
|
+
const t = Math.min(1, Math.max(0, amount));
|
|
297
|
+
const a = base.a * (1 - t) + over2.a * t;
|
|
298
|
+
if (a === 0) return { r: 0, g: 0, b: 0, a: 0 };
|
|
299
|
+
const ch = (k) => (base[k] * base.a * (1 - t) + over2[k] * over2.a * t) / a;
|
|
300
|
+
return { r: ch("r"), g: ch("g"), b: ch("b"), a };
|
|
301
|
+
}
|
|
302
|
+
function toDtcgColor({ r, g, b, a }) {
|
|
303
|
+
const byte = (c) => Math.round(Math.min(1, Math.max(0, c)) * 255);
|
|
304
|
+
const [R, G, B] = [byte(r), byte(g), byte(b)];
|
|
305
|
+
const round = (n) => Math.round(n / 255 * 1e4) / 1e4;
|
|
306
|
+
const value = { colorSpace: "srgb", components: [round(R), round(G), round(B)] };
|
|
307
|
+
const alpha = Math.round(a * 1e4) / 1e4;
|
|
308
|
+
if (alpha !== 1) value.alpha = alpha;
|
|
309
|
+
value.hex = `#${[R, G, B].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
|
|
310
|
+
return value;
|
|
311
|
+
}
|
|
312
|
+
var linear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
313
|
+
var luminance = ({ r, g, b }) => 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
|
|
314
|
+
function contrastRatio(fg, bg) {
|
|
315
|
+
const a = fg.a ?? 1;
|
|
316
|
+
const over2 = { r: fg.r * a + bg.r * (1 - a), g: fg.g * a + bg.g * (1 - a), b: fg.b * a + bg.b * (1 - a) };
|
|
317
|
+
const [hi, lo] = [luminance(over2), luminance(bg)].sort((x, y) => y - x);
|
|
318
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
319
|
+
}
|
|
320
|
+
function pickByContrast(on, candidates) {
|
|
321
|
+
let best = null;
|
|
322
|
+
for (const candidate of candidates) {
|
|
323
|
+
const ratio = contrastRatio(candidate.color, on);
|
|
324
|
+
if (!best || ratio > best.ratio) best = { ...candidate, ratio };
|
|
325
|
+
}
|
|
326
|
+
return best;
|
|
327
|
+
}
|
|
328
|
+
function checkContrastPick(rule, id) {
|
|
329
|
+
if (!isRef2(rule.on)) throw new SystemError(`${id}: "contrast-pick" needs "on": the color token the result must be readable on, as "{\u2026}"`);
|
|
330
|
+
if (!Array.isArray(rule.from) || rule.from.length < 2 || !rule.from.every(isRef2)) throw new SystemError(`${id}: "contrast-pick" needs "from": two or more color tokens to choose among, each as "{\u2026}"`);
|
|
331
|
+
}
|
|
332
|
+
function statePlan(system, documents, NS3, across) {
|
|
333
|
+
if (across?.plan) return across.plan;
|
|
334
|
+
const comp = Object.entries(documents).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc);
|
|
335
|
+
const vocabulary = expandStateVocabulary(comp);
|
|
336
|
+
const authored = /* @__PURE__ */ new Map();
|
|
337
|
+
const authoredColors = /* @__PURE__ */ new Set();
|
|
338
|
+
for (const doc of Object.values(documents)) for (const entry of walkTokens(doc)) authored.set(entry.id, entry.token), entry.type === "color" && authoredColors.add(entry.id);
|
|
339
|
+
const rationales = new Map(vocabulary.map((v) => [v.component, v.rationale]));
|
|
340
|
+
const declaring = (node, path11) => {
|
|
341
|
+
if (node.$extensions?.[STATES] && !rationales.has(path11.join("."))) rationales.set(path11.join("."), node.$extensions[VOCABULARY]?.rationale);
|
|
342
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) declaring(child, [...path11, key]);
|
|
343
|
+
};
|
|
344
|
+
for (const doc of comp) declaring(doc, []);
|
|
345
|
+
const resting = Object.entries(system.tokens).filter(([id, op]) => id.startsWith(`${NS3}.comp.`) && authoredColors.has(id) && isColorRule(op)).map(([id]) => ({ id, type: "color", state: null, rationale: rationales.get(id.split(".").slice(0, 3).join(".")) }));
|
|
346
|
+
for (const entry of resting) if (!entry.rationale) throw new SystemError(`${entry.id}: a resting color takes a color rule only in a component that declares states`);
|
|
347
|
+
vocabulary.push(...resting);
|
|
348
|
+
const said = /* @__PURE__ */ new Map();
|
|
349
|
+
const plan = {
|
|
350
|
+
vocabulary,
|
|
351
|
+
declared: new Map(vocabulary.map((v) => [v.id, v])),
|
|
352
|
+
authored,
|
|
353
|
+
operations: /* @__PURE__ */ new Map(),
|
|
354
|
+
written: /* @__PURE__ */ new Map(),
|
|
355
|
+
/** One `dev.tanrei.vocabulary` entry per rationale: a component's tokens say the same thing. */
|
|
356
|
+
rationale: (text2) => said.get(text2) ?? said.set(text2, Object.freeze({ rationale: text2 })).get(text2)
|
|
357
|
+
};
|
|
358
|
+
if (across) across.plan = plan;
|
|
359
|
+
return plan;
|
|
360
|
+
}
|
|
361
|
+
var fromDtcgColor = (v) => ({ r: v.components[0], g: v.components[1], b: v.components[2], a: v.alpha ?? 1 });
|
|
362
|
+
function generateStateDocument({ system, documents, roleColor, toneColor, note, scheme, across }) {
|
|
363
|
+
const NS3 = system.namespace ?? "tanrei";
|
|
364
|
+
const NS_PATTERN = NS3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
365
|
+
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
366
|
+
const REF_PALETTE = `${NS3}.ref.palette.`;
|
|
367
|
+
const plan = statePlan(system, documents, NS3, across);
|
|
368
|
+
const { vocabulary, declared, authored } = plan;
|
|
369
|
+
if (!vocabulary.length) return null;
|
|
370
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
371
|
+
const picked = /* @__PURE__ */ new Map();
|
|
372
|
+
const operation = (id) => {
|
|
373
|
+
if (!plan.operations.has(id)) plan.operations.set(id, operationFor(id, system));
|
|
374
|
+
return plan.operations.get(id);
|
|
375
|
+
};
|
|
376
|
+
const amount = (id, rule, trail) => {
|
|
377
|
+
const v = rule.amount;
|
|
378
|
+
if (isRef2(v)) return resolve(refId2(v), trail);
|
|
379
|
+
const isMap = Array.isArray(v) || v !== null && typeof v === "object";
|
|
380
|
+
if (isMap && !scheme) throw new SystemError(`${id}: the "${rule.fn}" rule's amount ${JSON.stringify(v)} is a context map, and generateStateDocument was called without a scheme to read it for`);
|
|
381
|
+
let n;
|
|
382
|
+
try {
|
|
383
|
+
n = isMap ? inContext(v, scheme) : v;
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw new SystemError(`${id}: the "${rule.fn}" rule's amount cannot be read for scheme "${scheme}": ${error.message}`);
|
|
386
|
+
}
|
|
387
|
+
if (isMap && isRef2(n)) return resolve(refId2(n), trail);
|
|
388
|
+
if (typeof n !== "number" || !Number.isFinite(n)) throw new SystemError(`${id}: the "${rule.fn}" rule's amount must be a number from 0 to 1, a "{\u2026}" reference to one, or a context map of those ([standard, medium, high] or { "light": [\u2026], "dark": [\u2026] }) \u2014 not ${JSON.stringify(v)}`);
|
|
389
|
+
return n;
|
|
390
|
+
};
|
|
391
|
+
function resolve(id, trail = []) {
|
|
392
|
+
if (trail.includes(id)) throw new Error(`cycle: ${[...trail, id].join(" \u2192 ")}`);
|
|
393
|
+
if (resolved.has(id)) return resolved.get(id);
|
|
394
|
+
let result;
|
|
395
|
+
if (id.startsWith(SYS_COLOR4)) result = roleColor(id.slice(SYS_COLOR4.length));
|
|
396
|
+
else if (id.startsWith(REF_PALETTE) && toneColor) {
|
|
397
|
+
const [palette, tone] = id.slice(REF_PALETTE.length).split(".");
|
|
398
|
+
result = toneColor(palette, Number(tone));
|
|
399
|
+
} else if (declared.has(id)) {
|
|
400
|
+
const op = operation(id);
|
|
401
|
+
if (!op) throw new Error(`${id}: system "${system.id}" gives this state no value. Add a rule such as { "match": "${id.replace(new RegExp(`^(${NS_PATTERN}\\.comp)\\.[^.]+\\.[^.]+`), "$1.*.*")}", \u2026 }.`);
|
|
402
|
+
const next = [...trail, id];
|
|
403
|
+
if (op.derive?.fn === "mix") result = mixColors(resolve(refId2(op.derive.base), next), resolve(refId2(op.derive.with), next), amount(id, op.derive, next));
|
|
404
|
+
else if (op.derive?.fn === "alpha") {
|
|
405
|
+
const of = resolve(refId2(op.derive.of), next);
|
|
406
|
+
result = { ...of, a: of.a * amount(id, op.derive, next) };
|
|
407
|
+
} else if (op.derive?.fn === "tone") {
|
|
408
|
+
if (declared.get(id).type !== "color") throw new SystemError(`${id}: "tone" values a color, and this token is a ${declared.get(id).type}`);
|
|
409
|
+
if (typeof op.derive.palette !== "string" || op.derive.tone === void 0) throw new SystemError(`${id}: "tone" needs "palette" (a declared palette) and "tone" (0\u2013100; [standard, medium, high]; or { "light": [\u2026], "dark": [\u2026] })`);
|
|
410
|
+
if (!toneColor) throw new Error(`${id}: the "tone" rule needs the palette engine (generateStateDocument was called without toneColor)`);
|
|
411
|
+
result = toneColor(op.derive.palette, op.derive.tone, id);
|
|
412
|
+
} else if (op.derive?.fn === "contrast-pick") {
|
|
413
|
+
checkContrastPick(op.derive, id);
|
|
414
|
+
const on = resolve(refId2(op.derive.on), next);
|
|
415
|
+
const winner = pickByContrast(on, op.derive.from.map((ref) => ({ ref, color: resolve(refId2(ref), next) })));
|
|
416
|
+
picked.set(id, winner.ref);
|
|
417
|
+
result = winner.color;
|
|
418
|
+
} else if (op.derive) throw new SystemError(`${id}: state tokens support the "mix", "alpha", "tone" and "contrast-pick" rules, not "${op.derive.fn}"`);
|
|
419
|
+
else if (isRef2(op.$value)) result = resolve(refId2(op.$value), next);
|
|
420
|
+
else result = op.$value;
|
|
421
|
+
} else {
|
|
422
|
+
const token = authored.get(id);
|
|
423
|
+
if (!token) throw new Error(`${trail.at(-1) ?? "?"}: references unknown token {${id}}`);
|
|
424
|
+
const v = token.$value;
|
|
425
|
+
result = isRef2(v) ? resolve(refId2(v), [...trail, id]) : v;
|
|
426
|
+
}
|
|
427
|
+
if (result && typeof result === "object" && "colorSpace" in result) result = fromDtcgColor(result);
|
|
428
|
+
resolved.set(id, result);
|
|
429
|
+
return result;
|
|
430
|
+
}
|
|
431
|
+
const root2 = { $description: note };
|
|
432
|
+
for (const entry of vocabulary) {
|
|
433
|
+
const op = operation(entry.id);
|
|
434
|
+
const value = resolve(entry.id);
|
|
435
|
+
let node = root2;
|
|
436
|
+
const parts = entry.parts ??= entry.id.split(".");
|
|
437
|
+
for (let i = 0; i < parts.length - 1; i += 1) node = node[parts[i]] ??= {};
|
|
438
|
+
let written = plan.written.get(entry.id);
|
|
439
|
+
if (!written) {
|
|
440
|
+
const aliasOnly = op && !op.derive && isRef2(op.$value);
|
|
441
|
+
const $extensions2 = { [VOCABULARY]: plan.rationale(entry.rationale), ...entry.state ? { "dev.tanrei.state": entry.state } : {} };
|
|
442
|
+
if (op?.derive) $extensions2[DERIVE] = op.derive;
|
|
443
|
+
else if (!aliasOnly) $extensions2[DERIVE] = { fixed: op.reason ?? "Set by the system layer." };
|
|
444
|
+
Object.freeze($extensions2);
|
|
445
|
+
written = aliasOnly ? { token: Object.freeze({ $type: entry.type, $value: op.$value, $extensions: $extensions2 }) } : { $extensions: $extensions2 };
|
|
446
|
+
plan.written.set(entry.id, written);
|
|
447
|
+
}
|
|
448
|
+
const $extensions = op?.derive && hasContextAmount(op.derive) ? Object.freeze({ ...written.$extensions, [DERIVE]: { ...op.derive, amount: inContext(op.derive.amount, scheme) } }) : written.$extensions;
|
|
449
|
+
node[parts.at(-1)] = written.token ?? { $type: entry.type, $value: picked.has(entry.id) ? picked.get(entry.id) : entry.type === "color" ? toDtcgColor(value) : value, $extensions };
|
|
450
|
+
}
|
|
451
|
+
return root2;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ../token-engine/src/palette.js
|
|
455
|
+
var STANDARD_TONES = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100];
|
|
456
|
+
var argbToRgb = (argb, a = 1) => ({ r: (argb >> 16 & 255) / 255, g: (argb >> 8 & 255) / 255, b: (argb & 255) / 255, a });
|
|
457
|
+
function hexToArgb(hex) {
|
|
458
|
+
return (4278190080 | Number.parseInt(hex.slice(1), 16)) >>> 0;
|
|
459
|
+
}
|
|
460
|
+
function argbToColor(argb, alphaValue) {
|
|
461
|
+
const r = argb >> 16 & 255;
|
|
462
|
+
const g = argb >> 8 & 255;
|
|
463
|
+
const b = argb & 255;
|
|
464
|
+
const round = (n) => Math.round(n / 255 * 1e4) / 1e4;
|
|
465
|
+
const hex = `#${[r, g, b].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
|
|
466
|
+
const value = { colorSpace: "srgb", components: [round(r), round(g), round(b)] };
|
|
467
|
+
if (alphaValue !== void 0) value.alpha = alphaValue;
|
|
468
|
+
value.hex = hex;
|
|
469
|
+
return value;
|
|
470
|
+
}
|
|
471
|
+
function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace: NS3 = "tanrei" }) {
|
|
472
|
+
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
473
|
+
const REF_PALETTE = `${NS3}.ref.palette.`;
|
|
474
|
+
function buildPalette(declaration, name) {
|
|
475
|
+
const source2 = declaration.source ?? {};
|
|
476
|
+
let generated;
|
|
477
|
+
if ("seed" in source2) {
|
|
478
|
+
const hct = Hct2.fromInt(hexToArgb(source2.seed));
|
|
479
|
+
generated = TonalPalette2.fromHueAndChroma(hct.hue, hct.chroma);
|
|
480
|
+
} else if ("hue" in source2 && "chroma" in source2) generated = TonalPalette2.fromHueAndChroma(source2.hue, source2.chroma);
|
|
481
|
+
else throw new Error(`palette "${name}": unsupported source ${JSON.stringify(source2)}`);
|
|
482
|
+
const fixed = new Map(Object.entries(source2.tones ?? {}).map(([tone, hex]) => [Number(tone), hexToArgb(hex)]));
|
|
483
|
+
if (!fixed.size) return generated;
|
|
484
|
+
return { tone: (t) => fixed.get(t) ?? generated.tone(t) };
|
|
485
|
+
}
|
|
486
|
+
const INTENT_TONES = {
|
|
487
|
+
"{name}": { light: [45, 38, 30], dark: [72, 80, 87] },
|
|
488
|
+
"on-{name}": { light: [100], dark: [10] },
|
|
489
|
+
"{name}-container": { light: [93, 91, 89], dark: [22] },
|
|
490
|
+
"on-{name}-container": { light: [20, 15, 10], dark: [88, 92, 96] }
|
|
491
|
+
};
|
|
492
|
+
const INVERSE_TONES = { light: [80, 85, 90], dark: [40, 30, 20] };
|
|
493
|
+
function roleOperation(system, role, entry) {
|
|
494
|
+
const op = system.tokens[`${SYS_COLOR4}${role}`];
|
|
495
|
+
const palette = entry?.template?.palette;
|
|
496
|
+
if (!palette || op?.derive?.fn !== "tone" || op.derive.palette === palette) return op;
|
|
497
|
+
const chain = system.chain ?? [];
|
|
498
|
+
const declared = chain.indexOf(system.paletteLayers?.[palette]);
|
|
499
|
+
return declared >= 0 && declared > chain.indexOf(op.layer) ? void 0 : op;
|
|
500
|
+
}
|
|
501
|
+
function roleTable(system, vocabulary) {
|
|
502
|
+
const table = /* @__PURE__ */ new Map();
|
|
503
|
+
const pattern = vocabulary.sets.intent.roles;
|
|
504
|
+
const add = (name, palette, rationale, declared) => {
|
|
505
|
+
for (const p of pattern) table.set(p.replace("{name}", name), { rationale, template: palette ? { palette, tone: INTENT_TONES[p] } : null, declared });
|
|
506
|
+
};
|
|
507
|
+
for (const [name, rationale] of Object.entries(vocabulary.intents)) add(name, name in system.palettes ? name : null, rationale, false);
|
|
508
|
+
const inverseOf = (role) => Object.keys(vocabulary.intents).find((name) => role === `inverse-${name}` && name in system.palettes);
|
|
509
|
+
for (const [role, rationale] of Object.entries(vocabulary.roles)) {
|
|
510
|
+
const intent = inverseOf(role);
|
|
511
|
+
table.set(role, { rationale, template: intent ? { palette: intent, tone: INVERSE_TONES } : null, declared: false });
|
|
512
|
+
}
|
|
513
|
+
for (const [name, decl] of Object.entries(system.palettes)) {
|
|
514
|
+
if (decl.roles !== "intent") continue;
|
|
515
|
+
if (name in vocabulary.intents) continue;
|
|
516
|
+
if (!decl.description) throw new Error(`palette "${name}": a declared palette with roles needs a "description" \u2014 why does this system need it?`);
|
|
517
|
+
add(name, name, decl.description, true);
|
|
518
|
+
}
|
|
519
|
+
for (const [id, decl] of Object.entries(system.vocabulary ?? {})) {
|
|
520
|
+
if (decl.kind !== "token" || !id.startsWith(SYS_COLOR4)) continue;
|
|
521
|
+
const role = id.slice(SYS_COLOR4.length);
|
|
522
|
+
if (table.has(role)) throw new SystemError(`${id}: "${role}" is a core color role; a layer declares only what the core lacks: delete this declaration, and write its value under "tokens"`);
|
|
523
|
+
if (decl.type !== "color") throw new Error(`${id}: a color role is declared with "$type": "color"`);
|
|
524
|
+
table.set(role, { rationale: decl.rationale, template: null, declared: true, extension: { declaredBy: decl.declaredBy, onRole: decl.onRole } });
|
|
525
|
+
}
|
|
526
|
+
return table;
|
|
527
|
+
}
|
|
528
|
+
function paletteToneColor(palettes, target, where) {
|
|
529
|
+
const [p, t] = target.slice(REF_PALETTE.length).split(".");
|
|
530
|
+
if (!palettes[p]) throw new SystemError(`${where}: {${target}} names the palette "${p}", which this system does not declare`);
|
|
531
|
+
return argbToRgb(palettes[p].tone(Number(t)));
|
|
532
|
+
}
|
|
533
|
+
function valueColor(palettes, def) {
|
|
534
|
+
if (def.alpha) {
|
|
535
|
+
const c = def.alpha === "white" ? 1 : 0;
|
|
536
|
+
return { r: c, g: c, b: c, a: def.a / 100 };
|
|
537
|
+
}
|
|
538
|
+
return argbToRgb(palettes[def.p].tone(def.t));
|
|
539
|
+
}
|
|
540
|
+
function rolesFor(system, scheme, vocabulary, palettes = buildPalettes(system)) {
|
|
541
|
+
const table = roleTable(system, vocabulary);
|
|
542
|
+
for (const id of Object.keys(system.tokens)) {
|
|
543
|
+
if (id.startsWith(SYS_COLOR4) && !table.has(id.slice(SYS_COLOR4.length))) {
|
|
544
|
+
throw new Error(`${id}: not a color role. Core roles are fixed by the vocabulary; for anything else declare a palette with "roles": "intent".`);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const out = {};
|
|
548
|
+
const picks = [];
|
|
549
|
+
for (const [role, entry] of table) {
|
|
550
|
+
const { template } = entry;
|
|
551
|
+
const id = `${SYS_COLOR4}${role}`;
|
|
552
|
+
const op = roleOperation(system, role, entry);
|
|
553
|
+
if (op && "$value" in op && typeof op.$value !== "string") {
|
|
554
|
+
throw new Error(`${id}: a color role cannot hold a literal. Alias another role ("{\u2026}"), use a tone or alpha rule, or declare a palette for the color.`);
|
|
555
|
+
}
|
|
556
|
+
const rule = op?.derive ?? (template ? { fn: "tone", ...template } : void 0);
|
|
557
|
+
if (typeof op?.$value === "string") out[role] = { ref: op.$value };
|
|
558
|
+
else if (rule?.fn === "tone") {
|
|
559
|
+
if (!(rule.palette in system.palettes)) throw new Error(`${id}: unknown palette "${rule.palette}"`);
|
|
560
|
+
out[role] = { p: rule.palette, t: inContext(rule.tone, scheme) };
|
|
561
|
+
} else if (rule?.fn === "alpha") out[role] = { alpha: inContext(rule.of, scheme), a: inContext(rule.amount, scheme) };
|
|
562
|
+
else if (rule?.fn === "contrast-pick") picks.push({ role, id, rule });
|
|
563
|
+
else if (rule?.fn) throw new SystemError(`${id}: a color role accepts the "tone", "alpha" and "contrast-pick" rules, not "${rule.fn}"`);
|
|
564
|
+
else throw new Error(`${id}: the system gives this core role no value. Add a rule, an alias, or a palette named after its intent.`);
|
|
565
|
+
}
|
|
566
|
+
const pending = new Map(picks.map((pick2) => [pick2.role, pick2]));
|
|
567
|
+
const colorOf = (ref, trail) => {
|
|
568
|
+
const target = ref.slice(1, -1);
|
|
569
|
+
if (target.startsWith(REF_PALETTE)) return paletteToneColor(palettes, target, trail.at(-1));
|
|
570
|
+
if (!target.startsWith(SYS_COLOR4)) throw new SystemError(`${trail.at(-1)}: "contrast-pick" on a color role chooses among color roles and ${REF_PALETTE}<palette>.<tone> \u2014 {${target}} is neither`);
|
|
571
|
+
const role = target.slice(SYS_COLOR4.length);
|
|
572
|
+
if (trail.includes(target)) throw new SystemError(`cycle: ${[...trail, target].join(" \u2192 ")}`);
|
|
573
|
+
if (pending.has(role)) decide(pending.get(role), trail);
|
|
574
|
+
const def = out[role];
|
|
575
|
+
if (!def) throw new SystemError(`${trail.at(-1)}: unknown color role {${target}}`);
|
|
576
|
+
if (def.ref) return colorOf(def.ref, [...trail, target]);
|
|
577
|
+
return valueColor(palettes, def);
|
|
578
|
+
};
|
|
579
|
+
function decide({ role, id, rule }, trail = []) {
|
|
580
|
+
checkContrastPick(rule, id);
|
|
581
|
+
const next = [...trail, id];
|
|
582
|
+
const winner = pickByContrast(colorOf(rule.on, next), rule.from.map((ref) => ({ ref, color: colorOf(ref, next) })));
|
|
583
|
+
pending.delete(role);
|
|
584
|
+
out[role] = { ref: winner.ref };
|
|
585
|
+
}
|
|
586
|
+
for (const pick2 of picks) if (pending.has(pick2.role)) decide(pick2);
|
|
587
|
+
return Object.fromEntries([...table.keys()].map((role) => [role, out[role]]));
|
|
588
|
+
}
|
|
589
|
+
const buildPalettes = (system) => Object.fromEntries(Object.entries(system.palettes).map(([name, decl]) => [name, buildPalette(decl, name)]));
|
|
590
|
+
function generateColorFiles(system, { sourcePath, vocabulary, documents }) {
|
|
591
|
+
const table = roleTable(system, vocabulary);
|
|
592
|
+
const palettes = buildPalettes(system);
|
|
593
|
+
const usedTones = Object.fromEntries(Object.keys(palettes).map((name) => [name, new Set(STANDARD_TONES)]));
|
|
594
|
+
const usedAlpha = { black: /* @__PURE__ */ new Set(), white: /* @__PURE__ */ new Set() };
|
|
595
|
+
const resolved = {};
|
|
596
|
+
for (const scheme of SCHEMES) {
|
|
597
|
+
resolved[scheme] = rolesFor(system, scheme, vocabulary, palettes);
|
|
598
|
+
for (const def of Object.values(resolved[scheme])) {
|
|
599
|
+
if (def.ref) continue;
|
|
600
|
+
if (def.alpha) usedAlpha[def.alpha].add(def.a);
|
|
601
|
+
else usedTones[def.p].add(def.t);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
for (const [, palette2, tone] of JSON.stringify([system.tokens, system.rules ?? []]).matchAll(new RegExp(`\\{${REF_PALETTE.replaceAll(".", "\\.")}([a-z0-9-]+)\\.(\\d+)\\}`, "g"))) usedTones[palette2]?.add(Number(tone));
|
|
605
|
+
const note = `Generated by @tanrei/tokens-build from ${sourcePath} (${system.specVersion}). Do not edit.`;
|
|
606
|
+
const files = {};
|
|
607
|
+
const palette = { $type: "color" };
|
|
608
|
+
for (const [name, tones] of Object.entries(usedTones)) {
|
|
609
|
+
palette[name] = {};
|
|
610
|
+
for (const tone of [...tones].sort((a, b) => a - b)) palette[name][String(tone)] = { $value: argbToColor(palettes[name].tone(tone)) };
|
|
611
|
+
}
|
|
612
|
+
const alphaGroup = { $type: "color" };
|
|
613
|
+
for (const [base, steps] of Object.entries(usedAlpha)) {
|
|
614
|
+
alphaGroup[base] = {};
|
|
615
|
+
const argb = base === "black" ? 4278190080 : 4294967295;
|
|
616
|
+
for (const step of [...steps].sort((a, b) => a - b)) alphaGroup[base][String(step)] = { $value: argbToColor(argb, step / 100) };
|
|
617
|
+
}
|
|
618
|
+
files["ref.palette.tokens.json"] = { $description: note, [NS3]: { ref: { palette, alpha: alphaGroup } } };
|
|
619
|
+
const across = {};
|
|
620
|
+
for (const scheme of SCHEMES) {
|
|
621
|
+
const color = { $type: "color", ...vocabulary.llm ? { $extensions: { "dev.tanrei.llm": vocabulary.llm } } : {} };
|
|
622
|
+
for (const [role, def] of Object.entries(resolved[scheme])) {
|
|
623
|
+
const value = def.ref ?? (def.alpha ? `{${NS3}.ref.alpha.${def.alpha}.${def.a}}` : `{${NS3}.ref.palette.${def.p}.${def.t}}`);
|
|
624
|
+
const { rationale, declared, extension } = table.get(role);
|
|
625
|
+
const origin = extension ? { declaredBy: extension.declaredBy, extension: true, ...extension.onRole ? { onRole: extension.onRole } : {} } : declared ? { declaredBy: system.id } : {};
|
|
626
|
+
color[role] = { $value: value, $description: rationale, $extensions: { "dev.tanrei.vocabulary": { rationale, ...origin } } };
|
|
627
|
+
}
|
|
628
|
+
files[`sys.color.${scheme}.tokens.json`] = { $description: note, [NS3]: { sys: { color } } };
|
|
629
|
+
if (documents) {
|
|
630
|
+
const roleColor = (role, trail = []) => {
|
|
631
|
+
const def = resolved[scheme][role];
|
|
632
|
+
if (!def) throw new Error(`unknown color role "${role}"`);
|
|
633
|
+
if (def.ref) {
|
|
634
|
+
const target = def.ref.slice(1, -1);
|
|
635
|
+
if (target.startsWith(REF_PALETTE)) return paletteToneColor(palettes, target, `${SYS_COLOR4}${role}`);
|
|
636
|
+
return roleColor(target.slice(SYS_COLOR4.length), [...trail, role]);
|
|
637
|
+
}
|
|
638
|
+
return valueColor(palettes, def);
|
|
639
|
+
};
|
|
640
|
+
const toneColor = (palette2, tone, id = "?") => {
|
|
641
|
+
if (!palettes[palette2]) throw new SystemError(`${id}: unknown palette "${palette2}". Declared: ${Object.keys(palettes).join(", ")}.`);
|
|
642
|
+
const t = inContext(tone, scheme);
|
|
643
|
+
if (typeof t !== "number" || t < 0 || t > 100) throw new SystemError(`${id}: a tone is a number from 0 to 100, not ${JSON.stringify(t)}`);
|
|
644
|
+
return argbToRgb(palettes[palette2].tone(t));
|
|
645
|
+
};
|
|
646
|
+
const states = generateStateDocument({ system: { namespace: NS3, ...system }, documents, roleColor, toneColor, note, scheme, across });
|
|
647
|
+
if (states) files[`comp.states.${scheme}.tokens.json`] = states;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
return files;
|
|
651
|
+
}
|
|
652
|
+
return { buildPalette, roleTable, roleOperation, rolesFor, generateColorFiles };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// ../token-engine/src/operations.js
|
|
656
|
+
var DEFAULT_NAMESPACE = "tanrei";
|
|
657
|
+
var REASON = "<why this product needs it \u2014 8+ characters>";
|
|
658
|
+
var RATIONALE = "<why this design system or product needs it \u2014 8+ characters>";
|
|
659
|
+
var cannot = (namespace = DEFAULT_NAMESPACE) => [
|
|
660
|
+
"remove or retype a core token \u2014 extensions are additive only",
|
|
661
|
+
"add an interaction state \u2014 hovered, focused, pressed and disabled are bound to platform behaviour",
|
|
662
|
+
"add a name to a choice of kind (pressed-feedback, focus-style) \u2014 the list of names is vocabulary; a layer chooses among them",
|
|
663
|
+
`reference a layer\u2019s own token from a ${namespace}.* token \u2014 the core never depends on a layer\u2019s namespace`,
|
|
664
|
+
"change an accessibility threshold \u2014 they are constants; a violation in a product layer is a warning printed by every build, and an imitation preset is held to fidelity to its original instead"
|
|
665
|
+
];
|
|
666
|
+
var CANNOT = cannot();
|
|
667
|
+
var tierOf = (id) => id.split(".")[1];
|
|
668
|
+
var isPaletteIn = (NS3) => (id) => id.startsWith(`${NS3}.ref.palette.`) || id.startsWith(`${NS3}.ref.alpha.`);
|
|
669
|
+
function tokenKind({ id, alias, rule }, { namespace: NS3 = DEFAULT_NAMESPACE } = {}) {
|
|
670
|
+
if (alias) return "alias";
|
|
671
|
+
if (id.startsWith(`${NS3}.sys.color.`) || isPaletteIn(NS3)(id)) return "derived";
|
|
672
|
+
if (rule && "fixed" in rule) return "fixed";
|
|
673
|
+
if (rule) return "derived";
|
|
674
|
+
return tierOf(id) === "dial" ? "dial" : "fixed";
|
|
675
|
+
}
|
|
676
|
+
var sample = (type) => type === "fontFamily" ? ["<Family a product installs>", "system-ui", "sans-serif"] : type === "number" ? 1 : type === "dimension" ? { value: 12, unit: "px" } : type === "duration" ? { value: 200, unit: "ms" } : type === "color" ? { colorSpace: "srgb", components: [0.9, 0.1, 0.1], hex: "#e61a1a" } : "<a literal of this $type>";
|
|
677
|
+
function legalOperations(descriptor, { namespace: NS3 = DEFAULT_NAMESPACE } = {}) {
|
|
678
|
+
const { id, type, value, alias, rule, state, choices } = descriptor;
|
|
679
|
+
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
680
|
+
const isPalette = isPaletteIn(NS3);
|
|
681
|
+
const kind = tokenKind(descriptor, { namespace: NS3 });
|
|
682
|
+
const entry = (op, write, effect) => ({ op, write: { tokens: { [id]: write } }, effect });
|
|
683
|
+
const literal = sample(type);
|
|
684
|
+
if (Array.isArray(choices) && choices.length) {
|
|
685
|
+
const current = typeof value === "number" ? choices[value] : value;
|
|
686
|
+
const other = choices.find((name) => name !== current) ?? choices[0];
|
|
687
|
+
return [{
|
|
688
|
+
...entry("choose", { $value: choices.indexOf(other), reason: REASON }, `One of: ${choices.map((name, i) => `${name} (${i})`).join(", ")}. It is "${current}" now; this example chooses "${other}". Write the index \u2014 or the name, which the engine accepts too: { "$value": "${other}" }. The names are part of the vocabulary: a layer chooses among them and cannot add one. Nothing scales or derives a choice.`),
|
|
689
|
+
choices,
|
|
690
|
+
current
|
|
691
|
+
}];
|
|
692
|
+
}
|
|
693
|
+
if (tierOf(id) === "dial") return [entry("set the dial", { $value: value, reason: REASON }, "Every token derived from this dial follows, on every platform. Tokens a layer pinned do not. This is the first thing to reach for.")];
|
|
694
|
+
if (isPalette(id)) {
|
|
695
|
+
const palette = id.split(".")[3];
|
|
696
|
+
return [{ op: "change the palette", write: { palettes: { [palette]: { source: { seed: "#rrggbb" } } } }, effect: `ref.palette tones are generated. Re-declare "${palette}" under "palettes" (a seed, or hue + chroma); every role that uses it follows in all six schemes.` }];
|
|
697
|
+
}
|
|
698
|
+
if (id.startsWith(SYS_COLOR4)) {
|
|
699
|
+
const role = id.slice(SYS_COLOR4.length);
|
|
700
|
+
return [
|
|
701
|
+
{ op: "change the palette", write: { palettes: { "<palette>": { source: { seed: "#rrggbb" } } } }, effect: "Usually what you want: the role keeps its tone rule and takes the new hue. `rule.palette` names the palette this role reads." },
|
|
702
|
+
entry("derive", { derive: { fn: "tone", palette: rule?.palette ?? "<palette>", tone: { light: [40, 30, 20], dark: [80, 85, 90] } } }, 'Pick tones per theme; the three numbers are standard, medium and high contrast (one number applies to all three). A role also accepts `{"fn": "alpha", "of": "black", "amount": {\u2026}}` and "contrast-pick" (below).'),
|
|
703
|
+
entry("derive (contrast-pick)", { derive: { fn: "contrast-pick", on: `{${SYS_COLOR4}<the role it is drawn on>}`, from: [`{${SYS_COLOR4}<candidate>}`, `{${SYS_COLOR4}<another candidate>}`] } }, 'The role aliases whichever candidate has the highest WCAG contrast against `on`, decided per scheme (the first wins a tie). Candidates are color roles or palette tones ("{' + NS3 + '.ref.palette.<palette>.<tone>}").'),
|
|
704
|
+
entry("re-point alias", { $value: `{${SYS_COLOR4}<another-role>}` }, `"${role}" takes another role's color in every scheme.`),
|
|
705
|
+
{ op: "declare a palette", write: { palettes: { "<name>": { description: "<why this product needs this color family>", source: { seed: "#rrggbb" }, roles: "intent" } } }, effect: "For a brand or domain color: generates <name>, on-<name>, <name>-container, on-<name>-container with contrast checks. A literal hex on a role is not accepted." },
|
|
706
|
+
{ op: "declare a single role", write: { vocabulary: { [`${SYS_COLOR4}<new-role>`]: { $type: "color", rationale: RATIONALE, derive: { fn: "tone", palette: "<palette>", tone: { light: [90], dark: [30] } }, onRole: `${SYS_COLOR4}<role drawn on it>` } } }, effect: "For one more role rather than a family of four (a reference system\u2019s `primary-fixed`). `onRole` registers the pair with the contrast checks." }
|
|
707
|
+
];
|
|
708
|
+
}
|
|
709
|
+
if (state) {
|
|
710
|
+
const parts = id.split(".");
|
|
711
|
+
const pattern = parts.map((part, i) => i === 2 || i === 3 && parts[4] === state ? "*" : part).join(".");
|
|
712
|
+
return [
|
|
713
|
+
entry("re-point alias", { $value: `{${NS3}.comp.<component>.<variant>.<part>}` }, "This state looks like another token (for example its resting value: a system without hover)."),
|
|
714
|
+
...type === "color" ? [
|
|
715
|
+
entry("derive", { derive: { fn: "mix", base: `{${NS3}.comp.\u2026container.color}`, with: `{${NS3}.comp.\u2026state-layer.color}`, amount: `{${NS3}.sys.state.hover-state-layer-opacity}` } }, 'A state layer ("mix") or a dim ("alpha": { "of": "{\u2026}", "amount": n }), computed from this system\u2019s colors in every scheme.'),
|
|
716
|
+
entry("derive (tone)", { derive: { fn: "tone", palette: "<palette>", tone: { light: [70, 60, 50], dark: [70, 80, 90] } } }, "An explicit tone of a declared palette for this one state \u2014 for ramps that are not monotonic (rest 80, hover 70, pressed 40), which no mix can express. The three numbers are standard, medium and high contrast; one number applies everywhere."),
|
|
717
|
+
entry("derive (contrast-pick)", { derive: { fn: "contrast-pick", on: `{${NS3}.comp.\u2026container.color}`, from: [`{${SYS_COLOR4}<candidate>}`, `{${SYS_COLOR4}<another candidate>}`] } }, "Whichever candidate is most readable (highest WCAG contrast) on `on`, decided per scheme; the first wins a tie. State tokens accept mix, alpha, tone and contrast-pick. Nothing else.")
|
|
718
|
+
] : [],
|
|
719
|
+
entry("pin $value", { $value: literal, reason: REASON }, "An explicit value for this one state."),
|
|
720
|
+
{ op: "pattern rule", write: { rules: [{ match: pattern, $value: "{\u2026$1\u2026$2\u2026}" }] }, effect: 'Value the same state of every component/variant at once. `*` matches one segment and is available as $1, $2\u2026. An explicit entry in "tokens" beats a pattern; fewer wildcards beat more; the later layer wins a tie.' }
|
|
721
|
+
];
|
|
722
|
+
}
|
|
723
|
+
const operations = [];
|
|
724
|
+
if (type === "typography" && alias) {
|
|
725
|
+
return [
|
|
726
|
+
entry("re-point alias", { $value: `{${alias.split(".").slice(0, -1).join(".")}.<another-role>}` }, `Use a different text style. It is "{${alias}}" now. To change the style itself, edit {${alias}}.`)
|
|
727
|
+
];
|
|
728
|
+
}
|
|
729
|
+
if (type === "fontFamily") {
|
|
730
|
+
const stack = Array.isArray(value) ? value : value ? [value] : null;
|
|
731
|
+
return [
|
|
732
|
+
entry("set the font stack", { $value: literal, reason: REASON }, `Named families first, in order of preference, then a system or generic fallback (system-ui, ui-monospace, sans-serif, serif, monospace) so text still renders where the font is missing.${stack ? ` It is ${JSON.stringify(stack)} now.` : ""} Fonts are referenced by NAME and never bundled: the product installs or registers each named family on every platform it ships (\`tanrei build\` lists them).`),
|
|
733
|
+
entry("re-point alias", { $value: `{${NS3}.ref.typeface.<brand|plain|mono|icon>}` }, `Follow one of the system\u2019s typefaces${alias ? ` \u2014 it is "{${alias}}" now` : ""}. Every text style that uses that typeface follows with it.`)
|
|
734
|
+
];
|
|
735
|
+
}
|
|
736
|
+
if (type === "typography") {
|
|
737
|
+
operations.push(entry("scale", { scale: { fontSize: 1.125 } }, "Multiply the inherited rule of the named fields; the token still follows dial.type.base."));
|
|
738
|
+
operations.push(entry("pin $value", { $value: { fontSize: { value: 11, unit: "px" } }, reason: REASON }, "Pins only the named fields (fontSize, lineHeight, fontWeight, \u2026); the others keep following their rules."));
|
|
739
|
+
operations.push(entry("derive", { derive: { fontSize: { fn: "mul", of: `{${NS3}.dial.type.base}`, by: 1.25 } } }, "Replace the rule of a field. Closed rule language: mul, scale, clamp, em."));
|
|
740
|
+
return operations;
|
|
741
|
+
}
|
|
742
|
+
if (kind === "alias") {
|
|
743
|
+
operations.push(entry("re-point alias", { $value: `{${alias.split(".").slice(0, -1).join(".")}.<another-step>}` }, `Use a different step of the same scale. It is "{${alias}}" now. The target must exist and be of the same $type.`));
|
|
744
|
+
if (["dimension", "duration", "number"].includes(type)) operations.push(entry("scale", { scale: 2 }, "N \xD7 the inherited alias target, still following its dial."));
|
|
745
|
+
}
|
|
746
|
+
if (kind === "derived" && rule?.fn === "pick") operations.push({ op: "note", effect: `This value follows the choice ${rule.by}: each of its names sets its own value (${Object.entries(rule.values ?? {}).map(([name, v]) => `${name}: ${typeof v === "object" && v !== null ? `${v.value}${v.unit ?? ""}` : v}`).join(", ")}). Choose another name there to change it with the others it sets, or pin this one.` });
|
|
747
|
+
if (kind === "derived" && rule?.fn === "mul") operations.push(entry("scale", { scale: 1.5 }, `N \xD7 the inherited rule (${rule.of} \xD7 ${rule.by}); still follows the dial. Composes with a parent layer's scale.`));
|
|
748
|
+
if (kind === "derived" || kind === "fixed") operations.push(entry("re-point alias", { $value: `{${NS3}.sys.<scale>.<step>}` }, "Make it follow another token instead of its own rule."));
|
|
749
|
+
operations.push(entry("derive", { derive: { fn: "mul", of: `{${NS3}.dial.<family>.unit}`, by: 3 } }, "Replace the rule. Closed language: mul (with optional round and min: max(min, round(of \xD7 by, round))), add (max(min, of + by \xD7 times): a step a number of units from another value), scale, clamp, sub (max(0, of \u2212 by): a corner inside another at an inset), pad (max(0, of \xD7 by + (height \u2212 height\u2081) / 2): a block padding that follows the height of its box), and pick (a value set by a choice of kind) for numbers. No other arithmetic, conditionals or functions of your own."));
|
|
750
|
+
operations.push(entry("pin $value", { $value: literal, reason: REASON }, "A literal that no longer follows any dial. Last resort; the reason is mandatory and is written into the generated tokens."));
|
|
751
|
+
if (kind === "fixed") operations.unshift({ op: "note", effect: `This token is fixed${rule?.fixed ? ` ("${rule.fixed}")` : ""}: "scale" is not legal on it \u2014 pin another $value (with a reason) or give it a rule.` });
|
|
752
|
+
return operations;
|
|
753
|
+
}
|
|
754
|
+
function extensionRecipes({ id, type, rule, alias, axis, choices }, layerId = "<layer id>", { namespace: NS3 = DEFAULT_NAMESPACE } = {}) {
|
|
755
|
+
const recipes = [];
|
|
756
|
+
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
757
|
+
if (choices?.length) return [];
|
|
758
|
+
const parent = id.split(".").slice(0, -1).join(".");
|
|
759
|
+
if (axis) {
|
|
760
|
+
recipes.push({ op: `add a ${axis.id.split(".").at(-1)}`, write: { vocabulary: { [`${axis.id}.<new-value>`]: { from: axis.key, ...axis.id.endsWith(".size") ? { scale: 1.5 } : {}, rationale: RATIONALE } } }, effect: `One line values every member of the axis from "${axis.key}"${axis.id.endsWith(".size") ? ", scaled and still following the dials" : "; the system\u2019s pattern rules value its hovered, focused, pressed and disabled tokens"}. Override single members under "tokens". Existing values: ${axis.values.join(", ")}.` });
|
|
761
|
+
} else if (id.startsWith(`${NS3}.sys.motion.spring.`)) {
|
|
762
|
+
const [scheme, name] = id.split(".").slice(4);
|
|
763
|
+
recipes.push({ op: "add a spring set", write: { vocabulary: { [`${NS3}.sys.motion.spring.${scheme}.<new-name>`]: { from: name, rationale: RATIONALE } } }, effect: `A named spring is a group of four tokens (damping, stiffness, easing, duration), so it is cloned whole from "${name}" and can never be half a spring; change single fields under "tokens". Declare it in every spring scheme the product uses (standard, expressive).` });
|
|
764
|
+
} else if (tierOf(id) === "sys" && !id.startsWith(SYS_COLOR4)) {
|
|
765
|
+
const definition = type === "typography" ? { $value: "<a full text style, or an alias to another role>" } : rule?.fn === "mul" ? { derive: { ...rule, by: "<coefficient>" } } : alias ? { $value: `{${alias}}` } : { $value: sample(type), reason: REASON };
|
|
766
|
+
recipes.push({ op: "add a step to this series", write: { vocabulary: { [`${parent}.<new-step>`]: { $type: type, rationale: RATIONALE, ...definition } } }, effect: "A new step next to this one, dial-driven like its neighbours. Platforms keep their named fields for core steps and reach yours through a typed accessor generated with your system." });
|
|
767
|
+
}
|
|
768
|
+
recipes.push({ op: "add your own token", write: { vocabulary: { [`${layerId}.comp.<your-component>.<part>`]: { $type: type, rationale: RATIONALE, $value: `{${id}}` } } }, effect: `For your own components: lives in your layer's namespace ("${layerId}.\u2026"), may reference any ${NS3}.* token (here: this one), follows dials and schemes, and is generated for every platform as a typed object next to your system.` });
|
|
769
|
+
return recipes;
|
|
770
|
+
}
|
|
771
|
+
function dependencyIndex(documents) {
|
|
772
|
+
const dependents = /* @__PURE__ */ new Map();
|
|
773
|
+
const add = (from, to) => (dependents.get(to) ?? dependents.set(to, /* @__PURE__ */ new Set()).get(to)).add(from);
|
|
774
|
+
for (const doc of Object.values(documents)) {
|
|
775
|
+
for (const { id, token } of walkTokens(doc)) {
|
|
776
|
+
if (typeof token.$value === "string" && /^\{[^}]+\}$/.test(token.$value)) add(id, token.$value.slice(1, -1));
|
|
777
|
+
for (const dep of ruleDependencies(token.$extensions?.[DERIVE])) add(id, dep);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
const followers = (id, seen = /* @__PURE__ */ new Set()) => {
|
|
781
|
+
for (const next of dependents.get(id) ?? []) if (!seen.has(next)) followers(next, seen.add(next));
|
|
782
|
+
return seen;
|
|
783
|
+
};
|
|
784
|
+
return { dependents, followers };
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// ../token-engine/src/vocabulary.js
|
|
788
|
+
var AXES = "dev.tanrei.axes";
|
|
789
|
+
var KEY = /^[a-z0-9][a-z0-9-]*$/;
|
|
790
|
+
var isRef3 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
791
|
+
var clone2 = (v) => JSON.parse(JSON.stringify(v));
|
|
792
|
+
var kindOf = (entry, id) => "document" in entry ? "component" : !("from" in entry) ? "token" : id.split(".")[1] === "sys" ? "group" : "axis-value";
|
|
793
|
+
var heldDocumentPath = (layerId, component) => `systems/${layerId}/comp/${component}.tokens.json`;
|
|
794
|
+
var componentDocumentPath = (component) => `comp/${component}.tokens.json`;
|
|
795
|
+
var isHeldDocument = (name) => name.startsWith("systems/");
|
|
796
|
+
function componentDeclaration(id, entry, layerId, CORE_NS) {
|
|
797
|
+
const segments2 = id.split(".");
|
|
798
|
+
if (segments2[0] !== CORE_NS || segments2[1] !== "comp" || segments2.length !== 3) throw new SystemError(`${id}: a component's whole vocabulary is declared as "${CORE_NS}.comp.<component>", in the core namespace, so that the names a product, a stylesheet and the native types use do not depend on where the component lives`);
|
|
799
|
+
const component = segments2[2];
|
|
800
|
+
if (entry.document !== componentDocumentPath(component)) throw new SystemError(`${id}: "document" is "${componentDocumentPath(component)}" \u2014 the component's document, kept in tokens/systems/${layerId}/`);
|
|
801
|
+
for (const key of ["$type", "from", "scale", "$value", "derive", "onRole"]) if (key in entry) throw new SystemError(`${id}: a component's whole vocabulary is its document; "${key}" belongs to a single token`);
|
|
802
|
+
for (const rule of entry.rules ?? []) {
|
|
803
|
+
if (typeof rule?.match !== "string" || !rule.match.startsWith(`${CORE_NS}.comp.${component}.`)) throw new SystemError(`${id}: its rules value the component's own states \u2014 "match" starts with "${CORE_NS}.comp.${component}.", not ${JSON.stringify(rule?.match)}`);
|
|
804
|
+
}
|
|
805
|
+
return component;
|
|
806
|
+
}
|
|
807
|
+
function borrowed({ name, from }, layer, lend, CORE_NS) {
|
|
808
|
+
const id = `${CORE_NS}.comp.${name}`;
|
|
809
|
+
if (!lend) throw new SystemError(`${layer.id}: components.include takes "${name}" from "${from}"; building it needs that layer \u2014 pass "lend"`);
|
|
810
|
+
const entry = lend(from)?.vocabulary?.[id];
|
|
811
|
+
if (!entry || typeof entry !== "object" || !("document" in entry)) throw new SystemError(`${layer.id}: components.include: "${name}" does not live in "${from}" \u2014 that layer declares no "${id}" with its document`);
|
|
812
|
+
return { id, component: componentDeclaration(id, entry, from, CORE_NS), entry };
|
|
813
|
+
}
|
|
814
|
+
function collectVocabulary(layers, { namespace: CORE_NS = "tanrei", lend } = {}) {
|
|
815
|
+
const out = {};
|
|
816
|
+
const copy = (rules) => JSON.parse(JSON.stringify(rules ?? []));
|
|
817
|
+
for (const layer of layers) {
|
|
818
|
+
for (const include of layer.components?.include ?? []) {
|
|
819
|
+
if (typeof include !== "object" || include === null) continue;
|
|
820
|
+
const { id, component, entry } = borrowed(include, layer, lend, CORE_NS);
|
|
821
|
+
if (out[id]) throw new SystemError(`${layer.id}: components.include: "${component}" is already in this system (declared by layer "${out[id].declaredBy}"); there is nothing to include`);
|
|
822
|
+
out[id] = { kind: "component", component, document: entry.document, rules: copy(entry.rules), rationale: entry.rationale, declaredBy: include.from, includedBy: layer.id, definition: {} };
|
|
823
|
+
}
|
|
824
|
+
for (const [id, entry] of Object.entries(layer.vocabulary ?? {})) {
|
|
825
|
+
if (out[id]) throw new SystemError(`${id}: already declared by layer "${out[id].declaredBy}". Declare a token once; change its value under "tokens".`);
|
|
826
|
+
if (typeof entry.rationale !== "string" || entry.rationale.length < 8) throw new SystemError(`${id}: an extension needs a "rationale" \u2014 why does this design system or product need it?`);
|
|
827
|
+
const namespace = id.split(".")[0];
|
|
828
|
+
const kind = kindOf(entry, id);
|
|
829
|
+
if (kind === "component") {
|
|
830
|
+
const component = componentDeclaration(id, entry, layer.id, CORE_NS);
|
|
831
|
+
out[id] = { kind, component, document: entry.document, rules: copy(entry.rules), rationale: entry.rationale, description: entry.$description, declaredBy: layer.id, definition: {} };
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
if (namespace !== CORE_NS) {
|
|
835
|
+
if (namespace !== layer.id) throw new SystemError(`${id}: a layer's own tokens live in its own namespace \u2014 "${layer.id}.\u2026", not "${namespace}.\u2026"`);
|
|
836
|
+
if (kind === "group") throw new SystemError(`${id}: a step cloned with "from" belongs to a series of the core vocabulary \u2014 "${CORE_NS}.sys.<series>.\u2026". In your own namespace declare each token with "$type".`);
|
|
837
|
+
if (kind !== "token") throw new SystemError(`${id}: an axis value belongs to a Tanrei component \u2014 "${CORE_NS}.comp.<component>.<axis>.<value>"`);
|
|
838
|
+
}
|
|
839
|
+
for (const segment of id.split(".").slice(1)) if (!KEY.test(segment)) throw new SystemError(`${id}: "${segment}" is not a valid name (lowercase letters, digits and hyphens)`);
|
|
840
|
+
const { rationale, $description, from, scale, onRole, $type, ...definition } = entry;
|
|
841
|
+
out[id] = { kind, type: $type, from, scale, rationale, description: $description, onRole, declaredBy: layer.id, definition };
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
return out;
|
|
845
|
+
}
|
|
846
|
+
var stamp = (node, decl) => {
|
|
847
|
+
(node.$extensions ??= {})[VOCABULARY] = { rationale: decl.rationale, declaredBy: decl.declaredBy, extension: true, ...decl.onRole ? { onRole: decl.onRole } : {} };
|
|
848
|
+
if (decl.description) node.$description = decl.description;
|
|
849
|
+
};
|
|
850
|
+
var isToken = (node) => node && typeof node === "object" && "$value" in node;
|
|
851
|
+
function groupAt(doc, segments2) {
|
|
852
|
+
let node = doc;
|
|
853
|
+
for (const key of segments2) {
|
|
854
|
+
node = node?.[key];
|
|
855
|
+
if (!node || typeof node !== "object" || isToken(node)) return void 0;
|
|
856
|
+
}
|
|
857
|
+
return node;
|
|
858
|
+
}
|
|
859
|
+
function ownerOf(docs, segments2) {
|
|
860
|
+
let best = null;
|
|
861
|
+
for (const [name, doc] of Object.entries(docs)) {
|
|
862
|
+
let depth = 0;
|
|
863
|
+
while (depth < segments2.length - 1 && groupAt(doc, segments2.slice(0, depth + 1))) depth += 1;
|
|
864
|
+
if (!best || depth > best.depth) best = { name, doc, depth };
|
|
865
|
+
}
|
|
866
|
+
return best;
|
|
867
|
+
}
|
|
868
|
+
function scaleNode(node, factor, id, type) {
|
|
869
|
+
if (factor === 1 || factor === void 0) return;
|
|
870
|
+
if (type !== "dimension" && type !== "number" && type !== "duration") return;
|
|
871
|
+
const ext = node.$extensions ??= {};
|
|
872
|
+
if (isRef3(node.$value)) {
|
|
873
|
+
ext[DERIVE] = { fn: "mul", of: node.$value, by: factor };
|
|
874
|
+
node.$value = null;
|
|
875
|
+
} else if (ext[DERIVE]?.fn === "mul") ext[DERIVE] = { ...ext[DERIVE], by: ext[DERIVE].by * factor };
|
|
876
|
+
else if (ext[DERIVE]?.fn === "pad") ext[DERIVE] = { ...ext[DERIVE], by: (ext[DERIVE].by ?? 1) * factor };
|
|
877
|
+
else throw new SystemError(`${id}: cannot scale a fixed value \u2014 give this member a value under "tokens"`);
|
|
878
|
+
}
|
|
879
|
+
function repointPad(node, componentPath, members, from, value) {
|
|
880
|
+
const rule = node.$extensions?.[DERIVE];
|
|
881
|
+
if (rule?.fn !== "pad" || !isRef3(rule.height)) return;
|
|
882
|
+
const prefix = `${componentPath.join(".")}.`;
|
|
883
|
+
const height = rule.height.slice(1, -1);
|
|
884
|
+
const member = members.find((m) => height === `${prefix}${m}.${from}`);
|
|
885
|
+
if (member) node.$extensions[DERIVE] = { ...rule, height: `{${prefix}${member}.${value}}` };
|
|
886
|
+
}
|
|
887
|
+
function* tokensUnder(node, path11 = [], type) {
|
|
888
|
+
const here = node.$type ?? type;
|
|
889
|
+
if (isToken(node)) {
|
|
890
|
+
yield { path: path11, token: node, type: here };
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object") yield* tokensUnder(child, [...path11, key], here);
|
|
894
|
+
}
|
|
895
|
+
function addAxisValue(docs, id, decl) {
|
|
896
|
+
const segments2 = id.split(".");
|
|
897
|
+
const value = segments2.at(-1);
|
|
898
|
+
const axis = segments2.at(-2);
|
|
899
|
+
const componentPath = segments2.slice(0, -2);
|
|
900
|
+
const home = Object.values(docs).find((doc) => groupAt(doc, componentPath)?.$extensions?.[AXES]);
|
|
901
|
+
const component = home && groupAt(home, componentPath);
|
|
902
|
+
const declared = component?.$extensions[AXES][axis];
|
|
903
|
+
if (!declared) throw new SystemError(`${id}: "${componentPath.join(".")}" has no axis "${axis}". Axes are declared by the component in $extensions["${AXES}"].`);
|
|
904
|
+
const states = component.$extensions[STATES];
|
|
905
|
+
const values = declared.from === "states" ? states.variants : declared.values;
|
|
906
|
+
if (!values.includes(decl.from)) throw new SystemError(`${id}: "from" must be an existing ${axis} (${values.join(", ")}), not "${decl.from}"`);
|
|
907
|
+
if (values.includes(value)) throw new SystemError(`${id}: "${value}" is a core ${axis} of ${componentPath.join(".")}; a layer declares only what the core lacks: delete this declaration (its values under "tokens" stay)`);
|
|
908
|
+
if ((states?.states ?? []).includes(value)) throw new SystemError(`${id}: "${value}" is an interaction state; states are not extensible`);
|
|
909
|
+
if (declared.from === "states") {
|
|
910
|
+
if (component[value]) throw new SystemError(`${id}: "${componentPath.join(".")}.${value}" already exists`);
|
|
911
|
+
const copy = clone2(component[decl.from]);
|
|
912
|
+
const own2 = `{${[...componentPath, decl.from].join(".")}.`;
|
|
913
|
+
for (const { token } of tokensUnder(copy)) {
|
|
914
|
+
if (typeof token.$value === "string" && token.$value.startsWith(own2)) token.$value = `{${[...componentPath, value].join(".")}.${token.$value.slice(own2.length)}`;
|
|
915
|
+
stamp(token, decl);
|
|
916
|
+
}
|
|
917
|
+
component[value] = copy;
|
|
918
|
+
states.variants = [...states.variants, value];
|
|
919
|
+
} else {
|
|
920
|
+
for (const member of declared.members) {
|
|
921
|
+
const group = groupAt(home, [...componentPath, ...member.split(".")]);
|
|
922
|
+
if (!group || !isToken(group[decl.from])) throw new SystemError(`${id}: axis member "${member}" has no "${decl.from}"`);
|
|
923
|
+
const copy = clone2(group[decl.from]);
|
|
924
|
+
const factor = typeof decl.scale === "object" ? decl.scale[member] : decl.scale;
|
|
925
|
+
repointPad(copy, componentPath, declared.members, decl.from, value);
|
|
926
|
+
scaleNode(copy, factor, `${componentPath.join(".")}.${member}.${value}`, copy.$type ?? group.$type);
|
|
927
|
+
stamp(copy, decl);
|
|
928
|
+
group[value] = copy;
|
|
929
|
+
}
|
|
930
|
+
if (typeof decl.scale === "object") {
|
|
931
|
+
for (const member of Object.keys(decl.scale)) if (!declared.members.includes(member)) throw new SystemError(`${id}: "scale" names "${member}", which is not a member of the ${axis} axis (${declared.members.join(", ")})`);
|
|
932
|
+
}
|
|
933
|
+
declared.values = [...declared.values, value];
|
|
934
|
+
}
|
|
935
|
+
(declared.extensions ??= []).push({ value, declaredBy: decl.declaredBy });
|
|
936
|
+
}
|
|
937
|
+
function addComponent(docs, id, decl, CORE_NS) {
|
|
938
|
+
const held2 = heldDocumentPath(decl.declaredBy, decl.component);
|
|
939
|
+
const name = componentDocumentPath(decl.component);
|
|
940
|
+
if (docs[name]) throw new SystemError(`${id}: the core vocabulary already has ${name}; a component lives in one place \u2014 the core, or the one layer that declares it`);
|
|
941
|
+
const doc = docs[held2];
|
|
942
|
+
if (!doc) throw new SystemError(`${id}: the component's document (tokens/${held2}) is not among the sources \u2014 pass the documents the layers hold along with the core's`);
|
|
943
|
+
const own2 = (node) => Object.keys(node ?? {}).filter((key) => !key.startsWith("$"));
|
|
944
|
+
if (own2(doc).join() !== CORE_NS || own2(doc[CORE_NS]).join() !== "comp" || own2(doc[CORE_NS].comp).join() !== decl.component) throw new SystemError(`${id}: tokens/${held2} holds the group "${CORE_NS}.comp.${decl.component}" and nothing else`);
|
|
945
|
+
docs[name] = doc;
|
|
946
|
+
}
|
|
947
|
+
function addGroup(docs, id, decl) {
|
|
948
|
+
const segments2 = id.split(".");
|
|
949
|
+
const name = segments2.at(-1);
|
|
950
|
+
const home = Object.values(docs).find((doc) => groupAt(doc, segments2.slice(0, -1)));
|
|
951
|
+
const series = home && groupAt(home, segments2.slice(0, -1));
|
|
952
|
+
const siblings = series ? Object.keys(series).filter((key) => !key.startsWith("$") && !isToken(series[key])) : [];
|
|
953
|
+
if (!series || !siblings.length) throw new SystemError(`${id}: "${segments2.slice(0, -1).join(".")}" is not a series whose steps are groups of tokens (such as ${segments2[0]}.sys.motion.spring.standard). A single token is declared with "$type", not "from".`);
|
|
954
|
+
if (series[name]) throw new SystemError(`${id}: "${name}" is a core step of ${segments2.slice(0, -1).join(".")}; a layer declares only what the core lacks: delete this declaration (its values under "tokens" stay)`);
|
|
955
|
+
if (!siblings.includes(decl.from)) throw new SystemError(`${id}: "from" must be an existing step of ${segments2.slice(0, -1).join(".")} (${siblings.join(", ")}), not "${decl.from}"`);
|
|
956
|
+
if (decl.scale !== void 0) throw new SystemError(`${id}: "scale" does not apply to a cloned step; change its fields under "tokens"`);
|
|
957
|
+
if (Object.entries(series[decl.from]).some(([key, child]) => !key.startsWith("$") && !isToken(child))) throw new SystemError(`${id}: "${decl.from}" is not a step but a group of steps. A cloned step is one named set of tokens, e.g. ${segments2.slice(0, -1).join(".")}.${decl.from}.<name>.`);
|
|
958
|
+
const copy = clone2(series[decl.from]);
|
|
959
|
+
for (const { token } of tokensUnder(copy)) stamp(token, decl);
|
|
960
|
+
if (decl.description) copy.$description = decl.description;
|
|
961
|
+
series[name] = copy;
|
|
962
|
+
}
|
|
963
|
+
function addToken(docs, id, decl, core, system) {
|
|
964
|
+
const CORE_NS = system.namespace ?? "tanrei";
|
|
965
|
+
const segments2 = id.split(".");
|
|
966
|
+
if (core.has(id)) {
|
|
967
|
+
const existing = core.get(id);
|
|
968
|
+
if (existing.type !== decl.type) throw new SystemError(`${id}: the core has this id as "${existing.type}", not "${decl.type}". Rename the extension.`);
|
|
969
|
+
throw new SystemError(`${id}: a core token; a layer declares only what the core lacks: delete this declaration, and write its value under "tokens"`);
|
|
970
|
+
}
|
|
971
|
+
if (!decl.type) throw new SystemError(`${id}: a declared token needs "$type"`);
|
|
972
|
+
const namespace = segments2[0];
|
|
973
|
+
let owner;
|
|
974
|
+
if (namespace === CORE_NS) {
|
|
975
|
+
owner = ownerOf(docs, segments2);
|
|
976
|
+
if (!owner || owner.depth < segments2.length - 1) throw new SystemError(`${id}: "${segments2.slice(0, -1).join(".")}" is not a group of the vocabulary. Inside ${CORE_NS}.* a layer adds a step to an existing series (e.g. ${CORE_NS}.sys.space.\u2026); for anything new use your layer's own namespace.`);
|
|
977
|
+
} else {
|
|
978
|
+
const name = `ext/${namespace}.tokens.json`;
|
|
979
|
+
docs[name] ??= {};
|
|
980
|
+
owner = { name, doc: docs[name] };
|
|
981
|
+
}
|
|
982
|
+
let node = owner.doc;
|
|
983
|
+
for (const key of segments2.slice(0, -1)) {
|
|
984
|
+
if (isToken(node[key])) throw new SystemError(`${id}: "${key}" is a token; a token cannot have children`);
|
|
985
|
+
node = node[key] ??= {};
|
|
986
|
+
}
|
|
987
|
+
if (node[segments2.at(-1)]) throw new SystemError(`${id}: a group with this name already exists`);
|
|
988
|
+
const { $value, derive, reason } = decl.definition;
|
|
989
|
+
if (decl.type === "typography" && $value === void 0 && derive) throw new SystemError(`${id}: a text style declared with "derive" alone has no fontFamily, fontWeight or lineHeight \u2014 its rules value only fontSize and letterSpacing. Write "$value" with the whole style, e.g. { "fontFamily": "{${CORE_NS}.ref.typeface.plain}", "fontSize": { "value": 14, "unit": "px" }, "fontWeight": 400, "letterSpacing": { "value": 0, "unit": "px" }, "lineHeight": 1.5 }, and keep "derive" for the fields that follow the dials; or alias an existing style with "$value": "{${CORE_NS}.sys.typescale.<role>}" and no "derive".`);
|
|
990
|
+
const token = { $type: decl.type, $value: $value === void 0 ? null : clone2($value) };
|
|
991
|
+
if (derive) token.$extensions = { [DERIVE]: clone2(derive) };
|
|
992
|
+
else if ($value !== void 0 && !isRef3($value)) token.$extensions = { [DERIVE]: { fixed: reason ?? decl.rationale } };
|
|
993
|
+
stamp(token, decl);
|
|
994
|
+
node[segments2.at(-1)] = token;
|
|
995
|
+
}
|
|
996
|
+
function materializeVocabulary(docs, system) {
|
|
997
|
+
const vocabulary = system.vocabulary ?? {};
|
|
998
|
+
const SYS_COLOR4 = `${system.namespace ?? "tanrei"}.sys.color.`;
|
|
999
|
+
for (const [id, decl] of Object.entries(vocabulary)) if (decl.kind === "component") addComponent(docs, id, decl, system.namespace ?? "tanrei");
|
|
1000
|
+
if (!Object.values(vocabulary).some((decl) => decl.kind !== "component")) return;
|
|
1001
|
+
const core = /* @__PURE__ */ new Map();
|
|
1002
|
+
for (const doc of Object.values(docs)) for (const entry of walkTokens(doc)) core.set(entry.id, entry);
|
|
1003
|
+
const ordered = Object.entries(vocabulary).sort(([, a], [, b]) => Number(a.kind === "axis-value") - Number(b.kind === "axis-value"));
|
|
1004
|
+
for (const [id, decl] of ordered) {
|
|
1005
|
+
if (decl.kind === "component") continue;
|
|
1006
|
+
if (decl.kind === "token" && id.startsWith(SYS_COLOR4)) continue;
|
|
1007
|
+
if (decl.kind === "axis-value") addAxisValue(docs, id, decl);
|
|
1008
|
+
else if (decl.kind === "group") addGroup(docs, id, decl);
|
|
1009
|
+
else addToken(docs, id, decl, core, system);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
function listExtensions(system) {
|
|
1013
|
+
return Object.entries(system.vocabulary ?? {}).map(([id, d]) => ({ id, kind: d.kind, ...d.type ? { $type: d.type } : {}, ...d.from ? { from: d.from } : {}, ...d.document ? { document: d.document } : {}, declaredBy: d.declaredBy, ...d.includedBy ? { includedBy: d.includedBy } : {}, rationale: d.rationale }));
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// ../token-engine/src/system.js
|
|
1017
|
+
var DEFAULT_NAMESPACE2 = "tanrei";
|
|
1018
|
+
var isRef4 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
1019
|
+
var refId3 = (v) => v.slice(1, -1);
|
|
1020
|
+
var clone3 = (v) => JSON.parse(JSON.stringify(v));
|
|
1021
|
+
function mergeLayers(layers, { namespace = DEFAULT_NAMESPACE2, lend } = {}) {
|
|
1022
|
+
const SYS_COLOR4 = `${namespace}.sys.color.`;
|
|
1023
|
+
const merged = { id: layers.at(-1).id, namespace, name: layers.at(-1).name, specVersion: layers[0].specVersion, palettes: {}, paletteLayers: {}, tokens: {}, rules: [], chain: layers.map((l) => l.id), vocabulary: collectVocabulary(layers, { namespace, lend }) };
|
|
1024
|
+
for (const layer of layers) {
|
|
1025
|
+
for (const decl of Object.values(merged.vocabulary)) {
|
|
1026
|
+
if (decl.kind === "component" && (decl.includedBy ?? decl.declaredBy) === layer.id) merged.rules.push(...clone3(decl.rules));
|
|
1027
|
+
}
|
|
1028
|
+
for (const [id, decl] of Object.entries(merged.vocabulary)) {
|
|
1029
|
+
if (decl.declaredBy === layer.id && decl.kind === "token" && id.startsWith(SYS_COLOR4)) merged.tokens[id] = { ...clone3(decl.definition), layer: layer.id };
|
|
1030
|
+
}
|
|
1031
|
+
if (layer.specVersion) merged.specVersion = layer.specVersion;
|
|
1032
|
+
for (const [name, declaration] of Object.entries(layer.palettes ?? {})) {
|
|
1033
|
+
if (declaration === null) {
|
|
1034
|
+
delete merged.palettes[name];
|
|
1035
|
+
delete merged.paletteLayers[name];
|
|
1036
|
+
} else {
|
|
1037
|
+
merged.paletteLayers[name] ??= layer.id;
|
|
1038
|
+
merged.palettes[name] = clone3(declaration);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
merged.rules.push(...clone3(layer.rules ?? []).map((rule) => ({ ...rule, layer: void 0 })));
|
|
1042
|
+
for (const [id, op] of Object.entries(layer.tokens ?? {})) {
|
|
1043
|
+
const previous = merged.tokens[id];
|
|
1044
|
+
const replaces = "$value" in op || "derive" in op;
|
|
1045
|
+
const inherited = replaces ? 1 : previous?.scale ?? 1;
|
|
1046
|
+
const own2 = op.scale ?? 1;
|
|
1047
|
+
let scale;
|
|
1048
|
+
if (typeof inherited === "number" && typeof own2 === "number") scale = inherited * own2;
|
|
1049
|
+
else {
|
|
1050
|
+
const fields = (v) => typeof v === "number" ? { fontSize: v } : v;
|
|
1051
|
+
const [x, y] = [fields(inherited), fields(own2)];
|
|
1052
|
+
scale = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(x), ...Object.keys(y)])].map((field) => [field, (x[field] ?? 1) * (y[field] ?? 1)]));
|
|
1053
|
+
}
|
|
1054
|
+
merged.tokens[id] = { ...replaces ? {} : previous, ...clone3(op), ...scale !== 1 ? { scale } : {}, layer: layer.id };
|
|
1055
|
+
if (scale === 1) delete merged.tokens[id].scale;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
return merged;
|
|
1059
|
+
}
|
|
1060
|
+
function scaleRule(rule, factor, id) {
|
|
1061
|
+
if (!rule || "fixed" in rule) throw new SystemError(`${id}: cannot scale a fixed value \u2014 set "$value" instead`);
|
|
1062
|
+
if (rule.fn === "mul") return { ...rule, by: rule.by * factor };
|
|
1063
|
+
if (rule.fn === "pad") return { ...rule, by: (rule.by ?? 1) * factor };
|
|
1064
|
+
throw new SystemError(`${id}: "scale" is supported on "mul" and "pad" rules and aliases, not on "${rule.fn}"`);
|
|
1065
|
+
}
|
|
1066
|
+
function generatedFrom(id, op, type, { namespace, stateIds }) {
|
|
1067
|
+
if (id.startsWith(`${namespace}.sys.color.`)) return "roles";
|
|
1068
|
+
if (stateIds.has(id)) return "states";
|
|
1069
|
+
if (type === "color" && id.startsWith(`${namespace}.comp.`) && isColorRule(op)) return "colors";
|
|
1070
|
+
return null;
|
|
1071
|
+
}
|
|
1072
|
+
var stateIdsOf = (documents) => new Set(expandStateVocabulary(Object.entries(documents).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc)).map((v) => v.id));
|
|
1073
|
+
function resolveNumericTokens(sources2, system) {
|
|
1074
|
+
const NS3 = system.namespace ?? DEFAULT_NAMESPACE2;
|
|
1075
|
+
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
1076
|
+
const isColorRef = (id) => id.startsWith(SYS_COLOR4) || id.startsWith(`${NS3}.ref.palette.`) || id.startsWith(`${NS3}.ref.alpha.`);
|
|
1077
|
+
const docs = Object.fromEntries(Object.entries(sources2).map(([name, doc]) => [name, clone3(doc)]));
|
|
1078
|
+
const work = { ...system, tokens: clone3(system.tokens) };
|
|
1079
|
+
materializeVocabulary(docs, work);
|
|
1080
|
+
for (const name of Object.keys(docs)) if (isHeldDocument(name)) delete docs[name];
|
|
1081
|
+
const index2 = /* @__PURE__ */ new Map();
|
|
1082
|
+
for (const doc of Object.values(docs)) for (const entry of walkTokens(doc)) index2.set(entry.id, entry);
|
|
1083
|
+
const stateIds = stateIdsOf(docs);
|
|
1084
|
+
for (const [id, op] of Object.entries(work.tokens)) {
|
|
1085
|
+
const entry = index2.get(id);
|
|
1086
|
+
const generated = generatedFrom(id, op, entry?.type, { namespace: NS3, stateIds });
|
|
1087
|
+
if (generated === "roles" || generated === "states") continue;
|
|
1088
|
+
if (!entry) throw new SystemError(`${id}: unknown token (layer "${op.layer}"). To add it, declare it under "vocabulary" with a rationale.`);
|
|
1089
|
+
if (op.$type && op.$type !== entry.type) throw new SystemError(`${id}: a layer cannot change $type (${entry.type} \u2192 ${op.$type})`);
|
|
1090
|
+
if (generated) continue;
|
|
1091
|
+
const token = entry.token;
|
|
1092
|
+
const ext = token.$extensions ??= {};
|
|
1093
|
+
const names = ext[ENUM]?.values;
|
|
1094
|
+
if (names) {
|
|
1095
|
+
if ("scale" in op || "derive" in op) throw new SystemError(`${id}: a choice of kind is neither scaled nor derived. Choose one of its names: { "$value": "${names[1] ?? names[0]}", "reason": "\u2026" } (${names.join(" | ")}).`);
|
|
1096
|
+
if ("$value" in op && !isRef4(op.$value)) {
|
|
1097
|
+
const index3 = typeof op.$value === "string" ? names.indexOf(op.$value) : op.$value;
|
|
1098
|
+
if (!Number.isInteger(index3) || index3 < 0 || index3 >= names.length) throw new SystemError(`${id}: ${JSON.stringify(op.$value)} is not one of its choices (layer "${op.layer}"). Allowed: ${names.map((name, i) => `"${name}" (${i})`).join(", ")}. The list is part of the vocabulary; a layer chooses among the names, it does not add one.`);
|
|
1099
|
+
op.$value = index3;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
if ("$value" in op) {
|
|
1103
|
+
if (isRef4(op.$value)) {
|
|
1104
|
+
if (!index2.has(refId3(op.$value)) && !isColorRef(refId3(op.$value))) throw new SystemError(`${id}: alias target ${op.$value} does not exist`);
|
|
1105
|
+
token.$value = op.$value;
|
|
1106
|
+
delete ext[DERIVE];
|
|
1107
|
+
} else {
|
|
1108
|
+
if (typeof op.reason !== "string" || op.reason.length < 8) throw new SystemError(`${id}: pinning a fixed value needs a "reason"`);
|
|
1109
|
+
if (entry.type === "typography" && typeof op.$value === "object") {
|
|
1110
|
+
const rule = clone3(ext[DERIVE] ?? {});
|
|
1111
|
+
for (const field of Object.keys(op.$value)) delete rule[field];
|
|
1112
|
+
token.$value = { ...token.$value, ...op.$value };
|
|
1113
|
+
ext[DERIVE] = Object.keys(rule).length ? { ...rule, pinned: { fields: Object.keys(op.$value), reason: op.reason } } : { fixed: op.reason };
|
|
1114
|
+
} else {
|
|
1115
|
+
token.$value = op.$value;
|
|
1116
|
+
ext[DERIVE] = { fixed: op.reason };
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
if ("derive" in op) {
|
|
1121
|
+
const pinned = ext[DERIVE]?.pinned;
|
|
1122
|
+
if (isRef4(token.$value) && entry.type !== "typography") token.$value = null;
|
|
1123
|
+
ext[DERIVE] = clone3(op.derive);
|
|
1124
|
+
if (pinned) for (const field of pinned.fields) delete ext[DERIVE][field];
|
|
1125
|
+
if (pinned) ext[DERIVE].pinned = pinned;
|
|
1126
|
+
}
|
|
1127
|
+
if ("scale" in op) {
|
|
1128
|
+
const factors = typeof op.scale === "number" ? null : op.scale;
|
|
1129
|
+
if (isRef4(token.$value) && entry.type === "typography") throw new SystemError(`${id}: "scale" does not apply to an alias of a text style. Re-point it to another text style, or scale ${token.$value} itself.`);
|
|
1130
|
+
if (isRef4(token.$value)) {
|
|
1131
|
+
ext[DERIVE] = { fn: "mul", of: token.$value, by: op.scale };
|
|
1132
|
+
token.$value = null;
|
|
1133
|
+
} else if (entry.type === "typography") {
|
|
1134
|
+
const rule = ext[DERIVE];
|
|
1135
|
+
const f = factors ?? { fontSize: op.scale };
|
|
1136
|
+
for (const [field, n] of Object.entries(f)) rule[field] = scaleRule(rule[field], n, `${id}.${field}`);
|
|
1137
|
+
} else {
|
|
1138
|
+
ext[DERIVE] = scaleRule(ext[DERIVE], op.scale, id);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
for (const [id, { token }] of index2) if (token.$value === null && !token.$extensions?.[DERIVE]) throw new SystemError(`${id}: declared under "vocabulary" but never given a value \u2014 add "$value" or "derive" to the declaration, or an entry under "tokens"`);
|
|
1143
|
+
const state = /* @__PURE__ */ new Map();
|
|
1144
|
+
const resolve = (id, trail = []) => {
|
|
1145
|
+
if (isColorRef(id)) return { color: id };
|
|
1146
|
+
const entry = index2.get(id);
|
|
1147
|
+
if (!entry) throw new SystemError(`${trail.at(-1) ?? "?"}: references unknown token {${id}}`);
|
|
1148
|
+
if (trail.length && trail.at(-1).startsWith(`${NS3}.`) && !id.startsWith(`${NS3}.`)) throw new SystemError(`${trail.at(-1)}: a ${NS3}.* token cannot reference {${id}}, a token in a layer's own namespace`);
|
|
1149
|
+
if (state.get(id) === "visiting") throw new SystemError(`cycle: ${[...trail, id].join(" \u2192 ")}`);
|
|
1150
|
+
const { token, type } = entry;
|
|
1151
|
+
if (state.get(id) !== "done") {
|
|
1152
|
+
state.set(id, "visiting");
|
|
1153
|
+
const rule = token.$extensions?.[DERIVE];
|
|
1154
|
+
const lookup = (dep) => resolve(dep, [...trail, id]);
|
|
1155
|
+
if (isRef4(token.$value)) resolve(refId3(token.$value), [...trail, id]);
|
|
1156
|
+
else if (rule && !("fixed" in rule)) {
|
|
1157
|
+
if (type === "typography") {
|
|
1158
|
+
if (!token.$value || typeof token.$value !== "object") throw new SystemError(`${id}: a text style's "derive" values its fontSize and letterSpacing, and this one has no style to write them into (${JSON.stringify(token.$value)}). Give it "$value" with the whole style \u2014 fontFamily, fontSize, fontWeight, letterSpacing, lineHeight \u2014 and keep "derive" for the fields that follow the dials.`);
|
|
1159
|
+
if (rule.fontSize) token.$value.fontSize = evaluateNumeric(rule.fontSize, lookup, { type: "dimension" });
|
|
1160
|
+
if (rule.letterSpacing) token.$value.letterSpacing = evaluateNumeric(rule.letterSpacing, lookup, { type: "dimension", fontSize: token.$value.fontSize.value });
|
|
1161
|
+
} else {
|
|
1162
|
+
const result = evaluateNumeric(rule, lookup, { type, unscaled });
|
|
1163
|
+
token.$value = type === "number" ? result.value : result;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
state.set(id, "done");
|
|
1167
|
+
}
|
|
1168
|
+
const v = isRef4(token.$value) ? resolve(refId3(token.$value), [...trail, id]) : token.$value;
|
|
1169
|
+
return typeof v === "number" ? { value: v, names: token.$extensions?.[ENUM]?.values } : v;
|
|
1170
|
+
};
|
|
1171
|
+
const unscaled = unscaledLookup((id) => {
|
|
1172
|
+
const entry = index2.get(id);
|
|
1173
|
+
if (!entry) return { value: resolve(id) };
|
|
1174
|
+
const rule = entry.token.$extensions?.[DERIVE];
|
|
1175
|
+
if (isRef4(entry.token.$value)) return { alias: refId3(entry.token.$value) };
|
|
1176
|
+
return rule && !("fixed" in rule) && entry.type !== "typography" ? { rule, type: entry.type } : { value: resolve(id), reference: entry.token.$extensions?.[REFERENCE] };
|
|
1177
|
+
});
|
|
1178
|
+
for (const id of index2.keys()) resolve(id);
|
|
1179
|
+
for (const [id, { token }] of index2) for (const dep of ruleDependencies(token.$extensions?.[DERIVE])) if (!index2.has(dep) && !isColorRef(dep)) throw new SystemError(`${id}: rule references unknown token {${dep}}`);
|
|
1180
|
+
return docs;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// ../../tanrei.config.json
|
|
1184
|
+
var tanrei_config_default = {
|
|
1185
|
+
$comment: "Single source for naming. Every generated artifact derives names from here; never hardcode them elsewhere. Checked by `pnpm validate`.",
|
|
1186
|
+
name: "Tanrei",
|
|
1187
|
+
namespace: "tanrei",
|
|
1188
|
+
version: "0.1.0-next.1",
|
|
1189
|
+
license: "Apache-2.0",
|
|
1190
|
+
site: "https://tanrei.chnotchy.com",
|
|
1191
|
+
repository: {
|
|
1192
|
+
public: "chnotchy/tanrei"
|
|
1193
|
+
},
|
|
1194
|
+
packages: {
|
|
1195
|
+
npmScope: "@tanrei",
|
|
1196
|
+
swiftPackage: "Tanrei",
|
|
1197
|
+
mavenGroup: "io.github.chnotchy",
|
|
1198
|
+
mavenArtifactPrefix: "tanrei",
|
|
1199
|
+
pubPackage: "tanrei"
|
|
1200
|
+
},
|
|
1201
|
+
web: {
|
|
1202
|
+
cssPrefix: "--tanrei",
|
|
1203
|
+
tagPrefix: "tanrei"
|
|
1204
|
+
},
|
|
1205
|
+
platforms: ["web", "swiftui", "compose", "flutter", "react-native"],
|
|
1206
|
+
statuses: ["planned", "lagging", "alpha", "beta", "stable", "deprecated"]
|
|
1207
|
+
};
|
|
1208
|
+
|
|
1209
|
+
// ../tokens-build/src/config.js
|
|
1210
|
+
var CONFIG = tanrei_config_default;
|
|
1211
|
+
|
|
1212
|
+
// ../tokens-build/src/pure.js
|
|
1213
|
+
var SYSTEM_ID = /^[a-z0-9][a-z0-9-]*$/;
|
|
1214
|
+
var isSystemId = (value) => typeof value === "string" && SYSTEM_ID.test(value);
|
|
1215
|
+
function assertSystemId(value, where = '"extends"') {
|
|
1216
|
+
if (!isSystemId(value)) throw new Error(`${where}: ${JSON.stringify(value) ?? String(value)} is not a system id (lowercase letters, digits and hyphens: ${SYSTEM_ID.source}). A parent layer is named by its id, never by a path.`);
|
|
1217
|
+
return value;
|
|
1218
|
+
}
|
|
1219
|
+
var kebab = (parts) => parts.join("-");
|
|
1220
|
+
function rgba(color) {
|
|
1221
|
+
const [r, g, b] = color.components.map((c) => Math.round(c * 255));
|
|
1222
|
+
return { r, g, b, a: color.alpha ?? 1 };
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
// ../tokens-build/src/layers.js
|
|
1226
|
+
var ROOT_SYSTEM = "core";
|
|
1227
|
+
var DEFAULT_SYSTEM = CONFIG.namespace;
|
|
1228
|
+
function layerChain(id, read) {
|
|
1229
|
+
const chain = [];
|
|
1230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1231
|
+
for (let current = id; current; current = chain[0].extends) {
|
|
1232
|
+
if (chain.length) assertSystemId(current, `${chain[0].id}.system.json "extends"`);
|
|
1233
|
+
if (seen.has(current)) throw new Error(`"extends" cycle: ${[...seen, current].join(" \u2192 ")}`);
|
|
1234
|
+
seen.add(current);
|
|
1235
|
+
chain.unshift(read(current));
|
|
1236
|
+
}
|
|
1237
|
+
if (chain[0].id !== ROOT_SYSTEM) throw new Error(`system "${id}" does not extend "${ROOT_SYSTEM}"`);
|
|
1238
|
+
return chain;
|
|
1239
|
+
}
|
|
1240
|
+
var includedName = (include) => typeof include === "string" ? include : include.name;
|
|
1241
|
+
function heldComponents(ids, read) {
|
|
1242
|
+
const held2 = /* @__PURE__ */ new Map();
|
|
1243
|
+
const prefix = `${CONFIG.namespace}.comp.`;
|
|
1244
|
+
for (const id of ids) {
|
|
1245
|
+
for (const [key, entry] of Object.entries(read(id).vocabulary ?? {})) {
|
|
1246
|
+
if (key.startsWith(prefix) && entry && typeof entry === "object" && "document" in entry) held2.set(key.slice(prefix.length), id);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return held2;
|
|
1250
|
+
}
|
|
1251
|
+
function outsideComponents(chain, held2) {
|
|
1252
|
+
const ids = new Set(chain.map((layer) => layer.id));
|
|
1253
|
+
const included = new Set(chain.flatMap((layer) => (layer.components?.include ?? []).filter((include) => typeof include === "object").map(includedName)));
|
|
1254
|
+
return Object.fromEntries([...held2].filter(([name, layer]) => !ids.has(layer) && !included.has(name)));
|
|
1255
|
+
}
|
|
1256
|
+
function componentChoices(chain) {
|
|
1257
|
+
const components = /* @__PURE__ */ new Map();
|
|
1258
|
+
const variants = /* @__PURE__ */ new Map();
|
|
1259
|
+
const variantsOf2 = (name) => variants.get(name) ?? variants.set(name, /* @__PURE__ */ new Map()).get(name);
|
|
1260
|
+
for (const layer of chain) {
|
|
1261
|
+
const own2 = layer.components ?? {};
|
|
1262
|
+
for (const [name, { reason, insteadUse }] of Object.entries(own2.omit ?? {})) {
|
|
1263
|
+
components.delete(name);
|
|
1264
|
+
components.set(name, { layer: layer.id, reason, ...insteadUse ? { insteadUse: [...insteadUse] } : {} });
|
|
1265
|
+
}
|
|
1266
|
+
for (const include of own2.include ?? []) components.delete(includedName(include));
|
|
1267
|
+
for (const [name, { omit = [], include = [] }] of Object.entries(own2.variants ?? {})) {
|
|
1268
|
+
const values = variantsOf2(name);
|
|
1269
|
+
for (const value of omit) values.delete(value), values.set(value, { layer: layer.id });
|
|
1270
|
+
for (const value of include) values.delete(value);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
for (const [name, values] of variants) if (!values.size) variants.delete(name);
|
|
1274
|
+
return { components, variants };
|
|
1275
|
+
}
|
|
1276
|
+
function omittedOf(chain, held2, standIns = /* @__PURE__ */ new Map()) {
|
|
1277
|
+
const { components: left } = componentChoices(chain);
|
|
1278
|
+
const outside = outsideComponents(chain, held2);
|
|
1279
|
+
const ships = (name) => !left.has(name) && !outside[name];
|
|
1280
|
+
return [
|
|
1281
|
+
...[...left].map(([name, { layer, reason, insteadUse }]) => ({ name, omittedBy: layer, ...reason ? { reason } : {}, ...insteadUse ? { insteadUse } : {} })),
|
|
1282
|
+
...Object.entries(outside).map(([name, layer]) => {
|
|
1283
|
+
const instead = standIns.get(name);
|
|
1284
|
+
const insteadUse = instead?.insteadUse.filter(ships) ?? [];
|
|
1285
|
+
return { name, providedBy: layer, ...instead ? { reason: instead.reason } : {}, ...insteadUse.length ? { insteadUse } : {} };
|
|
1286
|
+
})
|
|
1287
|
+
].sort((a, b) => a.name.localeCompare(b.name));
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
// ../tokens-build/src/scheme.js
|
|
1291
|
+
import crypto from "node:crypto";
|
|
1292
|
+
import fs from "node:fs";
|
|
1293
|
+
import path2 from "node:path";
|
|
1294
|
+
|
|
1295
|
+
// ../tokens-build/src/mcu.js
|
|
1296
|
+
import { createRequire } from "node:module";
|
|
1297
|
+
import path from "node:path";
|
|
1298
|
+
import { pathToFileURL } from "node:url";
|
|
1299
|
+
var require2 = createRequire(import.meta.url);
|
|
1300
|
+
var root = path.dirname(require2.resolve("@material/material-color-utilities"));
|
|
1301
|
+
var load = (p) => import(pathToFileURL(path.join(root, p)).href);
|
|
1302
|
+
var { Hct } = await load("hct/hct.js");
|
|
1303
|
+
var { TonalPalette } = await load("palettes/tonal_palette.js");
|
|
1304
|
+
|
|
1305
|
+
// ../tokens-build/src/scheme.js
|
|
1306
|
+
var NAMESPACE = CONFIG.namespace;
|
|
1307
|
+
var engine = createPaletteEngine({ Hct, TonalPalette, namespace: NAMESPACE });
|
|
1308
|
+
var systemPath = (id) => `tokens/systems/${id}.system.json`;
|
|
1309
|
+
function loadSystem(repoRoot, id = NAMESPACE) {
|
|
1310
|
+
assertSystemId(id, "a shipped system");
|
|
1311
|
+
return JSON.parse(fs.readFileSync(path2.join(repoRoot, systemPath(id)), "utf8"));
|
|
1312
|
+
}
|
|
1313
|
+
function colorVocabulary(repoRoot) {
|
|
1314
|
+
return JSON.parse(fs.readFileSync(path2.join(repoRoot, "tokens/sys/color.vocabulary.json"), "utf8"));
|
|
1315
|
+
}
|
|
1316
|
+
function generateSchemeFiles(system, repoRoot, documents) {
|
|
1317
|
+
const merged = system.chain ? system : mergeLayers([system], { namespace: NAMESPACE });
|
|
1318
|
+
const docs = documents ?? resolveNumericTokens({ ...sourceFiles(repoRoot), ...heldDocuments(repoRoot, merged) }, merged);
|
|
1319
|
+
return engine.generateColorFiles(merged, { sourcePath: systemPath(merged.id), vocabulary: colorVocabulary(repoRoot), documents: docs });
|
|
1320
|
+
}
|
|
1321
|
+
function sourcePaths(repoRoot) {
|
|
1322
|
+
const dir = path2.join(repoRoot, "tokens");
|
|
1323
|
+
const resolverFile = `${NAMESPACE}.resolver.json`;
|
|
1324
|
+
const resolver = JSON.parse(fs.readFileSync(path2.join(dir, resolverFile), "utf8"));
|
|
1325
|
+
const refs = Object.values(resolver.sets).flatMap((set) => set.sources.map((s) => s.$ref)).filter((ref) => !ref.startsWith("generated/"));
|
|
1326
|
+
return { dir, resolverFile, refs };
|
|
1327
|
+
}
|
|
1328
|
+
function sourceFiles(repoRoot) {
|
|
1329
|
+
const { dir, refs } = sourcePaths(repoRoot);
|
|
1330
|
+
return Object.fromEntries(refs.map((ref) => [ref, JSON.parse(fs.readFileSync(path2.join(dir, ref), "utf8"))]));
|
|
1331
|
+
}
|
|
1332
|
+
function heldDocuments(repoRoot, system) {
|
|
1333
|
+
const relative = system ? Object.values(system.vocabulary ?? {}).filter((decl) => decl.kind === "component").map((decl) => heldDocumentPath(decl.declaredBy, decl.component)) : fs.readdirSync(path2.join(repoRoot, "tokens/systems"), { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
|
|
1334
|
+
const dir = path2.join(repoRoot, "tokens/systems", entry.name, "comp");
|
|
1335
|
+
return fs.existsSync(dir) ? fs.readdirSync(dir).filter((file) => file.endsWith(".tokens.json")).map((file) => `systems/${entry.name}/comp/${file}`) : [];
|
|
1336
|
+
});
|
|
1337
|
+
return Object.fromEntries(relative.map((name) => [name, JSON.parse(fs.readFileSync(path2.join(repoRoot, "tokens", name), "utf8"))]));
|
|
1338
|
+
}
|
|
1339
|
+
function vocabularyDigest(repoRoot) {
|
|
1340
|
+
const { dir, resolverFile, refs } = sourcePaths(repoRoot);
|
|
1341
|
+
const files = [resolverFile, ...refs, "sys/color.vocabulary.json"];
|
|
1342
|
+
const stamp2 = (file) => {
|
|
1343
|
+
try {
|
|
1344
|
+
const { size, mtimeMs } = fs.statSync(path2.join(dir, file));
|
|
1345
|
+
return `${file}:${size}:${mtimeMs}`;
|
|
1346
|
+
} catch {
|
|
1347
|
+
return `${file}:missing`;
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
return crypto.createHash("sha256").update(files.map(stamp2).join("\n")).digest("hex").slice(0, 32);
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
// ../tokens-build/src/bundle.js
|
|
1354
|
+
var RECIPE = "dev.tanrei.system";
|
|
1355
|
+
function listSystems(repoRoot) {
|
|
1356
|
+
return fs2.readdirSync(path3.join(repoRoot, "tokens/systems")).filter((f) => f.endsWith(".system.json")).map((f) => f.replace(".system.json", "")).sort();
|
|
1357
|
+
}
|
|
1358
|
+
var shippedSystems = (repoRoot) => listSystems(repoRoot).filter((id) => id !== ROOT_SYSTEM);
|
|
1359
|
+
var validateLayer;
|
|
1360
|
+
function validateLayerFile(repoRoot, layer, fileId) {
|
|
1361
|
+
if (!validateLayer) {
|
|
1362
|
+
const schema2 = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens/schema/system.schema.json"), "utf8"));
|
|
1363
|
+
validateLayer = new Ajv2020({ allErrors: true, strict: false }).compile(schema2);
|
|
1364
|
+
}
|
|
1365
|
+
const problems = validateLayer(layer) ? [] : validateLayer.errors.map((e) => `${fileId}.system.json ${e.instancePath || "/"} ${e.message}`);
|
|
1366
|
+
if (layer.id !== fileId) problems.push(`${fileId}.system.json: "id" must equal the file name`);
|
|
1367
|
+
if (fileId === ROOT_SYSTEM ? "extends" in layer : !layer.extends) problems.push(`${fileId}.system.json: only the root layer "${ROOT_SYSTEM}" omits "extends"`);
|
|
1368
|
+
return problems;
|
|
1369
|
+
}
|
|
1370
|
+
function buildBundle(repoRoot, chain, { lend = (id) => loadSystem(repoRoot, id) } = {}) {
|
|
1371
|
+
const system = mergeLayers(chain, { namespace: CONFIG.namespace, lend });
|
|
1372
|
+
const files = resolveNumericTokens({ ...sourceFiles(repoRoot), ...heldDocuments(repoRoot, system) }, system);
|
|
1373
|
+
for (const [name, doc] of Object.entries(generateSchemeFiles(system, repoRoot, files))) files[`generated/${name}`] = doc;
|
|
1374
|
+
const resolver = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens", `${DEFAULT_SYSTEM}.resolver.json`), "utf8"));
|
|
1375
|
+
const held2 = Object.values(system.vocabulary).filter((decl) => decl.kind === "component").map((decl) => ({ $ref: componentDocumentPath(decl.component) }));
|
|
1376
|
+
resolver.sets.comp.sources.push(...held2);
|
|
1377
|
+
resolver.name = system.name ?? system.id;
|
|
1378
|
+
resolver.description = `Design system "${system.id}" (${system.chain.join(" \u2190 ")}), fully valued. Generated by Tanrei; do not edit.`;
|
|
1379
|
+
const own2 = Object.keys(files).filter((name) => name.startsWith("ext/")).sort();
|
|
1380
|
+
if (own2.length) resolver.resolutionOrder.push({ $ref: "#/sets/ext" });
|
|
1381
|
+
if (own2.length) resolver.sets.ext = { description: "Tokens that layers of this system declare in their own namespace.", sources: own2.map((name) => ({ $ref: name })) };
|
|
1382
|
+
files[`${system.id}.resolver.json`] = resolver;
|
|
1383
|
+
const dial = files["dial/dial.tokens.json"];
|
|
1384
|
+
const extensions = listExtensions(system);
|
|
1385
|
+
files["dial/dial.tokens.json"] = { $extensions: { [RECIPE]: { id: system.id, chain: system.chain, ...extensions.length ? { extensions } : {}, layers: chain } }, ...dial };
|
|
1386
|
+
return { system, files };
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
// ../tokens-build/src/components-manifest.js
|
|
1390
|
+
import fs3 from "node:fs";
|
|
1391
|
+
import path4 from "node:path";
|
|
1392
|
+
var CATALOG_FILE = "packages/tokens-build/generated/component-catalog.json";
|
|
1393
|
+
var manifestFile = (id) => `tokens/generated/${id}/components.json`;
|
|
1394
|
+
var WEB = `${CONFIG.packages.npmScope}/web`;
|
|
1395
|
+
var REACT = `${CONFIG.packages.npmScope}/react`;
|
|
1396
|
+
var REACT_ADVANCED = `${REACT}/advanced`;
|
|
1397
|
+
var REACT_ALL = `${REACT}/all`;
|
|
1398
|
+
var reactEntryOf = (id) => id === DEFAULT_SYSTEM ? REACT : `${REACT}/${id}`;
|
|
1399
|
+
var webEntryOf = (system) => system === DEFAULT_SYSTEM ? WEB : `${WEB}/${system}`;
|
|
1400
|
+
function importOf(component, { registeredBy, system, shipped }) {
|
|
1401
|
+
return {
|
|
1402
|
+
web: registeredBy ? webEntryOf(registeredBy) : component.web?.module,
|
|
1403
|
+
react: component.listing === "advanced" ? REACT_ADVANCED : shipped.has(system) ? reactEntryOf(system) : REACT_ALL
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
function readComponentCatalog(root2) {
|
|
1407
|
+
const file = path4.join(root2, CATALOG_FILE);
|
|
1408
|
+
return fs3.existsSync(file) ? JSON.parse(fs3.readFileSync(file, "utf8")) : null;
|
|
1409
|
+
}
|
|
1410
|
+
function addedValues(chain, axis) {
|
|
1411
|
+
if (!axis) return [];
|
|
1412
|
+
const prefix = `${axis}.`;
|
|
1413
|
+
return chain.flatMap(
|
|
1414
|
+
(layer) => Object.entries(layer.vocabulary ?? {}).filter(([id, entry]) => id.startsWith(prefix) && !id.slice(prefix.length).includes(".") && entry && typeof entry === "object" && "from" in entry && !("document" in entry)).map(([id]) => id.slice(prefix.length))
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
var shipsIn = (chain, catalog, held2) => {
|
|
1418
|
+
const { components: left } = componentChoices(chain);
|
|
1419
|
+
const outside = outsideComponents(chain, held2);
|
|
1420
|
+
return new Set(catalog.components.map((component) => component.name).filter((name) => !left.has(name) && !outside[name]));
|
|
1421
|
+
};
|
|
1422
|
+
function componentsManifest(chain, catalog, held2, shipped) {
|
|
1423
|
+
if (!shipped) throw new Error("componentsManifest: name the shipped systems, whose entries register their components");
|
|
1424
|
+
const system = chain.at(-1);
|
|
1425
|
+
const { components: left, variants: leftValues } = componentChoices(chain);
|
|
1426
|
+
const outside = outsideComponents(chain, held2);
|
|
1427
|
+
const byName = new Map(catalog.components.map((component) => [component.name, component]));
|
|
1428
|
+
const title = (name) => byName.get(name)?.title ?? name;
|
|
1429
|
+
const ids = new Set(shipped);
|
|
1430
|
+
const entries = chain.map((layer, at) => ids.has(layer.id) ? { id: layer.id, ships: shipsIn(chain.slice(0, at + 1), catalog, held2) } : null).filter(Boolean).reverse();
|
|
1431
|
+
const registeredBy = (name) => entries.find(({ ships }) => ships.has(name))?.id ?? null;
|
|
1432
|
+
const components = [];
|
|
1433
|
+
const omittedVariants = {};
|
|
1434
|
+
for (const component of [...catalog.components].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1435
|
+
if (left.has(component.name) || outside[component.name]) continue;
|
|
1436
|
+
const entry = { name: component.name, title: component.title, level: component.level, listing: component.listing, layer: component.layer };
|
|
1437
|
+
const imports = importOf(component, { registeredBy: registeredBy(component.name), system: system.id, shipped: ids });
|
|
1438
|
+
if (component.web) entry.web = component.web.tag ? { tag: component.web.tag, import: imports.web, module: component.web.module } : { class: component.web.class, import: component.web.stylesheet };
|
|
1439
|
+
if (component.react) entry.react = { name: component.react.name, import: imports.react };
|
|
1440
|
+
if (component.variant) {
|
|
1441
|
+
const out = /* @__PURE__ */ new Set([...leftValues.get(component.variant.source)?.keys() ?? [], ...leftValues.get(component.name)?.keys() ?? []]);
|
|
1442
|
+
const values = [.../* @__PURE__ */ new Set([...component.variant.values, ...addedValues(chain, component.variant.axis)])];
|
|
1443
|
+
entry.variants = values.filter((value) => !out.has(value));
|
|
1444
|
+
const gone = values.filter((value) => out.has(value));
|
|
1445
|
+
if (gone.length) omittedVariants[component.name] = gone;
|
|
1446
|
+
}
|
|
1447
|
+
components.push(entry);
|
|
1448
|
+
}
|
|
1449
|
+
const standIns = new Map(catalog.components.filter((component) => component.outside).map((component) => [component.name, component.outside]));
|
|
1450
|
+
const omitted = omittedOf(chain, held2, standIns).map(({ name, ...entry }) => ({ name, title: title(name), ...entry }));
|
|
1451
|
+
return {
|
|
1452
|
+
system: system.id,
|
|
1453
|
+
name: system.name ?? system.id,
|
|
1454
|
+
...system.extends ? { extends: system.extends } : {},
|
|
1455
|
+
chain: chain.map((layer) => layer.id),
|
|
1456
|
+
components,
|
|
1457
|
+
omitted,
|
|
1458
|
+
omittedVariants
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// ../tokens-build/src/components-audit.js
|
|
1463
|
+
var PREFIX = `${CONFIG.web.tagPrefix}-`;
|
|
1464
|
+
var WEB2 = `${CONFIG.packages.npmScope}/web`;
|
|
1465
|
+
var REACT2 = `${CONFIG.packages.npmScope}/react`;
|
|
1466
|
+
var TAG = `${PREFIX}[a-z0-9]+(?:-[a-z0-9]+)*`;
|
|
1467
|
+
var pascal = (name) => name.split("-").map((word) => word[0].toUpperCase() + word.slice(1)).join("");
|
|
1468
|
+
function textKind(file) {
|
|
1469
|
+
const ext = /\.([a-z0-9]+)$/i.exec(file ?? "")?.[1]?.toLowerCase();
|
|
1470
|
+
if (["scss", "less"].includes(ext)) return "scss";
|
|
1471
|
+
if (["css", "pcss"].includes(ext)) return "css";
|
|
1472
|
+
if (["html", "htm", "vue", "svelte", "astro"].includes(ext)) return "html";
|
|
1473
|
+
return "script";
|
|
1474
|
+
}
|
|
1475
|
+
var blank = (chars, from, to) => {
|
|
1476
|
+
for (let i = from; i < to; i++) if (chars[i] !== "\n" && chars[i] !== "\r") chars[i] = " ";
|
|
1477
|
+
};
|
|
1478
|
+
function blankHtmlComments(chars, text2, from, to) {
|
|
1479
|
+
for (let at = text2.indexOf("<!--", from); at !== -1 && at < to; at = text2.indexOf("<!--", at + 4)) {
|
|
1480
|
+
const end = text2.indexOf("-->", at + 4);
|
|
1481
|
+
const stop = end === -1 || end + 3 > to ? to : end + 3;
|
|
1482
|
+
blank(chars, at, stop);
|
|
1483
|
+
at = stop - 4;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
var BEFORE_REGEX = /* @__PURE__ */ new Set(["", "(", ",", "=", ":", "[", "!", "&", "|", "?", "{", ";", "+", "-", "*", "%", "<", ">", "~", "^"]);
|
|
1487
|
+
var KEYWORDS_BEFORE_REGEX = /* @__PURE__ */ new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
|
|
1488
|
+
function readScript(chars, text2, from = 0, to = text2.length) {
|
|
1489
|
+
const templates = [];
|
|
1490
|
+
const open = [];
|
|
1491
|
+
let depth = 0;
|
|
1492
|
+
let last = "";
|
|
1493
|
+
let i = from;
|
|
1494
|
+
const templateText = (template, at) => {
|
|
1495
|
+
let j = at;
|
|
1496
|
+
while (j < to && text2[j] !== "`" && !(text2[j] === "$" && text2[j + 1] === "{")) j += text2[j] === "\\" ? 2 : 1;
|
|
1497
|
+
blankHtmlComments(chars, text2, at, Math.min(j, to));
|
|
1498
|
+
if (j < to && text2[j] === "$") {
|
|
1499
|
+
open.push({ depth, template });
|
|
1500
|
+
depth++;
|
|
1501
|
+
last = "{";
|
|
1502
|
+
i = j + 2;
|
|
1503
|
+
} else {
|
|
1504
|
+
template.end = Math.min(j, to);
|
|
1505
|
+
last = "`";
|
|
1506
|
+
i = j + 1;
|
|
1507
|
+
}
|
|
1508
|
+
};
|
|
1509
|
+
while (i < to) {
|
|
1510
|
+
const c = text2[i];
|
|
1511
|
+
const next = text2[i + 1];
|
|
1512
|
+
if (c === "/" && next === "/" && text2[i - 1] !== ":" && last !== "<") {
|
|
1513
|
+
const end = text2.indexOf("\n", i);
|
|
1514
|
+
const stop = end === -1 || end > to ? to : end;
|
|
1515
|
+
blank(chars, i, stop);
|
|
1516
|
+
i = stop;
|
|
1517
|
+
} else if (c === "/" && next === "*" && last !== "<") {
|
|
1518
|
+
const end = text2.indexOf("*/", i + 2);
|
|
1519
|
+
const stop = end === -1 || end + 2 > to ? to : end + 2;
|
|
1520
|
+
blank(chars, i, stop);
|
|
1521
|
+
i = stop;
|
|
1522
|
+
} else if (c === '"' || c === "'") {
|
|
1523
|
+
let j = i + 1;
|
|
1524
|
+
while (j < to && text2[j] !== c && text2[j] !== "\n") j += text2[j] === "\\" ? 2 : 1;
|
|
1525
|
+
blankHtmlComments(chars, text2, i + 1, Math.min(j, to));
|
|
1526
|
+
i = j + 1;
|
|
1527
|
+
last = c;
|
|
1528
|
+
} else if (c === "`") {
|
|
1529
|
+
const template = { tag: /([\w$]+)\s*$/.exec(text2.slice(Math.max(from, i - 40), i))?.[1] ?? "", start: i + 1, end: to };
|
|
1530
|
+
templates.push(template);
|
|
1531
|
+
templateText(template, i + 1);
|
|
1532
|
+
} else if (c === "/" && last !== "<" && next !== ">" && (BEFORE_REGEX.has(last) || KEYWORDS_BEFORE_REGEX.has(last))) {
|
|
1533
|
+
let j = i + 1;
|
|
1534
|
+
let inClass = false;
|
|
1535
|
+
while (j < to && text2[j] !== "\n") {
|
|
1536
|
+
if (text2[j] === "\\") j++;
|
|
1537
|
+
else if (text2[j] === "[") inClass = true;
|
|
1538
|
+
else if (text2[j] === "]") inClass = false;
|
|
1539
|
+
else if (text2[j] === "/" && !inClass) break;
|
|
1540
|
+
j++;
|
|
1541
|
+
}
|
|
1542
|
+
i = j + 1;
|
|
1543
|
+
last = "regex";
|
|
1544
|
+
} else if (c === "{") {
|
|
1545
|
+
depth++;
|
|
1546
|
+
last = "{";
|
|
1547
|
+
i++;
|
|
1548
|
+
} else if (c === "}") {
|
|
1549
|
+
depth--;
|
|
1550
|
+
if (open.length && open.at(-1).depth === depth) templateText(open.pop().template, i + 1);
|
|
1551
|
+
else {
|
|
1552
|
+
last = "}";
|
|
1553
|
+
i++;
|
|
1554
|
+
}
|
|
1555
|
+
} else if (/\s/.test(c)) i++;
|
|
1556
|
+
else if (/[\w$]/.test(c)) {
|
|
1557
|
+
let j = i + 1;
|
|
1558
|
+
while (j < to && /[\w$]/.test(text2[j])) j++;
|
|
1559
|
+
last = text2.slice(i, j);
|
|
1560
|
+
i = j;
|
|
1561
|
+
} else {
|
|
1562
|
+
last = c;
|
|
1563
|
+
i++;
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
return templates;
|
|
1567
|
+
}
|
|
1568
|
+
function readCss(chars, text2, from, to, { lineComments = false } = {}) {
|
|
1569
|
+
let i = from;
|
|
1570
|
+
while (i < to) {
|
|
1571
|
+
const c = text2[i];
|
|
1572
|
+
if (c === "/" && text2[i + 1] === "*") {
|
|
1573
|
+
const end = text2.indexOf("*/", i + 2);
|
|
1574
|
+
const stop = end === -1 || end + 2 > to ? to : end + 2;
|
|
1575
|
+
blank(chars, i, stop);
|
|
1576
|
+
i = stop;
|
|
1577
|
+
} else if (lineComments && c === "/" && text2[i + 1] === "/" && text2[i - 1] !== ":" && text2[i - 1] !== "(") {
|
|
1578
|
+
const end = text2.indexOf("\n", i);
|
|
1579
|
+
blank(chars, i, end === -1 || end > to ? to : end);
|
|
1580
|
+
i = end === -1 || end > to ? to : end;
|
|
1581
|
+
} else if (c === '"' || c === "'") {
|
|
1582
|
+
let j = i + 1;
|
|
1583
|
+
while (j < to && text2[j] !== c && text2[j] !== "\n") j += text2[j] === "\\" ? 2 : 1;
|
|
1584
|
+
i = j + 1;
|
|
1585
|
+
} else i++;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
function readText(text2, kind) {
|
|
1589
|
+
const chars = text2.split("");
|
|
1590
|
+
const styles = [];
|
|
1591
|
+
if (kind === "css" || kind === "scss") {
|
|
1592
|
+
readCss(chars, text2, 0, text2.length, { lineComments: kind === "scss" });
|
|
1593
|
+
styles.push([0, text2.length]);
|
|
1594
|
+
} else if (kind === "html") {
|
|
1595
|
+
const blocks = [...text2.matchAll(/<(script|style)\b[^>]*>([\s\S]*?)<\/\1\s*>/gi)].map((match) => {
|
|
1596
|
+
const start = match.index + match[0].indexOf(">") + 1;
|
|
1597
|
+
return { name: match[1].toLowerCase(), start, end: start + match[2].length, outer: [match.index, match.index + match[0].length] };
|
|
1598
|
+
});
|
|
1599
|
+
const frontmatter = /^---\r?\n[\s\S]*?\r?\n---(?=\r?\n|$)/.exec(text2);
|
|
1600
|
+
if (frontmatter) blocks.unshift({ name: "script", start: 3, end: frontmatter[0].length - 3, outer: [0, frontmatter[0].length] });
|
|
1601
|
+
let at = 0;
|
|
1602
|
+
for (const block of blocks) {
|
|
1603
|
+
blankHtmlComments(chars, text2, at, block.outer[0]);
|
|
1604
|
+
at = block.outer[1];
|
|
1605
|
+
if (block.name === "style") {
|
|
1606
|
+
readCss(chars, text2, block.start, block.end);
|
|
1607
|
+
styles.push([block.start, block.end]);
|
|
1608
|
+
} else {
|
|
1609
|
+
for (const template of readScript(chars, text2, block.start, block.end)) {
|
|
1610
|
+
if (template.tag !== "css") continue;
|
|
1611
|
+
readCss(chars, text2, template.start, template.end);
|
|
1612
|
+
styles.push([template.start, template.end]);
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
blankHtmlComments(chars, text2, at, text2.length);
|
|
1617
|
+
} else {
|
|
1618
|
+
for (const template of readScript(chars, text2)) {
|
|
1619
|
+
if (template.tag === "css") {
|
|
1620
|
+
readCss(chars, text2, template.start, template.end);
|
|
1621
|
+
styles.push([template.start, template.end]);
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
for (const match of chars.join("").matchAll(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi)) {
|
|
1625
|
+
const start = match.index + match[0].indexOf(">") + 1;
|
|
1626
|
+
readCss(chars, text2, start, start + match[1].length);
|
|
1627
|
+
styles.push([start, start + match[1].length]);
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
return { code: chars.join(""), styles };
|
|
1631
|
+
}
|
|
1632
|
+
function selectorTags(code, from, to) {
|
|
1633
|
+
const found = [];
|
|
1634
|
+
let start = from;
|
|
1635
|
+
for (let i = from; i < to; i++) {
|
|
1636
|
+
const c = code[i];
|
|
1637
|
+
if (c === '"' || c === "'") {
|
|
1638
|
+
const end = code.indexOf(c, i + 1);
|
|
1639
|
+
i = end === -1 || end > to ? to : end;
|
|
1640
|
+
} else if (c === ";" || c === "}") start = i + 1;
|
|
1641
|
+
else if (c === "{") {
|
|
1642
|
+
const prelude = code.slice(start, i);
|
|
1643
|
+
if (!/^\s*@/.test(prelude)) {
|
|
1644
|
+
for (const match of prelude.matchAll(new RegExp(`(?<![\\w\\-.#:\\[\\\\@$%'"=])(${TAG})(?![\\w-])`, "g"))) {
|
|
1645
|
+
const before = prelude.slice(0, match.index);
|
|
1646
|
+
if (/::?(?:part|state|lang|dir|nth-[a-z-]+|highlight)\(\s*[^)]*$/.test(before)) continue;
|
|
1647
|
+
found.push({ offset: start + match.index, tag: match[1] });
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
start = i + 1;
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
return found;
|
|
1654
|
+
}
|
|
1655
|
+
function positions(text2) {
|
|
1656
|
+
const starts = [0];
|
|
1657
|
+
for (let i = 0; i < text2.length; i++) if (text2[i] === "\n") starts.push(i + 1);
|
|
1658
|
+
return (at) => {
|
|
1659
|
+
let low = 0;
|
|
1660
|
+
let high = starts.length - 1;
|
|
1661
|
+
while (low < high) {
|
|
1662
|
+
const mid = low + high + 1 >> 1;
|
|
1663
|
+
if (starts[mid] <= at) low = mid;
|
|
1664
|
+
else high = mid - 1;
|
|
1665
|
+
}
|
|
1666
|
+
return { line: low + 1, column: at - starts[low] + 1 };
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
function openingTagEnd(text2, from) {
|
|
1670
|
+
let quote = null;
|
|
1671
|
+
let depth = 0;
|
|
1672
|
+
for (let i = from; i < text2.length; i++) {
|
|
1673
|
+
const c = text2[i];
|
|
1674
|
+
if (quote) {
|
|
1675
|
+
if (c === quote) quote = null;
|
|
1676
|
+
} else if (c === '"' || c === "'" || c === "`") quote = c;
|
|
1677
|
+
else if (c === "{") depth++;
|
|
1678
|
+
else if (c === "}") depth = Math.max(0, depth - 1);
|
|
1679
|
+
else if (c === ">" && depth === 0) return i;
|
|
1680
|
+
}
|
|
1681
|
+
return text2.length;
|
|
1682
|
+
}
|
|
1683
|
+
var VARIANT = /(?<![\w.:-])variant\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(?:"([^"]*)"|'([^']*)'|`([^`$]*)`)\s*\}|([^\s"'=<>`{}$]+))/g;
|
|
1684
|
+
var IMPORT = /\b(?:import|export)\s*(?:type\s+)?([\w$*\s{},]*?)\s*from\s*(['"])([^'"]+)\2|\bimport\s*\(?\s*(['"])([^'"]+)\4|\brequire\s*\(\s*(['"])([^'"]+)\6/g;
|
|
1685
|
+
var indexes = /* @__PURE__ */ new WeakMap();
|
|
1686
|
+
function elementIndex(catalog) {
|
|
1687
|
+
if (indexes.has(catalog)) return indexes.get(catalog);
|
|
1688
|
+
const byTag = /* @__PURE__ */ new Map();
|
|
1689
|
+
for (const component of catalog.components) if (component.web?.tag) byTag.set(component.web.tag, { components: [component.name], own: true });
|
|
1690
|
+
for (const component of catalog.components) {
|
|
1691
|
+
for (const tag of component.web?.items ?? []) {
|
|
1692
|
+
const at = byTag.get(tag) ?? { components: [], own: false };
|
|
1693
|
+
if (!at.components.includes(component.name)) at.components.push(component.name);
|
|
1694
|
+
byTag.set(tag, at);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
const byReactName = new Map([...byTag].map(([tag, at]) => [pascal(tag.slice(PREFIX.length)), { ...at, tag }]));
|
|
1698
|
+
indexes.set(catalog, { byTag, byReactName });
|
|
1699
|
+
return indexes.get(catalog);
|
|
1700
|
+
}
|
|
1701
|
+
function auditContext(catalog, manifest, shipped, { product = false } = {}) {
|
|
1702
|
+
const { byTag, byReactName } = elementIndex(catalog);
|
|
1703
|
+
const byWebModule = /* @__PURE__ */ new Map();
|
|
1704
|
+
const webEntries = /* @__PURE__ */ new Map();
|
|
1705
|
+
const register = (specifier, name) => byWebModule.set(specifier, [.../* @__PURE__ */ new Set([...byWebModule.get(specifier) ?? [], name])]);
|
|
1706
|
+
for (const component of catalog.components) {
|
|
1707
|
+
if (component.web?.module) register(component.web.module, component.name);
|
|
1708
|
+
if (component.web?.stylesheet) register(component.web.stylesheet, component.name);
|
|
1709
|
+
if (component.web?.tag) register(`${WEB2}/all`, component.name);
|
|
1710
|
+
}
|
|
1711
|
+
webEntries.set(`${WEB2}/all`, "*");
|
|
1712
|
+
for (const [id, each] of shipped) {
|
|
1713
|
+
webEntries.set(webEntryOf(id), id);
|
|
1714
|
+
for (const { name, web } of each.components) if (web?.tag) register(webEntryOf(id), name);
|
|
1715
|
+
}
|
|
1716
|
+
const reactEntries = /* @__PURE__ */ new Map();
|
|
1717
|
+
for (const each of shipped.values()) for (const { name, react } of each.components) if (react) reactEntries.set(react.import, (reactEntries.get(react.import) ?? /* @__PURE__ */ new Set()).add(name));
|
|
1718
|
+
const listed = new Map(manifest.components.map((component) => [component.name, component]));
|
|
1719
|
+
const ownEntries = new Set(manifest.components.map((component) => component.web?.import).filter((specifier) => webEntries.has(specifier)));
|
|
1720
|
+
return { catalog, manifest, shipped, product, byTag, byReactName, byWebModule, webEntries, reactEntries, listed, ownEntries };
|
|
1721
|
+
}
|
|
1722
|
+
function briefComponent(entry) {
|
|
1723
|
+
return { name: entry.name, title: entry.title, ...entry.web ? { web: entry.web } : {}, ...entry.react ? { react: entry.react } : {} };
|
|
1724
|
+
}
|
|
1725
|
+
var variantsOf = (manifest, name) => ({ values: manifest.components.find((c) => c.name === name)?.variants, omitted: manifest.omittedVariants[name] ?? [] });
|
|
1726
|
+
function standInsFor({ manifest, shipped, product }, name) {
|
|
1727
|
+
const omitted = manifest.omitted.find((o) => o.name === name);
|
|
1728
|
+
if (!omitted) return null;
|
|
1729
|
+
const listed = new Map(manifest.components.map((c) => [c.name, c]));
|
|
1730
|
+
const { name: _name, title: _title, ...why } = omitted;
|
|
1731
|
+
const take = omitted.providedBy ? { name, from: omitted.providedBy } : name;
|
|
1732
|
+
return {
|
|
1733
|
+
...why,
|
|
1734
|
+
...omitted.insteadUse ? { insteadUse: omitted.insteadUse.filter((other) => listed.has(other)).map((other) => briefComponent(listed.get(other))) } : {},
|
|
1735
|
+
availableIn: [...shipped].filter(([, each]) => each.components.some((c) => c.name === name)).map(([id]) => id),
|
|
1736
|
+
// A layer that left it out itself takes it back by no longer leaving it out; a later layer includes it.
|
|
1737
|
+
howToInclude: product && omitted.omittedBy === manifest.system ? { note: `Remove "${name}" from components.omit in ${manifest.system}.system.json.` } : { ...product ? {} : { note: `A shipped system is not edited: a product layer that extends "${manifest.system}" may take it.` }, write: { components: { include: [take] } } }
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
function distance(a, b) {
|
|
1741
|
+
let row = [...Array(b.length + 1).keys()];
|
|
1742
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1743
|
+
const next = [i];
|
|
1744
|
+
for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
1745
|
+
row = next;
|
|
1746
|
+
}
|
|
1747
|
+
return row[b.length];
|
|
1748
|
+
}
|
|
1749
|
+
var plainName = (name) => name.replace(new RegExp(`^${PREFIX}`), "").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
1750
|
+
function spelledLike({ manifest }, name, limit = 3) {
|
|
1751
|
+
const plain = plainName(name);
|
|
1752
|
+
return manifest.components.map((component) => [component.name, distance(plain, component.name)]).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0])).slice(0, limit).map(([other]) => other);
|
|
1753
|
+
}
|
|
1754
|
+
function auditText(context, text2, { file, kind = textKind(file), near } = {}) {
|
|
1755
|
+
const { manifest, byTag, byReactName, byWebModule, webEntries, reactEntries, listed, ownEntries } = context;
|
|
1756
|
+
const { code, styles } = readText(text2, kind);
|
|
1757
|
+
const at = positions(text2);
|
|
1758
|
+
const findings = [];
|
|
1759
|
+
const add = (offset, finding) => findings.push({ ...file ? { file } : {}, ...at(offset), ...finding });
|
|
1760
|
+
const unavailable = (names) => names.filter((name) => !listed.has(name));
|
|
1761
|
+
const missing = (offset, kind2, found, names) => {
|
|
1762
|
+
for (const name of names) add(offset, { kind: kind2, found, component: name, problem: `"${manifest.system}" does not have ${name}`, ...standInsFor(context, name) });
|
|
1763
|
+
};
|
|
1764
|
+
const unknownTag = (offset, kind2, found, tag) => add(offset, { kind: kind2, found, problem: `Tanrei has no element <${tag}>`, near: (near ?? ((name) => spelledLike(context, name)))(tag) });
|
|
1765
|
+
const inStyle = (offset) => styles.some(([from, to]) => offset >= from && offset < to);
|
|
1766
|
+
const local = /* @__PURE__ */ new Map();
|
|
1767
|
+
for (const match of code.matchAll(IMPORT)) {
|
|
1768
|
+
const specifier = match[3] ?? match[5] ?? match[7];
|
|
1769
|
+
const offset = match.index + match[0].lastIndexOf(specifier);
|
|
1770
|
+
if (specifier === WEB2 || specifier.startsWith(`${WEB2}/`)) {
|
|
1771
|
+
const names = byWebModule.get(specifier);
|
|
1772
|
+
if (!names) continue;
|
|
1773
|
+
if (webEntries.has(specifier) && ownEntries.size && !ownEntries.has(specifier)) {
|
|
1774
|
+
const of = webEntries.get(specifier);
|
|
1775
|
+
const extra = unavailable(names);
|
|
1776
|
+
const use = [...ownEntries][0];
|
|
1777
|
+
add(offset, {
|
|
1778
|
+
kind: "import",
|
|
1779
|
+
found: specifier,
|
|
1780
|
+
problem: `'${specifier}' registers ${of === "*" ? "every component" : `what "${of}" ships`}${extra.length ? `, with ${extra.join(", ")}, which "${manifest.system}" does not have` : ""}: in "${manifest.system}", the components are registered by '${use}'`,
|
|
1781
|
+
...extra.length ? { notInThisSystem: extra } : {},
|
|
1782
|
+
use
|
|
1783
|
+
});
|
|
1784
|
+
} else if (!webEntries.has(specifier) && unavailable(names).length === names.length) missing(offset, "import", specifier, names);
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
if (specifier !== REACT2 && !specifier.startsWith(`${REACT2}/`)) continue;
|
|
1788
|
+
const named = /\{([^}]*)\}/.exec(match[1] ?? "")?.[1];
|
|
1789
|
+
if (!named) continue;
|
|
1790
|
+
let cursor = match.index + match[0].indexOf("{");
|
|
1791
|
+
for (const part of named.split(",")) {
|
|
1792
|
+
const [, typeOnly, imported, alias] = /^\s*(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+))?\s*$/.exec(part) ?? [];
|
|
1793
|
+
const partAt = code.indexOf(imported ?? part.trim(), cursor);
|
|
1794
|
+
cursor = partAt + part.length;
|
|
1795
|
+
const wrapper = imported && byReactName.get(imported);
|
|
1796
|
+
if (!wrapper) continue;
|
|
1797
|
+
if (!typeOnly) local.set(alias ?? imported, { components: wrapper.components, imported });
|
|
1798
|
+
const names = unavailable(wrapper.components);
|
|
1799
|
+
if (names.length === wrapper.components.length) missing(partAt, "import", imported, names);
|
|
1800
|
+
else {
|
|
1801
|
+
const owner = listed.get(wrapper.components.find((name) => listed.has(name)));
|
|
1802
|
+
const expected = owner.react?.import;
|
|
1803
|
+
if (!expected || specifier === expected) continue;
|
|
1804
|
+
const holds = specifier === REACT_ALL || reactEntries.get(specifier)?.has(owner.name);
|
|
1805
|
+
const entryOf = [...context.shipped.keys()].find((id) => reactEntryOf(id) === specifier);
|
|
1806
|
+
const typedFor = specifier === REACT_ALL ? "every system" : entryOf ? `"${entryOf}"` : "another system";
|
|
1807
|
+
add(partAt, { kind: "import", found: `${imported} from '${specifier}'`, component: owner.name, problem: holds ? `in "${manifest.system}", ${imported} is imported from '${expected}': '${specifier}' types it for ${typedFor}` : `'${specifier}' does not export ${imported}`, use: expected });
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
const element = (offset, found, components, own2, end) => {
|
|
1812
|
+
const names = unavailable(components);
|
|
1813
|
+
if (names.length === components.length) return missing(offset, "element", found, names);
|
|
1814
|
+
if (!own2) return;
|
|
1815
|
+
const name = components[0];
|
|
1816
|
+
const { values, omitted } = variantsOf(manifest, name);
|
|
1817
|
+
if (!values) return;
|
|
1818
|
+
for (const value of code.slice(offset, end).matchAll(VARIANT)) {
|
|
1819
|
+
const chosen = value.slice(1).find((v) => v !== void 0);
|
|
1820
|
+
if (values.includes(chosen) || chosen.includes("${")) continue;
|
|
1821
|
+
const gone = omitted.includes(chosen);
|
|
1822
|
+
add(offset + value.index, { kind: "variant", found: `variant="${chosen}"`, component: name, problem: gone ? `"${manifest.system}" leaves the ${chosen} ${name} out` : `${name} has no variant "${chosen}"`, values });
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
for (const match of code.matchAll(new RegExp(`<(${TAG})(?![\\w-])`, "g"))) {
|
|
1826
|
+
const tag = match[1];
|
|
1827
|
+
const known = byTag.get(tag);
|
|
1828
|
+
if (known) element(match.index + 1, `<${tag}>`, known.components, known.own, openingTagEnd(code, match.index));
|
|
1829
|
+
else unknownTag(match.index + 1, "element", `<${tag}>`, tag);
|
|
1830
|
+
}
|
|
1831
|
+
for (const match of code.matchAll(new RegExp(`(['"\`])(${TAG})\\1`, "g"))) {
|
|
1832
|
+
const known = byTag.get(match[2]);
|
|
1833
|
+
if (known && !inStyle(match.index)) element(match.index + 1, `'${match[2]}'`, known.components, false, match.index);
|
|
1834
|
+
}
|
|
1835
|
+
if (local.size) {
|
|
1836
|
+
for (const match of code.matchAll(/<([A-Z][\w$]*)(?![\w$])/g)) {
|
|
1837
|
+
const bound = local.get(match[1]);
|
|
1838
|
+
if (bound) element(match.index + 1, `<${match[1]}>`, bound.components, byTag.get(byReactName.get(bound.imported).tag).own, openingTagEnd(code, match.index));
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
for (const [from, to] of styles) {
|
|
1842
|
+
for (const { offset, tag } of selectorTags(code, from, to)) {
|
|
1843
|
+
const known = byTag.get(tag);
|
|
1844
|
+
if (!known) unknownTag(offset, "selector", tag, tag);
|
|
1845
|
+
else if (unavailable(known.components).length === known.components.length) missing(offset, "selector", tag, known.components);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return findings.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
1849
|
+
}
|
|
1850
|
+
function auditTexts(context, texts, options = {}) {
|
|
1851
|
+
const findings = texts.flatMap(({ file, text: text2, kind }) => auditText(context, text2, { file, kind, ...options }));
|
|
1852
|
+
return {
|
|
1853
|
+
system: context.manifest.system,
|
|
1854
|
+
...context.product ? { product: true } : {},
|
|
1855
|
+
checked: texts.length,
|
|
1856
|
+
clean: findings.length === 0,
|
|
1857
|
+
errors: findings.length,
|
|
1858
|
+
findings,
|
|
1859
|
+
...findings.length ? { next: "Replace each finding with what it names (insteadUse, use, values), or take the component into the product's layer (howToInclude) and run `tanrei build`." } : {}
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
// ../tools/src/from.js
|
|
1864
|
+
var source = (from) => {
|
|
1865
|
+
const at = from.indexOf(".");
|
|
1866
|
+
return { component: from.slice(0, at), name: from.slice(at + 1) };
|
|
1867
|
+
};
|
|
1868
|
+
var LISTS = [
|
|
1869
|
+
["props", "prop"],
|
|
1870
|
+
["events", "event"],
|
|
1871
|
+
["slots", "slot"]
|
|
1872
|
+
];
|
|
1873
|
+
var forwards = (spec) => LISTS.some(([list]) => (spec?.[list] ?? []).some((entry) => entry.from)) || (spec?.items ?? []).some((kind) => kind.from);
|
|
1874
|
+
function resolveFrom(spec, byName, seen = /* @__PURE__ */ new Set()) {
|
|
1875
|
+
if (!forwards(spec)) return spec;
|
|
1876
|
+
const resolved = { ...spec };
|
|
1877
|
+
for (const [list] of LISTS) {
|
|
1878
|
+
if (!spec[list]) continue;
|
|
1879
|
+
resolved[list] = spec[list].map((entry) => {
|
|
1880
|
+
if (!entry.from) return entry;
|
|
1881
|
+
const { component, name } = source(entry.from);
|
|
1882
|
+
const member = byName.get(component);
|
|
1883
|
+
if (!member || component === spec.name || seen.has(component)) return entry;
|
|
1884
|
+
const theirs = (resolveFrom(member, byName, /* @__PURE__ */ new Set([...seen, spec.name]))[list] ?? []).find((e) => e.name === name);
|
|
1885
|
+
if (!theirs || !("description" in theirs)) return entry;
|
|
1886
|
+
const { from: _theirFrom, note: _theirNote, ...own2 } = theirs;
|
|
1887
|
+
return { ...own2, name: entry.name, from: entry.from, ...entry.note ? { note: entry.note } : {} };
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
if ((spec.items ?? []).some((kind) => kind.from)) {
|
|
1891
|
+
resolved.items = spec.items.map((kind) => {
|
|
1892
|
+
if (!kind.from) return kind;
|
|
1893
|
+
const { component, name } = source(kind.from);
|
|
1894
|
+
const member = byName.get(component);
|
|
1895
|
+
if (!member || component === spec.name || seen.has(component)) return kind;
|
|
1896
|
+
const theirs = (resolveFrom(member, byName, /* @__PURE__ */ new Set([...seen, spec.name])).items ?? []).find((k) => k.name === name);
|
|
1897
|
+
if (!theirs || !("summary" in theirs)) return kind;
|
|
1898
|
+
const { from: _theirFrom, note: _theirNote, ...own2 } = theirs;
|
|
1899
|
+
return { ...own2, name: kind.name, from: kind.from, ...kind.note ? { note: kind.note } : {} };
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
return resolved;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
// src/systems.js
|
|
1906
|
+
import fs6 from "node:fs";
|
|
1907
|
+
import path7 from "node:path";
|
|
1908
|
+
|
|
1909
|
+
// ../tokens-build/src/invariants.js
|
|
1910
|
+
var lin = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
1911
|
+
var luminance2 = ({ r, g, b }) => 0.2126 * lin(r / 255) + 0.7152 * lin(g / 255) + 0.0722 * lin(b / 255);
|
|
1912
|
+
var over = (fg, bg) => ({
|
|
1913
|
+
r: fg.r * fg.a + bg.r * (1 - fg.a),
|
|
1914
|
+
g: fg.g * fg.a + bg.g * (1 - fg.a),
|
|
1915
|
+
b: fg.b * fg.a + bg.b * (1 - fg.a),
|
|
1916
|
+
a: 1
|
|
1917
|
+
});
|
|
1918
|
+
var leadWithStructure = (warnings) => [...warnings.filter((w) => !/^\[[a-z-]+\] /.test(w)), ...warnings.filter((w) => /^\[[a-z-]+\] /.test(w))];
|
|
1919
|
+
var isCriterionFinding = (finding) => /^\[[a-z-]+\] [a-z0-9.-]+ on [a-z0-9.-]+: \d+\.\d+:1 < \d+(\.\d+)?:1 \(/.test(finding) || isTargetSizeFinding(finding);
|
|
1920
|
+
var isTargetSizeFinding = (finding) => finding.startsWith("target size: ");
|
|
1921
|
+
var isRefusedEverywhere = (finding) => finding.startsWith("target floor: ");
|
|
1922
|
+
var TARGET_THRESHOLDS = Object.freeze({ minimum: 24 });
|
|
1923
|
+
function targetFloors(documents) {
|
|
1924
|
+
const MIN = `{${CONFIG.namespace}.sys.target.minimum}`;
|
|
1925
|
+
const floored = /* @__PURE__ */ new Set();
|
|
1926
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
1927
|
+
const walk = (node, path11) => {
|
|
1928
|
+
if (!node || typeof node !== "object") return;
|
|
1929
|
+
if ("$value" in node) {
|
|
1930
|
+
const id = path11.join(".");
|
|
1931
|
+
if (node.$extensions?.["dev.tanrei.derive"]?.min === MIN) floored.add(id);
|
|
1932
|
+
else if (typeof node.$value === "string" && /^\{[^{}]+\}$/.test(node.$value)) aliases.set(id, node.$value.slice(1, -1));
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$")) walk(child, [...path11, key]);
|
|
1936
|
+
};
|
|
1937
|
+
for (const doc of documents) walk(doc, []);
|
|
1938
|
+
for (let grew = true; grew; ) {
|
|
1939
|
+
grew = false;
|
|
1940
|
+
for (const [id, target] of aliases) {
|
|
1941
|
+
if (floored.has(target) && !floored.has(id)) {
|
|
1942
|
+
floored.add(id);
|
|
1943
|
+
grew = true;
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
return [...floored].sort();
|
|
1948
|
+
}
|
|
1949
|
+
function ladderReaders(documents) {
|
|
1950
|
+
const STEP = new RegExp(`^\\{${CONFIG.namespace}\\.sys\\.control\\.height\\.([a-z-]+)\\}$`);
|
|
1951
|
+
const steps = /* @__PURE__ */ new Map();
|
|
1952
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
1953
|
+
const walk = (node, path11) => {
|
|
1954
|
+
if (!node || typeof node !== "object") return;
|
|
1955
|
+
if ("$value" in node) {
|
|
1956
|
+
const id = path11.join(".");
|
|
1957
|
+
const rule = node.$extensions?.["dev.tanrei.derive"];
|
|
1958
|
+
const step = rule?.fn === "mul" && rule.by === 1 && rule.round === void 0 && typeof rule.of === "string" && rule.of.match(STEP)?.[1] || typeof node.$value === "string" && node.$value.match(STEP)?.[1];
|
|
1959
|
+
if (step) steps.set(id, step);
|
|
1960
|
+
else if (typeof node.$value === "string" && /^\{[^{}]+\}$/.test(node.$value)) aliases.set(id, node.$value.slice(1, -1));
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$")) walk(child, [...path11, key]);
|
|
1964
|
+
};
|
|
1965
|
+
for (const doc of documents) walk(doc, []);
|
|
1966
|
+
for (let grew = true; grew; ) {
|
|
1967
|
+
grew = false;
|
|
1968
|
+
for (const [id, target] of aliases) {
|
|
1969
|
+
if (steps.has(target) && !steps.has(id)) {
|
|
1970
|
+
steps.set(id, steps.get(target));
|
|
1971
|
+
grew = true;
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
return Object.fromEntries([...steps].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
1976
|
+
}
|
|
1977
|
+
var ALIGNED = "dev.tanrei.aligned";
|
|
1978
|
+
function alignedTokens(documents, mark = "control") {
|
|
1979
|
+
const marked = [];
|
|
1980
|
+
const walk = (node, path11) => {
|
|
1981
|
+
if (!node || typeof node !== "object") return;
|
|
1982
|
+
if ("$value" in node) {
|
|
1983
|
+
if (node.$extensions?.[ALIGNED] === mark) marked.push(path11.join("."));
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$")) walk(child, [...path11, key]);
|
|
1987
|
+
};
|
|
1988
|
+
for (const doc of documents) walk(doc, []);
|
|
1989
|
+
return marked.sort();
|
|
1990
|
+
}
|
|
1991
|
+
var ownHeights = (documents) => alignedTokens(documents, "own");
|
|
1992
|
+
var PRESET_CRITERIA_NOTE = "An imitation preset is held to fidelity to the system it imitates, not to Tanrei's accessibility criteria, in every contrast scheme. These are measurements against the fixed thresholds, kept as information: they are not warnings and not mimicry gaps.";
|
|
1993
|
+
var SELECTED_ROWS = [
|
|
1994
|
+
["list.selected.container.color", "list.unselected.hovered.container.color", "list.selected.content.color"],
|
|
1995
|
+
["tree-view.selected.container.color", "tree-view.unselected.hovered.container.color", "tree-view.selected.label.color"],
|
|
1996
|
+
["navigation-drawer.selected.item.container.color", "navigation-drawer.unselected.hovered.item.container.color", "navigation-drawer.selected.item.label.color"],
|
|
1997
|
+
["table.row.selected.container.color", "table.row.unselected.hovered.container.color", "table.row.selected.text.color"]
|
|
1998
|
+
];
|
|
1999
|
+
var COMPONENTS_HELD_IN_EVERY_SCHEME = ["radio-button", "menu", "snackbar", "chip", ...new Set(SELECTED_ROWS.map(([selected]) => selected.split(".")[0]))];
|
|
2000
|
+
function contrast(fgColor, bgColor) {
|
|
2001
|
+
const bg = rgba(bgColor);
|
|
2002
|
+
const fg = over(rgba(fgColor), bg);
|
|
2003
|
+
const [hi, lo] = [luminance2(fg), luminance2(bg)].sort((a, b) => b - a);
|
|
2004
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
2005
|
+
}
|
|
2006
|
+
var SURFACES = [
|
|
2007
|
+
"surface",
|
|
2008
|
+
"surface-dim",
|
|
2009
|
+
"surface-bright",
|
|
2010
|
+
"surface-container-lowest",
|
|
2011
|
+
"surface-container-low",
|
|
2012
|
+
"surface-container",
|
|
2013
|
+
"surface-container-high",
|
|
2014
|
+
"surface-container-highest"
|
|
2015
|
+
];
|
|
2016
|
+
var TEXT = 4.5;
|
|
2017
|
+
var NON_TEXT = 3;
|
|
2018
|
+
var STATUSES = ["info", "warning", "error", "success"];
|
|
2019
|
+
function intentsOf(roles) {
|
|
2020
|
+
return Object.keys(roles).filter((r) => [`on-${r}`, `${r}-container`, `on-${r}-container`].every((k) => k in roles));
|
|
2021
|
+
}
|
|
2022
|
+
function pairsFor(roles, focusStyle = "ring") {
|
|
2023
|
+
const intents = intentsOf(roles);
|
|
2024
|
+
const focus = focusStyle === "ring" ? "focus indicator (WCAG 2.4.13)" : `focus indicator, drawn as a ${focusStyle} (WCAG 2.4.13)`;
|
|
2025
|
+
return [
|
|
2026
|
+
...intents.flatMap((r) => [
|
|
2027
|
+
[`on-${r}`, r, TEXT, "content on filled container"],
|
|
2028
|
+
[`on-${r}-container`, `${r}-container`, TEXT, "content on tonal container"]
|
|
2029
|
+
]),
|
|
2030
|
+
...STATUSES.filter((r) => intents.includes(r)).map((r) => [r, `${r}-container`, NON_TEXT, "status mark on its tonal container (WCAG 1.4.11)"]),
|
|
2031
|
+
["inverse-on-surface", "inverse-surface", TEXT, "content on inverse surface"],
|
|
2032
|
+
// inverse-primary on inverse-surface is a snackbar's action label: text.
|
|
2033
|
+
["inverse-primary", "inverse-surface", TEXT, "accent text on inverse surface"],
|
|
2034
|
+
// A link on a surface of the opposite theme: the counterpart of `link` on the surfaces below.
|
|
2035
|
+
["inverse-link", "inverse-surface", TEXT, "inline links on inverse surface"],
|
|
2036
|
+
...SURFACES.flatMap((s) => [
|
|
2037
|
+
["on-surface", s, TEXT, "body text"],
|
|
2038
|
+
["on-surface-variant", s, TEXT, "secondary text"],
|
|
2039
|
+
["link", s, TEXT, "inline links"],
|
|
2040
|
+
...intents.map((r) => [r, s, TEXT, `${r}-colored text`]),
|
|
2041
|
+
["outline", s, NON_TEXT, "functional boundary (WCAG 1.4.11)"],
|
|
2042
|
+
["focus-ring", s, NON_TEXT, focus]
|
|
2043
|
+
])
|
|
2044
|
+
];
|
|
2045
|
+
}
|
|
2046
|
+
var tonalPairs = (roles) => ["secondary", ...STATUSES].filter((r) => `${r}-container` in roles).flatMap((r) => [
|
|
2047
|
+
["link", `${r}-container`, TEXT, "inline link on a tonal container"],
|
|
2048
|
+
["focus-ring", `${r}-container`, NON_TEXT, "focus indicator on a tonal container (WCAG 2.4.13)"]
|
|
2049
|
+
]);
|
|
2050
|
+
var HIGH_CONTRAST_TEXT = 7;
|
|
2051
|
+
var HAIRLINE = { medium: 3, high: 4.5 };
|
|
2052
|
+
var ROW_SELECTION = 1.1;
|
|
2053
|
+
var CONTRAST_THRESHOLDS = Object.freeze({
|
|
2054
|
+
/** Text, and a content color on its container, in the standard and medium contrast schemes. */
|
|
2055
|
+
text: TEXT,
|
|
2056
|
+
/** The same pairs in the high-contrast schemes. */
|
|
2057
|
+
highContrastText: HIGH_CONTRAST_TEXT,
|
|
2058
|
+
/** A boundary that identifies a control, a status's mark, the focus indicator: in every scheme. */
|
|
2059
|
+
nonText: NON_TEXT,
|
|
2060
|
+
/** The hairline (outline-variant) in the default system's raised-contrast schemes. */
|
|
2061
|
+
hairline: Object.freeze({ ...HAIRLINE })
|
|
2062
|
+
});
|
|
2063
|
+
var OTHER_THEME = { light: "dark", "light-medium": "dark-medium", "light-high": "dark-high", dark: "light", "dark-medium": "light-medium", "dark-high": "light-high" };
|
|
2064
|
+
var choiceOf = (model, name) => {
|
|
2065
|
+
const token = model.tokens[`${CONFIG.namespace}.sys.behavior.${name}`];
|
|
2066
|
+
return token?.enum?.values?.[token.value];
|
|
2067
|
+
};
|
|
2068
|
+
var choiceOfToken = (model, token) => {
|
|
2069
|
+
const target = token?.alias ? model.tokens[token.aliasFinal ?? token.alias] : token;
|
|
2070
|
+
return token?.enum?.values?.[target?.value];
|
|
2071
|
+
};
|
|
2072
|
+
var STACKED_ITEMS = [
|
|
2073
|
+
{
|
|
2074
|
+
component: "navigation-bar",
|
|
2075
|
+
what: "destination",
|
|
2076
|
+
height: "container.height",
|
|
2077
|
+
around: [["container.padding"], ["item.container.padding-block"]],
|
|
2078
|
+
glyph: "item.icon-indicator.height",
|
|
2079
|
+
gap: "item.gap",
|
|
2080
|
+
label: "item.label.typescale"
|
|
2081
|
+
},
|
|
2082
|
+
{
|
|
2083
|
+
component: "tabs",
|
|
2084
|
+
what: "primary tab",
|
|
2085
|
+
height: "container.height-with-icon",
|
|
2086
|
+
sizes: (tokens) => Object.keys(tokens).map((id) => id.match(new RegExp(`^${CONFIG.namespace}\\.comp\\.tabs\\.icon\\.size\\.([a-z0-9-]+)$`))?.[1]).filter(Boolean),
|
|
2087
|
+
when: ["icon.placement.<size>", "stacked", "icon.placement.medium"],
|
|
2088
|
+
// The content stands inside the indicator's box, held in by track.padding or by the primary underline's thickness,
|
|
2089
|
+
// whichever is more, and keeps the active indicator's padding-block inside it.
|
|
2090
|
+
around: [["track.padding", "primary.<state>.underline.thickness"], ["active-indicator.padding-block.<size>"]],
|
|
2091
|
+
glyph: "icon.size.<size>",
|
|
2092
|
+
gap: "container.gap",
|
|
2093
|
+
label: "label.typescale"
|
|
2094
|
+
}
|
|
2095
|
+
];
|
|
2096
|
+
var STACK_STATES = ["", "hovered.", "focused.", "pressed.", "disabled."];
|
|
2097
|
+
function auditInvariants(model) {
|
|
2098
|
+
const failures = [];
|
|
2099
|
+
const checked = Object.fromEntries(model.schemes.map((scheme) => [scheme, { rolePairs: 0, componentPairs: 0 }]));
|
|
2100
|
+
const measure = (scheme, kind, fg, bg) => {
|
|
2101
|
+
checked[scheme][kind] += 1;
|
|
2102
|
+
return contrast(fg, bg);
|
|
2103
|
+
};
|
|
2104
|
+
const focusStyle = choiceOf(model, "focus-style");
|
|
2105
|
+
for (const scheme of model.schemes) {
|
|
2106
|
+
const roles = model.colors[scheme];
|
|
2107
|
+
const isHigh = scheme.endsWith("-high");
|
|
2108
|
+
const declared = Object.entries(roles).filter(([, token]) => token.vocabulary?.onRole).map(([role2, token]) => [token.vocabulary.onRole.split(".").at(-1), role2, TEXT, `content on the declared role "${role2}"`]);
|
|
2109
|
+
const tonal = model.system === CONFIG.namespace ? tonalPairs(roles) : [];
|
|
2110
|
+
for (const [fg, bg, min, why] of [...pairsFor(roles, focusStyle), ...tonal, ...declared]) {
|
|
2111
|
+
if (!roles[fg] || !roles[bg]) {
|
|
2112
|
+
failures.push(`[${scheme}] missing role for pair ${fg} / ${bg}`);
|
|
2113
|
+
continue;
|
|
2114
|
+
}
|
|
2115
|
+
const required = isHigh && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
2116
|
+
const ratio = measure(scheme, "rolePairs", roles[fg].value, roles[bg].value);
|
|
2117
|
+
if (ratio < required) {
|
|
2118
|
+
failures.push(`[${scheme}] ${fg} on ${bg}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
const level = model.system !== CONFIG.namespace ? null : isHigh ? "high" : scheme.endsWith("-medium") ? "medium" : null;
|
|
2122
|
+
if (level && roles["outline-variant"] && roles.outline) {
|
|
2123
|
+
for (const s of SURFACES.filter((each) => roles[each])) {
|
|
2124
|
+
const hairline = measure(scheme, "rolePairs", roles["outline-variant"].value, roles[s].value);
|
|
2125
|
+
if (hairline < HAIRLINE[level]) failures.push(`[${scheme}] outline-variant on ${s}: ${hairline.toFixed(2)}:1 < ${HAIRLINE[level]}:1 (the hairline in a raised-contrast scheme)`);
|
|
2126
|
+
const edge = measure(scheme, "rolePairs", roles.outline.value, roles[s].value);
|
|
2127
|
+
if (edge < hairline) failures.push(`[${scheme}] outline on ${s}: ${edge.toFixed(2)}:1 < ${hairline.toFixed(2)}:1 (an input's edge stays stronger than the hairline)`);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
if (choiceOf(model, "pressed-feedback") === "dim") {
|
|
2132
|
+
const pressed = Object.values(model.tokens).filter((t) => t.path[0] === "comp" && /(^|\.)pressed\.opacity$/.test(t.path.slice(2).join(".")));
|
|
2133
|
+
if (pressed.length && pressed.every((t) => t.value >= 1)) failures.push(`sys.behavior.pressed-feedback is "dim", but every pressed opacity is 1 (${pressed.map((t) => t.id).join(", ")}): a press would show nothing \u2014 set the pressed opacity below 1, or choose another feedback`);
|
|
2134
|
+
}
|
|
2135
|
+
for (const token of Object.values(model.tokens)) {
|
|
2136
|
+
const tier = token.path[0];
|
|
2137
|
+
if (tier === "sys" && token.path[1] === "color") {
|
|
2138
|
+
if (!token.alias) failures.push(`${token.id}: sys.color roles must alias ref.palette / ref.alpha`);
|
|
2139
|
+
} else if ((tier === "sys" || tier === "comp") && !token.alias && !token.derive) {
|
|
2140
|
+
failures.push(`${token.id}: a literal needs a rule or a stated reason for being fixed; component tokens normally alias a sys token`);
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
for (const token of Object.values(model.tokens)) {
|
|
2144
|
+
if (!token.enum) continue;
|
|
2145
|
+
const names = token.enum.values;
|
|
2146
|
+
const list = (values) => (values ?? []).map((name, i) => `${name} (${i})`).join(", ");
|
|
2147
|
+
let value = token.value;
|
|
2148
|
+
if (token.alias) {
|
|
2149
|
+
const targetId = token.aliasFinal ?? token.alias;
|
|
2150
|
+
const target = model.tokens[targetId];
|
|
2151
|
+
if (!Array.isArray(target?.enum?.values)) {
|
|
2152
|
+
failures.push(`${token.id}: aliases ${targetId}, which is not a choice of kind \u2014 a choice follows another choice or is one of its own names: ${list(names)}`);
|
|
2153
|
+
continue;
|
|
2154
|
+
}
|
|
2155
|
+
if (!Array.isArray(names) || names.length !== target.enum.values.length || names.some((name, i) => name !== target.enum.values[i])) {
|
|
2156
|
+
failures.push(`${token.id}: aliases ${targetId}, whose choices differ \u2014 ${list(names)} here, ${list(target.enum.values)} there`);
|
|
2157
|
+
continue;
|
|
2158
|
+
}
|
|
2159
|
+
value = target.value;
|
|
2160
|
+
}
|
|
2161
|
+
if (!Array.isArray(names) || !Number.isInteger(value) || value < 0 || value >= names.length) failures.push(`${token.id}: ${JSON.stringify(value)} is not one of its choices \u2014 ${list(names)}`);
|
|
2162
|
+
}
|
|
2163
|
+
for (const token of Object.values(model.tokens)) {
|
|
2164
|
+
if (token.type !== "shadow" || token.alias) continue;
|
|
2165
|
+
if (!Array.isArray(token.value)) failures.push(`${token.id}: a shadow is a list of layers (an empty list draws nothing)`);
|
|
2166
|
+
else token.value.forEach((_, i) => {
|
|
2167
|
+
if (!token.partialAlias?.[i]?.color?.startsWith(`${CONFIG.namespace}.sys.color.`)) failures.push(`${token.id}: shadow layer ${i + 1} must take its color from a sys.color role`);
|
|
2168
|
+
});
|
|
2169
|
+
}
|
|
2170
|
+
for (const token of Object.values(model.tokens)) {
|
|
2171
|
+
const [tier, component, part, property, size] = token.path;
|
|
2172
|
+
if (tier !== "comp" || part !== "container" || property !== "height") continue;
|
|
2173
|
+
const at = (...rest) => model.tokens[[CONFIG.namespace, "comp", component, ...rest].join(".")];
|
|
2174
|
+
const padding = at("container", "padding-block", size)?.value?.value;
|
|
2175
|
+
const label = at("label", "typescale", size)?.value;
|
|
2176
|
+
if (padding === void 0 || !label?.fontSize) continue;
|
|
2177
|
+
const inset = at("set", "padding")?.value?.value ?? 0;
|
|
2178
|
+
const needed = 2 * padding + 2 * inset + Math.round(label.fontSize.value * label.lineHeight * 100) / 100;
|
|
2179
|
+
if (token.value.value < needed) failures.push(`${token.id}: ${token.value.value}px cannot hold its content \u2014 2 \xD7 padding-block (${padding}px)${inset ? ` + 2 \xD7 set.padding (${inset}px)` : ""} + one label line = ${needed}px`);
|
|
2180
|
+
}
|
|
2181
|
+
for (const stack of STACKED_ITEMS) {
|
|
2182
|
+
const of = (part) => model.tokens[`${CONFIG.namespace}.comp.${stack.component}.${part}`];
|
|
2183
|
+
const height = of(stack.height)?.value?.value;
|
|
2184
|
+
if (typeof height !== "number") continue;
|
|
2185
|
+
for (const size of stack.sizes ? stack.sizes(model.tokens) : [""]) {
|
|
2186
|
+
const named = (part) => part.replaceAll("<size>", size);
|
|
2187
|
+
if (stack.when && (choiceOfToken(model, of(named(stack.when[0]))) ?? choiceOfToken(model, of(stack.when[2]))) !== stack.when[1]) continue;
|
|
2188
|
+
const label = of(named(stack.label))?.value;
|
|
2189
|
+
if (!label?.fontSize) continue;
|
|
2190
|
+
const around = stack.around.map(
|
|
2191
|
+
(band) => band.flatMap((part) => part.includes("<state>.") ? STACK_STATES.map((state) => named(part).replace("<state>.", state)) : [named(part)]).map((part) => [part, of(part)?.value?.value]).filter(([, value]) => typeof value === "number").reduce((most, each) => each[1] > most[1] ? each : most, [named(band[0]).replace("<state>.", ""), 0])
|
|
2192
|
+
);
|
|
2193
|
+
const [glyph, gap] = [stack.glyph, stack.gap].map((part) => [named(part), of(named(part))?.value?.value ?? 0]);
|
|
2194
|
+
const line = Math.round(label.fontSize.value * label.lineHeight * 100) / 100;
|
|
2195
|
+
const needed = Math.round((around.reduce((sum, [, value]) => sum + 2 * value, 0) + glyph[1] + gap[1] + line) * 100) / 100;
|
|
2196
|
+
if (height >= needed) continue;
|
|
2197
|
+
const terms = [...around.map(([part, value]) => `2 \xD7 ${part} (${value}px)`), `${glyph[0]} (${glyph[1]}px)`, `${gap[0]} (${gap[1]}px)`, `one ${named(stack.label)} line (${line}px)`];
|
|
2198
|
+
failures.push(`${CONFIG.namespace}.comp.${stack.component}.${stack.height}: ${height}px cannot hold its stacked ${stack.what}${size ? ` (${size})` : ""} \u2014 ${terms.join(" + ")} = ${needed}px`);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
const role = (token) => {
|
|
2202
|
+
for (let at = token, hops = 0; at?.alias && hops < 16; at = model.tokens[at.alias], hops++) {
|
|
2203
|
+
if (at.alias.startsWith(`${CONFIG.namespace}.sys.color.`)) return at.alias.slice(`${CONFIG.namespace}.sys.color.`.length);
|
|
2204
|
+
}
|
|
2205
|
+
return void 0;
|
|
2206
|
+
};
|
|
2207
|
+
const short = (id) => id.slice(CONFIG.namespace.length + 1);
|
|
2208
|
+
for (const ring of Object.values(model.tokens)) {
|
|
2209
|
+
if (ring.path[0] !== "comp" || ring.type !== "color" || ring.path.at(-2) !== "focus-ring" || ring.path.at(-1) !== "color") continue;
|
|
2210
|
+
const barId = [CONFIG.namespace, ...ring.path.slice(0, -2), "container", "color"].join(".");
|
|
2211
|
+
const bar = model.tokens[barId];
|
|
2212
|
+
if (!bar) continue;
|
|
2213
|
+
const [ringRole, barRole] = [role(ring), role(bar)];
|
|
2214
|
+
for (const scheme of model.schemes) {
|
|
2215
|
+
const byRole = ringRole && barRole && model.colors[scheme][ringRole] && model.colors[scheme][barRole];
|
|
2216
|
+
const fg = byRole ? model.colors[scheme][ringRole].value : model.componentColors?.[scheme]?.[ring.id]?.value;
|
|
2217
|
+
const bg = byRole ? model.colors[scheme][barRole].value : model.componentColors?.[scheme]?.[barId]?.value;
|
|
2218
|
+
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
2219
|
+
const ratio = measure(scheme, "componentPairs", fg, bg);
|
|
2220
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(ring.id)} on ${short(barId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (focus indicator on the component's own bar, WCAG 2.4.13)`);
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
const snackbar = `${CONFIG.namespace}.comp.snackbar`;
|
|
2224
|
+
const inScheme = (scheme, id) => model.componentColors?.[scheme]?.[id]?.value;
|
|
2225
|
+
const number = (id) => typeof model.tokens[id]?.value === "number" ? model.tokens[id].value : 1;
|
|
2226
|
+
const faded = (color, opacity) => ({ ...color, alpha: (color.alpha ?? 1) * opacity });
|
|
2227
|
+
const flat = (fg, bg) => {
|
|
2228
|
+
const c = over(rgba(fg), rgba(bg));
|
|
2229
|
+
return { colorSpace: "srgb", components: [c.r / 255, c.g / 255, c.b / 255], alpha: 1 };
|
|
2230
|
+
};
|
|
2231
|
+
const sameColor = (x, y) => ["r", "g", "b", "a"].every((k) => rgba(x)[k] === rgba(y)[k]);
|
|
2232
|
+
const hex = (color) => `#${[rgba(color).r, rgba(color).g, rgba(color).b].map((n) => n.toString(16).padStart(2, "0")).join("")}${rgba(color).a < 1 ? ` at ${rgba(color).a}` : ""}`;
|
|
2233
|
+
if (model.system === CONFIG.namespace) {
|
|
2234
|
+
for (const scheme of model.schemes) {
|
|
2235
|
+
const other = OTHER_THEME[scheme];
|
|
2236
|
+
for (const id of Object.keys(model.componentColors?.[scheme] ?? {})) {
|
|
2237
|
+
if (!id.startsWith(`${snackbar}.`) || !STATUSES.some((status) => id.includes(`.inverse-${status}.`))) continue;
|
|
2238
|
+
const twin = id.replace(".inverse-", ".");
|
|
2239
|
+
const [here, there] = [inScheme(scheme, id), inScheme(other, twin)];
|
|
2240
|
+
if (!here || !there || sameColor(here, there)) continue;
|
|
2241
|
+
failures.push(`[${scheme}] ${short(id)} is ${hex(here)}, but ${short(twin)} is ${hex(there)} in ${other}: a status's inverse form is that status's form in the other theme (SNK-30)`);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
const STATES2 = ["", "hovered.", "focused.", "pressed."];
|
|
2246
|
+
for (const status of STATUSES) {
|
|
2247
|
+
const form = `inverse-${status}`;
|
|
2248
|
+
const barId = `${snackbar}.${form}.container.color`;
|
|
2249
|
+
if (!model.tokens[barId]) continue;
|
|
2250
|
+
const pairs = [
|
|
2251
|
+
[`${form}.title.color`, null, 1, TEXT, "title on its bar"],
|
|
2252
|
+
[`${form}.supporting-text.color`, null, 1, TEXT, "message on its bar"],
|
|
2253
|
+
[`${form}.icon.color`, null, number(`${snackbar}.icon.opacity`), NON_TEXT, "status glyph at icon.opacity on its bar"],
|
|
2254
|
+
[`${form}.supporting-text.color`, null, number(`${snackbar}.supporting-text.under-title.opacity`), TEXT, "description at its opacity under a title"]
|
|
2255
|
+
];
|
|
2256
|
+
for (const [fgName, groundName, opacity, min, why] of pairs) {
|
|
2257
|
+
const [fgId, groundId] = [`${snackbar}.${fgName}`, groundName && `${snackbar}.${groundName}`];
|
|
2258
|
+
if (!model.tokens[fgId] || groundId && !model.tokens[groundId]) continue;
|
|
2259
|
+
if (!groundId && opacity === 1 && role(model.tokens[fgId]) && role(model.tokens[barId])) continue;
|
|
2260
|
+
for (const scheme of model.schemes) {
|
|
2261
|
+
const [fg, bar, ground] = [inScheme(scheme, fgId), inScheme(scheme, barId), groundId && inScheme(scheme, groundId)];
|
|
2262
|
+
if (!fg || !bar || rgba(bar).a < 1 || groundId && !ground) continue;
|
|
2263
|
+
const bg = ground ? flat(ground, bar) : bar;
|
|
2264
|
+
const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
2265
|
+
const ratio = measure(scheme, "componentPairs", faded(fg, opacity), bg);
|
|
2266
|
+
if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(groundId ?? barId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
const ns = CONFIG.namespace;
|
|
2271
|
+
const toneOpacity = model.tokens[`${ns}.comp.button.tone.container.opacity`]?.value;
|
|
2272
|
+
const variant = model.tokens[`${snackbar}.close-button.variant`]?.value;
|
|
2273
|
+
const LAYERS = { rest: null, hovered: "hover", focused: "focus", pressed: "pressed" };
|
|
2274
|
+
const layerOpacity = Object.fromEntries(Object.entries(LAYERS).map(([state, name]) => [state, name ? model.tokens[`${ns}.sys.state.${name}-state-layer-opacity`]?.value : 0]));
|
|
2275
|
+
if (["dim", "none"].includes(choiceOf(model, "pressed-feedback"))) delete layerOpacity.pressed;
|
|
2276
|
+
if (typeof toneOpacity === "number" && typeof variant === "number" && Object.values(layerOpacity).every((value) => typeof value === "number")) {
|
|
2277
|
+
const bare = variant === 3 || variant === 4;
|
|
2278
|
+
for (const form of ["", ...STATUSES, "inverse", ...STATUSES.map((status) => `inverse-${status}`)]) {
|
|
2279
|
+
const prefix = form ? `${snackbar}.${form}` : snackbar;
|
|
2280
|
+
const [toneId, barId] = [`${prefix}.supporting-text.color`, `${prefix}.container.color`];
|
|
2281
|
+
if (!model.tokens[toneId] || !model.tokens[barId]) continue;
|
|
2282
|
+
for (const scheme of model.schemes) {
|
|
2283
|
+
const [tone, bar] = [inScheme(scheme, toneId), inScheme(scheme, barId)];
|
|
2284
|
+
if (!tone || !bar || rgba(bar).a < 1) continue;
|
|
2285
|
+
const circle = bare ? bar : flat(faded(tone, toneOpacity), bar);
|
|
2286
|
+
for (const [state, opacity] of Object.entries(layerOpacity)) {
|
|
2287
|
+
if (bare && state === "rest") continue;
|
|
2288
|
+
const ground = opacity ? flat(faded(tone, opacity), circle) : circle;
|
|
2289
|
+
const ratio = measure(scheme, "componentPairs", tone, ground);
|
|
2290
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(toneId)} on ${short(barId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (expand and close glyph on its circle over the bar, ${state})`);
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
const held2 = /* @__PURE__ */ new Map();
|
|
2296
|
+
for (const scheme of model.schemes) for (const [fg, bg, min] of pairsFor(model.colors[scheme], focusStyle)) held2.set(`${fg} ${bg}`, Math.max(min, held2.get(`${fg} ${bg}`) ?? 0));
|
|
2297
|
+
const codeBlock = `${CONFIG.namespace}.comp.code-block`;
|
|
2298
|
+
const inlineCode = `${CONFIG.namespace}.comp.inline-code`;
|
|
2299
|
+
const SYNTAX = Object.keys(model.tokens).filter((id) => id.startsWith(`${codeBlock}.syntax.color.`)).map((id) => id.slice(codeBlock.length + 1));
|
|
2300
|
+
const CODE_TEXT = ["code.color", "line-number.color", "prompt.color", ...SYNTAX];
|
|
2301
|
+
const CODE_MARKS = ["line.highlighted.mark.color", "line.added.mark.color", "line.removed.mark.color"];
|
|
2302
|
+
const codePairs = [
|
|
2303
|
+
...CODE_TEXT.flatMap((part) => [
|
|
2304
|
+
[`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, TEXT, "code on the block's fill"],
|
|
2305
|
+
[`${codeBlock}.${part}`, `${codeBlock}.line.highlighted.container.color`, TEXT, "code on a highlighted line's band"],
|
|
2306
|
+
[`${codeBlock}.${part}`, `${codeBlock}.line.added.container.color`, TEXT, "code on an added line's band"],
|
|
2307
|
+
[`${codeBlock}.${part}`, `${codeBlock}.line.removed.container.color`, TEXT, "code on a removed line's band"]
|
|
2308
|
+
]),
|
|
2309
|
+
[`${codeBlock}.line.added.mark.color`, `${codeBlock}.line.added.container.color`, NON_TEXT, "an added line's bar and sign on its band"],
|
|
2310
|
+
[`${codeBlock}.line.removed.mark.color`, `${codeBlock}.line.removed.container.color`, NON_TEXT, "a removed line's bar and sign on its band"],
|
|
2311
|
+
...CODE_MARKS.map((part) => [`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, NON_TEXT, "a marked line's bar on the block's fill"]),
|
|
2312
|
+
// An outlined block has no fill: its code is read on the surface it is placed on, so a syntax color is held on
|
|
2313
|
+
// every surface role. The other text colors of the block are roles the role pairs hold there.
|
|
2314
|
+
...SYNTAX.flatMap((part) => SURFACES.map((surface) => [`${codeBlock}.${part}`, `${CONFIG.namespace}.sys.color.${surface}`, TEXT, "code in an outlined block on a surface"])),
|
|
2315
|
+
[`${inlineCode}.label.color`, `${inlineCode}.container.color`, TEXT, "inline code on its fill"]
|
|
2316
|
+
];
|
|
2317
|
+
const comp = (name) => `${CONFIG.namespace}.comp.${name}`;
|
|
2318
|
+
const match = comp("combobox.option.match");
|
|
2319
|
+
const markPairs = [
|
|
2320
|
+
[comp("search.result.mark.color"), comp("search.result.mark.container.color"), TEXT, "a match on its fill"],
|
|
2321
|
+
[`${match}.color`, `${match}.container.color`, TEXT, "a matched run of an option on its fill"],
|
|
2322
|
+
[`${match}.selected.color`, `${match}.selected.container.color`, TEXT, "a matched run of an option on the fill a selected one takes"]
|
|
2323
|
+
];
|
|
2324
|
+
for (const [fgId, bgId, min, why] of [...codePairs, ...markPairs]) {
|
|
2325
|
+
const [fgToken, bgToken] = [model.tokens[fgId], model.tokens[bgId]];
|
|
2326
|
+
if (!fgToken || !bgToken) continue;
|
|
2327
|
+
const [fgRole, bgRole] = [role(fgToken), bgId.startsWith(`${CONFIG.namespace}.sys.color.`) ? bgId.split(".").at(-1) : role(bgToken)];
|
|
2328
|
+
if (fgRole && bgRole && (held2.get(`${fgRole} ${bgRole}`) ?? 0) >= min) continue;
|
|
2329
|
+
for (const scheme of model.schemes) {
|
|
2330
|
+
const fg = fgRole && model.colors[scheme][fgRole] ? model.colors[scheme][fgRole].value : inScheme(scheme, fgId);
|
|
2331
|
+
const bg = bgRole && model.colors[scheme][bgRole] ? model.colors[scheme][bgRole].value : inScheme(scheme, bgId);
|
|
2332
|
+
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
2333
|
+
const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
2334
|
+
const ratio = measure(scheme, "componentPairs", fg, bg);
|
|
2335
|
+
if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(bgId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
const meter = `${CONFIG.namespace}.comp.meter`;
|
|
2339
|
+
const meterGrounds = [[`${meter}.track.color`, "its track"], ...SURFACES.map((surface) => [`${CONFIG.namespace}.sys.color.${surface}`, "the surface it stands on"])];
|
|
2340
|
+
for (const part of ["indicator.color", ...STATUSES.map((status) => `${status}.indicator.color`)]) {
|
|
2341
|
+
const fgId = `${meter}.${part}`;
|
|
2342
|
+
if (!model.tokens[fgId]) continue;
|
|
2343
|
+
for (const [bgId, what] of meterGrounds) {
|
|
2344
|
+
const isRole = bgId.startsWith(`${CONFIG.namespace}.sys.color.`);
|
|
2345
|
+
if (!isRole && !model.tokens[bgId]) continue;
|
|
2346
|
+
const [fgRole, bgRole] = [role(model.tokens[fgId]), isRole ? bgId.split(".").at(-1) : role(model.tokens[bgId])];
|
|
2347
|
+
if (fgRole && bgRole && (held2.get(`${fgRole} ${bgRole}`) ?? 0) >= NON_TEXT) continue;
|
|
2348
|
+
for (const scheme of model.schemes) {
|
|
2349
|
+
const fg = fgRole && model.colors[scheme][fgRole] ? model.colors[scheme][fgRole].value : inScheme(scheme, fgId);
|
|
2350
|
+
const bg = bgRole && model.colors[scheme][bgRole] ? model.colors[scheme][bgRole].value : inScheme(scheme, bgId);
|
|
2351
|
+
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
2352
|
+
const ratio = measure(scheme, "componentPairs", fg, bg);
|
|
2353
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(fgId)} on ${short(bgId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (a meter's indicator against ${what}, where its value is read \u2014 WCAG 1.4.11)`);
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
const RADIO_MARKS = [
|
|
2358
|
+
{
|
|
2359
|
+
component: "radio-button",
|
|
2360
|
+
conditions: ["unselected", "selected", "error-unselected", "error-selected"],
|
|
2361
|
+
ring: "ring",
|
|
2362
|
+
fill: "fill",
|
|
2363
|
+
opacity: "fill.opacity",
|
|
2364
|
+
inset: "fill.inset",
|
|
2365
|
+
grounds: SURFACES.map((surface) => `${CONFIG.namespace}.sys.color.${surface}`)
|
|
2366
|
+
},
|
|
2367
|
+
{
|
|
2368
|
+
// A menu draws the radio look only while its radio items are marked as radios (MNU-40), and fills a checked one.
|
|
2369
|
+
component: "menu",
|
|
2370
|
+
when: ["radio-item.mark", "radio"],
|
|
2371
|
+
conditions: ["selected"],
|
|
2372
|
+
ring: "control",
|
|
2373
|
+
fill: "control",
|
|
2374
|
+
opacity: "control.fill.opacity",
|
|
2375
|
+
inset: "control.fill.inset",
|
|
2376
|
+
grounds: [`${CONFIG.namespace}.comp.menu.surface.color`]
|
|
2377
|
+
}
|
|
2378
|
+
];
|
|
2379
|
+
const colorOf = (scheme, id) => {
|
|
2380
|
+
const colorRole = id.startsWith(`${CONFIG.namespace}.sys.color.`) ? id.split(".").at(-1) : model.tokens[id] && role(model.tokens[id]);
|
|
2381
|
+
return colorRole && model.colors[scheme]?.[colorRole] ? model.colors[scheme][colorRole].value : inScheme(scheme, id);
|
|
2382
|
+
};
|
|
2383
|
+
for (const mark of RADIO_MARKS) {
|
|
2384
|
+
const at = (rest) => `${CONFIG.namespace}.comp.${mark.component}.${rest}`;
|
|
2385
|
+
if (!model.tokens[at(`${mark.conditions[0]}.${mark.ring}.color`)]) continue;
|
|
2386
|
+
if (mark.when) {
|
|
2387
|
+
const choice = model.tokens[at(mark.when[0])];
|
|
2388
|
+
const target = choice?.alias ? model.tokens[choice.aliasFinal ?? choice.alias] : choice;
|
|
2389
|
+
if (choice?.enum?.values?.[target?.value] !== mark.when[1]) continue;
|
|
2390
|
+
}
|
|
2391
|
+
const opacity = number(at(mark.opacity));
|
|
2392
|
+
const gap = (model.tokens[at(mark.inset)]?.value?.value ?? 0) > 0;
|
|
2393
|
+
for (const scheme of model.schemes) {
|
|
2394
|
+
for (const condition of mark.conditions) {
|
|
2395
|
+
for (const state of STATES2) {
|
|
2396
|
+
const part = (name) => inScheme(scheme, at(`${condition}.${state}${name}.color`)) ?? inScheme(scheme, at(`${condition}.${name}.color`));
|
|
2397
|
+
const [ring, fill, layer] = [part(mark.ring), part(mark.fill), part("container")];
|
|
2398
|
+
if (!ring || !fill || rgba(fill).a * opacity === 0) continue;
|
|
2399
|
+
let worst;
|
|
2400
|
+
for (const groundId of mark.grounds) {
|
|
2401
|
+
const surface = colorOf(scheme, groundId);
|
|
2402
|
+
if (!surface || rgba(surface).a < 1) continue;
|
|
2403
|
+
const ground = layer ? flat(layer, surface) : surface;
|
|
2404
|
+
const center = flat(faded(fill, opacity), ground);
|
|
2405
|
+
const ratio = contrast(center, gap ? ground : flat(ring, ground));
|
|
2406
|
+
if (!worst || ratio < worst.ratio) worst = { ratio, groundId };
|
|
2407
|
+
}
|
|
2408
|
+
if (worst) checked[scheme].componentPairs += 1;
|
|
2409
|
+
if (!worst || worst.ratio >= NON_TEXT) continue;
|
|
2410
|
+
const [fillId, besideId] = [at(`${condition}.${state}${mark.fill}.color`), gap ? short(worst.groundId) : short(at(`${condition}.${state}${mark.ring}.color`))];
|
|
2411
|
+
const why = gap ? `the dot of a radio against the gap its fill.inset leaves, which shows ${short(worst.groundId)} through the state layer \u2014 WCAG 1.4.11` : `the fill of a radio against the ring it meets, at ${short(at(mark.opacity))} ${opacity} over ${short(worst.groundId)} and the state layer \u2014 WCAG 1.4.11`;
|
|
2412
|
+
failures.push(`[${scheme}] ${short(fillId)} on ${besideId}: ${worst.ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (${why})`);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
const chip = `${CONFIG.namespace}.comp.chip`;
|
|
2418
|
+
for (const variant2 of ["outlined", "elevated"]) {
|
|
2419
|
+
const at = (rest) => `${chip}.${variant2}.${rest}`;
|
|
2420
|
+
if (!model.tokens[at("container.color")]) continue;
|
|
2421
|
+
for (const look of ["remove", "destructive-remove"]) {
|
|
2422
|
+
if (!model.tokens[at(`${look}.icon.color`)]) continue;
|
|
2423
|
+
for (const scheme of model.schemes) {
|
|
2424
|
+
for (const state of STATES2) {
|
|
2425
|
+
const part = (name) => colorOf(scheme, at(`${state}${look}.${name}.color`)) ?? colorOf(scheme, at(`${look}.${name}.color`));
|
|
2426
|
+
const [glyph, layer, container] = [part("icon"), part("container"), colorOf(scheme, at("container.color"))];
|
|
2427
|
+
if (!glyph || !container) continue;
|
|
2428
|
+
let worst;
|
|
2429
|
+
for (const surface of SURFACES) {
|
|
2430
|
+
const ground = colorOf(scheme, `${CONFIG.namespace}.sys.color.${surface}`);
|
|
2431
|
+
if (!ground || rgba(ground).a < 1) continue;
|
|
2432
|
+
const chipGround = flat(container, ground);
|
|
2433
|
+
const ratio = contrast(glyph, layer ? flat(layer, chipGround) : chipGround);
|
|
2434
|
+
if (!worst || ratio < worst.ratio) worst = { ratio, surface };
|
|
2435
|
+
if (rgba(container).a >= 1) break;
|
|
2436
|
+
}
|
|
2437
|
+
if (worst) checked[scheme].componentPairs += 1;
|
|
2438
|
+
if (!worst || worst.ratio >= NON_TEXT) continue;
|
|
2439
|
+
const beneath = rgba(container).a >= 1 ? short(at("container.color")) : `sys.color.${worst.surface}`;
|
|
2440
|
+
failures.push(`[${scheme}] ${short(at(`${state}${look}.icon.color`))} on ${short(at(`${state}${look}.container.color`))}: ${worst.ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (the remove glyph of an input chip against its round container over ${beneath} \u2014 WCAG 1.4.11)`);
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
if (model.system === CONFIG.namespace) {
|
|
2446
|
+
for (const [selectedName, hoveredName, textName] of SELECTED_ROWS) {
|
|
2447
|
+
const [selectedId, hoveredId, textId] = [selectedName, hoveredName, textName].map((name) => `${CONFIG.namespace}.comp.${name}`);
|
|
2448
|
+
if (!model.tokens[selectedId] || !model.tokens[hoveredId]) continue;
|
|
2449
|
+
for (const scheme of model.schemes) {
|
|
2450
|
+
const [selected, hovered, text2] = [colorOf(scheme, selectedId), colorOf(scheme, hoveredId), model.tokens[textId] && colorOf(scheme, textId)];
|
|
2451
|
+
if (!selected || !hovered) continue;
|
|
2452
|
+
let apart;
|
|
2453
|
+
let read;
|
|
2454
|
+
for (const surface of SURFACES) {
|
|
2455
|
+
const ground = model.colors[scheme][surface]?.value;
|
|
2456
|
+
if (!ground || rgba(ground).a < 1) continue;
|
|
2457
|
+
const fill = flat(selected, ground);
|
|
2458
|
+
const ratio = contrast(fill, flat(hovered, ground));
|
|
2459
|
+
if (!apart || ratio < apart.ratio) apart = { ratio, surface };
|
|
2460
|
+
if (text2 && !role(model.tokens[selectedId])) {
|
|
2461
|
+
const textRatio = contrast(text2, fill);
|
|
2462
|
+
if (!read || textRatio < read.ratio) read = { ratio: textRatio, surface };
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
if (apart) checked[scheme].componentPairs += 1;
|
|
2466
|
+
if (read) checked[scheme].componentPairs += 1;
|
|
2467
|
+
if (apart && apart.ratio < ROW_SELECTION) failures.push(`[${scheme}] ${short(selectedId)} on ${short(hoveredId)}: ${apart.ratio.toFixed(2)}:1 < ${ROW_SELECTION}:1 (a selected row against a hovered one, each laid over sys.color.${apart.surface}: the two read as one fill \u2014 make the selection a layer of the row's content color, as comp.list.selected.container.color is)`);
|
|
2468
|
+
const required = scheme.endsWith("-high") ? HIGH_CONTRAST_TEXT : TEXT;
|
|
2469
|
+
if (read && read.ratio < required) failures.push(`[${scheme}] ${short(textId)} on ${short(selectedId)}: ${read.ratio.toFixed(2)}:1 < ${required}:1 (a selected row's text on its fill, laid over sys.color.${read.surface})`);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
if (model.system === CONFIG.namespace) {
|
|
2474
|
+
const px2 = (id) => model.tokens[id]?.value?.value;
|
|
2475
|
+
for (const token of Object.values(model.tokens)) {
|
|
2476
|
+
if (!token.concentric) continue;
|
|
2477
|
+
const [outerId, insetId] = [token.concentric.outer, token.concentric.inset].map((ref) => typeof ref === "string" ? ref.replace(/^\{|\}$/g, "") : void 0);
|
|
2478
|
+
const [inner, outer, inset] = [token.value?.value, px2(outerId), px2(insetId)];
|
|
2479
|
+
if (typeof inner !== "number" || typeof outer !== "number" || typeof inset !== "number") {
|
|
2480
|
+
failures.push(`${short(token.id)}: dev.tanrei.concentric names ${JSON.stringify(token.concentric)}, which must be two dimension tokens, { "outer": "{id}", "inset": "{id}" }`);
|
|
2481
|
+
continue;
|
|
2482
|
+
}
|
|
2483
|
+
const expected = Math.max(0, outer - inset);
|
|
2484
|
+
if (inner !== expected) failures.push(`${short(token.id)}: ${inner}px, but an inner corner is its outer corner less the inset, never below zero \u2014 max(0, ${short(outerId)} ${outer}px \u2212 ${short(insetId)} ${inset}px) = ${expected}px; derive it with { "fn": "sub", "of": "{${outerId}}", "by": "{${insetId}}" }`);
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
const px = (id) => model.tokens[`${CONFIG.namespace}.${id}`]?.value?.value;
|
|
2488
|
+
const minimum = px("sys.target.minimum");
|
|
2489
|
+
for (const name of ["minimum", "pointer", "touch"]) {
|
|
2490
|
+
const value = px(`sys.target.${name}`);
|
|
2491
|
+
if (typeof value === "number" && value < TARGET_THRESHOLDS.minimum) failures.push(`target size: sys.target.${name}: ${value}px < ${TARGET_THRESHOLDS.minimum}px (WCAG 2.5.8: the least target a person presses)`);
|
|
2492
|
+
if (name !== "minimum" && typeof value === "number" && typeof minimum === "number" && value < minimum) failures.push(`target floor: sys.target.${name}: ${value}px is under sys.target.minimum (${minimum}px) \u2014 the area a press is taken from is never smaller than what is drawn; set it to the minimum or above`);
|
|
2493
|
+
}
|
|
2494
|
+
if (typeof minimum === "number") {
|
|
2495
|
+
const MIN = `{${CONFIG.namespace}.sys.target.minimum}`;
|
|
2496
|
+
const floored = /* @__PURE__ */ new Set([...model.floored ?? [], ...Object.values(model.tokens).filter((token) => token.derive?.min === MIN).map((token) => token.id)]);
|
|
2497
|
+
for (const id of [...floored].sort()) {
|
|
2498
|
+
const value = model.tokens[id]?.value?.value;
|
|
2499
|
+
if (typeof value === "number" && value < minimum) failures.push(`target size: ${id.slice(CONFIG.namespace.length + 1)}: ${value}px < sys.target.minimum ${minimum}px (a box a person presses is drawn at least the minimum target; derive it with "min": "${MIN}", or lower the minimum)`);
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
const controlHeight = px("dial.control.height");
|
|
2503
|
+
if (typeof minimum === "number" && typeof controlHeight === "number" && minimum > controlHeight) failures.push(`target floor: sys.target.minimum: ${minimum}px is above dial.control.height (${controlHeight}px) \u2014 a control of the default size is drawn at the control height; lower the minimum or raise the control height`);
|
|
2504
|
+
if ((model.system === CONFIG.namespace || model.system === "core") && model.ladder) {
|
|
2505
|
+
for (const id of model.aligned ?? []) {
|
|
2506
|
+
if (model.ladder[id] !== "medium") failures.push(`${short(id)}: marked ${ALIGNED}, but it does not read sys.control.height.medium \u2014 derive it with { "fn": "mul", "of": "{${CONFIG.namespace}.sys.control.height.medium}", "by": 1, "min": "{${CONFIG.namespace}.sys.target.minimum}" }, or alias a token that does`);
|
|
2507
|
+
}
|
|
2508
|
+
const own2 = new Set(model.own ?? []);
|
|
2509
|
+
for (const id of model.floored ?? []) {
|
|
2510
|
+
if (!(id in model.ladder) && !own2.has(id)) failures.push(`${short(id)}: a pressable height that reads no step of the control height ladder \u2014 read the step of its size, { "fn": "mul", "of": "{${CONFIG.namespace}.sys.control.height.<step>}", "by": 1, "min": "{${CONFIG.namespace}.sys.target.minimum}" }, or, where its spec says it keeps a size of its own at every control height, mark it "${ALIGNED}": "own"`);
|
|
2511
|
+
}
|
|
2512
|
+
const floored = new Set(model.floored ?? []);
|
|
2513
|
+
for (const id of own2) {
|
|
2514
|
+
if (id in model.ladder || !floored.has(id)) failures.push(`${short(id)}: marked ${ALIGNED} "own", but it ${id in model.ladder ? "reads a step of the ladder" : "is no pressable height the core floors"} \u2014 take the mark off`);
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
if (model.system === CONFIG.namespace && model.ladder) {
|
|
2518
|
+
const floored = new Set(model.floored ?? []);
|
|
2519
|
+
for (const [id, step] of Object.entries(model.ladder)) {
|
|
2520
|
+
const [value, height] = [model.tokens[id]?.value?.value, px(`sys.control.height.${step}`)];
|
|
2521
|
+
if (typeof value !== "number" || typeof height !== "number") continue;
|
|
2522
|
+
const held3 = floored.has(id) && typeof minimum === "number" && minimum > height;
|
|
2523
|
+
const expected = held3 ? minimum : height;
|
|
2524
|
+
if (value !== expected) failures.push(`${short(id)}: ${value}px, but a control of the ${step} size is as tall as sys.control.height.${step} (${height}px)${held3 ? `, held at sys.target.minimum (${minimum}px)` : ""} \u2014 read the step, { "fn": "mul", "of": "{${CONFIG.namespace}.sys.control.height.${step}}", "by": 1${floored.has(id) ? `, "min": "{${CONFIG.namespace}.sys.target.minimum}"` : ""} }`);
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
const TOLD_APART = [
|
|
2528
|
+
["link", "standard.label.color", "sys.color.on-surface", "a link beside body text"],
|
|
2529
|
+
["link", "inverse.label.color", "sys.color.inverse-on-surface", "a link beside text on an inverse surface"],
|
|
2530
|
+
["breadcrumbs", "item.content.color", "comp.breadcrumbs.label.color", "a level that is a link beside a level that is text"]
|
|
2531
|
+
];
|
|
2532
|
+
for (const [component, fgName, besideName, why] of TOLD_APART) {
|
|
2533
|
+
const choice = model.tokens[`${CONFIG.namespace}.comp.${component}.underline.visibility`];
|
|
2534
|
+
if (!choice?.enum) continue;
|
|
2535
|
+
const target = choice.alias ? model.tokens[choice.aliasFinal ?? choice.alias] : choice;
|
|
2536
|
+
const named = choice.enum.values?.[target?.value];
|
|
2537
|
+
if (!named || named === "always") continue;
|
|
2538
|
+
const [fgId, besideId] = [`${CONFIG.namespace}.comp.${component}.${fgName}`, `${CONFIG.namespace}.${besideName}`];
|
|
2539
|
+
const colorIn = (scheme, id) => {
|
|
2540
|
+
const colorRole = id.startsWith(`${CONFIG.namespace}.sys.color.`) ? id.split(".").at(-1) : model.tokens[id] && role(model.tokens[id]);
|
|
2541
|
+
return colorRole && model.colors[scheme][colorRole] ? model.colors[scheme][colorRole].value : inScheme(scheme, id);
|
|
2542
|
+
};
|
|
2543
|
+
for (const scheme of model.schemes) {
|
|
2544
|
+
const [fg, beside] = [colorIn(scheme, fgId), colorIn(scheme, besideId)];
|
|
2545
|
+
if (!fg || !beside || rgba(fg).a < 1 || rgba(beside).a < 1) continue;
|
|
2546
|
+
const ratio = measure(scheme, "componentPairs", fg, beside);
|
|
2547
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(fgId)} against ${short(besideId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (${why}, while ${short(choice.id)} is "${named}": a link not underlined at rest is told from text by color alone \u2014 WCAG 1.4.1; underline it always, or move the link color)`);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
const drawer = (rest) => model.tokens[`${CONFIG.namespace}.comp.navigation-drawer.${rest}`];
|
|
2551
|
+
const [least, opens, greatest] = ["min-width", "width", "max-width"].map((name) => drawer(`container.${name}`)?.value?.value);
|
|
2552
|
+
if (typeof least === "number" && typeof opens === "number" && typeof greatest === "number") {
|
|
2553
|
+
if (!(least <= opens && opens <= greatest)) failures.push(`navigation drawer widths: comp.navigation-drawer.container.min-width ${least}px \u2264 container.width ${opens}px \u2264 container.max-width ${greatest}px does not hold \u2014 the drawer opens at its width, between the least and the greatest a person can give it`);
|
|
2554
|
+
for (const token of Object.values(model.tokens)) {
|
|
2555
|
+
if (!token.id.startsWith(`${CONFIG.namespace}.comp.navigation-drawer.collapsed.container.width.`)) continue;
|
|
2556
|
+
const column = token.value?.value;
|
|
2557
|
+
if (typeof column === "number" && !(column < least)) failures.push(`navigation drawer widths: ${short(token.id)} ${column}px is not below container.min-width ${least}px \u2014 a drag folds a collapsible drawer halfway between its column and its least width, so the column is the narrower of the two at every size`);
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
return { failures, checked };
|
|
2561
|
+
}
|
|
2562
|
+
var checkInvariants = (model) => auditInvariants(model).failures;
|
|
2563
|
+
|
|
2564
|
+
// ../tokens-build/src/model.js
|
|
2565
|
+
import fs4 from "node:fs";
|
|
2566
|
+
import path5 from "node:path";
|
|
2567
|
+
import { fileURLToPath, pathToFileURL as pathToFileURL2 } from "node:url";
|
|
2568
|
+
|
|
2569
|
+
// ../tokens-build/src/reader.js
|
|
2570
|
+
var TokenReadError = class extends Error {
|
|
2571
|
+
};
|
|
2572
|
+
var collator = new Intl.Collator("en-us", { numeric: true });
|
|
2573
|
+
var ALIAS = /^\{([^}]+)\}$/;
|
|
2574
|
+
var isAlias = (value) => typeof value === "string" && ALIAS.test(value);
|
|
2575
|
+
var isObject = (value) => value !== null && typeof value === "object";
|
|
2576
|
+
var DTCG_TYPES = /* @__PURE__ */ new Set(["color", "dimension", "fontFamily", "fontWeight", "duration", "cubicBezier", "number", "strokeStyle", "border", "transition", "shadow", "gradient", "typography"]);
|
|
2577
|
+
var NESTED = {
|
|
2578
|
+
border: { color: ["color"], stroke: ["strokeStyle"], width: ["dimension"] },
|
|
2579
|
+
gradient: { color: ["color"], position: ["number"] },
|
|
2580
|
+
shadow: { color: ["color"], offsetX: ["dimension"], offsetY: ["dimension"], blur: ["dimension"], spread: ["dimension"], inset: ["boolean"] },
|
|
2581
|
+
strokeStyle: { dashArray: ["dimension"] },
|
|
2582
|
+
transition: { duration: ["duration"], delay: ["duration"], timingFunction: ["cubicBezier"] },
|
|
2583
|
+
typography: { fontFamily: ["fontFamily"], fontWeight: ["fontWeight"], fontSize: ["dimension"], lineHeight: ["dimension", "number"], letterSpacing: ["dimension"], paragraphSpacing: ["dimension", "string"], wordSpacing: ["dimension", "string"] }
|
|
2584
|
+
};
|
|
2585
|
+
var FONT_WEIGHTS = {
|
|
2586
|
+
thin: 100,
|
|
2587
|
+
hairline: 100,
|
|
2588
|
+
"extra-light": 200,
|
|
2589
|
+
"ultra-light": 200,
|
|
2590
|
+
light: 300,
|
|
2591
|
+
normal: 400,
|
|
2592
|
+
regular: 400,
|
|
2593
|
+
book: 400,
|
|
2594
|
+
medium: 500,
|
|
2595
|
+
"semi-bold": 600,
|
|
2596
|
+
"demi-bold": 600,
|
|
2597
|
+
bold: 700,
|
|
2598
|
+
"extra-bold": 800,
|
|
2599
|
+
"ultra-bold": 800,
|
|
2600
|
+
black: 900,
|
|
2601
|
+
heavy: 900,
|
|
2602
|
+
"extra-black": 950,
|
|
2603
|
+
"ultra-black": 950
|
|
2604
|
+
};
|
|
2605
|
+
function merge(under, over2) {
|
|
2606
|
+
if (under === void 0 || !isObject(over2) || Array.isArray(over2)) return over2;
|
|
2607
|
+
if (under === null) return null;
|
|
2608
|
+
if (typeof under !== "object") return over2;
|
|
2609
|
+
const out = Array.isArray(under) ? [...under] : { ...under };
|
|
2610
|
+
for (const key of Object.keys(over2)) out[key] = Object.hasOwn(under, key) ? merge(under[key], over2[key]) : over2[key];
|
|
2611
|
+
return out;
|
|
2612
|
+
}
|
|
2613
|
+
var GROUP_KEYS = /* @__PURE__ */ new Set(["$type", "$description", "$deprecated", "$extensions", "$value", "$schema"]);
|
|
2614
|
+
var resolvedForms = /* @__PURE__ */ new WeakMap();
|
|
2615
|
+
var normalForms = /* @__PURE__ */ new WeakMap();
|
|
2616
|
+
function normalColor(value, id) {
|
|
2617
|
+
if (typeof value === "string" && !isAlias(value)) throw new TokenReadError(`${id}: a color written as a string ("${value}") is not read; write it in the object notation`);
|
|
2618
|
+
if (!isObject(value) || value.alpha !== void 0) return value;
|
|
2619
|
+
return normalForm(value, "color", () => ({ ...value, alpha: 1 }));
|
|
2620
|
+
}
|
|
2621
|
+
function normalForm(value, type, make) {
|
|
2622
|
+
let forms = normalForms.get(value);
|
|
2623
|
+
if (!forms) normalForms.set(value, forms = /* @__PURE__ */ new Map());
|
|
2624
|
+
if (!forms.has(type)) forms.set(type, make());
|
|
2625
|
+
return forms.get(type);
|
|
2626
|
+
}
|
|
2627
|
+
var fontFamily = (value) => typeof value === "string" ? [value] : value;
|
|
2628
|
+
var fontWeight = (value) => typeof value === "string" && FONT_WEIGHTS[value] || value;
|
|
2629
|
+
function withFields(value, changes) {
|
|
2630
|
+
let out = value;
|
|
2631
|
+
for (const [key, next] of changes) {
|
|
2632
|
+
if (next === value[key] && key in value) continue;
|
|
2633
|
+
if (out === value) out = Array.isArray(value) ? [...value] : { ...value };
|
|
2634
|
+
out[key] = next;
|
|
2635
|
+
}
|
|
2636
|
+
return out;
|
|
2637
|
+
}
|
|
2638
|
+
function normalize(value, type, id) {
|
|
2639
|
+
switch (type) {
|
|
2640
|
+
case "color":
|
|
2641
|
+
return normalColor(value, id);
|
|
2642
|
+
case "fontFamily":
|
|
2643
|
+
return fontFamily(value);
|
|
2644
|
+
case "fontWeight":
|
|
2645
|
+
return fontWeight(value);
|
|
2646
|
+
case "border":
|
|
2647
|
+
return isObject(value) && value.color ? normalForm(value, type, () => withFields(value, [["color", normalColor(value.color, id)]])) : value;
|
|
2648
|
+
case "shadow": {
|
|
2649
|
+
const layer = (shadow) => isObject(shadow) ? withFields(shadow, [...shadow.color ? [["color", normalColor(shadow.color, id)]] : [], ..."inset" in shadow ? [] : [["inset", false]]]) : shadow;
|
|
2650
|
+
if (!isObject(value)) return [value];
|
|
2651
|
+
return normalForm(value, type, () => Array.isArray(value) ? withFields(value, value.map((shadow, i) => [i, layer(shadow)])) : [layer(value)]);
|
|
2652
|
+
}
|
|
2653
|
+
case "gradient":
|
|
2654
|
+
if (!Array.isArray(value)) return value;
|
|
2655
|
+
return normalForm(value, type, () => withFields(value, value.map((stop, i) => [i, isObject(stop) && stop.color ? withFields(stop, [["color", normalColor(stop.color, id)]]) : stop])));
|
|
2656
|
+
case "transition":
|
|
2657
|
+
if (!isObject(value)) return value;
|
|
2658
|
+
return normalForm(value, type, () => withFields(value, [...value.duration ? [] : [["duration", { value: 0, unit: "ms" }]], ...value.delay ? [] : [["delay", { value: 0, unit: "ms" }]], ...value.timingFunction ? [] : [["timingFunction", [0, 0, 1, 1]]]]));
|
|
2659
|
+
case "typography":
|
|
2660
|
+
if (!isObject(value)) return value;
|
|
2661
|
+
return normalForm(value, type, () => withFields(value, [..."fontFamily" in value ? [["fontFamily", fontFamily(value.fontFamily)]] : [], ..."fontWeight" in value ? [["fontWeight", fontWeight(value.fontWeight)]] : []]));
|
|
2662
|
+
default:
|
|
2663
|
+
return value;
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
var pointerPart = (part) => part.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
2667
|
+
var Name = class _Name {
|
|
2668
|
+
constructor(parent, key) {
|
|
2669
|
+
this.id = parent ? parent.id ? `${parent.id}.${key}` : key : "";
|
|
2670
|
+
this.jsonID = parent ? `${parent.jsonID === "#/" ? "#" : parent.jsonID}/${pointerPart(key)}` : "#/";
|
|
2671
|
+
this.children = void 0;
|
|
2672
|
+
this.reference = void 0;
|
|
2673
|
+
this.rank = void 0;
|
|
2674
|
+
}
|
|
2675
|
+
child(key) {
|
|
2676
|
+
let child = (this.children ??= /* @__PURE__ */ new Map()).get(key);
|
|
2677
|
+
if (!child) this.children.set(key, child = new _Name(this, key));
|
|
2678
|
+
return child;
|
|
2679
|
+
}
|
|
2680
|
+
/** The reference a dependency is written as: the pointer of the token's value. */
|
|
2681
|
+
get ref() {
|
|
2682
|
+
return this.reference ??= `${this.jsonID}/$value`;
|
|
2683
|
+
}
|
|
2684
|
+
};
|
|
2685
|
+
var SCALARS = ["$type", "$description", "$deprecated", "$value", "$extensions", "aliasOf", "originalValue"];
|
|
2686
|
+
var LISTS2 = ["aliasChain", "aliasedBy", "dependencies"];
|
|
2687
|
+
var sameList = (a, b) => a === b || a !== void 0 && b !== void 0 && a.length === b.length && a.every((item, i) => item === b[i]);
|
|
2688
|
+
var sameShape = (a, b) => a === b || isObject(a) && isObject(b) && Array.isArray(a) === Array.isArray(b) && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => key in b && sameShape(a[key], b[key]));
|
|
2689
|
+
function readBundle(files, systemId) {
|
|
2690
|
+
const name = `${systemId}.resolver.json`;
|
|
2691
|
+
const resolver = files[name];
|
|
2692
|
+
if (!resolver) throw new Error(`the bundle has no ${name}`);
|
|
2693
|
+
const documentOf = (source2, where) => {
|
|
2694
|
+
if (typeof source2?.$ref !== "string") return source2;
|
|
2695
|
+
if (source2.$ref.startsWith("#")) throw new TokenReadError(`${name} ${where}: a source that points into the resolver document ("${source2.$ref}") is not read`);
|
|
2696
|
+
const doc = files[source2.$ref];
|
|
2697
|
+
if (!doc) throw new Error(`the bundle has no ${source2.$ref}`);
|
|
2698
|
+
return doc;
|
|
2699
|
+
};
|
|
2700
|
+
const steps = (resolver.resolutionOrder ?? []).map(({ $ref }, i) => {
|
|
2701
|
+
const [, kind, key] = /^#\/(sets|modifiers)\/(.+)$/.exec($ref ?? "") ?? [];
|
|
2702
|
+
const item = kind && resolver[kind]?.[key];
|
|
2703
|
+
if (!item) throw new TokenReadError(`${name} resolutionOrder[${i}]: "${$ref}" names no set and no modifier of this document`);
|
|
2704
|
+
return kind === "sets" ? { set: key, sources: item.sources ?? [] } : { modifier: key, contexts: item.contexts ?? {}, default: typeof item.default === "string" ? item.default : Object.keys(item.contexts ?? {})[0] };
|
|
2705
|
+
});
|
|
2706
|
+
const modifiers = steps.filter((step) => step.modifier);
|
|
2707
|
+
const schemeModifier = modifiers.find((step) => step.modifier === "scheme");
|
|
2708
|
+
const mergeSources = (tree, sources2, where) => sources2.reduce((acc, source2) => merge(acc, documentOf(source2, where)), tree);
|
|
2709
|
+
const firstModifier = steps.findIndex((step) => step.modifier);
|
|
2710
|
+
const shared = steps.slice(0, firstModifier < 0 ? steps.length : firstModifier);
|
|
2711
|
+
let common;
|
|
2712
|
+
const treeOf = (input) => {
|
|
2713
|
+
common ??= { tree: shared.reduce((tree2, step) => mergeSources(tree2, step.sources, `sets.${step.set}`), {}) };
|
|
2714
|
+
let tree = common.tree;
|
|
2715
|
+
for (const step of steps.slice(shared.length)) {
|
|
2716
|
+
if (step.set) tree = mergeSources(tree, step.sources, `sets.${step.set}`);
|
|
2717
|
+
else {
|
|
2718
|
+
const context = input[step.modifier] ?? step.default;
|
|
2719
|
+
if (!step.contexts[context]) throw new TokenReadError(`Modifier ${step.modifier} has no context ${JSON.stringify(context)}.`);
|
|
2720
|
+
tree = mergeSources(tree, step.contexts[context], `modifiers.${step.modifier}.contexts.${context}`);
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
return tree;
|
|
2724
|
+
};
|
|
2725
|
+
const root2 = new Name();
|
|
2726
|
+
const canonical = /* @__PURE__ */ new Map();
|
|
2727
|
+
let sorted;
|
|
2728
|
+
const ranked = /* @__PURE__ */ new Set();
|
|
2729
|
+
const read = /* @__PURE__ */ new Map();
|
|
2730
|
+
function tokensOf(input) {
|
|
2731
|
+
const key = JSON.stringify(modifiers.map((step) => input[step.modifier] ?? step.default));
|
|
2732
|
+
if (!read.has(key)) read.set(key, resolveTree(treeOf(input)));
|
|
2733
|
+
return read.get(key);
|
|
2734
|
+
}
|
|
2735
|
+
function resolveTree(tree) {
|
|
2736
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2737
|
+
const walk = (node, at, type, deprecated) => {
|
|
2738
|
+
const ownType = node.$type || type;
|
|
2739
|
+
const ownDeprecated = node.$deprecated ?? deprecated;
|
|
2740
|
+
if (Object.hasOwn(node, "$value")) entries.set(at.id, { name: at, node, type: ownType, deprecated: ownDeprecated, state: 0 });
|
|
2741
|
+
for (const key of Object.keys(node)) {
|
|
2742
|
+
const child = node[key];
|
|
2743
|
+
if (key.charCodeAt(0) === 36) {
|
|
2744
|
+
if (!GROUP_KEYS.has(key) && (key === "$ref" || key === "$extends" || key === "$root" || isObject(child))) throw new TokenReadError(`${at.id || "(the document)"}: "${key}" is not read by Tanrei's reader of its own bundles`);
|
|
2745
|
+
continue;
|
|
2746
|
+
}
|
|
2747
|
+
if (isObject(child) && !Array.isArray(child)) walk(child, at.child(key), ownType, ownDeprecated);
|
|
2748
|
+
}
|
|
2749
|
+
};
|
|
2750
|
+
walk(tree, root2, void 0, void 0);
|
|
2751
|
+
const fail = (entry, message) => {
|
|
2752
|
+
throw new TokenReadError(`${entry.name.id}: ${message}`);
|
|
2753
|
+
};
|
|
2754
|
+
const chainOf = (alias, entry) => {
|
|
2755
|
+
const target = entries.get(alias.slice(1, -1));
|
|
2756
|
+
if (!target) fail(entry, `Could not resolve alias ${alias}.`);
|
|
2757
|
+
if (target.way) return target.way;
|
|
2758
|
+
if (target.walking) fail(entry, "Circular alias detected.");
|
|
2759
|
+
target.walking = true;
|
|
2760
|
+
const links = isAlias(target.node.$value) ? [target, ...chainOf(target.node.$value, entry).links] : [target];
|
|
2761
|
+
target.walking = false;
|
|
2762
|
+
return target.way = { links, end: links.at(-1), ids: links.map((link) => link.name.id), refs: links.map((link) => link.name.ref).sort(collator.compare) };
|
|
2763
|
+
};
|
|
2764
|
+
const deep = (value, expected, path11, entry, partials) => {
|
|
2765
|
+
if (typeof value !== "string") {
|
|
2766
|
+
if (Array.isArray(value)) {
|
|
2767
|
+
const inner = expected?.includes("cubicBezier") ? ["number"] : expected;
|
|
2768
|
+
return withFields(value, value.flatMap((item, i) => item ? [[i, deep(item, inner, [...path11, i], entry, partials)]] : []));
|
|
2769
|
+
}
|
|
2770
|
+
const fields = isObject(value) && expected?.length ? NESTED[expected[0]] : void 0;
|
|
2771
|
+
return fields ? withFields(value, Object.keys(value).map((key) => [key, deep(value[key], fields[key], [...path11, key], entry, partials)])) : value;
|
|
2772
|
+
}
|
|
2773
|
+
if (!isAlias(value)) {
|
|
2774
|
+
if ((!expected?.[0] || DTCG_TYPES.has(expected[0])) && (value.includes("{") || value.includes("}"))) fail(entry, "Invalid alias syntax.");
|
|
2775
|
+
return value;
|
|
2776
|
+
}
|
|
2777
|
+
const way = chainOf(value, entry);
|
|
2778
|
+
if (expected?.length && !expected.includes(way.end.type)) fail(entry, `Cannot alias to $type "${way.end.type}" from $type "${expected.join(" / ")}".`);
|
|
2779
|
+
partials.push({ path: path11, way });
|
|
2780
|
+
return literal(way.end).value;
|
|
2781
|
+
};
|
|
2782
|
+
const literal = (entry) => {
|
|
2783
|
+
if (entry.state === 2) return entry;
|
|
2784
|
+
if (entry.state === 1) fail(entry, "Circular alias detected.");
|
|
2785
|
+
entry.state = 1;
|
|
2786
|
+
const raw = entry.node.$value;
|
|
2787
|
+
if (isObject(raw) && hasReference(raw)) fail(entry, `"$ref" inside a value is not read by Tanrei's reader of its own bundles`);
|
|
2788
|
+
entry.partials = [];
|
|
2789
|
+
entry.value = deep(raw, entry.type ? [entry.type] : void 0, [], entry, entry.partials);
|
|
2790
|
+
if (entry.value !== raw) {
|
|
2791
|
+
const ends = entry.partials.map((partial) => partial.way.end.value);
|
|
2792
|
+
const forms = resolvedForms.get(raw) ?? resolvedForms.set(raw, []).get(raw);
|
|
2793
|
+
const known = forms.find((form) => form.type === entry.type && sameList(form.ends, ends));
|
|
2794
|
+
if (known) entry.value = known.value;
|
|
2795
|
+
else forms.push({ type: entry.type, ends, value: entry.value });
|
|
2796
|
+
}
|
|
2797
|
+
entry.state = 2;
|
|
2798
|
+
return entry;
|
|
2799
|
+
};
|
|
2800
|
+
for (const entry of entries.values()) {
|
|
2801
|
+
const raw = entry.node.$value;
|
|
2802
|
+
if (!isAlias(raw)) {
|
|
2803
|
+
literal(entry);
|
|
2804
|
+
continue;
|
|
2805
|
+
}
|
|
2806
|
+
entry.walking = true;
|
|
2807
|
+
entry.chain = chainOf(raw, entry);
|
|
2808
|
+
entry.walking = false;
|
|
2809
|
+
const { end } = entry.chain;
|
|
2810
|
+
if (entry.type && entry.type !== end.type) fail(entry, `Cannot alias to $type "${end.type}" from $type "${entry.type}".`);
|
|
2811
|
+
entry.type ||= end.type;
|
|
2812
|
+
entry.value = literal(end).value || raw;
|
|
2813
|
+
}
|
|
2814
|
+
const aliasedBy = /* @__PURE__ */ new Map();
|
|
2815
|
+
const reached = (target, by) => {
|
|
2816
|
+
let set = aliasedBy.get(target);
|
|
2817
|
+
if (!set) aliasedBy.set(target, set = /* @__PURE__ */ new Set());
|
|
2818
|
+
set.add(by);
|
|
2819
|
+
};
|
|
2820
|
+
for (const entry of entries.values()) {
|
|
2821
|
+
for (const { links } of entry.chain ? [entry.chain] : entry.partials.map((partial) => partial.way)) {
|
|
2822
|
+
for (let i = 0; i < links.length; i += 1) {
|
|
2823
|
+
reached(links[i], entry.name);
|
|
2824
|
+
for (let j = 0; j < i; j += 1) reached(links[i], links[j].name);
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
const walked = [...entries.values()];
|
|
2829
|
+
if (!sorted || sorted.walked.length !== walked.length || !sorted.walked.every((at, i) => at === walked[i].name)) {
|
|
2830
|
+
const order = walked.map((entry) => entry.name).sort((a, b) => collator.compare(a.jsonID, b.jsonID));
|
|
2831
|
+
sorted = { walked: walked.map((entry) => entry.name), order };
|
|
2832
|
+
if (order.some((at) => at.rank === void 0)) {
|
|
2833
|
+
for (const at of order) ranked.add(at);
|
|
2834
|
+
[...ranked].sort((a, b) => collator.compare(a.id, b.id)).forEach((at, i) => at.rank = i);
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
const byRank = (a, b) => a.rank - b.rank;
|
|
2838
|
+
const tokens = {};
|
|
2839
|
+
for (const at of sorted.order) {
|
|
2840
|
+
const entry = entries.get(at.id);
|
|
2841
|
+
const { node } = entry;
|
|
2842
|
+
const ways = entry.chain ? void 0 : entry.partials.map((partial) => partial.way);
|
|
2843
|
+
const token = {
|
|
2844
|
+
id: at.id,
|
|
2845
|
+
$type: entry.type,
|
|
2846
|
+
$description: node.$description || void 0,
|
|
2847
|
+
$deprecated: entry.deprecated ?? void 0,
|
|
2848
|
+
$value: normalize(entry.value, entry.type, at.id),
|
|
2849
|
+
$extensions: node.$extensions || void 0,
|
|
2850
|
+
aliasChain: entry.chain?.ids,
|
|
2851
|
+
aliasedBy: aliasedBy.has(entry) ? [...aliasedBy.get(entry)].sort(byRank).map((by) => by.id) : void 0,
|
|
2852
|
+
aliasOf: entry.chain?.end.name.id,
|
|
2853
|
+
partialAliasOf: entry.chain ? void 0 : partialAliases(entry),
|
|
2854
|
+
dependencies: entry.chain ? entry.chain.refs : ways.length === 1 ? ways[0].refs : ways.length ? [...new Set(ways.flatMap((way) => way.refs))].sort(collator.compare) : void 0,
|
|
2855
|
+
originalValue: node,
|
|
2856
|
+
jsonID: at.jsonID
|
|
2857
|
+
};
|
|
2858
|
+
tokens[at.id] = share(token);
|
|
2859
|
+
}
|
|
2860
|
+
return tokens;
|
|
2861
|
+
}
|
|
2862
|
+
function share(token) {
|
|
2863
|
+
const known = canonical.get(token.id);
|
|
2864
|
+
if (!known) return canonical.set(token.id, [token]), token;
|
|
2865
|
+
for (const other of known) {
|
|
2866
|
+
if (SCALARS.every((key) => token[key] === other[key]) && LISTS2.every((key) => sameList(token[key], other[key])) && sameShape(token.partialAliasOf, other.partialAliasOf)) return other;
|
|
2867
|
+
}
|
|
2868
|
+
for (const key of LISTS2) if (sameList(token[key], known[0][key])) token[key] = known[0][key];
|
|
2869
|
+
if (sameShape(token.partialAliasOf, known[0].partialAliasOf)) token.partialAliasOf = known[0].partialAliasOf;
|
|
2870
|
+
known.push(token);
|
|
2871
|
+
return token;
|
|
2872
|
+
}
|
|
2873
|
+
const reader = {
|
|
2874
|
+
schemes: Object.keys(schemeModifier?.contexts ?? {}),
|
|
2875
|
+
defaultScheme: schemeModifier?.default,
|
|
2876
|
+
/** The tokens of one scheme, by id. Read on first use, then kept. */
|
|
2877
|
+
tokens: (scheme) => tokensOf(scheme === void 0 ? {} : { scheme }),
|
|
2878
|
+
/** The same, in the words of a DTCG resolver: `apply({ scheme })`. */
|
|
2879
|
+
apply: (input = {}) => tokensOf(input)
|
|
2880
|
+
};
|
|
2881
|
+
return reader;
|
|
2882
|
+
}
|
|
2883
|
+
var referenceFree = /* @__PURE__ */ new WeakSet();
|
|
2884
|
+
function hasReference(value) {
|
|
2885
|
+
if (referenceFree.has(value)) return false;
|
|
2886
|
+
for (const [key, child] of Array.isArray(value) ? value.entries() : Object.entries(value)) {
|
|
2887
|
+
if (key === "$ref" || isObject(child) && hasReference(child)) return true;
|
|
2888
|
+
}
|
|
2889
|
+
referenceFree.add(value);
|
|
2890
|
+
return false;
|
|
2891
|
+
}
|
|
2892
|
+
function partialAliases(entry) {
|
|
2893
|
+
const value = entry.value;
|
|
2894
|
+
if (!entry.partials.length || !isObject(value)) return void 0;
|
|
2895
|
+
const loneShadow = entry.type === "shadow" && !Array.isArray(value);
|
|
2896
|
+
const out = Array.isArray(value) || entry.type === "shadow" ? [] : {};
|
|
2897
|
+
for (const { path: path11, way } of entry.partials) {
|
|
2898
|
+
if (!path11.length) continue;
|
|
2899
|
+
if (loneShadow && !out.length) out.push({});
|
|
2900
|
+
let into = loneShadow ? out[0] : out;
|
|
2901
|
+
let node = value;
|
|
2902
|
+
path11.forEach((key, i) => {
|
|
2903
|
+
if (isObject(node) && key in node && node[key] !== void 0) node = node[key];
|
|
2904
|
+
if (i === path11.length - 1) into[key] = way.ids[0];
|
|
2905
|
+
if (!(key in into)) into[key] = Array.isArray(node) ? [] : {};
|
|
2906
|
+
into = into[key];
|
|
2907
|
+
});
|
|
2908
|
+
}
|
|
2909
|
+
return out;
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2912
|
+
// ../tokens-build/src/model.js
|
|
2913
|
+
var REPO_ROOT = process.env.TANREI_VOCABULARY_ROOT ? path5.resolve(process.env.TANREI_VOCABULARY_ROOT) : path5.resolve(path5.dirname(fileURLToPath(import.meta.url)), "../../..");
|
|
2914
|
+
var TOKENS_DIR = path5.join(REPO_ROOT, "tokens");
|
|
2915
|
+
var NS = CONFIG.namespace;
|
|
2916
|
+
var MEMORY = new URL("file:///tanrei-bundle-in-memory/");
|
|
2917
|
+
function componentDeclarations(bundleDir, systemId, read = (name) => JSON.parse(fs4.readFileSync(path5.join(bundleDir, name), "utf8"))) {
|
|
2918
|
+
const resolver = read(`${systemId}.resolver.json`);
|
|
2919
|
+
const out = {};
|
|
2920
|
+
for (const { $ref } of resolver.sets.comp?.sources ?? []) {
|
|
2921
|
+
const components = read($ref)[NS]?.comp ?? {};
|
|
2922
|
+
for (const [name, group] of Object.entries(components)) {
|
|
2923
|
+
const axes = group.$extensions?.["dev.tanrei.axes"];
|
|
2924
|
+
if (axes) out[name] = { axes, states: group.$extensions["dev.tanrei.states"] };
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
return out;
|
|
2928
|
+
}
|
|
2929
|
+
var linted = /* @__PURE__ */ new Set();
|
|
2930
|
+
var LINTED_AT_MOST = 2e5;
|
|
2931
|
+
async function lintValues(tokens) {
|
|
2932
|
+
const written = (id) => tokens[id].aliasOf ? written(tokens[id].aliasOf) : inlined(tokens[id].originalValue.$value, tokens[id].partialAliasOf);
|
|
2933
|
+
const inlined = (value, partial) => {
|
|
2934
|
+
if (typeof partial === "string") return written(partial);
|
|
2935
|
+
if (!partial || value === null || typeof value !== "object") return value;
|
|
2936
|
+
if (Array.isArray(partial) && !Array.isArray(value)) return inlined(value, partial[0]);
|
|
2937
|
+
const out = Array.isArray(value) ? [...value] : { ...value };
|
|
2938
|
+
for (const key of Object.keys(partial)) out[key] = inlined(value[key], partial[key]);
|
|
2939
|
+
return out;
|
|
2940
|
+
};
|
|
2941
|
+
const lines = ["{"];
|
|
2942
|
+
const at = [null];
|
|
2943
|
+
const seen = /* @__PURE__ */ new Map();
|
|
2944
|
+
for (const token of Object.values(tokens)) {
|
|
2945
|
+
if (token.aliasOf) continue;
|
|
2946
|
+
const text2 = JSON.stringify({ $type: token.$type, $value: inlined(token.originalValue.$value, token.partialAliasOf) });
|
|
2947
|
+
if (linted.has(text2) || seen.has(text2)) continue;
|
|
2948
|
+
seen.set(text2, token.id);
|
|
2949
|
+
}
|
|
2950
|
+
if (!seen.size) return;
|
|
2951
|
+
[...seen].forEach(([text2, id], i) => {
|
|
2952
|
+
lines.push(`"v${i}": ${text2}${i === seen.size - 1 ? "" : ","}`);
|
|
2953
|
+
at.push(id);
|
|
2954
|
+
});
|
|
2955
|
+
lines.push("}");
|
|
2956
|
+
const { Logger, defineConfig, parse } = await import("@terrazzo/parser");
|
|
2957
|
+
class Problems extends Logger {
|
|
2958
|
+
error(...entries) {
|
|
2959
|
+
const said = entries.filter((entry) => !(entry.group === "lint" && entry.label === "lint"));
|
|
2960
|
+
throw new TokenReadError(said.map((entry) => `${at[entry.node?.loc?.start?.line - 1] ?? "a value"}: ${entry.message}${entry.group === "lint" ? ` (${entry.label})` : ""}`).join("\n"));
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
const filename = new URL("values.tokens.json", MEMORY);
|
|
2964
|
+
await parse([{ filename, src: lines.join("\n") }], { config: defineConfig({}, { cwd: MEMORY }), logger: new Problems({ level: "error" }) });
|
|
2965
|
+
if (linted.size + seen.size > LINTED_AT_MOST) linted.clear();
|
|
2966
|
+
for (const text2 of seen.keys()) linted.add(text2);
|
|
2967
|
+
}
|
|
2968
|
+
var segments = (id) => id.split(".").slice(1);
|
|
2969
|
+
function simplify(token, paths) {
|
|
2970
|
+
let tokenPath = paths?.get(token.id);
|
|
2971
|
+
if (!tokenPath) paths?.set(token.id, tokenPath = segments(token.id));
|
|
2972
|
+
return simplified(token, tokenPath ?? segments(token.id));
|
|
2973
|
+
}
|
|
2974
|
+
function simplified(token, tokenPath) {
|
|
2975
|
+
return {
|
|
2976
|
+
id: token.id,
|
|
2977
|
+
path: tokenPath,
|
|
2978
|
+
// `tanrei` for the vocabulary (core and extensions inside its tree); a layer's id for its own tokens.
|
|
2979
|
+
namespace: token.id.split(".")[0],
|
|
2980
|
+
// Set on extensions: { rationale, declaredBy, extension: true, onRole? }.
|
|
2981
|
+
vocabulary: token.$extensions?.["dev.tanrei.vocabulary"],
|
|
2982
|
+
type: token.$type,
|
|
2983
|
+
value: token.$value,
|
|
2984
|
+
description: token.$description,
|
|
2985
|
+
// Direct alias target (one hop), so emitters can keep the ref → sys → comp chain visible.
|
|
2986
|
+
alias: token.aliasChain?.[0],
|
|
2987
|
+
// The end of the alias chain (a comp token may alias another comp token that aliases a sys token).
|
|
2988
|
+
aliasFinal: token.aliasOf,
|
|
2989
|
+
partialAlias: token.partialAliasOf,
|
|
2990
|
+
// How the value is decided when it is not an alias: a rule, or { fixed: reason }.
|
|
2991
|
+
derive: token.$extensions?.["dev.tanrei.derive"],
|
|
2992
|
+
// Set on generated per-state component tokens: 'hovered' | 'focused' | 'pressed' | 'disabled'.
|
|
2993
|
+
state: token.$extensions?.["dev.tanrei.state"],
|
|
2994
|
+
// Set on a choice of kind: { values: [...] }; the value is an index into it.
|
|
2995
|
+
enum: token.$extensions?.["dev.tanrei.enum"],
|
|
2996
|
+
// Set on a dial a padding measures from (the control height): its core default, { value, unit }.
|
|
2997
|
+
reference: token.$extensions?.["dev.tanrei.reference"],
|
|
2998
|
+
// Set on an inner corner: { outer: "{id}", inset: "{id}" }, the corner it stands in and how far inside it.
|
|
2999
|
+
concentric: token.$extensions?.["dev.tanrei.concentric"]
|
|
3000
|
+
};
|
|
3001
|
+
}
|
|
3002
|
+
var floors;
|
|
3003
|
+
function coreTargetFloors() {
|
|
3004
|
+
return floors ??= targetFloors(coreComponentDocuments());
|
|
3005
|
+
}
|
|
3006
|
+
var ladder;
|
|
3007
|
+
function coreLadderReaders() {
|
|
3008
|
+
return ladder ??= ladderReaders(coreComponentDocuments());
|
|
3009
|
+
}
|
|
3010
|
+
var aligned;
|
|
3011
|
+
function coreAlignedTokens() {
|
|
3012
|
+
return aligned ??= alignedTokens(coreComponentDocuments());
|
|
3013
|
+
}
|
|
3014
|
+
var own;
|
|
3015
|
+
function coreOwnHeights() {
|
|
3016
|
+
return own ??= ownHeights(coreComponentDocuments());
|
|
3017
|
+
}
|
|
3018
|
+
var componentDocuments;
|
|
3019
|
+
function coreComponentDocuments() {
|
|
3020
|
+
if (componentDocuments) return componentDocuments;
|
|
3021
|
+
const documents = [];
|
|
3022
|
+
const read = (dir) => {
|
|
3023
|
+
if (!fs4.existsSync(dir)) return;
|
|
3024
|
+
for (const name of fs4.readdirSync(dir)) if (name.endsWith(".tokens.json")) documents.push(JSON.parse(fs4.readFileSync(path5.join(dir, name), "utf8")));
|
|
3025
|
+
};
|
|
3026
|
+
read(path5.join(TOKENS_DIR, "comp"));
|
|
3027
|
+
const systems = path5.join(TOKENS_DIR, "systems");
|
|
3028
|
+
if (fs4.existsSync(systems)) {
|
|
3029
|
+
for (const entry of fs4.readdirSync(systems, { withFileTypes: true })) if (entry.isDirectory()) read(path5.join(systems, entry.name, "comp"));
|
|
3030
|
+
}
|
|
3031
|
+
return componentDocuments = documents;
|
|
3032
|
+
}
|
|
3033
|
+
var SYS_COLOR = `${NS}.sys.color.`;
|
|
3034
|
+
var COMP = `${NS}.comp.`;
|
|
3035
|
+
var WHOLE_ALIAS = /^\{[^{}]+\}$/;
|
|
3036
|
+
function simplifyAll(set, paths) {
|
|
3037
|
+
const tokens = {};
|
|
3038
|
+
for (const [id, token] of Object.entries(set)) tokens[id] = simplify(token, paths);
|
|
3039
|
+
for (const token of Object.values(tokens)) {
|
|
3040
|
+
if (typeof token.value === "string" && WHOLE_ALIAS.test(token.value) && token.aliasFinal && tokens[token.aliasFinal]) token.value = tokens[token.aliasFinal].value;
|
|
3041
|
+
}
|
|
3042
|
+
return tokens;
|
|
3043
|
+
}
|
|
3044
|
+
function assertEveryRole(colors) {
|
|
3045
|
+
const roles = Object.keys(colors.light);
|
|
3046
|
+
for (const scheme of SCHEMES) {
|
|
3047
|
+
const missing = roles.filter((r) => !(r in colors[scheme]));
|
|
3048
|
+
if (missing.length) throw new Error(`Scheme "${scheme}" is missing color roles: ${missing.join(", ")}`);
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
function partialModel(base, systemId, components, colors, otherSchemes = {}) {
|
|
3052
|
+
const tokens = simplifyAll(base);
|
|
3053
|
+
const light = Object.fromEntries(Object.entries(tokens).filter(([id, t]) => id.startsWith(COMP) && t.type === "color"));
|
|
3054
|
+
return { system: systemId, schemes: SCHEMES, tokens, colors, componentColors: { ...otherSchemes, light }, components, partial: true, floored: coreTargetFloors(), ladder: coreLadderReaders(), aligned: coreAlignedTokens(), own: coreOwnHeights() };
|
|
3055
|
+
}
|
|
3056
|
+
async function schemeColors(reader) {
|
|
3057
|
+
const colors = {};
|
|
3058
|
+
const componentColors = {};
|
|
3059
|
+
const held2 = COMPONENTS_HELD_IN_EVERY_SCHEME.map((component) => `${COMP}${component}.`);
|
|
3060
|
+
for (const scheme of SCHEMES) {
|
|
3061
|
+
colors[scheme] = {};
|
|
3062
|
+
componentColors[scheme] = {};
|
|
3063
|
+
for (const [id, token] of Object.entries(reader.apply({ scheme }))) {
|
|
3064
|
+
if (id.startsWith(SYS_COLOR)) colors[scheme][id.slice(SYS_COLOR.length)] = simplify(token);
|
|
3065
|
+
else if (token.$type === "color" && held2.some((prefix) => id.startsWith(prefix))) componentColors[scheme][id] = simplify(token);
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
assertEveryRole(colors);
|
|
3069
|
+
return { colors, componentColors };
|
|
3070
|
+
}
|
|
3071
|
+
async function invariantModel(files, systemId, light, reader) {
|
|
3072
|
+
const { colors, componentColors } = await schemeColors(reader);
|
|
3073
|
+
return partialModel(light, systemId, componentDeclarations(null, systemId, (name) => files[name]), colors, componentColors);
|
|
3074
|
+
}
|
|
3075
|
+
|
|
3076
|
+
// ../tokens-build/src/resolve.js
|
|
3077
|
+
import crypto2 from "node:crypto";
|
|
3078
|
+
import fs5 from "node:fs";
|
|
3079
|
+
import path6 from "node:path";
|
|
3080
|
+
var LAYER_SUFFIX = ".system.json";
|
|
3081
|
+
var systemIdOf = (file) => path6.basename(file, LAYER_SUFFIX);
|
|
3082
|
+
function localLayerFile(dir, id) {
|
|
3083
|
+
assertSystemId(id);
|
|
3084
|
+
const file = path6.join(dir, `${id}${LAYER_SUFFIX}`);
|
|
3085
|
+
if (!fs5.lstatSync(file, { throwIfNoEntry: false })) return null;
|
|
3086
|
+
const name = `${id}${LAYER_SUFFIX}`;
|
|
3087
|
+
let real;
|
|
3088
|
+
try {
|
|
3089
|
+
real = fs5.realpathSync(file);
|
|
3090
|
+
} catch {
|
|
3091
|
+
throw new Error(`${name}: a link that leads nowhere. A parent layer is a regular file in ${dir}`);
|
|
3092
|
+
}
|
|
3093
|
+
const root2 = fs5.realpathSync(dir);
|
|
3094
|
+
if (!real.startsWith(root2 + path6.sep)) throw new Error(`${name}: a link that leaves ${dir}. A parent layer is read only from inside the directory of the product's layers`);
|
|
3095
|
+
if (!fs5.statSync(real).isFile()) throw new Error(`${name}: not a regular file`);
|
|
3096
|
+
return file;
|
|
3097
|
+
}
|
|
3098
|
+
function readSystemChain({ system, layerFile, layers, dir } = {}) {
|
|
3099
|
+
const given = [system !== void 0, layerFile !== void 0, layers !== void 0].filter(Boolean).length;
|
|
3100
|
+
if (given !== 1) throw new Error('name the system with exactly one of "system" (a shipped id), "layerFile" (a path) or "layers" (layer objects, the last one being the system)');
|
|
3101
|
+
if (layers && (!Array.isArray(layers) || !layers.length || layers.some((l) => !l || typeof l !== "object" || typeof l.id !== "string" || !l.id))) throw new Error('"layers" is a non-empty list of layer objects, each with an "id"');
|
|
3102
|
+
const inline = new Map((layers ?? []).map((layer) => [layer.id, layer]));
|
|
3103
|
+
if (inline.size !== (layers ?? []).length) throw new Error(`"layers" names the same id twice (${(layers ?? []).map((l) => l.id).join(", ")})`);
|
|
3104
|
+
const local = dir ?? (layerFile ? path6.dirname(path6.resolve(layerFile)) : null);
|
|
3105
|
+
const shipped = new Set(listSystems(REPO_ROOT));
|
|
3106
|
+
const id = system ?? (layerFile ? systemIdOf(layerFile) : layers.at(-1).id);
|
|
3107
|
+
const origin = /* @__PURE__ */ new Map();
|
|
3108
|
+
const read = (wanted) => {
|
|
3109
|
+
if (inline.has(wanted)) return origin.set(wanted, null), inline.get(wanted);
|
|
3110
|
+
const own2 = layerFile && wanted === id ? path6.resolve(layerFile) : null;
|
|
3111
|
+
const file = system !== void 0 ? null : own2 ? fs5.existsSync(own2) ? own2 : null : local ? localLayerFile(local, wanted) : null;
|
|
3112
|
+
if (file) return origin.set(wanted, file), JSON.parse(fs5.readFileSync(file, "utf8"));
|
|
3113
|
+
if (shipped.has(wanted)) return origin.set(wanted, path6.join(REPO_ROOT, systemPath(wanted))), loadSystem(REPO_ROOT, wanted);
|
|
3114
|
+
const where = [...inline.size ? ["not among the layers passed"] : [], ...local ? [`no ${wanted}${LAYER_SUFFIX} in ${layerFile ? `the directory of ${path6.basename(layerFile)}` : local}`] : []];
|
|
3115
|
+
throw new Error(`system "${wanted}" not found: ${[...where, `not a shipped system (${[...shipped].join(", ")})`].join(", ")}`);
|
|
3116
|
+
};
|
|
3117
|
+
const wantedIds = [];
|
|
3118
|
+
const chain = layerChain(id, (wanted) => (wantedIds.unshift(wanted), read(wanted)));
|
|
3119
|
+
return { id, chain, sources: wantedIds.map((wanted) => origin.get(wanted)), fileIds: wantedIds };
|
|
3120
|
+
}
|
|
3121
|
+
function validateSystem(input) {
|
|
3122
|
+
if (input.layerFile !== void 0 && !input.layerFile.endsWith(LAYER_SUFFIX)) return [`${input.layerFile}: a layer file is named <id>${LAYER_SUFFIX}`];
|
|
3123
|
+
const { id, chain, fileIds } = readSystemChain(input);
|
|
3124
|
+
if (input.system === void 0 && id === ROOT_SYSTEM) return [`"${ROOT_SYSTEM}" is the root system; a product layer needs its own id and "extends"`];
|
|
3125
|
+
const problems = [];
|
|
3126
|
+
if (chain.at(-1).id !== id) problems.push(`${id}${LAYER_SUFFIX}: "id" must equal the file name`);
|
|
3127
|
+
chain.forEach((layer, i) => problems.push(...validateLayerFile(REPO_ROOT, layer, fileIds[i])));
|
|
3128
|
+
const outside = outsideComponents(chain, heldComponents(listSystems(REPO_ROOT), (shipped) => loadSystem(REPO_ROOT, shipped)));
|
|
3129
|
+
chain.forEach((layer, i) => {
|
|
3130
|
+
for (const name of (layer.components?.include ?? []).filter((include) => typeof include === "string" && outside[include])) {
|
|
3131
|
+
problems.push(`${fileIds[i] ?? layer.id}${LAYER_SUFFIX} components.include: "${name}" lives in the layer "${outside[name]}", which this system does not extend \u2014 include it from there: { "name": "${name}", "from": "${outside[name]}" }`);
|
|
3132
|
+
}
|
|
3133
|
+
});
|
|
3134
|
+
return [...new Set(problems)];
|
|
3135
|
+
}
|
|
3136
|
+
var chainDigest = (chain) => crypto2.createHash("sha256").update(JSON.stringify(chain)).digest("hex").slice(0, 32);
|
|
3137
|
+
async function resolveChainByScheme(chain) {
|
|
3138
|
+
const id = chain.at(-1).id;
|
|
3139
|
+
const { system, files } = buildBundle(REPO_ROOT, chain);
|
|
3140
|
+
const reader = readBundle(files, id);
|
|
3141
|
+
const loaded = /* @__PURE__ */ new Set();
|
|
3142
|
+
const load2 = async (scheme) => {
|
|
3143
|
+
const tokens = reader.tokens(scheme);
|
|
3144
|
+
loaded.add(scheme);
|
|
3145
|
+
return tokens;
|
|
3146
|
+
};
|
|
3147
|
+
await lintValues(await load2("light"));
|
|
3148
|
+
let warnings;
|
|
3149
|
+
return {
|
|
3150
|
+
id,
|
|
3151
|
+
chain,
|
|
3152
|
+
digest: chainDigest(chain),
|
|
3153
|
+
system,
|
|
3154
|
+
files,
|
|
3155
|
+
tokens(scheme = "light") {
|
|
3156
|
+
if (!loaded.has(scheme)) throw new Error(`scheme "${scheme}" is not loaded yet: await load("${scheme}") first`);
|
|
3157
|
+
return reader.tokens(scheme);
|
|
3158
|
+
},
|
|
3159
|
+
load: load2,
|
|
3160
|
+
// From the light tokens and the role colors of every scheme: the model's warnings without the model's component colors.
|
|
3161
|
+
warnings: () => warnings ??= invariantModel(files, id, reader.tokens("light"), reader).then(checkInvariants)
|
|
3162
|
+
};
|
|
3163
|
+
}
|
|
3164
|
+
|
|
3165
|
+
// src/systems.js
|
|
3166
|
+
var NS2 = CONFIG.namespace;
|
|
3167
|
+
var VOCABULARY2 = "dev.tanrei.vocabulary";
|
|
3168
|
+
var LLM2 = "dev.tanrei.llm";
|
|
3169
|
+
var DERIVE2 = "dev.tanrei.derive";
|
|
3170
|
+
var STATE = "dev.tanrei.state";
|
|
3171
|
+
var RECIPE2 = "dev.tanrei.system";
|
|
3172
|
+
var SYS_COLOR2 = `${NS2}.sys.color.`;
|
|
3173
|
+
var SEGMENT = /^[a-z0-9][a-z0-9-]*$/;
|
|
3174
|
+
var isPlaceholder = (text2) => typeof text2 === "string" && /^\s*<[^>]*>\s*$/.test(text2);
|
|
3175
|
+
var clone4 = (value) => JSON.parse(JSON.stringify(value));
|
|
3176
|
+
var collectVocabulary2 = (layers, chain = layers) => collectVocabulary(layers, { namespace: NS2, lend: (id) => chain.find((layer) => layer.id === id) ?? (listSystems(REPO_ROOT).includes(id) ? loadSystem(REPO_ROOT, id) : void 0) });
|
|
3177
|
+
var LAYER_SUFFIX2 = ".system.json";
|
|
3178
|
+
var ToolError = class extends Error {
|
|
3179
|
+
constructor(message, details) {
|
|
3180
|
+
super(message);
|
|
3181
|
+
this.details = details;
|
|
3182
|
+
}
|
|
3183
|
+
};
|
|
3184
|
+
var shippedSystems2 = () => listSystems(REPO_ROOT);
|
|
3185
|
+
var listedSystems = () => shippedSystems(REPO_ROOT);
|
|
3186
|
+
var shippedLayer = (id) => loadSystem(REPO_ROOT, id);
|
|
3187
|
+
var isRef5 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
3188
|
+
function matchSegments(pattern, id) {
|
|
3189
|
+
const p = pattern.split(".");
|
|
3190
|
+
const s = id.split(".");
|
|
3191
|
+
return p.length === s.length && p.every((part, i) => part === "*" || part === s[i]);
|
|
3192
|
+
}
|
|
3193
|
+
function describeReference({ system, layerFile, layer, parents, dir } = {}) {
|
|
3194
|
+
if (layer) {
|
|
3195
|
+
if (parents !== void 0 && (!Array.isArray(parents) || parents.some((p) => !p || typeof p !== "object" || typeof p.id !== "string"))) throw new ToolError('"parents" is a list of layer objects, each with an "id": the layers that exist only in this request and that "layer" (or another parent) extends.');
|
|
3196
|
+
if (dir !== void 0 && (typeof dir !== "string" || !fs6.existsSync(path7.resolve(dir)))) throw new ToolError(`${dir}: no such directory. "dir" is where the product's other <id>${LAYER_SUFFIX2} files live.`);
|
|
3197
|
+
return { kind: "inline", layer, parents: parents ?? [], dir: dir === void 0 ? void 0 : path7.resolve(dir) };
|
|
3198
|
+
}
|
|
3199
|
+
if (!layerFile && typeof system === "string" && system.endsWith(LAYER_SUFFIX2)) layerFile = system;
|
|
3200
|
+
if (layerFile) {
|
|
3201
|
+
const file = path7.resolve(layerFile);
|
|
3202
|
+
if (!file.endsWith(LAYER_SUFFIX2)) throw new ToolError(`${layerFile}: a layer file is named <id>${LAYER_SUFFIX2}`);
|
|
3203
|
+
if (!fs6.existsSync(file)) throw new ToolError(`${layerFile}: no such file. Pass an absolute path, or one relative to the server's working directory (${process.cwd()}).`);
|
|
3204
|
+
return { kind: "file", file };
|
|
3205
|
+
}
|
|
3206
|
+
const id = system ?? DEFAULT_SYSTEM;
|
|
3207
|
+
if (!shippedSystems2().includes(id)) throw new ToolError(`"${id}" is not a shipped system. Shipped: ${shippedSystems2().join(", ")}. For a product's own system pass "layerFile": the path of its <id>${LAYER_SUFFIX2}.`);
|
|
3208
|
+
return { kind: "shipped", id };
|
|
3209
|
+
}
|
|
3210
|
+
function readChain(reference) {
|
|
3211
|
+
const input = reference.kind === "shipped" ? { system: reference.id } : reference.kind === "file" ? { layerFile: reference.file } : { layers: [...reference.parents.filter((p) => p.id !== reference.layer.id), reference.layer], dir: reference.dir };
|
|
3212
|
+
const { id, chain, sources: sources2 } = readSystemChain(input);
|
|
3213
|
+
return { id, chain, sources: sources2, input };
|
|
3214
|
+
}
|
|
3215
|
+
function readLayers(input) {
|
|
3216
|
+
const reference = describeReference(input);
|
|
3217
|
+
try {
|
|
3218
|
+
return { reference, ...readChain(reference) };
|
|
3219
|
+
} catch (error) {
|
|
3220
|
+
throw new ToolError(error.message);
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
var declaredExtensions = (chain) => listExtensions({ vocabulary: collectVocabulary2(chain) });
|
|
3224
|
+
function componentsOf(files) {
|
|
3225
|
+
const out = {};
|
|
3226
|
+
for (const [name, doc] of Object.entries(files)) {
|
|
3227
|
+
if (!name.startsWith("comp/")) continue;
|
|
3228
|
+
for (const [component, group] of Object.entries(doc[NS2]?.comp ?? {})) {
|
|
3229
|
+
const axes = group?.$extensions?.[AXES];
|
|
3230
|
+
if (!axes) continue;
|
|
3231
|
+
const states = group.$extensions[STATES];
|
|
3232
|
+
out[component] = {
|
|
3233
|
+
id: `${NS2}.comp.${component}`,
|
|
3234
|
+
states: states?.states ?? [],
|
|
3235
|
+
axes: Object.fromEntries(Object.entries(axes).map(([axis, decl]) => [axis, { default: decl.default, values: decl.from === "states" ? states?.variants ?? [] : decl.values, members: decl.from === "states" ? null : decl.members }]))
|
|
3236
|
+
};
|
|
3237
|
+
}
|
|
3238
|
+
}
|
|
3239
|
+
return out;
|
|
3240
|
+
}
|
|
3241
|
+
function componentNamesOf(files) {
|
|
3242
|
+
return Object.entries(files).filter(([name]) => name.startsWith("comp/")).flatMap(([, doc]) => Object.keys(doc[NS2]?.comp ?? {}).filter((key) => !key.startsWith("$")));
|
|
3243
|
+
}
|
|
3244
|
+
function axisOf(components, id) {
|
|
3245
|
+
for (const component of Object.values(components)) {
|
|
3246
|
+
if (!id.startsWith(`${component.id}.`)) continue;
|
|
3247
|
+
const rest = id.slice(component.id.length + 1);
|
|
3248
|
+
for (const [axis, { values, members }] of Object.entries(component.axes)) {
|
|
3249
|
+
if (!members) continue;
|
|
3250
|
+
for (const member of members) for (const key of values) if (rest === `${member}.${key}`) return { id: `${component.id}.${axis}`, key, values };
|
|
3251
|
+
}
|
|
3252
|
+
for (const [axis, { values, members }] of Object.entries(component.axes)) {
|
|
3253
|
+
const key = rest.split(".")[0];
|
|
3254
|
+
if (!members && rest.includes(".") && values.includes(key)) return { id: `${component.id}.${axis}`, key, values };
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
return null;
|
|
3258
|
+
}
|
|
3259
|
+
function collectMetadata(files) {
|
|
3260
|
+
const meta = /* @__PURE__ */ new Map();
|
|
3261
|
+
const visit = (node, trail, inherited) => {
|
|
3262
|
+
const ext = node.$extensions ?? {};
|
|
3263
|
+
const id = trail.join(".");
|
|
3264
|
+
const here = {
|
|
3265
|
+
vocabulary: ext[VOCABULARY2] ? { ...ext[VOCABULARY2], from: id } : inherited.vocabulary,
|
|
3266
|
+
llm: ext[LLM2] ? [...inherited.llm, { from: id, guidance: ext[LLM2] }] : inherited.llm
|
|
3267
|
+
};
|
|
3268
|
+
if ("$value" in node) return void meta.set(id, here);
|
|
3269
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object") visit(child, [...trail, key], here);
|
|
3270
|
+
};
|
|
3271
|
+
for (const [name, doc] of Object.entries(files)) {
|
|
3272
|
+
if (name.endsWith(".resolver.json")) continue;
|
|
3273
|
+
if (/^generated\/(sys\.color|comp\.states)\./.test(name) && !name.includes(".light.tokens")) continue;
|
|
3274
|
+
visit(doc, [], { vocabulary: void 0, llm: [] });
|
|
3275
|
+
}
|
|
3276
|
+
return meta;
|
|
3277
|
+
}
|
|
3278
|
+
var cache = /* @__PURE__ */ new Map();
|
|
3279
|
+
var CACHE_LIMIT = 6;
|
|
3280
|
+
function cached(id, chain) {
|
|
3281
|
+
const key = `${chainDigest(chain)}:${vocabularyDigest(REPO_ROOT)}`;
|
|
3282
|
+
const hit = cache.get(key);
|
|
3283
|
+
if (hit) {
|
|
3284
|
+
cache.delete(key);
|
|
3285
|
+
cache.set(key, hit);
|
|
3286
|
+
return hit;
|
|
3287
|
+
}
|
|
3288
|
+
const promise = assemble(id, chain).catch((error) => {
|
|
3289
|
+
if (cache.get(key) === promise) cache.delete(key);
|
|
3290
|
+
throw error;
|
|
3291
|
+
});
|
|
3292
|
+
cache.set(key, promise);
|
|
3293
|
+
while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
|
|
3294
|
+
return promise;
|
|
3295
|
+
}
|
|
3296
|
+
function loadContext(input, { scheme = "light" } = {}) {
|
|
3297
|
+
const reference = describeReference(input);
|
|
3298
|
+
let read;
|
|
3299
|
+
try {
|
|
3300
|
+
read = readChain(reference);
|
|
3301
|
+
} catch (error) {
|
|
3302
|
+
throw new ToolError(error.message);
|
|
3303
|
+
}
|
|
3304
|
+
const problems = layerProblems(reference, read);
|
|
3305
|
+
if (problems.length) return Promise.reject(new ToolError(`"${read.id}" is not a valid layer, so it has no values yet. Fix these first (validate_layer reports the same list):`, { problems }));
|
|
3306
|
+
return withScheme(cached(read.id, read.chain), scheme);
|
|
3307
|
+
}
|
|
3308
|
+
async function withScheme(context, scheme) {
|
|
3309
|
+
const ctx = await context;
|
|
3310
|
+
if (scheme !== "light") {
|
|
3311
|
+
try {
|
|
3312
|
+
await ctx.load(scheme);
|
|
3313
|
+
} catch (error) {
|
|
3314
|
+
throw new ToolError(`"${ctx.id}" cannot be built: ${error.message}`);
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
return ctx;
|
|
3318
|
+
}
|
|
3319
|
+
function readValidLayers(input) {
|
|
3320
|
+
const reference = describeReference(input);
|
|
3321
|
+
let read;
|
|
3322
|
+
try {
|
|
3323
|
+
read = readChain(reference);
|
|
3324
|
+
} catch (error) {
|
|
3325
|
+
throw new ToolError(error.message);
|
|
3326
|
+
}
|
|
3327
|
+
const problems = layerProblems(reference, read);
|
|
3328
|
+
if (problems.length) throw new ToolError(`"${read.id}" is not a valid layer. Fix these first (validate_layer reports the same list):`, { problems });
|
|
3329
|
+
return { reference, id: read.id, chain: read.chain };
|
|
3330
|
+
}
|
|
3331
|
+
function trialBuild(chain) {
|
|
3332
|
+
const layer = chain.at(-1);
|
|
3333
|
+
const problems = tidySchemaProblems(validateLayerFile(REPO_ROOT, layer, layer.id), [layer]);
|
|
3334
|
+
if (problems.length) throw new ToolError(`"${layer.id}" is not a valid layer`, { problems });
|
|
3335
|
+
return cached(layer.id, chain);
|
|
3336
|
+
}
|
|
3337
|
+
async function assemble(id, chain) {
|
|
3338
|
+
let resolved;
|
|
3339
|
+
try {
|
|
3340
|
+
resolved = await resolveChainByScheme(chain);
|
|
3341
|
+
} catch (error) {
|
|
3342
|
+
throw new ToolError(`"${id}" cannot be built: ${error.message}`);
|
|
3343
|
+
}
|
|
3344
|
+
const { system, files } = resolved;
|
|
3345
|
+
let dependencies;
|
|
3346
|
+
const extensions = files["dial/dial.tokens.json"].$extensions?.[RECIPE2]?.extensions ?? [];
|
|
3347
|
+
const components = componentsOf(files);
|
|
3348
|
+
return {
|
|
3349
|
+
id,
|
|
3350
|
+
chain,
|
|
3351
|
+
system,
|
|
3352
|
+
files,
|
|
3353
|
+
meta: collectMetadata(files),
|
|
3354
|
+
// What the layers of this system added to the vocabulary, as the bundle itself records it.
|
|
3355
|
+
extensions,
|
|
3356
|
+
components,
|
|
3357
|
+
/** Every component's name, whether it declares an axis or not (`components` holds those that do). */
|
|
3358
|
+
componentNames: componentNamesOf(files),
|
|
3359
|
+
axisOf: (tokenId) => axisOf(components, tokenId),
|
|
3360
|
+
/** { declaredBy, rationale, declaredAs? } when a layer added this token; null for core vocabulary. */
|
|
3361
|
+
extensionOf(token) {
|
|
3362
|
+
const own2 = token.$extensions?.[VOCABULARY2];
|
|
3363
|
+
if (own2?.extension) return { declaredBy: own2.declaredBy, rationale: own2.rationale };
|
|
3364
|
+
const component = extensions.find((e) => e.kind === "component" && token.id.startsWith(`${e.id}.`));
|
|
3365
|
+
if (component) return { declaredBy: component.declaredBy, rationale: component.rationale, declaredAs: component.id };
|
|
3366
|
+
const axis = axisOf(components, token.id);
|
|
3367
|
+
const declaration = axis && extensions.find((e) => e.id === `${axis.id}.${axis.key}`);
|
|
3368
|
+
return declaration ? { declaredBy: declaration.declaredBy, rationale: declaration.rationale, declaredAs: declaration.id } : null;
|
|
3369
|
+
},
|
|
3370
|
+
/** Every token whose value moves when `tokenId` does — through aliases and rules, transitively. Ids are the same in every scheme. */
|
|
3371
|
+
followers(tokenId) {
|
|
3372
|
+
dependencies ??= dependencyIndex(Object.fromEntries(Object.entries(files).filter(([name]) => !name.endsWith(".resolver.json") && (!name.startsWith("generated/") || !/\.(light-|dark)/.test(name)))));
|
|
3373
|
+
return [...dependencies.followers(tokenId)].sort();
|
|
3374
|
+
},
|
|
3375
|
+
tokens: resolved.tokens,
|
|
3376
|
+
load: resolved.load,
|
|
3377
|
+
// Accessibility and structure invariants: constants in @tanrei/tokens-build, the same ones a build reports.
|
|
3378
|
+
// Computed once, on first use, from the light tokens and the role colors of every scheme.
|
|
3379
|
+
warnings: resolved.warnings
|
|
3380
|
+
};
|
|
3381
|
+
}
|
|
3382
|
+
var rootIds;
|
|
3383
|
+
async function coreIds() {
|
|
3384
|
+
rootIds ??= loadContext({ system: ROOT_SYSTEM }).then((ctx) => new Map(Object.entries(ctx.tokens("light")).map(([id, token]) => [id, token.$type])));
|
|
3385
|
+
return rootIds;
|
|
3386
|
+
}
|
|
3387
|
+
var INTENT_ROLES = (name) => [name, `on-${name}`, `${name}-container`, `on-${name}-container`].map((role) => `${SYS_COLOR2}${role}`);
|
|
3388
|
+
function tidySchemaProblems(problems, layers) {
|
|
3389
|
+
const out = [];
|
|
3390
|
+
const told = /* @__PURE__ */ new Set();
|
|
3391
|
+
for (const problem of problems) {
|
|
3392
|
+
const keys = /^(\S+) \/vocabulary (?:must match pattern "(.+)"|property name must be valid)$/.exec(problem);
|
|
3393
|
+
if (keys) {
|
|
3394
|
+
const layer = layers.find((l) => `${l.id}${LAYER_SUFFIX2}` === keys[1]);
|
|
3395
|
+
if (keys[2] && layer) {
|
|
3396
|
+
for (const id of Object.keys(layer.vocabulary ?? {})) if (!new RegExp(keys[2]).test(id)) out.push(`${keys[1]} /vocabulary/${id}: not an id a layer can declare. Declare "${NS2}.sys.\u2026" / "${NS2}.comp.\u2026" (inside Tanrei's tree) or "${layer.id}.sys.\u2026" / "${layer.id}.comp.\u2026" (your own namespace); every segment is lowercase letters, digits and hyphens.`);
|
|
3397
|
+
}
|
|
3398
|
+
if (layer) continue;
|
|
3399
|
+
}
|
|
3400
|
+
const at = /^(\S+) \/vocabulary\/([^/\s]+)(\/\S*)? /.exec(problem);
|
|
3401
|
+
const entry = at && layers.find((l) => `${l.id}${LAYER_SUFFIX2}` === at[1])?.vocabulary?.[at[2]];
|
|
3402
|
+
if (!at || !entry || typeof entry !== "object") {
|
|
3403
|
+
out.push(problem);
|
|
3404
|
+
continue;
|
|
3405
|
+
}
|
|
3406
|
+
const where = `${at[1]} /vocabulary/${at[2]}`;
|
|
3407
|
+
const say = (message) => void (told.has(`${where}${message}`) || (told.add(`${where}${message}`), out.push(`${where}: ${message}`)));
|
|
3408
|
+
if ("from" in entry === "$type" in entry) say('an extension is either a token \u2014 "$type" with a value ("$value" or "derive") \u2014 or a value on a component axis \u2014 "from", an existing value of that axis. It has ' + ("from" in entry ? "both" : "neither") + ".");
|
|
3409
|
+
else if (typeof entry.rationale !== "string" || entry.rationale.length < 8) say('an extension needs a "rationale" (8+ characters): why does this design system or product need it?');
|
|
3410
|
+
else {
|
|
3411
|
+
const branchNoise = "from" in entry ? /required property '\$type'/ : /required property 'from'/;
|
|
3412
|
+
if (!/must match exactly one schema in oneOf/.test(problem) && !branchNoise.test(problem)) out.push(problem);
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
return [...new Set(out)];
|
|
3416
|
+
}
|
|
3417
|
+
function layerProblems(reference, { chain, input }) {
|
|
3418
|
+
const problems = validateSystem(input);
|
|
3419
|
+
return reference.kind === "shipped" ? problems : tidySchemaProblems(problems, chain);
|
|
3420
|
+
}
|
|
3421
|
+
function checkVocabulary(chain, reports) {
|
|
3422
|
+
const problems = [];
|
|
3423
|
+
const failed = [];
|
|
3424
|
+
const fail = (layer, id, message) => {
|
|
3425
|
+
failed.push(id);
|
|
3426
|
+
if (reports(layer)) problems.push(`${layer}: vocabulary: ${message}`);
|
|
3427
|
+
};
|
|
3428
|
+
const accepted = chain.map((layer) => ({ id: layer.id, ...layer.components ? { components: layer.components } : {}, vocabulary: {} }));
|
|
3429
|
+
chain.forEach((layer, i) => {
|
|
3430
|
+
for (const [id, entry] of Object.entries(layer.vocabulary ?? {})) {
|
|
3431
|
+
if (isPlaceholder(entry?.rationale)) {
|
|
3432
|
+
fail(layer.id, id, `${id}: the "rationale" is still the placeholder. Say why this design system or product needs it \u2014 it is shown wherever the token is shown.`);
|
|
3433
|
+
continue;
|
|
3434
|
+
}
|
|
3435
|
+
try {
|
|
3436
|
+
collectVocabulary2([...accepted.slice(0, i), { ...accepted[i], vocabulary: { ...accepted[i].vocabulary, [id]: entry } }].map(({ components, ...rest }) => rest));
|
|
3437
|
+
accepted[i].vocabulary[id] = entry;
|
|
3438
|
+
} catch (error) {
|
|
3439
|
+
fail(layer.id, id, error.message);
|
|
3440
|
+
}
|
|
3441
|
+
}
|
|
3442
|
+
});
|
|
3443
|
+
const docs = clone4({ ...sourceFiles(REPO_ROOT), ...heldDocuments(REPO_ROOT) });
|
|
3444
|
+
const known = /* @__PURE__ */ new Map();
|
|
3445
|
+
let collected = {};
|
|
3446
|
+
try {
|
|
3447
|
+
collected = collectVocabulary2(accepted, chain);
|
|
3448
|
+
} catch (error) {
|
|
3449
|
+
fail(chain.at(-1).id, "components.include", error.message);
|
|
3450
|
+
}
|
|
3451
|
+
const declared = Object.entries(collected).sort(([, a], [, b]) => Number(a.kind === "axis-value") - Number(b.kind === "axis-value"));
|
|
3452
|
+
for (const [id, declaration] of declared) {
|
|
3453
|
+
if (declaration.kind === "token" && id.startsWith(SYS_COLOR2)) known.set(id, "color");
|
|
3454
|
+
try {
|
|
3455
|
+
materializeVocabulary(docs, { vocabulary: { [id]: declaration }, tokens: {} });
|
|
3456
|
+
} catch (error) {
|
|
3457
|
+
fail(declaration.declaredBy, id, error.message);
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
for (const name of Object.keys(docs)) if (isHeldDocument(name)) delete docs[name];
|
|
3461
|
+
for (const doc of Object.values(docs)) for (const { id, type } of walkTokens(doc)) known.set(id, type);
|
|
3462
|
+
for (const { id, type } of expandStateVocabulary(Object.entries(docs).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc))) known.set(id, type);
|
|
3463
|
+
return { problems, failed, known };
|
|
3464
|
+
}
|
|
3465
|
+
function echoesFailure(tokenId, failed) {
|
|
3466
|
+
return failed.some((id) => {
|
|
3467
|
+
if (tokenId === id) return true;
|
|
3468
|
+
const parts = id.split(".");
|
|
3469
|
+
return parts[1] === "comp" && tokenId.startsWith(`${parts.slice(0, 3).join(".")}.`) && tokenId.split(".").includes(parts.at(-1));
|
|
3470
|
+
});
|
|
3471
|
+
}
|
|
3472
|
+
async function philosophyProblems(chain) {
|
|
3473
|
+
const shipped = new Set(shippedSystems2());
|
|
3474
|
+
const reports = (layerId) => !shipped.has(layerId) || layerId === chain.at(-1).id;
|
|
3475
|
+
const vocabulary = checkVocabulary(chain, reports);
|
|
3476
|
+
const known = new Map([...await coreIds(), ...vocabulary.known]);
|
|
3477
|
+
for (const layer of chain) for (const [name, decl] of Object.entries(layer.palettes ?? {})) if (decl?.roles === "intent") for (const id of INTENT_ROLES(name)) known.set(id, "color");
|
|
3478
|
+
const problems = [...vocabulary.problems];
|
|
3479
|
+
for (const layer of chain) {
|
|
3480
|
+
if (!reports(layer.id)) continue;
|
|
3481
|
+
for (const [id, op] of Object.entries(layer.tokens ?? {})) {
|
|
3482
|
+
const at = `${layer.id}: ${id}`;
|
|
3483
|
+
if (!known.has(id)) {
|
|
3484
|
+
if (echoesFailure(id, vocabulary.failed)) continue;
|
|
3485
|
+
problems.push(`${at}: not a token of this system. If a token with this meaning already exists, use it (search_tokens). Otherwise ADD it: declare it under "vocabulary" with a "rationale" \u2014 a step in a series, a value on a component axis, or a token in this layer's own namespace ("${layer.id}.comp.\u2026") \u2014 and propose_extension writes the declaration for you. For a whole color family, declare a palette with "roles": "intent".`);
|
|
3486
|
+
continue;
|
|
3487
|
+
}
|
|
3488
|
+
if (op.$type && op.$type !== known.get(id)) problems.push(`${at}: a layer cannot change $type (${known.get(id)} \u2192 ${op.$type}). Extensions are additive: declare a token of your own instead.`);
|
|
3489
|
+
const pinsLiteral = "$value" in op && !isRef5(op.$value);
|
|
3490
|
+
if (pinsLiteral && id.startsWith(SYS_COLOR2)) problems.push(`${at}: a color role is not pinned to a literal. Give it a rule ({"derive": {"fn": "tone", "palette": \u2026, "tone": {"light": [\u2026], "dark": [\u2026]}}}), alias another role, or change the palette's seed under "palettes".`);
|
|
3491
|
+
else if (pinsLiteral && (typeof op.reason !== "string" || op.reason.length < 8)) problems.push(`${at}: pinning a literal "$value" needs a "reason" (8+ characters): a pinned token stops following the dials, and the next person must know why.`);
|
|
3492
|
+
else if (pinsLiteral && isPlaceholder(op.reason)) problems.push(`${at}: the "reason" is still the placeholder. Say why this value is pinned.`);
|
|
3493
|
+
}
|
|
3494
|
+
for (const [index2, rule] of (layer.rules ?? []).entries()) {
|
|
3495
|
+
const at = `${layer.id}: rules[${index2}] ${rule.match}`;
|
|
3496
|
+
if (![...known.keys()].some((id) => matchSegments(rule.match, id)) && !vocabulary.failed.length) problems.push(`${at}: matches no token. Patterns value the per-state component tokens that exist \u2014 core ones, and those of a variant declared under "vocabulary". Interaction states themselves are not extensible.`);
|
|
3497
|
+
if ("$value" in rule && !isRef5(rule.$value) && (typeof rule.reason !== "string" || rule.reason.length < 8)) problems.push(`${at}: a literal "$value" needs a "reason".`);
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
return problems;
|
|
3501
|
+
}
|
|
3502
|
+
async function validateLayer2(input) {
|
|
3503
|
+
const reference = describeReference(input);
|
|
3504
|
+
if (reference.kind === "shipped") throw new ToolError('validate_layer checks a product layer: pass "layerFile" or "layer". Shipped systems are validated by the Tanrei repository itself.');
|
|
3505
|
+
if (reference.kind === "inline" && (typeof reference.layer.id !== "string" || !reference.layer.id)) return { id: null, chain: [], valid: false, problems: ["/ must have required property 'id'"] };
|
|
3506
|
+
let read;
|
|
3507
|
+
try {
|
|
3508
|
+
read = readChain(reference);
|
|
3509
|
+
} catch (error) {
|
|
3510
|
+
return { id: reference.layer?.id ?? systemIdOf(reference.file), chain: [], valid: false, problems: [error.message] };
|
|
3511
|
+
}
|
|
3512
|
+
const chain = read.chain.map((l) => l.id);
|
|
3513
|
+
const problems = layerProblems(reference, read);
|
|
3514
|
+
if (!problems.length) problems.push(...await philosophyProblems(read.chain));
|
|
3515
|
+
if (problems.length) return { id: read.id, chain, valid: false, problems };
|
|
3516
|
+
try {
|
|
3517
|
+
const ctx = await loadContext(input);
|
|
3518
|
+
const warnings = await ctx.warnings();
|
|
3519
|
+
const refused = warnings.filter(isRefusedEverywhere);
|
|
3520
|
+
if (refused.length) return { id: read.id, chain, valid: false, problems: refused };
|
|
3521
|
+
return { id: read.id, chain, valid: true, problems: [], tokens: Object.keys(ctx.tokens("light")).length, extensions: ctx.extensions.length, warnings };
|
|
3522
|
+
} catch (error) {
|
|
3523
|
+
return { id: read.id, chain, valid: false, problems: [error.message, ...error.details?.problems ?? []] };
|
|
3524
|
+
}
|
|
3525
|
+
}
|
|
3526
|
+
|
|
3527
|
+
// src/components.js
|
|
3528
|
+
var PREFIX2 = `${CONFIG.web.tagPrefix}-`;
|
|
3529
|
+
var readJson = (file) => JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
3530
|
+
var schema = readJson(path8.join(REPO_ROOT, "specs/component.schema.json"));
|
|
3531
|
+
var PLATFORMS = Object.keys(schema.properties.platforms.properties);
|
|
3532
|
+
var STATUSES2 = schema.$defs.platform.properties.status.enum;
|
|
3533
|
+
var LEVELS = schema.properties.level.enum;
|
|
3534
|
+
var LISTINGS = schema.properties.listing.enum;
|
|
3535
|
+
var CATEGORIES = [...new Set(readJson(path8.join(REPO_ROOT, "specs/inventory.json")).components.map((row) => row.category))].sort();
|
|
3536
|
+
var sources;
|
|
3537
|
+
function readSources() {
|
|
3538
|
+
if (sources) return sources;
|
|
3539
|
+
const catalog = readComponentCatalog(REPO_ROOT);
|
|
3540
|
+
if (!catalog) throw new ToolError("The component catalog is missing: run `pnpm generate` in the Tanrei repository.");
|
|
3541
|
+
const inventory = readJson(path8.join(REPO_ROOT, "specs/inventory.json")).components;
|
|
3542
|
+
const written = new Map(catalog.components.map(({ name }) => [name, readJson(path8.join(REPO_ROOT, "specs", `${name}.spec.json`))]));
|
|
3543
|
+
const specs = new Map([...written].map(([name, spec]) => [name, resolveFrom(spec, written)]));
|
|
3544
|
+
const categories = new Map(inventory.map((row) => [row.name, row.category]));
|
|
3545
|
+
sources = { catalog, specs, written, categories };
|
|
3546
|
+
return sources;
|
|
3547
|
+
}
|
|
3548
|
+
var shippedManifests = /* @__PURE__ */ new Map();
|
|
3549
|
+
function shippedManifest(id) {
|
|
3550
|
+
if (!shippedManifests.has(id)) {
|
|
3551
|
+
const file = path8.join(REPO_ROOT, manifestFile(id));
|
|
3552
|
+
if (!fs7.existsSync(file)) throw new ToolError(`No components manifest for "${id}" (${manifestFile(id)}): run \`pnpm generate\` in the Tanrei repository.`);
|
|
3553
|
+
const { $comment, ...manifest } = readJson(file);
|
|
3554
|
+
shippedManifests.set(id, manifest);
|
|
3555
|
+
}
|
|
3556
|
+
return shippedManifests.get(id);
|
|
3557
|
+
}
|
|
3558
|
+
var held;
|
|
3559
|
+
function manifestOf({ system, layerFile } = {}) {
|
|
3560
|
+
if (!layerFile && (system === void 0 || !system.endsWith(".system.json"))) {
|
|
3561
|
+
const id = system ?? DEFAULT_SYSTEM;
|
|
3562
|
+
if (id === ROOT_SYSTEM) throw new ToolError(`"${ROOT_SYSTEM}" is the root layer every system extends; it ships no components of its own. Pick a system: ${listedSystems().join(", ")}, or pass "layerFile" (a product's <id>.system.json).`);
|
|
3563
|
+
if (listedSystems().includes(id)) return { product: false, manifest: shippedManifest(id) };
|
|
3564
|
+
}
|
|
3565
|
+
const { reference, chain } = readValidLayers({ system, layerFile });
|
|
3566
|
+
if (reference.kind === "shipped") return { product: false, manifest: shippedManifest(reference.id) };
|
|
3567
|
+
held ??= heldComponents(listSystems(REPO_ROOT), (id) => loadSystem(REPO_ROOT, id));
|
|
3568
|
+
return { product: true, manifest: componentsManifest(chain, readSources().catalog, held, listedSystems()) };
|
|
3569
|
+
}
|
|
3570
|
+
var shippedAll = () => new Map(listedSystems().map((id) => [id, shippedManifest(id)]));
|
|
3571
|
+
var standInsFor2 = (manifest, name, product) => standInsFor({ manifest, shipped: shippedAll(), product }, name);
|
|
3572
|
+
function componentNamed(name) {
|
|
3573
|
+
const { catalog } = readSources();
|
|
3574
|
+
const { byTag, byReactName } = elementIndex(catalog);
|
|
3575
|
+
if (catalog.components.some((c) => c.name === name)) return name;
|
|
3576
|
+
const at = byTag.get(name) ?? byReactName.get(name);
|
|
3577
|
+
return at ? at.components[0] : null;
|
|
3578
|
+
}
|
|
3579
|
+
var STOP = new Set("a an and are as at be by can do for from has have i in into is it its let lets me my need of on one or our people show so some that the their them this to use user users want we what when where which with without you your".split(" "));
|
|
3580
|
+
function stem(word) {
|
|
3581
|
+
for (const ending of ["ings", "ing", "ers", "er", "ies", "es", "ed", "s"]) if (word.length - ending.length >= 3 && word.endsWith(ending)) return ending === "ies" ? `${word.slice(0, -3)}y` : word.slice(0, -ending.length);
|
|
3582
|
+
return word;
|
|
3583
|
+
}
|
|
3584
|
+
var words = (text2) => (String(text2 ?? "").toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((word) => !STOP.has(word)).map(stem);
|
|
3585
|
+
var clip = (text2, max = 200) => typeof text2 === "string" && text2.length > max ? `${text2.slice(0, max - 1)}\u2026` : text2;
|
|
3586
|
+
function listComponents({ listing, category, level, platform = "web", status, limit = 100, offset = 0, ...reference }) {
|
|
3587
|
+
const { manifest, product } = manifestOf(reference);
|
|
3588
|
+
const { specs, categories } = readSources();
|
|
3589
|
+
const rows = manifest.components.map((entry) => {
|
|
3590
|
+
const spec = specs.get(entry.name);
|
|
3591
|
+
const variant = spec.props?.find((prop) => prop.name === "variant");
|
|
3592
|
+
return {
|
|
3593
|
+
name: entry.name,
|
|
3594
|
+
title: entry.title,
|
|
3595
|
+
category: categories.get(entry.name),
|
|
3596
|
+
level: entry.level,
|
|
3597
|
+
listing: entry.listing,
|
|
3598
|
+
summary: clip(spec.summary, 140),
|
|
3599
|
+
...entry.web ? { web: entry.web } : {},
|
|
3600
|
+
...entry.react ? { react: entry.react } : {},
|
|
3601
|
+
...entry.variants ? { variants: entry.variants, ...variant?.default !== void 0 ? { defaultVariant: variant.default } : {} } : {},
|
|
3602
|
+
status: spec.platforms?.[platform]?.status,
|
|
3603
|
+
...entry.layer !== ROOT_SYSTEM ? { layer: entry.layer } : {}
|
|
3604
|
+
};
|
|
3605
|
+
}).filter((row) => (!listing || row.listing === listing) && (!category || row.category === category) && (!level || row.level === level) && (!status || row.status === status));
|
|
3606
|
+
const slice = rows.slice(offset, offset + limit);
|
|
3607
|
+
return {
|
|
3608
|
+
system: manifest.system,
|
|
3609
|
+
chain: manifest.chain,
|
|
3610
|
+
...product ? { product: true } : {},
|
|
3611
|
+
rule: `Write UI with these components only. Anything this list does not have is not part of "${manifest.system}" \u2014 omitted names it, with what to use instead.`,
|
|
3612
|
+
total: rows.length,
|
|
3613
|
+
offset,
|
|
3614
|
+
limit,
|
|
3615
|
+
nextOffset: offset + slice.length < rows.length ? offset + slice.length : null,
|
|
3616
|
+
components: slice,
|
|
3617
|
+
omitted: manifest.omitted.map(({ name, title }) => ({ name, title, ...standInsFor2(manifest, name, product) })),
|
|
3618
|
+
omittedVariants: manifest.omittedVariants
|
|
3619
|
+
};
|
|
3620
|
+
}
|
|
3621
|
+
var SECTIONS = ["props", "events", "slots", "items", "states", "behavior", "accessibility", "example", "anatomy", "tokens", "platforms", "fixtures"];
|
|
3622
|
+
var DEFAULT_SECTIONS = ["props", "events", "slots", "items", "states", "behavior", "accessibility", "example"];
|
|
3623
|
+
function shownProp(prop, variants) {
|
|
3624
|
+
const { words: _words, ...rest } = prop;
|
|
3625
|
+
if (prop.name !== "variant" || !variants.values) return rest;
|
|
3626
|
+
return { ...rest, values: variants.values, ...variants.omitted.length ? { notInThisSystem: variants.omitted } : {} };
|
|
3627
|
+
}
|
|
3628
|
+
function exampleOf(spec, variants) {
|
|
3629
|
+
const usable = (fixture2) => !variants.values || fixture2.props?.variant === void 0 || variants.values.includes(fixture2.props.variant);
|
|
3630
|
+
const fixture = (spec.fixtures ?? []).find(usable);
|
|
3631
|
+
if (!fixture) return null;
|
|
3632
|
+
const { twin: _twin, ...shown } = fixture;
|
|
3633
|
+
return shown;
|
|
3634
|
+
}
|
|
3635
|
+
function getComponent({ name, sections = DEFAULT_SECTIONS, ...reference }) {
|
|
3636
|
+
const { manifest, product } = manifestOf(reference);
|
|
3637
|
+
const { specs, categories } = readSources();
|
|
3638
|
+
const found = componentNamed(name);
|
|
3639
|
+
if (!found) throw new ToolError(`"${name}" is not a Tanrei component. Pass a component's name ("text-field"), its element ("${PREFIX2}text-field") or its React name ("TextField"); find_component looks one up by what it is for.`, { near: nearestNames(manifest, name, 5) });
|
|
3640
|
+
const spec = specs.get(found);
|
|
3641
|
+
const entry = manifest.components.find((c) => c.name === found);
|
|
3642
|
+
const head = { name: found, title: spec.title, system: manifest.system, category: categories.get(found), level: spec.level, listing: spec.listing, summary: spec.summary };
|
|
3643
|
+
if (!entry) return { ...head, available: false, ...standInsFor2(manifest, found, product) };
|
|
3644
|
+
const variants = variantsOf(manifest, found);
|
|
3645
|
+
const out = { ...head, available: true, ...entry.web ? { web: entry.web } : {}, ...entry.react ? { react: entry.react } : {}, ...spec.builtFrom ? { builtFrom: spec.builtFrom } : {} };
|
|
3646
|
+
const want = new Set(sections);
|
|
3647
|
+
if (want.has("props")) out.props = (spec.props ?? []).map((prop) => shownProp(prop, variants));
|
|
3648
|
+
if (want.has("events") && spec.events) out.events = spec.events;
|
|
3649
|
+
if (want.has("slots") && spec.slots) out.slots = spec.slots;
|
|
3650
|
+
if (want.has("items") && spec.items) out.items = spec.items;
|
|
3651
|
+
if (want.has("states") && spec.states) out.states = spec.states;
|
|
3652
|
+
if (want.has("behavior")) out.behavior = (spec.behavior ?? []).map(({ id, text: text2 }) => ({ id, text: text2 }));
|
|
3653
|
+
if (want.has("accessibility") && spec.accessibility) out.accessibility = spec.accessibility;
|
|
3654
|
+
if (want.has("anatomy") && spec.anatomy) out.anatomy = spec.anatomy;
|
|
3655
|
+
if (want.has("tokens") && spec.tokens) out.tokens = { group: `${CONFIG.namespace}.${spec.tokens}`, find: `search_tokens { "query": "${CONFIG.namespace}.${spec.tokens}.**" }` };
|
|
3656
|
+
if (want.has("platforms")) out.platforms = spec.platforms;
|
|
3657
|
+
if (want.has("example")) {
|
|
3658
|
+
const example = exampleOf(spec, variants);
|
|
3659
|
+
if (example) out.example = { ...example, note: 'One of the fixtures the spec is tested with: the props, slots, content and items to set. "fixtures" lists them all; "platforms" names each prop on each platform.' };
|
|
3660
|
+
}
|
|
3661
|
+
if (want.has("fixtures") && spec.fixtures) out.fixtures = spec.fixtures.map(({ twin: _twin, ...fixture }) => ({ ...fixture, ...variants.values && fixture.props?.variant !== void 0 && !variants.values.includes(fixture.props.variant) ? { notInThisSystem: true } : {} }));
|
|
3662
|
+
return out;
|
|
3663
|
+
}
|
|
3664
|
+
var index;
|
|
3665
|
+
function wordIndex() {
|
|
3666
|
+
if (index) return index;
|
|
3667
|
+
const { specs, categories } = readSources();
|
|
3668
|
+
index = new Map(
|
|
3669
|
+
[...specs].map(([name, spec]) => [
|
|
3670
|
+
name,
|
|
3671
|
+
{
|
|
3672
|
+
name: /* @__PURE__ */ new Set([...words(name.replace(/-/g, " ")), ...words(spec.title)]),
|
|
3673
|
+
summary: /* @__PURE__ */ new Set([...words(spec.summary), ...words(categories.get(name)), ...words(spec.accessibility?.role)]),
|
|
3674
|
+
props: new Set((spec.props ?? []).flatMap((prop) => [...words(prop.name.replace(/([a-z])([A-Z])/g, "$1 $2")), ...words(prop.description)]))
|
|
3675
|
+
}
|
|
3676
|
+
])
|
|
3677
|
+
);
|
|
3678
|
+
return index;
|
|
3679
|
+
}
|
|
3680
|
+
function nearestNames(manifest, name, limit, { availableOnly = false } = {}) {
|
|
3681
|
+
const plain = plainName(name);
|
|
3682
|
+
const spelled = readSources().catalog.components.map((c) => [c.name, distance(plain, c.name)]).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1]).map(([n]) => n);
|
|
3683
|
+
const names = [.../* @__PURE__ */ new Set([...spelled, ...findIn(manifest, plain.replace(/-/g, " "), limit).map((hit) => hit.name)])];
|
|
3684
|
+
return (availableOnly ? names.filter((other) => manifest.components.some((c) => c.name === other)) : names).slice(0, limit);
|
|
3685
|
+
}
|
|
3686
|
+
function findIn(manifest, need, limit) {
|
|
3687
|
+
const asked = [...new Set(words(need))];
|
|
3688
|
+
if (!asked.length) return [];
|
|
3689
|
+
const meets = (set, word) => set.has(word) || word.length >= 4 && [...set].some((other) => other.length >= 4 && (other.startsWith(word) || word.startsWith(other)));
|
|
3690
|
+
const hits = [];
|
|
3691
|
+
for (const [name, fields] of wordIndex()) {
|
|
3692
|
+
let score = 0;
|
|
3693
|
+
const matched = [];
|
|
3694
|
+
for (const word of asked) {
|
|
3695
|
+
const weight = meets(fields.name, word) ? 5 : meets(fields.summary, word) ? 2 : meets(fields.props, word) ? 1 : 0;
|
|
3696
|
+
if (weight) matched.push(word);
|
|
3697
|
+
score += weight;
|
|
3698
|
+
}
|
|
3699
|
+
if (score) hits.push({ name, score, matched, available: manifest.components.some((c) => c.name === name) });
|
|
3700
|
+
}
|
|
3701
|
+
return hits.sort((a, b) => b.score - a.score || b.matched.length - a.matched.length || a.name.localeCompare(b.name)).slice(0, limit);
|
|
3702
|
+
}
|
|
3703
|
+
function findComponent({ need, limit = 5, ...reference }) {
|
|
3704
|
+
const { manifest, product } = manifestOf(reference);
|
|
3705
|
+
const { specs } = readSources();
|
|
3706
|
+
const hits = findIn(manifest, need, 40);
|
|
3707
|
+
const listed = new Map(manifest.components.map((c) => [c.name, c]));
|
|
3708
|
+
const available = hits.filter((hit) => hit.available).slice(0, limit);
|
|
3709
|
+
const elsewhere = hits.filter((hit) => !hit.available && (!available.length || hit.score >= available.at(-1).score));
|
|
3710
|
+
return {
|
|
3711
|
+
system: manifest.system,
|
|
3712
|
+
need,
|
|
3713
|
+
components: available.map(({ name, score, matched }) => ({ ...briefComponent(listed.get(name)), summary: clip(specs.get(name).summary), score, matched })),
|
|
3714
|
+
...elsewhere.length ? { notInThisSystem: elsewhere.map(({ name, score }) => ({ name, title: specs.get(name).title, score, ...standInsFor2(manifest, name, product) })) } : {},
|
|
3715
|
+
...available.length ? { next: "get_component gives the props, events, slots, the EARS rules and an example of one." } : { next: "No component of this system matches these words: try others, or list_components for the whole list." }
|
|
3716
|
+
};
|
|
3717
|
+
}
|
|
3718
|
+
var MAX_FILES = 50;
|
|
3719
|
+
var MAX_BYTES = 1024 * 1024;
|
|
3720
|
+
function checkUsage({ code, files, path: name, ...reference }) {
|
|
3721
|
+
if (code === void 0 === (files === void 0)) throw new ToolError('Pass "code" (the text to check) or "files" (paths of files to read), not both.');
|
|
3722
|
+
const { manifest, product } = manifestOf(reference);
|
|
3723
|
+
const texts = [];
|
|
3724
|
+
if (code !== void 0) texts.push({ file: name, text: code });
|
|
3725
|
+
else {
|
|
3726
|
+
if (files.length > MAX_FILES) throw new ToolError(`At most ${MAX_FILES} files at a time.`);
|
|
3727
|
+
for (const file of files) {
|
|
3728
|
+
const full = path8.resolve(file);
|
|
3729
|
+
let stat;
|
|
3730
|
+
try {
|
|
3731
|
+
stat = fs7.statSync(full);
|
|
3732
|
+
} catch {
|
|
3733
|
+
throw new ToolError(`${file}: no such file. Pass a path absolute, or relative to the server's working directory (${process.cwd()}).`);
|
|
3734
|
+
}
|
|
3735
|
+
if (!stat.isFile()) throw new ToolError(`${file}: not a file.`);
|
|
3736
|
+
if (stat.size > MAX_BYTES) throw new ToolError(`${file}: larger than ${MAX_BYTES / 1024 / 1024} MB.`);
|
|
3737
|
+
texts.push({ file, text: fs7.readFileSync(full, "utf8") });
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
return auditTexts(auditContext(readSources().catalog, manifest, shippedAll(), { product }), texts, { near: (tag) => nearestNames(manifest, tag, 3, { availableOnly: true }) });
|
|
3741
|
+
}
|
|
3742
|
+
var COMPONENTS_URI = /^tanrei:\/\/components\/([a-z0-9-]+)$/;
|
|
3743
|
+
var componentsResource = (id) => listedSystems().includes(id) ? shippedManifest(id) : null;
|
|
3744
|
+
|
|
3745
|
+
// src/resources.js
|
|
3746
|
+
var INSTRUCTIONS = `Tanrei is a small, simply named core vocabulary of design tokens shipped to five platforms, which any design system can reproduce exactly: a design system is a layer file (<id>.system.json) that changes VALUES and, where the core has no word for something, EXTENDS the vocabulary.
|
|
3747
|
+
Components: first call list_components to settle the system, and use no component it does not list (omitted says what to use instead); when asked to rebuild a product with Tanrei, use system=${DEFAULT_SYSTEM}. get_component gives a component's props and its EARS rules; check_usage checks code before it is kept.
|
|
3748
|
+
Hard rules:
|
|
3749
|
+
- Values first. Find the existing token with search_tokens and change it in the layer, in this order of preference: set a dial, "scale" an inherited rule, re-point an alias, replace "derive", and only then pin a literal "$value" \u2014 a pinned literal needs a "reason" (8+ characters). New color families are declared under "palettes" with "roles": "intent". Never edit generated files.
|
|
3750
|
+
- If the word really is missing, add it \u2014 in the layer, under "vocabulary", with a "rationale" (8+ characters): a step in a series, a value on a component axis (a size, a variant), or the layer's own token in its own namespace ("<layer id>.comp.\u2026"). propose_extension writes and verifies the declaration. Additive only: never re-declare, remove or retype what exists (change its value under "tokens"); interaction states are not extensible; nothing in tanrei.* may reference a layer's own token.
|
|
3751
|
+
- Accessibility thresholds are constants, for extensions too. Nothing in a layer changes them; a violation in a product layer is a warning that every build prints. Do not try to silence it \u2014 fix the value or report it.
|
|
3752
|
+
- Call explain_token before editing a token and validate_layer before saving; after editing the layer run \`tanrei build\` (@tanrei/cli) to regenerate every platform.
|
|
3753
|
+
Read tanrei://philosophy once.`;
|
|
3754
|
+
var PHILOSOPHY = `# Tanrei in one page
|
|
3755
|
+
|
|
3756
|
+
Tanrei holds two ideals at once:
|
|
3757
|
+
- **(a) a small core** \u2014 Tanrei's own tokens are a necessary and sufficient set, simply named, fitted to no one design system;
|
|
3758
|
+
- **(b) exact reproduction** \u2014 by customizing Tanrei, any design system can be matched exactly, not approximated.
|
|
3759
|
+
Both hold because **the core stays small and any layer may extend it**. Nothing is added to the core for somebody else's sake.
|
|
3760
|
+
|
|
3761
|
+
## The core: the one-product test
|
|
3762
|
+
A core token exists because ONE product may need the distinction, by meaning or by place (\`focus-ring\` is not \`primary\`:
|
|
3763
|
+
a product may want a saturated brand color and a quiet focus ring). It does not exist because one design system has it,
|
|
3764
|
+
nor because a component uses it today. Core changes happen only in the Tanrei repository (tokens/, lock file, review).
|
|
3765
|
+
|
|
3766
|
+
## Tiers and kinds
|
|
3767
|
+
Four tiers, one reference order: \`dial < ref < sys < comp\`. Components read \`comp\` tokens only. Eight numeric dials sit
|
|
3768
|
+
under everything: type.base 16px, type.contrast 1, space.unit 8px, size.unit 4px, control.height 40px, shape.unit 2px,
|
|
3769
|
+
stroke.unit 1px, motion.unit 50ms. \`control.height\` is the height controls and rows are drawn at in their default size: the ladder sys.control.height.* is whole size units from it (small 32, medium 40, large 56), and a pressable height never goes below \`sys.target.minimum\`, which is no dial (36px, the developer's value). Color seeds are palette declarations, not dials. Every value is one of three kinds:
|
|
3770
|
+
- **derived** \u2014 a rule in a closed language: \`mul\` ({ of, by, exp?, round?, min? } \u2192 max(min, round(of \xD7 by^exp, round)): round a step, ties upward, min a floor after rounding), \`add\` ({ of, by, times?, min? } \u2192 max(min, of + by \xD7 times): a step a number of units from another value), \`scale\`, \`clamp\`, \`sub\` ({ of, by } \u2192 max(0, of \u2212 by): a corner inside another at an inset), \`pad\` ({ of, height, by? } \u2192 max(0, of \xD7 by + (height \u2212 height\u2081) / 2), by being 1 unless a scale multiplies it and height\u2081 being the height with no min: a block padding that gives up or takes half of what its box's height lost or gained), \`em\`; \`tone\`, \`alpha\`, \`contrast-pick\` for color roles; \`mix\`, \`alpha\`, \`tone\`,
|
|
3771
|
+
\`contrast-pick\` ({ on, from: [\u2026] } \u2192 the most readable candidate, per scheme) for per-state component colors. No other arithmetic, conditionals or user functions.
|
|
3772
|
+
- **fixed** \u2014 a literal with a stated reason, exempt from the dials. - **alias** \u2014 a reference that can be re-pointed.
|
|
3773
|
+
|
|
3774
|
+
## A design system is a layer
|
|
3775
|
+
\`<id>.system.json\`: \`id\`, \`extends\` (every chain ends at the root \`core\`; the default system \`tanrei\` extends it), \`vocabulary\`, \`palettes\`, \`tokens\`, \`rules\`.
|
|
3776
|
+
**Values first.** Operations under \`tokens\`, keyed by an existing token id \u2014 prefer the earliest that does the job:
|
|
3777
|
+
1. set a dial \`"tanrei.dial.type.base": { "$value": { "value": 17, "unit": "px" }, "reason": "\u2026" }\`
|
|
3778
|
+
2. scale \`{ "scale": 2 }\` \u2014 N \xD7 the inherited rule or alias, still following its dial
|
|
3779
|
+
3. re-point alias \`{ "$value": "{tanrei.sys.space.space50}" }\`
|
|
3780
|
+
4. replace the rule \`{ "derive": { "fn": "mul", "of": "{tanrei.dial.shape.unit}", "by": 4 } }\`
|
|
3781
|
+
5. pin a literal \`{ "$value": \u2026, "reason": "\u2026" }\` \u2014 stops following dials; the reason is mandatory.
|
|
3782
|
+
\`palettes\`: re-declare a palette (\`{ "source": { "seed": "#rrggbb" } }\`) to recolor every role that reads it; \`"roles": "intent"\`
|
|
3783
|
+
plus a \`description\` gives \`<name>\`, \`on-<name>\`, \`<name>-container\`, \`on-<name>-container\`, contrast-checked; \`null\` drops one.
|
|
3784
|
+
A source may state single tones exactly \u2014 \`"tones": { "40": "#6750a4" }\` (a published ramp, a brand color); the rest are generated.
|
|
3785
|
+
Color roles take \`derive\` (tone / alpha / contrast-pick) or an alias, never a literal. A choice of kind (\`tanrei.sys.behavior.*\`) takes one of its NAMES (\`{ "$value": "ripple", "reason": "\u2026" }\`); a typeface takes a font stack that ends in a system or generic fallback.
|
|
3786
|
+
\`rules\`: pattern rules value per-state component tokens (\`tanrei.comp.*.*.hovered.container.color\`); \`*\` is one segment,
|
|
3787
|
+
available as $1, $2\u2026. An explicit \`tokens\` entry beats a pattern; fewer wildcards win; then the later layer.
|
|
3788
|
+
|
|
3789
|
+
## Extending the vocabulary
|
|
3790
|
+
\`vocabulary\` says that something EXISTS; \`tokens\` and \`rules\` then value it like any core token. Three kinds, one mechanism:
|
|
3791
|
+
1. **a step in a series**, inside Tanrei's tree \u2014 or a single color role with its \`onRole\`:
|
|
3792
|
+
\`"tanrei.sys.space.space1200": { "$type": "dimension", "rationale": "\u2026", "derive": { "fn": "mul", "of": "{tanrei.dial.space.unit}", "by": 12 } }\`
|
|
3793
|
+
2. **a value on a component axis** \u2014 one line values every member; a variant's state tokens come from the pattern rules:
|
|
3794
|
+
\`"tanrei.comp.button.size.3x": { "from": "large", "scale": 1.5, "rationale": "\u2026" }\`, \`"tanrei.comp.button.variant.danger": { "from": "filled", "rationale": "\u2026" }\`
|
|
3795
|
+
3. **the layer's own tokens**, in its own namespace = the layer id: \`"acme.comp.rating.star.size": { "$type": "dimension", \u2026 }\`.
|
|
3796
|
+
They may reference \`tanrei.*\`; nothing in \`tanrei.*\` may reference them. On the web they are \`--acme-\u2026\`.
|
|
3797
|
+
- Every declaration carries a **rationale** (8+ characters) and is attributed to its layer (\`declaredBy\`).
|
|
3798
|
+
- **Additive only**, inherited down \`extends\`. No layer removes or retypes vocabulary; re-declaring what core or an
|
|
3799
|
+
ancestor declared is an error \u2014 change its value under \`tokens\`.
|
|
3800
|
+
- **Interaction states are not extensible**: hovered, focused, pressed, disabled are platform behaviour. How they LOOK is a value.
|
|
3801
|
+
- Traits no token can express are Tanrei defects, listed by mimicry_gaps until a token can express them.
|
|
3802
|
+
|
|
3803
|
+
## Accessibility
|
|
3804
|
+
The ruler never changes, for core and extensions alike: text 4.5:1 (7:1 in high contrast), non-text and focus 3:1, and a
|
|
3805
|
+
control's height must hold its content. \`sys.target.minimum\` (36px; \`sys.target.pointer\` and \`.touch\` alias it, and a layer may set them higher, never lower) and both of those are never under 24px (WCAG 2.5.8), and every pressable height the core floors at the minimum stays at or above it. These are constants in code. In the default system a violation fails the build; in
|
|
3806
|
+
a product layer it is a warning \u2014 printed, written to a11y-report.json, stamped into every generated file. An imitation
|
|
3807
|
+
preset is held to fidelity to its original, not to Tanrei's accessibility criteria, in every contrast scheme: its
|
|
3808
|
+
contrast is reported as measurements, not warnings; a structural or functional failure fails its build, as in the default system. Two findings fail every build, a product layer's too: \`sys.target.pointer\` or \`.touch\` under \`sys.target.minimum\`, and \`sys.target.minimum\` above \`dial.control.height\`.
|
|
3809
|
+
|
|
3810
|
+
## Workflow for a product
|
|
3811
|
+
search_tokens \u2192 explain_token (\`howToChange\`, \`howToExtend\`) \u2192 propose_extension if a word is missing \u2192 edit the layer \u2192
|
|
3812
|
+
validate_layer \u2192 \`tanrei build\` (one layer in; DTCG bundle, CSS, Tailwind/shadcn, SwiftUI, Compose, Flutter, React Native out).
|
|
3813
|
+
`;
|
|
3814
|
+
var SYSTEM_URI = /^tanrei:\/\/systems\/([a-z0-9-]+)$/;
|
|
3815
|
+
function listResources() {
|
|
3816
|
+
return [
|
|
3817
|
+
{ uri: "tanrei://philosophy", name: "Tanrei philosophy", description: "The two ideals (a small core, exact reproduction), tiers and kinds, the operations a layer may perform and the three ways it may extend the vocabulary. Read once before editing a layer.", mimeType: "text/markdown" },
|
|
3818
|
+
{ uri: "tanrei://schema/system", name: "Layer JSON Schema", description: "JSON Schema of a design system layer (<id>.system.json).", mimeType: "application/schema+json" },
|
|
3819
|
+
...shippedSystems2().map((id) => {
|
|
3820
|
+
const layer = shippedLayer(id);
|
|
3821
|
+
return { uri: `tanrei://systems/${id}`, name: `System layer: ${id}`, description: `${layer.name ?? id}${layer.extends ? ` (extends ${layer.extends})` : " (root)"} \u2014 the layer file as authored. A worked example of every operation.`, mimeType: "application/json" };
|
|
3822
|
+
}),
|
|
3823
|
+
...listedSystems().map((id) => ({ uri: `tanrei://components/${id}`, name: `Components: ${id}`, description: `The components manifest of "${id}": every component it ships with the module that registers it, those it does not have with what to use instead, and the variant values it leaves out.`, mimeType: "application/json" }))
|
|
3824
|
+
];
|
|
3825
|
+
}
|
|
3826
|
+
function readResource(uri) {
|
|
3827
|
+
if (uri === "tanrei://philosophy") return { uri, mimeType: "text/markdown", text: PHILOSOPHY };
|
|
3828
|
+
if (uri === "tanrei://schema/system") return { uri, mimeType: "application/schema+json", text: fs8.readFileSync(path9.join(REPO_ROOT, "tokens/schema/system.schema.json"), "utf8") };
|
|
3829
|
+
const id = SYSTEM_URI.exec(uri)?.[1];
|
|
3830
|
+
if (id && shippedSystems2().includes(id)) return { uri, mimeType: "application/json", text: fs8.readFileSync(path9.join(REPO_ROOT, "tokens/systems", `${id}.system.json`), "utf8") };
|
|
3831
|
+
const manifest = componentsResource(COMPONENTS_URI.exec(uri)?.[1]);
|
|
3832
|
+
if (manifest) return { uri, mimeType: "application/json", text: JSON.stringify(manifest) };
|
|
3833
|
+
throw new ToolError(`unknown resource ${uri}. Known: ${listResources().map((r) => r.uri).join(", ")}`);
|
|
3834
|
+
}
|
|
3835
|
+
|
|
3836
|
+
// src/tools.js
|
|
3837
|
+
import fs9 from "node:fs";
|
|
3838
|
+
import path10 from "node:path";
|
|
3839
|
+
|
|
3840
|
+
// ../tokens-build/src/emit/css.js
|
|
3841
|
+
var PREFIX3 = CONFIG.web.cssPrefix;
|
|
3842
|
+
var varName = (path11) => `${PREFIX3}-${kebab(path11)}`;
|
|
3843
|
+
var VAR_NAMES = /* @__PURE__ */ new Map();
|
|
3844
|
+
var idToVar = (id) => {
|
|
3845
|
+
let name = VAR_NAMES.get(id);
|
|
3846
|
+
if (name === void 0) VAR_NAMES.set(id, name = id.startsWith(`${CONFIG.namespace}.`) ? varName(id.split(".").slice(1)) : `--${kebab(id.split("."))}`);
|
|
3847
|
+
return name;
|
|
3848
|
+
};
|
|
3849
|
+
var CORNER = `${CONFIG.namespace}.sys.shape.corner.`;
|
|
3850
|
+
var FULL = `${CORNER}full`;
|
|
3851
|
+
|
|
3852
|
+
// src/tools.js
|
|
3853
|
+
var legalOperations2 = (descriptor) => legalOperations(descriptor, { namespace: NS2 });
|
|
3854
|
+
var extensionRecipes2 = (descriptor, layerId) => extensionRecipes(descriptor, layerId, { namespace: NS2 });
|
|
3855
|
+
var CANNOT2 = cannot(NS2);
|
|
3856
|
+
var TIERS = ["dial", "ref", "sys", "comp"];
|
|
3857
|
+
var SYS_COLOR3 = `${NS2}.sys.color.`;
|
|
3858
|
+
var systemProperties = {
|
|
3859
|
+
system: { type: "string", description: `A shipped system id (default "${DEFAULT_SYSTEM}"), or the path of a product's <id>.system.json.` },
|
|
3860
|
+
layerFile: { type: "string", description: "Path of a product's <id>.system.json (absolute, or relative to the server's working directory). Wins over `system`." }
|
|
3861
|
+
};
|
|
3862
|
+
var schemeProperty = { type: "string", enum: SCHEMES, default: "light", description: "Theme \xD7 contrast. Only colors differ between schemes." };
|
|
3863
|
+
var pagination = (limit, max) => ({
|
|
3864
|
+
limit: { type: "integer", minimum: 1, maximum: max, default: limit },
|
|
3865
|
+
offset: { type: "integer", minimum: 0, default: 0 }
|
|
3866
|
+
});
|
|
3867
|
+
function page(items, { offset = 0, limit }) {
|
|
3868
|
+
const slice = items.slice(offset, offset + limit);
|
|
3869
|
+
return { total: items.length, offset, limit, nextOffset: offset + slice.length < items.length ? offset + slice.length : null, items: slice };
|
|
3870
|
+
}
|
|
3871
|
+
var tierOf2 = (id) => id.split(".")[1];
|
|
3872
|
+
var clip2 = (text2, max = 140) => typeof text2 === "string" && text2.length > max ? `${text2.slice(0, max - 1)}\u2026` : text2;
|
|
3873
|
+
function formatValue(value) {
|
|
3874
|
+
if (Array.isArray(value)) return value.map(formatValue);
|
|
3875
|
+
if (!value || typeof value !== "object") return value;
|
|
3876
|
+
if ("colorSpace" in value) {
|
|
3877
|
+
const hex = value.hex ?? `#${value.components.map((c) => Math.round(c * 255).toString(16).padStart(2, "0")).join("")}`;
|
|
3878
|
+
return value.alpha === void 0 || value.alpha === 1 ? hex : `${hex} / ${value.alpha}`;
|
|
3879
|
+
}
|
|
3880
|
+
if ("value" in value && "unit" in value && Object.keys(value).length === 2) return `${value.value}${value.unit}`;
|
|
3881
|
+
return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, formatValue(v)]));
|
|
3882
|
+
}
|
|
3883
|
+
var choiceOf2 = (token) => {
|
|
3884
|
+
const names = token.$extensions?.[ENUM]?.values;
|
|
3885
|
+
return names ? { value: enumName(token) ?? token.$value, choice: { name: enumName(token) ?? null, index: token.$value, of: names } } : null;
|
|
3886
|
+
};
|
|
3887
|
+
var shownValue = (token) => choiceOf2(token)?.value ?? formatValue(token.$value);
|
|
3888
|
+
function kindAndRule(ctx, token) {
|
|
3889
|
+
const id = token.id;
|
|
3890
|
+
if (id.startsWith(SYS_COLOR3)) {
|
|
3891
|
+
const op = ctx.system.tokens[id];
|
|
3892
|
+
if (isRef5(op?.$value)) return { kind: "alias" };
|
|
3893
|
+
const target = token.aliasChain?.[0]?.split(".") ?? [];
|
|
3894
|
+
return { kind: "derived", rule: op?.derive ?? { fn: "tone", palette: target[3], note: 'The default tones every intent palette gets; the palette is declared under "palettes".' } };
|
|
3895
|
+
}
|
|
3896
|
+
if (id.startsWith(`${NS2}.ref.palette.`)) {
|
|
3897
|
+
const [palette, tone] = id.split(".").slice(3);
|
|
3898
|
+
const exact = ctx.system.palettes?.[palette]?.source?.tones?.[tone];
|
|
3899
|
+
return { kind: "derived", rule: { palette, tone: Number(tone), ...exact ? { exact, note: 'An exact color the palette declares under "source.tones" \u2014 not generated from the seed. Change the palette under "palettes", not this token.' } : { note: 'A tone of a declared palette. Change the palette under "palettes", not this token.' } } };
|
|
3900
|
+
}
|
|
3901
|
+
if (isRef5(token.originalValue?.$value)) return { kind: "alias" };
|
|
3902
|
+
const rule = token.$extensions?.[DERIVE2];
|
|
3903
|
+
if (rule && "fixed" in rule) return { kind: "fixed", rule };
|
|
3904
|
+
if (rule) return { kind: "derived", rule };
|
|
3905
|
+
return { kind: tierOf2(id) === "dial" ? "dial" : "fixed" };
|
|
3906
|
+
}
|
|
3907
|
+
function requireToken(ctx, id, scheme = "light") {
|
|
3908
|
+
const token = ctx.tokens(scheme)[id];
|
|
3909
|
+
if (token) return token;
|
|
3910
|
+
const ids = Object.keys(ctx.tokens("light"));
|
|
3911
|
+
let prefix = id.split(".");
|
|
3912
|
+
let near = [];
|
|
3913
|
+
while (prefix.length > 3 && !near.length) {
|
|
3914
|
+
prefix = prefix.slice(0, -1);
|
|
3915
|
+
near = ids.filter((other) => other.startsWith(`${prefix.join(".")}.`));
|
|
3916
|
+
}
|
|
3917
|
+
throw new ToolError(`${id}: not in system "${ctx.id}". If a token with this meaning exists, use it (search_tokens; \`near\` lists its neighbours). To add it, declare it under "vocabulary" with a rationale \u2014 see propose_extension.`, { near: near.slice(0, 8) });
|
|
3918
|
+
}
|
|
3919
|
+
function descriptorOf(ctx, token, { kind, rule }) {
|
|
3920
|
+
return { id: token.id, type: token.$type, value: token.$value, alias: kind === "alias" ? token.aliasChain?.[0] ?? null : null, rule: rule ?? null, state: token.$extensions?.[STATE] ?? false, axis: ctx.axisOf(token.id) ?? void 0, choices: token.$extensions?.[ENUM]?.values };
|
|
3921
|
+
}
|
|
3922
|
+
var editableLayerId = (ctx) => shippedSystems2().includes(ctx.id) ? void 0 : ctx.id;
|
|
3923
|
+
var extensionFlags = (ctx, token) => {
|
|
3924
|
+
const extension = ctx.extensionOf(token);
|
|
3925
|
+
return extension ? { extension: true, declaredBy: extension.declaredBy } : {};
|
|
3926
|
+
};
|
|
3927
|
+
function summarizeExtensions(extensions, first = 6) {
|
|
3928
|
+
const byKind = {};
|
|
3929
|
+
for (const { kind } of extensions) byKind[kind] = (byKind[kind] ?? 0) + 1;
|
|
3930
|
+
return { total: extensions.length, ...extensions.length ? { byKind } : {}, first: extensions.slice(0, first).map(({ id, kind, declaredBy }) => ({ id, kind, declaredBy })) };
|
|
3931
|
+
}
|
|
3932
|
+
function fidelityOf(id) {
|
|
3933
|
+
const file = path10.join(REPO_ROOT, "tokens/generated", id, "fidelity.json");
|
|
3934
|
+
if (!fs9.existsSync(file)) return void 0;
|
|
3935
|
+
const { equal, total, covered, different, unmapped, reference } = JSON.parse(fs9.readFileSync(file, "utf8"));
|
|
3936
|
+
return { equal, measured: total - covered, different: different.length, unmapped: unmapped.length, reference: reference.map(({ name, version, source: source2 }) => ({ name, version, source: source2 })) };
|
|
3937
|
+
}
|
|
3938
|
+
function summarizeLayer(layer, chain) {
|
|
3939
|
+
const palettes = Object.entries(layer.palettes ?? {});
|
|
3940
|
+
return {
|
|
3941
|
+
id: layer.id,
|
|
3942
|
+
name: layer.name,
|
|
3943
|
+
extends: layer.extends ?? null,
|
|
3944
|
+
description: layer.description,
|
|
3945
|
+
inspiredBy: layer.attribution?.inspiredBy,
|
|
3946
|
+
palettes: palettes.filter(([, decl]) => decl).map(([name, decl]) => decl.roles === "intent" ? `${name} (intent roles)` : name),
|
|
3947
|
+
droppedPalettes: palettes.filter(([, decl]) => decl === null).map(([name]) => name),
|
|
3948
|
+
valueChanges: Object.keys(layer.tokens ?? {}).length,
|
|
3949
|
+
patternRules: (layer.rules ?? []).length,
|
|
3950
|
+
extensions: summarizeExtensions(declaredExtensions(chain))
|
|
3951
|
+
};
|
|
3952
|
+
}
|
|
3953
|
+
async function listSystemsTool({ layerFile, warnings = true }) {
|
|
3954
|
+
const ctx = layerFile ? await loadContext({ layerFile }) : null;
|
|
3955
|
+
const shipped = [];
|
|
3956
|
+
for (const id of listedSystems()) {
|
|
3957
|
+
const summary = summarizeLayer(shippedLayer(id), readLayers({ system: id }).chain);
|
|
3958
|
+
const fidelity = fidelityOf(id);
|
|
3959
|
+
if (fidelity) summary.fidelity = fidelity;
|
|
3960
|
+
if (warnings) {
|
|
3961
|
+
const findings = await (await loadContext({ system: id })).warnings();
|
|
3962
|
+
if (id === DEFAULT_SYSTEM) summary.accessibilityWarnings = findings.length;
|
|
3963
|
+
else {
|
|
3964
|
+
const failures = findings.filter((f) => !isCriterionFinding(f));
|
|
3965
|
+
summary.accessibility = { criteria: "not-applied", measurements: findings.length - failures.length, because: PRESET_CRITERIA_NOTE, ...failures.length ? { failures } : {} };
|
|
3966
|
+
}
|
|
3967
|
+
}
|
|
3968
|
+
shipped.push(summary);
|
|
3969
|
+
}
|
|
3970
|
+
const result = { root: ROOT_SYSTEM, default: DEFAULT_SYSTEM, schemes: SCHEMES, shipped };
|
|
3971
|
+
if (ctx) {
|
|
3972
|
+
const known = new Set(shippedSystems2());
|
|
3973
|
+
result.product = {
|
|
3974
|
+
id: ctx.id,
|
|
3975
|
+
chain: ctx.chain.map((l) => l.id),
|
|
3976
|
+
layers: ctx.chain.filter((l) => !known.has(l.id)).map((l) => summarizeLayer(l, ctx.chain.slice(0, ctx.chain.indexOf(l) + 1))),
|
|
3977
|
+
...warnings ? { accessibilityWarnings: (await ctx.warnings()).length } : {}
|
|
3978
|
+
};
|
|
3979
|
+
}
|
|
3980
|
+
return result;
|
|
3981
|
+
}
|
|
3982
|
+
function matcher(query, namespaces = [NS2]) {
|
|
3983
|
+
if (!query) return () => true;
|
|
3984
|
+
if (!query.includes("*")) {
|
|
3985
|
+
const needle = query.toLowerCase();
|
|
3986
|
+
return (id) => id.toLowerCase().includes(needle);
|
|
3987
|
+
}
|
|
3988
|
+
const rooted = namespaces.includes(query.split(".")[0]) || query.startsWith("*") ? query : `${NS2}.${query}`;
|
|
3989
|
+
const segments2 = rooted.split(".");
|
|
3990
|
+
const source2 = segments2.map((segment, i) => segment === "**" || segment === "*" && i === segments2.length - 1 && i > 0 ? ".+" : segment.replace(/[$()+?[\]^{|}\\]/g, "\\$&").replace(/\*/g, "[^.]*")).join("\\.");
|
|
3991
|
+
const pattern = new RegExp(`^${source2}$`);
|
|
3992
|
+
return (id) => pattern.test(id);
|
|
3993
|
+
}
|
|
3994
|
+
async function searchTokens({ query, tier, type, kind, extensions, limit = 25, offset = 0, ...reference }) {
|
|
3995
|
+
const ctx = await loadContext(reference);
|
|
3996
|
+
const all = Object.values(ctx.tokens("light"));
|
|
3997
|
+
const matches = matcher(query, [...new Set(all.map((token) => token.id.split(".")[0]))]);
|
|
3998
|
+
const found = [];
|
|
3999
|
+
for (const token of all) {
|
|
4000
|
+
if (!matches(token.id) || tier && tierOf2(token.id) !== tier || type && token.$type !== type) continue;
|
|
4001
|
+
const described = kindAndRule(ctx, token).kind;
|
|
4002
|
+
if (kind && described !== kind) continue;
|
|
4003
|
+
const flags = extensionFlags(ctx, token);
|
|
4004
|
+
if (extensions !== void 0 && extensions !== Boolean(flags.extension)) continue;
|
|
4005
|
+
found.push({ id: token.id, $type: token.$type, kind: described, ...choiceOf2(token) ? { value: choiceOf2(token).value, choices: choiceOf2(token).choice.of } : {}, ...flags, description: clip2(token.$description ?? ctx.meta.get(token.id)?.vocabulary?.rationale) });
|
|
4006
|
+
}
|
|
4007
|
+
found.sort((a, b) => a.id.localeCompare(b.id));
|
|
4008
|
+
const { items, ...rest } = page(found, { offset, limit });
|
|
4009
|
+
return { system: ctx.id, ...rest, tokens: items };
|
|
4010
|
+
}
|
|
4011
|
+
function resolveOne(ctx, id, scheme, raw) {
|
|
4012
|
+
const token = requireToken(ctx, id, scheme);
|
|
4013
|
+
const { kind, rule } = kindAndRule(ctx, token);
|
|
4014
|
+
const tokens = ctx.tokens(scheme);
|
|
4015
|
+
const inputs = Object.fromEntries(ruleDependencies(rule).filter((dep) => tokens[dep]).map((dep) => [dep, formatValue(tokens[dep].$value)]));
|
|
4016
|
+
return {
|
|
4017
|
+
id,
|
|
4018
|
+
$type: token.$type,
|
|
4019
|
+
value: shownValue(token),
|
|
4020
|
+
...choiceOf2(token) ? { choice: choiceOf2(token).choice } : {},
|
|
4021
|
+
...raw ? { $value: token.$value } : {},
|
|
4022
|
+
kind,
|
|
4023
|
+
...token.aliasChain?.length ? { aliasChain: token.aliasChain } : {},
|
|
4024
|
+
...rule ? { rule } : {},
|
|
4025
|
+
...Object.keys(inputs).length ? { inputs } : {},
|
|
4026
|
+
...ctx.system.tokens[id]?.layer ? { setBy: ctx.system.tokens[id].layer } : {},
|
|
4027
|
+
...extensionFlags(ctx, token),
|
|
4028
|
+
cssVar: idToVar(id)
|
|
4029
|
+
};
|
|
4030
|
+
}
|
|
4031
|
+
async function resolveTool({ token, tokens, scheme = "light", raw = false, ...reference }) {
|
|
4032
|
+
const ids = [...token ? [token] : [], ...tokens ?? []];
|
|
4033
|
+
if (!ids.length) throw new ToolError('Pass "token" (one id) or "tokens" (up to 50 ids). Use search_tokens to find ids.');
|
|
4034
|
+
const ctx = await loadContext(reference, { scheme });
|
|
4035
|
+
return {
|
|
4036
|
+
system: ctx.id,
|
|
4037
|
+
chain: ctx.chain.map((l) => l.id),
|
|
4038
|
+
scheme,
|
|
4039
|
+
tokens: ids.map((id) => {
|
|
4040
|
+
try {
|
|
4041
|
+
return resolveOne(ctx, id, scheme, raw);
|
|
4042
|
+
} catch (error) {
|
|
4043
|
+
if (!(error instanceof ToolError)) throw error;
|
|
4044
|
+
return { id, error: error.message, ...error.details };
|
|
4045
|
+
}
|
|
4046
|
+
})
|
|
4047
|
+
};
|
|
4048
|
+
}
|
|
4049
|
+
async function explainToken({ token: id, scheme = "light", ...reference }) {
|
|
4050
|
+
const ctx = await loadContext(reference, { scheme });
|
|
4051
|
+
const token = requireToken(ctx, id, scheme);
|
|
4052
|
+
const { kind, rule } = kindAndRule(ctx, token);
|
|
4053
|
+
const descriptor = descriptorOf(ctx, token, { kind, rule });
|
|
4054
|
+
const extension = ctx.extensionOf(token);
|
|
4055
|
+
const followers = ctx.followers(id);
|
|
4056
|
+
const meta = ctx.meta.get(id) ?? {};
|
|
4057
|
+
const palette = id.startsWith(SYS_COLOR3) ? rule?.palette ?? null : id.startsWith(`${NS2}.ref.palette.`) ? id.split(".")[3] : null;
|
|
4058
|
+
const precedence = matchingRules(id, ctx.chain);
|
|
4059
|
+
const touchedBy = [];
|
|
4060
|
+
for (const layer of ctx.chain) {
|
|
4061
|
+
const operation = layer.tokens?.[id];
|
|
4062
|
+
const rules = precedence.rules.filter((r) => r.layer === layer.id).map(({ index: index2, wins, because }) => ({ ...layer.rules[index2], index: index2, wins, because }));
|
|
4063
|
+
const declares = palette && layer.palettes && palette in layer.palettes ? { [palette]: layer.palettes[palette] } : void 0;
|
|
4064
|
+
if (operation || rules.length || declares) touchedBy.push({ layer: layer.id, ...operation ? { operation } : {}, ...rules.length ? { rules } : {}, ...declares ? { palette: declares } : {} });
|
|
4065
|
+
}
|
|
4066
|
+
const effective = token.$extensions?.[STATE] ? operationFor(id, ctx.system) : ctx.system.tokens[id];
|
|
4067
|
+
const { layer: setBy, ...effectiveOperation } = effective ?? {};
|
|
4068
|
+
return {
|
|
4069
|
+
id,
|
|
4070
|
+
system: ctx.id,
|
|
4071
|
+
chain: ctx.chain.map((l) => l.id),
|
|
4072
|
+
$type: token.$type,
|
|
4073
|
+
kind,
|
|
4074
|
+
value: shownValue(token),
|
|
4075
|
+
...choiceOf2(token) ? { choice: choiceOf2(token).choice } : {},
|
|
4076
|
+
scheme,
|
|
4077
|
+
...token.aliasChain?.length ? { aliasChain: token.aliasChain } : {},
|
|
4078
|
+
...rule ? { rule } : {},
|
|
4079
|
+
cssVar: idToVar(id),
|
|
4080
|
+
description: token.$description,
|
|
4081
|
+
// Core vocabulary, or an extension a layer of this system declared — with who declared it and why.
|
|
4082
|
+
...extension ? { extension: true, ...extension } : {},
|
|
4083
|
+
vocabulary: meta.vocabulary ?? null,
|
|
4084
|
+
// Usage guidance for agents, from the token and every group above it (outermost first). Optional metadata.
|
|
4085
|
+
llm: meta.llm?.length ? meta.llm : null,
|
|
4086
|
+
touchedBy: touchedBy.length ? touchedBy : extension ? `No layer changes ${id} after "${extension.declaredBy}" declared it: it has the value of its declaration.` : `No layer changes ${id}: it has the default the vocabulary gives it.`,
|
|
4087
|
+
...effective ? { effectiveOperation, ...setBy ? { setBy } : {} } : {},
|
|
4088
|
+
// For a per-state token: the ONE pattern rule that values it (or the explicit entry that beats them all), and why.
|
|
4089
|
+
...precedence.rules.length ? { winningRule: precedence.explicit ? { explicit: true, layer: precedence.explicit.layer, because: `an explicit entry under "tokens" (layer "${precedence.explicit.layer}") beats every pattern` } : (({ layer, index: index2, match, wildcards, because }) => ({ layer, index: index2, match, wildcards, because }))(precedence.rules.find((r) => r.wins)) } : {},
|
|
4090
|
+
usedBy: token.aliasedBy?.length ? { total: token.aliasedBy.length, first: token.aliasedBy.slice(0, 8) } : void 0,
|
|
4091
|
+
// What follows this token: every token whose value moves when it does, through aliases and rules (transitively).
|
|
4092
|
+
followers: { total: followers.length, first: followers.slice(0, 8) },
|
|
4093
|
+
howToChange: legalOperations2(descriptor),
|
|
4094
|
+
howToExtend: extensionRecipes2(descriptor, editableLayerId(ctx)),
|
|
4095
|
+
cannot: CANNOT2,
|
|
4096
|
+
then: 'Every `write` is a fragment of a layer: merge it into the product\'s <id>.system.json ("tokens", "palettes", "rules" or "vocabulary"), check the file with validate_layer, then run `tanrei build`. For a complete, verified `vocabulary` declaration use propose_extension.'
|
|
4097
|
+
};
|
|
4098
|
+
}
|
|
4099
|
+
var groupOf = (id) => id.split(".").slice(1, 3).join(".");
|
|
4100
|
+
function onlyIn(ctx, tokens, ids) {
|
|
4101
|
+
const extensions = ids.flatMap((id) => {
|
|
4102
|
+
const extension = ctx.extensionOf(tokens[id]);
|
|
4103
|
+
return extension ? [{ id, declaredBy: extension.declaredBy }] : [];
|
|
4104
|
+
});
|
|
4105
|
+
const declared = new Set(extensions.map((e) => e.id));
|
|
4106
|
+
const fromPalettes = ids.filter((id) => !declared.has(id));
|
|
4107
|
+
return {
|
|
4108
|
+
total: ids.length,
|
|
4109
|
+
extensions: { total: extensions.length, first: extensions.slice(0, 12) },
|
|
4110
|
+
fromPalettes: { total: fromPalettes.length, first: fromPalettes.filter((id) => !id.startsWith(`${NS2}.ref.`)).slice(0, 12) }
|
|
4111
|
+
};
|
|
4112
|
+
}
|
|
4113
|
+
async function diffSystems({ a, b, scheme = "light", group, limit = 20, offset = 0 }) {
|
|
4114
|
+
const [left, right] = await Promise.all([loadContext({ system: a }, { scheme }), loadContext({ system: b }, { scheme })]);
|
|
4115
|
+
const [ta, tb] = [left.tokens(scheme), right.tokens(scheme)];
|
|
4116
|
+
const changed = [];
|
|
4117
|
+
const onlyInA = [];
|
|
4118
|
+
const onlyInB = Object.keys(tb).filter((id) => !(id in ta));
|
|
4119
|
+
for (const [id, token] of Object.entries(ta)) {
|
|
4120
|
+
if (!(id in tb)) onlyInA.push(id);
|
|
4121
|
+
else if (JSON.stringify(formatValue(token.$value)) !== JSON.stringify(formatValue(tb[id].$value))) {
|
|
4122
|
+
const direct = [left, right].flatMap((ctx) => ctx.system.tokens[id]?.layer && ctx.system.tokens[id].layer !== ROOT_SYSTEM ? [ctx.system.tokens[id].layer] : []);
|
|
4123
|
+
changed.push({ id, a: shownValue(token), b: shownValue(tb[id]), ...direct.length ? { setBy: [...new Set(direct)] } : {} });
|
|
4124
|
+
}
|
|
4125
|
+
}
|
|
4126
|
+
changed.sort((x, y) => TIERS.indexOf(tierOf2(x.id)) - TIERS.indexOf(tierOf2(y.id)) || x.id.localeCompare(y.id));
|
|
4127
|
+
const groups = {};
|
|
4128
|
+
for (const { id } of changed) groups[groupOf(id)] = (groups[groupOf(id)] ?? 0) + 1;
|
|
4129
|
+
const byTier = Object.fromEntries(TIERS.map((tier) => [tier, changed.filter(({ id }) => tierOf2(id) === tier).length]));
|
|
4130
|
+
const selected = group ? changed.filter(({ id }) => groupOf(id) === group || tierOf2(id) === group) : changed;
|
|
4131
|
+
const { items, ...rest } = page(selected, { offset, limit });
|
|
4132
|
+
return {
|
|
4133
|
+
a: left.id,
|
|
4134
|
+
b: right.id,
|
|
4135
|
+
scheme,
|
|
4136
|
+
compared: Object.keys(ta).length - onlyInA.length,
|
|
4137
|
+
changed: changed.length,
|
|
4138
|
+
byTier,
|
|
4139
|
+
byGroup: groups,
|
|
4140
|
+
// Token SETS differ for two legitimate reasons: a layer extended the vocabulary, or declared/dropped a palette.
|
|
4141
|
+
onlyInA: onlyIn(left, ta, onlyInA),
|
|
4142
|
+
onlyInB: onlyIn(right, tb, onlyInB),
|
|
4143
|
+
...onlyInA.length || onlyInB.length ? { note: "Ids on one side only are either EXTENSIONS \u2014 vocabulary a layer of that system declared, listed with `declaredBy` \u2014 or come from declared palettes (their four roles, and the ref.palette tones some role needs). Neither is an error." } : {},
|
|
4144
|
+
...group ? { group } : {},
|
|
4145
|
+
...rest,
|
|
4146
|
+
changes: items
|
|
4147
|
+
};
|
|
4148
|
+
}
|
|
4149
|
+
async function validateLayerTool({ layer, layerFile, parents, dir, limit = 20 }) {
|
|
4150
|
+
if (!layer === !layerFile) throw new ToolError('Pass exactly one of "layer" (the JSON object) or "layerFile" (its path).');
|
|
4151
|
+
if (layerFile && (parents || dir)) throw new ToolError('"parents" and "dir" go with "layer". A layer FILE finds its parents next to itself.');
|
|
4152
|
+
const result = await validateLayer2({ layer, layerFile, parents, dir });
|
|
4153
|
+
const { warnings, ...rest } = result;
|
|
4154
|
+
if (!result.valid) return { ...rest, next: "Fix the problems and validate again. Nothing is built from an invalid layer." };
|
|
4155
|
+
return {
|
|
4156
|
+
...rest,
|
|
4157
|
+
// Thresholds are constants — for extensions too. In a product layer a violation warns; it is printed by `tanrei build` and stamped into every generated file.
|
|
4158
|
+
warnings: { total: warnings.length, severity: "warning", first: leadWithStructure(warnings).slice(0, limit) },
|
|
4159
|
+
next: "Run `tanrei build` to regenerate every platform from this layer."
|
|
4160
|
+
};
|
|
4161
|
+
}
|
|
4162
|
+
var RATIONALE2 = "<why this design system or product needs it \u2014 8+ characters>";
|
|
4163
|
+
var REASON2 = "<why this value is pinned \u2014 8+ characters>";
|
|
4164
|
+
var STAND_IN = "Stand-in text for a trial build; it is never written anywhere.";
|
|
4165
|
+
var parentOf = (id) => id.split(".").slice(0, -1).join(".");
|
|
4166
|
+
function checkNames(id, segments2) {
|
|
4167
|
+
for (const segment of segments2) if (!SEGMENT.test(segment)) throw new ToolError(`${id}: "${segment}" is not a valid name. Every segment is lowercase letters, digits and hyphens, starting with a letter or a digit (${SEGMENT.source}).`);
|
|
4168
|
+
}
|
|
4169
|
+
function refuseExisting(ctx, id, token, what) {
|
|
4170
|
+
const declaredBy = (token && ctx.extensionOf(token)?.declaredBy) ?? ctx.extensions.find((e) => e.id === id)?.declaredBy;
|
|
4171
|
+
throw new ToolError(`${id} already exists in "${ctx.id}" \u2014 ${declaredBy ? `layer "${declaredBy}" declared it` : "it is core vocabulary"}. Declaring it again is an error (extensions are additive, declared once). ${what}`, {
|
|
4172
|
+
exists: { id, declaredBy: declaredBy ?? "core" },
|
|
4173
|
+
...token ? { howToChange: legalOperations2(descriptorOf(ctx, token, kindAndRule(ctx, token))) } : {}
|
|
4174
|
+
});
|
|
4175
|
+
}
|
|
4176
|
+
function briefValue(token) {
|
|
4177
|
+
const value = formatValue(token.$value);
|
|
4178
|
+
if (typeof value !== "object" || value === null) return value;
|
|
4179
|
+
if (choiceOf2(token)) return choiceOf2(token).value;
|
|
4180
|
+
if (token.$type === "typography") return `typography ${value.fontSize} / ${value.lineHeight} / ${value.fontWeight}${token.aliasChain?.length ? ` = {${token.aliasChain[0]}}` : ""}`;
|
|
4181
|
+
return `${token.$type}${token.aliasChain?.length ? ` = {${token.aliasChain[0]}}` : " (composite; use resolve)"}`;
|
|
4182
|
+
}
|
|
4183
|
+
function definitionLike(ctx, near, tokens) {
|
|
4184
|
+
const { kind, rule } = kindAndRule(ctx, near);
|
|
4185
|
+
if (near.id.startsWith(SYS_COLOR3)) {
|
|
4186
|
+
const role = near.id.slice(SYS_COLOR3.length);
|
|
4187
|
+
const onRole = tokens[`${SYS_COLOR3}on-${role}`] ? `${SYS_COLOR3}on-${role}` : `${SYS_COLOR3}on-surface`;
|
|
4188
|
+
return { derive: rule?.fn ? rule : { fn: "tone", palette: rule?.palette ?? "<palette>", tone: { light: [90], dark: [30] } }, onRole };
|
|
4189
|
+
}
|
|
4190
|
+
if (kind === "alias") return { $value: `{${near.aliasChain[0]}}` };
|
|
4191
|
+
if (kind === "derived" && rule?.fn === "mul") return { derive: { ...rule, by: `<coefficient \u2014 ${near.id.split(".").at(-1)} is ${rule.by}>` } };
|
|
4192
|
+
if (near.$type === "typography") return { $value: "<a full text style, or an alias to another typescale role>" };
|
|
4193
|
+
return { $value: near.$value, reason: REASON2 };
|
|
4194
|
+
}
|
|
4195
|
+
async function proposeExtension({ kind, near, component, axis, from, value, scale, id, $type, definition, layerId, ...reference }) {
|
|
4196
|
+
const { reference: described, chain } = readLayers(reference);
|
|
4197
|
+
const into = described.kind === "shipped" ? null : chain.at(-1);
|
|
4198
|
+
if (into && layerId && layerId !== into.id) throw new ToolError(`"layerId" (${layerId}) is not the id of ${reference.layerFile ?? reference.system} (${into.id}). Pass one of them.`);
|
|
4199
|
+
const layer = into?.id ?? layerId ?? null;
|
|
4200
|
+
if (layer !== null && !into && (shippedSystems2().includes(layer) || !/^[a-z][a-z0-9-]*$/.test(layer))) throw new ToolError(`"${layer}" cannot be a product layer's id: lowercase letters, digits and hyphens, and not a shipped system (${shippedSystems2().join(", ")}).`);
|
|
4201
|
+
const ctx = await loadContext(reference);
|
|
4202
|
+
const tokens = ctx.tokens("light");
|
|
4203
|
+
const nearToken = near ? requireToken(ctx, near) : null;
|
|
4204
|
+
const fragment = { vocabulary: {} };
|
|
4205
|
+
const notes = [];
|
|
4206
|
+
let declaration;
|
|
4207
|
+
if (kind === "axis-value") {
|
|
4208
|
+
const located = nearToken && ctx.axisOf(near);
|
|
4209
|
+
if (near && !located) throw new ToolError(`${near} is not on a component axis, so there is no size or variant to add next to it. Pass "component" and "axis", or use kind "step" / "own-token".`, { components: Object.fromEntries(Object.entries(ctx.components).map(([name, c]) => [name, Object.keys(c.axes)])) });
|
|
4210
|
+
const [componentName, axisName] = located ? located.id.split(".").slice(-2) : [component, axis];
|
|
4211
|
+
const declared = ctx.components[componentName];
|
|
4212
|
+
if (!declared) {
|
|
4213
|
+
const what = !componentName ? 'Pass "component" and "axis" (or "near": a token on the axis)' : ctx.componentNames.includes(componentName) ? `${NS2}.comp.${componentName} declares no axis, so there is no size or variant to add a value to; a layer adds VALUES to an axis, not axes` : `"${componentName}" is not a component of this system`;
|
|
4214
|
+
throw new ToolError(`${what}. Components with an axis: ${Object.keys(ctx.components).join(", ")}.`);
|
|
4215
|
+
}
|
|
4216
|
+
const onAxis = declared.axes[axisName];
|
|
4217
|
+
if (!onAxis) throw new ToolError(`${declared.id} has no axis "${axisName}". Its axes: ${Object.keys(declared.axes).join(", ")}. Axes are declared by the component; a layer adds VALUES to an axis, not axes.`);
|
|
4218
|
+
if (!value) throw new ToolError(`Pass "value": the name of the new ${axisName} (e.g. "3x", "danger").`);
|
|
4219
|
+
checkNames(`${declared.id}.${axisName}.${value}`, [value]);
|
|
4220
|
+
if (declared.states.includes(value)) throw new ToolError(`"${value}" is an interaction state. States are not extensible: ${declared.states.join(", ")} are bound to platform behaviour, not to values. How a state LOOKS is a value \u2014 see explain_token on ${declared.id}.<variant>.${value}.container.color, or a pattern rule.`);
|
|
4221
|
+
declaration = `${declared.id}.${axisName}.${value}`;
|
|
4222
|
+
if (onAxis.values.includes(value)) refuseExisting(ctx, declaration, null, `Value its tokens under "tokens": search_tokens "${onAxis.members ? `${declared.id}.**.${value}` : `${declared.id}.${value}.**`}".`);
|
|
4223
|
+
const source2 = from ?? located?.key ?? onAxis.default;
|
|
4224
|
+
if (!onAxis.values.includes(source2)) throw new ToolError(`"from" must be an existing ${axisName} of ${componentName} (${onAxis.values.join(", ")}), not "${source2}".`);
|
|
4225
|
+
if (scale !== void 0 && !onAxis.members) throw new ToolError(`"scale" applies to a size-like axis, whose members are numeric. A ${axisName} is cloned as it is; give its resting tokens values under "tokens".`);
|
|
4226
|
+
fragment.vocabulary[declaration] = { from: source2, ...scale !== void 0 ? { scale } : {}, rationale: RATIONALE2 };
|
|
4227
|
+
if (onAxis.members) notes.push(`One line values every member of the axis (${onAxis.members.join(", ")}) from "${source2}"${scale !== void 0 ? ", scaled and still following the dials" : ""}. Override a single member under "tokens", e.g. "${declared.id}.${onAxis.members[0]}.${value}".`);
|
|
4228
|
+
else {
|
|
4229
|
+
const prefix = `${declared.id}.${source2}.`;
|
|
4230
|
+
const resting = Object.values(tokens).filter((t) => t.id.startsWith(prefix) && !t.$extensions?.[STATE] && t.$type === "color" && t.aliasChain?.length && !t.aliasChain[0].startsWith(prefix));
|
|
4231
|
+
if (resting.length) fragment.tokens = Object.fromEntries(resting.map((t) => [`${declared.id}.${value}.${t.id.slice(prefix.length)}`, { $value: `{${t.aliasChain[0]}}` }]));
|
|
4232
|
+
notes.push(`"tokens" holds the resting colors of "${value}", as cloned from "${source2}": re-point the ones that make it a distinct ${axisName} and delete the rest. Its ${declared.states.join(", ")} tokens are valued by the system's pattern rules.`);
|
|
4233
|
+
}
|
|
4234
|
+
} else {
|
|
4235
|
+
declaration = id ?? (nearToken && value ? `${parentOf(near)}.${value}` : null);
|
|
4236
|
+
if (!declaration) throw new ToolError(kind === "step" ? 'Pass "id" (the full id of the new token), or "near" (a token of the series) with "value" (the name of the new step).' : `Pass "id": the full id of the new token, in the layer's own namespace.`);
|
|
4237
|
+
const segments2 = declaration.split(".");
|
|
4238
|
+
if (kind === "own-token") {
|
|
4239
|
+
if (!layer) throw new ToolError(`A layer's own tokens live in the namespace of its id: pass "layerFile" (the product's layer) or "layerId".`);
|
|
4240
|
+
if (segments2[0] === NS2) throw new ToolError(`${declaration} is inside Tanrei's tree; that is kind "step". A layer's own token is "${layer}.comp.<your-component>.<part>".`);
|
|
4241
|
+
if (segments2[0] !== layer) throw new ToolError(`${declaration}: a layer's own tokens live in its own namespace \u2014 "${layer}.\u2026", not "${segments2[0]}.\u2026". Did you mean "${[layer, ...segments2.slice(1)].join(".")}"?`);
|
|
4242
|
+
} else if (segments2[0] !== NS2) throw new ToolError(`${declaration}: a step in a series is inside Tanrei's tree ("${NS2}.sys.\u2026"). For a token of your own namespace use kind "own-token".`);
|
|
4243
|
+
if (!["sys", "comp"].includes(segments2[1]) || segments2.length < 4) throw new ToolError(`${declaration}: declare tokens under "${segments2[0]}.sys.<group>.\u2026" or "${segments2[0]}.comp.<component>.\u2026". Dials and the reference tier are not extensible; a color family is a palette ("palettes" with "roles": "intent").`);
|
|
4244
|
+
checkNames(declaration, segments2.slice(1));
|
|
4245
|
+
if (tokens[declaration]) refuseExisting(ctx, declaration, tokens[declaration], "Change its value instead \u2014 `howToChange` lists the legal operations.");
|
|
4246
|
+
const type = $type ?? nearToken?.$type;
|
|
4247
|
+
if (!type) throw new ToolError('Pass "$type" (color, dimension, number, duration, typography, shadow, cubicBezier, fontFamily, fontWeight), or "near": a token whose type and rule the new one takes after.');
|
|
4248
|
+
if (kind === "step" && !Object.keys(tokens).some((other) => other.startsWith(`${parentOf(declaration)}.`))) notes.push(`${parentOf(declaration)} has no tokens yet: this starts a NEW group inside Tanrei's tree rather than adding a step to a series. The engine accepts it, but what only your product has is better declared in your own namespace (kind "own-token").`);
|
|
4249
|
+
const value_ = definition ?? (nearToken ? kind === "own-token" ? { $value: `{${near}}` } : definitionLike(ctx, nearToken, tokens) : { $value: '<an alias "{tanrei.sys.\u2026}", or a literal with a "reason">' });
|
|
4250
|
+
fragment.vocabulary[declaration] = { $type: type, rationale: RATIONALE2, ...value_ };
|
|
4251
|
+
if (kind === "own-token") notes.push(`Emitted as ${idToVar(declaration)} on the web and as a typed object next to your system on the native platforms. It may reference any ${NS2}.* token; nothing in ${NS2}.* may reference it.`);
|
|
4252
|
+
}
|
|
4253
|
+
const fill = [`vocabulary["${declaration}"].rationale \u2014 why this design system or product needs it. validate_layer refuses the placeholder; so should you.`];
|
|
4254
|
+
const standIn = JSON.parse(JSON.stringify(fragment), (key, v) => (key === "rationale" || key === "reason") && isPlaceholder(v) ? STAND_IN : v);
|
|
4255
|
+
if (isPlaceholder(fragment.vocabulary[declaration].reason)) fill.push(`vocabulary["${declaration}"].reason \u2014 why the value is pinned.`);
|
|
4256
|
+
const open = JSON.stringify(standIn).match(/<[^<>"]*>/g) ?? [];
|
|
4257
|
+
fill.push(...open.map((text2) => `${text2} \u2014 replace it`));
|
|
4258
|
+
let verified;
|
|
4259
|
+
if (open.length) verified = { built: false, because: `The fragment still has ${open.length === 1 ? "a placeholder" : "placeholders"} only you can fill (${open.join(", ")}). Pass "definition" ({ "$value" | "derive", "reason"? }) to have the proposal built and its values reported, or fill it and run validate_layer.` };
|
|
4260
|
+
else {
|
|
4261
|
+
const base = into ?? { id: layer ?? "proposal", name: "Proposal", extends: ctx.id };
|
|
4262
|
+
const merged = { ...base, vocabulary: { ...base.vocabulary, ...standIn.vocabulary }, ...standIn.tokens ? { tokens: { ...standIn.tokens, ...base.tokens } } : {} };
|
|
4263
|
+
try {
|
|
4264
|
+
const trial = await trialBuild([...into ? chain.slice(0, -1) : chain, merged]);
|
|
4265
|
+
const after = trial.tokens("light");
|
|
4266
|
+
const added = Object.keys(after).filter((other) => !(other in tokens)).sort();
|
|
4267
|
+
const before = new Set(await ctx.warnings());
|
|
4268
|
+
verified = {
|
|
4269
|
+
built: true,
|
|
4270
|
+
how: `Built "${ctx.id}" + this fragment with the real pipeline (a stand-in for the rationale). Nothing was written.`,
|
|
4271
|
+
newTokens: { total: added.length, values: Object.fromEntries(added.slice(0, 40).map((other) => [other, briefValue(after[other])])) },
|
|
4272
|
+
// The parent is resolved once per chain digest and kept; the trial's warnings read its light tokens and role colors only.
|
|
4273
|
+
newWarnings: (await trial.warnings()).filter((warning) => !before.has(warning))
|
|
4274
|
+
};
|
|
4275
|
+
} catch (error) {
|
|
4276
|
+
if (!(error instanceof ToolError)) throw error;
|
|
4277
|
+
verified = { built: false, error: error.message, ...error.details ?? {} };
|
|
4278
|
+
}
|
|
4279
|
+
}
|
|
4280
|
+
return {
|
|
4281
|
+
kind,
|
|
4282
|
+
declares: declaration,
|
|
4283
|
+
system: ctx.id,
|
|
4284
|
+
layer: layer ?? "<the product layer that will declare it>",
|
|
4285
|
+
write: fragment,
|
|
4286
|
+
fill,
|
|
4287
|
+
...notes.length ? { notes } : {},
|
|
4288
|
+
verified,
|
|
4289
|
+
next: `Merge \`write\` into ${into ? reference.layerFile ?? reference.system : "the product's <id>.system.json"}, fill the rationale, run validate_layer, then \`tanrei build\`. \`vocabulary\` says the token exists; change its value later under "tokens", like any core token.`
|
|
4290
|
+
};
|
|
4291
|
+
}
|
|
4292
|
+
var registry;
|
|
4293
|
+
function gapsRegistry() {
|
|
4294
|
+
registry ??= JSON.parse(fs9.readFileSync(path10.join(REPO_ROOT, "docs/governance/mimicry-gaps.json"), "utf8"));
|
|
4295
|
+
return registry;
|
|
4296
|
+
}
|
|
4297
|
+
function mimicryGaps({ status, kind, system, id, limit = 10, offset = 0 }) {
|
|
4298
|
+
const { gaps } = gapsRegistry();
|
|
4299
|
+
const needle = system?.toLowerCase();
|
|
4300
|
+
const found = gaps.filter((gap) => (!id || gap.id === id) && (!status || gap.status === status) && (!kind || gap.kind === kind) && (!needle || gap.systems.some((s) => s.toLowerCase().includes(needle))));
|
|
4301
|
+
const count = (key) => found.reduce((acc, gap) => ({ ...acc, [gap[key]]: (acc[gap[key]] ?? 0) + 1 }), {});
|
|
4302
|
+
const { items, ...rest } = page(found, { offset, limit });
|
|
4303
|
+
return {
|
|
4304
|
+
about: `Traits of other design systems that Tanrei cannot reproduce yet. A shipped preset's accessibility measurements are not gaps: Tanrei's accessibility criteria do not apply to an imitation preset. MISSING VOCABULARY IS NOT A GAP any more: a size, a variant, a step, a color role or a product's own token is declared by the layer under "vocabulary" (propose_extension). What stays here is what no token can express \u2014 behaviours and mechanisms (ripple, continuous corners, materials) \u2014 each a defect in Tanrei, resolved by a new token TYPE, a small enumerated behaviour token, or a component composition option.`,
|
|
4305
|
+
byStatus: count("status"),
|
|
4306
|
+
byKind: count("kind"),
|
|
4307
|
+
...rest,
|
|
4308
|
+
gaps: items
|
|
4309
|
+
};
|
|
4310
|
+
}
|
|
4311
|
+
var object = (properties, required = []) => ({ type: "object", additionalProperties: false, properties, required });
|
|
4312
|
+
var TOOLS = [
|
|
4313
|
+
{
|
|
4314
|
+
name: "list_systems",
|
|
4315
|
+
description: "The design systems that ship with Tanrei (the default `tanrei` and the presets; every chain starts at the root layer `core`, which values the vocabulary and is not listed) and, with `layerFile`, a product's own layer chain. A system is a LAYER: it changes values of a small shared core vocabulary, and may EXTEND it under `vocabulary` \u2014 each system lists its extensions with the layer that declared them, and a preset measured against the published system it reproduces lists its `fidelity` (equal / measured reference tokens, how many differ or have no counterpart, and the reference). Start here.",
|
|
4316
|
+
inputSchema: object({
|
|
4317
|
+
layerFile: systemProperties.layerFile,
|
|
4318
|
+
warnings: { type: "boolean", default: true, description: "Count accessibility/structure warnings per system (builds each system once; cached). For an imitation preset the count is of contrast measurements that do not apply to it, under `accessibility`." }
|
|
4319
|
+
}),
|
|
4320
|
+
handler: listSystemsTool
|
|
4321
|
+
},
|
|
4322
|
+
{
|
|
4323
|
+
name: "list_components",
|
|
4324
|
+
description: `The components a system ships, from its components manifest \u2014 call it first, to settle the system, and write UI with nothing it does not list. Each component: name, title, category, level, listing (\`advanced\` = a building block that a composed component usually wraps), a short summary, the web element with the module that registers it, the React wrapper with the entry to import it from, the \`variant\` values this system offers, and each platform's status. \`omitted\` lists the components the system does not have \u2014 the layer that left each out and why, or the layer it lives in \u2014 with \`insteadUse\` (what this system ships for the same job), the shipped systems that have it and the layer line that takes it; \`omittedVariants\` the variant values it leaves out. Default system "${DEFAULT_SYSTEM}"; with \`layerFile\`, a product's system as \`tanrei build\` works it out.`,
|
|
4325
|
+
inputSchema: object({
|
|
4326
|
+
...systemProperties,
|
|
4327
|
+
listing: { type: "string", enum: LISTINGS, description: "advanced: the building blocks a composed component wraps; a product usually writes the composed one." },
|
|
4328
|
+
category: { type: "string", enum: CATEGORIES },
|
|
4329
|
+
level: { type: "string", enum: LEVELS },
|
|
4330
|
+
platform: { type: "string", enum: PLATFORMS, default: "web", description: "The platform whose status is shown, and filtered on with `status`." },
|
|
4331
|
+
status: { type: "string", enum: STATUSES2 },
|
|
4332
|
+
...pagination(100, 200)
|
|
4333
|
+
}),
|
|
4334
|
+
handler: listComponents
|
|
4335
|
+
},
|
|
4336
|
+
{
|
|
4337
|
+
name: "get_component",
|
|
4338
|
+
description: "One component as its spec describes it, for one system: its props (`variant` narrowed to the values this system offers), events, slots, the elements it holds (`items`), states, its behaviour as EARS rules each with its stable id (`BTN-1` \u2026), accessibility (role, keys, labeling), and one fixture as an example of what to set. `name` may be the component's name, its element or its React wrapper. A component the system does not have answers `available: false` with what to use instead. `sections` narrows the answer, or adds `anatomy`, `tokens`, `platforms` (each platform's names for every prop and event) and `fixtures` (all of them).",
|
|
4339
|
+
inputSchema: object(
|
|
4340
|
+
{
|
|
4341
|
+
name: { type: "string", description: 'e.g. "text-field", "tanrei-text-field" or "TextField".' },
|
|
4342
|
+
...systemProperties,
|
|
4343
|
+
sections: { type: "array", items: { type: "string", enum: SECTIONS }, uniqueItems: true, default: DEFAULT_SECTIONS, description: `Default: ${DEFAULT_SECTIONS.join(", ")}.` }
|
|
4344
|
+
},
|
|
4345
|
+
["name"]
|
|
4346
|
+
),
|
|
4347
|
+
handler: getComponent
|
|
4348
|
+
},
|
|
4349
|
+
{
|
|
4350
|
+
name: "find_component",
|
|
4351
|
+
description: 'Which component does a job: the words of `need` ("pick a date", "confirm before deleting") against each spec\'s name and title, its summary and its props, best first, among the components the system has. A component that matches as well but that the system does not have is listed apart (`notInThisSystem`), with what to use instead.',
|
|
4352
|
+
inputSchema: object(
|
|
4353
|
+
{
|
|
4354
|
+
need: { type: "string", minLength: 2, description: "What the UI has to do, in plain English." },
|
|
4355
|
+
...systemProperties,
|
|
4356
|
+
limit: { type: "integer", minimum: 1, maximum: 20, default: 5 }
|
|
4357
|
+
},
|
|
4358
|
+
["need"]
|
|
4359
|
+
),
|
|
4360
|
+
handler: findComponent
|
|
4361
|
+
},
|
|
4362
|
+
{
|
|
4363
|
+
name: "check_usage",
|
|
4364
|
+
description: "Check code against a system's components manifest \u2014 the check `tanrei audit` runs: every element (`<tanrei-\u2026>`, a tag in a string, an imported React wrapper) and every CSS selector naming an element of a component the system does not have; every import of an entry that does not fit the system (another system's, or the one of every component), of a web module or of a React wrapper it does not have; and every literal `variant` the system leaves out. Each with its file, line and column, why, and what to write instead (`insteadUse` for a component, also the shipped systems that have it and the layer line that takes it into a product; `use` for an import; `values` for a variant). An unknown `tanrei-` element is reported with the nearest components. Comments are skipped. It reads the text, not a syntax tree: a variant set from a variable is not seen. Pass `code` (with `path`, whose extension says how to read it: .html, .css, or script by default) or `files`. Reads, never writes.",
|
|
4365
|
+
inputSchema: object({
|
|
4366
|
+
code: { type: "string", maxLength: 1048576, description: "Source text: HTML, a template, JSX/TSX, Vue, Svelte\u2026" },
|
|
4367
|
+
path: { type: "string", description: "With `code`: the name findings carry as `file`; its extension says how to read the text (.html, .vue, .svelte and .astro as markup, .css, .scss and .less as a stylesheet, anything else as script)." },
|
|
4368
|
+
files: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 50, description: "Paths of files to read (absolute, or relative to the server's working directory)." },
|
|
4369
|
+
...systemProperties
|
|
4370
|
+
}),
|
|
4371
|
+
handler: checkUsage
|
|
4372
|
+
},
|
|
4373
|
+
{
|
|
4374
|
+
name: "search_tokens",
|
|
4375
|
+
description: `Find tokens of the vocabulary by id. \`query\` is a case-insensitive substring, or a glob when it contains \`*\`: \`*\` matches within one segment, \`**\` any number of segments (e.g. \`${NS2}.comp.button.*.hovered.*\`, \`sys.color.on-*\`, \`**.opacity\`). A layer's own tokens are found by their namespace (\`acme.comp.*\`). Returns id, $type, kind (derived | fixed | alias | dial), \`extension: true\` + \`declaredBy\` for vocabulary a layer added, and a short description, paginated. A choice of kind (\`sys.behavior.*\`) shows the NAME it has and the names it may take. Search before concluding a token is missing; if it really is, propose_extension adds it.`,
|
|
4376
|
+
inputSchema: object({
|
|
4377
|
+
query: { type: "string", description: "Substring or glob over token ids. Omit to list by tier/type." },
|
|
4378
|
+
tier: { type: "string", enum: TIERS, description: "dial < ref < sys < comp. Components read comp tokens; comp aliases sys; sys derives from dials and palettes." },
|
|
4379
|
+
type: { type: "string", description: "DTCG $type: color, dimension, number, duration, typography, cubicBezier, shadow, fontFamily, fontWeight\u2026" },
|
|
4380
|
+
kind: { type: "string", enum: ["derived", "fixed", "alias", "dial"] },
|
|
4381
|
+
extensions: { type: "boolean", description: "true: only vocabulary that a layer of this system declared. false: only core vocabulary." },
|
|
4382
|
+
...systemProperties,
|
|
4383
|
+
...pagination(25, 200)
|
|
4384
|
+
}),
|
|
4385
|
+
handler: searchTokens
|
|
4386
|
+
},
|
|
4387
|
+
{
|
|
4388
|
+
name: "resolve",
|
|
4389
|
+
description: "The resolved value of one or more tokens in a system and scheme (a choice of kind \u2014 `sys.behavior.*` \u2014 as its NAME, with `choice: { name, index, of }`), with where it comes from: the alias chain, the derive rule and the current value of its inputs, which layer set it (and, for an extension, which layer declared it), and the CSS custom property name (`--tanrei-\u2026`; `--<namespace>-\u2026` for a layer's own tokens).",
|
|
4390
|
+
inputSchema: object({
|
|
4391
|
+
token: { type: "string", description: `One token id, e.g. ${NS2}.sys.shape.corner.small` },
|
|
4392
|
+
tokens: { type: "array", items: { type: "string" }, maxItems: 50 },
|
|
4393
|
+
...systemProperties,
|
|
4394
|
+
scheme: schemeProperty,
|
|
4395
|
+
raw: { type: "boolean", default: false, description: "Also return the DTCG $value object (colors as components)." }
|
|
4396
|
+
}),
|
|
4397
|
+
handler: resolveTool
|
|
4398
|
+
},
|
|
4399
|
+
{
|
|
4400
|
+
name: "explain_token",
|
|
4401
|
+
description: 'Everything needed to change ONE token correctly: why it exists (the core rationale, or \u2014 for an extension \u2014 who declared it and why), usage guidance if the vocabulary carries any, which layers and pattern rules touch it (root first; every matching pattern rule says whether it `wins` and `because` \u2014 an explicit entry beats patterns, fewer wildcards beat more, the later layer wins a tie \u2014 and `winningRule` names the one that values the token), what follows it (`followers`), the operations a layer may legally write for it (`howToChange`; for a choice of kind: "choose", with the names; for a typeface: "set the font stack") and how to add vocabulary next to it (`howToExtend`: a step in its series, a size/variant on its axis, a token of your own). Every `write` is a ready-to-edit fragment of a layer. Call this before editing a layer.',
|
|
4402
|
+
inputSchema: object({ token: { type: "string" }, ...systemProperties, scheme: schemeProperty }, ["token"]),
|
|
4403
|
+
handler: explainToken
|
|
4404
|
+
},
|
|
4405
|
+
{
|
|
4406
|
+
name: "diff_systems",
|
|
4407
|
+
description: "Tokens whose resolved value differs between two systems in one scheme. Counts come first (by tier and by group such as `sys.color`, `comp.button`); details are paginated and can be narrowed with `group`. Ids that exist on one side only are reported apart: extensions (with `declaredBy`) and what declared palettes bring.",
|
|
4408
|
+
inputSchema: object(
|
|
4409
|
+
{
|
|
4410
|
+
a: { type: "string", description: "Shipped system id, or path of a <id>.system.json." },
|
|
4411
|
+
b: { type: "string", description: "Shipped system id, or path of a <id>.system.json." },
|
|
4412
|
+
scheme: schemeProperty,
|
|
4413
|
+
group: { type: "string", description: "A tier (`sys`) or a group from `byGroup` (`sys.shape`)." },
|
|
4414
|
+
...pagination(20, 200)
|
|
4415
|
+
},
|
|
4416
|
+
["a", "b"]
|
|
4417
|
+
),
|
|
4418
|
+
handler: diffSystems
|
|
4419
|
+
},
|
|
4420
|
+
{
|
|
4421
|
+
name: "validate_layer",
|
|
4422
|
+
description: `Check a product layer before it is saved or built: JSON Schema; then every problem at once, with the way out \u2014 \`vocabulary\` declarations as the engine judges them (a rationale, the layer's own namespace, declared once, an existing axis and \`from\`, never an interaction state), ids under \`tokens\`/\`rules\` that are neither core nor declared (declare them, or use the token that exists), a pinned literal without a \`reason\`, a \`$type\` change, leftover placeholders; then the real build, which is the final authority, and what it refuses in every layer: \`${NS2}.sys.target.pointer\` or \`.touch\` under \`${NS2}.sys.target.minimum\` (they alias it; set them higher, never lower), and \`${NS2}.sys.target.minimum\` above \`${NS2}.dial.control.height\`. If valid, returns the accessibility/structure warnings \`tanrei build\` would print \u2014 among them \`sys.target.minimum\`, \`.pointer\` or \`.touch\` under 24px (WCAG 2.5.8) and a pressable height under \`sys.target.minimum\` (no size step draws one lower; derive it with \`"min": "{${NS2}.sys.target.minimum}"\`, or lower the minimum). Writes nothing.`,
|
|
4423
|
+
inputSchema: object({
|
|
4424
|
+
layer: { type: "object", description: 'The layer as JSON: { "id", "extends", "vocabulary", "palettes", "tokens", "rules" }. It may extend a shipped system, a layer passed in "parents", or a layer file in "dir".' },
|
|
4425
|
+
parents: { type: "array", items: { type: "object" }, maxItems: 8, description: 'With "layer": other layers that exist only in this request and that the layer (or another parent) extends \u2014 a product that stacks its own layers. Any order; each needs an "id". They are validated too.' },
|
|
4426
|
+
dir: { type: "string", description: `With "layer": the directory that holds the product's other <id>.system.json files, where "extends" is looked up after "parents" and before the shipped systems. The layer itself shadows a file of the same id, so this validates what WOULD be written. "extends" is an id, never a path: only <dir>/<id>.system.json \u2014 a regular file inside the directory \u2014 is read.` },
|
|
4427
|
+
layerFile: systemProperties.layerFile,
|
|
4428
|
+
limit: { type: "integer", minimum: 1, maximum: 200, default: 20, description: "How many warnings to return." }
|
|
4429
|
+
}),
|
|
4430
|
+
handler: validateLayerTool
|
|
4431
|
+
},
|
|
4432
|
+
{
|
|
4433
|
+
name: "propose_extension",
|
|
4434
|
+
description: `Write the \`vocabulary\` declaration that ADDS something to a system, checked and \u2014 where possible \u2014 built. Three kinds: "step" (a token inside Tanrei's tree: one more step of a series, or a single color role), "axis-value" (a size or variant of a component: one line values every member, e.g. button size "3x" from "large" \xD7 1.5), "own-token" (a token of the product's own components, in the layer's namespace). Refuses what the engine would refuse \u2014 an id that already exists (change its value under \`tokens\` instead), an invalid name, a foreign namespace, an unknown axis or \`from\`, an interaction state \u2014 and returns \`write\` (a layer fragment with a rationale placeholder YOU must fill; validate_layer rejects the placeholder) plus \`verified\`: the new token ids and their values from a trial build, and any new warnings. Writes nothing.`,
|
|
4435
|
+
inputSchema: object(
|
|
4436
|
+
{
|
|
4437
|
+
kind: { type: "string", enum: ["step", "axis-value", "own-token"] },
|
|
4438
|
+
near: { type: "string", description: "An existing token id the new thing sits next to. step: a token of the series (gives the group, $type and the shape of the rule). axis-value: a token on the axis (gives component, axis and `from`). own-token: the token it references." },
|
|
4439
|
+
id: { type: "string", description: `step / own-token: the full id of the new token, e.g. ${NS2}.sys.space.space1200 or acme.comp.rating.star.size. A step may pass "near" + "value" instead.` },
|
|
4440
|
+
value: { type: "string", description: 'axis-value: the name of the new size or variant ("3x", "danger"). step: the name of the new step, next to "near".' },
|
|
4441
|
+
component: { type: "string", description: 'axis-value: the component, e.g. "button".' },
|
|
4442
|
+
axis: { type: "string", description: 'axis-value: the axis, e.g. "size" or "variant".' },
|
|
4443
|
+
from: { type: "string", description: "axis-value: the existing value to clone. Defaults to the value of `near`, or the axis's default." },
|
|
4444
|
+
scale: { description: 'axis-value on a size-like axis: multiply the numeric members \u2014 a number, or a map of member \u2192 number ({"container.height": 1.5}).', oneOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "object", additionalProperties: { type: "number", exclusiveMinimum: 0 } }] },
|
|
4445
|
+
$type: { type: "string", description: "step / own-token: the DTCG $type. Defaults to the $type of `near`." },
|
|
4446
|
+
definition: { type: "object", description: 'step / own-token: the value, exactly as the declaration takes it \u2014 { "$value": "{tanrei.sys.\u2026}" } | { "$value": <literal>, "reason": "\u2026" } | { "derive": {\u2026} }, plus "onRole" for a color role. Without it the proposal takes after `near` and may leave a placeholder.' },
|
|
4447
|
+
...systemProperties,
|
|
4448
|
+
layerId: { type: "string", description: "The id of the product layer that will declare it, when there is no file yet. It is the namespace of the layer's own tokens." }
|
|
4449
|
+
},
|
|
4450
|
+
["kind"]
|
|
4451
|
+
),
|
|
4452
|
+
handler: proposeExtension
|
|
4453
|
+
},
|
|
4454
|
+
{
|
|
4455
|
+
name: "mimicry_gaps",
|
|
4456
|
+
description: "Tanrei's registry of traits it cannot reproduce yet (ripple, continuous corners, backdrop materials\u2026). Missing VOCABULARY is not a gap \u2014 a layer declares it (propose_extension). Check this when a trait is a behaviour or a mechanism that no token value can express.",
|
|
4457
|
+
inputSchema: object({
|
|
4458
|
+
status: { type: "string", enum: ["open", "planned", "resolved", "wont-fix"] },
|
|
4459
|
+
kind: { type: "string", description: "behavior | mechanism | vocabulary | anatomy" },
|
|
4460
|
+
system: { type: "string", description: 'Substring of the imitated system, e.g. "Material", "HIG", "cupertino".' },
|
|
4461
|
+
id: { type: "string" },
|
|
4462
|
+
...pagination(10, 100)
|
|
4463
|
+
}),
|
|
4464
|
+
handler: mimicryGaps
|
|
4465
|
+
}
|
|
4466
|
+
];
|
|
4467
|
+
|
|
4468
|
+
// src/server.js
|
|
4469
|
+
var VERSION = JSON.parse(fs10.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
4470
|
+
var ajv = new Ajv20202({ allErrors: true, strict: false, useDefaults: true });
|
|
4471
|
+
var tools = new Map(TOOLS.map((tool) => [tool.name, { ...tool, validate: ajv.compile(tool.inputSchema) }]));
|
|
4472
|
+
var text = (value, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(value) }], ...isError ? { isError: true } : {} });
|
|
4473
|
+
async function callTool(name, args = {}) {
|
|
4474
|
+
const tool = tools.get(name);
|
|
4475
|
+
if (!tool) throw new McpError(ErrorCode.InvalidParams, `unknown tool "${name}". Tools: ${[...tools.keys()].join(", ")}`);
|
|
4476
|
+
const input = structuredClone(args);
|
|
4477
|
+
if (!tool.validate(input)) return text({ error: "invalid arguments", problems: tool.validate.errors.map((e) => `${e.instancePath || "/"} ${e.message}${e.params?.additionalProperty ? ` ("${e.params.additionalProperty}")` : ""}${e.params?.allowedValues ? `: ${e.params.allowedValues.join(", ")}` : ""}`) }, true);
|
|
4478
|
+
try {
|
|
4479
|
+
return text(await tool.handler(input));
|
|
4480
|
+
} catch (error) {
|
|
4481
|
+
if (error instanceof ToolError) return text({ error: error.message, ...error.details }, true);
|
|
4482
|
+
return text({ error: `${name} failed: ${error.message}` }, true);
|
|
4483
|
+
}
|
|
4484
|
+
}
|
|
4485
|
+
function createServer() {
|
|
4486
|
+
const server = new Server({ name: "tanrei", title: "Tanrei design system", version: VERSION }, { capabilities: { tools: {}, resources: {} }, instructions: INSTRUCTIONS });
|
|
4487
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
4488
|
+
tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema, annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false } }))
|
|
4489
|
+
}));
|
|
4490
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => callTool(request.params.name, request.params.arguments));
|
|
4491
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: listResources() }));
|
|
4492
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
|
|
4493
|
+
resourceTemplates: [
|
|
4494
|
+
{ uriTemplate: "tanrei://systems/{id}", name: "System layer", description: "The layer file of a shipped system, as authored.", mimeType: "application/json" },
|
|
4495
|
+
{ uriTemplate: "tanrei://components/{id}", name: "Components manifest", description: "The components a shipped system ships, those it does not have, and the variant values it leaves out.", mimeType: "application/json" }
|
|
4496
|
+
]
|
|
4497
|
+
}));
|
|
4498
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
4499
|
+
try {
|
|
4500
|
+
return { contents: [readResource(request.params.uri)] };
|
|
4501
|
+
} catch (error) {
|
|
4502
|
+
throw new McpError(ErrorCode.InvalidParams, error.message);
|
|
4503
|
+
}
|
|
4504
|
+
});
|
|
4505
|
+
return server;
|
|
4506
|
+
}
|
|
4507
|
+
async function main() {
|
|
4508
|
+
console.log = console.info = console.debug = (...args) => console.error(...args);
|
|
4509
|
+
await createServer().connect(new StdioServerTransport());
|
|
4510
|
+
}
|
|
4511
|
+
export {
|
|
4512
|
+
callTool,
|
|
4513
|
+
createServer,
|
|
4514
|
+
main
|
|
4515
|
+
};
|