daigram 0.0.0-stage → 0.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 (581) hide show
  1. package/LICENSE +661 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +11 -0
  4. package/README.md +788 -2
  5. package/assets/fonts/CascadiaCode-Regular.ttf +0 -0
  6. package/assets/fonts/Excalifont-Regular.ttf +0 -0
  7. package/assets/fonts/LICENSES.md +63 -0
  8. package/assets/fonts/LiberationSans-Regular.ttf +0 -0
  9. package/assets/fonts/Virgil-Regular.ttf +0 -0
  10. package/dist/ai/config.d.ts +11 -0
  11. package/dist/ai/config.d.ts.map +1 -0
  12. package/dist/ai/config.js +59 -0
  13. package/dist/ai/config.js.map +1 -0
  14. package/dist/ai/providers/anthropic.d.ts +3 -0
  15. package/dist/ai/providers/anthropic.d.ts.map +1 -0
  16. package/dist/ai/providers/anthropic.js +71 -0
  17. package/dist/ai/providers/anthropic.js.map +1 -0
  18. package/dist/ai/providers/openai-compatible.d.ts +3 -0
  19. package/dist/ai/providers/openai-compatible.d.ts.map +1 -0
  20. package/dist/ai/providers/openai-compatible.js +95 -0
  21. package/dist/ai/providers/openai-compatible.js.map +1 -0
  22. package/dist/ai/request-settings.d.ts +9 -0
  23. package/dist/ai/request-settings.d.ts.map +1 -0
  24. package/dist/ai/request-settings.js +56 -0
  25. package/dist/ai/request-settings.js.map +1 -0
  26. package/dist/ai/routes.d.ts +7 -0
  27. package/dist/ai/routes.d.ts.map +1 -0
  28. package/dist/ai/routes.js +192 -0
  29. package/dist/ai/routes.js.map +1 -0
  30. package/dist/ai/runner.d.ts +19 -0
  31. package/dist/ai/runner.d.ts.map +1 -0
  32. package/dist/ai/runner.js +77 -0
  33. package/dist/ai/runner.js.map +1 -0
  34. package/dist/ai/sse.d.ts +4 -0
  35. package/dist/ai/sse.d.ts.map +1 -0
  36. package/dist/ai/sse.js +53 -0
  37. package/dist/ai/sse.js.map +1 -0
  38. package/dist/ai/system.d.ts +2 -0
  39. package/dist/ai/system.d.ts.map +1 -0
  40. package/dist/ai/system.js +17 -0
  41. package/dist/ai/system.js.map +1 -0
  42. package/dist/ai/tools.d.ts +10 -0
  43. package/dist/ai/tools.d.ts.map +1 -0
  44. package/dist/ai/tools.js +134 -0
  45. package/dist/ai/tools.js.map +1 -0
  46. package/dist/ai/types.d.ts +72 -0
  47. package/dist/ai/types.d.ts.map +1 -0
  48. package/dist/ai/types.js +2 -0
  49. package/dist/ai/types.js.map +1 -0
  50. package/dist/bin.d.ts +3 -0
  51. package/dist/bin.d.ts.map +1 -0
  52. package/dist/bin.js +52 -0
  53. package/dist/bin.js.map +1 -0
  54. package/dist/cli/args.d.ts +15 -0
  55. package/dist/cli/args.d.ts.map +1 -0
  56. package/dist/cli/args.js +78 -0
  57. package/dist/cli/args.js.map +1 -0
  58. package/dist/cli/commands/ai.d.ts +2 -0
  59. package/dist/cli/commands/ai.d.ts.map +1 -0
  60. package/dist/cli/commands/ai.js +45 -0
  61. package/dist/cli/commands/ai.js.map +1 -0
  62. package/dist/cli/commands/arrange.d.ts +2 -0
  63. package/dist/cli/commands/arrange.d.ts.map +1 -0
  64. package/dist/cli/commands/arrange.js +103 -0
  65. package/dist/cli/commands/arrange.js.map +1 -0
  66. package/dist/cli/commands/canvases.d.ts +2 -0
  67. package/dist/cli/commands/canvases.d.ts.map +1 -0
  68. package/dist/cli/commands/canvases.js +38 -0
  69. package/dist/cli/commands/canvases.js.map +1 -0
  70. package/dist/cli/commands/check.d.ts +2 -0
  71. package/dist/cli/commands/check.d.ts.map +1 -0
  72. package/dist/cli/commands/check.js +15 -0
  73. package/dist/cli/commands/check.js.map +1 -0
  74. package/dist/cli/commands/comment.d.ts +2 -0
  75. package/dist/cli/commands/comment.d.ts.map +1 -0
  76. package/dist/cli/commands/comment.js +76 -0
  77. package/dist/cli/commands/comment.js.map +1 -0
  78. package/dist/cli/commands/elements.d.ts +8 -0
  79. package/dist/cli/commands/elements.d.ts.map +1 -0
  80. package/dist/cli/commands/elements.js +285 -0
  81. package/dist/cli/commands/elements.js.map +1 -0
  82. package/dist/cli/commands/frame.d.ts +2 -0
  83. package/dist/cli/commands/frame.d.ts.map +1 -0
  84. package/dist/cli/commands/frame.js +58 -0
  85. package/dist/cli/commands/frame.js.map +1 -0
  86. package/dist/cli/commands/install-skill.d.ts +2 -0
  87. package/dist/cli/commands/install-skill.d.ts.map +1 -0
  88. package/dist/cli/commands/install-skill.js +108 -0
  89. package/dist/cli/commands/install-skill.js.map +1 -0
  90. package/dist/cli/commands/layout.d.ts +2 -0
  91. package/dist/cli/commands/layout.d.ts.map +1 -0
  92. package/dist/cli/commands/layout.js +15 -0
  93. package/dist/cli/commands/layout.js.map +1 -0
  94. package/dist/cli/commands/render.d.ts +2 -0
  95. package/dist/cli/commands/render.d.ts.map +1 -0
  96. package/dist/cli/commands/render.js +64 -0
  97. package/dist/cli/commands/render.js.map +1 -0
  98. package/dist/cli/commands/scene.d.ts +8 -0
  99. package/dist/cli/commands/scene.d.ts.map +1 -0
  100. package/dist/cli/commands/scene.js +147 -0
  101. package/dist/cli/commands/scene.js.map +1 -0
  102. package/dist/cli/commands/server.d.ts +4 -0
  103. package/dist/cli/commands/server.d.ts.map +1 -0
  104. package/dist/cli/commands/server.js +66 -0
  105. package/dist/cli/commands/server.js.map +1 -0
  106. package/dist/cli/commands/snapshot.d.ts +2 -0
  107. package/dist/cli/commands/snapshot.d.ts.map +1 -0
  108. package/dist/cli/commands/snapshot.js +41 -0
  109. package/dist/cli/commands/snapshot.js.map +1 -0
  110. package/dist/cli/image-options.d.ts +43 -0
  111. package/dist/cli/image-options.d.ts.map +1 -0
  112. package/dist/cli/image-options.js +71 -0
  113. package/dist/cli/image-options.js.map +1 -0
  114. package/dist/cli/run.d.ts +2 -0
  115. package/dist/cli/run.d.ts.map +1 -0
  116. package/dist/cli/run.js +115 -0
  117. package/dist/cli/run.js.map +1 -0
  118. package/dist/cli/util.d.ts +5 -0
  119. package/dist/cli/util.d.ts.map +1 -0
  120. package/dist/cli/util.js +35 -0
  121. package/dist/cli/util.js.map +1 -0
  122. package/dist/core/arrow-routing.d.ts +31 -0
  123. package/dist/core/arrow-routing.d.ts.map +1 -0
  124. package/dist/core/arrow-routing.js +244 -0
  125. package/dist/core/arrow-routing.js.map +1 -0
  126. package/dist/core/bulk-ops.d.ts +55 -0
  127. package/dist/core/bulk-ops.d.ts.map +1 -0
  128. package/dist/core/bulk-ops.js +181 -0
  129. package/dist/core/bulk-ops.js.map +1 -0
  130. package/dist/core/canvas-client.d.ts +110 -0
  131. package/dist/core/canvas-client.d.ts.map +1 -0
  132. package/dist/core/canvas-client.js +416 -0
  133. package/dist/core/canvas-client.js.map +1 -0
  134. package/dist/core/canvas-id.d.ts +4 -0
  135. package/dist/core/canvas-id.d.ts.map +1 -0
  136. package/dist/core/canvas-id.js +5 -0
  137. package/dist/core/canvas-id.js.map +1 -0
  138. package/dist/core/canvas-persistence.d.ts +30 -0
  139. package/dist/core/canvas-persistence.d.ts.map +1 -0
  140. package/dist/core/canvas-persistence.js +854 -0
  141. package/dist/core/canvas-persistence.js.map +1 -0
  142. package/dist/core/canvas-registry.d.ts +36 -0
  143. package/dist/core/canvas-registry.d.ts.map +1 -0
  144. package/dist/core/canvas-registry.js +161 -0
  145. package/dist/core/canvas-registry.js.map +1 -0
  146. package/dist/core/canvas-routes.d.ts +5 -0
  147. package/dist/core/canvas-routes.d.ts.map +1 -0
  148. package/dist/core/canvas-routes.js +29 -0
  149. package/dist/core/canvas-routes.js.map +1 -0
  150. package/dist/core/canvas-state.d.ts +14 -0
  151. package/dist/core/canvas-state.d.ts.map +1 -0
  152. package/dist/core/canvas-state.js +20 -0
  153. package/dist/core/canvas-state.js.map +1 -0
  154. package/dist/core/canvas.d.ts +13 -0
  155. package/dist/core/canvas.d.ts.map +1 -0
  156. package/dist/core/canvas.js +4 -0
  157. package/dist/core/canvas.js.map +1 -0
  158. package/dist/core/comment-ops.d.ts +3 -0
  159. package/dist/core/comment-ops.d.ts.map +1 -0
  160. package/dist/core/comment-ops.js +36 -0
  161. package/dist/core/comment-ops.js.map +1 -0
  162. package/dist/core/comments.d.ts +5 -0
  163. package/dist/core/comments.d.ts.map +1 -0
  164. package/dist/core/comments.js +137 -0
  165. package/dist/core/comments.js.map +1 -0
  166. package/dist/core/compact.d.ts +13 -0
  167. package/dist/core/compact.d.ts.map +1 -0
  168. package/dist/core/compact.js +20 -0
  169. package/dist/core/compact.js.map +1 -0
  170. package/dist/core/config.d.ts +8 -0
  171. package/dist/core/config.d.ts.map +1 -0
  172. package/dist/core/config.js +18 -0
  173. package/dist/core/config.js.map +1 -0
  174. package/dist/core/describe.d.ts +3 -0
  175. package/dist/core/describe.d.ts.map +1 -0
  176. package/dist/core/describe.js +94 -0
  177. package/dist/core/describe.js.map +1 -0
  178. package/dist/core/design-guide.d.ts +2 -0
  179. package/dist/core/design-guide.d.ts.map +1 -0
  180. package/dist/core/design-guide.js +115 -0
  181. package/dist/core/design-guide.js.map +1 -0
  182. package/dist/core/diagram-layout.d.ts +64 -0
  183. package/dist/core/diagram-layout.d.ts.map +1 -0
  184. package/dist/core/diagram-layout.js +238 -0
  185. package/dist/core/diagram-layout.js.map +1 -0
  186. package/dist/core/diagram-ops.d.ts +165 -0
  187. package/dist/core/diagram-ops.d.ts.map +1 -0
  188. package/dist/core/diagram-ops.js +46 -0
  189. package/dist/core/diagram-ops.js.map +1 -0
  190. package/dist/core/entry.d.ts +3 -0
  191. package/dist/core/entry.d.ts.map +1 -0
  192. package/dist/core/entry.js +35 -0
  193. package/dist/core/entry.js.map +1 -0
  194. package/dist/core/expand-elements.d.ts +9 -0
  195. package/dist/core/expand-elements.d.ts.map +1 -0
  196. package/dist/core/expand-elements.js +277 -0
  197. package/dist/core/expand-elements.js.map +1 -0
  198. package/dist/core/frame-ops.d.ts +60 -0
  199. package/dist/core/frame-ops.d.ts.map +1 -0
  200. package/dist/core/frame-ops.js +90 -0
  201. package/dist/core/frame-ops.js.map +1 -0
  202. package/dist/core/frames.d.ts +31 -0
  203. package/dist/core/frames.d.ts.map +1 -0
  204. package/dist/core/frames.js +95 -0
  205. package/dist/core/frames.js.map +1 -0
  206. package/dist/core/geometry.d.ts +30 -0
  207. package/dist/core/geometry.d.ts.map +1 -0
  208. package/dist/core/geometry.js +167 -0
  209. package/dist/core/geometry.js.map +1 -0
  210. package/dist/core/layout-check.d.ts +30 -0
  211. package/dist/core/layout-check.d.ts.map +1 -0
  212. package/dist/core/layout-check.js +181 -0
  213. package/dist/core/layout-check.js.map +1 -0
  214. package/dist/core/local-origin.d.ts +4 -0
  215. package/dist/core/local-origin.d.ts.map +1 -0
  216. package/dist/core/local-origin.js +27 -0
  217. package/dist/core/local-origin.js.map +1 -0
  218. package/dist/core/mcp-dispatch.d.ts +9 -0
  219. package/dist/core/mcp-dispatch.d.ts.map +1 -0
  220. package/dist/core/mcp-dispatch.js +741 -0
  221. package/dist/core/mcp-dispatch.js.map +1 -0
  222. package/dist/core/mcp-http.d.ts +3 -0
  223. package/dist/core/mcp-http.d.ts.map +1 -0
  224. package/dist/core/mcp-http.js +38 -0
  225. package/dist/core/mcp-http.js.map +1 -0
  226. package/dist/core/mcp-server.d.ts +19 -0
  227. package/dist/core/mcp-server.d.ts.map +1 -0
  228. package/dist/core/mcp-server.js +57 -0
  229. package/dist/core/mcp-server.js.map +1 -0
  230. package/dist/core/mcp-tools.d.ts +3 -0
  231. package/dist/core/mcp-tools.d.ts.map +1 -0
  232. package/dist/core/mcp-tools.js +723 -0
  233. package/dist/core/mcp-tools.js.map +1 -0
  234. package/dist/core/normalize.d.ts +26 -0
  235. package/dist/core/normalize.d.ts.map +1 -0
  236. package/dist/core/normalize.js +134 -0
  237. package/dist/core/normalize.js.map +1 -0
  238. package/dist/core/obsidian-md.d.ts +4 -0
  239. package/dist/core/obsidian-md.d.ts.map +1 -0
  240. package/dist/core/obsidian-md.js +227 -0
  241. package/dist/core/obsidian-md.js.map +1 -0
  242. package/dist/core/pidfile.d.ts +5 -0
  243. package/dist/core/pidfile.d.ts.map +1 -0
  244. package/dist/core/pidfile.js +51 -0
  245. package/dist/core/pidfile.js.map +1 -0
  246. package/dist/core/png-scene.d.ts +4 -0
  247. package/dist/core/png-scene.d.ts.map +1 -0
  248. package/dist/core/png-scene.js +176 -0
  249. package/dist/core/png-scene.js.map +1 -0
  250. package/dist/core/render/excalidraw-node/dom.d.ts +29 -0
  251. package/dist/core/render/excalidraw-node/dom.d.ts.map +1 -0
  252. package/dist/core/render/excalidraw-node/dom.js +132 -0
  253. package/dist/core/render/excalidraw-node/dom.js.map +1 -0
  254. package/dist/core/render/excalidraw-node/index.d.ts +11 -0
  255. package/dist/core/render/excalidraw-node/index.d.ts.map +1 -0
  256. package/dist/core/render/excalidraw-node/index.js +77 -0
  257. package/dist/core/render/excalidraw-node/index.js.map +1 -0
  258. package/dist/core/render/fonts.d.ts +34 -0
  259. package/dist/core/render/fonts.d.ts.map +1 -0
  260. package/dist/core/render/fonts.js +133 -0
  261. package/dist/core/render/fonts.js.map +1 -0
  262. package/dist/core/render/index.d.ts +40 -0
  263. package/dist/core/render/index.d.ts.map +1 -0
  264. package/dist/core/render/index.js +135 -0
  265. package/dist/core/render/index.js.map +1 -0
  266. package/dist/core/render/png-worker.d.ts +2 -0
  267. package/dist/core/render/png-worker.d.ts.map +1 -0
  268. package/dist/core/render/png-worker.js +65 -0
  269. package/dist/core/render/png-worker.js.map +1 -0
  270. package/dist/core/render/png.d.ts +15 -0
  271. package/dist/core/render/png.d.ts.map +1 -0
  272. package/dist/core/render/png.js +128 -0
  273. package/dist/core/render/png.js.map +1 -0
  274. package/dist/core/render/text-metrics.d.ts +2 -0
  275. package/dist/core/render/text-metrics.d.ts.map +1 -0
  276. package/dist/core/render/text-metrics.js +136 -0
  277. package/dist/core/render/text-metrics.js.map +1 -0
  278. package/dist/core/request-canvas.d.ts +9 -0
  279. package/dist/core/request-canvas.d.ts.map +1 -0
  280. package/dist/core/request-canvas.js +2 -0
  281. package/dist/core/request-canvas.js.map +1 -0
  282. package/dist/core/request-headers.d.ts +5 -0
  283. package/dist/core/request-headers.d.ts.map +1 -0
  284. package/dist/core/request-headers.js +80 -0
  285. package/dist/core/request-headers.js.map +1 -0
  286. package/dist/core/scene-input.d.ts +2 -0
  287. package/dist/core/scene-input.d.ts.map +1 -0
  288. package/dist/core/scene-input.js +11 -0
  289. package/dist/core/scene-input.js.map +1 -0
  290. package/dist/core/scene-io.d.ts +16 -0
  291. package/dist/core/scene-io.d.ts.map +1 -0
  292. package/dist/core/scene-io.js +95 -0
  293. package/dist/core/scene-io.js.map +1 -0
  294. package/dist/core/share-url.d.ts +3 -0
  295. package/dist/core/share-url.d.ts.map +1 -0
  296. package/dist/core/share-url.js +77 -0
  297. package/dist/core/share-url.js.map +1 -0
  298. package/dist/core/spawn.d.ts +41 -0
  299. package/dist/core/spawn.d.ts.map +1 -0
  300. package/dist/core/spawn.js +153 -0
  301. package/dist/core/spawn.js.map +1 -0
  302. package/dist/core/version.d.ts +2 -0
  303. package/dist/core/version.d.ts.map +1 -0
  304. package/dist/core/version.js +14 -0
  305. package/dist/core/version.js.map +1 -0
  306. package/dist/frontend/assets/Assistant-Bold-gm-uSS1B.woff2 +0 -0
  307. package/dist/frontend/assets/Assistant-Medium-DrcxCXg3.woff2 +0 -0
  308. package/dist/frontend/assets/Assistant-Regular-DVxZuzxb.woff2 +0 -0
  309. package/dist/frontend/assets/Assistant-SemiBold-SCI4bEL9.woff2 +0 -0
  310. package/dist/frontend/assets/Tableau10-CvOaoHrI.js +1 -0
  311. package/dist/frontend/assets/_commonjs-dynamic-modules-TDtrdbi3.js +1 -0
  312. package/dist/frontend/assets/abnfDiagram-VCTEODGH-CO_aNPe5.js +1 -0
  313. package/dist/frontend/assets/advancedFormat-DE2dNp0u.js +1 -0
  314. package/dist/frontend/assets/ar-SA-G6X2FPQ2-Bq4yiKbc.js +10 -0
  315. package/dist/frontend/assets/arc--vhPzIZC.js +1 -0
  316. package/dist/frontend/assets/architectureDiagram-5GKGNRK7-aHYJQElw.js +36 -0
  317. package/dist/frontend/assets/array-BKyUJesY.js +1 -0
  318. package/dist/frontend/assets/az-AZ-76LH7QW2-BB3yat67.js +1 -0
  319. package/dist/frontend/assets/band-dPffDWoQ.js +1 -0
  320. package/dist/frontend/assets/bg-BG-XCXSNQG7-DmC2FjQc.js +5 -0
  321. package/dist/frontend/assets/blockDiagram-68f4deed-Bn83vchM.js +118 -0
  322. package/dist/frontend/assets/blockDiagram-NRAW4CY4-CxaW-TzC.js +129 -0
  323. package/dist/frontend/assets/bn-BD-2XOGV67Q-DpCbZMS6.js +5 -0
  324. package/dist/frontend/assets/c4Diagram-15b5d702-Bq7Ko0Vs.js +10 -0
  325. package/dist/frontend/assets/c4Diagram-UCG6FXSJ-Dh883fAO.js +38 -0
  326. package/dist/frontend/assets/ca-ES-6MX7JW3Y-CBOshpbV.js +8 -0
  327. package/dist/frontend/assets/channel-DYvM7vRx.js +1 -0
  328. package/dist/frontend/assets/chunk-2Q5K7J3B-DaFhLtFc.js +1 -0
  329. package/dist/frontend/assets/chunk-5VM5RSS4-CyLfaWw7.js +15 -0
  330. package/dist/frontend/assets/chunk-F27PBJKO-BHNc-edD.js +1 -0
  331. package/dist/frontend/assets/chunk-G27WJ6UU-BBKiZxqf.js +231 -0
  332. package/dist/frontend/assets/chunk-JWPE2WC7-7twsn51D.js +1 -0
  333. package/dist/frontend/assets/chunk-LCL6LL3I-BTwZuXJ6.js +206 -0
  334. package/dist/frontend/assets/chunk-POPQ4Y6H-CaHDxqyV.js +1 -0
  335. package/dist/frontend/assets/chunk-SVP7TREG-B8-zByXy.js +88 -0
  336. package/dist/frontend/assets/chunk-XXDRQBXY-DQLro-7R.js +1 -0
  337. package/dist/frontend/assets/classDiagram-DTDB5LWJ-Dpwx6IJK.js +1 -0
  338. package/dist/frontend/assets/classDiagram-d40c83e7-BPxlcZuc.js +2 -0
  339. package/dist/frontend/assets/classDiagram-v2-JRS7N3AN-Dpwx6IJK.js +1 -0
  340. package/dist/frontend/assets/classDiagram-v2-d5a6b087-Cyz34qAK.js +2 -0
  341. package/dist/frontend/assets/clone-Iw0eB1Cb.js +1 -0
  342. package/dist/frontend/assets/cose-bilkent-JH36ORCC-C4ZX1Xvi.js +1 -0
  343. package/dist/frontend/assets/createText-d213de94-CDH1rzxH.js +7 -0
  344. package/dist/frontend/assets/cs-CZ-2BRQDIVT-CGAN69M4.js +11 -0
  345. package/dist/frontend/assets/cynefin-OW5HDTMX-B8XT9png.js +178 -0
  346. package/dist/frontend/assets/cynefinDiagram-5FMLGOSQ-COTZjqlj.js +62 -0
  347. package/dist/frontend/assets/cytoscape-cose-bilkent-D4yGolDn.js +1 -0
  348. package/dist/frontend/assets/cytoscape.esm-BjAbmLdb.js +331 -0
  349. package/dist/frontend/assets/da-DK-5WZEPLOC-FIDoeOAn.js +5 -0
  350. package/dist/frontend/assets/dagre-3AP2YEHR-v8EtxNwx.js +4 -0
  351. package/dist/frontend/assets/de-DE-XR44H4JA-Hquyrt1G.js +8 -0
  352. package/dist/frontend/assets/defaultLocale-C4B-KCzX.js +1 -0
  353. package/dist/frontend/assets/diagram-S7CK7UJ4-BiwOlZBI.js +30 -0
  354. package/dist/frontend/assets/diagram-UQ7AKVKN-DIfzNs7s.js +41 -0
  355. package/dist/frontend/assets/diagram-VSXAHHWV-kKkEHy5z.js +3 -0
  356. package/dist/frontend/assets/diagram-VX7I27RA-zTp2qGKo.js +24 -0
  357. package/dist/frontend/assets/diagram-Z3DM3KII-hUxSr-QT.js +24 -0
  358. package/dist/frontend/assets/directory-open-01563666-DWU9wJ6I.js +1 -0
  359. package/dist/frontend/assets/directory-open-4ed118d0-CunoC1EB.js +1 -0
  360. package/dist/frontend/assets/ebnfDiagram-PWID7BFC-CRwXBVzS.js +1 -0
  361. package/dist/frontend/assets/edges-332bd1c7-CbPhghy3.js +4 -0
  362. package/dist/frontend/assets/el-GR-BZB4AONW-CWRJJANX.js +10 -0
  363. package/dist/frontend/assets/erDiagram-880f2ed8-CY1dU-f9.js +51 -0
  364. package/dist/frontend/assets/erDiagram-SSCWMZ5O-BfDW8Lxf.js +99 -0
  365. package/dist/frontend/assets/es-ES-U4NZUMDT-BwZWIjT5.js +9 -0
  366. package/dist/frontend/assets/eu-ES-A7QVB2H4-B9suQ9BE.js +11 -0
  367. package/dist/frontend/assets/fa-IR-HGAKTJCU-tgrKvE4J.js +8 -0
  368. package/dist/frontend/assets/fi-FI-Z5N7JZ37-Ddoc7R-q.js +6 -0
  369. package/dist/frontend/assets/file-open-002ab408-DIuFHtCF.js +1 -0
  370. package/dist/frontend/assets/file-open-7c801643-684qeFg4.js +1 -0
  371. package/dist/frontend/assets/file-save-3189631c-C1wFhQhH.js +1 -0
  372. package/dist/frontend/assets/file-save-745eba88-Bb9F9Kg7.js +1 -0
  373. package/dist/frontend/assets/flowDb-7c981674-DkYacLUz.js +10 -0
  374. package/dist/frontend/assets/flowDiagram-A5DVABFB-CCBuG42p.js +168 -0
  375. package/dist/frontend/assets/flowDiagram-cbd28bf7-DhhBmCsw.js +4 -0
  376. package/dist/frontend/assets/flowDiagram-v2-ffc7f31a-BICbZ5-w.js +1 -0
  377. package/dist/frontend/assets/flowchart-elk-definition-36e2d292-BsyTsM2Q.js +139 -0
  378. package/dist/frontend/assets/fr-FR-RHASNOE6-Bzn_6dcd.js +9 -0
  379. package/dist/frontend/assets/ganttDiagram-04f9e578-CCKAlfpJ.js +257 -0
  380. package/dist/frontend/assets/ganttDiagram-EL5Y4UJY-B8CXkutd.js +292 -0
  381. package/dist/frontend/assets/gitGraphDiagram-21fc4d3e-DBAYEQql.js +70 -0
  382. package/dist/frontend/assets/gitGraphDiagram-WWUBYQGX-Ge5QWjv2.js +106 -0
  383. package/dist/frontend/assets/gl-ES-HMX3MZ6V-vcZHbFum.js +10 -0
  384. package/dist/frontend/assets/graph-87dI2d0Q.js +1 -0
  385. package/dist/frontend/assets/has-D7z5cd7K.js +1 -0
  386. package/dist/frontend/assets/he-IL-6SHJWFNN-CK07fY3l.js +10 -0
  387. package/dist/frontend/assets/hi-IN-IWLTKZ5I-CDZ0p7Jv.js +4 -0
  388. package/dist/frontend/assets/hu-HU-A5ZG7DT2-FH5SLnWy.js +7 -0
  389. package/dist/frontend/assets/id-ID-SAP4L64H-MjXIXb2f.js +10 -0
  390. package/dist/frontend/assets/image-blob-reduce.esm-HwCm7IZ0.js +7 -0
  391. package/dist/frontend/assets/index-6079d271-DiB2AL6F.js +1 -0
  392. package/dist/frontend/assets/index-BcAUh2Nm.css +1 -0
  393. package/dist/frontend/assets/index-Biw8Vgb3.js +320 -0
  394. package/dist/frontend/assets/index-fTyH8AV3.js +354 -0
  395. package/dist/frontend/assets/infoDiagram-4a4f5b27-BOdJmCUU.js +7 -0
  396. package/dist/frontend/assets/infoDiagram-RXCK75RN-CNm06Rxs.js +2 -0
  397. package/dist/frontend/assets/init-Gi6I4Gst.js +1 -0
  398. package/dist/frontend/assets/ishikawaDiagram-5VMMS53U-DoLWy3n2.js +70 -0
  399. package/dist/frontend/assets/it-IT-JPQ66NNP-D3n0iaPa.js +11 -0
  400. package/dist/frontend/assets/ja-JP-DBVTYXUO-ejSNO7M9.js +8 -0
  401. package/dist/frontend/assets/journeyDiagram-29694f62-Cm6qVjA9.js +139 -0
  402. package/dist/frontend/assets/journeyDiagram-EYS64GPL-ByZmvOcj.js +139 -0
  403. package/dist/frontend/assets/kaa-6HZHGXH3-D8l_gwno.js +1 -0
  404. package/dist/frontend/assets/kab-KAB-ZGHBKWFO-CCdAUgdW.js +8 -0
  405. package/dist/frontend/assets/kanban-definition-3QL26DDD-Y5ylzca9.js +89 -0
  406. package/dist/frontend/assets/katex-C5jXJg4s.js +257 -0
  407. package/dist/frontend/assets/kk-KZ-P5N5QNE5-DeuZqHeo.js +1 -0
  408. package/dist/frontend/assets/km-KH-HSX4SM5Z-CiG2k5fk.js +11 -0
  409. package/dist/frontend/assets/ko-KR-MTYHY66A-KQOGYf_l.js +9 -0
  410. package/dist/frontend/assets/ku-TR-6OUDTVRD-iPec9Wpx.js +9 -0
  411. package/dist/frontend/assets/layout-ChryVliD.js +1 -0
  412. package/dist/frontend/assets/layout-chXYHUIV.js +1 -0
  413. package/dist/frontend/assets/line-V0o6yOnB.js +1 -0
  414. package/dist/frontend/assets/linear-BvV3B0Vg.js +1 -0
  415. package/dist/frontend/assets/lt-LT-XHIRWOB4-CATjC2gQ.js +3 -0
  416. package/dist/frontend/assets/lv-LV-5QDEKY6T-BsDP-7Dd.js +7 -0
  417. package/dist/frontend/assets/mindmap-definition-FBJOCRG2-z4KcwRlx.js +96 -0
  418. package/dist/frontend/assets/mindmap-definition-ac74a2e8-C1QU2vBv.js +95 -0
  419. package/dist/frontend/assets/mr-IN-CRQNXWMA-DWJhwvxv.js +13 -0
  420. package/dist/frontend/assets/my-MM-5M5IBNSE-DckXEMN8.js +1 -0
  421. package/dist/frontend/assets/nb-NO-T6EIAALU-HaOR9ZeX.js +10 -0
  422. package/dist/frontend/assets/nl-NL-IS3SIHDZ-ef_ywpFu.js +8 -0
  423. package/dist/frontend/assets/nn-NO-6E72VCQL-Bg7QdVqf.js +8 -0
  424. package/dist/frontend/assets/oc-FR-POXYY2M6-D5HmBPnC.js +8 -0
  425. package/dist/frontend/assets/ordinal-Cboi1Yqb.js +1 -0
  426. package/dist/frontend/assets/pa-IN-N4M65BXN-BHYM0tZp.js +4 -0
  427. package/dist/frontend/assets/path-CbwjOpE9.js +1 -0
  428. package/dist/frontend/assets/pegDiagram-XKGWAZYB-BL0-JiYs.js +1 -0
  429. package/dist/frontend/assets/pica-CHpl3DYP.js +7 -0
  430. package/dist/frontend/assets/pie-b97pL0mM.js +1 -0
  431. package/dist/frontend/assets/pieDiagram-421022e6-DiRybrxD.js +35 -0
  432. package/dist/frontend/assets/pieDiagram-E7YTZNPT-VybkpWmu.js +39 -0
  433. package/dist/frontend/assets/pl-PL-T2D74RX3-uZIVDHgu.js +9 -0
  434. package/dist/frontend/assets/pt-BR-5N22H2LF-dJVfhAeV.js +9 -0
  435. package/dist/frontend/assets/pt-PT-UZXXM6DQ-DjJzcznP.js +9 -0
  436. package/dist/frontend/assets/quadrantDiagram-0957ecba-BHJpECv1.js +7 -0
  437. package/dist/frontend/assets/quadrantDiagram-AXDQQJYC-RAG8nSkZ.js +7 -0
  438. package/dist/frontend/assets/railroadDiagram-O6MQD6OU-lCMtporN.js +1 -0
  439. package/dist/frontend/assets/requirementDiagram-23d650b8-mSFTWSrD.js +52 -0
  440. package/dist/frontend/assets/requirementDiagram-EFPCY7ZU-B8YnTqPO.js +84 -0
  441. package/dist/frontend/assets/ro-RO-JPDTUUEW-B5X8VOmp.js +11 -0
  442. package/dist/frontend/assets/roundRect-0PYZxl1G.js +1 -0
  443. package/dist/frontend/assets/ru-RU-B4JR7IUQ-Czv9kfuz.js +9 -0
  444. package/dist/frontend/assets/sankeyDiagram-23345273-B3g3P-D1.js +8 -0
  445. package/dist/frontend/assets/sankeyDiagram-P5KCCOFB-DRm9HHoQ.js +40 -0
  446. package/dist/frontend/assets/sankeyLinkHorizontal-CgO6js3K.js +1 -0
  447. package/dist/frontend/assets/sequenceDiagram-17ac3bff-DzZiSttS.js +122 -0
  448. package/dist/frontend/assets/sequenceDiagram-WJ2MYXX4-BrSDYDx-.js +162 -0
  449. package/dist/frontend/assets/si-LK-N5RQ5JYF-DFWOZdgD.js +1 -0
  450. package/dist/frontend/assets/sizeCapture-X5ZJPWSS-CbaN7yeQ.js +1 -0
  451. package/dist/frontend/assets/sk-SK-C5VTKIMK-B8VlFn2Z.js +6 -0
  452. package/dist/frontend/assets/sl-SI-NN7IZMDC-CJeSgLEg.js +6 -0
  453. package/dist/frontend/assets/stateDiagram-9c5f0230-Dzm1fyzw.js +1 -0
  454. package/dist/frontend/assets/stateDiagram-HBIQ2CUA-B5Nv-PBX.js +1 -0
  455. package/dist/frontend/assets/stateDiagram-v2-4QOOHH4V-B72hUL6s.js +1 -0
  456. package/dist/frontend/assets/stateDiagram-v2-51a3dcff-DvLAYBjA.js +1 -0
  457. package/dist/frontend/assets/styles-2ab5d517-D6473lhT.js +116 -0
  458. package/dist/frontend/assets/styles-5f03d8d2-CZ5U9u1n.js +160 -0
  459. package/dist/frontend/assets/styles-edf9a4b0-DzQC88FF.js +207 -0
  460. package/dist/frontend/assets/subset-shared.chunk.js +84 -0
  461. package/dist/frontend/assets/subset-worker.chunk.js +1 -0
  462. package/dist/frontend/assets/sv-SE-XGPEYMSR-BKMKxZWF.js +10 -0
  463. package/dist/frontend/assets/svgDrawCommon-3ba9043b-CQsuw6x4.js +1 -0
  464. package/dist/frontend/assets/swimlanes-XN3QIQJK-D6c81JTS.js +1 -0
  465. package/dist/frontend/assets/swimlanesDiagram-VK2B7HYN-SMIGSMWR.js +8 -0
  466. package/dist/frontend/assets/ta-IN-2NMHFXQM-BtPPl3RQ.js +9 -0
  467. package/dist/frontend/assets/th-TH-HPSO5L25-CSjFGi1j.js +2 -0
  468. package/dist/frontend/assets/timeline-definition-24CTP7MA-DTBgPsOR.js +120 -0
  469. package/dist/frontend/assets/timeline-definition-7e6b55e7-D44e8lHF.js +61 -0
  470. package/dist/frontend/assets/tr-TR-DEFEU3FU-BS1kZ0-G.js +7 -0
  471. package/dist/frontend/assets/uk-UA-QMV73CPH--ucRdDwc.js +6 -0
  472. package/dist/frontend/assets/union-DI_iry4-.js +1 -0
  473. package/dist/frontend/assets/vennDiagram-4TSXK5OY-DDIUJU_f.js +34 -0
  474. package/dist/frontend/assets/vi-VN-M7AON7JQ-BcGYkPOn.js +5 -0
  475. package/dist/frontend/assets/wardleyDiagram-VM6X3IG4-TfvrOirV.js +78 -0
  476. package/dist/frontend/assets/xychartDiagram-S5SC5T6Z-DaSdOJbv.js +7 -0
  477. package/dist/frontend/assets/xychartDiagram-b6496bcd-VIsyqEG1.js +7 -0
  478. package/dist/frontend/assets/zh-CN-LNUGB5OW-RL4CyEYU.js +10 -0
  479. package/dist/frontend/assets/zh-HK-E62DVLB3-DKGVR3J1.js +1 -0
  480. package/dist/frontend/assets/zh-TW-RAJ6MFWO-C7djgh-M.js +9 -0
  481. package/dist/frontend/assets/zipObject-Bl99JdSU.js +1 -0
  482. package/dist/frontend/index.html +569 -0
  483. package/dist/index.d.ts +7 -0
  484. package/dist/index.d.ts.map +1 -0
  485. package/dist/index.js +74 -0
  486. package/dist/index.js.map +1 -0
  487. package/dist/render/excalidraw-node.mjs +540 -0
  488. package/dist/server.d.ts +5 -0
  489. package/dist/server.d.ts.map +1 -0
  490. package/dist/server.js +1684 -0
  491. package/dist/server.js.map +1 -0
  492. package/dist/types.d.ts +263 -0
  493. package/dist/types.d.ts.map +1 -0
  494. package/dist/types.js +49 -0
  495. package/dist/types.js.map +1 -0
  496. package/dist/utils/logger.d.ts +4 -0
  497. package/dist/utils/logger.d.ts.map +1 -0
  498. package/dist/utils/logger.js +63 -0
  499. package/dist/utils/logger.js.map +1 -0
  500. package/package.json +127 -4
  501. package/skills/excalidraw-skill/SKILL.md +331 -0
  502. package/skills/excalidraw-skill/evals/evals.json +35 -0
  503. package/skills/excalidraw-skill/references/cheatsheet.md +217 -0
  504. package/src/ai/config.ts +58 -0
  505. package/src/ai/providers/anthropic.ts +62 -0
  506. package/src/ai/providers/openai-compatible.ts +84 -0
  507. package/src/ai/request-settings.ts +50 -0
  508. package/src/ai/routes.ts +157 -0
  509. package/src/ai/runner.ts +80 -0
  510. package/src/ai/sse.ts +40 -0
  511. package/src/ai/system.ts +16 -0
  512. package/src/ai/tools.ts +130 -0
  513. package/src/ai/types.ts +48 -0
  514. package/src/bin.ts +56 -0
  515. package/src/cli/args.ts +97 -0
  516. package/src/cli/commands/ai.ts +40 -0
  517. package/src/cli/commands/arrange.ts +112 -0
  518. package/src/cli/commands/canvases.ts +37 -0
  519. package/src/cli/commands/check.ts +15 -0
  520. package/src/cli/commands/comment.ts +72 -0
  521. package/src/cli/commands/elements.ts +299 -0
  522. package/src/cli/commands/frame.ts +55 -0
  523. package/src/cli/commands/install-skill.ts +116 -0
  524. package/src/cli/commands/layout.ts +14 -0
  525. package/src/cli/commands/render.ts +68 -0
  526. package/src/cli/commands/scene.ts +168 -0
  527. package/src/cli/commands/server.ts +71 -0
  528. package/src/cli/commands/snapshot.ts +45 -0
  529. package/src/cli/image-options.ts +77 -0
  530. package/src/cli/run.ts +123 -0
  531. package/src/cli/util.ts +39 -0
  532. package/src/core/arrow-routing.ts +256 -0
  533. package/src/core/bulk-ops.ts +183 -0
  534. package/src/core/canvas-client.ts +525 -0
  535. package/src/core/canvas-id.ts +8 -0
  536. package/src/core/canvas-persistence.ts +1067 -0
  537. package/src/core/canvas-registry.ts +180 -0
  538. package/src/core/canvas-routes.ts +34 -0
  539. package/src/core/canvas-state.ts +37 -0
  540. package/src/core/canvas.ts +18 -0
  541. package/src/core/comment-ops.ts +36 -0
  542. package/src/core/comments.ts +142 -0
  543. package/src/core/compact.ts +21 -0
  544. package/src/core/config.ts +24 -0
  545. package/src/core/describe.ts +100 -0
  546. package/src/core/design-guide.ts +114 -0
  547. package/src/core/diagram-layout.ts +278 -0
  548. package/src/core/diagram-ops.ts +48 -0
  549. package/src/core/entry.ts +37 -0
  550. package/src/core/expand-elements.ts +316 -0
  551. package/src/core/frame-ops.ts +112 -0
  552. package/src/core/frames.ts +113 -0
  553. package/src/core/geometry.ts +213 -0
  554. package/src/core/layout-check.ts +200 -0
  555. package/src/core/local-origin.ts +27 -0
  556. package/src/core/mcp-dispatch.ts +858 -0
  557. package/src/core/mcp-http.ts +38 -0
  558. package/src/core/mcp-server.ts +72 -0
  559. package/src/core/mcp-tools.ts +725 -0
  560. package/src/core/normalize.ts +158 -0
  561. package/src/core/obsidian-md.ts +231 -0
  562. package/src/core/pidfile.ts +52 -0
  563. package/src/core/png-scene.ts +177 -0
  564. package/src/core/render/excalidraw-node/dom.ts +159 -0
  565. package/src/core/render/excalidraw-node/index.ts +100 -0
  566. package/src/core/render/fonts.ts +173 -0
  567. package/src/core/render/index.ts +198 -0
  568. package/src/core/render/png-worker.ts +75 -0
  569. package/src/core/render/png.ts +148 -0
  570. package/src/core/render/text-metrics.ts +141 -0
  571. package/src/core/request-canvas.ts +10 -0
  572. package/src/core/request-headers.ts +79 -0
  573. package/src/core/scene-input.ts +11 -0
  574. package/src/core/scene-io.ts +125 -0
  575. package/src/core/share-url.ts +99 -0
  576. package/src/core/spawn.ts +186 -0
  577. package/src/core/version.ts +13 -0
  578. package/src/index.ts +86 -0
  579. package/src/server.ts +1873 -0
  580. package/src/types.ts +384 -0
  581. package/src/utils/logger.ts +77 -0
package/src/server.ts ADDED
@@ -0,0 +1,1873 @@
1
+ import express, { Request, Response, NextFunction } from 'express';
2
+ import cors from 'cors';
3
+ import { WebSocketServer } from 'ws';
4
+ import { createServer, IncomingHttpHeaders, IncomingMessage } from 'http';
5
+ import net from 'net';
6
+ import path from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ import dotenv from 'dotenv';
9
+ import logger from './utils/logger.js';
10
+ import type { Canvas } from './core/canvas.js';
11
+ import { CanvasRegistry } from './core/canvas-registry.js';
12
+ import { createCanvasRouter } from './core/canvas-routes.js';
13
+ import {
14
+ generateId,
15
+ EXCALIDRAW_ELEMENT_TYPES,
16
+ ServerElement,
17
+ ExcalidrawElementType,
18
+ ExcalidrawFile,
19
+ WebSocketMessage,
20
+ ElementCreatedMessage,
21
+ ElementUpdatedMessage,
22
+ ElementDeletedMessage,
23
+ BatchCreatedMessage,
24
+ SyncStatusMessage,
25
+ InitialElementsMessage,
26
+ Snapshot,
27
+ normalizeFontFamily
28
+ } from './types.js';
29
+ import { z } from 'zod';
30
+ import WebSocket from 'ws';
31
+ import { isMainModule } from './core/entry.js';
32
+ import { createCommentRouter } from './core/comments.js';
33
+ import { createAiRouter } from './ai/routes.js';
34
+ import { createMcpRouter } from './core/mcp-http.js';
35
+ import { routeArrowAround } from './core/arrow-routing.js';
36
+ import { EXPRESS_SERVER_URL } from './core/config.js';
37
+ import { isTrustedRequest, parseAllowedOrigins } from './core/local-origin.js';
38
+ import { writePidFile, removePidFile } from './core/pidfile.js';
39
+ import { renderScene, RenderError, MAX_SCALE } from './core/render/index.js';
40
+ import {
41
+ CanvasFileImmutabilityError,
42
+ CanvasFileReferenceError,
43
+ CanvasPersistenceError,
44
+ acquireDurableStateLock,
45
+ commitCanvasMutation,
46
+ durableStateDirectory,
47
+ durableStateEnabled,
48
+ releaseDurableStateLock,
49
+ } from './core/canvas-persistence.js';
50
+ import type { DurableStateStatus } from './core/canvas-persistence.js';
51
+
52
+ function mutationErrorStatus(error: unknown, fallback: number): number {
53
+ if (error instanceof CanvasPersistenceError) return 500;
54
+ if (error instanceof CanvasFileImmutabilityError ||
55
+ error instanceof CanvasFileReferenceError) return 409;
56
+ return fallback;
57
+ }
58
+
59
+ // Load environment variables
60
+ dotenv.config();
61
+
62
+ const __filename = fileURLToPath(import.meta.url);
63
+ const __dirname = path.dirname(__filename);
64
+
65
+ const app = express();
66
+ const server = createServer(app);
67
+ const allowedOrigins = parseAllowedOrigins(process.env.ALLOWED_ORIGINS);
68
+ const isTrusted = (headers: IncomingHttpHeaders): boolean => isTrustedRequest(headers, HOST, allowedOrigins);
69
+
70
+ const wss = new WebSocketServer({ server, verifyClient: ({ req }: { req: IncomingMessage }) => isTrusted(req.headers) });
71
+
72
+ // Case-insensitive like Express's own routing, or /API/... would skip the check.
73
+ const API_PATH = /^\/(?:c\/[^/?#]+\/)?(?:api|mcp)(?:[/?#]|$)/i;
74
+ app.use((req: Request, res: Response, next: NextFunction) => {
75
+ if (!API_PATH.test(req.url) || isTrusted(req.headers)) return next();
76
+ res.status(403).json({ success: false, error: 'Cross-site requests to the canvas API are refused' });
77
+ });
78
+
79
+ // /c/<id>/... addresses one canvas, with the rest of the path as usual; any other path is the main canvas.
80
+ const CANVAS_PATH = /^\/c\/([^/?#]+)(\/[^?#]*)?(\?.*)?$/i;
81
+
82
+ // A canvas whose saved state is damaged must fail its own requests, not the server.
83
+ function lookupCanvas(id: string): { canvas?: Canvas; failed?: boolean } {
84
+ try {
85
+ return { canvas: registry.get(id) };
86
+ } catch (error) {
87
+ logger.error(`Canvas "${id}" could not be loaded:`, error);
88
+ return { failed: true };
89
+ }
90
+ }
91
+
92
+ app.use((req: Request, res: Response, next: NextFunction) => {
93
+ const match = CANVAS_PATH.exec(req.url);
94
+ if (!match) {
95
+ req.canvas = registry.main();
96
+ return next();
97
+ }
98
+ const { canvas, failed } = lookupCanvas(match[1]!);
99
+ if (failed) return res.status(500).json({ success: false, error: `Canvas "${match[1]}" could not be loaded` });
100
+ if (!canvas) return res.status(404).json({ success: false, error: `Canvas "${match[1]}" not found` });
101
+ req.canvas = canvas;
102
+ req.url = `${match[2] ?? '/'}${match[3] ?? ''}`;
103
+ next();
104
+ });
105
+
106
+ app.use(cors({ origin: allowedOrigins }));
107
+ app.use(express.json({ limit: '10mb' }));
108
+
109
+ // Serve static files from the build directory
110
+ const staticDir = path.join(__dirname, '../dist');
111
+ // No redirect to a trailing slash: /c/<id> is a page, not a directory.
112
+ app.use(express.static(staticDir, { redirect: false }));
113
+ // Also serve frontend assets
114
+ // Vite names these files by content hash, so a cached copy is never stale; without this every page load
115
+ // revalidates each of the ~170 chunks, a round trip apiece.
116
+ const HASHED_ASSET = /-[\w-]{8}\.(?:js|css|woff2)$/;
117
+ app.use(express.static(path.join(__dirname, '../dist/frontend'), {
118
+ redirect: false,
119
+ setHeaders: (res, file) => { if (HASHED_ASSET.test(file)) res.setHeader('Cache-Control', 'max-age=31536000, immutable'); }
120
+ }));
121
+ // Excalidraw's fonts, for the page (EXCALIDRAW_ASSET_PATH in index.html) and the export subsetting worker. Some
122
+ // names are not hashed (Virgil-Regular.woff2), so a week rather than forever.
123
+ app.use('/assets/fonts', express.static(
124
+ path.join(__dirname, '../node_modules/@excalidraw/excalidraw/dist/prod/fonts'),
125
+ { maxAge: '7d' }
126
+ ));
127
+
128
+ const registry = new CanvasRegistry(durableStateDirectory());
129
+
130
+ // Connected tabs, by the canvas they opened.
131
+ const clientsByCanvas = new Map<string, Set<WebSocket>>();
132
+ const clientsOf = (canvas: Canvas): Set<WebSocket> => {
133
+ let clients = clientsByCanvas.get(canvas.id);
134
+ if (!clients) clientsByCanvas.set(canvas.id, clients = new Set());
135
+ return clients;
136
+ };
137
+
138
+ // In-memory canvas selection tracked across active tabs.
139
+ // The most recently active tab of a canvas wins; cleared when its tab closes.
140
+ interface TabSelection {
141
+ selectedElementIds: string[];
142
+ updatedAt: number;
143
+ }
144
+ const clientSelections = new Map<WebSocket, TabSelection>();
145
+
146
+ function getActiveSelection(canvas: Canvas): string[] {
147
+ let latestTab: TabSelection | null = null;
148
+ for (const ws of clientsOf(canvas)) {
149
+ const sel = clientSelections.get(ws);
150
+ if (!sel) continue;
151
+ if (ws.readyState === WebSocket.OPEN) {
152
+ if (!latestTab || sel.updatedAt > latestTab.updatedAt) {
153
+ latestTab = sel;
154
+ }
155
+ } else {
156
+ clientSelections.delete(ws);
157
+ }
158
+ }
159
+ return latestTab ? latestTab.selectedElementIds : [];
160
+ }
161
+
162
+ // Broadcast to the tabs open on one canvas
163
+ function broadcast(canvas: Canvas, message: WebSocketMessage): void {
164
+ const data = JSON.stringify(message);
165
+ const clients = clientsOf(canvas);
166
+ clients.forEach(client => {
167
+ try {
168
+ if (client.readyState === WebSocket.OPEN) {
169
+ client.send(data);
170
+ }
171
+ } catch (err) {
172
+ logger.warn('Failed to send to client, removing');
173
+ clients.delete(client);
174
+ }
175
+ });
176
+ }
177
+
178
+ function normalizeLineBreakMarkup(text: string): string {
179
+ return text
180
+ .replace(/<\s*b\s*r\s*\/?\s*>/gi, '\n')
181
+ .replace(/\n{3,}/g, '\n\n');
182
+ }
183
+
184
+ function prepareFileWrites(canvas: Canvas, fileList: unknown[]): ExcalidrawFile[] {
185
+ const durable = durableStateEnabled();
186
+
187
+ // Preserve the pre-persistence endpoint exactly when durability is disabled:
188
+ // valid entries overwrite in request order, omitted metadata uses the same
189
+ // truthy defaults, and an existing file contributes no implicit defaults.
190
+ if (!durable) {
191
+ const prepared: ExcalidrawFile[] = [];
192
+ for (const value of fileList) {
193
+ if (value === null || typeof value !== 'object') continue;
194
+ const candidate = value as Partial<ExcalidrawFile>;
195
+ if (!candidate.id || !candidate.dataURL) continue;
196
+ prepared.push({
197
+ id: candidate.id,
198
+ dataURL: candidate.dataURL,
199
+ mimeType: candidate.mimeType || 'image/png',
200
+ created: candidate.created || Date.now(),
201
+ });
202
+ }
203
+ return prepared;
204
+ }
205
+
206
+ const prepared = new Map<string, ExcalidrawFile>();
207
+
208
+ for (const value of fileList) {
209
+ if (value === null || typeof value !== 'object') continue;
210
+ const candidate = value as Partial<ExcalidrawFile>;
211
+ if (typeof candidate.id !== 'string' || candidate.id.length === 0 ||
212
+ typeof candidate.dataURL !== 'string' || candidate.dataURL.length === 0) {
213
+ continue;
214
+ }
215
+
216
+ const previous = prepared.get(candidate.id) ?? canvas.files.get(candidate.id);
217
+ const mimeType = typeof candidate.mimeType === 'string' && candidate.mimeType.length > 0
218
+ ? candidate.mimeType
219
+ : previous?.mimeType ?? 'image/png';
220
+
221
+ if (previous) {
222
+ if (previous.dataURL !== candidate.dataURL || previous.mimeType !== mimeType) {
223
+ throw new CanvasFileImmutabilityError(candidate.id);
224
+ }
225
+ prepared.set(candidate.id, previous);
226
+ continue;
227
+ }
228
+
229
+ prepared.set(candidate.id, {
230
+ id: candidate.id,
231
+ dataURL: candidate.dataURL,
232
+ mimeType,
233
+ // Preserve the original in-memory endpoint's overwrite behavior:
234
+ // an omitted/zero timestamp is replaced with the current time. Durable
235
+ // retries of an existing immutable id returned above keep prior metadata.
236
+ created: typeof candidate.created === 'number' && Number.isFinite(candidate.created) && candidate.created > 0
237
+ ? candidate.created
238
+ : Date.now(),
239
+ });
240
+ }
241
+
242
+ return [...prepared.values()];
243
+ }
244
+
245
+ // WebSocket connection handling
246
+ wss.on('connection', (ws: WebSocket, request: IncomingMessage) => {
247
+ const match = CANVAS_PATH.exec(request.url ?? '/');
248
+ const { canvas, failed } = match ? lookupCanvas(match[1]!) : { canvas: registry.main(), failed: false };
249
+ if (failed) {
250
+ ws.close(1011, 'Canvas could not be loaded');
251
+ return;
252
+ }
253
+ if (!canvas) {
254
+ ws.close(4404, 'Canvas not found');
255
+ return;
256
+ }
257
+ const clients = clientsOf(canvas);
258
+ clients.add(ws);
259
+ logger.info('New WebSocket connection established');
260
+
261
+ // Send current elements to new client
262
+ const filesObj: Record<string, ExcalidrawFile> = {};
263
+ canvas.files.forEach((f, id) => { filesObj[id] = f; });
264
+ const initialMessage: InitialElementsMessage & { files?: Record<string, ExcalidrawFile> } = {
265
+ type: 'initial_elements',
266
+ elements: Array.from(canvas.elements.values()),
267
+ ...(canvas.files.size > 0 ? { files: filesObj } : {})
268
+ };
269
+ ws.send(JSON.stringify(initialMessage));
270
+
271
+ // Send sync status to new client
272
+ const syncMessage: SyncStatusMessage = {
273
+ type: 'sync_status',
274
+ elementCount: canvas.elements.size,
275
+ timestamp: new Date().toISOString()
276
+ };
277
+ ws.send(JSON.stringify(syncMessage));
278
+
279
+ ws.on('message', (raw: WebSocket.Data) => {
280
+ try {
281
+ const msg = JSON.parse(raw.toString());
282
+ if (msg && msg.type === 'selection_updated' && Array.isArray(msg.selectedElementIds)) {
283
+ clientSelections.set(ws, {
284
+ selectedElementIds: msg.selectedElementIds.filter((id: unknown) => typeof id === 'string'),
285
+ updatedAt: Date.now()
286
+ });
287
+ }
288
+ } catch {
289
+ // Ignore malformed client frames
290
+ }
291
+ });
292
+
293
+ ws.on('close', () => {
294
+ clients.delete(ws);
295
+ clientSelections.delete(ws);
296
+ logger.info('WebSocket connection closed');
297
+ });
298
+
299
+ ws.on('error', (error) => {
300
+ logger.error('WebSocket error:', error);
301
+ clients.delete(ws);
302
+ clientSelections.delete(ws);
303
+ });
304
+ });
305
+
306
+ // Schema validation
307
+ const CreateElementSchema = z.object({
308
+ id: z.string().optional(), // Allow passing ID for MCP sync
309
+ type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES) as [ExcalidrawElementType, ...ExcalidrawElementType[]]),
310
+ x: z.number(),
311
+ y: z.number(),
312
+ width: z.number().optional(),
313
+ height: z.number().optional(),
314
+ backgroundColor: z.string().optional(),
315
+ strokeColor: z.string().optional(),
316
+ strokeWidth: z.number().optional(),
317
+ strokeStyle: z.string().optional(),
318
+ roughness: z.number().optional(),
319
+ opacity: z.number().optional(),
320
+ text: z.string().optional(),
321
+ label: z.object({
322
+ text: z.string()
323
+ }).optional(),
324
+ fontSize: z.number().optional(),
325
+ fontFamily: z.union([z.string(), z.number()]).optional(),
326
+ // Bound-text back-pointer — without it, zod strips containerId on import
327
+ // and re-imported bound labels detach from their containers
328
+ containerId: z.string().nullable().optional(),
329
+ // Excalidraw identity fields — preserve through import so re-exported
330
+ // scenes keep their stacking order, roughness seeds, and timestamps, and
331
+ // no-op import→export cycles stay byte-stable
332
+ index: z.string().nullable().optional(),
333
+ seed: z.number().optional(),
334
+ versionNonce: z.number().optional(),
335
+ updated: z.number().optional(),
336
+ groupIds: z.array(z.string()).optional(),
337
+ locked: z.boolean().optional(),
338
+ roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
339
+ fillStyle: z.string().optional(),
340
+ // Arrow-specific properties
341
+ points: z.any().optional(),
342
+ start: z.object({ id: z.string() }).optional(),
343
+ end: z.object({ id: z.string() }).optional(),
344
+ startArrowhead: z.string().nullable().optional(),
345
+ endArrowhead: z.string().nullable().optional(),
346
+ elbowed: z.boolean().optional(),
347
+ // Arrow binding properties (preserved for Excalidraw frontend)
348
+ startBinding: z.object({
349
+ elementId: z.string(),
350
+ focus: z.number().optional(),
351
+ gap: z.number().optional(),
352
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
353
+ mode: z.string().optional(),
354
+ }).nullable().optional(),
355
+ endBinding: z.object({
356
+ elementId: z.string(),
357
+ focus: z.number().optional(),
358
+ gap: z.number().optional(),
359
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
360
+ mode: z.string().optional(),
361
+ }).nullable().optional(),
362
+ boundElements: z.array(z.object({
363
+ id: z.string(),
364
+ type: z.enum(['arrow', 'text']),
365
+ })).nullable().optional(),
366
+ // Image-specific properties
367
+ fileId: z.string().optional(),
368
+ status: z.string().optional(),
369
+ scale: z.tuple([z.number(), z.number()]).optional(),
370
+ }).passthrough();
371
+
372
+ const UpdateElementSchema = z.object({
373
+ id: z.string(),
374
+ type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES) as [ExcalidrawElementType, ...ExcalidrawElementType[]]).optional(),
375
+ x: z.number().optional(),
376
+ y: z.number().optional(),
377
+ width: z.number().optional(),
378
+ height: z.number().optional(),
379
+ backgroundColor: z.string().optional(),
380
+ strokeColor: z.string().optional(),
381
+ strokeWidth: z.number().optional(),
382
+ strokeStyle: z.string().optional(),
383
+ roughness: z.number().optional(),
384
+ opacity: z.number().optional(),
385
+ text: z.string().optional(),
386
+ originalText: z.string().optional(),
387
+ label: z.object({
388
+ text: z.string()
389
+ }).optional(),
390
+ fontSize: z.number().optional(),
391
+ fontFamily: z.union([z.string(), z.number()]).optional(),
392
+ // Bound-text back-pointer — without it, zod strips containerId on import
393
+ // and re-imported bound labels detach from their containers
394
+ containerId: z.string().nullable().optional(),
395
+ // Excalidraw identity fields — preserve through import so re-exported
396
+ // scenes keep their stacking order, roughness seeds, and timestamps, and
397
+ // no-op import→export cycles stay byte-stable
398
+ index: z.string().nullable().optional(),
399
+ seed: z.number().optional(),
400
+ versionNonce: z.number().optional(),
401
+ updated: z.number().optional(),
402
+ groupIds: z.array(z.string()).optional(),
403
+ locked: z.boolean().optional(),
404
+ roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
405
+ fillStyle: z.string().optional(),
406
+ points: z.array(z.union([
407
+ z.tuple([z.number(), z.number()]),
408
+ z.object({ x: z.number(), y: z.number() })
409
+ ])).optional(),
410
+ start: z.object({ id: z.string() }).optional(),
411
+ end: z.object({ id: z.string() }).optional(),
412
+ startArrowhead: z.string().nullable().optional(),
413
+ endArrowhead: z.string().nullable().optional(),
414
+ elbowed: z.boolean().optional(),
415
+ // Arrow binding properties (preserved for Excalidraw frontend)
416
+ startBinding: z.object({
417
+ elementId: z.string(),
418
+ focus: z.number().optional(),
419
+ gap: z.number().optional(),
420
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
421
+ mode: z.string().optional(),
422
+ }).nullable().optional(),
423
+ endBinding: z.object({
424
+ elementId: z.string(),
425
+ focus: z.number().optional(),
426
+ gap: z.number().optional(),
427
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
428
+ mode: z.string().optional(),
429
+ }).nullable().optional(),
430
+ boundElements: z.array(z.object({
431
+ id: z.string(),
432
+ type: z.enum(['arrow', 'text']),
433
+ })).nullable().optional(),
434
+ // Image-specific properties
435
+ fileId: z.string().optional(),
436
+ status: z.string().optional(),
437
+ scale: z.tuple([z.number(), z.number()]).optional(),
438
+ }).passthrough();
439
+
440
+ // API Routes
441
+
442
+ // Get current canvas selection
443
+ app.get('/api/selection', (req: Request, res: Response) => {
444
+ const selectedElementIds = getActiveSelection(req.canvas);
445
+ res.json({
446
+ success: true,
447
+ selectedElementIds,
448
+ count: selectedElementIds.length
449
+ });
450
+ });
451
+
452
+ // Get all elements
453
+ app.get('/api/elements', (req: Request, res: Response) => {
454
+ const canvas = req.canvas;
455
+ try {
456
+ const elementsArray = Array.from(canvas.elements.values());
457
+ res.json({
458
+ success: true,
459
+ elements: elementsArray,
460
+ count: elementsArray.length
461
+ });
462
+ } catch (error) {
463
+ logger.error('Error fetching elements:', error);
464
+ res.status(500).json({
465
+ success: false,
466
+ error: (error as Error).message
467
+ });
468
+ }
469
+ });
470
+
471
+ // Create new element
472
+ app.post('/api/elements', (req: Request, res: Response) => {
473
+ const canvas = req.canvas;
474
+ try {
475
+ const params = CreateElementSchema.parse(req.body);
476
+ logger.info('Creating element via API', { type: params.type });
477
+
478
+ // Prioritize passed ID (for MCP sync), otherwise generate new ID
479
+ const id = params.id || generateId();
480
+ const element: ServerElement = {
481
+ id,
482
+ ...params,
483
+ fontFamily: normalizeFontFamily(params.fontFamily),
484
+ createdAt: new Date().toISOString(),
485
+ updatedAt: new Date().toISOString(),
486
+ version: 1
487
+ };
488
+
489
+ // Resolve arrow bindings against existing elements
490
+ if (element.type === 'arrow' || element.type === 'line') {
491
+ resolveArrowBindings(canvas, [element]);
492
+ }
493
+
494
+ commitCanvasMutation(canvas, () => canvas.elements.set(id, element));
495
+
496
+ // Broadcast to all connected clients
497
+ const message: ElementCreatedMessage = {
498
+ type: 'element_created',
499
+ element: element
500
+ };
501
+ broadcast(canvas, message);
502
+
503
+ res.json({
504
+ success: true,
505
+ element: element
506
+ });
507
+ } catch (error) {
508
+ logger.error('Error creating element:', error);
509
+ res.status(mutationErrorStatus(error, 400)).json({
510
+ success: false,
511
+ error: (error as Error).message
512
+ });
513
+ }
514
+ });
515
+
516
+ // Update element
517
+ app.put('/api/elements/:id', (req: Request, res: Response) => {
518
+ const canvas = req.canvas;
519
+ try {
520
+ const { id } = req.params;
521
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
522
+ const updates = UpdateElementSchema.parse({ id, ...body });
523
+
524
+ if (!id) {
525
+ return res.status(400).json({
526
+ success: false,
527
+ error: 'Element ID is required'
528
+ });
529
+ }
530
+
531
+ const existingElement = canvas.elements.get(id);
532
+ if (!existingElement) {
533
+ return res.status(404).json({
534
+ success: false,
535
+ error: `Element with ID ${id} not found`
536
+ });
537
+ }
538
+
539
+ const updatedElement: ServerElement = {
540
+ ...existingElement,
541
+ ...updates,
542
+ fontFamily: updates.fontFamily !== undefined ? normalizeFontFamily(updates.fontFamily) : existingElement.fontFamily,
543
+ updatedAt: new Date().toISOString(),
544
+ version: (existingElement.version || 0) + 1
545
+ };
546
+
547
+ // Keep Excalidraw text source in sync when clients update text via REST.
548
+ // If originalText lags behind text, rendered wrapping/position can drift.
549
+ const hasTextUpdate = Object.prototype.hasOwnProperty.call(body, 'text');
550
+ const hasOriginalTextUpdate = Object.prototype.hasOwnProperty.call(body, 'originalText');
551
+ if (updatedElement.type === EXCALIDRAW_ELEMENT_TYPES.TEXT && hasTextUpdate && !hasOriginalTextUpdate) {
552
+ const incomingText = updates.text ?? '';
553
+ const existingText = typeof existingElement.text === 'string' ? existingElement.text : '';
554
+ const existingOriginalText = typeof existingElement.originalText === 'string'
555
+ ? existingElement.originalText
556
+ : '';
557
+ const existingOriginalHasBr = /<\s*b\s*r\s*\/?\s*>/i.test(existingOriginalText);
558
+ const normalizedExistingText = normalizeLineBreakMarkup(existingText);
559
+ const normalizedExistingOriginalText = normalizeLineBreakMarkup(existingOriginalText);
560
+
561
+ // Handle common cleanup flow: caller normalizes the rendered text value.
562
+ // In this case, prefer normalized originalText so words aren't split by stale wraps.
563
+ if (existingOriginalHasBr && incomingText === normalizedExistingText && normalizedExistingOriginalText) {
564
+ updatedElement.text = normalizedExistingOriginalText;
565
+ updatedElement.originalText = normalizedExistingOriginalText;
566
+ } else {
567
+ updatedElement.originalText = incomingText;
568
+ }
569
+ }
570
+
571
+ // Moving/resizing a shape must drag its bound arrows along. Keep the
572
+ // element update and every in-place arrow reroute in one durable mutation.
573
+ const geometryChanged = ['x', 'y', 'width', 'height']
574
+ .some(key => Object.prototype.hasOwnProperty.call(body, key));
575
+ const reroutedArrows = commitCanvasMutation(canvas, () => {
576
+ canvas.elements.set(id, updatedElement);
577
+ return geometryChanged && updatedElement.type !== 'arrow' && updatedElement.type !== 'line'
578
+ ? rerouteBoundArrows(canvas, id)
579
+ : [];
580
+ });
581
+
582
+ // Publish only after the complete mutation has been checkpointed.
583
+ const message: ElementUpdatedMessage = {
584
+ type: 'element_updated',
585
+ element: updatedElement
586
+ };
587
+ broadcast(canvas, message);
588
+ for (const arrow of reroutedArrows) {
589
+ broadcast(canvas, { type: 'element_updated', element: arrow } as ElementUpdatedMessage);
590
+ }
591
+
592
+ res.json({
593
+ success: true,
594
+ element: updatedElement
595
+ });
596
+ } catch (error) {
597
+ logger.error('Error updating element:', error);
598
+ res.status(mutationErrorStatus(error, 400)).json({
599
+ success: false,
600
+ error: (error as Error).message
601
+ });
602
+ }
603
+ });
604
+
605
+ // A clear or replace cannot be undone, so the scene it discards is kept as a snapshot first. Call inside commitCanvasMutation.
606
+ const SAFETY_COPIES = 3;
607
+ const SAFETY_PREFIX = 'auto-';
608
+ function keepSafetyCopy(canvas: Canvas): void {
609
+ if (canvas.elements.size === 0) return;
610
+ const createdAt = new Date().toISOString();
611
+ const name = `${SAFETY_PREFIX}${createdAt.replace(/[:.]/g, '-')}`;
612
+ canvas.snapshots.set(name, { name, elements: structuredClone(Array.from(canvas.elements.values())), createdAt });
613
+ const kept = Array.from(canvas.snapshots.values()).filter(s => s.name.startsWith(SAFETY_PREFIX)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
614
+ kept.slice(SAFETY_COPIES).forEach(s => canvas.snapshots.delete(s.name));
615
+ }
616
+
617
+ // Clear all elements (must be before /:id route)
618
+ app.delete('/api/elements/clear', (req: Request, res: Response) => {
619
+ const canvas = req.canvas;
620
+ try {
621
+ const count = canvas.elements.size;
622
+ commitCanvasMutation(canvas, () => { keepSafetyCopy(canvas); canvas.elements.clear(); });
623
+
624
+ broadcast(canvas, {
625
+ type: 'canvas_cleared',
626
+ timestamp: new Date().toISOString()
627
+ });
628
+
629
+ logger.info(`Canvas cleared: ${count} elements removed`);
630
+
631
+ res.json({
632
+ success: true,
633
+ message: `Cleared ${count} elements`,
634
+ count
635
+ });
636
+ } catch (error) {
637
+ logger.error('Error clearing canvas:', error);
638
+ res.status(mutationErrorStatus(error, 500)).json({
639
+ success: false,
640
+ error: (error as Error).message
641
+ });
642
+ }
643
+ });
644
+
645
+ // Delete element
646
+ app.delete('/api/elements/:id', (req: Request, res: Response) => {
647
+ const canvas = req.canvas;
648
+ try {
649
+ const { id } = req.params;
650
+
651
+ if (!id) {
652
+ return res.status(400).json({
653
+ success: false,
654
+ error: 'Element ID is required'
655
+ });
656
+ }
657
+
658
+ if (!canvas.elements.has(id)) {
659
+ return res.status(404).json({
660
+ success: false,
661
+ error: `Element with ID ${id} not found`
662
+ });
663
+ }
664
+
665
+ commitCanvasMutation(canvas, () => canvas.elements.delete(id));
666
+
667
+ // Broadcast to all connected clients
668
+ const message: ElementDeletedMessage = {
669
+ type: 'element_deleted',
670
+ elementId: id!
671
+ };
672
+ broadcast(canvas, message);
673
+
674
+ res.json({
675
+ success: true,
676
+ message: `Element ${id} deleted successfully`
677
+ });
678
+ } catch (error) {
679
+ logger.error('Error deleting element:', error);
680
+ res.status(mutationErrorStatus(error, 500)).json({
681
+ success: false,
682
+ error: (error as Error).message
683
+ });
684
+ }
685
+ });
686
+
687
+ // Query elements with filters
688
+ app.get('/api/elements/search', (req: Request, res: Response) => {
689
+ const canvas = req.canvas;
690
+ try {
691
+ const { type, x_min, x_max, y_min, y_max, ...filters } = req.query;
692
+ let results = Array.from(canvas.elements.values());
693
+
694
+ // Filter by type if specified
695
+ if (type && typeof type === 'string') {
696
+ results = results.filter(element => element.type === type);
697
+ }
698
+
699
+ // Filter by bounding box if specified
700
+ if (x_min !== undefined || x_max !== undefined || y_min !== undefined || y_max !== undefined) {
701
+ const xMin = x_min !== undefined ? Number(x_min) : -Infinity;
702
+ const xMax = x_max !== undefined ? Number(x_max) : Infinity;
703
+ const yMin = y_min !== undefined ? Number(y_min) : -Infinity;
704
+ const yMax = y_max !== undefined ? Number(y_max) : Infinity;
705
+
706
+ results = results.filter(el =>
707
+ el.x >= xMin &&
708
+ el.x <= xMax &&
709
+ el.y >= yMin &&
710
+ el.y <= yMax
711
+ );
712
+ }
713
+
714
+ // Apply additional exact-match filters
715
+ if (Object.keys(filters).length > 0) {
716
+ results = results.filter(element => {
717
+ return Object.entries(filters).every(([key, value]) => {
718
+ return (element as any)[key] === value;
719
+ });
720
+ });
721
+ }
722
+
723
+ res.json({
724
+ success: true,
725
+ elements: results,
726
+ count: results.length
727
+ });
728
+ } catch (error) {
729
+ logger.error('Error querying elements:', error);
730
+ res.status(500).json({
731
+ success: false,
732
+ error: (error as Error).message
733
+ });
734
+ }
735
+ });
736
+
737
+ // Get element by ID
738
+ app.get('/api/elements/:id', (req: Request, res: Response) => {
739
+ const canvas = req.canvas;
740
+ try {
741
+ const { id } = req.params;
742
+
743
+ if (!id) {
744
+ return res.status(400).json({
745
+ success: false,
746
+ error: 'Element ID is required'
747
+ });
748
+ }
749
+
750
+ const element = canvas.elements.get(id);
751
+
752
+ if (!element) {
753
+ return res.status(404).json({
754
+ success: false,
755
+ error: `Element with ID ${id} not found`
756
+ });
757
+ }
758
+
759
+ res.json({
760
+ success: true,
761
+ element: element
762
+ });
763
+ } catch (error) {
764
+ logger.error('Error fetching element:', error);
765
+ res.status(500).json({
766
+ success: false,
767
+ error: (error as Error).message
768
+ });
769
+ }
770
+ });
771
+
772
+ // Helper: compute edge point for an element given a direction toward a target
773
+ function computeEdgePoint(
774
+ el: ServerElement,
775
+ targetCenterX: number,
776
+ targetCenterY: number
777
+ ): { x: number; y: number } {
778
+ const cx = el.x + (el.width || 0) / 2;
779
+ const cy = el.y + (el.height || 0) / 2;
780
+ const dx = targetCenterX - cx;
781
+ const dy = targetCenterY - cy;
782
+
783
+ if (el.type === 'diamond') {
784
+ // Diamond edge: use diamond geometry (rotated square)
785
+ const hw = (el.width || 0) / 2;
786
+ const hh = (el.height || 0) / 2;
787
+ if (dx === 0 && dy === 0) return { x: cx, y: cy + hh };
788
+ const absDx = Math.abs(dx);
789
+ const absDy = Math.abs(dy);
790
+ // Scale factor to reach diamond edge
791
+ const scale = (absDx / hw + absDy / hh) > 0
792
+ ? 1 / (absDx / hw + absDy / hh)
793
+ : 1;
794
+ return { x: cx + dx * scale, y: cy + dy * scale };
795
+ }
796
+
797
+ if (el.type === 'ellipse') {
798
+ // Ellipse edge: parametric intersection
799
+ const a = (el.width || 0) / 2;
800
+ const b = (el.height || 0) / 2;
801
+ if (dx === 0 && dy === 0) return { x: cx, y: cy + b };
802
+ const angle = Math.atan2(dy, dx);
803
+ return { x: cx + a * Math.cos(angle), y: cy + b * Math.sin(angle) };
804
+ }
805
+
806
+ // Rectangle: find intersection with edges
807
+ const hw = (el.width || 0) / 2;
808
+ const hh = (el.height || 0) / 2;
809
+ if (dx === 0 && dy === 0) return { x: cx, y: cy + hh };
810
+ const angle = Math.atan2(dy, dx);
811
+ const tanA = Math.tan(angle);
812
+ // Check if ray intersects top/bottom edge or left/right edge
813
+ if (Math.abs(tanA * hw) <= hh) {
814
+ // Intersects left or right edge
815
+ const signX = dx >= 0 ? 1 : -1;
816
+ return { x: cx + signX * hw, y: cy + signX * hw * tanA };
817
+ } else {
818
+ // Intersects top or bottom edge
819
+ const signY = dy >= 0 ? 1 : -1;
820
+ return { x: cx + signY * hh / tanA, y: cy + signY * hh };
821
+ }
822
+ }
823
+
824
+ // Helper: resolve arrow bindings in a batch
825
+ function resolveArrowBindings(canvas: Canvas, batchElements: ServerElement[], includeExisting = true): void {
826
+ const elementMap = new Map<string, ServerElement>();
827
+ batchElements.forEach(el => elementMap.set(el.id, el));
828
+
829
+ // Also check existing elements for cross-batch references
830
+ if (includeExisting) {
831
+ canvas.elements.forEach((el, id) => {
832
+ if (!elementMap.has(id)) elementMap.set(id, el);
833
+ });
834
+ }
835
+
836
+ for (const el of batchElements) {
837
+ if (el.type !== 'arrow' && el.type !== 'line') continue;
838
+ const startRef = (el as any).start as { id: string } | undefined;
839
+ const endRef = (el as any).end as { id: string } | undefined;
840
+
841
+ if (!startRef && !endRef) continue;
842
+
843
+ const startEl = startRef ? elementMap.get(startRef.id) : undefined;
844
+ const endEl = endRef ? elementMap.get(endRef.id) : undefined;
845
+
846
+ // An elbow arrow between two shapes runs at right angles round whatever else is in the way.
847
+ if ((el as any).elbowed === true && startEl && endEl && routeArrowAround(el, startEl, endEl, elementMap.values())) continue;
848
+
849
+ // Calculate arrow path from edge to edge
850
+ const startCenter = startEl
851
+ ? { x: startEl.x + (startEl.width || 0) / 2, y: startEl.y + (startEl.height || 0) / 2 }
852
+ : { x: el.x, y: el.y };
853
+ const endCenter = endEl
854
+ ? { x: endEl.x + (endEl.width || 0) / 2, y: endEl.y + (endEl.height || 0) / 2 }
855
+ : { x: el.x + 100, y: el.y };
856
+
857
+ const GAP = 8;
858
+ const startPt = startEl
859
+ ? computeEdgePoint(startEl, endCenter.x, endCenter.y)
860
+ : startCenter;
861
+ const endPt = endEl
862
+ ? computeEdgePoint(endEl, startCenter.x, startCenter.y)
863
+ : endCenter;
864
+
865
+ // Apply gap: move start point slightly away from source, end point slightly away from target
866
+ const startDx = endPt.x - startPt.x;
867
+ const startDy = endPt.y - startPt.y;
868
+ const startDist = Math.sqrt(startDx * startDx + startDy * startDy) || 1;
869
+ const endDx = startPt.x - endPt.x;
870
+ const endDy = startPt.y - endPt.y;
871
+ const endDist = Math.sqrt(endDx * endDx + endDy * endDy) || 1;
872
+
873
+ const finalStart = {
874
+ x: startPt.x + (startDx / startDist) * GAP,
875
+ y: startPt.y + (startDy / startDist) * GAP
876
+ };
877
+ const finalEnd = {
878
+ x: endPt.x + (endDx / endDist) * GAP,
879
+ y: endPt.y + (endDy / endDist) * GAP
880
+ };
881
+
882
+ // Set arrow position and points
883
+ el.x = finalStart.x;
884
+ el.y = finalStart.y;
885
+ el.points = [[0, 0], [finalEnd.x - finalStart.x, finalEnd.y - finalStart.y]];
886
+
887
+ // Do NOT delete `start` and `end` here.
888
+ // Excalidraw's frontend `convertToExcalidrawElements` method looks for these exact properties
889
+ // to calculate mathematically sound `startBinding`, `endBinding`, `focus`, `gap`, and `boundElements`.
890
+ }
891
+ }
892
+
893
+ // After a shape's geometry changes, recompute every arrow bound to it so the
894
+ // visual connection follows the shape — bindings are otherwise only resolved
895
+ // at creation time, which left arrows floating at stale coordinates when
896
+ // update/align/distribute moved their endpoints. Returns the re-routed arrows.
897
+ function rerouteBoundArrows(canvas: Canvas, movedId: string): ServerElement[] {
898
+ const rerouted: ServerElement[] = [];
899
+ canvas.elements.forEach(el => {
900
+ if (el.type !== 'arrow' && el.type !== 'line') return;
901
+ const startRef = (el as any).start as { id: string } | undefined;
902
+ const endRef = (el as any).end as { id: string } | undefined;
903
+ if (startRef?.id !== movedId && endRef?.id !== movedId) return;
904
+ resolveArrowBindings(canvas, [el]);
905
+ el.updatedAt = new Date().toISOString();
906
+ el.version = (el.version || 0) + 1;
907
+ rerouted.push(el);
908
+ });
909
+ return rerouted;
910
+ }
911
+
912
+ // Batch create elements
913
+ app.post('/api/elements/batch', (req: Request, res: Response) => {
914
+ const canvas = req.canvas;
915
+ try {
916
+ const { elements: elementsToCreate, replace = false } = req.body ?? {};
917
+
918
+ if (!Array.isArray(elementsToCreate)) {
919
+ return res.status(400).json({
920
+ success: false,
921
+ error: 'Expected an array of elements'
922
+ });
923
+ }
924
+ if (typeof replace !== 'boolean') {
925
+ return res.status(400).json({
926
+ success: false,
927
+ error: 'replace must be a boolean'
928
+ });
929
+ }
930
+
931
+ const createdElements: ServerElement[] = [];
932
+
933
+ elementsToCreate.forEach(elementData => {
934
+ const params = CreateElementSchema.parse(elementData);
935
+ // Prioritize passed ID (for MCP sync), otherwise generate new ID
936
+ const id = params.id || generateId();
937
+ const element: ServerElement = {
938
+ id,
939
+ ...params,
940
+ fontFamily: normalizeFontFamily(params.fontFamily),
941
+ createdAt: new Date().toISOString(),
942
+ updatedAt: new Date().toISOString(),
943
+ version: 1
944
+ };
945
+
946
+ createdElements.push(element);
947
+ });
948
+
949
+ // Fully prepare the batch before mutating storage. Replacement imports do
950
+ // not resolve bindings against elements that are about to be discarded.
951
+ resolveArrowBindings(canvas, createdElements, !replace);
952
+
953
+ const replacedCount = replace ? canvas.elements.size : 0;
954
+ commitCanvasMutation(canvas, () => {
955
+ if (replace) { keepSafetyCopy(canvas); canvas.elements.clear(); }
956
+ createdElements.forEach(el => canvas.elements.set(el.id, el));
957
+ });
958
+
959
+ // Publish only after clear + replacement have reached one checkpoint.
960
+ if (replace) {
961
+ broadcast(canvas, {
962
+ type: 'canvas_cleared',
963
+ timestamp: new Date().toISOString()
964
+ });
965
+ logger.info(`Canvas replaced: ${replacedCount} existing elements removed`);
966
+ }
967
+
968
+ // Broadcast to all connected clients
969
+ const message: BatchCreatedMessage = {
970
+ type: 'elements_batch_created',
971
+ elements: createdElements
972
+ };
973
+ broadcast(canvas, message);
974
+
975
+ res.json({
976
+ success: true,
977
+ elements: createdElements,
978
+ count: createdElements.length
979
+ });
980
+ } catch (error) {
981
+ logger.error('Error batch creating elements:', error);
982
+ res.status(mutationErrorStatus(error, 400)).json({
983
+ success: false,
984
+ error: (error as Error).message
985
+ });
986
+ }
987
+ });
988
+
989
+ // Routes arrows at right angles round the other shapes (and marks them elbowed), for a layout that has changed since
990
+ // they were drawn. Each arrow's ends are the shapes it starts and ends on, by `start`/`end` or by its bindings.
991
+ app.post('/api/elements/route', (req: Request, res: Response) => {
992
+ const canvas = req.canvas;
993
+ const ids: string[] | undefined = req.body?.ids;
994
+ if (ids !== undefined && (!Array.isArray(ids) || !ids.every(id => typeof id === 'string'))) {
995
+ return res.status(400).json({ success: false, error: 'ids must be a list of element ids' });
996
+ }
997
+ const arrows = ids
998
+ ? [...new Set(ids)].map(id => canvas.elements.get(id)).filter((e): e is ServerElement => !!e)
999
+ : Array.from(canvas.elements.values()).filter(e => e.type === 'arrow' && (e as any).elbowed === true);
1000
+ const missing = (ids ?? []).filter(id => !canvas.elements.has(id));
1001
+ if (missing.length) return res.status(404).json({ success: false, error: `Not found: ${missing.join(', ')}` });
1002
+
1003
+ const routed: ServerElement[] = [];
1004
+ const skipped: Array<{ id: string; reason: string }> = [];
1005
+ // A search can take tens of milliseconds and nothing else runs meanwhile, so one call routes a bounded number.
1006
+ const MAX_ROUTES = 200;
1007
+ arrows.slice(MAX_ROUTES).forEach(arrow => skipped.push({ id: arrow.id, reason: `over ${MAX_ROUTES} arrows in one call; call again with these ids` }));
1008
+ commitCanvasMutation(canvas, () => {
1009
+ for (const arrow of arrows.slice(0, MAX_ROUTES)) {
1010
+ const ends = [(arrow as any).start?.id ?? (arrow as any).startBinding?.elementId, (arrow as any).end?.id ?? (arrow as any).endBinding?.elementId];
1011
+ const [start, end] = ends.map(id => (id ? canvas.elements.get(id) : undefined));
1012
+ if (arrow.type !== 'arrow') skipped.push({ id: arrow.id, reason: 'not an arrow' });
1013
+ else if (!start || !end) skipped.push({ id: arrow.id, reason: 'it does not start and end on shapes' });
1014
+ else if (!routeArrowAround(arrow, start, end, canvas.elements.values())) skipped.push({ id: arrow.id, reason: 'no route found; left as it was' });
1015
+ else {
1016
+ Object.assign(arrow, { elbowed: true, updatedAt: new Date().toISOString(), version: (arrow.version || 0) + 1 });
1017
+ routed.push(arrow);
1018
+ }
1019
+ }
1020
+ });
1021
+ for (const arrow of routed) broadcast(canvas, { type: 'element_updated', element: arrow } as ElementUpdatedMessage);
1022
+ res.json({ success: true, routed: routed.map(a => a.id), skipped });
1023
+ });
1024
+
1025
+ // Stacking order is the order of the scene, so sending elements to the back or front rebuilds it. A text label goes with
1026
+ // its container, and the elements keep their order among themselves.
1027
+ app.post('/api/elements/order', (req: Request, res: Response) => {
1028
+ const canvas = req.canvas;
1029
+ const { ids, to } = req.body ?? {};
1030
+ if (!Array.isArray(ids) || ids.length === 0 || !ids.every(id => typeof id === 'string')) {
1031
+ return res.status(400).json({ success: false, error: 'ids must be a non-empty list of element ids' });
1032
+ }
1033
+ if (to !== 'back' && to !== 'front') return res.status(400).json({ success: false, error: 'to must be back or front' });
1034
+ const missing = ids.filter(id => !canvas.elements.has(id));
1035
+ if (missing.length) return res.status(404).json({ success: false, error: `Not found: ${missing.join(', ')}` });
1036
+
1037
+ const moving = new Set<string>(ids);
1038
+ const all = Array.from(canvas.elements.values());
1039
+ for (const element of all) if (element.type === 'text' && element.containerId && moving.has(element.containerId)) moving.add(element.id);
1040
+ const picked = all.filter(element => moving.has(element.id));
1041
+ const rest = all.filter(element => !moving.has(element.id));
1042
+ const ordered = to === 'back' ? [...picked, ...rest] : [...rest, ...picked];
1043
+ commitCanvasMutation(canvas, () => {
1044
+ canvas.elements.clear();
1045
+ ordered.forEach(element => canvas.elements.set(element.id, element));
1046
+ });
1047
+ // The same two messages a replacement sends: a client takes the new order from them.
1048
+ broadcast(canvas, { type: 'canvas_cleared', timestamp: new Date().toISOString() });
1049
+ broadcast(canvas, { type: 'elements_batch_created', elements: ordered } as BatchCreatedMessage);
1050
+ res.json({ success: true, count: picked.length });
1051
+ });
1052
+
1053
+ // Convert Mermaid diagram to Excalidraw elements
1054
+ app.post('/api/elements/from-mermaid', (req: Request, res: Response) => {
1055
+ const canvas = req.canvas;
1056
+ try {
1057
+ const { mermaidDiagram, config } = req.body;
1058
+
1059
+ if (!mermaidDiagram || typeof mermaidDiagram !== 'string') {
1060
+ return res.status(400).json({
1061
+ success: false,
1062
+ error: 'Mermaid diagram definition is required'
1063
+ });
1064
+ }
1065
+
1066
+ logger.info('Received Mermaid conversion request', {
1067
+ diagramLength: mermaidDiagram.length,
1068
+ hasConfig: !!config
1069
+ });
1070
+
1071
+ // Broadcast to all WebSocket clients to process the Mermaid diagram
1072
+ broadcast(canvas, {
1073
+ type: 'mermaid_convert',
1074
+ mermaidDiagram,
1075
+ config: config || {},
1076
+ timestamp: new Date().toISOString()
1077
+ });
1078
+
1079
+ // Return the diagram for frontend processing
1080
+ res.json({
1081
+ success: true,
1082
+ mermaidDiagram,
1083
+ config: config || {},
1084
+ message: 'Mermaid diagram sent to frontend for conversion.'
1085
+ });
1086
+ } catch (error) {
1087
+ logger.error('Error processing Mermaid diagram:', error);
1088
+ res.status(400).json({
1089
+ success: false,
1090
+ error: (error as Error).message
1091
+ });
1092
+ }
1093
+ });
1094
+
1095
+ // Sync elements from frontend (overwrite sync)
1096
+ app.post('/api/elements/sync', (req: Request, res: Response) => {
1097
+ const canvas = req.canvas;
1098
+ try {
1099
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
1100
+ const { elements: frontendElements, timestamp } = body;
1101
+
1102
+ // Validate input data
1103
+ if (!Array.isArray(frontendElements)) {
1104
+ return res.status(400).json({
1105
+ success: false,
1106
+ error: 'Expected elements to be an array'
1107
+ });
1108
+ }
1109
+
1110
+ logger.info(`Sync request received: ${frontendElements.length} elements`, {
1111
+ timestamp,
1112
+ elementCount: frontendElements.length
1113
+ });
1114
+
1115
+ // Record element count before sync
1116
+ const beforeCount = canvas.elements.size;
1117
+ let successCount = 0;
1118
+ const processedElements: ServerElement[] = [];
1119
+
1120
+ commitCanvasMutation(canvas, () => {
1121
+ if (frontendElements.length === 0) keepSafetyCopy(canvas);
1122
+ canvas.elements.clear();
1123
+ frontendElements.forEach((element: any, index: number) => {
1124
+ try {
1125
+ // Ensure element has ID, generate one if missing
1126
+ const elementId = element.id || generateId();
1127
+
1128
+ // Add server metadata
1129
+ const processedElement: ServerElement = {
1130
+ ...element,
1131
+ id: elementId,
1132
+ syncedAt: new Date().toISOString(),
1133
+ source: 'frontend_sync',
1134
+ syncTimestamp: timestamp,
1135
+ version: 1
1136
+ };
1137
+
1138
+ canvas.elements.set(elementId, processedElement);
1139
+ processedElements.push(processedElement);
1140
+ successCount++;
1141
+ } catch (elementError) {
1142
+ logger.warn(`Failed to process element ${index}:`, elementError);
1143
+ }
1144
+ });
1145
+ });
1146
+
1147
+ logger.info(`Cleared existing elements: ${beforeCount} elements removed`);
1148
+ logger.info(`Sync completed: ${successCount}/${frontendElements.length} elements synced`);
1149
+
1150
+ // 3. Broadcast sync event to all WebSocket clients
1151
+ broadcast(canvas, {
1152
+ type: 'elements_synced',
1153
+ count: successCount,
1154
+ timestamp: new Date().toISOString(),
1155
+ source: 'manual_sync'
1156
+ });
1157
+
1158
+ // 4. Return sync results
1159
+ res.json({
1160
+ success: true,
1161
+ message: `Successfully synced ${successCount} elements`,
1162
+ count: successCount,
1163
+ syncedAt: new Date().toISOString(),
1164
+ beforeCount,
1165
+ afterCount: canvas.elements.size
1166
+ });
1167
+
1168
+ } catch (error) {
1169
+ logger.error('Sync error:', error);
1170
+ res.status(500).json({
1171
+ success: false,
1172
+ error: (error as Error).message,
1173
+ details: 'Internal server error during sync operation'
1174
+ });
1175
+ }
1176
+ });
1177
+
1178
+ // ─── Files API (for image elements) ───────────────────────────
1179
+ // GET all files
1180
+ app.get('/api/files', (req: Request, res: Response) => {
1181
+ const canvas = req.canvas;
1182
+ const filesObj: Record<string, ExcalidrawFile> = {};
1183
+ canvas.files.forEach((f, id) => { filesObj[id] = f; });
1184
+ res.json({ files: filesObj });
1185
+ });
1186
+
1187
+ // POST add/update files (batch)
1188
+ app.post('/api/files', (req: Request, res: Response) => {
1189
+ const canvas = req.canvas;
1190
+ try {
1191
+ const body = req.body;
1192
+ // Keep the existing endpoint's accepted wrapper/array shapes and count
1193
+ // behavior. Durable mode adds publication guarantees without redefining
1194
+ // the memory-only request contract.
1195
+ const fileList = (Array.isArray(body) ? body : (body?.files || [])) as unknown[];
1196
+ const preparedFiles = prepareFileWrites(canvas, fileList);
1197
+
1198
+ commitCanvasMutation(canvas, () => {
1199
+ preparedFiles.forEach(file => canvas.files.set(file.id, file));
1200
+ });
1201
+ // Broadcast only after every referenced blob and the checkpoint are durable.
1202
+ broadcast(canvas, { type: 'files_added', files: fileList });
1203
+ res.json({ success: true, count: fileList.length });
1204
+ } catch (error) {
1205
+ logger.error('Error storing canvas files:', error);
1206
+ if (!durableStateEnabled()) throw error;
1207
+ res.status(mutationErrorStatus(error, 400)).json({
1208
+ success: false,
1209
+ error: (error as Error).message
1210
+ });
1211
+ }
1212
+ });
1213
+
1214
+ // DELETE a file
1215
+ app.delete('/api/files/:id', (req: Request, res: Response) => {
1216
+ const canvas = req.canvas;
1217
+ try {
1218
+ const id = req.params.id as string;
1219
+ if (!canvas.files.has(id)) {
1220
+ return res.status(404).json({ success: false, error: `File with ID ${id} not found` });
1221
+ }
1222
+ commitCanvasMutation(canvas, () => canvas.files.delete(id));
1223
+ broadcast(canvas, { type: 'file_deleted', fileId: id });
1224
+ res.json({ success: true });
1225
+ } catch (error) {
1226
+ logger.error('Error deleting canvas file:', error);
1227
+ res.status(mutationErrorStatus(error, 500)).json({
1228
+ success: false,
1229
+ error: (error as Error).message
1230
+ });
1231
+ }
1232
+ });
1233
+
1234
+ // Image export: request (MCP -> Express -> WebSocket -> Frontend)
1235
+ interface PendingExport {
1236
+ canvasId: string;
1237
+ resolve: (data: { format: string; data: string }) => void;
1238
+ reject: (error: Error) => void;
1239
+ timeout: ReturnType<typeof setTimeout>;
1240
+ collectionTimeout: ReturnType<typeof setTimeout> | null;
1241
+ bestResult: { format: string; data: string } | null;
1242
+ }
1243
+ const pendingExports = new Map<string, PendingExport>();
1244
+
1245
+ const exportImageSchema = z.object({
1246
+ format: z.enum(['png', 'svg']),
1247
+ background: z.boolean().optional(),
1248
+ renderer: z.enum(['auto', 'node', 'browser']).optional(),
1249
+ dark: z.boolean().optional(),
1250
+ scale: z.number().min(1).max(MAX_SCALE).optional(),
1251
+ padding: z.number().min(0).optional(),
1252
+ elementIds: z.array(z.string()).min(1).optional(),
1253
+ frameId: z.string().optional(),
1254
+ embedScene: z.boolean().default(false),
1255
+ embedFonts: z.boolean().optional()
1256
+ });
1257
+ type ExportImageBody = z.infer<typeof exportImageSchema>;
1258
+
1259
+ const NO_BROWSER_TAB_ERROR = 'No frontend client connected. Open the canvas in a browser first.';
1260
+
1261
+ // Ask the open browser tab(s) to render — Excalidraw's own exporter in a real
1262
+ // browser. Slower (re-sync + 3 s collection window) and needs a tab, but it
1263
+ // is the reference rendering, so it stays available as renderer:'browser'.
1264
+ function exportViaBrowserTab(canvas: Canvas, options: ExportImageBody): Promise<{ format: string; data: string }> {
1265
+ const { format, background, renderer: _renderer, ...rest } = options;
1266
+ const requestId = generateId();
1267
+
1268
+ const exportPromise = new Promise<{ format: string; data: string }>((resolve, reject) => {
1269
+ const timeout = setTimeout(() => {
1270
+ const pending = pendingExports.get(requestId);
1271
+ pendingExports.delete(requestId);
1272
+ // If we collected any result during the window, use it
1273
+ if (pending?.bestResult) {
1274
+ resolve(pending.bestResult);
1275
+ } else {
1276
+ reject(new Error('Export timed out after 30 seconds'));
1277
+ }
1278
+ }, 30000);
1279
+
1280
+ pendingExports.set(requestId, { canvasId: canvas.id, resolve, reject, timeout, collectionTimeout: null, bestResult: null });
1281
+ });
1282
+
1283
+ // Re-broadcast current elements so all connected clients (including stale ones)
1284
+ // sync to the canonical server state before exporting
1285
+ const filesObj: Record<string, ExcalidrawFile> = {};
1286
+ canvas.files.forEach((f, id) => { filesObj[id] = f; });
1287
+ broadcast(canvas, {
1288
+ type: 'initial_elements',
1289
+ elements: Array.from(canvas.elements.values()),
1290
+ forExport: true,
1291
+ ...(canvas.files.size > 0 ? { files: filesObj } : {})
1292
+ } as InitialElementsMessage & { files?: Record<string, ExcalidrawFile> });
1293
+
1294
+ // Give browsers time to process the reload before requesting export
1295
+ setTimeout(() => {
1296
+ broadcast(canvas, {
1297
+ type: 'export_image_request',
1298
+ requestId,
1299
+ format,
1300
+ background: background ?? true,
1301
+ options: { background, ...rest }
1302
+ });
1303
+ }, 800);
1304
+
1305
+ return exportPromise;
1306
+ }
1307
+
1308
+ app.post('/api/export/image', async (req: Request, res: Response) => {
1309
+ const canvas = req.canvas;
1310
+ const parsed = exportImageSchema.safeParse(req.body ?? {});
1311
+ if (!parsed.success) {
1312
+ const issue = parsed.error.issues[0];
1313
+ const where = issue?.path.join('.');
1314
+ return res.status(400).json({
1315
+ success: false,
1316
+ error: where === 'format'
1317
+ ? 'format must be "png" or "svg"'
1318
+ : `${where ? `${where}: ` : ''}${issue?.message ?? 'invalid request'}`
1319
+ });
1320
+ }
1321
+ const options = parsed.data;
1322
+ if (options.embedScene && options.format !== 'png') {
1323
+ return res.status(400).json({ success: false, error: 'embedScene is only supported for PNG exports' });
1324
+ }
1325
+ const renderer = options.renderer ?? 'auto';
1326
+
1327
+ const respondBrowser = async () => {
1328
+ if (clientsOf(canvas).size === 0) {
1329
+ return res.status(503).json({ success: false, error: NO_BROWSER_TAB_ERROR });
1330
+ }
1331
+ try {
1332
+ const result = await exportViaBrowserTab(canvas, options);
1333
+ res.json({ success: true, format: result.format, data: result.data, renderer: 'browser' });
1334
+ } catch (error) {
1335
+ res.status(500).json({ success: false, error: (error as Error).message });
1336
+ }
1337
+ };
1338
+
1339
+ if (renderer === 'browser') return respondBrowser();
1340
+
1341
+ try {
1342
+ const { renderer: _renderer, ...renderOptions } = options;
1343
+ const scene = { elements: Array.from(canvas.elements.values()), files: Object.fromEntries(canvas.files) };
1344
+ const result = await renderScene(scene, renderOptions);
1345
+ res.json({
1346
+ success: true,
1347
+ format: result.format,
1348
+ data: result.data,
1349
+ renderer: 'node',
1350
+ width: result.width,
1351
+ height: result.height,
1352
+ ...(result.warnings.length > 0 ? { warnings: result.warnings } : {})
1353
+ });
1354
+ } catch (error) {
1355
+ if (error instanceof RenderError) {
1356
+ return res.status(error.status).json({ success: false, error: error.message });
1357
+ }
1358
+ logger.error('Headless image export failed:', error);
1359
+ if (renderer === 'auto' && clientsOf(canvas).size > 0) {
1360
+ // The reference renderer is available; use it rather than fail
1361
+ logger.warn('Falling back to the browser tab for this export');
1362
+ return respondBrowser();
1363
+ }
1364
+ res.status(500).json({ success: false, error: (error as Error).message });
1365
+ }
1366
+ });
1367
+
1368
+ // Image export: result (Frontend -> Express -> MCP)
1369
+ app.post('/api/export/image/result', (req: Request, res: Response) => {
1370
+ const canvas = req.canvas;
1371
+ try {
1372
+ const { requestId, format, data, error } = req.body;
1373
+
1374
+ if (!requestId) {
1375
+ return res.status(400).json({
1376
+ success: false,
1377
+ error: 'requestId is required'
1378
+ });
1379
+ }
1380
+
1381
+ const pending = pendingExports.get(requestId);
1382
+ if (!pending || pending.canvasId !== canvas.id) {
1383
+ // Already resolved by another client, or expired — ignore silently
1384
+ return res.json({ success: true });
1385
+ }
1386
+
1387
+ if (error) {
1388
+ // Don't reject on error — another WebSocket client may still succeed.
1389
+ logger.warn(`Export error from one client (requestId=${requestId}): ${error}`);
1390
+ return res.json({ success: true });
1391
+ }
1392
+
1393
+ // Keep the largest response (most complete canvas state wins)
1394
+ if (!pending.bestResult || data.length > pending.bestResult.data.length) {
1395
+ pending.bestResult = { format, data };
1396
+ }
1397
+
1398
+ // Start a short collection window on the first response, then resolve with best
1399
+ if (!pending.collectionTimeout) {
1400
+ pending.collectionTimeout = setTimeout(() => {
1401
+ const p = pendingExports.get(requestId);
1402
+ if (p?.bestResult) {
1403
+ clearTimeout(p.timeout);
1404
+ pendingExports.delete(requestId);
1405
+ p.resolve(p.bestResult);
1406
+ }
1407
+ }, 3000);
1408
+ }
1409
+
1410
+ res.json({ success: true });
1411
+ } catch (error) {
1412
+ logger.error('Error processing export result:', error);
1413
+ res.status(500).json({
1414
+ success: false,
1415
+ error: (error as Error).message
1416
+ });
1417
+ }
1418
+ });
1419
+
1420
+ // Viewport control: request (MCP -> Express -> WebSocket -> Frontend)
1421
+ interface PendingViewport {
1422
+ canvasId: string;
1423
+ resolve: (data: { success: boolean; message: string }) => void;
1424
+ reject: (error: Error) => void;
1425
+ timeout: ReturnType<typeof setTimeout>;
1426
+ }
1427
+ const pendingViewports = new Map<string, PendingViewport>();
1428
+
1429
+ const viewportRequestSchema = z.object({
1430
+ scrollToContent: z.boolean().optional(),
1431
+ scrollToElementIds: z.array(z.string().min(1)).min(1).optional(),
1432
+ viewportZoomFactor: z.number().positive().max(1).optional(),
1433
+ scrollToElementId: z.string().min(1).optional(),
1434
+ zoom: z.number().min(0.1).max(10).optional(),
1435
+ offsetX: z.number().optional(),
1436
+ offsetY: z.number().optional()
1437
+ }).superRefine((params, ctx) => {
1438
+ const modes = [
1439
+ params.scrollToContent === true,
1440
+ params.scrollToElementIds !== undefined,
1441
+ params.scrollToElementId !== undefined,
1442
+ params.zoom !== undefined || params.offsetX !== undefined || params.offsetY !== undefined
1443
+ ].filter(Boolean).length;
1444
+
1445
+ if (modes !== 1) {
1446
+ ctx.addIssue({
1447
+ code: z.ZodIssueCode.custom,
1448
+ message: 'Specify exactly one viewport mode: scrollToContent, scrollToElementIds, scrollToElementId, or manual zoom/offset'
1449
+ });
1450
+ }
1451
+ if (params.viewportZoomFactor !== undefined &&
1452
+ params.scrollToContent !== true &&
1453
+ params.scrollToElementIds === undefined) {
1454
+ ctx.addIssue({
1455
+ code: z.ZodIssueCode.custom,
1456
+ path: ['viewportZoomFactor'],
1457
+ message: 'viewportZoomFactor requires scrollToContent or scrollToElementIds'
1458
+ });
1459
+ }
1460
+ });
1461
+
1462
+ app.post('/api/viewport', (req: Request, res: Response) => {
1463
+ const canvas = req.canvas;
1464
+ try {
1465
+ const {
1466
+ scrollToContent,
1467
+ scrollToElementIds,
1468
+ scrollToElementId,
1469
+ viewportZoomFactor,
1470
+ zoom,
1471
+ offsetX,
1472
+ offsetY
1473
+ } = viewportRequestSchema.parse(req.body);
1474
+
1475
+ if (clientsOf(canvas).size === 0) {
1476
+ return res.status(503).json({
1477
+ success: false,
1478
+ error: 'No frontend client connected. Open the canvas in a browser first.'
1479
+ });
1480
+ }
1481
+
1482
+ const requestId = generateId();
1483
+
1484
+ const viewportPromise = new Promise<{ success: boolean; message: string }>((resolve, reject) => {
1485
+ const timeout = setTimeout(() => {
1486
+ pendingViewports.delete(requestId);
1487
+ reject(new Error('Viewport request timed out after 10 seconds'));
1488
+ }, 10000);
1489
+
1490
+ pendingViewports.set(requestId, { canvasId: canvas.id, resolve, reject, timeout });
1491
+ });
1492
+
1493
+ broadcast(canvas, {
1494
+ type: 'set_viewport',
1495
+ requestId,
1496
+ scrollToContent,
1497
+ scrollToElementIds,
1498
+ scrollToElementId,
1499
+ viewportZoomFactor,
1500
+ zoom,
1501
+ offsetX,
1502
+ offsetY
1503
+ });
1504
+
1505
+ viewportPromise
1506
+ .then(result => {
1507
+ res.json(result);
1508
+ })
1509
+ .catch(error => {
1510
+ res.status(500).json({
1511
+ success: false,
1512
+ error: (error as Error).message
1513
+ });
1514
+ });
1515
+ } catch (error) {
1516
+ logger.error('Error initiating viewport change:', error);
1517
+ res.status(error instanceof z.ZodError ? 400 : 500).json({
1518
+ success: false,
1519
+ error: error instanceof z.ZodError
1520
+ ? error.issues.map(issue => issue.message).join('; ')
1521
+ : (error as Error).message
1522
+ });
1523
+ }
1524
+ });
1525
+
1526
+ // Viewport control: result (Frontend -> Express -> MCP)
1527
+ app.post('/api/viewport/result', (req: Request, res: Response) => {
1528
+ try {
1529
+ const { requestId, success, message, error } = req.body;
1530
+
1531
+ if (!requestId) {
1532
+ return res.status(400).json({
1533
+ success: false,
1534
+ error: 'requestId is required'
1535
+ });
1536
+ }
1537
+
1538
+ const pending = pendingViewports.get(requestId);
1539
+ if (!pending || pending.canvasId !== req.canvas.id) {
1540
+ return res.json({ success: true });
1541
+ }
1542
+
1543
+ if (error || success === false) {
1544
+ clearTimeout(pending.timeout);
1545
+ pendingViewports.delete(requestId);
1546
+ pending.reject(new Error(error || message || 'Viewport update failed'));
1547
+ return res.json({ success: true });
1548
+ }
1549
+
1550
+ clearTimeout(pending.timeout);
1551
+ pendingViewports.delete(requestId);
1552
+ pending.resolve({ success: true, message: message || 'Viewport updated' });
1553
+
1554
+ res.json({ success: true });
1555
+ } catch (error) {
1556
+ logger.error('Error processing viewport result:', error);
1557
+ res.status(500).json({
1558
+ success: false,
1559
+ error: (error as Error).message
1560
+ });
1561
+ }
1562
+ });
1563
+
1564
+ app.use('/api/comments', createCommentRouter(broadcast));
1565
+ app.use('/api/canvases', createCanvasRouter(registry, removed => {
1566
+ clientsOf(removed).forEach(client => client.close(4410, 'Canvas deleted'));
1567
+ clientsByCanvas.delete(removed.id);
1568
+ }));
1569
+ app.use('/api/ai', createAiRouter());
1570
+ app.use('/mcp', createMcpRouter());
1571
+ // A host in front of the canvas may answer this itself with links for the signed-in user.
1572
+ app.get('/api/nav', (_req: Request, res: Response) => { res.json({ success: true, links: [] }); });
1573
+
1574
+ // Snapshots: save
1575
+ app.post('/api/snapshots', (req: Request, res: Response) => {
1576
+ const canvas = req.canvas;
1577
+ try {
1578
+ const { name } = req.body;
1579
+
1580
+ if (!name || typeof name !== 'string') {
1581
+ return res.status(400).json({
1582
+ success: false,
1583
+ error: 'Snapshot name is required'
1584
+ });
1585
+ }
1586
+
1587
+ if (name.startsWith(SAFETY_PREFIX)) {
1588
+ return res.status(400).json({
1589
+ success: false,
1590
+ error: `Snapshot names starting with "${SAFETY_PREFIX}" are reserved for the copies kept before a clear`
1591
+ });
1592
+ }
1593
+
1594
+ const snapshot: Snapshot = {
1595
+ name,
1596
+ // Snapshots are historical values, not aliases to live mutable elements.
1597
+ // Bound-arrow rerouting mutates arrow objects in place. structuredClone
1598
+ // is available across the supported Node.js >=20 runtime range.
1599
+ elements: structuredClone(Array.from(canvas.elements.values())),
1600
+ createdAt: new Date().toISOString()
1601
+ };
1602
+
1603
+ commitCanvasMutation(canvas, () => canvas.snapshots.set(name, snapshot));
1604
+ logger.info(`Snapshot saved: "${name}" with ${snapshot.elements.length} elements`);
1605
+
1606
+ res.json({
1607
+ success: true,
1608
+ name,
1609
+ elementCount: snapshot.elements.length,
1610
+ createdAt: snapshot.createdAt
1611
+ });
1612
+ } catch (error) {
1613
+ logger.error('Error saving snapshot:', error);
1614
+ res.status(mutationErrorStatus(error, 500)).json({
1615
+ success: false,
1616
+ error: (error as Error).message
1617
+ });
1618
+ }
1619
+ });
1620
+
1621
+ // Snapshots: list
1622
+ app.get('/api/snapshots', (req: Request, res: Response) => {
1623
+ const canvas = req.canvas;
1624
+ try {
1625
+ const list = Array.from(canvas.snapshots.values()).map(s => ({
1626
+ name: s.name,
1627
+ elementCount: s.elements.length,
1628
+ createdAt: s.createdAt
1629
+ }));
1630
+
1631
+ res.json({
1632
+ success: true,
1633
+ snapshots: list,
1634
+ count: list.length
1635
+ });
1636
+ } catch (error) {
1637
+ logger.error('Error listing snapshots:', error);
1638
+ res.status(500).json({
1639
+ success: false,
1640
+ error: (error as Error).message
1641
+ });
1642
+ }
1643
+ });
1644
+
1645
+ // Snapshots: get by name
1646
+ app.get('/api/snapshots/:name', (req: Request, res: Response) => {
1647
+ const canvas = req.canvas;
1648
+ try {
1649
+ const { name } = req.params;
1650
+ const snapshot = canvas.snapshots.get(name!);
1651
+
1652
+ if (!snapshot) {
1653
+ return res.status(404).json({
1654
+ success: false,
1655
+ error: `Snapshot "${name}" not found`
1656
+ });
1657
+ }
1658
+
1659
+ res.json({
1660
+ success: true,
1661
+ snapshot
1662
+ });
1663
+ } catch (error) {
1664
+ logger.error('Error fetching snapshot:', error);
1665
+ res.status(500).json({
1666
+ success: false,
1667
+ error: (error as Error).message
1668
+ });
1669
+ }
1670
+ });
1671
+
1672
+ // Serve the frontend
1673
+ app.get('/', (req: Request, res: Response) => {
1674
+ const htmlFile = path.join(__dirname, '../dist/frontend/index.html');
1675
+ res.sendFile(htmlFile, (err) => {
1676
+ if (err) {
1677
+ logger.error('Error serving frontend:', err);
1678
+ res.status(404).send('Frontend not found. Please run "npm run build" first.');
1679
+ }
1680
+ });
1681
+ });
1682
+
1683
+ // Health check endpoint
1684
+ app.get('/health', (req: Request, res: Response) => {
1685
+ const canvas = req.canvas;
1686
+ res.json({
1687
+ status: 'healthy',
1688
+ timestamp: new Date().toISOString(),
1689
+ elements_count: canvas.elements.size,
1690
+ websocket_clients: clientsOf(canvas).size,
1691
+ // Image renderers available right now: headless (always, in-process) and
1692
+ // the number of browser tabs that can render on request
1693
+ renderers: { node: true, browser: clientsOf(canvas).size },
1694
+ ...(durableStateEnabled() ? { durable_state_enabled: true } : {}),
1695
+ // Identity for `stop`: it must only ever signal a process that both
1696
+ // identifies as this service AND self-reports its pid — never a pid
1697
+ // from a stale pidfile or an unrelated app squatting on the port.
1698
+ service: 'daigram-canvas',
1699
+ pid: process.pid
1700
+ });
1701
+ });
1702
+
1703
+ // Sync status endpoint
1704
+ app.get('/api/sync/status', (req: Request, res: Response) => {
1705
+ const canvas = req.canvas;
1706
+ res.json({
1707
+ success: true,
1708
+ elementCount: canvas.elements.size,
1709
+ ...(durableStateEnabled() ? { durableStateEnabled: true } : {}),
1710
+ timestamp: new Date().toISOString(),
1711
+ memoryUsage: {
1712
+ heapUsed: Math.round(process.memoryUsage().heapUsed / 1024 / 1024), // MB
1713
+ heapTotal: Math.round(process.memoryUsage().heapTotal / 1024 / 1024), // MB
1714
+ },
1715
+ websocketClients: clientsOf(req.canvas).size
1716
+ });
1717
+ });
1718
+
1719
+ // Error handling middleware
1720
+ app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
1721
+ logger.error('Unhandled error:', err);
1722
+ res.status(500).json({
1723
+ success: false,
1724
+ error: 'Internal server error'
1725
+ });
1726
+ });
1727
+
1728
+ // Start server
1729
+ const PORT = parseInt(process.env.PORT || '3000', 10);
1730
+ const HOST = process.env.HOST || '127.0.0.1';
1731
+ const LOOPBACK_GUARD_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0', '::']);
1732
+ const LOOPBACK_ADDRESSES = ['127.0.0.1', '::1'];
1733
+
1734
+ function formatHostForUrl(host: string): string {
1735
+ return host.includes(':') ? `[${host}]` : host;
1736
+ }
1737
+
1738
+ function canConnect(host: string, port: number): Promise<boolean> {
1739
+ return new Promise(resolve => {
1740
+ let settled = false;
1741
+ const socket = net.createConnection({ host, port });
1742
+
1743
+ const finish = (isOpen: boolean): void => {
1744
+ if (settled) return;
1745
+ settled = true;
1746
+ socket.destroy();
1747
+ resolve(isOpen);
1748
+ };
1749
+
1750
+ socket.setTimeout(250);
1751
+ socket.once('connect', () => finish(true));
1752
+ socket.once('timeout', () => finish(false));
1753
+ socket.once('error', () => finish(false));
1754
+ });
1755
+ }
1756
+
1757
+ async function findExistingLoopbackListener(port: number): Promise<string | null> {
1758
+ for (const host of LOOPBACK_ADDRESSES) {
1759
+ if (await canConnect(host, port)) {
1760
+ return host;
1761
+ }
1762
+ }
1763
+ return null;
1764
+ }
1765
+
1766
+ function releaseDurableStateLockSafely(): void {
1767
+ try {
1768
+ releaseDurableStateLock();
1769
+ } catch (error) {
1770
+ logger.error('Failed to release canvas data-directory lock:', error);
1771
+ }
1772
+ }
1773
+
1774
+ server.on('error', (error: NodeJS.ErrnoException) => {
1775
+ if (error.code === 'EADDRINUSE') {
1776
+ const address = (error as NodeJS.ErrnoException & { address?: string }).address || HOST;
1777
+ logger.error(`Canvas server port ${PORT} is already in use on ${formatHostForUrl(address)}.`);
1778
+ } else if (error.code === 'EACCES') {
1779
+ logger.error(`Canvas server cannot bind ${formatHostForUrl(HOST)}:${PORT}: permission denied.`);
1780
+ } else {
1781
+ logger.error('Failed to start canvas server:', error);
1782
+ }
1783
+ releaseDurableStateLockSafely();
1784
+ process.exit(1);
1785
+ });
1786
+
1787
+ async function startServer(): Promise<void> {
1788
+ acquireDurableStateLock();
1789
+ let durableState: DurableStateStatus;
1790
+ try {
1791
+ durableState = registry.openMain();
1792
+ } catch (error) {
1793
+ releaseDurableStateLockSafely();
1794
+ throw error;
1795
+ }
1796
+
1797
+ if (durableState.loaded) {
1798
+ logger.info('Loaded durable canvas state', {
1799
+ elements: durableState.elements,
1800
+ files: durableState.files,
1801
+ snapshots: durableState.snapshots
1802
+ });
1803
+ } else if (durableState.enabled) {
1804
+ logger.info('Durable canvas state enabled; starting without an existing checkpoint');
1805
+ }
1806
+
1807
+ if (LOOPBACK_GUARD_HOSTS.has(HOST)) {
1808
+ const existingHost = await findExistingLoopbackListener(PORT);
1809
+ if (existingHost) {
1810
+ logger.error(
1811
+ `Refusing to start canvas server on ${formatHostForUrl(HOST)}:${PORT}: ` +
1812
+ `${formatHostForUrl(existingHost)}:${PORT} is already listening. ` +
1813
+ 'This prevents duplicate IPv4/IPv6 canvas servers from splitting state.'
1814
+ );
1815
+ releaseDurableStateLockSafely();
1816
+ process.exit(1);
1817
+ }
1818
+ }
1819
+
1820
+ // The pidfile identifies the listening process for CLI lifecycle commands.
1821
+ // The data-directory lock independently protects durable-state ownership.
1822
+ let ownsPidFile = false;
1823
+
1824
+ server.listen(PORT, HOST, () => {
1825
+ const hostForUrl = formatHostForUrl(HOST);
1826
+ logger.info(`POC server running on http://${hostForUrl}:${PORT}`);
1827
+ logger.info(`WebSocket server running on ws://${hostForUrl}:${PORT}`);
1828
+
1829
+ // Written only after listen succeeds so stale files can't shadow a
1830
+ // server that never came up; lets `daigram stop` find us.
1831
+ writePidFile(PORT, process.pid);
1832
+ ownsPidFile = true;
1833
+
1834
+ // The AI runner drives the canvas through the same HTTP API as the CLI, so it must be able to reach this server.
1835
+ if (process.env.AI_PROVIDER && new URL(EXPRESS_SERVER_URL).port !== String(PORT)) {
1836
+ logger.warn(`AI is configured but EXPRESS_SERVER_URL (${EXPRESS_SERVER_URL}) is not this server's port ${PORT}; set it so AI runs can reach the canvas.`);
1837
+ }
1838
+ });
1839
+
1840
+ const shutdown = (signal: NodeJS.Signals): void => {
1841
+ logger.info(`Received ${signal}, shutting down canvas server`);
1842
+ if (ownsPidFile) removePidFile(PORT);
1843
+ server.close(() => {
1844
+ releaseDurableStateLockSafely();
1845
+ process.exit(0);
1846
+ });
1847
+ // Force-exit if open sockets keep the server from closing promptly.
1848
+ setTimeout(() => {
1849
+ releaseDurableStateLockSafely();
1850
+ process.exit(0);
1851
+ }, 2000).unref();
1852
+ };
1853
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
1854
+ process.on('SIGINT', () => shutdown('SIGINT'));
1855
+ process.on('exit', () => {
1856
+ if (ownsPidFile) removePidFile(PORT);
1857
+ releaseDurableStateLockSafely();
1858
+ });
1859
+ }
1860
+
1861
+ // Start the canvas server only when this file is the process entry point
1862
+ // (`node dist/server.js`, `npm run canvas`, or spawned by the CLI/MCP
1863
+ // auto-start). Importing this module must never start the server.
1864
+ if (isMainModule(import.meta.url)) {
1865
+ void startServer().catch(error => {
1866
+ logger.error('Failed to start canvas server:', error);
1867
+ releaseDurableStateLockSafely();
1868
+ process.exit(1);
1869
+ });
1870
+ }
1871
+
1872
+ export { startServer };
1873
+ export default app;