soma-core 2.2.9 → 2.2.11

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 (51) hide show
  1. package/README.md +8 -19
  2. package/bin/service-codegen.cjs +2 -3
  3. package/bin/soma.cjs +2 -2
  4. package/core/build/compiler/soma-precompile.js +19 -6
  5. package/core/client/data/region-scope-port.ts +8 -3
  6. package/core/client/engine/event-engine.ts +1 -1
  7. package/core/client/engine/soma-bootstrap.ts +9 -0
  8. package/core/client/engines/diff/code.ts +205 -0
  9. package/core/client/engines/diff/index.ts +27 -1
  10. package/core/client/engines/diff/port.ts +75 -0
  11. package/core/client/parser/confirm-spec.ts +10 -4
  12. package/core/client/parser/ui-config-parser.ts +14 -2
  13. package/core/index.ts +1 -1
  14. package/core/server/api/load-host-service.ts +0 -1
  15. package/core/server/host/source-packages.cjs +3 -0
  16. package/core/shared/registry-generated/diagnostic-registry-index.ts +16 -0
  17. package/core/shared/registry-generated/diagnostic-registry.ts +130 -0
  18. package/core/shared/registry-generated/limits.ts +6 -2
  19. package/core/shared/registry-generated/std-grammar-views.ts +1 -1
  20. package/core/shared/registry-generated/std-grammar.ts +1 -1
  21. package/core/shared/types/region-scope.types.ts +6 -0
  22. package/dist/browser/runtime-bundle.manifest.json +12 -12
  23. package/dist/browser/soma-runtime.js +752 -489
  24. package/dist/core/index.cjs +752 -489
  25. package/dist/host-native/aot-builder.cjs +366 -226
  26. package/dist/host-native/native-server.cjs +131 -56
  27. package/dist/lsp/component-tree.cjs +23 -10
  28. package/dist/types/client/data/region-scope-port.d.ts +1 -1
  29. package/dist/types/client/engine/soma-bootstrap.d.ts +5 -0
  30. package/dist/types/client/engines/diff/code.d.ts +27 -0
  31. package/dist/types/client/engines/diff/index.d.ts +2 -1
  32. package/dist/types/client/engines/diff/port.d.ts +77 -0
  33. package/dist/types/client/parser/confirm-spec.d.ts +1 -1
  34. package/dist/types/server/host/source-packages.d.cts +5 -0
  35. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +113 -1
  36. package/dist/types/shared/registry-generated/limits.d.ts +4 -0
  37. package/dist/types/shared/registry-generated/std-grammar-views.d.ts +1 -1
  38. package/dist/types/shared/registry-generated/std-grammar.d.ts +1 -1
  39. package/dist/types/shared/types/region-scope.types.d.ts +6 -0
  40. package/host-native/bin/host-native.cjs +1 -1
  41. package/host-native/client/browser-entry.ts +12 -1
  42. package/host-native/client/first-frame.ts +8 -0
  43. package/host-native/client/router-bridge.ts +8 -2
  44. package/host-native/src/aot-builder.ts +173 -93
  45. package/host-native/src/native-server.ts +131 -25
  46. package/host-native/src/public-packages.cjs +156 -50
  47. package/host-native/styles/globals.css +28 -2
  48. package/package.json +2 -2
  49. package/dist/core/adaptive-pure.cjs +0 -41
  50. package/dist/core/theme-pure.cjs +0 -38
  51. package/dist/preview-export.cjs +0 -3401
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
1
  # soma-core
2
2
 
3
3
  SOMA 通用运行时:core 的标准体系 = HTML + 一份 `_ui.yaml` + 组件。页面 = HTML 锚点(Soma Mark)
4
- + 一份 core 标准格式页面声明(四件套:`html/<page>.html` + 平铺 `ui/<page>_ui.yaml`(`soma: 1`)+ `event/<page>_event.yaml` + `style/<page>_style.yaml`;含 Soma Show / Flow / Timer / Data / Scope / State / Envelope / Fragment 等各子 DSL,语法见《soma DSL 语法全书》第一章总表;BDL / kit 页面源是方言源文件,编译成四件套后交给 core)
5
- + 组件 + 可选 Domain TS —— 声明即数据,落盘即渲染,零构建。core 不认识 BDL / kit 页面源:方言由 soma-ui / soma-kit 在运行期
4
+ + 一份 core 标准格式页面声明(四件套:`html/<page>.html` + 平铺 `ui/<page>_ui.yaml`(`soma: 1`)+ `event/<page>_event.yaml` + `style/<page>_style.yaml`;含 Soma Show / Flow / Timer / Data / Scope / State / Envelope / Fragment 等各子 DSL;上层方言源文件编译成四件套后交给 core)
5
+ + 组件 + 可选 Domain TS —— 声明即数据,落盘即渲染,零构建。core 不认识上层方言页面源:方言由上层扩展包在编译/运行期
6
6
  编译成标准格式后经 `registerSomaPage(s)` 按 URL 注入。
7
7
 
8
8
  Registry 页面以页面名作为公开根路径:注册 `myworkspace` 后直接访问 `/myworkspace`。
9
9
  Host 文件页优先,Registry 页面在 Host 404 时兜底;存量 `/pages/<name>` 链接仅保留兼容读取。
10
10
 
11
- 当前版本为 `soma-core@2.2.4`(唯一版本)。core 不含纯计算出口(纯计算由 `soma-foundation` 与 `soma-ui/{theme-pure,space-pure}` 提供,边界由根 `scripts/verify-foundation.mjs` 检查)。
11
+ 当前版本为 `soma-core@2.2.10`(唯一版本)。core 不含纯计算出口(纯计算由 `soma-foundation` 提供,边界由根 `scripts/verify-foundation.mjs` 检查)。
12
12
 
13
13
  ## 当前能力(以代码为准)
14
14
 
@@ -22,35 +22,24 @@ Host 文件页优先,Registry 页面在 Host 404 时兜底;存量 `/pages/<n
22
22
  - **数据对象层**:数据对象解析器(输入是标准格式的数据对象声明、`_ui.yaml` 顶层 `data:`;
23
23
  多接口 DAG 依赖编排/字段字典/类型双态映射/速记列/mock 样本兜底),解析结果注入 `page.data`,支持 `reloadData`(`core/client/data`)。
24
24
  窗口 `block` 缺省不写在 core:Host 装配调 `configureWindowBlockDefaults` 注入(值取 soma-design 限值表 `hostDefaults.windowBlock`),未注入即抛错。
25
- - **主题**:core 不认识主题。派生在 soma-foundation,编译在 soma-ui;core 只装载编译产出的普通样式(见《soma 引擎端口》§2)。
25
+ - **主题**:core 不认识主题。派生在 `soma-foundation`,编译在上层扩展包;core 只装载编译产出的普通样式。
26
26
  - **引擎端口**:样式(`style-engine`)、行为(`behavior`)、会话焦点(`session-focus`)、表格(`table`)、虚拟滚动(`virtual`)、
27
27
  Temporal 值语义(`temporal`)、图表(`chart`)、拖放(`dnd`)、文本差异(`diff`)、二维码(`qrcode`)各一个子路径;
28
28
  引擎库只在 `adapter-*.ts` 里动态 import,可经 `SomaBootstrapOptions.engines` 逐槽替换。
29
- - **渲染端口**:`render-ports` 的 notify / regionFallback 由 UI 体系注入,缺省无头(只记录 / 只打标记)。
29
+ - **渲染端口**:`render-ports` 的 notify / regionFallback 由上层体系注入,缺省无头(只记录 / 只打标记)。
30
30
  - **宿主与 CLI**:core 运行时与宿主壳均零 Next / React 依赖;原生极速单进程宿主壳在包内 `host-native/`(含客户端分片与后端服务预先静态编译,支持 `--web-dir` / `--api-dir` 前后端分目录同进程运行),`soma dev/build/start` 以子进程转调它;`soma` CLI
31
- (`dev/build/start` 转调包内 host-native、`codegen`、`sync`、`lsp`、`component eject|diff|upgrade` 与 `pack init` 转调 soma-ui,见 `bin/` 与 `soma help`)。
31
+ (`dev/build/start` 转调包内 host-native、`codegen`、`sync`、`lsp`、以及通过 `soma.commands` 注册转调的扩展子命令,见 `bin/` 与 `soma help`)。
32
32
  mock 服务器与 `soma-mock` 已迁 soma-testkit;`verify` 在 soma-testkit。
33
33
 
34
34
  ## 文档索引
35
35
 
36
- 对外接入文档在仓库 `external-docs/`,本目录是 soma-core 的**模块详设**,面向模块维护者。
36
+ 对外接入文档见仓库 `external-docs/soma-core接入指南.md`,内部工程文档统一归口于仓库 `docs/`。
37
37
 
38
38
  子路径与依赖:`package.json` `exports` 是唯一清单。`soma-core/scheduling`(`createObserverPool` / `scheduleFlush`,原 adaptive 目录改名)
39
39
  与各引擎端口子路径见上;命名判据 `COMPONENT_NAME_PATTERN` / `isComponentName` 引自 `soma-foundation/design/naming`,core 不自带。
40
40
  引擎库(`@tanstack/*`、`@zag-js/*`、`diff`、`qrcode-generator`、`temporal-polyfill`)是 dependencies;`echarts`、`tailwindcss` 为可选 peer。
41
41
 
42
- 主要篇目(`doc/`):
43
-
44
- - `soma 运行时引擎详设.md` — 引擎架构拓扑、编译管线、组件运行时、作用域、emit 路由、services 白名单。模块详设旗舰篇
45
- - `soma 业务领域详设.md` — 业务领域模块:三类领域对象、服务层分层、生命周期、基类与注解驱动
46
- - `soma 数据对象层.md` — 数据对象语法与解析器
47
- - `soma 引擎端口.md` — 引擎端口、样式引擎与渲染端口
48
- - `soma 页面 Registry 详设.md` — 页面 / API 注册中心、发布与回滚
49
- - `soma Runtime 扩展内部设计.md` — Runtime 扩展与跨端接入
50
- - `soma CLI 与 Host 工作区.md` — CLI 与 Next Host 实施方案
51
- - `soma DSL 语法全书.md` — core 标准格式与 `std-grammar` 的实现级语法参考,自成一册(对外入口是 `external-docs/soma-core原生手册.md`;BDL 归 soma-ui、kit 页面源归 soma-kit)
52
-
53
- 全局架构见仓库 `docs/02-系统架构/SOMA全局系统架构.md`,模块类设计见 `docs/03-类与模块/soma-core类与模块设计.md`。
42
+ 全局架构见仓库 `docs/02-系统架构/SOMA全局系统架构.md`,模块类设计见 `docs/03-类与模块/soma-core类与模块设计.md`,语法规范见 `docs/04-语法与规范/`。
54
43
 
55
44
  ## 测试
56
45
 
@@ -33,14 +33,13 @@ function generateServiceSource({ name, methods, route }) {
33
33
  const methodBlocks = methods.map((m) => {
34
34
  const upper = m.toUpperCase();
35
35
  return `
36
- async ${m}(req: NextRequest): Promise<Response> {
36
+ async ${m}(req: Request): Promise<Response> {
37
37
  // TODO: 实现 ${upper} /api/service/${routeHint}
38
38
  return Response.json({ code: 0, message: '${upper} ${className} stub' });
39
39
  }`;
40
40
  }).join('\n');
41
41
 
42
- return `import type { NextRequest } from 'next/server';
43
- import type { IService } from '@core/server/api/IService';
42
+ return `import type { IService } from '@core/server/api/IService';
44
43
 
45
44
  /** Generated by soma codegen service — ${new Date().toISOString()} */
46
45
  export default class ${className} implements IService {
package/bin/soma.cjs CHANGED
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * 扩展命令表(Host 工程里的 `package.json` 或已装的 `soma-*` 包的 `package.json`):
13
13
  * { "soma": { "commands": { "<命令名>": "<相对该 package.json 所在目录的入口文件>" } } }
14
- * · 表由方言包(soma-ui / soma-kit 等)安装时带上,core 不在代码里点名任何方言命令;
14
+ * · 表由上层方言扩展包安装时带上,core 不在代码里点名任何方言命令;
15
15
  * · 这里从 Host 工程(`SOMA_HOST_DIR`,其次当前目录及其各级父目录)按命令名查表,
16
16
  * 以**子进程**执行入口文件并透传退出码——不经任何 import / require 说明符,所以 core 对方言包零依赖;
17
17
  * · 环境变量 `SOMA_EXTENSION_CLI` 显式指定一个入口文件,对所有扩展命令生效,优先于查表;
@@ -116,7 +116,7 @@ function runExtensionCommand(name, argv) {
116
116
  * 已下线的子命令 → 替代做法。入口在这里集中拦截:stderr 写明替代命令,退出码 2(与「命令不存在」的 1 区分)。
117
117
  */
118
118
  const RETIRED_COMMANDS = {
119
- init: '应用工程请在 Host 根配置 soma.app.ts(应用配置按所用方言的约定);新建组件包请使用 soma pack init <包名> [--dir <目录>];soma-kit 应用请用 `npx soma-kit init <目录>`',
119
+ init: '应用工程请在 Host 根配置 soma.app.ts(应用配置与工程初始化按所用上层扩展包的约定);新建组件包请使用 soma pack init <包名> [--dir <目录>]',
120
120
  'package-vscode': '请直接通过 soma lsp(或 soma-lsp)以 stdio 协议接入编辑器',
121
121
  };
122
122
 
@@ -3362,7 +3362,7 @@ var SOMA_STD_PAGE_FORBIDDEN_LOGIC_KEYS = {
3362
3362
  "roleBy": { "code": "CORE-PAGE-ROLE-BY-INVALID", "pathPattern": "^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$", "positions": ["bind.role_by"], "was": "bind.role_by \u5199\u4E86\u8868\u8FBE\u5F0F / \u53D6\u53CD / \u7BA1\u9053 / \u6620\u5C04", "remedy": 'role_by \u53EA\u8BB8\u7EAF\u8DEF\u5F84\uFF1A\u884C\u5B57\u6BB5\u7684\u503C\u76F4\u63A5\u4F5C\u4E3A\u6A21\u677F\u540D\uFF0C\u5339\u914D data-soma-role="item:\u53D6\u503C"\uFF1B\u884C\u6570\u636E\u81EA\u5E26\u6A21\u677F\u540D' }
3363
3363
  },
3364
3364
  "exemptContexts": ["diagnostics", "diagnosticExamples", "rejected", "title", "basis", "was", "summary", "docSummary"],
3365
- "exampleRoots": ["soma-kit-demo/pages", "soma-kit/examples", "soma-ui/tests/fixtures/hosts", "soma-core-demo/ui", "soma-core-demo/pages"],
3365
+ "exampleRoots": ["soma-kit-demo/pages", "soma-kit/examples", "soma-ui/tests/fixtures/hosts"],
3366
3366
  "exampleFilePatterns": ["_ui.yaml", ".kit.yaml", "_style.yaml"],
3367
3367
  "exampleSkipDirs": ["node_modules", "negative", "__negative__"],
3368
3368
  "note": "forbiddenShape: 'object' = \u53EA\u7981\u5BF9\u8C61 / \u5217\u8868\u5F62\uFF0C\u503C\u4E3A\u5B57\u7B26\u4E32\uFF08\u7EAF\u8DEF\u5F84\u7ED1\u5B9A\uFF09\u653E\u884C\uFF1Bscope: 'standard' = \u53EA\u5728 core \u6807\u51C6\u683C\u5F0F\uFF08\u56DB\u4EF6\u5957 / \u6CE8\u5165\u53E3\uFF09\u5224\u5B9A\uFF0C\u4E0D\u8FDB G83 \u7684\u8DE8\u65B9\u8A00\u8BED\u6CD5\u6E90\u4E0E\u793A\u4F8B\u9875\u626B\u63CF\uFF08\u65B9\u8A00\u540C\u540D\u952E\u542B\u4E49\u4E0D\u540C\uFF0C\u5982 steps \u9875\u9762\u6A21\u5F0F\uFF09"
@@ -3711,7 +3711,7 @@ function parseUiConfig(raw, options) {
3711
3711
  config.initProps = parseInitProps(raw.initProps, "initProps");
3712
3712
  }
3713
3713
  if ("adaptive" in raw && raw.adaptive !== void 0) {
3714
- throw new SomaUiConfigError("adaptive \u58F0\u660E\u5DF2\u9000\u5F79\uFF1A\u81EA\u9002\u5E94\u5728\u7F16\u8BD1\u671F\u7531 soma-ui \u51B3\u5B9A\uFF0C\u9875\u9762\u58F0\u660E\u91CC\u4E0D\u518D\u5199 adaptive", "adaptive");
3714
+ throw new SomaUiConfigError("adaptive \u58F0\u660E\u5DF2\u9000\u5F79\uFF1A\u81EA\u9002\u5E94\u5728\u7F16\u8BD1\u671F\u7531\u4E0A\u5C42\u65B9\u8A00\u51B3\u5B9A\uFF0C\u9875\u9762\u58F0\u660E\u91CC\u4E0D\u518D\u5199 adaptive", "adaptive");
3715
3715
  }
3716
3716
  if ("state" in raw && raw.state !== void 0) {
3717
3717
  config.state = parsePageState(
@@ -3821,6 +3821,13 @@ function isMapValue(value) {
3821
3821
  function isTextValue(value) {
3822
3822
  return typeof value === "string" && value.trim() !== "";
3823
3823
  }
3824
+ function isPlainJsonValue(value) {
3825
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
3826
+ if (typeof value === "number") return Number.isFinite(value);
3827
+ if (Array.isArray(value)) return value.every(isPlainJsonValue);
3828
+ if (typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value))) return Object.values(value).every(isPlainJsonValue);
3829
+ return false;
3830
+ }
3824
3831
  function shapeError(message, path) {
3825
3832
  throw new SomaUiConfigError(message, path);
3826
3833
  }
@@ -3844,7 +3851,7 @@ function shapeClosedKeys(value, allowed, what, path) {
3844
3851
  var SCOPE_DECL_KEYS = { id: true, object: true, slices: true, mirrors: true, gates: true };
3845
3852
  var SCOPE_MIRROR_KEYS = { key: true, slice: true, path: true, as: true };
3846
3853
  var SCOPE_GATE_KEYS = { hook: true, slice: true, path: true };
3847
- var SCOPE_SLICE_KEYS = { name: true, owner: true, writers: true, readers: true, ready: true };
3854
+ var SCOPE_SLICE_KEYS = { name: true, owner: true, writers: true, readers: true, ready: true, initial: true };
3848
3855
  function parseScopeDeclarations(raw, path) {
3849
3856
  if (!Array.isArray(raw)) shapeError(`${path} \u5FC5\u987B\u662F\u6570\u7EC4\uFF08\u533A\u57DF\u534F\u8C03\u4F5C\u7528\u57DF\u58F0\u660E\uFF09`, path);
3850
3857
  const decls = raw.map((item, index) => {
@@ -3875,12 +3882,14 @@ function parseScopeDeclarations(raw, path) {
3875
3882
  readers = slice.readers;
3876
3883
  }
3877
3884
  if (slice.ready !== void 0 && typeof slice.ready !== "boolean") shapeError("ready \u5FC5\u987B\u662F\u5E03\u5C14\u503C", `${sliceAt}.ready`);
3885
+ if (slice.initial !== void 0 && !isPlainJsonValue(slice.initial)) shapeError("initial \u5FC5\u987B\u662F\u7EAF JSON \u503C\uFF08\u5BF9\u8C61 / \u6570\u7EC4 / \u5B57\u7B26\u4E32 / \u6570\u5B57 / \u5E03\u5C14 / null\uFF09", `${sliceAt}.initial`);
3878
3886
  return {
3879
3887
  name,
3880
3888
  owner,
3881
3889
  ...writers !== void 0 ? { writers } : {},
3882
3890
  ...readers !== void 0 ? { readers } : {},
3883
- ...slice.ready === true ? { ready: true } : {}
3891
+ ...slice.ready === true ? { ready: true } : {},
3892
+ ...slice.initial !== void 0 ? { initial: slice.initial } : {}
3884
3893
  };
3885
3894
  });
3886
3895
  const object = entry.object === void 0 ? void 0 : shapeText(entry.object, "object", `${at}.object`);
@@ -6745,7 +6754,9 @@ var SOMA_PIPELINE_LIMITS = {
6745
6754
  "bodyAt": "\u65E0 key \u6761\u76EE\u6309\u6B63\u6587\u914D\u5BF9\u7684\u76F8\u4F3C\u5EA6\u9608\u503C\uFF08\u7B14\u8BB0 C.2 ItemOpts.match.bodyAt 0.5\uFF09",
6746
6755
  "maxAlignTokens": "\u5E8F\u5217\u5BF9\u9F50\u7684\u4E0D\u540C\u952E\u6570\u4E0A\u9650\uFF08\u6BCF\u4E2A\u952E\u6620\u5C04\u4E3A\u4E00\u4E2A BMP \u79C1\u7528\u533A\u5B57\u7B26\uFF0CU+E000\u2013U+F8FF \u5171 6400 \u4E2A\uFF09",
6747
6756
  "maxPairMatrix": "\u4E00\u6BB5\u5220\u589E\u533A\u95F4\u5185\u53E5 / \u6BB5\u914D\u5BF9\u7684\u5019\u9009\u77E9\u9635\u4E0A\u9650\uFF08\u5220\u6570 \xD7 \u589E\u6570\uFF09\uFF0C\u8D85\u51FA\u4E0D\u914D\u5BF9\u3001\u6309\u5220 + \u589E\u5448\u73B0\uFF1B\u7ECF\u9A8C\u503C\uFF0C\u8BC1\u636E\u5F31",
6748
- "maxPairCandidates": "\u65E0 key \u6761\u76EE\u6309\u76F8\u4F3C\u5EA6\u914D\u5BF9\u7684\u5019\u9009\u77E9\u9635\u4E0A\u9650\uFF08\u5269\u4F59\u65E7\u6761\u76EE \xD7 \u5269\u4F59\u65B0\u6761\u76EE\uFF09\uFF1B\u7ECF\u9A8C\u503C\uFF0C\u8BC1\u636E\u5F31"
6757
+ "maxPairCandidates": "\u65E0 key \u6761\u76EE\u6309\u76F8\u4F3C\u5EA6\u914D\u5BF9\u7684\u5019\u9009\u77E9\u9635\u4E0A\u9650\uFF08\u5269\u4F59\u65E7\u6761\u76EE \xD7 \u5269\u4F59\u65B0\u6761\u76EE\uFF09\uFF1B\u7ECF\u9A8C\u503C\uFF0C\u8BC1\u636E\u5F31",
6758
+ "codeContext": "\u4EE3\u7801\u5DEE\u5F02\u6BCF\u5757\u7684\u4E0A\u4E0B\u6587\u884C\u6570\uFF08\u7B14\u8BB0 C.5\u300C\u4E0A\u4E0B\u6587 3 \u884C\u300D\uFF0C\u540C git diff -U3 / VS Code\uFF09",
6759
+ "codeIntraMaxLine": "\u4EE3\u7801\u6539\u884C\u505A\u884C\u5185\u5B57\u7B26\u5DEE\u5F02\u7684\u5355\u884C\u957F\u5EA6\u4E0A\u9650\uFF08\u5B57\u7B26\uFF09\uFF1B\u66F4\u957F\u7684\u884C\u53EA\u6807\u6574\u884C\u589E\u5220\uFF08\u7ECF\u9A8C\u503C\uFF1A\u538B\u7F29\u540E\u7684\u957F\u884C\u9010\u5B57\u6BD4\u8F83\u65E0\u610F\u4E49\u4E14\u8017\u65F6\uFF09"
6749
6760
  },
6750
6761
  "maxChars": 2e5,
6751
6762
  "maxCharsPerCompare": 2e4,
@@ -6760,7 +6771,9 @@ var SOMA_PIPELINE_LIMITS = {
6760
6771
  "bodyAt": 0.5,
6761
6772
  "maxAlignTokens": 6400,
6762
6773
  "maxPairMatrix": 2500,
6763
- "maxPairCandidates": 25e4
6774
+ "maxPairCandidates": 25e4,
6775
+ "codeContext": 3,
6776
+ "codeIntraMaxLine": 500
6764
6777
  },
6765
6778
  "highlight": {
6766
6779
  "basis": {
@@ -55,13 +55,18 @@ export interface SomaRegionScopeStore {
55
55
  /** 清空(数据层失效、页面卸载) */
56
56
  clear(): void;
57
57
  /**
58
- * 重置切片值(C43,切换主体时清理,接 `resetOnContextChange`):声明保留,值回到未写过的初始态、`ready` 回到声明的初值,
58
+ * 重置切片值(C43,切换主体时清理,接 `resetOnContextChange`):声明保留,值回到声明的初值(`initial`,没声明 = 空)、`ready` 回到声明的初值,
59
59
  * 写入序号加一(在途的取数响应按序号判迟到,不会写回上个主体的数据),订阅者收到通知。
60
60
  * `scopeIds` 缺省 = 全部作用域;`names` 缺省 = 全部切片。返回被重置的切片个数。
61
61
  */
62
62
  reset(scopeIds?: readonly string[], names?: readonly SomaRegionSliceName[]): number;
63
63
  }
64
64
 
65
+ /** 切片初值(声明的 `initial`,纯 JSON 值)的独立副本;没声明 = undefined(空切片) */
66
+ function initialOf(decl: SomaScopeSliceDecl): unknown {
67
+ return decl.initial === undefined ? undefined : structuredClone(decl.initial);
68
+ }
69
+
65
70
  interface SliceState {
66
71
  readonly decl: SomaScopeSliceDecl;
67
72
  value: unknown;
@@ -188,7 +193,7 @@ export function createRegionScopeStore(): SomaRegionScopeStore {
188
193
  const slices = new Map<SomaRegionSliceName, SliceState>();
189
194
  for (const sliceDecl of decl.slices) {
190
195
  slices.set(sliceDecl.name, {
191
- decl: sliceDecl, value: undefined, ready: sliceDecl.ready !== true, revision: 0, listeners: new Set(), queued: false,
196
+ decl: sliceDecl, value: initialOf(sliceDecl), ready: sliceDecl.ready !== true, revision: 0, listeners: new Set(), queued: false,
192
197
  });
193
198
  }
194
199
  next.set(decl.id, { decl, slices, semantic: new Set() });
@@ -259,7 +264,7 @@ export function createRegionScopeStore(): SomaRegionScopeStore {
259
264
  if (scopeIds !== undefined && !scopeIds.includes(id)) continue;
260
265
  for (const [name, slice] of scope.slices) {
261
266
  if (names !== undefined && !names.includes(name)) continue;
262
- slice.value = undefined;
267
+ slice.value = initialOf(slice.decl);
263
268
  slice.ready = slice.decl.ready !== true;
264
269
  slice.revision += 1;
265
270
  notify(slice);
@@ -617,7 +617,7 @@ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<s
617
617
  }
618
618
 
619
619
  if (config.confirm) {
620
- // 确认文案占位(`{字段}` / `{n}`)在触发时代入:只替换 text / impact,permission / roles 顺序与确认级别不受影响
620
+ // 确认文案占位(`{字段}` / `{n}`)在触发时代入:替换 text / impact / typed 的 phrase(缺值的 phrase 作废 → 确认钮恒不可用),permission / roles 顺序与确认级别不受影响
621
621
  const spec = resolveConfirmSpec(
622
622
  config.confirmSpec ?? { level: 'plain', text: config.confirm },
623
623
  confirmContext,
@@ -1266,6 +1266,15 @@ export class SomaBootstrap {
1266
1266
  && (this.domainInstance?._services?.http.pendingCount() ?? 0) === 0;
1267
1267
  }
1268
1268
 
1269
+ /**
1270
+ * 首轮渲染落定:组件初始化完成、调度队列清空;不等在途请求(与 whenSettled 的区别)。
1271
+ * 宿主据此在数据到位前判断页面是否已画出自己声明的加载态(见 host-native 首帧显示)。
1272
+ */
1273
+ async whenRendered(): Promise<void> {
1274
+ await this.componentManager?.whenInitialized();
1275
+ await this.scheduler.whenSettled();
1276
+ }
1277
+
1269
1278
  async whenSettled(): Promise<void> {
1270
1279
  do {
1271
1280
  await this.componentManager?.whenInitialized();
@@ -0,0 +1,205 @@
1
+ // 代码差异与 Markdown 差异流水线(内容展示批次 ⑥;纯函数 + 适配器调用,零 DOM,不 import soma 其它模块)。
2
+ // 代码:按行 LCS 对齐(alignKeys)→ 删增区间内按相似度配对成「改行」并做行内字符差异 → 按上下文行数切块(hunk)。
3
+ // Markdown:源码按块切分(空行分隔、围栏代码整块)→ 块序列对齐(键 = 块类型 + 归一化文字)→ 同类型且相似的块配对,
4
+ // 块内做中文词级差异;结构变化(标题层级、列表有序 / 无序、代码语言)给块级说明。渲染交给组件(块用 Markdown 端口渲染)。
5
+
6
+ import type { CodeDiff, CodeDiffHunk, CodeDiffLine, DiffFragment, DiffPart, MarkdownBlockKind, MarkdownDiff, MarkdownDiffBlock } from './port';
7
+ import { alignKeys, diceSimilarity, hasHan, pairAligned, safeDiff, tidy, type ProseRun } from './prose';
8
+
9
+ export interface CodeConfig {
10
+ readonly maxChars: number;
11
+ readonly maxAlignTokens: number;
12
+ readonly maxPairMatrix: number;
13
+ readonly pairAt: number;
14
+ /** 每块上下文行数 */
15
+ readonly context: number;
16
+ /** 行内字符差异只对不超过此长度的行做 */
17
+ readonly intraMaxLine: number;
18
+ }
19
+
20
+ const toFrags = (parts: readonly DiffPart[]): DiffFragment[] =>
21
+ tidy(parts.map((p) => ({ v: p.text, op: p.op === 'equal' ? 'eq' as const : p.op === 'insert' ? 'ins' as const : 'del' as const })));
22
+
23
+ const linesOf = (s: string): string[] => (s === '' ? [] : s.replace(/\r\n?/gu, '\n').split('\n'));
24
+ const squash = (s: string): string => s.replace(/\s+/gu, '');
25
+
26
+ /** 行级操作 → 按上下文切块(纯函数) */
27
+ export function hunksOf(lines: readonly CodeDiffLine[], context: number): CodeDiffHunk[] {
28
+ const changed: number[] = [];
29
+ lines.forEach((l, i) => { if (l.op !== 'eq') changed.push(i); });
30
+ if (changed.length === 0) return [];
31
+ const ranges: [number, number][] = [];
32
+ for (const i of changed) {
33
+ const from = Math.max(0, i - context);
34
+ const to = Math.min(lines.length - 1, i + context);
35
+ const last = ranges[ranges.length - 1];
36
+ if (last && from <= last[1] + 1) last[1] = Math.max(last[1], to);
37
+ else ranges.push([from, to]);
38
+ }
39
+ return ranges.map(([from, to]) => {
40
+ const slice = lines.slice(from, to + 1);
41
+ const firstA = slice.find((l) => l.a !== undefined)?.a ?? 0;
42
+ const firstB = slice.find((l) => l.b !== undefined)?.b ?? 0;
43
+ return {
44
+ aStart: firstA, aLines: slice.filter((l) => l.a !== undefined).length,
45
+ bStart: firstB, bLines: slice.filter((l) => l.b !== undefined).length,
46
+ from, to, lines: slice,
47
+ };
48
+ });
49
+ }
50
+
51
+ export async function runCode(run: ProseRun, cfg: CodeConfig, a: string, b: string): Promise<CodeDiff> {
52
+ const aLines = linesOf(a);
53
+ const bLines = linesOf(b);
54
+ const whitespaceOnly = a !== b && squash(a) === squash(b);
55
+ if (a === b) {
56
+ const lines = aLines.map((text, i): CodeDiffLine => ({ op: 'eq', a: i + 1, b: i + 1, text }));
57
+ return { kind: 'same', lines, hunks: [], stats: { added: 0, removed: 0, modified: 0 }, whitespaceOnly: false };
58
+ }
59
+ const plain = (degraded: 'too-large' | 'timeout'): CodeDiff => {
60
+ const lines: CodeDiffLine[] = [
61
+ ...aLines.map((text, i): CodeDiffLine => ({ op: 'del', a: i + 1, text })),
62
+ ...bLines.map((text, i): CodeDiffLine => ({ op: 'ins', b: i + 1, text })),
63
+ ];
64
+ return { kind: 'changed', lines, hunks: [{ aStart: 1, aLines: aLines.length, bStart: 1, bLines: bLines.length, from: 0, to: lines.length - 1, lines }], stats: { added: bLines.length, removed: aLines.length, modified: 0 }, whitespaceOnly, degraded };
65
+ };
66
+ if (a.length + b.length > cfg.maxChars) return plain('too-large');
67
+ const ops = await alignKeys(run, aLines, bLines, cfg.maxAlignTokens);
68
+ if (ops === null) return plain(run.degraded === 'timeout' ? 'timeout' : 'too-large');
69
+ const units = pairAligned(ops, aLines, bLines, cfg.pairAt, cfg.maxPairMatrix);
70
+ const lines: CodeDiffLine[] = [];
71
+ let added = 0;
72
+ let removed = 0;
73
+ let modified = 0;
74
+ // 改行:先列删行、再列增行(合并视图「删行在增行上方」);连续的改行成组输出
75
+ let pendingDel: CodeDiffLine[] = [];
76
+ let pendingIns: CodeDiffLine[] = [];
77
+ const flush = (): void => { lines.push(...pendingDel, ...pendingIns); pendingDel = []; pendingIns = []; };
78
+ for (const u of units) {
79
+ if (u.op === 'eq') { flush(); lines.push({ op: 'eq', a: u.a + 1, b: u.b + 1, text: aLines[u.a]! }); continue; }
80
+ if (u.op === 'del') { removed += 1; pendingDel.push({ op: 'del', a: u.a + 1, text: aLines[u.a]! }); continue; }
81
+ if (u.op === 'ins') { added += 1; pendingIns.push({ op: 'ins', b: u.b + 1, text: bLines[u.b]! }); continue; }
82
+ modified += 1;
83
+ const la = aLines[u.a]!;
84
+ const lb = bLines[u.b]!;
85
+ let frags: DiffFragment[] | null = null;
86
+ if (la.length <= cfg.intraMaxLine && lb.length <= cfg.intraMaxLine) {
87
+ const parts = await safeDiff(run, la, lb, 'chars');
88
+ if (parts !== null) frags = toFrags(parts);
89
+ }
90
+ pendingDel.push({ op: 'del', a: u.a + 1, text: la, pair: u.b + 1, ...(frags ? { fragments: frags.filter((f) => f.op !== 'ins') } : {}) });
91
+ pendingIns.push({ op: 'ins', b: u.b + 1, text: lb, pair: u.a + 1, ...(frags ? { fragments: frags.filter((f) => f.op !== 'del') } : {}) });
92
+ }
93
+ flush();
94
+ const out: CodeDiff = { kind: 'changed', lines, hunks: hunksOf(lines, cfg.context), stats: { added, removed, modified }, whitespaceOnly };
95
+ return run.degraded !== undefined ? { ...out, degraded: run.degraded === 'timeout' ? 'timeout' : 'too-large' } : out;
96
+ }
97
+
98
+ // ── Markdown ──
99
+
100
+ /** 源码 → 块(空行分隔;围栏代码整块,围栏里的空行不切);纯函数 */
101
+ export function splitMarkdownBlocks(source: string): string[] {
102
+ const out: string[] = [];
103
+ let cur: string[] = [];
104
+ let fence: string | null = null;
105
+ for (const line of source.replace(/\r\n?/gu, '\n').split('\n')) {
106
+ const m = /^\s{0,3}(`{3,}|~{3,})/u.exec(line);
107
+ if (fence !== null) {
108
+ cur.push(line);
109
+ if (m && m[1]!.startsWith(fence)) { out.push(cur.join('\n')); cur = []; fence = null; }
110
+ continue;
111
+ }
112
+ if (m) { if (cur.length > 0) out.push(cur.join('\n')); cur = [line]; fence = m[1]!.slice(0, 3); continue; }
113
+ if (line.trim() === '') { if (cur.length > 0) out.push(cur.join('\n')); cur = []; continue; }
114
+ cur.push(line);
115
+ }
116
+ if (cur.length > 0) out.push(cur.join('\n'));
117
+ return out;
118
+ }
119
+
120
+ export function markdownBlockKind(block: string): { kind: MarkdownBlockKind; detail: string } {
121
+ const first = block.split('\n', 1)[0]!.trimStart();
122
+ const h = /^(#{1,6})\s/u.exec(first);
123
+ if (h) return { kind: 'heading', detail: String(h[1]!.length) };
124
+ const f = /^(`{3,}|~{3,})\s*([^\s`]*)/u.exec(first);
125
+ if (f) return { kind: 'code', detail: f[2] ?? '' };
126
+ if (/^>/u.test(first)) return { kind: 'quote', detail: '' };
127
+ if (/^\d+[.)]\s/u.test(first)) return { kind: 'list', detail: 'ordered' };
128
+ if (/^[-*+]\s/u.test(first)) return { kind: 'list', detail: 'bullet' };
129
+ if (/^\|/u.test(first)) return { kind: 'table', detail: '' };
130
+ if (/^(-{3,}|\*{3,}|_{3,})\s*$/u.test(first)) return { kind: 'hr', detail: '' };
131
+ return { kind: 'paragraph', detail: '' };
132
+ }
133
+
134
+ /** 块的可比文字:去掉块首标记(# / > / 列表符号 / 围栏行),空白归一 */
135
+ export function markdownBlockText(block: string, kind: MarkdownBlockKind): string {
136
+ if (kind === 'code') return block.split('\n').slice(1).filter((l, i, arr) => !(i === arr.length - 1 && /^\s*(`{3,}|~{3,})\s*$/u.test(l))).join('\n');
137
+ return block.split('\n').map((l) => l.replace(/^\s{0,3}(#{1,6}\s+|>\s?|[-*+]\s+(\[[ xX]\]\s+)?|\d+[.)]\s+)/u, '')).join('\n').trim();
138
+ }
139
+
140
+ export interface MarkdownConfig extends CodeConfig { readonly maxBlocks: number }
141
+
142
+ export async function runMarkdown(run: ProseRun, cfg: MarkdownConfig, a: string, b: string): Promise<MarkdownDiff> {
143
+ if (a === b) {
144
+ const blocks = splitMarkdownBlocks(a).map((s): MarkdownDiffBlock => ({ op: 'eq', kind: markdownBlockKind(s).kind, before: s, after: s }));
145
+ return { kind: 'same', blocks, stats: { added: 0, removed: 0, modified: 0, same: blocks.length } };
146
+ }
147
+ const aBlocks = splitMarkdownBlocks(a);
148
+ const bBlocks = splitMarkdownBlocks(b);
149
+ if (a.length + b.length > cfg.maxChars || aBlocks.length + bBlocks.length > cfg.maxBlocks) {
150
+ return { kind: 'changed', blocks: [], stats: { added: 0, removed: 0, modified: 0, same: 0 }, degraded: 'too-large' };
151
+ }
152
+ const meta = (s: string): { kind: MarkdownBlockKind; detail: string; text: string } => { const k = markdownBlockKind(s); return { ...k, text: markdownBlockText(s, k.kind) }; };
153
+ const am = aBlocks.map(meta);
154
+ const bm = bBlocks.map(meta);
155
+ // 对齐键:类型 + 归一化文字(标题层级、列表种类不进键,变化由块级说明给出)
156
+ const key = (m: { kind: string; text: string }): string => `${m.kind}\u0000${m.text.replace(/\s+/gu, ' ')}`;
157
+ const ops = await alignKeys(run, am.map(key), bm.map(key), cfg.maxAlignTokens);
158
+ if (ops === null) return { kind: 'changed', blocks: [], stats: { added: 0, removed: 0, modified: 0, same: 0 }, degraded: run.degraded === 'timeout' ? 'timeout' : 'too-large' };
159
+ // 配对:同类型才配(相似度用块文字);不同类型的键前缀不同,相似度天然低
160
+ const units = pairAligned(ops, am.map((m) => `${m.kind}:${m.text}`), bm.map((m) => `${m.kind}:${m.text}`), cfg.pairAt, cfg.maxPairMatrix);
161
+ const blocks: MarkdownDiffBlock[] = [];
162
+ let added = 0;
163
+ let removed = 0;
164
+ let modified = 0;
165
+ let same = 0;
166
+ for (const u of units) {
167
+ if (u.op === 'eq') {
168
+ const x = am[u.a]!;
169
+ const y = bm[u.b]!;
170
+ const notes = structureNotes(x, y);
171
+ if (notes.length === 0 && aBlocks[u.a] === bBlocks[u.b]) { same += 1; blocks.push({ op: 'eq', kind: y.kind, before: aBlocks[u.a]!, after: bBlocks[u.b]! }); continue; }
172
+ modified += 1;
173
+ blocks.push({ op: 'mod', kind: y.kind, before: aBlocks[u.a]!, after: bBlocks[u.b]!, fragments: [{ v: y.text, op: 'eq' }], ...(notes.length > 0 ? { notes } : {}) });
174
+ continue;
175
+ }
176
+ if (u.op === 'del') { removed += 1; blocks.push({ op: 'del', kind: am[u.a]!.kind, before: aBlocks[u.a]! }); continue; }
177
+ if (u.op === 'ins') { added += 1; blocks.push({ op: 'ins', kind: bm[u.b]!.kind, after: bBlocks[u.b]! }); continue; }
178
+ const x = am[u.a]!;
179
+ const y = bm[u.b]!;
180
+ if (x.kind !== y.kind) {
181
+ removed += 1; added += 1;
182
+ blocks.push({ op: 'del', kind: x.kind, before: aBlocks[u.a]! }, { op: 'ins', kind: y.kind, after: bBlocks[u.b]! });
183
+ continue;
184
+ }
185
+ modified += 1;
186
+ const mode = hasHan(x.text) || hasHan(y.text) ? 'words-zh' as const : 'words' as const;
187
+ const parts = x.kind === 'code' ? null : await safeDiff(run, x.text, y.text, mode);
188
+ const notes = structureNotes(x, y);
189
+ blocks.push({
190
+ op: 'mod', kind: y.kind, before: aBlocks[u.a]!, after: bBlocks[u.b]!,
191
+ ...(parts !== null ? { fragments: toFrags(parts) } : {}),
192
+ ...(notes.length > 0 ? { notes } : {}),
193
+ similarity: diceSimilarity(x.text, y.text),
194
+ });
195
+ }
196
+ const out: MarkdownDiff = { kind: 'changed', blocks, stats: { added, removed, modified, same } };
197
+ return run.degraded !== undefined ? { ...out, degraded: run.degraded === 'timeout' ? 'timeout' : 'too-large' } : out;
198
+ }
199
+
200
+ /** 结构变化说明:标题层级、列表有序 / 无序、代码块语言(值只给数据,文案由组件定) */
201
+ function structureNotes(x: { kind: MarkdownBlockKind; detail: string }, y: { kind: MarkdownBlockKind; detail: string }): { readonly what: 'heading-level' | 'list-type' | 'code-language'; readonly before: string; readonly after: string }[] {
202
+ if (x.kind !== y.kind || x.detail === y.detail) return [];
203
+ const what = x.kind === 'heading' ? 'heading-level' as const : x.kind === 'list' ? 'list-type' as const : x.kind === 'code' ? 'code-language' as const : null;
204
+ return what === null ? [] : [{ what, before: x.detail, after: y.detail }];
205
+ }
@@ -2,18 +2,21 @@
2
2
  // 输入校验(类型、粒度、上限)与散文 / 条目流水线在这里,换适配器也一样受约束。
3
3
  // 上限与阈值的缺省只读 design(`limits.json#contentEngines.diff`);调用方给的时限 / 字数只能比缺省更小。
4
4
  export type {
5
+ CodeDiff, CodeDiffHunk, CodeDiffLine, CodeDiffOptions, MarkdownBlockKind, MarkdownDiff, MarkdownDiffBlock,
5
6
  DiffFragment, DiffMode, DiffOptions, DiffPart, ItemDiff, ItemDiffEntry, ItemDiffOptions, ItemFieldDiff, ItemFieldSpec, ItemFieldType,
6
7
  ItemState, ProseBlock, ProseDegraded, ProseDiff, ProseDiffOptions, ProseNormalizeOptions, SomaDiffAdapter, SomaDiffPort,
7
8
  } from './port';
8
9
  export { assertDiffAdapter } from './port';
10
+ export { hunksOf, markdownBlockKind, markdownBlockText, splitMarkdownBlocks } from './code';
9
11
 
10
12
  import { SomaEngineError } from '../../../shared/engines/engine-error';
11
13
  import { SOMA_PIPELINE_LIMITS } from '../../../shared/registry-generated/limits';
12
14
  import type { EngineLoadTelemetry } from '../load';
13
15
  import { createJsdiffAdapter } from './adapter-jsdiff';
14
16
  import { runItems, type ItemsConfig } from './items';
17
+ import { runCode, runMarkdown, type CodeConfig } from './code';
15
18
  import {
16
- assertDiffAdapter, type DiffMode, type DiffOptions, type DiffPart, type ItemDiff, type ItemDiffOptions, type ProseDiff,
19
+ assertDiffAdapter, type CodeDiff, type CodeDiffOptions, type MarkdownDiff, type DiffMode, type DiffOptions, type DiffPart, type ItemDiff, type ItemDiffOptions, type ProseDiff,
17
20
  type ProseDiffOptions, type SomaDiffAdapter, type SomaDiffPort,
18
21
  } from './port';
19
22
  import { clock, runProse, type ProseRun } from './prose';
@@ -48,6 +51,17 @@ function configOf(o: ProseDiffOptions | ItemDiffOptions | undefined): ItemsConfi
48
51
  };
49
52
  }
50
53
 
54
+ function codeConfigOf(o: CodeDiffOptions | undefined): CodeConfig {
55
+ return {
56
+ maxChars: LIMITS.maxChars,
57
+ maxAlignTokens: LIMITS.maxAlignTokens,
58
+ maxPairMatrix: LIMITS.maxPairMatrix,
59
+ pairAt: LIMITS.pairAt,
60
+ context: typeof o?.context === 'number' && Number.isInteger(o.context) && o.context >= 0 ? Math.min(o.context, LIMITS.codeContext) : LIMITS.codeContext,
61
+ intraMaxLine: LIMITS.codeIntraMaxLine,
62
+ };
63
+ }
64
+
51
65
  /** 整段替换(端口级退化:超时、适配器失败) */
52
66
  function wholeReplace(a: string, b: string): DiffPart[] {
53
67
  if (a === b) return a === '' ? [] : [{ op: 'equal', text: a }];
@@ -104,5 +118,17 @@ export function createDiffPort(adapter?: SomaDiffAdapter, options: DiffPortOptio
104
118
  record('items', started);
105
119
  return out;
106
120
  },
121
+ async diffCode(a: string, b: string, codeOptions?: CodeDiffOptions): Promise<CodeDiff> {
122
+ const started = clock();
123
+ const out = await runCode(newRun(codeOptions?.timeoutMs), codeConfigOf(codeOptions), textOrEmpty(a), textOrEmpty(b));
124
+ record('code', started);
125
+ return out;
126
+ },
127
+ async diffMarkdown(a: string, b: string, mdOptions?: CodeDiffOptions): Promise<MarkdownDiff> {
128
+ const started = clock();
129
+ const out = await runMarkdown(newRun(mdOptions?.timeoutMs), { ...codeConfigOf(mdOptions), maxBlocks: LIMITS.maxItems }, textOrEmpty(a), textOrEmpty(b));
130
+ record('markdown', started);
131
+ return out;
132
+ },
107
133
  };
108
134
  }
@@ -149,6 +149,77 @@ export interface ItemDiff {
149
149
  readonly degraded?: ProseDegraded | 'too-many-items';
150
150
  }
151
151
 
152
+ // ── 代码差异(内容展示批次 ⑥) ──
153
+
154
+ export interface CodeDiffLine {
155
+ readonly op: 'eq' | 'ins' | 'del';
156
+ /** 旧版行号(1 起;增行无) */
157
+ readonly a?: number;
158
+ /** 新版行号(1 起;删行无) */
159
+ readonly b?: number;
160
+ readonly text: string;
161
+ /** 改行:配对另一侧的行号(删行给新版行号,增行给旧版行号) */
162
+ readonly pair?: number;
163
+ /** 改行的行内字符差异(删行只含 eq / del,增行只含 eq / ins);行过长或超时缺省 */
164
+ readonly fragments?: readonly DiffFragment[];
165
+ }
166
+
167
+ export interface CodeDiffHunk {
168
+ readonly aStart: number;
169
+ readonly aLines: number;
170
+ readonly bStart: number;
171
+ readonly bLines: number;
172
+ /** 在 `lines` 中的起止下标(含) */
173
+ readonly from: number;
174
+ readonly to: number;
175
+ readonly lines: readonly CodeDiffLine[];
176
+ }
177
+
178
+ export interface CodeDiff {
179
+ readonly kind: 'same' | 'changed';
180
+ /** 全部行(合并视图顺序:改行组内删行在增行上方) */
181
+ readonly lines: readonly CodeDiffLine[];
182
+ /** 按 design `contentEngines.diff.codeContext` 行上下文切出的块 */
183
+ readonly hunks: readonly CodeDiffHunk[];
184
+ readonly stats: { readonly added: number; readonly removed: number; readonly modified: number };
185
+ /** 去掉全部空白后两侧相同 */
186
+ readonly whitespaceOnly: boolean;
187
+ /** too-large / timeout:不逐行对齐,整体按「全删 + 全增」给出 */
188
+ readonly degraded?: 'too-large' | 'timeout';
189
+ }
190
+
191
+ // ── Markdown 差异(内容展示批次 ⑥;源码块级对齐 + 块内词级) ──
192
+
193
+ export type MarkdownBlockKind = 'heading' | 'paragraph' | 'list' | 'quote' | 'code' | 'table' | 'hr';
194
+
195
+ export interface MarkdownDiffBlock {
196
+ readonly op: 'eq' | 'ins' | 'del' | 'mod';
197
+ readonly kind: MarkdownBlockKind;
198
+ /** 块的 Markdown 源码(组件经 Markdown 端口渲染) */
199
+ readonly before?: string;
200
+ readonly after?: string;
201
+ /** mod:块文字(去块首标记)的词级差异;代码块不给(组件改用 diffCode) */
202
+ readonly fragments?: readonly DiffFragment[];
203
+ /** 结构变化:标题层级、列表有序 / 无序、代码语言 */
204
+ readonly notes?: readonly { readonly what: 'heading-level' | 'list-type' | 'code-language'; readonly before: string; readonly after: string }[];
205
+ readonly similarity?: number;
206
+ }
207
+
208
+ export interface MarkdownDiff {
209
+ readonly kind: 'same' | 'changed';
210
+ readonly blocks: readonly MarkdownDiffBlock[];
211
+ readonly stats: { readonly added: number; readonly removed: number; readonly modified: number; readonly same: number };
212
+ /** too-large / timeout:blocks 为空,组件退回源码对比(diffCode) */
213
+ readonly degraded?: 'too-large' | 'timeout';
214
+ }
215
+
216
+ export interface CodeDiffOptions {
217
+ /** 时限(调用方只能更小) */
218
+ readonly timeoutMs?: number;
219
+ /** 上下文行数(调用方只能更小) */
220
+ readonly context?: number;
221
+ }
222
+
152
223
  export interface SomaDiffPort {
153
224
  /** 两段字符串按粒度求片段(超时退回整段替换,不抛错) */
154
225
  diff(a: string, b: string, mode: DiffMode, options?: DiffOptions): Promise<readonly DiffPart[]>;
@@ -156,6 +227,10 @@ export interface SomaDiffPort {
156
227
  diffProse(a: string, b: string, options?: ProseDiffOptions): Promise<ProseDiff>;
157
228
  /** 条目列表差异:key 或内容配对、字段差异、LIS 最少移动 */
158
229
  diffItems(before: readonly unknown[], after: readonly unknown[], options?: ItemDiffOptions): Promise<ItemDiff>;
230
+ /** 代码差异:按行对齐、改行行内字符差异、按上下文切块;超长 / 超时退化为全删 + 全增(不抛) */
231
+ diffCode(a: string, b: string, options?: CodeDiffOptions): Promise<CodeDiff>;
232
+ /** Markdown 差异:源码块级对齐 + 块内词级 + 结构变化说明;超长 / 超时 blocks 为空并标 degraded(不抛) */
233
+ diffMarkdown(a: string, b: string, options?: CodeDiffOptions): Promise<MarkdownDiff>;
159
234
  }
160
235
 
161
236
  export function assertDiffAdapter(adapter: unknown): void {
@@ -119,7 +119,8 @@ export function parseConfirmSegment(message: string): SomaConfirmSegment | { rea
119
119
  //
120
120
  // · 语法:`{名字}`,名字 = `[A-Za-z_][A-Za-z0-9_]*`(标识符,不含点、不含路径、不含格式化函数);
121
121
  // `{{` 是字面 `{`,`}}` 是字面 `}`;不符合标识符语法的花括号原样保留(不是占位)。
122
- // · 作用位置:确认的 `text` 与 `impact`(`phrase` 是要用户键入的比对串,永远是字面量,不代入)。
122
+ // · 作用位置:确认的 `text`、`impact` 与 typed 级的 `phrase`(要用户键入的比对串,如被操作对象的名称 `{name}`),三处同一代入函数。
123
+ // `phrase` 有任一占位取不到值时整串作废(代入为空串):确认钮恒不可用——宁可点不了,也不能让用户照着「—」键入就放行。
123
124
  // · 取值:`{n}` 是保留名 = 本次触发的已选行数(载荷 `rows` 数组的长度);其余名字取载荷 `row`(对象)的同名字段,
124
125
  // 行内触发而载荷没带 `row` 时取所在行的数据(与具名动作载荷同口径)。
125
126
  // · 值一律转成纯文本:字符串原样、数字 / 布尔 String();对象 / 数组 / null / undefined / 缺字段 / 无行可取 = 缺失。
@@ -174,12 +175,17 @@ export function substituteConfirmText(text: string, context: SomaConfirmContext,
174
175
  });
175
176
  }
176
177
 
177
- /** 把确认规格的 text / impact 代入占位;无花括号时返回原规格(同一引用) */
178
+ /** 把确认规格的 text / impact / phrase 代入占位;无花括号时返回原规格(同一引用)。phrase 缺任一占位值 → 空串(确认钮恒不可用) */
178
179
  export function resolveConfirmSpec(spec: SomaConfirmSpec, context: SomaConfirmContext, onMissing?: (name: string) => void): SomaConfirmSpec {
179
180
  const text = substituteConfirmText(spec.text, context, onMissing);
180
181
  const impact = spec.impact === undefined ? undefined : substituteConfirmText(spec.impact, context, onMissing);
181
- if (text === spec.text && impact === spec.impact) return spec;
182
- return { ...spec, text, ...(impact !== undefined ? { impact } : {}) };
182
+ let phraseMissing = false;
183
+ const phrase = spec.phrase === undefined
184
+ ? undefined
185
+ : substituteConfirmText(spec.phrase, context, (name) => { phraseMissing = true; onMissing?.(name); });
186
+ const finalPhrase = phrase === undefined ? undefined : phraseMissing ? '' : phrase;
187
+ if (text === spec.text && impact === spec.impact && finalPhrase === spec.phrase) return spec;
188
+ return { ...spec, text, ...(impact !== undefined ? { impact } : {}), ...(finalPhrase !== undefined ? { phrase: finalPhrase } : {}) };
183
189
  }
184
190
 
185
191
  /** 开发期告警(按占位名去重;生产构建不输出) */