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/dist/server.js ADDED
@@ -0,0 +1,1684 @@
1
+ import express from 'express';
2
+ import cors from 'cors';
3
+ import { WebSocketServer } from 'ws';
4
+ import { createServer } 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 { CanvasRegistry } from './core/canvas-registry.js';
11
+ import { createCanvasRouter } from './core/canvas-routes.js';
12
+ import { generateId, EXCALIDRAW_ELEMENT_TYPES, normalizeFontFamily } from './types.js';
13
+ import { z } from 'zod';
14
+ import WebSocket from 'ws';
15
+ import { isMainModule } from './core/entry.js';
16
+ import { createCommentRouter } from './core/comments.js';
17
+ import { createAiRouter } from './ai/routes.js';
18
+ import { createMcpRouter } from './core/mcp-http.js';
19
+ import { routeArrowAround } from './core/arrow-routing.js';
20
+ import { EXPRESS_SERVER_URL } from './core/config.js';
21
+ import { isTrustedRequest, parseAllowedOrigins } from './core/local-origin.js';
22
+ import { writePidFile, removePidFile } from './core/pidfile.js';
23
+ import { renderScene, RenderError, MAX_SCALE } from './core/render/index.js';
24
+ import { CanvasFileImmutabilityError, CanvasFileReferenceError, CanvasPersistenceError, acquireDurableStateLock, commitCanvasMutation, durableStateDirectory, durableStateEnabled, releaseDurableStateLock, } from './core/canvas-persistence.js';
25
+ function mutationErrorStatus(error, fallback) {
26
+ if (error instanceof CanvasPersistenceError)
27
+ return 500;
28
+ if (error instanceof CanvasFileImmutabilityError ||
29
+ error instanceof CanvasFileReferenceError)
30
+ return 409;
31
+ return fallback;
32
+ }
33
+ // Load environment variables
34
+ dotenv.config();
35
+ const __filename = fileURLToPath(import.meta.url);
36
+ const __dirname = path.dirname(__filename);
37
+ const app = express();
38
+ const server = createServer(app);
39
+ const allowedOrigins = parseAllowedOrigins(process.env.ALLOWED_ORIGINS);
40
+ const isTrusted = (headers) => isTrustedRequest(headers, HOST, allowedOrigins);
41
+ const wss = new WebSocketServer({ server, verifyClient: ({ req }) => isTrusted(req.headers) });
42
+ // Case-insensitive like Express's own routing, or /API/... would skip the check.
43
+ const API_PATH = /^\/(?:c\/[^/?#]+\/)?(?:api|mcp)(?:[/?#]|$)/i;
44
+ app.use((req, res, next) => {
45
+ if (!API_PATH.test(req.url) || isTrusted(req.headers))
46
+ return next();
47
+ res.status(403).json({ success: false, error: 'Cross-site requests to the canvas API are refused' });
48
+ });
49
+ // /c/<id>/... addresses one canvas, with the rest of the path as usual; any other path is the main canvas.
50
+ const CANVAS_PATH = /^\/c\/([^/?#]+)(\/[^?#]*)?(\?.*)?$/i;
51
+ // A canvas whose saved state is damaged must fail its own requests, not the server.
52
+ function lookupCanvas(id) {
53
+ try {
54
+ return { canvas: registry.get(id) };
55
+ }
56
+ catch (error) {
57
+ logger.error(`Canvas "${id}" could not be loaded:`, error);
58
+ return { failed: true };
59
+ }
60
+ }
61
+ app.use((req, res, next) => {
62
+ const match = CANVAS_PATH.exec(req.url);
63
+ if (!match) {
64
+ req.canvas = registry.main();
65
+ return next();
66
+ }
67
+ const { canvas, failed } = lookupCanvas(match[1]);
68
+ if (failed)
69
+ return res.status(500).json({ success: false, error: `Canvas "${match[1]}" could not be loaded` });
70
+ if (!canvas)
71
+ return res.status(404).json({ success: false, error: `Canvas "${match[1]}" not found` });
72
+ req.canvas = canvas;
73
+ req.url = `${match[2] ?? '/'}${match[3] ?? ''}`;
74
+ next();
75
+ });
76
+ app.use(cors({ origin: allowedOrigins }));
77
+ app.use(express.json({ limit: '10mb' }));
78
+ // Serve static files from the build directory
79
+ const staticDir = path.join(__dirname, '../dist');
80
+ // No redirect to a trailing slash: /c/<id> is a page, not a directory.
81
+ app.use(express.static(staticDir, { redirect: false }));
82
+ // Also serve frontend assets
83
+ // Vite names these files by content hash, so a cached copy is never stale; without this every page load
84
+ // revalidates each of the ~170 chunks, a round trip apiece.
85
+ const HASHED_ASSET = /-[\w-]{8}\.(?:js|css|woff2)$/;
86
+ app.use(express.static(path.join(__dirname, '../dist/frontend'), {
87
+ redirect: false,
88
+ setHeaders: (res, file) => { if (HASHED_ASSET.test(file))
89
+ res.setHeader('Cache-Control', 'max-age=31536000, immutable'); }
90
+ }));
91
+ // Excalidraw's fonts, for the page (EXCALIDRAW_ASSET_PATH in index.html) and the export subsetting worker. Some
92
+ // names are not hashed (Virgil-Regular.woff2), so a week rather than forever.
93
+ app.use('/assets/fonts', express.static(path.join(__dirname, '../node_modules/@excalidraw/excalidraw/dist/prod/fonts'), { maxAge: '7d' }));
94
+ const registry = new CanvasRegistry(durableStateDirectory());
95
+ // Connected tabs, by the canvas they opened.
96
+ const clientsByCanvas = new Map();
97
+ const clientsOf = (canvas) => {
98
+ let clients = clientsByCanvas.get(canvas.id);
99
+ if (!clients)
100
+ clientsByCanvas.set(canvas.id, clients = new Set());
101
+ return clients;
102
+ };
103
+ const clientSelections = new Map();
104
+ function getActiveSelection(canvas) {
105
+ let latestTab = null;
106
+ for (const ws of clientsOf(canvas)) {
107
+ const sel = clientSelections.get(ws);
108
+ if (!sel)
109
+ continue;
110
+ if (ws.readyState === WebSocket.OPEN) {
111
+ if (!latestTab || sel.updatedAt > latestTab.updatedAt) {
112
+ latestTab = sel;
113
+ }
114
+ }
115
+ else {
116
+ clientSelections.delete(ws);
117
+ }
118
+ }
119
+ return latestTab ? latestTab.selectedElementIds : [];
120
+ }
121
+ // Broadcast to the tabs open on one canvas
122
+ function broadcast(canvas, message) {
123
+ const data = JSON.stringify(message);
124
+ const clients = clientsOf(canvas);
125
+ clients.forEach(client => {
126
+ try {
127
+ if (client.readyState === WebSocket.OPEN) {
128
+ client.send(data);
129
+ }
130
+ }
131
+ catch (err) {
132
+ logger.warn('Failed to send to client, removing');
133
+ clients.delete(client);
134
+ }
135
+ });
136
+ }
137
+ function normalizeLineBreakMarkup(text) {
138
+ return text
139
+ .replace(/<\s*b\s*r\s*\/?\s*>/gi, '\n')
140
+ .replace(/\n{3,}/g, '\n\n');
141
+ }
142
+ function prepareFileWrites(canvas, fileList) {
143
+ const durable = durableStateEnabled();
144
+ // Preserve the pre-persistence endpoint exactly when durability is disabled:
145
+ // valid entries overwrite in request order, omitted metadata uses the same
146
+ // truthy defaults, and an existing file contributes no implicit defaults.
147
+ if (!durable) {
148
+ const prepared = [];
149
+ for (const value of fileList) {
150
+ if (value === null || typeof value !== 'object')
151
+ continue;
152
+ const candidate = value;
153
+ if (!candidate.id || !candidate.dataURL)
154
+ continue;
155
+ prepared.push({
156
+ id: candidate.id,
157
+ dataURL: candidate.dataURL,
158
+ mimeType: candidate.mimeType || 'image/png',
159
+ created: candidate.created || Date.now(),
160
+ });
161
+ }
162
+ return prepared;
163
+ }
164
+ const prepared = new Map();
165
+ for (const value of fileList) {
166
+ if (value === null || typeof value !== 'object')
167
+ continue;
168
+ const candidate = value;
169
+ if (typeof candidate.id !== 'string' || candidate.id.length === 0 ||
170
+ typeof candidate.dataURL !== 'string' || candidate.dataURL.length === 0) {
171
+ continue;
172
+ }
173
+ const previous = prepared.get(candidate.id) ?? canvas.files.get(candidate.id);
174
+ const mimeType = typeof candidate.mimeType === 'string' && candidate.mimeType.length > 0
175
+ ? candidate.mimeType
176
+ : previous?.mimeType ?? 'image/png';
177
+ if (previous) {
178
+ if (previous.dataURL !== candidate.dataURL || previous.mimeType !== mimeType) {
179
+ throw new CanvasFileImmutabilityError(candidate.id);
180
+ }
181
+ prepared.set(candidate.id, previous);
182
+ continue;
183
+ }
184
+ prepared.set(candidate.id, {
185
+ id: candidate.id,
186
+ dataURL: candidate.dataURL,
187
+ mimeType,
188
+ // Preserve the original in-memory endpoint's overwrite behavior:
189
+ // an omitted/zero timestamp is replaced with the current time. Durable
190
+ // retries of an existing immutable id returned above keep prior metadata.
191
+ created: typeof candidate.created === 'number' && Number.isFinite(candidate.created) && candidate.created > 0
192
+ ? candidate.created
193
+ : Date.now(),
194
+ });
195
+ }
196
+ return [...prepared.values()];
197
+ }
198
+ // WebSocket connection handling
199
+ wss.on('connection', (ws, request) => {
200
+ const match = CANVAS_PATH.exec(request.url ?? '/');
201
+ const { canvas, failed } = match ? lookupCanvas(match[1]) : { canvas: registry.main(), failed: false };
202
+ if (failed) {
203
+ ws.close(1011, 'Canvas could not be loaded');
204
+ return;
205
+ }
206
+ if (!canvas) {
207
+ ws.close(4404, 'Canvas not found');
208
+ return;
209
+ }
210
+ const clients = clientsOf(canvas);
211
+ clients.add(ws);
212
+ logger.info('New WebSocket connection established');
213
+ // Send current elements to new client
214
+ const filesObj = {};
215
+ canvas.files.forEach((f, id) => { filesObj[id] = f; });
216
+ const initialMessage = {
217
+ type: 'initial_elements',
218
+ elements: Array.from(canvas.elements.values()),
219
+ ...(canvas.files.size > 0 ? { files: filesObj } : {})
220
+ };
221
+ ws.send(JSON.stringify(initialMessage));
222
+ // Send sync status to new client
223
+ const syncMessage = {
224
+ type: 'sync_status',
225
+ elementCount: canvas.elements.size,
226
+ timestamp: new Date().toISOString()
227
+ };
228
+ ws.send(JSON.stringify(syncMessage));
229
+ ws.on('message', (raw) => {
230
+ try {
231
+ const msg = JSON.parse(raw.toString());
232
+ if (msg && msg.type === 'selection_updated' && Array.isArray(msg.selectedElementIds)) {
233
+ clientSelections.set(ws, {
234
+ selectedElementIds: msg.selectedElementIds.filter((id) => typeof id === 'string'),
235
+ updatedAt: Date.now()
236
+ });
237
+ }
238
+ }
239
+ catch {
240
+ // Ignore malformed client frames
241
+ }
242
+ });
243
+ ws.on('close', () => {
244
+ clients.delete(ws);
245
+ clientSelections.delete(ws);
246
+ logger.info('WebSocket connection closed');
247
+ });
248
+ ws.on('error', (error) => {
249
+ logger.error('WebSocket error:', error);
250
+ clients.delete(ws);
251
+ clientSelections.delete(ws);
252
+ });
253
+ });
254
+ // Schema validation
255
+ const CreateElementSchema = z.object({
256
+ id: z.string().optional(), // Allow passing ID for MCP sync
257
+ type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES)),
258
+ x: z.number(),
259
+ y: z.number(),
260
+ width: z.number().optional(),
261
+ height: z.number().optional(),
262
+ backgroundColor: z.string().optional(),
263
+ strokeColor: z.string().optional(),
264
+ strokeWidth: z.number().optional(),
265
+ strokeStyle: z.string().optional(),
266
+ roughness: z.number().optional(),
267
+ opacity: z.number().optional(),
268
+ text: z.string().optional(),
269
+ label: z.object({
270
+ text: z.string()
271
+ }).optional(),
272
+ fontSize: z.number().optional(),
273
+ fontFamily: z.union([z.string(), z.number()]).optional(),
274
+ // Bound-text back-pointer — without it, zod strips containerId on import
275
+ // and re-imported bound labels detach from their containers
276
+ containerId: z.string().nullable().optional(),
277
+ // Excalidraw identity fields — preserve through import so re-exported
278
+ // scenes keep their stacking order, roughness seeds, and timestamps, and
279
+ // no-op import→export cycles stay byte-stable
280
+ index: z.string().nullable().optional(),
281
+ seed: z.number().optional(),
282
+ versionNonce: z.number().optional(),
283
+ updated: z.number().optional(),
284
+ groupIds: z.array(z.string()).optional(),
285
+ locked: z.boolean().optional(),
286
+ roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
287
+ fillStyle: z.string().optional(),
288
+ // Arrow-specific properties
289
+ points: z.any().optional(),
290
+ start: z.object({ id: z.string() }).optional(),
291
+ end: z.object({ id: z.string() }).optional(),
292
+ startArrowhead: z.string().nullable().optional(),
293
+ endArrowhead: z.string().nullable().optional(),
294
+ elbowed: z.boolean().optional(),
295
+ // Arrow binding properties (preserved for Excalidraw frontend)
296
+ startBinding: z.object({
297
+ elementId: z.string(),
298
+ focus: z.number().optional(),
299
+ gap: z.number().optional(),
300
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
301
+ mode: z.string().optional(),
302
+ }).nullable().optional(),
303
+ endBinding: z.object({
304
+ elementId: z.string(),
305
+ focus: z.number().optional(),
306
+ gap: z.number().optional(),
307
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
308
+ mode: z.string().optional(),
309
+ }).nullable().optional(),
310
+ boundElements: z.array(z.object({
311
+ id: z.string(),
312
+ type: z.enum(['arrow', 'text']),
313
+ })).nullable().optional(),
314
+ // Image-specific properties
315
+ fileId: z.string().optional(),
316
+ status: z.string().optional(),
317
+ scale: z.tuple([z.number(), z.number()]).optional(),
318
+ }).passthrough();
319
+ const UpdateElementSchema = z.object({
320
+ id: z.string(),
321
+ type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES)).optional(),
322
+ x: z.number().optional(),
323
+ y: z.number().optional(),
324
+ width: z.number().optional(),
325
+ height: z.number().optional(),
326
+ backgroundColor: z.string().optional(),
327
+ strokeColor: z.string().optional(),
328
+ strokeWidth: z.number().optional(),
329
+ strokeStyle: z.string().optional(),
330
+ roughness: z.number().optional(),
331
+ opacity: z.number().optional(),
332
+ text: z.string().optional(),
333
+ originalText: z.string().optional(),
334
+ label: z.object({
335
+ text: z.string()
336
+ }).optional(),
337
+ fontSize: z.number().optional(),
338
+ fontFamily: z.union([z.string(), z.number()]).optional(),
339
+ // Bound-text back-pointer — without it, zod strips containerId on import
340
+ // and re-imported bound labels detach from their containers
341
+ containerId: z.string().nullable().optional(),
342
+ // Excalidraw identity fields — preserve through import so re-exported
343
+ // scenes keep their stacking order, roughness seeds, and timestamps, and
344
+ // no-op import→export cycles stay byte-stable
345
+ index: z.string().nullable().optional(),
346
+ seed: z.number().optional(),
347
+ versionNonce: z.number().optional(),
348
+ updated: z.number().optional(),
349
+ groupIds: z.array(z.string()).optional(),
350
+ locked: z.boolean().optional(),
351
+ roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
352
+ fillStyle: z.string().optional(),
353
+ points: z.array(z.union([
354
+ z.tuple([z.number(), z.number()]),
355
+ z.object({ x: z.number(), y: z.number() })
356
+ ])).optional(),
357
+ start: z.object({ id: z.string() }).optional(),
358
+ end: z.object({ id: z.string() }).optional(),
359
+ startArrowhead: z.string().nullable().optional(),
360
+ endArrowhead: z.string().nullable().optional(),
361
+ elbowed: z.boolean().optional(),
362
+ // Arrow binding properties (preserved for Excalidraw frontend)
363
+ startBinding: z.object({
364
+ elementId: z.string(),
365
+ focus: z.number().optional(),
366
+ gap: z.number().optional(),
367
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
368
+ mode: z.string().optional(),
369
+ }).nullable().optional(),
370
+ endBinding: z.object({
371
+ elementId: z.string(),
372
+ focus: z.number().optional(),
373
+ gap: z.number().optional(),
374
+ fixedPoint: z.tuple([z.number(), z.number()]).nullable().optional(),
375
+ mode: z.string().optional(),
376
+ }).nullable().optional(),
377
+ boundElements: z.array(z.object({
378
+ id: z.string(),
379
+ type: z.enum(['arrow', 'text']),
380
+ })).nullable().optional(),
381
+ // Image-specific properties
382
+ fileId: z.string().optional(),
383
+ status: z.string().optional(),
384
+ scale: z.tuple([z.number(), z.number()]).optional(),
385
+ }).passthrough();
386
+ // API Routes
387
+ // Get current canvas selection
388
+ app.get('/api/selection', (req, res) => {
389
+ const selectedElementIds = getActiveSelection(req.canvas);
390
+ res.json({
391
+ success: true,
392
+ selectedElementIds,
393
+ count: selectedElementIds.length
394
+ });
395
+ });
396
+ // Get all elements
397
+ app.get('/api/elements', (req, res) => {
398
+ const canvas = req.canvas;
399
+ try {
400
+ const elementsArray = Array.from(canvas.elements.values());
401
+ res.json({
402
+ success: true,
403
+ elements: elementsArray,
404
+ count: elementsArray.length
405
+ });
406
+ }
407
+ catch (error) {
408
+ logger.error('Error fetching elements:', error);
409
+ res.status(500).json({
410
+ success: false,
411
+ error: error.message
412
+ });
413
+ }
414
+ });
415
+ // Create new element
416
+ app.post('/api/elements', (req, res) => {
417
+ const canvas = req.canvas;
418
+ try {
419
+ const params = CreateElementSchema.parse(req.body);
420
+ logger.info('Creating element via API', { type: params.type });
421
+ // Prioritize passed ID (for MCP sync), otherwise generate new ID
422
+ const id = params.id || generateId();
423
+ const element = {
424
+ id,
425
+ ...params,
426
+ fontFamily: normalizeFontFamily(params.fontFamily),
427
+ createdAt: new Date().toISOString(),
428
+ updatedAt: new Date().toISOString(),
429
+ version: 1
430
+ };
431
+ // Resolve arrow bindings against existing elements
432
+ if (element.type === 'arrow' || element.type === 'line') {
433
+ resolveArrowBindings(canvas, [element]);
434
+ }
435
+ commitCanvasMutation(canvas, () => canvas.elements.set(id, element));
436
+ // Broadcast to all connected clients
437
+ const message = {
438
+ type: 'element_created',
439
+ element: element
440
+ };
441
+ broadcast(canvas, message);
442
+ res.json({
443
+ success: true,
444
+ element: element
445
+ });
446
+ }
447
+ catch (error) {
448
+ logger.error('Error creating element:', error);
449
+ res.status(mutationErrorStatus(error, 400)).json({
450
+ success: false,
451
+ error: error.message
452
+ });
453
+ }
454
+ });
455
+ // Update element
456
+ app.put('/api/elements/:id', (req, res) => {
457
+ const canvas = req.canvas;
458
+ try {
459
+ const { id } = req.params;
460
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
461
+ const updates = UpdateElementSchema.parse({ id, ...body });
462
+ if (!id) {
463
+ return res.status(400).json({
464
+ success: false,
465
+ error: 'Element ID is required'
466
+ });
467
+ }
468
+ const existingElement = canvas.elements.get(id);
469
+ if (!existingElement) {
470
+ return res.status(404).json({
471
+ success: false,
472
+ error: `Element with ID ${id} not found`
473
+ });
474
+ }
475
+ const updatedElement = {
476
+ ...existingElement,
477
+ ...updates,
478
+ fontFamily: updates.fontFamily !== undefined ? normalizeFontFamily(updates.fontFamily) : existingElement.fontFamily,
479
+ updatedAt: new Date().toISOString(),
480
+ version: (existingElement.version || 0) + 1
481
+ };
482
+ // Keep Excalidraw text source in sync when clients update text via REST.
483
+ // If originalText lags behind text, rendered wrapping/position can drift.
484
+ const hasTextUpdate = Object.prototype.hasOwnProperty.call(body, 'text');
485
+ const hasOriginalTextUpdate = Object.prototype.hasOwnProperty.call(body, 'originalText');
486
+ if (updatedElement.type === EXCALIDRAW_ELEMENT_TYPES.TEXT && hasTextUpdate && !hasOriginalTextUpdate) {
487
+ const incomingText = updates.text ?? '';
488
+ const existingText = typeof existingElement.text === 'string' ? existingElement.text : '';
489
+ const existingOriginalText = typeof existingElement.originalText === 'string'
490
+ ? existingElement.originalText
491
+ : '';
492
+ const existingOriginalHasBr = /<\s*b\s*r\s*\/?\s*>/i.test(existingOriginalText);
493
+ const normalizedExistingText = normalizeLineBreakMarkup(existingText);
494
+ const normalizedExistingOriginalText = normalizeLineBreakMarkup(existingOriginalText);
495
+ // Handle common cleanup flow: caller normalizes the rendered text value.
496
+ // In this case, prefer normalized originalText so words aren't split by stale wraps.
497
+ if (existingOriginalHasBr && incomingText === normalizedExistingText && normalizedExistingOriginalText) {
498
+ updatedElement.text = normalizedExistingOriginalText;
499
+ updatedElement.originalText = normalizedExistingOriginalText;
500
+ }
501
+ else {
502
+ updatedElement.originalText = incomingText;
503
+ }
504
+ }
505
+ // Moving/resizing a shape must drag its bound arrows along. Keep the
506
+ // element update and every in-place arrow reroute in one durable mutation.
507
+ const geometryChanged = ['x', 'y', 'width', 'height']
508
+ .some(key => Object.prototype.hasOwnProperty.call(body, key));
509
+ const reroutedArrows = commitCanvasMutation(canvas, () => {
510
+ canvas.elements.set(id, updatedElement);
511
+ return geometryChanged && updatedElement.type !== 'arrow' && updatedElement.type !== 'line'
512
+ ? rerouteBoundArrows(canvas, id)
513
+ : [];
514
+ });
515
+ // Publish only after the complete mutation has been checkpointed.
516
+ const message = {
517
+ type: 'element_updated',
518
+ element: updatedElement
519
+ };
520
+ broadcast(canvas, message);
521
+ for (const arrow of reroutedArrows) {
522
+ broadcast(canvas, { type: 'element_updated', element: arrow });
523
+ }
524
+ res.json({
525
+ success: true,
526
+ element: updatedElement
527
+ });
528
+ }
529
+ catch (error) {
530
+ logger.error('Error updating element:', error);
531
+ res.status(mutationErrorStatus(error, 400)).json({
532
+ success: false,
533
+ error: error.message
534
+ });
535
+ }
536
+ });
537
+ // A clear or replace cannot be undone, so the scene it discards is kept as a snapshot first. Call inside commitCanvasMutation.
538
+ const SAFETY_COPIES = 3;
539
+ const SAFETY_PREFIX = 'auto-';
540
+ function keepSafetyCopy(canvas) {
541
+ if (canvas.elements.size === 0)
542
+ return;
543
+ const createdAt = new Date().toISOString();
544
+ const name = `${SAFETY_PREFIX}${createdAt.replace(/[:.]/g, '-')}`;
545
+ canvas.snapshots.set(name, { name, elements: structuredClone(Array.from(canvas.elements.values())), createdAt });
546
+ const kept = Array.from(canvas.snapshots.values()).filter(s => s.name.startsWith(SAFETY_PREFIX)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
547
+ kept.slice(SAFETY_COPIES).forEach(s => canvas.snapshots.delete(s.name));
548
+ }
549
+ // Clear all elements (must be before /:id route)
550
+ app.delete('/api/elements/clear', (req, res) => {
551
+ const canvas = req.canvas;
552
+ try {
553
+ const count = canvas.elements.size;
554
+ commitCanvasMutation(canvas, () => { keepSafetyCopy(canvas); canvas.elements.clear(); });
555
+ broadcast(canvas, {
556
+ type: 'canvas_cleared',
557
+ timestamp: new Date().toISOString()
558
+ });
559
+ logger.info(`Canvas cleared: ${count} elements removed`);
560
+ res.json({
561
+ success: true,
562
+ message: `Cleared ${count} elements`,
563
+ count
564
+ });
565
+ }
566
+ catch (error) {
567
+ logger.error('Error clearing canvas:', error);
568
+ res.status(mutationErrorStatus(error, 500)).json({
569
+ success: false,
570
+ error: error.message
571
+ });
572
+ }
573
+ });
574
+ // Delete element
575
+ app.delete('/api/elements/:id', (req, res) => {
576
+ const canvas = req.canvas;
577
+ try {
578
+ const { id } = req.params;
579
+ if (!id) {
580
+ return res.status(400).json({
581
+ success: false,
582
+ error: 'Element ID is required'
583
+ });
584
+ }
585
+ if (!canvas.elements.has(id)) {
586
+ return res.status(404).json({
587
+ success: false,
588
+ error: `Element with ID ${id} not found`
589
+ });
590
+ }
591
+ commitCanvasMutation(canvas, () => canvas.elements.delete(id));
592
+ // Broadcast to all connected clients
593
+ const message = {
594
+ type: 'element_deleted',
595
+ elementId: id
596
+ };
597
+ broadcast(canvas, message);
598
+ res.json({
599
+ success: true,
600
+ message: `Element ${id} deleted successfully`
601
+ });
602
+ }
603
+ catch (error) {
604
+ logger.error('Error deleting element:', error);
605
+ res.status(mutationErrorStatus(error, 500)).json({
606
+ success: false,
607
+ error: error.message
608
+ });
609
+ }
610
+ });
611
+ // Query elements with filters
612
+ app.get('/api/elements/search', (req, res) => {
613
+ const canvas = req.canvas;
614
+ try {
615
+ const { type, x_min, x_max, y_min, y_max, ...filters } = req.query;
616
+ let results = Array.from(canvas.elements.values());
617
+ // Filter by type if specified
618
+ if (type && typeof type === 'string') {
619
+ results = results.filter(element => element.type === type);
620
+ }
621
+ // Filter by bounding box if specified
622
+ if (x_min !== undefined || x_max !== undefined || y_min !== undefined || y_max !== undefined) {
623
+ const xMin = x_min !== undefined ? Number(x_min) : -Infinity;
624
+ const xMax = x_max !== undefined ? Number(x_max) : Infinity;
625
+ const yMin = y_min !== undefined ? Number(y_min) : -Infinity;
626
+ const yMax = y_max !== undefined ? Number(y_max) : Infinity;
627
+ results = results.filter(el => el.x >= xMin &&
628
+ el.x <= xMax &&
629
+ el.y >= yMin &&
630
+ el.y <= yMax);
631
+ }
632
+ // Apply additional exact-match filters
633
+ if (Object.keys(filters).length > 0) {
634
+ results = results.filter(element => {
635
+ return Object.entries(filters).every(([key, value]) => {
636
+ return element[key] === value;
637
+ });
638
+ });
639
+ }
640
+ res.json({
641
+ success: true,
642
+ elements: results,
643
+ count: results.length
644
+ });
645
+ }
646
+ catch (error) {
647
+ logger.error('Error querying elements:', error);
648
+ res.status(500).json({
649
+ success: false,
650
+ error: error.message
651
+ });
652
+ }
653
+ });
654
+ // Get element by ID
655
+ app.get('/api/elements/:id', (req, res) => {
656
+ const canvas = req.canvas;
657
+ try {
658
+ const { id } = req.params;
659
+ if (!id) {
660
+ return res.status(400).json({
661
+ success: false,
662
+ error: 'Element ID is required'
663
+ });
664
+ }
665
+ const element = canvas.elements.get(id);
666
+ if (!element) {
667
+ return res.status(404).json({
668
+ success: false,
669
+ error: `Element with ID ${id} not found`
670
+ });
671
+ }
672
+ res.json({
673
+ success: true,
674
+ element: element
675
+ });
676
+ }
677
+ catch (error) {
678
+ logger.error('Error fetching element:', error);
679
+ res.status(500).json({
680
+ success: false,
681
+ error: error.message
682
+ });
683
+ }
684
+ });
685
+ // Helper: compute edge point for an element given a direction toward a target
686
+ function computeEdgePoint(el, targetCenterX, targetCenterY) {
687
+ const cx = el.x + (el.width || 0) / 2;
688
+ const cy = el.y + (el.height || 0) / 2;
689
+ const dx = targetCenterX - cx;
690
+ const dy = targetCenterY - cy;
691
+ if (el.type === 'diamond') {
692
+ // Diamond edge: use diamond geometry (rotated square)
693
+ const hw = (el.width || 0) / 2;
694
+ const hh = (el.height || 0) / 2;
695
+ if (dx === 0 && dy === 0)
696
+ return { x: cx, y: cy + hh };
697
+ const absDx = Math.abs(dx);
698
+ const absDy = Math.abs(dy);
699
+ // Scale factor to reach diamond edge
700
+ const scale = (absDx / hw + absDy / hh) > 0
701
+ ? 1 / (absDx / hw + absDy / hh)
702
+ : 1;
703
+ return { x: cx + dx * scale, y: cy + dy * scale };
704
+ }
705
+ if (el.type === 'ellipse') {
706
+ // Ellipse edge: parametric intersection
707
+ const a = (el.width || 0) / 2;
708
+ const b = (el.height || 0) / 2;
709
+ if (dx === 0 && dy === 0)
710
+ return { x: cx, y: cy + b };
711
+ const angle = Math.atan2(dy, dx);
712
+ return { x: cx + a * Math.cos(angle), y: cy + b * Math.sin(angle) };
713
+ }
714
+ // Rectangle: find intersection with edges
715
+ const hw = (el.width || 0) / 2;
716
+ const hh = (el.height || 0) / 2;
717
+ if (dx === 0 && dy === 0)
718
+ return { x: cx, y: cy + hh };
719
+ const angle = Math.atan2(dy, dx);
720
+ const tanA = Math.tan(angle);
721
+ // Check if ray intersects top/bottom edge or left/right edge
722
+ if (Math.abs(tanA * hw) <= hh) {
723
+ // Intersects left or right edge
724
+ const signX = dx >= 0 ? 1 : -1;
725
+ return { x: cx + signX * hw, y: cy + signX * hw * tanA };
726
+ }
727
+ else {
728
+ // Intersects top or bottom edge
729
+ const signY = dy >= 0 ? 1 : -1;
730
+ return { x: cx + signY * hh / tanA, y: cy + signY * hh };
731
+ }
732
+ }
733
+ // Helper: resolve arrow bindings in a batch
734
+ function resolveArrowBindings(canvas, batchElements, includeExisting = true) {
735
+ const elementMap = new Map();
736
+ batchElements.forEach(el => elementMap.set(el.id, el));
737
+ // Also check existing elements for cross-batch references
738
+ if (includeExisting) {
739
+ canvas.elements.forEach((el, id) => {
740
+ if (!elementMap.has(id))
741
+ elementMap.set(id, el);
742
+ });
743
+ }
744
+ for (const el of batchElements) {
745
+ if (el.type !== 'arrow' && el.type !== 'line')
746
+ continue;
747
+ const startRef = el.start;
748
+ const endRef = el.end;
749
+ if (!startRef && !endRef)
750
+ continue;
751
+ const startEl = startRef ? elementMap.get(startRef.id) : undefined;
752
+ const endEl = endRef ? elementMap.get(endRef.id) : undefined;
753
+ // An elbow arrow between two shapes runs at right angles round whatever else is in the way.
754
+ if (el.elbowed === true && startEl && endEl && routeArrowAround(el, startEl, endEl, elementMap.values()))
755
+ continue;
756
+ // Calculate arrow path from edge to edge
757
+ const startCenter = startEl
758
+ ? { x: startEl.x + (startEl.width || 0) / 2, y: startEl.y + (startEl.height || 0) / 2 }
759
+ : { x: el.x, y: el.y };
760
+ const endCenter = endEl
761
+ ? { x: endEl.x + (endEl.width || 0) / 2, y: endEl.y + (endEl.height || 0) / 2 }
762
+ : { x: el.x + 100, y: el.y };
763
+ const GAP = 8;
764
+ const startPt = startEl
765
+ ? computeEdgePoint(startEl, endCenter.x, endCenter.y)
766
+ : startCenter;
767
+ const endPt = endEl
768
+ ? computeEdgePoint(endEl, startCenter.x, startCenter.y)
769
+ : endCenter;
770
+ // Apply gap: move start point slightly away from source, end point slightly away from target
771
+ const startDx = endPt.x - startPt.x;
772
+ const startDy = endPt.y - startPt.y;
773
+ const startDist = Math.sqrt(startDx * startDx + startDy * startDy) || 1;
774
+ const endDx = startPt.x - endPt.x;
775
+ const endDy = startPt.y - endPt.y;
776
+ const endDist = Math.sqrt(endDx * endDx + endDy * endDy) || 1;
777
+ const finalStart = {
778
+ x: startPt.x + (startDx / startDist) * GAP,
779
+ y: startPt.y + (startDy / startDist) * GAP
780
+ };
781
+ const finalEnd = {
782
+ x: endPt.x + (endDx / endDist) * GAP,
783
+ y: endPt.y + (endDy / endDist) * GAP
784
+ };
785
+ // Set arrow position and points
786
+ el.x = finalStart.x;
787
+ el.y = finalStart.y;
788
+ el.points = [[0, 0], [finalEnd.x - finalStart.x, finalEnd.y - finalStart.y]];
789
+ // Do NOT delete `start` and `end` here.
790
+ // Excalidraw's frontend `convertToExcalidrawElements` method looks for these exact properties
791
+ // to calculate mathematically sound `startBinding`, `endBinding`, `focus`, `gap`, and `boundElements`.
792
+ }
793
+ }
794
+ // After a shape's geometry changes, recompute every arrow bound to it so the
795
+ // visual connection follows the shape — bindings are otherwise only resolved
796
+ // at creation time, which left arrows floating at stale coordinates when
797
+ // update/align/distribute moved their endpoints. Returns the re-routed arrows.
798
+ function rerouteBoundArrows(canvas, movedId) {
799
+ const rerouted = [];
800
+ canvas.elements.forEach(el => {
801
+ if (el.type !== 'arrow' && el.type !== 'line')
802
+ return;
803
+ const startRef = el.start;
804
+ const endRef = el.end;
805
+ if (startRef?.id !== movedId && endRef?.id !== movedId)
806
+ return;
807
+ resolveArrowBindings(canvas, [el]);
808
+ el.updatedAt = new Date().toISOString();
809
+ el.version = (el.version || 0) + 1;
810
+ rerouted.push(el);
811
+ });
812
+ return rerouted;
813
+ }
814
+ // Batch create elements
815
+ app.post('/api/elements/batch', (req, res) => {
816
+ const canvas = req.canvas;
817
+ try {
818
+ const { elements: elementsToCreate, replace = false } = req.body ?? {};
819
+ if (!Array.isArray(elementsToCreate)) {
820
+ return res.status(400).json({
821
+ success: false,
822
+ error: 'Expected an array of elements'
823
+ });
824
+ }
825
+ if (typeof replace !== 'boolean') {
826
+ return res.status(400).json({
827
+ success: false,
828
+ error: 'replace must be a boolean'
829
+ });
830
+ }
831
+ const createdElements = [];
832
+ elementsToCreate.forEach(elementData => {
833
+ const params = CreateElementSchema.parse(elementData);
834
+ // Prioritize passed ID (for MCP sync), otherwise generate new ID
835
+ const id = params.id || generateId();
836
+ const element = {
837
+ id,
838
+ ...params,
839
+ fontFamily: normalizeFontFamily(params.fontFamily),
840
+ createdAt: new Date().toISOString(),
841
+ updatedAt: new Date().toISOString(),
842
+ version: 1
843
+ };
844
+ createdElements.push(element);
845
+ });
846
+ // Fully prepare the batch before mutating storage. Replacement imports do
847
+ // not resolve bindings against elements that are about to be discarded.
848
+ resolveArrowBindings(canvas, createdElements, !replace);
849
+ const replacedCount = replace ? canvas.elements.size : 0;
850
+ commitCanvasMutation(canvas, () => {
851
+ if (replace) {
852
+ keepSafetyCopy(canvas);
853
+ canvas.elements.clear();
854
+ }
855
+ createdElements.forEach(el => canvas.elements.set(el.id, el));
856
+ });
857
+ // Publish only after clear + replacement have reached one checkpoint.
858
+ if (replace) {
859
+ broadcast(canvas, {
860
+ type: 'canvas_cleared',
861
+ timestamp: new Date().toISOString()
862
+ });
863
+ logger.info(`Canvas replaced: ${replacedCount} existing elements removed`);
864
+ }
865
+ // Broadcast to all connected clients
866
+ const message = {
867
+ type: 'elements_batch_created',
868
+ elements: createdElements
869
+ };
870
+ broadcast(canvas, message);
871
+ res.json({
872
+ success: true,
873
+ elements: createdElements,
874
+ count: createdElements.length
875
+ });
876
+ }
877
+ catch (error) {
878
+ logger.error('Error batch creating elements:', error);
879
+ res.status(mutationErrorStatus(error, 400)).json({
880
+ success: false,
881
+ error: error.message
882
+ });
883
+ }
884
+ });
885
+ // Routes arrows at right angles round the other shapes (and marks them elbowed), for a layout that has changed since
886
+ // they were drawn. Each arrow's ends are the shapes it starts and ends on, by `start`/`end` or by its bindings.
887
+ app.post('/api/elements/route', (req, res) => {
888
+ const canvas = req.canvas;
889
+ const ids = req.body?.ids;
890
+ if (ids !== undefined && (!Array.isArray(ids) || !ids.every(id => typeof id === 'string'))) {
891
+ return res.status(400).json({ success: false, error: 'ids must be a list of element ids' });
892
+ }
893
+ const arrows = ids
894
+ ? [...new Set(ids)].map(id => canvas.elements.get(id)).filter((e) => !!e)
895
+ : Array.from(canvas.elements.values()).filter(e => e.type === 'arrow' && e.elbowed === true);
896
+ const missing = (ids ?? []).filter(id => !canvas.elements.has(id));
897
+ if (missing.length)
898
+ return res.status(404).json({ success: false, error: `Not found: ${missing.join(', ')}` });
899
+ const routed = [];
900
+ const skipped = [];
901
+ // A search can take tens of milliseconds and nothing else runs meanwhile, so one call routes a bounded number.
902
+ const MAX_ROUTES = 200;
903
+ arrows.slice(MAX_ROUTES).forEach(arrow => skipped.push({ id: arrow.id, reason: `over ${MAX_ROUTES} arrows in one call; call again with these ids` }));
904
+ commitCanvasMutation(canvas, () => {
905
+ for (const arrow of arrows.slice(0, MAX_ROUTES)) {
906
+ const ends = [arrow.start?.id ?? arrow.startBinding?.elementId, arrow.end?.id ?? arrow.endBinding?.elementId];
907
+ const [start, end] = ends.map(id => (id ? canvas.elements.get(id) : undefined));
908
+ if (arrow.type !== 'arrow')
909
+ skipped.push({ id: arrow.id, reason: 'not an arrow' });
910
+ else if (!start || !end)
911
+ skipped.push({ id: arrow.id, reason: 'it does not start and end on shapes' });
912
+ else if (!routeArrowAround(arrow, start, end, canvas.elements.values()))
913
+ skipped.push({ id: arrow.id, reason: 'no route found; left as it was' });
914
+ else {
915
+ Object.assign(arrow, { elbowed: true, updatedAt: new Date().toISOString(), version: (arrow.version || 0) + 1 });
916
+ routed.push(arrow);
917
+ }
918
+ }
919
+ });
920
+ for (const arrow of routed)
921
+ broadcast(canvas, { type: 'element_updated', element: arrow });
922
+ res.json({ success: true, routed: routed.map(a => a.id), skipped });
923
+ });
924
+ // Stacking order is the order of the scene, so sending elements to the back or front rebuilds it. A text label goes with
925
+ // its container, and the elements keep their order among themselves.
926
+ app.post('/api/elements/order', (req, res) => {
927
+ const canvas = req.canvas;
928
+ const { ids, to } = req.body ?? {};
929
+ if (!Array.isArray(ids) || ids.length === 0 || !ids.every(id => typeof id === 'string')) {
930
+ return res.status(400).json({ success: false, error: 'ids must be a non-empty list of element ids' });
931
+ }
932
+ if (to !== 'back' && to !== 'front')
933
+ return res.status(400).json({ success: false, error: 'to must be back or front' });
934
+ const missing = ids.filter(id => !canvas.elements.has(id));
935
+ if (missing.length)
936
+ return res.status(404).json({ success: false, error: `Not found: ${missing.join(', ')}` });
937
+ const moving = new Set(ids);
938
+ const all = Array.from(canvas.elements.values());
939
+ for (const element of all)
940
+ if (element.type === 'text' && element.containerId && moving.has(element.containerId))
941
+ moving.add(element.id);
942
+ const picked = all.filter(element => moving.has(element.id));
943
+ const rest = all.filter(element => !moving.has(element.id));
944
+ const ordered = to === 'back' ? [...picked, ...rest] : [...rest, ...picked];
945
+ commitCanvasMutation(canvas, () => {
946
+ canvas.elements.clear();
947
+ ordered.forEach(element => canvas.elements.set(element.id, element));
948
+ });
949
+ // The same two messages a replacement sends: a client takes the new order from them.
950
+ broadcast(canvas, { type: 'canvas_cleared', timestamp: new Date().toISOString() });
951
+ broadcast(canvas, { type: 'elements_batch_created', elements: ordered });
952
+ res.json({ success: true, count: picked.length });
953
+ });
954
+ // Convert Mermaid diagram to Excalidraw elements
955
+ app.post('/api/elements/from-mermaid', (req, res) => {
956
+ const canvas = req.canvas;
957
+ try {
958
+ const { mermaidDiagram, config } = req.body;
959
+ if (!mermaidDiagram || typeof mermaidDiagram !== 'string') {
960
+ return res.status(400).json({
961
+ success: false,
962
+ error: 'Mermaid diagram definition is required'
963
+ });
964
+ }
965
+ logger.info('Received Mermaid conversion request', {
966
+ diagramLength: mermaidDiagram.length,
967
+ hasConfig: !!config
968
+ });
969
+ // Broadcast to all WebSocket clients to process the Mermaid diagram
970
+ broadcast(canvas, {
971
+ type: 'mermaid_convert',
972
+ mermaidDiagram,
973
+ config: config || {},
974
+ timestamp: new Date().toISOString()
975
+ });
976
+ // Return the diagram for frontend processing
977
+ res.json({
978
+ success: true,
979
+ mermaidDiagram,
980
+ config: config || {},
981
+ message: 'Mermaid diagram sent to frontend for conversion.'
982
+ });
983
+ }
984
+ catch (error) {
985
+ logger.error('Error processing Mermaid diagram:', error);
986
+ res.status(400).json({
987
+ success: false,
988
+ error: error.message
989
+ });
990
+ }
991
+ });
992
+ // Sync elements from frontend (overwrite sync)
993
+ app.post('/api/elements/sync', (req, res) => {
994
+ const canvas = req.canvas;
995
+ try {
996
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
997
+ const { elements: frontendElements, timestamp } = body;
998
+ // Validate input data
999
+ if (!Array.isArray(frontendElements)) {
1000
+ return res.status(400).json({
1001
+ success: false,
1002
+ error: 'Expected elements to be an array'
1003
+ });
1004
+ }
1005
+ logger.info(`Sync request received: ${frontendElements.length} elements`, {
1006
+ timestamp,
1007
+ elementCount: frontendElements.length
1008
+ });
1009
+ // Record element count before sync
1010
+ const beforeCount = canvas.elements.size;
1011
+ let successCount = 0;
1012
+ const processedElements = [];
1013
+ commitCanvasMutation(canvas, () => {
1014
+ if (frontendElements.length === 0)
1015
+ keepSafetyCopy(canvas);
1016
+ canvas.elements.clear();
1017
+ frontendElements.forEach((element, index) => {
1018
+ try {
1019
+ // Ensure element has ID, generate one if missing
1020
+ const elementId = element.id || generateId();
1021
+ // Add server metadata
1022
+ const processedElement = {
1023
+ ...element,
1024
+ id: elementId,
1025
+ syncedAt: new Date().toISOString(),
1026
+ source: 'frontend_sync',
1027
+ syncTimestamp: timestamp,
1028
+ version: 1
1029
+ };
1030
+ canvas.elements.set(elementId, processedElement);
1031
+ processedElements.push(processedElement);
1032
+ successCount++;
1033
+ }
1034
+ catch (elementError) {
1035
+ logger.warn(`Failed to process element ${index}:`, elementError);
1036
+ }
1037
+ });
1038
+ });
1039
+ logger.info(`Cleared existing elements: ${beforeCount} elements removed`);
1040
+ logger.info(`Sync completed: ${successCount}/${frontendElements.length} elements synced`);
1041
+ // 3. Broadcast sync event to all WebSocket clients
1042
+ broadcast(canvas, {
1043
+ type: 'elements_synced',
1044
+ count: successCount,
1045
+ timestamp: new Date().toISOString(),
1046
+ source: 'manual_sync'
1047
+ });
1048
+ // 4. Return sync results
1049
+ res.json({
1050
+ success: true,
1051
+ message: `Successfully synced ${successCount} elements`,
1052
+ count: successCount,
1053
+ syncedAt: new Date().toISOString(),
1054
+ beforeCount,
1055
+ afterCount: canvas.elements.size
1056
+ });
1057
+ }
1058
+ catch (error) {
1059
+ logger.error('Sync error:', error);
1060
+ res.status(500).json({
1061
+ success: false,
1062
+ error: error.message,
1063
+ details: 'Internal server error during sync operation'
1064
+ });
1065
+ }
1066
+ });
1067
+ // ─── Files API (for image elements) ───────────────────────────
1068
+ // GET all files
1069
+ app.get('/api/files', (req, res) => {
1070
+ const canvas = req.canvas;
1071
+ const filesObj = {};
1072
+ canvas.files.forEach((f, id) => { filesObj[id] = f; });
1073
+ res.json({ files: filesObj });
1074
+ });
1075
+ // POST add/update files (batch)
1076
+ app.post('/api/files', (req, res) => {
1077
+ const canvas = req.canvas;
1078
+ try {
1079
+ const body = req.body;
1080
+ // Keep the existing endpoint's accepted wrapper/array shapes and count
1081
+ // behavior. Durable mode adds publication guarantees without redefining
1082
+ // the memory-only request contract.
1083
+ const fileList = (Array.isArray(body) ? body : (body?.files || []));
1084
+ const preparedFiles = prepareFileWrites(canvas, fileList);
1085
+ commitCanvasMutation(canvas, () => {
1086
+ preparedFiles.forEach(file => canvas.files.set(file.id, file));
1087
+ });
1088
+ // Broadcast only after every referenced blob and the checkpoint are durable.
1089
+ broadcast(canvas, { type: 'files_added', files: fileList });
1090
+ res.json({ success: true, count: fileList.length });
1091
+ }
1092
+ catch (error) {
1093
+ logger.error('Error storing canvas files:', error);
1094
+ if (!durableStateEnabled())
1095
+ throw error;
1096
+ res.status(mutationErrorStatus(error, 400)).json({
1097
+ success: false,
1098
+ error: error.message
1099
+ });
1100
+ }
1101
+ });
1102
+ // DELETE a file
1103
+ app.delete('/api/files/:id', (req, res) => {
1104
+ const canvas = req.canvas;
1105
+ try {
1106
+ const id = req.params.id;
1107
+ if (!canvas.files.has(id)) {
1108
+ return res.status(404).json({ success: false, error: `File with ID ${id} not found` });
1109
+ }
1110
+ commitCanvasMutation(canvas, () => canvas.files.delete(id));
1111
+ broadcast(canvas, { type: 'file_deleted', fileId: id });
1112
+ res.json({ success: true });
1113
+ }
1114
+ catch (error) {
1115
+ logger.error('Error deleting canvas file:', error);
1116
+ res.status(mutationErrorStatus(error, 500)).json({
1117
+ success: false,
1118
+ error: error.message
1119
+ });
1120
+ }
1121
+ });
1122
+ const pendingExports = new Map();
1123
+ const exportImageSchema = z.object({
1124
+ format: z.enum(['png', 'svg']),
1125
+ background: z.boolean().optional(),
1126
+ renderer: z.enum(['auto', 'node', 'browser']).optional(),
1127
+ dark: z.boolean().optional(),
1128
+ scale: z.number().min(1).max(MAX_SCALE).optional(),
1129
+ padding: z.number().min(0).optional(),
1130
+ elementIds: z.array(z.string()).min(1).optional(),
1131
+ frameId: z.string().optional(),
1132
+ embedScene: z.boolean().default(false),
1133
+ embedFonts: z.boolean().optional()
1134
+ });
1135
+ const NO_BROWSER_TAB_ERROR = 'No frontend client connected. Open the canvas in a browser first.';
1136
+ // Ask the open browser tab(s) to render — Excalidraw's own exporter in a real
1137
+ // browser. Slower (re-sync + 3 s collection window) and needs a tab, but it
1138
+ // is the reference rendering, so it stays available as renderer:'browser'.
1139
+ function exportViaBrowserTab(canvas, options) {
1140
+ const { format, background, renderer: _renderer, ...rest } = options;
1141
+ const requestId = generateId();
1142
+ const exportPromise = new Promise((resolve, reject) => {
1143
+ const timeout = setTimeout(() => {
1144
+ const pending = pendingExports.get(requestId);
1145
+ pendingExports.delete(requestId);
1146
+ // If we collected any result during the window, use it
1147
+ if (pending?.bestResult) {
1148
+ resolve(pending.bestResult);
1149
+ }
1150
+ else {
1151
+ reject(new Error('Export timed out after 30 seconds'));
1152
+ }
1153
+ }, 30000);
1154
+ pendingExports.set(requestId, { canvasId: canvas.id, resolve, reject, timeout, collectionTimeout: null, bestResult: null });
1155
+ });
1156
+ // Re-broadcast current elements so all connected clients (including stale ones)
1157
+ // sync to the canonical server state before exporting
1158
+ const filesObj = {};
1159
+ canvas.files.forEach((f, id) => { filesObj[id] = f; });
1160
+ broadcast(canvas, {
1161
+ type: 'initial_elements',
1162
+ elements: Array.from(canvas.elements.values()),
1163
+ forExport: true,
1164
+ ...(canvas.files.size > 0 ? { files: filesObj } : {})
1165
+ });
1166
+ // Give browsers time to process the reload before requesting export
1167
+ setTimeout(() => {
1168
+ broadcast(canvas, {
1169
+ type: 'export_image_request',
1170
+ requestId,
1171
+ format,
1172
+ background: background ?? true,
1173
+ options: { background, ...rest }
1174
+ });
1175
+ }, 800);
1176
+ return exportPromise;
1177
+ }
1178
+ app.post('/api/export/image', async (req, res) => {
1179
+ const canvas = req.canvas;
1180
+ const parsed = exportImageSchema.safeParse(req.body ?? {});
1181
+ if (!parsed.success) {
1182
+ const issue = parsed.error.issues[0];
1183
+ const where = issue?.path.join('.');
1184
+ return res.status(400).json({
1185
+ success: false,
1186
+ error: where === 'format'
1187
+ ? 'format must be "png" or "svg"'
1188
+ : `${where ? `${where}: ` : ''}${issue?.message ?? 'invalid request'}`
1189
+ });
1190
+ }
1191
+ const options = parsed.data;
1192
+ if (options.embedScene && options.format !== 'png') {
1193
+ return res.status(400).json({ success: false, error: 'embedScene is only supported for PNG exports' });
1194
+ }
1195
+ const renderer = options.renderer ?? 'auto';
1196
+ const respondBrowser = async () => {
1197
+ if (clientsOf(canvas).size === 0) {
1198
+ return res.status(503).json({ success: false, error: NO_BROWSER_TAB_ERROR });
1199
+ }
1200
+ try {
1201
+ const result = await exportViaBrowserTab(canvas, options);
1202
+ res.json({ success: true, format: result.format, data: result.data, renderer: 'browser' });
1203
+ }
1204
+ catch (error) {
1205
+ res.status(500).json({ success: false, error: error.message });
1206
+ }
1207
+ };
1208
+ if (renderer === 'browser')
1209
+ return respondBrowser();
1210
+ try {
1211
+ const { renderer: _renderer, ...renderOptions } = options;
1212
+ const scene = { elements: Array.from(canvas.elements.values()), files: Object.fromEntries(canvas.files) };
1213
+ const result = await renderScene(scene, renderOptions);
1214
+ res.json({
1215
+ success: true,
1216
+ format: result.format,
1217
+ data: result.data,
1218
+ renderer: 'node',
1219
+ width: result.width,
1220
+ height: result.height,
1221
+ ...(result.warnings.length > 0 ? { warnings: result.warnings } : {})
1222
+ });
1223
+ }
1224
+ catch (error) {
1225
+ if (error instanceof RenderError) {
1226
+ return res.status(error.status).json({ success: false, error: error.message });
1227
+ }
1228
+ logger.error('Headless image export failed:', error);
1229
+ if (renderer === 'auto' && clientsOf(canvas).size > 0) {
1230
+ // The reference renderer is available; use it rather than fail
1231
+ logger.warn('Falling back to the browser tab for this export');
1232
+ return respondBrowser();
1233
+ }
1234
+ res.status(500).json({ success: false, error: error.message });
1235
+ }
1236
+ });
1237
+ // Image export: result (Frontend -> Express -> MCP)
1238
+ app.post('/api/export/image/result', (req, res) => {
1239
+ const canvas = req.canvas;
1240
+ try {
1241
+ const { requestId, format, data, error } = req.body;
1242
+ if (!requestId) {
1243
+ return res.status(400).json({
1244
+ success: false,
1245
+ error: 'requestId is required'
1246
+ });
1247
+ }
1248
+ const pending = pendingExports.get(requestId);
1249
+ if (!pending || pending.canvasId !== canvas.id) {
1250
+ // Already resolved by another client, or expired — ignore silently
1251
+ return res.json({ success: true });
1252
+ }
1253
+ if (error) {
1254
+ // Don't reject on error — another WebSocket client may still succeed.
1255
+ logger.warn(`Export error from one client (requestId=${requestId}): ${error}`);
1256
+ return res.json({ success: true });
1257
+ }
1258
+ // Keep the largest response (most complete canvas state wins)
1259
+ if (!pending.bestResult || data.length > pending.bestResult.data.length) {
1260
+ pending.bestResult = { format, data };
1261
+ }
1262
+ // Start a short collection window on the first response, then resolve with best
1263
+ if (!pending.collectionTimeout) {
1264
+ pending.collectionTimeout = setTimeout(() => {
1265
+ const p = pendingExports.get(requestId);
1266
+ if (p?.bestResult) {
1267
+ clearTimeout(p.timeout);
1268
+ pendingExports.delete(requestId);
1269
+ p.resolve(p.bestResult);
1270
+ }
1271
+ }, 3000);
1272
+ }
1273
+ res.json({ success: true });
1274
+ }
1275
+ catch (error) {
1276
+ logger.error('Error processing export result:', error);
1277
+ res.status(500).json({
1278
+ success: false,
1279
+ error: error.message
1280
+ });
1281
+ }
1282
+ });
1283
+ const pendingViewports = new Map();
1284
+ const viewportRequestSchema = z.object({
1285
+ scrollToContent: z.boolean().optional(),
1286
+ scrollToElementIds: z.array(z.string().min(1)).min(1).optional(),
1287
+ viewportZoomFactor: z.number().positive().max(1).optional(),
1288
+ scrollToElementId: z.string().min(1).optional(),
1289
+ zoom: z.number().min(0.1).max(10).optional(),
1290
+ offsetX: z.number().optional(),
1291
+ offsetY: z.number().optional()
1292
+ }).superRefine((params, ctx) => {
1293
+ const modes = [
1294
+ params.scrollToContent === true,
1295
+ params.scrollToElementIds !== undefined,
1296
+ params.scrollToElementId !== undefined,
1297
+ params.zoom !== undefined || params.offsetX !== undefined || params.offsetY !== undefined
1298
+ ].filter(Boolean).length;
1299
+ if (modes !== 1) {
1300
+ ctx.addIssue({
1301
+ code: z.ZodIssueCode.custom,
1302
+ message: 'Specify exactly one viewport mode: scrollToContent, scrollToElementIds, scrollToElementId, or manual zoom/offset'
1303
+ });
1304
+ }
1305
+ if (params.viewportZoomFactor !== undefined &&
1306
+ params.scrollToContent !== true &&
1307
+ params.scrollToElementIds === undefined) {
1308
+ ctx.addIssue({
1309
+ code: z.ZodIssueCode.custom,
1310
+ path: ['viewportZoomFactor'],
1311
+ message: 'viewportZoomFactor requires scrollToContent or scrollToElementIds'
1312
+ });
1313
+ }
1314
+ });
1315
+ app.post('/api/viewport', (req, res) => {
1316
+ const canvas = req.canvas;
1317
+ try {
1318
+ const { scrollToContent, scrollToElementIds, scrollToElementId, viewportZoomFactor, zoom, offsetX, offsetY } = viewportRequestSchema.parse(req.body);
1319
+ if (clientsOf(canvas).size === 0) {
1320
+ return res.status(503).json({
1321
+ success: false,
1322
+ error: 'No frontend client connected. Open the canvas in a browser first.'
1323
+ });
1324
+ }
1325
+ const requestId = generateId();
1326
+ const viewportPromise = new Promise((resolve, reject) => {
1327
+ const timeout = setTimeout(() => {
1328
+ pendingViewports.delete(requestId);
1329
+ reject(new Error('Viewport request timed out after 10 seconds'));
1330
+ }, 10000);
1331
+ pendingViewports.set(requestId, { canvasId: canvas.id, resolve, reject, timeout });
1332
+ });
1333
+ broadcast(canvas, {
1334
+ type: 'set_viewport',
1335
+ requestId,
1336
+ scrollToContent,
1337
+ scrollToElementIds,
1338
+ scrollToElementId,
1339
+ viewportZoomFactor,
1340
+ zoom,
1341
+ offsetX,
1342
+ offsetY
1343
+ });
1344
+ viewportPromise
1345
+ .then(result => {
1346
+ res.json(result);
1347
+ })
1348
+ .catch(error => {
1349
+ res.status(500).json({
1350
+ success: false,
1351
+ error: error.message
1352
+ });
1353
+ });
1354
+ }
1355
+ catch (error) {
1356
+ logger.error('Error initiating viewport change:', error);
1357
+ res.status(error instanceof z.ZodError ? 400 : 500).json({
1358
+ success: false,
1359
+ error: error instanceof z.ZodError
1360
+ ? error.issues.map(issue => issue.message).join('; ')
1361
+ : error.message
1362
+ });
1363
+ }
1364
+ });
1365
+ // Viewport control: result (Frontend -> Express -> MCP)
1366
+ app.post('/api/viewport/result', (req, res) => {
1367
+ try {
1368
+ const { requestId, success, message, error } = req.body;
1369
+ if (!requestId) {
1370
+ return res.status(400).json({
1371
+ success: false,
1372
+ error: 'requestId is required'
1373
+ });
1374
+ }
1375
+ const pending = pendingViewports.get(requestId);
1376
+ if (!pending || pending.canvasId !== req.canvas.id) {
1377
+ return res.json({ success: true });
1378
+ }
1379
+ if (error || success === false) {
1380
+ clearTimeout(pending.timeout);
1381
+ pendingViewports.delete(requestId);
1382
+ pending.reject(new Error(error || message || 'Viewport update failed'));
1383
+ return res.json({ success: true });
1384
+ }
1385
+ clearTimeout(pending.timeout);
1386
+ pendingViewports.delete(requestId);
1387
+ pending.resolve({ success: true, message: message || 'Viewport updated' });
1388
+ res.json({ success: true });
1389
+ }
1390
+ catch (error) {
1391
+ logger.error('Error processing viewport result:', error);
1392
+ res.status(500).json({
1393
+ success: false,
1394
+ error: error.message
1395
+ });
1396
+ }
1397
+ });
1398
+ app.use('/api/comments', createCommentRouter(broadcast));
1399
+ app.use('/api/canvases', createCanvasRouter(registry, removed => {
1400
+ clientsOf(removed).forEach(client => client.close(4410, 'Canvas deleted'));
1401
+ clientsByCanvas.delete(removed.id);
1402
+ }));
1403
+ app.use('/api/ai', createAiRouter());
1404
+ app.use('/mcp', createMcpRouter());
1405
+ // A host in front of the canvas may answer this itself with links for the signed-in user.
1406
+ app.get('/api/nav', (_req, res) => { res.json({ success: true, links: [] }); });
1407
+ // Snapshots: save
1408
+ app.post('/api/snapshots', (req, res) => {
1409
+ const canvas = req.canvas;
1410
+ try {
1411
+ const { name } = req.body;
1412
+ if (!name || typeof name !== 'string') {
1413
+ return res.status(400).json({
1414
+ success: false,
1415
+ error: 'Snapshot name is required'
1416
+ });
1417
+ }
1418
+ if (name.startsWith(SAFETY_PREFIX)) {
1419
+ return res.status(400).json({
1420
+ success: false,
1421
+ error: `Snapshot names starting with "${SAFETY_PREFIX}" are reserved for the copies kept before a clear`
1422
+ });
1423
+ }
1424
+ const snapshot = {
1425
+ name,
1426
+ // Snapshots are historical values, not aliases to live mutable elements.
1427
+ // Bound-arrow rerouting mutates arrow objects in place. structuredClone
1428
+ // is available across the supported Node.js >=20 runtime range.
1429
+ elements: structuredClone(Array.from(canvas.elements.values())),
1430
+ createdAt: new Date().toISOString()
1431
+ };
1432
+ commitCanvasMutation(canvas, () => canvas.snapshots.set(name, snapshot));
1433
+ logger.info(`Snapshot saved: "${name}" with ${snapshot.elements.length} elements`);
1434
+ res.json({
1435
+ success: true,
1436
+ name,
1437
+ elementCount: snapshot.elements.length,
1438
+ createdAt: snapshot.createdAt
1439
+ });
1440
+ }
1441
+ catch (error) {
1442
+ logger.error('Error saving snapshot:', error);
1443
+ res.status(mutationErrorStatus(error, 500)).json({
1444
+ success: false,
1445
+ error: error.message
1446
+ });
1447
+ }
1448
+ });
1449
+ // Snapshots: list
1450
+ app.get('/api/snapshots', (req, res) => {
1451
+ const canvas = req.canvas;
1452
+ try {
1453
+ const list = Array.from(canvas.snapshots.values()).map(s => ({
1454
+ name: s.name,
1455
+ elementCount: s.elements.length,
1456
+ createdAt: s.createdAt
1457
+ }));
1458
+ res.json({
1459
+ success: true,
1460
+ snapshots: list,
1461
+ count: list.length
1462
+ });
1463
+ }
1464
+ catch (error) {
1465
+ logger.error('Error listing snapshots:', error);
1466
+ res.status(500).json({
1467
+ success: false,
1468
+ error: error.message
1469
+ });
1470
+ }
1471
+ });
1472
+ // Snapshots: get by name
1473
+ app.get('/api/snapshots/:name', (req, res) => {
1474
+ const canvas = req.canvas;
1475
+ try {
1476
+ const { name } = req.params;
1477
+ const snapshot = canvas.snapshots.get(name);
1478
+ if (!snapshot) {
1479
+ return res.status(404).json({
1480
+ success: false,
1481
+ error: `Snapshot "${name}" not found`
1482
+ });
1483
+ }
1484
+ res.json({
1485
+ success: true,
1486
+ snapshot
1487
+ });
1488
+ }
1489
+ catch (error) {
1490
+ logger.error('Error fetching snapshot:', error);
1491
+ res.status(500).json({
1492
+ success: false,
1493
+ error: error.message
1494
+ });
1495
+ }
1496
+ });
1497
+ // Serve the frontend
1498
+ app.get('/', (req, res) => {
1499
+ const htmlFile = path.join(__dirname, '../dist/frontend/index.html');
1500
+ res.sendFile(htmlFile, (err) => {
1501
+ if (err) {
1502
+ logger.error('Error serving frontend:', err);
1503
+ res.status(404).send('Frontend not found. Please run "npm run build" first.');
1504
+ }
1505
+ });
1506
+ });
1507
+ // Health check endpoint
1508
+ app.get('/health', (req, res) => {
1509
+ const canvas = req.canvas;
1510
+ res.json({
1511
+ status: 'healthy',
1512
+ timestamp: new Date().toISOString(),
1513
+ elements_count: canvas.elements.size,
1514
+ websocket_clients: clientsOf(canvas).size,
1515
+ // Image renderers available right now: headless (always, in-process) and
1516
+ // the number of browser tabs that can render on request
1517
+ renderers: { node: true, browser: clientsOf(canvas).size },
1518
+ ...(durableStateEnabled() ? { durable_state_enabled: true } : {}),
1519
+ // Identity for `stop`: it must only ever signal a process that both
1520
+ // identifies as this service AND self-reports its pid — never a pid
1521
+ // from a stale pidfile or an unrelated app squatting on the port.
1522
+ service: 'daigram-canvas',
1523
+ pid: process.pid
1524
+ });
1525
+ });
1526
+ // Sync status endpoint
1527
+ app.get('/api/sync/status', (req, res) => {
1528
+ const canvas = req.canvas;
1529
+ res.json({
1530
+ success: true,
1531
+ elementCount: canvas.elements.size,
1532
+ ...(durableStateEnabled() ? { durableStateEnabled: true } : {}),
1533
+ timestamp: new Date().toISOString(),
1534
+ memoryUsage: {
1535
+ heapUsed: Math.round(process.memoryUsage().heapUsed / 1024 / 1024), // MB
1536
+ heapTotal: Math.round(process.memoryUsage().heapTotal / 1024 / 1024), // MB
1537
+ },
1538
+ websocketClients: clientsOf(req.canvas).size
1539
+ });
1540
+ });
1541
+ // Error handling middleware
1542
+ app.use((err, req, res, next) => {
1543
+ logger.error('Unhandled error:', err);
1544
+ res.status(500).json({
1545
+ success: false,
1546
+ error: 'Internal server error'
1547
+ });
1548
+ });
1549
+ // Start server
1550
+ const PORT = parseInt(process.env.PORT || '3000', 10);
1551
+ const HOST = process.env.HOST || '127.0.0.1';
1552
+ const LOOPBACK_GUARD_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0', '::']);
1553
+ const LOOPBACK_ADDRESSES = ['127.0.0.1', '::1'];
1554
+ function formatHostForUrl(host) {
1555
+ return host.includes(':') ? `[${host}]` : host;
1556
+ }
1557
+ function canConnect(host, port) {
1558
+ return new Promise(resolve => {
1559
+ let settled = false;
1560
+ const socket = net.createConnection({ host, port });
1561
+ const finish = (isOpen) => {
1562
+ if (settled)
1563
+ return;
1564
+ settled = true;
1565
+ socket.destroy();
1566
+ resolve(isOpen);
1567
+ };
1568
+ socket.setTimeout(250);
1569
+ socket.once('connect', () => finish(true));
1570
+ socket.once('timeout', () => finish(false));
1571
+ socket.once('error', () => finish(false));
1572
+ });
1573
+ }
1574
+ async function findExistingLoopbackListener(port) {
1575
+ for (const host of LOOPBACK_ADDRESSES) {
1576
+ if (await canConnect(host, port)) {
1577
+ return host;
1578
+ }
1579
+ }
1580
+ return null;
1581
+ }
1582
+ function releaseDurableStateLockSafely() {
1583
+ try {
1584
+ releaseDurableStateLock();
1585
+ }
1586
+ catch (error) {
1587
+ logger.error('Failed to release canvas data-directory lock:', error);
1588
+ }
1589
+ }
1590
+ server.on('error', (error) => {
1591
+ if (error.code === 'EADDRINUSE') {
1592
+ const address = error.address || HOST;
1593
+ logger.error(`Canvas server port ${PORT} is already in use on ${formatHostForUrl(address)}.`);
1594
+ }
1595
+ else if (error.code === 'EACCES') {
1596
+ logger.error(`Canvas server cannot bind ${formatHostForUrl(HOST)}:${PORT}: permission denied.`);
1597
+ }
1598
+ else {
1599
+ logger.error('Failed to start canvas server:', error);
1600
+ }
1601
+ releaseDurableStateLockSafely();
1602
+ process.exit(1);
1603
+ });
1604
+ async function startServer() {
1605
+ acquireDurableStateLock();
1606
+ let durableState;
1607
+ try {
1608
+ durableState = registry.openMain();
1609
+ }
1610
+ catch (error) {
1611
+ releaseDurableStateLockSafely();
1612
+ throw error;
1613
+ }
1614
+ if (durableState.loaded) {
1615
+ logger.info('Loaded durable canvas state', {
1616
+ elements: durableState.elements,
1617
+ files: durableState.files,
1618
+ snapshots: durableState.snapshots
1619
+ });
1620
+ }
1621
+ else if (durableState.enabled) {
1622
+ logger.info('Durable canvas state enabled; starting without an existing checkpoint');
1623
+ }
1624
+ if (LOOPBACK_GUARD_HOSTS.has(HOST)) {
1625
+ const existingHost = await findExistingLoopbackListener(PORT);
1626
+ if (existingHost) {
1627
+ logger.error(`Refusing to start canvas server on ${formatHostForUrl(HOST)}:${PORT}: ` +
1628
+ `${formatHostForUrl(existingHost)}:${PORT} is already listening. ` +
1629
+ 'This prevents duplicate IPv4/IPv6 canvas servers from splitting state.');
1630
+ releaseDurableStateLockSafely();
1631
+ process.exit(1);
1632
+ }
1633
+ }
1634
+ // The pidfile identifies the listening process for CLI lifecycle commands.
1635
+ // The data-directory lock independently protects durable-state ownership.
1636
+ let ownsPidFile = false;
1637
+ server.listen(PORT, HOST, () => {
1638
+ const hostForUrl = formatHostForUrl(HOST);
1639
+ logger.info(`POC server running on http://${hostForUrl}:${PORT}`);
1640
+ logger.info(`WebSocket server running on ws://${hostForUrl}:${PORT}`);
1641
+ // Written only after listen succeeds so stale files can't shadow a
1642
+ // server that never came up; lets `daigram stop` find us.
1643
+ writePidFile(PORT, process.pid);
1644
+ ownsPidFile = true;
1645
+ // The AI runner drives the canvas through the same HTTP API as the CLI, so it must be able to reach this server.
1646
+ if (process.env.AI_PROVIDER && new URL(EXPRESS_SERVER_URL).port !== String(PORT)) {
1647
+ 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.`);
1648
+ }
1649
+ });
1650
+ const shutdown = (signal) => {
1651
+ logger.info(`Received ${signal}, shutting down canvas server`);
1652
+ if (ownsPidFile)
1653
+ removePidFile(PORT);
1654
+ server.close(() => {
1655
+ releaseDurableStateLockSafely();
1656
+ process.exit(0);
1657
+ });
1658
+ // Force-exit if open sockets keep the server from closing promptly.
1659
+ setTimeout(() => {
1660
+ releaseDurableStateLockSafely();
1661
+ process.exit(0);
1662
+ }, 2000).unref();
1663
+ };
1664
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
1665
+ process.on('SIGINT', () => shutdown('SIGINT'));
1666
+ process.on('exit', () => {
1667
+ if (ownsPidFile)
1668
+ removePidFile(PORT);
1669
+ releaseDurableStateLockSafely();
1670
+ });
1671
+ }
1672
+ // Start the canvas server only when this file is the process entry point
1673
+ // (`node dist/server.js`, `npm run canvas`, or spawned by the CLI/MCP
1674
+ // auto-start). Importing this module must never start the server.
1675
+ if (isMainModule(import.meta.url)) {
1676
+ void startServer().catch(error => {
1677
+ logger.error('Failed to start canvas server:', error);
1678
+ releaseDurableStateLockSafely();
1679
+ process.exit(1);
1680
+ });
1681
+ }
1682
+ export { startServer };
1683
+ export default app;
1684
+ //# sourceMappingURL=server.js.map