@hydranium/core 1.0.0-next.22 → 1.0.0-next.220

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 (652) hide show
  1. package/README.md +14 -8
  2. package/lib/documents/ast-document-manager.d.ts +219 -122
  3. package/lib/documents/ast-document-manager.d.ts.map +1 -1
  4. package/lib/documents/ast-document-manager.js +241 -130
  5. package/lib/documents/ast-document-manager.js.map +1 -1
  6. package/lib/documents/client-ids.d.ts +5 -19
  7. package/lib/documents/client-ids.d.ts.map +1 -1
  8. package/lib/documents/client-ids.js +5 -19
  9. package/lib/documents/client-ids.js.map +1 -1
  10. package/lib/documents/client-session-errors.d.ts +15 -0
  11. package/lib/documents/client-session-errors.d.ts.map +1 -0
  12. package/lib/documents/client-session-errors.js +15 -0
  13. package/lib/documents/client-session-errors.js.map +1 -0
  14. package/lib/documents/client-session-registry.d.ts +146 -0
  15. package/lib/documents/client-session-registry.d.ts.map +1 -0
  16. package/lib/documents/client-session-registry.js +207 -0
  17. package/lib/documents/client-session-registry.js.map +1 -0
  18. package/lib/documents/dirty-state-tracker.d.ts +79 -0
  19. package/lib/documents/dirty-state-tracker.d.ts.map +1 -0
  20. package/lib/documents/dirty-state-tracker.js +69 -0
  21. package/lib/documents/dirty-state-tracker.js.map +1 -0
  22. package/lib/documents/document-release-handler.d.ts +179 -0
  23. package/lib/documents/document-release-handler.d.ts.map +1 -0
  24. package/lib/documents/document-release-handler.js +283 -0
  25. package/lib/documents/document-release-handler.js.map +1 -0
  26. package/lib/documents/document-release-scheduler.d.ts +67 -0
  27. package/lib/documents/document-release-scheduler.d.ts.map +1 -0
  28. package/lib/documents/document-release-scheduler.js +80 -0
  29. package/lib/documents/document-release-scheduler.js.map +1 -0
  30. package/lib/documents/file-system-task-queue.d.ts +49 -0
  31. package/lib/documents/file-system-task-queue.d.ts.map +1 -0
  32. package/lib/documents/file-system-task-queue.js +34 -0
  33. package/lib/documents/file-system-task-queue.js.map +1 -0
  34. package/lib/documents/hydranium-text-documents.d.ts +399 -282
  35. package/lib/documents/hydranium-text-documents.d.ts.map +1 -1
  36. package/lib/documents/hydranium-text-documents.js +816 -483
  37. package/lib/documents/hydranium-text-documents.js.map +1 -1
  38. package/lib/documents/index.d.ts +10 -2
  39. package/lib/documents/index.d.ts.map +1 -1
  40. package/lib/documents/index.js +10 -2
  41. package/lib/documents/index.js.map +1 -1
  42. package/lib/documents/language-client-shadow.d.ts +218 -0
  43. package/lib/documents/language-client-shadow.d.ts.map +1 -0
  44. package/lib/documents/language-client-shadow.js +283 -0
  45. package/lib/documents/language-client-shadow.js.map +1 -0
  46. package/lib/documents/model-ledger.d.ts +47 -0
  47. package/lib/documents/model-ledger.d.ts.map +1 -0
  48. package/lib/documents/model-ledger.js +30 -0
  49. package/lib/documents/model-ledger.js.map +1 -0
  50. package/lib/documents/text-ledger.d.ts +64 -0
  51. package/lib/documents/text-ledger.d.ts.map +1 -0
  52. package/lib/documents/text-ledger.js +63 -0
  53. package/lib/documents/text-ledger.js.map +1 -0
  54. package/lib/documents/version-sync-service.d.ts +134 -0
  55. package/lib/documents/version-sync-service.d.ts.map +1 -0
  56. package/lib/documents/version-sync-service.js +171 -0
  57. package/lib/documents/version-sync-service.js.map +1 -0
  58. package/lib/index.d.ts +4 -0
  59. package/lib/index.d.ts.map +1 -1
  60. package/lib/index.js +7 -0
  61. package/lib/index.js.map +1 -1
  62. package/lib/langium/ast-extension/ast-extension-service.d.ts.map +1 -1
  63. package/lib/langium/ast-extension/ast-extension-service.js.map +1 -1
  64. package/lib/langium/ast-extension/ast-node-builder.d.ts +32 -9
  65. package/lib/langium/ast-extension/ast-node-builder.d.ts.map +1 -1
  66. package/lib/langium/ast-extension/ast-node-builder.js +60 -22
  67. package/lib/langium/ast-extension/ast-node-builder.js.map +1 -1
  68. package/lib/langium/bootstrap.d.ts +5 -5
  69. package/lib/langium/bootstrap.d.ts.map +1 -1
  70. package/lib/langium/bootstrap.js +42 -17
  71. package/lib/langium/bootstrap.js.map +1 -1
  72. package/lib/langium/build-phase-pass/build-phase-pass-service.d.ts.map +1 -1
  73. package/lib/langium/build-phase-pass/build-phase-pass-service.js.map +1 -1
  74. package/lib/langium/composite-ast-reflection.d.ts +43 -0
  75. package/lib/langium/composite-ast-reflection.d.ts.map +1 -0
  76. package/lib/langium/composite-ast-reflection.js +92 -0
  77. package/lib/langium/composite-ast-reflection.js.map +1 -0
  78. package/lib/langium/config/configuration-provider.d.ts +81 -0
  79. package/lib/langium/config/configuration-provider.d.ts.map +1 -0
  80. package/lib/langium/config/configuration-provider.js +112 -0
  81. package/lib/langium/config/configuration-provider.js.map +1 -0
  82. package/lib/langium/config/index.d.ts +1 -0
  83. package/lib/langium/config/index.d.ts.map +1 -1
  84. package/lib/langium/config/index.js +1 -0
  85. package/lib/langium/config/index.js.map +1 -1
  86. package/lib/langium/config/settings.js.map +1 -1
  87. package/lib/langium/diagnostics/hydranium-langium-profiler.d.ts.map +1 -1
  88. package/lib/langium/diagnostics/hydranium-langium-profiler.js.map +1 -1
  89. package/lib/langium/diagnostics/logger.d.ts +10 -3
  90. package/lib/langium/diagnostics/logger.d.ts.map +1 -1
  91. package/lib/langium/diagnostics/logger.js +12 -5
  92. package/lib/langium/diagnostics/logger.js.map +1 -1
  93. package/lib/langium/diagnostics/lsp-logger.d.ts +17 -0
  94. package/lib/langium/diagnostics/lsp-logger.d.ts.map +1 -1
  95. package/lib/langium/diagnostics/lsp-logger.js +57 -16
  96. package/lib/langium/diagnostics/lsp-logger.js.map +1 -1
  97. package/lib/langium/diagnostics/server-tracer.d.ts.map +1 -1
  98. package/lib/langium/diagnostics/server-tracer.js.map +1 -1
  99. package/lib/langium/document-builder/build-pipeline-integration.d.ts +21 -1
  100. package/lib/langium/document-builder/build-pipeline-integration.d.ts.map +1 -1
  101. package/lib/langium/document-builder/build-pipeline-integration.js +32 -5
  102. package/lib/langium/document-builder/build-pipeline-integration.js.map +1 -1
  103. package/lib/langium/document-builder/build-session.d.ts +93 -0
  104. package/lib/langium/document-builder/build-session.d.ts.map +1 -0
  105. package/lib/langium/document-builder/build-session.js +72 -0
  106. package/lib/langium/document-builder/build-session.js.map +1 -0
  107. package/lib/langium/document-builder/document-builder.d.ts +401 -29
  108. package/lib/langium/document-builder/document-builder.d.ts.map +1 -1
  109. package/lib/langium/document-builder/document-builder.js +698 -61
  110. package/lib/langium/document-builder/document-builder.js.map +1 -1
  111. package/lib/langium/document-builder/index.d.ts +1 -0
  112. package/lib/langium/document-builder/index.d.ts.map +1 -1
  113. package/lib/langium/document-builder/index.js +1 -0
  114. package/lib/langium/document-builder/index.js.map +1 -1
  115. package/lib/langium/documentation/comment-provider.d.ts.map +1 -1
  116. package/lib/langium/documentation/comment-provider.js.map +1 -1
  117. package/lib/langium/integration-services.d.ts +61 -19
  118. package/lib/langium/integration-services.d.ts.map +1 -1
  119. package/lib/langium/integration-services.js +10 -5
  120. package/lib/langium/integration-services.js.map +1 -1
  121. package/lib/langium/integrity/integrity-rule.d.ts +16 -8
  122. package/lib/langium/integrity/integrity-rule.d.ts.map +1 -1
  123. package/lib/langium/integrity/integrity-rule.js.map +1 -1
  124. package/lib/langium/integrity/integrity-service.d.ts +81 -24
  125. package/lib/langium/integrity/integrity-service.d.ts.map +1 -1
  126. package/lib/langium/integrity/integrity-service.js +264 -57
  127. package/lib/langium/integrity/integrity-service.js.map +1 -1
  128. package/lib/langium/keys/containment.d.ts +64 -0
  129. package/lib/langium/keys/containment.d.ts.map +1 -0
  130. package/lib/langium/keys/containment.js +53 -0
  131. package/lib/langium/keys/containment.js.map +1 -0
  132. package/lib/langium/keys/index.d.ts +1 -0
  133. package/lib/langium/keys/index.d.ts.map +1 -1
  134. package/lib/langium/keys/index.js +1 -0
  135. package/lib/langium/keys/index.js.map +1 -1
  136. package/lib/langium/keys/name-based-key-provider.d.ts +4 -0
  137. package/lib/langium/keys/name-based-key-provider.d.ts.map +1 -1
  138. package/lib/langium/keys/name-based-key-provider.js +4 -0
  139. package/lib/langium/keys/name-based-key-provider.js.map +1 -1
  140. package/lib/langium/keys/positional-key-provider.d.ts.map +1 -1
  141. package/lib/langium/keys/positional-key-provider.js.map +1 -1
  142. package/lib/langium/labeling/label-provider.d.ts.map +1 -1
  143. package/lib/langium/labeling/label-provider.js.map +1 -1
  144. package/lib/langium/language-module.d.ts +29 -4
  145. package/lib/langium/language-module.d.ts.map +1 -1
  146. package/lib/langium/language-module.js +18 -4
  147. package/lib/langium/language-module.js.map +1 -1
  148. package/lib/langium/model-service/client-session.d.ts +343 -0
  149. package/lib/langium/model-service/client-session.d.ts.map +1 -0
  150. package/lib/langium/model-service/client-session.js +411 -0
  151. package/lib/langium/model-service/client-session.js.map +1 -0
  152. package/lib/langium/model-service/index.d.ts +2 -0
  153. package/lib/langium/model-service/index.d.ts.map +1 -1
  154. package/lib/langium/model-service/index.js +2 -0
  155. package/lib/langium/model-service/index.js.map +1 -1
  156. package/lib/langium/model-service/model-events.d.ts +61 -0
  157. package/lib/langium/model-service/model-events.d.ts.map +1 -0
  158. package/lib/langium/model-service/model-events.js +10 -0
  159. package/lib/langium/model-service/model-events.js.map +1 -0
  160. package/lib/langium/model-service/model-service.d.ts +432 -282
  161. package/lib/langium/model-service/model-service.d.ts.map +1 -1
  162. package/lib/langium/model-service/model-service.js +504 -438
  163. package/lib/langium/model-service/model-service.js.map +1 -1
  164. package/lib/langium/module.d.ts +157 -35
  165. package/lib/langium/module.d.ts.map +1 -1
  166. package/lib/langium/module.js +52 -35
  167. package/lib/langium/module.js.map +1 -1
  168. package/lib/langium/naming/name-provider.d.ts +25 -4
  169. package/lib/langium/naming/name-provider.d.ts.map +1 -1
  170. package/lib/langium/naming/name-provider.js +2 -1
  171. package/lib/langium/naming/name-provider.js.map +1 -1
  172. package/lib/langium/naming/name-separator-validation.d.ts +23 -0
  173. package/lib/langium/naming/name-separator-validation.d.ts.map +1 -1
  174. package/lib/langium/naming/name-separator-validation.js +30 -1
  175. package/lib/langium/naming/name-separator-validation.js.map +1 -1
  176. package/lib/langium/project/abstract-project-manager.d.ts.map +1 -1
  177. package/lib/langium/project/abstract-project-manager.js +9 -2
  178. package/lib/langium/project/abstract-project-manager.js.map +1 -1
  179. package/lib/langium/project/project-change-event.d.ts +2 -2
  180. package/lib/langium/project/single-project-manager.d.ts.map +1 -1
  181. package/lib/langium/project/single-project-manager.js.map +1 -1
  182. package/lib/langium/residency/cst-residency-service.d.ts +31 -11
  183. package/lib/langium/residency/cst-residency-service.d.ts.map +1 -1
  184. package/lib/langium/residency/cst-residency-service.js +23 -57
  185. package/lib/langium/residency/cst-residency-service.js.map +1 -1
  186. package/lib/langium/scope/ast-node-description-provider.d.ts.map +1 -1
  187. package/lib/langium/scope/ast-node-description-provider.js.map +1 -1
  188. package/lib/langium/scope/hydranium-scope-computation.d.ts.map +1 -1
  189. package/lib/langium/scope/hydranium-scope-computation.js.map +1 -1
  190. package/lib/langium/scope/hydranium-scope-provider.d.ts +48 -13
  191. package/lib/langium/scope/hydranium-scope-provider.d.ts.map +1 -1
  192. package/lib/langium/scope/hydranium-scope-provider.js +56 -20
  193. package/lib/langium/scope/hydranium-scope-provider.js.map +1 -1
  194. package/lib/langium/scope/reference-builder.d.ts.map +1 -1
  195. package/lib/langium/scope/reference-builder.js.map +1 -1
  196. package/lib/langium/scope/reference-candidate-provider.d.ts.map +1 -1
  197. package/lib/langium/scope/reference-candidate-provider.js.map +1 -1
  198. package/lib/langium/scope/scope-extension-service.d.ts.map +1 -1
  199. package/lib/langium/scope/scope-extension-service.js.map +1 -1
  200. package/lib/langium/serialization/abstract-serializer.d.ts +11 -20
  201. package/lib/langium/serialization/abstract-serializer.d.ts.map +1 -1
  202. package/lib/langium/serialization/abstract-serializer.js +12 -21
  203. package/lib/langium/serialization/abstract-serializer.js.map +1 -1
  204. package/lib/langium/serialization/json-serializer.d.ts +1 -1
  205. package/lib/langium/serialization/json-serializer.d.ts.map +1 -1
  206. package/lib/langium/serialization/json-serializer.js.map +1 -1
  207. package/lib/langium/serialization/yaml-serializer.d.ts.map +1 -1
  208. package/lib/langium/serialization/yaml-serializer.js.map +1 -1
  209. package/lib/langium/service-registry.d.ts +29 -1
  210. package/lib/langium/service-registry.d.ts.map +1 -1
  211. package/lib/langium/service-registry.js +37 -0
  212. package/lib/langium/service-registry.js.map +1 -1
  213. package/lib/langium/shared-services.d.ts +23 -6
  214. package/lib/langium/shared-services.d.ts.map +1 -1
  215. package/lib/langium/shared-services.js.map +1 -1
  216. package/lib/langium/transfer/transfer-encoder.d.ts +77 -26
  217. package/lib/langium/transfer/transfer-encoder.d.ts.map +1 -1
  218. package/lib/langium/transfer/transfer-encoder.js +46 -24
  219. package/lib/langium/transfer/transfer-encoder.js.map +1 -1
  220. package/lib/langium/trivia/comment-preserver.d.ts +423 -0
  221. package/lib/langium/trivia/comment-preserver.d.ts.map +1 -0
  222. package/lib/langium/trivia/comment-preserver.js +906 -0
  223. package/lib/langium/trivia/comment-preserver.js.map +1 -0
  224. package/lib/langium/trivia/document-ending-preserver.d.ts +43 -0
  225. package/lib/langium/trivia/document-ending-preserver.d.ts.map +1 -0
  226. package/lib/langium/trivia/document-ending-preserver.js +48 -0
  227. package/lib/langium/trivia/document-ending-preserver.js.map +1 -0
  228. package/lib/langium/trivia/index.d.ts +14 -0
  229. package/lib/langium/trivia/index.d.ts.map +1 -0
  230. package/lib/langium/trivia/index.js +14 -0
  231. package/lib/langium/trivia/index.js.map +1 -0
  232. package/lib/langium/trivia/trivia-contribution.d.ts +37 -0
  233. package/lib/langium/trivia/trivia-contribution.d.ts.map +1 -0
  234. package/lib/langium/trivia/trivia-contribution.js +10 -0
  235. package/lib/langium/trivia/trivia-contribution.js.map +1 -0
  236. package/lib/langium/trivia/trivia-preserver.d.ts +50 -0
  237. package/lib/langium/trivia/trivia-preserver.d.ts.map +1 -0
  238. package/lib/langium/trivia/trivia-preserver.js +10 -0
  239. package/lib/langium/trivia/trivia-preserver.js.map +1 -0
  240. package/lib/langium/trivia/trivia-service.d.ts +70 -0
  241. package/lib/langium/trivia/trivia-service.d.ts.map +1 -0
  242. package/lib/langium/trivia/trivia-service.js +56 -0
  243. package/lib/langium/trivia/trivia-service.js.map +1 -0
  244. package/lib/langium/update-rewrite/normalize-empty-strings.d.ts.map +1 -1
  245. package/lib/langium/update-rewrite/update-rewrite-service.d.ts.map +1 -1
  246. package/lib/langium/update-rewrite/update-rewrite-service.js.map +1 -1
  247. package/lib/langium/update-rewrite/update-rewrite.d.ts +1 -1
  248. package/lib/langium/validation/document-validator.d.ts +294 -10
  249. package/lib/langium/validation/document-validator.d.ts.map +1 -1
  250. package/lib/langium/validation/document-validator.js +448 -5
  251. package/lib/langium/validation/document-validator.js.map +1 -1
  252. package/lib/langium/validation/validation-contribution-collector.d.ts +9 -1
  253. package/lib/langium/validation/validation-contribution-collector.d.ts.map +1 -1
  254. package/lib/langium/validation/validation-contribution-collector.js +1 -1
  255. package/lib/langium/validation/validation-contribution-collector.js.map +1 -1
  256. package/lib/langium/workspace/document-uri-policy.d.ts +18 -14
  257. package/lib/langium/workspace/document-uri-policy.d.ts.map +1 -1
  258. package/lib/langium/workspace/document-uri-policy.js +10 -9
  259. package/lib/langium/workspace/document-uri-policy.js.map +1 -1
  260. package/lib/langium/workspace/file-not-found.d.ts +23 -0
  261. package/lib/langium/workspace/file-not-found.d.ts.map +1 -0
  262. package/lib/langium/workspace/file-not-found.js +31 -0
  263. package/lib/langium/workspace/file-not-found.js.map +1 -0
  264. package/lib/langium/workspace/file-system-provider.d.ts +135 -9
  265. package/lib/langium/workspace/file-system-provider.d.ts.map +1 -1
  266. package/lib/langium/workspace/file-system-provider.js +93 -14
  267. package/lib/langium/workspace/file-system-provider.js.map +1 -1
  268. package/lib/langium/workspace/hydranium-langium-document-factory.d.ts +56 -1
  269. package/lib/langium/workspace/hydranium-langium-document-factory.d.ts.map +1 -1
  270. package/lib/langium/workspace/hydranium-langium-document-factory.js +79 -0
  271. package/lib/langium/workspace/hydranium-langium-document-factory.js.map +1 -1
  272. package/lib/langium/workspace/hydranium-workspace-lock.d.ts +43 -1
  273. package/lib/langium/workspace/hydranium-workspace-lock.d.ts.map +1 -1
  274. package/lib/langium/workspace/hydranium-workspace-lock.js +58 -1
  275. package/lib/langium/workspace/hydranium-workspace-lock.js.map +1 -1
  276. package/lib/langium/workspace/hydranium-workspace-manager.d.ts +82 -9
  277. package/lib/langium/workspace/hydranium-workspace-manager.d.ts.map +1 -1
  278. package/lib/langium/workspace/hydranium-workspace-manager.js +128 -10
  279. package/lib/langium/workspace/hydranium-workspace-manager.js.map +1 -1
  280. package/lib/langium/workspace/in-memory-file-system-provider.d.ts +26 -3
  281. package/lib/langium/workspace/in-memory-file-system-provider.d.ts.map +1 -1
  282. package/lib/langium/workspace/in-memory-file-system-provider.js +41 -15
  283. package/lib/langium/workspace/in-memory-file-system-provider.js.map +1 -1
  284. package/lib/langium/workspace/index-manager.d.ts.map +1 -1
  285. package/lib/langium/workspace/index-manager.js.map +1 -1
  286. package/lib/langium/workspace/index.d.ts +1 -0
  287. package/lib/langium/workspace/index.d.ts.map +1 -1
  288. package/lib/langium/workspace/index.js +1 -0
  289. package/lib/langium/workspace/index.js.map +1 -1
  290. package/lib/langium/workspace/initialize-workspace.d.ts +31 -2
  291. package/lib/langium/workspace/initialize-workspace.d.ts.map +1 -1
  292. package/lib/langium/workspace/initialize-workspace.js +13 -5
  293. package/lib/langium/workspace/initialize-workspace.js.map +1 -1
  294. package/lib/langium/workspace/langium-documents.d.ts +86 -17
  295. package/lib/langium/workspace/langium-documents.d.ts.map +1 -1
  296. package/lib/langium/workspace/langium-documents.js +101 -29
  297. package/lib/langium/workspace/langium-documents.js.map +1 -1
  298. package/lib/langium/workspace/persistent-file-system-provider.d.ts +1 -8
  299. package/lib/langium/workspace/persistent-file-system-provider.d.ts.map +1 -1
  300. package/lib/langium/workspace/persistent-file-system-provider.js +0 -7
  301. package/lib/langium/workspace/persistent-file-system-provider.js.map +1 -1
  302. package/lib/{documents → langium/workspace}/self-save-registry.d.ts +38 -7
  303. package/lib/langium/workspace/self-save-registry.d.ts.map +1 -0
  304. package/lib/{documents → langium/workspace}/self-save-registry.js +29 -16
  305. package/lib/langium/workspace/self-save-registry.js.map +1 -0
  306. package/lib/langium/workspace/virtual-document.d.ts +48 -15
  307. package/lib/langium/workspace/virtual-document.d.ts.map +1 -1
  308. package/lib/langium/workspace/virtual-document.js +78 -18
  309. package/lib/langium/workspace/virtual-document.js.map +1 -1
  310. package/lib/langium/workspace/write-lock-scope.d.ts +20 -10
  311. package/lib/langium/workspace/write-lock-scope.d.ts.map +1 -1
  312. package/lib/langium/workspace/write-lock-scope.js +12 -4
  313. package/lib/langium/workspace/write-lock-scope.js.map +1 -1
  314. package/lib/locale/index.d.ts +10 -0
  315. package/lib/locale/index.d.ts.map +1 -0
  316. package/lib/locale/index.js +10 -0
  317. package/lib/locale/index.js.map +1 -0
  318. package/lib/locale/server-locale.d.ts +73 -0
  319. package/lib/locale/server-locale.d.ts.map +1 -0
  320. package/lib/locale/server-locale.js +61 -0
  321. package/lib/locale/server-locale.js.map +1 -0
  322. package/lib/lsp/completion/hydranium-completion-provider.d.ts +44 -2
  323. package/lib/lsp/completion/hydranium-completion-provider.d.ts.map +1 -1
  324. package/lib/lsp/completion/hydranium-completion-provider.js +68 -0
  325. package/lib/lsp/completion/hydranium-completion-provider.js.map +1 -1
  326. package/lib/lsp/connection-features.d.ts +23 -0
  327. package/lib/lsp/connection-features.d.ts.map +1 -0
  328. package/lib/lsp/connection-features.js +60 -0
  329. package/lib/lsp/connection-features.js.map +1 -0
  330. package/lib/lsp/diagnostics-connection.d.ts +27 -0
  331. package/lib/lsp/diagnostics-connection.d.ts.map +1 -0
  332. package/lib/lsp/diagnostics-connection.js +53 -0
  333. package/lib/lsp/diagnostics-connection.js.map +1 -0
  334. package/lib/lsp/hydranium-document-update-handler.d.ts +92 -81
  335. package/lib/lsp/hydranium-document-update-handler.d.ts.map +1 -1
  336. package/lib/lsp/hydranium-document-update-handler.js +153 -99
  337. package/lib/lsp/hydranium-document-update-handler.js.map +1 -1
  338. package/lib/lsp/index.d.ts +3 -1
  339. package/lib/lsp/index.d.ts.map +1 -1
  340. package/lib/lsp/index.js +3 -1
  341. package/lib/lsp/index.js.map +1 -1
  342. package/lib/lsp/lsp-latency.d.ts +39 -0
  343. package/lib/lsp/lsp-latency.d.ts.map +1 -0
  344. package/lib/lsp/lsp-latency.js +58 -0
  345. package/lib/lsp/lsp-latency.js.map +1 -0
  346. package/lib/lsp/semantic-token-provider.d.ts +34 -1
  347. package/lib/lsp/semantic-token-provider.d.ts.map +1 -1
  348. package/lib/lsp/semantic-token-provider.js +55 -8
  349. package/lib/lsp/semantic-token-provider.js.map +1 -1
  350. package/lib/lsp/shared-module.d.ts +4 -8
  351. package/lib/lsp/shared-module.d.ts.map +1 -1
  352. package/lib/lsp/shared-module.js.map +1 -1
  353. package/lib/lsp/start-language-server.d.ts +8 -7
  354. package/lib/lsp/start-language-server.d.ts.map +1 -1
  355. package/lib/lsp/start-language-server.js +13 -7
  356. package/lib/lsp/start-language-server.js.map +1 -1
  357. package/lib/messages/carriers.d.ts +54 -0
  358. package/lib/messages/carriers.d.ts.map +1 -0
  359. package/lib/messages/carriers.js +62 -0
  360. package/lib/messages/carriers.js.map +1 -0
  361. package/lib/messages/index.d.ts +25 -0
  362. package/lib/messages/index.d.ts.map +1 -0
  363. package/lib/messages/index.js +25 -0
  364. package/lib/messages/index.js.map +1 -0
  365. package/lib/messages/renderer.d.ts +142 -0
  366. package/lib/messages/renderer.d.ts.map +1 -0
  367. package/lib/messages/renderer.js +165 -0
  368. package/lib/messages/renderer.js.map +1 -0
  369. package/lib/node/event-loop-monitor.js.map +1 -1
  370. package/lib/node/heap-ceiling.d.ts +61 -0
  371. package/lib/node/heap-ceiling.d.ts.map +1 -0
  372. package/lib/node/heap-ceiling.js +72 -0
  373. package/lib/node/heap-ceiling.js.map +1 -0
  374. package/lib/node/index.d.ts +1 -1
  375. package/lib/node/index.d.ts.map +1 -1
  376. package/lib/node/index.js +1 -1
  377. package/lib/node/index.js.map +1 -1
  378. package/lib/node/latency-from-env.d.ts +1 -1
  379. package/lib/node/latency-from-env.js +1 -1
  380. package/lib/node/lint-grammar.js.map +1 -1
  381. package/lib/node/measure-memory.d.ts.map +1 -1
  382. package/lib/node/measure-memory.js +1 -0
  383. package/lib/node/measure-memory.js.map +1 -1
  384. package/lib/node/memory-monitor.js.map +1 -1
  385. package/lib/node/node-file-system-provider.d.ts +41 -6
  386. package/lib/node/node-file-system-provider.d.ts.map +1 -1
  387. package/lib/node/node-file-system-provider.js +109 -49
  388. package/lib/node/node-file-system-provider.js.map +1 -1
  389. package/lib/node/profile-capture.d.ts +8 -2
  390. package/lib/node/profile-capture.d.ts.map +1 -1
  391. package/lib/node/profile-capture.js +1 -1
  392. package/lib/node/profile-capture.js.map +1 -1
  393. package/lib/node/profile-digest.js.map +1 -1
  394. package/lib/node/profiling-run.d.ts +13 -3
  395. package/lib/node/profiling-run.d.ts.map +1 -1
  396. package/lib/node/profiling-run.js +17 -8
  397. package/lib/node/profiling-run.js.map +1 -1
  398. package/lib/node/rename-over-open-readers.d.ts +52 -0
  399. package/lib/node/rename-over-open-readers.d.ts.map +1 -0
  400. package/lib/node/rename-over-open-readers.js +66 -0
  401. package/lib/node/rename-over-open-readers.js.map +1 -0
  402. package/lib/node/socket-launcher.d.ts +20 -4
  403. package/lib/node/socket-launcher.d.ts.map +1 -1
  404. package/lib/node/socket-launcher.js +5 -4
  405. package/lib/node/socket-launcher.js.map +1 -1
  406. package/lib/node/stdio-launcher.d.ts +6 -5
  407. package/lib/node/stdio-launcher.d.ts.map +1 -1
  408. package/lib/node/stdio-launcher.js +2 -2
  409. package/lib/node/stdio-launcher.js.map +1 -1
  410. package/lib/testing/document-uri-policy-conformance.js.map +1 -1
  411. package/lib/testing/fake-description.js.map +1 -1
  412. package/lib/testing/fake-document.d.ts +16 -4
  413. package/lib/testing/fake-document.d.ts.map +1 -1
  414. package/lib/testing/fake-document.js +18 -3
  415. package/lib/testing/fake-document.js.map +1 -1
  416. package/lib/testing/index.d.ts +1 -1
  417. package/lib/testing/index.d.ts.map +1 -1
  418. package/lib/testing/index.js +2 -1
  419. package/lib/testing/index.js.map +1 -1
  420. package/lib/testing/langium-test-helpers.d.ts.map +1 -1
  421. package/lib/testing/langium-test-helpers.js +1 -0
  422. package/lib/testing/langium-test-helpers.js.map +1 -1
  423. package/lib/testing/make-noop-language-services.js.map +1 -1
  424. package/lib/testing/make-noop-shared-services.d.ts +14 -0
  425. package/lib/testing/make-noop-shared-services.d.ts.map +1 -1
  426. package/lib/testing/make-noop-shared-services.js +28 -2
  427. package/lib/testing/make-noop-shared-services.js.map +1 -1
  428. package/lib/testing/make-test-services.d.ts +72 -14
  429. package/lib/testing/make-test-services.d.ts.map +1 -1
  430. package/lib/testing/make-test-services.js +42 -10
  431. package/lib/testing/make-test-services.js.map +1 -1
  432. package/lib/testing/make-test-tracer.d.ts +12 -0
  433. package/lib/testing/make-test-tracer.d.ts.map +1 -1
  434. package/lib/testing/make-test-tracer.js +13 -0
  435. package/lib/testing/make-test-tracer.js.map +1 -1
  436. package/lib/testing/node/golden-corpus.js.map +1 -1
  437. package/lib/testing/node/index.d.ts +1 -0
  438. package/lib/testing/node/index.d.ts.map +1 -1
  439. package/lib/testing/node/index.js +1 -0
  440. package/lib/testing/node/index.js.map +1 -1
  441. package/lib/testing/node/lsp-harness.d.ts.map +1 -1
  442. package/lib/testing/node/lsp-harness.js +2 -0
  443. package/lib/testing/node/lsp-harness.js.map +1 -1
  444. package/lib/testing/node/lsp-server-connection.d.ts +11 -3
  445. package/lib/testing/node/lsp-server-connection.d.ts.map +1 -1
  446. package/lib/testing/node/lsp-server-connection.js +43 -10
  447. package/lib/testing/node/lsp-server-connection.js.map +1 -1
  448. package/lib/testing/node/scratch-workspace.d.ts.map +1 -1
  449. package/lib/testing/node/scratch-workspace.js +10 -5
  450. package/lib/testing/node/scratch-workspace.js.map +1 -1
  451. package/lib/testing/node/spawned-server.d.ts +14 -0
  452. package/lib/testing/node/spawned-server.d.ts.map +1 -1
  453. package/lib/testing/node/spawned-server.js +34 -2
  454. package/lib/testing/node/spawned-server.js.map +1 -1
  455. package/lib/testing/node/unhandled-rejections.d.ts +20 -0
  456. package/lib/testing/node/unhandled-rejections.d.ts.map +1 -0
  457. package/lib/testing/node/unhandled-rejections.js +32 -0
  458. package/lib/testing/node/unhandled-rejections.js.map +1 -0
  459. package/lib/testing/playwright/browser-capture-bridge.js.map +1 -1
  460. package/lib/testing/playwright/e2e-profiling.js.map +1 -1
  461. package/lib/testing/playwright/flaky-network-proxy.d.ts +76 -0
  462. package/lib/testing/playwright/flaky-network-proxy.d.ts.map +1 -0
  463. package/lib/testing/playwright/flaky-network-proxy.js +164 -0
  464. package/lib/testing/playwright/flaky-network-proxy.js.map +1 -0
  465. package/lib/testing/playwright/index.d.ts +1 -0
  466. package/lib/testing/playwright/index.d.ts.map +1 -1
  467. package/lib/testing/playwright/index.js +1 -0
  468. package/lib/testing/playwright/index.js.map +1 -1
  469. package/lib/testing/playwright/server-log-capture.d.ts +24 -8
  470. package/lib/testing/playwright/server-log-capture.d.ts.map +1 -1
  471. package/lib/testing/playwright/server-log-capture.js +27 -6
  472. package/lib/testing/playwright/server-log-capture.js.map +1 -1
  473. package/lib/testing/playwright/server-log-rename-reporter.d.ts.map +1 -1
  474. package/lib/testing/playwright/server-log-rename-reporter.js +10 -1
  475. package/lib/testing/playwright/server-log-rename-reporter.js.map +1 -1
  476. package/lib/testing/run-update-pipeline.d.ts +4 -4
  477. package/lib/testing/run-update-pipeline.d.ts.map +1 -1
  478. package/lib/testing/stub-ast-document-manager.d.ts +11 -52
  479. package/lib/testing/stub-ast-document-manager.d.ts.map +1 -1
  480. package/lib/testing/stub-ast-document-manager.js +24 -65
  481. package/lib/testing/stub-ast-document-manager.js.map +1 -1
  482. package/lib/testing/stub-document-builder.d.ts +26 -11
  483. package/lib/testing/stub-document-builder.d.ts.map +1 -1
  484. package/lib/testing/stub-document-builder.js +78 -5
  485. package/lib/testing/stub-document-builder.js.map +1 -1
  486. package/lib/testing/stub-hydranium-text-documents.d.ts +33 -10
  487. package/lib/testing/stub-hydranium-text-documents.d.ts.map +1 -1
  488. package/lib/testing/stub-hydranium-text-documents.js +115 -16
  489. package/lib/testing/stub-hydranium-text-documents.js.map +1 -1
  490. package/lib/testing/stub-index-manager.js.map +1 -1
  491. package/lib/testing/stub-langium-documents.d.ts +3 -2
  492. package/lib/testing/stub-langium-documents.d.ts.map +1 -1
  493. package/lib/testing/stub-langium-documents.js.map +1 -1
  494. package/lib/testing/stub-model-service.d.ts +7 -6
  495. package/lib/testing/stub-model-service.d.ts.map +1 -1
  496. package/lib/testing/stub-model-service.js +4 -4
  497. package/lib/testing/stub-model-service.js.map +1 -1
  498. package/lib/testing/stub-project-manager.js.map +1 -1
  499. package/lib/testing/stub-self-save-registry.d.ts +1 -1
  500. package/lib/testing/stub-self-save-registry.d.ts.map +1 -1
  501. package/lib/testing/stub-service-registry.d.ts +1 -1
  502. package/lib/testing/stub-service-registry.js.map +1 -1
  503. package/lib/testing/stub-writable-file-system.d.ts +1 -1
  504. package/lib/testing/stub-writable-file-system.d.ts.map +1 -1
  505. package/lib/util/connection-liveness.d.ts +7 -6
  506. package/lib/util/connection-liveness.d.ts.map +1 -1
  507. package/lib/util/connection-liveness.js +35 -14
  508. package/lib/util/connection-liveness.js.map +1 -1
  509. package/lib/util/environment.d.ts.map +1 -1
  510. package/lib/util/environment.js.map +1 -1
  511. package/lib/util/registry.d.ts.map +1 -1
  512. package/package.json +32 -48
  513. package/src/documents/ast-document-manager.ts +379 -231
  514. package/src/documents/client-ids.ts +5 -22
  515. package/src/documents/client-session-errors.ts +24 -0
  516. package/src/documents/client-session-registry.ts +262 -0
  517. package/src/documents/dirty-state-tracker.ts +130 -0
  518. package/src/documents/document-release-handler.ts +365 -0
  519. package/src/documents/document-release-scheduler.ts +121 -0
  520. package/src/documents/file-system-task-queue.ts +68 -0
  521. package/src/documents/hydranium-text-documents.ts +931 -595
  522. package/src/documents/index.ts +10 -2
  523. package/src/documents/language-client-shadow.ts +451 -0
  524. package/src/documents/model-ledger.ts +66 -0
  525. package/src/documents/text-ledger.ts +112 -0
  526. package/src/documents/version-sync-service.ts +267 -0
  527. package/src/index.ts +7 -0
  528. package/src/langium/ast-extension/ast-node-builder.ts +66 -22
  529. package/src/langium/bootstrap.ts +42 -17
  530. package/src/langium/composite-ast-reflection.ts +107 -0
  531. package/src/langium/config/configuration-provider.ts +119 -0
  532. package/src/langium/config/index.ts +1 -0
  533. package/src/langium/diagnostics/logger.ts +12 -5
  534. package/src/langium/diagnostics/lsp-logger.ts +59 -15
  535. package/src/langium/document-builder/build-pipeline-integration.ts +50 -5
  536. package/src/langium/document-builder/build-session.ts +87 -0
  537. package/src/langium/document-builder/document-builder.ts +825 -59
  538. package/src/langium/document-builder/index.ts +1 -0
  539. package/src/langium/integration-services.ts +83 -24
  540. package/src/langium/integrity/integrity-rule.ts +16 -8
  541. package/src/langium/integrity/integrity-service.ts +287 -62
  542. package/src/langium/keys/containment.ts +87 -0
  543. package/src/langium/keys/index.ts +1 -0
  544. package/src/langium/keys/name-based-key-provider.ts +4 -0
  545. package/src/langium/language-module.ts +48 -7
  546. package/src/langium/model-service/client-session.ts +644 -0
  547. package/src/langium/model-service/index.ts +2 -0
  548. package/src/langium/model-service/model-events.ts +75 -0
  549. package/src/langium/model-service/model-service.ts +790 -468
  550. package/src/langium/module.ts +210 -64
  551. package/src/langium/naming/name-provider.ts +27 -5
  552. package/src/langium/naming/name-separator-validation.ts +34 -5
  553. package/src/langium/project/abstract-project-manager.ts +9 -1
  554. package/src/langium/project/project-change-event.ts +2 -2
  555. package/src/langium/residency/cst-residency-service.ts +46 -15
  556. package/src/langium/scope/hydranium-scope-provider.ts +60 -22
  557. package/src/langium/serialization/abstract-serializer.ts +13 -32
  558. package/src/langium/service-registry.ts +41 -2
  559. package/src/langium/shared-services.ts +27 -6
  560. package/src/langium/transfer/transfer-encoder.ts +104 -37
  561. package/src/langium/trivia/comment-preserver.ts +1100 -0
  562. package/src/langium/trivia/document-ending-preserver.ts +55 -0
  563. package/src/langium/trivia/index.ts +14 -0
  564. package/src/langium/trivia/trivia-contribution.ts +39 -0
  565. package/src/langium/trivia/trivia-preserver.ts +54 -0
  566. package/src/langium/trivia/trivia-service.ts +99 -0
  567. package/src/langium/update-rewrite/update-rewrite.ts +1 -1
  568. package/src/langium/validation/document-validator.ts +537 -11
  569. package/src/langium/validation/validation-contribution-collector.ts +10 -1
  570. package/src/langium/workspace/document-uri-policy.ts +18 -14
  571. package/src/langium/workspace/file-not-found.ts +35 -0
  572. package/src/langium/workspace/file-system-provider.ts +205 -17
  573. package/src/langium/workspace/hydranium-langium-document-factory.ts +117 -0
  574. package/src/langium/workspace/hydranium-workspace-lock.ts +86 -2
  575. package/src/langium/workspace/hydranium-workspace-manager.ts +154 -14
  576. package/src/langium/workspace/in-memory-file-system-provider.ts +48 -17
  577. package/src/langium/workspace/index.ts +1 -0
  578. package/src/langium/workspace/initialize-workspace.ts +43 -5
  579. package/src/langium/workspace/langium-documents.ts +124 -33
  580. package/src/langium/workspace/persistent-file-system-provider.ts +1 -8
  581. package/src/{documents → langium/workspace}/self-save-registry.ts +54 -15
  582. package/src/langium/workspace/virtual-document.ts +96 -19
  583. package/src/langium/workspace/write-lock-scope.ts +24 -11
  584. package/src/locale/index.ts +10 -0
  585. package/src/locale/server-locale.ts +86 -0
  586. package/src/lsp/completion/hydranium-completion-provider.ts +82 -2
  587. package/src/lsp/connection-features.ts +67 -0
  588. package/src/lsp/diagnostics-connection.ts +56 -0
  589. package/src/lsp/hydranium-document-update-handler.ts +187 -108
  590. package/src/lsp/index.ts +3 -1
  591. package/src/lsp/lsp-latency.ts +62 -0
  592. package/src/lsp/semantic-token-provider.ts +74 -7
  593. package/src/lsp/shared-module.ts +4 -8
  594. package/src/lsp/start-language-server.ts +13 -7
  595. package/src/messages/carriers.ts +78 -0
  596. package/src/messages/index.ts +36 -0
  597. package/src/messages/renderer.ts +212 -0
  598. package/src/node/heap-ceiling.ts +108 -0
  599. package/src/node/index.ts +1 -1
  600. package/src/node/latency-from-env.ts +1 -1
  601. package/src/node/measure-memory.ts +1 -0
  602. package/src/node/node-file-system-provider.ts +124 -53
  603. package/src/node/profile-capture.ts +9 -3
  604. package/src/node/profiling-run.ts +30 -8
  605. package/src/node/rename-over-open-readers.ts +78 -0
  606. package/src/node/socket-launcher.ts +24 -8
  607. package/src/node/stdio-launcher.ts +8 -7
  608. package/src/testing/fake-document.ts +24 -5
  609. package/src/testing/index.ts +2 -1
  610. package/src/testing/langium-test-helpers.ts +1 -0
  611. package/src/testing/make-noop-shared-services.ts +50 -2
  612. package/src/testing/make-test-services.ts +125 -31
  613. package/src/testing/make-test-tracer.ts +26 -0
  614. package/src/testing/node/index.ts +1 -0
  615. package/src/testing/node/lsp-harness.ts +2 -0
  616. package/src/testing/node/lsp-server-connection.ts +66 -12
  617. package/src/testing/node/scratch-workspace.ts +10 -5
  618. package/src/testing/node/spawned-server.ts +36 -2
  619. package/src/testing/node/unhandled-rejections.ts +31 -0
  620. package/src/testing/parse-semantic-root.ts +1 -1
  621. package/src/testing/playwright/flaky-network-proxy.ts +240 -0
  622. package/src/testing/playwright/index.ts +1 -0
  623. package/src/testing/playwright/server-log-capture.ts +45 -11
  624. package/src/testing/playwright/server-log-rename-reporter.ts +12 -1
  625. package/src/testing/run-update-pipeline.ts +4 -4
  626. package/src/testing/stub-ast-document-manager.ts +36 -138
  627. package/src/testing/stub-document-builder.ts +102 -18
  628. package/src/testing/stub-hydranium-text-documents.ts +165 -27
  629. package/src/testing/stub-langium-documents.ts +3 -2
  630. package/src/testing/stub-model-service.ts +9 -8
  631. package/src/testing/stub-self-save-registry.ts +1 -1
  632. package/src/testing/stub-service-registry.ts +1 -1
  633. package/src/testing/stub-writable-file-system.ts +1 -1
  634. package/src/util/connection-liveness.ts +37 -14
  635. package/src/util/environment.ts +9 -1
  636. package/lib/documents/language-client-text-shadow.d.ts +0 -101
  637. package/lib/documents/language-client-text-shadow.d.ts.map +0 -1
  638. package/lib/documents/language-client-text-shadow.js +0 -156
  639. package/lib/documents/language-client-text-shadow.js.map +0 -1
  640. package/lib/documents/self-save-registry.d.ts.map +0 -1
  641. package/lib/documents/self-save-registry.js.map +0 -1
  642. package/lib/lsp/instrument-connection.d.ts +0 -36
  643. package/lib/lsp/instrument-connection.d.ts.map +0 -1
  644. package/lib/lsp/instrument-connection.js +0 -62
  645. package/lib/lsp/instrument-connection.js.map +0 -1
  646. package/lib/node/process-memory.d.ts +0 -66
  647. package/lib/node/process-memory.d.ts.map +0 -1
  648. package/lib/node/process-memory.js +0 -252
  649. package/lib/node/process-memory.js.map +0 -1
  650. package/src/documents/language-client-text-shadow.ts +0 -175
  651. package/src/lsp/instrument-connection.ts +0 -66
  652. package/src/node/process-memory.ts +0 -299
@@ -9,42 +9,61 @@
9
9
 
10
10
  import {
11
11
  type CanonicalUri,
12
- type CloseModelArgs,
13
- ConflictError,
14
- Logger,
12
+ defineMessage,
15
13
  type MaybeObservableValue,
16
14
  type MaybePromise,
17
15
  ObservableValue,
18
- type TransferDiagnostic,
16
+ randomUuid,
17
+ TIMED_OUT,
19
18
  type TransferElement,
20
- type OpenModelArgs,
19
+ type TextVersion,
21
20
  type Tracer,
22
- type TransferSaveArgs,
23
- type TransferUpdateArgs
21
+ UNRECORDED_VERSION
24
22
  } from '@hydranium/protocol';
25
- import { type AstNode, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
23
+ import { type AstNode, DocumentState, type LangiumDocument, OperationCancelled, UriUtils, type URI } from '@hydranium/langium';
24
+ import { type AstDiagnostic } from '../validation/document-validator.js';
26
25
  import { type DocumentUriPolicy } from '../workspace/document-uri-policy.js';
27
- import { ReentrantWriteLockError, isInsideWriteLock } from '../workspace/write-lock-scope.js';
28
- import { type CancellationToken, type Disposable } from 'vscode-languageserver';
29
- import { AstDocument, type AstDocumentSavedEvent, type AstDocumentUpdatedEvent } from '../../documents/ast-document-manager.js';
26
+ import { ReentrantWriteLockError, isInsideWriteLock, isWriteLockScopeInstalled } from '../workspace/write-lock-scope.js';
27
+ import { CancellationToken, Disposable } from 'vscode-languageserver';
28
+ import { AstDocument } from '../../documents/ast-document-manager.js';
30
29
  import { isConnectionGoneError } from '../../util/connection-liveness.js';
31
30
  import { type LogNameOptions } from '../diagnostics/logger.js';
32
31
  import { IntegrityService } from '../integrity/integrity-service.js';
33
32
  import { labelPhaseListener } from '../document-builder/labeled-phase-listener.js';
34
33
  import { LANGUAGE_CLIENT_ID } from '../../documents/client-ids.js';
34
+ import { type OpenOptions } from '../../documents/client-session-registry.js';
35
35
  import { type ServerSharedServices } from '../module.js';
36
-
37
- /** Max time {@link ModelService.settleSave} waits for the build to settle and the sync chain to drain. */
38
- const SAVE_SETTLE_TIMEOUT_MS = 10_000;
36
+ import { type ClientSession } from './client-session.js';
37
+ import {
38
+ type ModelDeletedEvent,
39
+ type ModelDirtyChangedEvent,
40
+ type ModelEventFilter,
41
+ type ModelPhaseFilter,
42
+ type ModelReleasedEvent,
43
+ type ModelSavedEvent,
44
+ type ModelsBuiltEvent,
45
+ type ModelUpdatedEvent
46
+ } from './model-events.js';
39
47
 
40
48
  /**
41
- * Marks the {@link SAVE_SETTLE_TIMEOUT_MS} branch of
42
- * {@link ModelService.settleSave}'s race so it stays distinguishable from a
43
- * genuine rejection (a cancelled token, an `applyEdit` reverse-RPC error, a
44
- * build throw). With a plain `Error` the only log line an adopter has blames
45
- * the timeout for every one of them, which points debugging at the wrong layer.
49
+ * The undo-stack entry for a server-authored write pushed to the editor.
50
+ *
51
+ * **A user-facing LABEL, not a log string**, which is easy to miss because it
52
+ * travels as an options field rather than as a message: LSP specifies
53
+ * `ApplyWorkspaceEditParams.label` as "presented in the user interface for
54
+ * example on an undo stack to undo the workspace edit". So a user who edits
55
+ * through a form or drags a diagram node reads this in their editor's undo menu
56
+ * — which is why it is rendered like any other message the server sends rather
57
+ * than left as the English literal it was.
58
+ *
59
+ * Parameterless deliberately. The obvious improvement is to name the document,
60
+ * and it is the wrong one: an undo menu is already grouped under the file, so
61
+ * the URI would be noise in the one place it is redundant.
46
62
  */
47
- class SaveSettleTimeoutError extends Error {}
63
+ export const MODEL_UPDATE_EDIT = defineMessage('hydranium/core/model-update-edit', 'Update Model');
64
+
65
+ /** Max time {@link DefaultModelService.settleSave} waits for the build to settle and the sync chain to drain. */
66
+ const SAVE_SETTLE_TIMEOUT_MS = 10_000;
48
67
 
49
68
  /**
50
69
  * Constructor options for {@link ModelService}. All fields are optional,
@@ -52,75 +71,63 @@ class SaveSettleTimeoutError extends Error {}
52
71
  */
53
72
  export interface ModelServiceOptions extends LogNameOptions {
54
73
  /**
55
- * When set, {@link ModelService.update} logs a `warn` line if its
56
- * end-to-end wait (serialise + content-change apply + rebuild +
57
- * settled-phase wait) exceeds this many milliseconds. Default
58
- * `undefined` (no warn line ever emitted; the underlying
59
- * `Logger.time` debug timing log is unchanged either way).
60
- *
61
- * Pure observability — does NOT abort the update, does NOT change
62
- * resolution semantics. Adopters wanting a hard timeout that throws
63
- * instead override {@link ModelService.update} on their subclass and
64
- * race the parent call against their own deadline.
65
- *
66
- * Recommended starting threshold: 2-5 seconds for interactive paths
67
- * (form save, diagram edit). Workspaces with very large documents
68
- * or slow validation may legitimately exceed 5s on the cold path —
69
- * tune per workspace.
70
- *
71
- * Accepts a {@link MaybeObservableValue} so the threshold can be a
72
- * fixed constant or bound to a user setting via `Settings.number`
73
- * and retuned live. Leaving it unset disables the warn line entirely
74
- * (and skips the per-update stopwatch).
75
- */
76
- readonly slowUpdateWarnMs?: MaybeObservableValue<number>;
77
- /**
78
- * Serialise the facade's own build under the workspace WRITE lock, the way
79
- * Langium's `DefaultDocumentUpdateHandler` dispatches its build. Default
80
- * `true`.
74
+ * Let the facade's build run without the workspace write lock when its
75
+ * caller already holds it: an integrity rule or build-phase pass that
76
+ * writes back through a session's `update` / `save`, or calls `rebuild`.
77
+ * Default `false`.
81
78
  *
82
- * **Why it defaults on.** Unlocked, the facade's build races the LSP bridge's
83
- * build of the same URI — both are legitimate (the bridge exists only under a
84
- * `Connection`, so the facade stands in for it headless), but nothing
85
- * serialises them, so both run a full validation pass and Langium appends the
86
- * second onto the first. Every diagnostic is then duplicated, and the
87
- * duplication compounds per rebuild. Serialised, Langium elides the second
88
- * build entirely, so the redundant work goes too.
79
+ * `WorkspaceLock` is not reentrant. Taking it from inside a holder cancels
80
+ * that holder and then waits for it to end, while the holder waits for this
81
+ * call, so neither completes. On `false` that call fails with
82
+ * {@link ReentrantWriteLockError} instead, wherever a host installs a
83
+ * write-lock scope tracker (`@hydranium/core/node` does at entry load); on
84
+ * `true` its build takes no lock. The wait after that build can still hang,
85
+ * because a document no build will carry is re-queued through the lock, and
86
+ * the re-queue waits for the holder to end.
89
87
  *
90
- * **What `false` costs.** The facade's build is then unserialised and can run
91
- * concurrently with the bridge's build of the same URI, so the affected
92
- * documents are validated twice per write — double the validation work.
93
- * Reported diagnostics stay correct even then, because
94
- * `HydraniumDocumentBuilder.dedupeDiagnostics` collapses the byte-identical
95
- * duplicates a repeated pass produces before any listener sees them; what this
96
- * option removes is the wasted pass, not just its visible symptom.
97
- *
98
- * **What `false` buys.** `WorkspaceLock` is not reentrant. A caller that
99
- * reaches `update` / `save` / `rebuild` while already holding the write lock —
100
- * an integrity rule or build-phase pass that writes through this facade —
101
- * deadlocks: acquiring the lock cancels the running holder, and the new
102
- * acquisition then waits for that holder to release while the holder waits
103
- * for this call. On `true` that shape is DETECTED and rejected with
104
- * {@link ReentrantWriteLockError} rather than hanging, wherever a host
105
- * installs a write-lock scope tracker (`@hydranium/core/node` does at entry
106
- * load; see {@link isInsideWriteLock}). Setting `false` is the escape hatch
107
- * for an adopter whose reentrant shape is unavoidable — nothing acquires the
108
- * lock then, so there is nothing to be reentrant about; prefer it over
109
- * unserialised builds only in that case.
88
+ * Every other facade build takes the lock on either value. Unlocked, it can
89
+ * overlap another build of the same document: both run a full validation
90
+ * pass that Langium appends, and a caller can be handed a version that an
91
+ * integrity repair still running in the other build then moves past. Without
92
+ * a tracker the two cases cannot be told apart (see
93
+ * {@link isWriteLockScopeInstalled}), so `true` builds without the lock every
94
+ * time and accepts both.
110
95
  *
111
96
  * Accepts a {@link MaybeObservableValue} so it can be bound to a setting and
112
97
  * flipped without a restart.
113
98
  */
114
- readonly serializeBuilds?: MaybeObservableValue<boolean>;
99
+ readonly allowReentrantBuilds?: MaybeObservableValue<boolean>;
100
+ }
101
+
102
+ /** One {@link ModelService.onModelUpdated} subscription; `uri` is canonical, absent for every document. */
103
+ export interface ModelUpdateSubscriber<TAst extends AstNode, TDiagnostic extends AstDiagnostic = AstDiagnostic> {
104
+ readonly uri?: CanonicalUri;
105
+ readonly listener: (event: ModelUpdatedEvent<TAst, TDiagnostic>) => void;
106
+ }
107
+
108
+ /** Options for a {@link DefaultModelService} wait on one document. */
109
+ export interface SyncedWaitOptions {
110
+ /**
111
+ * Build a root parsed from text older than the store's at the call, and
112
+ * reject once that build, or one the builder re-queues, is given up. Without
113
+ * it, such a root is left to other builds, and a wait they never end stays
114
+ * pending until its token is cancelled.
115
+ */
116
+ readonly sync?: boolean;
115
117
  }
116
118
 
117
119
  /**
120
+ * The seam every non-LSP head talks to: the data server, the GLSP head and an
121
+ * adopter's own services reach documents through this slot rather than through
122
+ * the workspace stores.
123
+ *
118
124
  * In-process facade over the framework's document plumbing
119
125
  * (`HydraniumTextDocuments`, `LangiumDocuments`,
120
- * `DocumentBuilder`, `WritableFileSystemProvider`). Owns the
121
- * `open / request / update / save / ready` lifecycle that protocol heads
122
- * (LSP, data-server, GLSP) delegate to so coordinating those primitives
123
- * doesn't have to be re-implemented per-head.
126
+ * `DocumentBuilder`, `WritableFileSystemProvider`). Owns the document
127
+ * lifecycle the data-server and GLSP heads delegate to — client sessions that
128
+ * open, update, save and close documents, the phase reads, and `ready` — so
129
+ * coordinating those primitives doesn't have to be re-implemented per head.
130
+ * Every open and write goes through a session from {@link createSession}.
124
131
  *
125
132
  * "Model" here means the parsed AST — distinct from the wire-shape
126
133
  * `TransferDocument` in `@hydranium/protocol`.
@@ -130,9 +137,9 @@ export interface ModelServiceOptions extends LogNameOptions {
130
137
  * Multiple in-process consumers want the same workspace-level
131
138
  * operations:
132
139
  * - The data-server head turns these into typed RPC methods.
133
- * - The GLSP head uses the same lifecycle for diagram-driven edits;
134
- * GModel operation handlers route through `update` for AST mutation,
135
- * `waitForDocumentState` for indexed-phase waits before reads, etc.
140
+ * - The GLSP head uses the same lifecycle for diagram-driven edits: GModel
141
+ * operation handlers write through the diagram's session and wait on phases
142
+ * before reading.
136
143
  * - Server-internal callers (integrity service, ad-hoc bridges, tests)
137
144
  * want the same operations without the wire serialisation step.
138
145
  *
@@ -145,15 +152,16 @@ export interface ModelServiceOptions extends LogNameOptions {
145
152
  *
146
153
  * **Read-latest supersession**
147
154
  *
148
- * The default `update` and `save` flows use Langium's per-URI
149
- * `DocumentBuilder.waitUntil` to wait for the integrity-settled landmark
150
- * ({@link IntegrityService.SettledState}), then read the post-build state. Concurrent
151
- * in-process callers on the same URI all see the latest post-build
152
- * snapshot — none deadlock waiting for a specific version's settled
153
- * event. Adopters wanting strict version-matched semantics (resolve
154
- * with vN's snapshot specifically, log "vN superseded by vM at vN+1")
155
- * override {@link update} to attach a phase-listener with explicit
156
- * version checks; the framework default doesn't need it for safety.
155
+ * A session's default `update` and `save` use Langium's per-URI
156
+ * `DocumentBuilder.waitUntil` to wait for `Validated` (the integrity-settled
157
+ * landmark {@link IntegrityService.SettledState} when rebuilds do not
158
+ * validate), then read the post-build state. Concurrent in-process callers
159
+ * on the same URI all see the latest post-build snapshot — none deadlock
160
+ * waiting for a specific version's settled event. Adopters wanting strict
161
+ * version-matched semantics (resolve with vN's snapshot specifically, log
162
+ * "vN superseded by vM at vN+1") override
163
+ * `DefaultClientSession.updateDocument` to attach a phase-listener with
164
+ * explicit version checks; the framework default doesn't need it for safety.
157
165
  *
158
166
  * **Returns AST snapshots, not wire envelopes**
159
167
  *
@@ -166,27 +174,172 @@ export interface ModelServiceOptions extends LogNameOptions {
166
174
  * the injected `TransferEncoder` — symmetric with the
167
175
  * `getModelDocument` envelope path.
168
176
  *
169
- * **Subscriptions** ({@link onModelUpdated} / {@link onModelSaved} /
170
- * {@link onClientClosed}) are thin pass-throughs over
171
- * `DocumentBuilder.onDocumentPhase` and
172
- * `HydraniumTextDocuments.onDidSave` / `onDidClose`. Filtering
173
- * by URI happens here so consumers can subscribe per-document without
174
- * implementing the URI gate at each callsite.
177
+ * **Subscriptions** (`on*`) are how a head follows documents; it subscribes
178
+ * here rather than to the builder or the text store. Each takes a filter, and
179
+ * one without a `uri` hears every document.
180
+ *
181
+ * **Two families.** `waitFor*` only waits: it rejects for a URI with no
182
+ * document, and for a root behind the store's text it waits for whatever
183
+ * builds it next, so it never ends if nothing does. `ensureDocumentState` and
184
+ * the phase shorthands over it build a missing document, and build a root
185
+ * behind its text, rejecting when that build fails twice. Both re-queue a
186
+ * document the builder's last build left short of the state.
187
+ *
188
+ * Both resolve at the state with a root parsed from text no older than the
189
+ * store's version at the call; inside the write lock, at the state alone, since
190
+ * the build that would sync the document to that version cannot start until
191
+ * it is released.
192
+ *
193
+ * Do not await one inside a build phase listener: a browser host installs no
194
+ * write-lock scope, so the wait cannot tell it is inside a build and waits for
195
+ * one that cannot start. Nor inside a `WorkspaceLock.read`: the lock starts no
196
+ * write, the build included, while a read runs.
197
+ *
198
+ * **Diagnostics are typed `never` below `Validated`.** Validation is the last
199
+ * phase, so at any earlier landmark the array either is not yet computed or
200
+ * still holds the previous build's, and reading it would take stale results
201
+ * for fresh ones. A caller that needs diagnostics asks for {@link validated}.
202
+ *
203
+ * What the `never` buys, exactly: reading a field off an element is a compile
204
+ * error, and nothing can be appended. It does NOT stop a caller assigning an
205
+ * element to a typed variable, because `never` is assignable to everything — so
206
+ * this is a guard against reaching for diagnostics by accident, not a seal
207
+ * against doing it deliberately.
208
+ *
209
+ * The waits resolve at or ABOVE their target, so an already-validated document
210
+ * does carry usable diagnostics and the `never` over-forbids there. That
211
+ * direction is the safe one: the alternative permits stale reads silently. A
212
+ * member taking a phase as a PARAMETER returns `TDiagnostic`, and leaves them
213
+ * absent for a phase below `Validated`.
175
214
  *
176
215
  * **Generic parameters.**
177
216
  * - `TAst` — the AST root type each consumer expects on the returned
178
217
  * {@link AstDocument}. Constrained to {@link AstNode}.
179
- * - `TDiagnostic` — wire diagnostic shape used by the injected
180
- * `TransferEncoder`. Defaults to {@link TransferDiagnostic}.
181
- * - `TTransfer` — transfer-model root accepted by `update` / `save`
218
+ * - `TDiagnostic` — the AST-layer diagnostic: whatever the build left on
219
+ * `LangiumDocument.diagnostics`, carried through on the returned
220
+ * {@link AstDocument}. Defaults to {@link AstDiagnostic}.
221
+ * **Not the `TransferEncoder`'s parameter of the same name**, which is
222
+ * that encoder's OUTPUT and so names the wire shape. This one names its
223
+ * input, and an adopter binds the two to different types.
224
+ * - `TTransfer` — transfer-model root a session's `update` / `save` accept
182
225
  * args. Constrained to {@link TransferElement}. Defaults to the
183
226
  * structural base.
184
227
  */
185
- export class ModelService<
228
+ export interface ModelService<
186
229
  TAst extends AstNode,
187
- TDiagnostic = TransferDiagnostic,
230
+ TDiagnostic extends AstDiagnostic = AstDiagnostic,
231
+ TTransfer extends TransferElement = TransferElement
232
+ > {
188
233
  /**
189
- * Structured payload accepted by `update` / `save`. Constrained to
234
+ * Resolves once the workspace has been initialised and its first build has
235
+ * completed — the gate every read should wait behind, since a document
236
+ * queried before it may be unbuilt and reach no phase.
237
+ *
238
+ * A property rather than a method, matching `ProjectManager.ready` and
239
+ * Langium's `WorkspaceManager.ready`. An implementation needing a stricter
240
+ * gate supplies a Promise that awaits its own concern as well.
241
+ */
242
+ readonly ready: Promise<void>;
243
+
244
+ // Wait only; a root behind its text is left to another build.
245
+ waitForDocumentState(uri: string, state: DocumentState, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>>;
246
+ waitForDocumentSettled(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>>;
247
+ waitForBuilderState(state: DocumentState, cancelToken?: CancellationToken): Promise<void>;
248
+
249
+ // Build what is missing or behind its text, then wait.
250
+ ensureDocumentState(uri: string, state?: DocumentState, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>>;
251
+ rebuild(uri: string, state?: DocumentState, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>>;
252
+ /**
253
+ * Throw where {@link rebuild} would reject as reentrant. A write calls it
254
+ * before applying its text: a text applied and then refused stays applied
255
+ * with no build to follow it.
256
+ */
257
+ assertCanBuild(uri: string): void;
258
+ parsed(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>>;
259
+ linked(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>>;
260
+ settled(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>>;
261
+ indexed(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>>;
262
+ validated(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>>;
263
+
264
+ isOpen(uri: string): boolean;
265
+ /**
266
+ * The version the document at `uri` was opened at, which a client's write
267
+ * or an integrity repair steps past; `undefined` while it is not open.
268
+ */
269
+ openedVersion(uri: string): TextVersion | undefined;
270
+ snapshot(uri: string): AstDocument<TAst, TDiagnostic> | undefined;
271
+ /**
272
+ * The text a session's write of `model` to `uri` applies: a textual model
273
+ * as given, a structured one rewritten and serialised.
274
+ */
275
+ modelToText(uri: string, model: TTransfer | string, cancelToken?: CancellationToken): Promise<string>;
276
+ getDocument(uri: string): LangiumDocument | undefined;
277
+
278
+ /**
279
+ * Fires as a document reaches the filter's phase, `Validated` by default.
280
+ * Listeners run inside the build, so one that throws is logged and the
281
+ * others still run.
282
+ */
283
+ onModelUpdated(listener: (event: ModelUpdatedEvent<TAst, TDiagnostic>) => void, filter?: ModelPhaseFilter): Disposable;
284
+ /**
285
+ * Fires once per build that reaches the phase, with every document it
286
+ * carried there. A listener that throws is logged, as for {@link onModelUpdated}.
287
+ */
288
+ onModelsBuilt(listener: (event: ModelsBuiltEvent) => void, filter?: Pick<ModelPhaseFilter, 'phase'>): Disposable;
289
+ /**
290
+ * Fires for every save, whichever client made it, as the store announces
291
+ * it. A document saved before its first build arrives as an empty envelope
292
+ * at `UNRECORDED_VERSION`, whose `root` is `undefined` despite its type.
293
+ */
294
+ onModelSaved(listener: (event: ModelSavedEvent<TAst, TDiagnostic>) => void, filter?: ModelEventFilter): Disposable;
295
+ onModelDeleted(listener: (event: ModelDeletedEvent) => void, filter?: ModelEventFilter): Disposable;
296
+ /** Fires when a document's text starts or stops differing from its file. */
297
+ onDirtyChanged(listener: (event: ModelDirtyChangedEvent) => void, filter?: ModelEventFilter): Disposable;
298
+ /**
299
+ * Fires when the store releases a document no client has open any more.
300
+ * What the build keeps for it is up to the
301
+ * `DocumentReleaseHandler` slot; the default reverts it to disk, and that
302
+ * rebuild follows as an {@link onModelUpdated} event, unless a client opens
303
+ * the document first or its file is deleted.
304
+ */
305
+ onModelReleased(listener: (event: ModelReleasedEvent) => void, filter?: ModelEventFilter): Disposable;
306
+ /** Fires when `filter.clientId` closes `filter.uri`, its session ending included. */
307
+ onClientClosed(listener: () => void, filter: { readonly uri: string; readonly clientId: string }): Disposable;
308
+
309
+ /**
310
+ * Start a client session, the only way to open and write documents through
311
+ * this service. Pass a `label` naming the participant; without one it is
312
+ * `session`. The id defaults to `label#` plus a random UUID; a fixed
313
+ * `clientId` is taken as given. Throws `ReservedClientIdError` when the id
314
+ * is reserved by the framework, and `DuplicateClientIdError` when it is
315
+ * held by another live session or has documents open under it as a client
316
+ * that is not a session.
317
+ *
318
+ * A `resumeToken` matching the one the live session under `clientId` was
319
+ * started with ends that session as lost first, so the documents it was
320
+ * last to hold keep their unsaved text for the new one. The token guards
321
+ * against taking over a session by accident, not against a peer: anyone who
322
+ * knows it can end the session.
323
+ *
324
+ * `TOpenOptions` types the options the session's `open` takes and its
325
+ * `openOptions` returns. The narrowing is an unchecked cast, and it holds
326
+ * only for the caller that started the session: a holder reached through
327
+ * {@link getSession} sees plain `OpenOptions`.
328
+ */
329
+ createSession<TOpenOptions extends OpenOptions = OpenOptions>(
330
+ label?: string,
331
+ clientId?: string,
332
+ options?: { readonly resumeToken?: string }
333
+ ): ClientSession<TAst, TDiagnostic, TTransfer, TOpenOptions>;
334
+ /** The live session started under `clientId`, or `undefined` once it has ended or was never started. */
335
+ getSession(clientId: string): ClientSession<TAst, TDiagnostic, TTransfer> | undefined;
336
+ }
337
+
338
+ export class DefaultModelService<
339
+ TAst extends AstNode,
340
+ TDiagnostic extends AstDiagnostic = AstDiagnostic,
341
+ /**
342
+ * Structured payload a session's `update` / `save` accept. Constrained to
190
343
  * {@link TransferElement} — the minimal `{ readonly $type: string }`
191
344
  * shape. Both transfer-model overlay roots (which extend
192
345
  * `TransferElement` explicitly) and AST root types (which have
@@ -195,7 +348,7 @@ export class ModelService<
195
348
  * integrity service) that pass AST roots remain compatible.
196
349
  */
197
350
  TTransfer extends TransferElement = TransferElement
198
- > {
351
+ > implements ModelService<TAst, TDiagnostic, TTransfer> {
199
352
  protected readonly tracer: Tracer;
200
353
  /**
201
354
  * The single document-identity seam (`services.workspace.DocumentUriPolicy`),
@@ -206,14 +359,8 @@ export class ModelService<
206
359
  * (see {@link DocumentUriPolicy}).
207
360
  */
208
361
  protected readonly uriPolicy: DocumentUriPolicy;
209
- /**
210
- * Live slow-update-warn threshold cell, or `undefined` when the option
211
- * was not supplied (warn line + stopwatch disabled). Reads `.value` per
212
- * update so a setting-bound threshold retunes without reconstruction.
213
- */
214
- protected readonly slowUpdateWarn?: ObservableValue<number>;
215
- /** See {@link ModelServiceOptions.serializeBuilds}. Defaults to `true`. */
216
- protected readonly serializeBuilds: ObservableValue<boolean>;
362
+ /** See {@link ModelServiceOptions.allowReentrantBuilds}. Defaults to `false`. */
363
+ protected readonly allowReentrantBuilds: ObservableValue<boolean>;
217
364
 
218
365
  /**
219
366
  * Per-URI applyEdit coalescing: at most one in-flight `applyEditToLanguageClient`
@@ -224,6 +371,23 @@ export class ModelService<
224
371
  protected readonly syncChains = new Map<string, Promise<void>>();
225
372
  protected readonly pendingSync = new Map<string, string>();
226
373
 
374
+ /** The live sessions this service started, by client id, for {@link getSession}. */
375
+ protected readonly sessions = new Map<string, ClientSession<TAst, TDiagnostic, TTransfer>>();
376
+ /**
377
+ * Drops an ended session from {@link sessions}. Subscribed by the first
378
+ * {@link createSession} rather than at construction, so a services tree with
379
+ * no text store, or one that knows nothing of sessions, still constructs
380
+ * this service.
381
+ */
382
+ protected sessionCloseListener?: Disposable;
383
+ /** The token each live session was started with, by client id, for a takeover by {@link createSession}. */
384
+ protected readonly resumeTokens = new Map<string, string>();
385
+ /**
386
+ * The {@link onModelUpdated} subscribers, by phase. One builder listener per
387
+ * phase serves them all, kept for the life of the service.
388
+ */
389
+ protected readonly updateSubscribers = new Map<DocumentState, Set<ModelUpdateSubscriber<TAst, TDiagnostic>>>();
390
+
227
391
  /**
228
392
  * Workspace-level readiness gate. Resolves when the framework has
229
393
  * finished its first workspace build cycle and the `ModelService`
@@ -264,21 +428,17 @@ export class ModelService<
264
428
  ) {
265
429
  this.tracer = services.Tracer.for(options.logName ?? 'ModelService').trace('instantiated');
266
430
  this.uriPolicy = services.workspace.DocumentUriPolicy;
267
- this.slowUpdateWarn = options.slowUpdateWarnMs !== undefined ? ObservableValue.from(options.slowUpdateWarnMs) : undefined;
268
- this.serializeBuilds = ObservableValue.from(options.serializeBuilds ?? true);
431
+ this.allowReentrantBuilds = ObservableValue.from(options.allowReentrantBuilds ?? false);
269
432
  // Optional-chain so a harness that binds no WorkspaceManager awaits
270
433
  // `undefined` and resolves immediately; production hosts always have it
271
434
  // bound.
272
435
  // Deliberately NO fallback to Langium's `ready`: it resolves pre-build,
273
436
  // so falling back to it would silently reinstate the very gap this gate
274
437
  // exists to close.
275
- // Captured rather than read off `this` inside the closure, which TS cannot
276
- // prove runs after the field is assigned.
277
- const tracer = this.tracer;
278
438
  this.ready = (async () => {
279
439
  try {
280
440
  await services.workspace.WorkspaceManager?.workspaceInitialized;
281
- } catch (error: unknown) {
441
+ } catch {
282
442
  // NEVER rejects, deliberately. This gate is about TIMING — "the
283
443
  // initial build has finished" — not about whether it succeeded, and
284
444
  // Langium's `ready` (what it replaced) could not reject at all.
@@ -286,8 +446,8 @@ export class ModelService<
286
446
  // build (routine — any write preempts one) and on a failed one
287
447
  // (e.g. a disposed connection at teardown). Propagating either would
288
448
  // fail every `waitForReady` for the rest of the process lifetime,
289
- // a far worse failure than the late gate this exists to fix.
290
- tracer.debug(`Initial workspace build did not complete cleanly: ${error instanceof Error ? error.message : String(error)}`);
449
+ // a far worse failure than the late gate this exists to fix. The
450
+ // workspace manager logs the outcome.
291
451
  }
292
452
  })();
293
453
  // One persistent listener mirroring non-LSP-client changes back to the LSP
@@ -309,10 +469,12 @@ export class ModelService<
309
469
  // ============================================================
310
470
 
311
471
  /**
312
- * Wait for the document at `uri` to reach `state`. Pure wait — does
313
- * not trigger a build. If `uri` is not yet in the document registry
314
- * the call will hang until something else drives it through the
315
- * pipeline; for the cold-start case use {@link rebuild} instead.
472
+ * Wait for the document at `uri` to reach `state` with a root no older than
473
+ * the store's text at the call. Rejects if `uri` is not in the document
474
+ * registry. A root behind its text is not built: the wait lasts until
475
+ * something else builds it, so use {@link ensureDocumentState} where
476
+ * nothing may. Builds that keep failing leave the wait pending, to its
477
+ * cancellation token.
316
478
  *
317
479
  * Wrapped in a debug-level timing log via {@link Tracer.time} so
318
480
  * slow per-URI waits surface in build telemetry; the URI is
@@ -326,11 +488,12 @@ export class ModelService<
326
488
  * Wait for the document at `uri` to reach the integrity-settled landmark
327
489
  * ({@link IntegrityService.SettledState}) — the earliest phase at which the
328
490
  * AST + serialised text are stable post-integrity. Convenience wrapper over
329
- * {@link waitForDocumentState} for the common "wait until content is stable"
330
- * case (e.g. settling a save). Pure wait — does not trigger a build.
491
+ * {@link waitForDocumentState}, and like it builds nothing behind its text.
331
492
  */
332
- async waitForDocumentSettled(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>> {
333
- return this.waitForDocumentStateCanonical(this.uriPolicy.canonicalUri(uri), IntegrityService.SettledState, cancelToken);
493
+ async waitForDocumentSettled(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>> {
494
+ return this.withoutDiagnostics(
495
+ await this.waitForDocumentStateCanonical(this.uriPolicy.canonicalUri(uri), IntegrityService.SettledState, cancelToken)
496
+ );
334
497
  }
335
498
 
336
499
  /**
@@ -342,21 +505,108 @@ export class ModelService<
342
505
  * the identity once instead of re-running the (filesystem-touching) `realpath`
343
506
  * at every wait. The `CanonicalUri` parameter type enforces that — a raw
344
507
  * `string` cannot be passed without minting through the URI policy.
508
+ *
509
+ * With `options.sync`, a root behind the store's text is built, as in
510
+ * {@link ensureDocumentState}; without it, the root is left to other builds,
511
+ * as in {@link waitForDocumentState}. Below `Validated` the envelope has no
512
+ * diagnostics: see {@link withoutDiagnostics}.
345
513
  */
346
514
  protected async waitForDocumentStateCanonical(
347
515
  uri: CanonicalUri,
348
516
  state: DocumentState,
349
- cancelToken?: CancellationToken
517
+ cancelToken?: CancellationToken,
518
+ options: SyncedWaitOptions = {}
350
519
  ): Promise<AstDocument<TAst, TDiagnostic>> {
351
520
  const documentUri = UriUtils.toUri(uri);
521
+ // Read at call time: a later edit must not extend this wait.
522
+ const textVersion = isInsideWriteLock() ? undefined : this.services.workspace.TextDocuments.textState(uri)?.version;
352
523
  await this.tracer
353
524
  .withUri(uri)
354
525
  .time(
355
526
  `Wait for document state '${DocumentState[state]}'`,
356
- () => this.services.workspace.DocumentBuilder.waitUntil(state, documentUri, cancelToken),
527
+ () => this.waitUntilSynced(documentUri, state, textVersion, cancelToken, options),
357
528
  'debug'
358
529
  );
359
- return this.toAstDocument(documentUri);
530
+ const document = this.toAstDocument(documentUri);
531
+ return state >= DocumentState.Validated ? document : this.withoutDiagnostics(document);
532
+ }
533
+
534
+ /**
535
+ * Wait for `state` with a root parsed from text at `textVersion` or later. A
536
+ * root no factory recorded counts as synced, since no build records it.
537
+ * With `options.sync`, a root still behind is built through
538
+ * `VersionSyncService.syncTo`, and the wait rejects once that build, or one
539
+ * the builder re-queues to reach `state`, is given up. Without it, the wait
540
+ * lasts until another build parses the text, and stays pending when the
541
+ * builder gives up re-queuing the document.
542
+ */
543
+ protected async waitUntilSynced(
544
+ uri: URI,
545
+ state: DocumentState,
546
+ textVersion: TextVersion | undefined,
547
+ cancelToken?: CancellationToken,
548
+ options: SyncedWaitOptions = {}
549
+ ): Promise<void> {
550
+ const builder = this.services.workspace.DocumentBuilder;
551
+ const sync = this.services.workspace.VersionSyncService;
552
+ const waitOptions = { rejectWhenStuck: options.sync === true };
553
+ await builder.waitUntil(state, uri, cancelToken, waitOptions);
554
+ if (textVersion === undefined) {
555
+ return;
556
+ }
557
+ while (!sync.isSyncedTo(uri, textVersion)) {
558
+ const build = options.sync === true ? sync.syncTo(uri, textVersion) : undefined;
559
+ this.tracer
560
+ .withUri(uri.toString())
561
+ .debug(`waiting for ${uri.toString()} to reach ${DocumentState[state]} at v${textVersion} or later`);
562
+ await this.nextParseOrDeletion(uri, cancelToken, build);
563
+ await builder.waitUntil(state, uri, cancelToken, waitOptions);
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Resolves once a parse of `uri` has been recorded or a build has deleted
569
+ * it, rejecting with `OperationCancelled` when `cancelToken` is cancelled
570
+ * first, and with an error when `build`, the build requested for it, is
571
+ * given up. A `Parsed` phase listener cannot serve: a cancel right after the
572
+ * parse skips it, and the resumed build does not parse again.
573
+ */
574
+ protected nextParseOrDeletion(
575
+ uri: URI,
576
+ cancelToken: CancellationToken = CancellationToken.None,
577
+ build?: Promise<boolean>
578
+ ): Promise<void> {
579
+ const builder = this.services.workspace.DocumentBuilder;
580
+ return new Promise<void>((resolve, reject) => {
581
+ // A cancelled token's listener runs a macrotask later, after a build
582
+ // that started meanwhile may have parsed.
583
+ if (cancelToken.isCancellationRequested) {
584
+ reject(OperationCancelled);
585
+ return;
586
+ }
587
+ const done = (settle: () => void): void => {
588
+ parsed.dispose();
589
+ deleted.dispose();
590
+ cancelled.dispose();
591
+ settle();
592
+ };
593
+ const parsed = this.services.workspace.VersionSyncService.onDidRecordModel(document => {
594
+ if (UriUtils.equals(document.uri, uri)) {
595
+ done(resolve);
596
+ }
597
+ });
598
+ const deleted = builder.onUpdate((_changed, deletedUris) => {
599
+ if (deletedUris.some(deletedUri => UriUtils.equals(deletedUri, uri))) {
600
+ done(resolve);
601
+ }
602
+ });
603
+ const cancelled = cancelToken.onCancellationRequested(() => done(() => reject(OperationCancelled)));
604
+ void build?.then(built => {
605
+ if (!built) {
606
+ done(() => reject(new Error(`The build that would sync ${uri.toString()} to its text failed`)));
607
+ }
608
+ });
609
+ });
360
610
  }
361
611
 
362
612
  /**
@@ -380,31 +630,35 @@ export class ModelService<
380
630
  * Force a fresh build of the document at `uri` and wait for it to
381
631
  * reach `state` (or the integrity-settled landmark
382
632
  * {@link IntegrityService.SettledState} if omitted).
383
- * Always triggers `DocumentBuilder.update([uri], [])` regardless of
384
- * whether the document is already in the registry — call this when
385
- * you want to re-process from scratch.
633
+ * Always builds the document, whether or not it is already in the
634
+ * registry, in a build of its own or in one already scheduled that carries
635
+ * it — call this when you want to re-process from scratch.
386
636
  *
387
- * The facade is responsible for firing `DocumentBuilder.update`
388
- * directly because Langium's `DefaultDocumentUpdateHandler.didChangeContent`
637
+ * The facade is responsible for requesting the build itself because Langium's `DefaultDocumentUpdateHandler.didChangeContent`
389
638
  * (the standard text-document → builder bridge) only runs under an
390
639
  * LSP `Connection`. Running headless the bridge never fires; the
391
640
  * facade stands in for it on its own update path.
392
641
  *
393
642
  * Coexistence with an LSP head running on the same `DocumentBuilder` is
394
- * fine, but not because the builder merges the two: Langium does NOT
395
- * coalesce concurrent builds of the same URI. The LSP head fires `update`
396
- * from the LSP-driven event and the facade fires it from its own RPC-driven
397
- * event — both legitimate — so this method takes the workspace WRITE lock,
398
- * the same one Langium's own text-change bridge builds under, to serialise
399
- * them. Two unserialised builds of one URI each run a full validation pass
400
- * and Langium appends the second set onto the first, duplicating every
401
- * diagnostic. Opt out via
402
- * {@link ModelServiceOptions.serializeBuilds} — see there for the
403
- * non-reentrancy hazard that is the reason the opt-out exists.
643
+ * fine: the LSP head builds from the LSP-driven event and the facade from
644
+ * its own RPC-driven event — both legitimate — and both go through
645
+ * `HydraniumDocumentBuilder.scheduleUpdate`, which serialises them under
646
+ * the workspace WRITE lock and lets the second share the first's build
647
+ * where that build carries it. Langium alone does not coalesce concurrent
648
+ * builds of one URI: two unserialised builds each run a full validation
649
+ * pass and Langium appends the second set onto the first, duplicating every
650
+ * diagnostic. A caller that already holds the lock builds without it only
651
+ * under {@link ModelServiceOptions.allowReentrantBuilds} — see there for the
652
+ * non-reentrancy hazard.
404
653
  *
405
- * Returns an empty `{ root, diagnostics }` envelope when the document
406
- * cannot be loaded; adopters that want to throw override this method
407
- * on their subclass.
654
+ * An override calls the base before it awaits. Under an LSP connection the
655
+ * store's change event has already asked the update handler to build a
656
+ * session's write; an override whose await outlasts that build makes the
657
+ * base's request start a build of its own, so the write is built and
658
+ * delivered twice.
659
+ *
660
+ * Rejects when the build leaves no document for `uri`, as for a URI with
661
+ * neither a file nor text: the wait after it has nothing to wait on.
408
662
  *
409
663
  * Consumers wanting "give me this doc at state X, building only if
410
664
  * needed" — use the per-state methods ({@link parsed} / {@link linked}
@@ -416,8 +670,8 @@ export class ModelService<
416
670
 
417
671
  /**
418
672
  * Internal build core operating on an already-{@link CanonicalUri canonical}
419
- * URI — the build counterpart to {@link waitForDocumentStateCanonical}. Drives
420
- * `DocumentBuilder.update` then waits via the canonical wait core, so the
673
+ * URI — the build counterpart to {@link waitForDocumentStateCanonical}.
674
+ * Requests the build, then waits via the canonical wait core, so the
421
675
  * identity is resolved once at the public door and neither sink re-runs the
422
676
  * `realpath`. (`DocumentBuilder.update` still resolves each URI internally for
423
677
  * directory flattening — that is the build's own existence-aware resolution,
@@ -429,66 +683,61 @@ export class ModelService<
429
683
  cancelToken?: CancellationToken
430
684
  ): Promise<AstDocument<TAst, TDiagnostic>> {
431
685
  const documentUri = UriUtils.toUri(uri);
432
- // Runs under the workspace WRITE lock, matching Langium's own
433
- // `DefaultDocumentUpdateHandler`, which dispatches its build as
434
- // `workspaceLock.write(token => documentBuilder.update(...))`.
686
+ // Runs under the workspace WRITE lock, through the builder's
687
+ // `scheduleUpdate` like the LSP update handler's build, so the build the
688
+ // store's change event already scheduled for this write carries this
689
+ // request too rather than being cancelled by it.
435
690
  //
436
691
  // Unlocked, this build races the LSP bridge's build of the same URI: both
437
692
  // are legitimate (the bridge only exists under a `Connection`, so the
438
- // facade stands in for it headless), and the coexistence note above relied
439
- // on Langium coalescing them by URI. It does not — nothing serialises the
440
- // two, so both reach `Validated`, and because each computes its missing
693
+ // facade stands in for it headless), and nothing serialises the two, so
694
+ // both reach `Validated`, and because each computes its missing
441
695
  // validation categories before the other has recorded its own, both run a
442
696
  // FULL pass and Langium appends the second onto the first (its append is
443
697
  // meant for category-partitioned passes). The user-visible result is every
444
698
  // diagnostic duplicated, plus double the validation work per write.
445
699
  //
446
- // Opt out via `ModelServiceOptions.serializeBuilds` — see there for
447
- // the non-reentrancy hazard that opt-out exists for.
448
- if (this.serializeBuilds.value) {
449
- // Fail loudly on the one shape the lock cannot survive. `WorkspaceLock`
450
- // is not reentrant: acquiring the write lock cancels the running holder,
451
- // so a caller already inside one — an integrity rule or build-phase pass
452
- // writing back through this facade — would cancel its own enclosing
453
- // build and then likely stall in the phase wait below. The check is
454
- // gated on `serializeBuilds` deliberately, because acquiring the lock IS
455
- // the hazard: with serialisation off there is nothing to be reentrant
456
- // about, which makes the existing opt-out the guard's opt-out too.
457
- // Detection needs async-context propagation, so it is inert until a host
458
- // installs a tracker (`@hydranium/core/node` does) — see
459
- // `isInsideWriteLock`.
460
- if (isInsideWriteLock()) {
461
- throw new ReentrantWriteLockError(uri);
462
- }
463
- // The lock's OWN token, not the caller's: a later `write` cancels the
464
- // running one through that token, so substituting the caller's would
465
- // leave this build deaf to the lock's cancellation protocol. A caller
466
- // token still governs the phase wait below.
467
- await this.services.workspace.WorkspaceLock.write(lockToken =>
468
- this.services.workspace.DocumentBuilder.update([documentUri], [], lockToken)
469
- );
470
- } else {
700
+ // A caller already inside the lock would cancel its own build and stall in
701
+ // the wait below; `allowReentrantBuilds` builds it unlocked, and without a
702
+ // tracker it cannot be told apart from any other caller.
703
+ if (this.allowReentrantBuilds.value && (isInsideWriteLock() || !isWriteLockScopeInstalled())) {
471
704
  await this.services.workspace.DocumentBuilder.update([documentUri], [], cancelToken);
705
+ } else {
706
+ this.assertCanBuild(uri);
707
+ // The build runs on the lock's own token, which a later write cancels;
708
+ // the caller's token governs only the phase wait below.
709
+ await this.services.workspace.DocumentBuilder.scheduleUpdate([documentUri], []);
710
+ }
711
+ return this.waitForDocumentStateCanonical(uri, state ?? IntegrityService.SettledState, cancelToken, { sync: true });
712
+ }
713
+
714
+ assertCanBuild(uri: string): void {
715
+ if (isInsideWriteLock() && !this.allowReentrantBuilds.value) {
716
+ throw new ReentrantWriteLockError(uri);
472
717
  }
473
- return this.waitForDocumentStateCanonical(uri, state ?? IntegrityService.SettledState, cancelToken);
474
718
  }
475
719
 
476
720
  /**
477
721
  * Per-state typed convenience methods. Each ensures the document at
478
722
  * `uri` reaches the named phase and returns the AST envelope with
479
- * the narrowest accurate diagnostics type for that phase. Smart
480
- * dispatch internally: warm path (URI already in the document
481
- * registry) just waits via {@link waitForDocumentState}; cold path
482
- * triggers a build via {@link rebuild}. Consumers do not need to
483
- * know which path was taken.
723
+ * the narrowest accurate diagnostics type for that phase, building as
724
+ * {@link ensureDocumentState} does.
484
725
  *
485
726
  * Phase invariants encoded in the return type:
486
727
  * - `parsed` / `linked` / `settled` / `indexed` return
487
- * `AstDocument<TAst, never>` — diagnostics array is empty by phase
488
- * contract.
728
+ * `AstDocument<TAst, never>` — no diagnostics have been computed at
729
+ * those phases.
489
730
  * - `validated` returns `AstDocument<TAst, TDiagnostic>` — diagnostics
490
731
  * are populated.
491
732
  *
733
+ * **The `never` is enforced, not merely declared.** The wait underneath
734
+ * resolves at or ABOVE the requested state, so a document something else
735
+ * already carried past `Validated` would otherwise come back from
736
+ * `settled()` carrying a full diagnostics array typed `never`; these four
737
+ * strip it. An empty array here therefore means "this read does not report
738
+ * diagnostics", never "this document is clean" — call {@link validated}
739
+ * when the answer has to mean the second.
740
+ *
492
741
  * `settled` is the integrity-overlay name for "all integrity rules
493
742
  * have fired"; it maps to {@link IntegrityService.SettledState} (which
494
743
  * equals `DocumentState.IndexedReferences`), but the dedicated method
@@ -496,19 +745,19 @@ export class ModelService<
496
745
  * ever moves.
497
746
  */
498
747
  async parsed(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>> {
499
- return this.ensureDocumentState(uri, DocumentState.Parsed, cancelToken) as Promise<AstDocument<TAst, never>>;
748
+ return this.withoutDiagnostics(await this.ensureDocumentState(uri, DocumentState.Parsed, cancelToken));
500
749
  }
501
750
 
502
751
  async linked(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>> {
503
- return this.ensureDocumentState(uri, DocumentState.Linked, cancelToken) as Promise<AstDocument<TAst, never>>;
752
+ return this.withoutDiagnostics(await this.ensureDocumentState(uri, DocumentState.Linked, cancelToken));
504
753
  }
505
754
 
506
755
  async settled(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>> {
507
- return this.ensureDocumentState(uri, IntegrityService.SettledState, cancelToken) as Promise<AstDocument<TAst, never>>;
756
+ return this.withoutDiagnostics(await this.ensureDocumentState(uri, IntegrityService.SettledState, cancelToken));
508
757
  }
509
758
 
510
759
  async indexed(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, never>> {
511
- return this.ensureDocumentState(uri, DocumentState.IndexedReferences, cancelToken) as Promise<AstDocument<TAst, never>>;
760
+ return this.withoutDiagnostics(await this.ensureDocumentState(uri, DocumentState.IndexedReferences, cancelToken));
512
761
  }
513
762
 
514
763
  async validated(uri: string, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>> {
@@ -518,18 +767,13 @@ export class ModelService<
518
767
  /**
519
768
  * Ensure the document at `uri` reaches `state` (or the integrity-settled
520
769
  * landmark {@link IntegrityService.SettledState} if omitted) and return its
521
- * AST envelope. Smart
522
- * dispatch: warm path (URI already in `LangiumDocuments`) just waits
523
- * via {@link waitForDocumentState}; cold path forces a build via
524
- * {@link rebuild}.
525
- *
526
- * Pairs with {@link rebuild} — same default phase, but `rebuild`
527
- * always builds while this skips the build for an already-loaded
528
- * document. Also pairs with {@link waitForDocumentState} — the verb
529
- * difference (`ensure` vs `waitFor`) signals the side-effect
530
- * difference. The per-state convenience methods (`parsed` / `linked`
531
- * / `settled` / `indexed` / `validated`) all delegate here with an
532
- * explicit phase.
770
+ * AST envelope, with a root no older than the store's text at the call.
771
+ * A document not in `LangiumDocuments` is built via {@link rebuild}; a
772
+ * loaded one whose root is behind its text is built through
773
+ * `VersionSyncService.syncTo`. Until `state` is reached, the call rejects
774
+ * once that build, or one the builder re-queues, has failed twice, or the
775
+ * builder stops re-queuing the document. A loaded, current document is only
776
+ * awaited.
533
777
  */
534
778
  async ensureDocumentState(uri: string, state?: DocumentState, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>> {
535
779
  return this.ensureDocumentStateCanonical(this.uriPolicy.canonicalUri(uri), state, cancelToken);
@@ -552,120 +796,20 @@ export class ModelService<
552
796
  ): Promise<AstDocument<TAst, TDiagnostic>> {
553
797
  const target = state ?? IntegrityService.SettledState;
554
798
  if (this.services.workspace.LangiumDocuments.hasDocument(UriUtils.toUri(uri))) {
555
- return this.waitForDocumentStateCanonical(uri, target, cancelToken);
799
+ return this.waitForDocumentStateCanonical(uri, target, cancelToken, { sync: true });
556
800
  }
557
801
  return this.rebuild(uri, target, cancelToken);
558
802
  }
559
803
 
560
804
  /**
561
- * Apply an update for `uri`. The structured-or-textual `model` payload
562
- * is serialised (via {@link serialize} after {@link rewriteModel} when
563
- * structured), pushed into the multi-client text-document store with
564
- * a fresh version, drives a build to the target phase, and returns
565
- * the post-build AST snapshot.
566
- *
567
- * **Read-latest supersession**: concurrent callers on the same URI
568
- * all see the same post-build state once `waitUntil` resolves; none
569
- * deadlock waiting for a specific version's settled event. The
570
- * framework emits a post-resolution `debug` log line distinguishing
571
- * "vN ready" from "vN ready at vM (superseded)" so callers can
572
- * observe when their write was overtaken by a newer one before
573
- * settling — purely observability, doesn't change resolution
574
- * semantics. Adopters wanting version-matched resolution (resolve
575
- * with vN's specific settled snapshot, intermediate-phase
576
- * observability, slow-warn / hard-timeout behaviour) override this
577
- * method.
578
- */
579
- async update(args: TransferUpdateArgs<TTransfer>, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>> {
580
- const stopwatch = this.slowUpdateWarn !== undefined ? this.services.Clock.stopwatch() : undefined;
581
- // Per-stage self-time breakdown of the update/reconcile chain (serialise →
582
- // open → apply → rebuild), opt-in at debug — the default path skips the
583
- // session and `run` calls the stage directly. `update` is a per-operation
584
- // method (one user save / diagram edit), not a per-node hot loop, so the
585
- // stage closures `run` allocates on the non-debug path are negligible.
586
- // Canonicalize the write URI once at the door and thread the resulting
587
- // CanonicalUri through the chain. The text store keys documents by their
588
- // canonical identity, so any spelling of a file — a canonical
589
- // (server-identity) URI from a GLSP cross-document save derived from
590
- // `findDocument(node).uri`, or the symlink path an editor opened — collapses
591
- // to the one registration; there is no second registration to fork. The
592
- // build step reuses the canonical wait core (`rebuildCanonical`) so the
593
- // identity is not re-resolved downstream.
594
- const uri = this.uriPolicy.canonicalUri(args.uri);
595
- const session = Logger.isLevelEnabled('debug') ? this.tracer.profile(`model-update ${uri}`) : undefined;
596
- const run = async <T>(stage: string, fn: () => MaybePromise<T>): Promise<T> => (session ? session.scope(stage, fn) : fn());
597
- // Open WITH the new text so a cold URI (no open editor, no file on disk) is
598
- // created from the payload rather than read from the filesystem — `update`
599
- // is an upsert. For an already-open document `open` refreshes content (the
600
- // text is ignored on that branch), so existing-document behaviour is
601
- // unchanged. `version` is intentionally NOT forwarded to `open`: a cold
602
- // create stays at its initial version, so a based-on-`version` update of a
603
- // not-yet-existing document still trips the conflict gate below.
604
- const text = await run('serialize', () => this.modelToText(uri, args.model, cancelToken));
605
- await run('open', () => this.open({ uri, clientId: args.clientId, text }));
606
- if (args.baseVersion !== undefined) {
607
- const current = this.services.workspace.TextDocuments.version(uri);
608
- if (current !== args.baseVersion) {
609
- // Distinct from the post-build "superseded" debug line below: this is a
610
- // based-on-stale rejection (the write never applies), not two writes racing.
611
- this.tracer.debug(`Conflict on ${uri}: based-on v${args.baseVersion} stale, server at v${current}`);
612
- throw new ConflictError(uri, args.baseVersion, current);
613
- }
614
- }
615
- const appliedVersion = await run('apply', () => this.services.workspace.AstDocumentManager.update(uri, text, args.clientId));
616
- // Dispatch through the public `rebuild` (which re-canonicalizes the already-
617
- // canonical `uri` once, idempotently) rather than `rebuildCanonical`, so an
618
- // adopter `rebuild` override stays in the update path. The redundant call is
619
- // a single kernel-cached `realpath`; correctness of the override contract
620
- // wins over shaving it.
621
- const doc = await run('rebuild', () => this.rebuild(uri, undefined, cancelToken));
622
- const finalVersion = this.services.workspace.TextDocuments.version(uri);
623
- if (finalVersion > appliedVersion) {
624
- this.tracer.debug(`Update to v${appliedVersion} ready at v${finalVersion} (superseded)`);
625
- } else {
626
- this.tracer.debug(`Update to v${appliedVersion} ready`);
627
- }
628
- if (this.slowUpdateWarn !== undefined && stopwatch) {
629
- const elapsed = Math.round(stopwatch.elapsedMs);
630
- const threshold = this.slowUpdateWarn.value;
631
- if (elapsed >= threshold) {
632
- this.tracer.withUri(uri).warn(`Slow update: ${elapsed}ms ≥ ${threshold}ms (v${appliedVersion}, client=${args.clientId})`);
633
- }
634
- }
635
- // One line per stage (serialise / open / apply / rebuild) + unaccounted — only when profiling.
636
- session?.report('debug');
637
- return doc;
638
- }
639
-
640
- /**
641
- * Persist `uri` to disk. Same content-change + settled-phase flow as
642
- * {@link update}, then writes via the
643
- * `WritableFileSystemProvider` and notifies the multi-client
644
- * text-document store of the save (so any open LSP-side editor sees
645
- * the `onDidSave` event regardless of who originated the persist).
646
- *
647
- * Returns the post-save AST snapshot.
648
- */
649
- async save(args: TransferSaveArgs<TTransfer>, cancelToken?: CancellationToken): Promise<AstDocument<TAst, TDiagnostic>> {
650
- // Dispatch through `update` (not its internals) so an adopter `update`
651
- // override — version-matched resolution, etc. — applies to saves too.
652
- const doc = await this.update(args, cancelToken);
653
- // Persist under the same canonical identity `update` operated on. Writing
654
- // the canonical (real) path follows any symlink to the same file, and the
655
- // `onDidSave` keys the one canonical registration.
656
- const uri = this.uriPolicy.canonicalUri(args.uri);
657
- await this.services.workspace.AstDocumentManager.save(uri, args.clientId);
658
- return doc;
659
- }
660
-
661
- /**
662
- * Wait for the document at `uri` to reach the integrity-settled landmark and
805
+ * Wait for the document at `uri` to reach the integrity-settled landmark,
806
+ * building a root behind its text as {@link ensureDocumentState} does, and
663
807
  * drain any in-flight write-path applyEdit sync chain (see {@link syncChains})
664
808
  * so every language client reflects the latest content before a save returns.
665
809
  * No-op tail for headless adopters — `syncChains` is empty without an LSP
666
810
  * client. Bounded by {@link SAVE_SETTLE_TIMEOUT_MS} so a hung build, or an
667
- * applyEdit reverse-RPC deadlock, can't freeze the caller; on timeout it logs
668
- * a warning and returns rather than throwing.
811
+ * applyEdit reverse-RPC deadlock, can't freeze the caller; on timeout or a
812
+ * failed wait it logs a warning and returns rather than throwing.
669
813
  *
670
814
  * Adopters with a save flow that must converge editor + disk before returning
671
815
  * (e.g. a dual form/code editor that would otherwise show a content-conflict
@@ -674,63 +818,61 @@ export class ModelService<
674
818
  protected async settleSave(uri: string, cancelToken?: CancellationToken): Promise<void> {
675
819
  const canonical = this.uriPolicy.canonicalUri(uri);
676
820
  const key = UriUtils.toUri(canonical).toString();
677
- const timeout = new Promise<void>((_, reject) =>
678
- setTimeout(() => reject(new SaveSettleTimeoutError('settle timeout')), SAVE_SETTLE_TIMEOUT_MS)
679
- );
821
+ // One race over both waits, so the bound is one deadline for the pair;
822
+ // a race per wait would let the save take twice the bound.
823
+ const settled = (async (): Promise<void> => {
824
+ await this.waitForDocumentStateCanonical(canonical, IntegrityService.SettledState, cancelToken, { sync: true });
825
+ await this.syncChains.get(key);
826
+ })();
680
827
  try {
681
- await Promise.race([this.waitForDocumentStateCanonical(canonical, IntegrityService.SettledState, cancelToken), timeout]);
682
- const pending = this.syncChains.get(key);
683
- if (pending) {
684
- await Promise.race([pending, timeout]);
685
- }
686
- } catch (err: unknown) {
687
- if (err instanceof SaveSettleTimeoutError) {
828
+ if ((await this.services.Clock.raceTimer(settled, SAVE_SETTLE_TIMEOUT_MS)) === TIMED_OUT) {
688
829
  this.tracer.withUri(key).warn(`Save settle exceeded ${SAVE_SETTLE_TIMEOUT_MS}ms — returning anyway`);
689
- } else {
690
- const detail = err instanceof Error ? (err.stack ?? err.message) : String(err);
691
- this.tracer.withUri(key).warn(`Save settle failed before the timeout — returning anyway. ${detail}`);
692
830
  }
831
+ } catch (err: unknown) {
832
+ // A failed wait, such as a cancelled token or a document the builder
833
+ // does not hold, gets its own line so it is not blamed on the bound.
834
+ const detail = err instanceof Error ? (err.stack ?? err.message) : String(err);
835
+ this.tracer.withUri(key).warn(`Save settle failed before the timeout — returning anyway. ${detail}`);
693
836
  }
694
837
  }
695
838
 
696
839
  /**
697
- * Open the document at `args.uri` on behalf of `args.clientId`.
698
- * Multi-client: each (uri, clientId) pair is tracked as one
699
- * registration; the underlying document stays open until the last
700
- * client closes it. If `args.text` is omitted the document content
701
- * is read from the `FileSystemProvider`.
702
- *
703
- * Returns a {@link Disposable} that closes the registration when
704
- * disposed — useful for `using` blocks and shutdown cleanup.
705
- *
706
- * Delegates to the framework-bound
707
- * `services.workspace.AstDocumentManager`. Adopter subclasses with
708
- * extra open-time behaviour (logging, sync-chain bootstrapping)
709
- * override on their `ModelService` subclass and call `super.open`.
710
- *
711
- * The open path does not thread cancellation: `AstDocumentManager.open`
712
- * and the filesystem read behind it take no token, so a cancelled caller
713
- * still completes the open.
840
+ * True when the document at `uri` is currently open for at least one
841
+ * client. Pure read; no side effects.
714
842
  */
715
- async open(args: OpenModelArgs): Promise<Disposable> {
716
- return this.services.workspace.AstDocumentManager.open(args);
843
+ isOpen(uri: string): boolean {
844
+ return this.services.workspace.AstDocumentManager.isOpen(uri);
717
845
  }
718
846
 
719
- /**
720
- * Close the document at `args.uri` for `args.clientId`. Counterpart
721
- * to {@link open}; the underlying document stays open until every
722
- * registered client has closed.
723
- */
724
- async close(args: CloseModelArgs): Promise<void> {
725
- return this.services.workspace.AstDocumentManager.close(args);
847
+ openedVersion(uri: string): TextVersion | undefined {
848
+ return this.services.workspace.TextDocuments.openedVersion(uri);
726
849
  }
727
850
 
728
851
  /**
729
- * True when the document at `uri` is currently open for at least one
730
- * client. Pure read; no side effects.
852
+ * Snapshot of `uri` as it stands RIGHT NOW — the synchronous sibling of the
853
+ * phase reads, which all wait. `undefined` when no document is registered,
854
+ * or only the builder's placeholder for one its build has not parsed yet:
855
+ * that root is no parse of any text, and its version gates no write.
856
+ *
857
+ * **This is what a writer wants, and {@link getDocument} is not.** The
858
+ * envelope's `version` is copied by value at projection time, so it cannot
859
+ * move afterwards; a version read off the live document at write time is
860
+ * whatever the server is at *now*, which is the number an optimistic gate is
861
+ * about to compare it against.
862
+ *
863
+ * Diagnostics only from a document that has reached `Validated`, and absent
864
+ * otherwise. Unlike the phase reads this one names no phase, so
865
+ * the state it finds is the only thing that can say whether the array
866
+ * describes the content being handed back or whatever an earlier build left.
867
+ * A caller that needs them unconditionally waits, via {@link validated}.
731
868
  */
732
- isOpen(uri: string): boolean {
733
- return this.services.workspace.AstDocumentManager.isOpen(uri);
869
+ snapshot(uri: string): AstDocument<TAst, TDiagnostic> | undefined {
870
+ const document = this.getDocument(uri);
871
+ if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
872
+ return undefined;
873
+ }
874
+ const envelope = this.services.workspace.AstDocumentManager.toAstDocument(document) as AstDocument<TAst, TDiagnostic>;
875
+ return document.state >= DocumentState.Validated ? envelope : this.withoutDiagnostics(envelope);
734
876
  }
735
877
 
736
878
  /**
@@ -741,11 +883,102 @@ export class ModelService<
741
883
  * into `LangiumDocuments` directly: a symlinked / `..` / case-divergent URI
742
884
  * still resolves to the one document the build keys by its real path. Returns
743
885
  * `undefined` if no document is registered for `uri`.
886
+ *
887
+ * **Live, so do not take a base version off it.** `textDocument` is the
888
+ * store's own object rather than a copy, so `.version` read here answers for
889
+ * the moment of the READ, not the moment of the earlier content — pass it to
890
+ * a write and the server compares its current version against itself, the
891
+ * gate passes unconditionally, and a concurrent edit is overwritten with
892
+ * nothing logged. Use {@link snapshot} for that, or a phase read.
744
893
  */
745
894
  getDocument(uri: string): LangiumDocument | undefined {
746
895
  return this.services.workspace.AstDocumentManager.getDocument(uri);
747
896
  }
748
897
 
898
+ // ============================================================
899
+ // Client sessions
900
+ // ============================================================
901
+
902
+ createSession<TOpenOptions extends OpenOptions = OpenOptions>(
903
+ label?: string,
904
+ clientId?: string,
905
+ options: { readonly resumeToken?: string } = {}
906
+ ): ClientSession<TAst, TDiagnostic, TTransfer, TOpenOptions> {
907
+ const sessionLabel = label ?? 'session';
908
+ const id = clientId ?? `${sessionLabel}#${randomUuid()}`;
909
+ const textDocuments = this.services.workspace.TextDocuments;
910
+ if (options.resumeToken !== undefined && this.resumeTokens.get(id) === options.resumeToken) {
911
+ this.sessions.get(id)?.dispose('lost');
912
+ }
913
+ textDocuments.registerSession(id);
914
+ this.sessionCloseListener ??= textDocuments.onDidCloseSession(event => {
915
+ // Also reached when the store ends a session directly; disposing the
916
+ // handle makes its later calls fail rather than write under an id
917
+ // this service no longer treats as a session. Forgotten first: a
918
+ // dispose listener may start a replacement under the same id.
919
+ const ended = this.sessions.get(event.clientId);
920
+ this.sessions.delete(event.clientId);
921
+ this.resumeTokens.delete(event.clientId);
922
+ ended?.dispose(event.cause);
923
+ });
924
+ let session: ClientSession<TAst, TDiagnostic, TTransfer, TOpenOptions>;
925
+ try {
926
+ // Unchecked: the session keeps whatever options its `open` is handed,
927
+ // and the factory types it for every grammar, so the narrowed type
928
+ // holds only for the caller that started it.
929
+ session = this.services.model.ClientSessionFactory.create(id, sessionLabel) as ClientSession<
930
+ TAst,
931
+ TDiagnostic,
932
+ TTransfer,
933
+ TOpenOptions
934
+ >;
935
+ } catch (err: unknown) {
936
+ textDocuments.closeSession(id);
937
+ throw err;
938
+ }
939
+ this.sessions.set(id, session);
940
+ if (options.resumeToken !== undefined) {
941
+ this.resumeTokens.set(id, options.resumeToken);
942
+ }
943
+ return session;
944
+ }
945
+
946
+ getSession(clientId: string): ClientSession<TAst, TDiagnostic, TTransfer> | undefined {
947
+ return this.sessions.get(clientId);
948
+ }
949
+
950
+ /**
951
+ * Convert a structured-or-textual `model` payload to its textual form.
952
+ *
953
+ * Textual payloads (LSP / pre-serialised callers) pass through untouched.
954
+ * Structured payloads run the per-language `UpdateRewriteService` chain
955
+ * (transfer-model transforms; diff-aware rewrites see the previous AST root),
956
+ * then serialise. The chain is the single transfer-model-transform seam — a
957
+ * unary normalisation is just a rewrite that ignores `previous`, as
958
+ * `NormalizeEmptyStringsContribution` does. The chain is empty by
959
+ * default, so this is a no-op for adopters that register none.
960
+ */
961
+ async modelToText(uri: string, model: TTransfer | string, cancelToken?: CancellationToken): Promise<string> {
962
+ if (typeof model === 'string') {
963
+ return model;
964
+ }
965
+ const rewritten = await this.rewriteModel(uri, model, cancelToken);
966
+ const target = UriUtils.toUri(uri);
967
+ const trivia = this.services.ServiceRegistry?.getServices(target)?.trivia?.TriviaService;
968
+ // Extracted BEFORE serializing, so it reads the document the write is
969
+ // about to replace rather than whatever a concurrent build left behind.
970
+ let document = this.services.workspace.LangiumDocuments.getDocument(target);
971
+ if (trivia !== undefined && document === undefined) {
972
+ const source = await this.textToTakeTriviaFrom(uri, target);
973
+ if (source !== undefined) {
974
+ document = this.services.workspace.LangiumDocumentFactory.fromString(source, target);
975
+ }
976
+ }
977
+ const extracted = trivia !== undefined && document !== undefined ? trivia.extract(document) : undefined;
978
+ const serialized = await this.serialize(uri, rewritten);
979
+ return extracted === undefined ? serialized : trivia!.apply(serialized, extracted, target);
980
+ }
981
+
749
982
  // ============================================================
750
983
  // LSP-client sync (mirror non-LSP-client changes back to Monaco)
751
984
  // ============================================================
@@ -754,18 +987,14 @@ export class ModelService<
754
987
  * Mirror a server-side change of `document` back to the LSP textual language
755
988
  * client, run per document as it reaches the post-integrity settled phase.
756
989
  * The single framework caller of
757
- * `HydraniumTextDocuments.applyEditToLanguageClient` and
758
- * `HydraniumTextDocuments.stagePendingContent`.
990
+ * `HydraniumTextDocuments.applyEditToLanguageClient`.
759
991
  *
760
- * Routes to one of two mechanisms by language-client registration, because
761
- * an open and a closed document answer different questions:
762
- *
763
- * - **Open in the language client** → {@link syncOpenDocument}: mirror the
764
- * settled text via a coalesced `applyEditToLanguageClient`, routed purely by
765
- * **content**.
766
- * - **Closed in the language client** → {@link stageClosedDocument}: stage the
767
- * text for the eventual first `didOpen`, gated by **provenance**
768
- * ({@link isNonLanguageClientEdit}).
992
+ * Only a document open in the language client is mirrored, through
993
+ * {@link syncOpenDocument}, routed purely by **content**. A document open
994
+ * only in another client needs nothing: a language client opening it joins
995
+ * the existing entry and is refreshed from the store. A session writes only
996
+ * what it has open, so no session edit of a closed document waits here for
997
+ * the language client's next open.
769
998
  *
770
999
  * The decision is **re-derived from the current settled state every time** (it
771
1000
  * is not a one-shot enrolment), which is what makes it self-healing: a doc
@@ -775,9 +1004,9 @@ export class ModelService<
775
1004
  */
776
1005
  protected syncToLanguageClient(document: LangiumDocument): void {
777
1006
  // `document.textDocument.uri` is the server-identity (canonical) URI off the
778
- // build. Route by language-client registration (a presence question —
779
- // `isOpenInLanguageClient` canonicalizes internally, so a divergent open path
780
- // still resolves to the same record), but key the outbound sync by this
1007
+ // build. Route by client registration (presence questions — both
1008
+ // predicates canonicalize internally, so a divergent open path still
1009
+ // resolves to the same record), but key the outbound sync by this
781
1010
  // CANONICAL URI — the same key `settleSave` looks the chain up under —
782
1011
  // so a save-settle can drain the in-flight applyEdit. The canonical→client-URI
783
1012
  // translation (a symlinked path the client opened, or a dual-open fan-out)
@@ -787,8 +1016,6 @@ export class ModelService<
787
1016
  // the drain would miss for a divergent open path.
788
1017
  if (this.services.workspace.TextDocuments.isOpenInLanguageClient(document.textDocument.uri)) {
789
1018
  this.syncOpenDocument(document.textDocument.uri, document.textDocument.getText());
790
- } else {
791
- this.stageClosedDocument(document);
792
1019
  }
793
1020
  }
794
1021
 
@@ -807,46 +1034,6 @@ export class ModelService<
807
1034
  this.queueSync(uri, text);
808
1035
  }
809
1036
 
810
- /**
811
- * Stage the settled text of a document closed in the language client so the
812
- * eventual first `didOpen` sees this in-memory text instead of stale disk —
813
- * but only for a {@link isNonLanguageClientEdit genuine non-language-client edit}.
814
- * A document rebuilt by an internal build is skipped, leaving disk authoritative
815
- * on the next open.
816
- */
817
- protected stageClosedDocument(document: LangiumDocument): void {
818
- if (this.isNonLanguageClientEdit(document)) {
819
- this.services.workspace.TextDocuments.stagePendingContent(document.textDocument.uri, document.textDocument.getText());
820
- }
821
- }
822
-
823
- /**
824
- * Whether `document`'s settled state is a genuine edit by a client *other than
825
- * the language client* — a write a form / GLSP / integrity client actually made.
826
- * Excludes two non-edits: the **language client** itself (the LSP/Monaco text
827
- * client — it already holds its own edits, and the staging here exists to feed
828
- * it) and an **internal build** (workspace startup, a cascade relink, a
829
- * `didClose`-reload). This is the gate for {@link stageClosedDocument}: staging
830
- * an internal build would
831
- * (a) pre-stage every file on boot and (b) re-stage discarded content after
832
- * close (e.g. a disposing GLSP session's debounced submit firing after close),
833
- * which then shadows clean disk on the next open.
834
- *
835
- * The signal is "a known client other than the language client authored this
836
- * version **and** the URI was in the last build's changed set
837
- * (`isDirectChange`)". A framework-internal rebuild reports no author
838
- * (`getAuthor` → `undefined`), so it fails `hasKnownAuthor` without comparing
839
- * against a sentinel. This is NOT redundant with content/registration — it
840
- * distinguishes "client edited" from "framework rebuilt", which neither the
841
- * shadow nor `isDirectChange` alone can.
842
- */
843
- protected isNonLanguageClientEdit(document: LangiumDocument): boolean {
844
- const documents = this.services.workspace.AstDocumentManager;
845
- const author = documents.getAuthor(document);
846
- const hasKnownAuthor = !!author && author !== LANGUAGE_CLIENT_ID;
847
- return hasKnownAuthor && documents.isDirectChange(document.textDocument.uri);
848
- }
849
-
850
1037
  /**
851
1038
  * Enqueue a sync to the language client. The pending slot per URI holds only
852
1039
  * the latest text: if a newer settle fires while the current RPC is in
@@ -878,23 +1065,38 @@ export class ModelService<
878
1065
  this.syncChains.set(uri, chain);
879
1066
  }
880
1067
 
1068
+ /**
1069
+ * The undo-stack label for a server-authored write, in the locale the server
1070
+ * was handed at init.
1071
+ *
1072
+ * One method rather than the literal at each `applyEdit`, because the two
1073
+ * call sites are the same edit — a push and its full-replace retry — and an
1074
+ * undo menu showing two different words for one operation would read as two
1075
+ * operations.
1076
+ */
1077
+ protected editLabel(): string {
1078
+ return this.services.MessageRenderer.renderMessage(MODEL_UPDATE_EDIT);
1079
+ }
1080
+
881
1081
  protected async drainSyncQueue(uri: string): Promise<void> {
882
1082
  const uriLogger = this.tracer.withUri(uri);
883
1083
  while (this.pendingSync.has(uri)) {
884
1084
  const text = this.pendingSync.get(uri)!;
885
1085
  this.pendingSync.delete(uri);
886
1086
  try {
887
- let result = await this.services.workspace.TextDocuments.applyEditToLanguageClient(uri, text, { label: 'Update Model' });
888
- if (result?.applied === false && !this.pendingSync.has(uri)) {
889
- // The push is addressed at the client's LAST DECLARED VERSION, so a
1087
+ const textDocuments = this.services.workspace.TextDocuments;
1088
+ let result = await textDocuments.applyEditToLanguageClient(uri, text, { label: this.editLabel() });
1089
+ if (result?.applied === false && !this.pendingSync.has(uri) && textDocuments.get(uri)?.getText() === text) {
1090
+ // The push is addressed at the client's last known version, so a
890
1091
  // rejection normally means the client's buffer moved while the
891
1092
  // line-keyed diff was in flight — exactly the case where applying it
892
1093
  // would splice the file. Dropping the push there would leave the
893
1094
  // editor showing text the server has already superseded, with no
894
1095
  // later settle guaranteed to correct it (a content-identical echo
895
- // mints no rebuild). The rejection invalidated the shadow, so the
896
- // retry is a full-range replace: position-independent, and therefore
897
- // correct against whatever the client now holds.
1096
+ // mints no rebuild). After a rejection the retry is a full-range
1097
+ // replace: position-independent, and therefore correct against
1098
+ // whatever the client now holds. It sends nothing when the client
1099
+ // was last heard to hold the text already.
898
1100
  //
899
1101
  // Retried INLINE rather than re-enqueued, and exactly once. Inline
900
1102
  // because a re-enqueue would have to out-order any settle that lands
@@ -903,9 +1105,11 @@ export class ModelService<
903
1105
  // the workspace) must cost one extra RPC rather than spin. The
904
1106
  // `pendingSync` check skips the retry when a newer settle has already
905
1107
  // queued — best-effort, since a settle arriving later simply pushes
906
- // after this and still wins.
907
- uriLogger.warn(`Language client rejected applyEdit at its declared version — re-pushing a full replace`);
908
- result = await this.services.workspace.TextDocuments.applyEditToLanguageClient(uri, text, { label: 'Update Model' });
1108
+ // after this and still wins. It is skipped too once the store holds
1109
+ // other text: the keystroke that made the client refuse replaced it,
1110
+ // and re-pushing would overwrite that keystroke in the editor.
1111
+ uriLogger.debug(`Re-pushing a full replace after the language client refused applyEdit`);
1112
+ result = await textDocuments.applyEditToLanguageClient(uri, text, { label: this.editLabel() });
909
1113
  if (result?.applied === false) {
910
1114
  uriLogger.warn(`Language client rejected the full-replace retry too — client content is stale`);
911
1115
  }
@@ -926,42 +1130,148 @@ export class ModelService<
926
1130
  }
927
1131
 
928
1132
  // ============================================================
929
- // Subscription pass-throughs
1133
+ // Subscriptions
930
1134
  // ============================================================
931
1135
 
932
- /**
933
- * Subscribe to AST-snapshot updates for `uri`. Fires after each
934
- * rebuild that reaches the target phase. Delegates to the
935
- * `HydraniumTextDocuments` — single listener registration shared with
936
- * any direct `HydraniumTextDocuments.onUpdate` subscriber, so the same
937
- * underlying `DocumentBuilder.onDocumentPhase` listener serves both
938
- * call paths. `sourceClientId` is resolved from the multi-client
939
- * author history; reason discrimination follows the manager's own
940
- * `lastUpdate` snapshot (see `AstDocumentManager.onUpdate`).
941
- */
942
- onModelUpdated(uri: string, listener: (event: AstDocumentUpdatedEvent<TAst, TDiagnostic>) => void): Disposable {
943
- return this.services.workspace.AstDocumentManager.onUpdate(uri, listener as never);
1136
+ onModelUpdated(listener: (event: ModelUpdatedEvent<TAst, TDiagnostic>) => void, filter: ModelPhaseFilter = {}): Disposable {
1137
+ const phase = filter.phase ?? DocumentState.Validated;
1138
+ let subscribers = this.updateSubscribers.get(phase);
1139
+ if (!subscribers) {
1140
+ const created = new Set<ModelUpdateSubscriber<TAst, TDiagnostic>>();
1141
+ this.updateSubscribers.set(phase, created);
1142
+ this.services.workspace.DocumentBuilder.onDocumentPhase(
1143
+ phase,
1144
+ labelPhaseListener(
1145
+ (document, cancelToken) => this.deliverUpdate(phase, created, document, cancelToken),
1146
+ 'ModelService.onModelUpdated'
1147
+ )
1148
+ );
1149
+ subscribers = created;
1150
+ }
1151
+ const subscriber = { uri: this.filterUri(filter), listener };
1152
+ subscribers.add(subscriber);
1153
+ return Disposable.create(() => subscribers.delete(subscriber));
944
1154
  }
945
1155
 
946
- /**
947
- * Subscribe to save events for `uri`. Fires on every persist through
948
- * the multi-client text-document store — including saves originated
949
- * by other heads (LSP editor `Ctrl+S`, the data-server `save`, etc.)
950
- * so subscribers see one consistent stream regardless of who wrote
951
- * the file. Delegates to the manager — single listener registration
952
- * shared with any direct `HydraniumTextDocuments.onSave` subscriber.
953
- */
954
- onModelSaved(uri: string, listener: (event: AstDocumentSavedEvent<TAst, TDiagnostic>) => void): Disposable {
955
- return this.services.workspace.AstDocumentManager.onSave(uri, listener as never);
1156
+ onModelsBuilt(listener: (event: ModelsBuiltEvent) => void, filter: Pick<ModelPhaseFilter, 'phase'> = {}): Disposable {
1157
+ const phase = filter.phase ?? DocumentState.Validated;
1158
+ return this.services.workspace.DocumentBuilder.onBuildPhase(phase, (built, cancelToken) => {
1159
+ if (cancelToken.isCancellationRequested) {
1160
+ return;
1161
+ }
1162
+ try {
1163
+ listener(Object.freeze({ uris: built.map(document => this.uriPolicy.canonicalUri(document.uri.toString())), phase }));
1164
+ } catch (err: unknown) {
1165
+ this.tracer.error(`onModelsBuilt listener threw: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
1166
+ }
1167
+ });
1168
+ }
1169
+
1170
+ onModelSaved(listener: (event: ModelSavedEvent<TAst, TDiagnostic>) => void, filter: ModelEventFilter = {}): Disposable {
1171
+ const target = this.filterUri(filter);
1172
+ return this.services.workspace.TextDocuments.onDidSave(event => {
1173
+ // LangiumDocuments keys by the canonical form, the saved event by the
1174
+ // client-facing one.
1175
+ const uri = this.uriPolicy.canonicalUri(event.document.uri);
1176
+ if (this.matches(target, uri)) {
1177
+ listener({ document: this.toAstDocument(UriUtils.toUri(uri)), sourceClientId: event.clientId });
1178
+ }
1179
+ });
1180
+ }
1181
+
1182
+ onModelDeleted(listener: (event: ModelDeletedEvent) => void, filter: ModelEventFilter = {}): Disposable {
1183
+ const target = this.filterUri(filter);
1184
+ return this.services.workspace.DocumentBuilder.onUpdate((_changed, deleted) => {
1185
+ for (const deletedUri of deleted) {
1186
+ const uri = this.uriPolicy.canonicalUri(deletedUri.toString());
1187
+ if (this.matches(target, uri)) {
1188
+ listener(Object.freeze({ uri }));
1189
+ }
1190
+ }
1191
+ });
1192
+ }
1193
+
1194
+ onDirtyChanged(listener: (event: ModelDirtyChangedEvent) => void, filter: ModelEventFilter = {}): Disposable {
1195
+ const target = this.filterUri(filter);
1196
+ return this.services.workspace.TextDocuments.onDidChangeDirty(event => {
1197
+ if (this.matches(target, event.uri)) {
1198
+ listener(event);
1199
+ }
1200
+ });
1201
+ }
1202
+
1203
+ onModelReleased(listener: (event: ModelReleasedEvent) => void, filter: ModelEventFilter = {}): Disposable {
1204
+ const target = this.filterUri(filter);
1205
+ return this.services.workspace.TextDocuments.onDidReleaseDocument(event => {
1206
+ if (this.matches(target, event.uri)) {
1207
+ listener(event);
1208
+ }
1209
+ });
1210
+ }
1211
+
1212
+ onClientClosed(listener: () => void, filter: { readonly uri: string; readonly clientId: string }): Disposable {
1213
+ const target = this.uriPolicy.canonicalUri(filter.uri);
1214
+ return this.services.workspace.TextDocuments.onDidClose(event => {
1215
+ if (event.clientId === filter.clientId && this.uriPolicy.canonicalUri(event.document.uri) === target) {
1216
+ listener();
1217
+ }
1218
+ });
1219
+ }
1220
+
1221
+ protected filterUri(filter: ModelEventFilter): CanonicalUri | undefined {
1222
+ return filter.uri === undefined ? undefined : this.uriPolicy.canonicalUri(filter.uri);
1223
+ }
1224
+
1225
+ protected matches(target: CanonicalUri | undefined, uri: CanonicalUri): boolean {
1226
+ return target === undefined || target === uri;
956
1227
  }
957
1228
 
958
1229
  /**
959
- * Subscribe to the `(uri, clientId)` close event. Delegates to the
960
- * manager so the listener registry is shared with any direct
961
- * `HydraniumTextDocuments.onClientClosed` subscriber.
1230
+ * Hand every subscriber of `phase` for `document` one event, built once, so
1231
+ * all of them see the same attribution. Built inside the build's listener
1232
+ * and handed out without an await: after one, another build can have reset
1233
+ * the document.
962
1234
  */
963
- onClientClosed(uri: string, clientId: string, listener: () => void): Disposable {
964
- return this.services.workspace.AstDocumentManager.onClientClosed(uri, clientId, listener);
1235
+ protected deliverUpdate(
1236
+ phase: DocumentState,
1237
+ subscribers: ReadonlySet<ModelUpdateSubscriber<TAst, TDiagnostic>>,
1238
+ document: LangiumDocument,
1239
+ cancelToken: CancellationToken
1240
+ ): void {
1241
+ if (cancelToken.isCancellationRequested || subscribers.size === 0) {
1242
+ return;
1243
+ }
1244
+ const uri = this.uriPolicy.canonicalUri(document.uri.toString());
1245
+ const matching = [...subscribers].filter(subscriber => this.matches(subscriber.uri, uri));
1246
+ if (matching.length === 0) {
1247
+ return;
1248
+ }
1249
+ const manager = this.services.workspace.AstDocumentManager;
1250
+ const envelope = manager.toAstDocument(document) as AstDocument<TAst, TDiagnostic>;
1251
+ const event: ModelUpdatedEvent<TAst, TDiagnostic> = Object.freeze({
1252
+ // Copied: a validation run without a reset, of further categories,
1253
+ // appends to the live array.
1254
+ document:
1255
+ phase >= DocumentState.Validated
1256
+ ? { ...envelope, ...(envelope.diagnostics && { diagnostics: [...envelope.diagnostics] }) }
1257
+ : (this.withoutDiagnostics(envelope) as AstDocument<TAst, TDiagnostic>),
1258
+ ...manager.attributeUpdate(document),
1259
+ phase
1260
+ });
1261
+ for (const { listener } of matching) {
1262
+ // A write queued by an earlier listener cancels this build. Thrown,
1263
+ // so the builder leaves the version undelivered for those skipped.
1264
+ if (cancelToken.isCancellationRequested) {
1265
+ throw OperationCancelled;
1266
+ }
1267
+ try {
1268
+ listener(event);
1269
+ } catch (err: unknown) {
1270
+ this.tracer
1271
+ .with(uri)
1272
+ .error(`onModelUpdated listener threw: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
1273
+ }
1274
+ }
965
1275
  }
966
1276
 
967
1277
  // ============================================================
@@ -979,13 +1289,13 @@ export class ModelService<
979
1289
  * Adopters whose serializer call shape differs (custom service
980
1290
  * names, generator-driven YAML pretty printers, etc.) override this
981
1291
  * method. Routes through `Serializer.serializeTransfer` because
982
- * `ModelService.update` / `ModelService.save` always receive a
1292
+ * a session's `update` / `save` always receive a
983
1293
  * transfer-model shape (cross-references as plain strings) from
984
1294
  * adopter callers — the AST-shape entry point is `serializeAst`.
985
1295
  *
986
1296
  * Returns {@link MaybePromise} so adopter `Serializer` overrides can be
987
1297
  * async (remote schema lookup, external canonical-value resolution); the
988
- * single caller ({@link modelToText} → {@link update}) is already `async`,
1298
+ * single caller ({@link modelToText}) is already `async`,
989
1299
  * so a naive `await` covers both branches without extra ceremony.
990
1300
  */
991
1301
  protected serialize(uri: string, root: TTransfer): MaybePromise<string> {
@@ -998,22 +1308,12 @@ export class ModelService<
998
1308
  // ============================================================
999
1309
 
1000
1310
  /**
1001
- * Convert a structured-or-textual `model` payload to its textual form.
1002
- *
1003
- * Textual payloads (LSP / pre-serialised callers) pass through untouched.
1004
- * Structured payloads run the per-language `UpdateRewriteService` chain
1005
- * (transfer-model transforms; diff-aware rewrites see the previous AST root),
1006
- * then serialise. The chain is the single transfer-model-transform seam — a
1007
- * unary normalisation is just a rewrite that ignores `previous`, as
1008
- * `NormalizeEmptyStringsContribution` does. The chain is empty by
1009
- * default, so this is a no-op for adopters that register none.
1311
+ * The text a write into a document not yet built should take its trivia
1312
+ * from: the store's, which a write always has, since it writes only a
1313
+ * document its client has open.
1010
1314
  */
1011
- protected async modelToText(uri: string, model: TTransfer | string, cancelToken?: CancellationToken): Promise<string> {
1012
- if (typeof model === 'string') {
1013
- return model;
1014
- }
1015
- const rewritten = await this.rewriteModel(uri, model, cancelToken);
1016
- return this.serialize(uri, rewritten);
1315
+ protected async textToTakeTriviaFrom(uri: string, _target: URI): Promise<string | undefined> {
1316
+ return this.services.workspace.TextDocuments.get(uri)?.getText();
1017
1317
  }
1018
1318
 
1019
1319
  /**
@@ -1037,15 +1337,37 @@ export class ModelService<
1037
1337
 
1038
1338
  /**
1039
1339
  * Build an {@link AstDocument} envelope from the current
1040
- * {@link LangiumDocument} state via the shared {@link AstDocument.from}
1041
- * projection. Returns an empty envelope (built via
1340
+ * {@link LangiumDocument} state via `AstDocumentManager.toAstDocument`,
1341
+ * the projection events use too. Returns an empty envelope (built via
1042
1342
  * {@link AstDocument.create}) when the document is absent from the
1043
- * registry — adopters that prefer to throw override on their subclass.
1343
+ * registry — adopters that prefer to throw override on their subclass. Its
1344
+ * version is {@link UNRECORDED_VERSION}, so a write based on it conflicts.
1044
1345
  */
1045
1346
  protected toAstDocument(uri: URI): AstDocument<TAst, TDiagnostic> {
1046
1347
  const document = this.services.workspace.LangiumDocuments.getDocument(uri);
1047
1348
  return document
1048
- ? AstDocument.from<TAst, TDiagnostic>(document)
1049
- : AstDocument.create<TAst, TDiagnostic>(uri.toString(), 0, undefined as unknown as TAst, []);
1349
+ ? (this.services.workspace.AstDocumentManager.toAstDocument(document) as AstDocument<TAst, TDiagnostic>)
1350
+ : AstDocument.create<TAst, TDiagnostic>(uri.toString(), UNRECORDED_VERSION, undefined as unknown as TAst);
1351
+ }
1352
+
1353
+ /**
1354
+ * The same envelope with no diagnostics, for a read that names a phase below
1355
+ * `Validated`. Absent rather than `[]`, which says the document was validated
1356
+ * and found clean.
1357
+ *
1358
+ * Langium fills `LangiumDocument.diagnostics` from inside `validateDocument`
1359
+ * and from nowhere else, so below that phase the array holds whatever an
1360
+ * EARLIER build left — a verdict about text the document may no longer have.
1361
+ * The wait underneath resolves at or above the phase asked for, so a document
1362
+ * something else carried past `Validated` would otherwise hand a full array
1363
+ * back from `parsed()`.
1364
+ *
1365
+ * A copy rather than a clear: the envelope is freshly built here, but
1366
+ * {@link toAstDocument} is overridable and an adopter's version may return
1367
+ * one it also keeps.
1368
+ */
1369
+ protected withoutDiagnostics(document: AstDocument<TAst, TDiagnostic>): AstDocument<TAst, never> {
1370
+ const { diagnostics: _diagnostics, ...rest } = document;
1371
+ return rest;
1050
1372
  }
1051
1373
  }