hd-garden 0.3.8 → 0.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/.agents/skills/garden-post-review/SKILL.md +2 -0
  2. package/.agents/skills/garden-ui/SKILL.md +111 -0
  3. package/.env.example +8 -0
  4. package/app/admin/page.tsx +14 -3
  5. package/app/admin/preview/[...path]/page.tsx +88 -0
  6. package/app/admin/ui/blocks/page.tsx +16 -0
  7. package/app/admin/ui/catalog/page.tsx +16 -0
  8. package/app/admin/ui/evals/page.tsx +19 -0
  9. package/app/admin/ui/page.tsx +22 -0
  10. package/app/admin-ui.css +227 -0
  11. package/app/api/admin/distribution/route.ts +4 -2
  12. package/app/api/admin/posts/source/route.ts +21 -0
  13. package/app/api/admin/preview/asset/route.ts +32 -0
  14. package/app/api/admin/thoughts/route.ts +1 -1
  15. package/app/api/admin/ui/blocks/route.ts +19 -0
  16. package/app/api/admin/ui/draft/route.ts +30 -0
  17. package/app/api/auth/github/route.ts +40 -1
  18. package/app/blog/page.tsx +6 -5
  19. package/app/columns/page.tsx +1 -1
  20. package/app/components/AdminDashboard.tsx +53 -1
  21. package/app/components/AdminUiPanels.tsx +258 -0
  22. package/app/components/AdminUiShell.tsx +56 -0
  23. package/app/components/ContentEmptyState.tsx +6 -6
  24. package/app/components/MarkdownArticle.tsx +15 -5
  25. package/app/components/UiBlock.tsx +22 -0
  26. package/app/components/UiStudio.tsx +422 -0
  27. package/app/components/ui-studio-keys.ts +3 -0
  28. package/app/globals.css +2 -0
  29. package/app/lib/admin-auth.ts +13 -1
  30. package/app/lib/content.ts +2 -1
  31. package/app/lib/fallback-site-config.ts +18 -18
  32. package/app/lib/github-content.ts +47 -4
  33. package/app/lib/repository-path.mjs +55 -0
  34. package/app/lib/ui-content.ts +79 -0
  35. package/app/lib/ui-model.ts +145 -0
  36. package/app/raw.d.ts +4 -0
  37. package/app/rss.xml/route.ts +2 -1
  38. package/app/ui-parity/page.tsx +120 -0
  39. package/bin/garden.mjs +71 -0
  40. package/eslint.config.mjs +3 -0
  41. package/package.json +15 -1
  42. package/scripts/build-content.mjs +35 -4
  43. package/scripts/build-ui-preview.mjs +29 -0
  44. package/scripts/check-post.mjs +26 -4
  45. package/scripts/ui-cli.mjs +303 -0
  46. package/site.config.yaml +19 -19
  47. package/templates/site/site.config.yaml +19 -19
  48. package/tsconfig.json +1 -1
  49. package/ui/core/apply.mjs +81 -0
  50. package/ui/core/catalog.mjs +536 -0
  51. package/ui/core/compile.mjs +63 -0
  52. package/ui/core/demos.mjs +223 -0
  53. package/ui/core/expr.mjs +310 -0
  54. package/ui/core/fence.mjs +201 -0
  55. package/ui/core/fix-prompt.mjs +35 -0
  56. package/ui/core/format.mjs +96 -0
  57. package/ui/core/index.mjs +37 -0
  58. package/ui/core/parse.mjs +229 -0
  59. package/ui/core/scan.mjs +53 -0
  60. package/ui/core/sha256.mjs +66 -0
  61. package/ui/core/starters.mjs +18 -0
  62. package/ui/core/state.mjs +259 -0
  63. package/ui/core/static.mjs +524 -0
  64. package/ui/core/transform.mjs +146 -0
  65. package/ui/core/validate.mjs +665 -0
  66. package/ui/evals/cases.yaml +155 -0
  67. package/ui/preview/dist/garden-ui.css +1182 -0
  68. package/ui/preview/dist/garden-ui.esm.js +367 -0
  69. package/ui/preview/dist/garden-ui.iife.js +367 -0
  70. package/ui/preview/index.tsx +191 -0
  71. package/ui/preview/mermaid-shim.ts +19 -0
  72. package/ui/prompt/build.mjs +24 -0
  73. package/ui/prompt/recipes/code-walkthrough.md +68 -0
  74. package/ui/prompt/recipes/compare.md +48 -0
  75. package/ui/prompt/recipes/converter.md +55 -0
  76. package/ui/prompt/recipes/data-chart.md +57 -0
  77. package/ui/prompt/recipes/inspect-grid.md +45 -0
  78. package/ui/prompt/recipes/param-bench.md +55 -0
  79. package/ui/prompt/recipes/plan.md +45 -0
  80. package/ui/prompt/recipes/stepper.md +52 -0
  81. package/ui/prompt/recipes/trace.md +62 -0
  82. package/ui/prompt/rules.md +104 -0
  83. package/ui/prompt/studio.md +20 -0
  84. package/ui/react/CatalogPage.tsx +166 -0
  85. package/ui/react/components/chart.tsx +470 -0
  86. package/ui/react/components/display.tsx +296 -0
  87. package/ui/react/components/inputs.tsx +268 -0
  88. package/ui/react/components/layout.tsx +236 -0
  89. package/ui/react/components/media.tsx +184 -0
  90. package/ui/react/index.tsx +59 -0
  91. package/ui/react/recipes.ts +25 -0
  92. package/ui/react/runtime.tsx +239 -0
  93. package/ui/react/types.ts +29 -0
  94. package/ui/react/ui.css +1182 -0
  95. package/vite.config.ts +4 -3
@@ -0,0 +1,665 @@
1
+ import { COMPONENTS, COMPONENT_NAMES, TONES } from "./catalog.mjs";
2
+ import { analyzeExpr, createBudget, evaluate, ExprError } from "./expr.mjs";
3
+ import { compiledOf, ID_PATTERN, intentHash, resolveSidecarPath, splitUiBody } from "./fence.mjs";
4
+ import { isValidFormat } from "./format.mjs";
5
+ import { parseUiBody } from "./parse.mjs";
6
+ import {
7
+ collectDecls,
8
+ computeScope,
9
+ defaultStateValues,
10
+ isPowerOfTwo,
11
+ isValidName,
12
+ lookupFrom,
13
+ orderLets,
14
+ parseDataFile,
15
+ runExpect,
16
+ } from "./state.mjs";
17
+
18
+ const HEADER_KEYS = new Set(["id", "caption", "intent", "compiled", "expect"]);
19
+ const MAX_ELEMENTS = 200;
20
+ const CONSTANT_NAMES = new Set(["PI", "E", "undefined", "NaN", "Infinity"]);
21
+ const INLINE_TYPES = new Set(["text", "x", "strong", "em", "code", "br", "link"]);
22
+ const DECL_COMPONENTS = new Set(["State", "Let", "Data"]);
23
+
24
+ function editDistance(left, right) {
25
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
26
+ for (let i = 1; i <= left.length; i += 1) {
27
+ let diagonal = previous[0];
28
+ previous[0] = i;
29
+ for (let j = 1; j <= right.length; j += 1) {
30
+ const saved = previous[j];
31
+ previous[j] = Math.min(
32
+ previous[j] + 1,
33
+ previous[j - 1] + 1,
34
+ diagonal + (left[i - 1].toLowerCase() === right[j - 1].toLowerCase() ? 0 : 1),
35
+ );
36
+ diagonal = saved;
37
+ }
38
+ }
39
+ return previous[right.length];
40
+ }
41
+
42
+ export function suggestComponent(name) {
43
+ let best = null;
44
+ for (const candidate of COMPONENT_NAMES) {
45
+ const distance = editDistance(name, candidate);
46
+ if (distance <= 2 && (!best || distance < best.distance)) best = { name: candidate, distance };
47
+ }
48
+ return best?.name ?? null;
49
+ }
50
+
51
+ const isPlainObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
52
+
53
+ /** Row fields shadow block names inside Chart / Table data mode. */
54
+ export const withRow = (row, lookup) => (name) =>
55
+ isPlainObject(row) && Object.hasOwn(row, name) ? { found: true, value: row[name] } : lookup(name);
56
+
57
+ const propExpression = (prop) => (prop.k === "expr" ? prop.e : { type: "Literal", value: prop.v });
58
+
59
+ /** Checks a literal or evaluated value against a prop spec. Returns a reason or null. */
60
+ function typeProblem(spec, value) {
61
+ switch (spec.type) {
62
+ case "string":
63
+ return typeof value === "string" || typeof value === "number" ? null : "需要文字";
64
+ case "number":
65
+ if (typeof value !== "number" || !Number.isFinite(value)) return "需要有限数字";
66
+ if (spec.min !== undefined && value < spec.min) return `不能小于 ${spec.min}`;
67
+ if (spec.max !== undefined && value > spec.max) return `不能大于 ${spec.max}`;
68
+ return null;
69
+ case "boolean":
70
+ return typeof value === "boolean" ? null : "需要 true 或 false";
71
+ case "array":
72
+ return Array.isArray(value) ? null : "需要数组";
73
+ case "object":
74
+ return isPlainObject(value) ? null : "需要对象";
75
+ case "enum":
76
+ return spec.values.includes(value) ? null : `只能是 ${spec.values.join(" / ")}`;
77
+ case "format":
78
+ return isValidFormat(value) ? null : "格式只能是 number、fixed:N、percent、percent:N、bytes、si、thousands";
79
+ case "gap":
80
+ return Number.isInteger(value) && value >= 0 && value <= 4 ? null : "只能是 0–4 的整数";
81
+ case "name":
82
+ return typeof value === "string" && isValidName(value) ? null : "需要小写字母开头的名字,且不能与函数名重名";
83
+ case "stateName":
84
+ return typeof value === "string" ? null : "需要状态名";
85
+ case "autoplay":
86
+ return value === false || (typeof value === "number" && value >= 800) ? null : "只能是 false 或不小于 800 的毫秒数";
87
+ default:
88
+ return null;
89
+ }
90
+ }
91
+
92
+ function headerLine(headerText, key, lineOffset) {
93
+ const index = headerText.split("\n").findIndex((line) => line.startsWith(`${key}:`));
94
+ return lineOffset + 2 + Math.max(0, index);
95
+ }
96
+
97
+ /**
98
+ * Full check of a `ui` fence body: header, syntax, catalog rules, evaluation
99
+ * at the default state (and at every bound step), `expect` and limits.
100
+ * Lines in diagnostics are file lines when `lineOffset` is the fence's first line.
101
+ */
102
+ export function checkUiBlock(body, options = {}) {
103
+ const { lineOffset = 0, markdownPath = null, readData = null, skipData = false } = options;
104
+ const diagnostics = [];
105
+ const seen = new Set();
106
+ const add = (code, line, message, severity = "error") => {
107
+ const key = `${code}|${line}|${message}`;
108
+ if (seen.has(key)) return;
109
+ seen.add(key);
110
+ diagnostics.push({ code, line, message, severity });
111
+ };
112
+ const result = (extra = {}) => ({
113
+ ok: !diagnostics.some((item) => item.severity === "error"),
114
+ diagnostics: diagnostics.sort((a, b) => a.line - b.line),
115
+ ...extra,
116
+ });
117
+
118
+ const split = splitUiBody(body);
119
+ if (!split.header) {
120
+ add("ui-header", lineOffset + 1, split.error ?? "块头无效");
121
+ return result({ header: null, root: null });
122
+ }
123
+ const { header, headerText } = split;
124
+ for (const key of Object.keys(header)) {
125
+ if (!HEADER_KEYS.has(key)) add("ui-header", headerLine(headerText, key, lineOffset), `块头不支持 ${key}`);
126
+ }
127
+ if (typeof header.id !== "string" || !ID_PATTERN.test(header.id)) {
128
+ add("ui-id", headerLine(headerText, "id", lineOffset), "id 必填,只能用小写字母、数字和连字符");
129
+ }
130
+ if (typeof header.caption !== "string" || !header.caption.trim()) {
131
+ add("ui-caption", headerLine(headerText, "caption", lineOffset), "caption 必填,写一句判断");
132
+ }
133
+ if (header.intent !== undefined && typeof header.intent !== "string") {
134
+ add("ui-header", headerLine(headerText, "intent", lineOffset), "intent 必须是文字");
135
+ }
136
+ const compiled = compiledOf(headerText);
137
+ if (compiled !== undefined && !/^[0-9a-f]{8}$/u.test(compiled)) {
138
+ add("ui-header", headerLine(headerText, "compiled", lineOffset), "compiled 是工具写入的 8 位哈希,不要手改");
139
+ } else if (typeof header.intent === "string" && compiled !== undefined && compiled !== intentHash(header.intent)) {
140
+ add("ui-stale", headerLine(headerText, "compiled", lineOffset), "原话改过了,还没重编译", "warning");
141
+ }
142
+ if (header.expect !== undefined && !Array.isArray(header.expect)) {
143
+ add("ui-header", headerLine(headerText, "expect", lineOffset), "expect 必须是数组");
144
+ }
145
+
146
+ const bodyLine = (line) => lineOffset + split.bodyLineOffset + line;
147
+ const parsed = parseUiBody(split.bodyText);
148
+ for (const item of parsed.diagnostics) add(item.code, bodyLine(item.line), item.message);
149
+ if (!parsed.root) return result({ header, root: null });
150
+ const { root } = parsed;
151
+
152
+ const decls = collectDecls(root);
153
+ const stateTypes = new Map();
154
+ const declared = new Map();
155
+ const declare = (name, line, kind) => {
156
+ if (!isValidName(name)) {
157
+ add("ui-prop", bodyLine(line), `${kind} 的名字 ${name} 不合法:要小写字母开头,不能与函数名重名`);
158
+ return;
159
+ }
160
+ if (declared.has(name)) add("ui-prop", bodyLine(line), `名字 ${name} 重复声明`);
161
+ declared.set(name, kind);
162
+ };
163
+ for (const state of decls.states) {
164
+ declare(state.name, state.line, "State");
165
+ if (state.prop.k !== "lit" || !["number", "string", "boolean"].includes(typeof state.prop.v)) {
166
+ add("ui-prop", bodyLine(state.line), `State ${state.name} 的默认值只能是数字、文字或布尔字面量`);
167
+ } else {
168
+ stateTypes.set(state.name, typeof state.prop.v);
169
+ }
170
+ }
171
+ for (const item of decls.lets) declare(item.name, item.line, "Let");
172
+ for (const item of decls.data) declare(item.name, item.line, "Data");
173
+ const knownNames = new Set(declared.keys());
174
+
175
+ const { cycle } = orderLets(decls.lets);
176
+ if (cycle) {
177
+ const first = decls.lets.find((item) => item.name === cycle[0]);
178
+ add("ui-cycle", bodyLine(first?.line ?? 1), `Let 互相依赖成环:${cycle.join(" → ")}`);
179
+ }
180
+
181
+ const checkExpression = (expression, line, locals, rowScope) => {
182
+ const { problems, names } = analyzeExpr(expression);
183
+ for (const problem of problems) add("ui-expr", bodyLine(line), problem);
184
+ if (rowScope) return;
185
+ for (const name of names) {
186
+ if (!knownNames.has(name) && !locals.has(name) && !CONSTANT_NAMES.has(name)) {
187
+ add("ui-expr", bodyLine(line), `未知名字 ${name}`);
188
+ }
189
+ }
190
+ };
191
+
192
+ for (const item of decls.lets) {
193
+ if (item.prop.k === "expr") checkExpression(item.prop.e, item.line, new Set(), false);
194
+ }
195
+
196
+ const sliderByState = new Map();
197
+ const collectSliders = (node) => {
198
+ if (node?.t === "el" && node.n === "Slider" && node.p.bind?.k === "lit") sliderByState.set(node.p.bind.v, node);
199
+ node?.c?.forEach?.(collectSliders);
200
+ };
201
+ collectSliders(root);
202
+
203
+ // Static pass: catalog, props, children, bindings, names.
204
+ const staticVisit = (node, parent, locals, chartDataMode) => {
205
+ if (node.t === "x") {
206
+ checkExpression(node.e, node.l, locals, false);
207
+ return;
208
+ }
209
+ if (node.t !== "el") {
210
+ node.c?.forEach((child) => staticVisit(child, parent, locals, chartDataMode));
211
+ return;
212
+ }
213
+ const spec = COMPONENTS[node.n];
214
+ if (!spec) {
215
+ const suggestion = suggestComponent(node.n);
216
+ add("ui-component", bodyLine(node.l), `组件 <${node.n}> 不在目录里${suggestion ? `,是不是 <${suggestion}>?` : ""}`);
217
+ return;
218
+ }
219
+ const parentSpec = COMPONENTS[parent] ?? { children: "content" };
220
+ if (spec.parents && !spec.parents.includes(parent)) {
221
+ add("ui-children", bodyLine(node.l), `<${node.n}> 只能放在 ${spec.parents.map((name) => `<${name}>`).join(" / ")} 里`);
222
+ } else if (spec.children === "transparent" || DECL_COMPONENTS.has(node.n)) {
223
+ // If / Each take their parent's rule; declarations may sit anywhere.
224
+ } else if (Array.isArray(parentSpec.children) && !parentSpec.children.includes(node.n)) {
225
+ add("ui-children", bodyLine(node.l), `<${parent}> 里只能放 ${parentSpec.children.map((name) => `<${name}>`).join(" / ")}`);
226
+ } else if (parentSpec.children === "none" || parentSpec.children === "text") {
227
+ add("ui-children", bodyLine(node.l), `<${parent}> 里不能放组件`);
228
+ }
229
+
230
+ const isTransparent = spec.children === "transparent";
231
+ const effectiveParent = isTransparent ? parent : node.n;
232
+ const nextLocals = new Set(locals);
233
+
234
+ if (!spec.kind) {
235
+ for (const [name, prop] of Object.entries(node.p)) {
236
+ const propSpec = spec.props[name];
237
+ if (!propSpec) {
238
+ add("ui-prop", bodyLine(node.l), `<${node.n}> 没有属性 ${name}`);
239
+ continue;
240
+ }
241
+ if (prop.k === "expr") {
242
+ if (propSpec.literal) {
243
+ add("ui-prop", bodyLine(node.l), `<${node.n}> 的 ${name} 只能写字面量`);
244
+ continue;
245
+ }
246
+ const rowScope = Boolean(
247
+ (propSpec.rowScope && node.p.data) || (spec.rowScopeProps?.includes(name) && chartDataMode),
248
+ );
249
+ checkExpression(prop.e, node.l, locals, rowScope);
250
+ } else {
251
+ const problem = typeProblem(propSpec, prop.v);
252
+ if (problem) add("ui-prop", bodyLine(node.l), `<${node.n}> 的 ${name} ${problem}`);
253
+ }
254
+ }
255
+ for (const [name, propSpec] of Object.entries(spec.props)) {
256
+ if (propSpec.required && !node.p[name]) add("ui-prop", bodyLine(node.l), `<${node.n}> 缺少 ${name}`);
257
+ }
258
+ }
259
+
260
+ const bind = node.p.bind?.k === "lit" ? node.p.bind.v : null;
261
+ if (bind !== null && spec.props.bind) {
262
+ if (!stateTypes.has(bind)) {
263
+ add("ui-bind", bodyLine(node.l), `<${node.n}> 绑定的 ${bind} 没有在 State 里声明`);
264
+ } else if (spec.props.bind.stateType && stateTypes.get(bind) !== spec.props.bind.stateType) {
265
+ add("ui-bind", bodyLine(node.l), `<${node.n}> 需要绑定${spec.props.bind.stateType === "number" ? "数字" : "布尔"}状态,${bind} 是 ${stateTypes.get(bind)}`);
266
+ }
267
+ }
268
+
269
+ switch (node.n) {
270
+ case "Each":
271
+ if (node.p.as?.k === "lit" && typeof node.p.as.v === "string") nextLocals.add(node.p.as.v);
272
+ if (node.p.index?.k === "lit" && typeof node.p.index.v === "string") nextLocals.add(node.p.index.v);
273
+ break;
274
+ case "Chart": {
275
+ const hasSweep = Boolean(node.p.sweep);
276
+ const hasData = Boolean(node.p.data);
277
+ if (hasSweep === hasData) add("ui-prop", bodyLine(node.l), "<Chart> 的 sweep 和 data 必须写且只能写一个");
278
+ if (hasData && !node.p.x) add("ui-prop", bodyLine(node.l), "<Chart> 数据模式需要 x");
279
+ if (hasSweep && node.p.sweep.k === "lit") {
280
+ const sweep = node.p.sweep.v;
281
+ if (!stateTypes.has(sweep)) add("ui-bind", bodyLine(node.l), `<Chart> 的 sweep ${sweep} 没有在 State 里声明`);
282
+ else if (stateTypes.get(sweep) !== "number") add("ui-bind", bodyLine(node.l), `<Chart> 的 sweep 必须是数字状态`);
283
+ if (!sliderByState.has(sweep) && (!node.p.from || !node.p.to)) {
284
+ add("ui-prop", bodyLine(node.l), `<Chart> 扫过的 ${sweep} 没有对应的 <Slider>,需要写 from 和 to`);
285
+ }
286
+ }
287
+ for (const child of node.c) {
288
+ if (child.t === "el" && (child.n === "Bar" || child.n === "Point") && hasSweep) {
289
+ add("ui-children", bodyLine(child.l), `<${child.n}> 只能用于数据模式的 <Chart>`);
290
+ }
291
+ }
292
+ break;
293
+ }
294
+ case "Button":
295
+ if (Boolean(node.p.set) === Boolean(node.p.reset)) add("ui-prop", bodyLine(node.l), "<Button> 的 set 和 reset 必须写且只能写一个");
296
+ break;
297
+ case "Meter":
298
+ if (Boolean(node.p.value) === Boolean(node.p.parts)) add("ui-prop", bodyLine(node.l), "<Meter> 的 value 和 parts 必须写且只能写一个");
299
+ break;
300
+ case "Table": {
301
+ const hasRows = node.c.some((child) => child.t === "el");
302
+ if (node.p.data && hasRows) add("ui-children", bodyLine(node.l), "<Table> 写了 data 就不能再写 <Row>");
303
+ if (!node.p.data && !hasRows) add("ui-children", bodyLine(node.l), "<Table> 需要 <Row> 或 data");
304
+ break;
305
+ }
306
+ case "Image":
307
+ if (node.p.src?.k === "lit" && markdownPath) {
308
+ const resolved = resolveSidecarPath(markdownPath, String(node.p.src.v));
309
+ if (resolved.error) add("ui-prop", bodyLine(node.l), `<Image> 的 src ${resolved.error}`);
310
+ }
311
+ break;
312
+ default:
313
+ break;
314
+ }
315
+
316
+ if (spec.children === "none" && node.c.length) {
317
+ add("ui-children", bodyLine(node.l), `<${node.n}> 不能有子元素`);
318
+ }
319
+ if (spec.children === "text") {
320
+ for (const child of node.c) {
321
+ const inlineOk = INLINE_TYPES.has(child.t) || (child.t === "p" && child.c.every((item) => INLINE_TYPES.has(item.t)));
322
+ if (!inlineOk && child.t !== "el") add("ui-children", bodyLine(node.l), `<${node.n}> 里只能写一段文字`);
323
+ }
324
+ }
325
+ if (Array.isArray(spec.children)) {
326
+ for (const child of node.c) {
327
+ if (child.t === "p" || child.t === "list" || child.t === "quote") {
328
+ add("ui-children", bodyLine(node.l), `<${node.n}> 里只能放 ${spec.children.map((name) => `<${name}>`).join(" / ")}`);
329
+ }
330
+ }
331
+ }
332
+
333
+ const nextChartData = node.n === "Chart" ? Boolean(node.p.data) : chartDataMode;
334
+ for (const child of node.c) staticVisit(child, effectiveParent, nextLocals, nextChartData);
335
+ };
336
+ for (const child of root.c) staticVisit(child, "root", new Set(), false);
337
+
338
+ // Data files.
339
+ const dataValues = {};
340
+ for (const item of decls.data) {
341
+ if (skipData) {
342
+ dataValues[item.name] = [];
343
+ continue;
344
+ }
345
+ if (markdownPath) {
346
+ const resolved = resolveSidecarPath(markdownPath, item.src);
347
+ if (resolved.error) {
348
+ add("ui-data", bodyLine(item.line), `Data ${item.name}:${resolved.error}`);
349
+ dataValues[item.name] = [];
350
+ continue;
351
+ }
352
+ }
353
+ const text = readData ? readData(item.src) : undefined;
354
+ if (typeof text !== "string") {
355
+ add("ui-data", bodyLine(item.line), `Data ${item.name}:读不到 ${item.src}`);
356
+ dataValues[item.name] = [];
357
+ continue;
358
+ }
359
+ const parsedData = parseDataFile(item.src, text);
360
+ if (parsedData.error) {
361
+ add("ui-data", bodyLine(item.line), `Data ${item.name}:${parsedData.error}`);
362
+ dataValues[item.name] = [];
363
+ } else {
364
+ dataValues[item.name] = parsedData.value;
365
+ }
366
+ }
367
+
368
+ const hasErrors = () => diagnostics.some((item) => item.severity === "error" && item.code !== "ui-data");
369
+ if (hasErrors()) return result({ header, root, decls, dataValues });
370
+
371
+ // Evaluation pass at the default state and at every bound step / tab.
372
+ const defaults = defaultStateValues(decls);
373
+ let elementCount = 0;
374
+
375
+ const evalTree = (stateValues, countElements) => {
376
+ const budget = createBudget(500000);
377
+ const scope = computeScope(decls, {
378
+ stateValues,
379
+ dataValues,
380
+ budget,
381
+ onError: (item, error) => add("ui-eval", bodyLine(item.line), `Let ${item.name} 算不出来:${error.message}`),
382
+ });
383
+
384
+ const evalProp = (node, name, lookup) => {
385
+ const prop = node.p[name];
386
+ if (!prop) return undefined;
387
+ if (prop.k === "lit") return prop.v;
388
+ try {
389
+ return evaluate(prop.e, lookup, budget);
390
+ } catch (error) {
391
+ add("ui-eval", bodyLine(node.l), `<${node.n}> 的 ${name} 算不出来:${error instanceof ExprError ? error.message : "出错"}`);
392
+ return undefined;
393
+ }
394
+ };
395
+
396
+ const expand = (children, lookup) => {
397
+ const output = [];
398
+ for (const child of children) {
399
+ if (child.t !== "el") continue;
400
+ if (child.n === "If") {
401
+ if (evalProp(child, "test", lookup)) output.push(...expand(child.c, lookup));
402
+ } else if (child.n === "Each") {
403
+ const items = evalProp(child, "of", lookup);
404
+ if (!Array.isArray(items)) continue;
405
+ items.slice(0, 200).forEach((item, index) => {
406
+ const locals = { [child.p.as.v]: item };
407
+ if (child.p.index?.k === "lit") locals[child.p.index.v] = index;
408
+ output.push(...expand(child.c, (name) => (Object.hasOwn(locals, name) ? { found: true, value: locals[name] } : lookup(name))));
409
+ });
410
+ } else {
411
+ output.push({ node: child, lookup });
412
+ }
413
+ }
414
+ return output;
415
+ };
416
+
417
+ const checkCount = (node, count, spec) => {
418
+ if (spec.minChildren !== undefined && count < spec.minChildren) add("ui-limit", bodyLine(node.l), `<${node.n}> 至少要 ${spec.minChildren} 个子元素`);
419
+ if (spec.maxChildren !== undefined && count > spec.maxChildren) add("ui-limit", bodyLine(node.l), `<${node.n}> 最多 ${spec.maxChildren} 个子元素`);
420
+ };
421
+
422
+ const checkTones = (node, tones, cellCount) => {
423
+ if (tones === undefined || tones === null) return;
424
+ const list = Array.isArray(tones) ? tones : [tones];
425
+ if (Array.isArray(tones) && tones.length !== cellCount) add("ui-prop", bodyLine(node.l), `<Row> 的 tones 长度要等于列数 ${cellCount}`);
426
+ for (const value of list) {
427
+ if (!TONES.includes(value)) add("ui-prop", bodyLine(node.l), `tone ${String(value)} 不存在,只能是 ${TONES.join(" / ")}`);
428
+ }
429
+ };
430
+
431
+ const visit = (node, lookup, parentContext) => {
432
+ if (node.t === "x") {
433
+ try {
434
+ evaluate(node.e, lookup, budget);
435
+ } catch (error) {
436
+ add("ui-eval", bodyLine(node.l), `插值 {${node.s}} 算不出来:${error instanceof ExprError ? error.message : "出错"}`);
437
+ }
438
+ return;
439
+ }
440
+ if (node.t !== "el") {
441
+ node.c?.forEach((child) => visit(child, lookup, parentContext));
442
+ return;
443
+ }
444
+ if (DECL_COMPONENTS.has(node.n)) return;
445
+ const spec = COMPONENTS[node.n];
446
+ if (!spec) return;
447
+
448
+ if (node.n === "If" || node.n === "Each") {
449
+ for (const item of expand([node], lookup)) visit(item.node, item.lookup, parentContext);
450
+ node.c.forEach((child) => {
451
+ if (child.t !== "el") visit(child, lookup, parentContext);
452
+ });
453
+ return;
454
+ }
455
+
456
+ if (countElements) elementCount += 1;
457
+ const values = {};
458
+ for (const [name, propSpec] of Object.entries(spec.props)) {
459
+ const prop = node.p[name];
460
+ if (!prop) continue;
461
+ const rowScope = (propSpec.rowScope && node.p.data) || (spec.rowScopeProps?.includes(name) && parentContext.chartData);
462
+ if (rowScope) continue;
463
+ values[name] = evalProp(node, name, lookup);
464
+ if (prop.k === "expr" && values[name] !== undefined) {
465
+ const problem = typeProblem(propSpec.type === "stateName" ? { type: "string" } : propSpec, values[name]);
466
+ if (problem && propSpec.type !== "any") add("ui-prop", bodyLine(node.l), `<${node.n}> 的 ${name} ${problem}`);
467
+ }
468
+ }
469
+
470
+ const childContext = { ...parentContext };
471
+ switch (node.n) {
472
+ case "Slider": {
473
+ const value = stateValues[values.bind];
474
+ const { min, max } = values;
475
+ if (typeof min === "number" && typeof max === "number") {
476
+ if (min >= max) add("ui-prop", bodyLine(node.l), "<Slider> 的 max 必须大于 min");
477
+ const scale = values.scale ?? "linear";
478
+ if (scale === "log" && min <= 0) add("ui-prop", bodyLine(node.l), "<Slider> 对数刻度的 min 必须大于 0");
479
+ if (typeof value === "number" && (value < min || value > max)) {
480
+ add("ui-prop", bodyLine(node.l), `<Slider> 的默认值 ${value} 不在 ${min}–${max} 之间`);
481
+ }
482
+ const snap = values.snap ?? (scale === "log" && isPowerOfTwo(min) && isPowerOfTwo(max) ? "pow2" : "none");
483
+ if (snap === "pow2" && (!isPowerOfTwo(min) || !isPowerOfTwo(max) || (typeof value === "number" && !isPowerOfTwo(value)))) {
484
+ add("ui-prop", bodyLine(node.l), "<Slider> 只停在 2 的幂上时,min、max 和默认值都要是 2 的幂");
485
+ }
486
+ }
487
+ break;
488
+ }
489
+ case "Choice": {
490
+ const options = values.options;
491
+ if (Array.isArray(options)) {
492
+ if (options.length < 2 || options.length > 8) add("ui-limit", bodyLine(node.l), "<Choice> 要有 2–8 个选项");
493
+ const optionValues = options.map((option) => (isPlainObject(option) ? option.value : option));
494
+ if (optionValues.some((value) => !["number", "string"].includes(typeof value))) {
495
+ add("ui-prop", bodyLine(node.l), "<Choice> 的选项只能是数字、文字或 { value, label }");
496
+ }
497
+ const current = stateValues[values.bind];
498
+ if (current !== undefined && !optionValues.includes(current)) {
499
+ add("ui-prop", bodyLine(node.l), `<Choice> 的默认值 ${String(current)} 不在选项里`);
500
+ }
501
+ }
502
+ break;
503
+ }
504
+ case "Checklist":
505
+ if (Array.isArray(values.items) && (values.items.length < 1 || values.items.length > 30)) {
506
+ add("ui-limit", bodyLine(node.l), "<Checklist> 要有 1–30 项");
507
+ }
508
+ break;
509
+ case "Stepper": {
510
+ const { min, max } = values;
511
+ if (typeof min === "number" && typeof max === "number" && min >= max) add("ui-prop", bodyLine(node.l), "<Stepper> 的 max 必须大于 min");
512
+ const current = stateValues[values.bind];
513
+ if (typeof current === "number" && typeof min === "number" && typeof max === "number" && (current < min || current > max)) {
514
+ add("ui-prop", bodyLine(node.l), `<Stepper> 的默认值 ${current} 不在 ${min}–${max} 之间`);
515
+ }
516
+ break;
517
+ }
518
+ case "Pie":
519
+ checkCount(node, expand(node.c, lookup).length, spec);
520
+ break;
521
+ case "Meter":
522
+ if (Array.isArray(values.parts) && values.parts.length > 5) add("ui-limit", bodyLine(node.l), "<Meter> 最多 5 段");
523
+ break;
524
+ case "Code":
525
+ if (typeof values.code === "string" && values.code.split("\n").length > 60) add("ui-limit", bodyLine(node.l), "<Code> 不能超过 60 行");
526
+ break;
527
+ case "Diagram":
528
+ if (typeof values.mermaid === "string" && !/^\s*(?:graph|flowchart|stateDiagram)/u.test(values.mermaid)) {
529
+ add("ui-prop", bodyLine(node.l), "<Diagram> 只支持 graph、flowchart 和 stateDiagram");
530
+ }
531
+ break;
532
+ case "Table": {
533
+ const columns = Array.isArray(values.columns) ? values.columns : [];
534
+ childContext.columns = columns.length;
535
+ if (node.p.data) {
536
+ const rows = Array.isArray(values.data) ? values.data : [];
537
+ if (rows.length > 50) add("ui-limit", bodyLine(node.l), "<Table> 最多 50 行");
538
+ if (columns.some((column) => !isPlainObject(column) || typeof column.key !== "string")) {
539
+ add("ui-prop", bodyLine(node.l), "<Table> 数据模式下每列都要写 { label, key }");
540
+ }
541
+ if (node.p.rowTone?.k === "expr") {
542
+ for (const row of rows.slice(0, 50)) {
543
+ try {
544
+ const toneValue = evaluate(node.p.rowTone.e, withRow(row, lookup), budget);
545
+ if (toneValue !== null && toneValue !== undefined && !TONES.includes(toneValue)) {
546
+ add("ui-prop", bodyLine(node.l), `rowTone 返回了不存在的 tone ${String(toneValue)}`);
547
+ break;
548
+ }
549
+ } catch (error) {
550
+ add("ui-eval", bodyLine(node.l), `<Table> 的 rowTone 算不出来:${error.message}`);
551
+ break;
552
+ }
553
+ }
554
+ }
555
+ } else {
556
+ checkCount(node, expand(node.c, lookup).length, spec);
557
+ }
558
+ break;
559
+ }
560
+ case "Grid": {
561
+ const cols = Array.isArray(values.cols) ? values.cols : [];
562
+ if (cols.length > 16) add("ui-limit", bodyLine(node.l), "<Grid> 最多 16 列");
563
+ childContext.columns = cols.length;
564
+ checkCount(node, expand(node.c, lookup).length, spec);
565
+ break;
566
+ }
567
+ case "Row": {
568
+ const cells = values.cells;
569
+ if (Array.isArray(cells) && parentContext.columns !== undefined && cells.length !== parentContext.columns) {
570
+ add("ui-prop", bodyLine(node.l), `<Row> 的 cells 有 ${cells.length} 项,表头有 ${parentContext.columns} 列`);
571
+ }
572
+ if (Array.isArray(cells)) checkTones(node, values.tones, cells.length);
573
+ if (Array.isArray(values.notes) && Array.isArray(cells) && values.notes.length !== cells.length) {
574
+ add("ui-prop", bodyLine(node.l), "<Row> 的 notes 长度要等于 cells");
575
+ }
576
+ break;
577
+ }
578
+ case "Chart": {
579
+ const series = expand(node.c, lookup);
580
+ checkCount(node, series.length, spec);
581
+ if (node.p.data) {
582
+ childContext.chartData = true;
583
+ const rows = Array.isArray(values.data) ? values.data : [];
584
+ if (rows.length > 2000) add("ui-limit", bodyLine(node.l), "<Chart> 最多 2000 个数据点");
585
+ const firstRow = rows.find(isPlainObject);
586
+ if (firstRow) {
587
+ const rowLookup = withRow(firstRow, lookup);
588
+ try {
589
+ evaluate(propExpression(node.p.x), rowLookup, budget);
590
+ } catch (error) {
591
+ add("ui-eval", bodyLine(node.l), `<Chart> 的 x 算不出来:${error.message}`);
592
+ }
593
+ for (const item of series) {
594
+ const y = item.node.p.y;
595
+ if (!y) continue;
596
+ try {
597
+ evaluate(propExpression(y), rowLookup, budget);
598
+ } catch (error) {
599
+ add("ui-eval", bodyLine(item.node.l), `<${item.node.n}> 的 y 算不出来:${error.message}`);
600
+ }
601
+ }
602
+ }
603
+ } else {
604
+ childContext.chartData = false;
605
+ const sweep = values.sweep;
606
+ const slider = sliderByState.get(sweep);
607
+ const from = values.from ?? (slider ? evalProp(slider, "min", lookup) : undefined);
608
+ const to = values.to ?? (slider ? evalProp(slider, "max", lookup) : undefined);
609
+ const scale = values.scale ?? (slider?.p.scale?.v ?? "linear");
610
+ if (typeof from === "number" && typeof to === "number") {
611
+ if (from >= to) add("ui-prop", bodyLine(node.l), "<Chart> 的 to 必须大于 from");
612
+ if (scale === "log" && from <= 0) add("ui-prop", bodyLine(node.l), "<Chart> 对数刻度的起点必须大于 0");
613
+ }
614
+ }
615
+ break;
616
+ }
617
+ case "Steps":
618
+ case "Tabs":
619
+ case "Columns":
620
+ case "Image":
621
+ checkCount(node, expand(node.c, lookup).length, spec);
622
+ break;
623
+ default:
624
+ break;
625
+ }
626
+ node.c.forEach((child) => visit(child, lookup, childContext));
627
+ };
628
+
629
+ const rootLookup = lookupFrom(scope);
630
+ root.c.forEach((child) => visit(child, rootLookup, { chartData: false }));
631
+ return { scope, expand };
632
+ };
633
+
634
+ const first = evalTree(defaults, true);
635
+ if (elementCount > MAX_ELEMENTS) add("ui-limit", bodyLine(1), `元素展开后有 ${elementCount} 个,上限 ${MAX_ELEMENTS}`);
636
+
637
+ const boundSwitchers = [];
638
+ const findSwitchers = (node) => {
639
+ if (node?.t === "el" && (node.n === "Steps" || node.n === "Tabs") && node.p.bind?.k === "lit") boundSwitchers.push(node);
640
+ node?.c?.forEach?.(findSwitchers);
641
+ };
642
+ findSwitchers(root);
643
+ for (const switcher of boundSwitchers) {
644
+ const name = switcher.p.bind.v;
645
+ if (!stateTypes.has(name)) continue;
646
+ const count = first.expand(switcher.c, lookupFrom(first.scope)).length;
647
+ for (let index = 0; index < count; index += 1) {
648
+ if (index === defaults[name]) continue;
649
+ evalTree({ ...defaults, [name]: index }, false);
650
+ }
651
+ }
652
+
653
+ if (Array.isArray(header.expect)) {
654
+ for (const failure of runExpect(decls, header.expect, { dataValues })) {
655
+ const where = headerLine(headerText, "expect", lineOffset);
656
+ const label = `expect 第 ${failure.index + 1} 条`;
657
+ if (failure.reason === "shape") add("ui-expect", where, `${label}格式不对:要写成 { given: {...}, 名字: 期望值 }`);
658
+ else if (failure.reason === "unknown-state") add("ui-expect", where, `${label}的 given 里 ${failure.name} 不是状态`);
659
+ else if (failure.reason === "unknown-name") add("ui-expect", where, `${label}里 ${failure.name} 不是状态或 Let`);
660
+ else add("ui-expect", where, `${label}:${failure.name} 期望 ${failure.expected},实际 ${failure.actual}`);
661
+ }
662
+ }
663
+
664
+ return result({ header, root, decls, dataValues });
665
+ }