soma-core 2.2.5 → 2.2.6

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 (259) hide show
  1. package/README.md +5 -6
  2. package/bin/soma.cjs +2 -2
  3. package/core/build/compiler/flat-page.ts +16 -0
  4. package/core/build/compiler/full-manifest-builder.ts +0 -3
  5. package/core/build/compiler/page-assets.ts +0 -1
  6. package/core/build/compiler/page-closure.ts +245 -0
  7. package/core/build/compiler/page-declaration-compiler.ts +2 -5
  8. package/core/build/compiler/soma-precompile.js +1848 -3244
  9. package/core/build/compiler/soma-precompile.ts +4 -7
  10. package/core/build/component-tree/artifact-codec.ts +4 -8
  11. package/core/build/lsp/soma-declaration.cjs +1 -1
  12. package/core/build/lsp/std-completion.generated.json +3 -3
  13. package/core/client/a11y/a11y-config.ts +2 -1
  14. package/core/client/a11y/dom-id.ts +1 -1
  15. package/core/client/base/SomaHttpClient.ts +11 -3
  16. package/core/client/base/SomaPageRootBase.ts +6 -0
  17. package/core/client/base/defineSomaView.ts +178 -0
  18. package/core/client/base/index.ts +13 -0
  19. package/core/client/base/view-context.ts +328 -0
  20. package/core/client/behavior/adapter-collection.ts +2 -2
  21. package/core/client/compiler/manifest-compiler.ts +5 -36
  22. package/core/client/component/component-definition.types.ts +2 -1
  23. package/core/client/component/component-manager.ts +110 -20
  24. package/core/client/component/structure-adapter.ts +3 -7
  25. package/core/client/container/SomaContainerAdapter.ts +9 -1
  26. package/core/client/data/data-object-resolver.ts +516 -181
  27. package/core/client/data/data-write-actions.ts +79 -15
  28. package/core/client/data/format-config.ts +3 -1
  29. package/core/client/data/region-scope-port.ts +11 -0
  30. package/core/client/engine/asset-resolver.ts +2 -5
  31. package/core/client/engine/dom-renderer.ts +7 -40
  32. package/core/client/engine/event-engine.ts +1 -105
  33. package/core/client/engine/property-watcher.ts +1 -1
  34. package/core/client/engine/reactive-proxy.ts +78 -17
  35. package/core/client/engine/runtime-builder.ts +0 -14
  36. package/core/client/engine/scope-resolver.ts +18 -0
  37. package/core/client/engine/soma-bootstrap.ts +385 -98
  38. package/core/client/engine/style-binder.ts +49 -106
  39. package/core/client/engine/timer-engine.ts +11 -1
  40. package/core/client/host-bridge/load-host-domain-class.ts +2 -1
  41. package/core/client/infra/http/SomaHttpService.ts +15 -4
  42. package/core/client/infra/i18n/pack-locales.ts +2 -2
  43. package/core/client/mount/domain-rule.ts +7 -3
  44. package/core/client/mount/mount-page.ts +38 -5
  45. package/core/client/mount/types.ts +2 -0
  46. package/core/client/parser/confirm-spec.ts +1 -1
  47. package/core/client/parser/data-config-parser.ts +27 -210
  48. package/core/client/parser/pipeline-parser.ts +14 -59
  49. package/core/client/parser/style-config-parser.ts +101 -95
  50. package/core/client/parser/timer-parser.ts +21 -0
  51. package/core/client/parser/ui-config-parser.ts +64 -12
  52. package/core/client/registry/declaration-renderer.ts +1 -1
  53. package/core/client/runtime/SomaRuntimeServices.ts +2 -1
  54. package/core/client/runtime/SomaSnapshotStore.ts +5 -0
  55. package/core/client/security/url-guard.ts +71 -11
  56. package/core/client/validation/async-check-registry.ts +2 -1
  57. package/core/client/validation/contract-validator.ts +2 -6
  58. package/core/client/validation/field-rules.ts +3 -13
  59. package/core/client/validation/object-rules.ts +2 -10
  60. package/core/index.ts +1 -35
  61. package/core/inspect/check-product.ts +5 -5
  62. package/core/inspect/runtime.ts +2 -1
  63. package/core/server/api/dispatch-service-api.ts +35 -36
  64. package/core/server/api/load-host-service.ts +5 -4
  65. package/core/server/compile-port.ts +1 -1
  66. package/core/server/host/app-config-composer.ts +2 -1
  67. package/core/server/host/host-assembly-entry.ts +1 -0
  68. package/core/server/host/host-assembly.ts +47 -3
  69. package/core/server/host/host-caller.ts +2 -1
  70. package/core/server/host/host-dir.ts +9 -0
  71. package/core/server/host/host-response-headers.ts +2 -1
  72. package/core/server/host/invoke-host-request-hook.ts +28 -4
  73. package/core/server/host/published-page-assets.ts +2 -1
  74. package/core/server/host/resolve-host-request-hook.ts +25 -7
  75. package/core/server/host/server-page-assets.ts +4 -4
  76. package/core/server/host/virtual-pages.ts +3 -2
  77. package/core/server/infra/cache/ServerFileCache.ts +79 -9
  78. package/core/server/registry/api-registry-store.ts +3 -1
  79. package/core/server/registry/declaration-precompiler.ts +0 -2
  80. package/core/server/registry/page-registry-repository.ts +2 -1
  81. package/core/server/registry/page-registry-store.ts +2 -1
  82. package/core/server/registry/registry-error.ts +6 -1
  83. package/core/server/registry/registry-file-lock.ts +296 -23
  84. package/core/server/registry/request-body-limit.ts +3 -2
  85. package/core/server/registry/validation/declaration-safety-scan.ts +151 -27
  86. package/core/server/runtime-space/access-gate.ts +21 -7
  87. package/core/server/runtime-space/bindings.ts +3 -6
  88. package/core/server/runtime-space/dynamic-pages.ts +181 -49
  89. package/core/server/runtime-space/errors.ts +3 -0
  90. package/core/server/runtime-space/inject.ts +74 -15
  91. package/core/server/runtime-space/page-grants.ts +7 -1
  92. package/core/server/runtime-space/resolve.ts +66 -19
  93. package/core/server/runtime-space/store.ts +32 -3
  94. package/core/server/runtime-space/submit-steps.ts +2 -1
  95. package/core/server/runtime-space/types.ts +3 -1
  96. package/core/shared/component-tree-errors.ts +2 -1
  97. package/core/shared/contract-a11y.ts +1 -1
  98. package/core/shared/contract-sections.ts +2 -2
  99. package/core/shared/core-diagnostic-codes.ts +8 -0
  100. package/core/shared/declaration-keys.ts +1 -1
  101. package/core/shared/engines/engine-error.ts +2 -1
  102. package/core/shared/generation-error.ts +2 -1
  103. package/core/shared/page-envelope.ts +1 -1
  104. package/core/shared/pure-binding.ts +88 -0
  105. package/core/shared/registry-generated/diagnostic-registry-index.ts +16 -19
  106. package/core/shared/registry-generated/diagnostic-registry.ts +135 -177
  107. package/core/shared/registry-generated/limits.ts +49 -13
  108. package/core/shared/registry-generated/std-grammar-completion.ts +0 -4
  109. package/core/shared/registry-generated/std-grammar-views.ts +40 -10
  110. package/core/shared/registry-generated/std-grammar.ts +42 -20
  111. package/core/shared/soma-error.ts +36 -0
  112. package/core/shared/types/compile-port.types.ts +1 -1
  113. package/core/shared/types/data-config.types.ts +17 -17
  114. package/core/shared/types/engine.types.ts +0 -3
  115. package/core/shared/types/event.types.ts +1 -11
  116. package/core/shared/types/generation-error.types.ts +5 -1
  117. package/core/shared/types/host-assembly.types.ts +7 -1
  118. package/core/shared/types/manifest.types.ts +0 -3
  119. package/core/shared/types/region-scope.types.ts +5 -1
  120. package/core/shared/types/scope-manifest.types.ts +0 -2
  121. package/core/shared/types/style-config.types.ts +21 -21
  122. package/core/shared/types/ui-config.types.ts +4 -5
  123. package/core/shared/types/watcher.types.ts +1 -1
  124. package/dist/browser/runtime-bundle.manifest.json +11 -13
  125. package/dist/browser/soma-runtime.js +2567 -2696
  126. package/dist/core/index.cjs +5446 -5486
  127. package/dist/host-native/aot-builder.cjs +46 -1
  128. package/dist/host-native/native-server.cjs +4879 -4505
  129. package/dist/lsp/component-tree.cjs +5814 -7042
  130. package/dist/types/build/compiler/full-manifest-builder.d.ts +0 -2
  131. package/dist/types/build/compiler/page-closure.d.ts +21 -0
  132. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -4
  133. package/dist/types/build/compiler/soma-precompile.d.ts +1 -3
  134. package/dist/types/build/component-tree/artifact-codec.d.ts +0 -2
  135. package/dist/types/client/a11y/a11y-config.d.ts +2 -1
  136. package/dist/types/client/base/SomaHttpClient.d.ts +1 -1
  137. package/dist/types/client/base/SomaPageRootBase.d.ts +5 -0
  138. package/dist/types/client/base/defineSomaView.d.ts +46 -0
  139. package/dist/types/client/base/index.d.ts +2 -0
  140. package/dist/types/client/base/view-context.d.ts +136 -0
  141. package/dist/types/client/behavior/adapter-collection.d.ts +1 -1
  142. package/dist/types/client/compiler/manifest-compiler.d.ts +0 -3
  143. package/dist/types/client/component/component-definition.types.d.ts +2 -1
  144. package/dist/types/client/component/component-manager.d.ts +29 -0
  145. package/dist/types/client/data/data-object-resolver.d.ts +91 -31
  146. package/dist/types/client/data/format-config.d.ts +2 -1
  147. package/dist/types/client/engine/dom-renderer.d.ts +1 -2
  148. package/dist/types/client/engine/event-engine.d.ts +0 -7
  149. package/dist/types/client/engine/reactive-proxy.d.ts +11 -4
  150. package/dist/types/client/engine/runtime-builder.d.ts +0 -4
  151. package/dist/types/client/engine/soma-bootstrap.d.ts +44 -6
  152. package/dist/types/client/engine/style-binder.d.ts +8 -4
  153. package/dist/types/client/host-bridge/load-host-domain-class.d.ts +2 -1
  154. package/dist/types/client/mount/domain-rule.d.ts +2 -0
  155. package/dist/types/client/mount/mount-page.d.ts +2 -1
  156. package/dist/types/client/mount/types.d.ts +2 -0
  157. package/dist/types/client/parser/data-config-parser.d.ts +6 -5
  158. package/dist/types/client/parser/style-config-parser.d.ts +7 -3
  159. package/dist/types/client/parser/timer-parser.d.ts +5 -0
  160. package/dist/types/client/parser/ui-config-parser.d.ts +6 -2
  161. package/dist/types/client/runtime/SomaSnapshotStore.d.ts +2 -0
  162. package/dist/types/client/security/url-guard.d.ts +14 -0
  163. package/dist/types/client/validation/async-check-registry.d.ts +2 -1
  164. package/dist/types/client/validation/object-rules.d.ts +0 -5
  165. package/dist/types/index.d.ts +2 -7
  166. package/dist/types/inspect/runtime.d.ts +2 -1
  167. package/dist/types/server/api/dispatch-service-api.d.ts +5 -0
  168. package/dist/types/server/api/load-host-service.d.ts +1 -1
  169. package/dist/types/server/compile-port.d.ts +1 -1
  170. package/dist/types/server/host/host-assembly-entry.d.ts +1 -1
  171. package/dist/types/server/host/host-assembly.d.ts +2 -0
  172. package/dist/types/server/host/host-dir.d.ts +2 -0
  173. package/dist/types/server/host/invoke-host-request-hook.d.ts +10 -3
  174. package/dist/types/server/host/published-page-assets.d.ts +2 -1
  175. package/dist/types/server/host/resolve-host-request-hook.d.ts +18 -5
  176. package/dist/types/server/host/server-page-assets.d.ts +2 -1
  177. package/dist/types/server/infra/cache/ServerFileCache.d.ts +8 -0
  178. package/dist/types/server/registry/declaration-precompiler.d.ts +0 -1
  179. package/dist/types/server/registry/registry-error.d.ts +5 -1
  180. package/dist/types/server/registry/registry-file-lock.d.ts +30 -0
  181. package/dist/types/server/registry/request-body-limit.d.ts +3 -2
  182. package/dist/types/server/registry/validation/declaration-safety-scan.d.ts +3 -0
  183. package/dist/types/server/runtime-space/access-gate.d.ts +7 -0
  184. package/dist/types/server/runtime-space/bindings.d.ts +3 -2
  185. package/dist/types/server/runtime-space/dynamic-pages.d.ts +6 -1
  186. package/dist/types/server/runtime-space/errors.d.ts +1 -1
  187. package/dist/types/server/runtime-space/resolve.d.ts +2 -0
  188. package/dist/types/server/runtime-space/store.d.ts +8 -1
  189. package/dist/types/server/runtime-space/submit-steps.d.ts +2 -1
  190. package/dist/types/server/runtime-space/types.d.ts +3 -1
  191. package/dist/types/shared/component-tree-errors.d.ts +2 -1
  192. package/dist/types/shared/core-diagnostic-codes.d.ts +1 -1
  193. package/dist/types/shared/declaration-keys.d.ts +1 -1
  194. package/dist/types/shared/engines/engine-error.d.ts +2 -1
  195. package/dist/types/shared/generation-error.d.ts +2 -1
  196. package/dist/types/shared/pure-binding.d.ts +48 -0
  197. package/dist/types/shared/registry-generated/diagnostic-registry.d.ts +119 -158
  198. package/dist/types/shared/registry-generated/limits.d.ts +40 -10
  199. package/dist/types/shared/registry-generated/std-grammar-completion.d.ts +0 -30
  200. package/dist/types/shared/registry-generated/std-grammar-views.d.ts +97 -23
  201. package/dist/types/shared/registry-generated/std-grammar.d.ts +109 -241
  202. package/dist/types/shared/soma-error.d.ts +15 -0
  203. package/dist/types/shared/types/data-config.types.d.ts +14 -16
  204. package/dist/types/shared/types/engine.types.d.ts +0 -3
  205. package/dist/types/shared/types/event.types.d.ts +1 -7
  206. package/dist/types/shared/types/generation-error.types.d.ts +1 -1
  207. package/dist/types/shared/types/host-assembly.types.d.ts +2 -0
  208. package/dist/types/shared/types/manifest.types.d.ts +0 -3
  209. package/dist/types/shared/types/region-scope.types.d.ts +4 -1
  210. package/dist/types/shared/types/scope-manifest.types.d.ts +0 -2
  211. package/dist/types/shared/types/style-config.types.d.ts +17 -19
  212. package/dist/types/shared/types/ui-config.types.d.ts +4 -5
  213. package/host-native/bin/host-native.cjs +22 -1
  214. package/host-native/client/browser-entry.ts +21 -172
  215. package/host-native/src/aot-builder.ts +52 -0
  216. package/host-native/src/host-prepare.ts +39 -5
  217. package/host-native/src/manifest-http.ts +2 -3
  218. package/host-native/src/native-server.ts +812 -174
  219. package/host-native/src/page-http.ts +3 -3
  220. package/host-native/src/public-packages.cjs +0 -1
  221. package/host-native/src/registry-handler.ts +12 -5
  222. package/host-native/src/static-file.ts +203 -53
  223. package/package.json +3 -2
  224. package/core/client/engine/step-runner.ts +0 -212
  225. package/core/client/engine/trigger-engine.ts +0 -55
  226. package/core/client/format/zoned.ts +0 -10
  227. package/core/client/parser/step-parser.ts +0 -359
  228. package/core/client/parser/trigger-parser.ts +0 -90
  229. package/core/client/parser/value-lang.ts +0 -340
  230. package/core/client/time/instant.ts +0 -2
  231. package/core/shared/calc/coerce.ts +0 -2
  232. package/core/shared/calc/errors.ts +0 -40
  233. package/core/shared/calc/evaluator.ts +0 -113
  234. package/core/shared/calc/index.ts +0 -11
  235. package/core/shared/calc/lexer.ts +0 -189
  236. package/core/shared/calc/parser.ts +0 -193
  237. package/core/shared/calc/typer.ts +0 -171
  238. package/core/shared/date-parts.ts +0 -2
  239. package/core/shared/show-when.ts +0 -77
  240. package/core/shared/types/step.types.ts +0 -91
  241. package/core/shared/types/trigger.types.ts +0 -14
  242. package/dist/types/client/engine/step-runner.d.ts +0 -42
  243. package/dist/types/client/engine/trigger-engine.d.ts +0 -16
  244. package/dist/types/client/format/zoned.d.ts +0 -1
  245. package/dist/types/client/parser/step-parser.d.ts +0 -23
  246. package/dist/types/client/parser/trigger-parser.d.ts +0 -13
  247. package/dist/types/client/parser/value-lang.d.ts +0 -63
  248. package/dist/types/client/time/instant.d.ts +0 -1
  249. package/dist/types/shared/calc/coerce.d.ts +0 -1
  250. package/dist/types/shared/calc/errors.d.ts +0 -14
  251. package/dist/types/shared/calc/evaluator.d.ts +0 -2
  252. package/dist/types/shared/calc/index.d.ts +0 -6
  253. package/dist/types/shared/calc/lexer.d.ts +0 -19
  254. package/dist/types/shared/calc/parser.d.ts +0 -43
  255. package/dist/types/shared/calc/typer.d.ts +0 -11
  256. package/dist/types/shared/date-parts.d.ts +0 -1
  257. package/dist/types/shared/show-when.d.ts +0 -21
  258. package/dist/types/shared/types/step.types.d.ts +0 -76
  259. package/dist/types/shared/types/trigger.types.d.ts +0 -12
@@ -1,23 +1,14 @@
1
1
  // core/client/data/data-object-resolver.ts — 数据对象解析器(数据对象层运行时核心)
2
2
  // 职责:按 page 块 `data:`(Soma Data)声明取数——解析 `$` 引用构建对象依赖 DAG → 拓扑序取数
3
- // (无依赖来源并发 Promise.all)→ into 聚合/根浅合并 → transform 走管道注册表补派生字段;
3
+ // (无依赖来源并发 Promise.all)→ into 聚合/根浅合并(页面不派生字段,只收接口给的数据);
4
4
  // 以及写通道(submit / remove / orderMove)与字段字典校验。
5
5
  // 纯客户端实现,http 服务依赖注入;产物 { objects, dicts } 由 bootstrap 挂到 page.data。
6
6
 
7
- import {
8
- defaultPipeRegistry,
9
- hasPipes,
10
- parsePipedValue,
11
- SomaPipeError,
12
- type SomaPipeContext,
13
- type SomaPipeRegistry,
14
- } from '../pipes/pipe-registry';
7
+ import { instantOf, isCivilDateText } from 'soma-foundation/values';
15
8
  import { unwrapHostPayload } from './collection-payload';
16
9
  import { readQueryParam } from '../infra/router/router-path';
17
10
  import {
18
- normalizeDataPipeValue,
19
11
  parseDataRef,
20
- SomaDataConfigError,
21
12
  } from '../parser/data-config-parser';
22
13
  import type {
23
14
  SomaCommandResult,
@@ -27,6 +18,8 @@ import type {
27
18
  SomaDataObjectConfig,
28
19
  SomaDataFieldConfig,
29
20
  SomaDataPort,
21
+ SomaDataReadState,
22
+ SomaDataReadStatus,
30
23
  SomaDataSourceConfig,
31
24
  SomaDataSubmitResult,
32
25
  SomaSubmitOptions,
@@ -43,11 +36,9 @@ import type { SomaFeedbackSituation, SomaWriteFeedbackMode } from '../../shared/
43
36
  import type { SomaWriteActionName } from '../../shared/types/write-outcome-view.types';
44
37
  import { parseUserRef, resolveUserRefs, type SomaIdentityPort, type SomaUserRefDiagnostic } from '../infra/identity/identity-port';
45
38
  import { decorateFailure, decorateSuccess, readConcurrencyToken, readConflictState } from './write-outcome';
46
- import type { SomaNamedPredicates } from '../../shared/predicates';
47
39
  import { envelopeFailureOf } from './envelope-failure';
48
40
  import { createWriteOutcomeStore, type SomaWriteOutcomeStore } from './write-outcome-store';
49
41
  import type { SomaObservedFetch } from '../../shared/types/observation.types';
50
- import { collectCalcRefs, evaluateCalc, parseCalc, type CalcAst } from '../../shared/calc';
51
42
 
52
43
  // ─── 错误类 ───────────────────────────────────────────────────────────────────
53
44
 
@@ -86,10 +77,6 @@ export interface SomaDataResolverOptions {
86
77
  query?: Record<string, string> | ((key: string) => string);
87
78
  /** $page 读取器:Domain 实例(或返回实例的函数,取最新代理引用) */
88
79
  page?: object | (() => object | null | undefined);
89
- /** 格式化管道注册表(缺省为内置管道集;Host 自定义管道经 bootstrap 传入) */
90
- pipes?: SomaPipeRegistry;
91
- /** locale 表提供者(校验文案词条等本地化取值) */
92
- locale?: () => Record<string, unknown> | undefined;
93
80
  /**
94
81
  * 当前身份只读端口(`services.identity`):请求参数里的 `$user.id` / `$user.team` 经它解析。
95
82
  * 缺省(未接入)= 没有任何身份字段:含 `$user.*` 引用的请求按「无结果」处理(不发请求),从不当成「不限制」。
@@ -102,8 +89,17 @@ export interface SomaDataResolverOptions {
102
89
  onDiagnostic?: (diagnostic: SomaCoreDiagnostic) => void;
103
90
  /** 取数观测钩子:每发一次读请求报一条(对象名、请求参数);抛错不影响取数 */
104
91
  onFetch?: (entry: SomaObservedFetch) => void;
105
- /** 重取完成钩子:reload(含写入后自动重取)写回 objects 后触发,供宿主刷新页面绑定与自治组件 */
92
+ /**
93
+ * 重取结束钩子:reload(含写入后自动重取)写回 objects 后触发,供宿主刷新页面绑定与自治组件。
94
+ * 非静默点名重取失败(或部分成功后失败)时也会触发一次:此时对象表里的数据可能未变、读状态已变(error / 已恢复),宿主据此重画以退出加载态。
95
+ */
106
96
  onReload?: (objects: Record<string, unknown>) => void;
97
+ /**
98
+ * 显式重新读取开始钩子:`reload(names)` 把对应对象读状态置为 loading(旧数据仍在对象上)后、等待网络前同步调一次,
99
+ * 参数为进入读取的对象名。首次解析、无参 reload、`silent` 重取(轮询 / 订阅推送)不触发;抛错被吞掉并记日志。
100
+ * 与 `onReload` 配对:开始通知过之后,无论成功还是失败,结束时宿主都会收到 `onReload`。
101
+ */
102
+ onReadStart?: (names: readonly string[]) => void;
107
103
  }
108
104
 
109
105
  /** 解析产物:数据对象 + 字段字典 */
@@ -295,6 +291,165 @@ function commandRefusalOf(data: unknown): string | null {
295
291
  return '服务端拒绝了该操作';
296
292
  }
297
293
 
294
+ const HTTP_UNAUTHORIZED = 401;
295
+ const HTTP_FORBIDDEN = 403;
296
+
297
+ /** 提取读错误中的 HTTP 状态码 */
298
+ function extractReadErrorStatus(error: unknown): number | undefined {
299
+ const direct = commandStatusOf(error);
300
+ if (direct !== undefined) return direct;
301
+ const msg = error instanceof Error ? error.message : typeof error === "string" ? error : "";
302
+ const split = splitHttpMessage(msg);
303
+ if (split !== null) return split.status;
304
+ const m = /\bHTTP\s*(\d{3})\b/i.exec(msg) ?? /\bstatus(?:\s*code)?[:\s]+(\d{3})\b/i.exec(msg);
305
+ if (m !== null) return Number(m[1]);
306
+ if (/\b401\b/.test(msg)) return HTTP_UNAUTHORIZED;
307
+ if (/\b403\b/.test(msg)) return HTTP_FORBIDDEN;
308
+ return undefined;
309
+ }
310
+
311
+ /** 判断读错误是否为 401/403 无权限 */
312
+ function isForbiddenReadError(error: unknown, status?: number): boolean {
313
+ if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) return true;
314
+ const msg = error instanceof Error ? error.message : typeof error === "string" ? error : "";
315
+ return /\b(401|403)\b|\b(forbidden|unauthorized)\b|无权限|未授权/i.test(msg);
316
+ }
317
+
318
+ /** 提取读错误的可读文案 */
319
+ function extractReadErrorMessage(error: unknown, status?: number): string {
320
+ const payload = extractErrorPayload(error);
321
+ if (payload.message && payload.message.trim() !== "") return payload.message.trim();
322
+ const raw = error instanceof Error ? error.message : typeof error === "string" ? error : "";
323
+ const split = splitHttpMessage(raw);
324
+ if (split !== null && split.text !== "") return split.text;
325
+ if (raw.trim() !== "") return raw.trim();
326
+ return status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN ? "无权限访问" : "数据加载失败";
327
+ }
328
+
329
+ /**
330
+ * 在数据对象(普通对象)上以非枚举属性挂载标准读状态字段,保持向后兼容 Object.keys / JSON.stringify / toEqual,
331
+ * 同时让组件与展示对象可直接读取 readState / loading / ready / errorMessage / errorStatus / retry。
332
+ */
333
+ const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):?[0-5]\d)?)?$/;
334
+
335
+ /**
336
+ * 校验 date / datetime 字段值是否为真实公历日历日(支持 YYYY-MM-DD 以及后端返回的 ISO 带时间字符串,如 2026-03-15T08:00:00Z / 2026-03-15 12:30:00)。
337
+ * 复用 soma-foundation/values 的 isCivilDateText 与 instantOf,真实拦截 2026-02-31、2026-04-31、2025-02-29 等不存在的非法日历日与越界时间。
338
+ */
339
+ export function isValidCalendarDate(value: unknown): boolean {
340
+ if (typeof value !== "string") return false;
341
+ const trimmed = value.trim();
342
+ if (!CALENDAR_DATE_RE.test(trimmed)) return false;
343
+ return isCivilDateText(trimmed.slice(0, 10)) && instantOf(trimmed) !== undefined;
344
+ }
345
+
346
+ function checkCalendarDateField(field: SomaDataFieldConfig, value: unknown): RuleFailure | null {
347
+ if (field.type !== "date" && field.type !== "datetime") return null;
348
+ if (isValidCalendarDate(value)) return null;
349
+ const label = field.name || "日期";
350
+ return {
351
+ rule: "format",
352
+ message: `${label}不是合法的公历日期(收到 "${String(value)}")`,
353
+ };
354
+ }
355
+
356
+ /** 读状态各字段的不可枚举属性描述(挂到数据对象与错误占位对象上共用) */
357
+ function readStatusProps(status: SomaDataReadStatus): PropertyDescriptorMap {
358
+ const hidden = (value: unknown): PropertyDescriptor => ({ value, enumerable: false, configurable: true, writable: true });
359
+ return {
360
+ readState: hidden(status.readState),
361
+ read_state: hidden(status.readState),
362
+ loading: hidden(status.loading),
363
+ ready: hidden(status.ready),
364
+ errorMessage: hidden(status.errorMessage),
365
+ errorStatus: hidden(status.errorStatus),
366
+ retry: hidden(status.retry),
367
+ };
368
+ }
369
+
370
+ /**
371
+ * 把读状态以不可枚举属性挂到目标对象上(目标不是普通对象则不动)。
372
+ * 失败状态(error / forbidden)另有两处补充,都只落在「本函数自己写的」不可枚举属性上,绝不改动真实数据(可枚举键):
373
+ * - 目标自身的 `error` 文案:没有同名键才写;已有的是本函数此前写的不可枚举属性则随本次失败更新;可枚举的真实字段不动。
374
+ * - `result`(及失败来源的 `into`)键的错误占位对象:没有该键才新建;已有的是此前补的不可枚举占位则更新其中各字段(含错误文案);可枚举的真实数据不动。
375
+ * 非失败状态(loading / ready)不清、不改已有占位:读取中占位保留,由界面按读状态判断。
376
+ * 目标是冻结 / 不可扩展对象时挂不上,按「挂不上」处理(直接返回、不抛错),读状态以 `getObjectReadStatus` 为准;
377
+ * 错误占位里已有的 `result` / into 值若不可扩展,同样不写。
378
+ */
379
+ export function attachReadStatusToObject(
380
+ target: unknown,
381
+ status: SomaDataReadStatus,
382
+ failedInto?: string,
383
+ ): void {
384
+ if (!isPlainObject(target) || !Object.isExtensible(target)) return;
385
+ const isErr = status.readState === "error" || status.readState === "forbidden";
386
+ const errText = isErr
387
+ ? (status.errorMessage ?? (status.readState === "forbidden" ? "无权限访问" : "数据加载失败"))
388
+ : undefined;
389
+ const ownError = Object.getOwnPropertyDescriptor(target, "error");
390
+ const writeError = errText !== undefined && (ownError ? ownError.enumerable === false : !("error" in target));
391
+ Object.defineProperties(target, {
392
+ readState: { value: status.readState, enumerable: false, configurable: true, writable: true },
393
+ read_state: { value: status.readState, enumerable: false, configurable: true, writable: true },
394
+ loading: { value: status.loading, enumerable: false, configurable: true, writable: true },
395
+ ready: { value: status.ready, enumerable: false, configurable: true, writable: true },
396
+ errorMessage: { value: status.errorMessage, enumerable: false, configurable: true, writable: true },
397
+ errorStatus: { value: status.errorStatus, enumerable: false, configurable: true, writable: true },
398
+ retry: { value: status.retry, enumerable: false, configurable: true, writable: true },
399
+ ...(writeError
400
+ ? { error: { value: errText, enumerable: false, configurable: true, writable: true } }
401
+ : {}),
402
+ });
403
+ const holderKeys = new Set<string>();
404
+ if (failedInto !== undefined && failedInto !== "") holderKeys.add(failedInto);
405
+ if (isErr) holderKeys.add("result");
406
+ for (const holderKey of holderKeys) {
407
+ const holderErr = errText ?? (status.readState === "forbidden" ? "无权限访问" : "数据加载失败");
408
+ const own = Object.getOwnPropertyDescriptor(target, holderKey);
409
+ if (own) {
410
+ // 已有键:不可枚举的是此前补的占位,失败时按本次刷新;可枚举的是真实数据,照旧跳过
411
+ if (own.enumerable !== false || !isErr || typeof own.value !== "object" || own.value === null || !Object.isExtensible(own.value)) continue;
412
+ Object.defineProperties(own.value, {
413
+ error: { value: holderErr, enumerable: false, configurable: true, writable: true },
414
+ ...readStatusProps(status),
415
+ });
416
+ continue;
417
+ }
418
+ if (holderKey in target) continue;
419
+ const intoHolder: Record<string, unknown> = {};
420
+ Object.defineProperties(intoHolder, {
421
+ error: { value: holderErr, enumerable: false, configurable: true, writable: true },
422
+ ...readStatusProps(status),
423
+ });
424
+ Object.defineProperty(target, holderKey, {
425
+ value: intoHolder,
426
+ enumerable: false,
427
+ configurable: true,
428
+ writable: true,
429
+ });
430
+ }
431
+ }
432
+
433
+ /**
434
+ * 读出「对象上实际显示着」的读状态:目标是普通对象且自身有不可枚举的 `readState`(本模块挂上去的)时,
435
+ * 用它身上的字段组成读状态;否则返回 undefined(没挂过 / 挂不上)。`retry` 不是函数时用 `fallbackRetry`。
436
+ */
437
+ function shownReadStatusOf(target: unknown, fallbackRetry: () => Promise<void>): SomaDataReadStatus | undefined {
438
+ if (!isPlainObject(target)) return undefined;
439
+ const own = Object.getOwnPropertyDescriptor(target, "readState");
440
+ if (!own || own.enumerable !== false) return undefined;
441
+ const view = target as Record<string, unknown>;
442
+ const retry = view.retry;
443
+ return {
444
+ readState: view.readState as SomaDataReadState,
445
+ loading: view.loading === true,
446
+ ready: view.ready === true,
447
+ errorMessage: typeof view.errorMessage === "string" ? view.errorMessage : undefined,
448
+ errorStatus: typeof view.errorStatus === "number" ? view.errorStatus : undefined,
449
+ retry: typeof retry === "function" ? (retry as () => Promise<void>) : fallbackRetry,
450
+ };
451
+ }
452
+
298
453
  // ─── 解析器 ──────────────────────────────────────────────────────────────────
299
454
 
300
455
  /** 未接入身份端口时的替身:什么字段都没有(含 `$user.*` 的请求因此按无结果处理) */
@@ -305,13 +460,33 @@ export class SomaDataObjectResolver {
305
460
  private readonly http: SomaDataHttpLike;
306
461
  private readonly queryOption?: Record<string, string> | ((key: string) => string);
307
462
  private readonly pageOption?: object | (() => object | null | undefined);
308
- private readonly pipes: SomaPipeRegistry;
309
- private readonly localeProvider?: () => Record<string, unknown> | undefined;
310
463
  private readonly identityOption?: SomaIdentityPort;
311
464
  private readonly onDiagnostic?: (diagnostic: SomaCoreDiagnostic) => void;
312
465
  private readonly onFetch?: (entry: SomaObservedFetch) => void;
313
466
  private readonly onReload?: (objects: Record<string, unknown>) => void;
467
+ private readonly onReadStart?: (names: readonly string[]) => void;
314
468
  private disposed = false;
469
+ /** `onReadStart` 回调正在执行的嵌套深度;> 0 时再进入的通知改走微任务(防同步递归) */
470
+ private readStartDepth = 0;
471
+ /**
472
+ * 已告知宿主「在读取中」(`onReadStart` 带过)、且宿主在该对象落定之后还没收到过 `onReload` 的对象名。
473
+ * 每次 `onReload` 之后只移出读状态已不是 loading 的对象,仍在读的保留;据此保证开始通知与结束通知按对象配对,
474
+ * 不论让它落定的是哪一轮重取(含静默接管者)。
475
+ */
476
+ private readonly notifiedReading = new Set<string>();
477
+ /**
478
+ * 仍被某一轮点名重取持有的「预标」loading 状态:持有它的那一轮还没结束,之后会落定它(或在结束时恢复它)。
479
+ * 轮次结束时移出;据此区分「他轮仍会落定的预标」与「已失效的预标」。
480
+ */
481
+ private readonly liveMarks = new Set<SomaDataReadStatus>();
482
+ /**
483
+ * 每个预标状态在标记时的来源(标记前状态表里的状态 / 对象上实际挂着的状态):
484
+ * 预标已失效时,沿它记下的来源回到最近的落定状态,不停在失效的 loading 上。
485
+ */
486
+ private readonly markOrigins = new WeakMap<SomaDataReadStatus, {
487
+ prev: SomaDataReadStatus | undefined;
488
+ shown: SomaDataReadStatus | undefined;
489
+ }>();
315
490
 
316
491
  /** 拓扑执行过程中已解析的对象(供 `$<对象>.<字段>` 引用读取) */
317
492
  private objects: Record<string, unknown> = {};
@@ -321,29 +496,11 @@ export class SomaDataObjectResolver {
321
496
  this.http = options.http;
322
497
  this.queryOption = options.query;
323
498
  this.pageOption = options.page;
324
- this.pipes = options.pipes ?? defaultPipeRegistry;
325
- this.localeProvider = options.locale;
326
499
  this.identityOption = options.identity;
327
500
  this.onDiagnostic = options.onDiagnostic;
328
501
  this.onFetch = options.onFetch;
329
502
  this.onReload = options.onReload;
330
-
331
- // 声明期白名单校验:transform 引用了未注册的管道名 → 声明错误(fail fast,不吞)
332
- for (const decl of Object.values(config.objects)) {
333
- for (const [key, rawValue] of Object.entries(decl.transform ?? {})) {
334
- const normalized = normalizeDataPipeValue(rawValue);
335
- if (!hasPipes(normalized)) continue;
336
- try {
337
- const parsed = parsePipedValue(normalized, () => false);
338
- this.pipes.assertKnown(parsed.pipes, `data.${decl.name}.transform.${key}`);
339
- } catch (error) {
340
- if (error instanceof SomaPipeError) {
341
- throw new SomaDataConfigError(error.message, `data.${decl.name}.transform.${key}`);
342
- }
343
- throw error;
344
- }
345
- }
346
- }
503
+ this.onReadStart = options.onReadStart;
347
504
  }
348
505
 
349
506
  /**
@@ -359,9 +516,12 @@ export class SomaDataObjectResolver {
359
516
  await Promise.all(
360
517
  layer.map(async (name) => {
361
518
  this.assertActive();
362
- const value = await this.resolveObject(this.config.objects[name]);
519
+ const seq = this.nextFetchSeq(name);
520
+ const value = await this.resolveObject(this.config.objects[name], false, seq);
363
521
  this.assertActive();
364
- this.objects[name] = value;
522
+ if (seq === this.getFetchSeq(name)) {
523
+ this.objects[name] = value;
524
+ }
365
525
  }),
366
526
  );
367
527
  }
@@ -379,17 +539,74 @@ export class SomaDataObjectResolver {
379
539
  /** 因必填参数缺而跳过过请求的对象(`from[].require`) */
380
540
  private readonly idleObjects = new Set<string>();
381
541
 
542
+ /** 每个数据对象的完整读状态表 */
543
+ private readonly readStatuses = new Map<string, SomaDataReadStatus>();
544
+
545
+ /** 单调递增的取数序号(防慢轮询覆盖写后最新数据) */
546
+ private readonly objectFetchSeqs = new Map<string, number>();
547
+
548
+ nextFetchSeq(name: string): number {
549
+ const next = (this.objectFetchSeqs.get(name) ?? 0) + 1;
550
+ this.objectFetchSeqs.set(name, next);
551
+ return next;
552
+ }
553
+
554
+ getFetchSeq(name: string): number {
555
+ return this.objectFetchSeqs.get(name) ?? 0;
556
+ }
557
+
382
558
  /** 对象读状态:`idle` = 有来源因必填参数缺被跳过(不是错误);未声明的对象返回 undefined */
383
559
  getObjectStatus(name: string): 'idle' | 'ready' | undefined {
384
560
  if (this.disposed || !Object.hasOwn(this.config.objects, name)) return undefined;
385
561
  return this.idleObjects.has(name) ? 'idle' : 'ready';
386
562
  }
387
563
 
564
+ /** 对象完整读状态(含 idle / loading / ready / error / forbidden / partial、错误信息与重试回调) */
565
+ getObjectReadStatus(name: string): SomaDataReadStatus | undefined {
566
+ if (this.disposed || !Object.hasOwn(this.config.objects, name)) return undefined;
567
+ const hit = this.readStatuses.get(name);
568
+ if (hit !== undefined) return hit;
569
+ const isIdle = this.idleObjects.has(name);
570
+ return {
571
+ readState: isIdle ? 'idle' : 'ready',
572
+ loading: false,
573
+ ready: !isIdle,
574
+ retry: () => this.reload([name]),
575
+ };
576
+ }
577
+
578
+ /** 获取对象完整读状态(getObjectReadStatus 的别名) */
579
+ readStatus(name: string): SomaDataReadStatus | undefined {
580
+ return this.getObjectReadStatus(name);
581
+ }
582
+
388
583
  /** 已解析对象的只读视图(data 端口的 getObject) */
389
584
  getObject(name: string): unknown {
390
585
  return this.disposed ? undefined : this.objects[name];
391
586
  }
392
587
 
588
+ /**
589
+ * 首次读取的待定占位:数据层从一开始就暴露「读取中」,不让「还没到」(undefined)与「到了但为空」混淆。
590
+ * 范围:有 `from` 的声明对象中、`existing` 里还没有值的那些(写入型对象无 from,不建占位)。
591
+ * 每个占位是空对象 `{}`(无可枚举键),挂 loading 读状态,并把读状态表置为同一个 loading 状态;
592
+ * 真实数据到达后由整体替换覆盖,占位随之作废。返回 `{ 对象名: 占位 }`。
593
+ */
594
+ initialPlaceholders(existing: Readonly<Record<string, unknown>> = {}): Record<string, unknown> {
595
+ const placeholders: Record<string, unknown> = {};
596
+ if (this.disposed) return placeholders;
597
+ for (const decl of Object.values(this.config.objects)) {
598
+ if (decl.from.length === 0 || existing[decl.name] !== undefined) continue;
599
+ const loadingStatus: SomaDataReadStatus = {
600
+ readState: 'loading', loading: true, ready: false, retry: () => this.reload([decl.name]),
601
+ };
602
+ const placeholder: Record<string, unknown> = {};
603
+ attachReadStatusToObject(placeholder, loadingStatus);
604
+ this.readStatuses.set(decl.name, loadingStatus);
605
+ placeholders[decl.name] = placeholder;
606
+ }
607
+ return placeholders;
608
+ }
609
+
393
610
  /** 字段字典(data 端口的 getDict);无字典时返回空表而不是 undefined */
394
611
  getDict(name: string): Record<string, SomaDataFieldConfig> {
395
612
  return this.disposed ? {} : this.config.objects[name]?.fields ?? {};
@@ -482,22 +699,23 @@ export class SomaDataObjectResolver {
482
699
  return { ok: false, message: `数据对象 "${name}" 没有声明 write 段(它是只读对象)` };
483
700
  }
484
701
 
485
- // 校验时机:声明了 validate_on 且含 submit 时,core 先按字典校验,不过不发请求
486
- if (write.validate_on?.includes('submit') && isPlainObject(model)) {
487
- const fieldErrors = this.fieldErrorsOf(decl, model);
488
- if (Object.keys(fieldErrors).length > 0) {
489
- return { ok: false, message: `数据对象 "${name}" 的提交未通过校验`, fieldErrors };
702
+ // 校验时机:声明了 validate_on 且含 submit 时,core 先按字典校验;
703
+ // 同时对字典里的 date / datetime 字段强制执行真实公历日历合法性校验,拦截 2026-02-31 等非法日期
704
+ if (isPlainObject(model)) {
705
+ const validateAll = write.validate_on?.includes('submit') === true;
706
+ const dateKeys = Object.keys(decl.fields ?? {}).filter((k) => {
707
+ const t = decl.fields?.[k]?.type;
708
+ return t === 'date' || t === 'datetime';
709
+ });
710
+ if (validateAll || dateKeys.length > 0) {
711
+ const fieldErrors = validateAll
712
+ ? this.fieldErrorsOf(decl, model)
713
+ : this.hardMessagesOf(this.gradedFailuresOf(decl, model, dateKeys));
714
+ if (Object.keys(fieldErrors).length > 0) {
715
+ return { ok: false, message: `数据对象 "${name}" 的提交未通过校验`, fieldErrors };
716
+ }
490
717
  }
491
718
  }
492
- // 派生字段是算出来的,不能以“成功但没有写入”的形式被静默过滤
493
- const derived = Object.keys(model).filter((key) => (decl.fields ?? {})[key]?.calc !== undefined);
494
- if (derived.length > 0) {
495
- return {
496
- ok: false,
497
- message: `派生字段不能提交:${derived.join(' / ')}`
498
- + `——它们由 calc 算出(改上游字段即可),写它们没有落点`,
499
- };
500
- }
501
719
  const prepared = this.prepareWrite(decl, model, mode ?? this.inferWriteMode(name, write), identityField);
502
720
  if (!prepared.ok) return prepared;
503
721
  try {
@@ -794,15 +1012,17 @@ export class SomaDataObjectResolver {
794
1012
  // ─── 校验 ────────────────────────────────────────────────────────────────
795
1013
 
796
1014
  /** 按字典校验一份表单值,返回 字段 → 全部失败(含非 hard 档) */
797
- gradedFailuresOf(decl: SomaDataObjectConfig, model: Readonly<Record<string, unknown>>): Record<string, RuleFailure[]> {
798
- const current = this.objects[decl.name];
799
- const context = { ...(isPlainObject(current) ? current : {}), ...model };
1015
+ gradedFailuresOf(
1016
+ decl: SomaDataObjectConfig,
1017
+ model: Readonly<Record<string, unknown>>,
1018
+ onlyKeys?: readonly string[],
1019
+ ): Record<string, RuleFailure[]> {
800
1020
  const fields = decl.fields ?? {};
801
- const keys = Object.keys(fields).filter((key) => decl.write?.only === undefined || decl.write.only.includes(key));
1021
+ const baseKeys = onlyKeys ?? Object.keys(fields);
1022
+ const keys = baseKeys.filter((key) => decl.write?.only === undefined || decl.write.only.includes(key));
802
1023
  return validateObjectRecordGraded(fields, model, {
803
1024
  keys,
804
- context,
805
- ...(decl.predicates !== undefined ? { named: decl.predicates as SomaNamedPredicates } : {}),
1025
+ protocolCheck: checkCalendarDateField,
806
1026
  });
807
1027
  }
808
1028
 
@@ -822,10 +1042,7 @@ export class SomaDataObjectResolver {
822
1042
  }
823
1043
 
824
1044
  failureMessage(failure: RuleFailure): string {
825
- if (failure.message !== undefined) return failure.message;
826
- const key = RULE_MESSAGE_KEYS[failure.rule];
827
- const text = this.localeProvider?.()?.[key];
828
- return typeof text === 'string' ? text : key;
1045
+ return failure.message ?? RULE_MESSAGE_KEYS[failure.rule];
829
1046
  }
830
1047
 
831
1048
  // ─── 重取 ────────────────────────────────────────────────────────────────
@@ -834,7 +1051,7 @@ export class SomaDataObjectResolver {
834
1051
  async reloadAfterWrite(name: string, write: SomaDataWriteConfig): Promise<void> {
835
1052
  if (!write.reload) return;
836
1053
  if (write.reload === 'all') {
837
- await this.resolve();
1054
+ await this.reload();
838
1055
  return;
839
1056
  }
840
1057
  if (write.reload === 'self') {
@@ -844,27 +1061,139 @@ export class SomaDataObjectResolver {
844
1061
  await this.reload([...write.reload]);
845
1062
  }
846
1063
 
847
- /** 手动重取(data 端口的 reload);不给名字时重取全部 */
848
- async reload(names?: string[]): Promise<void> {
1064
+ /**
1065
+ * 手动重取(data 端口的 reload);不给名字时重取全部。
1066
+ * 点名重取时旧数据留在对象上,读状态先置 loading 并通知 `onReadStart`;无参重取会换掉整张对象表(旧数据不在当前表上),不通知。
1067
+ * `options.silent`:后台重取(轮询 / 订阅推送 / 展示层重取入口)不打扰界面:不通知读取开始、不把 loading 挂到当前数据对象上,
1068
+ * 失败时也不把失败状态挂到当前数据对象上(读状态查询接口 `getObjectReadStatus` 照常反映 loading / 失败);
1069
+ * 例外:该对象此前已告知宿主在读取中(界面正显示读取中)时,失败状态照常挂上,并按下条规则补一次 `onReload` 让界面退出读取中。
1070
+ * `onReload`(重取结束,请宿主重读对象表)触发规则:无参重取结束;点名重取结束(正常或抛错)时,本次有对象写回,
1071
+ * 或本次对象里有「已告知读取开始、且读状态已不是 loading」的对象(对象仍在 loading 说明别的一轮在读它,留给让它落定的那一轮)。
1072
+ * 抛错路径上的回调抛错只记日志、不盖原错误。每次通知后只把已落定的对象移出「已告知」集合。
1073
+ * 未被处理到的对象恢复时:状态表回到标记前的值,对象上回到标记前实际挂着的状态(静默失败只进状态表、不挂对象,不会因本次中止冒出来)。
1074
+ */
1075
+ async reload(names?: string[], options?: { silent?: boolean }): Promise<void> {
849
1076
  this.assertActive();
850
1077
  if (!names || names.length === 0) {
851
1078
  await this.resolve();
852
- if (!this.disposed) this.onReload?.(this.objects);
1079
+ if (!this.disposed) this.notifyReload();
853
1080
  return;
854
1081
  }
855
1082
  let changed = false;
856
- for (const name of [...names, ...this.requireDependentsOf(names)]) {
857
- const decl = this.config.objects[name];
858
- if (!decl) continue;
859
- // 写入型对象(无 from)没有可重取的来源:跳过,不报错、不覆盖当前值
860
- if (decl.from.length === 0) continue;
861
- this.assertActive();
862
- const value = await this.resolveObject(decl, true);
863
- this.assertActive();
864
- this.objects[name] = value;
865
- changed = true;
1083
+ const targets = [...names, ...this.requireDependentsOf(names)];
1084
+ // 本次提前标成 loading 的对象:标记前的读状态 + 本次挂上的 loading 状态(用于结束时恢复未被处理到的对象)
1085
+ // prev = 状态表里标记前的状态;shown = 标记前对象上实际挂着的状态(静默失败只进表、不挂对象,两者可能不同)
1086
+ const premarked = new Map<string, {
1087
+ prev: SomaDataReadStatus | undefined;
1088
+ shown: SomaDataReadStatus | undefined;
1089
+ mark: SomaDataReadStatus | undefined;
1090
+ }>();
1091
+ const started = new Set<string>();
1092
+ if (options?.silent !== true && this.onReadStart) {
1093
+ const reading = targets.filter((name) => (this.config.objects[name]?.from.length ?? 0) > 0);
1094
+ if (reading.length > 0) {
1095
+ for (const name of reading) {
1096
+ if (premarked.has(name)) continue;
1097
+ const prev = this.readStatuses.get(name);
1098
+ const shown = shownReadStatusOf(this.objects[name], () => this.reload([name]));
1099
+ this.markReadLoading(this.config.objects[name]);
1100
+ const mark = this.readStatuses.get(name);
1101
+ premarked.set(name, { prev, shown, mark });
1102
+ if (mark) {
1103
+ this.markOrigins.set(mark, { prev, shown });
1104
+ this.liveMarks.add(mark);
1105
+ }
1106
+ }
1107
+ for (const name of reading) this.notifiedReading.add(name);
1108
+ // 回调链(refreshAll → 组件)可能同步再发起非静默点名重取:回调执行期间再进入的那一轮改在微任务里通知,
1109
+ // 避免 onReadStart → reload → onReadStart 同步递归;其读状态标记已在上面同步挂好,界面语义不丢。
1110
+ const notifyStart = this.onReadStart;
1111
+ const deliver = (): void => {
1112
+ this.readStartDepth += 1;
1113
+ try {
1114
+ notifyStart(reading);
1115
+ } catch (error) {
1116
+ console.error('[soma-core][数据] onReadStart 回调抛错(已忽略,不影响读取):', error);
1117
+ } finally {
1118
+ this.readStartDepth -= 1;
1119
+ }
1120
+ };
1121
+ if (this.readStartDepth > 0) {
1122
+ queueMicrotask(() => {
1123
+ if (this.disposed) return;
1124
+ deliver();
1125
+ });
1126
+ } else {
1127
+ deliver();
1128
+ }
1129
+ }
1130
+ }
1131
+ let completed = false;
1132
+ try {
1133
+ for (const name of targets) {
1134
+ const decl = this.config.objects[name];
1135
+ if (!decl) continue;
1136
+ // 写入型对象(无 from)没有可重取的来源:跳过,不报错、不覆盖当前值
1137
+ if (decl.from.length === 0) continue;
1138
+ this.assertActive();
1139
+ const seq = this.nextFetchSeq(name);
1140
+ started.add(name);
1141
+ try {
1142
+ const value = await this.resolveObject(decl, true, seq, options?.silent === true);
1143
+ this.assertActive();
1144
+ if (seq === this.getFetchSeq(name)) {
1145
+ this.objects[name] = value;
1146
+ changed = true;
1147
+ }
1148
+ } catch (error) {
1149
+ if (seq === this.getFetchSeq(name)) {
1150
+ throw error;
1151
+ }
1152
+ }
1153
+ }
1154
+ completed = true;
1155
+ } finally {
1156
+ // 未被实际处理到的对象(前面的对象抛错 / 被销毁中止):恢复为标记前的读状态,不能永久停在本次设的 loading。
1157
+ // 以「当前状态仍是本次挂的那个 loading 对象」为准:已被更新一轮接管或落定的对象不覆盖。
1158
+ // 状态表按 prev 恢复;对象上恢复成标记前它实际挂着的状态(shown),只进了状态表的静默失败不会因为这次中止冒出来。
1159
+ // 本轮结束,不再持有自己的预标(无论是否需要恢复)。
1160
+ // 恢复来源(prev / shown)若是他轮的预标:他轮仍持有(那一轮还会落定它)则保持 loading;
1161
+ // 已失效(那一轮已结束且没处理它)则沿它记下的来源回到最近的落定状态,否则会永久停在 loading。
1162
+ // resolveObject 内部的 markReadLoading 产生的 loading 不进 markOrigins,解开时停在它身上(那一轮取数仍会落定它)。
1163
+ for (const [name, { prev, shown, mark }] of premarked) {
1164
+ if (mark) this.liveMarks.delete(mark);
1165
+ if (started.has(name) || !mark || this.readStatuses.get(name) !== mark) continue;
1166
+ let tableTarget = prev;
1167
+ let objectTarget = shown;
1168
+ const visited = new Set<SomaDataReadStatus>();
1169
+ while (tableTarget && !this.liveMarks.has(tableTarget) && !visited.has(tableTarget)) {
1170
+ const origin = this.markOrigins.get(tableTarget);
1171
+ if (!origin) break;
1172
+ visited.add(tableTarget);
1173
+ tableTarget = origin.prev;
1174
+ objectTarget = origin.shown;
1175
+ }
1176
+ const restored: SomaDataReadStatus = objectTarget ?? tableTarget ?? { readState: 'idle', loading: false, ready: false, retry: () => this.reload([name]) };
1177
+ if (tableTarget) this.readStatuses.set(name, tableTarget);
1178
+ else this.readStatuses.delete(name);
1179
+ attachReadStatusToObject(this.objects[name], restored);
1180
+ }
1181
+ // 统一判定:有对象写回,或本次对象里有「已告知读取开始、且读状态已落定」的对象(成功 / 失败 / 被恢复)。
1182
+ // 仍在 loading 的对象说明别的一轮在读它,由让它落定的那一轮通知。
1183
+ const settledNotified = targets.some((name) => this.notifiedReading.has(name) && this.readStatuses.get(name)?.readState !== 'loading');
1184
+ if (!this.disposed && (changed || settledNotified)) {
1185
+ if (completed) {
1186
+ this.notifyReload();
1187
+ } else {
1188
+ // 抛错退出:回调抛错只记日志,不盖原错误
1189
+ try {
1190
+ this.notifyReload();
1191
+ } catch (error) {
1192
+ console.error('[soma-core][数据] onReload 回调抛错(重取失败路径,已忽略,原错误照常抛出):', error);
1193
+ }
1194
+ }
1195
+ }
866
1196
  }
867
- if (changed && !this.disposed) this.onReload?.(this.objects);
868
1197
  }
869
1198
 
870
1199
  /**
@@ -937,15 +1266,44 @@ export class SomaDataObjectResolver {
937
1266
 
938
1267
  // ─── 单对象解析 ────────────────────────────────────────────────────────────
939
1268
 
1269
+ /**
1270
+ * 读状态置 loading:先更新 `readStatuses` 表(读状态查询接口据此),再(非静默时)挂到当前对象上(旧数据保留)。
1271
+ * 静默(后台重取)只更新表,不碰当前对象,避免无关重绘时界面突然显示读取中。
1272
+ * 对象值不是普通对象时(如未声明 `into` 的列表型对象,其值是行数组)读状态挂不上去,此时读状态以 `getObjectReadStatus(name)` 为准。
1273
+ */
1274
+ private markReadLoading(decl: SomaDataObjectConfig, silent = false): void {
1275
+ const loadingStatus: SomaDataReadStatus = {
1276
+ readState: 'loading', loading: true, ready: false, retry: () => this.reload([decl.name]),
1277
+ };
1278
+ this.readStatuses.set(decl.name, loadingStatus);
1279
+ if (!silent && isPlainObject(this.objects[decl.name])) {
1280
+ attachReadStatusToObject(this.objects[decl.name], loadingStatus);
1281
+ }
1282
+ }
1283
+
1284
+ /**
1285
+ * 解析单个对象。`rejectReadFailure`:失败时保留旧数据并抛错(重取用);
1286
+ * `silent`:后台重取,读取开始不把 loading 挂到当前对象;失败时仅当该对象已告知宿主在读取中(`notifiedReading`)才把失败状态挂到旧对象,
1287
+ * 纯后台刷新失败只写 `readStatuses` 表,当前对象的读状态保持原样。非静默行为不变。
1288
+ */
940
1289
  async resolveObject(
941
1290
  decl: SomaDataObjectConfig,
942
1291
  rejectReadFailure = false,
1292
+ expectedSeq?: number,
1293
+ silent = false,
943
1294
  ): Promise<unknown> {
1295
+ const seq = expectedSeq ?? this.nextFetchSeq(decl.name);
1296
+ const retry = (): Promise<void> => this.reload([decl.name]);
944
1297
  // 写入型对象(无 from,只有 write):不取数,落中性空形,读状态 idle(与 from.require 跳过同口径)
945
1298
  if (decl.from.length === 0) {
946
1299
  this.idleObjects.add(decl.name);
947
- return this.finalize({}, decl);
1300
+ const idleStatus: SomaDataReadStatus = { readState: 'idle', loading: false, ready: false, retry };
1301
+ this.readStatuses.set(decl.name, idleStatus);
1302
+ const empty = {};
1303
+ attachReadStatusToObject(empty, idleStatus);
1304
+ return empty;
948
1305
  }
1306
+ this.markReadLoading(decl, silent);
949
1307
  // 来源分波:不自引用的来源无内部依赖 → 首波并发 Promise.all;
950
1308
  // 引用本对象($<自身>.<字段>,如 $order.id)的来源需读取先行来源的合并结果 → 次波按声明序串行。
951
1309
  const concurrent: SomaDataSourceConfig[] = [];
@@ -955,7 +1313,8 @@ export class SomaDataObjectResolver {
955
1313
  }
956
1314
 
957
1315
  let value: unknown = {};
958
- let failed: unknown = null;
1316
+ let failed: { api: string; error: unknown; source: SomaDataSourceConfig } | null = null;
1317
+ let succeededCount = 0;
959
1318
 
960
1319
  let idle = false;
961
1320
  /** 必填参数缺 → 该来源不并入;写了 into 的子键落空数组 */
@@ -976,12 +1335,13 @@ export class SomaDataObjectResolver {
976
1335
  this.assertActive();
977
1336
  for (const outcome of settled) {
978
1337
  if ('error' in outcome && outcome.error !== undefined) {
979
- failed = { api: outcome.source.api, error: outcome.error };
1338
+ failed = { api: outcome.source.api, error: outcome.error, source: outcome.source };
980
1339
  break;
981
1340
  }
982
1341
  const fetched = (outcome as { fetched: { skipped: boolean; data?: unknown } }).fetched;
983
1342
  if (fetched.skipped) { mergeSkipped(outcome.source); continue; }
984
1343
  value = this.mergeSource(value, outcome.source, fetched.data);
1344
+ succeededCount += 1;
985
1345
  }
986
1346
 
987
1347
  if (!failed) {
@@ -991,25 +1351,72 @@ export class SomaDataObjectResolver {
991
1351
  this.assertActive();
992
1352
  if (fetched.skipped) { mergeSkipped(source); continue; }
993
1353
  value = this.mergeSource(value, source, fetched.data);
1354
+ succeededCount += 1;
994
1355
  } catch (error) {
995
- failed = { api: source.api, error };
1356
+ failed = { api: source.api, error, source };
996
1357
  break;
997
1358
  }
998
1359
  }
999
1360
  }
1000
1361
 
1362
+ if (this.disposed || seq !== this.getFetchSeq(decl.name)) {
1363
+ return this.objects[decl.name] ?? {};
1364
+ }
1365
+
1001
1366
  if (idle) this.idleObjects.add(decl.name); else this.idleObjects.delete(decl.name);
1002
1367
 
1003
1368
  if (failed) {
1004
- const { api, error } = failed as { api: string; error: unknown };
1005
- // 写后刷新失败独立报告;不得用部分读态覆盖现有事实或否定已确认的写入。
1006
- if (rejectReadFailure) throw error;
1007
- // 401 / 403:对象按空处理
1008
- if (this.noteForbidden(decl.name, error)) return this.finalize({}, decl);
1369
+ if (this.disposed || seq !== this.getFetchSeq(decl.name)) {
1370
+ return this.objects[decl.name] ?? {};
1371
+ }
1372
+ const { api, error, source: failedSource } = failed;
1373
+ const errStatus = extractReadErrorStatus(error);
1374
+ const isForbidden = this.noteForbidden(decl.name, error) || isForbiddenReadError(error, errStatus);
1375
+ const errMsg = extractReadErrorMessage(error, errStatus);
1376
+ const failReadState: SomaDataReadState = isForbidden
1377
+ ? 'forbidden'
1378
+ : succeededCount > 0 ? 'partial' : 'error';
1379
+ const failStatus: SomaDataReadStatus = {
1380
+ readState: failReadState,
1381
+ loading: false,
1382
+ ready: failReadState === 'partial',
1383
+ errorMessage: errMsg,
1384
+ ...(isForbidden ? { errorStatus: errStatus ?? HTTP_FORBIDDEN } : errStatus !== undefined ? { errorStatus: errStatus } : {}),
1385
+ retry,
1386
+ };
1387
+ this.readStatuses.set(decl.name, failStatus);
1388
+ // 重取失败:保留旧数据、不以失败结果覆盖数据,但把失败的读状态挂在旧对象上,供界面提示;错误向上抛由调用方独立报告(不否定已确认的写入)。
1389
+ if (rejectReadFailure) {
1390
+ if (isPlainObject(this.objects[decl.name]) && (!silent || this.notifiedReading.has(decl.name))) {
1391
+ attachReadStatusToObject(this.objects[decl.name], failStatus, failedSource.into);
1392
+ }
1393
+ throw error;
1394
+ }
1395
+ // 401 / 403:对象按空处理,但附带非枚举 forbidden 读状态与 into 错误占位
1396
+ if (isForbidden) {
1397
+ const forbiddenObj = {};
1398
+ attachReadStatusToObject(forbiddenObj, failStatus, failedSource.into);
1399
+ return forbiddenObj;
1400
+ }
1009
1401
  console.error(`[soma-core][数据] 对象 "${decl.name}" 来源 "${api}" 取数失败(保留已取得的部分数据):`, error);
1402
+ attachReadStatusToObject(value, failStatus, failedSource.into);
1403
+ return value;
1404
+ }
1405
+
1406
+ if (this.disposed || seq !== this.getFetchSeq(decl.name)) {
1407
+ return this.objects[decl.name] ?? {};
1010
1408
  }
1011
1409
 
1012
- return this.finalize(value, decl);
1410
+ const finalState: SomaDataReadState = idle ? 'idle' : 'ready';
1411
+ const okStatus: SomaDataReadStatus = {
1412
+ readState: finalState,
1413
+ loading: false,
1414
+ ready: finalState === 'ready' || succeededCount > 0,
1415
+ retry,
1416
+ };
1417
+ this.readStatuses.set(decl.name, okStatus);
1418
+ attachReadStatusToObject(value, okStatus);
1419
+ return value;
1013
1420
  }
1014
1421
 
1015
1422
  async fetchSource(
@@ -1161,104 +1568,27 @@ export class SomaDataObjectResolver {
1161
1568
  return typeof this.pageOption === 'function' ? this.pageOption() : this.pageOption;
1162
1569
  }
1163
1570
 
1164
- // ─── transform 派生字段 ────────────────────────────────────────────────────
1165
-
1166
1571
  /** 与 Host 数据层同寿:旧句柄与后续未派发写入一并失效。 */
1167
1572
  dispose(): void {
1168
1573
  if (this.disposed) return;
1169
1574
  this.disposed = true;
1575
+ this.notifiedReading.clear();
1576
+ this.liveMarks.clear();
1170
1577
  }
1171
1578
 
1172
- private assertActive(): void {
1173
- if (this.disposed) throw new Error('数据对象解析器已失效');
1174
- }
1175
-
1176
- /** 派生列 AST 缓存:对象名 → 字段名 → AST */
1177
- private readonly derivedAsts = new Map<string, Map<string, CalcAst>>();
1178
-
1179
- /**
1180
- * 取数收尾:先算派生列,再跑展示管道。
1181
- *
1182
- * 次序不能反:`calc` 产出的是带类型的值(能排序、能求和),`transform` 产出的是给人看的串。
1183
- * 先格式化再算式的话,`[金额] - [折扣]` 拿到的是 "¥1,000.00" 这样的串。
1184
- */
1185
- finalize(value: unknown, decl: SomaDataObjectConfig): unknown {
1186
- return this.applyTransform(this.applyDerived(value, decl), decl);
1187
- }
1188
-
1189
- /**
1190
- * 派生列求值:把 `fields.<x>.calc` 算出来挂到值上。
1191
- *
1192
- * 与 `transform:` 的分工:`transform` 是展示管道,产出字符串;`calc` 是算式,产出带类型的值。
1193
- * 只作用于普通对象与对象数组两种形状,其余形状原样返回。
1194
- */
1195
- private applyDerived(value: unknown, decl: SomaDataObjectConfig): unknown {
1196
- const fields = decl.fields ?? {};
1197
- const derived = Object.keys(fields).filter((key) => fields[key].calc !== undefined);
1198
- if (derived.length === 0) return value;
1199
-
1200
- // AST 按对象缓存:声明在页面生命周期内不变,没必要每次重取都重新解析
1201
- let asts = this.derivedAsts.get(decl.name);
1202
- if (!asts) {
1203
- asts = new Map();
1204
- for (const key of derived) asts.set(key, parseCalc(fields[key].calc!));
1205
- this.derivedAsts.set(decl.name, asts);
1206
- }
1207
-
1208
- // 派生列可以引用另一个派生列,所以按依赖序算(解析期已检过环)
1209
- const order: string[] = [];
1210
- const seen = new Set<string>();
1211
- const visit = (key: string): void => {
1212
- if (seen.has(key)) return;
1213
- seen.add(key);
1214
- for (const ref of collectCalcRefs(asts!.get(key)!)) {
1215
- if (asts!.has(ref)) visit(ref);
1216
- }
1217
- order.push(key);
1218
- };
1219
- for (const key of derived) visit(key);
1220
-
1221
- const fill = (row: Record<string, unknown>): void => {
1222
- for (const key of order) row[key] = evaluateCalc(asts!.get(key)!, row);
1223
- };
1224
-
1225
- if (Array.isArray(value)) {
1226
- for (const row of value) if (isPlainObject(row)) fill(row);
1227
- return value;
1228
- }
1229
- if (isPlainObject(value)) {
1230
- fill(value);
1231
- // 对象里挂着的行数组(`{ list: [...] }` 这种取数形状)同样要算
1232
- for (const nested of Object.values(value)) {
1233
- if (Array.isArray(nested)) for (const row of nested) if (isPlainObject(row)) fill(row);
1579
+ /** 触发宿主重读对象表;之后只把读状态已落定(不是 loading,表里没有也算)的对象移出「已告知读取开始」集合,仍在读的保留 */
1580
+ private notifyReload(): void {
1581
+ try {
1582
+ this.onReload?.(this.objects);
1583
+ } finally {
1584
+ for (const name of [...this.notifiedReading]) {
1585
+ if (this.readStatuses.get(name)?.readState !== 'loading') this.notifiedReading.delete(name);
1234
1586
  }
1235
1587
  }
1236
- return value;
1237
1588
  }
1238
1589
 
1239
- private applyTransform(value: unknown, decl: SomaDataObjectConfig): unknown {
1240
- if (!decl.transform) return value;
1241
- if (!isPlainObject(value)) {
1242
- console.warn(`[soma-core][数据] 对象 "${decl.name}" 不是对象结构,transform 派生字段被跳过`);
1243
- return value;
1244
- }
1245
-
1246
- const ctx: SomaPipeContext = {
1247
- read: (path) => readPath(value, path.split('.')),
1248
- locale: () => this.localeProvider?.(),
1249
- };
1250
-
1251
- for (const [key, rawValue] of Object.entries(decl.transform)) {
1252
- const normalized = normalizeDataPipeValue(rawValue);
1253
- if (!hasPipes(normalized)) {
1254
- value[key] = readPath(value, normalized.split('.'));
1255
- continue;
1256
- }
1257
- const parsed = parsePipedValue(normalized, () => false);
1258
- const base = readPath(value, parsed.basePath.split('.'));
1259
- value[key] = this.pipes.apply(base, parsed.pipes, ctx);
1260
- }
1261
- return value;
1590
+ private assertActive(): void {
1591
+ if (this.disposed) throw new Error('数据对象解析器已失效');
1262
1592
  }
1263
1593
  }
1264
1594
 
@@ -1283,7 +1613,7 @@ export function createSomaDataPort(
1283
1613
  ok: false,
1284
1614
  message: `数据对象尚未就绪,无法${action}(本页可能没有在页面块声明 data:)`,
1285
1615
  });
1286
- return {
1616
+ const port: SomaDataPort = {
1287
1617
  getObject: (name) => currentResolver()?.getObject(name),
1288
1618
  getObjectStatus: (name) => currentResolver()?.getObjectStatus(name),
1289
1619
  getDict: (name) => currentResolver()?.getDict(name) ?? {},
@@ -1305,6 +1635,13 @@ export function createSomaDataPort(
1305
1635
  clearOutcome: (scope) => hostState.writeOutcomes().clear(scope),
1306
1636
  dispatch: (name: SomaWriteActionName, payload) => hostState.dispatchAction(name, payload),
1307
1637
  };
1638
+ Object.defineProperty(port, 'getObjectReadStatus', {
1639
+ value: (name: string) => currentResolver()?.getObjectReadStatus(name),
1640
+ enumerable: false,
1641
+ configurable: true,
1642
+ writable: true,
1643
+ });
1644
+ return port;
1308
1645
  }
1309
1646
 
1310
1647
  /**
@@ -1354,7 +1691,6 @@ export interface SomaDataResolverCapabilities {
1354
1691
  ): Record<string, string> | undefined | null;
1355
1692
  resolveParamValue(raw: unknown, selfName: string, selfValue: unknown): unknown;
1356
1693
  mergeSource(current: unknown, source: SomaDataSourceConfig, data: unknown): unknown;
1357
- finalize(value: unknown, decl: SomaDataObjectConfig): unknown;
1358
1694
  /** 写前预检构体;第四参 `transactionIdField` 给事务批次用,core 不用它,只为与完整版调用形状一致 */
1359
1695
  prepareWrite(
1360
1696
  decl: SomaDataObjectConfig,
@@ -1380,7 +1716,6 @@ export function bindDataResolverCapabilities(resolver: SomaDataObjectResolver):
1380
1716
  resolveParams: (params, selfName, selfValue, userRefs) => resolver.resolveParams(params, selfName, selfValue, userRefs),
1381
1717
  resolveParamValue: (raw, selfName, selfValue) => resolver.resolveParamValue(raw, selfName, selfValue),
1382
1718
  mergeSource: (current, source, data) => resolver.mergeSource(current, source, data),
1383
- finalize: (value, decl) => resolver.finalize(value, decl),
1384
1719
  prepareWrite: (decl, model, mode, _transactionIdField, identityField) => resolver.prepareWrite(decl, model, mode, identityField),
1385
1720
  mapSubmitError: (error, write) => resolver.mapSubmitError(error, write),
1386
1721
  inferWriteMode: (name, write) => resolver.inferWriteMode(name, write),