@realnation/content-config 0.3.0 → 0.5.0
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 +51 -1
- package/package.json +10 -2
- package/src/canvas.d.ts +75 -0
- package/src/canvas.mjs +225 -0
- package/src/exits.d.ts +38 -0
- package/src/exits.mjs +129 -0
- package/src/index.d.ts +7 -0
- package/src/index.mjs +3 -2
- package/src/labels.mjs +110 -110
- package/src/vite-plugin.mjs +7 -2
package/README.md
CHANGED
|
@@ -34,6 +34,37 @@ AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/p
|
|
|
34
34
|
} satisfies ContentConfigSpec;
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
+
## 动态出口(0.4.0 起)
|
|
38
|
+
|
|
39
|
+
有的模块的出口不在模块目录里,而是配置页按内容配置算出来、保存时经宿主 `setAccessDynamicPorts` 推给 Builder 的
|
|
40
|
+
(Dial Pad 每个号码一个,Access Time / Access Device 每个放行规则组一个,Access URL 首次、再次、用完)。
|
|
41
|
+
这类模块在说明里再导出 `dynamicExits`:用数据把配置页那段算法原样写出来,建活动 skill 拿保存后读回的请求体照着算出同样的出口,
|
|
42
|
+
补进节点并接线,不执行模块代码,也不用打开配置页。出口全在模块目录里的模块不写。
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
export default {
|
|
46
|
+
endpoint: 'common',
|
|
47
|
+
defaultBody: () => ({ configId: 0, detail: createEmptyDetail() }),
|
|
48
|
+
schema: { /* ... */ },
|
|
49
|
+
dynamicExits: [
|
|
50
|
+
// 列表里每一项一个出口:each 是请求体里列表的路径,where 里的字段都相等的项才算
|
|
51
|
+
{ each: 'detail.numbers', id: '{key}', event: `${DIAL_EVENT_PREFIX}{key}`, name: ['{exitName}', '{number}'] },
|
|
52
|
+
// 固定出口:when 里的路径都等于给的值才有
|
|
53
|
+
{ id: 'exhausted', event: 'access_url_exhausted', name: 'Exhausted', when: { 'detail.exhaustedAllow': true } }
|
|
54
|
+
]
|
|
55
|
+
} satisfies ContentConfigSpec;
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- `id`、`event`、`name` 是模板:`{字段}` 换成这一项的字段值(去掉首尾空白),`{index}` 是这一项在整个列表里的序号,
|
|
59
|
+
`{n}` 是在通过 `where` 的项里的序号(都从 1 起)。有一处换成空串整个模板就算空;`name` 给数组时取第一个不空的。
|
|
60
|
+
固定出口的模板只能写原文。
|
|
61
|
+
- 出口的顺序、id、事件名、名字都要和配置页推给宿主的那一份**一模一样**:照配置页的代码写,事件名前缀引用代码里的同一个常量。
|
|
62
|
+
id 为空、事件名为空、id 重复的会被跳过,与 Builder 收到出口时的做法相同。
|
|
63
|
+
- 构建时核对:路径与字段在字段说明里找得到、固定出口没用字段、拿出厂请求体算出的出口 id 里没有横杠
|
|
64
|
+
(连线的键按「源-模块-端口-目标」用横杠拆,有横杠会拆错)。不过关构建就失败。
|
|
65
|
+
- 出口规则算法在 `@realnation/content-config/exits`(`computeExits`、`checkExitRules`),模块构建与建活动 skill 用同一份。
|
|
66
|
+
- 产物 `content-config.json` 多一个可选的 `dynamicExits` 键,`format` 仍是 1:读取方不认识就当没有。
|
|
67
|
+
|
|
37
68
|
## 写字段说明的规矩
|
|
38
69
|
|
|
39
70
|
- **默认值与范围引用代码里的同一份常量**(默认值函数、LIMITS、枚举表),不照抄数字;改代码说明自动跟上。
|
|
@@ -59,6 +90,24 @@ AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/p
|
|
|
59
90
|
minimum、maximum、minLength、maxLength、pattern、anyOf、format,另加 $schema、title、description、x-label。
|
|
60
91
|
用到别的会被当成问题报出来。
|
|
61
92
|
|
|
93
|
+
## 画布说明 canvas-config.json(0.5.0 起,体验端)
|
|
94
|
+
|
|
95
|
+
给 AI 摆元件、改属性用(待办 #80):说明模块放到 UI Editor 画布上的元件是什么、模块真读哪些属性、两档默认版面、什么配置下才出现、摆放约束。
|
|
96
|
+
体验端仓写 `src/canvas-config.ts`(默认导出 `CanvasConfigSpec`,类型在 `@realnation/content-config/canvas`),vite.config 加:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { canvasConfig } from '@realnation/content-config/canvas';
|
|
100
|
+
// plugins: [..., pageEventsPlugin(), canvasConfig()]
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
构建时检查并写 `assets/canvas-config.json`(与 `page-events.js` 同目录),不过关构建失败。规矩:
|
|
104
|
+
|
|
105
|
+
- 键是 componentName。`kind: 'system'` 是登记在 editor_tabs.components 的;`kind: 'pushed'` 是 page-data 推的,要写 `key`、`type`、英文 `appearsWhen`,可选机器可读的 `when`(`{ 内容配置读回的请求体里的路径: 值 }`,如 `{ 'design.wheelCount': 2 }`)。
|
|
106
|
+
- 面板项的类型、默认值、选项、范围不写,以后台登记的 collocation 为准;`properties` 只写模块真读的属性的英文说明(宿主统一套在外框上的位置、大小、颜色、字体不列),`ignores` 列面板上有、模块不读的。
|
|
107
|
+
- `layout`、`layoutVariants`、`key` 都从模块代码 import 同一份常量(如 placeholders.ts),不抄数字。推送元件的 key、componentName 与 `module` 要在构建用到的源码里原样找得到(另加 `src/page-events.ts`),对不上构建失败。
|
|
108
|
+
- `constraints` 只写模块自己的摆放规矩:`aspect`、`minWidth`、`minHeight`、`anchorsTo`(压在谁的正中)、`overlapAllowed`、`face`(盒子里真正画东西的是贴着远离某条边的正方形,如转盘的圆,`anchorsTo` 对准它的中心,`aspect` 在那条边为左右时宽高对调)。不出屏、不压角标这类平台规矩不写在这里。
|
|
109
|
+
- 说明文字一律英文。完整样例:体验仓 qiksense-lottery-spin-and-win-experience 的 `src/canvas-config.ts`。
|
|
110
|
+
|
|
62
111
|
## 其他用法
|
|
63
112
|
|
|
64
113
|
- `import { validate } from '@realnation/content-config/validate'`:返回问题清单,空数组 = 通过(skill 读到说明后用它校验要提交的请求体)。
|
|
@@ -67,4 +116,5 @@ AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/p
|
|
|
67
116
|
|
|
68
117
|
## 发版
|
|
69
118
|
|
|
70
|
-
`npm publish`(在本目录;账号要两步验证,由 PF 在自己的终端里发)。改了产物格式就把 `FORMAT`
|
|
119
|
+
`npm publish`(在本目录;账号要两步验证,由 PF 在自己的终端里发)。改了产物格式就把 `FORMAT` 加一,并同步改读取方;
|
|
120
|
+
只加读取方可以不认识的可选键(如 0.4.0 的 `dynamicExits`)不算改格式。
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@realnation/content-config",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "qiksense 模块内容配置的机器可读说明:构建时导出 content-config.json
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "qiksense 模块内容配置的机器可读说明:构建时导出 content-config.json,并用字段说明校验默认请求体;0.5.0 起另导出画布说明 canvas-config.json(体验端)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
@@ -11,6 +11,14 @@
|
|
|
11
11
|
"./validate": {
|
|
12
12
|
"types": "./src/validate.d.ts",
|
|
13
13
|
"import": "./src/validate.mjs"
|
|
14
|
+
},
|
|
15
|
+
"./exits": {
|
|
16
|
+
"types": "./src/exits.d.ts",
|
|
17
|
+
"import": "./src/exits.mjs"
|
|
18
|
+
},
|
|
19
|
+
"./canvas": {
|
|
20
|
+
"types": "./src/canvas.d.ts",
|
|
21
|
+
"import": "./src/canvas.mjs"
|
|
14
22
|
}
|
|
15
23
|
},
|
|
16
24
|
"files": [
|
package/src/canvas.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
|
|
3
|
+
/** 一档版面(设计坐标:竖屏 360×640、横屏 640×360) */
|
|
4
|
+
export interface CanvasBox {
|
|
5
|
+
'x-position': number;
|
|
6
|
+
'y-position': number;
|
|
7
|
+
width: number;
|
|
8
|
+
height: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** 推送条件:{ 内容配置请求体里的路径: 值 },全部相等才成立,写法同 dynamicExits 的 when */
|
|
12
|
+
export type CanvasWhen = Record<string, string | number | boolean | null>;
|
|
13
|
+
|
|
14
|
+
export interface CanvasElement {
|
|
15
|
+
/** system:登记在 editor_tabs.components,新建节点就有,不能删、不能复制;pushed:page-data 推出来的,编号 display-<tab>-<key> */
|
|
16
|
+
kind: 'system' | 'pushed';
|
|
17
|
+
/** pushed 必填:page-data 里的 key,引用代码里的常量 */
|
|
18
|
+
key?: string;
|
|
19
|
+
/** 所在页签 id */
|
|
20
|
+
tab: string;
|
|
21
|
+
/** pushed 必填:page-data 里的 type(平台拼写 compnent) */
|
|
22
|
+
type?: 'compnent' | 'image' | 'image-ratio-clip' | 'text' | 'video' | 'button';
|
|
23
|
+
/** 英文,给 AI:访客看到什么、模块拿它做什么、运营通常怎么改 */
|
|
24
|
+
description: string;
|
|
25
|
+
/** pushed 必填,英文:什么配置下才推 */
|
|
26
|
+
appearsWhen?: string;
|
|
27
|
+
/** 机器可读的推送条件(可选) */
|
|
28
|
+
when?: CanvasWhen;
|
|
29
|
+
/** 两档默认版面:系统元件写出厂画布的位置,推送元件引用 propertyByRatio 的同一份常量 */
|
|
30
|
+
layout: { v: CanvasBox; h: CanvasBox };
|
|
31
|
+
/** 模块按配置挪自己元件时的版面(共用包 2.31 起 target: 'system',只在运营没动过时挪) */
|
|
32
|
+
layoutVariants?: Record<string, { when?: CanvasWhen; appearsWhen: string; v?: CanvasBox; h?: CanvasBox }>;
|
|
33
|
+
/** 推送元件新建时抄同页哪个元件的样式(共用包 2.32 起) */
|
|
34
|
+
styleFrom?: string;
|
|
35
|
+
/** 模块真读的画布属性 { uuid: { description } };宿主统一套在外框上的位置、大小、字号、颜色、字体不列。类型、范围、选项以 collocation 为准 */
|
|
36
|
+
properties: Record<string, { description: string }>;
|
|
37
|
+
/** 面板上有、模块不读的属性,让 AI 别白改 */
|
|
38
|
+
ignores?: string[];
|
|
39
|
+
/** 图片、视频型:素材从哪来、比例锁 */
|
|
40
|
+
assets?: { source: 'from config' | 'operator' | 'none'; ratioSize?: string; description: string };
|
|
41
|
+
/** 模块自己的摆放规矩;不出屏、不压角标这类平台规矩不写在这里 */
|
|
42
|
+
constraints?: {
|
|
43
|
+
/** 宽:高。写了 face.awayFrom 的,按那条边在上下时写;在左右时盒子横放,读取方把宽高对调 */
|
|
44
|
+
aspect?: string;
|
|
45
|
+
minWidth?: number;
|
|
46
|
+
minHeight?: number;
|
|
47
|
+
anchorsTo?: { element: string; at: 'center' | 'top' | 'bottom' | 'left' | 'right' };
|
|
48
|
+
overlapAllowed?: string[];
|
|
49
|
+
/** 盒子里真正画东西的是一个正方形(如转盘的圆),贴着远离 awayFrom 属性所指那条边的一端;anchorsTo 指向它时对准正方形中心 */
|
|
50
|
+
face?: { shape: 'square'; awayFrom?: string };
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 体验端 src/canvas-config.ts 默认导出的形状 */
|
|
55
|
+
export interface CanvasConfigSpec {
|
|
56
|
+
/** 与 page-data 的 detail.type 同一个字 */
|
|
57
|
+
module: string;
|
|
58
|
+
/** 键 = componentName */
|
|
59
|
+
elements: Record<string, CanvasElement>;
|
|
60
|
+
/** 可选:页签 id → 英文说明 */
|
|
61
|
+
pages?: Record<string, { description: string }>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 构建产物 canvas-config.json 的形状 */
|
|
65
|
+
export interface CanvasConfigFile extends CanvasConfigSpec {
|
|
66
|
+
format: 1;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export declare const CANVAS_FORMAT: 1;
|
|
70
|
+
export declare function validateCanvasConfig(spec: unknown): string[];
|
|
71
|
+
export declare function checkCanvasNames(spec: CanvasConfigSpec, root: string, options?: { files?: string[]; exclude?: string[] }): string[];
|
|
72
|
+
export declare function canvasConfigDoc(spec: CanvasConfigSpec): CanvasConfigFile;
|
|
73
|
+
export declare function buildCanvasConfig(root: string, entry?: string, options?: { files?: string[] }): Promise<CanvasConfigFile>;
|
|
74
|
+
export declare function canvasConfig(options?: { entry?: string; fileName?: string; extraFiles?: string[] }): Plugin;
|
|
75
|
+
export default canvasConfig;
|
package/src/canvas.mjs
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// 画布说明 canvas-config.json(0.5.0 起,待办 #80,PF 2026-10-22 定乙、2026-11-12 定第七节五件事):
|
|
2
|
+
// 模块体验端说明自己放到 UI Editor 画布上的元件,给 AI 摆元件、改属性用。
|
|
3
|
+
// 一个模块一份,构建时由体验端的 src/canvas-config.ts 生成,放在 remoteEntry.js、page-events.js 同一目录。
|
|
4
|
+
//
|
|
5
|
+
// 只写后台登记(collocation)里没有的东西:英文说明、两档默认版面、什么配置下才出现、模块真读的属性、摆放约束。
|
|
6
|
+
// 面板项的类型、默认值、选项、范围以 collocation 为准,这里不重复(PF 2026-11-12「31 甲」)。
|
|
7
|
+
// 推送条件写英文 appearsWhen,另可选填机器能读的 when(「32 乙」),写法同 dynamicExits 的 when:
|
|
8
|
+
// { 内容配置请求体里的路径: 值 },路径是读回的整份请求体(如 Spin and Win 的 design.wheelCount)。
|
|
9
|
+
|
|
10
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { join, resolve, sep } from 'node:path'
|
|
12
|
+
import { pathToFileURL } from 'node:url'
|
|
13
|
+
import { stripScriptComments } from './labels.mjs'
|
|
14
|
+
|
|
15
|
+
export const CANVAS_FORMAT = 1
|
|
16
|
+
|
|
17
|
+
const KINDS = new Set(['system', 'pushed'])
|
|
18
|
+
// page-data 里的 type(平台拼写 compnent,别「修正」)
|
|
19
|
+
const PUSHED_TYPES = new Set(['compnent', 'image', 'image-ratio-clip', 'text', 'video', 'button'])
|
|
20
|
+
const ELEMENT_KEYS = new Set(['kind', 'key', 'tab', 'type', 'description', 'appearsWhen', 'when', 'layout', 'layoutVariants', 'styleFrom', 'properties', 'ignores', 'assets', 'constraints'])
|
|
21
|
+
const BOX_KEYS = ['x-position', 'y-position', 'width', 'height']
|
|
22
|
+
const ASSET_SOURCES = new Set(['from config', 'operator', 'none'])
|
|
23
|
+
const ANCHOR_AT = new Set(['center', 'top', 'bottom', 'left', 'right'])
|
|
24
|
+
const CONSTRAINT_KEYS = new Set(['aspect', 'minWidth', 'minHeight', 'anchorsTo', 'overlapAllowed', 'face'])
|
|
25
|
+
// 说明给 AI 看,一律英文:出现中日韩文字就算没写成英文
|
|
26
|
+
const CJK = /[ -〿㐀-鿿-]/
|
|
27
|
+
|
|
28
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
29
|
+
const isNum = (v) => typeof v === 'number' && Number.isFinite(v)
|
|
30
|
+
const isText = (v) => typeof v === 'string' && v.trim().length > 0
|
|
31
|
+
|
|
32
|
+
function english(errors, where, v) {
|
|
33
|
+
if (!isText(v)) errors.push(`${where}:要写一句英文`)
|
|
34
|
+
else if (CJK.test(v)) errors.push(`${where}:要写英文(给 AI 看),现在有中文`)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function checkWhen(errors, where, when) {
|
|
38
|
+
if (!isObj(when) || !Object.keys(when).length) return errors.push(`${where}:写成 { "请求体里的路径": 值 },至少一条`)
|
|
39
|
+
for (const [k, v] of Object.entries(when)) {
|
|
40
|
+
if (!/^[A-Za-z_$][\w$]*(\.[\w$]+)*$/.test(k)) errors.push(`${where}:路径 ${k} 要用点号分隔的字段名`)
|
|
41
|
+
if (v !== null && !['string', 'number', 'boolean'].includes(typeof v)) errors.push(`${where}.${k}:值只能是字符串、数字、布尔或 null`)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function checkBox(errors, where, box) {
|
|
46
|
+
if (!isObj(box)) return errors.push(`${where}:要写 { x-position, y-position, width, height }`)
|
|
47
|
+
for (const k of BOX_KEYS) if (!isNum(box[k])) errors.push(`${where}.${k}:要是数字`)
|
|
48
|
+
for (const k of Object.keys(box)) if (!BOX_KEYS.includes(k)) errors.push(`${where}:不认识的键 ${k}(只写位置与大小)`)
|
|
49
|
+
if (isNum(box.width) && box.width <= 0) errors.push(`${where}.width:要大于 0`)
|
|
50
|
+
if (isNum(box.height) && box.height <= 0) errors.push(`${where}.height:要大于 0`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function checkLayout(errors, where, layout, { partial = false } = {}) {
|
|
54
|
+
for (const o of ['v', 'h']) {
|
|
55
|
+
if (layout[o] === undefined && partial) continue
|
|
56
|
+
checkBox(errors, `${where}.${o}`, layout[o])
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 检查一份画布说明(src/canvas-config.ts 的默认导出,或产物 canvas-config.json 去掉 format 的部分)。返回问题清单,空数组为通过
|
|
61
|
+
export function validateCanvasConfig(spec) {
|
|
62
|
+
const errors = []
|
|
63
|
+
if (!isObj(spec)) return ['画布说明要是一个对象 { module, elements, pages? }']
|
|
64
|
+
for (const k of Object.keys(spec)) if (!['format', 'module', 'elements', 'pages'].includes(k)) errors.push(`不认识的顶层键 ${k}`)
|
|
65
|
+
if (!isText(spec.module)) errors.push('module:写模块推送里 page-data 的 detail.type(如 spin-and-win)')
|
|
66
|
+
if (!isObj(spec.elements) || !Object.keys(spec.elements).length) {
|
|
67
|
+
errors.push('elements:至少写一个元件,键是 componentName')
|
|
68
|
+
return errors
|
|
69
|
+
}
|
|
70
|
+
const names = new Set(Object.keys(spec.elements))
|
|
71
|
+
const tabs = new Set()
|
|
72
|
+
for (const [name, el] of Object.entries(spec.elements)) {
|
|
73
|
+
const w = `elements.${name}`
|
|
74
|
+
if (!isObj(el)) { errors.push(`${w}:要是一个对象`); continue }
|
|
75
|
+
for (const k of Object.keys(el)) if (!ELEMENT_KEYS.has(k)) errors.push(`${w}:不认识的键 ${k}`)
|
|
76
|
+
if (!KINDS.has(el.kind)) errors.push(`${w}.kind:写 system(登记在 editor_tabs.components)或 pushed(page-data 推出来的)`)
|
|
77
|
+
if (!isText(el.tab)) errors.push(`${w}.tab:写所在页签 id(如 Main)`)
|
|
78
|
+
else tabs.add(el.tab)
|
|
79
|
+
english(errors, `${w}.description`, el.description)
|
|
80
|
+
if (el.kind === 'pushed') {
|
|
81
|
+
if (!isText(el.key)) errors.push(`${w}.key:推送元件要写 page-data 里的 key`)
|
|
82
|
+
if (!PUSHED_TYPES.has(el.type)) errors.push(`${w}.type:推送元件要写 page-data 里的 type(${[...PUSHED_TYPES].join('、')})`)
|
|
83
|
+
english(errors, `${w}.appearsWhen`, el.appearsWhen)
|
|
84
|
+
} else if (el.kind === 'system') {
|
|
85
|
+
if (el.key !== undefined) errors.push(`${w}.key:系统元件没有 key`)
|
|
86
|
+
if (el.type !== undefined && el.type !== 'compnent') errors.push(`${w}.type:系统元件固定是 compnent,可不写`)
|
|
87
|
+
if (el.appearsWhen !== undefined || el.when !== undefined) errors.push(`${w}:系统元件新建节点就有,不写 appearsWhen、when`)
|
|
88
|
+
}
|
|
89
|
+
if (el.when !== undefined) checkWhen(errors, `${w}.when`, el.when)
|
|
90
|
+
if (!isObj(el.layout)) errors.push(`${w}.layout:写两档默认版面 { v: {…}, h: {…} }`)
|
|
91
|
+
else checkLayout(errors, `${w}.layout`, el.layout)
|
|
92
|
+
if (el.layoutVariants !== undefined) {
|
|
93
|
+
if (!isObj(el.layoutVariants)) errors.push(`${w}.layoutVariants:写 { 变体名: { when, appearsWhen, v, h } }`)
|
|
94
|
+
else for (const [vn, v] of Object.entries(el.layoutVariants)) {
|
|
95
|
+
const vw = `${w}.layoutVariants.${vn}`
|
|
96
|
+
if (!isObj(v)) { errors.push(`${vw}:要是一个对象`); continue }
|
|
97
|
+
for (const k of Object.keys(v)) if (!['when', 'appearsWhen', 'v', 'h'].includes(k)) errors.push(`${vw}:不认识的键 ${k}`)
|
|
98
|
+
english(errors, `${vw}.appearsWhen`, v.appearsWhen)
|
|
99
|
+
if (v.when !== undefined) checkWhen(errors, `${vw}.when`, v.when)
|
|
100
|
+
if (v.v === undefined && v.h === undefined) errors.push(`${vw}:v、h 至少写一档`)
|
|
101
|
+
checkLayout(errors, vw, v, { partial: true })
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (el.styleFrom !== undefined && !names.has(el.styleFrom)) errors.push(`${w}.styleFrom:${el.styleFrom} 不是本模块的元件`)
|
|
105
|
+
if (!isObj(el.properties)) errors.push(`${w}.properties:写模块真读的画布属性 { uuid: { description } },一个都不读写 {}`)
|
|
106
|
+
else for (const [uuid, p] of Object.entries(el.properties)) {
|
|
107
|
+
if (!isObj(p)) { errors.push(`${w}.properties.${uuid}:写 { description }`); continue }
|
|
108
|
+
for (const k of Object.keys(p)) if (k !== 'description') errors.push(`${w}.properties.${uuid}:只写 description(类型、范围、选项以后台登记的 collocation 为准)`)
|
|
109
|
+
english(errors, `${w}.properties.${uuid}.description`, p.description)
|
|
110
|
+
}
|
|
111
|
+
if (el.ignores !== undefined) {
|
|
112
|
+
if (!Array.isArray(el.ignores) || !el.ignores.every(isText)) errors.push(`${w}.ignores:写属性 uuid 的数组`)
|
|
113
|
+
else for (const u of el.ignores) if (isObj(el.properties) && u in el.properties) errors.push(`${w}.ignores:${u} 同时写在 properties 里`)
|
|
114
|
+
}
|
|
115
|
+
if (el.assets !== undefined) {
|
|
116
|
+
const a = el.assets
|
|
117
|
+
if (!isObj(a)) errors.push(`${w}.assets:写 { source, ratioSize?, description }`)
|
|
118
|
+
else {
|
|
119
|
+
for (const k of Object.keys(a)) if (!['source', 'ratioSize', 'description'].includes(k)) errors.push(`${w}.assets:不认识的键 ${k}`)
|
|
120
|
+
if (!ASSET_SOURCES.has(a.source)) errors.push(`${w}.assets.source:写 ${[...ASSET_SOURCES].join('、')} 之一`)
|
|
121
|
+
if (a.ratioSize !== undefined && !/^\d+(\.\d+)?:\d+(\.\d+)?$/.test(a.ratioSize)) errors.push(`${w}.assets.ratioSize:写成 "宽:高"`)
|
|
122
|
+
english(errors, `${w}.assets.description`, a.description)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (el.constraints !== undefined) {
|
|
126
|
+
const c = el.constraints
|
|
127
|
+
if (!isObj(c)) { errors.push(`${w}.constraints:要是一个对象`); continue }
|
|
128
|
+
for (const k of Object.keys(c)) if (!CONSTRAINT_KEYS.has(k)) errors.push(`${w}.constraints:不认识的键 ${k}(平台规矩不写在这里)`)
|
|
129
|
+
if (c.aspect !== undefined && !/^\d+(\.\d+)?:\d+(\.\d+)?$/.test(c.aspect)) errors.push(`${w}.constraints.aspect:写成 "宽:高"`)
|
|
130
|
+
for (const k of ['minWidth', 'minHeight']) if (c[k] !== undefined && !(isNum(c[k]) && c[k] > 0)) errors.push(`${w}.constraints.${k}:要是正数`)
|
|
131
|
+
if (c.anchorsTo !== undefined) {
|
|
132
|
+
if (!isObj(c.anchorsTo) || !names.has(c.anchorsTo.element) || c.anchorsTo.element === name) errors.push(`${w}.constraints.anchorsTo.element:要是本模块的另一个元件`)
|
|
133
|
+
if (!ANCHOR_AT.has(c.anchorsTo?.at)) errors.push(`${w}.constraints.anchorsTo.at:写 ${[...ANCHOR_AT].join('、')} 之一`)
|
|
134
|
+
}
|
|
135
|
+
// face:盒子里真正画东西的是一个正方形(转盘的圆),贴着远离某条边的一端放;那条边由一个属性给(top / right / bottom / left)。
|
|
136
|
+
// anchorsTo 指向它的元件对准的是这个正方形的中心,不是盒子中心
|
|
137
|
+
if (c.face !== undefined) {
|
|
138
|
+
if (!isObj(c.face) || c.face.shape !== 'square') errors.push(`${w}.constraints.face:写 { shape: 'square', awayFrom: '<属性 uuid>' }`)
|
|
139
|
+
else if (c.face.awayFrom !== undefined && !(isObj(el.properties) && c.face.awayFrom in el.properties)) errors.push(`${w}.constraints.face.awayFrom:${c.face.awayFrom} 要是 properties 里的属性(值为 top、right、bottom、left)`)
|
|
140
|
+
for (const k of Object.keys(c.face ?? {})) if (!['shape', 'awayFrom'].includes(k)) errors.push(`${w}.constraints.face:不认识的键 ${k}`)
|
|
141
|
+
}
|
|
142
|
+
if (c.overlapAllowed !== undefined) {
|
|
143
|
+
if (!Array.isArray(c.overlapAllowed)) errors.push(`${w}.constraints.overlapAllowed:写元件名的数组`)
|
|
144
|
+
else for (const o of c.overlapAllowed) if (!names.has(o) || o === name) errors.push(`${w}.constraints.overlapAllowed:${o} 不是本模块的另一个元件`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (spec.pages !== undefined) {
|
|
149
|
+
if (!isObj(spec.pages)) errors.push('pages:写 { 页签 id: { description } }')
|
|
150
|
+
else for (const [tab, p] of Object.entries(spec.pages)) {
|
|
151
|
+
if (!isObj(p)) { errors.push(`pages.${tab}:写 { description }`); continue }
|
|
152
|
+
for (const k of Object.keys(p)) if (k !== 'description') errors.push(`pages.${tab}:只写 description`)
|
|
153
|
+
english(errors, `pages.${tab}.description`, p.description)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return errors
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 推送元件的 key 与 componentName、本模块的 module 名都要在构建用到的源码里(去掉注释后)原样出现过,
|
|
160
|
+
// 防止推送改了名字说明没跟上。说明文件本身不算
|
|
161
|
+
export function checkCanvasNames(spec, root, { files = [], exclude = [] } = {}) {
|
|
162
|
+
const src = resolve(root, 'src') + sep
|
|
163
|
+
const skip = new Set(exclude.map((e) => resolve(root, e)))
|
|
164
|
+
const texts = files
|
|
165
|
+
.map((f) => resolve(f))
|
|
166
|
+
.filter((f) => f.startsWith(src) && !skip.has(f) && /\.(vue|ts|tsx|js|jsx|mjs)$/.test(f))
|
|
167
|
+
.map((f) => { try { return stripScriptComments(readFileSync(f, 'utf8')) } catch { return '' } })
|
|
168
|
+
const all = texts.join('\n')
|
|
169
|
+
const has = (s) => all.includes(`'${s}'`) || all.includes(`"${s}"`) || all.includes(`\`${s}\``)
|
|
170
|
+
const missing = []
|
|
171
|
+
if (isText(spec.module) && !has(spec.module)) missing.push(`module ${spec.module} 在源码里找不到(应与 page-data 的 detail.type 同一个字)`)
|
|
172
|
+
for (const [name, el] of Object.entries(spec.elements ?? {})) {
|
|
173
|
+
if (el?.kind !== 'pushed') continue
|
|
174
|
+
if (!has(name)) missing.push(`elements.${name}:推送元件的 componentName 在源码里找不到`)
|
|
175
|
+
if (isText(el.key) && !has(el.key)) missing.push(`elements.${name}.key:${el.key} 在源码里找不到`)
|
|
176
|
+
}
|
|
177
|
+
return missing
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 产物:format 在最前,键的顺序照源文件
|
|
181
|
+
export function canvasConfigDoc(spec) {
|
|
182
|
+
const doc = { format: CANVAS_FORMAT, module: spec.module, elements: spec.elements }
|
|
183
|
+
if (spec.pages !== undefined) doc.pages = spec.pages
|
|
184
|
+
return JSON.parse(JSON.stringify(doc))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function loadSpecFile(root, entry) {
|
|
188
|
+
let build
|
|
189
|
+
try { ({ build } = await import('esbuild')) } catch { throw new Error('canvas-config:构建时要用 esbuild 加载 src/canvas-config.ts(vite 自带)。这个项目里找不到它,请 npm install -D esbuild') }
|
|
190
|
+
const dir = join(root, 'node_modules', '.content-config')
|
|
191
|
+
mkdirSync(dir, { recursive: true })
|
|
192
|
+
const out = join(dir, `canvas-${process.pid}-${Date.now()}.mjs`)
|
|
193
|
+
const result = await build({ entryPoints: [resolve(root, entry)], bundle: true, format: 'esm', platform: 'node', packages: 'external', write: false, logLevel: 'silent', alias: { '@': resolve(root, 'src') } })
|
|
194
|
+
writeFileSync(out, result.outputFiles[0].text)
|
|
195
|
+
try { return (await import(pathToFileURL(out).href)).default } finally { rmSync(out, { force: true }) }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// 读出说明、检查、核对名字,返回要写进 canvas-config.json 的内容;不合规时抛错,逐条列出
|
|
199
|
+
export async function buildCanvasConfig(root, entry = 'src/canvas-config.ts', { files } = {}) {
|
|
200
|
+
const spec = await loadSpecFile(root, entry)
|
|
201
|
+
const errors = validateCanvasConfig(spec)
|
|
202
|
+
if (!errors.length && files) errors.push(...checkCanvasNames(spec, root, { files, exclude: [entry] }))
|
|
203
|
+
if (errors.length) throw new Error(`canvas-config:画布说明没通过检查(${errors.length} 处)\n ${errors.join('\n ')}`)
|
|
204
|
+
return canvasConfigDoc(spec)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// vite 插件:体验端 vite.config 里加 canvasConfig(),构建时生成 assets/canvas-config.json(与 page-events.js 同目录)
|
|
208
|
+
export function canvasConfig({ entry = 'src/canvas-config.ts', fileName = 'assets/canvas-config.json', extraFiles = ['src/page-events.ts'] } = {}) {
|
|
209
|
+
let root = process.cwd()
|
|
210
|
+
return {
|
|
211
|
+
name: 'realnation-canvas-config',
|
|
212
|
+
apply: 'build',
|
|
213
|
+
configResolved(config) { root = config.root },
|
|
214
|
+
async generateBundle() {
|
|
215
|
+
// 构建用到的源码,加上只在推送清单(page-events.ts,另打的包)里用到的源码
|
|
216
|
+
const used = [...this.getModuleIds()].filter((id) => !id.startsWith('\0')).map((id) => id.split('?')[0])
|
|
217
|
+
const files = [...used, ...extraFiles.map((f) => resolve(root, f))]
|
|
218
|
+
let doc
|
|
219
|
+
try { doc = await buildCanvasConfig(root, entry, { files }) } catch (e) { this.error(e.message) }
|
|
220
|
+
this.emitFile({ type: 'asset', fileName, source: JSON.stringify(doc, null, 2) + '\n' })
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export default canvasConfig
|
package/src/exits.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { JsonSchema } from './validate';
|
|
2
|
+
|
|
3
|
+
type Scalar = string | number | boolean | null;
|
|
4
|
+
|
|
5
|
+
/** 固定出口:when 里的路径(点号分隔,从请求体算起)都等于给的值才有这个出口;模板只能写原文 */
|
|
6
|
+
export interface FixedExitRule {
|
|
7
|
+
id: string;
|
|
8
|
+
event: string;
|
|
9
|
+
name: string | readonly string[];
|
|
10
|
+
when?: Record<string, Scalar>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 列表里每一项一个出口。each 是请求体里列表的路径(如 'detail.numbers'),where 里的字段都相等的项才算。
|
|
15
|
+
* id、event、name 是模板:{字段} 换成这一项的字段值(去掉首尾空白),{index} 是在整个列表里的序号,{n} 是在通过 where 的项里的序号(从 1 起);
|
|
16
|
+
* 有一处换成空串整个模板就算空,name 给数组时取第一个不空的。
|
|
17
|
+
*/
|
|
18
|
+
export interface EachExitRule {
|
|
19
|
+
each: string;
|
|
20
|
+
where?: Record<string, Scalar>;
|
|
21
|
+
id: string;
|
|
22
|
+
event: string;
|
|
23
|
+
name: string | readonly string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type DynamicExitRule = FixedExitRule | EachExitRule;
|
|
27
|
+
|
|
28
|
+
/** 算出来的一个出口,对应配置页推给宿主 setAccessDynamicPorts 的 { key, event, name } */
|
|
29
|
+
export interface DynamicExit {
|
|
30
|
+
id: string;
|
|
31
|
+
event: string;
|
|
32
|
+
name: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 按规则从(保存后读回的)请求体算出口;id 为空、event 为空、id 重复的跳过,与 Builder 相同 */
|
|
36
|
+
export declare function computeExits(rules: readonly DynamicExitRule[] | undefined, body: unknown): DynamicExit[];
|
|
37
|
+
/** 检查规则写法;给了字段说明与出厂请求体时再核对路径、字段与算出的出口 id。返回问题清单,空数组 = 通过 */
|
|
38
|
+
export declare function checkExitRules(rules: unknown, options?: { schema?: JsonSchema; body?: unknown }): string[];
|
package/src/exits.mjs
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// 动态出口规则(0.4.0 起):有的模块的出口不是写死在模块目录里的,而是配置页按内容配置算出来、
|
|
2
|
+
// 保存时经宿主 setAccessDynamicPorts 推给 Builder 的(Dial Pad 每个号码一个、Access Time 每个放行规则组一个……)。
|
|
3
|
+
// 模块在 content-config.ts 里用数据把同一套算法写出来(dynamicExits),建活动 skill 拿保存后读回的请求体照着算,
|
|
4
|
+
// 不执行模块代码,也就不用打开配置页。
|
|
5
|
+
//
|
|
6
|
+
// 一条规则是下面两种之一:
|
|
7
|
+
// { id, event, name, when? } 固定出口。when 是 { 请求体里的路径: 值 },这些路径上的值都等于给的值才有这个出口
|
|
8
|
+
// { each, where?, id, event, name } 列表里每一项一个出口。each 是请求体里列表的路径(点号分隔,如 detail.numbers);
|
|
9
|
+
// where 是 { 项里的字段: 值 },都相等的项才算
|
|
10
|
+
// id、event、name 都是模板:{字段} 换成这一项里那个字段的值(转成字符串、去掉首尾空白),{index} 是这一项在整个列表里的
|
|
11
|
+
// 序号,{n} 是它在通过 where 的项里的序号(都从 1 起)。固定出口的模板只能写原文。模板里只要有一处换成了空串,
|
|
12
|
+
// 整个模板就算空;name 可以给数组,按顺序取第一个不空的。
|
|
13
|
+
// 出口按规则的顺序、列表的顺序排;id 为空、event 为空、id 与前面重复的跳过(与 Builder 收到出口时的做法相同,
|
|
14
|
+
// qik-sense-partner src/views/flow-items/content-config.vue 的 normalizeAccessDynamicPorts)。
|
|
15
|
+
|
|
16
|
+
const PLACEHOLDER = /\{([^{}]+)\}/g
|
|
17
|
+
const RULE_KEYS = new Set(['each', 'where', 'when', 'id', 'event', 'name'])
|
|
18
|
+
|
|
19
|
+
function at(obj, path) {
|
|
20
|
+
let cur = obj
|
|
21
|
+
for (const seg of path.split('.')) {
|
|
22
|
+
if (cur === null || typeof cur !== 'object') return undefined
|
|
23
|
+
cur = cur[seg]
|
|
24
|
+
}
|
|
25
|
+
return cur
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const matches = (obj, cond, get) => Object.entries(cond ?? {}).every(([k, v]) => get(obj, k) === v)
|
|
29
|
+
|
|
30
|
+
function fill(template, item, index, n) {
|
|
31
|
+
let empty = false
|
|
32
|
+
const out = template.replace(PLACEHOLDER, (_, field) => {
|
|
33
|
+
const v = field === 'index' ? index : field === 'n' ? n : item?.[field]
|
|
34
|
+
const s = v === undefined || v === null ? '' : String(v).trim()
|
|
35
|
+
if (!s) empty = true
|
|
36
|
+
return s
|
|
37
|
+
})
|
|
38
|
+
return empty ? '' : out.trim()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const firstFilled = (names, item, index, n) => {
|
|
42
|
+
for (const t of Array.isArray(names) ? names : [names]) {
|
|
43
|
+
const s = fill(t, item, index, n)
|
|
44
|
+
if (s) return s
|
|
45
|
+
}
|
|
46
|
+
return ''
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 按规则算出口:[{ id, event, name }],与配置页推给 Builder 的 key、event、name 一一对应
|
|
50
|
+
export function computeExits(rules, body) {
|
|
51
|
+
const out = []
|
|
52
|
+
const seen = new Set()
|
|
53
|
+
const push = (id, event, name) => {
|
|
54
|
+
if (!id || !event || seen.has(id)) return
|
|
55
|
+
seen.add(id)
|
|
56
|
+
out.push({ id, event, name: name || event })
|
|
57
|
+
}
|
|
58
|
+
for (const rule of rules ?? []) {
|
|
59
|
+
if (rule.each === undefined) {
|
|
60
|
+
if (matches(body, rule.when, at)) push(fill(rule.id), fill(rule.event), firstFilled(rule.name))
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
const list = at(body, rule.each)
|
|
64
|
+
if (!Array.isArray(list)) continue
|
|
65
|
+
let n = 0
|
|
66
|
+
list.forEach((item, i) => {
|
|
67
|
+
if (!matches(item, rule.where, (o, k) => o?.[k])) return
|
|
68
|
+
n += 1
|
|
69
|
+
push(fill(rule.id, item, i + 1, n), fill(rule.event, item, i + 1, n), firstFilled(rule.name, item, i + 1, n))
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
return out
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 字段说明里某个路径(点号分隔)对应的子说明;走不下去时给 undefined
|
|
76
|
+
function schemaAt(schema, path) {
|
|
77
|
+
let cur = schema
|
|
78
|
+
for (const seg of path.split('.')) {
|
|
79
|
+
cur = cur?.properties?.[seg]
|
|
80
|
+
if (!cur) return undefined
|
|
81
|
+
}
|
|
82
|
+
return cur
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 检查规则的写法;给了字段说明与出厂请求体,再核对路径与字段都对得上、出厂请求体能算出合法的出口。返回问题清单
|
|
86
|
+
export function checkExitRules(rules, { schema, body } = {}) {
|
|
87
|
+
const errors = []
|
|
88
|
+
if (!Array.isArray(rules)) return ['dynamicExits 要写成数组']
|
|
89
|
+
rules.forEach((rule, i) => {
|
|
90
|
+
const at$ = `dynamicExits[${i}]`
|
|
91
|
+
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) return errors.push(`${at$} 要写成对象`)
|
|
92
|
+
for (const k of Object.keys(rule)) if (!RULE_KEYS.has(k)) errors.push(`${at$} 有不认识的键 ${k}`)
|
|
93
|
+
const isEach = rule.each !== undefined
|
|
94
|
+
if (isEach && typeof rule.each !== 'string') errors.push(`${at$}.each 要写列表的路径(字符串)`)
|
|
95
|
+
if (isEach && rule.when !== undefined) errors.push(`${at$} 按列表出的出口用 where,不用 when`)
|
|
96
|
+
if (!isEach && rule.where !== undefined) errors.push(`${at$} 固定出口用 when,不用 where`)
|
|
97
|
+
for (const k of ['where', 'when']) {
|
|
98
|
+
const c = rule[k]
|
|
99
|
+
if (c === undefined) continue
|
|
100
|
+
if (!c || typeof c !== 'object' || Array.isArray(c)) { errors.push(`${at$}.${k} 要写成 { 字段: 值 }`); continue }
|
|
101
|
+
for (const [f, v] of Object.entries(c)) if (v !== null && typeof v === 'object') errors.push(`${at$}.${k}.${f} 的值只能是字符串、数字、布尔或 null`)
|
|
102
|
+
}
|
|
103
|
+
const names = Array.isArray(rule.name) ? rule.name : [rule.name]
|
|
104
|
+
const templates = [['id', rule.id], ['event', rule.event], ...names.map((t, j) => [Array.isArray(rule.name) ? `name[${j}]` : 'name', t])]
|
|
105
|
+
if (!names.length) errors.push(`${at$}.name 不能是空数组`)
|
|
106
|
+
for (const [k, t] of templates) {
|
|
107
|
+
if (typeof t !== 'string' || !t.trim()) { errors.push(`${at$}.${k} 要写成非空字符串`); continue }
|
|
108
|
+
const fields = [...t.matchAll(PLACEHOLDER)].map((m) => m[1])
|
|
109
|
+
if (!isEach && fields.length) errors.push(`${at$}.${k} 是固定出口,不能用 {${fields[0]}}`)
|
|
110
|
+
if (isEach && schema && typeof rule.each === 'string') {
|
|
111
|
+
const props = schemaAt(schema, rule.each)?.items?.properties
|
|
112
|
+
for (const f of fields) if (props && f !== 'index' && f !== 'n' && !props[f]) errors.push(`${at$}.${k} 里的 {${f}} 不是 ${rule.each} 列表项的字段`)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (isEach && schema && typeof rule.each === 'string') {
|
|
116
|
+
const list = schemaAt(schema, rule.each)
|
|
117
|
+
if (!list) errors.push(`${at$}.each:字段说明里没有 ${rule.each}`)
|
|
118
|
+
else if (!list.items) errors.push(`${at$}.each:${rule.each} 在字段说明里不是列表`)
|
|
119
|
+
const props = list?.items?.properties
|
|
120
|
+
for (const f of Object.keys(rule.where ?? {})) if (props && !props[f]) errors.push(`${at$}.where 里的 ${f} 不是 ${rule.each} 列表项的字段`)
|
|
121
|
+
}
|
|
122
|
+
if (!isEach && schema) for (const p of Object.keys(rule.when ?? {})) if (!schemaAt(schema, p)) errors.push(`${at$}.when:字段说明里没有 ${p}`)
|
|
123
|
+
})
|
|
124
|
+
if (!errors.length && body !== undefined) {
|
|
125
|
+
// 连线的键按「源-模块-端口-目标」用横杠拆开(Builder 与后端都这样读),所以出口 id 里不能有横杠
|
|
126
|
+
for (const e of computeExits(rules, body)) if (e.id.includes('-')) errors.push(`出厂请求体算出的出口 id「${e.id}」里有横杠,连线的键会拆错`)
|
|
127
|
+
}
|
|
128
|
+
return errors
|
|
129
|
+
}
|
package/src/index.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import type { Plugin } from 'vite';
|
|
2
2
|
import type { JsonSchema } from './validate';
|
|
3
|
+
import type { DynamicExitRule } from './exits';
|
|
3
4
|
|
|
4
5
|
export type { JsonSchema } from './validate';
|
|
5
6
|
export { validate, SUPPORTED_KEYWORDS } from './validate';
|
|
7
|
+
export type { DynamicExitRule, FixedExitRule, EachExitRule, DynamicExit } from './exits';
|
|
8
|
+
export { computeExits, checkExitRules } from './exits';
|
|
6
9
|
|
|
7
10
|
/** 模块 src/content-config.ts 默认导出的形状 */
|
|
8
11
|
export interface ContentConfigSpec<Body = unknown> {
|
|
@@ -12,6 +15,8 @@ export interface ContentConfigSpec<Body = unknown> {
|
|
|
12
15
|
defaultBody: Body | (() => Body | Promise<Body>);
|
|
13
16
|
/** 请求体的字段说明 */
|
|
14
17
|
schema: JsonSchema;
|
|
18
|
+
/** 配置页按内容配置算出、保存时推给宿主 setAccessDynamicPorts 的出口,用数据写成的同一套算法(0.4.0 起);出口全在模块目录里的模块不写 */
|
|
19
|
+
dynamicExits?: readonly DynamicExitRule[];
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
/** 构建产物 content-config.json 的形状 */
|
|
@@ -20,6 +25,8 @@ export interface ContentConfigFile<Body = unknown> {
|
|
|
20
25
|
endpoint: string;
|
|
21
26
|
defaultBody: Body;
|
|
22
27
|
schema: JsonSchema;
|
|
28
|
+
/** 模块写了 dynamicExits 才有 */
|
|
29
|
+
dynamicExits?: readonly DynamicExitRule[];
|
|
23
30
|
}
|
|
24
31
|
|
|
25
32
|
export interface ContentConfigPluginOptions {
|
package/src/index.mjs
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export { default, buildContentConfig, loadSpec, checkLabels, collectLabels, FORMAT } from './vite-plugin.mjs'
|
|
2
|
-
export { validate, SUPPORTED_KEYWORDS } from './validate.mjs'
|
|
1
|
+
export { default, buildContentConfig, loadSpec, checkLabels, collectLabels, FORMAT } from './vite-plugin.mjs'
|
|
2
|
+
export { validate, SUPPORTED_KEYWORDS } from './validate.mjs'
|
|
3
|
+
export { computeExits, checkExitRules } from './exits.mjs'
|
package/src/labels.mjs
CHANGED
|
@@ -1,110 +1,110 @@
|
|
|
1
|
-
// 核对字段名:配置页不动,说明自己写 x-label(PF 2026-09-29)。为防配置页改了名字说明没跟上,
|
|
2
|
-
// 每个 x-label 按「 · 」拆开后,每一段都要在模块源码里原样出现过(说明文件本身不算)。
|
|
3
|
-
// 0.3.0 起去掉注释再核对;vite 插件只拿构建实际用到的源码来核对,旧名字只留在注释或没人引用的文件里时不再漏检。
|
|
4
|
-
|
|
5
|
-
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
6
|
-
import { extname, join, resolve, sep } from 'node:path'
|
|
7
|
-
|
|
8
|
-
const SOURCE_EXTENSIONS = new Set(['.vue', '.ts', '.tsx', '.js', '.jsx', '.mjs'])
|
|
9
|
-
|
|
10
|
-
const isSubSchema = (s) => typeof s === 'object' && s !== null && !Array.isArray(s)
|
|
11
|
-
|
|
12
|
-
// 字段说明里所有的 x-label,连同它在说明里的位置
|
|
13
|
-
export function collectLabels(schema, path = '$') {
|
|
14
|
-
const found = []
|
|
15
|
-
if (!schema || typeof schema !== 'object') return found
|
|
16
|
-
if (typeof schema['x-label'] === 'string') found.push({ path, label: schema['x-label'] })
|
|
17
|
-
for (const [key, sub] of Object.entries(schema.properties ?? {})) found.push(...collectLabels(sub, `${path}.${key}`))
|
|
18
|
-
if (isSubSchema(schema.additionalProperties)) found.push(...collectLabels(schema.additionalProperties, `${path}.*`))
|
|
19
|
-
if (schema.items) found.push(...collectLabels(schema.items, `${path}[]`))
|
|
20
|
-
for (const sub of schema.anyOf ?? []) found.push(...collectLabels(sub, path))
|
|
21
|
-
return found
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function* sourceFiles(dir) {
|
|
25
|
-
for (const name of readdirSync(dir)) {
|
|
26
|
-
const p = join(dir, name)
|
|
27
|
-
if (statSync(p).isDirectory()) yield* sourceFiles(p)
|
|
28
|
-
else if (SOURCE_EXTENSIONS.has(extname(name))) yield p
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// 去掉脚本里的 // 与 /* */ 注释。字符串与模板字符串里的照留(如网址);不认正则字面量,
|
|
33
|
-
// 但 '、" 字符串不跨行,认错时最多影响那一行
|
|
34
|
-
export function stripScriptComments(code) {
|
|
35
|
-
let out = ''
|
|
36
|
-
let quote = null
|
|
37
|
-
for (let i = 0; i < code.length; i++) {
|
|
38
|
-
const c = code[i]
|
|
39
|
-
if (quote) {
|
|
40
|
-
out += c
|
|
41
|
-
if (c === '\\' && i + 1 < code.length) out += code[++i]
|
|
42
|
-
else if (c === quote || (c === '\n' && quote !== '`')) quote = null
|
|
43
|
-
continue
|
|
44
|
-
}
|
|
45
|
-
if (c === '/' && code[i + 1] === '/') {
|
|
46
|
-
while (i + 1 < code.length && code[i + 1] !== '\n') i++
|
|
47
|
-
continue
|
|
48
|
-
}
|
|
49
|
-
if (c === '/' && code[i + 1] === '*') {
|
|
50
|
-
const end = code.indexOf('*/', i + 2)
|
|
51
|
-
i = end < 0 ? code.length : end + 1
|
|
52
|
-
out += ' '
|
|
53
|
-
continue
|
|
54
|
-
}
|
|
55
|
-
if (c === '"' || c === "'" || c === '`') quote = c
|
|
56
|
-
out += c
|
|
57
|
-
}
|
|
58
|
-
return out
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// .vue 文件:去掉 <!-- --> 注释,<script> 里按脚本去注释;模板正文里的 // 是文字(如网址),不动
|
|
62
|
-
export function stripComments(text, ext) {
|
|
63
|
-
if (ext !== '.vue') return stripScriptComments(text)
|
|
64
|
-
return text
|
|
65
|
-
.replace(/<!--[\s\S]*?-->/g, ' ')
|
|
66
|
-
.replace(/(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g, (_, open, body, close) => open + stripScriptComments(body) + close)
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// 模板里的文字常写成 HTML 转义(如 Playlists & Tracks),页面上显示的是转义前的样子;
|
|
70
|
-
// x-label 写页面上看到的,所以核对时两种写法都认
|
|
71
|
-
const decodeEntities = (s) =>
|
|
72
|
-
s
|
|
73
|
-
.replace(/&/g, '&')
|
|
74
|
-
.replace(/</g, '<')
|
|
75
|
-
.replace(/>/g, '>')
|
|
76
|
-
.replace(/"/g, '"')
|
|
77
|
-
.replace(/'|'/g, "'")
|
|
78
|
-
.replace(/ /g, ' ')
|
|
79
|
-
|
|
80
|
-
// Windows 上路径不分大小写
|
|
81
|
-
const pathKey = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p))
|
|
82
|
-
|
|
83
|
-
// files:构建实际用到的源码(vite 插件从模块图里取)。只留 dirs 下、扩展名对得上、确实存在的文件;
|
|
84
|
-
// 不传就照旧扫 dirs 下全部源码(不经 vite 直接调用时)
|
|
85
|
-
function filesToCheck(root, dirs, files) {
|
|
86
|
-
if (!files) return dirs.flatMap((dir) => [...sourceFiles(resolve(root, dir))])
|
|
87
|
-
const bases = dirs.map((dir) => pathKey(resolve(root, dir)) + sep)
|
|
88
|
-
const seen = new Map()
|
|
89
|
-
for (const f of files) {
|
|
90
|
-
const k = pathKey(f)
|
|
91
|
-
if (SOURCE_EXTENSIONS.has(extname(f)) && bases.some((b) => k.startsWith(b)) && existsSync(f)) seen.set(k, resolve(f))
|
|
92
|
-
}
|
|
93
|
-
return [...seen.values()]
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
export function checkLabels(schema, root, { dirs = ['src'], exclude = [], files } = {}) {
|
|
97
|
-
const excluded = new Set(exclude.map((f) => pathKey(resolve(root, f))))
|
|
98
|
-
let text = ''
|
|
99
|
-
for (const file of filesToCheck(root, dirs, files)) {
|
|
100
|
-
if (!excluded.has(pathKey(file))) text += stripComments(readFileSync(file, 'utf8'), extname(file)) + '\n'
|
|
101
|
-
}
|
|
102
|
-
text += '\n' + decodeEntities(text)
|
|
103
|
-
const problems = []
|
|
104
|
-
for (const { path, label } of collectLabels(schema)) {
|
|
105
|
-
for (const part of label.split(' · ')) {
|
|
106
|
-
if (!text.includes(part)) problems.push(`${path}:x-label「${label}」里的「${part}」在配置页源码里找不到`)
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
return problems
|
|
110
|
-
}
|
|
1
|
+
// 核对字段名:配置页不动,说明自己写 x-label(PF 2026-09-29)。为防配置页改了名字说明没跟上,
|
|
2
|
+
// 每个 x-label 按「 · 」拆开后,每一段都要在模块源码里原样出现过(说明文件本身不算)。
|
|
3
|
+
// 0.3.0 起去掉注释再核对;vite 插件只拿构建实际用到的源码来核对,旧名字只留在注释或没人引用的文件里时不再漏检。
|
|
4
|
+
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
6
|
+
import { extname, join, resolve, sep } from 'node:path'
|
|
7
|
+
|
|
8
|
+
const SOURCE_EXTENSIONS = new Set(['.vue', '.ts', '.tsx', '.js', '.jsx', '.mjs'])
|
|
9
|
+
|
|
10
|
+
const isSubSchema = (s) => typeof s === 'object' && s !== null && !Array.isArray(s)
|
|
11
|
+
|
|
12
|
+
// 字段说明里所有的 x-label,连同它在说明里的位置
|
|
13
|
+
export function collectLabels(schema, path = '$') {
|
|
14
|
+
const found = []
|
|
15
|
+
if (!schema || typeof schema !== 'object') return found
|
|
16
|
+
if (typeof schema['x-label'] === 'string') found.push({ path, label: schema['x-label'] })
|
|
17
|
+
for (const [key, sub] of Object.entries(schema.properties ?? {})) found.push(...collectLabels(sub, `${path}.${key}`))
|
|
18
|
+
if (isSubSchema(schema.additionalProperties)) found.push(...collectLabels(schema.additionalProperties, `${path}.*`))
|
|
19
|
+
if (schema.items) found.push(...collectLabels(schema.items, `${path}[]`))
|
|
20
|
+
for (const sub of schema.anyOf ?? []) found.push(...collectLabels(sub, path))
|
|
21
|
+
return found
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function* sourceFiles(dir) {
|
|
25
|
+
for (const name of readdirSync(dir)) {
|
|
26
|
+
const p = join(dir, name)
|
|
27
|
+
if (statSync(p).isDirectory()) yield* sourceFiles(p)
|
|
28
|
+
else if (SOURCE_EXTENSIONS.has(extname(name))) yield p
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 去掉脚本里的 // 与 /* */ 注释。字符串与模板字符串里的照留(如网址);不认正则字面量,
|
|
33
|
+
// 但 '、" 字符串不跨行,认错时最多影响那一行
|
|
34
|
+
export function stripScriptComments(code) {
|
|
35
|
+
let out = ''
|
|
36
|
+
let quote = null
|
|
37
|
+
for (let i = 0; i < code.length; i++) {
|
|
38
|
+
const c = code[i]
|
|
39
|
+
if (quote) {
|
|
40
|
+
out += c
|
|
41
|
+
if (c === '\\' && i + 1 < code.length) out += code[++i]
|
|
42
|
+
else if (c === quote || (c === '\n' && quote !== '`')) quote = null
|
|
43
|
+
continue
|
|
44
|
+
}
|
|
45
|
+
if (c === '/' && code[i + 1] === '/') {
|
|
46
|
+
while (i + 1 < code.length && code[i + 1] !== '\n') i++
|
|
47
|
+
continue
|
|
48
|
+
}
|
|
49
|
+
if (c === '/' && code[i + 1] === '*') {
|
|
50
|
+
const end = code.indexOf('*/', i + 2)
|
|
51
|
+
i = end < 0 ? code.length : end + 1
|
|
52
|
+
out += ' '
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
if (c === '"' || c === "'" || c === '`') quote = c
|
|
56
|
+
out += c
|
|
57
|
+
}
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// .vue 文件:去掉 <!-- --> 注释,<script> 里按脚本去注释;模板正文里的 // 是文字(如网址),不动
|
|
62
|
+
export function stripComments(text, ext) {
|
|
63
|
+
if (ext !== '.vue') return stripScriptComments(text)
|
|
64
|
+
return text
|
|
65
|
+
.replace(/<!--[\s\S]*?-->/g, ' ')
|
|
66
|
+
.replace(/(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g, (_, open, body, close) => open + stripScriptComments(body) + close)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 模板里的文字常写成 HTML 转义(如 Playlists & Tracks),页面上显示的是转义前的样子;
|
|
70
|
+
// x-label 写页面上看到的,所以核对时两种写法都认
|
|
71
|
+
const decodeEntities = (s) =>
|
|
72
|
+
s
|
|
73
|
+
.replace(/&/g, '&')
|
|
74
|
+
.replace(/</g, '<')
|
|
75
|
+
.replace(/>/g, '>')
|
|
76
|
+
.replace(/"/g, '"')
|
|
77
|
+
.replace(/'|'/g, "'")
|
|
78
|
+
.replace(/ /g, ' ')
|
|
79
|
+
|
|
80
|
+
// Windows 上路径不分大小写
|
|
81
|
+
const pathKey = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p))
|
|
82
|
+
|
|
83
|
+
// files:构建实际用到的源码(vite 插件从模块图里取)。只留 dirs 下、扩展名对得上、确实存在的文件;
|
|
84
|
+
// 不传就照旧扫 dirs 下全部源码(不经 vite 直接调用时)
|
|
85
|
+
function filesToCheck(root, dirs, files) {
|
|
86
|
+
if (!files) return dirs.flatMap((dir) => [...sourceFiles(resolve(root, dir))])
|
|
87
|
+
const bases = dirs.map((dir) => pathKey(resolve(root, dir)) + sep)
|
|
88
|
+
const seen = new Map()
|
|
89
|
+
for (const f of files) {
|
|
90
|
+
const k = pathKey(f)
|
|
91
|
+
if (SOURCE_EXTENSIONS.has(extname(f)) && bases.some((b) => k.startsWith(b)) && existsSync(f)) seen.set(k, resolve(f))
|
|
92
|
+
}
|
|
93
|
+
return [...seen.values()]
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function checkLabels(schema, root, { dirs = ['src'], exclude = [], files } = {}) {
|
|
97
|
+
const excluded = new Set(exclude.map((f) => pathKey(resolve(root, f))))
|
|
98
|
+
let text = ''
|
|
99
|
+
for (const file of filesToCheck(root, dirs, files)) {
|
|
100
|
+
if (!excluded.has(pathKey(file))) text += stripComments(readFileSync(file, 'utf8'), extname(file)) + '\n'
|
|
101
|
+
}
|
|
102
|
+
text += '\n' + decodeEntities(text)
|
|
103
|
+
const problems = []
|
|
104
|
+
for (const { path, label } of collectLabels(schema)) {
|
|
105
|
+
for (const part of label.split(' · ')) {
|
|
106
|
+
if (!text.includes(part)) problems.push(`${path}:x-label「${label}」里的「${part}」在配置页源码里找不到`)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return problems
|
|
110
|
+
}
|
package/src/vite-plugin.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { join, resolve } from 'node:path'
|
|
|
7
7
|
import { pathToFileURL } from 'node:url'
|
|
8
8
|
import { validate } from './validate.mjs'
|
|
9
9
|
import { checkLabels } from './labels.mjs'
|
|
10
|
+
import { checkExitRules } from './exits.mjs'
|
|
10
11
|
|
|
11
12
|
export { checkLabels, collectLabels } from './labels.mjs'
|
|
12
13
|
|
|
@@ -52,16 +53,20 @@ export async function loadSpec(root, entry) {
|
|
|
52
53
|
export async function buildContentConfig(root, entry = 'src/content-config.ts', { labelDirs = ['src'], labelFiles } = {}) {
|
|
53
54
|
const spec = await loadSpec(root, entry)
|
|
54
55
|
if (!spec || typeof spec.endpoint !== 'string' || !spec.endpoint || !spec.schema || spec.defaultBody === undefined) {
|
|
55
|
-
throw new Error(`content-config:${entry} 要默认导出 { endpoint, defaultBody, schema }
|
|
56
|
+
throw new Error(`content-config:${entry} 要默认导出 { endpoint, defaultBody, schema }(有动态出口的再加 dynamicExits)`)
|
|
56
57
|
}
|
|
57
58
|
const defaultBody = typeof spec.defaultBody === 'function' ? await spec.defaultBody() : spec.defaultBody
|
|
58
59
|
// 出厂默认可以留空「保存前必须填」的字段(x-fill-before-save),其余照常校验
|
|
59
60
|
const errors = validate(spec.schema, defaultBody, '$', { allowUnfilled: true })
|
|
60
61
|
if (labelDirs.length) errors.push(...checkLabels(spec.schema, root, { dirs: labelDirs, exclude: [entry], files: labelFiles }))
|
|
62
|
+
if (spec.dynamicExits !== undefined) errors.push(...checkExitRules(spec.dynamicExits, { schema: spec.schema, body: defaultBody }))
|
|
61
63
|
if (errors.length) {
|
|
62
64
|
throw new Error(`content-config:字段说明没通过检查(${errors.length} 处)\n ${errors.join('\n ')}`)
|
|
63
65
|
}
|
|
64
|
-
|
|
66
|
+
// dynamicExits 是 0.4.0 加的可选键,格式号不变:读取方不认识就当没有(建活动 skill 读到才补出口)
|
|
67
|
+
const doc = { format: FORMAT, endpoint: spec.endpoint, defaultBody, schema: spec.schema }
|
|
68
|
+
if (spec.dynamicExits !== undefined) doc.dynamicExits = spec.dynamicExits
|
|
69
|
+
return doc
|
|
65
70
|
}
|
|
66
71
|
|
|
67
72
|
export default function contentConfig({ entry = 'src/content-config.ts', fileName = 'assets/content-config.json', labelDirs = ['src'] } = {}) {
|