soma-kit 0.1.17 → 0.1.18

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-kit",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "description": "SOMA 第三条 UI 路线:写死模板与规则,DSL 显式传入,基础组件 + 数据组件",
5
5
  "type": "module",
6
6
  "exports": {
@@ -6061,6 +6061,10 @@
6061
6061
  "KIT-APP-013": "应用代码直接 import \"soma-core\" 或 \"soma-core/*\"(含 import type、export … from、动态 import、require);应用唯一的接触面是 soma-kit/app(tests/ 与 test/ 目录豁免)",
6062
6062
  "KIT-APP-014": "应用组件的 controllerFactory 必须由 createKitController((api) => ({ ... })) 生成(不接受纯声明式无控制器组件或手写工厂)",
6063
6063
  "KIT-APP-015": "应用违反双平面与四层分层边界(R-APP-1/2/3):客户端面(web/、soma.app.ts、views/、actions/、components/)静态引用了服务端面(bff/、api/、config/、soma.server.*),或服务端面反向引用客户端面,或 shared/ 引用了端侧或 Node 内置模块,或 BFF 下层(foundation/、domain/)反向引用上层,或页面视图 views/*.view.ts 之间横向互引",
6064
+ "KIT-APP-016": "业务应用禁止注册非业务/非数据的野生 baseComponents(基础控件一律复用官方闭集);外部界面扩展仅开放两档:① 业务组件 bizComponents(静态画布 + 按 DSL 装配,可自带私有 dataComponents);② 纯数据驱动自定义数据组件 staticObjectComponents(一份数据一个组件、数据进事件出,供业务组件 DSL 槽位按名选用)",
6065
+ "KIT-APP-017": "禁止野生样式表与野生页面 HTML:应用目录不得出现 .css / .scss / .less / .sass / .styl 文件或在源码中 import / export / require 样式表,kit.app.yaml 不得配置 style: 外链样式,且 pages/、src/web/、views/、components/ 下不得手写 .html / .htm;样式外观统一走 kit.app.yaml#theme 14 维 DSL 与 Tailwind 刻度类",
6066
+ "KIT-APP-018": "禁止命令式浮层、非组件 DOM 构造与伪造框架内部符号:全应用禁止调用 .showModal() / .showPopover() / createElement('dialog') / document.body.append* 及引用或伪造 Symbol.for('soma-kit.*');components/ 之外的源码禁止调用 createElement / createElementNS / insertAdjacentHTML 或写入 innerHTML / outerHTML",
6067
+ "KIT-APP-019": "自定义业务组件或其私有协作组件违反纯声明式装数据契约:业务组件未经 defineKitBizComponent 构造、组件源码内手写 <table> / <thead> / <form> / <dialog> 或直接调用 fetch() / new XMLHttpRequest,或业务组件源码硬编码 '/api/...' 接口路径(必须从页面 input.objects 的 behavior.from 与具名动作读取)",
6064
6068
  "KIT-COMP-002": "业务组件定义非法:名字不是 PascalCase、没有必填角色槽、areas 重名、缺 compile(),或 composeKitBizComponents 的子部件 / 角色映射不成立",
6065
6069
  "KIT-COMP-003": "组件候选类 / rootClass / slotClass 含非法 Tailwind 类(不在刻度内或带方括号任意值)",
6066
6070
  "KIT-COMP-004": "数据组件定义 / 包装 / 登记非法:缺 define()、accept 不是 single / list、被包装组件无控制器、登记名与契约名不一致、layer 不是 data、事件名不是 snake_case,或 composeKitDataComponents 没有子部件",
@@ -6369,6 +6373,43 @@
6369
6373
  "bad": "// src/web/views/orders.view.ts\nimport { orderRepo } from '../../bff/foundation/repositories/orderRepo';",
6370
6374
  "good": "// src/web/views/orders.view.ts\nimport type { OrderDto } from '../../shared/contracts/orders';"
6371
6375
  },
6376
+ "KIT-APP-016": {
6377
+ "causes": [
6378
+ "在 defineKitApp({ baseComponents }) 中注册了非业务/非数据的野生基础组件",
6379
+ "在 kit.app.yaml 中声明了 baseComponents"
6380
+ ],
6381
+ "bad": "defineKitApp({\n baseComponents: {\n AppWildButton: declareKitUses(AppWildButton, [])\n }\n});",
6382
+ "good": "// 方式 ①:纯数据驱动自定义数据组件(一份数据一个组件、数据进事件出,供页面 staticComponent 槽位按名选用)\ndefineKitApp({\n staticObjectComponents: {\n AppDocAnnotationView: { define: declareKitUses(AppDocAnnotationView, ['Button'], ['flex', 'gap-2']), accept: 'single' }\n }\n});\n// 方式 ②:自定义业务组件(可自带私有 dataComponents 与 candidates)\ndefineKitApp({\n bizComponents: {\n AnnotationBoard: defineKitBizComponent({\n kind: 'AnnotationBoard',\n roles: { document: { required: true, views: ['summary'] } },\n areas: ['root', 'canvas'],\n dataComponents: { AnnotationCanvasCore: declareKitUses(AnnotationCanvasCore, ['Button'], ['flex', 'gap-2']) },\n candidates: ['rounded-card', 'bg-surface'],\n compile(input, ctx) { /* 按 input.objects 编排返回 KitFragment */ }\n })\n }\n});"
6383
+ },
6384
+ "KIT-APP-017": {
6385
+ "causes": [
6386
+ "应用目录下存在手写的 .css / .scss / .less / .sass / .styl 样式文件",
6387
+ "TS / JS 源码通过 import / export / require 加载了样式表文件",
6388
+ "kit.app.yaml 配置了 style: 自定义 CSS 文件路径",
6389
+ "pages/、src/web/、views/ 或 components/ 目录下存在手写 .html / .htm 页面文件"
6390
+ ],
6391
+ "bad": "# kit.app.yaml\nstyle: custom.css\n// 或源码中 import './override.css' / pages/dashboard.html",
6392
+ "good": "# kit.app.yaml\ntheme:\n preset: portal\n palette: blue\n layering: paper\n# 页面一律写 pages/*.kit.yaml,样式由框架主题引擎与 Tailwind 刻度类统一生成"
6393
+ },
6394
+ "KIT-APP-018": {
6395
+ "causes": [
6396
+ "调用了 .showModal()、.showPopover()、createElement('dialog') 或 document.body.appendChild(...) 构造命令式浮层",
6397
+ "在 actions/、views/、api/ 或 soma.app.ts 等非 components/ 目录中调用 createElement / createElementNS / insertAdjacentHTML 或写入 innerHTML / outerHTML",
6398
+ "在外部应用源码中引用或伪造 Symbol.for('soma-kit.*') 框架内部符号"
6399
+ ],
6400
+ "bad": "// actions/open-modal.ts\nconst dlg = document.createElement('dialog');\ndocument.body.appendChild(dlg);\ndlg.showModal();",
6401
+ "good": "# pages/orders.kit.yaml\noverlays:\n edit:\n kind: dialog\n title: 编辑订单\n view: { form: { fields: [title] } }"
6402
+ },
6403
+ "KIT-APP-019": {
6404
+ "causes": [
6405
+ "bizComponents 中登记了未经 defineKitBizComponent(...) 构造的裸对象",
6406
+ "自定义组件或业务组件私有协作内核中手写了 <table> / <thead> / <form> / <dialog> 规整结构",
6407
+ "自定义组件源码中直接调用 fetch() 或 new XMLHttpRequest 绕过数据与动作管道",
6408
+ "defineKitBizComponent 所在文件在函数体内硬编码了 '/api/...' 接口路径"
6409
+ ],
6410
+ "bad": "// components/BadBoard.ts\nconst html = '<table><thead><tr><th>标题</th></tr></thead></table>';\nawait fetch('/api/orders');",
6411
+ "good": "// 业务组件只负责编排 input.objects 与私有协作内核;数据读取由页面 behavior.from 声明,写操作交 defineKitActions\nconst from = input.objects.orders.behavior?.from;"
6412
+ },
6372
6413
  "KIT-COMP-002": {
6373
6414
  "causes": [
6374
6415
  "kind 小写开头",
@@ -1,14 +1,17 @@
1
- // 应用扩展组件的唯一接入路径门禁(KIT-APP-004 / KIT-APP-005)。
1
+ // 应用扩展组件的唯一接入路径与防逃逸硬门禁(KIT-APP-004 / KIT-APP-005 / KIT-APP-014 / KIT-APP-017 / KIT-APP-018 / KIT-APP-019)。
2
2
  //
3
- // 设计原则:接入 soma-kit 只有一条路,禁止应用组件绕过标准组件库与样式编译管线:
4
- // 1) KIT-APP-004:所有登记进 baseComponents / staticObjectComponents 的 App* 组件,必须经
3
+ // 设计原则:接入 soma-kit 只有一条路,禁止应用绕过业务组件与样式编译管线:
4
+ // 1) KIT-APP-004:所有登记的自定义组件(含业务组件私有 dataComponents),必须经
5
5
  // wrapKitDataComponent、composeKitDataComponents 或 declareKitUses 显式登记依赖组件与候选类元数据;
6
6
  // 声明的 uses 必须是真实存在的内置组件名,own 候选类必须通过 checkClasses 校验(禁方括号任意值)。
7
7
  // 2) KIT-APP-005:严禁应用组件在 templateHtml、控制器或源码中私自拼写已被 soma-kit
8
8
  // 标准组件接管的原生表单控件(原生 <select>、原生 <input type="range">、原生 <input type="date|datetime-local|time|month|week">),
9
9
  // 严禁在 TS/HTML 中书写内联 style / 操作 .style / setAttribute('style', ...),
10
10
  // 也严禁在非组件 TS(views/actions/api/soma.app.ts 等)中操作 .className / .classList 或手绑 addEventListener 等 DOM 事件。
11
- // 下拉一律走 Select / Combobox / mountKitSelectField,滑块一律走 Range,日期时间一律走 Date / DateRange / TimePicker。
11
+ // 3) KIT-APP-017:全应用零野生 CSS(.css/.scss/.less/.sass/.styl 文件与 import/require)与野生页面 HTML(pages/src/web/views/components 下 .html/.htm)。
12
+ // 4) KIT-APP-018:禁命令式浮层(showModal / showPopover / createElement('dialog') / document.body.append*)、
13
+ // 禁非组件目录 DOM 构造(createElement / createElementNS / innerHTML / outerHTML / insertAdjacentHTML)与禁伪造 Symbol.for('soma-kit.*')。
14
+ // 5) KIT-APP-019:禁组件内手写 <table>/<thead>/<form>/<dialog> 与裸 fetch / XMLHttpRequest,禁业务组件源码硬编码 '/api/...'。
12
15
 
13
16
  import type { SomaComponentDefinition } from 'soma-core';
14
17
  import { KIT_BASE_COMPONENTS } from '../base/index';
@@ -146,11 +149,89 @@ export function findForbiddenNativeControls(text: string): Array<{ line: number;
146
149
  return hits;
147
150
  }
148
151
 
152
+ const FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS: readonly ForbiddenRule[] = [
153
+ {
154
+ id: 'show-modal',
155
+ pattern: /\.\s*showModal\s*\(/,
156
+ message: '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
157
+ },
158
+ {
159
+ id: 'show-popover',
160
+ pattern: /\.\s*showPopover\s*\(/,
161
+ message: '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays 或框架浮层端口',
162
+ },
163
+ {
164
+ id: 'create-dialog',
165
+ pattern: /\bcreateElement\s*\(\s*['"`]dialog['"`]\s*\)/i,
166
+ message: '禁止调用 createElement("dialog") 创建命令式浮层;请改用页面声明 overlays(dialog / drawer)',
167
+ },
168
+ {
169
+ id: 'body-append-portal',
170
+ pattern: /\bdocument\s*\.\s*body\s*\.\s*(?:appendChild|append|prepend|insertAdjacentHTML|insertAdjacentElement)\s*\(/,
171
+ message: '禁止向 document.body 命令式挂载浮层或野生 DOM 节点;浮层必须通过页面 overlays 或框架浮层端口托管',
172
+ },
173
+ ];
174
+
175
+ const FORBIDDEN_STRUCTURED_OR_NET_PATTERNS: readonly ForbiddenRule[] = [
176
+ {
177
+ id: 'raw-table-tag',
178
+ pattern: /<\s*table(?=[\s>/])/i,
179
+ message: '禁止在自定义组件中手写 <table> 规整表格;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
180
+ },
181
+ {
182
+ id: 'raw-thead-tag',
183
+ pattern: /<\s*thead(?=[\s>/])/i,
184
+ message: '禁止在自定义组件中手写 <thead> 规整表头;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
185
+ },
186
+ {
187
+ id: 'raw-form-tag',
188
+ pattern: /<\s*form(?=[\s>/])/i,
189
+ message: '禁止在自定义组件中手写 <form> 表单;请使用 soma-kit 标准表单(view.form / KitObjectForm)与业务组件装数据',
190
+ },
191
+ {
192
+ id: 'raw-dialog-tag',
193
+ pattern: /<\s*dialog(?=[\s>/])/i,
194
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
195
+ },
196
+ {
197
+ id: 'raw-fetch-call',
198
+ pattern: /(?:^|[^.\w$])fetch\s*\(|\b(?:window|globalThis|self)\s*\.\s*fetch\s*\(/,
199
+ message: '禁止在组件源码中直接调用 fetch() 绕过数据与动作管道;数据读取请通过页面 behavior.from,写操作请通过 defineKitActions 具名动作',
200
+ },
201
+ {
202
+ id: 'raw-xhr',
203
+ pattern: /\bnew\s+XMLHttpRequest\b/,
204
+ message: '禁止在组件源码中使用 new XMLHttpRequest 绕过数据与动作管道;请改用页面 behavior.from 与 defineKitActions',
205
+ },
206
+ ];
207
+
208
+ function findRuleHits(text: string, rules: readonly ForbiddenRule[]): Array<{ line: number; message: string }> {
209
+ const cleaned = stripCodeComments(text);
210
+ const lines = cleaned.split('\n');
211
+ const hits: Array<{ line: number; message: string }> = [];
212
+ for (let idx = 0; idx < lines.length; idx++) {
213
+ const line = lines[idx]!;
214
+ for (const rule of rules) {
215
+ if (rule.pattern.test(line)) {
216
+ hits.push({ line: idx + 1, message: rule.message });
217
+ break;
218
+ }
219
+ }
220
+ }
221
+ return hits;
222
+ }
223
+
149
224
  /**
150
225
  * 装配期同步校验单个应用扩展组件(浏览器与服务端共用):
151
- * 拦截未经唯一接入路径包装声明的野生组件(KIT-APP-004)与私造非标原生控件(KIT-APP-005)。
226
+ * 拦截未经唯一接入路径包装声明的野生组件(KIT-APP-004)、无标准控制器(KIT-APP-014)、
227
+ * 私造非标原生控件/内联样式(KIT-APP-005);
228
+ * 严格业务组件模式下(strictBizOnly !== false)额外拦截命令式浮层(KIT-APP-018)及手写 table/form/dialog/裸 fetch(KIT-APP-019)。
152
229
  */
153
- export function assertSinglePathComponent(name: string, def: SomaComponentDefinition): void {
230
+ export function assertSinglePathComponent(
231
+ name: string,
232
+ def: SomaComponentDefinition,
233
+ opts?: { readonly strictBizOnly?: boolean },
234
+ ): void {
154
235
  const meta = wrappedCandidateSource(def);
155
236
  if (meta === undefined) {
156
237
  kitFail('KIT-APP-004', `components.${name}`, `应用组件 ${name} 未经唯一接入路径声明:必须通过 wrapKitDataComponent / composeKitDataComponents 包装组合,或经 declareKitUses(${name}, uses, candidates) 显式登记依赖组件与候选类`, `用 wrapKitDataComponent 包装,或在定义处调用 declareKitUses(${name}, uses, candidates)`);
@@ -176,12 +257,36 @@ export function assertSinglePathComponent(name: string, def: SomaComponentDefini
176
257
  if (tplHits.length > 0) {
177
258
  kitFail('KIT-APP-005', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplHits[0]!.message}`, '改用 soma-kit 标准组件(Select / Slider / DatePicker 等),不手写原生控件');
178
259
  }
179
- if (typeof def.controllerFactory === 'function') {
180
- const fnHits = findForbiddenNativeControls(getKitControllerSource(def.controllerFactory));
260
+ const ctrlSrc = typeof def.controllerFactory === 'function' ? getKitControllerSource(def.controllerFactory) : '';
261
+ if (ctrlSrc !== '') {
262
+ const fnHits = findForbiddenNativeControls(ctrlSrc);
181
263
  if (fnHits.length > 0) {
182
264
  kitFail('KIT-APP-005', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${fnHits[0]!.message}`, '控制器里不要创建原生控件,改用 soma-kit 标准组件');
183
265
  }
184
266
  }
267
+
268
+ if (opts?.strictBizOnly !== false) {
269
+ const tplOverlayHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS) : [];
270
+ if (tplOverlayHits.length > 0) {
271
+ kitFail('KIT-APP-018', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays 声明或框架浮层端口托管');
272
+ }
273
+ if (ctrlSrc !== '') {
274
+ const ctrlOverlayHits = findRuleHits(ctrlSrc, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS);
275
+ if (ctrlOverlayHits.length > 0) {
276
+ kitFail('KIT-APP-018', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays 声明或框架浮层端口托管');
277
+ }
278
+ }
279
+ const tplStructHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS) : [];
280
+ if (tplStructHits.length > 0) {
281
+ kitFail('KIT-APP-019', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplStructHits[0]!.message}`, '表格/表单/浮层改用标准数据视图与页面 overlays;数据与写操作经 behavior.from 与 defineKitActions 注入');
282
+ }
283
+ if (ctrlSrc !== '') {
284
+ const ctrlStructHits = findRuleHits(ctrlSrc, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS);
285
+ if (ctrlStructHits.length > 0) {
286
+ kitFail('KIT-APP-019', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlStructHits[0]!.message}`, '表格/表单/浮层改用标准数据视图与页面 overlays;数据与写操作经 behavior.from 与 defineKitActions 注入');
287
+ }
288
+ }
289
+ }
185
290
  }
186
291
 
187
292
  const SKIP_SCAN_DIRS = new Set([
@@ -246,6 +351,37 @@ const HTML_INLINE_ATTR_RULES: readonly ForbiddenRule[] = [
246
351
  },
247
352
  ];
248
353
 
354
+ const HTML_STRUCTURE_FORBIDDEN_RULES: readonly ForbiddenRule[] = [
355
+ {
356
+ id: 'raw-table-tag',
357
+ pattern: /<\s*table(?=[\s>/])/i,
358
+ message: '禁止在自定义组件中手写 <table> 规整表格;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
359
+ },
360
+ {
361
+ id: 'raw-thead-tag',
362
+ pattern: /<\s*thead(?=[\s>/])/i,
363
+ message: '禁止在自定义组件中手写 <thead> 规整表头;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
364
+ },
365
+ {
366
+ id: 'raw-form-tag',
367
+ pattern: /<\s*form(?=[\s>/])/i,
368
+ message: '禁止在自定义组件中手写 <form> 表单;请使用 soma-kit 标准表单(view.form / KitObjectForm)与业务组件装数据',
369
+ },
370
+ {
371
+ id: 'raw-dialog-tag',
372
+ pattern: /<\s*dialog(?=[\s>/])/i,
373
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口',
374
+ },
375
+ ];
376
+
377
+ const CSS_FILE_EXT_RE = /\.(?:css|scss|less|sass|styl)$/i;
378
+ const CSS_IMPORT_SPEC_RE = /\.(?:css|scss|less|sass|styl)(?:[?#].*)?$/i;
379
+ const HTML_FILE_EXT_RE = /\.(?:html|htm)$/i;
380
+ const WILD_HTML_DIR_RE = /^(?:pages|src\/web|views|components)\//;
381
+ const BODY_MUTATION_METHODS = new Set(['appendChild', 'append', 'prepend', 'insertAdjacentHTML', 'insertAdjacentElement']);
382
+ const HARDCODED_API_PATH_RE = /(?:^|[\s:=,'"(`])\/api(?:\/[A-Za-z0-9_./:-]*|$)|\bhttps?:\/\/[^\s'"`]*\/api(?:\/|$)/;
383
+ const APP_HOOK_PROP_NAMES = new Set(['actions', 'requestHook', 'startup', 'services']);
384
+
249
385
  type TsModule = typeof import('typescript');
250
386
 
251
387
  function scriptKindForFile(ts: TsModule, fileName: string): import('typescript').ScriptKind {
@@ -279,108 +415,275 @@ function propertyAccessName(ts: TsModule, node: import('typescript').Expression)
279
415
  return undefined;
280
416
  }
281
417
 
418
+ function isDocumentBodyExpr(ts: TsModule, node: import('typescript').Expression): boolean {
419
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) {
420
+ return isDocumentBodyExpr(ts, node.expression);
421
+ }
422
+ if (propertyAccessName(ts, node) !== 'body') return false;
423
+ const base = ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? node.expression : undefined;
424
+ if (base === undefined) return false;
425
+ if (ts.isIdentifier(base) && base.text === 'document') return true;
426
+ if ((ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) && propertyAccessName(ts, base) === 'document') {
427
+ return ts.isIdentifier(base.expression) && (base.expression.text === 'window' || base.expression.text === 'globalThis' || base.expression.text === 'self');
428
+ }
429
+ return false;
430
+ }
431
+
432
+ function isSymbolForCall(ts: TsModule, node: import('typescript').CallExpression): boolean {
433
+ const expr = node.expression;
434
+ if (!(ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr))) return false;
435
+ if (propertyAccessName(ts, expr) !== 'for') return false;
436
+ const base = expr.expression;
437
+ if (ts.isIdentifier(base) && base.text === 'Symbol') return true;
438
+ if ((ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) && propertyAccessName(ts, base) === 'Symbol') {
439
+ return ts.isIdentifier(base.expression) && (base.expression.text === 'globalThis' || base.expression.text === 'window' || base.expression.text === 'self');
440
+ }
441
+ return false;
442
+ }
443
+
444
+ function isGlobalFetchCall(ts: TsModule, node: import('typescript').CallExpression): boolean {
445
+ const expr = node.expression;
446
+ if (ts.isIdentifier(expr) && expr.text === 'fetch') return true;
447
+ if ((ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr)) && propertyAccessName(ts, expr) === 'fetch') {
448
+ return ts.isIdentifier(expr.expression) && (expr.expression.text === 'window' || expr.expression.text === 'globalThis' || expr.expression.text === 'self');
449
+ }
450
+ return false;
451
+ }
452
+
453
+ function fileDefinesBizComponent(ts: TsModule, sourceFile: import('typescript').SourceFile): boolean {
454
+ let found = false;
455
+ const scan = (node: import('typescript').Node): void => {
456
+ if (found) return;
457
+ if (ts.isCallExpression(node)) {
458
+ const callee = ts.isIdentifier(node.expression)
459
+ ? node.expression.text
460
+ : propertyAccessName(ts, node.expression);
461
+ if (callee === 'defineKitBizComponent') {
462
+ found = true;
463
+ return;
464
+ }
465
+ }
466
+ ts.forEachChild(node, scan);
467
+ };
468
+ scan(sourceFile);
469
+ return found;
470
+ }
471
+
472
+ interface AstScanHit {
473
+ readonly code: string;
474
+ readonly line: number;
475
+ readonly message: string;
476
+ readonly hint?: string;
477
+ }
478
+
479
+ interface AstScanFlags {
480
+ readonly inComponentsDir: boolean;
481
+ readonly isNonCompAllowedIoDir: boolean;
482
+ readonly internalLab: boolean;
483
+ /** 仅 internalLab 时用于区分 *.css.ts 模块导入与真实 .css 样式表导入 */
484
+ readonly isInternalTsModuleSpecifier?: (spec: string) => boolean;
485
+ }
486
+
282
487
  function scanSourceWithAst(
283
488
  ts: TsModule,
284
489
  fullPath: string,
285
490
  code: string,
286
- inComponentsDir: boolean,
287
- ): Array<{ line: number; message: string }> {
491
+ flags: AstScanFlags,
492
+ ): AstScanHit[] {
493
+ const { inComponentsDir, isNonCompAllowedIoDir, internalLab, isInternalTsModuleSpecifier } = flags;
288
494
  const sourceFile = ts.createSourceFile(fullPath, code, ts.ScriptTarget.Latest, true, scriptKindForFile(ts, fullPath));
289
- const hits: Array<{ line: number; message: string }> = [];
495
+ const hasBizComponentDef = !internalLab && fileDefinesBizComponent(ts, sourceFile);
496
+ const checkComponentPurity = !internalLab && !isNonCompAllowedIoDir;
497
+ const hits: AstScanHit[] = [];
290
498
  const seen = new Set<string>();
291
499
 
292
- const pushHit = (node: import('typescript').Node, message: string): void => {
500
+ const pushHit = (codeId: string, node: import('typescript').Node, message: string, hint?: string): void => {
293
501
  const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
294
- const key = `${line}:${message}`;
502
+ const key = `${codeId}:${line}:${message}`;
295
503
  if (seen.has(key)) return;
296
504
  seen.add(key);
297
- hits.push({ line, message });
505
+ hits.push(hint !== undefined ? { code: codeId, line, message, hint } : { code: codeId, line, message });
298
506
  };
299
507
 
300
- const checkHtmlString = (node: import('typescript').Node, html: string, includeInlineAttrs: boolean): void => {
508
+ const checkHtmlString = (
509
+ node: import('typescript').Node,
510
+ html: string,
511
+ includeInlineAttrs: boolean,
512
+ checkStructuredTags: boolean,
513
+ ): void => {
301
514
  if (!html) return;
302
515
  if (includeInlineAttrs) {
303
516
  for (const rule of HTML_INLINE_ATTR_RULES) {
304
- if (rule.pattern.test(html)) pushHit(node, rule.message);
517
+ if (rule.pattern.test(html)) pushHit('KIT-APP-005', node, rule.message);
305
518
  }
306
519
  }
307
520
  for (const rule of HTML_TAG_FORBIDDEN_RULES) {
308
- if (rule.pattern.test(html)) pushHit(node, rule.message);
521
+ if (rule.pattern.test(html)) pushHit('KIT-APP-005', node, rule.message);
522
+ }
523
+ if (checkStructuredTags) {
524
+ for (const rule of HTML_STRUCTURE_FORBIDDEN_RULES) {
525
+ if (rule.pattern.test(html)) {
526
+ pushHit(
527
+ 'KIT-APP-019',
528
+ node,
529
+ rule.message,
530
+ '规整表格/表单/浮层须由页面声明(view.list / view.form / overlays)与标准业务组件渲染',
531
+ );
532
+ }
533
+ }
309
534
  }
310
535
  };
311
536
 
312
- const visit = (node: import('typescript').Node, insideFunction: boolean): void => {
537
+ const checkCssSpecifier = (node: import('typescript').Node, spec: string): void => {
538
+ if (CSS_IMPORT_SPEC_RE.test(spec)) {
539
+ if (internalLab && isInternalTsModuleSpecifier?.(spec) === true) return;
540
+ pushHit(
541
+ 'KIT-APP-017',
542
+ node,
543
+ `禁止在源码中导入野生样式表 "${spec}";样式必须由框架主题求解引擎与 Tailwind 刻度类统一生成`,
544
+ '删除样式表导入,改用 kit.app.yaml#theme 14 维 DSL 与组件候选类',
545
+ );
546
+ }
547
+ };
548
+
549
+ const visit = (node: import('typescript').Node, insideFunction: boolean, insideActionOrHook: boolean): void => {
313
550
  if (ts.isTypeNode(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) {
314
551
  return;
315
552
  }
316
553
 
317
- // 1. AST .style / ['style'] 访问(全应用禁止)
554
+ // 0. KIT-APP-017:静态 import / export / import = require 野生 CSS 文件
555
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
556
+ checkCssSpecifier(node.moduleSpecifier, node.moduleSpecifier.text);
557
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined && ts.isStringLiteral(node.moduleSpecifier)) {
558
+ checkCssSpecifier(node.moduleSpecifier, node.moduleSpecifier.text);
559
+ } else if (
560
+ ts.isImportEqualsDeclaration(node)
561
+ && ts.isExternalModuleReference(node.moduleReference)
562
+ && ts.isStringLiteral(node.moduleReference.expression)
563
+ ) {
564
+ checkCssSpecifier(node.moduleReference.expression, node.moduleReference.expression.text);
565
+ }
566
+
567
+ // 1. AST .style / ['style'] 访问(全应用禁止,KIT-APP-005)
318
568
  if (
319
569
  (ts.isPropertyAccessExpression(node) && node.name.text === 'style')
320
570
  || (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) && node.argumentExpression.text === 'style')
321
571
  ) {
322
- pushHit(node, MSG_STYLE_PROP);
572
+ pushHit('KIT-APP-005', node, MSG_STYLE_PROP);
323
573
  }
324
574
 
325
- // 2. AST 非组件目录禁止操作 .className / .classList
575
+ // 2. AST 非组件目录禁止操作 .className / .classList(KIT-APP-005)
326
576
  if (!inComponentsDir) {
327
577
  const propName = ts.isPropertyAccessExpression(node)
328
578
  ? node.name.text
329
579
  : (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text : undefined);
330
580
  if (propName === 'className' || propName === 'classList') {
331
- pushHit(node, MSG_NON_COMP_CLASS);
581
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
332
582
  }
333
583
  }
334
584
 
335
585
  // 3. AST 函数调用检查
336
586
  if (ts.isCallExpression(node)) {
587
+ // 3a. KIT-APP-017:动态 import('...css') / require('...css')
588
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
589
+ checkCssSpecifier(node.arguments[0], node.arguments[0].text);
590
+ } else if (ts.isIdentifier(node.expression) && node.expression.text === 'require' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
591
+ checkCssSpecifier(node.arguments[0], node.arguments[0].text);
592
+ }
593
+
337
594
  const calleeName = ts.isIdentifier(node.expression)
338
595
  ? node.expression.text
339
- : (ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : undefined);
596
+ : propertyAccessName(ts, node.expression);
597
+
598
+ // 3b. KIT-APP-018(非 internalLab):全应用禁命令式浮层、document.body 挂载与伪造 Symbol.for('soma-kit.*')
599
+ if (!internalLab) {
600
+ if (calleeName === 'showModal') {
601
+ pushHit('KIT-APP-018', node, '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer)或框架浮层端口', '移除命令式 showModal,改用页面 overlays 声明');
602
+ } else if (calleeName === 'showPopover') {
603
+ pushHit('KIT-APP-018', node, '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays 或框架浮层端口', '移除命令式 showPopover,改用页面 overlays 或框架浮层端口');
604
+ }
605
+ if (
606
+ (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
607
+ && calleeName !== undefined
608
+ && BODY_MUTATION_METHODS.has(calleeName)
609
+ && isDocumentBodyExpr(ts, node.expression.expression)
610
+ ) {
611
+ pushHit('KIT-APP-018', node, `禁止调用 document.body.${calleeName}() 命令式挂载浮层或野生 DOM 节点`, '浮层必须通过页面 overlays 或框架浮层端口托管');
612
+ }
613
+ if (isSymbolForCall(ts, node) && node.arguments.length >= 1) {
614
+ const symKey = extractStaticHtmlText(ts, node.arguments[0]!);
615
+ if (symKey.startsWith('soma-kit.')) {
616
+ pushHit('KIT-APP-018', node, `禁止在应用源码中引用或伪造 soma-kit 内部符号 Symbol.for("${symKey}")`, '移除内部符号调用,业务定制一律通过 defineKitBizComponent 登记至 bizComponents');
617
+ }
618
+ }
619
+ }
620
+
621
+ // 3c. KIT-APP-019(非 internalLab):组件源码禁直接调用 fetch()
622
+ if (checkComponentPurity && !insideActionOrHook && isGlobalFetchCall(ts, node)) {
623
+ pushHit('KIT-APP-019', node, '禁止在组件源码中直接调用 fetch() 绕过数据与动作管道;数据读取请通过页面 behavior.from,写操作请通过 defineKitActions 具名动作', '移除组件内 fetch(),改由页面 YAML 的 behavior.from 与 defineKitActions 驱动数据');
624
+ }
340
625
 
626
+ // 3d. KIT-APP-005 + KIT-APP-018(DOM 构造与属性操作)
341
627
  if (calleeName === 'setAttribute' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
342
628
  const attr = node.arguments[0].text.toLowerCase();
343
- if (attr === 'style') pushHit(node, MSG_SET_ATTR_STYLE);
344
- if (!inComponentsDir && attr === 'class') pushHit(node, MSG_NON_COMP_CLASS);
629
+ if (attr === 'style') pushHit('KIT-APP-005', node, MSG_SET_ATTR_STYLE);
630
+ if (!inComponentsDir && attr === 'class') pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
345
631
  } else if (calleeName === 'setAttributeNS' && node.arguments.length >= 2 && ts.isStringLiteralLike(node.arguments[1])) {
346
632
  const attr = node.arguments[1].text.toLowerCase();
347
- if (attr === 'style') pushHit(node, MSG_SET_ATTR_STYLE);
348
- if (!inComponentsDir && attr === 'class') pushHit(node, MSG_NON_COMP_CLASS);
349
- } else if (calleeName === 'createElement' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
350
- const tag = node.arguments[0].text.toLowerCase();
633
+ if (attr === 'style') pushHit('KIT-APP-005', node, MSG_SET_ATTR_STYLE);
634
+ if (!inComponentsDir && attr === 'class') pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
635
+ } else if (calleeName === 'createElement') {
636
+ const tag = node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0]) ? node.arguments[0].text.toLowerCase() : undefined;
351
637
  if (tag === 'style') {
352
- pushHit(node, '禁止调用 createElement("style") 动态注入样式表;请统一使用 Tailwind 候选类与 --soma-* 设计令牌');
638
+ pushHit('KIT-APP-005', node, '禁止调用 createElement("style") 动态注入样式表;请统一使用 Tailwind 候选类与 --soma-* 设计令牌');
353
639
  } else if (tag === 'select') {
354
- pushHit(node, '禁止调用 createElement("select") 创建原生下拉框;请改用 mountKitSelectField 或 Select 组件');
640
+ pushHit('KIT-APP-005', node, '禁止调用 createElement("select") 创建原生下拉框;请改用 mountKitSelectField 或 Select 组件');
641
+ } else if (!internalLab && tag === 'dialog') {
642
+ pushHit('KIT-APP-018', node, '禁止调用 createElement("dialog") 创建命令式浮层;请改用页面声明 overlays(dialog / drawer)', '使用页面 *.kit.yaml 的 overlays 声明浮层');
643
+ } else if (!internalLab && !inComponentsDir) {
644
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 createElement() 命令式构造 DOM;界面必须封装为业务组件及其私有协作组件', '将视图交互内核移入 components/ 下并作为业务组件的 dataComponents 注册');
355
645
  }
646
+ } else if (!internalLab && !inComponentsDir && calleeName === 'createElementNS') {
647
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 createElementNS() 命令式构造 DOM;界面必须封装为业务组件及其私有协作组件', '将 SVG/画布交互内核移入 components/ 下并作为业务组件的 dataComponents 注册');
356
648
  } else if (calleeName === 'insertAdjacentHTML' && node.arguments.length >= 2) {
357
- checkHtmlString(node.arguments[1]!, extractStaticHtmlText(ts, node.arguments[1]!), true);
649
+ checkHtmlString(node.arguments[1]!, extractStaticHtmlText(ts, node.arguments[1]!), true, checkComponentPurity && !insideActionOrHook);
650
+ if (!internalLab && !inComponentsDir) {
651
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 insertAdjacentHTML() 写入野生 DOM;界面必须封装为业务组件', '移除非组件目录中的 DOM 写入逻辑');
652
+ }
358
653
  } else if (!inComponentsDir && (calleeName === 'addEventListener' || calleeName === 'removeEventListener' || calleeName === 'dispatchEvent')) {
359
- pushHit(node, MSG_NON_COMP_EVENT);
654
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_EVENT);
360
655
  } else if (!inComponentsDir && calleeName === 'insertRule') {
361
- pushHit(node, MSG_NON_COMP_CLASS);
656
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
362
657
  }
363
658
  }
364
659
 
365
- // 4. AST new CSSStyleSheet()(非组件目录禁止)
366
- if (!inComponentsDir && ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'CSSStyleSheet') {
367
- pushHit(node, MSG_NON_COMP_CLASS);
660
+ // 4. AST new CSSStyleSheet() / new XMLHttpRequest()
661
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
662
+ if (!inComponentsDir && node.expression.text === 'CSSStyleSheet') {
663
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
664
+ }
665
+ if (checkComponentPurity && !insideActionOrHook && node.expression.text === 'XMLHttpRequest') {
666
+ pushHit('KIT-APP-019', node, '禁止在组件源码中使用 new XMLHttpRequest 绕过数据与动作管道;请改用页面 behavior.from 与 defineKitActions', '移除组件内 XMLHttpRequest,改由页面数据契约与具名动作驱动');
667
+ }
368
668
  }
369
669
 
370
670
  // 5. AST 赋值表达式检查(innerHTML / outerHTML / .on* = / .type = 'range'|'date')
371
671
  if (ts.isBinaryExpression(node) && (node.operatorToken.kind === ts.SyntaxKind.EqualsToken || node.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken)) {
372
672
  const leftName = propertyAccessName(ts, node.left);
373
673
  if (leftName === 'innerHTML' || leftName === 'outerHTML') {
374
- checkHtmlString(node.right, extractStaticHtmlText(ts, node.right), true);
674
+ checkHtmlString(node.right, extractStaticHtmlText(ts, node.right), true, checkComponentPurity && !insideActionOrHook);
675
+ if (!internalLab && !inComponentsDir) {
676
+ pushHit('KIT-APP-018', node, `非组件源码(components/ 之外)禁止写入 .${leftName} 构造野生 DOM;界面必须封装为业务组件`, '将交互视图封装为业务组件及其私有协作组件');
677
+ }
375
678
  } else if (node.operatorToken.kind === ts.SyntaxKind.EqualsToken && leftName !== undefined) {
376
679
  if (DOM_INLINE_ON_EVENTS.has(leftName)) {
377
- pushHit(node, MSG_INLINE_ON_EVENT);
680
+ pushHit('KIT-APP-005', node, MSG_INLINE_ON_EVENT);
378
681
  } else if (leftName === 'type' && ts.isStringLiteralLike(node.right)) {
379
682
  const val = node.right.text.toLowerCase();
380
683
  if (val === 'range') {
381
- pushHit(node, '禁止设置 input.type = "range" 创建原生滑块;请改用 soma-kit 标准组件 Range');
684
+ pushHit('KIT-APP-005', node, '禁止设置 input.type = "range" 创建原生滑块;请改用 soma-kit 标准组件 Range');
382
685
  } else if (/^(?:date|datetime-local|time|month|week)$/.test(val)) {
383
- pushHit(node, '禁止设置原生日期/时间 input.type;请改用 soma-kit 标准组件 Date / DateRange / TimePicker');
686
+ pushHit('KIT-APP-005', node, '禁止设置原生日期/时间 input.type;请改用 soma-kit 标准组件 Date / DateRange / TimePicker');
384
687
  }
385
688
  }
386
689
  }
@@ -390,30 +693,56 @@ function scanSourceWithAst(
390
693
  if (ts.isPropertyAssignment(node)) {
391
694
  const propName = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
392
695
  if (propName === 'templateHtml') {
393
- checkHtmlString(node.initializer, extractStaticHtmlText(ts, node.initializer), true);
696
+ checkHtmlString(node.initializer, extractStaticHtmlText(ts, node.initializer), true, checkComponentPurity && !insideActionOrHook);
394
697
  }
395
698
  }
396
699
 
397
- // 7. 函数体内的字符串/模板字面量中的原生控件标签(如 renderSneaky 返回 `<select>...`),不误伤顶层纯数据字典
700
+ // 7. 函数体内的字符串/模板字面量检查(不误伤顶层纯数据字典)
398
701
  if (insideFunction && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node))) {
399
- checkHtmlString(node, extractStaticHtmlText(ts, node), false);
702
+ const text = extractStaticHtmlText(ts, node);
703
+ checkHtmlString(node, text, false, checkComponentPurity && !insideActionOrHook);
704
+ if (hasBizComponentDef && !insideActionOrHook && HARDCODED_API_PATH_RE.test(text)) {
705
+ pushHit(
706
+ 'KIT-APP-019',
707
+ node,
708
+ '禁止在业务组件源码中硬编码 "/api/..." 接口路径;业务组件必须纯声明式装数据,接口地址须从页面传入的 input.objects(behavior.from / actions)读取',
709
+ '移除硬编码接口路径,改为从 input.objects 读取页面声明的 behavior.from 或具名动作',
710
+ );
711
+ }
712
+ }
713
+
714
+ let nextInsideActionOrHook = insideActionOrHook;
715
+ if (!nextInsideActionOrHook) {
716
+ if (ts.isCallExpression(node)) {
717
+ const callName = ts.isIdentifier(node.expression) ? node.expression.text : propertyAccessName(ts, node.expression);
718
+ if (callName === 'defineKitActions') nextInsideActionOrHook = true;
719
+ } else if (ts.isPropertyAssignment(node)) {
720
+ const propName = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
721
+ if (propName !== undefined && APP_HOOK_PROP_NAMES.has(propName)) nextInsideActionOrHook = true;
722
+ }
400
723
  }
401
724
 
402
725
  const nextInsideFunction = insideFunction || ts.isFunctionLike(node);
403
- ts.forEachChild(node, (child) => visit(child, nextInsideFunction));
726
+ ts.forEachChild(node, (child) => visit(child, nextInsideFunction, nextInsideActionOrHook));
404
727
  };
405
728
 
406
- visit(sourceFile, false);
729
+ visit(sourceFile, false, false);
407
730
  return hits;
408
731
  }
409
732
 
410
733
  /**
411
- * 服务端编译与 `soma kit check` 全量源码 AST 门禁:
412
- * 递归扫描应用根目录 `<root>` 下全部 `.ts` / `.tsx` / `.js` / `.mjs` 源码(跳过 `node_modules` / `dist` / `tests` / `.soma` 等),
413
- * 1) 全应用禁止:非标原生控件、<style>、AST `.style` 访问、`setAttribute('style', ...)`、`innerHTML`/`outerHTML`/`templateHtml` 内联 `style="..."` 或 `on*`、`.onclick =` 等赋值;
414
- * 2) 非 `components/` 目录(如 `views/**`、`actions/**`、`api/**`、`soma.app.ts`)额外禁止:操作 `.className` / `.classList` / `setAttribute('class', ...)` / `CSSStyleSheet` 与手绑 `addEventListener`。
734
+ * 服务端编译与 `soma kit check` 全量源码文件与 AST 门禁:
735
+ * 递归扫描应用根目录 `<root>`(跳过 `node_modules` / `dist` / `tests` / `.soma` 等):
736
+ * 1) KIT-APP-005(全应用始终生效):非标原生控件、<style>、AST `.style` 访问、`setAttribute('style', ...)`、`innerHTML`/`outerHTML`/`templateHtml` 内联 `style="..."` 或 `on*`、`.onclick =`;非 `components/` 禁 `.className`/`.classList`/`setAttribute('class', ...)`/`CSSStyleSheet`/`addEventListener`;
737
+ * 2) KIT-APP-017(全应用始终生效):禁野生 CSS(.css/.scss/.less/.sass/.styl 文件与 import/require)及 `pages/`、`src/web/`、`views/`、`components/` 下手写 `.html`/`.htm`;
738
+ * 3) KIT-APP-018(非 `internalLab` 生效):全应用禁命令式浮层(showModal/showPopover/createElement('dialog')/document.body.append*)与伪造 `Symbol.for('soma-kit.*')`;非 `components/` 禁 `createElement`/`createElementNS`/`innerHTML`/`outerHTML`/`insertAdjacentHTML`;
739
+ * 4) KIT-APP-019(非 `internalLab` 生效):组件源码禁手写 `<table>`/`<thead>`/`<form>`/`<dialog>` 与直接 `fetch()`/`new XMLHttpRequest`;`defineKitBizComponent` 文件禁硬编码 `'/api/...'`。
415
740
  */
416
- export async function scanAppComponentSources(root: string): Promise<KitDiagnostic[]> {
741
+ export async function scanAppComponentSources(
742
+ root: string,
743
+ opts?: { readonly internalLab?: boolean },
744
+ ): Promise<KitDiagnostic[]> {
745
+ const internalLab = opts?.internalLab === true;
417
746
  const fsSpec = 'node:fs/promises';
418
747
  const pathSpec = 'node:path';
419
748
  const tsSpec = 'typescript';
@@ -439,15 +768,68 @@ export async function scanAppComponentSources(root: string): Promise<KitDiagnost
439
768
  await walk(full);
440
769
  continue;
441
770
  }
771
+ const rel = path.relative(root, full).split(path.sep).join('/');
772
+
773
+ // KIT-APP-017:应用目录内零野生 CSS 文件
774
+ if (CSS_FILE_EXT_RE.test(entry.name)) {
775
+ diagnostics.push({
776
+ code: 'KIT-APP-017',
777
+ path: rel,
778
+ message: `禁止在应用目录放置野生样式表文件 "${rel}";样式必须由框架主题引擎与 Tailwind 刻度类统一生成`,
779
+ hint: '删除自定义 CSS/SCSS/LESS 文件,改用 kit.app.yaml#theme 14 维主题 DSL 声明外观',
780
+ });
781
+ continue;
782
+ }
783
+
784
+ // KIT-APP-017:pages/、src/web/、views/、components/ 禁止手写野生 .html/.htm(跳过 public/)
785
+ if (HTML_FILE_EXT_RE.test(entry.name) && WILD_HTML_DIR_RE.test(rel) && !rel.startsWith('public/') && !rel.includes('/public/')) {
786
+ diagnostics.push({
787
+ code: 'KIT-APP-017',
788
+ path: rel,
789
+ message: `禁止在源码目录手写野生 HTML 文件 "${rel}";页面必须通过 pages/*.kit.yaml 声明式编译生成`,
790
+ hint: '删除手写 HTML 文件,改用 pages/*.kit.yaml + 业务组件声明页面',
791
+ });
792
+ continue;
793
+ }
794
+
442
795
  if (!/\.(?:ts|tsx|js|mjs)$/.test(entry.name) || entry.name.endsWith('.d.ts')) continue;
443
796
  const code = await fs.readFile(full, 'utf8');
444
- const rel = path.relative(root, full).split(path.sep).join('/');
445
- const inComponentsDir = rel === 'components' || rel.startsWith('components/');
446
- for (const hit of scanSourceWithAst(ts, full, code, inComponentsDir)) {
797
+ const siblingNames = internalLab ? new Set(entries.filter((e) => !e.isDirectory()).map((e) => e.name)) : undefined;
798
+ const isInternalTsModuleSpecifier = internalLab
799
+ ? (spec: string): boolean => {
800
+ if (!spec.startsWith('./')) return false;
801
+ const base = spec.slice(2);
802
+ if (base.includes('/')) return false;
803
+ return siblingNames!.has(`${base}.ts`) || siblingNames!.has(`${base}.tsx`) || siblingNames!.has(`${base}.mts`);
804
+ }
805
+ : undefined;
806
+ const inComponentsDir =
807
+ rel === 'components'
808
+ || rel.startsWith('components/')
809
+ || rel === 'src/web/components'
810
+ || rel.startsWith('src/web/components/');
811
+ const isNonCompAllowedIoDir =
812
+ rel.startsWith('api/')
813
+ || rel.startsWith('bff/')
814
+ || rel.startsWith('actions/')
815
+ || rel.startsWith('views/')
816
+ || rel.startsWith('src/bff/')
817
+ || rel.startsWith('src/web/actions/')
818
+ || rel.startsWith('src/web/views/')
819
+ || rel.startsWith('server/')
820
+ || /^soma\.server\./.test(rel)
821
+ || /\/soma\.server\./.test(rel);
822
+ for (const hit of scanSourceWithAst(ts, full, code, {
823
+ inComponentsDir,
824
+ isNonCompAllowedIoDir,
825
+ internalLab,
826
+ ...(isInternalTsModuleSpecifier !== undefined ? { isInternalTsModuleSpecifier } : {}),
827
+ })) {
447
828
  diagnostics.push({
448
- code: 'KIT-APP-005',
829
+ code: hit.code,
449
830
  path: `${rel}:${hit.line}`,
450
831
  message: hit.message,
832
+ ...(hit.hint !== undefined ? { hint: hit.hint } : {}),
451
833
  });
452
834
  }
453
835
  }
@@ -17,7 +17,10 @@ import type { SomaHostAssembly } from 'soma-core/server/host-assembly';
17
17
  import { createKitBaseComponents, KIT_BASE_COMPONENTS } from '../base/index';
18
18
  import { bizDataComponents, KIT_BIZ_DATA_COMPONENTS } from '../biz/data-components';
19
19
  import { KIT_BIZ_COMPONENT_NAMES, KIT_FRAME_NAMES } from '../biz/names';
20
+ import { isDefinedKitBizComponent } from '../biz/define';
20
21
  import type { KitBizDefinition } from '../biz/types';
22
+ import { hasInternalLabMark } from './internal-lab';
23
+ import { checkClasses } from '../shared/merge-class';
21
24
  import type { KitThemeConfig } from '../theme/theme-tokens';
22
25
  import type { KitAppDicts, KitAppEntities, KitAppTheme } from './app-config';
23
26
  import { parseKitAppEnvelopeFromYaml, registerKitAppDefaultEnvelope, type KitEnvelope } from '../shared/envelope';
@@ -140,6 +143,8 @@ export interface KitAppRegistry {
140
143
  bizComponents: Record<string, KitBizDefinition>;
141
144
  frames: Record<string, KitFrameDefinition>;
142
145
  appCandidates: readonly string[];
146
+ /** 自定义业务组件自携的私有协作数据组件(已实例化,并入浏览器组件表;页面不可直接选用) */
147
+ bizDataComponents: Record<string, SomaComponentDefinition>;
143
148
  /** 领域包的协作数据组件(已实例化,并入浏览器组件表;页面不可直接选用) */
144
149
  packDataComponents: Record<string, SomaComponentDefinition>;
145
150
  /** 已登记的领域包名 */
@@ -211,6 +216,16 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
211
216
  kitFail('KIT-APP-001', 'pagesDir', pagesDiags[0]!.message, '改为相对应用根的页面子目录名(如 pages),严禁 ./、../ 或宿主机系统绝对路径');
212
217
  }
213
218
  }
219
+ const allowLab = hasInternalLabMark(options);
220
+ const rawBaseNames = Object.keys(options.baseComponents ?? {});
221
+ if (!allowLab && rawBaseNames.length > 0) {
222
+ kitFail(
223
+ 'KIT-APP-016',
224
+ `baseComponents.${rawBaseNames[0]!}`,
225
+ `禁止业务应用注册非业务/非数据的野生基础组件(baseComponents:${rawBaseNames.join('、')});基础控件一律复用框架官方闭集`,
226
+ '外部界面扩展仅开放两档:① 业务组件 bizComponents(defineKitBizComponent,可自带私有 dataComponents);② 纯数据驱动自定义数据组件 staticObjectComponents(一份数据一个组件、数据进事件出,供业务组件 DSL 槽位按名选用)',
227
+ );
228
+ }
214
229
  const allow = new Set(options.overrides ?? []);
215
230
  const builtinBase = new Set<string>(Object.keys(KIT_BASE_COMPONENTS));
216
231
  const baseComponents: KitAppRegistry['baseComponents'] = {};
@@ -219,7 +234,7 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
219
234
  if (builtinBase.has(name) && !allow.has(name)) kitFail('KIT-APP-007', `baseComponents.${name}`, `基础组件 "${name}" 已内置;要覆盖请在 overrides 点名`, `换一个 App 开头的新名字,或在 defineKitApp 的 overrides 里加入 "${name}"`);
220
235
  const def = instantiate(name, input);
221
236
  if (def.contract['layer'] !== 'basic') kitFail('KIT-APP-006', `baseComponents.${name}`, `应用基础组件 ${name} 的契约 layer 必须是 basic`, '契约 layer 改为 basic;业务含数据的组件请登记到 staticObjectComponents');
222
- assertSinglePathComponent(name, def);
237
+ assertSinglePathComponent(name, def, { strictBizOnly: !allowLab });
223
238
  baseComponents[name] = def;
224
239
  }
225
240
 
@@ -233,7 +248,7 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
233
248
  const spec = isSpec(input);
234
249
  const def = instantiate(name, spec ? input.define : input);
235
250
  if (def.contract['layer'] !== 'data') kitFail('KIT-APP-006', `staticObjectComponents.${name}`, `应用数据组件 ${name} 的契约 layer 必须是 data`, '契约 layer 改为 data;纯展示小件请登记到 baseComponents');
236
- assertSinglePathComponent(name, def);
251
+ assertSinglePathComponent(name, def, { strictBizOnly: !allowLab });
237
252
  staticComponents[name] = spec ? { definition: def, accept: input.accept } : { definition: def };
238
253
  }
239
254
 
@@ -285,12 +300,62 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
285
300
  }
286
301
  }
287
302
 
288
- // 业务组件 / 页面框与内置同名:必须在 overrides 点名,不静默覆盖;登记名必须等于定义的 kind
303
+ // 业务组件 / 页面框与内置同名:必须在 overrides 点名,不静默覆盖;登记名必须等于定义的 kind,且必须经 defineKitBizComponent 构造
304
+ const bizDataComponentsMap: Record<string, SomaComponentDefinition> = {};
305
+ const bizCandidates: string[] = [];
306
+ const builtinBizData = new Set<string>(Object.keys(KIT_BIZ_DATA_COMPONENTS));
289
307
  for (const [name, def] of Object.entries(options.bizComponents ?? {})) {
290
308
  if (def === null || typeof def !== 'object' || def.kind !== name) kitFail('KIT-APP-009', `bizComponents.${name}`, `业务组件登记名 "${name}" 与定义的 kind 不一致`, '登记名必须等于定义的 kind');
309
+ if (!isDefinedKitBizComponent(def)) {
310
+ kitFail(
311
+ 'KIT-APP-019',
312
+ `bizComponents.${name}`,
313
+ `业务组件 "${name}" 未通过 defineKitBizComponent(...) 构造,禁止以裸对象绕过业务组件契约`,
314
+ '使用 defineKitBizComponent({ kind, roles, areas, dataComponents?, candidates?, compile }) 定义后再登记至 bizComponents',
315
+ );
316
+ }
291
317
  if (KIT_BIZ_COMPONENT_NAMES.includes(name) && !allow.has(name)) {
292
318
  kitFail('KIT-APP-007', `bizComponents.${name}`, `业务组件 "${name}" 已内置;要覆盖请在 overrides 点名`, `换一个新名字,或在 defineKitApp 的 overrides 里加入 "${name}"`);
293
319
  }
320
+ for (const [compName, compInput] of Object.entries(def.dataComponents ?? {})) {
321
+ if (
322
+ builtinBase.has(compName)
323
+ || KIT_STATIC_BUILTIN_NAMES.includes(compName)
324
+ || KIT_BIZ_COMPONENT_NAMES.includes(compName)
325
+ || builtinBizData.has(compName)
326
+ || compName in baseComponents
327
+ || compName in staticComponents
328
+ || compName in bizDataComponentsMap
329
+ ) {
330
+ kitFail(
331
+ 'KIT-APP-007',
332
+ `bizComponents.${name}.dataComponents.${compName}`,
333
+ `业务组件 ${name} 的私有协作数据组件 "${compName}" 与内置或已登记组件重名`,
334
+ `为 ${name} 的私有协作组件更换唯一不冲突的名称`,
335
+ );
336
+ }
337
+ const compDef = instantiate(compName, compInput);
338
+ if (compDef.contract['layer'] !== 'data') {
339
+ kitFail(
340
+ 'KIT-APP-006',
341
+ `bizComponents.${name}.dataComponents.${compName}`,
342
+ `业务组件 ${name} 的私有协作数据组件 ${compName} 的契约 layer 必须是 data`,
343
+ '契约 layer 改为 data;业务组件私有交互内核须通过 data 层组件承接业务数据',
344
+ );
345
+ }
346
+ assertSinglePathComponent(compName, compDef, { strictBizOnly: !allowLab });
347
+ bizDataComponentsMap[compName] = compDef;
348
+ }
349
+ for (const rawCand of def.candidates ?? []) {
350
+ for (const tok of rawCand.split(/\s+/)) {
351
+ if (tok === '') continue;
352
+ const bad = checkClasses(tok, `bizComponents.${name}.candidates`);
353
+ if (bad.length > 0) {
354
+ kitFail('KIT-COMP-003', `bizComponents.${name}.candidates`, `业务组件 ${name} 的候选类 "${tok}" 非法:${bad[0]!.message}`, '候选类只能用刻度内的 Tailwind 类,不写方括号任意值');
355
+ }
356
+ bizCandidates.push(tok);
357
+ }
358
+ }
294
359
  }
295
360
  for (const [name, def] of Object.entries(options.frames ?? {})) {
296
361
  if (def === null || typeof def !== 'object' || def.kind !== name) kitFail('KIT-APP-009', `frames.${name}`, `页面框登记名 "${name}" 与定义的 kind 不一致`, '登记名必须等于定义的 kind');
@@ -300,9 +365,9 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
300
365
  }
301
366
  const bizComponents: Record<string, KitBizDefinition> = { ...(options.bizComponents ?? {}) };
302
367
  const packDataComponents: Record<string, SomaComponentDefinition> = {};
303
- const candidates = new Set<string>(options.appCandidates ?? []);
368
+ const candidates = new Set<string>([...(options.appCandidates ?? []), ...bizCandidates]);
304
369
  const packNames: string[] = [];
305
- mergePacks(options.packs ?? [], { baseComponents, staticComponents, bizComponents, packDataComponents, candidates, packNames });
370
+ mergePacks(options.packs ?? [], { baseComponents, staticComponents, bizComponents, bizDataComponents: bizDataComponentsMap, packDataComponents, candidates, packNames });
306
371
 
307
372
  return {
308
373
  baseComponents,
@@ -312,7 +377,8 @@ export function buildAppRegistry(options: DefineKitAppOptions): KitAppRegistry {
312
377
  viewInfos,
313
378
  bizComponents,
314
379
  frames: { ...(options.frames ?? {}) },
315
- appCandidates: options.packs !== undefined && options.packs.length > 0 ? [...candidates] : (options.appCandidates ?? []),
380
+ appCandidates: (options.packs !== undefined && options.packs.length > 0) || bizCandidates.length > 0 ? [...candidates] : (options.appCandidates ?? []),
381
+ bizDataComponents: bizDataComponentsMap,
316
382
  packDataComponents,
317
383
  packNames,
318
384
  appEnvelope,
@@ -323,6 +389,7 @@ interface PackMergeTarget {
323
389
  baseComponents: KitAppRegistry['baseComponents'];
324
390
  staticComponents: KitAppRegistry['staticComponents'];
325
391
  bizComponents: Record<string, KitBizDefinition>;
392
+ bizDataComponents: Record<string, SomaComponentDefinition>;
326
393
  packDataComponents: Record<string, SomaComponentDefinition>;
327
394
  candidates: Set<string>;
328
395
  packNames: string[];
@@ -344,6 +411,7 @@ function mergePacks(packs: readonly KitPack[], t: PackMergeTarget): void {
344
411
  for (const n of Object.keys(t.baseComponents)) taken.set(n, '应用基础组件');
345
412
  for (const n of Object.keys(t.staticComponents)) taken.set(n, '应用数据组件');
346
413
  for (const n of Object.keys(t.bizComponents)) taken.set(n, '应用业务组件');
414
+ for (const n of Object.keys(t.bizDataComponents)) taken.set(n, '业务组件私有协作数据组件');
347
415
 
348
416
  const claim = (name: string, path: string, who: string): boolean => {
349
417
  const prev = taken.get(name);
@@ -410,6 +478,7 @@ export function buildBrowserMount(registry: KitAppRegistry): KitBrowserMount {
410
478
  // 业务组件壳与页面框层依赖的协作常驻组件与内置数据组件同表;内置名不与应用名冲突(应用名须 App 开头)
411
479
  const components: Record<string, SomaComponentDefinition> = { ...base, ...data, ...createKitFrameResidentComponents(), ...bizDataComponents() };
412
480
  for (const [name, entry] of Object.entries(registry.staticComponents)) components[name] = entry.definition;
481
+ for (const [name, def] of Object.entries(registry.bizDataComponents)) components[name] = def;
413
482
  for (const [name, def] of Object.entries(registry.packDataComponents)) components[name] = def;
414
483
  // 应用登记项同名覆盖内置时,常驻表优先(core 以 components 为准),不再按需加载内置版
415
484
  return { components, lazyComponents: { ...KIT_STATIC_LAZY_LOADERS }, actions: { ...registry.actions }, pageRoots: { ...registry.views } };
@@ -0,0 +1,90 @@
1
+ // 仓内内部实验室豁免判定(内部私有模块,严禁从 soma-kit/app 或 package.json#exports 导出)。
2
+ //
3
+ // 安全闭环:
4
+ // 1. 仓内单测通过 withInternalLabMode(options) 将夹具对象登记进进程内私有 WeakSet,外部代码拿不到该函数;
5
+ // 2. 仓内视觉实验室 soma-kit-demo 需跨浏览器与服务端双面运行且不能深导入 soma-kit/src/**,
6
+ // 故在其 defineKitApp 选项上标注非公开符号 KIT_INTERNAL_DEMO_MARK;
7
+ // 3. 服务端 assembleKitServer 必须调用 verifyInternalLabRoot 对该符号做目录物理验真
8
+ // (package.json 的 name === 'soma-kit-demo'、private === true 且同级存在 ../soma-kit/spec/kit-grammar.json),
9
+ // 且非真实验室应用的源码 AST 门禁(KIT-APP-018)直接拦截 Symbol.for('soma-kit.*') 字面量,外部应用 0 绕过口。
10
+ //
11
+ // 注意:本模块会被 define-kit-app.ts 静态引入(进浏览器包),顶层严禁静态 import node:* 或 typescript。
12
+
13
+ import type { DefineKitAppOptions } from './define-kit-app';
14
+ import type { KitDiagnostic } from '../object-renderer/types';
15
+
16
+ const INTERNAL_LAB_OPTIONS = new WeakSet<object>();
17
+
18
+ /** 仓内视觉实验室(soma-kit-demo)专用内部标记;外部应用伪造将被服务端物理验真与 AST 门禁双杀(KIT-APP-018) */
19
+ export const KIT_INTERNAL_DEMO_MARK = Symbol.for('soma-kit.internal.monorepo-demo');
20
+
21
+ /** 仅限 soma-kit 仓内单测使用:标记测试夹具选项处于内部实验室模式(走私有 WeakSet,不泄漏公开字段) */
22
+ export function withInternalLabMode<T extends DefineKitAppOptions>(options: T): T {
23
+ INTERNAL_LAB_OPTIONS.add(options);
24
+ return options;
25
+ }
26
+
27
+ /** 判定选项是否通过仓内私有 WeakSet 登记为内部实验室测试夹具 */
28
+ export function isInternalLabOptions(options: unknown): boolean {
29
+ return typeof options === 'object' && options !== null && INTERNAL_LAB_OPTIONS.has(options);
30
+ }
31
+
32
+ /** 判定选项对象是否携带仓内演示应用标记(浏览器期只作形态判断,服务端必须经 verifyInternalLabRoot 物理验真) */
33
+ export function hasInternalDemoMark(options: unknown): boolean {
34
+ return typeof options === 'object' && options !== null && (options as Record<symbol, unknown>)[KIT_INTERNAL_DEMO_MARK] === true;
35
+ }
36
+
37
+ /** 浏览器/同步装配期快速判断(WeakSet 测试夹具或带仓内演示标记);最终可信裁决由服务端 verifyInternalLabRoot 做出 */
38
+ export function hasInternalLabMark(options: unknown): boolean {
39
+ return isInternalLabOptions(options) || hasInternalDemoMark(options);
40
+ }
41
+
42
+ /** 服务端物理验真:仅当 root 确系本仓库同级 soma-kit-demo 时返回 true */
43
+ export async function isMonorepoKitDemoRoot(
44
+ root: string,
45
+ fs: typeof import('node:fs/promises'),
46
+ path: typeof import('node:path'),
47
+ ): Promise<boolean> {
48
+ try {
49
+ const pkgText = await fs.readFile(path.join(root, 'package.json'), 'utf8');
50
+ const pkg = JSON.parse(pkgText) as { name?: unknown; private?: unknown };
51
+ if (pkg.name !== 'soma-kit-demo' || pkg.private !== true) return false;
52
+ const siblingGrammar = path.resolve(root, '..', 'soma-kit', 'spec', 'kit-grammar.json');
53
+ await fs.access(siblingGrammar);
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * 服务端实验室身份物理验真:
62
+ * - WeakSet 登记的仓内单测夹具直接放行;
63
+ * - 携带 KIT_INTERNAL_DEMO_MARK 的应用必须通过 soma-kit-demo 物理目录验真,伪造即产出 KIT-APP-018 硬诊断并取消豁免。
64
+ */
65
+ export async function verifyInternalLabRoot(
66
+ root: string,
67
+ options: unknown,
68
+ fs: typeof import('node:fs/promises'),
69
+ path: typeof import('node:path'),
70
+ ): Promise<{ readonly internalLab: boolean; readonly diagnostics: KitDiagnostic[] }> {
71
+ if (isInternalLabOptions(options)) {
72
+ return { internalLab: true, diagnostics: [] };
73
+ }
74
+ if (hasInternalDemoMark(options)) {
75
+ const ok = await isMonorepoKitDemoRoot(root, fs, path);
76
+ if (ok) return { internalLab: true, diagnostics: [] };
77
+ return {
78
+ internalLab: false,
79
+ diagnostics: [
80
+ {
81
+ code: 'KIT-APP-018',
82
+ path: 'soma.app.ts',
83
+ message: '检测到非框架内部实验室应用伪造内部实验室符号(Symbol.for("soma-kit.internal.monorepo-demo")),已拒绝豁免',
84
+ hint: '移除伪造的内部符号标记,并将自定义界面封装为标准业务组件(defineKitBizComponent + bizComponents)',
85
+ },
86
+ ],
87
+ };
88
+ }
89
+ return { internalLab: false, diagnostics: [] };
90
+ }
package/src/app/server.ts CHANGED
@@ -28,6 +28,7 @@ import { kitThemeShardUsageOfPage, mergeKitThemeShardUsage, sameKitThemeShardUsa
28
28
  import type { KitThemeUsage } from '../shared/theme-usage';
29
29
  import { parseAppConfig, checkRemovedThemeKeys, migrateKitRuntimeTheme, parseKitTheme, type KitAppTheme } from './app-config';
30
30
  import { scanAppComponentSources } from './component-gate';
31
+ import { verifyInternalLabRoot } from './internal-lab';
31
32
  import { handleKitThemeRequest } from './theme-endpoint';
32
33
  import type { DefineKitAppOptions, KitAppRegistry } from './define-kit-app';
33
34
  import { KIT_PAGE_OWNER, KIT_TIER_FACTS_MISSING, createKitServerPages, kitRuntimePageFactsOfVersion, type KitRuntimePageFacts, type KitRuntimePagePlan } from './server-pages';
@@ -743,17 +744,48 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
743
744
  const path = await nodePath();
744
745
  const fs = await nodeFs();
745
746
  const root = await resolveKitAppRoot(options.root, path);
747
+ const labCheck = await verifyInternalLabRoot(root, options, fs, path);
748
+ const internalLab = labCheck.internalLab;
746
749
 
747
750
  // 1 kit.app.yaml
748
751
  const appFile = path.join(root, options.app ?? 'kit.app.yaml');
749
752
  const appText = await readIfExists(appFile);
750
- const diagnostics: KitDiagnostic[] = [];
753
+ const diagnostics: KitDiagnostic[] = [...labCheck.diagnostics];
751
754
  const parsedAppYaml = appText === undefined ? undefined : await parseYaml(appText, 'kit.app.yaml', diagnostics);
752
755
  const config = parseAppConfig(parsedAppYaml, diagnostics);
753
756
 
754
- // 2 与代码登记对账(两边都要有)
755
- for (const name of Object.keys(config.baseComponents)) {
756
- if (!(name in registry.baseComponents)) diagnostics.push({ code: 'KIT-APP-001', path: `baseComponents.${name}`, message: `kit.app.yaml 登记了基础组件 ${name},soma.app.ts 没有提供实现` });
757
+ if (!internalLab) {
758
+ for (const name of Object.keys(options.baseComponents ?? {})) {
759
+ diagnostics.push({
760
+ code: 'KIT-APP-016',
761
+ path: `baseComponents.${name}`,
762
+ message: `禁止业务应用注册非业务/非数据的野生基础组件 ${name}(baseComponents);基础控件一律复用框架官方闭集`,
763
+ hint: '改用 bizComponents(defineKitBizComponent,可自带私有 dataComponents)或纯数据驱动自定义数据组件 staticObjectComponents',
764
+ });
765
+ }
766
+ for (const name of Object.keys(config.baseComponents)) {
767
+ diagnostics.push({
768
+ code: 'KIT-APP-016',
769
+ path: `kit.app.yaml.baseComponents.${name}`,
770
+ message: `禁止在 kit.app.yaml 中声明非业务/非数据的野生基础组件 ${name}(baseComponents);基础控件一律复用框架官方闭集`,
771
+ hint: '删除 kit.app.yaml#baseComponents,改用业务组件 bizComponents 或纯数据驱动数据组件 staticObjectComponents',
772
+ });
773
+ }
774
+ if (config.style !== undefined) {
775
+ diagnostics.push({
776
+ code: 'KIT-APP-017',
777
+ path: 'kit.app.yaml.style',
778
+ message: `禁止在 kit.app.yaml 中通过 style: "${config.style}" 引入野生样式表;样式必须由框架主题求解引擎统一生成`,
779
+ hint: '删除 kit.app.yaml#style,改用 kit.app.yaml#theme 14 维主题 DSL 声明配色、字阶、圆角与层次',
780
+ });
781
+ }
782
+ }
783
+
784
+ // 2 与代码登记对账(两边都要有;非实验室应用的 baseComponents 已由 KIT-APP-016 拒收,staticObjectComponents 照常对账)
785
+ if (internalLab) {
786
+ for (const name of Object.keys(config.baseComponents)) {
787
+ if (!(name in registry.baseComponents)) diagnostics.push({ code: 'KIT-APP-001', path: `baseComponents.${name}`, message: `kit.app.yaml 登记了基础组件 ${name},soma.app.ts 没有提供实现` });
788
+ }
757
789
  }
758
790
  // 只在代码里登记(kit.app.yaml#baseComponents 没有条目):不报错,按代码登记即可(不往配置对象里写东西)
759
791
  const staticContracts: Record<string, { accept: 'single' | 'list'; emits: readonly string[]; props: readonly string[]; propTypes: Readonly<Record<string, string>>; composition?: KitCompositionRole }> = {};
@@ -777,12 +809,12 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
777
809
  staticContracts[name] = { accept, emits: Object.keys(entry.definition.contract.emits ?? {}), props: Object.keys(entry.definition.contract.props ?? {}), propTypes: staticPropTypesOf(entry.definition), ...(role !== undefined ? { composition: role } : {}) };
778
810
  }
779
811
  }
780
- const sourceGateDiagnostics = await scanAppComponentSources(root);
812
+ const sourceGateDiagnostics = await scanAppComponentSources(root, { internalLab });
781
813
  diagnostics.push(...sourceGateDiagnostics);
782
814
 
783
- // 3 主题头(不在此处提前抛错,确保后面页面的编译诊断也能一次收集报全)
815
+ // 3 主题头(不在此处提前抛错,确保后面页面的编译诊断也能一次收集报全;非实验室应用禁止 kit.app.yaml#style,已报 KIT-APP-017)
784
816
  let themeCss = KIT_DEFAULT_THEME_CSS;
785
- if (config.style !== undefined) {
817
+ if (internalLab && config.style !== undefined) {
786
818
  const text = await readIfExists(path.resolve(root, config.style));
787
819
  if (text === undefined) {
788
820
  diagnostics.push({ code: 'KIT-APP-001', path: 'style', message: `找不到 ${config.style}` });
@@ -881,6 +913,7 @@ export async function assembleKitServer(options: DefineKitAppOptions, registry:
881
913
  const componentDefinitions = {
882
914
  ...registry.baseComponents,
883
915
  ...Object.fromEntries(Object.entries(registry.staticComponents).map(([n, e]) => [n, e.definition])),
916
+ ...registry.bizDataComponents,
884
917
  ...registry.packDataComponents,
885
918
  };
886
919
  // 应用组件契约上的静态自报声明 → 页面线的补登表来源(逐组件校验、坏组件隔离告警);没有任何合法声明时不写这个键
package/src/biz/define.ts CHANGED
@@ -1,10 +1,17 @@
1
1
  // defineKitBizComponent:登记一个业务组件定义。只做形状自检,不做编译。
2
- // 业务组件的 kind 必须是 PascalCase;roles 至少一个必填角色;areas 不得重名。
2
+ // 业务组件的 kind 必须是 PascalCase;roles 至少一个必填角色;areas 不得重名;
3
+ // 可选携带私有协作数据组件(dataComponents)与 Tailwind 候选类(candidates)。
3
4
 
4
5
  import type { KitBizDefinition } from './types';
5
6
  import { kitFail } from '../shared/kit-error';
6
7
 
7
8
  const KIND = /^[A-Z][A-Za-z0-9]*$/;
9
+ const DEFINED_BIZ_COMPONENTS = new WeakSet<KitBizDefinition>();
10
+
11
+ /** 判定对象是否经 defineKitBizComponent(...) 合法构造(用于装配期 KIT-APP-019 校验) */
12
+ export function isDefinedKitBizComponent(def: unknown): def is KitBizDefinition {
13
+ return def !== null && typeof def === 'object' && DEFINED_BIZ_COMPONENTS.has(def as KitBizDefinition);
14
+ }
8
15
 
9
16
  export function defineKitBizComponent(def: KitBizDefinition): KitBizDefinition {
10
17
  if (!KIND.test(def.kind)) {
@@ -17,8 +24,30 @@ export function defineKitBizComponent(def: KitBizDefinition): KitBizDefinition {
17
24
  if (new Set(def.areas).size !== def.areas.length) {
18
25
  kitFail('KIT-COMP-002', `bizComponents.${def.kind}.areas`, `业务组件 ${def.kind} 的 areas 有重名`, 'areas 里每个区域名只写一次');
19
26
  }
27
+ if (def.dataComponents !== undefined) {
28
+ if (def.dataComponents === null || typeof def.dataComponents !== 'object' || Array.isArray(def.dataComponents)) {
29
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.dataComponents`, `业务组件 ${def.kind} 的 dataComponents 必须是 { 组件名: 组件定义或工厂函数 } 对象`, '传入私有协作数据组件映射对象,或省略该字段');
30
+ }
31
+ for (const [compName, compVal] of Object.entries(def.dataComponents)) {
32
+ if (!KIND.test(compName)) {
33
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.dataComponents.${compName}`, `业务组件 ${def.kind} 的私有协作组件名必须是 PascalCase,收到 "${compName}"`, '改成大写字母开头的驼峰名,如 AnnotationCanvasCore');
34
+ }
35
+ const validComp =
36
+ typeof compVal === 'function'
37
+ || (typeof compVal === 'object' && compVal !== null && (compVal as { contract?: unknown }).contract !== undefined);
38
+ if (!validComp) {
39
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.dataComponents.${compName}`, `业务组件 ${def.kind} 的私有协作组件 "${compName}" 必须是组件定义(含 contract)或返回它的函数`, '传入 defineComponent(...) 返回值或 () => defineComponent(...) 工厂函数');
40
+ }
41
+ }
42
+ }
43
+ if (def.candidates !== undefined) {
44
+ if (!Array.isArray(def.candidates) || !def.candidates.every((c) => typeof c === 'string')) {
45
+ kitFail('KIT-COMP-002', `bizComponents.${def.kind}.candidates`, `业务组件 ${def.kind} 的 candidates 必须是字符串数组`, '传入 Tailwind 候选类字符串数组,如 ["flex", "gap-section"]');
46
+ }
47
+ }
20
48
  if (typeof def.compile !== 'function') {
21
49
  kitFail('KIT-COMP-002', `bizComponents.${def.kind}.compile`, `业务组件 ${def.kind} 缺 compile()`, '提供 compile(input, ctx) 返回片段');
22
50
  }
51
+ DEFINED_BIZ_COMPONENTS.add(def);
23
52
  return def;
24
53
  }
package/src/biz/types.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // 它不是组件层:编译器按 `product.kind` 查 `KIT_BIZ_COMPONENTS`,把页面传入的各对象交给 `compile`,
5
5
  // 得到一个 KitFragment(HTML + `_ui.yaml` 片段 + `_event.yaml` 片段 + 候选类 + 诊断),再交页面框装入。
6
6
 
7
+ import type { SomaComponentDefinition } from 'soma-core';
7
8
  import type { ArrangePageEnvelopeSurfaceKind, ArrangePageEnvelopeTier } from 'soma-foundation/arrange';
8
9
  import type { KitObject } from '../object-renderer/types';
9
10
  import type { KitListLayout } from '../recipes/page-width';
@@ -141,5 +142,12 @@ export interface KitBizDefinition {
141
142
  * 页面模式推导的版心(兼容自定义业务组件旧口;内置组件优先使用声明式 envelope 特征)。
142
143
  */
143
144
  pageMaxWidth?: string;
145
+ /**
146
+ * 业务组件私有的协作数据组件(浏览器运行期交互内核,如批注画布、泳道图等):
147
+ * 装配时自动实例化并并入浏览器组件表,但**不**暴露到页面 `*.kit.yaml` 的 `staticComponent` 选用表中。
148
+ */
149
+ dataComponents?: Readonly<Record<string, SomaComponentDefinition | (() => SomaComponentDefinition)>>;
150
+ /** 业务组件及其私有协作数据组件用到的 Tailwind 候选类(装配时自动合并入应用候选类) */
151
+ candidates?: readonly string[];
144
152
  compile(input: KitBizInput, ctx: KitBizContext): KitFragment;
145
153
  }
@@ -1,6 +1,6 @@
1
1
  // 生成物,不得改写:由 soma-kit/scripts/build-kit-grammar-runtime.mjs 从 spec/kit-grammar.json 抽出。
2
2
  // 浏览器侧只读这份运行期切片(闭集与限值);编译侧读完整真源。改真源后运行 `npm run grammar:runtime -w soma-kit` 重新生成。
3
- // 真源指纹 sha256:6ec6018db18518977c7b44090e1c8582d1feeeea8fcec69eec48e555b71132a4
3
+ // 真源指纹 sha256:90ec5184ad50b6f7883453fb235c402ad194efe51506c441b2b61a0f95f0d52d
4
4
 
5
5
  export const KIT_GRAMMAR_RUNTIME = {
6
6
  "i18n": {
@@ -510,6 +510,10 @@ export const KIT_GRAMMAR_RUNTIME = {
510
510
  "KIT-APP-013": "应用代码直接 import \"soma-core\" 或 \"soma-core/*\"(含 import type、export … from、动态 import、require);应用唯一的接触面是 soma-kit/app(tests/ 与 test/ 目录豁免)",
511
511
  "KIT-APP-014": "应用组件的 controllerFactory 必须由 createKitController((api) => ({ ... })) 生成(不接受纯声明式无控制器组件或手写工厂)",
512
512
  "KIT-APP-015": "应用违反双平面与四层分层边界(R-APP-1/2/3):客户端面(web/、soma.app.ts、views/、actions/、components/)静态引用了服务端面(bff/、api/、config/、soma.server.*),或服务端面反向引用客户端面,或 shared/ 引用了端侧或 Node 内置模块,或 BFF 下层(foundation/、domain/)反向引用上层,或页面视图 views/*.view.ts 之间横向互引",
513
+ "KIT-APP-016": "业务应用禁止注册非业务/非数据的野生 baseComponents(基础控件一律复用官方闭集);外部界面扩展仅开放两档:① 业务组件 bizComponents(静态画布 + 按 DSL 装配,可自带私有 dataComponents);② 纯数据驱动自定义数据组件 staticObjectComponents(一份数据一个组件、数据进事件出,供业务组件 DSL 槽位按名选用)",
514
+ "KIT-APP-017": "禁止野生样式表与野生页面 HTML:应用目录不得出现 .css / .scss / .less / .sass / .styl 文件或在源码中 import / export / require 样式表,kit.app.yaml 不得配置 style: 外链样式,且 pages/、src/web/、views/、components/ 下不得手写 .html / .htm;样式外观统一走 kit.app.yaml#theme 14 维 DSL 与 Tailwind 刻度类",
515
+ "KIT-APP-018": "禁止命令式浮层、非组件 DOM 构造与伪造框架内部符号:全应用禁止调用 .showModal() / .showPopover() / createElement('dialog') / document.body.append* 及引用或伪造 Symbol.for('soma-kit.*');components/ 之外的源码禁止调用 createElement / createElementNS / insertAdjacentHTML 或写入 innerHTML / outerHTML",
516
+ "KIT-APP-019": "自定义业务组件或其私有协作组件违反纯声明式装数据契约:业务组件未经 defineKitBizComponent 构造、组件源码内手写 <table> / <thead> / <form> / <dialog> 或直接调用 fetch() / new XMLHttpRequest,或业务组件源码硬编码 '/api/...' 接口路径(必须从页面 input.objects 的 behavior.from 与具名动作读取)",
513
517
  "KIT-COMP-002": "业务组件定义非法:名字不是 PascalCase、没有必填角色槽、areas 重名、缺 compile(),或 composeKitBizComponents 的子部件 / 角色映射不成立",
514
518
  "KIT-COMP-003": "组件候选类 / rootClass / slotClass 含非法 Tailwind 类(不在刻度内或带方括号任意值)",
515
519
  "KIT-COMP-004": "数据组件定义 / 包装 / 登记非法:缺 define()、accept 不是 single / list、被包装组件无控制器、登记名与契约名不一致、layer 不是 data、事件名不是 snake_case,或 composeKitDataComponents 没有子部件",