@realnation/content-config 0.2.1 → 0.4.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 CHANGED
@@ -1,66 +1,102 @@
1
- # @realnation/content-config
2
-
3
- qiksense 模块「内容配置」的机器可读说明(ClickUp 任务 8,方案 B,2026-09-29 定)。
4
-
5
- 模块每次构建时,这个 vite 插件读取模块的 `src/content-config.ts`,用其中的字段说明校验默认请求体,
6
- 不通过就让构建失败;通过就在 `remoteEntry.js` 同一目录生成 `content-config.json`,随配置端产物一起发布
7
- (`deploy.mjs` 把 `dist` 整个搬进 `qik-sense-partner-remotes/<模块>/<vN>/`,发布流程不变)。
8
-
9
- AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/projects/modulecontents` 拿到模块的
10
- `partnerRemote.remoteEntry`,把末尾的 `remoteEntry.js`(连同 `?v=` 之类的查询串)换成 `content-config.json` 去取。
11
- 同一目录重新发布时说明跟着代码一起换;换了新目录(vN)的版本取新目录里的那份。
12
-
13
- ## 模块里怎么接
14
-
15
- 1. 装包:`npm install -D @realnation/content-config`。esbuild 与 vite 是可选的同伴依赖(0.2.1 起):模块仓装了 vite 就带着 esbuild,
16
- 不用另装;只用 `./validate` 的项目(如建活动 skill)两样都不用装。
17
- 2. `vite.config.ts` 里加插件:
18
-
19
- ```ts
20
- import contentConfig from '@realnation/content-config';
21
- // plugins: [ ..., contentConfig(), federation({ ... }) ]
22
- ```
23
-
24
- 3. 写 `src/content-config.ts`,默认导出三样:
25
-
26
- ```ts
27
- import type { ContentConfigSpec } from '@realnation/content-config';
28
- import { createEmptyDetail, LIMITS } from './types/config';
29
-
30
- export default {
31
- endpoint: 'common', // POST /partner/contents/<endpoint>/config/{projectId}
32
- defaultBody: () => ({ configId: 0, detail: createEmptyDetail() }), // 配置页新建时提交的完整请求体
33
- schema: { type: 'object', properties: { /* ... */ } }
34
- } satisfies ContentConfigSpec;
35
- ```
36
-
37
- ## 写字段说明的规矩
38
-
39
- - **默认值与范围引用代码里的同一份常量**(默认值函数、LIMITS、枚举表),不照抄数字;改代码说明自动跟上。
40
- - **配置页不动**(PF 2026-09-29)。`x-label` 写配置页上显示的名字,一个字段在页上分几层时用「 · 」连起来
41
- (如 `Game Sounds · Grab`);**构建时每一段都要在模块 `src/` 的源码里原样找得到**,配置页改了名字而说明没跟上,
42
- 构建就报错。按页面上看到的样子写:模板里写成 HTML 转义的(如 `Playlists &amp; Tracks`),`x-label` 写
43
- `Playlists & Tracks`,核对时两种写法都认。页上没有单独名字的字段(如随图片读回的宽高)不写 `x-label`。
44
- - `description` 用英文写,给 AI 看:写清单位、取值的含义、空值与 0 代表什么;能用配置页上的提示就用它,不必一字不差。
45
- - **请求体按服务器格式写**:配置端内部与存库格式不同的(如 Personality Test 题目内部叫 questions、存时叫 details),
46
- 写转换后的。
47
- - **空串会被存成 null**:后端全局有 `ConvertEmptyStringsToNull`(qik-sense-api `app/Http/Kernel.php`),
48
- 允许空串的字段写 `type: ['string', 'null']`,并在说明里写清空串或 null 的含义。
49
- - `detail` 写 `additionalProperties: false` 并把默认值里的每个键都列进 `required`,默认值多出或少了字段构建就会报。
50
- - **保存前必须填、出厂默认却是空的字段**(如 Video Player 叠层的视频:配置页新建时是空的,不传视频存不了):
51
- 照实写约束(如 `minLength: 1`),再加 `'x-fill-before-save': true`。构建时校验出厂默认会放过它的空值
52
- (空串、null 或空数组);skill 与 AI 校验真正要提交的请求体时照样拦住,AI 读到这个标注就知道这一格要自己填。
53
- 不要为了让构建通过去放宽约束,也不要改产品的出厂默认。
54
- - 只支持这些关键字:type、properties、required、additionalProperties、items、minItems、maxItems、enum、const、
55
- minimum、maximum、minLength、maxLength、pattern、anyOf、format,另加 $schema、title、description、x-label。
56
- 用到别的会被当成问题报出来。
57
-
58
- ## 其他用法
59
-
60
- - `import { validate } from '@realnation/content-config/validate'`:返回问题清单,空数组 = 通过(skill 读到说明后用它校验要提交的请求体)。
61
- 第四个参数 `{ allowUnfilled: true }` 只在校验出厂默认时用,会放过标了 `x-fill-before-save` 的空值。
62
- - `buildContentConfig(root, entry)`:不经 vite,直接读出并校验,返回要写进 `content-config.json` 的内容。
63
-
64
- ## 发版
65
-
66
- `npm publish`(在本目录;账号要两步验证,由 PF 在自己的终端里发)。改了产物格式就把 `FORMAT` 加一,并同步改读取方。
1
+ # @realnation/content-config
2
+
3
+ qiksense 模块「内容配置」的机器可读说明(ClickUp 任务 8,方案 B,2026-09-29 定)。
4
+
5
+ 模块每次构建时,这个 vite 插件读取模块的 `src/content-config.ts`,用其中的字段说明校验默认请求体,
6
+ 不通过就让构建失败;通过就在 `remoteEntry.js` 同一目录生成 `content-config.json`,随配置端产物一起发布
7
+ (`deploy.mjs` 把 `dist` 整个搬进 `qik-sense-partner-remotes/<模块>/<vN>/`,发布流程不变)。
8
+
9
+ AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/projects/modulecontents` 拿到模块的
10
+ `partnerRemote.remoteEntry`,把末尾的 `remoteEntry.js`(连同 `?v=` 之类的查询串)换成 `content-config.json` 去取。
11
+ 同一目录重新发布时说明跟着代码一起换;换了新目录(vN)的版本取新目录里的那份。
12
+
13
+ ## 模块里怎么接
14
+
15
+ 1. 装包:`npm install -D @realnation/content-config`。esbuild 与 vite 是可选的同伴依赖(0.2.1 起):模块仓装了 vite 就带着 esbuild,
16
+ 不用另装;只用 `./validate` 的项目(如建活动 skill)两样都不用装。
17
+ 2. `vite.config.ts` 里加插件:
18
+
19
+ ```ts
20
+ import contentConfig from '@realnation/content-config';
21
+ // plugins: [ ..., contentConfig(), federation({ ... }) ]
22
+ ```
23
+
24
+ 3. 写 `src/content-config.ts`,默认导出三样:
25
+
26
+ ```ts
27
+ import type { ContentConfigSpec } from '@realnation/content-config';
28
+ import { createEmptyDetail, LIMITS } from './types/config';
29
+
30
+ export default {
31
+ endpoint: 'common', // POST /partner/contents/<endpoint>/config/{projectId}
32
+ defaultBody: () => ({ configId: 0, detail: createEmptyDetail() }), // 配置页新建时提交的完整请求体
33
+ schema: { type: 'object', properties: { /* ... */ } }
34
+ } satisfies ContentConfigSpec;
35
+ ```
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
+
68
+ ## 写字段说明的规矩
69
+
70
+ - **默认值与范围引用代码里的同一份常量**(默认值函数、LIMITS、枚举表),不照抄数字;改代码说明自动跟上。
71
+ - **配置页不动**(PF 2026-09-29)。`x-label` 写配置页上显示的名字,一个字段在页上分几层时用「 · 」连起来
72
+ (如 `Game Sounds · Grab`);**构建时每一段都要在模块 `src/` 的源码里原样找得到**,配置页改了名字而说明没跟上,
73
+ 构建就报错。按页面上看到的样子写:模板里写成 HTML 转义的(如 `Playlists &amp; Tracks`),`x-label` 写
74
+ `Playlists & Tracks`,核对时两种写法都认。页上没有单独名字的字段(如随图片读回的宽高)不写 `x-label`。
75
+ 0.3.0 起核对前先去掉注释,vite 构建时只看构建实际用到的源码:旧名字只留在注释或没人引用的文件里,也算找不到。
76
+ - `description` 用英文写,给 AI 看:写清单位、取值的含义、空值与 0 代表什么;能用配置页上的提示就用它,不必一字不差。
77
+ - **请求体按服务器格式写**:配置端内部与存库格式不同的(如 Personality Test 题目内部叫 questions、存时叫 details),
78
+ 写转换后的。
79
+ - **空串会被存成 null**:后端全局有 `ConvertEmptyStringsToNull`(qik-sense-api `app/Http/Kernel.php`),
80
+ 允许空串的字段写 `type: ['string', 'null']`,并在说明里写清空串或 null 的含义。
81
+ - `detail` 写 `additionalProperties: false` 并把默认值里的每个键都列进 `required`,默认值多出或少了字段构建就会报。
82
+ - **以 id 为键的表**(如 Image Tracking 每张目标图的 AR 内容,键是条目 id):`additionalProperties` 写成子说明,
83
+ 表里每一项都按它校验(0.3.0 起)。后端把空表读回成 `[]`,这类表写 `type: ['object', 'array']` 加 `maxItems: 0`。
84
+ - **保存前必须填、出厂默认却是空的字段**(如 Video Player 叠层的视频:配置页新建时是空的,不传视频存不了):
85
+ 照实写约束(如 `minLength: 1`),再加 `'x-fill-before-save': true`。构建时校验出厂默认会放过它的空值
86
+ (空串、null 或空数组;0.3.0 起出厂默认里整个键缺席也放过,不必用 null 占位);skill 与 AI 校验真正要提交的
87
+ 请求体时照样拦住,AI 读到这个标注就知道这一格要自己填。
88
+ 不要为了让构建通过去放宽约束,也不要改产品的出厂默认。
89
+ - 只支持这些关键字:type、properties、required、additionalProperties、items、minItems、maxItems、enum、const、
90
+ minimum、maximum、minLength、maxLength、pattern、anyOf、format,另加 $schema、title、description、x-label。
91
+ 用到别的会被当成问题报出来。
92
+
93
+ ## 其他用法
94
+
95
+ - `import { validate } from '@realnation/content-config/validate'`:返回问题清单,空数组 = 通过(skill 读到说明后用它校验要提交的请求体)。
96
+ 第四个参数 `{ allowUnfilled: true }` 只在校验出厂默认时用,会放过标了 `x-fill-before-save` 的空值。
97
+ - `buildContentConfig(root, entry)`:不经 vite,直接读出并校验,返回要写进 `content-config.json` 的内容。
98
+
99
+ ## 发版
100
+
101
+ `npm publish`(在本目录;账号要两步验证,由 PF 在自己的终端里发)。改了产物格式就把 `FORMAT` 加一,并同步改读取方;
102
+ 只加读取方可以不认识的可选键(如 0.4.0 的 `dynamicExits`)不算改格式。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realnation/content-config",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "qiksense 模块内容配置的机器可读说明:构建时导出 content-config.json,并用字段说明校验默认请求体",
5
5
  "type": "module",
6
6
  "exports": {
@@ -11,6 +11,10 @@
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"
14
18
  }
15
19
  },
16
20
  "files": [
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,41 +1,48 @@
1
- import type { Plugin } from 'vite';
2
- import type { JsonSchema } from './validate';
3
-
4
- export type { JsonSchema } from './validate';
5
- export { validate, SUPPORTED_KEYWORDS } from './validate';
6
-
7
- /** 模块 src/content-config.ts 默认导出的形状 */
8
- export interface ContentConfigSpec<Body = unknown> {
9
- /** POST /partner/contents/<endpoint>/config/{projectId} 里的 <endpoint>,如 common、form、quiz */
10
- endpoint: string;
11
- /** 配置页新建内容配置时提交的完整请求体(服务器格式);可以是返回它的函数 */
12
- defaultBody: Body | (() => Body | Promise<Body>);
13
- /** 请求体的字段说明 */
14
- schema: JsonSchema;
15
- }
16
-
17
- /** 构建产物 content-config.json 的形状 */
18
- export interface ContentConfigFile<Body = unknown> {
19
- format: 1;
20
- endpoint: string;
21
- defaultBody: Body;
22
- schema: JsonSchema;
23
- }
24
-
25
- export interface ContentConfigPluginOptions {
26
- /** 说明文件,默认 src/content-config.ts */
27
- entry?: string;
28
- /** 产物位置,默认 assets/content-config.json(与 remoteEntry.js 同一目录) */
29
- fileName?: string;
30
- /** 在哪些目录的源码里核对 x-label,默认 ['src'];传 [] 不核对 */
31
- labelDirs?: string[];
32
- }
33
-
34
- export declare const FORMAT: 1;
35
- export declare function loadSpec(root: string, entry: string): Promise<ContentConfigSpec>;
36
- export declare function buildContentConfig(root: string, entry?: string, options?: { labelDirs?: string[] }): Promise<ContentConfigFile>;
37
- /** 字段说明里所有的 x-label 与它们的位置 */
38
- export declare function collectLabels(schema: JsonSchema, path?: string): Array<{ path: string; label: string }>;
39
- /** 每个 x-label 按「 · 」拆开后,每一段都要在源码里原样出现过;返回找不到的清单 */
40
- export declare function checkLabels(schema: JsonSchema, root: string, options?: { dirs?: string[]; exclude?: string[] }): string[];
41
- export default function contentConfig(options?: ContentConfigPluginOptions): Plugin;
1
+ import type { Plugin } from 'vite';
2
+ import type { JsonSchema } from './validate';
3
+ import type { DynamicExitRule } from './exits';
4
+
5
+ export type { JsonSchema } from './validate';
6
+ export { validate, SUPPORTED_KEYWORDS } from './validate';
7
+ export type { DynamicExitRule, FixedExitRule, EachExitRule, DynamicExit } from './exits';
8
+ export { computeExits, checkExitRules } from './exits';
9
+
10
+ /** 模块 src/content-config.ts 默认导出的形状 */
11
+ export interface ContentConfigSpec<Body = unknown> {
12
+ /** POST /partner/contents/<endpoint>/config/{projectId} 里的 <endpoint>,如 common、form、quiz */
13
+ endpoint: string;
14
+ /** 配置页新建内容配置时提交的完整请求体(服务器格式);可以是返回它的函数 */
15
+ defaultBody: Body | (() => Body | Promise<Body>);
16
+ /** 请求体的字段说明 */
17
+ schema: JsonSchema;
18
+ /** 配置页按内容配置算出、保存时推给宿主 setAccessDynamicPorts 的出口,用数据写成的同一套算法(0.4.0 起);出口全在模块目录里的模块不写 */
19
+ dynamicExits?: readonly DynamicExitRule[];
20
+ }
21
+
22
+ /** 构建产物 content-config.json 的形状 */
23
+ export interface ContentConfigFile<Body = unknown> {
24
+ format: 1;
25
+ endpoint: string;
26
+ defaultBody: Body;
27
+ schema: JsonSchema;
28
+ /** 模块写了 dynamicExits 才有 */
29
+ dynamicExits?: readonly DynamicExitRule[];
30
+ }
31
+
32
+ export interface ContentConfigPluginOptions {
33
+ /** 说明文件,默认 src/content-config.ts */
34
+ entry?: string;
35
+ /** 产物位置,默认 assets/content-config.json(与 remoteEntry.js 同一目录) */
36
+ fileName?: string;
37
+ /** 在哪些目录的源码里核对 x-label,默认 ['src'];传 [] 不核对 */
38
+ labelDirs?: string[];
39
+ }
40
+
41
+ export declare const FORMAT: 1;
42
+ export declare function loadSpec(root: string, entry: string): Promise<ContentConfigSpec>;
43
+ export declare function buildContentConfig(root: string, entry?: string, options?: { labelDirs?: string[]; labelFiles?: string[] }): Promise<ContentConfigFile>;
44
+ /** 字段说明里所有的 x-label 与它们的位置 */
45
+ export declare function collectLabels(schema: JsonSchema, path?: string): Array<{ path: string; label: string }>;
46
+ /** 每个 x-label 按「 · 」拆开后,每一段都要在源码里(去掉注释后)原样出现过;返回找不到的清单。传了 files 就只看其中落在 dirs 下的源码 */
47
+ export declare function checkLabels(schema: JsonSchema, root: string, options?: { dirs?: string[]; exclude?: string[]; files?: string[] }): string[];
48
+ export default function contentConfig(options?: ContentConfigPluginOptions): Plugin;
package/src/index.mjs CHANGED
@@ -1,2 +1,3 @@
1
1
  export { default, buildContentConfig, loadSpec, checkLabels, collectLabels, FORMAT } from './vite-plugin.mjs'
2
2
  export { validate, SUPPORTED_KEYWORDS } from './validate.mjs'
3
+ export { computeExits, checkExitRules } from './exits.mjs'
package/src/labels.mjs CHANGED
@@ -1,55 +1,110 @@
1
- // 核对字段名:配置页不动,说明自己写 x-label(PF 2026-09-29)。为防配置页改了名字说明没跟上,
2
- // 每个 x-label 按「 · 」拆开后,每一段都要在模块源码里原样出现过(说明文件本身不算)。
3
-
4
- import { readdirSync, readFileSync, statSync } from 'node:fs'
5
- import { extname, join, resolve } from 'node:path'
6
-
7
- const SOURCE_EXTENSIONS = new Set(['.vue', '.ts', '.tsx', '.js', '.jsx', '.mjs'])
8
-
9
- // 字段说明里所有的 x-label,连同它在说明里的位置
10
- export function collectLabels(schema, path = '$') {
11
- const found = []
12
- if (!schema || typeof schema !== 'object') return found
13
- if (typeof schema['x-label'] === 'string') found.push({ path, label: schema['x-label'] })
14
- for (const [key, sub] of Object.entries(schema.properties ?? {})) found.push(...collectLabels(sub, `${path}.${key}`))
15
- if (schema.items) found.push(...collectLabels(schema.items, `${path}[]`))
16
- for (const sub of schema.anyOf ?? []) found.push(...collectLabels(sub, path))
17
- return found
18
- }
19
-
20
- function* sourceFiles(dir) {
21
- for (const name of readdirSync(dir)) {
22
- const p = join(dir, name)
23
- if (statSync(p).isDirectory()) yield* sourceFiles(p)
24
- else if (SOURCE_EXTENSIONS.has(extname(name))) yield p
25
- }
26
- }
27
-
28
- // 模板里的文字常写成 HTML 转义(如 Playlists &amp; Tracks),页面上显示的是转义前的样子;
29
- // x-label 写页面上看到的,所以核对时两种写法都认
30
- const decodeEntities = (s) =>
31
- s
32
- .replace(/&amp;/g, '&')
33
- .replace(/&lt;/g, '<')
34
- .replace(/&gt;/g, '>')
35
- .replace(/&quot;/g, '"')
36
- .replace(/&#39;|&apos;/g, "'")
37
- .replace(/&nbsp;/g, ' ')
38
-
39
- export function checkLabels(schema, root, { dirs = ['src'], exclude = [] } = {}) {
40
- const excluded = new Set(exclude.map((f) => resolve(root, f)))
41
- let text = ''
42
- for (const dir of dirs) {
43
- for (const file of sourceFiles(resolve(root, dir))) {
44
- if (!excluded.has(resolve(file))) text += readFileSync(file, 'utf8') + '\n'
45
- }
46
- }
47
- text += '\n' + decodeEntities(text)
48
- const problems = []
49
- for (const { path, label } of collectLabels(schema)) {
50
- for (const part of label.split(' · ')) {
51
- if (!text.includes(part)) problems.push(`${path}:x-label「${label}」里的「${part}」在配置页源码里找不到`)
52
- }
53
- }
54
- return problems
55
- }
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 &amp; Tracks),页面上显示的是转义前的样子;
70
+ // x-label 写页面上看到的,所以核对时两种写法都认
71
+ const decodeEntities = (s) =>
72
+ s
73
+ .replace(/&amp;/g, '&')
74
+ .replace(/&lt;/g, '<')
75
+ .replace(/&gt;/g, '>')
76
+ .replace(/&quot;/g, '"')
77
+ .replace(/&#39;|&apos;/g, "'")
78
+ .replace(/&nbsp;/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/validate.d.ts CHANGED
@@ -1,37 +1,38 @@
1
- /** 字段说明:JSON Schema 2020-12 里本包支持的那部分关键字 */
2
- export interface JsonSchema {
3
- $schema?: string;
4
- title?: string;
5
- /** 给人和 AI 看的说明,用英文写 */
6
- description?: string;
7
- /** 配置页上这个字段显示的名字 */
8
- 'x-label'?: string;
9
- type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null' | ReadonlyArray<'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null'>;
10
- properties?: Record<string, JsonSchema>;
11
- required?: ReadonlyArray<string>;
12
- additionalProperties?: boolean;
13
- items?: JsonSchema;
14
- minItems?: number;
15
- maxItems?: number;
16
- enum?: ReadonlyArray<unknown>;
17
- const?: unknown;
18
- minimum?: number;
19
- maximum?: number;
20
- minLength?: number;
21
- maxLength?: number;
22
- pattern?: string;
23
- anyOf?: ReadonlyArray<JsonSchema>;
24
- format?: string;
25
- /** 保存前必须填、出厂默认可以留空(空串、null 或空数组)的字段;AI 与 skill 提交前要把它填好 */
26
- 'x-fill-before-save'?: boolean;
27
- }
28
-
29
- export declare const SUPPORTED_KEYWORDS: ReadonlySet<string>;
30
-
31
- export interface ValidateOptions {
32
- /** 放过标了 x-fill-before-save 且还没填的字段。构建时校验出厂默认用;校验真正要提交的请求体时不要开 */
33
- allowUnfilled?: boolean;
34
- }
35
-
36
- /** 返回问题清单,空数组 = 通过 */
37
- export declare function validate(schema: JsonSchema, value: unknown, path?: string, options?: ValidateOptions): string[];
1
+ /** 字段说明:JSON Schema 2020-12 里本包支持的那部分关键字 */
2
+ export interface JsonSchema {
3
+ $schema?: string;
4
+ title?: string;
5
+ /** 给人和 AI 看的说明,用英文写 */
6
+ description?: string;
7
+ /** 配置页上这个字段显示的名字 */
8
+ 'x-label'?: string;
9
+ type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null' | ReadonlyArray<'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null'>;
10
+ properties?: Record<string, JsonSchema>;
11
+ required?: ReadonlyArray<string>;
12
+ /** false = 只许 properties 里列出的键;写成子说明 = 以 id 为键的表,其余每个键的值都按它校验(0.3.0 起) */
13
+ additionalProperties?: boolean | JsonSchema;
14
+ items?: JsonSchema;
15
+ minItems?: number;
16
+ maxItems?: number;
17
+ enum?: ReadonlyArray<unknown>;
18
+ const?: unknown;
19
+ minimum?: number;
20
+ maximum?: number;
21
+ minLength?: number;
22
+ maxLength?: number;
23
+ pattern?: string;
24
+ anyOf?: ReadonlyArray<JsonSchema>;
25
+ format?: string;
26
+ /** 保存前必须填、出厂默认可以留空(空串、null 或空数组)的字段;AI 与 skill 提交前要把它填好 */
27
+ 'x-fill-before-save'?: boolean;
28
+ }
29
+
30
+ export declare const SUPPORTED_KEYWORDS: ReadonlySet<string>;
31
+
32
+ export interface ValidateOptions {
33
+ /** 放过标了 x-fill-before-save 且还没填的字段。构建时校验出厂默认用;校验真正要提交的请求体时不要开 */
34
+ allowUnfilled?: boolean;
35
+ }
36
+
37
+ /** 返回问题清单,空数组 = 通过 */
38
+ export declare function validate(schema: JsonSchema, value: unknown, path?: string, options?: ValidateOptions): string[];
package/src/validate.mjs CHANGED
@@ -1,65 +1,71 @@
1
- // 用字段说明(JSON Schema 2020-12 的一个子集)校验一份值,返回问题清单,空数组 = 通过。
2
- // 只支持字段说明里用得到的关键字;用到别的会直接列为问题,免得写了却没校验。
3
- // 构建插件与团队建活动 skill 共用这一份,两边的判断不会不一样。
4
-
5
- export const SUPPORTED_KEYWORDS = new Set([
6
- '$schema', 'title', 'description', 'x-label', 'type', 'properties', 'required', 'additionalProperties',
7
- 'items', 'minItems', 'maxItems', 'enum', 'const', 'minimum', 'maximum', 'minLength', 'maxLength', 'pattern',
8
- 'anyOf', 'format', 'x-fill-before-save'
9
- ])
10
-
11
- // 值算不算「还没填」:空串、null、空数组。标了 x-fill-before-save 的字段,出厂默认可以是这样
12
- const isUnfilled = (v) => v === '' || v === null || (Array.isArray(v) && v.length === 0)
13
-
14
- const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v)
15
- const matchesType = (v, t) => t === typeOf(v) || (t === 'number' && typeof v === 'number' && Number.isFinite(v))
16
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
17
-
18
- // options.allowUnfilled:构建时校验出厂默认用,放过标了 x-fill-before-save 且还没填的字段;
19
- // skill 校验真正要提交的请求体时不传,这类字段照样必须填好
20
- export function validate(schema, value, path = '$', options = {}) {
21
- const errors = []
22
- if (options.allowUnfilled && schema['x-fill-before-save'] === true && isUnfilled(value)) return errors
23
- for (const key of Object.keys(schema)) {
24
- if (!SUPPORTED_KEYWORDS.has(key)) errors.push(`${path}:字段说明用了不支持的关键字 ${key}`)
25
- }
26
- if (schema.anyOf && !schema.anyOf.some((s) => validate(s, value, path, options).length === 0)) {
27
- errors.push(`${path}:${JSON.stringify(value)} 不符合 anyOf 里的任何一种`)
28
- }
29
- if (schema.type) {
30
- const types = Array.isArray(schema.type) ? schema.type : [schema.type]
31
- if (!types.some((t) => matchesType(value, t))) {
32
- errors.push(`${path}:应为 ${types.join(' 或 ')},实为 ${typeOf(value)}`)
33
- return errors
34
- }
35
- }
36
- if ('const' in schema && !same(value, schema.const)) errors.push(`${path}:应为 ${JSON.stringify(schema.const)}`)
37
- if (schema.enum && !schema.enum.some((e) => same(e, value))) {
38
- errors.push(`${path}:${JSON.stringify(value)} 不在可选值 ${JSON.stringify(schema.enum)} 里`)
39
- }
40
- if (typeof value === 'number') {
41
- if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path}:${value} 小于下限 ${schema.minimum}`)
42
- if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path}:${value} 大于上限 ${schema.maximum}`)
43
- }
44
- if (typeof value === 'string') {
45
- if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path}:长度 ${value.length} 小于 ${schema.minLength}`)
46
- if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path}:长度 ${value.length} 大于 ${schema.maxLength}`)
47
- if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${path}:${JSON.stringify(value)} 不符合 ${schema.pattern}`)
48
- }
49
- if (Array.isArray(value)) {
50
- if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${path}:${value.length} 项,少于 ${schema.minItems}`)
51
- if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${path}:${value.length} 项,多于 ${schema.maxItems}`)
52
- if (schema.items) value.forEach((item, i) => errors.push(...validate(schema.items, item, `${path}[${i}]`, options)))
53
- }
54
- if (typeOf(value) === 'object') {
55
- const props = schema.properties ?? {}
56
- for (const key of schema.required ?? []) {
57
- if (!(key in value)) errors.push(`${path}:缺少必填字段 ${key}`)
58
- }
59
- for (const [key, v] of Object.entries(value)) {
60
- if (props[key]) errors.push(...validate(props[key], v, `${path}.${key}`, options))
61
- else if (schema.additionalProperties === false) errors.push(`${path}.${key}:字段说明里没有这个字段`)
62
- }
63
- }
64
- return errors
65
- }
1
+ // 用字段说明(JSON Schema 2020-12 的一个子集)校验一份值,返回问题清单,空数组 = 通过。
2
+ // 只支持字段说明里用得到的关键字;用到别的会直接列为问题,免得写了却没校验。
3
+ // 构建插件与团队建活动 skill 共用这一份,两边的判断不会不一样。
4
+
5
+ export const SUPPORTED_KEYWORDS = new Set([
6
+ '$schema', 'title', 'description', 'x-label', 'type', 'properties', 'required', 'additionalProperties',
7
+ 'items', 'minItems', 'maxItems', 'enum', 'const', 'minimum', 'maximum', 'minLength', 'maxLength', 'pattern',
8
+ 'anyOf', 'format', 'x-fill-before-save'
9
+ ])
10
+
11
+ // 值算不算「还没填」:空串、null、空数组。标了 x-fill-before-save 的字段,出厂默认可以是这样
12
+ const isUnfilled = (v) => v === '' || v === null || (Array.isArray(v) && v.length === 0)
13
+
14
+ const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v)
15
+ // additionalProperties 写成子说明时(0.3.0 起),以 id 为键的表每一项都按它校验
16
+ const isSubSchema =(s) => typeof s === 'object' && s !== null && !Array.isArray(s)
17
+ const matchesType = (v, t) => t === typeOf(v) || (t === 'number' && typeof v === 'number' && Number.isFinite(v))
18
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
19
+
20
+ // options.allowUnfilled:构建时校验出厂默认用,放过标了 x-fill-before-save 且还没填的字段;
21
+ // skill 校验真正要提交的请求体时不传,这类字段照样必须填好
22
+ export function validate(schema, value, path = '$', options = {}) {
23
+ const errors = []
24
+ if (options.allowUnfilled && schema['x-fill-before-save'] === true && isUnfilled(value)) return errors
25
+ for (const key of Object.keys(schema)) {
26
+ if (!SUPPORTED_KEYWORDS.has(key)) errors.push(`${path}:字段说明用了不支持的关键字 ${key}`)
27
+ }
28
+ if (schema.anyOf && !schema.anyOf.some((s) => validate(s, value, path, options).length === 0)) {
29
+ errors.push(`${path}:${JSON.stringify(value)} 不符合 anyOf 里的任何一种`)
30
+ }
31
+ if (schema.type) {
32
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type]
33
+ if (!types.some((t) => matchesType(value, t))) {
34
+ errors.push(`${path}:应为 ${types.join(' 或 ')},实为 ${typeOf(value)}`)
35
+ return errors
36
+ }
37
+ }
38
+ if ('const' in schema && !same(value, schema.const)) errors.push(`${path}:应为 ${JSON.stringify(schema.const)}`)
39
+ if (schema.enum && !schema.enum.some((e) => same(e, value))) {
40
+ errors.push(`${path}:${JSON.stringify(value)} 不在可选值 ${JSON.stringify(schema.enum)} 里`)
41
+ }
42
+ if (typeof value === 'number') {
43
+ if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path}:${value} 小于下限 ${schema.minimum}`)
44
+ if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path}:${value} 大于上限 ${schema.maximum}`)
45
+ }
46
+ if (typeof value === 'string') {
47
+ if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path}:长度 ${value.length} 小于 ${schema.minLength}`)
48
+ if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path}:长度 ${value.length} 大于 ${schema.maxLength}`)
49
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${path}:${JSON.stringify(value)} 不符合 ${schema.pattern}`)
50
+ }
51
+ if (Array.isArray(value)) {
52
+ if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(`${path}:${value.length} 项,少于 ${schema.minItems}`)
53
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(`${path}:${value.length} 项,多于 ${schema.maxItems}`)
54
+ if (schema.items) value.forEach((item, i) => errors.push(...validate(schema.items, item, `${path}[${i}]`, options)))
55
+ }
56
+ if (typeOf(value) === 'object') {
57
+ const props = schema.properties ?? {}
58
+ for (const key of schema.required ?? []) {
59
+ if (key in value) continue
60
+ // 标了 x-fill-before-save 的字段,出厂默认里整个键缺席也算还没填(0.3.0 起),不必用 null 占位
61
+ if (options.allowUnfilled && props[key]?.['x-fill-before-save'] === true) continue
62
+ errors.push(`${path}:缺少必填字段 ${key}`)
63
+ }
64
+ for (const [key, v] of Object.entries(value)) {
65
+ if (props[key]) errors.push(...validate(props[key], v, `${path}.${key}`, options))
66
+ else if (schema.additionalProperties === false) errors.push(`${path}.${key}:字段说明里没有这个字段`)
67
+ else if (isSubSchema(schema.additionalProperties)) errors.push(...validate(schema.additionalProperties, v, `${path}.${key}`, options))
68
+ }
69
+ }
70
+ return errors
71
+ }
@@ -1,84 +1,92 @@
1
- // vite 插件:构建时加载模块的 src/content-config.ts,用它的字段说明校验默认请求体,
2
- // 不通过就让构建失败;通过就在 remoteEntry.js 同一目录生成 content-config.json,随配置端产物发布。
3
- // 模块每次构建都跑(本机 npm run build、deploy.mjs 发 UAT 与正式),所以说明永远跟着当时的代码。
4
-
5
- import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
- import { join, resolve } from 'node:path'
7
- import { pathToFileURL } from 'node:url'
8
- import { validate } from './validate.mjs'
9
- import { checkLabels } from './labels.mjs'
10
-
11
- export { checkLabels, collectLabels } from './labels.mjs'
12
-
13
- export const FORMAT = 1
14
-
15
- // esbuild 是可选的同伴依赖(0.2.1 起):模块仓装了 vite 就有它;只用 ./validate 的场合(如建活动 skill)用不到,不必装
16
- async function loadEsbuild() {
17
- try {
18
- return await import('esbuild')
19
- } catch {
20
- throw new Error('content-config:构建时要用 esbuild 加载 src/content-config.ts(vite 自带)。这个项目里找不到它,请 npm install -D esbuild')
21
- }
22
- }
23
-
24
- // 用 esbuild 把 content-config.ts 连同它引用的模块代码打成一个 ESM 文件再加载:TS、相对引用与 @/ 别名都能处理;
25
- // node_modules 里的包不打进去,加载时照常从模块仓解析(所以临时文件放在模块仓的 node_modules 下)
26
- export async function loadSpec(root, entry) {
27
- const { build } = await loadEsbuild()
28
- const dir = join(root, 'node_modules', '.content-config')
29
- mkdirSync(dir, { recursive: true })
30
- const out = join(dir, `spec-${process.pid}-${Date.now()}.mjs`)
31
- const result = await build({
32
- entryPoints: [resolve(root, entry)],
33
- bundle: true,
34
- format: 'esm',
35
- platform: 'node',
36
- packages: 'external',
37
- write: false,
38
- logLevel: 'silent',
39
- alias: { '@': resolve(root, 'src') }
40
- })
41
- writeFileSync(out, result.outputFiles[0].text)
42
- try {
43
- const mod = await import(pathToFileURL(out).href)
44
- return mod.default
45
- } finally {
46
- rmSync(out, { force: true })
47
- }
48
- }
49
-
50
- // 读出说明并校验,返回要写进 content-config.json 的内容;不合规时抛错,错误信息逐条列出
51
- export async function buildContentConfig(root, entry = 'src/content-config.ts', { labelDirs = ['src'] } = {}) {
52
- const spec = await loadSpec(root, entry)
53
- if (!spec || typeof spec.endpoint !== 'string' || !spec.endpoint || !spec.schema || spec.defaultBody === undefined) {
54
- throw new Error(`content-config:${entry} 要默认导出 { endpoint, defaultBody, schema }`)
55
- }
56
- const defaultBody = typeof spec.defaultBody === 'function' ? await spec.defaultBody() : spec.defaultBody
57
- // 出厂默认可以留空「保存前必须填」的字段(x-fill-before-save),其余照常校验
58
- const errors = validate(spec.schema, defaultBody, '$', { allowUnfilled: true })
59
- if (labelDirs.length) errors.push(...checkLabels(spec.schema, root, { dirs: labelDirs, exclude: [entry] }))
60
- if (errors.length) {
61
- throw new Error(`content-config:字段说明没通过检查(${errors.length} 处)\n ${errors.join('\n ')}`)
62
- }
63
- return { format: FORMAT, endpoint: spec.endpoint, defaultBody, schema: spec.schema }
64
- }
65
-
66
- export default function contentConfig({ entry = 'src/content-config.ts', fileName = 'assets/content-config.json', labelDirs = ['src'] } = {}) {
67
- let root = process.cwd()
68
- return {
69
- name: 'realnation-content-config',
70
- apply: 'build',
71
- configResolved(config) {
72
- root = config.root
73
- },
74
- async generateBundle() {
75
- let doc
76
- try {
77
- doc = await buildContentConfig(root, entry, { labelDirs })
78
- } catch (e) {
79
- this.error(e.message)
80
- }
81
- this.emitFile({ type: 'asset', fileName, source: JSON.stringify(doc, null, 2) + '\n' })
82
- }
83
- }
84
- }
1
+ // vite 插件:构建时加载模块的 src/content-config.ts,用它的字段说明校验默认请求体,
2
+ // 不通过就让构建失败;通过就在 remoteEntry.js 同一目录生成 content-config.json,随配置端产物发布。
3
+ // 模块每次构建都跑(本机 npm run build、deploy.mjs 发 UAT 与正式),所以说明永远跟着当时的代码。
4
+
5
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { join, resolve } from 'node:path'
7
+ import { pathToFileURL } from 'node:url'
8
+ import { validate } from './validate.mjs'
9
+ import { checkLabels } from './labels.mjs'
10
+ import { checkExitRules } from './exits.mjs'
11
+
12
+ export { checkLabels, collectLabels } from './labels.mjs'
13
+
14
+ export const FORMAT = 1
15
+
16
+ // esbuild 是可选的同伴依赖(0.2.1 起):模块仓装了 vite 就有它;只用 ./validate 的场合(如建活动 skill)用不到,不必装
17
+ async function loadEsbuild() {
18
+ try {
19
+ return await import('esbuild')
20
+ } catch {
21
+ throw new Error('content-config:构建时要用 esbuild 加载 src/content-config.ts(vite 自带)。这个项目里找不到它,请 npm install -D esbuild')
22
+ }
23
+ }
24
+
25
+ // 用 esbuild 把 content-config.ts 连同它引用的模块代码打成一个 ESM 文件再加载:TS、相对引用与 @/ 别名都能处理;
26
+ // node_modules 里的包不打进去,加载时照常从模块仓解析(所以临时文件放在模块仓的 node_modules 下)
27
+ export async function loadSpec(root, entry) {
28
+ const { build } = await loadEsbuild()
29
+ const dir = join(root, 'node_modules', '.content-config')
30
+ mkdirSync(dir, { recursive: true })
31
+ const out = join(dir, `spec-${process.pid}-${Date.now()}.mjs`)
32
+ const result = await build({
33
+ entryPoints: [resolve(root, entry)],
34
+ bundle: true,
35
+ format: 'esm',
36
+ platform: 'node',
37
+ packages: 'external',
38
+ write: false,
39
+ logLevel: 'silent',
40
+ alias: { '@': resolve(root, 'src') }
41
+ })
42
+ writeFileSync(out, result.outputFiles[0].text)
43
+ try {
44
+ const mod = await import(pathToFileURL(out).href)
45
+ return mod.default
46
+ } finally {
47
+ rmSync(out, { force: true })
48
+ }
49
+ }
50
+
51
+ // 读出说明并校验,返回要写进 content-config.json 的内容;不合规时抛错,错误信息逐条列出
52
+ // labelFiles:只拿这些源码核对 x-label(vite 插件传构建实际用到的模块);不传就扫 labelDirs 下全部源码
53
+ export async function buildContentConfig(root, entry = 'src/content-config.ts', { labelDirs = ['src'], labelFiles } = {}) {
54
+ const spec = await loadSpec(root, entry)
55
+ if (!spec || typeof spec.endpoint !== 'string' || !spec.endpoint || !spec.schema || spec.defaultBody === undefined) {
56
+ throw new Error(`content-config:${entry} 要默认导出 { endpoint, defaultBody, schema }(有动态出口的再加 dynamicExits)`)
57
+ }
58
+ const defaultBody = typeof spec.defaultBody === 'function' ? await spec.defaultBody() : spec.defaultBody
59
+ // 出厂默认可以留空「保存前必须填」的字段(x-fill-before-save),其余照常校验
60
+ const errors = validate(spec.schema, defaultBody, '$', { allowUnfilled: true })
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 }))
63
+ if (errors.length) {
64
+ throw new Error(`content-config:字段说明没通过检查(${errors.length} 处)\n ${errors.join('\n ')}`)
65
+ }
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
70
+ }
71
+
72
+ export default function contentConfig({ entry = 'src/content-config.ts', fileName = 'assets/content-config.json', labelDirs = ['src'] } = {}) {
73
+ let root = process.cwd()
74
+ return {
75
+ name: 'realnation-content-config',
76
+ apply: 'build',
77
+ configResolved(config) {
78
+ root = config.root
79
+ },
80
+ async generateBundle() {
81
+ // 构建实际用到的模块(去掉 ?vue&type=… 这类查询串与虚拟模块);没人引用的闲置文件不在里面,不拿来核对名字
82
+ const labelFiles = [...this.getModuleIds()].filter((id) => !id.startsWith('\0')).map((id) => id.split('?')[0])
83
+ let doc
84
+ try {
85
+ doc = await buildContentConfig(root, entry, { labelDirs, labelFiles })
86
+ } catch (e) {
87
+ this.error(e.message)
88
+ }
89
+ this.emitFile({ type: 'asset', fileName, source: JSON.stringify(doc, null, 2) + '\n' })
90
+ }
91
+ }
92
+ }