soma-core 1.4.1 → 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/core/build/compiler/soma-precompile.js +12 -4
- package/core/build/component/package-loader.ts +32 -0
- package/core/build/pack/pack-init.ts +19 -14
- package/core/client/base/SomaHttpClient.ts +34 -1
- package/core/client/component/ai-catalog.ts +42 -0
- package/core/client/component/verify-pack.ts +120 -1
- package/core/client/container/SomaContainerAdapter.ts +6 -2
- package/core/client/infra/http/SomaHttpService.ts +2 -2
- package/core/index.ts +21 -0
- package/core/shared/component/derive-sample.ts +105 -0
- package/core/shared/component/field-lines.ts +473 -0
- package/core/shared/types/component-contract.types.ts +23 -7
- package/dist/core/index.cjs +925 -362
- package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
- package/dist/types/client/component/ai-catalog.d.ts +9 -0
- package/dist/types/client/component/verify-pack.d.ts +10 -0
- package/dist/types/index.d.ts +4 -1
- 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/types/component-contract.types.d.ts +22 -6
- package/package.json +2 -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
|
+
}
|
|
@@ -30,15 +30,34 @@ export type SomaContractPropType =
|
|
|
30
30
|
| 'object'
|
|
31
31
|
| 'array';
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* 字段(REQ-012)。
|
|
35
|
+
*
|
|
36
|
+
* prop、对象里的字段、数组元素、事件载荷是同一种东西,所以只有这一个形状,递归到底:
|
|
37
|
+
* `type: object` 用 `fields` 继续描述,`type: array` 用 `items` 描述元素。
|
|
38
|
+
*
|
|
39
|
+
* 为什么要 `example` 而不是靠 `default`:规则 C4 要求可选 prop 有默认值,而默认值按
|
|
40
|
+
* C4a 必须是空串 / 空数组这类浅结构——拿它渲染出来的永远是空态。展示页、视觉矩阵与
|
|
41
|
+
* AI 需要的是「这个字段真实长什么样」,那是另一个值,必须另有一处写。
|
|
42
|
+
*/
|
|
43
|
+
export interface SomaContractField {
|
|
34
44
|
type: SomaContractPropType;
|
|
45
|
+
desc?: string;
|
|
35
46
|
required?: boolean;
|
|
36
47
|
/** 非 required 的 prop 必须有默认值(契约规则 C4:零 props 可渲染) */
|
|
37
48
|
default?: unknown;
|
|
38
|
-
|
|
49
|
+
/** 示例值(REQ-012):样张与展示页的数据来源;不参与运行时,只被派生与目录消费 */
|
|
50
|
+
example?: unknown;
|
|
39
51
|
/** type === 'enum' 时的取值集合 */
|
|
40
52
|
values?: (string | number)[];
|
|
41
|
-
/**
|
|
53
|
+
/** type === 'object' 时的子字段(REQ-012) */
|
|
54
|
+
fields?: Record<string, SomaContractField>;
|
|
55
|
+
/** type === 'array' 时的元素形状(REQ-012) */
|
|
56
|
+
items?: SomaContractField;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface SomaContractProp extends SomaContractField {
|
|
60
|
+
/** 绑定模式:oneway(默认)| model(双向,一个组件最多一个)。只在 prop 一层有意义 */
|
|
42
61
|
mode?: 'oneway' | 'model';
|
|
43
62
|
}
|
|
44
63
|
|
|
@@ -67,10 +86,7 @@ export function findNestedMutableContractDefault(value: unknown): string | null
|
|
|
67
86
|
return null;
|
|
68
87
|
}
|
|
69
88
|
|
|
70
|
-
export interface SomaContractEmitPayloadField {
|
|
71
|
-
type: SomaContractPropType;
|
|
72
|
-
desc?: string;
|
|
73
|
-
}
|
|
89
|
+
export interface SomaContractEmitPayloadField extends SomaContractField {}
|
|
74
90
|
|
|
75
91
|
export interface SomaContractEmit {
|
|
76
92
|
payload?: Record<string, SomaContractEmitPayloadField>;
|