soma-kit 0.1.17 → 0.1.19

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.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/spec/generated/kit-page.schema.json +11 -1
  3. package/spec/kit-grammar.json +174 -13
  4. package/spec/kit-grammar.schema.json +4 -0
  5. package/src/app/component-gate.ts +668 -55
  6. package/src/app/define-kit-app.ts +75 -6
  7. package/src/app/index.ts +4 -1
  8. package/src/app/internal-lab.ts +90 -0
  9. package/src/app/kit-view-context.ts +44 -2
  10. package/src/app/server.ts +51 -9
  11. package/src/biz/compose.ts +66 -0
  12. package/src/biz/define.ts +38 -1
  13. package/src/biz/index.ts +1 -0
  14. package/src/biz/layout-contracts.ts +119 -4
  15. package/src/biz/link/hub.ts +31 -0
  16. package/src/biz/master-sub/compile.ts +45 -3
  17. package/src/biz/master-sub/index.ts +3 -1
  18. package/src/biz/record-detail/compile.ts +120 -10
  19. package/src/biz/shared/coordinator.ts +245 -48
  20. package/src/biz/shared/index.ts +5 -1
  21. package/src/biz/shared/object-aliases.ts +14 -3
  22. package/src/biz/shared/overlay-compile.ts +56 -5
  23. package/src/biz/shared/overlay-shell.ts +5 -2
  24. package/src/biz/shared/page-form.ts +9 -5
  25. package/src/biz/shared/page-overlay-host.ts +126 -0
  26. package/src/biz/shared/page-overlay-names.ts +27 -0
  27. package/src/biz/shared/runtime-hub.ts +37 -2
  28. package/src/biz/single-form/compile.ts +60 -5
  29. package/src/biz/single-form/index.ts +2 -1
  30. package/src/biz/standard-crud/compile.ts +9 -2
  31. package/src/biz/types.ts +26 -0
  32. package/src/cli/kit-cli.ts +1 -0
  33. package/src/cli/view-writes.ts +130 -3
  34. package/src/compile/compile-page.ts +49 -4
  35. package/src/compile/page-pipeline.ts +4 -0
  36. package/src/compile/parse.ts +14 -0
  37. package/src/compile/stages.ts +5 -4
  38. package/src/compile/types.ts +1 -1
  39. package/src/compile/view-check.ts +49 -17
  40. package/src/data/comment-thread.ts +78 -18
  41. package/src/data/navbar.ts +4 -0
  42. package/src/data/object-form.ts +17 -3
  43. package/src/data/prompt-dialog.ts +102 -15
  44. package/src/frames/page-header.ts +11 -2
  45. package/src/frames/shared.ts +6 -0
  46. package/src/frames/types.ts +2 -0
  47. package/src/generated/kit-grammar-runtime.ts +47 -5
  48. package/src/i18n/kit-text.ts +1 -0
  49. package/src/object-renderer/request-actions.ts +145 -17
  50. package/src/object-renderer/types.ts +7 -0
  51. package/src/shared/dom-attrs-registry.ts +5 -3
  52. package/src/shared/dom-attrs.ts +2 -0
  53. package/src/spatial/declared-actions.ts +6 -3
  54. package/src/spatial/emit.ts +1 -1
  55. package/src/spatial/expand.ts +7 -2
@@ -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,107 @@ 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),由 ctx.openOverlay / builtin: openOverlay 打开',
157
+ },
158
+ {
159
+ id: 'show-popover',
160
+ pattern: /\.\s*showPopover\s*\(/,
161
+ message: '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
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
+ /**
176
+ * 框架内部的命令式浮层原语(soma-kit/data 导出;框架内 ctx.confirm / ctx.prompt / 记录选择器在用):
177
+ * 应用源码导入或调用报 KIT-APP-020(0.1.19 过渡期告警,进 deprecations;0.2.0 并入 KIT-APP-018)
178
+ */
179
+ const KIT_IMPERATIVE_OVERLAY_PORTS: ReadonlySet<string> = new Set(['mountKitModal', 'mountKitDrawer']);
180
+ /** 命令式浮层原语所在模块(主导出在 soma-kit/data;soma-kit 根入口 src/index.ts 当前未再导出,保留作历史/别名兜底) */
181
+ const KIT_PORT_MODULES: ReadonlySet<string> = new Set(['soma-kit/data', 'soma-kit']);
182
+ const MSG_IMPERATIVE_PORT = '应用代码不再命令式开窗(mountKitModal / mountKitDrawer 是框架内部原语):窗口在页面 overlays(或 page.overlays)声明,由展示对象 ctx.openOverlay / ctx.closeOverlay 开关,简单确认与输入用 ctx.confirm / ctx.prompt';
183
+ const HINT_IMPERATIVE_PORT = '把窗口内容写成浮层的 view(表单用 view.form,草稿要保留写 draft: keep;异形内容用数据组件 view.summary.staticComponent),开窗改为 builtin: openOverlay 或 ctx.openOverlay(名)';
184
+
185
+ /** KIT-APP-019 的 fetch 允许去处(相对应用根),提示语与 hint 共用 */
186
+ const IO_DIRS_TEXT = 'api/ bff/ actions/ server/ src/bff/ src/web/actions/ soma.server.*,或 defineKitActions / requestHook / startup / services 内';
187
+ const MSG_NON_IO_FETCH = `非 IO 目录禁止直接调用 fetch() 绕过数据与动作管道(允许目录:${IO_DIRS_TEXT})`;
188
+ const MSG_NON_IO_XHR = `非 IO 目录禁止使用 new XMLHttpRequest 绕过数据与动作管道(允许目录:${IO_DIRS_TEXT})`;
189
+ const HINT_NON_IO_NET = '数据读取走页面 behavior.from,写操作走 defineKitActions 具名动作;浏览器侧传输封装与 SSE 读取器放 actions/(如 actions/transport/)';
190
+ const MSG_VIEW_FETCH = '展示对象目录(views/)直接调用 fetch() / new XMLHttpRequest 绕过了 ctx.http 只读面与 ctx.request 写通道(过渡期告警,0.2.0 并入 KIT-APP-019)';
191
+ const HINT_VIEW_FETCH = '读用 ctx.http.get,写用 ctx.request(对象, 动作 id, 载荷) 或具名动作;传输封装放 actions/(如 actions/transport/)';
192
+
193
+ const FORBIDDEN_STRUCTURED_OR_NET_PATTERNS: readonly ForbiddenRule[] = [
194
+ {
195
+ id: 'raw-table-tag',
196
+ pattern: /<\s*table(?=[\s>/])/i,
197
+ message: '禁止在自定义组件中手写 <table> 规整表格;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
198
+ },
199
+ {
200
+ id: 'raw-thead-tag',
201
+ pattern: /<\s*thead(?=[\s>/])/i,
202
+ message: '禁止在自定义组件中手写 <thead> 规整表头;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
203
+ },
204
+ {
205
+ id: 'raw-form-tag',
206
+ pattern: /<\s*form(?=[\s>/])/i,
207
+ message: '禁止在自定义组件中手写 <form> 表单;请使用 soma-kit 标准表单(view.form / KitObjectForm)与业务组件装数据',
208
+ },
209
+ {
210
+ id: 'raw-dialog-tag',
211
+ pattern: /<\s*dialog(?=[\s>/])/i,
212
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
213
+ },
214
+ {
215
+ id: 'raw-fetch-call',
216
+ pattern: /(?:^|[^.\w$])fetch\s*\(|\b(?:window|globalThis|self)\s*\.\s*fetch\s*\(/,
217
+ message: '禁止在组件源码中直接调用 fetch() 绕过数据与动作管道;数据读取请通过页面 behavior.from,写操作请通过 defineKitActions 具名动作',
218
+ },
219
+ {
220
+ id: 'raw-xhr',
221
+ pattern: /\bnew\s+XMLHttpRequest\b/,
222
+ message: '禁止在组件源码中使用 new XMLHttpRequest 绕过数据与动作管道;请改用页面 behavior.from 与 defineKitActions',
223
+ },
224
+ ];
225
+
226
+ function findRuleHits(text: string, rules: readonly ForbiddenRule[]): Array<{ line: number; message: string }> {
227
+ const cleaned = stripCodeComments(text);
228
+ const lines = cleaned.split('\n');
229
+ const hits: Array<{ line: number; message: string }> = [];
230
+ for (let idx = 0; idx < lines.length; idx++) {
231
+ const line = lines[idx]!;
232
+ for (const rule of rules) {
233
+ if (rule.pattern.test(line)) {
234
+ hits.push({ line: idx + 1, message: rule.message });
235
+ break;
236
+ }
237
+ }
238
+ }
239
+ return hits;
240
+ }
241
+
149
242
  /**
150
243
  * 装配期同步校验单个应用扩展组件(浏览器与服务端共用):
151
- * 拦截未经唯一接入路径包装声明的野生组件(KIT-APP-004)与私造非标原生控件(KIT-APP-005)。
244
+ * 拦截未经唯一接入路径包装声明的野生组件(KIT-APP-004)、无标准控制器(KIT-APP-014)、
245
+ * 私造非标原生控件/内联样式(KIT-APP-005);
246
+ * 严格业务组件模式下(strictBizOnly !== false)额外拦截命令式浮层(KIT-APP-018)及手写 table/form/dialog/裸 fetch(KIT-APP-019)。
152
247
  */
153
- export function assertSinglePathComponent(name: string, def: SomaComponentDefinition): void {
248
+ export function assertSinglePathComponent(
249
+ name: string,
250
+ def: SomaComponentDefinition,
251
+ opts?: { readonly strictBizOnly?: boolean },
252
+ ): void {
154
253
  const meta = wrappedCandidateSource(def);
155
254
  if (meta === undefined) {
156
255
  kitFail('KIT-APP-004', `components.${name}`, `应用组件 ${name} 未经唯一接入路径声明:必须通过 wrapKitDataComponent / composeKitDataComponents 包装组合,或经 declareKitUses(${name}, uses, candidates) 显式登记依赖组件与候选类`, `用 wrapKitDataComponent 包装,或在定义处调用 declareKitUses(${name}, uses, candidates)`);
@@ -176,12 +275,36 @@ export function assertSinglePathComponent(name: string, def: SomaComponentDefini
176
275
  if (tplHits.length > 0) {
177
276
  kitFail('KIT-APP-005', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplHits[0]!.message}`, '改用 soma-kit 标准组件(Select / Slider / DatePicker 等),不手写原生控件');
178
277
  }
179
- if (typeof def.controllerFactory === 'function') {
180
- const fnHits = findForbiddenNativeControls(getKitControllerSource(def.controllerFactory));
278
+ const ctrlSrc = typeof def.controllerFactory === 'function' ? getKitControllerSource(def.controllerFactory) : '';
279
+ if (ctrlSrc !== '') {
280
+ const fnHits = findForbiddenNativeControls(ctrlSrc);
181
281
  if (fnHits.length > 0) {
182
282
  kitFail('KIT-APP-005', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${fnHits[0]!.message}`, '控制器里不要创建原生控件,改用 soma-kit 标准组件');
183
283
  }
184
284
  }
285
+
286
+ if (opts?.strictBizOnly !== false) {
287
+ const tplOverlayHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS) : [];
288
+ if (tplOverlayHits.length > 0) {
289
+ kitFail('KIT-APP-018', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays(或 page.overlays)声明');
290
+ }
291
+ if (ctrlSrc !== '') {
292
+ const ctrlOverlayHits = findRuleHits(ctrlSrc, FORBIDDEN_IMPERATIVE_OVERLAY_PATTERNS);
293
+ if (ctrlOverlayHits.length > 0) {
294
+ kitFail('KIT-APP-018', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlOverlayHits[0]!.message}`, '浮层改由页面 *.kit.yaml 的 overlays(或 page.overlays)声明');
295
+ }
296
+ }
297
+ const tplStructHits = typeof def.templateHtml === 'string' ? findRuleHits(def.templateHtml, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS) : [];
298
+ if (tplStructHits.length > 0) {
299
+ kitFail('KIT-APP-019', `components.${name}.templateHtml`, `应用组件 ${name} 的 templateHtml 违规:${tplStructHits[0]!.message}`, '表格/表单/浮层改用标准数据视图与页面 overlays;数据与写操作经 behavior.from 与 defineKitActions 注入');
300
+ }
301
+ if (ctrlSrc !== '') {
302
+ const ctrlStructHits = findRuleHits(ctrlSrc, FORBIDDEN_STRUCTURED_OR_NET_PATTERNS);
303
+ if (ctrlStructHits.length > 0) {
304
+ kitFail('KIT-APP-019', `components.${name}.controller`, `应用组件 ${name} 的控制器违规:${ctrlStructHits[0]!.message}`, '表格/表单/浮层改用标准数据视图与页面 overlays;数据与写操作经 behavior.from 与 defineKitActions 注入');
305
+ }
306
+ }
307
+ }
185
308
  }
186
309
 
187
310
  const SKIP_SCAN_DIRS = new Set([
@@ -246,6 +369,37 @@ const HTML_INLINE_ATTR_RULES: readonly ForbiddenRule[] = [
246
369
  },
247
370
  ];
248
371
 
372
+ const HTML_STRUCTURE_FORBIDDEN_RULES: readonly ForbiddenRule[] = [
373
+ {
374
+ id: 'raw-table-tag',
375
+ pattern: /<\s*table(?=[\s>/])/i,
376
+ message: '禁止在自定义组件中手写 <table> 规整表格;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
377
+ },
378
+ {
379
+ id: 'raw-thead-tag',
380
+ pattern: /<\s*thead(?=[\s>/])/i,
381
+ message: '禁止在自定义组件中手写 <thead> 规整表头;请使用 soma-kit 标准集合表格(view.list)与业务组件装数据',
382
+ },
383
+ {
384
+ id: 'raw-form-tag',
385
+ pattern: /<\s*form(?=[\s>/])/i,
386
+ message: '禁止在自定义组件中手写 <form> 表单;请使用 soma-kit 标准表单(view.form / KitObjectForm)与业务组件装数据',
387
+ },
388
+ {
389
+ id: 'raw-dialog-tag',
390
+ pattern: /<\s*dialog(?=[\s>/])/i,
391
+ message: '禁止在自定义组件中手写 <dialog> 浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开',
392
+ },
393
+ ];
394
+
395
+ const CSS_FILE_EXT_RE = /\.(?:css|scss|less|sass|styl)$/i;
396
+ const CSS_IMPORT_SPEC_RE = /\.(?:css|scss|less|sass|styl)(?:[?#].*)?$/i;
397
+ const HTML_FILE_EXT_RE = /\.(?:html|htm)$/i;
398
+ const WILD_HTML_DIR_RE = /^(?:pages|src\/web|views|components)\//;
399
+ const BODY_MUTATION_METHODS = new Set(['appendChild', 'append', 'prepend', 'insertAdjacentHTML', 'insertAdjacentElement']);
400
+ const HARDCODED_API_PATH_RE = /(?:^|[\s:=,'"(`])\/api(?:\/[A-Za-z0-9_./:-]*|$)|\bhttps?:\/\/[^\s'"`]*\/api(?:\/|$)/;
401
+ const APP_HOOK_PROP_NAMES = new Set(['actions', 'requestHook', 'startup', 'services']);
402
+
249
403
  type TsModule = typeof import('typescript');
250
404
 
251
405
  function scriptKindForFile(ts: TsModule, fileName: string): import('typescript').ScriptKind {
@@ -279,108 +433,482 @@ function propertyAccessName(ts: TsModule, node: import('typescript').Expression)
279
433
  return undefined;
280
434
  }
281
435
 
436
+ function unwrapExpr(ts: TsModule, expr: import('typescript').Expression): import('typescript').Expression {
437
+ let cur = expr;
438
+ while (true) {
439
+ if (
440
+ ts.isParenthesizedExpression(cur)
441
+ || ts.isAsExpression(cur)
442
+ || ts.isTypeAssertionExpression(cur)
443
+ || ts.isNonNullExpression(cur)
444
+ || (typeof ts.isSatisfiesExpression === 'function' && ts.isSatisfiesExpression(cur))
445
+ ) {
446
+ cur = cur.expression;
447
+ continue;
448
+ }
449
+ break;
450
+ }
451
+ return cur;
452
+ }
453
+
454
+ function propertyNameText(ts: TsModule, name: import('typescript').PropertyName): string | undefined {
455
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
456
+ if (ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression)) return name.expression.text;
457
+ return undefined;
458
+ }
459
+
460
+ function bindingElementPropName(ts: TsModule, el: import('typescript').BindingElement): string | undefined {
461
+ if (el.propertyName !== undefined) return propertyNameText(ts, el.propertyName);
462
+ return ts.isIdentifier(el.name) ? el.name.text : undefined;
463
+ }
464
+
465
+ function isPortModuleLoad(ts: TsModule, expr: import('typescript').Expression, allowAwait: boolean): boolean {
466
+ let cur = unwrapExpr(ts, expr);
467
+ if (allowAwait && ts.isAwaitExpression(cur)) {
468
+ cur = unwrapExpr(ts, cur.expression);
469
+ }
470
+ if (!ts.isCallExpression(cur) || cur.arguments.length < 1 || !ts.isStringLiteralLike(cur.arguments[0])) {
471
+ return false;
472
+ }
473
+ const spec = cur.arguments[0].text;
474
+ if (!KIT_PORT_MODULES.has(spec)) return false;
475
+ return cur.expression.kind === ts.SyntaxKind.ImportKeyword
476
+ || (ts.isIdentifier(cur.expression) && cur.expression.text === 'require');
477
+ }
478
+
479
+ function isDocumentBodyExpr(ts: TsModule, node: import('typescript').Expression): boolean {
480
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) {
481
+ return isDocumentBodyExpr(ts, node.expression);
482
+ }
483
+ if (propertyAccessName(ts, node) !== 'body') return false;
484
+ const base = ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? node.expression : undefined;
485
+ if (base === undefined) return false;
486
+ if (ts.isIdentifier(base) && base.text === 'document') return true;
487
+ if ((ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) && propertyAccessName(ts, base) === 'document') {
488
+ return ts.isIdentifier(base.expression) && (base.expression.text === 'window' || base.expression.text === 'globalThis' || base.expression.text === 'self');
489
+ }
490
+ return false;
491
+ }
492
+
493
+ function isSymbolForCall(ts: TsModule, node: import('typescript').CallExpression): boolean {
494
+ const expr = node.expression;
495
+ if (!(ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr))) return false;
496
+ if (propertyAccessName(ts, expr) !== 'for') return false;
497
+ const base = expr.expression;
498
+ if (ts.isIdentifier(base) && base.text === 'Symbol') return true;
499
+ if ((ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) && propertyAccessName(ts, base) === 'Symbol') {
500
+ return ts.isIdentifier(base.expression) && (base.expression.text === 'globalThis' || base.expression.text === 'window' || base.expression.text === 'self');
501
+ }
502
+ return false;
503
+ }
504
+
505
+ function isGlobalFetchCall(ts: TsModule, node: import('typescript').CallExpression): boolean {
506
+ const expr = node.expression;
507
+ if (ts.isIdentifier(expr) && expr.text === 'fetch') return true;
508
+ if ((ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr)) && propertyAccessName(ts, expr) === 'fetch') {
509
+ return ts.isIdentifier(expr.expression) && (expr.expression.text === 'window' || expr.expression.text === 'globalThis' || expr.expression.text === 'self');
510
+ }
511
+ return false;
512
+ }
513
+
514
+ function fileDefinesBizComponent(ts: TsModule, sourceFile: import('typescript').SourceFile): boolean {
515
+ let found = false;
516
+ const scan = (node: import('typescript').Node): void => {
517
+ if (found) return;
518
+ if (ts.isCallExpression(node)) {
519
+ const callee = ts.isIdentifier(node.expression)
520
+ ? node.expression.text
521
+ : propertyAccessName(ts, node.expression);
522
+ if (callee === 'defineKitBizComponent') {
523
+ found = true;
524
+ return;
525
+ }
526
+ }
527
+ ts.forEachChild(node, scan);
528
+ };
529
+ scan(sourceFile);
530
+ return found;
531
+ }
532
+
533
+ interface AstScanHit {
534
+ readonly code: string;
535
+ readonly line: number;
536
+ readonly message: string;
537
+ readonly hint?: string;
538
+ }
539
+
540
+ interface AstScanFlags {
541
+ readonly inComponentsDir: boolean;
542
+ readonly isNonCompAllowedIoDir: boolean;
543
+ readonly internalLab: boolean;
544
+ /**
545
+ * 展示对象目录(views/、src/web/views/):直接 fetch / XMLHttpRequest 报 KIT-APP-021(过渡期告警)而不是放行。
546
+ * 其余检查仍按 IO 目录口径(结构标签检查不扩到 views/,本版不把现有通过的写法变成错误)
547
+ */
548
+ readonly isViewDir?: boolean;
549
+ /** 仅 internalLab 时用于区分 *.css.ts 模块导入与真实 .css 样式表导入 */
550
+ readonly isInternalTsModuleSpecifier?: (spec: string) => boolean;
551
+ }
552
+
282
553
  function scanSourceWithAst(
283
554
  ts: TsModule,
284
555
  fullPath: string,
285
556
  code: string,
286
- inComponentsDir: boolean,
287
- ): Array<{ line: number; message: string }> {
557
+ flags: AstScanFlags,
558
+ ): AstScanHit[] {
559
+ const { inComponentsDir, isNonCompAllowedIoDir, internalLab, isInternalTsModuleSpecifier } = flags;
560
+ const isViewDir = !internalLab && flags.isViewDir === true;
288
561
  const sourceFile = ts.createSourceFile(fullPath, code, ts.ScriptTarget.Latest, true, scriptKindForFile(ts, fullPath));
289
- const hits: Array<{ line: number; message: string }> = [];
562
+ const hasBizComponentDef = !internalLab && fileDefinesBizComponent(ts, sourceFile);
563
+ const checkComponentPurity = !internalLab && !isNonCompAllowedIoDir;
564
+ // KIT-APP-020:本文件从 soma-kit/data(或 soma-kit)导入/加载的命令式浮层原语的本地名(含 as 改名、解构重命名、require/动态 import)与命名空间名;
565
+ // 调用与属性访问判定只认这些名字,不误伤应用里自己写的同名函数
566
+ const localPortNames = new Set<string>();
567
+ const portNamespaces = new Set<string>();
568
+ const isPortNamespaceExpr = (expr: import('typescript').Expression): boolean => {
569
+ const e = unwrapExpr(ts, expr);
570
+ return isPortModuleLoad(ts, e, true) || (ts.isIdentifier(e) && portNamespaces.has(e.text));
571
+ };
572
+ const isPortMemberAccess = (expr: import('typescript').Expression): boolean => {
573
+ const e = unwrapExpr(ts, expr);
574
+ if (!(ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e))) return false;
575
+ const prop = propertyAccessName(ts, e);
576
+ return prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop) && isPortNamespaceExpr(e.expression);
577
+ };
578
+ const collectBindingPatternPorts = (pattern: import('typescript').ObjectBindingPattern): void => {
579
+ for (const el of pattern.elements) {
580
+ const prop = bindingElementPropName(ts, el);
581
+ if (prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop) && ts.isIdentifier(el.name)) {
582
+ localPortNames.add(el.name.text);
583
+ }
584
+ }
585
+ };
586
+ const collectObjectLiteralAssignPorts = (objLit: import('typescript').ObjectLiteralExpression): void => {
587
+ for (const prop of objLit.properties) {
588
+ if (ts.isShorthandPropertyAssignment(prop)) {
589
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has(prop.name.text)) localPortNames.add(prop.name.text);
590
+ } else if (ts.isPropertyAssignment(prop)) {
591
+ const key = propertyNameText(ts, prop.name);
592
+ if (key !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(key)) {
593
+ const target = unwrapExpr(ts, prop.initializer);
594
+ if (ts.isIdentifier(target)) localPortNames.add(target.text);
595
+ }
596
+ }
597
+ }
598
+ };
599
+ if (!internalLab) {
600
+ const collectPortBindings = (node: import('typescript').Node): void => {
601
+ if (ts.isTypeNode(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return;
602
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && KIT_PORT_MODULES.has(node.moduleSpecifier.text)) {
603
+ const named = node.importClause?.namedBindings;
604
+ if (named !== undefined) {
605
+ if (ts.isNamespaceImport(named)) {
606
+ portNamespaces.add(named.name.text);
607
+ } else {
608
+ for (const el of named.elements) {
609
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has((el.propertyName ?? el.name).text)) localPortNames.add(el.name.text);
610
+ }
611
+ }
612
+ }
613
+ } else if (
614
+ ts.isImportEqualsDeclaration(node)
615
+ && ts.isExternalModuleReference(node.moduleReference)
616
+ && ts.isStringLiteral(node.moduleReference.expression)
617
+ && KIT_PORT_MODULES.has(node.moduleReference.expression.text)
618
+ ) {
619
+ portNamespaces.add(node.name.text);
620
+ } else if (ts.isVariableDeclaration(node) && node.initializer !== undefined) {
621
+ if (isPortNamespaceExpr(node.initializer)) {
622
+ if (ts.isIdentifier(node.name)) portNamespaces.add(node.name.text);
623
+ else if (ts.isObjectBindingPattern(node.name)) collectBindingPatternPorts(node.name);
624
+ } else if (isPortMemberAccess(node.initializer) && ts.isIdentifier(node.name)) {
625
+ localPortNames.add(node.name.text);
626
+ } else if (ts.isIdentifier(node.name)) {
627
+ const init = unwrapExpr(ts, node.initializer);
628
+ if (ts.isIdentifier(init) && localPortNames.has(init.text)) localPortNames.add(node.name.text);
629
+ }
630
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
631
+ const left = unwrapExpr(ts, node.left);
632
+ if (isPortNamespaceExpr(node.right)) {
633
+ if (ts.isIdentifier(left)) portNamespaces.add(left.text);
634
+ else if (ts.isObjectLiteralExpression(left)) collectObjectLiteralAssignPorts(left);
635
+ } else if (isPortMemberAccess(node.right) && ts.isIdentifier(left)) {
636
+ localPortNames.add(left.text);
637
+ }
638
+ } else if (
639
+ ts.isCallExpression(node)
640
+ && (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
641
+ && propertyAccessName(ts, node.expression) === 'then'
642
+ && isPortModuleLoad(ts, node.expression.expression, false)
643
+ && node.arguments.length >= 1
644
+ ) {
645
+ const cb = unwrapExpr(ts, node.arguments[0]!);
646
+ if ((ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) && cb.parameters.length >= 1) {
647
+ const p0 = cb.parameters[0]!.name;
648
+ if (ts.isIdentifier(p0)) portNamespaces.add(p0.text);
649
+ else if (ts.isObjectBindingPattern(p0)) collectBindingPatternPorts(p0);
650
+ }
651
+ }
652
+ ts.forEachChild(node, collectPortBindings);
653
+ };
654
+ for (let pass = 0; pass < 3; pass++) {
655
+ const before = localPortNames.size + portNamespaces.size;
656
+ collectPortBindings(sourceFile);
657
+ if (localPortNames.size + portNamespaces.size === before) break;
658
+ }
659
+ }
660
+ const hits: AstScanHit[] = [];
290
661
  const seen = new Set<string>();
291
662
 
292
- const pushHit = (node: import('typescript').Node, message: string): void => {
663
+ const pushHit = (codeId: string, node: import('typescript').Node, message: string, hint?: string): void => {
293
664
  const line = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
294
- const key = `${line}:${message}`;
665
+ const key = `${codeId}:${line}:${message}`;
295
666
  if (seen.has(key)) return;
296
667
  seen.add(key);
297
- hits.push({ line, message });
668
+ hits.push(hint !== undefined ? { code: codeId, line, message, hint } : { code: codeId, line, message });
298
669
  };
299
670
 
300
- const checkHtmlString = (node: import('typescript').Node, html: string, includeInlineAttrs: boolean): void => {
671
+ const checkHtmlString = (
672
+ node: import('typescript').Node,
673
+ html: string,
674
+ includeInlineAttrs: boolean,
675
+ checkStructuredTags: boolean,
676
+ ): void => {
301
677
  if (!html) return;
302
678
  if (includeInlineAttrs) {
303
679
  for (const rule of HTML_INLINE_ATTR_RULES) {
304
- if (rule.pattern.test(html)) pushHit(node, rule.message);
680
+ if (rule.pattern.test(html)) pushHit('KIT-APP-005', node, rule.message);
305
681
  }
306
682
  }
307
683
  for (const rule of HTML_TAG_FORBIDDEN_RULES) {
308
- if (rule.pattern.test(html)) pushHit(node, rule.message);
684
+ if (rule.pattern.test(html)) pushHit('KIT-APP-005', node, rule.message);
685
+ }
686
+ if (checkStructuredTags) {
687
+ for (const rule of HTML_STRUCTURE_FORBIDDEN_RULES) {
688
+ if (rule.pattern.test(html)) {
689
+ pushHit(
690
+ 'KIT-APP-019',
691
+ node,
692
+ rule.message,
693
+ '规整表格/表单/浮层须由页面声明(view.list / view.form / overlays)与标准业务组件渲染',
694
+ );
695
+ }
696
+ }
697
+ }
698
+ };
699
+
700
+ const checkCssSpecifier = (node: import('typescript').Node, spec: string): void => {
701
+ if (CSS_IMPORT_SPEC_RE.test(spec)) {
702
+ if (internalLab && isInternalTsModuleSpecifier?.(spec) === true) return;
703
+ pushHit(
704
+ 'KIT-APP-017',
705
+ node,
706
+ `禁止在源码中导入野生样式表 "${spec}";样式必须由框架主题求解引擎与 Tailwind 刻度类统一生成`,
707
+ '删除样式表导入,改用 kit.app.yaml#theme 14 维 DSL 与组件候选类',
708
+ );
309
709
  }
310
710
  };
311
711
 
312
- const visit = (node: import('typescript').Node, insideFunction: boolean): void => {
712
+ const visit = (node: import('typescript').Node, insideFunction: boolean, insideActionOrHook: boolean): void => {
313
713
  if (ts.isTypeNode(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) {
314
714
  return;
315
715
  }
316
716
 
317
- // 1. AST .style / ['style'] 访问(全应用禁止)
717
+ // 0. KIT-APP-017:静态 import / export / import = require 野生 CSS 文件
718
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
719
+ checkCssSpecifier(node.moduleSpecifier, node.moduleSpecifier.text);
720
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined && ts.isStringLiteral(node.moduleSpecifier)) {
721
+ checkCssSpecifier(node.moduleSpecifier, node.moduleSpecifier.text);
722
+ } else if (
723
+ ts.isImportEqualsDeclaration(node)
724
+ && ts.isExternalModuleReference(node.moduleReference)
725
+ && ts.isStringLiteral(node.moduleReference.expression)
726
+ ) {
727
+ checkCssSpecifier(node.moduleReference.expression, node.moduleReference.expression.text);
728
+ }
729
+
730
+ // 0b. KIT-APP-020(非 internalLab,过渡期告警):从 soma-kit/data 或 soma-kit 导入/再导出/解构/访问命令式浮层原语
731
+ if (!internalLab) {
732
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && KIT_PORT_MODULES.has(node.moduleSpecifier.text)) {
733
+ const named = node.importClause?.namedBindings;
734
+ if (named !== undefined && ts.isNamedImports(named)) {
735
+ for (const el of named.elements) {
736
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has((el.propertyName ?? el.name).text)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
737
+ }
738
+ }
739
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined && ts.isStringLiteral(node.moduleSpecifier) && KIT_PORT_MODULES.has(node.moduleSpecifier.text)) {
740
+ const clause = node.exportClause;
741
+ if (clause !== undefined && ts.isNamedExports(clause)) {
742
+ for (const el of clause.elements) {
743
+ if (KIT_IMPERATIVE_OVERLAY_PORTS.has((el.propertyName ?? el.name).text)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
744
+ }
745
+ }
746
+ } else if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer !== undefined && isPortNamespaceExpr(node.initializer)) {
747
+ for (const el of node.name.elements) {
748
+ const prop = bindingElementPropName(ts, el);
749
+ if (prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
750
+ }
751
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken && isPortNamespaceExpr(node.right)) {
752
+ const left = unwrapExpr(ts, node.left);
753
+ if (ts.isObjectLiteralExpression(left)) {
754
+ for (const prop of left.properties) {
755
+ const key = ts.isShorthandPropertyAssignment(prop)
756
+ ? prop.name.text
757
+ : (ts.isPropertyAssignment(prop) ? propertyNameText(ts, prop.name) : undefined);
758
+ if (key !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(key)) pushHit('KIT-APP-020', prop, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
759
+ }
760
+ }
761
+ } else if (
762
+ (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
763
+ && isPortMemberAccess(node)
764
+ ) {
765
+ pushHit('KIT-APP-020', node, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
766
+ }
767
+ }
768
+
769
+ // 1. AST .style / ['style'] 访问(全应用禁止,KIT-APP-005)
318
770
  if (
319
771
  (ts.isPropertyAccessExpression(node) && node.name.text === 'style')
320
772
  || (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) && node.argumentExpression.text === 'style')
321
773
  ) {
322
- pushHit(node, MSG_STYLE_PROP);
774
+ pushHit('KIT-APP-005', node, MSG_STYLE_PROP);
323
775
  }
324
776
 
325
- // 2. AST 非组件目录禁止操作 .className / .classList
777
+ // 2. AST 非组件目录禁止操作 .className / .classList(KIT-APP-005)
326
778
  if (!inComponentsDir) {
327
779
  const propName = ts.isPropertyAccessExpression(node)
328
780
  ? node.name.text
329
781
  : (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text : undefined);
330
782
  if (propName === 'className' || propName === 'classList') {
331
- pushHit(node, MSG_NON_COMP_CLASS);
783
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
332
784
  }
333
785
  }
334
786
 
335
787
  // 3. AST 函数调用检查
336
788
  if (ts.isCallExpression(node)) {
789
+ // 3a. KIT-APP-017:动态 import('...css') / require('...css')
790
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
791
+ checkCssSpecifier(node.arguments[0], node.arguments[0].text);
792
+ } else if (ts.isIdentifier(node.expression) && node.expression.text === 'require' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
793
+ checkCssSpecifier(node.arguments[0], node.arguments[0].text);
794
+ }
795
+
337
796
  const calleeName = ts.isIdentifier(node.expression)
338
797
  ? node.expression.text
339
- : (ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : undefined);
798
+ : propertyAccessName(ts, node.expression);
340
799
 
800
+ // 3b. KIT-APP-018(非 internalLab):全应用禁命令式浮层、document.body 挂载与伪造 Symbol.for('soma-kit.*')
801
+ if (!internalLab) {
802
+ if (calleeName === 'showModal') {
803
+ pushHit('KIT-APP-018', node, '禁止调用 showModal() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开', '移除命令式 showModal,改用页面 overlays 声明');
804
+ } else if (calleeName === 'showPopover') {
805
+ pushHit('KIT-APP-018', node, '禁止调用 showPopover() 打开命令式原生浮层;请改用页面声明 overlays(dialog / drawer),由 ctx.openOverlay / builtin: openOverlay 打开', '移除命令式 showPopover,改用页面 overlays 声明');
806
+ }
807
+ // KIT-APP-020(过渡期告警):调用本文件从 soma-kit/data(或 soma-kit)导入/加载的 mountKitModal / mountKitDrawer(含改名、解构、命名空间点访问与计算属性访问、.then 回调解构)
808
+ const callExpr = unwrapExpr(ts, node.expression);
809
+ const portCall = (ts.isIdentifier(callExpr) && localPortNames.has(callExpr.text)) || isPortMemberAccess(callExpr);
810
+ if (portCall) pushHit('KIT-APP-020', node, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
811
+ if (
812
+ (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
813
+ && propertyAccessName(ts, node.expression) === 'then'
814
+ && isPortModuleLoad(ts, node.expression.expression, false)
815
+ && node.arguments.length >= 1
816
+ ) {
817
+ const cb = unwrapExpr(ts, node.arguments[0]!);
818
+ if ((ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) && cb.parameters.length >= 1) {
819
+ const p0 = cb.parameters[0]!.name;
820
+ if (ts.isObjectBindingPattern(p0)) {
821
+ for (const el of p0.elements) {
822
+ const prop = bindingElementPropName(ts, el);
823
+ if (prop !== undefined && KIT_IMPERATIVE_OVERLAY_PORTS.has(prop)) pushHit('KIT-APP-020', el, MSG_IMPERATIVE_PORT, HINT_IMPERATIVE_PORT);
824
+ }
825
+ }
826
+ }
827
+ }
828
+ if (
829
+ (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression))
830
+ && calleeName !== undefined
831
+ && BODY_MUTATION_METHODS.has(calleeName)
832
+ && isDocumentBodyExpr(ts, node.expression.expression)
833
+ ) {
834
+ pushHit('KIT-APP-018', node, `禁止调用 document.body.${calleeName}() 命令式挂载浮层或野生 DOM 节点`, '浮层必须通过页面 overlays 声明托管');
835
+ }
836
+ if (isSymbolForCall(ts, node) && node.arguments.length >= 1) {
837
+ const symKey = extractStaticHtmlText(ts, node.arguments[0]!);
838
+ if (symKey.startsWith('soma-kit.')) {
839
+ pushHit('KIT-APP-018', node, `禁止在应用源码中引用或伪造 soma-kit 内部符号 Symbol.for("${symKey}")`, '移除内部符号调用,业务定制一律通过 defineKitBizComponent 登记至 bizComponents');
840
+ }
841
+ }
842
+ }
843
+
844
+ // 3c. KIT-APP-019(非 internalLab):非 IO 目录禁直接调用 fetch();展示对象目录(views/)改报 KIT-APP-021(过渡期告警)
845
+ if (!insideActionOrHook && isGlobalFetchCall(ts, node)) {
846
+ if (isViewDir) pushHit('KIT-APP-021', node, MSG_VIEW_FETCH, HINT_VIEW_FETCH);
847
+ else if (checkComponentPurity) pushHit('KIT-APP-019', node, MSG_NON_IO_FETCH, HINT_NON_IO_NET);
848
+ }
849
+
850
+ // 3d. KIT-APP-005 + KIT-APP-018(DOM 构造与属性操作)
341
851
  if (calleeName === 'setAttribute' && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
342
852
  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);
853
+ if (attr === 'style') pushHit('KIT-APP-005', node, MSG_SET_ATTR_STYLE);
854
+ if (!inComponentsDir && attr === 'class') pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
345
855
  } else if (calleeName === 'setAttributeNS' && node.arguments.length >= 2 && ts.isStringLiteralLike(node.arguments[1])) {
346
856
  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();
857
+ if (attr === 'style') pushHit('KIT-APP-005', node, MSG_SET_ATTR_STYLE);
858
+ if (!inComponentsDir && attr === 'class') pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
859
+ } else if (calleeName === 'createElement') {
860
+ const tag = node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0]) ? node.arguments[0].text.toLowerCase() : undefined;
351
861
  if (tag === 'style') {
352
- pushHit(node, '禁止调用 createElement("style") 动态注入样式表;请统一使用 Tailwind 候选类与 --soma-* 设计令牌');
862
+ pushHit('KIT-APP-005', node, '禁止调用 createElement("style") 动态注入样式表;请统一使用 Tailwind 候选类与 --soma-* 设计令牌');
353
863
  } else if (tag === 'select') {
354
- pushHit(node, '禁止调用 createElement("select") 创建原生下拉框;请改用 mountKitSelectField 或 Select 组件');
864
+ pushHit('KIT-APP-005', node, '禁止调用 createElement("select") 创建原生下拉框;请改用 mountKitSelectField 或 Select 组件');
865
+ } else if (!internalLab && tag === 'dialog') {
866
+ pushHit('KIT-APP-018', node, '禁止调用 createElement("dialog") 创建命令式浮层;请改用页面声明 overlays(dialog / drawer)', '使用页面 *.kit.yaml 的 overlays 声明浮层');
867
+ } else if (!internalLab && !inComponentsDir) {
868
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 createElement() 命令式构造 DOM;界面必须封装为业务组件及其私有协作组件', '将视图交互内核移入 components/ 下并作为业务组件的 dataComponents 注册');
355
869
  }
870
+ } else if (!internalLab && !inComponentsDir && calleeName === 'createElementNS') {
871
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 createElementNS() 命令式构造 DOM;界面必须封装为业务组件及其私有协作组件', '将 SVG/画布交互内核移入 components/ 下并作为业务组件的 dataComponents 注册');
356
872
  } else if (calleeName === 'insertAdjacentHTML' && node.arguments.length >= 2) {
357
- checkHtmlString(node.arguments[1]!, extractStaticHtmlText(ts, node.arguments[1]!), true);
873
+ checkHtmlString(node.arguments[1]!, extractStaticHtmlText(ts, node.arguments[1]!), true, checkComponentPurity && !insideActionOrHook);
874
+ if (!internalLab && !inComponentsDir) {
875
+ pushHit('KIT-APP-018', node, '非组件源码(components/ 之外)禁止调用 insertAdjacentHTML() 写入野生 DOM;界面必须封装为业务组件', '移除非组件目录中的 DOM 写入逻辑');
876
+ }
358
877
  } else if (!inComponentsDir && (calleeName === 'addEventListener' || calleeName === 'removeEventListener' || calleeName === 'dispatchEvent')) {
359
- pushHit(node, MSG_NON_COMP_EVENT);
878
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_EVENT);
360
879
  } else if (!inComponentsDir && calleeName === 'insertRule') {
361
- pushHit(node, MSG_NON_COMP_CLASS);
880
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
362
881
  }
363
882
  }
364
883
 
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);
884
+ // 4. AST new CSSStyleSheet() / new XMLHttpRequest()
885
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
886
+ if (!inComponentsDir && node.expression.text === 'CSSStyleSheet') {
887
+ pushHit('KIT-APP-005', node, MSG_NON_COMP_CLASS);
888
+ }
889
+ if (!insideActionOrHook && node.expression.text === 'XMLHttpRequest') {
890
+ if (isViewDir) pushHit('KIT-APP-021', node, MSG_VIEW_FETCH, HINT_VIEW_FETCH);
891
+ else if (checkComponentPurity) pushHit('KIT-APP-019', node, MSG_NON_IO_XHR, HINT_NON_IO_NET);
892
+ }
368
893
  }
369
894
 
370
895
  // 5. AST 赋值表达式检查(innerHTML / outerHTML / .on* = / .type = 'range'|'date')
371
896
  if (ts.isBinaryExpression(node) && (node.operatorToken.kind === ts.SyntaxKind.EqualsToken || node.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken)) {
372
897
  const leftName = propertyAccessName(ts, node.left);
373
898
  if (leftName === 'innerHTML' || leftName === 'outerHTML') {
374
- checkHtmlString(node.right, extractStaticHtmlText(ts, node.right), true);
899
+ checkHtmlString(node.right, extractStaticHtmlText(ts, node.right), true, checkComponentPurity && !insideActionOrHook);
900
+ if (!internalLab && !inComponentsDir) {
901
+ pushHit('KIT-APP-018', node, `非组件源码(components/ 之外)禁止写入 .${leftName} 构造野生 DOM;界面必须封装为业务组件`, '将交互视图封装为业务组件及其私有协作组件');
902
+ }
375
903
  } else if (node.operatorToken.kind === ts.SyntaxKind.EqualsToken && leftName !== undefined) {
376
904
  if (DOM_INLINE_ON_EVENTS.has(leftName)) {
377
- pushHit(node, MSG_INLINE_ON_EVENT);
905
+ pushHit('KIT-APP-005', node, MSG_INLINE_ON_EVENT);
378
906
  } else if (leftName === 'type' && ts.isStringLiteralLike(node.right)) {
379
907
  const val = node.right.text.toLowerCase();
380
908
  if (val === 'range') {
381
- pushHit(node, '禁止设置 input.type = "range" 创建原生滑块;请改用 soma-kit 标准组件 Range');
909
+ pushHit('KIT-APP-005', node, '禁止设置 input.type = "range" 创建原生滑块;请改用 soma-kit 标准组件 Range');
382
910
  } else if (/^(?:date|datetime-local|time|month|week)$/.test(val)) {
383
- pushHit(node, '禁止设置原生日期/时间 input.type;请改用 soma-kit 标准组件 Date / DateRange / TimePicker');
911
+ pushHit('KIT-APP-005', node, '禁止设置原生日期/时间 input.type;请改用 soma-kit 标准组件 Date / DateRange / TimePicker');
384
912
  }
385
913
  }
386
914
  }
@@ -390,30 +918,59 @@ function scanSourceWithAst(
390
918
  if (ts.isPropertyAssignment(node)) {
391
919
  const propName = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
392
920
  if (propName === 'templateHtml') {
393
- checkHtmlString(node.initializer, extractStaticHtmlText(ts, node.initializer), true);
921
+ checkHtmlString(node.initializer, extractStaticHtmlText(ts, node.initializer), true, checkComponentPurity && !insideActionOrHook);
394
922
  }
395
923
  }
396
924
 
397
- // 7. 函数体内的字符串/模板字面量中的原生控件标签(如 renderSneaky 返回 `<select>...`),不误伤顶层纯数据字典
925
+ // 7. 函数体内的字符串/模板字面量检查(不误伤顶层纯数据字典)
398
926
  if (insideFunction && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node))) {
399
- checkHtmlString(node, extractStaticHtmlText(ts, node), false);
927
+ const text = extractStaticHtmlText(ts, node);
928
+ checkHtmlString(node, text, false, checkComponentPurity && !insideActionOrHook);
929
+ if (hasBizComponentDef && !insideActionOrHook && HARDCODED_API_PATH_RE.test(text)) {
930
+ pushHit(
931
+ 'KIT-APP-019',
932
+ node,
933
+ '禁止在业务组件源码中硬编码 "/api/..." 接口路径;业务组件必须纯声明式装数据,接口地址须从页面传入的 input.objects(behavior.from / actions)读取',
934
+ '移除硬编码接口路径,改为从 input.objects 读取页面声明的 behavior.from 或具名动作',
935
+ );
936
+ }
937
+ }
938
+
939
+ let nextInsideActionOrHook = insideActionOrHook;
940
+ if (!nextInsideActionOrHook) {
941
+ if (ts.isCallExpression(node)) {
942
+ const callName = ts.isIdentifier(node.expression) ? node.expression.text : propertyAccessName(ts, node.expression);
943
+ if (callName === 'defineKitActions') nextInsideActionOrHook = true;
944
+ } else if (ts.isPropertyAssignment(node)) {
945
+ const propName = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
946
+ if (propName !== undefined && APP_HOOK_PROP_NAMES.has(propName)) nextInsideActionOrHook = true;
947
+ }
400
948
  }
401
949
 
402
950
  const nextInsideFunction = insideFunction || ts.isFunctionLike(node);
403
- ts.forEachChild(node, (child) => visit(child, nextInsideFunction));
951
+ ts.forEachChild(node, (child) => visit(child, nextInsideFunction, nextInsideActionOrHook));
404
952
  };
405
953
 
406
- visit(sourceFile, false);
954
+ visit(sourceFile, false, false);
407
955
  return hits;
408
956
  }
409
957
 
410
958
  /**
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`。
959
+ * 服务端编译与 `soma kit check` 全量源码文件与 AST 门禁:
960
+ * 递归扫描应用根目录 `<root>`(跳过 `node_modules` / `dist` / `tests` / `.soma` 等):
961
+ * 1) KIT-APP-005(全应用始终生效):非标原生控件、<style>、AST `.style` 访问、`setAttribute('style', ...)`、`innerHTML`/`outerHTML`/`templateHtml` 内联 `style="..."` 或 `on*`、`.onclick =`;非 `components/` 禁 `.className`/`.classList`/`setAttribute('class', ...)`/`CSSStyleSheet`/`addEventListener`;
962
+ * 2) KIT-APP-017(全应用始终生效):禁野生 CSS(.css/.scss/.less/.sass/.styl 文件与 import/require)及 `pages/`、`src/web/`、`views/`、`components/` 下手写 `.html`/`.htm`;
963
+ * 3) KIT-APP-018(非 `internalLab` 生效):全应用禁命令式浮层(showModal/showPopover/createElement('dialog')/document.body.append*)与伪造 `Symbol.for('soma-kit.*')`;非 `components/` 禁 `createElement`/`createElementNS`/`innerHTML`/`outerHTML`/`insertAdjacentHTML`;
964
+ * 3b) KIT-APP-020(非 `internalLab`,过渡期告警,装配时进 deprecations):应用源码从 `soma-kit/data` / `soma-kit` 导入或调用 `mountKitModal` / `mountKitDrawer`;
965
+ * 4) KIT-APP-019(非 `internalLab` 生效):非 IO 目录禁手写 `<table>`/`<thead>`/`<form>`/`<dialog>` 与直接 `fetch()`/`new XMLHttpRequest`
966
+ * (IO 目录:`api/` `bff/` `actions/` `server/` `src/bff/` `src/web/actions/` `soma.server.*`,及 defineKitActions / requestHook / startup / services 内;`views/` 与 `src/web/views/` 仅对 `KIT-APP-019` 豁免结构标签,其直接网络请求交由下述 `KIT-APP-021` 告警处理);`defineKitBizComponent` 文件禁硬编码 `'/api/...'`;
967
+ * 4b) KIT-APP-021(非 `internalLab`,过渡期告警,装配时进 deprecations):展示对象目录(`views/`、`src/web/views/`)直接 `fetch()`/`new XMLHttpRequest`。
415
968
  */
416
- export async function scanAppComponentSources(root: string): Promise<KitDiagnostic[]> {
969
+ export async function scanAppComponentSources(
970
+ root: string,
971
+ opts?: { readonly internalLab?: boolean },
972
+ ): Promise<KitDiagnostic[]> {
973
+ const internalLab = opts?.internalLab === true;
417
974
  const fsSpec = 'node:fs/promises';
418
975
  const pathSpec = 'node:path';
419
976
  const tsSpec = 'typescript';
@@ -439,15 +996,71 @@ export async function scanAppComponentSources(root: string): Promise<KitDiagnost
439
996
  await walk(full);
440
997
  continue;
441
998
  }
999
+ const rel = path.relative(root, full).split(path.sep).join('/');
1000
+
1001
+ // KIT-APP-017:应用目录内零野生 CSS 文件
1002
+ if (CSS_FILE_EXT_RE.test(entry.name)) {
1003
+ diagnostics.push({
1004
+ code: 'KIT-APP-017',
1005
+ path: rel,
1006
+ message: `禁止在应用目录放置野生样式表文件 "${rel}";样式必须由框架主题引擎与 Tailwind 刻度类统一生成`,
1007
+ hint: '删除自定义 CSS/SCSS/LESS 文件,改用 kit.app.yaml#theme 14 维主题 DSL 声明外观',
1008
+ });
1009
+ continue;
1010
+ }
1011
+
1012
+ // KIT-APP-017:pages/、src/web/、views/、components/ 禁止手写野生 .html/.htm(跳过 public/)
1013
+ if (HTML_FILE_EXT_RE.test(entry.name) && WILD_HTML_DIR_RE.test(rel) && !rel.startsWith('public/') && !rel.includes('/public/')) {
1014
+ diagnostics.push({
1015
+ code: 'KIT-APP-017',
1016
+ path: rel,
1017
+ message: `禁止在源码目录手写野生 HTML 文件 "${rel}";页面必须通过 pages/*.kit.yaml 声明式编译生成`,
1018
+ hint: '删除手写 HTML 文件,改用 pages/*.kit.yaml + 业务组件声明页面',
1019
+ });
1020
+ continue;
1021
+ }
1022
+
442
1023
  if (!/\.(?:ts|tsx|js|mjs)$/.test(entry.name) || entry.name.endsWith('.d.ts')) continue;
443
1024
  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)) {
1025
+ const siblingNames = internalLab ? new Set(entries.filter((e) => !e.isDirectory()).map((e) => e.name)) : undefined;
1026
+ const isInternalTsModuleSpecifier = internalLab
1027
+ ? (spec: string): boolean => {
1028
+ if (!spec.startsWith('./')) return false;
1029
+ const base = spec.slice(2);
1030
+ if (base.includes('/')) return false;
1031
+ return siblingNames!.has(`${base}.ts`) || siblingNames!.has(`${base}.tsx`) || siblingNames!.has(`${base}.mts`);
1032
+ }
1033
+ : undefined;
1034
+ const inComponentsDir =
1035
+ rel === 'components'
1036
+ || rel.startsWith('components/')
1037
+ || rel === 'src/web/components'
1038
+ || rel.startsWith('src/web/components/');
1039
+ const isNonCompAllowedIoDir =
1040
+ rel.startsWith('api/')
1041
+ || rel.startsWith('bff/')
1042
+ || rel.startsWith('actions/')
1043
+ || rel.startsWith('views/')
1044
+ || rel.startsWith('src/bff/')
1045
+ || rel.startsWith('src/web/actions/')
1046
+ || rel.startsWith('src/web/views/')
1047
+ || rel.startsWith('server/')
1048
+ || /^soma\.server\./.test(rel)
1049
+ || /\/soma\.server\./.test(rel);
1050
+ // 展示对象目录:仍算 IO 目录(结构标签等检查口径不变),但其中直接 fetch / XMLHttpRequest 报 KIT-APP-021(过渡期告警,0.2.0 并入 019)
1051
+ const isViewDir = rel.startsWith('views/') || rel.startsWith('src/web/views/');
1052
+ for (const hit of scanSourceWithAst(ts, full, code, {
1053
+ inComponentsDir,
1054
+ isNonCompAllowedIoDir,
1055
+ internalLab,
1056
+ isViewDir,
1057
+ ...(isInternalTsModuleSpecifier !== undefined ? { isInternalTsModuleSpecifier } : {}),
1058
+ })) {
447
1059
  diagnostics.push({
448
- code: 'KIT-APP-005',
1060
+ code: hit.code,
449
1061
  path: `${rel}:${hit.line}`,
450
1062
  message: hit.message,
1063
+ ...(hit.hint !== undefined ? { hint: hit.hint } : {}),
451
1064
  });
452
1065
  }
453
1066
  }