@wkgeo/cli 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,957 @@
1
+ /**
2
+ * 模板 / 内容契约(**纯函数层**,不碰网络、不碰文件、不碰数据库)。
3
+ *
4
+ * ## 这个文件解决什么
5
+ * 「模板声明的字段」和「库里真实的字段」是两套形状:
6
+ * * 模板侧(`templates/<key>/template.json`,v2 格式):`columns[].fields[]`
7
+ * —— `{key,label,type,required,options,group,sort}`,type 实测只有 `text|textarea|link`;
8
+ * * 库侧(`public.cms_field`):`{key,label,type,required,options,rules,sort,enabled,...}`,
9
+ * type 实测只有 `input|textarea|richtext|image|images|file|number|date|video`。
10
+ * 两边名字不一样、取值集合不一样 ⇒ 不做映射就会出「模板写了、表单没有」「表单能填、库里存不下」。
11
+ * 这里给出**一张类型映射表 + 一套值校验**,`content apply` / `content check` 都只认这一份口径。
12
+ *
13
+ * ## 契约类型的权威定义
14
+ * 老板 2026-10-30:「字段类型对齐」。契约层固定 11 个类型(见 `CONTRACT_TYPES`),
15
+ * 每个类型钉死四件事:**平台落地 type / 存储载体 / 值形状 / 能不能写**。
16
+ * 模板里写别名(`text`、`rich`、`images`、`select`…)由 `normalizeFieldType()` 归一,
17
+ * 归一不了的一律当**契约错误**(不猜、不兜底)。
18
+ *
19
+ * ## 为什么这里要「重复」服务端的校验
20
+ * 服务端 `validateFieldRules`(`aliyun/fc/wkgeo-cms/src/index.js:24090`)**只校验它知道的规则**
21
+ * (required / maxLength / minLength / pattern / min / max / maxSizeKb / accept),
22
+ * 而且 `splitContentExt`(同文件 `:1354`)对**未知字段是静默塞进 ext 的**。
23
+ * 也就是说「字段写错名」「类型传错」在服务端不会报错,只会变成一条谁都不看的脏数据。
24
+ * 老板要的「拒绝并点名」只能在写库之前做 ⇒ 校验放在这里,CLI 是唯一的执行者。
25
+ */
26
+
27
+ /* ------------------------------------------------------------------ 类型映射表 */
28
+
29
+ /**
30
+ * 契约类型 → 平台落地。
31
+ *
32
+ * 字段含义:
33
+ * * `platform` —— 落到 `cms_field.type` 的取值(`null` = 平台没有对应控件);
34
+ * * `storage` —— 值最终存在哪:`column:<列名>` / `ext` / `cms_richtext.body` / `jsonb[]`;
35
+ * * `value` —— 契约层要求的**值形状**(校验用);
36
+ * * `writes` —— 能不能经 `content apply` 写库(`false` = 平台无控件,硬拒);
37
+ * * `label` —— 给人和给报告看的中文名。
38
+ */
39
+ export const CONTRACT_TYPES = {
40
+ text: {
41
+ platform: 'input',
42
+ storage: 'column(按字段目录)|ext',
43
+ value: 'string',
44
+ writes: true,
45
+ label: '单行文本',
46
+ },
47
+ textarea: {
48
+ platform: 'textarea',
49
+ storage: 'column(按字段目录)|ext',
50
+ value: 'string',
51
+ writes: true,
52
+ label: '多行文本',
53
+ },
54
+ /** 上面两个是「文本」;下面 12 个补齐模板规范 `template-validate.mjs` 的 FIELD_TYPES */
55
+ select: {
56
+ platform: 'select',
57
+ storage: 'ext(取值受 options.choices 约束)',
58
+ value: 'string∈choices',
59
+ writes: true,
60
+ label: '单选(下拉)',
61
+ },
62
+ phone: {
63
+ platform: 'input',
64
+ storage: 'ext',
65
+ value: 'string(电话号码)',
66
+ writes: true,
67
+ label: '电话',
68
+ },
69
+ email: {
70
+ platform: 'input',
71
+ storage: 'ext',
72
+ value: 'string(邮箱)',
73
+ writes: true,
74
+ label: '邮箱',
75
+ },
76
+ boolean: {
77
+ platform: 'switch',
78
+ storage: 'ext',
79
+ value: 'true|false',
80
+ writes: true,
81
+ label: '开关',
82
+ },
83
+ richtext: {
84
+ platform: 'richtext',
85
+ storage: 'cms_richtext.body(format=html)',
86
+ value: 'blocks[]',
87
+ writes: true,
88
+ label: '富文本(结构化块)',
89
+ },
90
+ image: {
91
+ platform: 'image',
92
+ storage: 'column(封面)|ext',
93
+ value: 'assetId',
94
+ writes: true,
95
+ label: '单图',
96
+ },
97
+ gallery: {
98
+ platform: 'images',
99
+ storage: 'column(attachments)|ext',
100
+ value: 'assetId[]',
101
+ writes: true,
102
+ label: '多图/组图',
103
+ },
104
+ file: {
105
+ platform: 'file',
106
+ storage: 'ext.files',
107
+ value: 'assetId[]',
108
+ writes: true,
109
+ label: '附件(文档)',
110
+ },
111
+ video: {
112
+ platform: 'video',
113
+ storage: 'video_asset_id',
114
+ value: 'assetId',
115
+ writes: true,
116
+ label: '视频',
117
+ },
118
+ number: {
119
+ platform: 'number',
120
+ storage: 'ext',
121
+ value: 'number',
122
+ writes: true,
123
+ label: '数字',
124
+ },
125
+ date: {
126
+ platform: 'date',
127
+ storage: 'column(published_at)|ext',
128
+ value: 'YYYY-MM-DD',
129
+ writes: true,
130
+ label: '日期',
131
+ },
132
+ link: {
133
+ platform: 'input',
134
+ storage: 'column(link_url)|ext',
135
+ value: 'string(http(s):// 或站内 /path) 或 {href,target,label}',
136
+ writes: true,
137
+ label: '跳转链接',
138
+ },
139
+ list: {
140
+ platform: null,
141
+ storage: 'jsonb[](平台无对应控件)',
142
+ value: 'object[]',
143
+ writes: false,
144
+ label: '子字段列表',
145
+ },
146
+ };
147
+
148
+ /** 模板 / 库里可能出现的别名 → 契约类型。**只收已知别名**,不认识的一律报错。 */
149
+ export const TYPE_ALIASES = {
150
+ input: 'text',
151
+ string: 'text',
152
+ varchar: 'text',
153
+ single: 'text',
154
+ oneline: 'text',
155
+ textarea: 'textarea',
156
+ multitext: 'textarea',
157
+ longtext: 'textarea',
158
+ multiline: 'textarea',
159
+ rich: 'richtext',
160
+ richtext: 'richtext',
161
+ html: 'richtext', // 只是**类型名**叫 html;值仍然不接受裸 HTML 串
162
+ editor: 'richtext',
163
+ image: 'image',
164
+ photo: 'image',
165
+ picture: 'image',
166
+ images: 'gallery',
167
+ gallery: 'gallery',
168
+ album: 'gallery',
169
+ photos: 'gallery',
170
+ file: 'file',
171
+ files: 'file',
172
+ attachment: 'file',
173
+ attachment_list: 'file',
174
+ video: 'video',
175
+ number: 'number',
176
+ int: 'number',
177
+ integer: 'number',
178
+ numeric: 'number',
179
+ float: 'number',
180
+ date: 'date',
181
+ datetime: 'date',
182
+ time: 'date',
183
+ select: 'select',
184
+ enum: 'select',
185
+ option: 'select',
186
+ radio: 'select',
187
+ dropdown: 'select',
188
+ imagegroup: 'gallery',
189
+ image_group: 'gallery',
190
+ switch: 'boolean',
191
+ bool: 'boolean',
192
+ checkbox: 'boolean',
193
+ tel: 'phone',
194
+ mobile: 'phone',
195
+ mail: 'email',
196
+ link: 'link',
197
+ href: 'link',
198
+ url: 'link',
199
+ list: 'list',
200
+ repeater: 'list',
201
+ array: 'list',
202
+ };
203
+
204
+ /** 平台的 `cms_field.type` → 契约类型(反查,给 `content check` 用) */
205
+ const PLATFORM_TO_CONTRACT = Object.entries(CONTRACT_TYPES).reduce((acc, [contract, spec]) => {
206
+ if (spec.platform && !acc[spec.platform]) acc[spec.platform] = contract;
207
+ return acc;
208
+ }, {});
209
+
210
+ /**
211
+ * 把任意类型名归一成契约类型。
212
+ *
213
+ * @param {string} raw 模板 / 库里的 type
214
+ * @returns {{type: string|null, raw: string}} `type === null` = 不认识
215
+ */
216
+ export function normalizeFieldType(raw) {
217
+ const key = String(raw == null ? '' : raw).trim().toLowerCase();
218
+ if (!key) return { type: null, raw: key };
219
+ if (CONTRACT_TYPES[key]) return { type: key, raw: key };
220
+ const alias = TYPE_ALIASES[key];
221
+ if (alias) return { type: alias, raw: key };
222
+ return { type: null, raw: key };
223
+ }
224
+
225
+ /** 平台 type(`cms_field.type`)→ 契约类型;不认识的返回 `null` */
226
+ export function contractTypeOfPlatform(platformType) {
227
+ const key = String(platformType == null ? '' : platformType).trim().toLowerCase();
228
+ if (!key) return null;
229
+ if (PLATFORM_TO_CONTRACT[key]) return PLATFORM_TO_CONTRACT[key];
230
+ const one = normalizeFieldType(key);
231
+ return one.type;
232
+ }
233
+
234
+ /** 契约类型在平台上能不能写(`list` 不能) */
235
+ export function isWritableType(type) {
236
+ const one = normalizeFieldType(type);
237
+ return !!(one.type && CONTRACT_TYPES[one.type].writes);
238
+ }
239
+
240
+ /* ------------------------------------------------------------------ 小工具 */
241
+
242
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
243
+
244
+ export function isUuid(v) {
245
+ return UUID_RE.test(String(v == null ? '' : v).trim());
246
+ }
247
+
248
+ /** 按「字」算长度(中文汉字算 1)——与服务端 `charLength` 同口径 */
249
+ export function charLength(v) {
250
+ return Array.from(String(v == null ? '' : v)).length;
251
+ }
252
+
253
+ /** 标题 → slug(英文/数字留着,中文按拼音不现实 ⇒ 退化成空,让调用方显式给 slug) */
254
+ export function slugify(v) {
255
+ const s = String(v == null ? '' : v)
256
+ .trim()
257
+ .toLowerCase()
258
+ .replace(/['"’]/g, '')
259
+ .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
260
+ .replace(/^-+|-+$/g, '');
261
+ /** 纯中文的 slug 在 URL 里能用但不稳定 ⇒ 只在完全没有 ASCII 时返回空串,交给调用方兜底 */
262
+ return /^[a-z0-9-]+$/.test(s) ? s : '';
263
+ }
264
+
265
+ /** 空值判定(与服务端 `isEmptyFieldValue` 同口径:'' / null / undefined / [] 都算空) */
266
+ export function isEmptyValue(v) {
267
+ if (v === null || v === undefined) return true;
268
+ if (typeof v === 'string') return v.trim() === '';
269
+ if (Array.isArray(v)) return v.length === 0;
270
+ return false;
271
+ }
272
+
273
+ /* ------------------------------------------------------------------ 富文本块 */
274
+
275
+ /** 富文本允许的块类型(**故意不含 `html`**:不接受裸 HTML 字符串回流) */
276
+ export const RICHTEXT_BLOCKS = ['p', 'h2', 'h3', 'h4', 'ul', 'ol', 'table', 'quote'];
277
+
278
+ function escapeHtml(s) {
279
+ return String(s == null ? '' : s)
280
+ .replace(/&/g, '&amp;')
281
+ .replace(/</g, '&lt;')
282
+ .replace(/>/g, '&gt;')
283
+ .replace(/"/g, '&quot;');
284
+ }
285
+
286
+ /**
287
+ * 富文本块数组 → 清洗友好的 HTML 片段。
288
+ *
289
+ * 为什么要这层:契约层存的是**结构化块**(老板 2026-10-30:「richtext→jsonb,存结构化块,
290
+ * 不存裸 HTML 字符串」),而库里 `cms_richtext.body` 是 text + `format=html`
291
+ * (`public.cms_richtext`,实测 qibukuai 站正文就是 HTML 串)。
292
+ * ⇒ 写库前在这里**一次性渲染**成允许标签集内的 HTML,不接受调用方直接塞 HTML 串。
293
+ *
294
+ * @param {Array} blocks 形如 `[{type:'p',text:'…'},{type:'ul',items:['a','b']},{type:'table',header:[],rows:[[]]}]`
295
+ * @returns {string} HTML
296
+ * @throws {Error} 块类型不认识 / 结构不对(`code='richtext'`)
297
+ */
298
+ export function renderBlocksToHtml(blocks) {
299
+ if (!Array.isArray(blocks)) {
300
+ const err = new Error('richtext 的值要写成**块数组**(如 [{"type":"p","text":"…"}]),不是字符串/HTML');
301
+ err.code = 'richtext';
302
+ throw err;
303
+ }
304
+ const out = [];
305
+ blocks.forEach((block, i) => {
306
+ if (!block || typeof block !== 'object') {
307
+ const err = new Error(`richtext 第 ${i + 1} 块不是对象`);
308
+ err.code = 'richtext';
309
+ throw err;
310
+ }
311
+ const type = String(block.type || '').trim();
312
+ if (!RICHTEXT_BLOCKS.includes(type)) {
313
+ const err = new Error(
314
+ `richtext 第 ${i + 1} 块的 type='${type}' 不支持(只允许 ${RICHTEXT_BLOCKS.join('/')};` +
315
+ '不接受 type="html" 的裸 HTML)',
316
+ );
317
+ err.code = 'richtext';
318
+ throw err;
319
+ }
320
+ if (type === 'ul' || type === 'ol') {
321
+ const items = Array.isArray(block.items) ? block.items : [];
322
+ out.push(`<${type}>\n${items.map(one => `<li>${escapeHtml(one)}</li>`).join('\n')}\n</${type}>`);
323
+ return;
324
+ }
325
+ if (type === 'table') {
326
+ const header = Array.isArray(block.header) ? block.header : [];
327
+ const rows = Array.isArray(block.rows) ? block.rows : [];
328
+ const head = header.length ? `<thead><tr>${header.map(one => `<th>${escapeHtml(one)}</th>`).join('')}</tr></thead>` : '';
329
+ const body = rows.map(row => `<tr>${(Array.isArray(row) ? row : [row]).map(one => `<td>${escapeHtml(one)}</td>`).join('')}</tr>`).join('\n');
330
+ out.push(`<table>${head}<tbody>\n${body}\n</tbody></table>`);
331
+ return;
332
+ }
333
+ if (type === 'quote') {
334
+ out.push(`<blockquote><p>${escapeHtml(block.text)}</p></blockquote>`);
335
+ return;
336
+ }
337
+ out.push(`<${type}>${escapeHtml(block.text)}</${type}>`);
338
+ });
339
+ return out.join('\n');
340
+ }
341
+
342
+ /** HTML 里最外层的纯文本(给评分 / 探针比对用,不做完整解析) */
343
+ export function htmlToText(html) {
344
+ return String(html == null ? '' : html)
345
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
346
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
347
+ .replace(/<[^>]+>/g, '')
348
+ .replace(/&nbsp;/g, ' ')
349
+ .replace(/&amp;/g, '&')
350
+ .replace(/&lt;/g, '<')
351
+ .replace(/&gt;/g, '>')
352
+ .replace(/\s+/g, ' ')
353
+ .trim();
354
+ }
355
+
356
+ /* ------------------------------------------------------------------ 字段规格归一 */
357
+
358
+ /**
359
+ * 把模板里的一个字段(或库里的 `cms_field` 行)归一成**契约字段规格**。
360
+ *
361
+ * 输出形状(`content apply` / `content check` 共用):
362
+ * ```
363
+ * {
364
+ * key, label, type, // type = 契约类型(归一后)
365
+ * rawType, // 原始 type(报错要点名)
366
+ * required, sort, group,
367
+ * choices[], // enum 可选值
368
+ * maxLen, minLen, pattern, min, max, maxSizeKb, accept[],
369
+ * imageSpec: {w,h,ratio,maxKB,formats[]} | null,
370
+ * source: 'template' | 'platform',
371
+ * }
372
+ * ```
373
+ *
374
+ * @param {object} raw 模板字段 / `cms_field` 行
375
+ * @param {'template'|'platform'} source
376
+ */
377
+ export function normalizeFieldSpec(raw, source = 'template') {
378
+ const one = raw && typeof raw === 'object' ? raw : {};
379
+ const rules = one.rules && typeof one.rules === 'object' ? one.rules : {};
380
+ const options = one.options && typeof one.options === 'object' ? one.options : {};
381
+ const norm = normalizeFieldType(one.type == null ? (source === 'platform' ? 'input' : 'text') : one.type);
382
+
383
+ /** choices:`options.choices`({value,label} 或字符串)/ `options.items` / 模板的 `options:[]` */
384
+ const rawChoices = Array.isArray(one.options)
385
+ ? one.options
386
+ : Array.isArray(options.choices)
387
+ ? options.choices
388
+ : Array.isArray(options.items)
389
+ ? options.items
390
+ : [];
391
+ const choices = rawChoices
392
+ .map(choice => (choice && typeof choice === 'object' ? choice.value ?? choice.key ?? choice.label : choice))
393
+ .map(choice => String(choice == null ? '' : choice).trim())
394
+ .filter(Boolean);
395
+
396
+ const imageSpecRaw = one.imageSpec && typeof one.imageSpec === 'object' ? one.imageSpec : {};
397
+ const accept = Array.isArray(rules.accept)
398
+ ? rules.accept.map(x => String(x).toLowerCase().replace(/^\./, '')).filter(Boolean)
399
+ : Array.isArray(imageSpecRaw.formats)
400
+ ? imageSpecRaw.formats.map(x => String(x).toLowerCase().replace(/^\./, '')).filter(Boolean)
401
+ : [];
402
+
403
+ const num = (v, fallback = 0) => {
404
+ const n = Number(v);
405
+ return Number.isFinite(n) ? n : fallback;
406
+ };
407
+
408
+ return {
409
+ key: String(one.key || '').trim(),
410
+ label: String(one.label || one.name || one.key || '').trim(),
411
+ type: norm.type,
412
+ rawType: norm.raw,
413
+ required: typeof rules.required === 'boolean' ? rules.required : one.required === true,
414
+ sort: num(one.sort, 0),
415
+ group: String(one.group || one.group_name || '').trim(),
416
+ choices,
417
+ maxLen: num(one.maxLen != null ? one.maxLen : rules.maxLength, 0),
418
+ minLen: num(rules.minLength, 0),
419
+ pattern: rules.pattern ? String(rules.pattern) : '',
420
+ min: rules.min === undefined ? null : num(rules.min, 0),
421
+ max: rules.max === undefined ? null : num(rules.max, 0),
422
+ maxSizeKb: num(rules.maxSizeKb != null ? rules.maxSizeKb : imageSpecRaw.maxKB, 0),
423
+ accept,
424
+ imageSpec: one.imageSpec
425
+ ? {
426
+ w: num(imageSpecRaw.w, 0),
427
+ h: num(imageSpecRaw.h, 0),
428
+ ratio: String(imageSpecRaw.ratio || ''),
429
+ maxKB: num(imageSpecRaw.maxKB, 0),
430
+ formats: accept,
431
+ }
432
+ : null,
433
+ source,
434
+ };
435
+ }
436
+
437
+ /* ------------------------------------------------------------------ 模板契约 */
438
+
439
+ /** v2 模板里「栏目」的两种写法(`columns` 是现行,`sections` 是老板口头/旧文档叫法) */
440
+ const COLUMN_KEYS = ['columns', 'sections'];
441
+
442
+ const PAGE_KINDS = { index: 'channel', channel: 'channel', list: 'list', page: 'page', content: 'list', article: 'list' };
443
+
444
+ /**
445
+ * 从 `template.json` 提取契约。
446
+ *
447
+ * 两种模板格式都要认:
448
+ * * **v2**(`_format: 'wkgeo-template@2'`,如 `templates/ind-law-firm`):
449
+ * `columns[]` = 栏目,`columns[].fields[]` + `columns[].items[]`;
450
+ * * **v1**(市场包,如 `templates/qbk-enterprise`):只有 `files[]`,**没有栏目契约** ——
451
+ * `contractPresent=false`,`content check --template` 会如实报「模板未声明栏目/字段契约」。
452
+ *
453
+ * @param {object} json `template.json` 解析结果
454
+ * @param {{source?: string}} [opts]
455
+ */
456
+ export function normalizeTemplateContract(json, opts = {}) {
457
+ const tpl = json && typeof json === 'object' ? json : {};
458
+ const problems = [];
459
+ const warnings = [];
460
+ const source = opts.source || '';
461
+
462
+ const format = String(tpl._format || '').trim();
463
+ const columnsRaw = COLUMN_KEYS.map(k => tpl[k]).find(v => Array.isArray(v) && v.length);
464
+ const columns = [];
465
+
466
+ if (!columnsRaw) {
467
+ warnings.push({
468
+ level: 'warn',
469
+ where: 'template.json',
470
+ message:
471
+ '模板没有声明 columns[]/sections[]:' +
472
+ (Array.isArray(tpl.files) && tpl.files.length
473
+ ? `这是 v1 市场包(files[] ${tpl.files.length} 个文件),栏目与字段只在 demo 包里,契约缺位`
474
+ : '栏目结构无法从模板推导'),
475
+ fix: '按 docs/规范-模板内容契约.md §2 补 columns[](key/name/slug/page/fields[]),或改用 wkgeo-template@2 格式',
476
+ });
477
+ }
478
+
479
+ const seenKeys = new Set();
480
+ (Array.isArray(columnsRaw) ? columnsRaw : []).forEach((rawCol, ci) => {
481
+ const col = rawCol && typeof rawCol === 'object' ? rawCol : {};
482
+ const key = String(col.key || col.slug || '').trim();
483
+ const at = `columns[${ci}]`;
484
+ if (!key) {
485
+ problems.push({ level: 'error', where: at, message: '栏目缺少 key', fix: '每个栏目必须有稳定的 key(改名不改 key)' });
486
+ return;
487
+ }
488
+ if (seenKeys.has(key)) {
489
+ problems.push({ level: 'error', where: at, message: `栏目 key 重复:${key}`, fix: '栏目 key 在一份模板里必须唯一' });
490
+ return;
491
+ }
492
+ seenKeys.add(key);
493
+
494
+ const fieldsRaw = Array.isArray(col.fields) ? col.fields : [];
495
+ const fieldKeys = new Set();
496
+ const fields = [];
497
+ fieldsRaw.forEach((rawField, fi) => {
498
+ const spec = normalizeFieldSpec(rawField, 'template');
499
+ const fat = `${at}.fields[${fi}]`;
500
+ if (!spec.key) {
501
+ problems.push({ level: 'error', where: fat, message: '字段缺少 key', fix: '字段 key 必填(表单、库列、契约三处同名)' });
502
+ return;
503
+ }
504
+ if (fieldKeys.has(spec.key)) {
505
+ problems.push({ level: 'error', where: fat, message: `字段 key 重复:${spec.key}`, fix: '同一栏目内字段 key 唯一' });
506
+ return;
507
+ }
508
+ fieldKeys.add(spec.key);
509
+ if (!spec.type) {
510
+ problems.push({
511
+ level: 'error',
512
+ where: fat,
513
+ message: `字段 ${spec.key} 的 type='${spec.rawType}' 不在契约类型表里`,
514
+ fix: `改成 ${Object.keys(CONTRACT_TYPES).join(' / ')} 之一(或已在 TYPE_ALIASES 里的别名)`,
515
+ });
516
+ } else if (!CONTRACT_TYPES[spec.type].writes) {
517
+ problems.push({
518
+ level: 'error',
519
+ where: fat,
520
+ message: `字段 ${spec.key} 用了契约类型 ${spec.type},平台没有对应控件/存储(list 类型是卡点)`,
521
+ fix: '改成 textarea(存 JSON 文本)或拆成独立栏目 + 多条内容',
522
+ });
523
+ }
524
+ if (spec.type === 'select' && !spec.choices.length) {
525
+ problems.push({
526
+ level: 'error',
527
+ where: fat,
528
+ message: `枚举字段 ${spec.key} 没给可选值`,
529
+ fix: '在 fields[].options 里列全取值(库侧落在 rules/options,缺了就变成自由文本)',
530
+ });
531
+ }
532
+ if (!spec.label) {
533
+ problems.push({ level: 'error', where: fat, message: `字段 ${spec.key} 没有 label`, fix: 'label 是 CMS 表单上的显示名,必填' });
534
+ }
535
+ fields.push(spec);
536
+ });
537
+
538
+ /** 模板自带的 items[] = 演示/种子内容;它用到的键必须在自己 fields[] 里(否则就是「模板内联了契约外字段」) */
539
+ const items = Array.isArray(col.items) ? col.items : [];
540
+ items.forEach((item, ii) => {
541
+ if (!item || typeof item !== 'object') return;
542
+ Object.keys(item).forEach(k => {
543
+ if (!fieldKeys.has(k)) {
544
+ problems.push({
545
+ level: 'error',
546
+ where: `${at}.items[${ii}]`,
547
+ message: `模板示例数据用了契约外字段 '${k}'(栏目 ${key} 的 fields[] 里没有)`,
548
+ fix: '先在 columns[].fields[] 声明该字段,再从 items[] 里用;模板不得内联契约外数据',
549
+ });
550
+ }
551
+ });
552
+ });
553
+
554
+ const page = String(col.page || '').trim();
555
+ const kind = String(col.kind || PAGE_KINDS[page] || (page === 'index' || !page ? 'channel' : 'list')).trim();
556
+ columns.push({
557
+ key,
558
+ name: String(col.name || key).trim(),
559
+ slug: String(col.slug || key).trim().replace(/^\/+|\/+$/g, ''),
560
+ page,
561
+ kind,
562
+ inMenu: col.in_menu === undefined ? true : col.in_menu !== false,
563
+ parent: String(col.parent || '').trim(),
564
+ sort: Number(col.sort || 0) || 0,
565
+ seo: col.seo && typeof col.seo === 'object' ? col.seo : {},
566
+ fields,
567
+ items,
568
+ });
569
+ });
570
+
571
+ return {
572
+ key: String(tpl.key || opts.key || '').trim(),
573
+ name: String(tpl.name || '').trim(),
574
+ format,
575
+ source,
576
+ contractPresent: !!(Array.isArray(columnsRaw) && columnsRaw.length),
577
+ columns,
578
+ problems,
579
+ warnings,
580
+ raw: tpl,
581
+ };
582
+ }
583
+
584
+ /* ------------------------------------------------------------------ 值校验 */
585
+
586
+ /**
587
+ * 校验一个字段值是否符合契约。
588
+ *
589
+ * @param {object} field `normalizeFieldSpec()` 的输出
590
+ * @param {*} value 待写入的值
591
+ * @returns {string[]} 错误信息(空数组 = 通过);**每条都带字段名**
592
+ */
593
+ export function validateFieldValue(field, value) {
594
+ const errors = [];
595
+ const f = field || {};
596
+ const name = f.label || f.key || '字段';
597
+ const empty = isEmptyValue(value);
598
+
599
+ if (f.required && empty) {
600
+ errors.push(`${name} 必填,不能为空`);
601
+ return errors;
602
+ }
603
+ if (empty) return errors;
604
+
605
+ const type = f.type;
606
+ if (!type) {
607
+ errors.push(`${name} 的类型 '${f.rawType}' 不认识`);
608
+ return errors;
609
+ }
610
+ if (!CONTRACT_TYPES[type].writes) {
611
+ errors.push(`${name} 的类型 ${type} 平台不支持落库(卡点:见 docs/规范-模板内容契约.md §3)`);
612
+ return errors;
613
+ }
614
+
615
+ if (type === 'text' || type === 'textarea') {
616
+ if (typeof value !== 'string') {
617
+ errors.push(`${name} 要是字符串(收到 ${describeValue(value)})`);
618
+ return errors;
619
+ }
620
+ const len = charLength(value);
621
+ if (f.maxLen > 0 && len > f.maxLen) errors.push(`${name} 最多 ${f.maxLen} 个字(当前 ${len})`);
622
+ if (f.minLen > 0 && len < f.minLen) errors.push(`${name} 至少 ${f.minLen} 个字(当前 ${len})`);
623
+ if (f.pattern && !safeRegexTest(f.pattern, value)) errors.push(`${name} 格式不正确(不满足 ${f.pattern})`);
624
+ return errors;
625
+ }
626
+
627
+ if (type === 'richtext') {
628
+ if (typeof value === 'string') {
629
+ errors.push(
630
+ `${name} 不接受裸 HTML 字符串:richtext 必须写成块数组([{"type":"p","text":"…"}])` +
631
+ `;如需在库里改正文,请改块数组后重跑 apply`,
632
+ );
633
+ return errors;
634
+ }
635
+ if (!Array.isArray(value)) {
636
+ errors.push(`${name} 要写成块数组(收到 ${describeValue(value)})`);
637
+ return errors;
638
+ }
639
+ try {
640
+ renderBlocksToHtml(value);
641
+ } catch (e) {
642
+ errors.push(`${name} 块结构不合法:${e.message}`);
643
+ }
644
+ return errors;
645
+ }
646
+
647
+ if (type === 'image' || type === 'video') {
648
+ if (typeof value !== 'string' || !isUuid(value)) {
649
+ errors.push(`${name} 要传**素材 id(uuid)**,不能传 URL/文件名(收到 ${describeValue(value)})`);
650
+ return errors;
651
+ }
652
+ return errors;
653
+ }
654
+
655
+ if (type === 'gallery' || type === 'file') {
656
+ if (!Array.isArray(value)) {
657
+ errors.push(`${name} 要传素材 id 数组(收到 ${describeValue(value)})`);
658
+ return errors;
659
+ }
660
+ value.forEach((one, i) => {
661
+ if (typeof one !== 'string' || !isUuid(one)) {
662
+ errors.push(`${name} 第 ${i + 1} 项不是素材 id(uuid):${describeValue(one)}`);
663
+ }
664
+ });
665
+ if (errors.length) return errors;
666
+ if (type === 'gallery' && f.maxLen > 0 && value.length > f.maxLen) {
667
+ errors.push(`${name} 最多 ${f.maxLen} 张(当前 ${value.length})`);
668
+ }
669
+ return errors;
670
+ }
671
+
672
+ if (type === 'number') {
673
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
674
+ /** 明确挡 `"abc"` 和 `"123"`:数字字段传字符串一律拒绝,不做隐式转换 */
675
+ errors.push(`${name} 要传数字(不带引号),收到 ${describeValue(value)}`);
676
+ return errors;
677
+ }
678
+ if (f.min !== null && Number(f.min) !== 0 && value < Number(f.min)) errors.push(`${name} 不能小于 ${f.min}`);
679
+ if (f.max !== null && Number(f.max) !== 0 && value > Number(f.max)) errors.push(`${name} 不能大于 ${f.max}`);
680
+ return errors;
681
+ }
682
+
683
+ if (type === 'date') {
684
+ const s = String(value);
685
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) {
686
+ errors.push(`${name} 要写 YYYY-MM-DD(收到 ${describeValue(value)})`);
687
+ return errors;
688
+ }
689
+ const d = new Date(`${s}T00:00:00Z`);
690
+ if (Number.isNaN(d.getTime())) errors.push(`${name} 不是合法日期:${s}`);
691
+ return errors;
692
+ }
693
+
694
+ if (type === 'select') {
695
+ const s = String(value);
696
+ if (f.choices.length && !f.choices.includes(s)) {
697
+ errors.push(`${name} 只能是 ${f.choices.join(' / ')} 之一(收到 '${s}')`);
698
+ }
699
+ return errors;
700
+ }
701
+
702
+ if (type === 'phone') {
703
+ const s = String(value).replace(/[\s-]/g, '');
704
+ if (!/^\+?\d{6,20}$/.test(s)) errors.push(`${name} 不是合法电话(收到 ${describeValue(value)})`);
705
+ return errors;
706
+ }
707
+
708
+ if (type === 'email') {
709
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value))) {
710
+ errors.push(`${name} 不是合法邮箱(收到 ${describeValue(value)})`);
711
+ }
712
+ return errors;
713
+ }
714
+
715
+ if (type === 'boolean') {
716
+ if (typeof value !== 'boolean') {
717
+ errors.push(`${name} 要传 true/false(收到 ${describeValue(value)})`);
718
+ }
719
+ return errors;
720
+ }
721
+
722
+ if (type === 'link') {
723
+ const href = typeof value === 'object' && value ? String(value.href || '') : String(value);
724
+ if (!href) {
725
+ errors.push(`${name} 缺少 href`);
726
+ return errors;
727
+ }
728
+ const internal = href.startsWith('/');
729
+ if (!internal && !/^https?:\/\//i.test(href)) {
730
+ errors.push(`${name} 只接受站内路径(/xxx)或 http(s):// 绝对地址(收到 '${href}')`);
731
+ return errors;
732
+ }
733
+ if (href.length > 500) errors.push(`${name} 链接过长(${href.length} > 500)`);
734
+ return errors;
735
+ }
736
+
737
+ if (type === 'list') {
738
+ errors.push(`${name} 是 list 类型,平台无对应控件(卡点)`);
739
+ return errors;
740
+ }
741
+
742
+ return errors;
743
+ }
744
+
745
+ function safeRegexTest(pattern, value) {
746
+ try {
747
+ return new RegExp(pattern).test(String(value));
748
+ } catch {
749
+ return true; // 正则本身坏了就放行(与服务端同口径)
750
+ }
751
+ }
752
+
753
+ function describeValue(v) {
754
+ if (v === null) return 'null';
755
+ if (Array.isArray(v)) return `数组[${v.length}]`;
756
+ if (typeof v === 'object') return `对象{${Object.keys(v).slice(0, 4).join(',')}}`;
757
+ return `${typeof v} ${JSON.stringify(v)}`;
758
+ }
759
+
760
+ /* ------------------------------------------------------------------ 媒体规格 */
761
+
762
+ /**
763
+ * 媒体值 → 规格问题(**平台侧不校验宽高**:老板 2026-10-19 拍板,rules 里保留但前后端都不用)。
764
+ *
765
+ * 这里只做**契约层能查的**:数量上限、扩展名白名单、单文件大小。
766
+ * 宽高/比例属于「契约声明了但平台不校验」⇒ `content check` 里记 warn,不拦。
767
+ *
768
+ * @param {object} field 契约字段
769
+ * @param {*} value 值
770
+ * @param {Map<string,{name?:string,size?:number,mime?:string,url?:string}>} assets 素材索引(可空)
771
+ * @returns {{errors: string[], warnings: string[]}}
772
+ */
773
+ export function validateMediaSpec(field, value, assets) {
774
+ const errors = [];
775
+ const warnings = [];
776
+ const f = field || {};
777
+ const name = f.label || f.key || '媒体';
778
+ if (isEmptyValue(value)) return { errors, warnings };
779
+ const ids = (Array.isArray(value) ? value : [value]).filter(Boolean);
780
+ if (!assets || !assets.size) {
781
+ return { errors, warnings: [`${name}:本次没取到素材索引,图片规格(大小/格式)未核对`] };
782
+ }
783
+ ids.forEach((id, i) => {
784
+ const asset = assets.get(String(id));
785
+ const at = ids.length > 1 ? `${name} 第 ${i + 1} 个` : name;
786
+ if (!asset) {
787
+ warnings.push(`${at}:库里查不到素材 ${id}(服务端保存时对查不到的素材是放行的)`);
788
+ return;
789
+ }
790
+ if (f.maxSizeKb > 0 && Number(asset.size || 0) > f.maxSizeKb * 1024) {
791
+ errors.push(`${at} 超过 ${f.maxSizeKb} KB(实际 ${Math.round(Number(asset.size || 0) / 1024)} KB)`);
792
+ }
793
+ const ext = String(asset.name || asset.url || '')
794
+ .split('?')[0]
795
+ .split('.')
796
+ .pop()
797
+ .toLowerCase();
798
+ if (f.accept.length && ext && !f.accept.includes(ext)) {
799
+ errors.push(`${at} 格式 ${ext} 不在允许列表(${f.accept.join('/')})`);
800
+ }
801
+ });
802
+ if (f.imageSpec && (f.imageSpec.w || f.imageSpec.h || f.imageSpec.ratio)) {
803
+ warnings.push(
804
+ `${name}:契约声明了宽高/比例(${f.imageSpec.w || '?'}×${f.imageSpec.h || '?'} ${f.imageSpec.ratio || ''}),` +
805
+ '但平台前后端都不校验宽高(老板 2026-10-19 拍板)',
806
+ );
807
+ }
808
+ return { errors, warnings };
809
+ }
810
+
811
+ /* ------------------------------------------------------------------ manifest */
812
+
813
+ /**
814
+ * 归一 `--manifest` 的内容清单(形状写死在 `docs/规范-模板内容契约.md` §5)。
815
+ *
816
+ * 输入:
817
+ * ```json
818
+ * {
819
+ * "siteId": "uuid(可省,省了用 --site / 本地选站)",
820
+ * "lang": "zh-CN(可省,默认站点默认语言)",
821
+ * "status": "published(可省,默认 published)",
822
+ * "pages": [ { "key": "about", "title": "关于我们", "seo": {"title":"","description":"","keywords":""}, "body": [块] } ],
823
+ * "sections":[ { "key": "news", "items": [ { "slug":"…", "title":"…", "status":"draft", "sort":1,
824
+ * "fields": { "字段key": 值 } } ] } ]
825
+ * }
826
+ * ```
827
+ * 也接受 `columns[]` 当 `sections[]` 的别名(与模板同口径)。
828
+ */
829
+ export function normalizeManifest(raw, opts = {}) {
830
+ const errors = [];
831
+ const m = raw && typeof raw === 'object' ? raw : {};
832
+ const sectionsRaw = Array.isArray(m.sections) ? m.sections : Array.isArray(m.columns) ? m.columns : [];
833
+ const pagesRaw = Array.isArray(m.pages) ? m.pages : [];
834
+
835
+ if (!sectionsRaw.length && !pagesRaw.length) {
836
+ errors.push({
837
+ level: 'error',
838
+ where: 'manifest',
839
+ message: '清单里既没有 sections[] 也没有 pages[](空清单不写库)',
840
+ fix: '按契约 §5 写 sections[{key,items[]}] 或 pages[{key,title}]',
841
+ });
842
+ }
843
+
844
+ const seen = new Set();
845
+ const sections = sectionsRaw.map((rawSection, si) => {
846
+ const s = rawSection && typeof rawSection === 'object' ? rawSection : {};
847
+ const key = String(s.key || s.slug || '').trim();
848
+ const at = `sections[${si}]`;
849
+ if (!key) {
850
+ errors.push({ level: 'error', where: at, message: '栏目缺少 key', fix: 'section.key 必填(对应模板栏目 key)' });
851
+ } else if (seen.has(key)) {
852
+ errors.push({ level: 'error', where: at, message: `栏目 key 重复:${key}`, fix: '一份清单里栏目 key 唯一' });
853
+ } else {
854
+ seen.add(key);
855
+ }
856
+ const itemsRaw = Array.isArray(s.items) ? s.items : [];
857
+ const items = itemsRaw.map((rawItem, ii) => {
858
+ const item = rawItem && typeof rawItem === 'object' ? rawItem : {};
859
+ const fields = item.fields && typeof item.fields === 'object' && !Array.isArray(item.fields) ? item.fields : {};
860
+ const title = String(item.title || fields.title || '').trim();
861
+ if (!title) {
862
+ errors.push({
863
+ level: 'error',
864
+ where: `${at}.items[${ii}]`,
865
+ message: '内容缺少 title',
866
+ fix: '每条内容给 title(或 fields.title);标题是库里的必填列',
867
+ });
868
+ }
869
+ return {
870
+ title,
871
+ slug: String(item.slug || '').trim(),
872
+ status: String(item.status || '').trim(),
873
+ sort: item.sort === undefined ? null : Number(item.sort),
874
+ pinned: item.pinned === undefined ? null : item.pinned === true,
875
+ fields,
876
+ at: `${at}.items[${ii}]`,
877
+ };
878
+ });
879
+ return { key, items, at };
880
+ });
881
+
882
+ const pageSeen = new Set();
883
+ const pages = pagesRaw.map((rawPage, pi) => {
884
+ const p = rawPage && typeof rawPage === 'object' ? rawPage : {};
885
+ const key = String(p.key || p.slug || '').trim();
886
+ const at = `pages[${pi}]`;
887
+ if (!key) errors.push({ level: 'error', where: at, message: '单页缺少 key', fix: 'pages[].key 对应模板里 page 类栏目' });
888
+ else if (pageSeen.has(key)) errors.push({ level: 'error', where: at, message: `单页 key 重复:${key}`, fix: '一份清单里单页 key 唯一' });
889
+ else pageSeen.add(key);
890
+ const seo = p.seo && typeof p.seo === 'object' ? p.seo : {};
891
+ return {
892
+ key,
893
+ title: String(p.title || '').trim(),
894
+ seo: {
895
+ title: String(seo.title || '').trim(),
896
+ description: String(seo.description || '').trim(),
897
+ keywords: String(seo.keywords || '').trim(),
898
+ },
899
+ body: Array.isArray(p.body) ? p.body : null,
900
+ at,
901
+ };
902
+ });
903
+
904
+ return {
905
+ siteId: String(m.siteId || opts.siteId || '').trim(),
906
+ lang: String(m.lang || opts.lang || '').trim(),
907
+ status: String(m.status || '').trim(),
908
+ pages,
909
+ sections,
910
+ errors,
911
+ };
912
+ }
913
+
914
+ /* ------------------------------------------------------------------ 评分 */
915
+
916
+ /**
917
+ * 汇总维度分。
918
+ *
919
+ * 规则:维度里出现 `hard` 级发现 → 该维度扣到 0(一致性是「有一处不符就不通过」,不给半分);
920
+ * 只有 warn → 按 warn 条数每条扣 max 的 1/3(最多扣到 0)。
921
+ * 不适用的维度(`applicable:false`)从总分里剔除。
922
+ *
923
+ * @param {Array<{key:string,name:string,max:number,findings:Array,dimensionNote?:string}>} dimensions
924
+ */
925
+ export function scoreDimensions(dimensions) {
926
+ const out = [];
927
+ let total = 0;
928
+ let max = 0;
929
+ (dimensions || []).forEach(dim => {
930
+ const findings = Array.isArray(dim.findings) ? dim.findings : [];
931
+ const applicable = dim.applicable !== false;
932
+ const hard = findings.filter(f => f.level === 'error' || f.hard);
933
+ const warn = findings.filter(f => f.level !== 'error' && !f.hard);
934
+ let score = dim.max;
935
+ if (!applicable) score = 0;
936
+ else if (hard.length) score = 0;
937
+ else if (warn.length) {
938
+ // 只有 warn 时**一条扣 1/3 分、最多扣到 60%**:warn 是"可以更好",
939
+ // 不该因为三五条提醒就把一整个维度清零(老逻辑 3 条 warn = 0 分,太吵也不可信)。
940
+ score = Math.max(Math.round(dim.max * 0.4), Math.round(dim.max - (dim.max / 3) * warn.length));
941
+ }
942
+ if (applicable) {
943
+ total += score;
944
+ max += dim.max;
945
+ }
946
+ out.push({
947
+ key: dim.key,
948
+ name: dim.name,
949
+ score,
950
+ max: dim.max,
951
+ applicable,
952
+ note: dim.note || '',
953
+ findings,
954
+ });
955
+ });
956
+ return { total, max, dimensions: out };
957
+ }