@ecsplico/editor 3.6.0 → 4.1.0

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 (593) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/dist/adapters/direct-ai.d.ts +4 -4
  3. package/dist/adapters/direct-ai.js +2 -2
  4. package/dist/adapters/direct-ai.js.map +1 -1
  5. package/dist/adapters/document-state.d.ts +1 -1
  6. package/dist/adapters/document-state.js.map +1 -1
  7. package/dist/adapters/forge.d.ts +2 -2
  8. package/dist/adapters/forge.js.map +1 -1
  9. package/dist/adapters/nitro.d.ts +11 -3
  10. package/dist/adapters/nitro.js +3 -1
  11. package/dist/adapters/nitro.js.map +1 -1
  12. package/dist/adapters/shared.d.ts +6 -6
  13. package/dist/adapters/shared.js.map +1 -1
  14. package/dist/code/CodeSurface.vue.d.ts +3 -3
  15. package/dist/config/index.d.ts +14 -14
  16. package/dist/config/index.js +8 -8
  17. package/dist/config/index.js.map +1 -1
  18. package/dist/core/backend-types.d.ts +3 -3
  19. package/dist/core/backend-types.js.map +1 -1
  20. package/dist/core/backend.d.ts +4 -4
  21. package/dist/core/backend.js.map +1 -1
  22. package/dist/core/block-convert.d.ts +1 -1
  23. package/dist/core/block-convert.js +5 -5
  24. package/dist/core/block-convert.js.map +1 -1
  25. package/dist/core/block-transfer.d.ts +8 -4
  26. package/dist/core/block-transfer.js +23 -14
  27. package/dist/core/block-transfer.js.map +1 -1
  28. package/dist/core/capabilities.d.ts +113 -0
  29. package/dist/core/capabilities.js +155 -0
  30. package/dist/core/capabilities.js.map +1 -0
  31. package/dist/core/command-types.d.ts +1 -1
  32. package/dist/core/context.js.map +1 -1
  33. package/dist/core/convert.d.ts +5 -5
  34. package/dist/core/convert.js +5 -5
  35. package/dist/core/convert.js.map +1 -1
  36. package/dist/core/core-feature.js +1 -1
  37. package/dist/core/define-editor.d.ts +2 -2
  38. package/dist/core/define-editor.js +34 -6
  39. package/dist/core/define-editor.js.map +1 -1
  40. package/dist/core/derivation.d.ts +119 -0
  41. package/dist/core/derivation.js +187 -0
  42. package/dist/core/derivation.js.map +1 -0
  43. package/dist/core/derive.d.ts +61 -0
  44. package/dist/core/derive.js +69 -0
  45. package/dist/core/derive.js.map +1 -0
  46. package/dist/core/extension-points.d.ts +16 -0
  47. package/dist/core/feature-context.d.ts +5 -1
  48. package/dist/core/feature-context.js +10 -3
  49. package/dist/core/feature-context.js.map +1 -1
  50. package/dist/core/feature.d.ts +41 -19
  51. package/dist/core/feature.js.map +1 -1
  52. package/dist/core/fences.js +1 -1
  53. package/dist/core/fences.js.map +1 -1
  54. package/dist/core/index.d.ts +6 -2
  55. package/dist/core/index.js +5 -1
  56. package/dist/core/pipeline.d.ts +14 -5
  57. package/dist/core/pipeline.js +19 -7
  58. package/dist/core/pipeline.js.map +1 -1
  59. package/dist/core/properties.d.ts +22 -0
  60. package/dist/core/properties.js +17 -0
  61. package/dist/core/properties.js.map +1 -0
  62. package/dist/core/schema/block-ids.js +5 -5
  63. package/dist/core/schema/block-ids.js.map +1 -1
  64. package/dist/core/schema/index.d.ts +2 -1
  65. package/dist/core/schema/index.js +2 -1
  66. package/dist/core/schema/index.js.map +1 -1
  67. package/dist/core/schema/opaque-fence.d.ts +4 -4
  68. package/dist/core/schema/opaque-fence.js +7 -7
  69. package/dist/core/schema/opaque-fence.js.map +1 -1
  70. package/dist/core/schema/persisted-names.d.ts +58 -0
  71. package/dist/core/schema/persisted-names.js +96 -0
  72. package/dist/core/schema/persisted-names.js.map +1 -0
  73. package/dist/core/toolbar-items.js +1 -1
  74. package/dist/core/toolbar-items.js.map +1 -1
  75. package/dist/core/util.js +5 -1
  76. package/dist/core/util.js.map +1 -1
  77. package/dist/document/DocumentSurface.vue.d.ts +3 -3
  78. package/dist/features/ai/agent-ops.js +1 -1
  79. package/dist/features/ai/ai-review.js +1 -1
  80. package/dist/features/ai/assistant.d.ts +4 -4
  81. package/dist/features/ai/assistant.js +1 -1
  82. package/dist/features/ai/assistant.js.map +1 -1
  83. package/dist/features/ai/components/AiSelectionMenu.js +1 -1
  84. package/dist/features/ai/components/AiSelectionMenu.js.map +1 -1
  85. package/dist/features/ai/components/ModelQuickSwitch.js +7 -7
  86. package/dist/features/ai/components/ModelQuickSwitch.js.map +1 -1
  87. package/dist/features/ai/components/ModelQuickSwitch.vue.d.ts +4 -4
  88. package/dist/features/ai/components/SettingsAiTab.js +8 -8
  89. package/dist/features/ai/components/SettingsAiTab.js.map +1 -1
  90. package/dist/features/ai/components/SettingsModelProfiles.js +1 -1
  91. package/dist/features/ai/components/SettingsModelProfiles.js.map +1 -1
  92. package/dist/features/ai/document-chat-model.d.ts +2 -2
  93. package/dist/features/ai/document-chat-model.js +5 -5
  94. package/dist/features/ai/document-chat-model.js.map +1 -1
  95. package/dist/features/ai/document-chat.js +2 -2
  96. package/dist/features/ai/document-chat.js.map +1 -1
  97. package/dist/features/ai/feature.d.ts +2 -2
  98. package/dist/features/ai/feature.js +2 -2
  99. package/dist/features/ai/feature.js.map +1 -1
  100. package/dist/features/ai/ghost-autocomplete.d.ts +4 -4
  101. package/dist/features/ai/ghost-autocomplete.js +1 -1
  102. package/dist/features/ai/ghost-autocomplete.js.map +1 -1
  103. package/dist/features/ai/index.d.ts +3 -3
  104. package/dist/features/ai/index.js +2 -2
  105. package/dist/features/ai/model-profiles.d.ts +9 -9
  106. package/dist/features/ai/model-profiles.js +13 -13
  107. package/dist/features/ai/model-profiles.js.map +1 -1
  108. package/dist/features/ai/protocol/agent-ops.d.ts +2 -2
  109. package/dist/features/ai/protocol/agent-ops.js +1 -1
  110. package/dist/features/ai/protocol/agent-ops.js.map +1 -1
  111. package/dist/features/ai/protocol/block-lines.d.ts +7 -7
  112. package/dist/features/ai/protocol/block-lines.js +10 -10
  113. package/dist/features/ai/protocol/block-lines.js.map +1 -1
  114. package/dist/features/ai/protocol/chat.d.ts +5 -5
  115. package/dist/features/ai/protocol/chat.js +12 -12
  116. package/dist/features/ai/protocol/chat.js.map +1 -1
  117. package/dist/features/ai/protocol/generate.d.ts +1 -1
  118. package/dist/features/ai/protocol/generate.js +1 -1
  119. package/dist/features/ai/protocol/generate.js.map +1 -1
  120. package/dist/features/ai/protocol/index.d.ts +3 -3
  121. package/dist/features/ai/protocol/index.js +2 -2
  122. package/dist/features/ai/protocol/models.d.ts +3 -3
  123. package/dist/features/ai/protocol/models.js +3 -3
  124. package/dist/features/ai/protocol/models.js.map +1 -1
  125. package/dist/features/ai/protocol/schemas.d.ts +1 -1
  126. package/dist/features/ai/protocol/schemas.js +1 -1
  127. package/dist/features/ai/protocol/schemas.js.map +1 -1
  128. package/dist/features/ai/protocol/tasks.d.ts +5 -5
  129. package/dist/features/ai/protocol/tasks.js +12 -12
  130. package/dist/features/ai/protocol/tasks.js.map +1 -1
  131. package/dist/features/ai/react/AiSelectionMenu.js.map +1 -1
  132. package/dist/features/ai/react/ModelQuickSwitch.d.ts +4 -4
  133. package/dist/features/ai/react/ModelQuickSwitch.js +6 -6
  134. package/dist/features/ai/react/ModelQuickSwitch.js.map +1 -1
  135. package/dist/features/ai/react/SettingsAiTab.d.ts +1 -1
  136. package/dist/features/ai/react/SettingsAiTab.js +8 -8
  137. package/dist/features/ai/react/SettingsAiTab.js.map +1 -1
  138. package/dist/features/ai/react/SettingsModelProfiles.d.ts +1 -1
  139. package/dist/features/ai/react/SettingsModelProfiles.js +1 -1
  140. package/dist/features/ai/react/SettingsModelProfiles.js.map +1 -1
  141. package/dist/features/ai/react/use-ai-assistant.d.ts +1 -1
  142. package/dist/features/ai/react/use-ai-assistant.js +1 -1
  143. package/dist/features/ai/react/use-ai-assistant.js.map +1 -1
  144. package/dist/features/ai/react/use-model-profiles.d.ts +5 -5
  145. package/dist/features/ai/react/use-model-profiles.js +2 -2
  146. package/dist/features/ai/react/use-model-profiles.js.map +1 -1
  147. package/dist/features/ai/use-ai-assistant.d.ts +1 -1
  148. package/dist/features/ai/use-ai-assistant.js +1 -1
  149. package/dist/features/ai/use-ai-assistant.js.map +1 -1
  150. package/dist/features/ai/use-model-profiles.d.ts +4 -4
  151. package/dist/features/ai/use-model-profiles.js +2 -2
  152. package/dist/features/ai/use-model-profiles.js.map +1 -1
  153. package/dist/features/block-ui/block-actions.d.ts +8 -4
  154. package/dist/features/block-ui/block-actions.js +38 -22
  155. package/dist/features/block-ui/block-actions.js.map +1 -1
  156. package/dist/features/block-ui/block-target.d.ts +29 -0
  157. package/dist/features/block-ui/block-target.js +63 -0
  158. package/dist/features/block-ui/block-target.js.map +1 -0
  159. package/dist/features/block-ui/components/BlockHandles.js +3 -3
  160. package/dist/features/block-ui/components/BlockHandles.js.map +1 -1
  161. package/dist/features/block-ui/components/BlockUi.js +11 -23
  162. package/dist/features/block-ui/components/BlockUi.js.map +1 -1
  163. package/dist/features/block-ui/feature.d.ts +3 -2
  164. package/dist/features/block-ui/feature.js +3 -2
  165. package/dist/features/block-ui/feature.js.map +1 -1
  166. package/dist/features/block-ui/handle-geometry.js +12 -23
  167. package/dist/features/block-ui/handle-geometry.js.map +1 -1
  168. package/dist/features/block-ui/index.d.ts +2 -1
  169. package/dist/features/block-ui/index.js +2 -1
  170. package/dist/features/block-ui/react/BlockHandles.d.ts +1 -1
  171. package/dist/features/block-ui/react/BlockHandles.js +4 -4
  172. package/dist/features/block-ui/react/BlockHandles.js.map +1 -1
  173. package/dist/features/block-ui/react/BlockUi.js +13 -25
  174. package/dist/features/block-ui/react/BlockUi.js.map +1 -1
  175. package/dist/features/comments/model.js +1 -1
  176. package/dist/features/composites/accepted-children.d.ts +5 -4
  177. package/dist/features/composites/accepted-children.js +26 -26
  178. package/dist/features/composites/accepted-children.js.map +1 -1
  179. package/dist/features/composites/ai-brief.d.ts +4 -4
  180. package/dist/features/composites/ai-brief.js +14 -12
  181. package/dist/features/composites/ai-brief.js.map +1 -1
  182. package/dist/features/composites/anchors.d.ts +1 -1
  183. package/dist/features/composites/anchors.js.map +1 -1
  184. package/dist/features/composites/baskets.d.ts +1 -1
  185. package/dist/features/composites/baskets.js.map +1 -1
  186. package/dist/features/composites/bibliography-command.d.ts +1 -1
  187. package/dist/features/composites/bibliography-form.js +1 -1
  188. package/dist/features/composites/bibliography-form.js.map +1 -1
  189. package/dist/features/composites/bibliography.js.map +1 -1
  190. package/dist/features/composites/block-types-json.d.ts +38 -0
  191. package/dist/features/composites/block-types-json.js +122 -0
  192. package/dist/features/composites/block-types-json.js.map +1 -0
  193. package/dist/features/composites/block-types.d.ts +119 -0
  194. package/dist/features/composites/block-types.js +343 -0
  195. package/dist/features/composites/block-types.js.map +1 -0
  196. package/dist/features/composites/capabilities.js +109 -0
  197. package/dist/features/composites/capabilities.js.map +1 -0
  198. package/dist/features/composites/components/BibliographyEditor.js +5 -5
  199. package/dist/features/composites/components/BibliographyEditor.js.map +1 -1
  200. package/dist/features/composites/components/CompositeBasketMenu.js +2 -2
  201. package/dist/features/composites/components/CompositeBasketMenu.js.map +1 -1
  202. package/dist/features/composites/components/CompositeChrome.js +18 -8
  203. package/dist/features/composites/components/CompositeChrome.js.map +1 -1
  204. package/dist/features/composites/components/CompositeChrome.vue.d.ts +1 -1
  205. package/dist/features/composites/components/CompositeDetails.js +11 -10
  206. package/dist/features/composites/components/CompositeDetails.js.map +1 -1
  207. package/dist/features/composites/components/CompositeDetails.vue.d.ts +1 -1
  208. package/dist/features/composites/components/CompositeFieldEditor.js +7 -7
  209. package/dist/features/composites/components/CompositeFieldEditor.js.map +1 -1
  210. package/dist/features/composites/components/CompositeFieldEditor.vue.d.ts +5 -5
  211. package/dist/features/composites/components/CompositeInspector.js +136 -113
  212. package/dist/features/composites/components/CompositeInspector.js.map +1 -1
  213. package/dist/features/composites/components/CompositeInspector.vue.d.ts +3 -3
  214. package/dist/features/composites/components/CompositeStatusMenu.js +2 -2
  215. package/dist/features/composites/components/CompositeStatusMenu.js.map +1 -1
  216. package/dist/features/composites/components/CompositeSummaryEditor.js +1 -1
  217. package/dist/features/composites/components/CompositeSummaryEditor.js.map +1 -1
  218. package/dist/features/composites/components/CompositeSummaryEditor.vue.d.ts +1 -1
  219. package/dist/features/composites/components/CompositeTable.js +2 -2
  220. package/dist/features/composites/components/CompositeTable.js.map +1 -1
  221. package/dist/features/composites/components/CompositeTagsEditor.js +1 -1
  222. package/dist/features/composites/components/CompositeTagsEditor.js.map +1 -1
  223. package/dist/features/composites/components/CompositeTagsEditor.vue.d.ts +1 -1
  224. package/dist/features/composites/components/CompositeView.js +19 -17
  225. package/dist/features/composites/components/CompositeView.js.map +1 -1
  226. package/dist/features/composites/components/DerivationBadge.js +15 -6
  227. package/dist/features/composites/components/DerivationBadge.js.map +1 -1
  228. package/dist/features/composites/components/FocusChip.js +1 -1
  229. package/dist/features/composites/components/FocusChip.js.map +1 -1
  230. package/dist/features/composites/components/FocusChip.vue.d.ts +1 -1
  231. package/dist/features/composites/components/ReferenceFieldSelect.js +3 -3
  232. package/dist/features/composites/components/ReferenceFieldSelect.js.map +1 -1
  233. package/dist/features/composites/components/ReferenceView.js +1 -1
  234. package/dist/features/composites/components/ReferenceView.js.map +1 -1
  235. package/dist/features/composites/components/SettingsEditingTab.js +18 -18
  236. package/dist/features/composites/components/SettingsEditingTab.js.map +1 -1
  237. package/dist/features/composites/components/SettingsEditingTab.vue.d.ts +3 -3
  238. package/dist/features/composites/convert.d.ts +4 -4
  239. package/dist/features/composites/convert.js +27 -28
  240. package/dist/features/composites/convert.js.map +1 -1
  241. package/dist/features/composites/derived-chrome.js +34 -28
  242. package/dist/features/composites/derived-chrome.js.map +1 -1
  243. package/dist/features/composites/editing-settings-keys.js +6 -6
  244. package/dist/features/composites/editing-settings-keys.js.map +1 -1
  245. package/dist/features/composites/feature.d.ts +10 -10
  246. package/dist/features/composites/feature.js +58 -46
  247. package/dist/features/composites/feature.js.map +1 -1
  248. package/dist/features/composites/fences.d.ts +3 -3
  249. package/dist/features/composites/fences.js +18 -13
  250. package/dist/features/composites/fences.js.map +1 -1
  251. package/dist/features/composites/focus.d.ts +10 -10
  252. package/dist/features/composites/focus.js +11 -11
  253. package/dist/features/composites/focus.js.map +1 -1
  254. package/dist/features/composites/heading-composites.d.ts +5 -5
  255. package/dist/features/composites/heading-composites.js +13 -16
  256. package/dist/features/composites/heading-composites.js.map +1 -1
  257. package/dist/features/composites/index.d.ts +20 -18
  258. package/dist/features/composites/index.js +9 -7
  259. package/dist/features/composites/inspector-model.d.ts +45 -22
  260. package/dist/features/composites/inspector-model.js +53 -14
  261. package/dist/features/composites/inspector-model.js.map +1 -1
  262. package/dist/features/composites/legacy.d.ts +5 -4
  263. package/dist/features/composites/legacy.js +16 -23
  264. package/dist/features/composites/legacy.js.map +1 -1
  265. package/dist/features/composites/markdown-export.js +3 -3
  266. package/dist/features/composites/markdown-export.js.map +1 -1
  267. package/dist/features/composites/merge.d.ts +8 -8
  268. package/dist/features/composites/merge.js +23 -22
  269. package/dist/features/composites/merge.js.map +1 -1
  270. package/dist/features/composites/meta-display.js +5 -5
  271. package/dist/features/composites/meta-display.js.map +1 -1
  272. package/dist/features/composites/meta-keys.d.ts +5 -5
  273. package/dist/features/composites/meta-keys.js +8 -8
  274. package/dist/features/composites/meta-keys.js.map +1 -1
  275. package/dist/features/composites/node-views.d.ts +3 -3
  276. package/dist/features/composites/node-views.js +2 -2
  277. package/dist/features/composites/node-views.js.map +1 -1
  278. package/dist/features/composites/nodes.d.ts +13 -13
  279. package/dist/features/composites/nodes.js +100 -77
  280. package/dist/features/composites/nodes.js.map +1 -1
  281. package/dist/features/composites/outline.d.ts +15 -12
  282. package/dist/features/composites/outline.js +24 -21
  283. package/dist/features/composites/outline.js.map +1 -1
  284. package/dist/features/composites/properties.d.ts +51 -0
  285. package/dist/features/composites/properties.js +89 -0
  286. package/dist/features/composites/properties.js.map +1 -0
  287. package/dist/features/composites/react/BibliographyEditor.js +5 -5
  288. package/dist/features/composites/react/BibliographyEditor.js.map +1 -1
  289. package/dist/features/composites/react/CompositeBasketMenu.js +2 -2
  290. package/dist/features/composites/react/CompositeBasketMenu.js.map +1 -1
  291. package/dist/features/composites/react/CompositeChrome.d.ts +1 -1
  292. package/dist/features/composites/react/CompositeChrome.js +15 -6
  293. package/dist/features/composites/react/CompositeChrome.js.map +1 -1
  294. package/dist/features/composites/react/CompositeDetails.d.ts +1 -1
  295. package/dist/features/composites/react/CompositeDetails.js +11 -10
  296. package/dist/features/composites/react/CompositeDetails.js.map +1 -1
  297. package/dist/features/composites/react/CompositeFieldEditor.d.ts +5 -5
  298. package/dist/features/composites/react/CompositeFieldEditor.js +6 -6
  299. package/dist/features/composites/react/CompositeFieldEditor.js.map +1 -1
  300. package/dist/features/composites/react/CompositeInspector.d.ts +3 -3
  301. package/dist/features/composites/react/CompositeInspector.js +142 -128
  302. package/dist/features/composites/react/CompositeInspector.js.map +1 -1
  303. package/dist/features/composites/react/CompositeStatusMenu.js +2 -2
  304. package/dist/features/composites/react/CompositeStatusMenu.js.map +1 -1
  305. package/dist/features/composites/react/CompositeSummaryEditor.d.ts +1 -1
  306. package/dist/features/composites/react/CompositeSummaryEditor.js +1 -1
  307. package/dist/features/composites/react/CompositeSummaryEditor.js.map +1 -1
  308. package/dist/features/composites/react/CompositeTable.d.ts +1 -1
  309. package/dist/features/composites/react/CompositeTable.js +3 -3
  310. package/dist/features/composites/react/CompositeTable.js.map +1 -1
  311. package/dist/features/composites/react/CompositeTagsEditor.d.ts +1 -1
  312. package/dist/features/composites/react/CompositeTagsEditor.js +1 -1
  313. package/dist/features/composites/react/CompositeTagsEditor.js.map +1 -1
  314. package/dist/features/composites/react/CompositeView.js +17 -15
  315. package/dist/features/composites/react/CompositeView.js.map +1 -1
  316. package/dist/features/composites/react/DerivationBadge.js +13 -4
  317. package/dist/features/composites/react/DerivationBadge.js.map +1 -1
  318. package/dist/features/composites/react/FocusChip.d.ts +1 -1
  319. package/dist/features/composites/react/FocusChip.js +1 -1
  320. package/dist/features/composites/react/FocusChip.js.map +1 -1
  321. package/dist/features/composites/react/ReferenceFieldSelect.js +3 -3
  322. package/dist/features/composites/react/ReferenceFieldSelect.js.map +1 -1
  323. package/dist/features/composites/react/ReferenceView.d.ts +1 -1
  324. package/dist/features/composites/react/ReferenceView.js +1 -1
  325. package/dist/features/composites/react/ReferenceView.js.map +1 -1
  326. package/dist/features/composites/react/SettingsEditingTab.d.ts +4 -4
  327. package/dist/features/composites/react/SettingsEditingTab.js +20 -20
  328. package/dist/features/composites/react/SettingsEditingTab.js.map +1 -1
  329. package/dist/features/composites/react.js +1 -1
  330. package/dist/features/composites/react.js.map +1 -1
  331. package/dist/features/composites/reference-ai.js +1 -1
  332. package/dist/features/composites/reference-ai.js.map +1 -1
  333. package/dist/features/composites/reference-label.d.ts +3 -3
  334. package/dist/features/composites/reference-label.js +6 -6
  335. package/dist/features/composites/reference-label.js.map +1 -1
  336. package/dist/features/composites/reference-suggestion.d.ts +1 -1
  337. package/dist/features/composites/reference-suggestion.js +3 -3
  338. package/dist/features/composites/reference-suggestion.js.map +1 -1
  339. package/dist/features/composites/reference-text.d.ts +2 -2
  340. package/dist/features/composites/reference-text.js +4 -4
  341. package/dist/features/composites/reference-text.js.map +1 -1
  342. package/dist/features/composites/reference.d.ts +3 -3
  343. package/dist/features/composites/reference.js +1 -1
  344. package/dist/features/composites/reference.js.map +1 -1
  345. package/dist/features/composites/reveal-source.d.ts +3 -3
  346. package/dist/features/composites/reveal-source.js +6 -6
  347. package/dist/features/composites/reveal-source.js.map +1 -1
  348. package/dist/features/composites/rows-model.d.ts +2 -2
  349. package/dist/features/composites/rows-model.js +4 -3
  350. package/dist/features/composites/rows-model.js.map +1 -1
  351. package/dist/features/composites/rows.d.ts +16 -28
  352. package/dist/features/composites/rows.js +20 -54
  353. package/dist/features/composites/rows.js.map +1 -1
  354. package/dist/features/composites/schema.d.ts +12 -11
  355. package/dist/features/composites/schema.js +10 -9
  356. package/dist/features/composites/schema.js.map +1 -1
  357. package/dist/features/composites/source.d.ts +20 -0
  358. package/dist/features/composites/source.js +40 -0
  359. package/dist/features/composites/source.js.map +1 -0
  360. package/dist/features/composites/split.d.ts +11 -11
  361. package/dist/features/composites/split.js +20 -20
  362. package/dist/features/composites/split.js.map +1 -1
  363. package/dist/features/composites/structure-mode.js +3 -3
  364. package/dist/features/composites/structure-mode.js.map +1 -1
  365. package/dist/features/composites/table-model.js +2 -2
  366. package/dist/features/composites/table-model.js.map +1 -1
  367. package/dist/features/composites/use-composite-inspector.js +3 -1
  368. package/dist/features/composites/use-composite-inspector.js.map +1 -1
  369. package/dist/features/composites/use-composite-rows.d.ts +2 -2
  370. package/dist/features/composites/use-composite-rows.js.map +1 -1
  371. package/dist/features/composites/vue.js +1 -1
  372. package/dist/features/composites/vue.js.map +1 -1
  373. package/dist/features/image-studio/components/ImageStudioDialog.js +150 -87
  374. package/dist/features/image-studio/components/ImageStudioDialog.js.map +1 -1
  375. package/dist/features/image-studio/components/ImageStudioDialog.vue.d.ts +5 -1
  376. package/dist/features/image-studio/components/ImageStudioLibraryPanel.js +186 -0
  377. package/dist/features/image-studio/components/ImageStudioLibraryPanel.js.map +1 -0
  378. package/dist/features/image-studio/components/ImageStudioLibraryTile.js +134 -0
  379. package/dist/features/image-studio/components/ImageStudioLibraryTile.js.map +1 -0
  380. package/dist/features/image-studio/components/ImageStudioView.js.map +1 -1
  381. package/dist/features/image-studio/feature.d.ts +1 -1
  382. package/dist/features/image-studio/feature.js +1 -1
  383. package/dist/features/image-studio/feature.js.map +1 -1
  384. package/dist/features/image-studio/index.d.ts +3 -2
  385. package/dist/features/image-studio/index.js +2 -2
  386. package/dist/features/image-studio/library.d.ts +35 -0
  387. package/dist/features/image-studio/node-core.d.ts +3 -3
  388. package/dist/features/image-studio/node-core.js +1 -1
  389. package/dist/features/image-studio/node-core.js.map +1 -1
  390. package/dist/features/image-studio/node-store.d.ts +1 -1
  391. package/dist/features/image-studio/node-store.js +1 -1
  392. package/dist/features/image-studio/node-store.js.map +1 -1
  393. package/dist/features/image-studio/react/ImageStudioDialog.d.ts +1 -1
  394. package/dist/features/image-studio/react/ImageStudioDialog.js +46 -5
  395. package/dist/features/image-studio/react/ImageStudioDialog.js.map +1 -1
  396. package/dist/features/image-studio/react/ImageStudioLibraryPanel.js +141 -0
  397. package/dist/features/image-studio/react/ImageStudioLibraryPanel.js.map +1 -0
  398. package/dist/features/image-studio/react/ImageStudioLibraryTile.js +105 -0
  399. package/dist/features/image-studio/react/ImageStudioLibraryTile.js.map +1 -0
  400. package/dist/features/image-studio/react/ImageStudioView.js +1 -1
  401. package/dist/features/image-studio/react/ImageStudioView.js.map +1 -1
  402. package/dist/features/image-studio/react/store.d.ts +8 -3
  403. package/dist/features/image-studio/react/store.js.map +1 -1
  404. package/dist/features/image-studio/react.d.ts +4 -3
  405. package/dist/features/image-studio/react.js +3 -3
  406. package/dist/features/image-studio/react.js.map +1 -1
  407. package/dist/features/image-studio/schema.d.ts +1 -1
  408. package/dist/features/image-studio/schema.js +1 -1
  409. package/dist/features/image-studio/schema.js.map +1 -1
  410. package/dist/features/image-studio/state.d.ts +8 -3
  411. package/dist/features/image-studio/state.js +11 -3
  412. package/dist/features/image-studio/state.js.map +1 -1
  413. package/dist/features/image-studio/store.d.ts +8 -3
  414. package/dist/features/image-studio/vue.d.ts +4 -3
  415. package/dist/features/image-studio/vue.js +3 -3
  416. package/dist/features/image-studio/vue.js.map +1 -1
  417. package/dist/features/mentions/tag.js +2 -1
  418. package/dist/features/mentions/tag.js.map +1 -1
  419. package/dist/features/themes/components/SettingsAppearanceTab.js +1 -1
  420. package/dist/features/themes/components/SettingsAppearanceTab.js.map +1 -1
  421. package/dist/features/themes/feature.d.ts +1 -1
  422. package/dist/features/themes/feature.js.map +1 -1
  423. package/dist/features/themes/react/SettingsAppearanceTab.d.ts +1 -1
  424. package/dist/features/themes/react/SettingsAppearanceTab.js +1 -1
  425. package/dist/features/themes/react/SettingsAppearanceTab.js.map +1 -1
  426. package/dist/features/themes/theme-runtime.js +1 -1
  427. package/dist/features/themes/theme-runtime.js.map +1 -1
  428. package/dist/features/transcript/TranscriptSegmentView.js +1 -1
  429. package/dist/features/transcript/TranscriptSegmentView.js.map +1 -1
  430. package/dist/features/transcript/react/TranscriptSegmentView.js +1 -1
  431. package/dist/features/transcript/react/TranscriptSegmentView.js.map +1 -1
  432. package/dist/features/transcript/segment-node.js.map +1 -1
  433. package/dist/features/transfer/feature.js +1 -1
  434. package/dist/features/transfer/feature.js.map +1 -1
  435. package/dist/features/transfer/transforms.d.ts +4 -4
  436. package/dist/features/transfer/transforms.js +12 -12
  437. package/dist/features/transfer/transforms.js.map +1 -1
  438. package/dist/i18n/de/ai.js +4 -4
  439. package/dist/i18n/de/ai.js.map +1 -1
  440. package/dist/i18n/de/authors.js +1 -1
  441. package/dist/i18n/de/authors.js.map +1 -1
  442. package/dist/i18n/de/comments.js +1 -1
  443. package/dist/i18n/de/comments.js.map +1 -1
  444. package/dist/i18n/de/composites.js +62 -59
  445. package/dist/i18n/de/composites.js.map +1 -1
  446. package/dist/i18n/de/image-studio.js +11 -2
  447. package/dist/i18n/de/image-studio.js.map +1 -1
  448. package/dist/i18n/de/integrations.js +20 -20
  449. package/dist/i18n/de/integrations.js.map +1 -1
  450. package/dist/i18n/de/markdown.js +1 -1
  451. package/dist/i18n/de/markdown.js.map +1 -1
  452. package/dist/i18n/de/palette.js +1 -1
  453. package/dist/i18n/de/palette.js.map +1 -1
  454. package/dist/i18n/de/themes.js +3 -3
  455. package/dist/i18n/de/themes.js.map +1 -1
  456. package/dist/i18n/de/transfer.js +2 -2
  457. package/dist/i18n/de/transfer.js.map +1 -1
  458. package/dist/i18n/de/tree.js +6 -6
  459. package/dist/i18n/de/tree.js.map +1 -1
  460. package/dist/i18n/de.d.ts +110 -98
  461. package/dist/i18n/en/ai.js +2 -2
  462. package/dist/i18n/en/ai.js.map +1 -1
  463. package/dist/i18n/en/composites.js +64 -61
  464. package/dist/i18n/en/composites.js.map +1 -1
  465. package/dist/i18n/en/image-studio.js +9 -0
  466. package/dist/i18n/en/image-studio.js.map +1 -1
  467. package/dist/i18n/en/integrations.js +9 -9
  468. package/dist/i18n/en/integrations.js.map +1 -1
  469. package/dist/i18n/en/markdown.js +1 -1
  470. package/dist/i18n/en/markdown.js.map +1 -1
  471. package/dist/i18n/en/palette.js +1 -1
  472. package/dist/i18n/en/palette.js.map +1 -1
  473. package/dist/i18n/en/themes.js +4 -4
  474. package/dist/i18n/en/themes.js.map +1 -1
  475. package/dist/i18n/en/tree.js +5 -5
  476. package/dist/i18n/en/tree.js.map +1 -1
  477. package/dist/index.d.ts +4 -1
  478. package/dist/integrations/composite-ai/bibliography-fetch.d.ts +6 -6
  479. package/dist/integrations/composite-ai/bibliography-fetch.js +19 -19
  480. package/dist/integrations/composite-ai/bibliography-fetch.js.map +1 -1
  481. package/dist/integrations/composite-ai/composite-fill.d.ts +4 -4
  482. package/dist/integrations/composite-ai/composite-fill.js +5 -5
  483. package/dist/integrations/composite-ai/composite-fill.js.map +1 -1
  484. package/dist/integrations/composite-ai/composite-summary.d.ts +2 -2
  485. package/dist/integrations/composite-ai/composite-summary.js +5 -5
  486. package/dist/integrations/composite-ai/composite-summary.js.map +1 -1
  487. package/dist/integrations/composite-ai/derive.d.ts +17 -17
  488. package/dist/integrations/composite-ai/derive.js +27 -26
  489. package/dist/integrations/composite-ai/derive.js.map +1 -1
  490. package/dist/integrations/composite-ai/index.d.ts +14 -15
  491. package/dist/integrations/composite-ai/index.js +98 -77
  492. package/dist/integrations/composite-ai/index.js.map +1 -1
  493. package/dist/integrations/composite-ai/outline-sanitize.d.ts +1 -1
  494. package/dist/integrations/composite-ai/outline-sanitize.js +1 -1
  495. package/dist/integrations/composite-ai/outline-sanitize.js.map +1 -1
  496. package/dist/integrations/composite-ai/rendition.d.ts +9 -9
  497. package/dist/integrations/composite-ai/rendition.js +27 -27
  498. package/dist/integrations/composite-ai/rendition.js.map +1 -1
  499. package/dist/integrations/composite-ai/split.d.ts +8 -8
  500. package/dist/integrations/composite-ai/split.js +12 -12
  501. package/dist/integrations/composite-ai/split.js.map +1 -1
  502. package/dist/integrations/composite-ai/transfer-transforms.d.ts +2 -2
  503. package/dist/integrations/composite-ai/transfer-transforms.js +11 -11
  504. package/dist/integrations/composite-ai/transfer-transforms.js.map +1 -1
  505. package/dist/integrations/composite-media/index.d.ts +4 -3
  506. package/dist/integrations/composite-media/index.js +20 -14
  507. package/dist/integrations/composite-media/index.js.map +1 -1
  508. package/dist/markdown/MarkdownSurface.vue.d.ts +7 -7
  509. package/dist/markdown/document.js +1 -1
  510. package/dist/markdown/document.js.map +1 -1
  511. package/dist/nuxt/module.d.ts +48 -24
  512. package/dist/nuxt/module.js.map +1 -1
  513. package/dist/nuxt/runtime/server/plugins/editor-server.js +3 -2
  514. package/dist/nuxt/runtime/server/plugins/editor-server.js.map +1 -1
  515. package/dist/presets/compose.d.ts +6 -6
  516. package/dist/presets/compose.js +7 -4
  517. package/dist/presets/compose.js.map +1 -1
  518. package/dist/react/AdvancedEditor.d.ts +2 -2
  519. package/dist/react/AdvancedEditor.js +1 -1
  520. package/dist/react/AdvancedEditor.js.map +1 -1
  521. package/dist/react/compose.d.ts +1 -1
  522. package/dist/react/compose.js +1 -1
  523. package/dist/react/compose.js.map +1 -1
  524. package/dist/react/composed-surface.d.ts +5 -5
  525. package/dist/react/composed-surface.js +2 -2
  526. package/dist/react/composed-surface.js.map +1 -1
  527. package/dist/server/ai.d.ts +7 -7
  528. package/dist/server/ai.js +1 -1
  529. package/dist/server/ai.js.map +1 -1
  530. package/dist/server/auth.d.ts +1 -1
  531. package/dist/server/collab-state.d.ts +1 -1
  532. package/dist/server/collab-state.js.map +1 -1
  533. package/dist/server/collab.d.ts +4 -4
  534. package/dist/server/collab.js +22 -17
  535. package/dist/server/collab.js.map +1 -1
  536. package/dist/server/handlers/ai.d.ts +9 -6
  537. package/dist/server/handlers/ai.js +13 -17
  538. package/dist/server/handlers/ai.js.map +1 -1
  539. package/dist/server/handlers/context.d.ts +4 -0
  540. package/dist/server/handlers/context.js.map +1 -1
  541. package/dist/server/handlers/editor.d.ts +33 -32
  542. package/dist/server/handlers/editor.js +13 -8
  543. package/dist/server/handlers/editor.js.map +1 -1
  544. package/dist/server/handlers/images.d.ts +1 -1
  545. package/dist/server/handlers/images.js +1 -1
  546. package/dist/server/handlers/images.js.map +1 -1
  547. package/dist/server/host.d.ts +4 -0
  548. package/dist/server/host.js +10 -2
  549. package/dist/server/host.js.map +1 -1
  550. package/dist/server/index.d.ts +3 -3
  551. package/dist/server/ports.d.ts +8 -8
  552. package/dist/server/ports.js.map +1 -1
  553. package/dist/settings/index.d.ts +20 -19
  554. package/dist/settings/index.js +25 -24
  555. package/dist/settings/index.js.map +1 -1
  556. package/dist/settings/migrate.d.ts +18 -0
  557. package/dist/settings/migrate.js +46 -0
  558. package/dist/settings/migrate.js.map +1 -0
  559. package/dist/settings/values.d.ts +12 -12
  560. package/dist/settings/values.js +11 -11
  561. package/dist/settings/values.js.map +1 -1
  562. package/dist/styles/composites.css +10 -10
  563. package/dist/tree/DocumentTree.js +12 -5
  564. package/dist/tree/DocumentTree.js.map +1 -1
  565. package/dist/tree/drop-rules.js +5 -5
  566. package/dist/tree/drop-rules.js.map +1 -1
  567. package/dist/tree/react/DocumentTree.js +14 -5
  568. package/dist/tree/react/DocumentTree.js.map +1 -1
  569. package/dist/tree/tree-host.js +5 -5
  570. package/dist/tree/tree-host.js.map +1 -1
  571. package/dist/tree/tree-items.js +34 -28
  572. package/dist/tree/tree-items.js.map +1 -1
  573. package/dist/tree/tree-model.js +16 -16
  574. package/dist/tree/tree-model.js.map +1 -1
  575. package/dist/tree/tree-rows.js +2 -2
  576. package/dist/tree/tree-rows.js.map +1 -1
  577. package/dist/tree/tree-view-model.d.ts +2 -2
  578. package/dist/tree/tree-view-model.js.map +1 -1
  579. package/dist/vue/AdvancedEditor.js +2 -2
  580. package/dist/vue/AdvancedEditor.js.map +1 -1
  581. package/dist/vue/AdvancedEditor.vue.d.ts +10 -10
  582. package/dist/vue/SimpleEditor.vue.d.ts +4 -4
  583. package/dist/vue/components/EditorSurface.vue.d.ts +4 -4
  584. package/dist/vue/compose.d.ts +1 -1
  585. package/dist/vue/compose.js +1 -1
  586. package/dist/vue/compose.js.map +1 -1
  587. package/package.json +1 -1
  588. package/dist/features/composites/derivation.d.ts +0 -62
  589. package/dist/features/composites/derivation.js +0 -102
  590. package/dist/features/composites/derivation.js.map +0 -1
  591. package/dist/features/composites/kinds.d.ts +0 -89
  592. package/dist/features/composites/kinds.js +0 -285
  593. package/dist/features/composites/kinds.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"collab.js","names":[],"sources":["../../src/server/collab.ts"],"sourcesContent":["import { type Configuration, Hocuspocus, type WebSocketLike } from '@hocuspocus/server'\nimport { type AnyExtension, getSchema, type JSONContent } from '@tiptap/core'\nimport type { Schema } from '@tiptap/pm/model'\nimport { prosemirrorToYDoc, prosemirrorToYXmlFragment, yDocToProsemirrorJSON, yXmlFragmentToProsemirror } from '@tiptap/y-tiptap'\nimport * as Y from 'yjs'\nimport { assignBlockIds, EMPTY_EDITOR_CONTENT } from '../core/schema'\nimport { LEGACY_COMPOSITE_NODE, migrateLegacyContent } from '../features/composites/schema'\nimport { advancedSchemaExtensions } from '../schema/advanced'\nimport { decodeCollabState, encodeCollabState, isStateStale } from './collab-state'\nimport type { CollabStateStore, DocumentStore, EditorPorts, Identity } from './ports'\n\n/** Y.XmlFragment the TipTap Collaboration extension binds to (its default `field`). */\nexport const COLLAB_FIELD = 'default'\n\n/** Close code of a connection whose client could not be authenticated (Hocuspocus' `Unauthorized`, HTTP 401 in websocket terms). */\nconst UNAUTHORIZED = { code: 4401, reason: 'Unauthorized' }\n\n/** Context key under which `handleConnection` hands the connection's socket closer to the `onAuthenticate` hook. */\nconst REJECT = Symbol('collab.reject')\n\nexport interface CollabServerOptions {\n /** Identity, documents and Yjs state of the editor backend; `collabState` is required. */\n ports: EditorPorts\n /** TipTap extensions of the collaboration schema; default `advancedSchemaExtensions()`. Host-defined nodes and marks: `() => [...advancedSchemaExtensions(), HostNode]` (Vue-free node files only, no node views). */\n schema?: () => AnyExtension[]\n /** Per-document access and content versioning; each defaults to the port's method of the same name. */\n hooks?: {\n authorize?: NonNullable<Identity['authorize']>\n contentVersion?: NonNullable<DocumentStore['contentVersion']>\n }\n /** Further Hocuspocus configuration (`debounce`, `timeout`, `quiet`, …); the editor's hooks win over equally named ones. */\n configuration?: Partial<Configuration>\n}\n\n/** One served websocket connection: feed it the socket's messages and its close event. */\nexport interface CollabConnection {\n handleMessage(data: Uint8Array): void\n handleClose(event?: CloseEvent): void\n}\n\nexport interface CollabServer {\n /**\n * The Hocuspocus instance of this server. The Yjs state (via the `collabState` port's `loadState`/`storeState`) is the\n * source of truth for content, the host's JSON content (via the `documents` port) is a mirror kept up to date on every store.\n */\n hocuspocus: Hocuspocus\n /** Schema of the collab server: `options.schema()` (default `advancedSchemaExtensions()`), built on first use. */\n schema(): Schema\n /**\n * Serves one websocket connection (any transport: crossws, `ws`, Bun, Deno). The user is authenticated in Hocuspocus'\n * `onAuthenticate` from the upgrade request's headers and the client's token, unless the transport already knows it\n * and passes it as `context.user`. Wire `handleMessage` and `handleClose` of the returned connection to the socket's events.\n */\n handleConnection(socket: WebSocketLike, request: Request, context?: { user?: object }): CollabConnection\n /** Tell connected clients the document is gone, disconnect them and drop the Yjs state. Call before removing the JSON. */\n forgetDocument(id: string): Promise<void>\n /** Current content of a document that is open in Hocuspocus (unsaved edits included), `null` when nobody has it open. */\n liveContent(id: string): JSONContent | null\n /**\n * The host rewrote the content behind the editor's back (an agent wrote the file): merge it into the open document now,\n * as a diff-update connected clients see as an ordinary edit. Without this the merge waits for the document's next store.\n * No-op when nobody has the document open or the content version is unchanged; needs the documents port's `contentVersion`.\n */\n contentChanged(id: string): Promise<void>\n /** Open collaboration connections and loaded documents of this server. */\n stats(): { connections: number, documents: number }\n /** Disconnect every client, write pending stores and wait until all documents are unloaded. The server accepts no connection afterwards. */\n close(): Promise<void>\n}\n\n/** ProseMirror document of stored JSON content: legacy nodes migrated, empty content replaced by the empty document, block IDs assigned. */\nfunction contentNode(schema: Schema, loaded: JSONContent) {\n const content = migrateLegacyContent(loaded)\n const node = schema.nodeFromJSON(content.type === 'doc' && content.content?.length ? content : EMPTY_EDITOR_CONTENT)\n return assignBlockIds(node) ?? node\n}\n\n/** Whether a `document` Baustein of the stored Yjs content still carries the flat `meta.transcript` that `migrateLegacyContent` turns into a `rendition` child. */\nfunction hasFlatTranscript(fragment: Y.XmlFragment): boolean {\n return !fragment.createTreeWalker((node) => {\n if (!(node instanceof Y.XmlElement) || node.nodeName !== 'composite' || node.getAttribute('kind') !== 'document') return false\n const meta: unknown = node.getAttribute('meta')\n return typeof meta === 'object' && meta !== null && 'transcript' in meta && typeof meta.transcript === 'string'\n }).next().done\n}\n\n/** Hocuspocus answers a thrown error's `reason` as permission-denied. */\nconst denied = (message: string, reason: string) => Object.assign(new Error(message), { reason })\n\n/** The `collabState` port; the collaboration server cannot run without it. */\nfunction collabStateOf(ports: EditorPorts): CollabStateStore {\n if (!ports.collabState) throw new Error('@ecsplico/editor: collaboration needs the collabState port')\n return ports.collabState\n}\n\n/**\n * The editor's collaboration server, independent of any web framework: Hocuspocus with the editor's hooks (seeding from\n * the stored JSON, versioned state, block-ID backfill, debounced `storeContent`/`storeState`) over `options.ports`.\n * `/nuxt` mounts one in Nitro; any Node/Bun/Deno process can serve `handleConnection` on its own websocket transport.\n */\nexport function createCollabServer(options: CollabServerOptions): CollabServer {\n const { identity, documents } = options.ports\n const state = collabStateOf(options.ports)\n const authorize = (user: object, id: string) => options.hooks?.authorize ? options.hooks.authorize(user, id) : identity.authorize?.(user, id)\n const contentVersion = (id: string) => options.hooks?.contentVersion ? options.hooks.contentVersion(id) : documents.contentVersion?.(id)\n\n let schema: Schema | undefined\n const collabSchema = () => schema ??= getSchema((options.schema ?? advancedSchemaExtensions)())\n\n /** Loaded documents deleted via `forgetDocument`; a store still pending for them must not write their Yjs state back. */\n const forgotten = new Set<string>()\n /** `contentVersion` the loaded document's content mirror had when it was last read or written; only tracked for documents ports with `contentVersion`. */\n const loadedVersions = new Map<string, string | null>()\n /** Resolvers of `close()` waiting for the last document to unload. */\n const idle: (() => void)[] = []\n let closed = false\n\n /** Merges content rewritten behind the editor's back into the open document and stores its state against `version`. */\n async function mergeRewrite(id: string, document: Y.Doc, version: string | null): Promise<void> {\n const rewritten = await documents.loadContent(id)\n if (!rewritten) return // removed meanwhile: nothing to merge, nothing to mirror\n // A diff-update: unchanged blocks keep their Yjs items, so connected clients see an ordinary edit and need no reload.\n prosemirrorToYXmlFragment(contentNode(collabSchema(), rewritten), document.getXmlFragment(COLLAB_FIELD))\n loadedVersions.set(id, version)\n await state.storeState(id, encodeCollabState({ version, update: Y.encodeStateAsUpdate(document) }))\n }\n\n /** Stored state of a document, `null` when there is none usable: it was written against another content version and is removed. */\n async function loadCurrentState(id: string, liveVersion: string | null | undefined): Promise<Uint8Array | null> {\n const payload = await state.loadState(id)\n if (!payload) return null\n const { version, update } = decodeCollabState(payload)\n if (isStateStale(version, liveVersion)) {\n await state.removeState(id)\n return null\n }\n return update\n }\n\n const hocuspocus = new Hocuspocus({\n ...options.configuration,\n async onAuthenticate({ context, token, requestHeaders, documentName, connectionConfig }) {\n // The transport may know the user already; otherwise it comes from the upgrade request's headers or the client's token.\n let user = context.user as object | null | undefined\n if (!user) user = await identity.authenticate({ headers: requestHeaders, ...(token && { token }) })\n if (!user) {\n // After the permission-denied answer Hocuspocus sends: close the socket, so a client without credentials does not linger.\n const socketCloser = context[REJECT] as (() => void) | undefined\n socketCloser?.()\n throw denied('Unauthorized', 'unauthorized')\n }\n const access = await authorize(user, documentName)\n // `undefined`: no authorize hook, every authenticated user may edit. `null`: rejected; the thrown error's `reason` is answered as permission-denied.\n if (access === null) throw denied('Forbidden', 'forbidden')\n if (access?.readOnly) connectionConfig.readOnly = true\n return { user }\n },\n async onLoadDocument({ documentName }) {\n const currentSchema = collabSchema()\n // Read before the content: a change in between leaves an older version on the state, which only costs a re-seed.\n const version = await contentVersion(documentName)\n const stored = await loadCurrentState(documentName, version)\n if (version !== undefined) loadedVersions.set(documentName, version)\n const persist = (doc: Y.Doc) => state.storeState(documentName, encodeCollabState({ version: version ?? null, update: Y.encodeStateAsUpdate(doc) }))\n if (stored) {\n // Decoded into a scratch doc: Hocuspocus only gets it once it is known to be current.\n const doc = new Y.Doc()\n Y.applyUpdate(doc, stored)\n const fragment = doc.getXmlFragment(COLLAB_FIELD)\n // State from before the composite family holds node names the schema no longer knows (any depth): drop it and\n // reseed below from the migrated JSON mirror, which also rewrites the stored state.\n const legacy = !fragment.createTreeWalker(node => node instanceof Y.XmlElement && node.nodeName === LEGACY_COMPOSITE_NODE).next().done\n if (!legacy) {\n // Blocks without an ID (state from before block IDs) and a `document` Baustein's flat `meta.transcript` (it\n // became a `rendition` child): migrate here, before any client syncs, so clients never backfill concurrently.\n // The diff-update keeps the Yjs items of everything that did not change.\n const current = yXmlFragmentToProsemirror(currentSchema, fragment)\n const migrated = hasFlatTranscript(fragment) ? currentSchema.nodeFromJSON(migrateLegacyContent(current.toJSON())) : current\n const withIds = assignBlockIds(migrated) ?? (migrated === current ? null : migrated)\n if (withIds) {\n prosemirrorToYXmlFragment(withIds, fragment)\n // Persist right away: a backfill after a restart would assign other IDs than clients already hold.\n await persist(doc)\n }\n return doc\n }\n }\n const loaded = await documents.loadContent(documentName)\n if (!loaded) throw new Error('Dokument nicht gefunden') // Hocuspocus closes the connection\n // No usable Yjs state (new, legacy, stale or restored document): seed it from the stored JSON, with block IDs.\n const seeded = prosemirrorToYDoc(contentNode(currentSchema, loaded), COLLAB_FIELD)\n // Persist right away: re-seeding later would create new Yjs items that duplicate what clients still hold.\n await persist(seeded)\n return seeded\n },\n async onStoreDocument({ documentName, document }) {\n if (forgotten.has(documentName)) return\n const tracked = loadedVersions.get(documentName)\n const current = tracked === undefined ? undefined : await contentVersion(documentName)\n if (current !== undefined && current !== tracked) {\n // The content was rewritten behind the editor's back: writing the Yjs content back would clobber the rewrite.\n // Merge the rewrite into the open document instead and store the state against the new version.\n await mergeRewrite(documentName, document, current)\n return\n }\n await documents.storeContent(documentName, yDocToProsemirrorJSON(document, COLLAB_FIELD))\n // After the content: the write itself moves the version, and the state must carry the one it matches.\n const version = await contentVersion(documentName)\n if (version !== undefined) loadedVersions.set(documentName, version)\n await state.storeState(documentName, encodeCollabState({ version: version ?? null, update: Y.encodeStateAsUpdate(document) }))\n },\n async afterUnloadDocument({ documentName }) {\n forgotten.delete(documentName)\n loadedVersions.delete(documentName)\n if (hocuspocus.getDocumentsCount() === 0) idle.splice(0).forEach(resolve => resolve())\n },\n })\n\n return {\n hocuspocus,\n schema: collabSchema,\n handleConnection(socket, request, context = {}) {\n if (closed) throw new Error('tiptap-editor: der Collab-Server ist geschlossen')\n // Deferred: Hocuspocus answers permission-denied first, then the socket closes.\n const reject = () => void setTimeout(() => socket.close(UNAUTHORIZED.code, UNAUTHORIZED.reason), 0)\n return hocuspocus.handleConnection(socket, request, { ...context, [REJECT]: reject })\n },\n async forgetDocument(id) {\n const doc = hocuspocus.documents.get(id)\n if (doc) {\n forgotten.add(id)\n doc.broadcastStateless('deleted')\n hocuspocus.closeConnections(id)\n }\n await state.removeState(id)\n },\n liveContent(id) {\n const doc = hocuspocus.documents.get(id)\n return doc ? yDocToProsemirrorJSON(doc, COLLAB_FIELD) as JSONContent : null\n },\n async contentChanged(id) {\n const doc = hocuspocus.documents.get(id)\n if (!doc || forgotten.has(id)) return\n const tracked = loadedVersions.get(id)\n if (tracked === undefined) return // no `contentVersion`: a rewrite cannot be told from the server's own writes\n const current = await contentVersion(id)\n if (current === undefined || current === tracked) return\n await mergeRewrite(id, doc, current)\n },\n stats: () => ({ connections: hocuspocus.getConnectionsCount(), documents: hocuspocus.getDocumentsCount() }),\n async close() {\n closed = true\n if (hocuspocus.getDocumentsCount() === 0) return\n await new Promise<void>((resolve) => {\n idle.push(resolve)\n hocuspocus.closeConnections()\n hocuspocus.flushPendingStores()\n })\n },\n }\n}\n\nexport type { WebSocketLike }\n"],"mappings":";;;;;;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AA,GAAW;GAC3B,MAAM,UAAU,MAAM,eAAe,EAAE;GACvC,IAAI,YAAY,KAAA,KAAa,YAAY,SAAS;GAClD,MAAM,aAAa,IAAI,KAAK,OAAO;EACrC;EACA,cAAc;GAAE,aAAa,WAAW,oBAAoB;GAAG,WAAW,WAAW,kBAAkB;EAAE;EACzG,MAAM,QAAQ;GACZ,SAAS;GACT,IAAI,WAAW,kBAAkB,MAAM,GAAG;GAC1C,MAAM,IAAI,SAAe,YAAY;IACnC,KAAK,KAAK,OAAO;IACjB,WAAW,iBAAiB;IAC5B,WAAW,mBAAmB;GAChC,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"collab.js","names":[],"sources":["../../src/server/collab.ts"],"sourcesContent":["import { type Configuration, Hocuspocus, type WebSocketLike } from '@hocuspocus/server'\nimport { type AnyExtension, getSchema, type JSONContent } from '@tiptap/core'\nimport type { Schema } from '@tiptap/pm/model'\nimport { prosemirrorToYDoc, prosemirrorToYXmlFragment, yDocToProsemirrorJSON, yXmlFragmentToProsemirror } from '@tiptap/y-tiptap'\nimport * as Y from 'yjs'\nimport { assignBlockIds, EMPTY_EDITOR_CONTENT, isOldPersistedNode, TYPED_BLOCK } from '../core/schema'\nimport { hasFlatTranscript, migrateLegacyContent } from '../features/composites/schema'\nimport { advancedSchemaExtensions } from '../schema/advanced'\nimport { decodeCollabState, encodeCollabState, isStateStale } from './collab-state'\nimport type { AccessControl, CollabStateStore, DocumentContentStore, EditorPorts } from './ports'\n\n/** Y.XmlFragment the TipTap Collaboration extension binds to (its default `field`). */\nexport const COLLAB_FIELD = 'default'\n\n/** Close code of a connection whose client could not be authenticated (Hocuspocus' `Unauthorized`, HTTP 401 in websocket terms). */\nconst UNAUTHORIZED = { code: 4401, reason: 'Unauthorized' }\n\n/** Context key under which `handleConnection` hands the connection's socket closer to the `onAuthenticate` hook. */\nconst REJECT = Symbol('collab.reject')\n\nexport interface CollabServerOptions {\n /** Access control, documents and Yjs state of the editor backend; `collabState` is required. */\n ports: EditorPorts\n /** TipTap extensions of the collaboration schema; default `advancedSchemaExtensions()`. Host-defined nodes and marks: `() => [...advancedSchemaExtensions(), HostNode]` (Vue-free node files only, no node views). */\n schema?: () => AnyExtension[]\n /** Per-document access and content versioning; each defaults to the port's method of the same name. */\n hooks?: {\n authorize?: NonNullable<AccessControl['authorize']>\n contentVersion?: NonNullable<DocumentContentStore['contentVersion']>\n }\n /** Further Hocuspocus configuration (`debounce`, `timeout`, `quiet`, …); the editor's hooks win over equally named ones. */\n configuration?: Partial<Configuration>\n}\n\n/** One served websocket connection: feed it the socket's messages and its close event. */\nexport interface CollabConnection {\n handleMessage(data: Uint8Array): void\n handleClose(event?: CloseEvent): void\n}\n\nexport interface CollabServer {\n /**\n * The Hocuspocus instance of this server. The Yjs state (via the `collabState` port's `loadState`/`storeState`) is the\n * source of truth for content, the host's JSON content (via the `documents` port) is a mirror kept up to date on every store.\n */\n hocuspocus: Hocuspocus\n /** Schema of the collab server: `options.schema()` (default `advancedSchemaExtensions()`), built on first use. */\n schema(): Schema\n /**\n * Serves one websocket connection (any transport: crossws, `ws`, Bun, Deno). The user is authenticated in Hocuspocus'\n * `onAuthenticate` from the upgrade request's headers and the client's token, unless the transport already knows it\n * and passes it as `context.user`. Wire `handleMessage` and `handleClose` of the returned connection to the socket's events.\n */\n handleConnection(socket: WebSocketLike, request: Request, context?: { user?: object }): CollabConnection\n /** Tell connected clients the document is gone, disconnect them and drop the Yjs state. Call before removing the JSON. */\n forgetDocument(id: string): Promise<void>\n /** Current content of a document that is open in Hocuspocus (unsaved edits included), `null` when nobody has it open. */\n liveContent(id: string): JSONContent | null\n /**\n * The host rewrote the content behind the editor's back (an agent wrote the file): merge it into the open document now,\n * as a diff-update connected clients see as an ordinary edit. Without this the merge waits for the document's next store.\n * No-op when nobody has the document open or the content version is unchanged; needs the documents port's `contentVersion`.\n */\n contentChanged(id: string): Promise<void>\n /** Open collaboration connections and loaded documents of this server. */\n stats(): { connections: number, documents: number }\n /** Disconnect every client, write pending stores and wait until all documents are unloaded. The server accepts no connection afterwards. */\n close(): Promise<void>\n}\n\n/** ProseMirror document of stored JSON content: old persisted names and legacy nodes migrated, empty content replaced by the empty document, block IDs assigned. */\nfunction contentNode(schema: Schema, loaded: JSONContent) {\n const content = migrateLegacyContent(loaded)\n const node = schema.nodeFromJSON(content.type === 'doc' && content.content?.length ? content : EMPTY_EDITOR_CONTENT)\n return assignBlockIds(node) ?? node\n}\n\n/** Whether the stored Yjs content still uses an old persisted name (the names listed in `persisted-names.ts`); the current schema does not know those elements. */\nfunction hasOldPersistedNames(fragment: Y.XmlFragment): boolean {\n return !fragment.createTreeWalker(node => node instanceof Y.XmlElement && isOldPersistedNode(node.nodeName, node.getAttributes(), { earliest: true })).next().done\n}\n\n/** Whether a Typed block of the stored Yjs content still carries the flat `meta.transcript` that `migrateLegacyContent` turns into a `rendition` child; its Block type does not matter. */\nfunction hasFlatTranscriptBlock(fragment: Y.XmlFragment): boolean {\n return !fragment.createTreeWalker(node => node instanceof Y.XmlElement && node.nodeName === TYPED_BLOCK && hasFlatTranscript(node.getAttribute('meta'))).next().done\n}\n\n/** Hocuspocus answers a thrown error's `reason` as permission-denied. */\nconst denied = (message: string, reason: string) => Object.assign(new Error(message), { reason })\n\n/** The `collabState` port; the collaboration server cannot run without it. */\nfunction collabStateOf(ports: EditorPorts): CollabStateStore {\n if (!ports.collabState) throw new Error('@ecsplico/editor: collaboration needs the collabState port')\n return ports.collabState\n}\n\n/**\n * The editor's collaboration server, independent of any web framework: Hocuspocus with the editor's hooks (seeding from\n * the stored JSON, versioned state, block-ID backfill, debounced `storeContent`/`storeState`) over `options.ports`.\n * `/nuxt` mounts one in Nitro; any Node/Bun/Deno process can serve `handleConnection` on its own websocket transport.\n */\nexport function createCollabServer(options: CollabServerOptions): CollabServer {\n const { identity, documents } = options.ports\n const state = collabStateOf(options.ports)\n const authorize = (user: object, id: string) => options.hooks?.authorize ? options.hooks.authorize(user, id) : identity.authorize?.(user, id)\n const contentVersion = (id: string) => options.hooks?.contentVersion ? options.hooks.contentVersion(id) : documents.contentVersion?.(id)\n\n let schema: Schema | undefined\n const collabSchema = () => schema ??= getSchema((options.schema ?? advancedSchemaExtensions)())\n\n /** Loaded documents deleted via `forgetDocument`; a store still pending for them must not write their Yjs state back. */\n const forgotten = new Set<string>()\n /** `contentVersion` the loaded document's content mirror had when it was last read or written; only tracked for documents ports with `contentVersion`. */\n const loadedVersions = new Map<string, string | null>()\n /** Resolvers of `close()` waiting for the last document to unload. */\n const idle: (() => void)[] = []\n let closed = false\n\n /** Merges content rewritten behind the editor's back into the open document and stores its state against `version`. */\n async function mergeRewrite(id: string, document: Y.Doc, version: string | null): Promise<void> {\n const rewritten = await documents.loadContent(id)\n if (!rewritten) return // removed meanwhile: nothing to merge, nothing to mirror\n // A diff-update: unchanged blocks keep their Yjs items, so connected clients see an ordinary edit and need no reload.\n prosemirrorToYXmlFragment(contentNode(collabSchema(), rewritten), document.getXmlFragment(COLLAB_FIELD))\n loadedVersions.set(id, version)\n await state.storeState(id, encodeCollabState({ version, update: Y.encodeStateAsUpdate(document) }))\n }\n\n /** Stored state of a document, `null` when there is none usable: it was written against another content version and is removed. */\n async function loadCurrentState(id: string, liveVersion: string | null | undefined): Promise<Uint8Array | null> {\n const payload = await state.loadState(id)\n if (!payload) return null\n const { version, update } = decodeCollabState(payload)\n if (isStateStale(version, liveVersion)) {\n await state.removeState(id)\n return null\n }\n return update\n }\n\n const hocuspocus = new Hocuspocus({\n ...options.configuration,\n async onAuthenticate({ context, token, requestHeaders, documentName, connectionConfig }) {\n // The transport may know the user already; otherwise it comes from the upgrade request's headers or the client's token.\n let user = context.user as object | null | undefined\n if (!user) user = await identity.authenticate({ headers: requestHeaders, ...(token && { token }) })\n if (!user) {\n // After the permission-denied answer Hocuspocus sends: close the socket, so a client without credentials does not linger.\n const socketCloser = context[REJECT] as (() => void) | undefined\n socketCloser?.()\n throw denied('Unauthorized', 'unauthorized')\n }\n const access = await authorize(user, documentName)\n // `undefined`: no authorize hook, every authenticated user may edit. `null`: rejected; the thrown error's `reason` is answered as permission-denied.\n if (access === null) throw denied('Forbidden', 'forbidden')\n if (access?.readOnly) connectionConfig.readOnly = true\n return { user }\n },\n async onLoadDocument({ documentName }) {\n const currentSchema = collabSchema()\n // Read before the content: a change in between leaves an older version on the state, which only costs a re-seed.\n const version = await contentVersion(documentName)\n const stored = await loadCurrentState(documentName, version)\n if (version !== undefined) loadedVersions.set(documentName, version)\n const persist = (doc: Y.Doc) => state.storeState(documentName, encodeCollabState({ version: version ?? null, update: Y.encodeStateAsUpdate(doc) }))\n if (stored) {\n // Decoded into a scratch doc: Hocuspocus only gets it once it is known to be current.\n const doc = new Y.Doc()\n Y.applyUpdate(doc, stored)\n const fragment = doc.getXmlFragment(COLLAB_FIELD)\n if (hasOldPersistedNames(fragment)) {\n // State from before the rename of Typed blocks (or from before the composite family) holds element names and\n // attributes the schema no longer knows, at any depth. Migrate from the state itself, not from the JSON mirror: the\n // schema-less JSON of the fragment goes through the JSON migration (block IDs and content stay), and is written back\n // here, before any client syncs. Persisted right away, so a second load finds nothing left to migrate.\n const migrated = contentNode(currentSchema, yDocToProsemirrorJSON(doc, COLLAB_FIELD))\n prosemirrorToYXmlFragment(migrated, fragment)\n await persist(doc)\n return doc\n }\n // Blocks without an ID (state from before block IDs) and a Typed block's flat `meta.transcript` (it\n // became a `rendition` child): migrate here, before any client syncs, so clients never backfill concurrently.\n // The diff-update keeps the Yjs items of everything that did not change.\n const current = yXmlFragmentToProsemirror(currentSchema, fragment)\n const migrated = hasFlatTranscriptBlock(fragment) ? currentSchema.nodeFromJSON(migrateLegacyContent(current.toJSON())) : current\n const withIds = assignBlockIds(migrated) ?? (migrated === current ? null : migrated)\n if (withIds) {\n prosemirrorToYXmlFragment(withIds, fragment)\n // Persist right away: a backfill after a restart would assign other IDs than clients already hold.\n await persist(doc)\n }\n return doc\n }\n const loaded = await documents.loadContent(documentName)\n if (!loaded) throw new Error('Dokument nicht gefunden') // Hocuspocus closes the connection\n // No usable Yjs state (new, legacy, stale or restored document): seed it from the stored JSON, with block IDs.\n const seeded = prosemirrorToYDoc(contentNode(currentSchema, loaded), COLLAB_FIELD)\n // Persist right away: re-seeding later would create new Yjs items that duplicate what clients still hold.\n await persist(seeded)\n return seeded\n },\n async onStoreDocument({ documentName, document }) {\n if (forgotten.has(documentName)) return\n const tracked = loadedVersions.get(documentName)\n const current = tracked === undefined ? undefined : await contentVersion(documentName)\n if (current !== undefined && current !== tracked) {\n // The content was rewritten behind the editor's back: writing the Yjs content back would clobber the rewrite.\n // Merge the rewrite into the open document instead and store the state against the new version.\n await mergeRewrite(documentName, document, current)\n return\n }\n await documents.storeContent(documentName, yDocToProsemirrorJSON(document, COLLAB_FIELD))\n // After the content: the write itself moves the version, and the state must carry the one it matches.\n const version = await contentVersion(documentName)\n if (version !== undefined) loadedVersions.set(documentName, version)\n await state.storeState(documentName, encodeCollabState({ version: version ?? null, update: Y.encodeStateAsUpdate(document) }))\n },\n async afterUnloadDocument({ documentName }) {\n forgotten.delete(documentName)\n loadedVersions.delete(documentName)\n if (hocuspocus.getDocumentsCount() === 0) idle.splice(0).forEach(resolve => resolve())\n },\n })\n\n return {\n hocuspocus,\n schema: collabSchema,\n handleConnection(socket, request, context = {}) {\n if (closed) throw new Error('tiptap-editor: der Collab-Server ist geschlossen')\n // Deferred: Hocuspocus answers permission-denied first, then the socket closes.\n const reject = () => void setTimeout(() => socket.close(UNAUTHORIZED.code, UNAUTHORIZED.reason), 0)\n return hocuspocus.handleConnection(socket, request, { ...context, [REJECT]: reject })\n },\n async forgetDocument(id) {\n const doc = hocuspocus.documents.get(id)\n if (doc) {\n forgotten.add(id)\n doc.broadcastStateless('deleted')\n hocuspocus.closeConnections(id)\n }\n await state.removeState(id)\n },\n liveContent(id) {\n const doc = hocuspocus.documents.get(id)\n return doc ? yDocToProsemirrorJSON(doc, COLLAB_FIELD) as JSONContent : null\n },\n async contentChanged(id) {\n const doc = hocuspocus.documents.get(id)\n if (!doc || forgotten.has(id)) return\n const tracked = loadedVersions.get(id)\n if (tracked === undefined) return // no `contentVersion`: a rewrite cannot be told from the server's own writes\n const current = await contentVersion(id)\n if (current === undefined || current === tracked) return\n await mergeRewrite(id, doc, current)\n },\n stats: () => ({ connections: hocuspocus.getConnectionsCount(), documents: hocuspocus.getDocumentsCount() }),\n async close() {\n closed = true\n if (hocuspocus.getDocumentsCount() === 0) return\n await new Promise<void>((resolve) => {\n idle.push(resolve)\n hocuspocus.closeConnections()\n hocuspocus.flushPendingStores()\n })\n },\n }\n}\n\nexport type { WebSocketLike }\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,eAAe;;AAG5B,MAAM,eAAe;CAAE,MAAM;CAAM,QAAQ;AAAe;;AAG1D,MAAM,SAAS,OAAO,eAAe;;AAqDrC,SAAS,YAAY,QAAgB,QAAqB;CACxD,MAAM,UAAU,qBAAqB,MAAM;CAC3C,MAAM,OAAO,OAAO,aAAa,QAAQ,SAAS,SAAS,QAAQ,SAAS,SAAS,UAAU,oBAAoB;CACnH,OAAO,eAAe,IAAI,KAAK;AACjC;;AAGA,SAAS,qBAAqB,UAAkC;CAC9D,OAAO,CAAC,SAAS,kBAAiB,SAAQ,gBAAgB,EAAE,cAAc,mBAAmB,KAAK,UAAU,KAAK,cAAc,GAAG,EAAE,UAAU,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAChK;;AAGA,SAAS,uBAAuB,UAAkC;CAChE,OAAO,CAAC,SAAS,kBAAiB,SAAQ,gBAAgB,EAAE,cAAc,KAAK,aAAA,gBAA4B,kBAAkB,KAAK,aAAa,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAClK;;AAGA,MAAM,UAAU,SAAiB,WAAmB,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,EAAE,OAAO,CAAC;;AAGhG,SAAS,cAAc,OAAsC;CAC3D,IAAI,CAAC,MAAM,aAAa,MAAM,IAAI,MA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F;EACA,MAAM,eAAe,IAAI;GACvB,MAAM,MAAM,WAAW,UAAU,IAAI,EAAE;GACvC,IAAI,KAAK;IACP,UAAU,IAAI,EAAE;IAChB,IAAI,mBAAmB,SAAS;IAChC,WAAW,iBAAiB,EAAE;GAChC;GACA,MAAM,MAAM,YAAY,EAAE;EAC5B;EACA,YAAY,IAAI;GACd,MAAM,MAAM,WAAW,UAAU,IAAI,EAAE;GACvC,OAAO,MAAM,sBAAsB,KAAK,YAAY,IAAmB;EACzE;EACA,MAAM,eAAe,IAAI;GACvB,MAAM,MAAM,WAAW,UAAU,IAAI,EAAE;GACvC,IAAI,CAAC,OAAO,UAAU,IAAI,EAAE,GAAG;GAC/B,MAAM,UAAU,eAAe,IAAI,EAAE;GACrC,IAAI,YAAY,KAAA,GAAW;GAC3B,MAAM,UAAU,MAAM,eAAe,EAAE;GACvC,IAAI,YAAY,KAAA,KAAa,YAAY,SAAS;GAClD,MAAM,aAAa,IAAI,KAAK,OAAO;EACrC;EACA,cAAc;GAAE,aAAa,WAAW,oBAAoB;GAAG,WAAW,WAAW,kBAAkB;EAAE;EACzG,MAAM,QAAQ;GACZ,SAAS;GACT,IAAI,WAAW,kBAAkB,MAAM,GAAG;GAC1C,MAAM,IAAI,SAAe,YAAY;IACnC,KAAK,KAAK,OAAO;IACjB,WAAW,iBAAiB;IAC5B,WAAW,mBAAmB;GAChC,CAAC;EACH;CACF;AACF"}
@@ -11,9 +11,9 @@ export declare const chatBodySchema: z.ZodObject<{
11
11
  feedback: z.ZodOptional<z.ZodArray<z.ZodObject<{
12
12
  op: z.ZodString;
13
13
  type: z.ZodEnum<{
14
- update: "update";
15
- delete: "delete";
16
14
  add: "add";
15
+ delete: "delete";
16
+ update: "update";
17
17
  convert: "convert";
18
18
  }>;
19
19
  target: z.ZodNullable<z.ZodString>;
@@ -66,7 +66,7 @@ export declare const chatBodySchema: z.ZodObject<{
66
66
  model: z.ZodString;
67
67
  apiKey: z.ZodString;
68
68
  }, z.core.$strip>]>;
69
- kinds: z.ZodArray<z.ZodObject<{
69
+ blockTypes: z.ZodArray<z.ZodObject<{
70
70
  id: z.ZodString;
71
71
  label: z.ZodString;
72
72
  purpose: z.ZodOptional<z.ZodString>;
@@ -77,9 +77,12 @@ export declare const chatBodySchema: z.ZodObject<{
77
77
  number: "number";
78
78
  date: "date";
79
79
  text: "text";
80
+ reference: "reference";
80
81
  select: "select";
81
82
  textarea: "textarea";
82
83
  multiselect: "multiselect";
84
+ bibliography: "bibliography";
85
+ derivation: "derivation";
83
86
  }>;
84
87
  options: z.ZodOptional<z.ZodArray<z.ZodObject<{
85
88
  value: z.ZodString;
@@ -97,7 +100,7 @@ export declare const chatBodySchema: z.ZodObject<{
97
100
  targets: z.ZodArray<z.ZodString>;
98
101
  structure: z.ZodEnum<{
99
102
  flat: "flat";
100
- composite: "composite";
103
+ structured: "structured";
101
104
  }>;
102
105
  }, z.core.$strip>;
103
106
  /**
@@ -105,7 +108,7 @@ export declare const chatBodySchema: z.ZodObject<{
105
108
  * `edit_document` tool. Operations pointing to IDs that are unknown or outside `scope`, an `add` without `afterId`, an
106
109
  * operation inside a block that another operation replaces or deletes, or converting into a type not in
107
110
  * `targets`, make the model retry (at most `AGENT_LIMITS.retries` times); what is still invalid then, or left out by a
108
- * corrected list, is dropped. The system prompt describes the editor's block model from `kinds`, `blocks` and `targets`. SSE like
111
+ * corrected list, is dropped. The system prompt describes the editor's block model from `blockTypes`, `blocks` and `targets`. SSE like
109
112
  * `/api/ai/generate`: `delta` (text), `ops` (`{ ops: AgentOp[], dropped: AgentOpProblem[], retries: number }`, once,
110
113
  * before `done`), `done`, `error`.
111
114
  */
@@ -116,7 +119,7 @@ export declare function completePost(ctx: AiHandlerContext, request: HandlerRequ
116
119
  export declare function generatePost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
117
120
  /**
118
121
  * The models the client may choose from (without keys) — the `models` port's `listModels` for the user, else the
119
- * server-defined presets — and the default preset id per model slot, for the client's model profiles. Requires an
122
+ * server-defined presets — and the default preset id per model role, for the client's model profiles. Requires an
120
123
  * authenticated user through the `identity` port; not rate limited, since it calls no model.
121
124
  */
122
125
  export declare function modelsGet(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
@@ -8,7 +8,9 @@ import { readBlockLines } from "../../features/ai/protocol/block-lines.js";
8
8
  import { AGENT_LIMITS, AGENT_OP_OUTCOMES, AGENT_OP_TYPES, AGENT_TOOL, agentOpTarget, agentRetryMessage, agentUnreadableProblem, checkAgentOps } from "../../features/ai/protocol/agent-ops.js";
9
9
  import { CHAT_LIMITS, documentChatMessages } from "../../features/ai/protocol/chat.js";
10
10
  import { TranscriptCleanupUnreadableError, runTranscriptCleanup, transcriptCleanupRequestSchema } from "../../integrations/transcript-ai/protocol.js";
11
+ import { PROPERTY_TYPES } from "../../core/properties.js";
11
12
  import { HttpError } from "../errors.js";
13
+ import { aiBlockTypesOf } from "../../features/composites/block-types.js";
12
14
  import { ASSET_DOCUMENT_ID, ASSET_NAME } from "../../features/media/assets.js";
13
15
  import { authenticated, enforceRateLimit, eventStream, json, port, readBody } from "./context.js";
14
16
  import { DOI_PATTERN } from "../crossref.js";
@@ -21,7 +23,7 @@ import { jsonSchema, tool } from "ai";
21
23
  const blockId = z.string().min(1).max(100);
22
24
  const opId = z.string().regex(/^op\d+$/);
23
25
  const markdown = z.string().min(1).max(AGENT_LIMITS.markdown);
24
- /** A `convert` target: a `CONVERT_TARGET_IDS` entry, `composite:<kind>`, or a host block id (`aiContext.blocks` with a conversion provider). */
26
+ /** A `convert` target: a `CONVERT_TARGET_IDS` entry, `typedBlock:<kind>`, or a host block id (`aiContext.blocks` with a conversion provider). */
25
27
  const convertTarget = z.string().min(1).max(100);
26
28
  const opSchema = z.discriminatedUnion("type", [
27
29
  z.object({
@@ -49,21 +51,14 @@ const opSchema = z.discriminatedUnion("type", [
49
51
  })
50
52
  ]);
51
53
  const label = z.string().min(1).max(100);
52
- const kindSchema = z.object({
54
+ const blockTypeSchema = z.object({
53
55
  id: z.string().regex(AI_ID_PATTERN).max(50),
54
56
  label,
55
57
  purpose: z.string().min(1).max(500).optional(),
56
58
  fields: z.array(z.object({
57
59
  key: z.string().min(1).max(50),
58
60
  label,
59
- type: z.enum([
60
- "text",
61
- "textarea",
62
- "date",
63
- "number",
64
- "select",
65
- "multiselect"
66
- ]),
61
+ type: z.enum(PROPERTY_TYPES),
67
62
  options: z.array(z.object({
68
63
  value: z.string().min(1).max(100),
69
64
  label
@@ -93,8 +88,8 @@ const chatBodySchema = z.object({
93
88
  /** Number of the first new operation (`op<n>`), so IDs stay unique across the conversation. */
94
89
  nextOp: z.number().int().min(1).max(1e6).default(1),
95
90
  model: modelRefSchema,
96
- /** The editor's composite kinds (`compositeKindsOf`), for the block model in the system prompt. */
97
- kinds: z.array(kindSchema).max(50),
91
+ /** The editor's Block types (`blockTypesOf`), for the block model in the system prompt. Ignored when the server resolves them itself (`AiHandlerContext.blockTypes`). */
92
+ blockTypes: z.array(blockTypeSchema).max(50),
98
93
  /** The editor's host blocks (`aiContext.blocks`), for the block model in the system prompt. */
99
94
  blocks: z.array(aiBlockSchema).max(50).default([]),
100
95
  /** Block types `convert` may turn a block into. */
@@ -146,13 +141,14 @@ const agentTools = { [AGENT_TOOL]: tool({
146
141
  * `edit_document` tool. Operations pointing to IDs that are unknown or outside `scope`, an `add` without `afterId`, an
147
142
  * operation inside a block that another operation replaces or deletes, or converting into a type not in
148
143
  * `targets`, make the model retry (at most `AGENT_LIMITS.retries` times); what is still invalid then, or left out by a
149
- * corrected list, is dropped. The system prompt describes the editor's block model from `kinds`, `blocks` and `targets`. SSE like
144
+ * corrected list, is dropped. The system prompt describes the editor's block model from `blockTypes`, `blocks` and `targets`. SSE like
150
145
  * `/api/ai/generate`: `delta` (text), `ops` (`{ ops: AgentOp[], dropped: AgentOpProblem[], retries: number }`, once,
151
146
  * before `done`), `done`, `error`.
152
147
  */
153
148
  async function chatPost(ctx, request) {
154
149
  const user = await enforceRateLimit(ctx, request);
155
- const { messages, document, scope, nextOp, model, kinds, blocks, targets, structure } = await readBody(request, chatBodySchema);
150
+ const { messages, document, scope, nextOp, model, blockTypes: clientBlockTypes, blocks, targets, structure } = await readBody(request, chatBodySchema);
151
+ const blockTypes = ctx.blockTypes ? aiBlockTypesOf(ctx.blockTypes) : clientBlockTypes;
156
152
  const languageModel = await ctx.ai.resolveModel(model, user);
157
153
  if (!messages.at(-1).content.trim()) throw new HttpError(400, "Nachricht fehlt");
158
154
  const lines = readBlockLines(document);
@@ -166,7 +162,7 @@ async function chatPost(ctx, request) {
166
162
  return eventStream(request, async (emit, signal) => {
167
163
  try {
168
164
  let conversation = documentChatMessages(messages, document, allowed && [...allowed], {
169
- kinds,
165
+ blockTypes,
170
166
  blocks,
171
167
  targets,
172
168
  structure
@@ -288,14 +284,14 @@ async function generatePost(ctx, request) {
288
284
  }
289
285
  /**
290
286
  * The models the client may choose from (without keys) — the `models` port's `listModels` for the user, else the
291
- * server-defined presets — and the default preset id per model slot, for the client's model profiles. Requires an
287
+ * server-defined presets — and the default preset id per model role, for the client's model profiles. Requires an
292
288
  * authenticated user through the `identity` port; not rate limited, since it calls no model.
293
289
  */
294
290
  async function modelsGet(ctx, request) {
295
291
  const user = await authenticated(ctx, request);
296
292
  return json({
297
293
  presets: await ctx.ai.listModels(user),
298
- slots: ctx.ai.slots
294
+ roles: ctx.ai.roles
299
295
  });
300
296
  }
301
297
  const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
@@ -1 +1 @@
1
- {"version":3,"file":"ai.js","names":[],"sources":["../../../src/server/handlers/ai.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto'\nimport { jsonSchema, type ModelMessage, tool } from 'ai'\nimport { z } from 'zod'\nimport {\n AGENT_LIMITS,\n AGENT_OP_OUTCOMES,\n AGENT_OP_TYPES,\n AGENT_TOOL,\n AI_ID_PATTERN,\n AI_TASKS,\n type AgentOp,\n type AgentOpProblem,\n agentOpTarget,\n agentRetryMessage,\n agentUnreadableProblem,\n aiBlockSchema,\n checkAgentOps,\n CHAT_LIMITS,\n completeBodySchema,\n documentChatMessages,\n generateBodySchema,\n generateProblem,\n type ModelAgentOp,\n modelRefSchema,\n readBlockLines,\n runCompletion,\n runGenerate,\n} from '../../features/ai/protocol'\nimport type { ExtractMethod, ExtractRequest, ExtractResponse } from '../../core/backend-types'\nimport type { CompositeMetaField } from '../../features/composites/schema'\nimport { ASSET_DOCUMENT_ID, ASSET_NAME } from '../../features/media/schema'\nimport {\n runTranscriptCleanup,\n TranscriptCleanupUnreadableError,\n transcriptCleanupRequestSchema,\n} from '../../integrations/transcript-ai/protocol'\nimport { STRUCTURE_MODES } from '../../settings'\nimport { HttpError } from '../errors'\nimport { BIBLIOGRAPHY_PAGES, bibliographyText, describeImage, extractBibliography, isScanned, joinPages, MAX_OCR_PAGES, MAX_TRANSCRIBE_BYTES, ocrPages, pdfPagesText, RasterError, transcribe, type TranscriptionResult } from '../extract'\nimport { DOI_PATTERN } from '../crossref'\nimport { openPdf } from '../pdf'\nimport { type AiHandlerContext, authenticated, enforceRateLimit, eventStream, type HandlerRequest, type HandlerResponse, json, port, readBody } from './context'\n\nconst blockId = z.string().min(1).max(100)\nconst opId = z.string().regex(/^op\\d+$/)\nconst markdown = z.string().min(1).max(AGENT_LIMITS.markdown)\n/** A `convert` target: a `CONVERT_TARGET_IDS` entry, `composite:<kind>`, or a host block id (`aiContext.blocks` with a conversion provider). */\nconst convertTarget = z.string().min(1).max(100)\n\nconst opSchema = z.discriminatedUnion('type', [\n z.object({ op: opId, type: z.literal('update'), id: blockId, markdown }),\n z.object({ op: opId, type: z.literal('delete'), id: blockId }),\n z.object({ op: opId, type: z.literal('add'), afterId: blockId.nullable(), markdown }),\n z.object({ op: opId, type: z.literal('convert'), id: blockId, to: convertTarget }),\n])\n\nconst label = z.string().min(1).max(100)\nconst kindSchema = z.object({\n // Same characters as the `::: kind` fence opener accepts.\n id: z.string().regex(AI_ID_PATTERN).max(50),\n label,\n purpose: z.string().min(1).max(500).optional(),\n fields: z.array(z.object({\n key: z.string().min(1).max(50),\n label,\n type: z.enum(['text', 'textarea', 'date', 'number', 'select', 'multiselect'] as const satisfies readonly CompositeMetaField['type'][]),\n options: z.array(z.object({ value: z.string().min(1).max(100), label })).max(50).optional(),\n })).max(20),\n})\n\nconst messageSchema = z.discriminatedUnion('role', [\n z.object({\n role: z.literal('user'),\n content: z.string().min(1).max(CHAT_LIMITS.message),\n feedback: z.array(z.object({ op: opId, type: z.enum(AGENT_OP_TYPES), target: blockId.nullable(), outcome: z.enum(AGENT_OP_OUTCOMES) })).max(500).optional(),\n }),\n z.object({\n role: z.literal('assistant'),\n content: z.string().max(CHAT_LIMITS.message),\n ops: z.array(opSchema).max(AGENT_LIMITS.ops).optional(),\n dropped: z.number().int().min(0).max(1000).optional(),\n }).refine(m => m.content || m.ops?.length || m.dropped, 'Leere Antwort im Verlauf'),\n])\n\nexport const chatBodySchema = z.object({\n messages: z.array(messageSchema).min(1).max(CHAT_LIMITS.messages).refine(messages => messages.at(-1)!.role === 'user', 'Die letzte Nachricht muss von der Nutzerin bzw. dem Nutzer sein'),\n document: z.string().max(CHAT_LIMITS.document),\n /** Block IDs edits are limited to (the selected blocks); null or missing: the whole document. */\n scope: z.array(blockId).min(1).max(AGENT_LIMITS.scope).nullish(),\n /** Number of the first new operation (`op<n>`), so IDs stay unique across the conversation. */\n nextOp: z.number().int().min(1).max(1_000_000).default(1),\n model: modelRefSchema,\n /** The editor's composite kinds (`compositeKindsOf`), for the block model in the system prompt. */\n kinds: z.array(kindSchema).max(50),\n /** The editor's host blocks (`aiContext.blocks`), for the block model in the system prompt. */\n blocks: z.array(aiBlockSchema).max(50).default([]),\n /** Block types `convert` may turn a block into. */\n targets: z.array(convertTarget).max(100),\n /** The user's preferred structure of new content (settings `blocks.structure`). */\n structure: z.enum(STRUCTURE_MODES),\n})\n\n/** `edit_document`: deliberately loose, so malformed calls reach `checkAgentOps` and get a precise retry message. */\nconst agentTools = {\n [AGENT_TOOL]: tool({\n description: 'Schlägt Änderungen am Dokument vor. Jede Operation wird der Nutzerin bzw. dem Nutzer im Dokument zur Prüfung angezeigt.',\n inputSchema: jsonSchema<{ ops: unknown[] }>({\n type: 'object',\n properties: {\n ops: {\n type: 'array',\n description: 'Die Operationen in Dokumentreihenfolge.',\n items: {\n type: 'object',\n properties: {\n type: { type: 'string', enum: [...AGENT_OP_TYPES], description: 'update: Blockinhalt ersetzen; delete: Block löschen; add: Blöcke einfügen; convert: Blocktyp ändern.' },\n id: { type: 'string', description: 'update/delete/convert: ID des Blocks aus dem Dokument.' },\n afterId: { type: ['string', 'null'], description: 'add (Pflicht): ID des Blocks, nach dem eingefügt wird; für den Dokumentanfang ausdrücklich null.' },\n markdown: { type: 'string', description: 'update/add: der neue Inhalt als Markdown, ohne Block-ID.' },\n to: { type: 'string', description: 'convert: der neue Blocktyp, einer der im Systemprompt erlaubten Werte (z. B. paragraph, heading2, composite:task).' },\n },\n required: ['type'],\n },\n },\n },\n required: ['ops'],\n }),\n }),\n}\n\n/**\n * Document chat: answers the last message of `messages` about `document`, or proposes edit operations through the\n * `edit_document` tool. Operations pointing to IDs that are unknown or outside `scope`, an `add` without `afterId`, an\n * operation inside a block that another operation replaces or deletes, or converting into a type not in\n * `targets`, make the model retry (at most `AGENT_LIMITS.retries` times); what is still invalid then, or left out by a\n * corrected list, is dropped. The system prompt describes the editor's block model from `kinds`, `blocks` and `targets`. SSE like\n * `/api/ai/generate`: `delta` (text), `ops` (`{ ops: AgentOp[], dropped: AgentOpProblem[], retries: number }`, once,\n * before `done`), `done`, `error`.\n */\nexport async function chatPost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { messages, document, scope, nextOp, model, kinds, blocks, targets, structure } = await readBody(request, chatBodySchema)\n // Unknown preset or missing key must fail as a plain JSON error before the SSE response starts.\n const languageModel = await ctx.ai.resolveModel(model, user)\n if (!messages.at(-1)!.content.trim()) throw new HttpError(400, 'Nachricht fehlt')\n\n const lines = readBlockLines(document)\n const allowed = scope ? new Set(scope.filter(id => lines.ids.has(id))) : null\n if (allowed && !allowed.size) throw new HttpError(400, 'Die Auswahl enthält keine Blöcke des Dokuments')\n const context = { lines, allowed, targets: new Set(targets) }\n\n return eventStream(request, async (emit, signal) => {\n try {\n let conversation: ModelMessage[] = documentChatMessages(messages, document, allowed && [...allowed], { kinds, blocks, targets, structure })\n let answered = false\n let result: { valid: ModelAgentOp[], problems: AgentOpProblem[] } | null = null\n // Problems of attempts that were retried: an operation the corrected list leaves out counts as dropped too.\n const retried: AgentOpProblem[] = []\n let retries = 0\n for (let attempt = 0; attempt <= AGENT_LIMITS.retries; attempt++) {\n const calls: { toolCallId: string, input: unknown, invalid: boolean }[] = []\n let text = ''\n for await (const part of ctx.ai.streamChatTurn({\n model: languageModel,\n messages: conversation,\n tools: agentTools,\n // Retries only correct the operations: no second answer text.\n toolChoice: attempt ? { type: 'tool', toolName: AGENT_TOOL } : 'auto',\n signal,\n })) {\n if (part.type === 'tool-call') {\n if (part.toolName === AGENT_TOOL) calls.push(part)\n }\n else if (!attempt) {\n text += part.text\n answered = true\n emit('delta', JSON.stringify({ text: part.text }))\n }\n }\n if (!calls.length) break\n\n const unreadable = calls.some(call => call.invalid || !Array.isArray((call.input as { ops?: unknown } | null)?.ops))\n const raw = calls.flatMap(call => (call.input as { ops?: unknown } | null)?.ops).filter(op => op !== undefined)\n const checked = checkAgentOps(raw, context)\n if (unreadable) checked.problems.unshift(agentUnreadableProblem())\n result = checked\n if (!checked.problems.length || attempt === AGENT_LIMITS.retries) break\n\n retried.push(...checked.problems)\n retries++\n const retry = agentRetryMessage(checked.problems, !!allowed)\n conversation = [\n ...conversation,\n {\n role: 'assistant',\n content: [\n ...(text ? [{ type: 'text' as const, text }] : []),\n ...calls.map(call => ({ type: 'tool-call' as const, toolCallId: call.toolCallId, toolName: AGENT_TOOL, input: call.input ?? {} })),\n ],\n },\n { role: 'tool', content: calls.map(call => ({ type: 'tool-result' as const, toolCallId: call.toolCallId, toolName: AGENT_TOOL, output: { type: 'text' as const, value: retry } })) },\n ]\n }\n\n if (result) {\n const ops: AgentOp[] = result.valid.map((op, i) => ({ ...op, op: `op${nextOp + i}` }))\n const targets = new Set(ops.map(op => agentOpTarget(op)))\n const dropped = [...result.problems]\n for (const problem of retried) {\n if (problem.id !== null && !targets.has(problem.id) && !dropped.some(d => d.id === problem.id && d.type === problem.type)) dropped.push(problem)\n }\n if (!answered && !ops.length) {\n emit('delta', JSON.stringify({ text: 'Ich konnte keine gültigen Änderungen vorschlagen.' }))\n }\n emit('ops', JSON.stringify({ ops, dropped, retries }))\n }\n emit('done', '{}')\n \n }\n catch (error) {\n if (!signal.aborted) {\n const { statusMessage, message } = error as { statusMessage?: string, message?: string }\n emit('error', JSON.stringify({ message: statusMessage ?? message ?? 'Unbekannter Fehler' }))\n }\n }\n })\n}\n\n// The body schemas live with the protocol (the browser-direct adapter validates with them too); the handlers keep exporting them.\nexport { completeBodySchema, generateBodySchema }\n\n/** Short inline continuation (ghost text) of the text before the caret. Plain JSON: `{ text }`, empty when nothing fits. */\nexport async function completePost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { before, model } = await readBody(request, completeBodySchema)\n const languageModel = await ctx.ai.resolveModel(model, user)\n\n // Typing on the client aborts its fetch; stop the upstream request with it.\n const abort = new AbortController()\n request.signal?.addEventListener('abort', () => abort.abort(), { once: true })\n return json({ text: await runCompletion(before, (messages, signal) => ctx.ai.streamChat({ model: languageModel, messages, signal }), abort.signal) })\n}\n\n/** Streams one text task (rewrite, translate, generate, …) as SSE: `delta` (`{ text }`), `done`, `error` (`{ message }`). */\nexport async function generatePost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { task: taskId, model, ...input } = await readBody(request, generateBodySchema)\n // Unknown preset or missing key must fail as a plain JSON error before the SSE response starts.\n const languageModel = await ctx.ai.resolveModel(model, user)\n const task = AI_TASKS[taskId]\n const problem = generateProblem(task, input)\n if (problem) throw new HttpError(400, problem)\n const users = task.needsUsers ? (await port(ctx, 'directory').listUsers()).map(u => u.username) : undefined\n\n return eventStream(request, async (emit, signal) => {\n for await (const { event, data } of runGenerate(task, input, users, (messages, streamSignal) => ctx.ai.streamChat({ model: languageModel, messages, signal: streamSignal }), signal)) {\n emit(event, JSON.stringify(data))\n }\n })\n}\n\n/**\n * The models the client may choose from (without keys) — the `models` port's `listModels` for the user, else the\n * server-defined presets — and the default preset id per model slot, for the client's model profiles. Requires an\n * authenticated user through the `identity` port; not rate limited, since it calls no model.\n */\nexport async function modelsGet(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await authenticated(ctx, request)\n return json({ presets: await ctx.ai.listModels(user), slots: ctx.ai.slots })\n}\n\nconst sha256Hex = (data: string | Uint8Array): string => createHash('sha256').update(data).digest('hex')\n\n/** PDF pages read by `pdf-text` and `ocr` unless the request caps them lower. */\nconst DEFAULT_MAX_PAGES = 200\n\n/** Body schema of `extractPost`. */\nexport const extractBodySchema = z.object({\n documentId: z.string().regex(ASSET_DOCUMENT_ID),\n name: z.string().regex(ASSET_NAME).optional(),\n method: z.enum(['auto', 'transcription', 'pdf-text', 'ocr', 'description', 'bibliography']),\n model: modelRefSchema,\n bibliography: z.boolean().optional(),\n doi: z.string().regex(DOI_PATTERN).optional(),\n maxPages: z.number().int().min(1).max(500).default(DEFAULT_MAX_PAGES),\n}).refine(body => body.name !== undefined || (body.method === 'bibliography' && body.doi !== undefined), {\n message: 'name fehlt (nur eine Literaturabfrage mit DOI braucht keine Datei)',\n path: ['name'],\n}) satisfies z.ZodType<ExtractRequest>\n\n/** The method an `ExtractRequest` runs for an asset of `mimeType`: `auto` picks by type; 415 when the type does not fit the method. */\nfunction extractMethodOf(requested: ExtractMethod, mimeType: string, hasDoi: boolean): ExtractResponse['method'] {\n const audioVideo = /^(?:audio|video)\\//.test(mimeType)\n const image = mimeType.startsWith('image/')\n const pdf = mimeType === 'application/pdf'\n const fits: Record<ExtractMethod, boolean> = {\n 'auto': audioVideo || image || pdf,\n 'transcription': audioVideo,\n 'description': image,\n 'pdf-text': pdf,\n 'ocr': pdf,\n // A given DOI needs no document text, so any asset can stand for the work.\n 'bibliography': pdf || hasDoi,\n }\n if (!fits[requested]) throw new HttpError(415, `Dateityp ${mimeType} wird für diese Auswertung nicht unterstützt`)\n if (requested !== 'auto') return requested\n if (audioVideo) return 'transcription'\n return image ? 'description' : 'pdf-text'\n}\n\n/**\n * Turns a stored asset into readable content (`ExtractRequest` → `ExtractResponse`): audio/video into a transcription\n * with segment timestamps, a PDF into its text per page (OCR through the model when it has no text layer), an image\n * into a description, bibliographic data from Crossref or the model. The raw Markdown is stored as an asset of the same\n * document (`output`), with the SHA-256 of input and output. Errors: 404 unknown asset, 415 type not supported, 413\n * oversize audio, 422 unreadable PDF, 501 transcription or OCR unavailable, 502 upstream failure.\n */\nexport async function extractPost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const body = await readBody(request, extractBodySchema)\n if (body.name === undefined) {\n // Only a DOI lookup comes without a file (the schema allows nothing else): no asset, no output, empty hashes.\n const { bib, warnings } = await extractBibliography({ doi: body.doi, text: '', resolveModel: () => ctx.ai.resolveModel(body.model, user), signal: request.signal })\n return json({ method: 'bibliography', markdown: '', bib, inputHash: '', outputHash: sha256Hex(''), output: null, warnings } satisfies ExtractResponse)\n }\n const assets = port(ctx, 'assets')\n const asset = await assets.loadAsset(body.documentId, body.name)\n if (!asset) throw new HttpError(404, 'Datei nicht gefunden')\n const inputHash = sha256Hex(asset.data)\n let method = extractMethodOf(body.method, asset.record.mimeType, body.doi !== undefined)\n // Closing the page aborts the client's fetch; the upstream requests stop with it.\n const { signal } = request\n const resolveModel = () => ctx.ai.resolveModel(body.model, user)\n\n const warnings: string[] = []\n let markdown = ''\n let model: string | undefined\n let segments: TranscriptionResult['segments']\n let bib: ExtractResponse['bib']\n\n if (method === 'transcription') {\n const config = ctx.ai.transcription\n if (!config?.endpoint || !config.model) throw new HttpError(501, 'Transkription nicht konfiguriert')\n if (asset.data.byteLength > MAX_TRANSCRIBE_BYTES) throw new HttpError(413, `Datei ist größer als ${MAX_TRANSCRIBE_BYTES / 1024 / 1024} MB`)\n ;({ markdown, segments } = await transcribe(config, asset, signal))\n model = config.model\n }\n else if (method === 'description') {\n markdown = await describeImage(await resolveModel(), asset.data, asset.record.mimeType, signal)\n }\n else if (asset.record.mimeType !== 'application/pdf') {\n // `bibliography` of a non-PDF asset: only reachable with a DOI.\n const found = await extractBibliography({ doi: body.doi, text: '', resolveModel, signal })\n bib = found.bib\n warnings.push(...found.warnings)\n }\n else {\n const pdf = await openPdf(asset.data)\n try {\n if (method === 'bibliography') {\n const pages = await pdfPagesText(pdf, Math.min(pdf.pageCount, BIBLIOGRAPHY_PAGES), signal)\n const found = await extractBibliography({ doi: body.doi, text: bibliographyText(pages), resolveModel, signal })\n bib = found.bib\n warnings.push(...found.warnings)\n }\n else {\n const count = Math.min(pdf.pageCount, body.maxPages)\n if (pdf.pageCount > count) warnings.push('pages-truncated')\n let pages = await pdfPagesText(pdf, count, signal)\n if (body.method === 'auto' && isScanned(pages)) method = 'ocr'\n if (method === 'ocr') {\n // One vision call per page: the OCR reads fewer pages than the text layer would.\n const ocrCount = Math.min(count, MAX_OCR_PAGES)\n try {\n pages = await ocrPages(pdf, ocrCount, resolveModel, signal)\n if (ocrCount < count) warnings.push('ocr-truncated')\n }\n catch (error) {\n if (!(error instanceof RasterError)) throw error\n // Pages cannot be rendered here: keep what the text layer has.\n if (!pages.some(Boolean)) throw new HttpError(501, 'OCR nicht verfügbar')\n warnings.push('ocr-unavailable')\n method = 'pdf-text'\n }\n }\n markdown = joinPages(pages)\n if (body.bibliography) {\n try {\n const found = await extractBibliography({ doi: body.doi, text: bibliographyText(pages), resolveModel, signal })\n bib = found.bib\n warnings.push(...found.warnings)\n }\n catch (error) {\n // The text is the result; missing bibliographic data must not lose it.\n if (signal?.aborted) throw error\n warnings.push('bibliography-failed')\n }\n }\n }\n }\n finally {\n await pdf.close()\n }\n }\n\n const outputHash = sha256Hex(markdown)\n let output: string | null = null\n if (method !== 'bibliography' && markdown) {\n const data = Buffer.from(markdown, 'utf8')\n output = `${randomUUID()}.md`\n await assets.storeAsset(body.documentId, {\n name: output,\n filename: `${asset.record.filename}.${method}.md`.slice(0, 255),\n mimeType: 'text/markdown',\n size: data.byteLength,\n createdAt: new Date().toISOString(),\n sha256: outputHash,\n data,\n })\n }\n return json({ method, markdown, ...(segments && { segments }), ...(bib && { bib }), ...(model && { model }), inputHash, outputHash, output, warnings } satisfies ExtractResponse)\n}\n\n/** Body schema of `transcriptCleanupPost`. */\nexport const transcriptCleanupBodySchema = transcriptCleanupRequestSchema\n\n/**\n * Cleans transcript segments (filler words, punctuation, casing, fragmented sentences) without touching speakers or\n * order: the model only returns a new text per segment ID. Plain JSON: `{ cleaned, failed }`.\n */\nexport async function transcriptCleanupPost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { segments, model } = await readBody(request, transcriptCleanupBodySchema)\n const languageModel = await ctx.ai.resolveModel(model, user)\n\n // Closing the menu or the page aborts the client's fetch; stop the upstream requests with it.\n const abort = new AbortController()\n request.signal?.addEventListener('abort', () => abort.abort(), { once: true })\n try {\n return json(await runTranscriptCleanup(segments, (messages, signal) => ctx.ai.streamChat({ model: languageModel, messages, signal }), abort.signal))\n }\n catch (error) {\n throw error instanceof TranscriptCleanupUnreadableError ? new HttpError(502, error.message) : error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AACzC,MAAM,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,S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IAAI;CAG3D,MAAM,QAAQ,IAAI,gBAAgB;CAClC,QAAQ,QAAQ,iBAAiB,eAAe,MAAM,MAAM,GAAG,EAAE,MAAM,KAAK,CAAC;CAC7E,IAAI;EACF,OAAO,KAAK,MAAM,qBAAqB,WAAW,UAAU,WAAW,IAAI,GAAG,WAAW;GAAE,OAAO;GAAe;GAAU;EAAO,CAAC,GAAG,MAAM,MAAM,CAAC;CACrJ,SACO,OAAO;EACZ,MAAM,iBAAiB,mCAAmC,IAAI,UAAU,KAAK,MAAM,OAAO,IAAI;CAChG;AACF"}
1
+ {"version":3,"file":"ai.js","names":[],"sources":["../../../src/server/handlers/ai.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto'\nimport { jsonSchema, type ModelMessage, tool } from 'ai'\nimport { z } from 'zod'\nimport {\n AGENT_LIMITS,\n AGENT_OP_OUTCOMES,\n AGENT_OP_TYPES,\n AGENT_TOOL,\n AI_ID_PATTERN,\n AI_TASKS,\n type AgentOp,\n type AgentOpProblem,\n agentOpTarget,\n agentRetryMessage,\n agentUnreadableProblem,\n aiBlockSchema,\n checkAgentOps,\n CHAT_LIMITS,\n completeBodySchema,\n documentChatMessages,\n generateBodySchema,\n generateProblem,\n type ModelAgentOp,\n modelRefSchema,\n readBlockLines,\n runCompletion,\n runGenerate,\n} from '../../features/ai/protocol'\nimport type { ExtractMethod, ExtractRequest, ExtractResponse } from '../../core/backend-types'\nimport { PROPERTY_TYPES } from '../../core/properties'\nimport { aiBlockTypesOf } from '../../features/composites/schema'\nimport { ASSET_DOCUMENT_ID, ASSET_NAME } from '../../features/media/schema'\nimport {\n runTranscriptCleanup,\n TranscriptCleanupUnreadableError,\n transcriptCleanupRequestSchema,\n} from '../../integrations/transcript-ai/protocol'\nimport { STRUCTURE_MODES } from '../../settings'\nimport { HttpError } from '../errors'\nimport { BIBLIOGRAPHY_PAGES, bibliographyText, describeImage, extractBibliography, isScanned, joinPages, MAX_OCR_PAGES, MAX_TRANSCRIBE_BYTES, ocrPages, pdfPagesText, RasterError, transcribe, type TranscriptionResult } from '../extract'\nimport { DOI_PATTERN } from '../crossref'\nimport { openPdf } from '../pdf'\nimport { type AiHandlerContext, authenticated, enforceRateLimit, eventStream, type HandlerRequest, type HandlerResponse, json, port, readBody } from './context'\n\nconst blockId = z.string().min(1).max(100)\nconst opId = z.string().regex(/^op\\d+$/)\nconst markdown = z.string().min(1).max(AGENT_LIMITS.markdown)\n/** A `convert` target: a `CONVERT_TARGET_IDS` entry, `typedBlock:<kind>`, or a host block id (`aiContext.blocks` with a conversion provider). */\nconst convertTarget = z.string().min(1).max(100)\n\nconst opSchema = z.discriminatedUnion('type', [\n z.object({ op: opId, type: z.literal('update'), id: blockId, markdown }),\n z.object({ op: opId, type: z.literal('delete'), id: blockId }),\n z.object({ op: opId, type: z.literal('add'), afterId: blockId.nullable(), markdown }),\n z.object({ op: opId, type: z.literal('convert'), id: blockId, to: convertTarget }),\n])\n\nconst label = z.string().min(1).max(100)\nconst blockTypeSchema = z.object({\n // Same characters as the `::: <Block type>` fence opener accepts.\n id: z.string().regex(AI_ID_PATTERN).max(50),\n label,\n purpose: z.string().min(1).max(500).optional(),\n fields: z.array(z.object({\n key: z.string().min(1).max(50),\n label,\n type: z.enum(PROPERTY_TYPES),\n options: z.array(z.object({ value: z.string().min(1).max(100), label })).max(50).optional(),\n })).max(20),\n})\n\nconst messageSchema = z.discriminatedUnion('role', [\n z.object({\n role: z.literal('user'),\n content: z.string().min(1).max(CHAT_LIMITS.message),\n feedback: z.array(z.object({ op: opId, type: z.enum(AGENT_OP_TYPES), target: blockId.nullable(), outcome: z.enum(AGENT_OP_OUTCOMES) })).max(500).optional(),\n }),\n z.object({\n role: z.literal('assistant'),\n content: z.string().max(CHAT_LIMITS.message),\n ops: z.array(opSchema).max(AGENT_LIMITS.ops).optional(),\n dropped: z.number().int().min(0).max(1000).optional(),\n }).refine(m => m.content || m.ops?.length || m.dropped, 'Leere Antwort im Verlauf'),\n])\n\nexport const chatBodySchema = z.object({\n messages: z.array(messageSchema).min(1).max(CHAT_LIMITS.messages).refine(messages => messages.at(-1)!.role === 'user', 'Die letzte Nachricht muss von der Nutzerin bzw. dem Nutzer sein'),\n document: z.string().max(CHAT_LIMITS.document),\n /** Block IDs edits are limited to (the selected blocks); null or missing: the whole document. */\n scope: z.array(blockId).min(1).max(AGENT_LIMITS.scope).nullish(),\n /** Number of the first new operation (`op<n>`), so IDs stay unique across the conversation. */\n nextOp: z.number().int().min(1).max(1_000_000).default(1),\n model: modelRefSchema,\n /** The editor's Block types (`blockTypesOf`), for the block model in the system prompt. Ignored when the server resolves them itself (`AiHandlerContext.blockTypes`). */\n blockTypes: z.array(blockTypeSchema).max(50),\n /** The editor's host blocks (`aiContext.blocks`), for the block model in the system prompt. */\n blocks: z.array(aiBlockSchema).max(50).default([]),\n /** Block types `convert` may turn a block into. */\n targets: z.array(convertTarget).max(100),\n /** The user's preferred structure of new content (settings `blocks.structure`). */\n structure: z.enum(STRUCTURE_MODES),\n})\n\n/** `edit_document`: deliberately loose, so malformed calls reach `checkAgentOps` and get a precise retry message. */\nconst agentTools = {\n [AGENT_TOOL]: tool({\n description: 'Schlägt Änderungen am Dokument vor. Jede Operation wird der Nutzerin bzw. dem Nutzer im Dokument zur Prüfung angezeigt.',\n inputSchema: jsonSchema<{ ops: unknown[] }>({\n type: 'object',\n properties: {\n ops: {\n type: 'array',\n description: 'Die Operationen in Dokumentreihenfolge.',\n items: {\n type: 'object',\n properties: {\n type: { type: 'string', enum: [...AGENT_OP_TYPES], description: 'update: Blockinhalt ersetzen; delete: Block löschen; add: Blöcke einfügen; convert: Blocktyp ändern.' },\n id: { type: 'string', description: 'update/delete/convert: ID des Blocks aus dem Dokument.' },\n afterId: { type: ['string', 'null'], description: 'add (Pflicht): ID des Blocks, nach dem eingefügt wird; für den Dokumentanfang ausdrücklich null.' },\n markdown: { type: 'string', description: 'update/add: der neue Inhalt als Markdown, ohne Block-ID.' },\n to: { type: 'string', description: 'convert: der neue Blocktyp, einer der im Systemprompt erlaubten Werte (z. B. paragraph, heading2, composite:task).' },\n },\n required: ['type'],\n },\n },\n },\n required: ['ops'],\n }),\n }),\n}\n\n/**\n * Document chat: answers the last message of `messages` about `document`, or proposes edit operations through the\n * `edit_document` tool. Operations pointing to IDs that are unknown or outside `scope`, an `add` without `afterId`, an\n * operation inside a block that another operation replaces or deletes, or converting into a type not in\n * `targets`, make the model retry (at most `AGENT_LIMITS.retries` times); what is still invalid then, or left out by a\n * corrected list, is dropped. The system prompt describes the editor's block model from `blockTypes`, `blocks` and `targets`. SSE like\n * `/api/ai/generate`: `delta` (text), `ops` (`{ ops: AgentOp[], dropped: AgentOpProblem[], retries: number }`, once,\n * before `done`), `done`, `error`.\n */\nexport async function chatPost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { messages, document, scope, nextOp, model, blockTypes: clientBlockTypes, blocks, targets, structure } = await readBody(request, chatBodySchema)\n const blockTypes = ctx.blockTypes ? aiBlockTypesOf(ctx.blockTypes) : clientBlockTypes\n // Unknown preset or missing key must fail as a plain JSON error before the SSE response starts.\n const languageModel = await ctx.ai.resolveModel(model, user)\n if (!messages.at(-1)!.content.trim()) throw new HttpError(400, 'Nachricht fehlt')\n\n const lines = readBlockLines(document)\n const allowed = scope ? new Set(scope.filter(id => lines.ids.has(id))) : null\n if (allowed && !allowed.size) throw new HttpError(400, 'Die Auswahl enthält keine Blöcke des Dokuments')\n const context = { lines, allowed, targets: new Set(targets) }\n\n return eventStream(request, async (emit, signal) => {\n try {\n let conversation: ModelMessage[] = documentChatMessages(messages, document, allowed && [...allowed], { blockTypes, blocks, targets, structure })\n let answered = false\n let result: { valid: ModelAgentOp[], problems: AgentOpProblem[] } | null = null\n // Problems of attempts that were retried: an operation the corrected list leaves out counts as dropped too.\n const retried: AgentOpProblem[] = []\n let retries = 0\n for (let attempt = 0; attempt <= AGENT_LIMITS.retries; attempt++) {\n const calls: { toolCallId: string, input: unknown, invalid: boolean }[] = []\n let text = ''\n for await (const part of ctx.ai.streamChatTurn({\n model: languageModel,\n messages: conversation,\n tools: agentTools,\n // Retries only correct the operations: no second answer text.\n toolChoice: attempt ? { type: 'tool', toolName: AGENT_TOOL } : 'auto',\n signal,\n })) {\n if (part.type === 'tool-call') {\n if (part.toolName === AGENT_TOOL) calls.push(part)\n }\n else if (!attempt) {\n text += part.text\n answered = true\n emit('delta', JSON.stringify({ text: part.text }))\n }\n }\n if (!calls.length) break\n\n const unreadable = calls.some(call => call.invalid || !Array.isArray((call.input as { ops?: unknown } | null)?.ops))\n const raw = calls.flatMap(call => (call.input as { ops?: unknown } | null)?.ops).filter(op => op !== undefined)\n const checked = checkAgentOps(raw, context)\n if (unreadable) checked.problems.unshift(agentUnreadableProblem())\n result = checked\n if (!checked.problems.length || attempt === AGENT_LIMITS.retries) break\n\n retried.push(...checked.problems)\n retries++\n const retry = agentRetryMessage(checked.problems, !!allowed)\n conversation = [\n ...conversation,\n {\n role: 'assistant',\n content: [\n ...(text ? [{ type: 'text' as const, text }] : []),\n ...calls.map(call => ({ type: 'tool-call' as const, toolCallId: call.toolCallId, toolName: AGENT_TOOL, input: call.input ?? {} })),\n ],\n },\n { role: 'tool', content: calls.map(call => ({ type: 'tool-result' as const, toolCallId: call.toolCallId, toolName: AGENT_TOOL, output: { type: 'text' as const, value: retry } })) },\n ]\n }\n\n if (result) {\n const ops: AgentOp[] = result.valid.map((op, i) => ({ ...op, op: `op${nextOp + i}` }))\n const targets = new Set(ops.map(op => agentOpTarget(op)))\n const dropped = [...result.problems]\n for (const problem of retried) {\n if (problem.id !== null && !targets.has(problem.id) && !dropped.some(d => d.id === problem.id && d.type === problem.type)) dropped.push(problem)\n }\n if (!answered && !ops.length) {\n emit('delta', JSON.stringify({ text: 'Ich konnte keine gültigen Änderungen vorschlagen.' }))\n }\n emit('ops', JSON.stringify({ ops, dropped, retries }))\n }\n emit('done', '{}')\n \n }\n catch (error) {\n if (!signal.aborted) {\n const { statusMessage, message } = error as { statusMessage?: string, message?: string }\n emit('error', JSON.stringify({ message: statusMessage ?? message ?? 'Unbekannter Fehler' }))\n }\n }\n })\n}\n\n// The body schemas live with the protocol (the browser-direct adapter validates with them too); the handlers keep exporting them.\nexport { completeBodySchema, generateBodySchema }\n\n/** Short inline continuation (ghost text) of the text before the caret. Plain JSON: `{ text }`, empty when nothing fits. */\nexport async function completePost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { before, model } = await readBody(request, completeBodySchema)\n const languageModel = await ctx.ai.resolveModel(model, user)\n\n // Typing on the client aborts its fetch; stop the upstream request with it.\n const abort = new AbortController()\n request.signal?.addEventListener('abort', () => abort.abort(), { once: true })\n return json({ text: await runCompletion(before, (messages, signal) => ctx.ai.streamChat({ model: languageModel, messages, signal }), abort.signal) })\n}\n\n/** Streams one text task (rewrite, translate, generate, …) as SSE: `delta` (`{ text }`), `done`, `error` (`{ message }`). */\nexport async function generatePost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { task: taskId, model, ...input } = await readBody(request, generateBodySchema)\n // Unknown preset or missing key must fail as a plain JSON error before the SSE response starts.\n const languageModel = await ctx.ai.resolveModel(model, user)\n const task = AI_TASKS[taskId]\n const problem = generateProblem(task, input)\n if (problem) throw new HttpError(400, problem)\n const users = task.needsUsers ? (await port(ctx, 'directory').listUsers()).map(u => u.username) : undefined\n\n return eventStream(request, async (emit, signal) => {\n for await (const { event, data } of runGenerate(task, input, users, (messages, streamSignal) => ctx.ai.streamChat({ model: languageModel, messages, signal: streamSignal }), signal)) {\n emit(event, JSON.stringify(data))\n }\n })\n}\n\n/**\n * The models the client may choose from (without keys) — the `models` port's `listModels` for the user, else the\n * server-defined presets — and the default preset id per model role, for the client's model profiles. Requires an\n * authenticated user through the `identity` port; not rate limited, since it calls no model.\n */\nexport async function modelsGet(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await authenticated(ctx, request)\n return json({ presets: await ctx.ai.listModels(user), roles: ctx.ai.roles })\n}\n\nconst sha256Hex = (data: string | Uint8Array): string => createHash('sha256').update(data).digest('hex')\n\n/** PDF pages read by `pdf-text` and `ocr` unless the request caps them lower. */\nconst DEFAULT_MAX_PAGES = 200\n\n/** Body schema of `extractPost`. */\nexport const extractBodySchema = z.object({\n documentId: z.string().regex(ASSET_DOCUMENT_ID),\n name: z.string().regex(ASSET_NAME).optional(),\n method: z.enum(['auto', 'transcription', 'pdf-text', 'ocr', 'description', 'bibliography']),\n model: modelRefSchema,\n bibliography: z.boolean().optional(),\n doi: z.string().regex(DOI_PATTERN).optional(),\n maxPages: z.number().int().min(1).max(500).default(DEFAULT_MAX_PAGES),\n}).refine(body => body.name !== undefined || (body.method === 'bibliography' && body.doi !== undefined), {\n message: 'name fehlt (nur eine Literaturabfrage mit DOI braucht keine Datei)',\n path: ['name'],\n}) satisfies z.ZodType<ExtractRequest>\n\n/** The method an `ExtractRequest` runs for an asset of `mimeType`: `auto` picks by type; 415 when the type does not fit the method. */\nfunction extractMethodOf(requested: ExtractMethod, mimeType: string, hasDoi: boolean): ExtractResponse['method'] {\n const audioVideo = /^(?:audio|video)\\//.test(mimeType)\n const image = mimeType.startsWith('image/')\n const pdf = mimeType === 'application/pdf'\n const fits: Record<ExtractMethod, boolean> = {\n 'auto': audioVideo || image || pdf,\n 'transcription': audioVideo,\n 'description': image,\n 'pdf-text': pdf,\n 'ocr': pdf,\n // A given DOI needs no document text, so any asset can stand for the work.\n 'bibliography': pdf || hasDoi,\n }\n if (!fits[requested]) throw new HttpError(415, `Dateityp ${mimeType} wird für diese Auswertung nicht unterstützt`)\n if (requested !== 'auto') return requested\n if (audioVideo) return 'transcription'\n return image ? 'description' : 'pdf-text'\n}\n\n/**\n * Turns a stored asset into readable content (`ExtractRequest` → `ExtractResponse`): audio/video into a transcription\n * with segment timestamps, a PDF into its text per page (OCR through the model when it has no text layer), an image\n * into a description, bibliographic data from Crossref or the model. The raw Markdown is stored as an asset of the same\n * document (`output`), with the SHA-256 of input and output. Errors: 404 unknown asset, 415 type not supported, 413\n * oversize audio, 422 unreadable PDF, 501 transcription or OCR unavailable, 502 upstream failure.\n */\nexport async function extractPost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const body = await readBody(request, extractBodySchema)\n if (body.name === undefined) {\n // Only a DOI lookup comes without a file (the schema allows nothing else): no asset, no output, empty hashes.\n const { bib, warnings } = await extractBibliography({ doi: body.doi, text: '', resolveModel: () => ctx.ai.resolveModel(body.model, user), signal: request.signal })\n return json({ method: 'bibliography', markdown: '', bib, inputHash: '', outputHash: sha256Hex(''), output: null, warnings } satisfies ExtractResponse)\n }\n const assets = port(ctx, 'assets')\n const asset = await assets.loadAsset(body.documentId, body.name)\n if (!asset) throw new HttpError(404, 'Datei nicht gefunden')\n const inputHash = sha256Hex(asset.data)\n let method = extractMethodOf(body.method, asset.record.mimeType, body.doi !== undefined)\n // Closing the page aborts the client's fetch; the upstream requests stop with it.\n const { signal } = request\n const resolveModel = () => ctx.ai.resolveModel(body.model, user)\n\n const warnings: string[] = []\n let markdown = ''\n let model: string | undefined\n let segments: TranscriptionResult['segments']\n let bib: ExtractResponse['bib']\n\n if (method === 'transcription') {\n const config = ctx.ai.transcription\n if (!config?.endpoint || !config.model) throw new HttpError(501, 'Transkription nicht konfiguriert')\n if (asset.data.byteLength > MAX_TRANSCRIBE_BYTES) throw new HttpError(413, `Datei ist größer als ${MAX_TRANSCRIBE_BYTES / 1024 / 1024} MB`)\n ;({ markdown, segments } = await transcribe(config, asset, signal))\n model = config.model\n }\n else if (method === 'description') {\n markdown = await describeImage(await resolveModel(), asset.data, asset.record.mimeType, signal)\n }\n else if (asset.record.mimeType !== 'application/pdf') {\n // `bibliography` of a non-PDF asset: only reachable with a DOI.\n const found = await extractBibliography({ doi: body.doi, text: '', resolveModel, signal })\n bib = found.bib\n warnings.push(...found.warnings)\n }\n else {\n const pdf = await openPdf(asset.data)\n try {\n if (method === 'bibliography') {\n const pages = await pdfPagesText(pdf, Math.min(pdf.pageCount, BIBLIOGRAPHY_PAGES), signal)\n const found = await extractBibliography({ doi: body.doi, text: bibliographyText(pages), resolveModel, signal })\n bib = found.bib\n warnings.push(...found.warnings)\n }\n else {\n const count = Math.min(pdf.pageCount, body.maxPages)\n if (pdf.pageCount > count) warnings.push('pages-truncated')\n let pages = await pdfPagesText(pdf, count, signal)\n if (body.method === 'auto' && isScanned(pages)) method = 'ocr'\n if (method === 'ocr') {\n // One vision call per page: the OCR reads fewer pages than the text layer would.\n const ocrCount = Math.min(count, MAX_OCR_PAGES)\n try {\n pages = await ocrPages(pdf, ocrCount, resolveModel, signal)\n if (ocrCount < count) warnings.push('ocr-truncated')\n }\n catch (error) {\n if (!(error instanceof RasterError)) throw error\n // Pages cannot be rendered here: keep what the text layer has.\n if (!pages.some(Boolean)) throw new HttpError(501, 'OCR nicht verfügbar')\n warnings.push('ocr-unavailable')\n method = 'pdf-text'\n }\n }\n markdown = joinPages(pages)\n if (body.bibliography) {\n try {\n const found = await extractBibliography({ doi: body.doi, text: bibliographyText(pages), resolveModel, signal })\n bib = found.bib\n warnings.push(...found.warnings)\n }\n catch (error) {\n // The text is the result; missing bibliographic data must not lose it.\n if (signal?.aborted) throw error\n warnings.push('bibliography-failed')\n }\n }\n }\n }\n finally {\n await pdf.close()\n }\n }\n\n const outputHash = sha256Hex(markdown)\n let output: string | null = null\n if (method !== 'bibliography' && markdown) {\n const data = Buffer.from(markdown, 'utf8')\n output = `${randomUUID()}.md`\n await assets.storeAsset(body.documentId, {\n name: output,\n filename: `${asset.record.filename}.${method}.md`.slice(0, 255),\n mimeType: 'text/markdown',\n size: data.byteLength,\n createdAt: new Date().toISOString(),\n sha256: outputHash,\n data,\n })\n }\n return json({ method, markdown, ...(segments && { segments }), ...(bib && { bib }), ...(model && { model }), inputHash, outputHash, output, warnings } satisfies ExtractResponse)\n}\n\n/** Body schema of `transcriptCleanupPost`. */\nexport const transcriptCleanupBodySchema = transcriptCleanupRequestSchema\n\n/**\n * Cleans transcript segments (filler words, punctuation, casing, fragmented sentences) without touching speakers or\n * order: the model only returns a new text per segment ID. Plain JSON: `{ cleaned, failed }`.\n */\nexport async function transcriptCleanupPost(ctx: AiHandlerContext, request: HandlerRequest): Promise<HandlerResponse> {\n const user = await enforceRateLimit(ctx, request)\n const { segments, model } = await readBody(request, transcriptCleanupBodySchema)\n const languageModel = await ctx.ai.resolveModel(model, user)\n\n // Closing the menu or the page aborts the client's fetch; stop the upstream requests with it.\n const abort = new AbortController()\n request.signal?.addEventListener('abort', () => abort.abort(), { once: true })\n try {\n return json(await runTranscriptCleanup(segments, (messages, signal) => ctx.ai.streamChat({ model: languageModel, messages, signal }), abort.signal))\n }\n catch (error) {\n throw error instanceof TranscriptCleanupUnreadableError ? new HttpError(502, error.message) : error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AACzC,MAAM,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,SAAS;AACvC,MAAM,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,aAAa,QAAQ;;AAE5D,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AAE/C,MAAM,WAAW,EAAE,mBAAmB,QAAQ;CAC5C,EAAE,OAAO;EAAE,IAAI;EAAM,MAAM,EAAE,QAAQ,QAAQ;EAAG,IAAI;EAAS;CAAS,CAAC;CACvE,EAAE,OAAO;EAAE,IAAI;EAAM,MAAM,EAAE,QAAQ,QAAQ;EAAG,IAAI;CAAQ,CAAC;CAC7D,EAAE,OAAO;EAAE,IAAI;EAAM,MAAM,EAAE,QAAQ,KAAK;EAAG,SAAS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.js";
4
+ import { BlockType } from "../../features/composites/block-types.js";
5
+ import "../../features/composites/schema.js";
4
6
  import { RateLimiter } from "../rate-limit.js";
5
7
  //#region src/server/handlers/context.d.ts
6
8
  /** What every editor handler needs: the ports of the backend (identity first). */
@@ -18,6 +20,8 @@ export interface HandlerContext {
18
20
  export interface AiHandlerContext extends HandlerContext {
19
21
  ai: AiModels;
20
22
  limiter: RateLimiter;
23
+ /** The Block types of the host's config (`EditorServerOptions.blockTypes`). Given: the chat describes these to the model and ignores the `blockTypes` the client sends. */
24
+ blockTypes?: readonly BlockType[];
21
25
  }
22
26
  /** A request, reduced to what the handlers read: any HTTP server maps its own request type onto it. */
23
27
  export interface HandlerRequest {
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../../src/server/handlers/context.ts"],"sourcesContent":["import type { AiModels } from '../ai'\nimport type { EditorPorts } from '../ports'\nimport type { CollabServer } from '../collab'\nimport { HttpError } from '../errors'\nimport type { RateLimiter } from '../rate-limit'\nimport { userKey } from '../rate-limit'\n\n/** What every editor handler needs: the ports of the backend (identity first). */\nexport interface HandlerContext {\n ports: EditorPorts\n /** The collaboration server of the process: documents open in it count for `tagsGet` with their unsaved content. */\n collab?: CollabServer\n /** What the installed server really serves (`capabilities` answers with it); without it, what `ports` imply. */\n served?: { ai?: boolean, collaboration?: boolean }\n}\n\n/** Context of the AI handlers: the configured models and the per-user limit shared by all of them. */\nexport interface AiHandlerContext extends HandlerContext {\n ai: AiModels\n limiter: RateLimiter\n}\n\n/** A request, reduced to what the handlers read: any HTTP server maps its own request type onto it. */\nexport interface HandlerRequest {\n headers: Headers\n /** Route parameters (`id`, `name`). */\n params?: Readonly<Record<string, string | undefined>>\n /** Query string values (`q`). */\n query?: Readonly<Record<string, string | undefined>>\n /** The JSON body. Lazy, so a handler authenticates (401) before it reads or validates anything. Rejects when the body is no JSON. */\n readJson?: () => Promise<unknown>\n /** The multipart body; `null` when it is none. Lazy like `readJson`. */\n readForm?: () => Promise<FormData | null>\n /** Aborts when the client goes away: handlers stop upstream requests with it. */\n signal?: AbortSignal\n}\n\n/** A response, as plain data any HTTP server can send (`new Response(body, { status, headers })` maps it 1:1). */\nexport interface HandlerResponse {\n status: number\n headers: Record<string, string>\n body: string | Uint8Array | ReadableStream<Uint8Array> | null\n}\n\nexport const json = (value: unknown, status = 200): HandlerResponse => ({\n status,\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(value),\n})\n\nexport const text = (value: string, contentType: string, headers: Record<string, string> = {}): HandlerResponse => ({\n status: 200,\n headers: { 'content-type': contentType, ...headers },\n body: value,\n})\n\nexport const empty = (status = 204, headers: Record<string, string> = {}): HandlerResponse => ({ status, headers, body: null })\n\n/**\n * Server-sent events. `run` writes events through `emit` and ends the stream by returning; `signal` aborts when the\n * client cancels the response or `request.signal` aborts. An `emit` after that is dropped.\n */\nexport function eventStream(request: HandlerRequest, run: (emit: (event: string, data: string) => void, signal: AbortSignal) => Promise<void>): HandlerResponse {\n const abort = new AbortController()\n if (request.signal?.aborted) abort.abort()\n else request.signal?.addEventListener('abort', () => abort.abort(), { once: true })\n const encoder = new TextEncoder()\n return {\n status: 200,\n headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no' },\n body: new ReadableStream<Uint8Array>({\n start(controller) {\n const emit = (event: string, data: string) => {\n if (!abort.signal.aborted) controller.enqueue(encoder.encode(`event: ${event}\\ndata: ${data}\\n\\n`))\n }\n void run(emit, abort.signal)\n .catch((error) => { if (!abort.signal.aborted) console.error('[editor-server]', error) })\n .finally(() => { try { controller.close() } catch { /* the client cancelled */ } })\n },\n cancel() { abort.abort() },\n }),\n }\n}\n\n/** The user `ports.identity.authenticate` finds behind the request's headers; 401 without one. */\nexport async function authenticated({ ports }: HandlerContext, request: HandlerRequest): Promise<object> {\n const user = await ports.identity.authenticate({ headers: request.headers })\n if (!user) throw new HttpError(401, 'Nicht angemeldet')\n return user\n}\n\n/** The port `name` of the backend; 501 when the host serves none. The one place absent ports turn into an answer. */\nexport function port<K extends Exclude<keyof EditorPorts, 'identity' | 'documents'>>(ctx: HandlerContext, name: K): NonNullable<EditorPorts[K]> {\n const found = ctx.ports[name]\n if (found === undefined) throw new HttpError(501, `Port \"${name}\" not supported`)\n return found as NonNullable<EditorPorts[K]>\n}\n\n/** Per-user limit for the AI handlers: 401 without a user, 429 with `Retry-After` when exceeded; returns the user, for `resolveModel`. */\nexport async function enforceRateLimit(ctx: AiHandlerContext, request: HandlerRequest): Promise<object> {\n const user = await authenticated(ctx, request)\n const waitMs = ctx.limiter.hit(userKey(user))\n if (!waitMs) return user\n throw new HttpError(429, 'Zu viele KI-Anfragen, bitte kurz warten', { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) })\n}\n\ninterface BodySchema<T> {\n safeParse(data: unknown): { success: true, data: T } | { success: false, error: { issues: unknown[] } }\n}\n\n/** The request's JSON body validated with `schema`; 400 for malformed JSON and for validation failures (`data`: the issues). */\nexport async function readBody<T>(request: HandlerRequest, schema: BodySchema<T>): Promise<T> {\n let raw: unknown\n try {\n raw = await request.readJson?.()\n }\n catch {\n throw new HttpError(400, 'Ungültiger JSON-Body')\n }\n const parsed = schema.safeParse(raw)\n if (!parsed.success) throw new HttpError(400, 'Validation Error', {}, parsed.error.issues)\n return parsed.data\n}\n"],"mappings":";;;AA4CA,MAAa,QAAQ,OAAgB,SAAS,SAA0B;CACtE;CACA,SAAS,EAAE,gBAAgB,mBAAmB;CAC9C,MAAM,KAAK,UAAU,KAAK;AAC5B;AAEA,MAAa,QAAQ,OAAe,aAAqB,UAAkC,CAAC,OAAwB;CAClH,QAAQ;CACR,SAAS;EAAE,gBAAgB;EAAa,GAAG;CAAQ;CACnD,MAAM;AACR;AAEA,MAAa,SAAS,SAAS,KAAK,UAAkC,CAAC,OAAwB;CAAE;CAAQ;CAAS,MAAM;AAAK;;;;;AAM7H,SAAgB,YAAY,SAAyB,KAA2G;CAC9J,MAAM,QAAQ,IAAI,gBAA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I,UAAU,KAAK,2CAA2C,EAAE,eAAe,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,SAAS,GAAI,CAAC,CAAC,EAAE,CAAC;AACtI;;AAOA,eAAsB,SAAY,SAAyB,QAAmC;CAC5F,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,QAAQ,WAAW;CACjC,QACM;EACJ,MAAM,IAAI,UAAU,KAAK,sBAAsB;CACjD;CACA,MAAM,SAAS,OAAO,UAAU,GAAG;CACnC,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,UAAU,KAAK,oBAAoB,CAAC,GAAG,OAAO,MAAM,MAAM;CACzF,OAAO,OAAO;AAChB"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../../src/server/handlers/context.ts"],"sourcesContent":["import type { BlockType } from '../../features/composites/schema'\nimport type { AiModels } from '../ai'\nimport type { EditorPorts } from '../ports'\nimport type { CollabServer } from '../collab'\nimport { HttpError } from '../errors'\nimport type { RateLimiter } from '../rate-limit'\nimport { userKey } from '../rate-limit'\n\n/** What every editor handler needs: the ports of the backend (identity first). */\nexport interface HandlerContext {\n ports: EditorPorts\n /** The collaboration server of the process: documents open in it count for `tagsGet` with their unsaved content. */\n collab?: CollabServer\n /** What the installed server really serves (`capabilities` answers with it); without it, what `ports` imply. */\n served?: { ai?: boolean, collaboration?: boolean }\n}\n\n/** Context of the AI handlers: the configured models and the per-user limit shared by all of them. */\nexport interface AiHandlerContext extends HandlerContext {\n ai: AiModels\n limiter: RateLimiter\n /** The Block types of the host's config (`EditorServerOptions.blockTypes`). Given: the chat describes these to the model and ignores the `blockTypes` the client sends. */\n blockTypes?: readonly BlockType[]\n}\n\n/** A request, reduced to what the handlers read: any HTTP server maps its own request type onto it. */\nexport interface HandlerRequest {\n headers: Headers\n /** Route parameters (`id`, `name`). */\n params?: Readonly<Record<string, string | undefined>>\n /** Query string values (`q`). */\n query?: Readonly<Record<string, string | undefined>>\n /** The JSON body. Lazy, so a handler authenticates (401) before it reads or validates anything. Rejects when the body is no JSON. */\n readJson?: () => Promise<unknown>\n /** The multipart body; `null` when it is none. Lazy like `readJson`. */\n readForm?: () => Promise<FormData | null>\n /** Aborts when the client goes away: handlers stop upstream requests with it. */\n signal?: AbortSignal\n}\n\n/** A response, as plain data any HTTP server can send (`new Response(body, { status, headers })` maps it 1:1). */\nexport interface HandlerResponse {\n status: number\n headers: Record<string, string>\n body: string | Uint8Array | ReadableStream<Uint8Array> | null\n}\n\nexport const json = (value: unknown, status = 200): HandlerResponse => ({\n status,\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(value),\n})\n\nexport const text = (value: string, contentType: string, headers: Record<string, string> = {}): HandlerResponse => ({\n status: 200,\n headers: { 'content-type': contentType, ...headers },\n body: value,\n})\n\nexport const empty = (status = 204, headers: Record<string, string> = {}): HandlerResponse => ({ status, headers, body: null })\n\n/**\n * Server-sent events. `run` writes events through `emit` and ends the stream by returning; `signal` aborts when the\n * client cancels the response or `request.signal` aborts. An `emit` after that is dropped.\n */\nexport function eventStream(request: HandlerRequest, run: (emit: (event: string, data: string) => void, signal: AbortSignal) => Promise<void>): HandlerResponse {\n const abort = new AbortController()\n if (request.signal?.aborted) abort.abort()\n else request.signal?.addEventListener('abort', () => abort.abort(), { once: true })\n const encoder = new TextEncoder()\n return {\n status: 200,\n headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no' },\n body: new ReadableStream<Uint8Array>({\n start(controller) {\n const emit = (event: string, data: string) => {\n if (!abort.signal.aborted) controller.enqueue(encoder.encode(`event: ${event}\\ndata: ${data}\\n\\n`))\n }\n void run(emit, abort.signal)\n .catch((error) => { if (!abort.signal.aborted) console.error('[editor-server]', error) })\n .finally(() => { try { controller.close() } catch { /* the client cancelled */ } })\n },\n cancel() { abort.abort() },\n }),\n }\n}\n\n/** The user `ports.identity.authenticate` finds behind the request's headers; 401 without one. */\nexport async function authenticated({ ports }: HandlerContext, request: HandlerRequest): Promise<object> {\n const user = await ports.identity.authenticate({ headers: request.headers })\n if (!user) throw new HttpError(401, 'Nicht angemeldet')\n return user\n}\n\n/** The port `name` of the backend; 501 when the host serves none. The one place absent ports turn into an answer. */\nexport function port<K extends Exclude<keyof EditorPorts, 'identity' | 'documents'>>(ctx: HandlerContext, name: K): NonNullable<EditorPorts[K]> {\n const found = ctx.ports[name]\n if (found === undefined) throw new HttpError(501, `Port \"${name}\" not supported`)\n return found as NonNullable<EditorPorts[K]>\n}\n\n/** Per-user limit for the AI handlers: 401 without a user, 429 with `Retry-After` when exceeded; returns the user, for `resolveModel`. */\nexport async function enforceRateLimit(ctx: AiHandlerContext, request: HandlerRequest): Promise<object> {\n const user = await authenticated(ctx, request)\n const waitMs = ctx.limiter.hit(userKey(user))\n if (!waitMs) return user\n throw new HttpError(429, 'Zu viele KI-Anfragen, bitte kurz warten', { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) })\n}\n\ninterface BodySchema<T> {\n safeParse(data: unknown): { success: true, data: T } | { success: false, error: { issues: unknown[] } }\n}\n\n/** The request's JSON body validated with `schema`; 400 for malformed JSON and for validation failures (`data`: the issues). */\nexport async function readBody<T>(request: HandlerRequest, schema: BodySchema<T>): Promise<T> {\n let raw: unknown\n try {\n raw = await request.readJson?.()\n }\n catch {\n throw new HttpError(400, 'Ungültiger JSON-Body')\n }\n const parsed = schema.safeParse(raw)\n if (!parsed.success) throw new HttpError(400, 'Validation Error', {}, parsed.error.issues)\n return parsed.data\n}\n"],"mappings":";;;AA+CA,MAAa,QAAQ,OAAgB,SAAS,SAA0B;CACtE;CACA,SAAS,EAAE,gBAAgB,mBAAmB;CAC9C,MAAM,KAAK,UAAU,KAAK;AAC5B;AAEA,MAAa,QAAQ,OAAe,aAAqB,UAAkC,CAAC,OAAwB;CAClH,QAAQ;CACR,SAAS;EAAE,gBAAgB;EAAa,GAAG;CAAQ;CACnD,MAAM;AACR;AAEA,MAAa,SAAS,SAAS,KAAK,UAAkC,CAAC,OAAwB;CAAE;CAAQ;C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,IAAI,QAAQ,IAAI,QAAQ,IAAI,CAAC;CAC5C,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,IAAI,UAAU,KAAK,2CAA2C,EAAE,eAAe,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,SAAS,GAAI,CAAC,CAAC,EAAE,CAAC;AACtI;;AAOA,eAAsB,SAAY,SAAyB,QAAmC;CAC5F,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,QAAQ,WAAW;CACjC,QACM;EACJ,MAAM,IAAI,UAAU,KAAK,sBAAsB;CACjD;CACA,MAAM,SAAS,OAAO,UAAU,GAAG;CACnC,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,UAAU,KAAK,oBAAoB,CAAC,GAAG,OAAO,MAAM,MAAM;CACzF,OAAO,OAAO;AAChB"}
@@ -1,4 +1,5 @@
1
1
  import { HandlerContext, HandlerRequest, HandlerResponse } from "./context.js";
2
+ import { z } from "zod";
2
3
  //#region src/server/handlers/editor.d.ts
3
4
  /**
4
5
  * The capabilities this server serves (`BackendCapability[]`, see `serverCapabilities`): what the client's probe
@@ -6,68 +7,68 @@ import { HandlerContext, HandlerRequest, HandlerResponse } from "./context.js";
6
7
  * routes whose capabilities it lists.
7
8
  */
8
9
  export declare function capabilitiesGet(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
9
- /** Body schema of `settingsPut`: the complete editor settings. */
10
- export declare const settingsPutBodySchema: import("zod").ZodObject<{
11
- version: import("zod").ZodLiteral<1>;
12
- editing: import("zod").ZodObject<{
13
- headingConversionScope: import("zod").ZodEnum<{
10
+ /** Body schema of `settingsPut`: the complete editor settings; a body of an older version (a tab from before the rename) is migrated first. */
11
+ export declare const settingsPutBodySchema: z.ZodPreprocess<z.ZodObject<{
12
+ version: z.ZodLiteral<2>;
13
+ editing: z.ZodObject<{
14
+ headingConversionScope: z.ZodEnum<{
14
15
  container: "container";
15
16
  document: "document";
16
17
  heading: "heading";
17
18
  }>;
18
- authorColors: import("zod").ZodBoolean;
19
- authorColorStyle: import("zod").ZodEnum<{
19
+ authorColors: z.ZodBoolean;
20
+ authorColorStyle: z.ZodEnum<{
20
21
  text: "text";
21
22
  background: "background";
22
23
  }>;
23
- commentsLayout: import("zod").ZodEnum<{
24
+ commentsLayout: z.ZodEnum<{
24
25
  margin: "margin";
25
26
  inline: "inline";
26
27
  }>;
27
- }, import("zod/v4/core").$strip>;
28
- ai: import("zod").ZodObject<{
29
- autocomplete: import("zod").ZodBoolean;
30
- slots: import("zod").ZodRecord<import("zod").ZodEnum<{
28
+ }, z.core.$strip>;
29
+ ai: z.ZodObject<{
30
+ autocomplete: z.ZodBoolean;
31
+ roles: z.ZodRecord<z.ZodEnum<{
31
32
  complete: "complete";
32
33
  rewrite: "rewrite";
33
34
  generate: "generate";
34
- }> & import("zod/v4/core").$partial, import("zod").ZodString>;
35
- translateLanguage: import("zod").ZodEnum<{
35
+ }> & z.core.$partial, z.ZodString>;
36
+ translateLanguage: z.ZodEnum<{
36
37
  Deutsch: "Deutsch";
37
38
  Englisch: "Englisch";
38
39
  Französisch: "Französisch";
39
40
  Spanisch: "Spanisch";
40
41
  Italienisch: "Italienisch";
41
42
  }>;
42
- }, import("zod/v4/core").$strip>;
43
- blocks: import("zod").ZodObject<{
44
- defaultKind: import("zod").ZodString;
45
- structure: import("zod").ZodEnum<{
43
+ }, z.core.$strip>;
44
+ blocks: z.ZodObject<{
45
+ defaultBlockType: z.ZodString;
46
+ structure: z.ZodEnum<{
46
47
  flat: "flat";
47
- composite: "composite";
48
+ structured: "structured";
48
49
  }>;
49
- treeRoot: import("zod").ZodEnum<{
50
+ treeRoot: z.ZodEnum<{
50
51
  file: "file";
51
52
  folders: "folders";
52
53
  }>;
53
- kindIcon: import("zod").ZodEnum<{
54
+ blockTypeIcon: z.ZodEnum<{
54
55
  always: "always";
55
56
  hover: "hover";
56
57
  }>;
57
- dragHandle: import("zod").ZodEnum<{
58
+ dragHandle: z.ZodEnum<{
58
59
  always: "always";
59
60
  hover: "hover";
60
61
  }>;
61
- splitTargetChars: import("zod").ZodNumber;
62
- }, import("zod/v4/core").$strip>;
63
- appearance: import("zod").ZodObject<{
64
- theme: import("zod").ZodNullable<import("zod").ZodString>;
65
- }, import("zod/v4/core").$strip>;
66
- }, import("zod/v4/core").$strip>;
62
+ splitTargetChars: z.ZodNumber;
63
+ }, z.core.$strip>;
64
+ appearance: z.ZodObject<{
65
+ theme: z.ZodNullable<z.ZodString>;
66
+ }, z.core.$strip>;
67
+ }, z.core.$strip>, unknown>;
67
68
  /**
68
- * The authenticated user's editor settings, normalized with `parseEditorSettings`. `204` without a `settings` port (the
69
- * client stays on localStorage); `200` with JSON `null` when the user has none stored yet (the client uploads its local
70
- * ones).
69
+ * The authenticated user's editor settings, normalized with `parseEditorSettings`. A stored record older than
70
+ * `EDITOR_SETTINGS_VERSION` is written back migrated, once. `204` without a `settings` port (the client stays on
71
+ * localStorage); `200` with JSON `null` when the user has none stored yet (the client uploads its local ones).
71
72
  */
72
73
  export declare function settingsGet(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
73
74
  /** Stores the authenticated user's editor settings (complete, validated: 400 otherwise); `501` without a `settings` port. */
@@ -75,7 +76,7 @@ export declare function settingsPut(ctx: HandlerContext, request: HandlerRequest
75
76
  /**
76
77
  * All `#` tag names used in any document, deduplicated and sorted. Documents currently open in the collaboration server
77
78
  * are read from their live Y.Doc (a tag added in document A shows up in document B before the debounced store); all
78
- * others from the stored content of `ports.documents`.
79
+ * others from the stored content of `ports.documents`, with its old persisted names migrated first (a stored document may predate the rename of the tags row).
79
80
  */
80
81
  export declare function listWorkspaceTags({ ports, collab }: HandlerContext): Promise<string[]>;
81
82
  /**