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

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
@@ -19,11 +19,17 @@
19
19
  // eslint-disable-next-line @typescript-eslint/no-restricted-imports
20
20
  import { NormalizedTextDocuments } from '@hydranium/langium/lsp';
21
21
  import { UriUtils } from '@hydranium/langium';
22
- import { OptionalVersionedTextDocumentIdentifier, TextDocumentEdit, TextDocumentSyncKind } from 'vscode-languageserver';
22
+ import { Emitter, OptionalVersionedTextDocumentIdentifier, TextDocumentEdit, TextDocumentSyncKind } from 'vscode-languageserver';
23
23
  import { TextDocument } from 'vscode-languageserver-textdocument';
24
- import { asLanguageClientUri, DisposableCollection } from '@hydranium/protocol';
24
+ import { asLanguageClientUri, DisposableCollection, STALE_VERSION, UNRECORDED_VERSION } from '@hydranium/protocol';
25
25
  import { LANGUAGE_CLIENT_ID } from './client-ids.js';
26
- import { isFullReplace, LanguageClientTextShadow } from './language-client-text-shadow.js';
26
+ import { INTEGRITY_CLIENT_ID } from '../langium/integrity/integrity-rule.js';
27
+ import { ClientSessionRegistry } from './client-session-registry.js';
28
+ import { DefaultLanguageClientShadow } from './language-client-shadow.js';
29
+ import { DefaultTextLedger } from './text-ledger.js';
30
+ import { isDocumentReleaseSkippedError } from './document-release-handler.js';
31
+ import { DefaultDocumentReleaseScheduler } from './document-release-scheduler.js';
32
+ import { DefaultDirtyStateTracker } from './dirty-state-tracker.js';
27
33
  /**
28
34
  * The LSP spec's "version is intentionally unknown" for an
29
35
  * {@link OptionalVersionedTextDocumentIdentifier} is `null`, but
@@ -33,141 +39,124 @@ import { isFullReplace, LanguageClientTextShadow } from './language-client-text-
33
39
  */
34
40
  const UNKNOWN_CLIENT_VERSION = null;
35
41
  /**
36
- * Upper bound on {@link HydraniumTextDocuments.__pendingPushes} entries
37
- * per URI. Echoes normally return within milliseconds and consume their
38
- * entry; a queue this deep means the client stopped echoing — cap instead
39
- * of leaking.
42
+ * The default of {@link HydraniumTextDocumentsOptions.releaseGraceMs}: long
43
+ * enough for a client whose connection dropped to register again and reopen
44
+ * its documents, which a data client does as soon as it has a connection.
40
45
  */
41
- const PENDING_ECHO_CAP = 32;
46
+ const DEFAULT_RELEASE_GRACE_MS = 10_000;
42
47
  /**
43
- * Cheap, stable, non-cryptographic content hash (cyrb53) for the version
44
- * sequence's "did the content change across close/reopen?" question. Only
45
- * needs to be collision-resistant enough that an accidental match across two
46
- * DIFFERENT revisions of the same file is practically impossible; 53 bits of
47
- * a well-mixed hash over full text + length gives that without pulling in
48
- * `node:crypto` (this module must stay runnable in browser hosts).
49
- */
50
- function contentHash(text) {
51
- let h1 = 0xdeadbeef;
52
- let h2 = 0x41c6ce57;
53
- for (let index = 0; index < text.length; index++) {
54
- const code = text.charCodeAt(index);
55
- h1 = Math.imul(h1 ^ code, 2654435761);
56
- h2 = Math.imul(h2 ^ code, 1597334677);
57
- }
58
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
59
- h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
60
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
61
- h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
62
- return `${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}:${text.length}`;
63
- }
64
- /**
65
- * Multi-client text-document tracking on top of Langium's `NormalizedTextDocuments`.
48
+ * The one text store every head writes to, on top of Langium's
49
+ * `NormalizedTextDocuments`, and the LSP text-sync endpoint: every
50
+ * `textDocument/*` notification and every `workspace/applyEdit` push goes
51
+ * through here.
52
+ *
53
+ * Each open, change, close and save is one synchronous transition over the
54
+ * held document and the collaborators its `create…` methods build. A
55
+ * collaborator that defers its part lets a listener of the transition's event
56
+ * read state from before it. A document no client holds any more is
57
+ * released to the `DocumentReleaseHandler` slot, after
58
+ * {@link HydraniumTextDocumentsOptions.releaseGraceMs} when its last client's
59
+ * connection was lost.
66
60
  *
67
- * Adds the framework features used by the integrity, model-server, and GLSP layers:
68
- * - Per-document client membership (multiple clients can attach to the same URI).
69
- * - A SERVER-OWNED shared version sequence: per-URI, monotonic across
70
- * close/reopen cycles, advancing exactly when the synced content changes.
71
- * Client-declared version ids (Monaco's buffer numbering) feed only a
72
- * per-client staleness guard and never leak into the shared sequence —
73
- * the two are different things (an editor's edit-operation counter vs the
74
- * document's content-revision number), and splicing them lets versions drift
75
- * silently past `baseVersion` gate holders.
76
- * - Version-author history so each edit is attributable to its originating client.
77
- * - Pending-content staging used by the integrity service to thread corrections
78
- * through `workspace/applyEdit` cycles for currently-closed documents.
79
- * - `didOpen` notifications arriving over the LSP connection wait on the
80
- * workspace-ready promise, so a client's first open cannot race workspace
81
- * discovery. Direct {@link notifyDidOpenTextDocument} calls (the non-LSP
82
- * heads) do not pass that gate — their caller owns the ordering.
61
+ * Client-declared version ids feed only the per-client staleness guard and
62
+ * never a running shared sequence: the two count different things, and
63
+ * splicing them lets versions drift past base-version gate holders. A URI
64
+ * with no ledger record and no built root starts at its opener's declared id:
65
+ * no version was handed out for it.
66
+ *
67
+ * `didOpen` notifications arriving over the LSP connection wait on the
68
+ * workspace-ready promise, so a client's first open cannot race workspace
69
+ * discovery. Direct {@link notifyDidOpenTextDocument} calls (the non-LSP
70
+ * heads) do not pass that gate — their caller owns the ordering.
83
71
  */
84
72
  export class HydraniumTextDocuments extends NormalizedTextDocuments {
85
73
  services;
74
+ options;
75
+ /** Content staged by integrity rules for a document no client holds, consumed by its first open. */
76
+ __pendingContent = new Map();
86
77
  /**
87
- * Per-URI client-facing tracking ({@link DocumentTracking}): client
88
- * membership, version-author history, and integrity-staged pending content,
89
- * keyed by normalized URI. One record per URI so the last-client close clears
90
- * every axis atomically. The language-client diff baseline stays in
91
- * {@link __shadow} (its own abstraction); the parsed-document store stays in
92
- * the inherited `__syncedDocuments`.
93
- */
94
- __documents = new Map();
95
- /**
96
- * Per-URI shared-version continuity across close/reopen cycles
97
- * ({@link VersionSequence}), written at last-client close and consulted by
98
- * the next first-client open. DELIBERATELY outside {@link DocumentTracking}:
99
- * that record is deleted on last close, while the version sequence must
100
- * survive it — the shared version is a server-owned, monotonic,
101
- * advances-iff-content-changes counter that never resets while the server
102
- * lives. That invariant is what makes an optimistic `baseVersion` gate
103
- * sound: "version unchanged ⇔ content unchanged", with no false conflicts
104
- * from close/reopen version resets and no false passes from a reopened
105
- * sequence coincidentally landing on a stale writer's number.
106
- *
107
- * Never pruned: two small values per URI ever touched — bounded by
108
- * workspace size, not by activity.
109
- */
110
- __versionSequences = new Map();
111
- /**
112
- * Texts pushed to the LSP textual language client via
113
- * {@link applyEditToLanguageClient} whose echoes have not come back yet
114
- * ({@link PendingPush}), keyed like the shadow by language-client URI.
115
- * Outbound pushes and inbound echoes are uncorrelated on the wire; this
116
- * FIFO is the explicit correlation, and it is what
117
- * {@link classifyLanguageClientChange} reconstructs against.
118
- *
119
- * **Each entry keeps the client's PRE-push text, not only a hash of the
120
- * post-push one.** A hash alone can classify a full-text echo, whose
121
- * application is a no-op either way — and that is all it ever classified,
122
- * because a conforming client echoes INCREMENTAL ranges keyed to its
123
- * previous buffer. Those ranges cannot be applied to the synced text (which
124
- * the authored write already advanced) and cannot be reconstructed without
125
- * the baseline: the line they insert lands twice, validates cleanly, and
126
- * compounds on every later edit.
127
- *
128
- * Lifecycle: entries are consumed by the matching echo (together with any
129
- * older entries it supersedes), and the whole queue drops when the client
130
- * stops being a pure mirror — a divergent change, an `applyEdit`
131
- * failure/rejection (shadow invalidation), a close, or an explicit
132
- * shadow (re)baseline. {@link PENDING_ECHO_CAP} bounds the queue against
133
- * a pathological echo that never arrives; the memory cost until then is
134
- * one pre-push text per in-flight push, for milliseconds.
135
- */
136
- __pendingPushes = new Map();
137
- /**
138
- * Tracked text content per URI for the LSP textual language client (Monaco / VS Code).
139
- * Owned here so {@link applyEditToLanguageClient} can compute minimal `workspace/applyEdit`
140
- * diffs instead of full-document replaces (5–20 s → <500 ms on 20-30 KB YAML diagrams).
141
- *
142
- * Auto-tracked from the multi-client text-document events: open / change / close of
143
- * the language client (re)baseline or invalidate the shadow. Other client ids
144
- * (form editor, GLSP, integrity) do NOT touch the shadow — only what Monaco believes
145
- * it has matters for the diff.
146
- *
147
- * Apply-verify safety net is built in: if the diff doesn't reconstruct `newText`
148
- * exactly, {@link LanguageClientTextShadow.computeEdits} falls back to a full-range
149
- * replace and invokes the `onFallback` callback — a diff regression becomes log
150
- * noise, not a 0-byte save.
151
- *
152
- * Assigned in the constructor body so the `onFallback` callback can capture
153
- * `this.logger` after the parameter-property assignment has run (field
154
- * initializers fire BEFORE parameter-property assignment in TS).
78
+ * Which client has which document open, which client ids are registered
79
+ * sessions, and each client's declared version, the staleness guard's
80
+ * baseline. Every open-state predicate on this class reads it, so an open
81
+ * recorded anywhere else is invisible to the last-close transition.
155
82
  */
156
- __shadow;
83
+ __sessions = new ClientSessionRegistry();
84
+ /** The version each open document was opened at; see {@link openedVersion}. */
85
+ __openedVersions = new Map();
157
86
  tracer;
158
87
  configuration;
88
+ __textLedger;
89
+ __languageClientShadow;
90
+ __dirtyStateTracker;
91
+ __documentReleaseScheduler;
92
+ documentReleasedEmitter = new Emitter();
93
+ languageClientSavedEmitter = new Emitter();
159
94
  constructor(services, options = {}) {
160
95
  const configuration = options.configuration ?? TextDocument;
161
96
  super(configuration);
162
97
  this.services = services;
98
+ this.options = options;
163
99
  this.configuration = configuration;
164
100
  this.tracer = services.Tracer.for(options.logName ?? 'TextDocuments').trace('instantiated');
165
- this.__shadow = new LanguageClientTextShadow((uri, reason) => this.tracer.with(uri).warn(`Diff apply-verify fallback (${reason}) — using full-document replace`), this);
166
101
  }
167
- // Re-exposed configuration factories — for framework-internal callers
168
- // (LanguageClientTextShadow's apply-verify probe; IntegrityService.resyncDocument)
169
- // that need to materialise documents outside the canonical didOpen/didChange flow
170
- // and must respect the adopter's custom text-document type.
102
+ // Each collaborator is built on first use, after every constructor has run,
103
+ // so a create method may read its subclass's fields and the other collaborators.
104
+ get textLedger() {
105
+ return (this.__textLedger ??= this.createTextLedger());
106
+ }
107
+ get languageClientShadow() {
108
+ return (this.__languageClientShadow ??= this.createLanguageClientShadow());
109
+ }
110
+ get dirtyStateTracker() {
111
+ return (this.__dirtyStateTracker ??= this.createDirtyStateTracker());
112
+ }
113
+ get documentReleaseScheduler() {
114
+ return (this.__documentReleaseScheduler ??= this.createDocumentReleaseScheduler());
115
+ }
116
+ createTextLedger() {
117
+ return new DefaultTextLedger();
118
+ }
119
+ createLanguageClientShadow() {
120
+ return new DefaultLanguageClientShadow(this, this.tracer);
121
+ }
122
+ createDirtyStateTracker() {
123
+ return new DefaultDirtyStateTracker(this.textLedger);
124
+ }
125
+ createDocumentReleaseScheduler() {
126
+ return new DefaultDocumentReleaseScheduler(this.services.Clock, this.options.releaseGraceMs ?? DEFAULT_RELEASE_GRACE_MS);
127
+ }
128
+ /** Hold `document` as the text of `key`, a new version authored by `author`. */
129
+ commitText(key, document, author) {
130
+ this.__syncedDocuments.set(key, document);
131
+ this.setAuthor(key, document.version, author);
132
+ this.dirtyStateTracker.refreshDirty(key, document);
133
+ }
134
+ /**
135
+ * Apply `changes` to `document`, the held text of `key`, and hold the
136
+ * result. The version steps only when the text changes, which is what a
137
+ * base-version gate relies on: unchanged text keeps its version and its
138
+ * author. The new text is known only once the changes are applied, so they
139
+ * go in at a tentative step that an identical result rolls back.
140
+ */
141
+ commitChange(key, document, changes, author) {
142
+ const previousText = document.getText();
143
+ const version = document.version;
144
+ let next = this.update(document, changes, version + 1);
145
+ const changed = next.getText() !== previousText;
146
+ if (changed) {
147
+ this.commitText(key, next, author);
148
+ }
149
+ else {
150
+ // An empty-changes update only re-stamps the version.
151
+ next = this.update(next, [], version);
152
+ this.__syncedDocuments.set(key, next);
153
+ }
154
+ return { document: next, changed };
155
+ }
156
+ // The configuration's factories. Every document the store makes or changes
157
+ // goes through them, so an override sees each call: the store's own writes,
158
+ // callers outside the didOpen/didChange flow, and the shadow's throwaway
159
+ // probes, at version 0 under a client URI.
171
160
  create(uri, languageId, version, content) {
172
161
  return this.configuration.create(uri, languageId, version, content);
173
162
  }
@@ -221,7 +210,7 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
221
210
  connection.__textDocumentSync = TextDocumentSyncKind.Incremental;
222
211
  const disposables = new DisposableCollection();
223
212
  disposables.push(connection.onDidOpenTextDocument(async (event) => {
224
- await this.services.workspace.WorkspaceManager.workspaceInitialized;
213
+ await this.initialBuildFinished();
225
214
  this.notifyDidOpenTextDocument(event);
226
215
  }));
227
216
  disposables.push(connection.onDidChangeTextDocument((event) => {
@@ -235,7 +224,7 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
235
224
  }));
236
225
  disposables.push(connection.onWillSaveTextDocumentWaitUntil((event, token) => this.notifyWillSaveTextDocumentWaitUntil(event, token)));
237
226
  disposables.push(connection.onDidSaveTextDocument((event) => {
238
- this.notifyDidSaveTextDocument(event);
227
+ void this.notifyLanguageClientSave(event);
239
228
  }));
240
229
  return disposables;
241
230
  }
@@ -252,80 +241,57 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
252
241
  const uri = this.documentKey(td.uri);
253
242
  let document = this.__syncedDocuments.get(uri);
254
243
  if (document !== undefined) {
255
- // Per-client staleness guard: client version ids are CLIENT-owned per
256
- // LSP (Monaco numbers its own buffer), so an incoming id is compared
257
- // against THAT client's last declared id — never against the shared
258
- // version, which the server assigns and which routinely runs ahead of
259
- // a client's ids (authored ModelService writes advance it without the
260
- // client knowing). Gating on the shared version drops real edits in
261
- // exactly that lag window. A client with no baseline (never opened —
262
- // a protocol anomaly) falls back to the shared-version compare, the
263
- // conservative answer.
264
- const record = this.trackingFor(uri);
265
- const lastSeen = record.clientVersions.get(clientId) ?? document.version;
244
+ // Client version ids are the client's own, so compared against what
245
+ // that client declared, never against the shared version: an authored
246
+ // write advances that without the client knowing, and gating on it
247
+ // drops real edits. The editor is checked per URI, since each is its
248
+ // own buffer; its client-wide entry is only the fallback for a URI it
249
+ // never opened, and may name another URI's buffer. A client with no
250
+ // baseline falls back to the shared version.
251
+ const clientUri = this.toLanguageClientUri(td.uri);
252
+ const editor = clientId === LANGUAGE_CLIENT_ID;
253
+ const lastSeen = (editor ? this.languageClientShadow.declaredVersion(uri, clientUri) : undefined) ??
254
+ this.__sessions.clientVersionOf(uri, clientId) ??
255
+ document.version;
266
256
  if (lastSeen >= td.version) {
267
257
  // Distinguish "already at this version" (common: an echo from the client that triggered
268
258
  // the update) from "incoming version older than ours" (stale race).
269
259
  const reason = lastSeen === td.version ? `already at version ${lastSeen}` : `incoming version ${td.version} older than current ${lastSeen}`;
270
- this.logUri(uri, `Ignore update by ${clientId}: ${reason}`, 'debug');
260
+ this.logUri(uri, `Ignore update by ${this.formatClientId(clientId)}: ${reason}`, 'debug');
271
261
  return;
272
262
  }
273
- record.clientVersions.set(clientId, td.version);
274
- // A language-client change arriving while one of our own pushes is in
275
- // flight is keyed to the buffer the client held BEFORE that push, NOT
276
- // to the synced text — the authored write already advanced the latter.
277
- // Resolve which it is, and against what, before touching anything.
278
- const inFlight = clientId === LANGUAGE_CLIENT_ID
279
- ? this.classifyLanguageClientChange(this.toLanguageClientUri(td.uri), document, changes)
280
- : undefined;
281
- if (inFlight?.kind === 'echo') {
282
- // The client is reporting a text we pushed it, so the synced
283
- // document is ALREADY there and the changes must not be applied a
284
- // second time. Nothing is minted and no rebuild fires. The
285
- // per-client baseline advanced above (the client's ids keep
286
- // counting); the shadow is deliberately NOT touched — it
287
- // optimistically tracks the NEWEST pushed text, and dragging it
288
- // back would make the next outbound diff wrong against what the
289
- // client actually holds.
263
+ this.__sessions.setClientVersion(uri, clientId, td.version);
264
+ // An editor change is keyed to the buffer the editor holds, which is
265
+ // the synced text only while the two agree — an authored write
266
+ // advances the synced text without the editor knowing, and a push in
267
+ // flight moves the editor without the store knowing.
268
+ const verdict = editor
269
+ ? this.languageClientShadow.acceptChange(uri, clientUri, td.version, document, changes)
270
+ : { kind: 'direct' };
271
+ if (verdict.kind === 'echo') {
272
+ // The synced document is already there, so the changes must not be
273
+ // applied a second time: nothing is minted and no rebuild fires. The
274
+ // shadow keeps the newest pushed text, which is what the next
275
+ // outbound diff has to be keyed to.
290
276
  this.logUri(uri, `Skip rebuild: echo of a server-authored push (client version ${td.version})`, 'debug');
291
277
  return;
292
278
  }
293
- // The SHARED version advances iff the content actually changes — the
294
- // invariant optimistic `baseVersion` gates rely on. The new text is
295
- // only known after applying the (possibly incremental) changes, so
296
- // apply at a tentative +1 and roll the version back on an identical
297
- // result (an empty-changes update only re-stamps the version).
298
- //
299
- // A divergent in-flight change is applied as its RECONSTRUCTED text
300
- // rather than as its own ranges: the ranges address the pre-push
301
- // baseline, so applying them here would splice the wrong lines.
302
- const previousText = document.getText();
303
- const sharedVersion = document.version;
304
- document = this.configuration.update(document, inFlight === undefined ? changes : [{ text: inFlight.text }], sharedVersion + 1);
305
- const changed = document.getText() !== previousText;
306
- if (!changed) {
307
- document = this.configuration.update(document, [], sharedVersion);
308
- }
309
- this.__syncedDocuments.set(uri, document);
310
- if (changed) {
311
- this.setAuthor(uri, document.version, clientId);
312
- }
313
- if (clientId === LANGUAGE_CLIENT_ID) {
314
- // Monaco just told us about its new content; record it so the next outbound
315
- // applyEditToLanguageClient diffs against the right baseline. Keyed by the
316
- // language-client URI (what Monaco holds), not the canonical document key.
317
- this.__shadow.set(this.toLanguageClientUri(td.uri), document.getText());
318
- // Content-identical echo: the language client is echoing text we already had
319
- // (e.g. Monaco re-emitting a server-pushed applyEditToLanguageClient). The model is
320
- // unchanged, so skip the rebuild. The per-client baseline + shadow still advanced
321
- // above so future staleness checks and diffs are correct. Restricted to the
322
- // language client: a ModelService-authored change is never skipped.
323
- if (!changed) {
279
+ // A divergent change is applied as its reconstructed text rather than
280
+ // as its own ranges: those ranges address the editor's own buffer, so
281
+ // applying them here would splice the wrong lines.
282
+ const committed = this.commitChange(uri, document, verdict.kind === 'direct' ? changes : [{ text: verdict.text }], clientId);
283
+ document = committed.document;
284
+ if (editor) {
285
+ this.languageClientShadow.setClientText(clientUri, document.getText());
286
+ // Content-identical echo: the editor is echoing text we already had.
287
+ // The model is unchanged, so skip the rebuild. Restricted to the
288
+ // editor: a ModelService-authored change is never skipped.
289
+ if (!committed.changed) {
324
290
  this.logUri(uri, `Skip rebuild: content unchanged (echo at client version ${td.version})`, 'debug');
325
291
  return;
326
292
  }
327
293
  }
328
- this.log(document.uri, `Update to version ${document.version} by ${clientId}${changed ? '' : ' (content unchanged)'}`);
294
+ this.log(document.uri, `Update to version ${document.version} by ${this.formatClientId(clientId)}${committed.changed ? '' : ' (content unchanged)'}`);
329
295
  this.__onDidChangeContent.fire(Object.freeze({ document, clientId }));
330
296
  }
331
297
  }
@@ -341,70 +307,167 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
341
307
  * A content-identical write still fires the change event (rebuild): the
342
308
  * authored write's server-side rebuild is correctness-bearing, it just
343
309
  * mints no new version — nothing observable changed, so watchers'
344
- * `baseVersion` pointers stay valid.
310
+ * base versions stay valid.
345
311
  *
346
312
  * Returns the resulting shared version. Throws when the document is not
347
313
  * open — callers (`AstDocumentManager.update`) open first.
348
314
  */
349
315
  applyContentChange(uri, text, clientId) {
350
316
  const key = this.documentKey(uri);
351
- let document = this.__syncedDocuments.get(key);
352
- if (document === undefined) {
317
+ const synced = this.__syncedDocuments.get(key);
318
+ if (synced === undefined) {
353
319
  throw new Error(`Document ${uri} is not open for content changes`);
354
320
  }
355
- const changed = document.getText() !== text;
356
- if (changed) {
357
- document = this.configuration.update(document, [{ text }], document.version + 1);
358
- this.__syncedDocuments.set(key, document);
359
- this.setAuthor(key, document.version, clientId);
360
- }
361
- this.log(document.uri, `Update to version ${document.version} by ${clientId}${changed ? '' : ' (content unchanged)'}`);
321
+ // Unchanged text calls no update: a configuration may return a new document for one.
322
+ const { document, changed } = synced.getText() === text ? { document: synced, changed: false } : this.commitChange(key, synced, [{ text }], clientId);
323
+ this.log(document.uri, `Update to version ${document.version} by ${this.formatClientId(clientId)}${changed ? '' : ' (content unchanged)'}`);
362
324
  this.__onDidChangeContent.fire(Object.freeze({ document, clientId }));
363
325
  return document.version;
364
326
  }
365
- notifyDidCloseTextDocument(event, clientId = LANGUAGE_CLIENT_ID) {
327
+ /**
328
+ * Close `clientId`'s open of the document. When it was the last open, the
329
+ * document is released, at once or, for a `'lost'`
330
+ * close, after {@link HydraniumTextDocumentsOptions.releaseGraceMs}.
331
+ */
332
+ notifyDidCloseTextDocument(event, clientId = LANGUAGE_CLIENT_ID, cause = 'closed') {
366
333
  const uri = this.documentKey(event.textDocument.uri);
367
- if (!this.isOpenInClient(uri, clientId)) {
334
+ if (clientId === LANGUAGE_CLIENT_ID) {
335
+ const clientUri = this.toLanguageClientUri(event.textDocument.uri);
336
+ // A close under a URI the editor never opened the document under ends its hold.
337
+ if (this.languageClientShadow.isOpen(uri, clientUri)) {
338
+ this.languageClientShadow.removeOpen(uri, clientUri);
339
+ }
340
+ else {
341
+ this.languageClientShadow.removeAllOpens(uri);
342
+ }
343
+ // Another URI still holds the document, so only this one's buffer goes.
344
+ if (this.languageClientShadow.isOpen(uri)) {
345
+ return;
346
+ }
347
+ }
348
+ if (!this.__sessions.removeOpen(uri, clientId)) {
368
349
  return;
369
350
  }
370
- const closingRecord = this.__documents.get(uri);
371
- closingRecord?.clients.delete(clientId);
372
- closingRecord?.clientVersions.delete(clientId);
351
+ if (cause === 'lost') {
352
+ this.documentReleaseScheduler.recordLoss(uri, clientId);
353
+ }
373
354
  const syncedDocument = this.__syncedDocuments.get(uri);
374
355
  if (syncedDocument !== undefined) {
375
- this.log(syncedDocument.uri, `Closed synced document: ${syncedDocument.version} by ${clientId}`);
356
+ this.log(syncedDocument.uri, `Closed synced document: ${syncedDocument.version} by ${this.formatClientId(clientId)}`);
376
357
  this.__onDidClose.fire(Object.freeze({ document: syncedDocument, clientId }));
377
- if (clientId === LANGUAGE_CLIENT_ID) {
378
- // Monaco closed the document; drop the URI it held and the shadow
379
- // baselined under it. (If this was the last URI/client the whole record
380
- // is deleted below, clearing the set anyway.)
381
- const droppedUri = this.toLanguageClientUri(event.textDocument.uri);
382
- this.__documents.get(uri)?.languageClientUris?.delete(droppedUri);
383
- this.__shadow.invalidate(droppedUri);
384
- this.__pendingPushes.delete(droppedUri);
358
+ if (!this.isOpenInAnyClient(uri)) {
359
+ if (cause === 'lost') {
360
+ this.deferRelease(uri);
361
+ }
362
+ else {
363
+ this.releaseDocument(uri);
364
+ }
385
365
  }
386
- if (!this.__documents.get(uri)?.clients.size) {
387
- // Last client closed the document; delete sync state. The downstream
388
- // "rebuild from disk for file URIs / drop from index for ephemeral
389
- // URIs" decision lives in `HydraniumDocumentUpdateHandler.didCloseDocument`,
390
- // which subscribes to `onDidClose` and consults `isOpenInAnyClient`
391
- // to detect the last-close transition.
392
- this.log(syncedDocument.uri, `Remove synced document: ${syncedDocument.version} (no client left)`);
393
- // Persist where the shared version sequence left off (version +
394
- // content hash) so the next open CONTINUES the sequence instead of
395
- // restarting at the reopening client's declared id. Hashed once
396
- // here at close, not on every change.
397
- this.__versionSequences.set(uri, {
398
- version: syncedDocument.version,
399
- contentHash: contentHash(syncedDocument.getText())
400
- });
401
- this.__syncedDocuments.delete(uri);
402
- // One delete clears every per-URI axis (version history + any staged
403
- // pending content) so a future open with the same URI starts fresh.
404
- this.__documents.delete(uri);
366
+ }
367
+ }
368
+ /**
369
+ * Keep the document, text and all, for the release grace, then release it.
370
+ * The document stays in the store meanwhile, so a lost client that opens it
371
+ * again within its own grace attaches to it and finds its unsaved text
372
+ * rather than reading disk; see {@link resolveDeferredRelease} for any other
373
+ * open.
374
+ */
375
+ deferRelease(uri) {
376
+ this.documentReleaseScheduler.defer(uri, () => {
377
+ if (!this.isOpenInAnyClient(uri)) {
378
+ this.releaseDocument(uri);
405
379
  }
380
+ });
381
+ if (this.documentReleaseScheduler.isDeferred(uri)) {
382
+ this.log(uri, `No client left; release deferred for ${this.documentReleaseScheduler.graceMs} ms (connection lost)`);
383
+ }
384
+ }
385
+ /** Resolve a deferred release of `uri` for an open by `clientId`: a release the scheduler decides on runs now. */
386
+ resolveDeferredRelease(uri, clientId) {
387
+ if (this.documentReleaseScheduler.resolveOpen(uri, clientId) === 'release') {
388
+ this.releaseDocument(uri);
406
389
  }
407
390
  }
391
+ /**
392
+ * Drop the document no client has open any more, announce it on
393
+ * {@link onDidReleaseDocument}, then hand it to the
394
+ * `DocumentReleaseHandler` slot: its listeners, such as the update
395
+ * handler dropping a change it still holds back, act before any build the
396
+ * handler runs.
397
+ */
398
+ releaseDocument(uri) {
399
+ const syncedDocument = this.__syncedDocuments.get(uri);
400
+ if (syncedDocument === undefined) {
401
+ return;
402
+ }
403
+ this.log(syncedDocument.uri, `Remove synced document: ${syncedDocument.version} (no client left)`);
404
+ // The next open continues the sequence instead of restarting at the
405
+ // reopening client's declared id.
406
+ this.textLedger.record(uri, syncedDocument);
407
+ this.textLedger.clearAuthors(uri);
408
+ const cleanAnnouncement = this.dirtyStateTracker.release(uri);
409
+ this.__syncedDocuments.delete(uri);
410
+ this.__openedVersions.delete(uri);
411
+ this.__sessions.forgetClientVersions(uri);
412
+ // A stage is for a first open; one released unconsumed is stale.
413
+ this.__pendingContent.delete(uri);
414
+ this.documentReleaseScheduler.clearLosses(uri);
415
+ this.documentReleasedEmitter.fire(Object.freeze({ uri }));
416
+ this.handOverRelease(this.toReleasedDocument(uri), cleanAnnouncement);
417
+ }
418
+ /**
419
+ * Call the `DocumentReleaseHandler` slot, and announce a document released
420
+ * dirty clean once the promise it returns settles, which is after the
421
+ * release event. A failure is logged rather than thrown: the store has let
422
+ * go of the document by now, and a throw would abort the transition that
423
+ * released it, a session's close of its other documents included.
424
+ */
425
+ handOverRelease(released, cleanAnnouncement) {
426
+ let settled;
427
+ try {
428
+ // Read here: a lazily built slot whose factory throws throws on this read.
429
+ const handler = this.services.workspace.DocumentReleaseHandler;
430
+ settled =
431
+ handler === undefined
432
+ ? Promise.reject(new Error('no workspace.DocumentReleaseHandler bound'))
433
+ : Promise.resolve(handler.didReleaseDocument(released));
434
+ }
435
+ catch (err) {
436
+ settled = Promise.reject(err);
437
+ }
438
+ // Names the text the build holds at the settle, so it follows anything a
439
+ // release listener did meanwhile: none when its build failed or it no
440
+ // longer has the document, since a removal leaves the record on the
441
+ // discarded text.
442
+ const announceClean = (built) => {
443
+ if (cleanAnnouncement?.isOwed()) {
444
+ const inBuild = built && this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(released.uri)) !== undefined;
445
+ cleanAnnouncement.announce(inBuild ? this.textState(released.uri) : undefined);
446
+ }
447
+ };
448
+ settled.then(() => announceClean(true), (err) => {
449
+ // A release skipped at teardown, its peer or its workspace gone, is
450
+ // routine, not a fault to investigate.
451
+ if (isDocumentReleaseSkippedError(err)) {
452
+ this.tracer.with(released.uri).debug(err.message);
453
+ }
454
+ else {
455
+ this.tracer
456
+ .with(released.uri)
457
+ .error(`Release handler failed. ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
458
+ }
459
+ // Left unsettled, a watcher keeps the document dirty though the store answers clean.
460
+ announceClean(false);
461
+ });
462
+ }
463
+ /** `uri` as the `DocumentReleaseHandler` slot receives it. */
464
+ toReleasedDocument(uri) {
465
+ return {
466
+ uri,
467
+ isFor: other => this.documentKey(other) === uri,
468
+ isReclaimed: () => this.isOpenInAnyClient(uri) || this.__syncedDocuments.has(uri)
469
+ };
470
+ }
408
471
  notifyWillSaveTextDocument(event) {
409
472
  const syncedDocument = this.__syncedDocuments.get(this.documentKey(event.textDocument.uri));
410
473
  if (syncedDocument !== undefined) {
@@ -420,86 +483,167 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
420
483
  return [];
421
484
  }
422
485
  }
486
+ /**
487
+ * Handle a save the language client reports: fire
488
+ * {@link onDidSaveInLanguageClient}, then announce it on {@link onDidSave}
489
+ * only once the file read back from disk holds the store's current text.
490
+ */
491
+ async notifyLanguageClientSave(event) {
492
+ const syncedDocument = this.__syncedDocuments.get(this.documentKey(event.textDocument.uri));
493
+ if (syncedDocument === undefined) {
494
+ return;
495
+ }
496
+ const uri = syncedDocument.uri;
497
+ this.languageClientSavedEmitter.fire(Object.freeze({ uri }));
498
+ // `onDidSave` tells its listeners that the shared document is on disk.
499
+ // The editor wrote its own buffer, which lags the store while another
500
+ // client's edit is still on its way to it, so only the file says
501
+ // whether that holds. Read it rather than trust the editor: `didSave`
502
+ // carries text only for a client that honours `includeText`, and asking
503
+ // for it means rewriting Langium's initialize answer, which advertises
504
+ // `save` as a Boolean. The read goes through the disk queue and waits on
505
+ // nothing but the provider, so it follows a server save queued
506
+ // meanwhile. A file changed again between the editor's write and this
507
+ // read compares unequal, and the save goes unannounced.
508
+ let onDisk;
509
+ try {
510
+ onDisk = await this.services.workspace.FileSystemTaskQueue.enqueue(uri, () => this.services.workspace.FileSystemProvider.readFile(UriUtils.toUri(uri)));
511
+ }
512
+ catch (err) {
513
+ this.tracer
514
+ .with(uri)
515
+ .debug(`Editor save not announced: reading the file back failed. ${err instanceof Error ? err.message : String(err)}`);
516
+ return;
517
+ }
518
+ // What the file holds, not what the editor meant to write: an editor
519
+ // that saved older text leaves the document dirty.
520
+ this.setDiskBaseline(uri, onDisk);
521
+ // An editor that saves and then closes releases the document while the
522
+ // read is under way; its save is still a save of the text it held.
523
+ const document = this.__syncedDocuments.get(this.documentKey(uri)) ?? syncedDocument;
524
+ if (onDisk !== document.getText()) {
525
+ this.tracer.with(uri).debug(`Editor save not announced: the file does not hold the text of version ${document.version}`);
526
+ return;
527
+ }
528
+ this.announceSave(document, LANGUAGE_CLIENT_ID);
529
+ }
530
+ /**
531
+ * Announce a save the server made. `event.text`, when given, is what the
532
+ * file now holds, written or found there, and becomes the disk baseline
533
+ * before the save is announced. It lags the store when an edit landed
534
+ * after the save took its text, and the document then stays dirty.
535
+ */
423
536
  notifyDidSaveTextDocument(event, clientId = LANGUAGE_CLIENT_ID) {
424
537
  const syncedDocument = this.__syncedDocuments.get(this.documentKey(event.textDocument.uri));
425
538
  if (syncedDocument !== undefined) {
426
- this.log(syncedDocument.uri, `Saved synced document: ${syncedDocument.version} by ${clientId}`);
427
- this.__onDidSave.fire(Object.freeze({ document: syncedDocument, clientId }));
539
+ if (event.text !== undefined) {
540
+ this.setDiskBaseline(syncedDocument.uri, event.text);
541
+ }
542
+ this.announceSave(syncedDocument, clientId);
428
543
  }
429
544
  }
545
+ /** Fire {@link onDidSave} for `document`, which need not be synced any more. */
546
+ announceSave(document, clientId) {
547
+ this.log(document.uri, `Saved synced document: ${document.version} by ${this.formatClientId(clientId)}`);
548
+ this.__onDidSave.fire(Object.freeze({ document, clientId }));
549
+ }
430
550
  notifyDidOpenTextDocument(event, clientId = LANGUAGE_CLIENT_ID) {
431
551
  const td = event.textDocument;
432
552
  const uri = this.documentKey(td.uri);
433
- if (this.isOpenInClient(uri, clientId)) {
434
- // Already open for this client under this canonical identity. If this is a
435
- // NEW client-facing URI for the same file (a second tab reached via a
436
- // divergent path, e.g. a symlink and its real path), record it and baseline
437
- // its shadow so outbound edits reach this tab too — but do NOT re-fire
438
- // open/rebuild; the document is already live.
439
- if (clientId === LANGUAGE_CLIENT_ID) {
440
- const clientFacing = this.toLanguageClientUri(td.uri);
441
- const record = this.__documents.get(uri);
442
- if (record && !record.languageClientUris?.has(clientFacing)) {
443
- (record.languageClientUris ??= new Set()).add(clientFacing);
444
- const open = this.__syncedDocuments.get(uri);
445
- if (open) {
446
- this.__shadow.set(clientFacing, open.getText());
447
- }
448
- }
449
- }
450
- return;
553
+ // Before the deferred release is resolved: refused after it, the open
554
+ // would leave a document whose grace it ended with no holder and no timer.
555
+ // A repeat open stays a no-op.
556
+ if (!this.__sessions.isOpenIn(uri, clientId)) {
557
+ this.__sessions.assertCanOpen(clientId);
451
558
  }
559
+ this.resolveDeferredRelease(uri, clientId);
452
560
  let document = this.__syncedDocuments.get(uri);
453
- const record = this.trackingFor(uri);
454
- const existingClients = [...record.clients];
455
- record.clients.add(clientId);
456
- // Baseline the per-client staleness guard at the version id the client
457
- // declared for its own buffer (client-owned per LSP).
458
- record.clientVersions.set(clientId, td.version);
561
+ // The client's declared text, never the synced document: staged
562
+ // content this open consumes leaves the two different, and a baseline
563
+ // asserting the client already holds it suppresses the one sync that
564
+ // would deliver it. On an attach, another client may already have
565
+ // changed the synced text, so the baseline is equality-only; a refresh
566
+ // pushing the full text would dirty the file on open.
459
567
  if (clientId === LANGUAGE_CLIENT_ID) {
460
- // Remember the URI Monaco opened under (may differ from the canonical key)
461
- // so outbound applyEditToLanguageClient can address the URI it actually holds.
462
- (record.languageClientUris ??= new Set()).add(this.toLanguageClientUri(td.uri));
568
+ this.languageClientShadow.addOpen(uri, this.toLanguageClientUri(td.uri), td.version, td.text, document === undefined);
463
569
  }
570
+ if (this.isOpenInClient(uri, clientId)) {
571
+ // A repeat open, or the editor's second URI for the file, e.g. a
572
+ // symlink and its real path: the shadow records it so pushes reach it,
573
+ // and nothing re-fires.
574
+ return;
575
+ }
576
+ const existingClients = this.__sessions.clientsOf(uri);
577
+ this.__sessions.addOpen(uri, clientId);
578
+ this.__sessions.setClientVersion(uri, clientId, td.version);
464
579
  if (!document) {
465
580
  // Use integrity-staged content if available, otherwise the client-provided (disk) text.
466
581
  const pendingText = this.consumePendingContent(uri);
467
582
  const text = pendingText ?? td.text;
468
583
  const source = pendingText ? ', source=pending' : '';
469
- // The SHARED version is server-assigned: continue the persisted
470
- // sequence — same version when the content is unchanged since the
471
- // last close (so watchers' `baseVersion` pointers stay valid), one
472
- // step when it changed (so no stale pointer can coincidentally pass
473
- // the optimistic gate). Only a first-ever open adopts the client's
474
- // declared id as the sequence seed.
475
- const sequence = this.__versionSequences.get(uri);
476
- const version = sequence === undefined ? td.version : sequence.contentHash === contentHash(text) ? sequence.version : sequence.version + 1;
477
- this.log(uri, `Open document: Version ${version} by ${clientId} [first client${source}]`);
478
- document = this.configuration.create(uri, td.languageId, version, text);
479
- this.__syncedDocuments.set(uri, document);
480
- this.setAuthor(uri, version, clientId);
481
- if (clientId === LANGUAGE_CLIENT_ID) {
482
- // Baseline the shadow to what Monaco just opened so the next outbound
483
- // applyEditToLanguageClient diffs against the right starting point. Keyed by the
484
- // language-client URI (what Monaco holds), not the canonical document key.
485
- this.__shadow.set(this.toLanguageClientUri(td.uri), document.getText());
486
- }
584
+ const version = this.textLedger.openingVersion(uri, text) ?? this.builtRootOpeningVersion(uri, text) ?? td.version;
585
+ this.log(uri, `Open document: Version ${version} by ${this.formatClientId(clientId)} [first client${source}]`);
586
+ document = this.create(uri, td.languageId, version, text);
587
+ this.commitText(uri, document, clientId);
588
+ this.__openedVersions.set(uri, version);
589
+ // The opener's text, not the staged content: a session's open read
590
+ // it from the file, and an editor opened its buffer from there. An
591
+ // editor that opens a buffer it never saved is taken as clean.
592
+ this.dirtyStateTracker.track(uri, document, td.text);
487
593
  const toFire = Object.freeze({ document, clientId });
488
594
  this.__onDidOpen.fire(toFire);
489
595
  this.__onDidChangeContent.fire(toFire);
490
596
  }
491
597
  else {
492
598
  // An additional client attaches to a document already open by another client.
493
- this.log(uri, `Attach client: ${clientId} joined existing document (version ${document.version}, ` +
494
- `now open in: ${[...existingClients, clientId].join(', ')})`);
599
+ this.logClientJoined(uri, clientId, document.version, existingClients);
495
600
  this.refreshContent(uri, clientId);
496
601
  }
497
602
  }
603
+ /**
604
+ * Record `clientId` as an additional holder of a document another client
605
+ * already has open.
606
+ *
607
+ * Unlike the attach branch of {@link notifyDidOpenTextDocument} this does
608
+ * not refresh. That branch re-renders an attaching TEXTUAL view; a client
609
+ * reaching a document through a non-textual route has nothing to re-render,
610
+ * and refreshing per attach turns each into a Langium rebuild and dependent
611
+ * relink cascade.
612
+ *
613
+ * Returns whether a hold was added — `false` when `uri` is not open,
614
+ * `clientId` already holds it, or the document was waiting out the release
615
+ * grace for other clients and was released instead (see
616
+ * {@link resolveDeferredRelease}); the caller then opens it anew.
617
+ */
618
+ attachClient(uri, clientId) {
619
+ const key = this.documentKey(uri);
620
+ if (!this.__syncedDocuments.has(key) || this.isOpenInClient(key, clientId)) {
621
+ return false;
622
+ }
623
+ // Before the deferred release is resolved, as for an open.
624
+ this.__sessions.assertCanOpen(clientId);
625
+ this.resolveDeferredRelease(key, clientId);
626
+ const document = this.__syncedDocuments.get(key);
627
+ if (!document) {
628
+ return false;
629
+ }
630
+ const existingClients = this.__sessions.clientsOf(key);
631
+ this.__sessions.addOpen(key, clientId);
632
+ // A client arriving this way holds no buffer of its own, so its guard
633
+ // starts at the synced version.
634
+ this.__sessions.setClientVersion(key, clientId, document.version);
635
+ this.logClientJoined(key, clientId, document.version, existingClients);
636
+ return true;
637
+ }
638
+ logClientJoined(uri, clientId, version, existingClients) {
639
+ this.log(uri, `Attach client: ${this.formatClientId(clientId)} joined existing document (version ${version}, ` +
640
+ `now open in: ${[...existingClients, clientId].map(id => this.formatClientId(id)).join(', ')})`);
641
+ }
498
642
  refreshContent(uri, clientId) {
499
643
  const syncedDocument = this.__syncedDocuments.get(this.documentKey(uri));
500
644
  if (syncedDocument) {
501
645
  // Trigger a (re-)build by firing a change event.
502
- const timer = this.startTimerForUri(syncedDocument.uri, `Refresh synced document: Version ${syncedDocument.version} by ${clientId}`);
646
+ const timer = this.startTimerForUri(syncedDocument.uri, `Refresh synced document: Version ${syncedDocument.version} by ${this.formatClientId(clientId)}`);
503
647
  this.__onDidChangeContent.fire(Object.freeze({ document: syncedDocument, clientId }));
504
648
  timer.dispose();
505
649
  }
@@ -511,7 +655,7 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
511
655
  * two URIs for one physical file (a symlink path and its real path) into a
512
656
  * single registration — dedup at the editor layer, not just in
513
657
  * `LangiumDocuments`. The URI the client opened under is preserved separately
514
- * for egress addressing (see {@link DocumentTracking.languageClientUris}). The
658
+ * for egress addressing, by the {@link LanguageClientShadow}. The
515
659
  * policy is always bound (the framework defaults it to
516
660
  * `DefaultDocumentUriPolicy`, where canonical ≡ syntactic normalize).
517
661
  */
@@ -529,17 +673,8 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
529
673
  toLanguageClientUri(uri) {
530
674
  return asLanguageClientUri(UriUtils.normalize(uri));
531
675
  }
532
- /** Get-or-create the per-URI tracking record. `uri` must already be a {@link documentKey}. */
533
- trackingFor(uri) {
534
- let record = this.__documents.get(uri);
535
- if (!record) {
536
- record = { clients: new Set(), versionAuthors: [], clientVersions: new Map() };
537
- this.__documents.set(uri, record);
538
- }
539
- return record;
540
- }
541
676
  setAuthor(uri, version, author) {
542
- this.trackingFor(this.documentKey(uri)).versionAuthors[version] = author;
677
+ this.textLedger.setAuthor(this.documentKey(uri), version, author);
543
678
  }
544
679
  /**
545
680
  * Resolve the synced `TextDocument` for `uri`. The store keys documents by
@@ -562,55 +697,142 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
562
697
  }
563
698
  /**
564
699
  * Current SHARED version of the document at `uri`: the open document's
565
- * version, else where the persisted sequence left off at last close, else
566
- * `0` for a URI this store has never seen. The shared sequence is
700
+ * version, else where its persisted sequence left off, else `0` for a URI
701
+ * this store has never seen. The shared sequence is
567
702
  * server-owned and monotonic across close/reopen cycles, and advances
568
703
  * exactly when the synced content changes — which is what makes it a sound
569
- * optimistic-concurrency token (`baseVersion` gates): version unchanged ⇔
704
+ * optimistic-concurrency token (base-version gates): version unchanged ⇔
570
705
  * content unchanged.
571
706
  */
572
707
  version(uri) {
573
- return this.get(uri)?.version ?? this.__versionSequences.get(this.documentKey(uri))?.version ?? 0;
708
+ return this.get(uri)?.version ?? this.textLedger.recordOf(this.documentKey(uri))?.version ?? 0;
709
+ }
710
+ /**
711
+ * The version the document at `uri` was opened at, which a client's write
712
+ * or an integrity repair steps past; `undefined` while it is not open.
713
+ */
714
+ openedVersion(uri) {
715
+ return this.__openedVersions.get(this.documentKey(uri));
716
+ }
717
+ /**
718
+ * The text the store holds for `uri`: an open document's, or for a closed
719
+ * one, the clean text its version sequence left off at, which for a deleted
720
+ * document is its last text. `undefined` for a URI no build and no client
721
+ * gave the store.
722
+ */
723
+ textState(uri) {
724
+ const document = this.get(uri);
725
+ if (document) {
726
+ return { version: document.version, hash: this.textLedger.hashOf(document), dirty: this.isDirty(uri) };
727
+ }
728
+ const recorded = this.textLedger.recordOf(this.documentKey(uri));
729
+ return recorded && { version: recorded.version, hash: recorded.hash, dirty: false };
730
+ }
731
+ /**
732
+ * The built root's recorded version for a first open of `key` with `text`,
733
+ * one on when the text differs from the root's; `undefined` when the root
734
+ * records no store version. Seeded from the opener's declared version
735
+ * instead, a write based on the built root passes the gate over other text,
736
+ * and the same text looks newer than its model. A built root records none
737
+ * only under a `LangiumDocuments` that does not reconcile at registration.
738
+ */
739
+ builtRootOpeningVersion(key, text) {
740
+ const built = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(key));
741
+ if (built === undefined) {
742
+ return undefined;
743
+ }
744
+ const ledger = this.services.workspace.ModelLedger;
745
+ const root = built.parseResult.value;
746
+ const recorded = ledger.versionOf(root);
747
+ if (recorded === UNRECORDED_VERSION || recorded === STALE_VERSION) {
748
+ return undefined;
749
+ }
750
+ return (ledger.textOf(root) ?? built.textDocument.getText()) === text ? recorded : recorded + 1;
574
751
  }
575
752
  /**
576
753
  * Reconcile the persisted version sequence with content that reached the
577
754
  * build OUTSIDE the store's write paths — a closed document rebuilt from
578
- * disk (last-close revert) or replaced by a watched-file change. Steps the
755
+ * disk after its release, or replaced by a watched-file change. Steps the
579
756
  * sequence iff `text` differs from the sequence's last-known content and
580
757
  * returns the resulting sequence version so the caller can re-stamp the
581
- * rebuilt document (see the `AstDocumentManager` Parsed-phase listener) —
758
+ * rebuilt document (`VersionSyncService.modelProduced`) —
582
759
  * keeping the "version advances iff content changes" invariant for
583
760
  * documents no client currently holds.
584
761
  *
585
- * Returns `undefined` — and does nothing — when the document is open (the
586
- * store's own content is authoritative; external transitions never reach
587
- * the Langium factory for open documents) or was never tracked (no gate
588
- * holder can hold a version pointer for it, and the early exit keeps
589
- * workspace-wide builds from hashing every untouched document).
762
+ * For an open document, its version when it holds `text`, since a build
763
+ * that read the file while the document was closed can finish after an
764
+ * open; else `undefined`, and the caller has to build the document again.
765
+ *
766
+ * A document without a sequence starts one at `0` with `text`: snapshots
767
+ * hand out versions for documents no client opened, so an uncounted change
768
+ * would let a write based on the old text pass the gate.
590
769
  */
591
770
  reconcileExternalContent(uri, text) {
592
771
  const key = this.documentKey(uri);
593
- if (this.__syncedDocuments.has(key)) {
594
- return undefined;
772
+ const open = this.__syncedDocuments.get(key);
773
+ if (open !== undefined) {
774
+ return open.getText() === text ? open.version : undefined;
595
775
  }
596
- const sequence = this.__versionSequences.get(key);
597
- if (sequence === undefined) {
598
- return undefined;
776
+ const before = this.textLedger.recordOf(key)?.version;
777
+ const version = this.textLedger.reconcile(key, text);
778
+ if (before !== undefined && version !== before) {
779
+ this.logUri(key, `External content change while closed: sequence stepped to version ${version}`, 'debug');
780
+ }
781
+ return version;
782
+ }
783
+ /**
784
+ * Commit an integrity repair into the OPEN document for `uri`, returning the
785
+ * document that now holds it, or `undefined` when there was nothing here to
786
+ * commit into.
787
+ *
788
+ * The one thing this exists to do is address the store BY URI. A repair
789
+ * reaches the resync as a text-document object, and that object is the
790
+ * store's own only on the LSP path; a document built for an already-open URI
791
+ * through `LangiumDocumentFactory.fromString` carries its own, so writing the
792
+ * repair into it corrects a copy the store does not know about and the editor
793
+ * never sees.
794
+ *
795
+ * `parsedFrom` is the text the repaired AST was parsed from, and a mismatch
796
+ * against the current content REFUSES the commit: the store has moved on,
797
+ * which means an editor change landed after that parse, and committing would
798
+ * overwrite a newer edit with a repair computed against text the user has
799
+ * already replaced. The build that change provokes recomputes the repair.
800
+ *
801
+ * Deliberately NOT compared by version. A separately created document seeds
802
+ * its own numbering, so requiring the two to agree would refuse every commit
803
+ * on the path this exists for. Content is the thing both sides can be held to.
804
+ *
805
+ * A changed text is a new version authored by {@link INTEGRITY_CLIENT_ID}.
806
+ * Kept at the old version, the repair is invisible to every reader keyed on
807
+ * versions: a write based on the unrepaired version passes the base-version gate
808
+ * and replaces the repair, and an echo filter credits the repair to the
809
+ * client whose edit it corrected. No change event is fired: the repair
810
+ * rides the build already under way, and an event would re-enter it.
811
+ */
812
+ commitRepair(uri, parsedFrom, repaired) {
813
+ const key = this.documentKey(uri);
814
+ const document = this.__syncedDocuments.get(key);
815
+ if (document === undefined) {
816
+ return { status: 'not-open' };
817
+ }
818
+ if (document.getText() !== parsedFrom) {
819
+ this.logUri(key, 'Refuse repair commit: the open document moved on from the text the AST was parsed from', 'debug');
820
+ return { status: 'stale' };
599
821
  }
600
- const hash = contentHash(text);
601
- if (hash === sequence.contentHash) {
602
- return sequence.version;
822
+ if (repaired === parsedFrom) {
823
+ return { status: 'committed', document };
603
824
  }
604
- const stepped = { version: sequence.version + 1, contentHash: hash };
605
- this.__versionSequences.set(key, stepped);
606
- this.logUri(key, `External content change while closed: sequence stepped to version ${stepped.version}`, 'debug');
607
- return stepped.version;
825
+ // Reassigned rather than mutated in place: the default configuration
826
+ // updates and returns the SAME instance, but an adopter-supplied one may
827
+ // return a new object, and the store must end up holding whichever it is.
828
+ const updated = this.commitChange(key, document, [{ text: repaired }], INTEGRITY_CLIENT_ID).document;
829
+ this.log(updated.uri, `Update to version ${updated.version} by ${this.formatClientId(INTEGRITY_CLIENT_ID)} (repair)`);
830
+ return { status: 'committed', document: updated };
608
831
  }
609
832
  getAuthor(uri, version) {
610
- const history = this.__documents.get(this.documentKey(uri))?.versionAuthors;
611
- // Either the requested version, or the latest. `version !== undefined` so we treat 0 correctly.
612
- const clientId = version !== undefined ? history?.[version] : history?.at(-1);
613
- if (!clientId && history) {
833
+ const key = this.documentKey(uri);
834
+ const clientId = this.textLedger.authorOf(key, version);
835
+ if (!clientId && this.textLedger.authorOf(key) !== undefined) {
614
836
  // Only warn when there IS a history but the specific version is missing; no history at all
615
837
  // means the document was rebuilt internally (e.g. by a project manager), not an error.
616
838
  this.log(uri, `Could not detect author of version ${version}.`);
@@ -624,16 +846,18 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
624
846
  * True iff any client still holds `uri` open. Distinct from {@link isOpen},
625
847
  * which reads `__syncedDocuments` — that map is cleared only AFTER the
626
848
  * `onDidClose` event fires for the last client, so `isOpen` returns `true`
627
- * during the close event itself. `isOpenInAnyClient` reads the tracking
628
- * record's `clients` set, which is updated BEFORE the fire, so an `onDidClose`
629
- * subscriber that finds this `false` knows the last client just closed and a
630
- * disk re-read / rebuild can proceed.
849
+ * during the close event itself. `isOpenInAnyClient` reads the open table
850
+ * ({@link __sessions}), which is updated BEFORE the fire, so an `onDidClose`
851
+ * subscriber that finds this `false` knows the last client just closed.
852
+ * What the build keeps is the release's: a subscriber that re-read or
853
+ * rebuilt the document would race the `DocumentReleaseHandler`, and after a
854
+ * lost connection the release waits out its grace.
631
855
  */
632
856
  isOpenInAnyClient(uri) {
633
- return (this.__documents.get(this.documentKey(uri))?.clients.size ?? 0) > 0;
857
+ return this.__sessions.isOpen(this.documentKey(uri));
634
858
  }
635
859
  isOpenInClient(uri, client) {
636
- return !!this.__documents.get(this.documentKey(uri))?.clients.has(client);
860
+ return this.__sessions.isOpenIn(this.documentKey(uri), client);
637
861
  }
638
862
  isOpenInLanguageClient(uri) {
639
863
  // Takes any URI form (canonicalizes internally via `documentKey`, like
@@ -641,14 +865,18 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
641
865
  // client-facing URI both resolve to the same registration.
642
866
  return this.isOpenInClient(uri, LANGUAGE_CLIENT_ID);
643
867
  }
868
+ /** The clients that have `uri` open, in the order they opened it. */
869
+ clientsOf(uri) {
870
+ return this.__sessions.clientsOf(this.documentKey(uri));
871
+ }
644
872
  isOnlyOpenInClient(uri, client) {
645
- const key = this.documentKey(uri);
646
- return this.__documents.get(key)?.clients.size === 1 && this.isOpenInClient(key, client);
873
+ const clients = this.__sessions.clientsOf(this.documentKey(uri));
874
+ return clients.length === 1 && clients[0] === client;
647
875
  }
648
876
  /**
649
877
  * Every document currently held open by at least one client, with the client
650
- * ids holding it. Reads the same per-URI tracking records as
651
- * {@link isOpenInAnyClient}, so it reflects a last-client close immediately.
878
+ * ids holding it. Reads the same open table as {@link isOpenInAnyClient}, so
879
+ * it reflects a last-client close immediately.
652
880
  *
653
881
  * Diagnostics-oriented — the server-state snapshot lists these so an operator
654
882
  * can see WHY a document is pinned: a document that lingers here after its
@@ -656,30 +884,219 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
656
884
  * under a shedding policy, explains why its CST is never shed).
657
885
  */
658
886
  openDocuments() {
659
- const result = [];
660
- for (const [uri, tracking] of this.__documents) {
661
- if (tracking.clients.size > 0) {
662
- result.push({ uri, clients: [...tracking.clients] });
887
+ return this.__sessions.openDocuments();
888
+ }
889
+ /** Fires once a client session has ended, after every document it had open was closed. */
890
+ get onDidCloseSession() {
891
+ return this.__sessions.onDidCloseSession;
892
+ }
893
+ /**
894
+ * Fires once a document no client has open is released: at its last close,
895
+ * or, for a lost client's last close, when its release grace runs out,
896
+ * another client opens it, or it is deleted, before the
897
+ * `DocumentReleaseHandler` slot is handed the document.
898
+ */
899
+ get onDidReleaseDocument() {
900
+ return this.documentReleasedEmitter.event;
901
+ }
902
+ /**
903
+ * Fires for every save the language client reports of a document it has
904
+ * open: the editor has written the file. {@link onDidSave} follows only
905
+ * when the file holds the store's text.
906
+ */
907
+ get onDidSaveInLanguageClient() {
908
+ return this.languageClientSavedEmitter.event;
909
+ }
910
+ /**
911
+ * Whether `uri` is waiting out the release grace: its last open closed with a
912
+ * lost connection, and it still holds its unsaved text. Such a document is
913
+ * open for no client, yet not closed either, so a caller that would persist
914
+ * a closed document's text to disk treats it as open.
915
+ */
916
+ isReleaseDeferred(uri) {
917
+ return this.documentReleaseScheduler.isDeferred(this.documentKey(uri));
918
+ }
919
+ /**
920
+ * Whether the store holds `uri` with text that differs from its disk
921
+ * baseline: what the server last knew the file to hold. `false` for a URI
922
+ * the store does not hold; a document waiting out the release grace is still
923
+ * held.
924
+ *
925
+ * The baseline is the text a first open brought, or what the server wrote,
926
+ * or read back after an editor's save or a watched-file change, so it can
927
+ * trail a change to the file that none of these has seen yet. A check that
928
+ * must know the file reads it instead.
929
+ */
930
+ isDirty(uri) {
931
+ return this.dirtyStateTracker.isDirty(this.documentKey(uri));
932
+ }
933
+ /**
934
+ * Fires each time the answer of {@link isDirty} changes. For a document
935
+ * released dirty it fires once the `DocumentReleaseHandler` slot reports the
936
+ * release settled: at the version of the text the build then holds, or
937
+ * without text when the document is gone or the handler failed, though
938
+ * {@link isDirty} answers clean from the release on.
939
+ */
940
+ get onDidChangeDirty() {
941
+ return this.dirtyStateTracker.onDidChangeDirty;
942
+ }
943
+ /**
944
+ * Record that the file behind `uri` holds `text`, or no file at all for
945
+ * `undefined`. A no-op for a URI the store does not hold: the next first
946
+ * open sets the baseline from its own text.
947
+ */
948
+ setDiskBaseline(uri, text) {
949
+ const key = this.documentKey(uri);
950
+ const document = this.__syncedDocuments.get(key);
951
+ if (document !== undefined) {
952
+ this.dirtyStateTracker.setDiskBaseline(key, document, text);
953
+ }
954
+ }
955
+ /**
956
+ * Read the file behind `uri` through its disk queue and take it as the
957
+ * baseline. A file that cannot be read counts as none, the side that
958
+ * leaves the document dirty.
959
+ */
960
+ async reloadDiskBaseline(uri) {
961
+ const key = this.documentKey(uri);
962
+ if (!this.__syncedDocuments.has(key)) {
963
+ return;
964
+ }
965
+ let onDisk;
966
+ try {
967
+ onDisk = await this.services.workspace.FileSystemTaskQueue.enqueue(key, () => this.services.workspace.FileSystemProvider.readFile(UriUtils.toUri(key)));
968
+ }
969
+ catch (err) {
970
+ this.tracer.with(key).debug(`Disk baseline: the file cannot be read. ${err instanceof Error ? err.message : String(err)}`);
971
+ }
972
+ this.setDiskBaseline(key, onDisk);
973
+ }
974
+ /**
975
+ * Start a client session under `clientId`. Throws where
976
+ * {@link ClientSessionRegistry.register} refuses the id.
977
+ */
978
+ registerSession(clientId) {
979
+ this.__sessions.register(clientId);
980
+ this.tracer.info(`Session started: ${this.formatClientId(clientId)}`);
981
+ this.tracer.trace(`Session started: ${clientId}`);
982
+ }
983
+ /**
984
+ * End the client session `clientId`: close every document it has open, then
985
+ * free the id. Immediate — each close runs the ordinary close path before
986
+ * this returns, with `cause` as its cause. A no-op for an id that is not a
987
+ * registered session.
988
+ */
989
+ closeSession(clientId, cause = 'closed') {
990
+ if (!this.__sessions.isRegistered(clientId)) {
991
+ return;
992
+ }
993
+ try {
994
+ for (const uri of this.__sessions.beginClose(clientId)) {
995
+ this.notifyDidCloseTextDocument({ textDocument: { uri } }, clientId, cause);
663
996
  }
664
997
  }
665
- return result;
998
+ finally {
999
+ this.__sessions.unregister(clientId, cause);
1000
+ this.tracer.info(`Session closed: ${this.formatClientId(clientId)}`);
1001
+ this.tracer.trace(`Session closed: ${clientId}`);
1002
+ }
1003
+ }
1004
+ /**
1005
+ * Close every document the language client has open, as a `didClose` for
1006
+ * each would, so each last close releases its document. For a host whose editor connection
1007
+ * can end while the process lives on, such as a worker whose port's peer
1008
+ * closed: the language client is no session, so nothing else closes them.
1009
+ *
1010
+ * It first waits for the workspace initialization the open handler waits
1011
+ * for, so an open that arrived before the close is closed too; closing at
1012
+ * once would leave that open to land afterwards, held by a client that is
1013
+ * gone.
1014
+ */
1015
+ async closeLanguageClientDocuments() {
1016
+ await this.initialBuildFinished();
1017
+ for (const uri of this.__sessions.opensOf(LANGUAGE_CLIENT_ID)) {
1018
+ // A close for one URI while others remain keeps the client's hold.
1019
+ this.languageClientShadow.removeAllOpens(uri);
1020
+ this.notifyDidCloseTextDocument({ textDocument: { uri } });
1021
+ }
1022
+ }
1023
+ /**
1024
+ * Settles once the initial workspace build has finished, whether it
1025
+ * completed, was cancelled or failed. Awaiting `workspaceInitialized` itself
1026
+ * throws after a cancelled build, which any write during startup causes, and
1027
+ * every open and close gated on it is then dropped for the process lifetime.
1028
+ * The workspace manager logs a failed build.
1029
+ */
1030
+ async initialBuildFinished() {
1031
+ await this.services.workspace.WorkspaceManager.workspaceInitialized.catch(() => undefined);
666
1032
  }
667
1033
  /**
668
- * Stages integrity-updated content for a closed document.
1034
+ * The file behind `uri` was deleted: close every open of it except the
1035
+ * language client's.
669
1036
  *
670
- * When `workspace/applyEdit` targets a closed file, the client opens it from
671
- * disk (stale) and sends `didOpen` before applying the edit. This staged
672
- * content is consumed by {@link notifyDidOpenTextDocument} to replace the
673
- * stale disk text, preventing a brief revert of the integrity update.
1037
+ * The editor's open is left alone because the editor owns it: it keeps the
1038
+ * buffer of a deleted file and goes on sending changes for it, and a store
1039
+ * that had closed the document would drop every one of them until the editor
1040
+ * reopened.
1041
+ */
1042
+ notifyDocumentDeleted(uri) {
1043
+ const key = this.documentKey(uri);
1044
+ for (const clientId of this.__sessions.clientsOf(key)) {
1045
+ if (clientId !== LANGUAGE_CLIENT_ID) {
1046
+ this.notifyDidCloseTextDocument({ textDocument: { uri: key } }, clientId);
1047
+ }
1048
+ }
1049
+ }
1050
+ /**
1051
+ * Remove the document for `uri`, closing every open of it first — the
1052
+ * editor's included, since the document it would keep editing is gone.
674
1053
  *
675
- * Not cleared on close: pending content is only staged for already-closed
676
- * documents (the integrity service checks `isOpenInLanguageClient` first), so
677
- * a close → stage → open cycle cannot occur. The only scenario where an
678
- * entry lingers is if `workspace/applyEdit` fails and the file is never
679
- * opened — the memory cost is one serialised string per URI.
1054
+ * The base removes the synced document without consulting the open table,
1055
+ * which leaves every open recorded against a document that no longer exists:
1056
+ * the store then answers that the URI is open, and the next open attaches to
1057
+ * nothing.
1058
+ */
1059
+ delete(uri) {
1060
+ const key = this.documentKey((typeof uri === 'object' && 'uri' in uri ? uri.uri : uri).toString());
1061
+ this.languageClientShadow.removeAllOpens(key);
1062
+ for (const clientId of this.__sessions.clientsOf(key)) {
1063
+ this.notifyDidCloseTextDocument({ textDocument: { uri: key } }, clientId);
1064
+ }
1065
+ // A document waiting out the grace has no client left to close, and is
1066
+ // released now as its last close would have released it.
1067
+ if (this.documentReleaseScheduler.isDeferred(key)) {
1068
+ this.documentReleaseScheduler.cancel(key);
1069
+ this.releaseDocument(key);
1070
+ }
1071
+ super.delete(key);
1072
+ }
1073
+ /**
1074
+ * A client id as log lines print it. An id containing `#` is cut eight
1075
+ * characters after its last `#`, which leaves a minted `label#uuid` as the
1076
+ * label and enough of the UUID to tell sessions apart; an id without `#`
1077
+ * prints whole. The full id goes out at trace level wherever a session
1078
+ * starts or ends.
1079
+ */
1080
+ formatClientId(clientId) {
1081
+ const separator = clientId.lastIndexOf('#');
1082
+ return separator < 0 ? clientId : clientId.slice(0, separator + 9);
1083
+ }
1084
+ /**
1085
+ * Stages integrity-updated content for a document no client holds.
1086
+ *
1087
+ * Nothing is pushed to a file no client holds. The next open of it reads
1088
+ * disk, which lacks the update; {@link notifyDidOpenTextDocument} takes this
1089
+ * staged content in place of that text, and the open's sync then delivers
1090
+ * it to an editor as an unsaved change.
1091
+ *
1092
+ * Only a FIRST open consumes it, so stage only for a URI no client holds
1093
+ * ({@link isOpenInAnyClient} is `false`). A URI held only through another
1094
+ * head is not closed: an editor attaching to it joins the existing entry and
1095
+ * never reads the stage, and the release discards it. An entry waits for
1096
+ * that first open, at one serialised string per URI.
680
1097
  */
681
1098
  stagePendingContent(uri, text) {
682
- this.trackingFor(this.documentKey(uri)).pendingContent = text;
1099
+ this.__pendingContent.set(this.documentKey(uri), text);
683
1100
  }
684
1101
  /**
685
1102
  * Send `newText` to the LSP textual language client (Monaco / VS Code) via
@@ -690,192 +1107,108 @@ export class HydraniumTextDocuments extends NormalizedTextDocuments {
690
1107
  * - The shared services have no LSP {@link Connection} bound (non-LSP
691
1108
  * hosts like CLI / tests).
692
1109
  * - The shadow already matches `newText` (no edits needed; quiet skip).
1110
+ * - The language client has not opened the document. A client applies an
1111
+ * edit to a closed file by opening it, and that open races the edit;
1112
+ * the document's own open delivers its text instead.
693
1113
  *
694
1114
  * On `applyEdit` rejection (`result.applied === false`) or RPC failure the
695
- * shadow is invalidated so the next call sends a full-replace baseline.
1115
+ * shadow is invalidated so the next call sends a full replace, or nothing
1116
+ * when the client was last heard to hold that text.
696
1117
  * Errors are re-thrown — callers wrap with their own retry / coalescing
697
1118
  * policy as needed.
698
1119
  *
699
1120
  * The diff path is apply-verify-safe: the shadow internally checks that
700
1121
  * `TextDocument.applyEdits(old, edits) === newText` and falls back to a
701
- * full replace on mismatch (logged via the warn-callback wired in the
702
- * constructor), so a diff regression becomes log noise, not data loss.
1122
+ * full replace on mismatch, logged, so a diff regression becomes log noise,
1123
+ * not data loss.
703
1124
  *
704
1125
  * That safety net verifies the diff against the SHADOW, which is what the
705
1126
  * client is *believed* to hold — so it cannot see the client's buffer moving
706
1127
  * underneath a push. A line-keyed edit is position-dependent: if a genuine
707
- * client keystroke lands between {@link LanguageClientTextShadow.computeEdits}
708
- * and the client applying, the ranges address the wrong lines and splice the
709
- * buffer (observed as a duplicated declaration, which the integrity tier then
1128
+ * client keystroke lands between computing the edits and the client
1129
+ * applying them, the ranges address the wrong lines and splice the buffer
1130
+ * (observed as a duplicated declaration, which the integrity tier then
710
1131
  * "repairs" into a suffixed name and persists). The edit is therefore
711
- * addressed at the language client's LAST DECLARED VERSION rather than at
712
- * `null` ("version intentionally unknown"), which is what lets the client
713
- * reject a push its buffer has outrun. On rejection the shadow is invalidated,
1132
+ * addressed at the language client's last known version for that URI rather
1133
+ * than at `null` ("version intentionally unknown"), which is what lets the
1134
+ * client reject a push its buffer has outrun. On rejection the shadow is invalidated,
714
1135
  * so the caller's retry is a full-range replace — position-independent, and
715
- * safe to apply to whatever the client now holds.
1136
+ * safe to apply to whatever the client now holds — or nothing when the
1137
+ * client was last heard to hold that text.
716
1138
  */
717
1139
  async applyEditToLanguageClient(uri, newText, options) {
718
1140
  const connection = this.services.lsp?.Connection;
719
1141
  if (!connection) {
720
1142
  return undefined;
721
1143
  }
722
- // The document is keyed by its canonical identity, but Monaco holds it under
723
- // the URI(s) it opened. Address each of those language-client URIs — the one
724
- // R→S translation, kept here at the egress. Usually one; more than one only
725
- // when the same file was opened under a symlink and its real path. Falls back
726
- // to the normalized URI when nothing is tracked. The shadow is keyed by each
727
- // URI, so every diff is against the right baseline.
728
- const recorded = this.__documents.get(this.documentKey(uri))?.languageClientUris;
729
- const targets = recorded && recorded.size > 0 ? recorded : [this.toLanguageClientUri(uri)];
1144
+ // The document is keyed by its canonical identity, but the client holds it
1145
+ // under each URI it opened, and each is diffed against its own baseline.
1146
+ const key = this.documentKey(uri);
730
1147
  let lastResult;
731
- for (const targetUri of targets) {
732
- // Read BEFORE computeEdits, which overwrites it. This is the text the
733
- // edits below are keyed to, and therefore the only text the client's
734
- // echo of them can be reconstructed against.
735
- const before = this.__shadow.get(targetUri);
736
- const edits = this.__shadow.computeEdits(targetUri, newText);
737
- if (edits.length === 0) {
1148
+ for (const clientUri of this.languageClientShadow.pushTargets(key)) {
1149
+ // Prepared per target, after the previous target's reply: prepared up
1150
+ // front, a later target is diffed against what it held before a change
1151
+ // that arrived meanwhile.
1152
+ const push = this.languageClientShadow.preparePush(key, clientUri, newText);
1153
+ if (push === undefined) {
738
1154
  continue;
739
1155
  }
740
- // Record the push for echo correlation BEFORE the RPC — the client's
741
- // echo can race the applyEdit response. See `__pendingPushes`.
742
- this.recordPendingPush(targetUri, before, newText);
743
1156
  try {
744
- // Version the push only when it is position-DEPENDENT. A full-range
745
- // replace lands correctly on any buffer, so gating it would turn a
746
- // stale-by-one version into a refused update for no safety gain — and
747
- // it is exactly what the caller retries with after a rejection, so
748
- // gating it there would refuse the recovery too.
749
- const version = isFullReplace(edits) ? UNKNOWN_CLIENT_VERSION : this.languageClientVersion(uri);
1157
+ // A full `ApplyWorkspaceEditParams`, `edit` and all — NOT a bare
1158
+ // `WorkspaceEdit` with a `label` beside it. `applyEdit` takes
1159
+ // `ApplyWorkspaceEditParams | WorkspaceEdit` and discriminates on
1160
+ // `!!value.edit`, so `{ label, documentChanges }` is wrapped as
1161
+ // `{ edit: { label, documentChanges } }` — putting the label inside
1162
+ // the edit, where LSP defines no such field and no client reads it.
1163
+ // The union is also what hides it at compile time: excess-property
1164
+ // checking admits a property present in EITHER member, so an object
1165
+ // matching neither type-checks against the union.
1166
+ const version = push.version ?? UNKNOWN_CLIENT_VERSION;
750
1167
  const result = await connection.workspace.applyEdit({
751
1168
  label: options?.label,
752
- documentChanges: [TextDocumentEdit.create(OptionalVersionedTextDocumentIdentifier.create(targetUri, version), edits)]
1169
+ edit: {
1170
+ documentChanges: [TextDocumentEdit.create(OptionalVersionedTextDocumentIdentifier.create(clientUri, version), push.edits)]
1171
+ }
753
1172
  });
754
1173
  if (result && result.applied === false) {
755
- this.__shadow.invalidate(targetUri);
756
- this.__pendingPushes.delete(targetUri);
1174
+ push.notifyOutcome('refused');
1175
+ }
1176
+ else if (result?.applied) {
1177
+ push.notifyOutcome('applied');
757
1178
  }
758
1179
  lastResult = result;
759
1180
  }
760
1181
  catch (err) {
761
- this.__shadow.invalidate(targetUri);
762
- this.__pendingPushes.delete(targetUri);
1182
+ push.notifyOutcome('failed');
763
1183
  throw err;
764
1184
  }
765
1185
  }
766
1186
  return lastResult;
767
1187
  }
768
1188
  /**
769
- * The version the LSP textual language client last declared for `uri`, for
770
- * addressing an outgoing `workspace/applyEdit`.
771
- *
772
- * Client version ids are CLIENT-owned per LSP, so this is the id the client
773
- * itself stamped on its last `didOpen` / `didChange` — never the shared
774
- * server version, which advances on authored writes the client knows nothing
775
- * about and would therefore reject every push.
776
- *
777
- * Falls back to {@link UNKNOWN_CLIENT_VERSION} when the client has never
778
- * declared one, which is the honest answer for a document it has not opened.
779
- * That is also the case in which there is no shadow, so the push is already a
780
- * position-independent full replace and has nothing to gain from a gate.
781
- */
782
- languageClientVersion(uri) {
783
- return this.__documents.get(this.documentKey(uri))?.clientVersions.get(LANGUAGE_CLIENT_ID) ?? UNKNOWN_CLIENT_VERSION;
784
- }
785
- /**
786
- * Append a push to the in-flight queue for `targetUri`
787
- * (see {@link __pendingPushes}). Bounded: beyond
788
- * {@link PENDING_ECHO_CAP} the oldest entry drops with a debug log — an
789
- * echo that far outstanding means the client is not echoing at all, and
790
- * an unbounded queue must not become the leak.
1189
+ * Explicitly baseline the language-client shadow for a URI the client has
1190
+ * open, for an adopter that knows what the client holds without a
1191
+ * `didChange` saying so (e.g. after a sideband save). Normal didOpen /
1192
+ * didChange paths from the LSP language client already auto-track the
1193
+ * shadow. A seed for a URI the client has not opened is kept but changes no
1194
+ * push, since nothing is pushed there; its open replaces it with the text it
1195
+ * declares.
791
1196
  */
792
- recordPendingPush(targetUri, before, newText) {
793
- let pending = this.__pendingPushes.get(targetUri);
794
- if (!pending) {
795
- pending = [];
796
- this.__pendingPushes.set(targetUri, pending);
797
- }
798
- pending.push({ before, afterHash: contentHash(newText) });
799
- if (pending.length > PENDING_ECHO_CAP) {
800
- pending.shift();
801
- this.logUri(targetUri, `Pending-echo queue exceeded ${PENDING_ECHO_CAP} entries; dropped the oldest`, 'debug');
802
- }
803
- }
804
- /**
805
- * Decide what an incoming language-client change actually is, by
806
- * reconstructing the client's resulting buffer against the OLDEST push still
807
- * in flight for `clientFacing`.
808
- *
809
- * `undefined` when nothing of ours is in flight, which is the ordinary path:
810
- * the client's ranges then address the synced text and the caller applies
811
- * them to it directly.
812
- *
813
- * **Why the oldest, and why reconstruct at all.** The client applies our
814
- * pushes in order and echoes each against the buffer it held before that
815
- * push, so the first echo to arrive belongs to the oldest entry — a FIFO
816
- * correspondence the queue preserves by consuming from the front. Comparing
817
- * the reconstruction against every pending hash, not only the oldest, is
818
- * what recognises an echo that a newer write already superseded: a rapid
819
- * write sequence can deliver the echo of push N after the store applied
820
- * push N+1, and everything older is then accounted for too.
821
- *
822
- * A reconstruction matching NO pending push means the client's buffer went
823
- * somewhere we did not send it — it coalesced a keystroke into the echo, or
824
- * typed before the push landed. That text is authoritative, and the queue
825
- * drops: the client has stopped being a pure mirror, so no outstanding echo
826
- * can match again. (A push still in flight at that point will be refused by
827
- * the client's own version gate, which invalidates the shadow and makes the
828
- * next sync a position-independent full replace.)
829
- *
830
- * Content equality is a sound echo proof because entries live only between a
831
- * push and its echo — a milliseconds window, never history — and the
832
- * client's `didChange` stream is ordered, so every buffer state arrives in
833
- * mutation order. An UNDO returning the buffer to previously-pushed text is
834
- * therefore never swallowed: the edit that preceded it already emptied the
835
- * queue, so undo revisits PAST states while the queue holds IN-FLIGHT ones.
836
- */
837
- classifyLanguageClientChange(clientFacing, document, changes) {
838
- const pending = this.__pendingPushes.get(clientFacing);
839
- if (pending === undefined || pending.length === 0) {
840
- return undefined;
841
- }
842
- // Through the configured factories, not `TextDocument` directly, so an
843
- // adopter's custom text-document type governs how the ranges are applied
844
- // here exactly as it does on the synced document.
845
- const probe = this.create(clientFacing, document.languageId, 0, pending[0].before ?? document.getText());
846
- const clientText = this.update(probe, changes, 0).getText();
847
- const matchIndex = pending.findIndex(push => push.afterHash === contentHash(clientText));
848
- if (matchIndex >= 0) {
849
- pending.splice(0, matchIndex + 1);
850
- return { kind: 'echo' };
851
- }
852
- pending.length = 0;
853
- return { kind: 'divergent', text: clientText };
1197
+ setLanguageClientText(uri, text) {
1198
+ this.languageClientShadow.setClientText(this.toLanguageClientUri(uri), text);
854
1199
  }
855
1200
  /**
856
- * Explicitly baseline the language-client text shadow for a URI. Useful in
857
- * tests and for adopters that need to seed the shadow without going through
858
- * a `didOpen` event (e.g. after a sideband save). Normal didOpen / didChange
859
- * paths from the LSP language client already auto-track the shadow.
1201
+ * Drop the shadow baseline for a URI; the next applyEditToLanguageClient
1202
+ * sends a full replace, or nothing when the client was last heard to hold
1203
+ * that text.
860
1204
  */
861
- setLanguageClientText(uri, text) {
862
- const clientFacing = this.toLanguageClientUri(uri);
863
- this.__shadow.set(clientFacing, text);
864
- // An explicit rebaseline supersedes whatever was in flight.
865
- this.__pendingPushes.delete(clientFacing);
866
- }
867
- /** Drop the shadow baseline for a URI; the next applyEditToLanguageClient sends a full replace. */
868
1205
  invalidateLanguageClientText(uri) {
869
- const clientFacing = this.toLanguageClientUri(uri);
870
- this.__shadow.invalidate(clientFacing);
871
- this.__pendingPushes.delete(clientFacing);
1206
+ this.languageClientShadow.invalidateClientText(this.toLanguageClientUri(uri));
872
1207
  }
873
1208
  consumePendingContent(uri) {
874
- const record = this.__documents.get(this.documentKey(uri));
875
- const content = record?.pendingContent;
876
- if (record) {
877
- record.pendingContent = undefined;
878
- }
1209
+ const key = this.documentKey(uri);
1210
+ const content = this.__pendingContent.get(key);
1211
+ this.__pendingContent.delete(key);
879
1212
  return content;
880
1213
  }
881
1214
  log(uri, message) {