soma-core 1.4.0 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/core/build/blocks/block-compile.ts +31 -2
- package/core/build/blocks/block-container.ts +2 -11
- package/core/build/compiler/page-declaration-compiler.ts +30 -2
- package/core/build/compiler/soma-precompile.js +2053 -23
- package/core/build/component/component-graph.ts +208 -0
- package/core/build/component/package-loader.ts +32 -0
- package/core/build/eject/component-eject.ts +473 -0
- package/core/build/eject/component-upgrade.ts +359 -0
- package/core/build/layout/constraint-solver.ts +235 -0
- package/core/build/layout/css-emitter.ts +116 -0
- package/core/build/layout/page-layout.ts +85 -0
- package/core/build/pack/pack-init.ts +270 -0
- package/core/client/base/SomaHttpClient.ts +34 -1
- package/core/client/base/SomaPageRootBase.ts +61 -0
- package/core/client/component/ai-catalog.ts +121 -4
- package/core/client/component/component-defaults.ts +100 -0
- package/core/client/component/component-definition.types.ts +39 -0
- package/core/client/component/component-manager.ts +79 -4
- package/core/client/component/component-pack.ts +126 -2
- package/core/client/component/keyboard-matrix.ts +144 -0
- package/core/client/component/pack-styles.ts +59 -1
- package/core/client/component/style-features.ts +131 -0
- package/core/client/component/theme-component-tokens.ts +83 -0
- package/core/client/component/verify-pack.ts +120 -1
- package/core/client/container/SomaContainerAdapter.ts +6 -2
- package/core/client/data/data-object-resolver.ts +407 -4
- package/core/client/data/reaction-engine.ts +176 -0
- package/core/client/data/window-engine.ts +477 -0
- package/core/client/engine/event-engine.ts +98 -0
- package/core/client/engine/soma-bootstrap.ts +265 -5
- package/core/client/engine/step-runner.ts +134 -0
- package/core/client/infra/http/SomaHttpService.ts +2 -2
- package/core/client/parser/blocks/page-parser.ts +15 -1
- package/core/client/parser/blocks/use-parser.ts +5 -12
- package/core/client/parser/data-config-parser.ts +316 -8
- package/core/client/parser/duration.ts +16 -0
- package/core/client/parser/layout-parser.ts +157 -0
- package/core/client/parser/page-state-parser.ts +166 -0
- package/core/client/parser/pipeline-parser.ts +76 -1
- package/core/client/parser/reaction-parser.ts +459 -0
- package/core/client/parser/reaction-sugar.ts +47 -0
- package/core/client/parser/step-parser.ts +359 -0
- package/core/client/parser/ui-config-parser.ts +59 -0
- package/core/client/parser/window-parser.ts +294 -0
- package/core/client/theme/theme-engine.ts +102 -2
- package/core/index.ts +184 -0
- package/core/shared/block-errors.ts +11 -0
- package/core/shared/calc/coerce.ts +29 -0
- package/core/shared/calc/errors.ts +43 -0
- package/core/shared/calc/evaluator.ts +101 -0
- package/core/shared/calc/index.ts +12 -0
- package/core/shared/calc/lexer.ts +194 -0
- package/core/shared/calc/parser.ts +204 -0
- package/core/shared/calc/typer.ts +184 -0
- package/core/shared/component/derive-sample.ts +105 -0
- package/core/shared/component/field-lines.ts +473 -0
- package/core/shared/path-algebra.ts +169 -0
- package/core/shared/predicates/index.ts +527 -0
- package/core/shared/types/component-contract.types.ts +151 -9
- package/core/shared/types/data-config.types.ts +120 -1
- package/core/shared/types/domain.types.ts +13 -0
- package/core/shared/types/event.types.ts +22 -2
- package/core/shared/types/layout-constraint.types.ts +73 -0
- package/core/shared/types/page-state.types.ts +60 -0
- package/core/shared/types/reaction.types.ts +144 -0
- package/core/shared/types/step.types.ts +91 -0
- package/core/shared/types/ui-config.types.ts +18 -0
- package/core/shared/types/window.types.ts +177 -0
- package/dist/cli/soma.js +13 -1
- package/dist/core/index.cjs +5529 -631
- package/dist/types/build/blocks/block-container.d.ts +1 -6
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
- package/dist/types/build/component/component-graph.d.ts +85 -0
- package/dist/types/build/eject/component-eject.d.ts +121 -0
- package/dist/types/build/eject/component-upgrade.d.ts +43 -0
- package/dist/types/build/layout/constraint-solver.d.ts +36 -0
- package/dist/types/build/layout/css-emitter.d.ts +18 -0
- package/dist/types/build/layout/page-layout.d.ts +24 -0
- package/dist/types/build/pack/pack-init.d.ts +8 -0
- package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
- package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
- package/dist/types/client/component/ai-catalog.d.ts +33 -1
- package/dist/types/client/component/component-defaults.d.ts +15 -0
- package/dist/types/client/component/component-definition.types.d.ts +38 -0
- package/dist/types/client/component/component-manager.d.ts +36 -0
- package/dist/types/client/component/component-pack.d.ts +32 -2
- package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
- package/dist/types/client/component/pack-styles.d.ts +21 -0
- package/dist/types/client/component/style-features.d.ts +26 -0
- package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
- package/dist/types/client/component/verify-pack.d.ts +10 -0
- package/dist/types/client/data/data-object-resolver.d.ts +106 -1
- package/dist/types/client/data/reaction-engine.d.ts +21 -0
- package/dist/types/client/data/window-engine.d.ts +27 -0
- package/dist/types/client/engine/event-engine.d.ts +15 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
- package/dist/types/client/engine/step-runner.d.ts +24 -0
- package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
- package/dist/types/client/parser/duration.d.ts +1 -0
- package/dist/types/client/parser/layout-parser.d.ts +9 -0
- package/dist/types/client/parser/page-state-parser.d.ts +32 -0
- package/dist/types/client/parser/reaction-parser.d.ts +16 -0
- package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
- package/dist/types/client/parser/step-parser.d.ts +23 -0
- package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
- package/dist/types/client/parser/window-parser.d.ts +25 -0
- package/dist/types/client/theme/theme-engine.d.ts +26 -0
- package/dist/types/index.d.ts +35 -2
- package/dist/types/shared/block-errors.d.ts +5 -0
- package/dist/types/shared/calc/coerce.d.ts +4 -0
- package/dist/types/shared/calc/errors.d.ts +14 -0
- package/dist/types/shared/calc/evaluator.d.ts +2 -0
- package/dist/types/shared/calc/index.d.ts +6 -0
- package/dist/types/shared/calc/lexer.d.ts +20 -0
- package/dist/types/shared/calc/parser.d.ts +49 -0
- package/dist/types/shared/calc/typer.d.ts +16 -0
- package/dist/types/shared/component/derive-sample.d.ts +23 -0
- package/dist/types/shared/component/field-lines.d.ts +19 -0
- package/dist/types/shared/path-algebra.d.ts +56 -0
- package/dist/types/shared/predicates/index.d.ts +79 -0
- package/dist/types/shared/types/component-contract.types.d.ts +134 -6
- package/dist/types/shared/types/data-config.types.d.ts +115 -1
- package/dist/types/shared/types/domain.types.d.ts +12 -0
- package/dist/types/shared/types/event.types.d.ts +8 -2
- package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
- package/dist/types/shared/types/page-state.types.d.ts +49 -0
- package/dist/types/shared/types/reaction.types.d.ts +115 -0
- package/dist/types/shared/types/step.types.d.ts +76 -0
- package/dist/types/shared/types/ui-config.types.d.ts +18 -0
- package/dist/types/shared/types/window.types.d.ts +171 -0
- package/package.json +3 -2
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
// 字段行文法(REQ-012):契约里 props / emits / slots 的文本块写法。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不是 YAML 嵌套对象:一个 prop 写全 type / desc / required / default / example
|
|
4
|
+
// 五件事,YAML 要五行或一行花括号;三层嵌套之后没人读得下去,于是大家退回
|
|
5
|
+
// `desc: '地址事实 { id, name, phone?, full }'` 这种花括号提示——那串东西机器读不出
|
|
6
|
+
// 字段、读不出类型、读不出示例,展示页与 AI 都拿它没办法。
|
|
7
|
+
//
|
|
8
|
+
// 文法只有一条:**一行一个字段,缩进即嵌套**。
|
|
9
|
+
//
|
|
10
|
+
// 名: 类型, 描述, 必填 或 默认 x, 示例 y, 双向
|
|
11
|
+
//
|
|
12
|
+
// · 类型:string | number | boolean | enum(a|b|c) | object | array<类型>
|
|
13
|
+
// · 名与类型必有;必填 与 默认 二选一(规则 C4);示例可省,省了样张取默认值
|
|
14
|
+
// · object → 下一级缩进写它的字段;array<object> → 下一级写元素字段;array<标量> 不下钻
|
|
15
|
+
// · 分隔符是 ASCII 的 `, `;中文描述里的全角「,」不受影响
|
|
16
|
+
// · 示例放在最后,从 `示例 ` 之后整段取值,所以示例里可以有逗号、冒号、空格
|
|
17
|
+
// · 行首 # 是注释;缩进固定两个空格,禁止 Tab
|
|
18
|
+
//
|
|
19
|
+
// 解析结果就是既有的契约结构(type / desc / required / default / example + fields / items),
|
|
20
|
+
// 所以对象写法与文本块写法在契约层面无差别:这是一种写法,不是第二套契约。
|
|
21
|
+
|
|
22
|
+
import type {
|
|
23
|
+
SomaContractEmit,
|
|
24
|
+
SomaContractField,
|
|
25
|
+
SomaContractProp,
|
|
26
|
+
SomaContractPropType,
|
|
27
|
+
SomaContractSlot,
|
|
28
|
+
} from '../types/component-contract.types';
|
|
29
|
+
|
|
30
|
+
const INDENT_UNIT = 2;
|
|
31
|
+
const PROP_TYPES = new Set<SomaContractPropType>([
|
|
32
|
+
'string', 'number', 'boolean', 'enum', 'object', 'array',
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
export class SomaFieldLinesError extends Error {
|
|
36
|
+
constructor(message: string, readonly line: number) {
|
|
37
|
+
super(`字段行第 ${line} 行:${message}`);
|
|
38
|
+
this.name = 'SomaFieldLinesError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface RawLine {
|
|
43
|
+
/** 文本块内的行号(1 起,含注释与空行),报错用 */
|
|
44
|
+
line: number;
|
|
45
|
+
depth: number;
|
|
46
|
+
name: string;
|
|
47
|
+
/** 冒号之后的整段,未切分 */
|
|
48
|
+
rest: string;
|
|
49
|
+
children: RawLine[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ── 词法:按缩进切树 ────────────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
function tokenize(text: string): RawLine[] {
|
|
55
|
+
const roots: RawLine[] = [];
|
|
56
|
+
const stack: RawLine[] = [];
|
|
57
|
+
|
|
58
|
+
const lines = text.split('\n');
|
|
59
|
+
|
|
60
|
+
// 去掉整块的公共缩进。
|
|
61
|
+
//
|
|
62
|
+
// 文本块有两个来源,基准缩进天生不同:`contract.yaml` 的 `|` 块被 YAML 解析器
|
|
63
|
+
// 剥到 0 列,而 TS 里的标签模板跟着代码缩进走(写在 `props:` 下面就是 6 或 8 列)。
|
|
64
|
+
// 按绝对列数判层级的话,同一段文本在两处会得到不同的树——TS 那侧首行直接
|
|
65
|
+
// 被判成「缩进跳级」。层级是**相对**的,所以先把公共前缀减掉。
|
|
66
|
+
let baseIndent = Infinity;
|
|
67
|
+
for (const raw of lines) {
|
|
68
|
+
if (!raw.trim() || raw.trimStart().startsWith('#')) continue;
|
|
69
|
+
baseIndent = Math.min(baseIndent, raw.length - raw.trimStart().length);
|
|
70
|
+
}
|
|
71
|
+
if (!Number.isFinite(baseIndent)) baseIndent = 0;
|
|
72
|
+
|
|
73
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
74
|
+
const raw = lines[i];
|
|
75
|
+
const lineNo = i + 1;
|
|
76
|
+
if (!raw.trim()) continue;
|
|
77
|
+
if (raw.trimStart().startsWith('#')) continue;
|
|
78
|
+
if (raw.includes('\t')) {
|
|
79
|
+
throw new SomaFieldLinesError('不能用 Tab 缩进——缩进固定两个空格', lineNo);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const spaces = raw.length - raw.trimStart().length - baseIndent;
|
|
83
|
+
if (spaces % INDENT_UNIT !== 0) {
|
|
84
|
+
throw new SomaFieldLinesError(`缩进比同块首层多 ${spaces} 个空格,不是 ${INDENT_UNIT} 的倍数`, lineNo);
|
|
85
|
+
}
|
|
86
|
+
const depth = spaces / INDENT_UNIT;
|
|
87
|
+
|
|
88
|
+
const body = raw.trim();
|
|
89
|
+
const colon = body.indexOf(':');
|
|
90
|
+
if (colon <= 0) {
|
|
91
|
+
throw new SomaFieldLinesError(`缺少冒号——写法是「名: 类型, 描述, …」,实际是 "${body}"`, lineNo);
|
|
92
|
+
}
|
|
93
|
+
const name = body.slice(0, colon).trim();
|
|
94
|
+
const rest = body.slice(colon + 1).trim();
|
|
95
|
+
if (!/^[a-z][a-z0-9_]*$/.test(name)) {
|
|
96
|
+
throw new SomaFieldLinesError(`名字 "${name}" 非法——只允许 ^[a-z][a-z0-9_]*$(它是运行时数据键)`, lineNo);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const node: RawLine = { line: lineNo, depth, name, rest, children: [] };
|
|
100
|
+
while (stack.length > 0 && stack[stack.length - 1].depth >= depth) stack.pop();
|
|
101
|
+
if (depth === 0) {
|
|
102
|
+
roots.push(node);
|
|
103
|
+
} else {
|
|
104
|
+
const parent = stack[stack.length - 1];
|
|
105
|
+
if (!parent || parent.depth !== depth - 1) {
|
|
106
|
+
throw new SomaFieldLinesError('缩进跳级——子字段只能比父字段深一级', lineNo);
|
|
107
|
+
}
|
|
108
|
+
parent.children.push(node);
|
|
109
|
+
}
|
|
110
|
+
stack.push(node);
|
|
111
|
+
}
|
|
112
|
+
return roots;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ── 值文法:YAML 流式标量与集合的最小子集 ──────────────────────────────────
|
|
116
|
+
//
|
|
117
|
+
// 只认 `""` / `[]` / `{}` / `[a, b]` / `{ k: v }` / 数字 / true / false / null / 裸串。
|
|
118
|
+
// 不引 js-yaml:这个模块要能被客户端侧引用,而 examples 的取值范围就这么大。
|
|
119
|
+
|
|
120
|
+
function parseValue(raw: string, line: number): unknown {
|
|
121
|
+
const text = raw.trim();
|
|
122
|
+
if (!text) return '';
|
|
123
|
+
if (text === 'null' || text === '~') return null;
|
|
124
|
+
if (text === 'true') return true;
|
|
125
|
+
if (text === 'false') return false;
|
|
126
|
+
if (/^-?\d+(\.\d+)?$/.test(text)) return Number(text);
|
|
127
|
+
if ((text.startsWith('"') && text.endsWith('"') && text.length >= 2)
|
|
128
|
+
|| (text.startsWith("'") && text.endsWith("'") && text.length >= 2)) {
|
|
129
|
+
return text.slice(1, -1);
|
|
130
|
+
}
|
|
131
|
+
if (text.startsWith('[') && text.endsWith(']')) {
|
|
132
|
+
const inner = text.slice(1, -1).trim();
|
|
133
|
+
if (!inner) return [];
|
|
134
|
+
return splitFlow(inner, line).map((item) => parseValue(item, line));
|
|
135
|
+
}
|
|
136
|
+
if (text.startsWith('{') && text.endsWith('}')) {
|
|
137
|
+
const inner = text.slice(1, -1).trim();
|
|
138
|
+
if (!inner) return {};
|
|
139
|
+
const out: Record<string, unknown> = {};
|
|
140
|
+
for (const pair of splitFlow(inner, line)) {
|
|
141
|
+
const colon = pair.indexOf(':');
|
|
142
|
+
if (colon <= 0) throw new SomaFieldLinesError(`流式对象里的 "${pair}" 缺少冒号`, line);
|
|
143
|
+
out[unquote(pair.slice(0, colon).trim())] = parseValue(pair.slice(colon + 1), line);
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
return text;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function unquote(key: string): string {
|
|
151
|
+
if (key.length >= 2 && ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'")))) {
|
|
152
|
+
return key.slice(1, -1);
|
|
153
|
+
}
|
|
154
|
+
return key;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 按顶层逗号切分流式集合内部(括号内的逗号不切) */
|
|
158
|
+
function splitFlow(inner: string, line: number): string[] {
|
|
159
|
+
const parts: string[] = [];
|
|
160
|
+
let depth = 0;
|
|
161
|
+
let quote: string | null = null;
|
|
162
|
+
let start = 0;
|
|
163
|
+
for (let i = 0; i < inner.length; i += 1) {
|
|
164
|
+
const ch = inner[i];
|
|
165
|
+
if (quote) {
|
|
166
|
+
if (ch === quote) quote = null;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
|
170
|
+
if (ch === '[' || ch === '{') depth += 1;
|
|
171
|
+
else if (ch === ']' || ch === '}') depth -= 1;
|
|
172
|
+
else if (ch === ',' && depth === 0) {
|
|
173
|
+
parts.push(inner.slice(start, i).trim());
|
|
174
|
+
start = i + 1;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (depth !== 0) throw new SomaFieldLinesError(`流式集合括号不配对:"${inner}"`, line);
|
|
178
|
+
parts.push(inner.slice(start).trim());
|
|
179
|
+
return parts.filter((part) => part.length > 0);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 把已解析的值按字段类型收口(文本块里 `示例 1299.00` 在 number 字段上要是数字) */
|
|
183
|
+
function coerce(value: unknown, type: SomaContractPropType): unknown {
|
|
184
|
+
if (type === 'number' && typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) {
|
|
185
|
+
return Number(value);
|
|
186
|
+
}
|
|
187
|
+
if (type === 'boolean' && typeof value === 'string') {
|
|
188
|
+
if (value.trim() === 'true') return true;
|
|
189
|
+
if (value.trim() === 'false') return false;
|
|
190
|
+
}
|
|
191
|
+
if (type === 'array' && !Array.isArray(value) && value !== undefined && value !== '') {
|
|
192
|
+
// `示例 顺丰包邮` 写在标量数组上 = 一个元素
|
|
193
|
+
return [value];
|
|
194
|
+
}
|
|
195
|
+
return value;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ── 类型段 ─────────────────────────────────────────────────────────────────
|
|
199
|
+
|
|
200
|
+
interface ParsedType {
|
|
201
|
+
type: SomaContractPropType;
|
|
202
|
+
values?: (string | number)[];
|
|
203
|
+
/** array<标量> 的元素类型;array<object> 时为 'object' */
|
|
204
|
+
itemType?: SomaContractPropType;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function parseType(raw: string, line: number): ParsedType {
|
|
208
|
+
const text = raw.trim();
|
|
209
|
+
const enumMatch = /^enum\((.*)\)$/.exec(text);
|
|
210
|
+
if (enumMatch) {
|
|
211
|
+
const values = enumMatch[1].split('|').map((item) => item.trim()).filter(Boolean);
|
|
212
|
+
if (values.length === 0) throw new SomaFieldLinesError('enum(...) 里一个取值都没有', line);
|
|
213
|
+
return { type: 'enum', values };
|
|
214
|
+
}
|
|
215
|
+
const arrayMatch = /^array(?:<(.+)>)?$/.exec(text);
|
|
216
|
+
if (arrayMatch) {
|
|
217
|
+
const inner = arrayMatch[1]?.trim();
|
|
218
|
+
if (!inner) return { type: 'array' };
|
|
219
|
+
if (!PROP_TYPES.has(inner as SomaContractPropType)) {
|
|
220
|
+
throw new SomaFieldLinesError(
|
|
221
|
+
`array<${inner}> 的元素类型非法——只允许 ${[...PROP_TYPES].join(' | ')}`,
|
|
222
|
+
line,
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return { type: 'array', itemType: inner as SomaContractPropType };
|
|
226
|
+
}
|
|
227
|
+
if (!PROP_TYPES.has(text as SomaContractPropType)) {
|
|
228
|
+
throw new SomaFieldLinesError(
|
|
229
|
+
`类型 "${text}" 非法——只允许 string | number | boolean | enum(a|b|c) | object | array<类型>`,
|
|
230
|
+
line,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
return { type: text as SomaContractPropType };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ── 字段行 ─────────────────────────────────────────────────────────────────
|
|
237
|
+
|
|
238
|
+
/** 切分 `类型, 描述, 修饰…`;`示例 ` 之后整段归示例(可含逗号冒号空格) */
|
|
239
|
+
function splitSegments(rest: string, line: number): string[] {
|
|
240
|
+
const parts = rest.split(', ');
|
|
241
|
+
const exampleAt = parts.findIndex((part) => part.startsWith('示例 ') || part === '示例');
|
|
242
|
+
if (exampleAt < 0) return parts.map((part) => part.trim());
|
|
243
|
+
const head = parts.slice(0, exampleAt).map((part) => part.trim());
|
|
244
|
+
const example = parts.slice(exampleAt).join(', ').trim();
|
|
245
|
+
if (example === '示例') throw new SomaFieldLinesError('「示例」后面没有值', line);
|
|
246
|
+
return [...head, example];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function buildField(node: RawLine, isProp: boolean): SomaContractProp {
|
|
250
|
+
const segments = splitSegments(node.rest, node.line);
|
|
251
|
+
if (segments.length === 0 || !segments[0]) {
|
|
252
|
+
throw new SomaFieldLinesError(`字段 "${node.name}" 没有类型`, node.line);
|
|
253
|
+
}
|
|
254
|
+
const parsedType = parseType(segments[0], node.line);
|
|
255
|
+
const field: SomaContractProp = { type: parsedType.type };
|
|
256
|
+
if (parsedType.values) field.values = parsedType.values;
|
|
257
|
+
|
|
258
|
+
if (segments.length >= 2 && segments[1] && !isModifier(segments[1])) {
|
|
259
|
+
field.desc = segments[1];
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const modifiers = segments.slice(field.desc === undefined ? 1 : 2);
|
|
263
|
+
for (const modifier of modifiers) {
|
|
264
|
+
if (!modifier) continue;
|
|
265
|
+
if (modifier === '必填') {
|
|
266
|
+
field.required = true;
|
|
267
|
+
} else if (modifier === '双向') {
|
|
268
|
+
if (!isProp) throw new SomaFieldLinesError('「双向」只能写在 prop 一层', node.line);
|
|
269
|
+
field.mode = 'model';
|
|
270
|
+
} else if (modifier.startsWith('默认 ')) {
|
|
271
|
+
field.default = coerce(parseValue(modifier.slice('默认 '.length), node.line), field.type);
|
|
272
|
+
} else if (modifier.startsWith('示例 ')) {
|
|
273
|
+
field.example = coerce(parseValue(modifier.slice('示例 '.length), node.line), field.type);
|
|
274
|
+
} else {
|
|
275
|
+
throw new SomaFieldLinesError(
|
|
276
|
+
`修饰 "${modifier}" 不认识——只有 必填 / 默认 x / 示例 y / 双向(描述里若要写逗号请用全角「,」)`,
|
|
277
|
+
node.line,
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (field.required === true && field.default !== undefined) {
|
|
283
|
+
throw new SomaFieldLinesError(`字段 "${node.name}" 同时写了 必填 与 默认——二选一`, node.line);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// 子字段:object 挂 fields,array<object> 挂 items.fields
|
|
287
|
+
if (field.type === 'object') {
|
|
288
|
+
if (node.children.length > 0) {
|
|
289
|
+
field.fields = buildFieldMap(node.children, false);
|
|
290
|
+
}
|
|
291
|
+
} else if (field.type === 'array') {
|
|
292
|
+
const itemType = parsedType.itemType;
|
|
293
|
+
if (node.children.length > 0) {
|
|
294
|
+
if (itemType !== undefined && itemType !== 'object') {
|
|
295
|
+
throw new SomaFieldLinesError(
|
|
296
|
+
`array<${itemType}> 是标量数组,不该有下一级字段——要写元素字段请用 array<object>`,
|
|
297
|
+
node.line,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
field.items = { type: 'object', fields: buildFieldMap(node.children, false) };
|
|
301
|
+
} else if (itemType) {
|
|
302
|
+
field.items = { type: itemType };
|
|
303
|
+
}
|
|
304
|
+
} else if (node.children.length > 0) {
|
|
305
|
+
throw new SomaFieldLinesError(
|
|
306
|
+
`字段 "${node.name}" 是 ${field.type},不能有下一级——只有 object 与 array<object> 可以下钻`,
|
|
307
|
+
node.line,
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return field;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function isModifier(segment: string): boolean {
|
|
315
|
+
return segment === '必填' || segment === '双向'
|
|
316
|
+
|| segment.startsWith('默认 ') || segment.startsWith('示例 ');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function buildFieldMap(nodes: RawLine[], isProp: boolean): Record<string, SomaContractField> {
|
|
320
|
+
const out: Record<string, SomaContractField> = {};
|
|
321
|
+
for (const node of nodes) {
|
|
322
|
+
if (out[node.name]) throw new SomaFieldLinesError(`字段 "${node.name}" 重复`, node.line);
|
|
323
|
+
out[node.name] = buildField(node, isProp);
|
|
324
|
+
}
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** props 文本块 → 契约 props */
|
|
329
|
+
export function parseFieldLines(text: string): Record<string, SomaContractProp> {
|
|
330
|
+
return buildFieldMap(tokenize(text), true) as Record<string, SomaContractProp>;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** emits 文本块 → 契约 emits。事件行是 `名: 描述`,下一级是载荷行 `名: 类型, 描述` */
|
|
334
|
+
export function parseEmitLines(text: string): Record<string, SomaContractEmit> {
|
|
335
|
+
const out: Record<string, SomaContractEmit> = {};
|
|
336
|
+
for (const node of tokenize(text)) {
|
|
337
|
+
if (out[node.name]) throw new SomaFieldLinesError(`事件 "${node.name}" 重复`, node.line);
|
|
338
|
+
const emit: SomaContractEmit = {};
|
|
339
|
+
if (node.rest) emit.desc = node.rest;
|
|
340
|
+
if (node.children.length > 0) {
|
|
341
|
+
emit.payload = {};
|
|
342
|
+
for (const child of node.children) {
|
|
343
|
+
const segments = splitSegments(child.rest, child.line);
|
|
344
|
+
if (!segments[0]) throw new SomaFieldLinesError(`载荷 "${child.name}" 没有类型`, child.line);
|
|
345
|
+
const parsed = parseType(segments[0], child.line);
|
|
346
|
+
emit.payload[child.name] = {
|
|
347
|
+
type: parsed.type,
|
|
348
|
+
...(segments[1] && !isModifier(segments[1]) ? { desc: segments[1] } : {}),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
out[node.name] = emit;
|
|
353
|
+
}
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** slots 文本块 → 契约 slots。插槽行是 `名: 描述, 必填`(必填可省) */
|
|
358
|
+
export function parseSlotLines(text: string): Record<string, SomaContractSlot> {
|
|
359
|
+
const out: Record<string, SomaContractSlot> = {};
|
|
360
|
+
for (const node of tokenize(text)) {
|
|
361
|
+
if (out[node.name]) throw new SomaFieldLinesError(`插槽 "${node.name}" 重复`, node.line);
|
|
362
|
+
if (node.children.length > 0) {
|
|
363
|
+
throw new SomaFieldLinesError(`插槽 "${node.name}" 不能有下一级`, node.line);
|
|
364
|
+
}
|
|
365
|
+
const segments = node.rest.split(', ').map((part) => part.trim()).filter(Boolean);
|
|
366
|
+
const slot: SomaContractSlot = {};
|
|
367
|
+
const desc = segments.filter((part) => part !== '必填').join(',');
|
|
368
|
+
if (desc) slot.desc = desc;
|
|
369
|
+
if (segments.includes('必填')) slot.required = true;
|
|
370
|
+
out[node.name] = slot;
|
|
371
|
+
}
|
|
372
|
+
return out;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ── 反向渲染:契约 → 字段行原文 ────────────────────────────────────────────
|
|
376
|
+
//
|
|
377
|
+
// 目录直接打印这段文本,不再另生成一张字段表:作者写的和读者读到的是同一份东西。
|
|
378
|
+
|
|
379
|
+
function renderValue(value: unknown): string {
|
|
380
|
+
if (value === null) return 'null';
|
|
381
|
+
if (typeof value === 'string') return value === '' ? '""' : value;
|
|
382
|
+
if (Array.isArray(value)) return `[${value.map(renderValue).join(', ')}]`;
|
|
383
|
+
if (typeof value === 'object') {
|
|
384
|
+
const entries = Object.entries(value as Record<string, unknown>);
|
|
385
|
+
if (entries.length === 0) return '{}';
|
|
386
|
+
return `{ ${entries.map(([key, item]) => `${key}: ${renderValue(item)}`).join(', ')} }`;
|
|
387
|
+
}
|
|
388
|
+
return String(value);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function renderTypeLabel(field: SomaContractField): string {
|
|
392
|
+
if (field.type === 'enum') return `enum(${(field.values ?? []).join('|')})`;
|
|
393
|
+
if (field.type === 'array') {
|
|
394
|
+
const itemType = field.items?.type;
|
|
395
|
+
return itemType ? `array<${itemType}>` : 'array';
|
|
396
|
+
}
|
|
397
|
+
return field.type;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function renderFieldNode(name: string, field: SomaContractField, depth: number, out: string[]): void {
|
|
401
|
+
const segments: string[] = [renderTypeLabel(field)];
|
|
402
|
+
if (field.desc) segments.push(field.desc);
|
|
403
|
+
if (field.required === true) segments.push('必填');
|
|
404
|
+
else if (field.default !== undefined) segments.push(`默认 ${renderValue(field.default)}`);
|
|
405
|
+
if (field.example !== undefined) segments.push(`示例 ${renderValue(field.example)}`);
|
|
406
|
+
if ((field as SomaContractProp).mode === 'model') segments.push('双向');
|
|
407
|
+
|
|
408
|
+
out.push(`${' '.repeat(depth * INDENT_UNIT)}${name}: ${segments.join(', ')}`);
|
|
409
|
+
|
|
410
|
+
const children = field.type === 'array' ? field.items?.fields : field.fields;
|
|
411
|
+
for (const [childName, child] of Object.entries(children ?? {})) {
|
|
412
|
+
renderFieldNode(childName, child, depth + 1, out);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** 契约 props(或任意字段表)→ 字段行文本块 */
|
|
417
|
+
export function renderFieldLines(fields: Record<string, SomaContractField>): string {
|
|
418
|
+
const out: string[] = [];
|
|
419
|
+
for (const [name, field] of Object.entries(fields ?? {})) {
|
|
420
|
+
renderFieldNode(name, field, 0, out);
|
|
421
|
+
}
|
|
422
|
+
return out.join('\n');
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ── TS 形态入口 ────────────────────────────────────────────────────────────
|
|
426
|
+
|
|
427
|
+
function raw(strings: TemplateStringsArray, values: unknown[]): string {
|
|
428
|
+
return strings.reduce((acc, part, i) => acc + part + (i < values.length ? String(values[i]) : ''), '');
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* 按调用点缓存解析结果。
|
|
433
|
+
*
|
|
434
|
+
* JS 引擎对同一个标签模板调用点复用同一个 `TemplateStringsArray` 实例,所以它就是
|
|
435
|
+
* 天然的调用点身份。`createXxxDef()` 在一次进程里会被调多次(Host 装配一次、
|
|
436
|
+
* 目录生成一次、测试里更多),没有这层缓存就每次重解析一遍同样的文本。
|
|
437
|
+
*
|
|
438
|
+
* 只对**无插值**的模板缓存:带 `${}` 的模板同一个调用点可能产出不同文本。
|
|
439
|
+
*/
|
|
440
|
+
const PARSE_CACHE = new WeakMap<TemplateStringsArray, unknown>();
|
|
441
|
+
|
|
442
|
+
function cached<T>(strings: TemplateStringsArray, values: unknown[], parse: (text: string) => T): T {
|
|
443
|
+
if (values.length > 0) return parse(raw(strings, values));
|
|
444
|
+
const hit = PARSE_CACHE.get(strings);
|
|
445
|
+
if (hit !== undefined) return hit as T;
|
|
446
|
+
const parsed = parse(raw(strings, values));
|
|
447
|
+
PARSE_CACHE.set(strings, parsed);
|
|
448
|
+
return parsed;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** TS 组件里写同一段文本:`props: somaFields\`…\`` */
|
|
452
|
+
export function somaFields(
|
|
453
|
+
strings: TemplateStringsArray,
|
|
454
|
+
...values: unknown[]
|
|
455
|
+
): Record<string, SomaContractProp> {
|
|
456
|
+
return cached(strings, values, parseFieldLines);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** TS 组件里写事件文本块 */
|
|
460
|
+
export function somaEmits(
|
|
461
|
+
strings: TemplateStringsArray,
|
|
462
|
+
...values: unknown[]
|
|
463
|
+
): Record<string, SomaContractEmit> {
|
|
464
|
+
return cached(strings, values, parseEmitLines);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** TS 组件里写插槽文本块 */
|
|
468
|
+
export function somaSlots(
|
|
469
|
+
strings: TemplateStringsArray,
|
|
470
|
+
...values: unknown[]
|
|
471
|
+
): Record<string, SomaContractSlot> {
|
|
472
|
+
return cached(strings, values, parseSlotLines);
|
|
473
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// 列表路径代数(REQ-010 F-11)——让一条反应作用在「每一项」上。
|
|
2
|
+
//
|
|
3
|
+
// ── 要解决的问题 ──────────────────────────────────────────────────────
|
|
4
|
+
// 明细行里的联动(「这一行选了折扣,这一行的折扣率就必填」)今天写不出来:
|
|
5
|
+
// 反应图的字段是**顶层**字段名,而明细行的字段住在 `items[3].discount` 这种位置上。
|
|
6
|
+
// 结果是列表内的联动只能回到组件里手写,而那正是反应图要消灭的东西。
|
|
7
|
+
//
|
|
8
|
+
// 三种形态,闭集:
|
|
9
|
+
//
|
|
10
|
+
// | 写法 | 意思 | 展开成 |
|
|
11
|
+
// |---|---|---|
|
|
12
|
+
// | `items[*].x` | 每一项的 x | 逐项一条,项数由运行期值决定 |
|
|
13
|
+
// | `items[..].x` | 同一项内的 x(在项作用域里写反应时用) | 当前项的 x |
|
|
14
|
+
// | `items[+1].x` | 下一项的 x(比如"结束日不能早于下一段的开始日") | 第 i+1 项 |
|
|
15
|
+
//
|
|
16
|
+
// 刻意**不做**的:分组(`items[status=paid].x`)、排除(`items[!0].x`)、
|
|
17
|
+
// 前缀匹配。它们都要求在展开期知道运行期的值,那等于把求值搬进编译期——
|
|
18
|
+
// 一旦开这个口,「这条反应会牵动谁」就重新变成一个运行期才有答案的问题,
|
|
19
|
+
// 而静态可回溯正是反应图存在的理由。
|
|
20
|
+
|
|
21
|
+
/** 三种形态的判别式 */
|
|
22
|
+
export type SomaPathSelector =
|
|
23
|
+
| { kind: 'each' } // [*]
|
|
24
|
+
| { kind: 'self' } // [..]
|
|
25
|
+
| { kind: 'offset'; delta: number }; // [+1] / [-1]
|
|
26
|
+
|
|
27
|
+
export interface SomaListPath {
|
|
28
|
+
/** 列表字段名(`items`) */
|
|
29
|
+
list: string;
|
|
30
|
+
selector: SomaPathSelector;
|
|
31
|
+
/** 项内字段名(`discount`);支持多级 `a.b` */
|
|
32
|
+
field: string;
|
|
33
|
+
/** 原样保留,报错时回指作者写的那串 */
|
|
34
|
+
source: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const PATH_PATTERN = /^([a-z][a-z0-9_]*)\[(\*|\.\.|[+-]\d+)\]\.([a-z][a-z0-9_.]*)$/i;
|
|
38
|
+
|
|
39
|
+
/** 一个引用是不是列表路径(不是的话按普通顶层字段处理) */
|
|
40
|
+
export function isListPath(reference: string): boolean {
|
|
41
|
+
return PATH_PATTERN.test(reference);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class SomaPathError extends Error {
|
|
45
|
+
constructor(message: string) {
|
|
46
|
+
super(`[SOMA Path] ${message}`);
|
|
47
|
+
this.name = 'SomaPathError';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function parseListPath(reference: string): SomaListPath {
|
|
52
|
+
const match = PATH_PATTERN.exec(reference);
|
|
53
|
+
if (!match) {
|
|
54
|
+
throw new SomaPathError(
|
|
55
|
+
`"${reference}" 不是合法的列表路径。三种形态:`
|
|
56
|
+
+ '`items[*].x`(每一项)/ `items[..].x`(同一项)/ `items[+1].x`(下一项)。'
|
|
57
|
+
+ '不支持分组、排除与前缀匹配——那些要在展开期知道运行期的值,'
|
|
58
|
+
+ '等于把求值搬进编译期,而静态可回溯正是反应图存在的理由。',
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
const [, list, selectorRaw, field] = match;
|
|
62
|
+
let selector: SomaPathSelector;
|
|
63
|
+
if (selectorRaw === '*') selector = { kind: 'each' };
|
|
64
|
+
else if (selectorRaw === '..') selector = { kind: 'self' };
|
|
65
|
+
else {
|
|
66
|
+
const delta = Number(selectorRaw);
|
|
67
|
+
if (delta === 0) {
|
|
68
|
+
// `[+0]` 与 `[..]` 是同一件事,但写成两种会让读的人以为有区别
|
|
69
|
+
throw new SomaPathError(`"${reference}" 的偏移是 0——同一项请写 \`${list}[..].${field}\``);
|
|
70
|
+
}
|
|
71
|
+
selector = { kind: 'offset', delta };
|
|
72
|
+
}
|
|
73
|
+
return { list, selector, field, source: reference };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 展开成逐项的具体路径。
|
|
78
|
+
*
|
|
79
|
+
* `count` 是运行期的项数——展开发生在**每次求值前**而不是解析期:
|
|
80
|
+
* 项数会变(用户增删行),而解析期展开出来的模板会立刻过期。
|
|
81
|
+
* 解析期做的是**校验**(列表字段在不在字典里、项内字段在不在 `item_fields` 里),
|
|
82
|
+
* 那部分才是静态的。
|
|
83
|
+
*
|
|
84
|
+
* 越界的偏移(最后一项的 `[+1]`)产出 `null` 而不是抛:
|
|
85
|
+
* 「最后一段没有下一段」是正常的数据形态,不是错误。调用方按"读不到值"处理。
|
|
86
|
+
*/
|
|
87
|
+
export function expandListPath(
|
|
88
|
+
path: SomaListPath,
|
|
89
|
+
count: number,
|
|
90
|
+
currentIndex?: number,
|
|
91
|
+
): Array<{ index: number; path: string } | null> {
|
|
92
|
+
if (path.selector.kind === 'each') {
|
|
93
|
+
return Array.from({ length: Math.max(0, count) }, (_unused, index) => ({
|
|
94
|
+
index,
|
|
95
|
+
path: `${path.list}[${index}].${path.field}`,
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
if (currentIndex === undefined) {
|
|
99
|
+
throw new SomaPathError(
|
|
100
|
+
`"${path.source}" 用了 ${path.selector.kind === 'self' ? '[..]' : '偏移'} 形态,`
|
|
101
|
+
+ '但求值时没有"当前项"——这两种形态只能出现在项作用域里的反应上',
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
const target = path.selector.kind === 'self'
|
|
105
|
+
? currentIndex
|
|
106
|
+
: currentIndex + path.selector.delta;
|
|
107
|
+
if (target < 0 || target >= count) return [null];
|
|
108
|
+
return [{ index: target, path: `${path.list}[${target}].${path.field}` }];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 从一份值里读列表路径指向的值。
|
|
113
|
+
*
|
|
114
|
+
* 读不到一律 `null`(不抛、不返回 undefined):反应图的求值面对的是**半填的表单**,
|
|
115
|
+
* 缺值是常态。抛的话,一个还没填到的明细行会炸掉整张表的联动。
|
|
116
|
+
*/
|
|
117
|
+
export function readListPath(
|
|
118
|
+
values: Record<string, unknown>,
|
|
119
|
+
path: SomaListPath,
|
|
120
|
+
index: number,
|
|
121
|
+
): unknown {
|
|
122
|
+
const list = values[path.list];
|
|
123
|
+
if (!Array.isArray(list)) return null;
|
|
124
|
+
const item = list[index];
|
|
125
|
+
if (item === null || typeof item !== 'object') return null;
|
|
126
|
+
let current: unknown = item;
|
|
127
|
+
for (const segment of path.field.split('.')) {
|
|
128
|
+
if (current === null || typeof current !== 'object') return null;
|
|
129
|
+
current = (current as Record<string, unknown>)[segment];
|
|
130
|
+
}
|
|
131
|
+
return current === undefined ? null : current;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 声明期校验:列表字段在不在字典里、它是不是 list、项内字段在不在 `item_fields` 里。
|
|
136
|
+
*
|
|
137
|
+
* 这三条是静态的,所以必须在声明期查完——留到运行期的话,一个拼错的项内字段名
|
|
138
|
+
* 只会让那条联动**永远不成立**,而"永远不成立"和"条件确实没满足"看不出区别。
|
|
139
|
+
*/
|
|
140
|
+
export function validateListPath(
|
|
141
|
+
path: SomaListPath,
|
|
142
|
+
fields: Record<string, { type?: string; item_fields?: unknown }>,
|
|
143
|
+
): string[] {
|
|
144
|
+
const issues: string[] = [];
|
|
145
|
+
const list = fields[path.list];
|
|
146
|
+
if (!list) {
|
|
147
|
+
issues.push(
|
|
148
|
+
`"${path.source}" 引用了不存在的字段 "${path.list}"`
|
|
149
|
+
+ `(本对象字典:${Object.keys(fields).join(' / ') || '空'})`,
|
|
150
|
+
);
|
|
151
|
+
return issues;
|
|
152
|
+
}
|
|
153
|
+
if (String(list.type ?? '') !== 'list') {
|
|
154
|
+
issues.push(`"${path.source}" 的 "${path.list}" 不是 list 类型(是 ${list.type ?? '未声明'})`);
|
|
155
|
+
return issues;
|
|
156
|
+
}
|
|
157
|
+
const items = Array.isArray(list.item_fields) ? list.item_fields : [];
|
|
158
|
+
const known = items
|
|
159
|
+
.map((entry) => (entry !== null && typeof entry === 'object' ? String((entry as { key?: unknown }).key ?? '') : ''))
|
|
160
|
+
.filter((key) => key !== '');
|
|
161
|
+
const root = path.field.split('.')[0];
|
|
162
|
+
if (known.length > 0 && !known.includes(root)) {
|
|
163
|
+
issues.push(
|
|
164
|
+
`"${path.source}" 的项内字段 "${root}" 不在 ${path.list}.item_fields 里`
|
|
165
|
+
+ `(可选:${known.join(' / ')})`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return issues;
|
|
169
|
+
}
|