orqevio 1.2.0 → 1.3.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 (242) hide show
  1. package/dist/web/assets/{AccessKeyReveal-C8pr7rZt.js → AccessKeyReveal-B8-53IsG.js} +2 -2
  2. package/dist/web/assets/{AccessRows-33_zo5aX.js → AccessRows-BvqV7IBl.js} +1 -1
  3. package/dist/web/assets/ActivityList-CMeaCWkv.js +1 -0
  4. package/dist/web/assets/AgentsPage-BFV4Irgu.js +1 -0
  5. package/dist/web/assets/Attachments-Ehl3SEHq.js +221 -0
  6. package/dist/web/assets/Avatar-XLUId3O5.js +1 -0
  7. package/dist/web/assets/BoardPage-yeO36gca.js +1 -0
  8. package/dist/web/assets/{Button-BsCJGAdQ.js → Button-DFtiJeUa.js} +1 -1
  9. package/dist/web/assets/{CardItem-CYvB_I7V.js → CardItem-BJSe5Yys.js} +2 -2
  10. package/dist/web/assets/Checkbox-D2glB_5Z.js +1 -0
  11. package/dist/web/assets/ColorPicker-DXWll90z.js +1 -0
  12. package/dist/web/assets/{ConsentPage-DMBzrJ3S.js → ConsentPage-LsyaMLAu.js} +1 -1
  13. package/dist/web/assets/CopyButton-DPGirLsh.js +1 -0
  14. package/dist/web/assets/DocPage-LDbLYm22.js +1 -0
  15. package/dist/web/assets/{EmptyState-DXTzO23V.js → EmptyState-NLNYFMbg.js} +1 -1
  16. package/dist/web/assets/Field-CJ08Txzu.js +1 -0
  17. package/dist/web/assets/HomePage-C5tasScn.js +1 -0
  18. package/dist/web/assets/Menu-D1dtpXQc.js +41 -0
  19. package/dist/web/assets/PageHeader-6CKm6Nmk.js +1 -0
  20. package/dist/web/assets/Popover-rUw84XS3.js +1 -0
  21. package/dist/web/assets/ProjectPage-sRIqleNm.js +1 -0
  22. package/dist/web/assets/ProjectSettingsDialog-Bu9Nh_f1.js +1 -0
  23. package/dist/web/assets/Segmented-CkRO6dAI.js +1 -0
  24. package/dist/web/assets/SettingsPage--HzCtlxW.js +1 -0
  25. package/dist/web/assets/States-YdzeahGB.js +1 -0
  26. package/dist/web/assets/TokenCard-Cxa4noi9.js +1 -0
  27. package/dist/web/assets/{Trans-CnOS9ct4.js → Trans-BeLoTtlV.js} +1 -1
  28. package/dist/web/assets/TrashPage-eI708eSb.js +1 -0
  29. package/dist/web/assets/VaultPage-DZ8whuhV.js +9 -0
  30. package/dist/web/assets/actions-BHpEdIG-.js +1 -0
  31. package/dist/web/assets/{activity-CdqdeoxV.js → activity-B9yvTGRK.js} +1 -1
  32. package/dist/web/assets/{activity-_4kW2ZJ_.js → activity-BhJh5gr8.js} +1 -1
  33. package/dist/web/assets/{activity-ZNUvkr3p.js → activity-C6uHBG-k.js} +1 -1
  34. package/dist/web/assets/activity-C_Gj6kNm.js +1 -0
  35. package/dist/web/assets/{activity-6zHhcitv.js → activity-DE5W3_Zl.js} +1 -1
  36. package/dist/web/assets/{activity-mAare-yB.js → activity-Da3DZwfO.js} +1 -1
  37. package/dist/web/assets/{activity-DGUXp5QL.js → activity-DklyxS1p.js} +1 -1
  38. package/dist/web/assets/{activity-CWpwjlzR.js → activity-DqxJDBNZ.js} +1 -1
  39. package/dist/web/assets/agents-BT7hhkmJ.js +1 -0
  40. package/dist/web/assets/agents-CH9hiW4n.js +1 -0
  41. package/dist/web/assets/agents-D2HbGZdI.js +1 -0
  42. package/dist/web/assets/agents-dOyd7e_g.js +1 -0
  43. package/dist/web/assets/agents-hwFgCutb.js +1 -0
  44. package/dist/web/assets/agents-mGUE0KF4.js +1 -0
  45. package/dist/web/assets/agents-rpBGYkV5.js +1 -0
  46. package/dist/web/assets/{arrow-up-right-ibGMG_I6.js → arrow-up-right-CZaZGd2b.js} +1 -1
  47. package/dist/web/assets/boards-B55T0dLc.js +1 -0
  48. package/dist/web/assets/boards-BJtzDCZ4.js +1 -0
  49. package/dist/web/assets/boards-BK-HIes0.js +1 -0
  50. package/dist/web/assets/boards-BRGCpMCs.js +1 -0
  51. package/dist/web/assets/boards-D9ITCVkH.js +1 -0
  52. package/dist/web/assets/{boards-Bd-B4hhr.js → boards-DAtCVLZ8.js} +1 -1
  53. package/dist/web/assets/boards-DkGEJNsi.js +1 -0
  54. package/dist/web/assets/check-zaEYRgm_.js +1 -0
  55. package/dist/web/assets/chevron-right-CKppr8-s.js +1 -0
  56. package/dist/web/assets/{clock-8LYeV_vK.js → clock-Or1e2dj9.js} +1 -1
  57. package/dist/web/assets/common-BEzNU6dg.js +1 -0
  58. package/dist/web/assets/common-BQxUpELz.js +1 -0
  59. package/dist/web/assets/common-BVdHyWon.js +1 -0
  60. package/dist/web/assets/common-DB87cQ0w.js +1 -0
  61. package/dist/web/assets/common-DIIWFfP1.js +1 -0
  62. package/dist/web/assets/common-DL87-WQe.js +1 -0
  63. package/dist/web/assets/common-pmlLlsX2.js +1 -0
  64. package/dist/web/assets/dist-BXudX2C8.js +1 -0
  65. package/dist/web/assets/{docs-_S4ttW8g.js → docs-CdU1zlr_.js} +1 -1
  66. package/dist/web/assets/{docs-Bx1kznfx.js → docs-CozS3xm2.js} +1 -1
  67. package/dist/web/assets/{docs-BPnASlp4.js → docs-DL4bSiKv.js} +1 -1
  68. package/dist/web/assets/{docs-BwYy_eWc.js → docs-DdRzy2fY.js} +1 -1
  69. package/dist/web/assets/{docs-B6tXalZZ.js → docs-DjihmilZ.js} +1 -1
  70. package/dist/web/assets/{docs-DEnWVVdL.js → docs-DkxJ3bH2.js} +1 -1
  71. package/dist/web/assets/{docs-BlYmrIPJ.js → docs-Duf_UKKw.js} +1 -1
  72. package/dist/web/assets/{download-D-lLkEl_.js → download-DeNtxt4D.js} +1 -1
  73. package/dist/web/assets/{errors-DjlTVQK3.js → errors-CWljhQp1.js} +1 -1
  74. package/dist/web/assets/errors-Cgnb5wfv.js +1 -0
  75. package/dist/web/assets/{errors-Cmb7VSBY.js → errors-D2gpUA7_.js} +1 -1
  76. package/dist/web/assets/errors-D3pMnz0U.js +1 -0
  77. package/dist/web/assets/errors-DAwX8-Fy.js +1 -0
  78. package/dist/web/assets/{errors-Mp8QlgCo.js → errors-DlcuhMif.js} +1 -1
  79. package/dist/web/assets/errors-gJfsmgEB.js +1 -0
  80. package/dist/web/assets/{eye-DctV5dJt.js → eye-DqmmpIUP.js} +1 -1
  81. package/dist/web/assets/{file-plus-h6mN7Cra.js → file-plus-B9RcccJq.js} +1 -1
  82. package/dist/web/assets/{folder-open-CMi40_Qn.js → folder-open-B5eZ7cqb.js} +1 -1
  83. package/dist/web/assets/{format-B7quLgVq.js → format-DEwJtk6a.js} +3 -3
  84. package/dist/web/assets/history-BTSLGRUd.js +1 -0
  85. package/dist/web/assets/history-BYQKniZP.js +1 -0
  86. package/dist/web/assets/history-CCBPyinv.js +1 -0
  87. package/dist/web/assets/history-DJRWWqQM.js +1 -0
  88. package/dist/web/assets/history-DKzmm79r.js +1 -0
  89. package/dist/web/assets/history-DTKtuTix.js +1 -0
  90. package/dist/web/assets/history-DiKunONf.js +1 -0
  91. package/dist/web/assets/index-DXZdSAQ6.js +9 -0
  92. package/dist/web/assets/index-JKAKpcGm.css +2 -0
  93. package/dist/web/assets/{lock-keyhole-CEVFyiXF.js → lock-keyhole-BSIBvxdl.js} +1 -1
  94. package/dist/web/assets/{paperclip-DGtxZG9D.js → paperclip-45hm0LEK.js} +1 -1
  95. package/dist/web/assets/{pencil-BQCLTZIj.js → pencil-BgKjfUw7.js} +1 -1
  96. package/dist/web/assets/plus-DkN0_LKK.js +1 -0
  97. package/dist/web/assets/{projects-BsY2PmjV.js → projects-B2JAODbF.js} +1 -1
  98. package/dist/web/assets/{projects--t9VhdYF.js → projects-BUM_86ov.js} +1 -1
  99. package/dist/web/assets/{projects-D3eU-Jew.js → projects-Bc_qRQF1.js} +1 -1
  100. package/dist/web/assets/{projects-aUO3NoCx.js → projects-C_ZQ0ABW.js} +1 -1
  101. package/dist/web/assets/{projects-BVQGJc7P.js → projects-DTgjzEHE.js} +1 -1
  102. package/dist/web/assets/{projects-CNfl9kuI.js → projects-NfKe5Y_d.js} +1 -1
  103. package/dist/web/assets/{projects-CrDJIGi7.js → projects-pq_l0OIa.js} +1 -1
  104. package/dist/web/assets/realtime-D4IlZ7la.js +1 -0
  105. package/dist/web/assets/restore-2dQEOQsU.js +1 -0
  106. package/dist/web/assets/router-Dq52n_dF.js +1 -0
  107. package/dist/web/assets/router-i53kBtjJ.js +6 -0
  108. package/dist/web/assets/{search-CorP7WeO.js → search-THqOJIwW.js} +1 -1
  109. package/dist/web/assets/session-BuK7KqOl.js +1 -0
  110. package/dist/web/assets/settings-B2K0CC6S.js +1 -0
  111. package/dist/web/assets/settings-C6mEKUST.js +1 -0
  112. package/dist/web/assets/settings-CHHy3vrT.js +1 -0
  113. package/dist/web/assets/settings-CcG0OlNC.js +1 -0
  114. package/dist/web/assets/settings-Clq39MFV.js +1 -0
  115. package/dist/web/assets/settings-D5LDNHZs.js +1 -0
  116. package/dist/web/assets/settings-DOUFAQf_.js +1 -0
  117. package/dist/web/assets/shell-BWsPUku5.js +1 -0
  118. package/dist/web/assets/shell-ChgP5xyE.js +1 -0
  119. package/dist/web/assets/shell-DNBUBxNa.js +1 -0
  120. package/dist/web/assets/{shell-CkzevnPH.js → shell-DND6HJAN.js} +1 -1
  121. package/dist/web/assets/shell-DQ0M6Blt.js +1 -0
  122. package/dist/web/assets/shell-DvS2WNEV.js +1 -0
  123. package/dist/web/assets/shell-jyyol4c1.js +1 -0
  124. package/dist/web/assets/{shield-exclamation-point-C1g5FW-Y.js → shield-exclamation-point-XUMrMBnT.js} +1 -1
  125. package/dist/web/assets/{square-kanban-DPQB8HVT.js → square-kanban-CMvSaNex.js} +1 -1
  126. package/dist/web/assets/{sticky-note-DDDireBz.js → sticky-note-DQns5zF8.js} +1 -1
  127. package/dist/web/assets/sync-7NhCAmaJ.js +1 -0
  128. package/dist/web/assets/tag-5EiSR0t7.js +1 -0
  129. package/dist/web/assets/trash-BS2DxHiH.js +1 -0
  130. package/dist/web/assets/trash-Blx5xyGN.js +1 -0
  131. package/dist/web/assets/trash-C8iQ5jx0.js +1 -0
  132. package/dist/web/assets/{trash-Cwc7ak-1.js → trash-CBo3hCgY.js} +1 -1
  133. package/dist/web/assets/trash-D4IUwUwV.js +1 -0
  134. package/dist/web/assets/trash-D6VCYSPP.js +1 -0
  135. package/dist/web/assets/trash-DHTLFm0L.js +1 -0
  136. package/dist/web/assets/trash-DlhKL2Eo.js +2 -0
  137. package/dist/web/assets/trash-Duy-tBWH.js +1 -0
  138. package/dist/web/assets/{triangle-exclamation-point-DAx_yYud.js → triangle-exclamation-point-fRu34PHx.js} +1 -1
  139. package/dist/web/assets/vault-CNRRr8jE.js +7 -0
  140. package/dist/web/assets/vault-D0qB-XRT.js +7 -0
  141. package/dist/web/assets/vault-DJFOCIz1.js +7 -0
  142. package/dist/web/assets/vault-DbyTbZAp.js +7 -0
  143. package/dist/web/assets/vault-DfGgsIOH.js +7 -0
  144. package/dist/web/assets/vault-Dw09SaES.js +7 -0
  145. package/dist/web/assets/vault-DyvlvJIG.js +7 -0
  146. package/dist/web/index.html +34 -34
  147. package/dist/worker/index.js +2296 -775
  148. package/package.json +1 -1
  149. package/dist/web/assets/ActivityList-BIkO7t1s.js +0 -1
  150. package/dist/web/assets/AgentsPage-EFClXhsD.js +0 -1
  151. package/dist/web/assets/Attachments-BQ-d5pab.js +0 -215
  152. package/dist/web/assets/Avatar-D0rGsnHO.js +0 -1
  153. package/dist/web/assets/BoardPage-E4Vb1Vzg.js +0 -1
  154. package/dist/web/assets/Checkbox-BFT-RFt3.js +0 -1
  155. package/dist/web/assets/ColorPicker-BzIkVZmd.js +0 -1
  156. package/dist/web/assets/CopyButton-C9OKZ9i-.js +0 -1
  157. package/dist/web/assets/DocPage-CQ0aKAqd.js +0 -1
  158. package/dist/web/assets/Field-R6tL5cq9.js +0 -1
  159. package/dist/web/assets/HomePage-Bu2He9yp.js +0 -1
  160. package/dist/web/assets/Menu-B-V63C8_.js +0 -1
  161. package/dist/web/assets/PageHeader-D3trjYfc.js +0 -1
  162. package/dist/web/assets/Popover-Co2GHl85.js +0 -1
  163. package/dist/web/assets/ProjectPage-D2StbdlS.js +0 -1
  164. package/dist/web/assets/ProjectSettingsDialog-Bp-VYMVG.js +0 -1
  165. package/dist/web/assets/Segmented-Dk6qWGHS.js +0 -1
  166. package/dist/web/assets/SettingsPage-BrEqLHwa.js +0 -1
  167. package/dist/web/assets/States-DqHu9GSj.js +0 -1
  168. package/dist/web/assets/TokenCard-DPhYIZLh.js +0 -1
  169. package/dist/web/assets/TrashPage-CFeq09im.js +0 -1
  170. package/dist/web/assets/VaultPage-C6RKw617.js +0 -9
  171. package/dist/web/assets/actions-CgdLcD8k.js +0 -1
  172. package/dist/web/assets/activity-CNh3v5Mu.js +0 -1
  173. package/dist/web/assets/agents-BGMKVi6i.js +0 -1
  174. package/dist/web/assets/agents-BXU0uzTH.js +0 -1
  175. package/dist/web/assets/agents-Cibz_z-h.js +0 -1
  176. package/dist/web/assets/agents-DOYJyzdo.js +0 -1
  177. package/dist/web/assets/agents-DrakTRAt.js +0 -1
  178. package/dist/web/assets/agents-de0xSyjY.js +0 -1
  179. package/dist/web/assets/agents-kJYxGRsw.js +0 -1
  180. package/dist/web/assets/boards-BExvvK2C.js +0 -1
  181. package/dist/web/assets/boards-CttGasCM.js +0 -1
  182. package/dist/web/assets/boards-DF_wEJNs.js +0 -1
  183. package/dist/web/assets/boards-DM5MZ8MK.js +0 -1
  184. package/dist/web/assets/boards-DRXX82kC.js +0 -1
  185. package/dist/web/assets/boards-DTnFEV0A.js +0 -1
  186. package/dist/web/assets/check-CBvAlEZm.js +0 -1
  187. package/dist/web/assets/chevron-right-DFw6KMv6.js +0 -1
  188. package/dist/web/assets/common-COjNB9BR.js +0 -1
  189. package/dist/web/assets/common-CxTPkV7X.js +0 -1
  190. package/dist/web/assets/common-D-VyKjDv.js +0 -1
  191. package/dist/web/assets/common-D3b_OJUw.js +0 -1
  192. package/dist/web/assets/common-DJe5JA5c.js +0 -1
  193. package/dist/web/assets/common-Dr48NU46.js +0 -1
  194. package/dist/web/assets/common-Vls4DuMQ.js +0 -1
  195. package/dist/web/assets/confirm-CwwEqH9-.js +0 -41
  196. package/dist/web/assets/errors-7otksh_4.js +0 -1
  197. package/dist/web/assets/errors-DIc3HG7-.js +0 -1
  198. package/dist/web/assets/errors-Dqi8AWNO.js +0 -1
  199. package/dist/web/assets/errors-znUyR2oX.js +0 -1
  200. package/dist/web/assets/history-BR28CO2x.js +0 -1
  201. package/dist/web/assets/history-BuXL4ZO8.js +0 -1
  202. package/dist/web/assets/history-CBSq8sT_.js +0 -1
  203. package/dist/web/assets/history-CUFddWVE.js +0 -1
  204. package/dist/web/assets/history-Cpw0AAmb.js +0 -1
  205. package/dist/web/assets/history-DXLLakuK.js +0 -1
  206. package/dist/web/assets/history-DpSejrKr.js +0 -1
  207. package/dist/web/assets/index-C5_JoNeq.css +0 -2
  208. package/dist/web/assets/index-Cic2D9gD.js +0 -14
  209. package/dist/web/assets/plus-BW1bFnsm.js +0 -1
  210. package/dist/web/assets/realtime-C6pi6J5c.js +0 -1
  211. package/dist/web/assets/rotate-ccw-lEgEs1OH.js +0 -1
  212. package/dist/web/assets/session-D4tJu2uV.js +0 -1
  213. package/dist/web/assets/settings-CZ5suLqg.js +0 -1
  214. package/dist/web/assets/settings-CcMXMgCo.js +0 -1
  215. package/dist/web/assets/settings-D88yFCM6.js +0 -1
  216. package/dist/web/assets/settings-DK2eMfka.js +0 -1
  217. package/dist/web/assets/settings-DmB3vkQI.js +0 -1
  218. package/dist/web/assets/settings-DroVpY4u.js +0 -1
  219. package/dist/web/assets/settings-XBdi63iw.js +0 -1
  220. package/dist/web/assets/shell--RN8OuYs.js +0 -1
  221. package/dist/web/assets/shell-Bhcgh15N.js +0 -1
  222. package/dist/web/assets/shell-BlFKTzFJ.js +0 -1
  223. package/dist/web/assets/shell-CVGGeBa9.js +0 -1
  224. package/dist/web/assets/shell-DOWo5KgD.js +0 -1
  225. package/dist/web/assets/shell-dLPGAa5r.js +0 -1
  226. package/dist/web/assets/tag-QzCcxSZT.js +0 -1
  227. package/dist/web/assets/trash-6g8wBk0g.js +0 -1
  228. package/dist/web/assets/trash-BJO-DupK.js +0 -1
  229. package/dist/web/assets/trash-BQQD171k.js +0 -1
  230. package/dist/web/assets/trash-Bxu4b7lw.js +0 -1
  231. package/dist/web/assets/trash-DFqgqLEp.js +0 -1
  232. package/dist/web/assets/trash-lAGOyPXd.js +0 -1
  233. package/dist/web/assets/trash-mj787YHq.js +0 -1
  234. package/dist/web/assets/trash-pWFmQnYh.js +0 -1
  235. package/dist/web/assets/vault-BAR96ObL.js +0 -7
  236. package/dist/web/assets/vault-BO3aMEV1.js +0 -7
  237. package/dist/web/assets/vault-BsPmxozG.js +0 -7
  238. package/dist/web/assets/vault-CDLe0b9o.js +0 -7
  239. package/dist/web/assets/vault-CTJTioNK.js +0 -7
  240. package/dist/web/assets/vault-Chnxpkuh.js +0 -7
  241. package/dist/web/assets/vault-Y3hqfCEF.js +0 -7
  242. package/dist/web/assets/workspace-BC7Gkm-H.js +0 -1
@@ -8632,8 +8632,8 @@ function nullish(input2) {
8632
8632
  __name(nullish, "nullish");
8633
8633
  function cleanRegex(source) {
8634
8634
  const start = source.startsWith("^") ? 1 : 0;
8635
- const end = source.endsWith("$") ? source.length - 1 : source.length;
8636
- return source.slice(start, end);
8635
+ const end2 = source.endsWith("$") ? source.length - 1 : source.length;
8636
+ return source.slice(start, end2);
8637
8637
  }
8638
8638
  __name(cleanRegex, "cleanRegex");
8639
8639
  function floatSafeRemainder(val, step) {
@@ -11139,17 +11139,17 @@ var $ZodCreditCard = /* @__PURE__ */ $constructor("$ZodCreditCard", (inst, def)
11139
11139
  };
11140
11140
  });
11141
11141
  function isIso7064Mod97(iban3) {
11142
- let remainder = 0;
11142
+ let remainder2 = 0;
11143
11143
  const len = iban3.length;
11144
11144
  for (let i2 = 4; i2 < len; i2++) {
11145
11145
  const code = iban3.charCodeAt(i2);
11146
- remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;
11146
+ remainder2 = (code >= 65 ? remainder2 * 100 + (code - 55) : remainder2 * 10 + (code - 48)) % 97;
11147
11147
  }
11148
11148
  for (let i2 = 0; i2 < 4; i2++) {
11149
11149
  const code = iban3.charCodeAt(i2);
11150
- remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;
11150
+ remainder2 = (code >= 65 ? remainder2 * 100 + (code - 55) : remainder2 * 10 + (code - 48)) % 97;
11151
11151
  }
11152
- return remainder === 1;
11152
+ return remainder2 === 1;
11153
11153
  }
11154
11154
  __name(isIso7064Mod97, "isIso7064Mod97");
11155
11155
  function isValidIBAN(input2) {
@@ -21497,8 +21497,8 @@ function generateMultipleOfCheck(doc, ctx, def, accessor) {
21497
21497
  throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");
21498
21498
  doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`);
21499
21499
  } else {
21500
- const remainder = addConstant(ctx, floatSafeRemainder);
21501
- doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`);
21500
+ const remainder2 = addConstant(ctx, floatSafeRemainder);
21501
+ doc.write(`if (${remainder2}(${accessor}, ${numericOperand(def.value, "multiple_of")}) !== 0) return INVALID;`);
21502
21502
  }
21503
21503
  }
21504
21504
  __name(generateMultipleOfCheck, "generateMultipleOfCheck");
@@ -23871,13 +23871,13 @@ function _promise(Class2, innerType) {
23871
23871
  __name(_promise, "_promise");
23872
23872
  // @__NO_SIDE_EFFECTS__
23873
23873
  function _custom(Class2, fn, _params) {
23874
- const norm = normalizeParams(_params);
23875
- norm.abort ?? (norm.abort = true);
23874
+ const norm2 = normalizeParams(_params);
23875
+ norm2.abort ?? (norm2.abort = true);
23876
23876
  const schema = new Class2({
23877
23877
  type: "custom",
23878
23878
  check: "custom",
23879
23879
  fn,
23880
- ...norm
23880
+ ...norm2
23881
23881
  });
23882
23882
  return schema;
23883
23883
  }
@@ -28290,8 +28290,9 @@ var SCOPES = ["tasks:read", "tasks:write", "docs:read", "docs:write", "organize"
28290
28290
 
28291
28291
  // ../../packages/shared/src/schemas.ts
28292
28292
  var id = external_exports.uuid();
28293
- var VISIBLE = /[^\s\p{Cc}\p{Cf}\p{Z}\u115F\u1160\u3164\uFFA0\u2800]/u;
28293
+ var VISIBLE = /[^\s\p{Cc}\p{Cf}\p{Z}\p{M}\u115F\u1160\u3164\uFFA0\u2800]/u;
28294
28294
  var name = /* @__PURE__ */ __name((max2 = 120) => external_exports.string().overwrite((value) => value.replace(/\p{Cc}+/gu, " ")).trim().min(1, { message: "Required", abort: true }).max(max2).refine((value) => VISIBLE.test(value), "Required"), "name");
28295
+ var optionalName = /* @__PURE__ */ __name((max2) => external_exports.string().overwrite((value) => value.replace(/\p{Cc}+/gu, " ")).trim().overwrite((value) => VISIBLE.test(value) ? value : "").max(max2), "optionalName");
28295
28296
  var color = external_exports.enum(PALETTE);
28296
28297
  var index = external_exports.number().int().min(0).max(1e5);
28297
28298
  var DUE_YEARS = { min: 1900, max: 2199 };
@@ -28314,6 +28315,17 @@ var dueAt = external_exports.string().transform((value, ctx) => {
28314
28315
  return external_exports.NEVER;
28315
28316
  });
28316
28317
  var MAX_MARKDOWN = 2e5;
28318
+ function characters(text2) {
28319
+ let count2 = text2.length;
28320
+ for (let i2 = 0; i2 < text2.length - 1; i2++) {
28321
+ if ((text2.charCodeAt(i2) & 64512) === 55296 && (text2.charCodeAt(i2 + 1) & 64512) === 56320) {
28322
+ count2--;
28323
+ i2++;
28324
+ }
28325
+ }
28326
+ return count2;
28327
+ }
28328
+ __name(characters, "characters");
28317
28329
  var secret = external_exports.string().trim().min(1, "Required").max(256);
28318
28330
  var claimInput = external_exports.object({ setupCode: secret, name: name(80), locale: external_exports.enum(LOCALES).optional() });
28319
28331
  var unlockInput = external_exports.object({ accessKey: secret });
@@ -28323,7 +28335,7 @@ var rotateAccessKeyInput = external_exports.object({ currentAccessKey: secret })
28323
28335
  var confirmAccessKeyInput = external_exports.object({ accessKey: secret });
28324
28336
  var uninstallInput = external_exports.object({ accessKey: secret, deleteBackups: external_exports.boolean() });
28325
28337
  var installerUninstallInput = external_exports.object({ token: external_exports.string().min(40).max(200), deleteBackups: external_exports.boolean().default(false) });
28326
- var restoreBackupInput = external_exports.object({ accessKey: secret });
28338
+ var restoreBackupInput = external_exports.object({ accessKey: secret, leaveOut: external_exports.array(external_exports.string().max(200)).max(1e5).default([]) });
28327
28339
  var updateAccountInput = external_exports.object({
28328
28340
  name: name(80).optional(),
28329
28341
  theme: external_exports.enum(["system", "light", "dark"]).optional(),
@@ -28348,8 +28360,8 @@ var boardCreateInput = external_exports.object({
28348
28360
  var boardUpdateInput = external_exports.object({ name: name(80) });
28349
28361
  var columnCreateInput = external_exports.object({ name: name(60), index: index.optional() });
28350
28362
  var columnUpdateInput = external_exports.object({ name: name(60).optional(), index: index.optional() });
28351
- var labelCreateInput = external_exports.object({ name: external_exports.string().trim().max(40).default(""), color });
28352
- var labelUpdateInput = external_exports.object({ name: external_exports.string().trim().max(40).optional(), color: color.optional() });
28363
+ var labelCreateInput = external_exports.object({ name: optionalName(40).default(""), color });
28364
+ var labelUpdateInput = external_exports.object({ name: optionalName(40).optional(), color: color.optional() });
28353
28365
  var cardCreateInput = external_exports.object({
28354
28366
  title: name(300),
28355
28367
  description: external_exports.string().max(MAX_MARKDOWN).optional(),
@@ -28376,13 +28388,13 @@ var checklistItemUpdateInput = external_exports.object({
28376
28388
  });
28377
28389
  var linkPageInput = external_exports.object({ pageId: id });
28378
28390
  var pageCreateInput = external_exports.object({
28379
- title: external_exports.string().trim().max(200).default(""),
28391
+ title: optionalName(200).default(""),
28380
28392
  icon: external_exports.string().max(16).nullable().optional(),
28381
28393
  parentId: id.nullable().optional(),
28382
28394
  content: external_exports.string().max(MAX_MARKDOWN).default("")
28383
28395
  });
28384
28396
  var pageUpdateInput = external_exports.object({
28385
- title: external_exports.string().trim().max(200).optional(),
28397
+ title: optionalName(200).optional(),
28386
28398
  icon: external_exports.string().max(16).nullable().optional(),
28387
28399
  content: external_exports.string().max(MAX_MARKDOWN).optional(),
28388
28400
  /** Required when `content` is sent: optimistic concurrency guard. */
@@ -28415,7 +28427,7 @@ var vaultKeysInput = external_exports.object({
28415
28427
  });
28416
28428
  var keyVersion = external_exports.number().int().min(0).max(2147483647);
28417
28429
  var vaultRekeyInput = vaultKeysInput.extend({ keyVersion });
28418
- var vaultItemInput = external_exports.object({ data: envelopeSchema, keyVersion });
28430
+ var vaultItemInput = external_exports.object({ data: envelopeSchema, keyVersion, baseUpdatedAt: external_exports.string().datetime().nullable().optional() });
28419
28431
  var vaultSettingsInput = external_exports.object({ autoLockMinutes: external_exports.union([external_exports.literal(1), external_exports.literal(5), external_exports.literal(15), external_exports.literal(30), external_exports.literal(60)]) });
28420
28432
  var oauthRequestInput = external_exports.object({ params: external_exports.record(external_exports.string(), external_exports.string().max(4e3)) });
28421
28433
  var oauthDecisionInput = oauthRequestInput.extend({
@@ -28428,10 +28440,35 @@ var oauthDecisionInput = oauthRequestInput.extend({
28428
28440
  var undoInput = external_exports.object({
28429
28441
  ids: external_exports.array(id).min(1).max(500).optional(),
28430
28442
  since: id.optional(),
28443
+ /** With `since`: only the changes older than this one, to go on after a batch that ended there. */
28444
+ until: id.optional(),
28431
28445
  conflicts: external_exports.enum(["ask", "skip", "force"]).default("ask"),
28432
28446
  /** Only say what would happen: nothing is undone. */
28433
28447
  dryRun: external_exports.boolean().default(false)
28434
- }).refine((v) => v.ids === void 0 !== (v.since === void 0), { message: "Send either ids or since" });
28448
+ }).refine((v) => v.ids === void 0 !== (v.since === void 0), { message: "Send either ids or since" }).refine((v) => v.until === void 0 || v.since !== void 0, { message: "until goes with since" });
28449
+ var UUID2 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
28450
+ var TRASH_KEY = new RegExp(`^(?:(?:project|board|column|card|page|attachment|label|checklist|checklist_item):${UUID2}|link:${UUID2}:${UUID2})$`, "i");
28451
+ var trashKey = external_exports.string().regex(TRASH_KEY, "Not a trash key");
28452
+ var trashRestoreInput = external_exports.object({
28453
+ key: trashKey,
28454
+ exclude: external_exports.array(trashKey).max(1e4).default([]),
28455
+ to: external_exports.discriminatedUnion("kind", [
28456
+ external_exports.object({ kind: external_exports.literal("original") }),
28457
+ external_exports.object({ kind: external_exports.literal("recreate") }),
28458
+ external_exports.object({ kind: external_exports.literal("other"), parent: external_exports.object({ kind: external_exports.enum(["project", "board", "column", "card", "page", "checklist"]), id }) })
28459
+ ]).optional(),
28460
+ names: external_exports.record(trashKey, name(300)).default({}),
28461
+ keepNames: external_exports.array(trashKey).max(1e4).default([]),
28462
+ include: external_exports.array(trashKey).max(1e3).default([]),
28463
+ dryRun: external_exports.boolean().default(false)
28464
+ });
28465
+ var trashPurgeInput = external_exports.object({ key: trashKey, dryRun: external_exports.boolean().default(false) });
28466
+ var MAX_TRASH_BATCH = 100;
28467
+ var trashRestoreManyInput = external_exports.object({
28468
+ items: external_exports.array(trashRestoreInput.omit({ dryRun: true })).min(1).max(MAX_TRASH_BATCH),
28469
+ dryRun: external_exports.boolean().default(false)
28470
+ });
28471
+ var trashPurgeManyInput = external_exports.object({ keys: external_exports.array(trashKey).min(1).max(MAX_TRASH_BATCH), dryRun: external_exports.boolean().default(false) });
28435
28472
 
28436
28473
  // ../../packages/shared/src/types.ts
28437
28474
  var INSTALL_KINDS = ["cli", "button", "docker", "source", "cloudflare"];
@@ -28487,10 +28524,67 @@ var HISTORY_DAYS = 30;
28487
28524
 
28488
28525
  // ../../packages/shared/src/uploads.ts
28489
28526
  var UPLOAD_NAME_HEADER = "X-File-Name";
28527
+ var BIDI_CONTROLS = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
28528
+ var withoutBidiControls = /* @__PURE__ */ __name((name2) => name2.replace(BIDI_CONTROLS, ""), "withoutBidiControls");
28529
+
28530
+ // src/lib/upload-limit.ts
28531
+ var DEFAULT_MAX_UPLOAD_MB = 20;
28532
+ function maxUploadBytes(value) {
28533
+ const text2 = value?.trim() ?? "";
28534
+ if (text2 === "") return DEFAULT_MAX_UPLOAD_MB * 1024 * 1024;
28535
+ const megabytes = Number(text2);
28536
+ return Number.isFinite(megabytes) && megabytes > 0 ? Math.round(megabytes * 1024 * 1024) : null;
28537
+ }
28538
+ __name(maxUploadBytes, "maxUploadBytes");
28539
+ var warned = false;
28540
+ function workerMaxUploadBytes(value) {
28541
+ const bytes = maxUploadBytes(value);
28542
+ if (bytes !== null) return bytes;
28543
+ if (!warned) console.warn(`MAX_UPLOAD_MB must be a number of megabytes greater than 0, such as 20 (got "${value}"): using ${DEFAULT_MAX_UPLOAD_MB}`);
28544
+ warned = true;
28545
+ return DEFAULT_MAX_UPLOAD_MB * 1024 * 1024;
28546
+ }
28547
+ __name(workerMaxUploadBytes, "workerMaxUploadBytes");
28548
+
28549
+ // src/lib/app-urls.ts
28550
+ var ConfigError = class extends Error {
28551
+ static {
28552
+ __name(this, "ConfigError");
28553
+ }
28554
+ };
28555
+ function parseAppUrls(value) {
28556
+ const urls = value.split(",").map((u) => u.trim()).filter(Boolean);
28557
+ if (urls.length === 0) throw new ConfigError("APP_URL is empty. Set it to the address people open Orqevio at, such as https://orqevio.example.com");
28558
+ return urls.map((u) => {
28559
+ const url2 = URL.canParse(u) ? new URL(u) : null;
28560
+ if (!url2 || url2.protocol !== "http:" && url2.protocol !== "https:") {
28561
+ throw new ConfigError(`APP_URL must be full addresses starting with https:// or http://, such as https://orqevio.example.com (got "${u}")`);
28562
+ }
28563
+ return url2.origin;
28564
+ });
28565
+ }
28566
+ __name(parseAppUrls, "parseAppUrls");
28567
+
28568
+ // src/worker/settings.ts
28569
+ function workerAppUrls(value) {
28570
+ return value?.split(",").some((url2) => url2.trim()) ? parseAppUrls(value) : [];
28571
+ }
28572
+ __name(workerAppUrls, "workerAppUrls");
28573
+ function appUrlProblem(value) {
28574
+ try {
28575
+ workerAppUrls(value);
28576
+ return null;
28577
+ } catch (error62) {
28578
+ if (error62 instanceof ConfigError) return error62.message;
28579
+ throw error62;
28580
+ }
28581
+ }
28582
+ __name(appUrlProblem, "appUrlProblem");
28490
28583
 
28491
28584
  // src/worker/env.ts
28585
+ var workerConfigProblem = /* @__PURE__ */ __name((bindings) => appUrlProblem(bindings.APP_URL), "workerConfigProblem");
28492
28586
  function workerEnv(bindings) {
28493
- const appUrls = (bindings.APP_URL ?? "").split(",").map((url2) => url2.trim()).filter(Boolean).map((url2) => new URL(url2).origin);
28587
+ const appUrls = workerAppUrls(bindings.APP_URL);
28494
28588
  return {
28495
28589
  nodeEnv: "production",
28496
28590
  port: 0,
@@ -28502,7 +28596,7 @@ function workerEnv(bindings) {
28502
28596
  migrationsDir: "",
28503
28597
  trustProxy: 0,
28504
28598
  secureCookies: true,
28505
- maxUploadBytes: Number(bindings.MAX_UPLOAD_MB ?? 20) * 1024 * 1024,
28599
+ maxUploadBytes: workerMaxUploadBytes(bindings.MAX_UPLOAD_MB),
28506
28600
  setupCode: bindings.SETUP_CODE?.trim() || null,
28507
28601
  install: installKind(bindings.ORQEVIO_INSTALL, "cloudflare"),
28508
28602
  copyName: bindings.ORQEVIO_COPY_NAME?.trim() || null,
@@ -28515,6 +28609,28 @@ function workerEnv(bindings) {
28515
28609
  }
28516
28610
  __name(workerEnv, "workerEnv");
28517
28611
 
28612
+ // src/worker/misconfigured.ts
28613
+ function misconfigured(request, problem) {
28614
+ const fix = "On Cloudflare APP_URL is optional: remove it to use the address each visit comes from, or set it to full addresses separated by commas.";
28615
+ const { pathname } = new URL(request.url);
28616
+ const headers = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };
28617
+ if (/^\/(?:api\/|mcp$|oauth\/|\.well-known\/)/.test(pathname)) {
28618
+ return Response.json({ error: { code: "misconfigured", message: `${problem} ${fix}` } }, { status: 503, headers });
28619
+ }
28620
+ if (pathname === "/healthz") return new Response(`misconfigured: ${problem}
28621
+ `, { status: 503, headers: { ...headers, "Content-Type": "text/plain; charset=utf-8" } });
28622
+ const escape2 = /* @__PURE__ */ __name((text2) => text2.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`), "escape");
28623
+ const page = `<!doctype html>
28624
+ <html lang="en">
28625
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Orqevio can't start</title>
28626
+ <style>body{font:16px/1.5 system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;color:#1f1d1a;background:#faf9f6}h1{font-size:1.5rem}code{background:#efede8;padding:.1em .3em;border-radius:4px}</style></head>
28627
+ <body><h1>Orqevio can't start</h1><p>${escape2(problem)}</p><p>${escape2(fix)}</p></body>
28628
+ </html>
28629
+ `;
28630
+ return new Response(page, { status: 503, headers: { ...headers, "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'" } });
28631
+ }
28632
+ __name(misconfigured, "misconfigured");
28633
+
28518
28634
  // src/worker/copy.ts
28519
28635
  import { DurableObject } from "cloudflare:workers";
28520
28636
 
@@ -28866,8 +28982,8 @@ var ForeignKey = class {
28866
28982
  onDelete;
28867
28983
  getName() {
28868
28984
  const { name: name2, columns: columns2, foreignColumns } = this.reference();
28869
- const columnNames = columns2.map((column) => column.name);
28870
- const foreignColumnNames = foreignColumns.map((column) => column.name);
28985
+ const columnNames = columns2.map((column2) => column2.name);
28986
+ const foreignColumnNames = foreignColumns.map((column2) => column2.name);
28871
28987
  const chunks = [
28872
28988
  this.table[TableName],
28873
28989
  ...columnNames,
@@ -28932,7 +29048,7 @@ var UniqueConstraint = class {
28932
29048
  constructor(table, columns2, nullsNotDistinct, name2) {
28933
29049
  this.table = table;
28934
29050
  this.columns = columns2;
28935
- this.name = name2 ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
29051
+ this.name = name2 ?? uniqueKeyName(this.table, this.columns.map((column2) => column2.name));
28936
29052
  this.nullsNotDistinct = nullsNotDistinct;
28937
29053
  }
28938
29054
  static [entityKind] = "PgUniqueConstraint";
@@ -29053,13 +29169,13 @@ var PgColumnBuilder = class extends ColumnBuilder {
29053
29169
  return this;
29054
29170
  }
29055
29171
  /** @internal */
29056
- buildForeignKeys(column, table) {
29172
+ buildForeignKeys(column2, table) {
29057
29173
  return this.foreignKeyConfigs.map(({ ref, actions }) => {
29058
29174
  return iife(
29059
29175
  (ref2, actions2) => {
29060
29176
  const builder = new ForeignKeyBuilder(() => {
29061
29177
  const foreignColumn = ref2();
29062
- return { columns: [column], foreignColumns: [foreignColumn] };
29178
+ return { columns: [column2], foreignColumns: [foreignColumn] };
29063
29179
  });
29064
29180
  if (actions2.onUpdate) {
29065
29181
  builder.onUpdate(actions2.onUpdate);
@@ -29974,14 +30090,14 @@ var PrimaryKey = class {
29974
30090
  columns;
29975
30091
  name;
29976
30092
  getName() {
29977
- return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
30093
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column2) => column2.name).join("_")}_pk`;
29978
30094
  }
29979
30095
  };
29980
30096
 
29981
30097
  // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261112.1_@types+better-sqlite3@9.6.0_@_b16c6a9aefdb6a18eed9dad740d7653e/node_modules/drizzle-orm/sql/expressions/conditions.js
29982
- function bindIfParam(value, column) {
29983
- if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
29984
- return new Param(value, column);
30098
+ function bindIfParam(value, column2) {
30099
+ if (isDriverValueEncoder(column2) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
30100
+ return new Param(value, column2);
29985
30101
  }
29986
30102
  return value;
29987
30103
  }
@@ -30042,24 +30158,24 @@ var lt = /* @__PURE__ */ __name((left, right) => {
30042
30158
  var lte = /* @__PURE__ */ __name((left, right) => {
30043
30159
  return sql`${left} <= ${bindIfParam(right, left)}`;
30044
30160
  }, "lte");
30045
- function inArray(column, values) {
30161
+ function inArray(column2, values) {
30046
30162
  if (Array.isArray(values)) {
30047
30163
  if (values.length === 0) {
30048
30164
  return sql`false`;
30049
30165
  }
30050
- return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
30166
+ return sql`${column2} in ${values.map((v) => bindIfParam(v, column2))}`;
30051
30167
  }
30052
- return sql`${column} in ${bindIfParam(values, column)}`;
30168
+ return sql`${column2} in ${bindIfParam(values, column2)}`;
30053
30169
  }
30054
30170
  __name(inArray, "inArray");
30055
- function notInArray(column, values) {
30171
+ function notInArray(column2, values) {
30056
30172
  if (Array.isArray(values)) {
30057
30173
  if (values.length === 0) {
30058
30174
  return sql`true`;
30059
30175
  }
30060
- return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
30176
+ return sql`${column2} not in ${values.map((v) => bindIfParam(v, column2))}`;
30061
30177
  }
30062
- return sql`${column} not in ${bindIfParam(values, column)}`;
30178
+ return sql`${column2} not in ${bindIfParam(values, column2)}`;
30063
30179
  }
30064
30180
  __name(notInArray, "notInArray");
30065
30181
  function isNull(value) {
@@ -30078,44 +30194,44 @@ function notExists(subquery) {
30078
30194
  return sql`not exists ${subquery}`;
30079
30195
  }
30080
30196
  __name(notExists, "notExists");
30081
- function between(column, min, max2) {
30082
- return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(
30197
+ function between(column2, min, max2) {
30198
+ return sql`${column2} between ${bindIfParam(min, column2)} and ${bindIfParam(
30083
30199
  max2,
30084
- column
30200
+ column2
30085
30201
  )}`;
30086
30202
  }
30087
30203
  __name(between, "between");
30088
- function notBetween(column, min, max2) {
30089
- return sql`${column} not between ${bindIfParam(
30204
+ function notBetween(column2, min, max2) {
30205
+ return sql`${column2} not between ${bindIfParam(
30090
30206
  min,
30091
- column
30092
- )} and ${bindIfParam(max2, column)}`;
30207
+ column2
30208
+ )} and ${bindIfParam(max2, column2)}`;
30093
30209
  }
30094
30210
  __name(notBetween, "notBetween");
30095
- function like(column, value) {
30096
- return sql`${column} like ${value}`;
30211
+ function like(column2, value) {
30212
+ return sql`${column2} like ${value}`;
30097
30213
  }
30098
30214
  __name(like, "like");
30099
- function notLike(column, value) {
30100
- return sql`${column} not like ${value}`;
30215
+ function notLike(column2, value) {
30216
+ return sql`${column2} not like ${value}`;
30101
30217
  }
30102
30218
  __name(notLike, "notLike");
30103
- function ilike(column, value) {
30104
- return sql`${column} ilike ${value}`;
30219
+ function ilike(column2, value) {
30220
+ return sql`${column2} ilike ${value}`;
30105
30221
  }
30106
30222
  __name(ilike, "ilike");
30107
- function notIlike(column, value) {
30108
- return sql`${column} not ilike ${value}`;
30223
+ function notIlike(column2, value) {
30224
+ return sql`${column2} not ilike ${value}`;
30109
30225
  }
30110
30226
  __name(notIlike, "notIlike");
30111
30227
 
30112
30228
  // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261112.1_@types+better-sqlite3@9.6.0_@_b16c6a9aefdb6a18eed9dad740d7653e/node_modules/drizzle-orm/sql/expressions/select.js
30113
- function asc(column) {
30114
- return sql`${column} asc`;
30229
+ function asc(column2) {
30230
+ return sql`${column2} asc`;
30115
30231
  }
30116
30232
  __name(asc, "asc");
30117
- function desc(column) {
30118
- return sql`${column} desc`;
30233
+ function desc(column2) {
30234
+ return sql`${column2} desc`;
30119
30235
  }
30120
30236
  __name(desc, "desc");
30121
30237
 
@@ -30239,11 +30355,11 @@ function extractTablesRelationalConfig(schema, configHelpers) {
30239
30355
  relations: bufferedRelations?.relations ?? {},
30240
30356
  primaryKey: bufferedRelations?.primaryKey ?? []
30241
30357
  };
30242
- for (const column of Object.values(
30358
+ for (const column2 of Object.values(
30243
30359
  value[Table.Symbol.Columns]
30244
30360
  )) {
30245
- if (column.primary) {
30246
- tablesConfig[key].primaryKey.push(column);
30361
+ if (column2.primary) {
30362
+ tablesConfig[key].primaryKey.push(column2);
30247
30363
  }
30248
30364
  }
30249
30365
  const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
@@ -30482,10 +30598,10 @@ function aliasedTable(table, tableAlias) {
30482
30598
  return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
30483
30599
  }
30484
30600
  __name(aliasedTable, "aliasedTable");
30485
- function aliasedTableColumn(column, tableAlias) {
30601
+ function aliasedTableColumn(column2, tableAlias) {
30486
30602
  return new Proxy(
30487
- column,
30488
- new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false)))
30603
+ column2,
30604
+ new ColumnAliasProxyHandler(new Proxy(column2.table, new TableAliasProxyHandler(tableAlias, false)))
30489
30605
  );
30490
30606
  }
30491
30607
  __name(aliasedTableColumn, "aliasedTableColumn");
@@ -30658,8 +30774,8 @@ var ForeignKey2 = class {
30658
30774
  onDelete;
30659
30775
  getName() {
30660
30776
  const { name: name2, columns: columns2, foreignColumns } = this.reference();
30661
- const columnNames = columns2.map((column) => column.name);
30662
- const foreignColumnNames = foreignColumns.map((column) => column.name);
30777
+ const columnNames = columns2.map((column2) => column2.name);
30778
+ const foreignColumnNames = foreignColumns.map((column2) => column2.name);
30663
30779
  const chunks = [
30664
30780
  this.table[TableName],
30665
30781
  ...columnNames,
@@ -30712,7 +30828,7 @@ var UniqueConstraint2 = class {
30712
30828
  constructor(table, columns2, name2) {
30713
30829
  this.table = table;
30714
30830
  this.columns = columns2;
30715
- this.name = name2 ?? uniqueKeyName2(this.table, this.columns.map((column) => column.name));
30831
+ this.name = name2 ?? uniqueKeyName2(this.table, this.columns.map((column2) => column2.name));
30716
30832
  }
30717
30833
  static [entityKind] = "SQLiteUniqueConstraint";
30718
30834
  columns;
@@ -30747,12 +30863,12 @@ var SQLiteColumnBuilder = class extends ColumnBuilder {
30747
30863
  return this;
30748
30864
  }
30749
30865
  /** @internal */
30750
- buildForeignKeys(column, table) {
30866
+ buildForeignKeys(column2, table) {
30751
30867
  return this.foreignKeyConfigs.map(({ ref, actions }) => {
30752
30868
  return ((ref2, actions2) => {
30753
30869
  const builder = new ForeignKeyBuilder2(() => {
30754
30870
  const foreignColumn = ref2();
30755
- return { columns: [column], foreignColumns: [foreignColumn] };
30871
+ return { columns: [column2], foreignColumns: [foreignColumn] };
30756
30872
  });
30757
30873
  if (actions2.onUpdate) {
30758
30874
  builder.onUpdate(actions2.onUpdate);
@@ -31309,9 +31425,9 @@ function sqliteTableBase(name2, columns2, extraConfig, schema, baseName = name2)
31309
31425
  Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
31310
31426
  const colBuilder = colBuilderBase;
31311
31427
  colBuilder.setName(name22);
31312
- const column = colBuilder.build(rawTable);
31313
- rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable));
31314
- return [name22, column];
31428
+ const column2 = colBuilder.build(rawTable);
31429
+ rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column2, rawTable));
31430
+ return [name22, column2];
31315
31431
  })
31316
31432
  );
31317
31433
  const table = Object.assign(rawTable, builtColumns);
@@ -31459,7 +31575,7 @@ var PrimaryKey2 = class {
31459
31575
  columns;
31460
31576
  name;
31461
31577
  getName() {
31462
- return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
31578
+ return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column2) => column2.name).join("_")}_pk`;
31463
31579
  }
31464
31580
  };
31465
31581
 
@@ -31662,13 +31778,13 @@ var CasingCache = class {
31662
31778
  constructor(casing) {
31663
31779
  this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
31664
31780
  }
31665
- getColumnCasing(column) {
31666
- if (!column.keyAsName) return column.name;
31667
- const schema = column.table[Table.Symbol.Schema] ?? "public";
31668
- const tableName = column.table[Table.Symbol.OriginalName];
31669
- const key = `${schema}.${tableName}.${column.name}`;
31781
+ getColumnCasing(column2) {
31782
+ if (!column2.keyAsName) return column2.name;
31783
+ const schema = column2.table[Table.Symbol.Schema] ?? "public";
31784
+ const tableName = column2.table[Table.Symbol.OriginalName];
31785
+ const key = `${schema}.${tableName}.${column2.name}`;
31670
31786
  if (!this.cache[key]) {
31671
- this.cacheTable(column.table);
31787
+ this.cacheTable(column2.table);
31672
31788
  }
31673
31789
  return this.cache[key];
31674
31790
  }
@@ -31677,9 +31793,9 @@ var CasingCache = class {
31677
31793
  const tableName = table[Table.Symbol.OriginalName];
31678
31794
  const tableKey = `${schema}.${tableName}`;
31679
31795
  if (!this.cachedTables[tableKey]) {
31680
- for (const column of Object.values(table[Table.Symbol.Columns])) {
31681
- const columnKey = `${tableKey}.${column.name}`;
31682
- this.cache[columnKey] = this.convert(column.name);
31796
+ for (const column2 of Object.values(table[Table.Symbol.Columns])) {
31797
+ const columnKey = `${tableKey}.${column2.name}`;
31798
+ this.cache[columnKey] = this.convert(column2.name);
31683
31799
  }
31684
31800
  this.cachedTables[tableKey] = true;
31685
31801
  }
@@ -32071,7 +32187,7 @@ var SQLiteDialect = class {
32071
32187
  const colEntries = Object.entries(columns2).filter(
32072
32188
  ([_, col]) => !col.shouldDisableInsert()
32073
32189
  );
32074
- const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
32190
+ const insertOrder = colEntries.map(([, column2]) => sql.identifier(this.casing.getColumnCasing(column2)));
32075
32191
  if (select) {
32076
32192
  const select2 = valuesOrSelect;
32077
32193
  if (is(select2, SQL)) {
@@ -32184,8 +32300,8 @@ var SQLiteDialect = class {
32184
32300
  selectedColumns = Object.keys(tableConfig.columns);
32185
32301
  }
32186
32302
  for (const field of selectedColumns) {
32187
- const column = tableConfig.columns[field];
32188
- fieldsSelection.push({ tsKey: field, value: column });
32303
+ const column2 = tableConfig.columns[field];
32304
+ fieldsSelection.push({ tsKey: field, value: column2 });
32189
32305
  }
32190
32306
  let selectedRelations = [];
32191
32307
  if (config2.with) {
@@ -34702,8 +34818,8 @@ var getPath = /* @__PURE__ */ __name((request) => {
34702
34818
  if (charCode === 37) {
34703
34819
  const queryIndex = url2.indexOf("?", i2);
34704
34820
  const hashIndex = url2.indexOf("#", i2);
34705
- const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
34706
- const path2 = url2.slice(start, end);
34821
+ const end2 = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
34822
+ const path2 = url2.slice(start, end2);
34707
34823
  return tryDecodeURI(path2.includes("%25") ? path2.replace(/%25/g, "%2525") : path2);
34708
34824
  } else if (charCode === 63 || charCode === 35) break;
34709
34825
  }
@@ -35559,8 +35675,8 @@ var getPathPrefixLength = /* @__PURE__ */ __name((c, pathPrefix, routePath) => {
35559
35675
  const value = matchResult.length === 2 ? matchResult[1][matchResult[0][c.req.routeIndex][1][pattern[1]]] : matchResult[0][c.req.routeIndex][1][pattern[1]];
35560
35676
  length += value.length + 1;
35561
35677
  } else if (pattern || part.endsWith("*")) {
35562
- const end = path2.indexOf("/", length + 1);
35563
- length = end === -1 ? path2.length : end;
35678
+ const end2 = path2.indexOf("/", length + 1);
35679
+ length = end2 === -1 ? path2.length : end2;
35564
35680
  } else length += part.length + 1;
35565
35681
  }
35566
35682
  return length;
@@ -37017,6 +37133,7 @@ var TokenService = class {
37017
37133
  await this.access.workspace(actor, data.workspaceId);
37018
37134
  const token = `${TOKEN_PREFIX}${randomToken(32)}`;
37019
37135
  const scopes = consistentScopes(data.scopes);
37136
+ if (scopes.length === 0) throw badRequest('Allow at least read access to tasks or docs: "organize" alone gives none');
37020
37137
  const [row] = await this.deps.db.insert(apiTokens).values({
37021
37138
  userId: actor.userId,
37022
37139
  workspaceId: data.workspaceId,
@@ -37209,7 +37326,9 @@ var registrationInput = external_exports.object({
37209
37326
  grant_types: external_exports.array(external_exports.string()).optional(),
37210
37327
  response_types: external_exports.array(external_exports.string()).optional()
37211
37328
  });
37212
- function registrationProblem(field) {
37329
+ function registrationProblem(path2 = []) {
37330
+ const [field] = path2;
37331
+ if (field === "redirect_uris" && path2.length > 1) return "Each address in redirect_uris must be text of at most 500 characters";
37213
37332
  switch (field) {
37214
37333
  case "client_name":
37215
37334
  return "client_name must be text of at most 200 characters";
@@ -37247,7 +37366,7 @@ var OAuthService = class {
37247
37366
  /** Dynamic Client Registration (RFC 7591). Nothing is stored: the client_id is signed. */
37248
37367
  async register(input2) {
37249
37368
  const result = registrationInput.safeParse(input2);
37250
- if (!result.success) throw new OAuthError("invalid_client_metadata", registrationProblem(result.error.issues[0]?.path[0]));
37369
+ if (!result.success) throw new OAuthError("invalid_client_metadata", registrationProblem(result.error.issues[0]?.path));
37251
37370
  const data = result.data;
37252
37371
  const bad = data.redirect_uris.find((uri) => !validRedirectUri(uri));
37253
37372
  if (bad) throw new OAuthError("invalid_redirect_uri", `Not an allowed redirect URI: ${bad.slice(0, 100)}`);
@@ -37534,18 +37653,18 @@ var relaxedCookieNameRegEx = /^[!#-:<>-[\]-~]+$/;
37534
37653
  var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
37535
37654
  var trimCookieWhitespace = /* @__PURE__ */ __name((value) => {
37536
37655
  let start = 0;
37537
- let end = value.length;
37538
- while (start < end) {
37656
+ let end2 = value.length;
37657
+ while (start < end2) {
37539
37658
  const charCode = value.charCodeAt(start);
37540
37659
  if (charCode !== 32 && charCode !== 9) break;
37541
37660
  start++;
37542
37661
  }
37543
- while (end > start) {
37544
- const charCode = value.charCodeAt(end - 1);
37662
+ while (end2 > start) {
37663
+ const charCode = value.charCodeAt(end2 - 1);
37545
37664
  if (charCode !== 32 && charCode !== 9) break;
37546
- end--;
37665
+ end2--;
37547
37666
  }
37548
- return start === 0 && end === value.length ? value : value.slice(start, end);
37667
+ return start === 0 && end2 === value.length ? value : value.slice(start, end2);
37549
37668
  }, "trimCookieWhitespace");
37550
37669
  var parse4 = /* @__PURE__ */ __name((cookie, name2) => {
37551
37670
  if (name2 && cookie.indexOf(name2) === -1) return {};
@@ -37660,8 +37779,18 @@ function hasScope(actor, scope) {
37660
37779
  }
37661
37780
  __name(hasScope, "hasScope");
37662
37781
 
37782
+ // src/db/groups.ts
37783
+ var MAX_PARAMETERS = 100;
37784
+ function inGroups(table, rows) {
37785
+ const size = Math.max(1, Math.floor(MAX_PARAMETERS / Object.keys(getTableColumns(table)).length));
37786
+ const groups = [];
37787
+ for (let i2 = 0; i2 < rows.length; i2 += size) groups.push(rows.slice(i2, i2 + size));
37788
+ return groups;
37789
+ }
37790
+ __name(inGroups, "inGroups");
37791
+
37663
37792
  // src/db/in-list.ts
37664
- var inList = /* @__PURE__ */ __name((column, values) => sql`${column} IN (SELECT value FROM json_each(${JSON.stringify(values)}))`, "inList");
37793
+ var inList = /* @__PURE__ */ __name((column2, values) => sql`${column2} IN (SELECT value FROM json_each(${JSON.stringify(values)}))`, "inList");
37665
37794
 
37666
37795
  // src/services/attachments.ts
37667
37796
  import { randomUUID } from "node:crypto";
@@ -37724,7 +37853,8 @@ __name(exactLength, "exactLength");
37724
37853
  var INLINE_IMAGES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
37725
37854
  var toAttachmentDTO = /* @__PURE__ */ __name((a) => ({
37726
37855
  id: a.id,
37727
- filename: a.filename,
37856
+ // Names stored before 1.2.1 may still hold them.
37857
+ filename: withoutBidiControls(a.filename),
37728
37858
  mimeType: a.mimeType,
37729
37859
  size: a.size,
37730
37860
  url: `/api/attachments/${a.id}`,
@@ -37733,10 +37863,10 @@ var toAttachmentDTO = /* @__PURE__ */ __name((a) => ({
37733
37863
  }), "toAttachmentDTO");
37734
37864
  var MAX_FILENAME = 180;
37735
37865
  function safeFilename(name2) {
37736
- const cleaned = name2.replace(/[\\/\u0000-\u001f\u007f"]/g, "_").trim();
37866
+ const cleaned = withoutBidiControls(name2).replace(/[\\/\u0000-\u001f\u007f"]/g, "_").trim();
37737
37867
  if (cleaned.length <= MAX_FILENAME) return cleaned || "file";
37738
37868
  const ext = /\.[^.\s]{1,16}$/.exec(cleaned)?.[0] ?? "";
37739
- return cleaned.slice(0, MAX_FILENAME - ext.length).trimEnd() + ext;
37869
+ return clip(cleaned, MAX_FILENAME - ext.length).trimEnd() + ext;
37740
37870
  }
37741
37871
  __name(safeFilename, "safeFilename");
37742
37872
  function sniff(bytes, declared) {
@@ -37779,8 +37909,10 @@ var AttachmentService = class {
37779
37909
  */
37780
37910
  /** Uploads still running, which uninstalling waits for (see close). */
37781
37911
  inFlight = /* @__PURE__ */ new Set();
37782
- closed = false;
37912
+ /** Why uploads are refused for now: the copy being uninstalled, or a backup being put back. */
37913
+ closed = null;
37783
37914
  async upload(actor, target, file2) {
37915
+ if (this.closed === "restoring") throw new AppError(409, "restoring", "A backup is being restored: upload the file again in a moment");
37784
37916
  if (this.closed) throw uninstalled();
37785
37917
  const work = this.store(actor, target, file2);
37786
37918
  this.inFlight.add(work);
@@ -37794,12 +37926,12 @@ var AttachmentService = class {
37794
37926
  * Refuses new uploads and waits for the running ones, so that deleting every stored
37795
37927
  * file afterwards cannot miss one still being written. reopen() undoes it.
37796
37928
  */
37797
- async close() {
37798
- this.closed = true;
37929
+ async close(reason = "uninstalling") {
37930
+ this.closed = reason;
37799
37931
  await Promise.allSettled([...this.inFlight]);
37800
37932
  }
37801
37933
  reopen() {
37802
- this.closed = false;
37934
+ this.closed = null;
37803
37935
  }
37804
37936
  async store(actor, target, file2) {
37805
37937
  this.access.requireScope(actor, target.pageId ? "docs:write" : "tasks:write");
@@ -37807,7 +37939,7 @@ var AttachmentService = class {
37807
37939
  throw new AppError(415, "raw_upload_required", "Send the file itself as the request body, with its name in the X-File-Name header");
37808
37940
  }
37809
37941
  if (!Number.isSafeInteger(file2.size) || file2.size < 0) throw new AppError(411, "length_required", "Content-Length is required");
37810
- if (file2.size === 0 || !file2.body) throw badRequest("The file is empty");
37942
+ if (file2.size === 0 || !file2.body) throw new AppError(400, "file_empty", "The file is empty");
37811
37943
  if (file2.size > this.deps.env.maxUploadBytes) {
37812
37944
  throw new AppError(413, "file_too_large", `Files are limited to ${Math.round(this.deps.env.maxUploadBytes / 1048576)} MB`);
37813
37945
  }
@@ -38462,13 +38594,14 @@ var PageService = class {
38462
38594
  }
38463
38595
  return null;
38464
38596
  }
38597
+ /** Every page above it, the top one first, however deep it is. */
38465
38598
  async breadcrumbs(page) {
38466
38599
  if (!page.parentId) return [];
38467
38600
  const rows = this.deps.db.all(sql`
38468
38601
  WITH RECURSIVE chain AS (
38469
38602
  SELECT id, parent_id, title, icon, 1 AS depth FROM pages WHERE id = ${page.parentId}
38470
38603
  UNION ALL
38471
- SELECT p.id, p.parent_id, p.title, p.icon, c.depth + 1 FROM pages p JOIN chain c ON p.id = c.parent_id WHERE c.depth < 32
38604
+ SELECT p.id, p.parent_id, p.title, p.icon, c.depth + 1 FROM pages p JOIN chain c ON p.id = c.parent_id WHERE c.depth < ${MAX_TREE_DEPTH}
38472
38605
  )
38473
38606
  SELECT id, title, icon, depth FROM chain ORDER BY depth DESC`);
38474
38607
  return rows.map((r) => ({ id: r.id, title: r.title, icon: r.icon }));
@@ -38495,8 +38628,8 @@ var PageService = class {
38495
38628
  if (data.title !== void 0) patch.title = data.title;
38496
38629
  if (data.icon !== void 0) patch.icon = data.icon;
38497
38630
  if (data.content !== void 0) {
38498
- const length = opts.append && prev.content !== "" ? prev.content.length + 2 + data.content.length : 0;
38499
- if (length > MAX_MARKDOWN) throw pageTooLong(prev.content.length, length);
38631
+ const length = opts.append && prev.content !== "" ? characters(prev.content) + 2 + characters(data.content) : 0;
38632
+ if (length > MAX_MARKDOWN) throw pageTooLong(characters(prev.content), length);
38500
38633
  patch.content = opts.append ? sql`CASE WHEN ${pages.content} = '' THEN ${data.content} ELSE ${pages.content} || ${"\n\n"} || ${data.content} END` : data.content;
38501
38634
  }
38502
38635
  const guard = data.baseVersion !== void 0 ? and(eq(pages.id, pageId), eq(pages.version, data.baseVersion)) : eq(pages.id, pageId);
@@ -38579,7 +38712,8 @@ var PageService = class {
38579
38712
  if (referenced.length === 0) return;
38580
38713
  const valid = db.select({ id: cards.id }).from(cards).where(and(inList(cards.id, referenced.slice(0, 200)), eq(cards.workspaceId, page.workspaceId))).all();
38581
38714
  if (valid.length === 0) return;
38582
- db.insert(cardPageLinks).values(valid.map((c) => ({ cardId: c.id, pageId: page.id, workspaceId: page.workspaceId, source: "mention" }))).onConflictDoNothing().run();
38715
+ const links = valid.map((c) => ({ cardId: c.id, pageId: page.id, workspaceId: page.workspaceId, source: "mention" }));
38716
+ for (const group of inGroups(cardPageLinks, links)) db.insert(cardPageLinks).values(group).onConflictDoNothing().run();
38583
38717
  }
38584
38718
  };
38585
38719
 
@@ -39141,6 +39275,11 @@ function limit(limiter2, key) {
39141
39275
  if (wait > 0) throw new AppError(429, "rate_limited", `Too many attempts. Try again in ${Math.ceil(wait / 60)} min.`, void 0, { "Retry-After": String(wait) });
39142
39276
  }
39143
39277
  __name(limit, "limit");
39278
+ function trashItemKey(value) {
39279
+ if (!TRASH_KEY.test(value)) throw badRequest("Not a trash key");
39280
+ return value;
39281
+ }
39282
+ __name(trashItemKey, "trashItemKey");
39144
39283
  async function json2(c) {
39145
39284
  try {
39146
39285
  return await c.req.json();
@@ -39149,7 +39288,8 @@ async function json2(c) {
39149
39288
  }
39150
39289
  }
39151
39290
  __name(json2, "json");
39152
- function contentDisposition(kind, name2) {
39291
+ function contentDisposition(kind, stored) {
39292
+ const name2 = withoutBidiControls(stored);
39153
39293
  const encoded = encodeURIComponent(name2).replace(/['()*]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
39154
39294
  const plain = name2.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
39155
39295
  return `${kind}; filename="${plain}"; filename*=UTF-8''${encoded}`;
@@ -39245,9 +39385,9 @@ function createApi(env) {
39245
39385
  api.get("/backups", async (c) => c.json(await c.get("services").backups.status(requireActor(c))));
39246
39386
  api.post("/backups", async (c) => c.json(await c.get("services").backups.createNow(requireActor(c)), 201));
39247
39387
  api.post("/backups/:id/restore", async (c) => {
39248
- const { session, restored } = await c.get("services").backups.restore(requireActor(c), c.req.param("id"), await json2(c), c.req.header("user-agent") ?? null);
39388
+ const { session, restored, leftOut } = await c.get("services").backups.restore(requireActor(c), c.req.param("id"), await json2(c), c.req.header("user-agent") ?? null);
39249
39389
  setSessionCookie(c, session.token, session.expiresAt);
39250
- return c.json({ restored });
39390
+ return c.json({ restored, ...leftOut && { leftOut } });
39251
39391
  });
39252
39392
  api.get("/export", async (c) => {
39253
39393
  const { body, filename } = await c.get("services").export.export(requireActor(c));
@@ -39271,6 +39411,17 @@ function createApi(env) {
39271
39411
  return c.body(null, 204);
39272
39412
  });
39273
39413
  api.get("/workspaces/:id/trash", async (c) => c.json(await c.get("services").trash.list(requireActor(c), c.req.param("id"))));
39414
+ api.post(
39415
+ "/workspaces/:id/trash/restore",
39416
+ async (c) => c.json(await c.get("services").trash.restoreItem(requireActor(c), c.req.param("id"), await json2(c)))
39417
+ );
39418
+ api.post("/workspaces/:id/trash/restore-many", async (c) => c.json(await c.get("services").trash.restoreMany(requireActor(c), c.req.param("id"), await json2(c))));
39419
+ api.post("/workspaces/:id/trash/purge", async (c) => c.json(await c.get("services").trash.purgeMany(requireActor(c), c.req.param("id"), await json2(c))));
39420
+ api.get("/workspaces/:id/trash/:key", async (c) => c.json(await c.get("services").trash.tree(requireActor(c), c.req.param("id"), trashItemKey(c.req.param("key")))));
39421
+ api.delete("/workspaces/:id/trash/:key", async (c) => {
39422
+ await c.get("services").trash.purgeItem(requireActor(c), c.req.param("id"), trashItemKey(c.req.param("key")));
39423
+ return c.body(null, 204);
39424
+ });
39274
39425
  api.post("/trash/:id/restore", async (c) => c.json(await c.get("services").trash.restore(requireActor(c), c.req.param("id"))));
39275
39426
  api.delete("/trash/:id", async (c) => {
39276
39427
  await c.get("services").trash.purge(requireActor(c), c.req.param("id"));
@@ -39294,6 +39445,7 @@ function createApi(env) {
39294
39445
  await services.activity.list(c.req.param("id"), {
39295
39446
  limit: limitParam(c),
39296
39447
  before: beforeParam(c),
39448
+ beforeId: c.req.query("beforeId") || void 0,
39297
39449
  tokenId: c.req.query("tokenId") || void 0,
39298
39450
  agentsOnly: c.req.query("agents") === "1"
39299
39451
  })
@@ -39463,7 +39615,7 @@ function createApi(env) {
39463
39615
  async (c) => c.json(await c.get("services").vault.putItem(requireActor(c), c.req.param("id"), await json2(c)))
39464
39616
  );
39465
39617
  vault.delete("/items/:id{[0-9a-f-]{36}}", async (c) => {
39466
- await c.get("services").vault.deleteItem(requireActor(c), c.req.param("id"));
39618
+ await c.get("services").vault.deleteItem(requireActor(c), c.req.param("id"), c.req.query("base"));
39467
39619
  return c.body(null, 204);
39468
39620
  });
39469
39621
  api.route("/vault", vault);
@@ -50129,7 +50281,7 @@ var EMPTY_COMPLETION_RESULT = {
50129
50281
  };
50130
50282
 
50131
50283
  // src/version.ts
50132
- var VERSION = "1.2.0";
50284
+ var VERSION = "1.3.0";
50133
50285
 
50134
50286
  // src/mcp/server.ts
50135
50287
  var MCP_SERVER_NAME = "orqevio";
@@ -50347,11 +50499,11 @@ function createMcpServer(services, actor) {
50347
50499
  "create_card",
50348
50500
  {
50349
50501
  title: "Create card",
50350
- description: "Creates a card in a column. Description is Markdown.",
50502
+ description: `Creates a card in a column. description is Markdown, up to ${MAX_MARKDOWN} characters.`,
50351
50503
  inputSchema: {
50352
50504
  column_id: uuid3,
50353
50505
  title: external_exports.string().min(1).max(300),
50354
- description: external_exports.string().max(5e4).optional(),
50506
+ description: external_exports.string().max(MAX_MARKDOWN).optional(),
50355
50507
  due_date: dueDate.optional(),
50356
50508
  label_ids: external_exports.array(uuid3).max(20).optional(),
50357
50509
  position: external_exports.enum(["top", "bottom"]).default("bottom")
@@ -50373,11 +50525,11 @@ function createMcpServer(services, actor) {
50373
50525
  "update_card",
50374
50526
  {
50375
50527
  title: "Update card",
50376
- description: "Updates a card. Only the fields you send change. label_ids replaces the full label set. With a description, send base_version (the version from get_card) to avoid overwriting newer edits.",
50528
+ description: `Updates a card. Only the fields you send change. label_ids replaces the full label set. description is Markdown, up to ${MAX_MARKDOWN} characters; with it, send base_version (the version from get_card) to avoid overwriting newer edits.`,
50377
50529
  inputSchema: {
50378
50530
  card_id: uuid3,
50379
50531
  title: external_exports.string().min(1).max(300).optional(),
50380
- description: external_exports.string().max(5e4).optional(),
50532
+ description: external_exports.string().max(MAX_MARKDOWN).optional(),
50381
50533
  base_version: external_exports.number().int().min(1).optional(),
50382
50534
  due_date: dueDate.nullable().optional(),
50383
50535
  label_ids: external_exports.array(uuid3).max(20).optional()
@@ -50444,8 +50596,8 @@ function createMcpServer(services, actor) {
50444
50596
  annotations: WRITE
50445
50597
  },
50446
50598
  ({ board_id, name: name2, index: index3 }) => run(async () => {
50447
- const column = await services.boards.createColumn(actor, board_id, { name: name2, index: index3 });
50448
- return { created: true, column_id: column.id };
50599
+ const column2 = await services.boards.createColumn(actor, board_id, { name: name2, index: index3 });
50600
+ return { created: true, column_id: column2.id };
50449
50601
  })
50450
50602
  );
50451
50603
  server.registerTool(
@@ -50457,8 +50609,8 @@ function createMcpServer(services, actor) {
50457
50609
  annotations: { ...WRITE, idempotentHint: true }
50458
50610
  },
50459
50611
  ({ column_id, name: name2, index: index3 }) => run(async () => {
50460
- const column = await services.boards.updateColumn(actor, column_id, { name: name2, index: index3 });
50461
- return { updated: true, column_id: column.id, name: column.name };
50612
+ const column2 = await services.boards.updateColumn(actor, column_id, { name: name2, index: index3 });
50613
+ return { updated: true, column_id: column2.id, name: column2.name };
50462
50614
  })
50463
50615
  );
50464
50616
  server.registerTool(
@@ -50474,11 +50626,24 @@ function createMcpServer(services, actor) {
50474
50626
  return { created: true, label_id: label.id };
50475
50627
  })
50476
50628
  );
50629
+ server.registerTool(
50630
+ "create_checklist",
50631
+ {
50632
+ title: "Create checklist",
50633
+ description: "Creates an empty checklist on a card. To create one with items, use add_checklist_items with checklist_title instead.",
50634
+ inputSchema: { card_id: uuid3, title: external_exports.string().min(1).max(120) },
50635
+ annotations: WRITE
50636
+ },
50637
+ ({ card_id, title }) => run(async () => {
50638
+ const checklist = await services.cards.createChecklist(actor, card_id, { title });
50639
+ return { created: true, checklist_id: checklist.id, title: checklist.title };
50640
+ })
50641
+ );
50477
50642
  server.registerTool(
50478
50643
  "add_checklist_items",
50479
50644
  {
50480
50645
  title: "Add checklist items",
50481
- description: "Adds items to a checklist of a card. Pass checklist_id to use an existing checklist; otherwise a new checklist is created with checklist_title.",
50646
+ description: "Adds items to a checklist of a card. Pass checklist_id to use an existing checklist; otherwise a new checklist is created with checklist_title. For an empty checklist, use create_checklist.",
50482
50647
  inputSchema: {
50483
50648
  card_id: uuid3,
50484
50649
  items: external_exports.array(external_exports.string().min(1).max(500)).min(1).max(50),
@@ -50636,7 +50801,7 @@ function createMcpServer(services, actor) {
50636
50801
  },
50637
50802
  (args) => run(async () => {
50638
50803
  if (args.card_id === void 0 === (args.page_id === void 0)) throw new AppError(400, "bad_request", "Send either card_id or page_id");
50639
- const bytes = args.encoding === "base64" ? Uint8Array.from(Buffer.from(args.content, "base64")) : new TextEncoder().encode(args.content);
50804
+ const bytes = args.encoding === "base64" ? fromBase64(args.content) : new TextEncoder().encode(args.content);
50640
50805
  if (bytes.byteLength > MCP_UPLOAD_MB * 1024 * 1024) throw new AppError(413, "file_too_large", `Files uploaded by agents are limited to ${MCP_UPLOAD_MB} MB`);
50641
50806
  const type = args.mime_type ?? (args.encoding === "text" ? "text/plain; charset=utf-8" : "application/octet-stream");
50642
50807
  const body = new Blob([bytes]).stream();
@@ -50739,6 +50904,15 @@ function createMcpServer(services, actor) {
50739
50904
  return server;
50740
50905
  }
50741
50906
  __name(createMcpServer, "createMcpServer");
50907
+ function fromBase64(content) {
50908
+ if (/^data:[^,]*,/i.test(content)) throw new AppError(400, "bad_request", "content is a data: URL: send only the base64 after the comma");
50909
+ const compact = content.replace(/\s+/g, "");
50910
+ const unpadded = compact.replace(/={1,2}$/, "");
50911
+ if (!/^[A-Za-z0-9+/]*$/.test(unpadded) && !/^[A-Za-z0-9_-]*$/.test(unpadded)) throw new AppError(400, "bad_request", "content is not valid base64");
50912
+ if (unpadded.length % 4 === 1 || compact.length !== unpadded.length && compact.length % 4 !== 0) throw new AppError(400, "bad_request", "content is not valid base64: its length is not that of encoded bytes");
50913
+ return Uint8Array.from(Buffer.from(unpadded, /[-_]/.test(unpadded) ? "base64url" : "base64"));
50914
+ }
50915
+ __name(fromBase64, "fromBase64");
50742
50916
  function invalidParamsForMalformedRequests(server) {
50743
50917
  const handlers = server.server._requestHandlers;
50744
50918
  if (!(handlers instanceof Map)) return;
@@ -50762,6 +50936,13 @@ var rpcError = /* @__PURE__ */ __name((status, code, message, headers = {}) => n
50762
50936
  status,
50763
50937
  headers: { "Content-Type": "application/json", ...headers }
50764
50938
  }), "rpcError");
50939
+ async function invalidRequestForNonRpc(response) {
50940
+ if (response.status !== 400 || !response.headers.get("content-type")?.includes("application/json")) return response;
50941
+ const body = await response.clone().json().catch(() => null);
50942
+ if (body?.error?.code !== -32700 || body.error.message !== "Parse error: Invalid JSON-RPC message") return response;
50943
+ return rpcError(400, -32600, 'Invalid Request: the body is JSON, but not a JSON-RPC 2.0 request (jsonrpc "2.0", method, and an id for a call)');
50944
+ }
50945
+ __name(invalidRequestForNonRpc, "invalidRequestForNonRpc");
50765
50946
  async function handleMcp(c) {
50766
50947
  if (c.req.method !== "POST") {
50767
50948
  return rpcError(405, -32e3, "Method not allowed. This server is stateless: use POST.", { Allow: "POST" });
@@ -50782,7 +50963,7 @@ async function handleMcp(c) {
50782
50963
  const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: void 0, enableJsonResponse: true, maxRequestBodySize: MCP_MAX_REQUEST_BYTES });
50783
50964
  await server.connect(transport);
50784
50965
  try {
50785
- return await transport.handleRequest(c.req.raw);
50966
+ return invalidRequestForNonRpc(await transport.handleRequest(c.req.raw));
50786
50967
  } finally {
50787
50968
  void server.close();
50788
50969
  }
@@ -50973,16 +51154,52 @@ var ActivityService = class {
50973
51154
  console.error("[realtime] publish failed", error62);
50974
51155
  }
50975
51156
  }
51157
+ /**
51158
+ * The workspace's activity, newest first. A page after the first starts after the last entry
51159
+ * of the previous one: `before`, its time, and `beforeId`, the entry itself, as several can
51160
+ * share a millisecond.
51161
+ */
50976
51162
  async list(workspaceId, opts = {}) {
50977
51163
  const filters = [eq(activity.workspaceId, workspaceId)];
50978
- if (opts.before) filters.push(lt(activity.createdAt, opts.before));
51164
+ const after = this.after(opts.before, opts.beforeId);
51165
+ if (after) filters.push(after);
50979
51166
  if (opts.entityId) filters.push(eq(activity.entityId, opts.entityId));
50980
51167
  if (opts.tokenId) filters.push(eq(activity.actorTokenId, opts.tokenId));
50981
51168
  if (opts.agentsOnly) filters.push(eq(activity.actorKind, "agent"));
50982
51169
  const rows = await this.deps.db.select().from(activity).where(and(...filters)).orderBy(desc(activity.createdAt), desc(sql`rowid`)).limit(Math.min(opts.limit ?? 30, 100));
50983
- return rows.map(toActivityDTO);
51170
+ return this.markTrashed(workspaceId, rows.map(toActivityDTO));
51171
+ }
51172
+ /**
51173
+ * Where the next page starts, in the list's order: after the time the previous page ended at
51174
+ * and, within that millisecond, after its last entry. The entry keeps its rowid when a later
51175
+ * one merges into it and takes it to the top, so it still marks where the page ended; only if
51176
+ * it is gone is the time alone the best there is.
51177
+ */
51178
+ after(before, beforeId) {
51179
+ if (!before) return void 0;
51180
+ const anchor2 = beforeId ? this.deps.db.get(sql`SELECT rowid AS seq FROM activity WHERE id = ${beforeId}`) : void 0;
51181
+ if (!anchor2) return lt(activity.createdAt, before);
51182
+ return or(lt(activity.createdAt, before), and(eq(activity.createdAt, before), sql`rowid < ${anchor2.seq}`));
51183
+ }
51184
+ /**
51185
+ * Entries about something that is in the trash now say so, with its key there: a link to it
51186
+ * would find nothing. What was deleted for good is in neither, and is told as text.
51187
+ */
51188
+ markTrashed(workspaceId, entries) {
51189
+ const ids = [...new Set(entries.filter((e) => e.action !== "trash.purged" && TRASH_TABLE[e.entityType]).map((e) => e.entityId))];
51190
+ if (ids.length === 0) return entries;
51191
+ const found = this.deps.db.all(
51192
+ sql`SELECT r.table_name AS tableName, json_extract(r.data, '$.id') AS id FROM trash_rows r JOIN trash t ON t.id = r.trash_id
51193
+ WHERE t.workspace_id = ${workspaceId} AND json_extract(r.data, '$.id') IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`
51194
+ );
51195
+ const trashed = new Set(found.map((r) => `${r.tableName}|${r.id}`));
51196
+ return entries.map((e) => {
51197
+ const table = e.action === "trash.purged" ? void 0 : TRASH_TABLE[e.entityType];
51198
+ return table && trashed.has(`${table}|${e.entityId}`) ? { ...e, inTrash: `${e.entityType}:${e.entityId}` } : e;
51199
+ });
50984
51200
  }
50985
51201
  };
51202
+ var TRASH_TABLE = { project: "projects", board: "boards", column: "board_columns", card: "cards", label: "labels", page: "pages" };
50986
51203
 
50987
51204
  // ../../node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/browser.js
50988
51205
  var u8 = Uint8Array;
@@ -51322,15 +51539,15 @@ var inflt = /* @__PURE__ */ __name(function(dat, st, buf, dict) {
51322
51539
  }
51323
51540
  if (resize)
51324
51541
  cbuf(bt + 131072);
51325
- var end = bt + add;
51542
+ var end2 = bt + add;
51326
51543
  if (bt < dt) {
51327
- var shift = dl - dt, dend = Math.min(dt, end);
51544
+ var shift = dl - dt, dend = Math.min(dt, end2);
51328
51545
  if (shift + bt < 0)
51329
51546
  err(3);
51330
51547
  for (; bt < dend; ++bt)
51331
51548
  buf[bt] = dict[shift + bt];
51332
51549
  }
51333
- for (; bt < end; ++bt)
51550
+ for (; bt < end2; ++bt)
51334
51551
  buf[bt] = buf[bt - dt];
51335
51552
  }
51336
51553
  }
@@ -51679,14 +51896,6 @@ var dopt = /* @__PURE__ */ __name(function(dat, opt, pre, post, st) {
51679
51896
  }
51680
51897
  return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
51681
51898
  }, "dopt");
51682
- var mrg = /* @__PURE__ */ __name(function(a, b) {
51683
- var o = {};
51684
- for (var k in a)
51685
- o[k] = a[k];
51686
- for (var k in b)
51687
- o[k] = b[k];
51688
- return o;
51689
- }, "mrg");
51690
51899
  var wbytes = /* @__PURE__ */ __name(function(d, b, v) {
51691
51900
  for (; v; ++b)
51692
51901
  d[b] = v, v >>>= 8;
@@ -51785,6 +51994,10 @@ var Deflate = /* @__PURE__ */ (function() {
51785
51994
  };
51786
51995
  return Deflate2;
51787
51996
  })();
51997
+ function deflateSync(data, opts) {
51998
+ return dopt(data, opts || {}, 0, 0);
51999
+ }
52000
+ __name(deflateSync, "deflateSync");
51788
52001
  var Inflate = /* @__PURE__ */ (function() {
51789
52002
  function Inflate2(opts, cb) {
51790
52003
  if (typeof opts == "function")
@@ -51924,239 +52137,6 @@ function strToU8(str, latin1) {
51924
52137
  return slc(ar, 0, ai);
51925
52138
  }
51926
52139
  __name(strToU8, "strToU8");
51927
- var dbf = /* @__PURE__ */ __name(function(l) {
51928
- return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0;
51929
- }, "dbf");
51930
- var exfl = /* @__PURE__ */ __name(function(ex) {
51931
- var le = 0;
51932
- if (ex) {
51933
- for (var k in ex) {
51934
- var l = ex[k].length;
51935
- if (l > 65535)
51936
- err(9);
51937
- le += l + 4;
51938
- }
51939
- }
51940
- return le;
51941
- }, "exfl");
51942
- var wzh = /* @__PURE__ */ __name(function(d, b, f, fn, u, c, ce, co) {
51943
- var fl2 = fn.length, ex = f.extra, col = co && co.length;
51944
- var exl = exfl(ex);
51945
- wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
51946
- if (ce != null)
51947
- d[b++] = 20, d[b++] = f.os;
51948
- d[b] = 20, b += 2;
51949
- d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
51950
- d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
51951
- var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
51952
- if (y < 0 || y > 119)
51953
- err(10);
51954
- wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
51955
- if (c != -1) {
51956
- wbytes(d, b, f.crc);
51957
- wbytes(d, b + 4, c < 0 ? -c - 2 : c);
51958
- wbytes(d, b + 8, f.size);
51959
- }
51960
- wbytes(d, b + 12, fl2);
51961
- wbytes(d, b + 14, exl), b += 16;
51962
- if (ce != null) {
51963
- wbytes(d, b, col);
51964
- wbytes(d, b + 6, f.attrs);
51965
- wbytes(d, b + 10, ce), b += 14;
51966
- }
51967
- d.set(fn, b);
51968
- b += fl2;
51969
- if (exl) {
51970
- for (var k in ex) {
51971
- var exf = ex[k], l = exf.length;
51972
- wbytes(d, b, +k);
51973
- wbytes(d, b + 2, l);
51974
- d.set(exf, b + 4), b += 4 + l;
51975
- }
51976
- }
51977
- if (col)
51978
- d.set(co, b), b += col;
51979
- return b;
51980
- }, "wzh");
51981
- var wzf = /* @__PURE__ */ __name(function(o, b, c, d, e) {
51982
- wbytes(o, b, 101010256);
51983
- wbytes(o, b + 8, c);
51984
- wbytes(o, b + 10, c);
51985
- wbytes(o, b + 12, d);
51986
- wbytes(o, b + 16, e);
51987
- }, "wzf");
51988
- var ZipPassThrough = /* @__PURE__ */ (function() {
51989
- function ZipPassThrough2(filename) {
51990
- this.filename = filename;
51991
- this.c = crc();
51992
- this.size = 0;
51993
- this.compression = 0;
51994
- }
51995
- __name(ZipPassThrough2, "ZipPassThrough");
51996
- ZipPassThrough2.prototype.process = function(chunk, final) {
51997
- this.ondata(null, chunk, final);
51998
- };
51999
- ZipPassThrough2.prototype.push = function(chunk, final) {
52000
- if (!this.ondata)
52001
- err(5);
52002
- this.c.p(chunk);
52003
- this.size += chunk.length;
52004
- if (final)
52005
- this.crc = this.c.d();
52006
- this.process(chunk, final || false);
52007
- };
52008
- return ZipPassThrough2;
52009
- })();
52010
- var ZipDeflate = /* @__PURE__ */ (function() {
52011
- function ZipDeflate2(filename, opts) {
52012
- var _this = this;
52013
- if (!opts)
52014
- opts = {};
52015
- ZipPassThrough.call(this, filename);
52016
- this.d = new Deflate(opts, function(dat, final) {
52017
- _this.ondata(null, dat, final);
52018
- });
52019
- this.compression = 8;
52020
- this.flag = dbf(opts.level);
52021
- }
52022
- __name(ZipDeflate2, "ZipDeflate");
52023
- ZipDeflate2.prototype.process = function(chunk, final) {
52024
- try {
52025
- this.d.push(chunk, final);
52026
- } catch (e) {
52027
- this.ondata(e, null, final);
52028
- }
52029
- };
52030
- ZipDeflate2.prototype.push = function(chunk, final) {
52031
- ZipPassThrough.prototype.push.call(this, chunk, final);
52032
- };
52033
- return ZipDeflate2;
52034
- })();
52035
- var Zip = /* @__PURE__ */ (function() {
52036
- function Zip2(cb) {
52037
- this.ondata = cb;
52038
- this.u = [];
52039
- this.d = 1;
52040
- }
52041
- __name(Zip2, "Zip");
52042
- Zip2.prototype.add = function(file2) {
52043
- var _this = this;
52044
- if (!this.ondata)
52045
- err(5);
52046
- if (this.d & 2)
52047
- this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
52048
- else {
52049
- var f = strToU8(file2.filename), fl_1 = f.length;
52050
- var com = file2.comment, o = com && strToU8(com);
52051
- var u = fl_1 != file2.filename.length || o && com.length != o.length;
52052
- var hl_1 = fl_1 + exfl(file2.extra) + 30;
52053
- if (fl_1 > 65535)
52054
- this.ondata(err(11, 0, 1), null, false);
52055
- var header = new u8(hl_1);
52056
- wzh(header, 0, file2, f, u, -1);
52057
- var chks_1 = [header];
52058
- var pAll_1 = /* @__PURE__ */ __name(function() {
52059
- for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
52060
- var chk = chks_2[_i];
52061
- _this.ondata(null, chk, false);
52062
- }
52063
- chks_1 = [];
52064
- }, "pAll_1");
52065
- var tr_1 = this.d;
52066
- this.d = 0;
52067
- var ind_1 = this.u.length;
52068
- var uf_1 = mrg(file2, {
52069
- f,
52070
- u,
52071
- o,
52072
- t: /* @__PURE__ */ __name(function() {
52073
- if (file2.terminate)
52074
- file2.terminate();
52075
- }, "t"),
52076
- r: /* @__PURE__ */ __name(function() {
52077
- pAll_1();
52078
- if (tr_1) {
52079
- var nxt = _this.u[ind_1 + 1];
52080
- if (nxt)
52081
- nxt.r();
52082
- else
52083
- _this.d = 1;
52084
- }
52085
- tr_1 = 1;
52086
- }, "r")
52087
- });
52088
- var cl_1 = 0;
52089
- file2.ondata = function(err2, dat, final) {
52090
- if (err2) {
52091
- _this.ondata(err2, dat, final);
52092
- _this.terminate();
52093
- } else {
52094
- cl_1 += dat.length;
52095
- chks_1.push(dat);
52096
- if (final) {
52097
- var dd = new u8(16);
52098
- wbytes(dd, 0, 134695760);
52099
- wbytes(dd, 4, file2.crc);
52100
- wbytes(dd, 8, cl_1);
52101
- wbytes(dd, 12, file2.size);
52102
- chks_1.push(dd);
52103
- uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file2.crc, uf_1.size = file2.size;
52104
- if (tr_1)
52105
- uf_1.r();
52106
- tr_1 = 1;
52107
- } else if (tr_1)
52108
- pAll_1();
52109
- }
52110
- };
52111
- this.u.push(uf_1);
52112
- }
52113
- };
52114
- Zip2.prototype.end = function() {
52115
- var _this = this;
52116
- if (this.d & 2) {
52117
- this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
52118
- return;
52119
- }
52120
- if (this.d)
52121
- this.e();
52122
- else
52123
- this.u.push({
52124
- r: /* @__PURE__ */ __name(function() {
52125
- if (!(_this.d & 1))
52126
- return;
52127
- _this.u.splice(-1, 1);
52128
- _this.e();
52129
- }, "r"),
52130
- t: /* @__PURE__ */ __name(function() {
52131
- }, "t")
52132
- });
52133
- this.d = 3;
52134
- };
52135
- Zip2.prototype.e = function() {
52136
- var bt = 0, l = 0, tl = 0;
52137
- for (var _i = 0, _a4 = this.u; _i < _a4.length; _i++) {
52138
- var f = _a4[_i];
52139
- tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
52140
- }
52141
- var out = new u8(tl + 22);
52142
- for (var _b2 = 0, _c = this.u; _b2 < _c.length; _b2++) {
52143
- var f = _c[_b2];
52144
- wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
52145
- bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
52146
- }
52147
- wzf(out, bt, this.u.length, tl, l);
52148
- this.ondata(null, out, true);
52149
- this.d = 2;
52150
- };
52151
- Zip2.prototype.terminate = function() {
52152
- for (var _i = 0, _a4 = this.u; _i < _a4.length; _i++) {
52153
- var f = _a4[_i];
52154
- f.t();
52155
- }
52156
- this.d = 2;
52157
- };
52158
- return Zip2;
52159
- })();
52160
52140
 
52161
52141
  // src/backups/dump.ts
52162
52142
  var DUMP_FORMAT = "orqevio-backup";
@@ -52321,6 +52301,31 @@ function readHeader(data) {
52321
52301
  return header;
52322
52302
  }
52323
52303
  __name(readHeader, "readHeader");
52304
+ function fileNames(data) {
52305
+ const names = /* @__PURE__ */ new Map();
52306
+ let reading = null;
52307
+ for (const line of readLines(data)) {
52308
+ if (Array.isArray(line)) {
52309
+ const key = reading ? line[reading.key] : void 0;
52310
+ if (!reading || typeof key !== "string") continue;
52311
+ if (reading.table === "attachments") {
52312
+ const name2 = line[reading.name];
52313
+ if (typeof name2 === "string") names.set(key, name2);
52314
+ } else {
52315
+ try {
52316
+ const row = JSON.parse(String(line[reading.data]));
52317
+ if (typeof row.filename === "string") names.set(key, row.filename);
52318
+ } catch {
52319
+ }
52320
+ }
52321
+ } else if (line && typeof line === "object" && "table" in line) {
52322
+ const { table, columns: columns2 } = line;
52323
+ reading = (table === "attachments" || table === "trash_rows") && columns2.includes("storage_key") ? { table, key: columns2.indexOf("storage_key"), name: columns2.indexOf("filename"), data: columns2.indexOf("data") } : null;
52324
+ } else if (line && typeof line === "object" && "end" in line) break;
52325
+ }
52326
+ return names;
52327
+ }
52328
+ __name(fileNames, "fileNames");
52324
52329
  var DumpError = class extends Error {
52325
52330
  constructor(code) {
52326
52331
  super(`This backup can't be restored: ${code}`);
@@ -52371,12 +52376,93 @@ function restoreDump(sql2, data, { migration, before }) {
52371
52376
  }
52372
52377
  __name(restoreDump, "restoreDump");
52373
52378
 
52379
+ // src/backups/kept.ts
52380
+ var num = /* @__PURE__ */ __name((value) => value === null || value === void 0 ? null : Number(value), "num");
52381
+ var column = /* @__PURE__ */ __name((sql2, query) => [...sql2.rows(query)].map((row) => String(row[0])), "column");
52382
+ var readVaults = /* @__PURE__ */ __name((sql2) => [...sql2.rows("SELECT user_id, key_version, wrapped_key FROM vaults")].map(([userId, keyVersion2, wrappedKey]) => ({
52383
+ userId: String(userId),
52384
+ keyVersion: Number(keyVersion2),
52385
+ wrappedKey: wrappedKey === null || wrappedKey === void 0 ? null : String(wrappedKey)
52386
+ })), "readVaults");
52387
+ function readKept(sql2) {
52388
+ const [instance2] = [...sql2.rows("SELECT owner_id FROM instance WHERE id = 1")];
52389
+ return {
52390
+ ownerId: instance2 ? String(instance2[0]) : null,
52391
+ tokens: new Map([...sql2.rows("SELECT id, revoked_at FROM api_tokens")].map(([id3, revokedAt]) => [String(id3), num(revokedAt)])),
52392
+ oauthTokens: new Map([...sql2.rows("SELECT id, rotated_at FROM oauth_tokens")].map(([id3, rotatedAt]) => [String(id3), num(rotatedAt)])),
52393
+ oauthCodes: new Map([...sql2.rows("SELECT id, used_at FROM oauth_codes")].map(([id3, usedAt]) => [String(id3), usedAt !== null && usedAt !== void 0])),
52394
+ vaults: new Map(readVaults(sql2).map(({ userId, ...vault }) => [userId, vault]))
52395
+ };
52396
+ }
52397
+ __name(readKept, "readKept");
52398
+ var hasColumn = /* @__PURE__ */ __name((sql2, table, column2) => {
52399
+ const [row] = [...sql2.rows("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", table)];
52400
+ return Boolean(row && new RegExp(`\\b${column2}\\b`).test(String(row[0])));
52401
+ }, "hasColumn");
52402
+ function applyKept(sql2, kept, restoredOwnerId, now = Date.now()) {
52403
+ if (kept.ownerId === restoredOwnerId) {
52404
+ for (const id3 of column(sql2, "SELECT id FROM api_tokens WHERE revoked_at IS NULL")) {
52405
+ const current = kept.tokens.get(id3);
52406
+ if (current === void 0 || current !== null) sql2.run("UPDATE api_tokens SET revoked_at = ? WHERE id = ?", current ?? now, id3);
52407
+ }
52408
+ for (const id3 of column(sql2, "SELECT id FROM oauth_tokens WHERE rotated_at IS NULL")) {
52409
+ const current = kept.oauthTokens.get(id3);
52410
+ if (current === void 0) sql2.run("DELETE FROM oauth_tokens WHERE id = ?", id3);
52411
+ else if (current !== null) sql2.run("UPDATE oauth_tokens SET rotated_at = ? WHERE id = ?", current, id3);
52412
+ }
52413
+ for (const id3 of column(sql2, "SELECT id FROM oauth_tokens WHERE rotated_at IS NOT NULL")) {
52414
+ if (!kept.oauthTokens.has(id3)) sql2.run("DELETE FROM oauth_tokens WHERE id = ?", id3);
52415
+ }
52416
+ for (const id3 of column(sql2, "SELECT id FROM oauth_codes WHERE used_at IS NULL")) {
52417
+ const used = kept.oauthCodes.get(id3);
52418
+ if (used === void 0) sql2.run("DELETE FROM oauth_codes WHERE id = ?", id3);
52419
+ else if (used) sql2.run("UPDATE oauth_codes SET used_at = ? WHERE id = ?", now, id3);
52420
+ }
52421
+ }
52422
+ if (!hasColumn(sql2, "vaults", "key_version")) return;
52423
+ const itemsLabelled = hasColumn(sql2, "vault_items", "key_version");
52424
+ for (const restored of readVaults(sql2)) {
52425
+ const current = kept.vaults.get(restored.userId);
52426
+ if (!current || current.keyVersion === restored.keyVersion && current.wrappedKey === restored.wrappedKey) continue;
52427
+ const next = Math.max(current.keyVersion, restored.keyVersion) + 1;
52428
+ sql2.run("UPDATE vaults SET key_version = ? WHERE user_id = ?", next, restored.userId);
52429
+ if (itemsLabelled) sql2.run("UPDATE vault_items SET key_version = ? WHERE user_id = ? AND key_version = ?", next, restored.userId, restored.keyVersion);
52430
+ }
52431
+ }
52432
+ __name(applyKept, "applyKept");
52433
+
52374
52434
  // src/backups/store.ts
52375
52435
  import { createReadStream, createWriteStream } from "node:fs";
52376
52436
  import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
52377
52437
  import path from "node:path";
52378
52438
  import { Readable, Writable } from "node:stream";
52439
+ function problemOf(error62, at) {
52440
+ const code = error62?.code;
52441
+ const uid = typeof process !== "undefined" ? process.getuid?.() : void 0;
52442
+ const gid = typeof process !== "undefined" ? process.getgid?.() : void 0;
52443
+ return {
52444
+ code: code === "EACCES" || code === "EPERM" ? "access" : code === "EROFS" ? "readonly" : code === "ENOSPC" || code === "EDQUOT" ? "full" : "other",
52445
+ path: at,
52446
+ user: uid === void 0 ? null : `${uid}:${gid ?? uid}`,
52447
+ detail: error62 instanceof Error ? error62.message : String(error62)
52448
+ };
52449
+ }
52450
+ __name(problemOf, "problemOf");
52451
+ function describeBackupProblem(problem, root = problem.path) {
52452
+ switch (problem.code) {
52453
+ case "access":
52454
+ return `Backups can't be made: this server's user (${problem.user ?? "unknown"}) can't read or write ${problem.path}. Give the backups folder back to that user: mounted from the host, with sudo chown -R ${problem.user ?? "100:101"} on it; inside the volume (backups copied in with docker compose cp are left to root), with docker compose run --rm --user root app chown -R orqevio:orqevio ${root}.`;
52455
+ case "readonly":
52456
+ return `Backups can't be made: ${problem.path} is read-only.`;
52457
+ case "full":
52458
+ return `Backups can't be made: the disk of ${problem.path} is full.`;
52459
+ default:
52460
+ return `Backups can't be made in ${problem.path}: ${problem.detail}`;
52461
+ }
52462
+ }
52463
+ __name(describeBackupProblem, "describeBackupProblem");
52379
52464
  var BACKUP_KEY = /^(?:snapshots\/[0-9A-Za-z-]+\/(?:data\.ndjson\.gz|manifest\.json)|files\/[0-9a-f-]{36}\/[0-9a-f-]{36})$/;
52465
+ var PROBE_BYTES = new Uint8Array(64 * 1024);
52380
52466
  async function emptyBackupStore(store) {
52381
52467
  const snapshots = (await store.list("snapshots/")).map((k) => k.key);
52382
52468
  const manifests = snapshots.filter((key) => key.endsWith("/manifest.json"));
@@ -52386,6 +52472,35 @@ async function emptyBackupStore(store) {
52386
52472
  }
52387
52473
  __name(emptyBackupStore, "emptyBackupStore");
52388
52474
 
52475
+ // src/lib/measure.ts
52476
+ import { createHash as createHash3 } from "node:crypto";
52477
+ function measure() {
52478
+ const hash2 = createHash3("sha256");
52479
+ let bytes = 0;
52480
+ let digest = null;
52481
+ const stream = new TransformStream({
52482
+ transform(chunk, controller) {
52483
+ hash2.update(chunk);
52484
+ bytes += chunk.length;
52485
+ controller.enqueue(chunk);
52486
+ },
52487
+ flush() {
52488
+ digest = hash2.digest("hex");
52489
+ }
52490
+ });
52491
+ return {
52492
+ stream,
52493
+ /** What went through, once all of it has. */
52494
+ result: /* @__PURE__ */ __name(() => {
52495
+ if (digest === null) throw new Error("Not measured yet");
52496
+ return { bytes, sha256: digest };
52497
+ }, "result"),
52498
+ /** How much has gone through so far, and whether that was all (the stream ended). */
52499
+ sofar: /* @__PURE__ */ __name(() => ({ bytes, ended: digest !== null }), "sofar")
52500
+ };
52501
+ }
52502
+ __name(measure, "measure");
52503
+
52389
52504
  // src/services/backups.ts
52390
52505
  var KEEP_BACKUPS = 7;
52391
52506
  var DUE_AFTER_MS = 23.5 * 60 * 60 * 1e3;
@@ -52425,15 +52540,34 @@ var BackupService = class {
52425
52540
  await this.accounts.requireOwner(actor);
52426
52541
  if (!this.enabled) return { where: null, keep: KEEP_BACKUPS, backups: [] };
52427
52542
  const migration = currentMigration(this.deps.sql);
52428
- const manifests = await this.manifests();
52429
- return { where: this.deps.backups.where, keep: KEEP_BACKUPS, backups: manifests.map((m) => this.toDTO(m, migration)) };
52543
+ let problem = await this.deps.backups.check?.() ?? null;
52544
+ let manifests = [];
52545
+ try {
52546
+ manifests = await this.manifests();
52547
+ } catch (error62) {
52548
+ const failed = this.folderError(error62);
52549
+ if (!(failed instanceof AppError) || failed.code !== "backup_folder") throw error62;
52550
+ problem ??= failed.details;
52551
+ }
52552
+ return { where: this.deps.backups.where, keep: KEEP_BACKUPS, backups: manifests.map((m) => this.toDTO(m, migration)), problem };
52430
52553
  }
52431
52554
  /** "Back up now", from Settings. */
52432
52555
  async createNow(actor) {
52433
52556
  await this.accounts.requireOwner(actor);
52434
52557
  if (!this.enabled) throw backupsOff();
52435
- const manifest = await this.exclusive(() => this.create("manual"));
52436
- return this.toDTO(manifest, currentMigration(this.deps.sql));
52558
+ try {
52559
+ const manifest = await this.exclusive(() => this.create("manual"));
52560
+ return this.toDTO(manifest, currentMigration(this.deps.sql));
52561
+ } catch (error62) {
52562
+ throw this.folderError(error62);
52563
+ }
52564
+ }
52565
+ /** A backup that failed because of where it goes (not the app's, read-only, full, not a folder): said as such. */
52566
+ folderError(error62) {
52567
+ if (error62 instanceof AppError || !this.deps.backups.failedHere?.(error62)) return error62;
52568
+ const where = this.deps.backups.where.name;
52569
+ const problem = problemOf(error62, error62.path ?? where);
52570
+ return new AppError(409, "backup_folder", describeBackupProblem(problem, where), problem);
52437
52571
  }
52438
52572
  /** Hourly: makes the daily backup once the last one is a day old, for a copy that is claimed and in use. */
52439
52573
  async runIfDue(now = Date.now()) {
@@ -52500,33 +52634,37 @@ var BackupService = class {
52500
52634
  const id3 = now.toISOString().replace(/[:.]/g, "-");
52501
52635
  const dump = writeDump(sql2, VERSION, now);
52502
52636
  const listed = /* @__PURE__ */ new Map();
52503
- for (const [key, size] of sql2.rows(
52504
- "SELECT storage_key, size FROM attachments UNION ALL SELECT storage_key, json_extract(data, '$.size') FROM trash_rows WHERE storage_key IS NOT NULL"
52637
+ for (const [key, size, name2] of sql2.rows(
52638
+ "SELECT storage_key, size, filename FROM attachments UNION ALL SELECT storage_key, json_extract(data, '$.size'), json_extract(data, '$.filename') FROM trash_rows WHERE storage_key IS NOT NULL"
52505
52639
  )) {
52506
- if (typeof key === "string") listed.set(key, Number(size ?? 0));
52640
+ if (typeof key === "string") listed.set(key, { size: Number(size ?? 0), name: typeof name2 === "string" ? name2 : key });
52507
52641
  }
52508
52642
  const migration = currentMigration(sql2);
52509
52643
  const count2 = /* @__PURE__ */ __name((table) => dump.counts[table] ?? 0, "count");
52510
52644
  await store.write(dataKey(id3), dump.data);
52511
- const stored = new Set((await store.list("files/")).map((f) => f.key));
52645
+ const stored = new Map((await store.list("files/")).map((f) => [f.key, f.size]));
52646
+ const known = await this.knownHashes();
52512
52647
  const files = [];
52513
52648
  const missingFiles = [];
52514
- for (const [key, size] of listed) {
52515
- if (!stored.has(fileKey(key))) {
52516
- try {
52517
- const body = await this.deps.storage.stream(key);
52518
- if (!body) {
52519
- missingFiles.push(key);
52520
- continue;
52521
- }
52522
- await store.writeStream(fileKey(key), body, size);
52523
- } catch (error62) {
52524
- console.error(`[backups] could not copy ${key}`, error62);
52649
+ for (const [key, { size, name: name2 }] of listed) {
52650
+ if (stored.get(fileKey(key)) === size) {
52651
+ files.push({ key, size, sha256: known.get(key), name: name2 });
52652
+ continue;
52653
+ }
52654
+ try {
52655
+ const body = await this.deps.storage.stream(key);
52656
+ if (!body) {
52525
52657
  missingFiles.push(key);
52526
52658
  continue;
52527
52659
  }
52660
+ const measured = measure();
52661
+ await store.writeStream(fileKey(key), body.pipeThrough(measured.stream), size);
52662
+ files.push({ key, size, sha256: measured.result().sha256, name: name2 });
52663
+ } catch (error62) {
52664
+ if (store.failedHere?.(error62)) throw error62;
52665
+ console.error(`[backups] could not copy ${key}`, error62);
52666
+ missingFiles.push(key);
52528
52667
  }
52529
- files.push({ key, size });
52530
52668
  }
52531
52669
  const manifest = {
52532
52670
  format: DUMP_FORMAT,
@@ -52551,18 +52689,25 @@ var BackupService = class {
52551
52689
  missingFiles
52552
52690
  };
52553
52691
  await store.write(manifestKey(id3), new TextEncoder().encode(JSON.stringify(manifest)));
52554
- if (prune) await this.prune(now.getTime());
52692
+ if (prune) await this.prune(now.getTime()).catch((error62) => console.error("[backups] prune failed", error62));
52555
52693
  return manifest;
52556
52694
  }
52695
+ /** What each kept attachment was, as the backups that say it do: a kept file never changes. */
52696
+ async knownHashes(manifests) {
52697
+ const known = /* @__PURE__ */ new Map();
52698
+ for (const m of manifests ?? await this.manifests()) for (const f of m.files) if (f.sha256 && !known.has(f.key)) known.set(f.key, f.sha256);
52699
+ return known;
52700
+ }
52557
52701
  /**
52558
- * Keeps the KEEP_BACKUPS newest daily or manual backups and the newest one made before a
52559
- * restore, removes the rest and the unfinished ones, then the attachments none of those kept lists.
52702
+ * Keeps the KEEP_BACKUPS newest daily backups, as many of those made by hand (which never push
52703
+ * out a daily one) and the newest one made before a restore; removes the rest, the unfinished
52704
+ * ones and what interrupted writes left, then the attachments none of those kept lists.
52560
52705
  */
52561
52706
  async prune(now) {
52562
52707
  const store = this.deps.backups;
52563
52708
  const manifests = await this.manifests();
52564
- const regular = manifests.filter((m) => m.kind !== "before-restore");
52565
- const kept = [...regular.slice(0, KEEP_BACKUPS), ...manifests.filter((m) => m.kind === "before-restore").slice(0, 1)];
52709
+ const newest = /* @__PURE__ */ __name((kind, count2) => manifests.filter((m) => m.kind === kind).slice(0, count2), "newest");
52710
+ const kept = [...newest("daily", KEEP_BACKUPS), ...newest("manual", KEEP_BACKUPS), ...newest("before-restore", 1)];
52566
52711
  const keptIds = new Set(kept.map((m) => m.id));
52567
52712
  const listed = await store.list("snapshots/");
52568
52713
  const withManifest = new Set(manifests.map((m) => m.id));
@@ -52579,24 +52724,32 @@ var BackupService = class {
52579
52724
  const needed = new Set(kept.flatMap((m) => m.files.map((f) => fileKey(f.key))));
52580
52725
  const unused = (await store.list("files/")).map((f) => f.key).filter((key) => !needed.has(key));
52581
52726
  if (unused.length) await store.delete(unused);
52727
+ await store.removeLeftovers?.(now - UNFINISHED_AFTER_MS);
52582
52728
  }
52583
52729
  /**
52584
- * Puts a backup back in place of everything. First a backup of the copy as it is now, kept
52585
- * apart from the daily ones; then the attachments the backup lists that are missing; then
52586
- * the database, in one transaction. The access key in use now still opens the copy, every
52587
- * session ends, and the person who restored it gets a new one.
52730
+ * Puts a backup back in place of everything. First the attachments it lists that the copy no
52731
+ * longer has, each checked as it is put back; then a backup of the copy as it is now, kept
52732
+ * apart from the daily ones; then the database, in one transaction. The access key in use now
52733
+ * still opens the copy, every session ends, and the person who restored it gets a new one.
52734
+ * Agents' accesses revoked since stay revoked, and the vault key version only goes up (see
52735
+ * backups/kept.ts).
52588
52736
  */
52589
52737
  async restore(actor, id3, input2, userAgent) {
52590
52738
  await this.accounts.requireOwner(actor);
52591
- const { accessKey } = parse3(restoreBackupInput, input2);
52739
+ const { accessKey, leaveOut } = parse3(restoreBackupInput, input2);
52592
52740
  if (!this.enabled) throw backupsOff();
52593
52741
  if (!/^[0-9A-Za-z-]+$/.test(id3)) throw notFound("Backup");
52594
52742
  const owner = await this.accounts.verifyAccessKey(actor.userId, accessKey);
52595
52743
  return this.exclusive(async () => {
52596
52744
  const store = this.deps.backups;
52597
52745
  const sql2 = this.deps.sql;
52598
- const manifest = (await this.manifests()).find((m) => m.id === id3);
52599
- const data = manifest && await store.read(dataKey(id3));
52746
+ const manifests = await this.manifests().catch((error62) => {
52747
+ throw this.folderError(error62);
52748
+ });
52749
+ const manifest = manifests.find((m) => m.id === id3);
52750
+ const data = manifest && await store.read(dataKey(id3)).catch((error62) => {
52751
+ throw this.folderError(error62);
52752
+ });
52600
52753
  if (!manifest || !data) throw notFound("Backup");
52601
52754
  if (data.length !== manifest.data.bytes || await sha2563(data) !== manifest.data.sha256) {
52602
52755
  throw new AppError(422, "backup_damaged", "This backup is damaged: its data is not what it was when it was made");
@@ -52608,15 +52761,77 @@ var BackupService = class {
52608
52761
  } catch (error62) {
52609
52762
  throw this.dumpError(error62);
52610
52763
  }
52611
- await this.create("before-restore", { prune: false });
52764
+ const names = manifest.files.some((f) => !f.name) ? fileNames(data) : /* @__PURE__ */ new Map();
52765
+ const named = /* @__PURE__ */ __name((file2, reason) => ({ key: file2.key, name: file2.name ?? names.get(file2.key) ?? file2.key, reason }), "named");
52766
+ const agreed = new Set(leaveOut);
52767
+ const damaged = [];
52768
+ const refuseUnlessAgreed = /* @__PURE__ */ __name(() => {
52769
+ if (damaged.some((f) => !agreed.has(f.key))) {
52770
+ throw new AppError(422, "backup_files_damaged", "Some attachments of this backup are damaged or gone: restore it without them, or keep this copy as it is", { files: damaged });
52771
+ }
52772
+ }, "refuseUnlessAgreed");
52773
+ const stored = new Map(
52774
+ (await store.list("files/").catch((error62) => {
52775
+ throw this.folderError(error62);
52776
+ })).map((f) => [f.key, f.size])
52777
+ );
52778
+ const wanted = [];
52779
+ for (const file2 of manifest.files) {
52780
+ if (await this.deps.storage.exists(file2.key)) continue;
52781
+ const size = stored.get(fileKey(file2.key));
52782
+ if (size === void 0) damaged.push(named(file2, "missing"));
52783
+ else if (size !== file2.size) damaged.push(named(file2, "size"));
52784
+ else wanted.push(file2);
52785
+ }
52786
+ refuseUnlessAgreed();
52787
+ const known = await this.knownHashes(manifests);
52788
+ const copied = [];
52789
+ const spoilt = [];
52790
+ const undo = /* @__PURE__ */ __name(() => Promise.all(copied.map((key) => this.deps.storage.delete(key).catch(() => {
52791
+ }))), "undo");
52612
52792
  let ownerId = "";
52613
- await this.attachments.close();
52793
+ let before = null;
52794
+ await this.attachments.close("restoring");
52614
52795
  try {
52615
- for (const file2 of manifest.files) {
52616
- if (await this.deps.storage.exists(file2.key)) continue;
52617
- const body = await store.stream(fileKey(file2.key));
52618
- if (body) await this.deps.storage.put(file2.key, body, file2.size, "application/octet-stream");
52796
+ for (const file2 of wanted) {
52797
+ const body = await store.stream(fileKey(file2.key)).catch((error62) => {
52798
+ throw this.folderError(error62);
52799
+ });
52800
+ if (!body) {
52801
+ damaged.push(named(file2, "missing"));
52802
+ continue;
52803
+ }
52804
+ const measured = measure();
52805
+ try {
52806
+ await this.deps.storage.put(file2.key, body.pipeThrough(measured.stream), file2.size, "application/octet-stream");
52807
+ } catch (error62) {
52808
+ const read = measured.sofar();
52809
+ if (!(error62 instanceof LengthMismatchError) && !(read.ended ? read.bytes !== file2.size : read.bytes > file2.size)) throw this.folderError(error62);
52810
+ damaged.push(named(file2, "size"));
52811
+ continue;
52812
+ }
52813
+ const expected = file2.sha256 ?? known.get(file2.key);
52814
+ if (expected && measured.result().sha256 !== expected) {
52815
+ await this.deps.storage.delete(file2.key);
52816
+ damaged.push(named(file2, "changed"));
52817
+ spoilt.push(fileKey(file2.key));
52818
+ continue;
52819
+ }
52820
+ copied.push(file2.key);
52619
52821
  }
52822
+ if (spoilt.length) await store.delete(spoilt).catch((error62) => console.error("[backups] could not remove damaged kept attachments", error62));
52823
+ refuseUnlessAgreed();
52824
+ before = await this.create("before-restore", { prune: false }).catch((error62) => {
52825
+ throw this.folderError(error62);
52826
+ });
52827
+ } catch (error62) {
52828
+ await undo();
52829
+ this.attachments.reopen();
52830
+ throw error62;
52831
+ }
52832
+ let restored = false;
52833
+ try {
52834
+ const kept = readKept(sql2);
52620
52835
  try {
52621
52836
  restoreDump(sql2, data, {
52622
52837
  migration,
@@ -52626,12 +52841,20 @@ var BackupService = class {
52626
52841
  ownerId = String(row[0]);
52627
52842
  sql2.run("UPDATE instance SET access_key_hash = ?, setup_code_hash = ?, key_changed_at = ? WHERE id = 1", owner.accessKeyHash, owner.setupCodeHash, owner.keyChangedAt.getTime());
52628
52843
  sql2.run("DELETE FROM sessions");
52844
+ applyKept(sql2, kept, ownerId);
52629
52845
  }, "before")
52630
52846
  });
52847
+ restored = true;
52631
52848
  } catch (error62) {
52632
52849
  throw this.dumpError(error62);
52633
52850
  }
52634
52851
  await this.deps.migrate?.();
52852
+ } catch (error62) {
52853
+ if (!restored) {
52854
+ await undo();
52855
+ if (before) await store.delete([manifestKey(before.id), dataKey(before.id)]).catch((e) => console.error("[backups] could not remove the backup made before a failed restore", e));
52856
+ }
52857
+ throw error62;
52635
52858
  } finally {
52636
52859
  this.attachments.reopen();
52637
52860
  await this.prune(Date.now()).catch((error62) => console.error("[backups] prune failed", error62));
@@ -52639,7 +52862,7 @@ var BackupService = class {
52639
52862
  this.accounts.forget();
52640
52863
  this.oauth.forget();
52641
52864
  const session = await this.accounts.startSession(ownerId, userAgent);
52642
- return { session, restored: this.toDTO(manifest, currentMigration(sql2)) };
52865
+ return { session, restored: this.toDTO(manifest, currentMigration(sql2)), ...damaged.length && { leftOut: damaged } };
52643
52866
  });
52644
52867
  }
52645
52868
  /**
@@ -52767,7 +52990,7 @@ var CardService = class {
52767
52990
  async detail(actor, cardId) {
52768
52991
  const card = await this.load(actor, cardId);
52769
52992
  const db = this.deps.db;
52770
- const [[summary], [column], [board], labelRows, checklistData, pageLinks, files, history2] = await Promise.all([
52993
+ const [[summary], [column2], [board], labelRows, checklistData, pageLinks, files, history2] = await Promise.all([
52771
52994
  this.summarize([card]),
52772
52995
  db.select({ id: columns.id, name: columns.name }).from(columns).where(eq(columns.id, card.columnId)),
52773
52996
  db.select({ id: boards.id, name: boards.name, projectId: boards.projectId }).from(boards).where(eq(boards.id, card.boardId)),
@@ -52788,7 +53011,7 @@ var CardService = class {
52788
53011
  workspaceId: card.workspaceId,
52789
53012
  description: card.description,
52790
53013
  archivedAt: card.archivedAt?.toISOString() ?? null,
52791
- column,
53014
+ column: column2,
52792
53015
  board,
52793
53016
  labels: labelRows.map((r) => toLabelDTO(r.label)),
52794
53017
  checklists: checklistData,
@@ -52802,7 +53025,7 @@ var CardService = class {
52802
53025
  const db = this.deps.db;
52803
53026
  const lists = await db.select().from(checklists).where(eq(checklists.cardId, cardId)).orderBy(asc(checklists.position), asc(checklists.id));
52804
53027
  if (lists.length === 0) return [];
52805
- const items = await db.select().from(checklistItems).where(inArray(checklistItems.checklistId, lists.map((l) => l.id))).orderBy(asc(checklistItems.position), asc(checklistItems.id));
53028
+ const items = await db.select().from(checklistItems).where(inList(checklistItems.checklistId, lists.map((l) => l.id))).orderBy(asc(checklistItems.position), asc(checklistItems.id));
52806
53029
  return lists.map((l) => ({
52807
53030
  id: l.id,
52808
53031
  cardId: l.cardId,
@@ -52821,14 +53044,14 @@ var CardService = class {
52821
53044
  async create(actor, columnId, input2) {
52822
53045
  this.access.requireScope(actor, "tasks:write");
52823
53046
  const data = parse3(cardCreateInput, input2);
52824
- const [column] = await this.deps.db.select().from(columns).where(eq(columns.id, columnId));
52825
- if (!column) throw notFound("Column");
52826
- await this.access.workspace(actor, column.workspaceId);
53047
+ const [column2] = await this.deps.db.select().from(columns).where(eq(columns.id, columnId));
53048
+ if (!column2) throw notFound("Column");
53049
+ await this.access.workspace(actor, column2.workspaceId);
52827
53050
  const card = this.deps.db.transaction((tx) => {
52828
53051
  const position2 = positionAt(tx, cards, and(eq(cards.columnId, columnId), isNull(cards.archivedAt)), data.index);
52829
53052
  const row = tx.insert(cards).values({
52830
- workspaceId: column.workspaceId,
52831
- boardId: column.boardId,
53053
+ workspaceId: column2.workspaceId,
53054
+ boardId: column2.boardId,
52832
53055
  columnId,
52833
53056
  title: data.title,
52834
53057
  description: data.description ?? "",
@@ -52837,16 +53060,16 @@ var CardService = class {
52837
53060
  createdByUserId: actor.userId,
52838
53061
  createdByTokenId: actor.kind === "agent" ? actor.tokenId : null
52839
53062
  }).returning().get();
52840
- const labelIds = this.validLabelIds(tx, column.boardId, data.labelIds ?? []);
53063
+ const labelIds = this.validLabelIds(tx, column2.boardId, data.labelIds ?? []);
52841
53064
  if (labelIds.length) tx.insert(cardLabels).values(labelIds.map((labelId) => ({ cardId: row.id, labelId }))).run();
52842
- this.change(tx, actor, row, { kind: "card.created", meta: { title: row.title, column: column.name } });
53065
+ this.change(tx, actor, row, { kind: "card.created", meta: { title: row.title, column: column2.name } });
52843
53066
  if (row.description) this.change(tx, actor, row, { kind: "card.description", before: "", after: row.description });
52844
53067
  return row;
52845
53068
  });
52846
53069
  await this.activity.record(
52847
53070
  actor,
52848
53071
  card.workspaceId,
52849
- { action: "card.created", entityType: "card", entityId: card.id, summary: card.title, meta: { column: column.name } },
53072
+ { action: "card.created", entityType: "card", entityId: card.id, summary: card.title, meta: { column: column2.name } },
52850
53073
  { boardId: card.boardId, cardId: card.id, structure: true }
52851
53074
  );
52852
53075
  const [summary] = await this.summarize([card]);
@@ -52855,62 +53078,68 @@ var CardService = class {
52855
53078
  async update(actor, cardId, input2) {
52856
53079
  const data = parse3(cardUpdateInput, input2);
52857
53080
  const card = await this.load(actor, cardId, "tasks:write");
52858
- const changed = Object.keys(data).filter((k) => k !== "baseVersion" && data[k] !== void 0);
52859
- if (changed.length === 0) {
52860
- const [summary2] = await this.summarize([card]);
52861
- return summary2;
52862
- }
52863
- const updated = this.deps.db.transaction((tx) => {
53081
+ const { row: updated, changed } = this.deps.db.transaction((tx) => {
52864
53082
  const prev = tx.select().from(cards).where(eq(cards.id, cardId)).get();
52865
53083
  if (!prev) throw notFound("Card");
53084
+ const title = data.title !== void 0 && data.title !== prev.title ? data.title : void 0;
53085
+ const description = data.description !== void 0 && data.description !== prev.description ? data.description : void 0;
53086
+ const due = data.dueAt === void 0 ? void 0 : data.dueAt ? new Date(data.dueAt) : null;
53087
+ const dueChanged = due !== void 0 && (due?.getTime() ?? null) !== (prev.dueAt?.getTime() ?? null);
53088
+ let labels2;
53089
+ if (data.labelIds) {
53090
+ const ids = this.validLabelIds(tx, card.boardId, data.labelIds);
53091
+ const was = tx.select({ id: cardLabels.labelId }).from(cardLabels).where(eq(cardLabels.cardId, cardId)).all().map((l) => l.id);
53092
+ if ([...new Set(ids)].sort().join() !== [...was].sort().join()) labels2 = { ids, was };
53093
+ }
53094
+ const changed2 = [title !== void 0 && "title", description !== void 0 && "description", dueChanged && "dueAt", labels2 && "labelIds"].filter((f) => Boolean(f));
53095
+ if (changed2.length === 0) return { row: prev, changed: changed2 };
52866
53096
  const patch = { updatedAt: /* @__PURE__ */ new Date() };
52867
- if (data.title !== void 0) patch.title = data.title;
52868
- if (data.description !== void 0) {
52869
- patch.description = data.description;
53097
+ if (title !== void 0) patch.title = title;
53098
+ if (description !== void 0) {
53099
+ patch.description = description;
52870
53100
  patch.version = sql`${cards.version} + 1`;
52871
53101
  }
52872
- if (data.dueAt !== void 0) patch.dueAt = data.dueAt ? new Date(data.dueAt) : null;
52873
- const guard = data.description !== void 0 && data.baseVersion !== void 0 ? and(eq(cards.id, cardId), eq(cards.version, data.baseVersion)) : eq(cards.id, cardId);
53102
+ if (dueChanged) patch.dueAt = due;
53103
+ const guard = description !== void 0 && data.baseVersion !== void 0 ? and(eq(cards.id, cardId), eq(cards.version, data.baseVersion)) : eq(cards.id, cardId);
52874
53104
  const row = tx.update(cards).set(patch).where(guard).returning().get();
52875
53105
  if (!row) {
52876
53106
  const latest = tx.select({ version: cards.version }).from(cards).where(eq(cards.id, cardId)).get();
52877
53107
  throw conflict("This card was modified since you loaded it", { currentVersion: latest?.version ?? null });
52878
53108
  }
52879
- if (data.title !== void 0) this.change(tx, actor, row, { kind: "card.title", before: prev.title, after: row.title });
52880
- if (data.description !== void 0) this.change(tx, actor, row, { kind: "card.description", before: prev.description, after: row.description });
52881
- if (data.dueAt !== void 0) this.change(tx, actor, row, { kind: "card.due", before: prev.dueAt?.toISOString() ?? null, after: row.dueAt?.toISOString() ?? null });
52882
- if (data.labelIds) {
52883
- const labelIds = this.validLabelIds(tx, card.boardId, data.labelIds);
52884
- const was = tx.select({ id: cardLabels.labelId }).from(cardLabels).where(eq(cardLabels.cardId, cardId)).all().map((l) => l.id);
53109
+ if (title !== void 0) this.change(tx, actor, row, { kind: "card.title", before: prev.title, after: row.title });
53110
+ if (description !== void 0) this.change(tx, actor, row, { kind: "card.description", before: prev.description, after: row.description });
53111
+ if (dueChanged) this.change(tx, actor, row, { kind: "card.due", before: prev.dueAt?.toISOString() ?? null, after: row.dueAt?.toISOString() ?? null });
53112
+ if (labels2) {
53113
+ const { ids, was } = labels2;
52885
53114
  tx.delete(cardLabels).where(eq(cardLabels.cardId, cardId)).run();
52886
- if (labelIds.length) tx.insert(cardLabels).values(labelIds.map((labelId) => ({ cardId, labelId }))).run();
52887
- const added = labelIds.filter((id3) => !was.includes(id3));
52888
- const removed = was.filter((id3) => !labelIds.includes(id3));
52889
- if (added.length || removed.length) {
52890
- this.change(tx, actor, row, {
52891
- kind: "card.labels",
52892
- before: [...was].sort(),
52893
- after: [...labelIds].sort(),
52894
- meta: { added: this.labelNames(tx, added), removed: this.labelNames(tx, removed) }
52895
- });
52896
- }
53115
+ if (ids.length) tx.insert(cardLabels).values(ids.map((labelId) => ({ cardId, labelId }))).run();
53116
+ const added = ids.filter((id3) => !was.includes(id3));
53117
+ const removed = was.filter((id3) => !ids.includes(id3));
53118
+ this.change(tx, actor, row, {
53119
+ kind: "card.labels",
53120
+ before: [...was].sort(),
53121
+ after: [...ids].sort(),
53122
+ meta: { added: this.labelNames(tx, added), removed: this.labelNames(tx, removed) }
53123
+ });
52897
53124
  }
52898
- return row;
53125
+ return { row, changed: changed2 };
52899
53126
  });
52900
- await this.activity.record(
52901
- actor,
52902
- card.workspaceId,
52903
- {
52904
- action: "card.updated",
52905
- entityType: "card",
52906
- entityId: cardId,
52907
- summary: updated.title,
52908
- meta: { fields: changed.join(",") },
52909
- coalesce: true
52910
- },
52911
- // Only changes to the description carry a version, so an open card refreshes its text only for those.
52912
- { boardId: card.boardId, cardId, ...data.description !== void 0 ? { version: updated.version } : {} }
52913
- );
53127
+ if (changed.length > 0) {
53128
+ await this.activity.record(
53129
+ actor,
53130
+ card.workspaceId,
53131
+ {
53132
+ action: "card.updated",
53133
+ entityType: "card",
53134
+ entityId: cardId,
53135
+ summary: updated.title,
53136
+ meta: { fields: changed.join(",") },
53137
+ coalesce: true
53138
+ },
53139
+ // Only changes to the description carry a version, so an open card refreshes its text only for those.
53140
+ { boardId: card.boardId, cardId, ...changed.includes("description") ? { version: updated.version } : {} }
53141
+ );
53142
+ }
52914
53143
  const [summary] = await this.summarize([updated]);
52915
53144
  return summary;
52916
53145
  }
@@ -52922,7 +53151,7 @@ var CardService = class {
52922
53151
  const otherBoard = target.boardId !== card.boardId;
52923
53152
  if (otherBoard) this.access.requireScope(actor, "organize");
52924
53153
  const boardName = /* @__PURE__ */ __name((id3) => otherBoard ? this.deps.db.select({ name: boards.name }).from(boards).where(eq(boards.id, id3)).get()?.name : void 0, "boardName");
52925
- const place = /* @__PURE__ */ __name((board, column) => board ? `${board} \u203A ${column ?? ""}` : column ?? null, "place");
53154
+ const place = /* @__PURE__ */ __name((board, column2) => board ? `${board} \u203A ${column2 ?? ""}` : column2 ?? null, "place");
52926
53155
  const fromColumn = this.deps.db.select({ name: columns.name }).from(columns).where(eq(columns.id, card.columnId)).get()?.name ?? null;
52927
53156
  const from = place(boardName(card.boardId), fromColumn);
52928
53157
  const to = place(boardName(target.boardId), target.name);
@@ -53213,7 +53442,8 @@ var BoardService = class {
53213
53442
  const position2 = positionAt(tx, boards, eq(boards.projectId, projectId), void 0);
53214
53443
  const b = tx.insert(boards).values({ workspaceId: project.workspaceId, projectId, name: data.name, position: position2 }).returning().get();
53215
53444
  const keys = evenlySpacedKeys(columnNames.length);
53216
- tx.insert(columns).values(columnNames.map((name2, i2) => ({ workspaceId: project.workspaceId, boardId: b.id, name: name2, position: keys[i2] }))).run();
53445
+ const rows = columnNames.map((name2, i2) => ({ workspaceId: project.workspaceId, boardId: b.id, name: name2, position: keys[i2] }));
53446
+ for (const group of inGroups(columns, rows)) tx.insert(columns).values(group).run();
53217
53447
  return b;
53218
53448
  });
53219
53449
  await this.activity.record(
@@ -53284,7 +53514,7 @@ var BoardService = class {
53284
53514
  async createColumn(actor, boardId, input2) {
53285
53515
  const data = parse3(columnCreateInput, input2);
53286
53516
  const board = await this.load(actor, boardId, "tasks:write");
53287
- const column = this.deps.db.transaction((tx) => {
53517
+ const column2 = this.deps.db.transaction((tx) => {
53288
53518
  const { total } = tx.select({ total: count() }).from(columns).where(eq(columns.boardId, boardId)).get();
53289
53519
  if (total >= MAX_COLUMNS) throw new AppError(400, "too_many_columns", `A board holds up to ${MAX_COLUMNS} columns`);
53290
53520
  const position2 = positionAt(tx, columns, eq(columns.boardId, boardId), data.index);
@@ -53293,51 +53523,51 @@ var BoardService = class {
53293
53523
  await this.activity.record(
53294
53524
  actor,
53295
53525
  board.workspaceId,
53296
- { action: "column.created", entityType: "column", entityId: column.id, summary: data.name, meta: { board: board.name } },
53526
+ { action: "column.created", entityType: "column", entityId: column2.id, summary: data.name, meta: { board: board.name } },
53297
53527
  { boardId }
53298
53528
  );
53299
- return toColumnDTO(column);
53529
+ return toColumnDTO(column2);
53300
53530
  }
53301
53531
  async loadColumn(actor, columnId, scope = "tasks:read") {
53302
53532
  this.access.requireScope(actor, scope);
53303
- const [column] = await this.deps.db.select().from(columns).where(eq(columns.id, columnId));
53304
- if (!column) throw notFound("Column");
53305
- await this.access.workspace(actor, column.workspaceId);
53306
- return column;
53533
+ const [column2] = await this.deps.db.select().from(columns).where(eq(columns.id, columnId));
53534
+ if (!column2) throw notFound("Column");
53535
+ await this.access.workspace(actor, column2.workspaceId);
53536
+ return column2;
53307
53537
  }
53308
53538
  async updateColumn(actor, columnId, input2) {
53309
53539
  const data = parse3(columnUpdateInput, input2);
53310
- const column = await this.loadColumn(actor, columnId, "tasks:write");
53540
+ const column2 = await this.loadColumn(actor, columnId, "tasks:write");
53311
53541
  const patch = {};
53312
53542
  if (data.name !== void 0) patch.name = data.name;
53313
53543
  if (data.index !== void 0) {
53314
- patch.position = positionAt(this.deps.db, columns, eq(columns.boardId, column.boardId), data.index, columnId);
53544
+ patch.position = positionAt(this.deps.db, columns, eq(columns.boardId, column2.boardId), data.index, columnId);
53315
53545
  }
53316
- if (Object.keys(patch).length === 0) return toColumnDTO(column);
53546
+ if (Object.keys(patch).length === 0) return toColumnDTO(column2);
53317
53547
  const [row] = await this.deps.db.update(columns).set(patch).where(eq(columns.id, columnId)).returning();
53318
53548
  await this.activity.record(
53319
53549
  actor,
53320
- column.workspaceId,
53550
+ column2.workspaceId,
53321
53551
  {
53322
53552
  action: data.index !== void 0 && data.name === void 0 ? "column.moved" : "column.updated",
53323
53553
  entityType: "column",
53324
53554
  entityId: columnId,
53325
53555
  summary: row.name
53326
53556
  },
53327
- { boardId: column.boardId }
53557
+ { boardId: column2.boardId }
53328
53558
  );
53329
53559
  return toColumnDTO(row);
53330
53560
  }
53331
53561
  async removeColumn(actor, columnId) {
53332
53562
  this.access.requireScope(actor, "organize");
53333
- const column = await this.loadColumn(actor, columnId, "tasks:write");
53563
+ const column2 = await this.loadColumn(actor, columnId, "tasks:write");
53334
53564
  const [{ total }] = await this.deps.db.select({ total: count() }).from(cards).where(eq(cards.columnId, columnId));
53335
- const trashId = this.deps.db.transaction((tx) => this.trash.move(tx, actor, column.workspaceId, { kind: "column", id: columnId }));
53565
+ const trashId = this.deps.db.transaction((tx) => this.trash.move(tx, actor, column2.workspaceId, { kind: "column", id: columnId }));
53336
53566
  await this.activity.record(
53337
53567
  actor,
53338
- column.workspaceId,
53339
- { action: "column.deleted", entityType: "column", entityId: columnId, summary: column.name, meta: { cards: total } },
53340
- { boardId: column.boardId, structure: total > 0 }
53568
+ column2.workspaceId,
53569
+ { action: "column.deleted", entityType: "column", entityId: columnId, summary: column2.name, meta: { cards: total } },
53570
+ { boardId: column2.boardId, structure: total > 0 }
53341
53571
  );
53342
53572
  return trashId;
53343
53573
  }
@@ -53364,8 +53594,12 @@ var BoardService = class {
53364
53594
  async updateLabel(actor, labelId, input2) {
53365
53595
  const data = parse3(labelUpdateInput, input2);
53366
53596
  const label = await this.loadLabel(actor, labelId);
53367
- if (data.name === void 0 && data.color === void 0) return toLabelDTO(label);
53368
- const [row] = await this.deps.db.update(labels).set(data).where(eq(labels.id, labelId)).returning();
53597
+ const patch = {
53598
+ ...data.name !== void 0 && data.name !== label.name ? { name: data.name } : {},
53599
+ ...data.color !== void 0 && data.color !== label.color ? { color: data.color } : {}
53600
+ };
53601
+ if (Object.keys(patch).length === 0) return toLabelDTO(label);
53602
+ const [row] = await this.deps.db.update(labels).set(patch).where(eq(labels.id, labelId)).returning();
53369
53603
  await this.activity.record(
53370
53604
  actor,
53371
53605
  label.workspaceId,
@@ -53389,14 +53623,233 @@ var BoardService = class {
53389
53623
  }
53390
53624
  };
53391
53625
 
53626
+ // src/lib/zip.ts
53627
+ var MAX32 = 4294967295;
53628
+ var MAX16 = 65535;
53629
+ var UTF8 = 2048;
53630
+ var DESCRIPTOR = 8;
53631
+ var ZIP64_EXTRA_MAX = 4 + 3 * 8;
53632
+ var STORED = 0;
53633
+ var DEFLATED = 8;
53634
+ var V20 = 20;
53635
+ var V45 = 45;
53636
+ var ZipWriter = class {
53637
+ /** `write` takes each piece in order; the ZIP waits for it, which is how a slow reader slows it down. */
53638
+ constructor(write, options = {}) {
53639
+ this.write = write;
53640
+ this.options = options;
53641
+ }
53642
+ write;
53643
+ options;
53644
+ static {
53645
+ __name(this, "ZipWriter");
53646
+ }
53647
+ offset = 0;
53648
+ entries = [];
53649
+ encoder = new TextEncoder();
53650
+ /** A text (or any data held in memory), compressed. */
53651
+ async add(name2, data, date5 = /* @__PURE__ */ new Date()) {
53652
+ const compressed = deflateSync(data, { level: 6 });
53653
+ const entry = this.entry(name2, date5, DEFLATED, 0);
53654
+ entry.crc = crc32(data);
53655
+ entry.compressed = compressed.length;
53656
+ entry.size = data.length;
53657
+ entry.zip64 = Boolean(this.options.alwaysZip64) || entry.size >= MAX32 || entry.compressed >= MAX32;
53658
+ await this.put(localHeader(entry));
53659
+ await this.put(compressed);
53660
+ }
53661
+ /**
53662
+ * A file of `size` bytes, read from `body` as it is written: stored as it is (attachments are
53663
+ * mostly compressed already). It must be `size` bytes long, or the ZIP stops there with an error.
53664
+ */
53665
+ async addStream(name2, size, body, date5 = /* @__PURE__ */ new Date()) {
53666
+ const entry = this.entry(name2, date5, STORED, DESCRIPTOR);
53667
+ entry.zip64 = Boolean(this.options.alwaysZip64) || size >= MAX32;
53668
+ await this.put(localHeader(entry));
53669
+ let crc2 = ~0;
53670
+ let length = 0;
53671
+ const reader = body.getReader();
53672
+ try {
53673
+ for (; ; ) {
53674
+ const { value, done } = await reader.read();
53675
+ if (done) break;
53676
+ length += value.length;
53677
+ if (length > size) throw new Error(`${name2} is longer than its ${size} bytes`);
53678
+ crc2 = crc32Update(crc2, value);
53679
+ await this.put(value);
53680
+ }
53681
+ } catch (error62) {
53682
+ await reader.cancel(error62).catch(() => {
53683
+ });
53684
+ throw error62;
53685
+ } finally {
53686
+ reader.releaseLock();
53687
+ }
53688
+ if (length !== size) throw new Error(`${name2} has ${length} bytes, not ${size}`);
53689
+ entry.crc = ~crc2 >>> 0;
53690
+ entry.compressed = entry.size = length;
53691
+ await this.put(dataDescriptor(entry));
53692
+ }
53693
+ /** The central directory, and the records at the end that say where it is. */
53694
+ async end() {
53695
+ const start = this.offset;
53696
+ for (const entry of this.entries) await this.put(centralHeader(entry, Boolean(this.options.alwaysZip64)));
53697
+ const size = this.offset - start;
53698
+ const count2 = this.entries.length;
53699
+ const zip64 = Boolean(this.options.alwaysZip64) || count2 >= MAX16 || size >= MAX32 || start >= MAX32;
53700
+ if (zip64) {
53701
+ const record2 = this.offset;
53702
+ await this.put(zip64End(count2, size, start));
53703
+ await this.put(zip64Locator(record2));
53704
+ }
53705
+ await this.put(end(zip64 ? MAX16 : count2, zip64 ? MAX32 : size, zip64 ? MAX32 : start));
53706
+ }
53707
+ entry(name2, date5, method, flags) {
53708
+ const bytes = this.encoder.encode(name2);
53709
+ if (bytes.length > MAX16) throw new Error(`The name ${name2.slice(0, 80)}\u2026 is longer than a ZIP holds (65,535 bytes)`);
53710
+ const fits = 9 + bytes.length + ZIP64_EXTRA_MAX <= MAX16;
53711
+ const unicode = bytes.length === name2.length || !fits ? new Uint8Array(0) : new Record(9 + bytes.length).u16(28789).u16(5 + bytes.length).raw(new Uint8Array([1])).u32(crc32(bytes)).raw(bytes).bytes;
53712
+ const entry = { name: bytes, flags: UTF8 | flags, method, ...dos(date5), crc: 0, compressed: 0, size: 0, offset: this.offset, zip64: false, unicode };
53713
+ this.entries.push(entry);
53714
+ return entry;
53715
+ }
53716
+ async put(chunk) {
53717
+ if (!chunk.length) return;
53718
+ this.offset += chunk.length;
53719
+ await this.write(chunk);
53720
+ }
53721
+ };
53722
+ function dos(date5) {
53723
+ const year = Math.max(1980, date5.getFullYear());
53724
+ return {
53725
+ time: date5.getHours() << 11 | date5.getMinutes() << 5 | date5.getSeconds() >> 1,
53726
+ date: year - 1980 << 9 | date5.getMonth() + 1 << 5 | date5.getDate()
53727
+ };
53728
+ }
53729
+ __name(dos, "dos");
53730
+ var Record = class {
53731
+ static {
53732
+ __name(this, "Record");
53733
+ }
53734
+ bytes;
53735
+ view;
53736
+ at = 0;
53737
+ constructor(size) {
53738
+ this.bytes = new Uint8Array(size);
53739
+ this.view = new DataView(this.bytes.buffer);
53740
+ }
53741
+ u16(value) {
53742
+ if (value > MAX16) throw new Error(`${value} does not fit in a ZIP field of 2 bytes`);
53743
+ this.view.setUint16(this.at, value, true);
53744
+ this.at += 2;
53745
+ return this;
53746
+ }
53747
+ u32(value) {
53748
+ this.view.setUint32(this.at, value >>> 0, true);
53749
+ this.at += 4;
53750
+ return this;
53751
+ }
53752
+ u64(value) {
53753
+ this.view.setBigUint64(this.at, BigInt(value), true);
53754
+ this.at += 8;
53755
+ return this;
53756
+ }
53757
+ raw(bytes) {
53758
+ this.bytes.set(bytes, this.at);
53759
+ this.at += bytes.length;
53760
+ return this;
53761
+ }
53762
+ };
53763
+ var concat = /* @__PURE__ */ __name((a, b) => {
53764
+ const out = new Uint8Array(a.length + b.length);
53765
+ out.set(a);
53766
+ out.set(b, a.length);
53767
+ return out;
53768
+ }, "concat");
53769
+ function zip64Extra(values) {
53770
+ const record2 = new Record(4 + values.length * 8).u16(1).u16(values.length * 8);
53771
+ for (const value of values) record2.u64(value);
53772
+ return record2.bytes;
53773
+ }
53774
+ __name(zip64Extra, "zip64Extra");
53775
+ function localHeader(entry) {
53776
+ const streamed = (entry.flags & DESCRIPTOR) !== 0;
53777
+ const extra = concat(entry.zip64 ? zip64Extra(streamed ? [0, 0] : [entry.size, entry.compressed]) : new Uint8Array(0), entry.unicode);
53778
+ const record2 = new Record(30 + entry.name.length + extra.length).u32(67324752).u16(entry.zip64 ? V45 : V20).u16(entry.flags).u16(entry.method).u16(entry.time).u16(entry.date).u32(streamed ? 0 : entry.crc);
53779
+ if (entry.zip64) record2.u32(MAX32).u32(MAX32);
53780
+ else record2.u32(streamed ? 0 : entry.compressed).u32(streamed ? 0 : entry.size);
53781
+ return record2.u16(entry.name.length).u16(extra.length).raw(entry.name).raw(extra).bytes;
53782
+ }
53783
+ __name(localHeader, "localHeader");
53784
+ function dataDescriptor(entry) {
53785
+ const record2 = new Record(entry.zip64 ? 24 : 16).u32(134695760).u32(entry.crc);
53786
+ if (entry.zip64) return record2.u64(entry.compressed).u64(entry.size).bytes;
53787
+ return record2.u32(entry.compressed).u32(entry.size).bytes;
53788
+ }
53789
+ __name(dataDescriptor, "dataDescriptor");
53790
+ function centralHeader(entry, always) {
53791
+ const big = /* @__PURE__ */ __name((value) => always || value >= MAX32, "big");
53792
+ const values = [entry.size, entry.compressed, entry.offset].filter(big);
53793
+ const extra = concat(values.length ? zip64Extra(values) : new Uint8Array(0), entry.unicode);
53794
+ const version3 = values.length || entry.zip64 ? V45 : V20;
53795
+ return new Record(46 + entry.name.length + extra.length).u32(33639248).u16(version3).u16(version3).u16(entry.flags).u16(entry.method).u16(entry.time).u16(entry.date).u32(entry.crc).u32(big(entry.compressed) ? MAX32 : entry.compressed).u32(big(entry.size) ? MAX32 : entry.size).u16(entry.name.length).u16(extra.length).u16(0).u16(0).u16(0).u32(0).u32(big(entry.offset) ? MAX32 : entry.offset).raw(entry.name).raw(extra).bytes;
53796
+ }
53797
+ __name(centralHeader, "centralHeader");
53798
+ function zip64End(count2, size, offset) {
53799
+ return new Record(56).u32(101075792).u64(44).u16(V45).u16(V45).u32(0).u32(0).u64(count2).u64(count2).u64(size).u64(offset).bytes;
53800
+ }
53801
+ __name(zip64End, "zip64End");
53802
+ function zip64Locator(record2) {
53803
+ return new Record(20).u32(117853008).u32(0).u64(record2).u32(1).bytes;
53804
+ }
53805
+ __name(zip64Locator, "zip64Locator");
53806
+ function end(count2, size, offset) {
53807
+ return new Record(22).u32(101010256).u16(0).u16(0).u16(count2).u16(count2).u32(size).u32(offset).u16(0).bytes;
53808
+ }
53809
+ __name(end, "end");
53810
+ var TABLES = (() => {
53811
+ const tables = new Int32Array(256 * 8);
53812
+ for (let n = 0; n < 256; n++) {
53813
+ let c = n;
53814
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
53815
+ tables[n] = c;
53816
+ }
53817
+ for (let n = 0; n < 256; n++) {
53818
+ let c = tables[n];
53819
+ for (let t = 1; t < 8; t++) {
53820
+ c = tables[c & 255] ^ c >>> 8;
53821
+ tables[t * 256 + n] = c;
53822
+ }
53823
+ }
53824
+ return tables;
53825
+ })();
53826
+ function crc32Update(crc2, data) {
53827
+ const t = TABLES;
53828
+ let c = crc2;
53829
+ let i2 = 0;
53830
+ const end8 = data.length - data.length % 8;
53831
+ for (; i2 < end8; i2 += 8) {
53832
+ const a = c ^ (data[i2] | data[i2 + 1] << 8 | data[i2 + 2] << 16 | data[i2 + 3] << 24);
53833
+ c = t[1792 + (a & 255)] ^ t[1536 + (a >>> 8 & 255)] ^ t[1280 + (a >>> 16 & 255)] ^ t[1024 + (a >>> 24)] ^ t[768 + data[i2 + 4]] ^ t[512 + data[i2 + 5]] ^ t[256 + data[i2 + 6]] ^ t[data[i2 + 7]];
53834
+ }
53835
+ for (; i2 < data.length; i2++) c = t[(c ^ data[i2]) & 255] ^ c >>> 8;
53836
+ return c;
53837
+ }
53838
+ __name(crc32Update, "crc32Update");
53839
+ function crc32(data) {
53840
+ return ~crc32Update(~0, data) >>> 0;
53841
+ }
53842
+ __name(crc32, "crc32");
53843
+
53392
53844
  // src/services/export.ts
53393
53845
  var EXPORT_FORMAT = "orqevio-export";
53394
53846
  var UNSAFE2 = /[\u0000-\u001f\u007f<>:"/\\|?*]/g;
53395
53847
  var NAME_BYTES = 150;
53396
53848
  var utf8 = new TextEncoder();
53397
53849
  var DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)(?=\.|$)/i;
53850
+ var INVISIBLE = /(?!\u200D)[\p{Cf}\u115F\u1160\u3164\uFFA0]/gu;
53398
53851
  function cleanName2(name2, maxBytes) {
53399
- const clean = name2.replace(UNSAFE2, "-").replace(/\s+/g, " ").trim().replace(/^\.+/, "").replace(/[. ]+$/, "");
53852
+ const clean = name2.normalize("NFC").replace(INVISIBLE, "").replace(UNSAFE2, "-").replace(/\s+/g, " ").trim().replace(/^\.+/, "").replace(/[. ]+$/, "");
53400
53853
  let cut = "";
53401
53854
  let bytes = 0;
53402
53855
  for (const char of clean) {
@@ -53412,12 +53865,13 @@ function safeName(name2, fallback = "Untitled", maxBytes = NAME_BYTES) {
53412
53865
  }
53413
53866
  __name(safeName, "safeName");
53414
53867
  function namer(reserved = []) {
53415
- const taken = new Set(reserved.map((name2) => name2.toLowerCase()));
53416
- const free = /* @__PURE__ */ __name((stem, endings) => endings.every((ending) => !taken.has(`${stem}${ending}`.toLowerCase())), "free");
53868
+ const same = /* @__PURE__ */ __name((name2) => name2.normalize("NFC").toLowerCase(), "same");
53869
+ const taken = new Set(reserved.map(same));
53870
+ const free = /* @__PURE__ */ __name((stem, endings) => endings.every((ending) => !taken.has(same(`${stem}${ending}`))), "free");
53417
53871
  return (name2, endings = [""]) => {
53418
53872
  let stem = name2;
53419
53873
  for (let n = 2; !free(stem, endings); n++) stem = `${name2} (${n})`;
53420
- for (const ending of endings) taken.add(`${stem}${ending}`.toLowerCase());
53874
+ for (const ending of endings) taken.add(same(`${stem}${ending}`));
53421
53875
  return stem;
53422
53876
  };
53423
53877
  }
@@ -53432,10 +53886,12 @@ function linkTo(fromDir, target) {
53432
53886
  }
53433
53887
  __name(linkTo, "linkTo");
53434
53888
  var DESTINATION = String.raw`(\]\(\s*<?|^[ \t]{0,3}\[[^\]\n]+\]:[ \t]*<?|\b(?:src|href)=["']?)`;
53435
- var UUID2 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
53436
- var ATTACHMENT_LINK = new RegExp(String.raw`${DESTINATION}(?:https?:\/\/[^\s()<>"']+)?\/api\/attachments\/(${UUID2})(?=[\s)>"'])`, "gim");
53437
- var REFERENCE = new RegExp(String.raw`${DESTINATION}\/(doc|card)\/(${UUID2})(?=[\s)>"'])`, "gim");
53889
+ var UUID3 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
53890
+ var ATTACHMENT_LINK = new RegExp(String.raw`${DESTINATION}(?:https?:\/\/[^\s()<>"']+)?\/api\/attachments\/(${UUID3})(?=[\s)>"'])`, "gim");
53891
+ var REFERENCE = new RegExp(String.raw`${DESTINATION}\/(doc|card)\/(${UUID3})(?=[\s)>"'])`, "gim");
53438
53892
  var FENCE = /^[ \t]*(?:>[ \t]?)*[ \t]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})(.*)$/;
53893
+ var INDENTED = /^(?: {4}|\t)/;
53894
+ var LIST_ITEM = /^[ \t]{0,3}(?:>[ \t]?)*(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)/;
53439
53895
  function outsideCode(markdown, change) {
53440
53896
  const out = [];
53441
53897
  let text2 = "";
@@ -53444,18 +53900,39 @@ function outsideCode(markdown, change) {
53444
53900
  text2 = "";
53445
53901
  }, "flush");
53446
53902
  let fence = null;
53903
+ let indented = false;
53904
+ let blank = true;
53905
+ let inList2 = false;
53447
53906
  for (const line of markdown.split(/(?<=\n)/)) {
53448
- const match2 = FENCE.exec(line.replace(/\r?\n$/, ""));
53907
+ const bare = line.replace(/\r?\n$/, "");
53908
+ const match2 = FENCE.exec(bare);
53449
53909
  if (fence) {
53450
53910
  out.push(line);
53451
53911
  if (match2 && match2[1][0] === fence.char && match2[1].length >= fence.size && !match2[2].trim()) fence = null;
53452
- } else if (match2 && !(match2[1][0] === "`" && match2[2].includes("`"))) {
53912
+ continue;
53913
+ }
53914
+ if (indented) {
53915
+ if (!bare.trim() || INDENTED.test(bare)) {
53916
+ out.push(line);
53917
+ blank = !bare.trim();
53918
+ continue;
53919
+ }
53920
+ indented = false;
53921
+ }
53922
+ if (match2 && !(match2[1][0] === "`" && match2[2].includes("`"))) {
53453
53923
  flush();
53454
53924
  out.push(line);
53455
53925
  fence = { char: match2[1][0], size: match2[1].length };
53926
+ } else if (blank && !inList2 && INDENTED.test(bare) && bare.trim()) {
53927
+ flush();
53928
+ out.push(line);
53929
+ indented = true;
53456
53930
  } else {
53457
53931
  text2 += line;
53932
+ if (LIST_ITEM.test(bare)) inList2 = true;
53933
+ else if (bare.trim() && !/^[ \t]/.test(bare) && blank) inList2 = false;
53458
53934
  }
53935
+ blank = !bare.trim();
53459
53936
  }
53460
53937
  flush();
53461
53938
  return out.join("");
@@ -53500,47 +53977,22 @@ var ExportService = class {
53500
53977
  const { texts, files, summary } = this.snapshot(actor.userId, root);
53501
53978
  const { readable, writable } = new TransformStream();
53502
53979
  const writer = writable.getWriter();
53503
- let failed = null;
53504
- const zip = new Zip((error62, chunk, final) => {
53505
- if (error62) {
53506
- failed = error62;
53507
- void writer.abort(error62).catch(() => {
53508
- });
53509
- return;
53510
- }
53511
- void writer.write(chunk).catch(() => {
53512
- });
53513
- if (final) void writer.close().catch(() => {
53514
- });
53515
- });
53516
- const add = /* @__PURE__ */ __name((entry, data) => {
53517
- zip.add(entry);
53518
- entry.push(data, true);
53519
- }, "add");
53980
+ const zip = new ZipWriter((chunk) => writer.write(chunk));
53981
+ const text2 = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value), "text");
53520
53982
  void (async () => {
53521
53983
  try {
53522
53984
  const missing = /* @__PURE__ */ new Set();
53523
53985
  for (const file2 of files) if (!await this.deps.storage.exists(file2.storageKey)) missing.add(file2.path);
53524
53986
  const about = { format: EXPORT_FORMAT, version: 1, app: VERSION, exportedAt: now.toISOString(), workspaces: summary, missingAttachments: [...missing].map((path2) => path2.slice(root.length + 1)) };
53525
- add(new ZipDeflate(`${root}/export.json`, { level: 6 }), strToU8(`${JSON.stringify(about, null, 2)}
53526
- `));
53527
- for (const [path2, text2] of texts) add(new ZipDeflate(path2, { level: 6 }), strToU8(text2));
53987
+ await zip.add(`${root}/export.json`, text2(`${JSON.stringify(about, null, 2)}
53988
+ `), now);
53989
+ for (const [path2, content] of texts) await zip.add(path2, text2(content), now);
53528
53990
  for (const file2 of files) {
53529
53991
  const body = missing.has(file2.path) ? null : await this.deps.storage.stream(file2.storageKey);
53530
- if (!body) continue;
53531
- const entry = new ZipPassThrough(file2.path);
53532
- zip.add(entry);
53533
- const reader = body.getReader();
53534
- for (; ; ) {
53535
- await writer.ready;
53536
- const { value, done } = await reader.read();
53537
- if (done) break;
53538
- if (failed) throw failed;
53539
- entry.push(value);
53540
- }
53541
- entry.push(new Uint8Array(0), true);
53992
+ if (body) await zip.addStream(file2.path, file2.size, body, now);
53542
53993
  }
53543
- zip.end();
53994
+ await zip.end();
53995
+ await writer.close();
53544
53996
  } catch (error62) {
53545
53997
  console.error("[export] failed", error62);
53546
53998
  await writer.abort(error62).catch(() => {
@@ -53666,9 +54118,9 @@ var ExportService = class {
53666
54118
  boards: boardsOf(project.id).map((board) => ({
53667
54119
  name: board.name,
53668
54120
  labels: labelsOf(board.id).map((l) => ({ name: l.name, color: l.color })),
53669
- columns: columnsOf(board.id).map((column) => ({
53670
- name: column.name,
53671
- cards: cardsOf(column.id).map((card) => ({
54121
+ columns: columnsOf(board.id).map((column2) => ({
54122
+ name: column2.name,
54123
+ cards: cardsOf(column2.id).map((card) => ({
53672
54124
  // What references to this task (#<id> after tasks.json) point at.
53673
54125
  id: card.id,
53674
54126
  title: card.title,
@@ -53677,7 +54129,8 @@ var ExportService = class {
53677
54129
  due: day(card.dueAt),
53678
54130
  archived: card.archivedAt !== null,
53679
54131
  checklists: checklistsOf(card.id).map((list) => ({ title: list.title, items: itemsOf(list.id).map((i2) => ({ text: i2.text, done: i2.done })) })),
53680
- documents: linksOf(card.id).map((link) => pagePath.get(link.pageId)).filter(Boolean),
54132
+ // A document linked by hand and mentioned too is one document.
54133
+ documents: [...new Set(linksOf(card.id).map((link) => pagePath.get(link.pageId)))].filter(Boolean),
53681
54134
  attachments: filesOf(card.id).map((f) => filePath.get(f.id)),
53682
54135
  createdAt: iso(card.createdAt),
53683
54136
  updatedAt: iso(card.updatedAt)
@@ -53841,6 +54294,13 @@ var HistoryService = class {
53841
54294
  * Forgets the history of what a trash entry holds, as it is deleted for good: the pages and
53842
54295
  * cards in it, and the checklists, items and files it took from a card or a page.
53843
54296
  */
54297
+ /** Forgets the history of things deleted for good, by their ids: as the page or card, or what a change is about. */
54298
+ forgetIds(db, ids) {
54299
+ for (let i2 = 0; i2 < ids.length; i2 += 500) {
54300
+ const chunk = ids.slice(i2, i2 + 500);
54301
+ db.delete(history).where(or(inList(history.entityId, chunk), inList(history.subjectId, chunk))).run();
54302
+ }
54303
+ }
53844
54304
  forget(db, trashId) {
53845
54305
  const ids = sql`SELECT json_extract(data, '$.id') FROM trash_rows WHERE trash_id = ${trashId}`;
53846
54306
  db.delete(history).where(or(sql`${history.entityId} IN (${ids})`, sql`${history.subjectId} IN (${ids})`)).run();
@@ -53951,8 +54411,763 @@ var SearchService = class {
53951
54411
  }
53952
54412
  };
53953
54413
 
54414
+ // src/services/trash-tree.ts
54415
+ var SEPARATOR = " \u203A ";
54416
+ var NODE_KIND = {
54417
+ projects: "project",
54418
+ boards: "board",
54419
+ board_columns: "column",
54420
+ labels: "label",
54421
+ cards: "card",
54422
+ checklists: "checklist",
54423
+ checklist_items: "checklist_item",
54424
+ pages: "page",
54425
+ attachments: "attachment"
54426
+ };
54427
+ var LIVE_TABLE = {
54428
+ project: "projects",
54429
+ board: "boards",
54430
+ column: "board_columns",
54431
+ label: "labels",
54432
+ card: "cards",
54433
+ checklist: "checklists",
54434
+ checklist_item: "checklist_items",
54435
+ page: "pages",
54436
+ attachment: "attachments"
54437
+ };
54438
+ var LIVE_COLUMNS = {
54439
+ project: sql`id, name`,
54440
+ board: sql`id, name, project_id`,
54441
+ column: sql`id, name, board_id`,
54442
+ label: sql`id, name, board_id`,
54443
+ card: sql`id, title AS name, column_id, board_id`,
54444
+ checklist: sql`id, title AS name, card_id`,
54445
+ checklist_item: sql`id, text AS name, checklist_id`,
54446
+ page: sql`id, title AS name, project_id, parent_id`,
54447
+ attachment: sql`id, filename AS name, card_id, page_id`
54448
+ };
54449
+ var RANK = { project: 0, board: 1, column: 2, label: 3, card: 4, checklist: 5, checklist_item: 6, page: 7, attachment: 8, link: 9 };
54450
+ var COUNTED = {
54451
+ project: "projects",
54452
+ board: "boards",
54453
+ column: "columns",
54454
+ card: "cards",
54455
+ page: "pages",
54456
+ attachment: "attachments",
54457
+ checklist: "checklists",
54458
+ checklist_item: "items",
54459
+ label: "labels",
54460
+ link: "links"
54461
+ };
54462
+ var CHOOSE = {
54463
+ project: [],
54464
+ board: ["project"],
54465
+ column: ["board"],
54466
+ label: ["board"],
54467
+ card: ["column"],
54468
+ checklist: ["card"],
54469
+ checklist_item: ["checklist"],
54470
+ page: ["project", "page"],
54471
+ attachment: ["card", "page"],
54472
+ link: []
54473
+ };
54474
+ var NAMED = /* @__PURE__ */ new Set(["project", "board", "column", "label", "card", "page", "attachment"]);
54475
+ var NAME_MAX = { project: 80, board: 80, column: 60, label: 40, card: 300, page: 200, attachment: 180 };
54476
+ var NAME_COLUMN = { project: "name", board: "name", column: "name", label: "name", card: "title", page: "title", attachment: "filename" };
54477
+ var keyOf = /* @__PURE__ */ __name((kind, id3) => `${kind}:${id3}`, "keyOf");
54478
+ var refKey = /* @__PURE__ */ __name((ref) => keyOf(ref.kind, ref.id), "refKey");
54479
+ var norm = /* @__PURE__ */ __name((name2) => name2.normalize("NFC").trim().toLowerCase(), "norm");
54480
+ var Live = class {
54481
+ constructor(db, workspaceId) {
54482
+ this.db = db;
54483
+ this.workspaceId = workspaceId;
54484
+ }
54485
+ db;
54486
+ workspaceId;
54487
+ static {
54488
+ __name(this, "Live");
54489
+ }
54490
+ rows = /* @__PURE__ */ new Map();
54491
+ /** Looks up many at once: SQLite in a Durable Object takes at most 100 parameters a query. */
54492
+ prefetch(kind, ids) {
54493
+ const unknown2 = [...new Set(ids)].filter((id3) => !this.rows.has(keyOf(kind, id3)));
54494
+ for (let i2 = 0; i2 < unknown2.length; i2 += 500) {
54495
+ const chunk = unknown2.slice(i2, i2 + 500);
54496
+ const found = this.db.all(
54497
+ sql`SELECT ${LIVE_COLUMNS[kind]} FROM ${sql.identifier(LIVE_TABLE[kind])} WHERE workspace_id = ${this.workspaceId} AND ${inList(sql`id`, chunk)}`
54498
+ );
54499
+ const byId = new Map(found.map((row) => [row.id, row]));
54500
+ for (const id3 of chunk) this.rows.set(keyOf(kind, id3), byId.get(id3) ?? null);
54501
+ }
54502
+ }
54503
+ get(kind, id3) {
54504
+ if (!id3) return null;
54505
+ const key = keyOf(kind, id3);
54506
+ if (!this.rows.has(key)) this.prefetch(kind, [id3]);
54507
+ return this.rows.get(key) ?? null;
54508
+ }
54509
+ exists(kind, id3) {
54510
+ return this.get(kind, id3) !== null;
54511
+ }
54512
+ /** The names from the top down to it, its own included: "Project › Board › Column". */
54513
+ path(ref, depth = 0) {
54514
+ if (!ref || depth > 64) return [];
54515
+ const row = this.get(ref.kind, ref.id);
54516
+ if (!row) return [];
54517
+ const name2 = row.name ?? "";
54518
+ const up = /* @__PURE__ */ __name((kind, id3) => id3 ? this.path({ kind, id: id3 }, depth + 1) : [], "up");
54519
+ switch (ref.kind) {
54520
+ case "project":
54521
+ return [name2];
54522
+ case "board":
54523
+ return [...up("project", row.project_id), name2];
54524
+ case "column":
54525
+ case "label":
54526
+ case "card":
54527
+ return [...up("board", row.board_id), name2];
54528
+ case "checklist":
54529
+ return [...up("card", row.card_id), name2];
54530
+ case "checklist_item":
54531
+ return [...up("checklist", row.checklist_id), name2];
54532
+ case "page":
54533
+ return [...row.parent_id ? up("page", row.parent_id) : up("project", row.project_id), name2];
54534
+ case "attachment":
54535
+ return [...row.card_id ? up("card", row.card_id) : up("page", row.page_id), name2];
54536
+ }
54537
+ }
54538
+ /** How many columns a board has now. */
54539
+ columnCount(boardId) {
54540
+ return this.db.get(sql`SELECT count(*) AS total FROM board_columns WHERE board_id = ${boardId}`)?.total ?? 0;
54541
+ }
54542
+ /** The names of what is next to where something of `kind` goes, in `container`. */
54543
+ siblingNames(kind, container) {
54544
+ const names = /* @__PURE__ */ __name((query) => this.db.all(query).map((r) => r.name), "names");
54545
+ const ws = this.workspaceId;
54546
+ switch (kind) {
54547
+ case "project":
54548
+ return names(sql`SELECT name FROM projects WHERE workspace_id = ${ws}`);
54549
+ case "board":
54550
+ return container ? names(sql`SELECT name FROM boards WHERE project_id = ${container.id}`) : [];
54551
+ case "column":
54552
+ return container ? names(sql`SELECT name FROM board_columns WHERE board_id = ${container.id}`) : [];
54553
+ case "label":
54554
+ return container ? names(sql`SELECT name FROM labels WHERE board_id = ${container.id}`) : [];
54555
+ case "card":
54556
+ return container ? names(sql`SELECT title AS name FROM cards WHERE column_id = ${container.id} AND archived_at IS NULL`) : [];
54557
+ case "page":
54558
+ if (!container) return [];
54559
+ return container.kind === "page" ? names(sql`SELECT title AS name FROM pages WHERE parent_id = ${container.id}`) : names(sql`SELECT title AS name FROM pages WHERE project_id = ${container.id} AND parent_id IS NULL`);
54560
+ case "attachment":
54561
+ if (!container) return [];
54562
+ return container.kind === "card" ? names(sql`SELECT filename AS name FROM attachments WHERE card_id = ${container.id}`) : names(sql`SELECT filename AS name FROM attachments WHERE page_id = ${container.id}`);
54563
+ default:
54564
+ return [];
54565
+ }
54566
+ }
54567
+ };
54568
+ function parentRef(kind, row) {
54569
+ const ref = /* @__PURE__ */ __name((k, id3) => id3 ? { kind: k, id: id3 } : null, "ref");
54570
+ switch (kind) {
54571
+ case "project":
54572
+ return null;
54573
+ case "board":
54574
+ return ref("project", row.projectId);
54575
+ case "column":
54576
+ case "label":
54577
+ return ref("board", row.boardId);
54578
+ case "card":
54579
+ return ref("column", row.columnId);
54580
+ case "checklist":
54581
+ return ref("card", row.cardId);
54582
+ case "checklist_item":
54583
+ return ref("checklist", row.checklistId);
54584
+ case "page":
54585
+ return row.parentId ? ref("page", row.parentId) : ref("project", row.projectId);
54586
+ case "attachment":
54587
+ return row.cardId ? ref("card", row.cardId) : ref("page", row.pageId);
54588
+ case "link":
54589
+ return ref("card", row.cardId);
54590
+ }
54591
+ }
54592
+ __name(parentRef, "parentRef");
54593
+ var byPosition = /* @__PURE__ */ __name((a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1, "byPosition");
54594
+ var byOrder = /* @__PURE__ */ __name((a, b) => RANK[a.kind] - RANK[b.kind] || byPosition(a.row.position, b.row.position) || a.title.localeCompare(b.title) || a.entry.deletedAt.getTime() - b.entry.deletedAt.getTime() || a.row.rowId - b.row.rowId, "byOrder");
54595
+ var TrashIndex = class _TrashIndex {
54596
+ static {
54597
+ __name(this, "TrashIndex");
54598
+ }
54599
+ nodes = /* @__PURE__ */ new Map();
54600
+ /** Rows joining two things (a card's label, a card and a page) that are not things of their own. */
54601
+ relations = [];
54602
+ /** Links made by a page mentioning a card: never put back, they are rebuilt from what pages say. */
54603
+ mentions = [];
54604
+ entries = /* @__PURE__ */ new Map();
54605
+ live;
54606
+ constructor(db, workspaceId) {
54607
+ this.live = new Live(db, workspaceId);
54608
+ }
54609
+ static load(db, workspaceId) {
54610
+ const index3 = new _TrashIndex(db, workspaceId);
54611
+ for (const entry of db.select().from(trash).where(eq(trash.workspaceId, workspaceId)).all()) index3.entries.set(entry.id, entry);
54612
+ const rows = db.all(sql`
54613
+ SELECT r.id AS rowId, r.trash_id AS trashId, r.table_name AS tableName,
54614
+ json_extract(r.data, '$.id') AS id,
54615
+ coalesce(json_extract(r.data, '$.name'), json_extract(r.data, '$.title'), json_extract(r.data, '$.filename'), json_extract(r.data, '$.text')) AS name,
54616
+ json_extract(r.data, '$.project_id') AS projectId,
54617
+ json_extract(r.data, '$.board_id') AS boardId,
54618
+ json_extract(r.data, '$.column_id') AS columnId,
54619
+ json_extract(r.data, '$.card_id') AS cardId,
54620
+ json_extract(r.data, '$.checklist_id') AS checklistId,
54621
+ json_extract(r.data, '$.parent_id') AS parentId,
54622
+ json_extract(r.data, '$.page_id') AS pageId,
54623
+ json_extract(r.data, '$.label_id') AS labelId,
54624
+ json_extract(r.data, '$.size') AS size,
54625
+ json_extract(r.data, '$.source') AS source,
54626
+ json_extract(r.data, '$.position') AS position,
54627
+ r.storage_key AS storageKey
54628
+ FROM trash_rows r JOIN trash t ON t.id = r.trash_id
54629
+ WHERE t.workspace_id = ${workspaceId}
54630
+ ORDER BY r.id`);
54631
+ for (const { tableName, ...rest } of rows) {
54632
+ const row = { ...rest, table: tableName };
54633
+ const entry = index3.entries.get(row.trashId);
54634
+ if (!entry) continue;
54635
+ const kind = NODE_KIND[row.table];
54636
+ if (kind && row.id) {
54637
+ index3.add(kind, row.id, row, entry);
54638
+ } else if (row.table === "card_page_links") {
54639
+ if (row.source === "mention") index3.mentions.push(row);
54640
+ else if (entry.kind === "link" && entry.entityId === `${row.cardId}:${row.pageId}`) index3.add("link", `${row.cardId}:${row.pageId}`, row, entry);
54641
+ else index3.relations.push(row);
54642
+ } else if (row.table === "card_labels") {
54643
+ index3.relations.push(row);
54644
+ }
54645
+ }
54646
+ index3.resolve();
54647
+ return index3;
54648
+ }
54649
+ add(kind, id3, row, entry) {
54650
+ const key = kind === "link" ? `link:${id3}` : keyOf(kind, id3);
54651
+ this.nodes.set(key, {
54652
+ key,
54653
+ kind,
54654
+ id: id3,
54655
+ row,
54656
+ entry,
54657
+ title: row.name ?? "",
54658
+ ref: parentRef(kind, row),
54659
+ parent: null,
54660
+ children: [],
54661
+ place: "original",
54662
+ entryRoot: entry.kind === kind && entry.entityId === id3
54663
+ });
54664
+ }
54665
+ /** Hangs each node from what held it, and says where the rest goes back. */
54666
+ resolve() {
54667
+ const missing = /* @__PURE__ */ new Map();
54668
+ for (const node2 of this.nodes.values()) {
54669
+ if (!node2.ref) continue;
54670
+ const parent = this.nodes.get(refKey(node2.ref));
54671
+ if (parent && parent !== node2) {
54672
+ node2.parent = parent;
54673
+ parent.children.push(node2);
54674
+ node2.place = "trash";
54675
+ } else {
54676
+ const ids = missing.get(node2.ref.kind) ?? /* @__PURE__ */ new Set();
54677
+ ids.add(node2.ref.id);
54678
+ missing.set(node2.ref.kind, ids);
54679
+ }
54680
+ }
54681
+ for (const [kind, ids] of missing) this.live.prefetch(kind, ids);
54682
+ this.live.prefetch("page", [...this.nodes.values()].filter((n) => n.kind === "link" && !this.nodes.has(keyOf("page", n.row.pageId ?? ""))).map((n) => n.row.pageId ?? ""));
54683
+ for (const node2 of this.nodes.values()) {
54684
+ if (node2.ref && !node2.parent) node2.place = this.live.exists(node2.ref.kind, node2.ref.id) ? "original" : "gone";
54685
+ if (node2.kind === "link") node2.title = this.nodes.get(keyOf("page", node2.row.pageId ?? ""))?.title ?? this.live.get("page", node2.row.pageId)?.name ?? "";
54686
+ node2.children.sort(byOrder);
54687
+ }
54688
+ for (const node2 of this.nodes.values()) {
54689
+ const seen = /* @__PURE__ */ new Set();
54690
+ for (let up = node2.parent; up; up = up.parent) {
54691
+ if (seen.has(up) || up === node2) {
54692
+ node2.parent?.children.splice(node2.parent.children.indexOf(node2), 1);
54693
+ node2.parent = null;
54694
+ node2.place = "gone";
54695
+ break;
54696
+ }
54697
+ seen.add(up);
54698
+ }
54699
+ }
54700
+ }
54701
+ node(key) {
54702
+ return this.nodes.get(key);
54703
+ }
54704
+ /** What is at the top: what is not held by anything else in the trash. Newest first. */
54705
+ top() {
54706
+ return [...this.nodes.values()].filter((n) => !n.parent).sort((a, b) => b.entry.deletedAt.getTime() - a.entry.deletedAt.getTime() || b.row.rowId - a.row.rowId);
54707
+ }
54708
+ /** The node and everything below it, each before what it holds. */
54709
+ subtree(node2) {
54710
+ const out = [];
54711
+ const walk = /* @__PURE__ */ __name((n) => {
54712
+ out.push(n);
54713
+ for (const child of n.children) walk(child);
54714
+ }, "walk");
54715
+ walk(node2);
54716
+ return out;
54717
+ }
54718
+ /** What holds it in the trash, top first. */
54719
+ ancestors(node2) {
54720
+ const out = [];
54721
+ for (let up = node2.parent; up; up = up.parent) out.unshift(up);
54722
+ return out;
54723
+ }
54724
+ /** Of `nodes`, those not below another one of them: what is below one comes with it. */
54725
+ outermost(nodes) {
54726
+ const picked = new Set(nodes);
54727
+ return [...picked].filter((node2) => !this.ancestors(node2).some((up) => picked.has(up)));
54728
+ }
54729
+ /**
54730
+ * What deleting `nodes` for good takes: everything below them, and the links to a page that goes
54731
+ * (with what is below them), wherever those wait in the trash.
54732
+ */
54733
+ goneWith(nodes) {
54734
+ const gone = /* @__PURE__ */ new Map();
54735
+ for (const node2 of nodes) for (const n of this.subtree(node2)) gone.set(n.key, n);
54736
+ for (const n of this.nodes.values()) if (n.kind === "link" && gone.has(`page:${n.row.pageId}`)) for (const m of this.subtree(n)) gone.set(m.key, m);
54737
+ return gone;
54738
+ }
54739
+ /** Everything deleting `nodes` for good takes (see goneWith), by kind, and the size of its files. */
54740
+ totals(nodes) {
54741
+ const all = this.goneWith(nodes);
54742
+ const contents = {};
54743
+ let bytes = 0;
54744
+ for (const n of all.values()) {
54745
+ if (n.kind === "attachment") bytes += Number(n.row.size ?? 0);
54746
+ const counted = COUNTED[n.kind];
54747
+ if (counted) contents[counted] = (contents[counted] ?? 0) + 1;
54748
+ }
54749
+ return { contents, bytes };
54750
+ }
54751
+ /** Whether `node` is `top` or below it. */
54752
+ within(node2, top) {
54753
+ for (let n = node2; n; n = n.parent) if (n === top) return true;
54754
+ return false;
54755
+ }
54756
+ /** Where it goes back, for people: "Project › Board" when that is there; where it was when that is gone. */
54757
+ location(node2) {
54758
+ if (node2.parent) return "";
54759
+ if (node2.place === "gone") return node2.entryRoot ? node2.entry.location : "";
54760
+ return this.live.path(node2.ref).join(SEPARATOR);
54761
+ }
54762
+ dto(node2) {
54763
+ const contents = {};
54764
+ const earlierContents = {};
54765
+ let bytes = 0;
54766
+ for (const n of this.subtree(node2)) {
54767
+ if (n.kind === "attachment") bytes += Number(n.row.size ?? 0);
54768
+ if (n === node2) continue;
54769
+ const counted = COUNTED[n.kind];
54770
+ if (!counted) continue;
54771
+ contents[counted] = (contents[counted] ?? 0) + 1;
54772
+ if (isEarlier(n)) earlierContents[counted] = (earlierContents[counted] ?? 0) + 1;
54773
+ }
54774
+ const entry = node2.entry;
54775
+ return {
54776
+ key: node2.key,
54777
+ kind: node2.kind,
54778
+ entityId: node2.id,
54779
+ title: node2.title,
54780
+ parentKey: node2.parent?.key ?? null,
54781
+ trashId: entry.id,
54782
+ place: node2.place,
54783
+ location: this.location(node2),
54784
+ earlier: isEarlier(node2),
54785
+ contents,
54786
+ earlierContents,
54787
+ bytes,
54788
+ deletedBy: actorOf(entry),
54789
+ deletedAt: entry.deletedAt.toISOString(),
54790
+ expiresAt: entry.expiresAt.toISOString()
54791
+ };
54792
+ }
54793
+ tree(node2) {
54794
+ return { node: this.dto(node2), below: this.subtree(node2).slice(1).map((n) => this.dto(n)), ancestors: this.ancestors(node2).map((n) => ({ key: n.key, kind: n.kind, title: n.title, trashId: n.entry.id })) };
54795
+ }
54796
+ };
54797
+ var isEarlier = /* @__PURE__ */ __name((node2) => node2.parent !== null && node2.parent.entry.id !== node2.entry.id, "isEarlier");
54798
+ var actorOf = /* @__PURE__ */ __name((entry) => ({
54799
+ kind: entry.actorKind,
54800
+ id: (entry.actorKind === "agent" ? entry.actorTokenId : entry.actorUserId) ?? "",
54801
+ name: entry.actorName
54802
+ }), "actorOf");
54803
+ var restoreError = /* @__PURE__ */ __name((code, message, details) => new AppError(409, code, message, details), "restoreError");
54804
+ function remainder(location, prefix) {
54805
+ const start = prefix.join(SEPARATOR);
54806
+ if (start && location.startsWith(start + SEPARATOR)) return location.slice(start.length + SEPARATOR.length);
54807
+ return location.split(SEPARATOR).at(-1) ?? location;
54808
+ }
54809
+ __name(remainder, "remainder");
54810
+ function creatable(index3, node2) {
54811
+ if (!node2.entryRoot) return null;
54812
+ const live = index3.live;
54813
+ const location = node2.entry.location;
54814
+ const made = /* @__PURE__ */ __name((kind, title, where) => [{ kind, id: crypto.randomUUID(), title: title.trim() || "Restored", in: where }], "made");
54815
+ switch (node2.kind) {
54816
+ case "board":
54817
+ return made("project", location, null);
54818
+ case "page":
54819
+ if (!node2.row.parentId) return made("project", location, null);
54820
+ if (!live.exists("project", node2.row.projectId)) return null;
54821
+ return made("page", remainder(location, live.path({ kind: "project", id: node2.row.projectId })), { kind: "project", id: node2.row.projectId });
54822
+ case "card":
54823
+ if (!live.exists("board", node2.row.boardId)) return null;
54824
+ return made("column", remainder(location, live.path({ kind: "board", id: node2.row.boardId })), { kind: "board", id: node2.row.boardId });
54825
+ default:
54826
+ return null;
54827
+ }
54828
+ }
54829
+ __name(creatable, "creatable");
54830
+ function planRestore(index3, input2) {
54831
+ const root = index3.node(input2.key);
54832
+ if (!root) throw notFound("Trash item");
54833
+ const live = index3.live;
54834
+ const subtree = index3.subtree(root);
54835
+ const asked = new Set(input2.exclude);
54836
+ asked.delete(root.key);
54837
+ const excluded = /* @__PURE__ */ new Set();
54838
+ for (const n of subtree) if (asked.has(n.key) || n.parent && excluded.has(n.parent.key)) excluded.add(n.key);
54839
+ const included = subtree.filter((n) => !excluded.has(n.key));
54840
+ let choose = CHOOSE[root.kind];
54841
+ let path2 = [];
54842
+ let create = [];
54843
+ let canRecreate = false;
54844
+ if (root.place === "trash") {
54845
+ path2 = index3.ancestors(root);
54846
+ const top = path2[0];
54847
+ const made = top.place === "gone" ? creatable(index3, top) : [];
54848
+ if (made) {
54849
+ create = made;
54850
+ canRecreate = true;
54851
+ }
54852
+ } else if (root.place === "gone") {
54853
+ const made = creatable(index3, root);
54854
+ if (made) {
54855
+ create = made;
54856
+ canRecreate = true;
54857
+ }
54858
+ }
54859
+ const linkPageGone = root.kind === "link" && !index3.node(keyOf("page", root.row.pageId ?? "")) && !live.exists("page", root.row.pageId);
54860
+ if (linkPageGone) {
54861
+ choose = [];
54862
+ canRecreate = false;
54863
+ }
54864
+ let to = input2.to?.kind ?? (root.place === "original" ? "original" : canRecreate ? "recreate" : null);
54865
+ if (linkPageGone || to === "original" && root.place !== "original") to = null;
54866
+ if (to === "recreate" && root.place === "original") to = "original";
54867
+ if (to === "recreate" && !canRecreate) to = null;
54868
+ let other = null;
54869
+ if (to === "other" && input2.to?.kind === "other") {
54870
+ const chosen = input2.to.parent;
54871
+ if (!choose.includes(chosen.kind) || !live.exists(chosen.kind, chosen.id)) throw restoreError("restore_place_gone", "The place chosen to put it in is not there.");
54872
+ other = chosen;
54873
+ }
54874
+ const recreatePath = path2;
54875
+ const recreateCreate = create;
54876
+ if (to !== "recreate") {
54877
+ path2 = [];
54878
+ create = [];
54879
+ }
54880
+ const comingKeys = /* @__PURE__ */ new Set();
54881
+ const coming = [];
54882
+ const add = /* @__PURE__ */ __name((n) => {
54883
+ if (comingKeys.has(n.key)) return;
54884
+ comingKeys.add(n.key);
54885
+ coming.push(n);
54886
+ }, "add");
54887
+ for (const n of path2) add(n);
54888
+ for (const n of included) add(n);
54889
+ const canInclude = /* @__PURE__ */ __name((n) => !comingKeys.has(n.key) && !index3.within(n, root) && (n.place === "original" || n.parent !== null && comingKeys.has(n.parent.key)), "canInclude");
54890
+ const relationRows = /* @__PURE__ */ __name((keys) => {
54891
+ const linkNodes = [...keys].map((k) => index3.node(k)).filter((n) => n.kind === "link");
54892
+ return [
54893
+ ...index3.relations.filter((r) => keys.has(keyOf("card", r.cardId ?? "")) || keys.has(r.table === "card_labels" ? keyOf("label", r.labelId ?? "") : keyOf("page", r.pageId ?? ""))),
54894
+ ...linkNodes.map((n) => n.row)
54895
+ ];
54896
+ }, "relationRows");
54897
+ const otherEnds = /* @__PURE__ */ new Map();
54898
+ for (const r of relationRows(comingKeys)) {
54899
+ for (const key of [keyOf("card", r.cardId ?? ""), r.table === "card_labels" ? keyOf("label", r.labelId ?? "") : keyOf("page", r.pageId ?? "")]) {
54900
+ const n = index3.node(key);
54901
+ if (n && canInclude(n)) otherEnds.set(key, n);
54902
+ }
54903
+ }
54904
+ const extraRoots = [];
54905
+ for (const key of new Set(input2.include)) {
54906
+ const n = otherEnds.get(key);
54907
+ if (n) extraRoots.push(n);
54908
+ else if (!input2.dryRun) throw restoreError("restore_changed", "Something in the trash changed meanwhile: look again before restoring.");
54909
+ }
54910
+ const own2 = new Set(comingKeys);
54911
+ const extras = [];
54912
+ for (const n of extraRoots) for (const below of index3.subtree(n)) if (!comingKeys.has(below.key)) extras.push(below);
54913
+ for (const n of extras) add(n);
54914
+ const createdById = new Map(create.map((c) => [c.id, c]));
54915
+ const lastMade = create.at(-1);
54916
+ const madeRef = /* @__PURE__ */ __name((c) => ({ kind: c.kind, id: c.id }), "madeRef");
54917
+ const finalBoard = /* @__PURE__ */ new Map();
54918
+ const finalProject = /* @__PURE__ */ new Map();
54919
+ const boardOfColumn = /* @__PURE__ */ __name((id3) => {
54920
+ const made = createdById.get(id3);
54921
+ if (made) return made.in?.id ?? null;
54922
+ return finalBoard.has(keyOf("column", id3)) ? finalBoard.get(keyOf("column", id3)) : live.get("column", id3)?.board_id ?? null;
54923
+ }, "boardOfColumn");
54924
+ const projectOfPage = /* @__PURE__ */ __name((id3) => {
54925
+ const made = createdById.get(id3);
54926
+ if (made) return made.in?.id ?? null;
54927
+ return finalProject.has(keyOf("page", id3)) ? finalProject.get(keyOf("page", id3)) : live.get("page", id3)?.project_id ?? null;
54928
+ }, "projectOfPage");
54929
+ const placement = /* @__PURE__ */ new Map();
54930
+ for (const n of coming) {
54931
+ if (!n.ref) continue;
54932
+ let container = n.ref;
54933
+ let moved = false;
54934
+ if (lastMade && (n === path2[0] || n === root && root.place === "gone")) {
54935
+ container = madeRef(lastMade);
54936
+ moved = true;
54937
+ }
54938
+ if (n === root && other) {
54939
+ container = other;
54940
+ moved = true;
54941
+ }
54942
+ const sets = {};
54943
+ switch (n.kind) {
54944
+ case "board":
54945
+ sets.project_id = container.id;
54946
+ finalProject.set(n.key, container.id);
54947
+ break;
54948
+ case "column":
54949
+ case "label":
54950
+ sets.board_id = container.id;
54951
+ finalBoard.set(n.key, container.id);
54952
+ break;
54953
+ case "card": {
54954
+ const board = boardOfColumn(container.id);
54955
+ sets.column_id = container.id;
54956
+ sets.board_id = board;
54957
+ finalBoard.set(n.key, board);
54958
+ break;
54959
+ }
54960
+ case "checklist":
54961
+ sets.card_id = container.id;
54962
+ break;
54963
+ case "checklist_item":
54964
+ sets.checklist_id = container.id;
54965
+ break;
54966
+ case "page": {
54967
+ const project = container.kind === "page" ? projectOfPage(container.id) : container.id;
54968
+ sets.parent_id = container.kind === "page" ? container.id : null;
54969
+ sets.project_id = project;
54970
+ finalProject.set(n.key, project);
54971
+ break;
54972
+ }
54973
+ case "attachment":
54974
+ sets.card_id = container.kind === "card" ? container.id : null;
54975
+ sets.page_id = container.kind === "page" ? container.id : null;
54976
+ break;
54977
+ }
54978
+ placement.set(n.key, { container, moved, sets });
54979
+ }
54980
+ const state = /* @__PURE__ */ __name((kind, id3) => {
54981
+ if (!id3) return "gone";
54982
+ const key = keyOf(kind, id3);
54983
+ if (comingKeys.has(key)) return "coming";
54984
+ if (index3.node(key)) return "trash";
54985
+ return live.exists(kind, id3) ? "live" : "gone";
54986
+ }, "state");
54987
+ const rows = relationRows(comingKeys);
54988
+ live.prefetch("card", rows.map((r) => r.cardId ?? ""));
54989
+ live.prefetch("label", rows.filter((r) => r.table === "card_labels").map((r) => r.labelId ?? ""));
54990
+ live.prefetch("page", rows.filter((r) => r.table === "card_page_links").map((r) => r.pageId ?? ""));
54991
+ const boardOfCard = /* @__PURE__ */ __name((id3) => finalBoard.has(keyOf("card", id3)) ? finalBoard.get(keyOf("card", id3)) : live.get("card", id3)?.board_id ?? null, "boardOfCard");
54992
+ const boardOfLabel = /* @__PURE__ */ __name((id3) => finalBoard.has(keyOf("label", id3)) ? finalBoard.get(keyOf("label", id3)) : live.get("label", id3)?.board_id ?? null, "boardOfLabel");
54993
+ const titleOf = /* @__PURE__ */ __name((kind, id3) => index3.node(keyOf(kind, id3))?.title ?? live.get(kind, id3)?.name ?? "", "titleOf");
54994
+ const extraKeys = new Set(extraRoots.map((n) => n.key));
54995
+ const reinsert = [];
54996
+ const wait = [];
54997
+ const drop = [];
54998
+ const groups = /* @__PURE__ */ new Map();
54999
+ const note = /* @__PURE__ */ __name((group, first) => {
55000
+ const id3 = `${group.state}|${group.kind}|${group.key ?? group.title}`;
55001
+ const found = groups.get(id3);
55002
+ if (found) found.count++;
55003
+ else groups.set(id3, { ...group, count: 1, first });
55004
+ }, "note");
55005
+ for (const r of rows) {
55006
+ const cardId = r.cardId ?? "";
55007
+ const isLabel = r.table === "card_labels";
55008
+ const otherKind = isLabel ? "label" : "page";
55009
+ const otherId = (isLabel ? r.labelId : r.pageId) ?? "";
55010
+ const ends = [
55011
+ { kind: "card", id: cardId, state: state("card", cardId) },
55012
+ { kind: otherKind, id: otherId, state: state(otherKind, otherId) }
55013
+ ];
55014
+ const isLinkNode = r.table === "card_page_links" && index3.node(`link:${cardId}:${otherId}`)?.row === r;
55015
+ const near = isLinkNode ? ends[0] : ends.find((e) => own2.has(keyOf(e.kind, e.id))) ?? ends.find((e) => e.state === "coming");
55016
+ if (!near) continue;
55017
+ const far = ends.find((e) => e !== near);
55018
+ const shown = extraKeys.has(keyOf(far.kind, far.id));
55019
+ if (shown) note({ kind: far.kind, title: titleOf(far.kind, far.id), key: keyOf(far.kind, far.id), state: "trash", included: true, canInclude: true }, titleOf(near.kind, near.id));
55020
+ if (far.state === "coming" || far.state === "live") {
55021
+ if (isLabel && boardOfCard(cardId) !== boardOfLabel(otherId)) {
55022
+ drop.push(r);
55023
+ note({ kind: "label", title: titleOf("label", otherId), key: index3.node(keyOf("label", otherId)) ? keyOf("label", otherId) : null, state: "other_board", included: false, canInclude: false }, titleOf("card", cardId));
55024
+ } else if (!isLinkNode) {
55025
+ reinsert.push(r);
55026
+ }
55027
+ } else if (far.state === "trash") {
55028
+ const holder = index3.node(keyOf(far.kind, far.id));
55029
+ if (r.trashId !== holder.entry.id) wait.push({ row: r, trashId: holder.entry.id });
55030
+ note({ kind: far.kind, title: holder.title, key: holder.key, state: "trash", included: false, canInclude: canInclude(holder) }, titleOf(near.kind, near.id));
55031
+ } else {
55032
+ drop.push(r);
55033
+ note({ kind: far.kind, title: "", key: null, state: "gone", included: false, canInclude: false }, titleOf(near.kind, near.id));
55034
+ }
55035
+ }
55036
+ const waitingLinks = new Set([...wait.map((w) => w.row), ...drop].filter((r) => r.table === "card_page_links").map((r) => `link:${r.cardId}:${r.pageId}`));
55037
+ const names = /* @__PURE__ */ new Map();
55038
+ for (const [key, value] of Object.entries(input2.names)) {
55039
+ const n = index3.node(key);
55040
+ if (!n || !comingKeys.has(key) || !NAMED.has(n.kind)) continue;
55041
+ const max2 = NAME_MAX[n.kind] ?? 300;
55042
+ if (value.length > max2) throw badRequest(`A ${n.kind} name has at most ${max2} characters`);
55043
+ const stored = n.kind === "attachment" ? safeFilename(value) : value;
55044
+ if (stored !== n.title) names.set(key, stored);
55045
+ }
55046
+ const keep = new Set(input2.keepNames);
55047
+ const conflicts = [];
55048
+ const madeIds = new Set(create.map((c) => c.id));
55049
+ const containerName = /* @__PURE__ */ __name((ref) => {
55050
+ if (!ref) return "";
55051
+ const made = createdById.get(ref.id);
55052
+ if (made) return made.title;
55053
+ const node2 = comingKeys.has(refKey(ref)) ? index3.node(refKey(ref)) : void 0;
55054
+ if (node2) return names.get(node2.key) ?? node2.title;
55055
+ return live.get(ref.kind, ref.id)?.name ?? "";
55056
+ }, "containerName");
55057
+ const byContainer = /* @__PURE__ */ new Map();
55058
+ for (const n of coming) {
55059
+ if (!NAMED.has(n.kind)) continue;
55060
+ const container = n.kind === "project" ? null : placement.get(n.key)?.container ?? null;
55061
+ const id3 = `${n.kind}@${container ? refKey(container) : "workspace"}`;
55062
+ const group = byContainer.get(id3) ?? { kind: n.kind, container, nodes: [] };
55063
+ group.nodes.push(n);
55064
+ byContainer.set(id3, group);
55065
+ }
55066
+ for (const { kind, container, nodes } of byContainer.values()) {
55067
+ const isLive = container === null || !comingKeys.has(refKey(container)) && !madeIds.has(container.id);
55068
+ const taken = new Set((isLive ? live.siblingNames(kind, container) : []).map(norm).filter(Boolean));
55069
+ const batches = /* @__PURE__ */ new Map();
55070
+ for (const n of nodes) batches.set(n.entry.id, [...batches.get(n.entry.id) ?? [], n]);
55071
+ const order2 = [...batches.values()].sort((a, b) => b[0].entry.deletedAt.getTime() - a[0].entry.deletedAt.getTime() || (a[0].entry.id < b[0].entry.id ? -1 : 1));
55072
+ for (const batch of order2) {
55073
+ for (const n of batch) {
55074
+ const renamed = names.get(n.key);
55075
+ const originalTaken = Boolean(norm(n.title)) && taken.has(norm(n.title));
55076
+ if (!originalTaken && renamed === void 0) continue;
55077
+ const name2 = renamed ?? n.title;
55078
+ conflicts.push({ key: n.key, kind: n.kind, original: n.title, name: name2, where: containerName(container), taken: Boolean(norm(name2)) && taken.has(norm(name2)), kept: keep.has(n.key) });
55079
+ }
55080
+ for (const n of batch) {
55081
+ const name2 = norm(names.get(n.key) ?? n.title);
55082
+ if (name2) taken.add(name2);
55083
+ }
55084
+ }
55085
+ }
55086
+ let location = "";
55087
+ if (to === "original") location = live.path(root.ref).join(SEPARATOR);
55088
+ else if (to === "other") location = live.path(other).join(SEPARATOR);
55089
+ else if (to === "recreate") {
55090
+ const base = create.length ? [...live.path(create[0].in), ...create.map((c) => c.title)] : live.path(path2[0]?.ref ?? null);
55091
+ location = [...base, ...path2.map((n) => names.get(n.key) ?? n.title)].join(SEPARATOR);
55092
+ }
55093
+ const columnsInto = /* @__PURE__ */ new Map();
55094
+ const into = /* @__PURE__ */ __name((boardId) => {
55095
+ if (boardId) columnsInto.set(boardId, (columnsInto.get(boardId) ?? 0) + 1);
55096
+ }, "into");
55097
+ for (const n of coming) if (n.kind === "column") into(placement.get(n.key)?.sets.board_id);
55098
+ for (const c of create) if (c.kind === "column") into(c.in?.id);
55099
+ const limits = [];
55100
+ for (const [boardId, incoming] of columnsInto) {
55101
+ const key = keyOf("board", boardId);
55102
+ const there = comingKeys.has(key) ? 0 : live.columnCount(boardId);
55103
+ if (there + incoming <= MAX_COLUMNS) continue;
55104
+ const board = comingKeys.has(key) ? names.get(key) ?? index3.node(key)?.title ?? "" : live.get("board", boardId)?.name ?? "";
55105
+ limits.push({ board, count: there + incoming, max: MAX_COLUMNS });
55106
+ }
55107
+ const missing = [];
55108
+ if (to === null) missing.push("place");
55109
+ if (limits.length) missing.push("columns");
55110
+ if (conflicts.some((c) => c.taken && !c.kept)) missing.push("names");
55111
+ return {
55112
+ root,
55113
+ to,
55114
+ subtree,
55115
+ excluded,
55116
+ path: path2,
55117
+ create,
55118
+ recreatePath,
55119
+ recreateCreate,
55120
+ extras,
55121
+ coming: coming.filter((n) => !waitingLinks.has(n.key)),
55122
+ comingKeys,
55123
+ placement,
55124
+ names,
55125
+ conflicts,
55126
+ reinsert,
55127
+ wait,
55128
+ drop,
55129
+ mentions: index3.mentions.filter((r) => comingKeys.has(keyOf("card", r.cardId ?? "")) || comingKeys.has(keyOf("page", r.pageId ?? ""))),
55130
+ relations: [...groups.values()],
55131
+ canRecreate,
55132
+ choose,
55133
+ location,
55134
+ limits,
55135
+ missing
55136
+ };
55137
+ }
55138
+ __name(planRestore, "planRestore");
55139
+ function planDTO(index3, plan) {
55140
+ const { root } = plan;
55141
+ return {
55142
+ node: index3.dto(root),
55143
+ nodes: plan.subtree.map((n) => ({
55144
+ key: n.key,
55145
+ parentKey: n === root ? null : n.parent?.key ?? null,
55146
+ kind: n.kind,
55147
+ title: n.title,
55148
+ earlier: n !== root && isEarlier(n),
55149
+ included: !plan.excluded.has(n.key)
55150
+ })),
55151
+ where: {
55152
+ place: root.place,
55153
+ to: plan.to,
55154
+ path: plan.recreatePath.map((n) => ({ key: n.key, kind: n.kind, title: plan.names.get(n.key) ?? n.title })),
55155
+ create: plan.recreateCreate.map((c) => ({ kind: c.kind, title: c.title })),
55156
+ canRecreate: plan.canRecreate,
55157
+ choose: plan.choose,
55158
+ location: plan.location
55159
+ },
55160
+ conflicts: plan.conflicts,
55161
+ relations: plan.relations,
55162
+ limits: plan.limits,
55163
+ ready: plan.missing.length === 0,
55164
+ missing: plan.missing
55165
+ };
55166
+ }
55167
+ __name(planDTO, "planDTO");
55168
+
53954
55169
  // src/services/trash.ts
53955
- var TABLES = {
55170
+ var TABLES2 = {
53956
55171
  projects,
53957
55172
  boards,
53958
55173
  board_columns: columns,
@@ -53965,7 +55180,7 @@ var TABLES = {
53965
55180
  card_page_links: cardPageLinks,
53966
55181
  attachments
53967
55182
  };
53968
- var ORDER = Object.keys(TABLES);
55183
+ var ORDER = Object.keys(TABLES2);
53969
55184
  var ROOT_TABLE = {
53970
55185
  project: "projects",
53971
55186
  board: "boards",
@@ -53978,7 +55193,7 @@ var ROOT_TABLE = {
53978
55193
  checklist_item: "checklist_items",
53979
55194
  link: "card_page_links"
53980
55195
  };
53981
- var COUNTED = {
55196
+ var COUNTED2 = {
53982
55197
  boards: "boards",
53983
55198
  board_columns: "columns",
53984
55199
  cards: "cards",
@@ -53989,7 +55204,7 @@ var COUNTED = {
53989
55204
  labels: "labels"
53990
55205
  };
53991
55206
  var DAY_MS2 = 24 * 60 * 60 * 1e3;
53992
- var SEPARATOR = " \u203A ";
55207
+ var SEPARATOR2 = " \u203A ";
53993
55208
  var Snapshot = class {
53994
55209
  constructor(db) {
53995
55210
  this.db = db;
@@ -54032,7 +55247,6 @@ var Snapshot = class {
54032
55247
  return this.rows.map((row, i2) => ({ row, i: i2 })).sort((a, b) => ORDER.indexOf(a.row.table) - ORDER.indexOf(b.row.table) || a.i - b.i).map((x2) => x2.row);
54033
55248
  }
54034
55249
  };
54035
- var restoreError = /* @__PURE__ */ __name((code, message, details) => new AppError(409, code, message, details), "restoreError");
54036
55250
  var TrashService = class {
54037
55251
  constructor(deps, access, activity2, history2) {
54038
55252
  this.deps = deps;
@@ -54092,7 +55306,7 @@ var TrashService = class {
54092
55306
  for (const { table, data } of rows) {
54093
55307
  if (table === "attachments") bytes += Number(data.size ?? 0);
54094
55308
  if (data === root.data) continue;
54095
- const counted = COUNTED[table];
55309
+ const counted = COUNTED2[table];
54096
55310
  if (counted) contents[counted] = (contents[counted] ?? 0) + 1;
54097
55311
  }
54098
55312
  const now = /* @__PURE__ */ new Date();
@@ -54121,7 +55335,7 @@ var TrashService = class {
54121
55335
  capture(db, snapshot, target) {
54122
55336
  const one = /* @__PURE__ */ __name((table, id3) => db.get(sql`SELECT * FROM ${sql.identifier(table)} WHERE id = ${id3}`), "one");
54123
55337
  const name2 = /* @__PURE__ */ __name((query) => db.get(query)?.name ?? "", "name");
54124
- const path2 = /* @__PURE__ */ __name((...parts) => parts.filter(Boolean).join(SEPARATOR), "path");
55338
+ const path2 = /* @__PURE__ */ __name((...parts) => parts.filter(Boolean).join(SEPARATOR2), "path");
54125
55339
  const boardPath = /* @__PURE__ */ __name((boardId) => path2(name2(sql`SELECT p.name FROM boards b JOIN projects p ON p.id = b.project_id WHERE b.id = ${boardId}`), name2(sql`SELECT name FROM boards WHERE id = ${boardId}`)), "boardPath");
54126
55340
  const cardPath = /* @__PURE__ */ __name((cardId) => {
54127
55341
  const card = db.get(sql`SELECT board_id, column_id, title FROM cards WHERE id = ${cardId}`);
@@ -54164,8 +55378,8 @@ var TrashService = class {
54164
55378
  const row = one("cards", target.id);
54165
55379
  if (!row) return null;
54166
55380
  snapshot.cards(sql`SELECT ${target.id}`);
54167
- const column = name2(sql`SELECT name FROM board_columns WHERE id = ${row.column_id}`);
54168
- return { data: snapshot.rows[0].data, title: String(row.title), location: path2(boardPath(row.board_id), column) };
55381
+ const column2 = name2(sql`SELECT name FROM board_columns WHERE id = ${row.column_id}`);
55382
+ return { data: snapshot.rows[0].data, title: String(row.title), location: path2(boardPath(row.board_id), column2) };
54169
55383
  }
54170
55384
  case "page": {
54171
55385
  const row = one("pages", target.id);
@@ -54223,17 +55437,29 @@ var TrashService = class {
54223
55437
  db.delete(cardPageLinks).where(and(eq(cardPageLinks.cardId, target.cardId), eq(cardPageLinks.pageId, target.pageId), eq(cardPageLinks.source, "manual"))).run();
54224
55438
  return;
54225
55439
  default: {
54226
- const table = TABLES[ROOT_TABLE[target.kind]];
55440
+ const table = TABLES2[ROOT_TABLE[target.kind]];
54227
55441
  db.delete(table).where(eq(table.id, target.id)).run();
54228
55442
  }
54229
55443
  }
54230
55444
  }
54231
55445
  // ── People's side: listing, restoring, deleting for good ─────
55446
+ /** What is at the top of the trash: what isn't held by anything else in it. Newest first. */
54232
55447
  async list(actor, workspaceId) {
54233
55448
  this.access.requireUser(actor);
54234
55449
  await this.access.workspace(actor, workspaceId);
54235
- const rows = await this.deps.db.select().from(trash).where(eq(trash.workspaceId, workspaceId)).orderBy(desc(trash.deletedAt));
54236
- return rows.map(toTrashEntryDTO);
55450
+ const index3 = TrashIndex.load(this.deps.db, workspaceId);
55451
+ return index3.top().map((node2) => index3.dto(node2));
55452
+ }
55453
+ /**
55454
+ * One thing in the trash, with everything below it and what holds it there; null when it is
55455
+ * not in the trash (any more): asking is how the app finds out.
55456
+ */
55457
+ async tree(actor, workspaceId, key) {
55458
+ this.access.requireUser(actor);
55459
+ await this.access.workspace(actor, workspaceId);
55460
+ const index3 = TrashIndex.load(this.deps.db, workspaceId);
55461
+ const node2 = index3.node(key);
55462
+ return node2 ? index3.tree(node2) : null;
54237
55463
  }
54238
55464
  async load(actor, trashId) {
54239
55465
  this.access.requireUser(actor);
@@ -54242,159 +55468,329 @@ var TrashService = class {
54242
55468
  await this.access.workspace(actor, entry.workspaceId);
54243
55469
  return entry;
54244
55470
  }
54245
- /** Puts the item back, with everything it held. If its place is gone, in the first one available. */
55471
+ /**
55472
+ * Restores something with everything below it but what is left out, where the person says.
55473
+ * With `dryRun`, only says what that would do. Without it, it does exactly that, worked out
55474
+ * again in the same transaction: if anything is still to decide (where, or names already
55475
+ * used there), nothing is done and the plan says what.
55476
+ */
55477
+ async restoreItem(actor, workspaceId, body) {
55478
+ this.access.requireUser(actor);
55479
+ await this.access.workspace(actor, workspaceId);
55480
+ const input2 = parse3(trashRestoreInput, body);
55481
+ if (input2.dryRun) {
55482
+ const index3 = TrashIndex.load(this.deps.db, workspaceId);
55483
+ return planDTO(index3, planRestore(index3, input2));
55484
+ }
55485
+ const done = this.deps.db.transaction((tx) => {
55486
+ const index3 = TrashIndex.load(tx, workspaceId);
55487
+ const plan = planRestore(index3, input2);
55488
+ if (plan.missing.length) throw new AppError(409, "restore_incomplete", "Say where it goes back, and what to do with names already used there, first.", planDTO(index3, plan));
55489
+ return this.apply(tx, actor, workspaceId, plan);
55490
+ });
55491
+ await this.announce(actor, workspaceId, done);
55492
+ return done.result;
55493
+ }
55494
+ /**
55495
+ * Restores several things at once, each as `restoreItem` does, in one transaction: what holds
55496
+ * others first, each planned with what the ones before it brought back already there, so the
55497
+ * plans say what restoring them together does. One that came back with another (below it, or
55498
+ * as the other end of one of its relations) is not asked for twice: `cameWith` says with
55499
+ * which. One no longer in the trash is in `missing`. With `dryRun`, or when anything is still to
55500
+ * decide for any of them, or one went missing, nothing is done and the plans say what.
55501
+ */
55502
+ async restoreMany(actor, workspaceId, body) {
55503
+ this.access.requireUser(actor);
55504
+ await this.access.workspace(actor, workspaceId);
55505
+ const input2 = parse3(trashRestoreManyInput, body);
55506
+ let answer = { plans: [], ready: false };
55507
+ const asked = new Error("only planned");
55508
+ let done;
55509
+ try {
55510
+ done = this.deps.db.transaction((tx) => {
55511
+ const plans = [];
55512
+ const cameWith = {};
55513
+ const applied = [];
55514
+ const first = TrashIndex.load(tx, workspaceId);
55515
+ const missing = input2.items.filter((item) => !first.node(item.key)).map((item) => item.key);
55516
+ const depth = /* @__PURE__ */ __name((key) => first.ancestors(first.node(key)).length, "depth");
55517
+ const items = input2.items.filter((item) => first.node(item.key)).sort((a, b) => depth(a.key) - depth(b.key));
55518
+ for (const item of items) {
55519
+ const index3 = TrashIndex.load(tx, workspaceId);
55520
+ const back = /* @__PURE__ */ __name((key) => first.node(key) !== void 0 && !index3.node(key), "back");
55521
+ if (back(item.key)) continue;
55522
+ const plan = planRestore(index3, { ...item, include: item.include.filter((key) => !back(key)), dryRun: input2.dryRun });
55523
+ plans.push(planDTO(index3, plan));
55524
+ if (plan.missing.length) continue;
55525
+ applied.push(this.apply(tx, actor, workspaceId, plan));
55526
+ const after = TrashIndex.load(tx, workspaceId);
55527
+ for (const other of items) if (other !== item && index3.node(other.key) && !after.node(other.key)) cameWith[other.key] ??= item.key;
55528
+ }
55529
+ answer = { plans, ready: missing.length === 0 && plans.every((p) => p.ready), ...Object.keys(cameWith).length && { cameWith }, ...missing.length && { missing } };
55530
+ if (input2.dryRun || !answer.ready) throw asked;
55531
+ return applied;
55532
+ });
55533
+ } catch (error62) {
55534
+ if (error62 !== asked) throw error62;
55535
+ if (input2.dryRun) return answer;
55536
+ throw new AppError(409, "restore_incomplete", "Say where each goes back, and what to do with names already used there, first.", answer);
55537
+ }
55538
+ for (const applied of done) await this.announce(actor, workspaceId, applied);
55539
+ return { restored: done.map((a) => a.result) };
55540
+ }
55541
+ /**
55542
+ * Puts back exactly what one deletion took away, where it was: what was deleted before on its
55543
+ * own stays in the trash. It is what undoing a deletion does, so it never goes anywhere else:
55544
+ * when its place is not there, it says so. Names stay as they were.
55545
+ */
54246
55546
  async restore(actor, trashId) {
54247
55547
  const entry = await this.load(actor, trashId);
54248
- const result = this.deps.db.transaction((tx) => {
54249
- const rows = tx.select({ table: trashRows.tableName, data: trashRows.data }).from(trashRows).where(eq(trashRows.trashId, trashId)).orderBy(trashRows.id).all();
54250
- const root = rows.find((r) => r.table === ROOT_TABLE[entry.kind]);
54251
- if (!root) throw notFound("Trash entry");
54252
- const placed = this.place(tx, entry.workspaceId, entry.kind, root.data, rows);
54253
- const reinsert = new Reinsert(tx);
54254
- for (const row of rows) {
54255
- if (row.table === "card_page_links" && row.data.source === "mention") continue;
54256
- if (!reinsert.insert(row) && row === root) throw restoreError("restore_place_gone", "It no longer fits anywhere it could go back to.");
54257
- }
54258
- rebuildMentions(tx, entry.workspaceId, reinsert.cards, reinsert.pages);
54259
- const restored = this.restoredChange(tx, entry.kind, root.data, { trashId, movedTo: placed.movedTo });
54260
- if (restored) this.history.record(tx, actor, entry.workspaceId, restored);
54261
- tx.delete(trash).where(eq(trash.id, trashId)).run();
54262
- return placed;
54263
- });
54264
- await this.activity.record(
54265
- actor,
54266
- entry.workspaceId,
54267
- { action: "trash.restored", entityType: result.entityType, entityId: result.entityId, summary: entry.title, meta: { kind: entry.kind, ...result.movedTo ? { movedTo: result.movedTo } : {} } },
54268
- result.event
54269
- );
54270
- return { kind: entry.kind, entityId: entry.entityId, movedTo: result.movedTo, path: result.path };
54271
- }
54272
- /**
54273
- * Checks the item still has somewhere to go back to and points its row there. Cards,
54274
- * columns, boards and pages whose place is gone go to the first one available; the
54275
- * rest need theirs. Throws when there is none.
54276
- */
54277
- place(tx, workspaceId, kind, root, rows) {
54278
- const exists2 = /* @__PURE__ */ __name((table, id3) => id3 != null && Boolean(tx.get(sql`SELECT 1 AS found FROM ${sql.identifier(table)} WHERE id = ${id3} LIMIT 1`)), "exists");
54279
- const atEnd = /* @__PURE__ */ __name((table, scope) => {
54280
- const keys = tx.all(sql`SELECT position FROM ${sql.identifier(table)} WHERE ${scope} ORDER BY position`).map((r) => r.position);
54281
- return keyAtEnd(keys);
54282
- }, "atEnd");
54283
- const missing = /* @__PURE__ */ __name((table, id3, what) => {
54284
- const holder = tx.get(
54285
- sql`SELECT t.title FROM trash_rows r JOIN trash t ON t.id = r.trash_id WHERE r.table_name = ${table} AND json_extract(r.data, '$.id') = ${id3} LIMIT 1`
55548
+ const done = this.deps.db.transaction((tx) => {
55549
+ const results = [];
55550
+ const seen = /* @__PURE__ */ new Set();
55551
+ for (; ; ) {
55552
+ const index3 = TrashIndex.load(tx, entry.workspaceId);
55553
+ const tops = [...index3.nodes.values()].filter((n) => n.entry.id === trashId && (!n.parent || n.parent.entry.id !== trashId)).sort((a, b) => Number(b.entryRoot) - Number(a.entryRoot) || a.row.rowId - b.row.rowId);
55554
+ const top = tops[0];
55555
+ if (!top) break;
55556
+ if (seen.has(top.key)) throw restoreError("restore_changed", "It could not be put back.");
55557
+ seen.add(top.key);
55558
+ if (top.place === "trash") {
55559
+ const holder = top.parent;
55560
+ throw restoreError("restore_place_in_trash", `Restore \u201C${holder.title}\u201D first: what it belongs to is in the trash too.`, { title: holder.title, key: holder.key });
55561
+ }
55562
+ if (top.place === "gone") throw restoreError("restore_place_gone", "What it belonged to no longer exists.");
55563
+ const subtree = index3.subtree(top);
55564
+ const plan = planRestore(index3, {
55565
+ key: top.key,
55566
+ exclude: subtree.filter((n) => n.entry.id !== trashId).map((n) => n.key),
55567
+ to: { kind: "original" },
55568
+ names: {},
55569
+ keepNames: subtree.map((n) => n.key),
55570
+ include: [],
55571
+ dryRun: false
55572
+ });
55573
+ if (plan.missing.includes("columns")) throw new AppError(409, "too_many_columns", `A board holds up to ${MAX_COLUMNS} columns: there is no room to put it back.`);
55574
+ if (plan.missing.length) throw restoreError("restore_place_gone", "What it belonged to no longer exists.");
55575
+ const waiting = top.kind === "link" ? plan.wait.find((w) => w.row === top.row) : void 0;
55576
+ if (waiting) {
55577
+ const page = index3.node(`page:${top.row.pageId}`);
55578
+ throw restoreError("restore_place_in_trash", `Restore \u201C${page?.title ?? ""}\u201D first: the page is in the trash too.`, { title: page?.title ?? "", key: page?.key });
55579
+ }
55580
+ results.push(this.apply(tx, actor, entry.workspaceId, plan));
55581
+ }
55582
+ if (!results.length) throw notFound("Trash entry");
55583
+ return results;
55584
+ });
55585
+ for (const applied of done) await this.announce(actor, entry.workspaceId, applied);
55586
+ const first = done[0].result;
55587
+ return { ...first, kind: entry.kind, entityId: entry.entityId, movedTo: null };
55588
+ }
55589
+ /** The end of the list of `table`'s rows in `scope`, for something put there now. */
55590
+ atEnd(tx, table, scope) {
55591
+ const keys = tx.all(sql`SELECT position FROM ${sql.identifier(table)} WHERE ${scope} ORDER BY position`).map((r) => r.position);
55592
+ return keyAtEnd(keys);
55593
+ }
55594
+ /** Applies a plan inside the transaction it was worked out in. */
55595
+ apply(tx, actor, workspaceId, plan) {
55596
+ const { root } = plan;
55597
+ for (const made of plan.create) {
55598
+ if (made.kind === "project") {
55599
+ tx.insert(projects).values({ id: made.id, workspaceId, name: made.title.slice(0, NAME_MAX.project), color: "slate", position: this.atEnd(tx, "projects", sql`workspace_id = ${workspaceId}`) }).run();
55600
+ } else if (made.kind === "page") {
55601
+ const projectId = made.in.id;
55602
+ tx.insert(pages).values({
55603
+ id: made.id,
55604
+ workspaceId,
55605
+ projectId,
55606
+ parentId: null,
55607
+ title: made.title.slice(0, NAME_MAX.page),
55608
+ position: this.atEnd(tx, "pages", sql`project_id = ${projectId} AND parent_id IS NULL`),
55609
+ createdByUserId: actor.kind === "user" ? actor.userId : null
55610
+ }).run();
55611
+ } else {
55612
+ const boardId = made.in.id;
55613
+ tx.insert(columns).values({ id: made.id, workspaceId, boardId, name: made.title.slice(0, NAME_MAX.column), position: this.atEnd(tx, "board_columns", sql`board_id = ${boardId}`) }).run();
55614
+ }
55615
+ }
55616
+ const wanted = [...plan.coming.map((n) => n.row.rowId), ...plan.reinsert.map((r) => r.rowId)];
55617
+ const kept = /* @__PURE__ */ new Map();
55618
+ for (let i2 = 0; i2 < wanted.length; i2 += 500) {
55619
+ const chunk = wanted.slice(i2, i2 + 500);
55620
+ for (const row of tx.select({ id: trashRows.id, table: trashRows.tableName, data: trashRows.data }).from(trashRows).where(sql`${trashRows.id} IN (SELECT value FROM json_each(${JSON.stringify(chunk)}))`).all()) {
55621
+ kept.set(row.id, { table: row.table, data: row.data });
55622
+ }
55623
+ }
55624
+ const order2 = new Map(plan.coming.map((n, i2) => [n.row.rowId, i2]));
55625
+ const byRow = new Map(plan.coming.map((n) => [n.row.rowId, n]));
55626
+ const rows = wanted.map((rowId) => ({ rowId, captured: kept.get(rowId), node: byRow.get(rowId) })).filter((r) => r.captured !== void 0).sort((a, b) => ORDER.indexOf(a.captured.table) - ORDER.indexOf(b.captured.table) || (order2.get(a.rowId) ?? Infinity) - (order2.get(b.rowId) ?? Infinity) || a.rowId - b.rowId);
55627
+ if (rows.filter((r) => r.node).length !== plan.coming.length) throw restoreError("restore_changed", "Something in the trash changed meanwhile: look again before restoring.");
55628
+ const reinsert = new Reinsert(tx);
55629
+ const data = /* @__PURE__ */ new Map();
55630
+ for (const { captured, node: node2 } of rows) {
55631
+ if (node2) {
55632
+ const place = plan.placement.get(node2.key);
55633
+ if (place) {
55634
+ Object.assign(captured.data, place.sets);
55635
+ const scope = place.moved ? positionScope(node2.kind, place.container) : null;
55636
+ if (scope) captured.data.position = this.atEnd(tx, scope.table, scope.where);
55637
+ }
55638
+ const name2 = plan.names.get(node2.key);
55639
+ const column2 = NAME_COLUMN[node2.kind];
55640
+ if (name2 !== void 0 && column2) captured.data[column2] = node2.kind === "attachment" ? safeFilename(name2) : name2;
55641
+ data.set(node2.key, captured.data);
55642
+ if (!reinsert.insert(captured)) throw restoreError("restore_place_gone", "It no longer fits where it goes back.");
55643
+ } else {
55644
+ reinsert.insert(captured);
55645
+ }
55646
+ }
55647
+ const removed = [...plan.coming.map((n) => n.row), ...plan.reinsert, ...plan.drop, ...plan.mentions].map((r) => r.rowId);
55648
+ for (let i2 = 0; i2 < removed.length; i2 += 500) {
55649
+ tx.delete(trashRows).where(sql`${trashRows.id} IN (SELECT value FROM json_each(${JSON.stringify(removed.slice(i2, i2 + 500))}))`).run();
55650
+ }
55651
+ for (const { row, trashId } of plan.wait) tx.update(trashRows).set({ trashId }).where(eq(trashRows.id, row.rowId)).run();
55652
+ const touched = /* @__PURE__ */ new Set([...plan.coming.map((n) => n.entry.id), ...[...plan.reinsert, ...plan.drop, ...plan.mentions, ...plan.wait.map((w) => w.row)].map((r) => r.trashId)]);
55653
+ this.dropEmpty(tx, touched);
55654
+ rebuildMentions(tx, workspaceId, reinsert.cards, reinsert.pages);
55655
+ const movedTo = plan.to === "other" || plan.create.length > 0 ? plan.location : null;
55656
+ for (const node2 of plan.coming) {
55657
+ if (!node2.entryRoot) continue;
55658
+ const change = this.restoredChange(tx, node2.kind, data.get(node2.key) ?? {}, { trashId: node2.entry.id, ...node2 === root && movedTo ? { movedTo } : {} });
55659
+ if (change) this.history.record(tx, actor, workspaceId, change);
55660
+ }
55661
+ const extras = plan.extras.filter((n) => !n.parent || !plan.comingKeys.has(n.parent.key));
55662
+ const targets = [root, ...extras].map((node2) => ({ node: node2, ...this.target(tx, node2, data.get(node2.key)) }));
55663
+ const main = targets[0];
55664
+ const result = {
55665
+ kind: root.kind,
55666
+ entityId: root.id,
55667
+ movedTo,
55668
+ path: main.path,
55669
+ location: plan.location,
55670
+ restored: Math.max(0, plan.coming.length - (data.has(root.key) ? 1 : 0)),
55671
+ left: plan.subtree.filter((n) => plan.excluded.has(n.key) && !(n.parent && plan.excluded.has(n.parent.key))).length
55672
+ };
55673
+ const waiting = root.kind === "link" && !data.has(root.key);
55674
+ if (waiting) result.waitsFor = root.title;
55675
+ const structure = plan.path.length > 0 || plan.create.length > 0;
55676
+ return {
55677
+ result,
55678
+ targets: targets.map((t) => ({ ...t, event: structure ? { ...t.event, structure: true } : t.event })),
55679
+ movedTo,
55680
+ waiting
55681
+ };
55682
+ }
55683
+ /** Deletes the entries left with nothing of their own; what else they kept goes with them. */
55684
+ dropEmpty(tx, trashIds) {
55685
+ for (const trashId of trashIds) {
55686
+ const left = tx.get(
55687
+ sql`SELECT 1 AS found FROM trash_rows WHERE trash_id = ${trashId} AND (table_name NOT IN ('card_labels', 'card_page_links') OR (table_name = 'card_page_links' AND trash_id IN (SELECT id FROM trash WHERE id = ${trashId} AND kind = 'link'))) LIMIT 1`
54286
55688
  );
54287
- if (holder) return restoreError("restore_place_in_trash", `Restore \u201C${holder.title}\u201D first: the ${what} it belongs to is in the trash too.`, { title: holder.title });
54288
- return restoreError("restore_place_gone", `The ${what} it belonged to no longer exists, and there is nowhere else to put it.`);
54289
- }, "missing");
54290
- const needs = /* @__PURE__ */ __name((table, id3, what) => {
54291
- if (!exists2(table, id3)) throw missing(table, id3, what);
54292
- }, "needs");
54293
- const firstProject = /* @__PURE__ */ __name(() => tx.get(sql`SELECT id, name FROM projects WHERE workspace_id = ${workspaceId} ORDER BY position, id LIMIT 1`), "firstProject");
54294
- const firstBoard = /* @__PURE__ */ __name(() => tx.get(
54295
- sql`SELECT b.id, b.name, p.name AS project FROM boards b JOIN projects p ON p.id = b.project_id WHERE b.workspace_id = ${workspaceId} ORDER BY p.position, p.id, b.position, b.id LIMIT 1`
54296
- ), "firstBoard");
54297
- const boardName = /* @__PURE__ */ __name((boardId) => tx.get(sql`SELECT b.name, p.name AS project FROM boards b JOIN projects p ON p.id = b.project_id WHERE b.id = ${boardId}`), "boardName");
54298
- const ofTable = /* @__PURE__ */ __name((table) => rows.filter((r) => r.table === table).map((r) => r.data), "ofTable");
54299
- const event = /* @__PURE__ */ __name((e) => e, "event");
54300
- let movedTo = null;
54301
- switch (kind) {
55689
+ if (!left) tx.delete(trash).where(eq(trash.id, trashId)).run();
55690
+ }
55691
+ }
55692
+ /** What restoring `node` is about, where to open it, and who hears of it. */
55693
+ target(tx, node2, data) {
55694
+ const text2 = /* @__PURE__ */ __name((value) => typeof value === "string" ? value : "", "text");
55695
+ const row = data ?? { id: node2.id, card_id: node2.row.cardId, page_id: node2.row.pageId, board_id: node2.row.boardId, project_id: node2.row.projectId, checklist_id: node2.row.checklistId };
55696
+ const id3 = text2(row.id) || node2.id;
55697
+ const boardOfCard = /* @__PURE__ */ __name((cardId) => tx.get(sql`SELECT board_id FROM cards WHERE id = ${cardId}`)?.board_id ?? "", "boardOfCard");
55698
+ const onCard = /* @__PURE__ */ __name((cardId, extra = {}) => {
55699
+ const boardId = boardOfCard(cardId);
55700
+ return { entityType: "card", entityId: cardId, path: boardId ? `b/${boardId}` : null, event: { boardId, cardId, ...extra } };
55701
+ }, "onCard");
55702
+ switch (node2.kind) {
54302
55703
  case "project":
54303
- return { entityType: "project", entityId: String(root.id), movedTo, path: `p/${root.id}`, event: event({ projectId: String(root.id), structure: true }) };
54304
- case "board": {
54305
- if (!exists2("projects", root.project_id)) {
54306
- const target = firstProject();
54307
- if (!target) throw missing("projects", root.project_id, "project");
54308
- root.project_id = target.id;
54309
- root.position = atEnd("boards", sql`project_id = ${target.id}`);
54310
- movedTo = target.name;
54311
- }
54312
- return { entityType: "board", entityId: String(root.id), movedTo, path: `b/${root.id}`, event: event({ boardId: String(root.id), projectId: String(root.project_id), structure: true }) };
54313
- }
54314
- case "column": {
54315
- if (!exists2("boards", root.board_id)) {
54316
- const target = firstBoard();
54317
- if (!target) throw missing("boards", root.board_id, "board");
54318
- root.board_id = target.id;
54319
- root.position = atEnd("board_columns", sql`board_id = ${target.id}`);
54320
- for (const card of ofTable("cards")) card.board_id = target.id;
54321
- movedTo = [target.project, target.name].join(SEPARATOR);
54322
- }
54323
- return { entityType: "column", entityId: String(root.id), movedTo, path: `b/${root.board_id}`, event: event({ boardId: String(root.board_id), structure: true }) };
54324
- }
54325
- case "card": {
54326
- const column = tx.get(sql`SELECT board_id, name FROM board_columns WHERE id = ${root.column_id}`);
54327
- if (column && column.board_id !== root.board_id) {
54328
- const board = boardName(column.board_id);
54329
- root.board_id = column.board_id;
54330
- root.position = atEnd("cards", sql`column_id = ${root.column_id}`);
54331
- movedTo = [board.project, board.name, column.name].join(SEPARATOR);
54332
- } else if (!column) {
54333
- const first = /* @__PURE__ */ __name((scope) => tx.get(
54334
- sql`SELECT c.id, c.name, b.id AS board_id, b.name AS board, p.name AS project FROM board_columns c JOIN boards b ON b.id = c.board_id JOIN projects p ON p.id = b.project_id WHERE ${scope} ORDER BY p.position, p.id, b.position, b.id, c.position, c.id LIMIT 1`
54335
- ), "first");
54336
- const target = first(sql`c.board_id = ${root.board_id}`) ?? first(sql`c.workspace_id = ${workspaceId}`);
54337
- if (!target) throw missing("board_columns", root.column_id, "column");
54338
- root.board_id = target.board_id;
54339
- root.column_id = target.id;
54340
- root.position = atEnd("cards", sql`column_id = ${target.id}`);
54341
- movedTo = [target.project, target.board, target.name].join(SEPARATOR);
54342
- }
54343
- return { entityType: "card", entityId: String(root.id), movedTo, path: `b/${root.board_id}`, event: event({ boardId: String(root.board_id), cardId: String(root.id), structure: true }) };
54344
- }
54345
- case "page": {
54346
- const parent = root.parent_id != null ? tx.get(sql`SELECT project_id FROM pages WHERE id = ${root.parent_id}`) : void 0;
54347
- const projectName = /* @__PURE__ */ __name((id3) => tx.get(sql`SELECT name FROM projects WHERE id = ${id3}`)?.name ?? null, "projectName");
54348
- if (parent) {
54349
- if (parent.project_id !== root.project_id) {
54350
- for (const page of ofTable("pages")) page.project_id = parent.project_id;
54351
- root.position = atEnd("pages", sql`parent_id = ${root.parent_id}`);
54352
- movedTo = projectName(parent.project_id);
54353
- }
54354
- } else if (!exists2("projects", root.project_id)) {
54355
- const target = firstProject();
54356
- if (!target) throw missing("projects", root.project_id, "project");
54357
- for (const page of ofTable("pages")) page.project_id = target.id;
54358
- root.parent_id = null;
54359
- root.position = atEnd("pages", sql`project_id = ${target.id} AND parent_id IS NULL`);
54360
- movedTo = target.name;
54361
- } else if (root.parent_id != null) {
54362
- root.parent_id = null;
54363
- root.position = atEnd("pages", sql`project_id = ${root.project_id} AND parent_id IS NULL`);
54364
- movedTo = projectName(root.project_id);
54365
- }
54366
- return { entityType: "page", entityId: String(root.id), movedTo, path: `d/${root.id}`, event: event({ pageId: String(root.id), projectId: String(root.project_id), structure: true }) };
54367
- }
54368
- case "attachment": {
54369
- if (root.card_id != null) {
54370
- needs("cards", root.card_id, "card");
54371
- const boardId = tx.get(sql`SELECT board_id FROM cards WHERE id = ${root.card_id}`).board_id;
54372
- return { entityType: "card", entityId: String(root.card_id), movedTo, path: `b/${boardId}`, event: event({ boardId, cardId: String(root.card_id) }) };
54373
- }
54374
- needs("pages", root.page_id, "page");
54375
- return { entityType: "page", entityId: String(root.page_id), movedTo, path: `d/${root.page_id}`, event: event({ pageId: String(root.page_id) }) };
54376
- }
55704
+ return { entityType: "project", entityId: id3, path: `p/${id3}`, event: { projectId: id3, structure: true } };
55705
+ case "board":
55706
+ return { entityType: "board", entityId: id3, path: `b/${id3}`, event: { boardId: id3, projectId: text2(row.project_id), structure: true } };
55707
+ case "column":
55708
+ return { entityType: "column", entityId: id3, path: `b/${text2(row.board_id)}`, event: { boardId: text2(row.board_id), structure: true } };
55709
+ case "card":
55710
+ return { entityType: "card", entityId: id3, path: `b/${text2(row.board_id)}`, event: { boardId: text2(row.board_id), cardId: id3, structure: true } };
55711
+ case "page":
55712
+ return { entityType: "page", entityId: id3, path: `d/${id3}`, event: { pageId: id3, projectId: text2(row.project_id), structure: true } };
54377
55713
  case "label":
54378
- needs("boards", root.board_id, "board");
54379
- return { entityType: "label", entityId: String(root.id), movedTo, path: `b/${root.board_id}`, event: event({ boardId: String(root.board_id) }) };
55714
+ return { entityType: "label", entityId: id3, path: `b/${text2(row.board_id)}`, event: { boardId: text2(row.board_id) } };
55715
+ case "attachment":
55716
+ if (row.card_id) return onCard(text2(row.card_id));
55717
+ return { entityType: "page", entityId: text2(row.page_id), path: `d/${text2(row.page_id)}`, event: { pageId: text2(row.page_id) } };
54380
55718
  case "checklist":
55719
+ return onCard(text2(row.card_id));
54381
55720
  case "checklist_item": {
54382
- const cardId = kind === "checklist" ? (needs("cards", root.card_id, "card"), root.card_id) : (needs("checklists", root.checklist_id, "checklist"), tx.get(sql`SELECT card_id FROM checklists WHERE id = ${root.checklist_id}`).card_id);
54383
- const boardId = tx.get(sql`SELECT board_id FROM cards WHERE id = ${cardId}`).board_id;
54384
- return { entityType: "card", entityId: String(cardId), movedTo, path: `b/${boardId}`, event: event({ boardId, cardId: String(cardId) }) };
54385
- }
54386
- case "link": {
54387
- needs("cards", root.card_id, "card");
54388
- needs("pages", root.page_id, "page");
54389
- const boardId = tx.get(sql`SELECT board_id FROM cards WHERE id = ${root.card_id}`).board_id;
54390
- return { entityType: "card", entityId: String(root.card_id), movedTo, path: `b/${boardId}`, event: event({ boardId, cardId: String(root.card_id), pageId: String(root.page_id) }) };
55721
+ const list = tx.get(sql`SELECT card_id FROM checklists WHERE id = ${text2(row.checklist_id)}`);
55722
+ return onCard(list?.card_id ?? "");
54391
55723
  }
55724
+ case "link":
55725
+ return onCard(text2(row.card_id), { pageId: text2(row.page_id) });
54392
55726
  }
54393
55727
  }
54394
- /** Deletes an entry for good, with the files of its attachments. */
55728
+ /** Records and announces what came back. */
55729
+ async announce(actor, workspaceId, applied) {
55730
+ if (applied.waiting && applied.targets.length === 1) {
55731
+ await this.activity.emit(workspaceId, { action: "trash.changed", actor: actorRef(actor), ...applied.targets[0].event });
55732
+ return;
55733
+ }
55734
+ for (const [i2, target] of applied.targets.entries()) {
55735
+ if (i2 === 0 && applied.waiting) continue;
55736
+ await this.activity.record(
55737
+ actor,
55738
+ workspaceId,
55739
+ {
55740
+ action: "trash.restored",
55741
+ entityType: target.entityType,
55742
+ entityId: target.entityId,
55743
+ summary: target.node.title,
55744
+ meta: { kind: target.node.kind, ...i2 === 0 && applied.movedTo ? { movedTo: applied.movedTo } : {} }
55745
+ },
55746
+ target.event
55747
+ );
55748
+ }
55749
+ }
55750
+ /** Deletes something for good with everything below it, and the files of its attachments. */
55751
+ async purgeItem(actor, workspaceId, key) {
55752
+ this.access.requireUser(actor);
55753
+ await this.access.workspace(actor, workspaceId);
55754
+ const erased = await this.erase(workspaceId, (index3) => {
55755
+ const node3 = index3.node(key);
55756
+ return node3 ? [node3] : [];
55757
+ });
55758
+ if (!erased) throw notFound("Trash item");
55759
+ const [node2] = erased;
55760
+ await this.activity.record(actor, workspaceId, { action: "trash.purged", entityType: purgedEntityType(node2.kind), entityId: node2.id, summary: node2.title, meta: { kind: node2.kind } });
55761
+ }
55762
+ /**
55763
+ * Deletes several things for good, with everything below them; what is below another one of
55764
+ * them goes with it. With `dryRun`, only says how much that takes. What is no longer in the
55765
+ * trash is skipped; the answer counts what went.
55766
+ */
55767
+ async purgeMany(actor, workspaceId, body) {
55768
+ this.access.requireUser(actor);
55769
+ await this.access.workspace(actor, workspaceId);
55770
+ const input2 = parse3(trashPurgeManyInput, body);
55771
+ const pick2 = /* @__PURE__ */ __name((index3) => index3.outermost(input2.keys.flatMap((key) => index3.node(key) ?? [])), "pick");
55772
+ const summary = /* @__PURE__ */ __name((index3, nodes) => ({ count: nodes.length, ...index3.totals(nodes) }), "summary");
55773
+ if (input2.dryRun) {
55774
+ const index3 = TrashIndex.load(this.deps.db, workspaceId);
55775
+ return summary(index3, pick2(index3));
55776
+ }
55777
+ let went = null;
55778
+ const erased = await this.erase(workspaceId, (index3) => {
55779
+ const picked = pick2(index3);
55780
+ went = summary(index3, picked);
55781
+ return picked;
55782
+ });
55783
+ if (!erased?.length || !went) throw notFound("Trash item");
55784
+ for (const node2 of erased) {
55785
+ await this.activity.record(actor, workspaceId, { action: "trash.purged", entityType: purgedEntityType(node2.kind), entityId: node2.id, summary: node2.title, meta: { kind: node2.kind } });
55786
+ }
55787
+ return went;
55788
+ }
55789
+ /** Deletes for good what one deletion took away, with everything below it. */
54395
55790
  async purge(actor, trashId) {
54396
55791
  const entry = await this.load(actor, trashId);
54397
- if (!await this.erase(trashId)) throw notFound("Trash entry");
55792
+ const erased = await this.erase(entry.workspaceId, (index3) => [...index3.nodes.values()].filter((n) => n.entry.id === trashId), [trashId]);
55793
+ if (!erased) throw notFound("Trash entry");
54398
55794
  await this.activity.record(actor, entry.workspaceId, {
54399
55795
  action: "trash.purged",
54400
55796
  entityType: purgedEntityType(entry.kind),
@@ -54405,30 +55801,71 @@ var TrashService = class {
54405
55801
  }
54406
55802
  /** Deletes for good what has been in the trash for TRASH_DAYS. Runs hourly. */
54407
55803
  async purgeExpired(now = /* @__PURE__ */ new Date()) {
54408
- const expired = await this.deps.db.select({ id: trash.id }).from(trash).where(lte(trash.expiresAt, now));
55804
+ const expired = await this.deps.db.select({ id: trash.id, workspaceId: trash.workspaceId }).from(trash).where(lte(trash.expiresAt, now));
55805
+ const byWorkspace = /* @__PURE__ */ new Map();
55806
+ for (const { id: id3, workspaceId } of expired) byWorkspace.set(workspaceId, [...byWorkspace.get(workspaceId) ?? [], id3]);
54409
55807
  let erased = 0;
54410
- for (const { id: id3 } of expired) if (await this.erase(id3)) erased++;
55808
+ for (const [workspaceId, ids] of byWorkspace) {
55809
+ const set2 = new Set(ids);
55810
+ if (await this.erase(workspaceId, (index3) => [...index3.nodes.values()].filter((n) => set2.has(n.entry.id)), ids)) erased += ids.length;
55811
+ }
54411
55812
  return erased;
54412
55813
  }
54413
55814
  /**
54414
- * Deletes an entry and then the files of its attachments. Reading the files and deleting
54415
- * the entry happen in one transaction, so a restore running at the same time either
54416
- * comes first (and nothing is erased) or finds nothing to restore. Returns whether this
54417
- * call erased it.
54418
- */
54419
- async erase(trashId) {
54420
- const files = this.deps.db.transaction((tx) => {
54421
- const keys = tx.select({ key: trashRows.storageKey }).from(trashRows).where(and(eq(trashRows.trashId, trashId), isNotNull(trashRows.storageKey))).all();
54422
- this.history.forget(tx, trashId);
54423
- const erased = tx.delete(trash).where(eq(trash.id, trashId)).returning({ id: trash.id }).all();
54424
- return erased.length > 0 ? keys : null;
55815
+ * Deletes for good what `pick` chooses, with everything below it, and then the files of its
55816
+ * attachments. Choosing, reading the files and deleting happen in one transaction, so a
55817
+ * restore running at the same time either comes first (and nothing of it is erased) or finds
55818
+ * nothing to restore. Relations of what goes can never come back: they go too, as do links
55819
+ * to a page that goes. Entries left with nothing of their own go, and so do `entries`.
55820
+ * Returns what was picked, or null when there was nothing.
55821
+ */
55822
+ async erase(workspaceId, pick2, entries = []) {
55823
+ const done = this.deps.db.transaction((tx) => {
55824
+ const index3 = TrashIndex.load(tx, workspaceId);
55825
+ const picked = pick2(index3);
55826
+ const gone = index3.goneWith(picked);
55827
+ const has = /* @__PURE__ */ __name((kind, id3) => gone.has(`${kind}:${id3}`), "has");
55828
+ const touches = /* @__PURE__ */ __name((r) => has("card", r.cardId) || (r.table === "card_labels" ? has("label", r.labelId) : has("page", r.pageId)), "touches");
55829
+ const rows = [...[...gone.values()].map((n) => n.row), ...index3.relations.filter(touches), ...index3.mentions.filter(touches)];
55830
+ const existing = entries.filter((id3) => index3.entries.has(id3));
55831
+ if (rows.length === 0 && existing.length === 0) return null;
55832
+ this.history.forgetIds(
55833
+ tx,
55834
+ [...gone.values()].filter((n) => n.kind !== "link").map((n) => n.id)
55835
+ );
55836
+ const ids = rows.map((r) => r.rowId);
55837
+ for (let i2 = 0; i2 < ids.length; i2 += 500) {
55838
+ tx.delete(trashRows).where(sql`${trashRows.id} IN (SELECT value FROM json_each(${JSON.stringify(ids.slice(i2, i2 + 500))}))`).run();
55839
+ }
55840
+ for (const id3 of existing) tx.delete(trash).where(eq(trash.id, id3)).run();
55841
+ this.dropEmpty(tx, new Set(rows.map((r) => r.trashId)));
55842
+ return { picked, files: rows.flatMap((r) => r.table === "attachments" && r.storageKey ? [r.storageKey] : []) };
54425
55843
  });
54426
- if (!files) return false;
54427
- for (const { key } of files) await this.deps.storage.delete(key).catch(() => {
55844
+ if (!done) return null;
55845
+ for (const key of done.files) await this.deps.storage.delete(key).catch(() => {
54428
55846
  });
54429
- return true;
55847
+ return done.picked.length ? done.picked : entries.length ? [] : null;
54430
55848
  }
54431
55849
  };
55850
+ function positionScope(kind, container) {
55851
+ switch (kind) {
55852
+ case "board":
55853
+ return { table: "boards", where: sql`project_id = ${container.id}` };
55854
+ case "column":
55855
+ return { table: "board_columns", where: sql`board_id = ${container.id}` };
55856
+ case "card":
55857
+ return { table: "cards", where: sql`column_id = ${container.id}` };
55858
+ case "checklist":
55859
+ return { table: "checklists", where: sql`card_id = ${container.id}` };
55860
+ case "checklist_item":
55861
+ return { table: "checklist_items", where: sql`checklist_id = ${container.id}` };
55862
+ case "page":
55863
+ return { table: "pages", where: container.kind === "page" ? sql`parent_id = ${container.id}` : sql`project_id = ${container.id} AND parent_id IS NULL` };
55864
+ default:
55865
+ return null;
55866
+ }
55867
+ }
55868
+ __name(positionScope, "positionScope");
54432
55869
  function rebuildMentions(tx, workspaceId, cards2, pages2) {
54433
55870
  if (cards2.size === 0 && pages2.size === 0) return;
54434
55871
  const exists2 = /* @__PURE__ */ new Map();
@@ -54454,7 +55891,7 @@ __name(rebuildMentions, "rebuildMentions");
54454
55891
  var AUTHORS = /* @__PURE__ */ new Set(["users", "api_tokens"]);
54455
55892
  var SHAPES = new Map(
54456
55893
  ORDER.map((table) => {
54457
- const definition = TABLES[table];
55894
+ const definition = TABLES2[table];
54458
55895
  const references = getTableConfig(definition).foreignKeys.map((fk) => {
54459
55896
  const reference = fk.reference();
54460
55897
  return { column: reference.columns[0].name, table: getTableConfig(reference.foreignTable).name, target: reference.foreignColumns[0].name };
@@ -54474,11 +55911,11 @@ var Reinsert = class {
54474
55911
  /** The cards and pages put back, for rebuilding their mentions. */
54475
55912
  cards = /* @__PURE__ */ new Set();
54476
55913
  pages = /* @__PURE__ */ new Set();
54477
- exists(table, column, value) {
54478
- const key = `${table} ${column} ${String(value)}`;
55914
+ exists(table, column2, value) {
55915
+ const key = `${table} ${column2} ${String(value)}`;
54479
55916
  let found = this.known.get(key);
54480
55917
  if (found === void 0) {
54481
- found = Boolean(this.tx.get(sql`SELECT 1 AS found FROM ${sql.identifier(table)} WHERE ${sql.identifier(column)} = ${value} LIMIT 1`));
55918
+ found = Boolean(this.tx.get(sql`SELECT 1 AS found FROM ${sql.identifier(table)} WHERE ${sql.identifier(column2)} = ${value} LIMIT 1`));
54482
55919
  this.known.set(key, found);
54483
55920
  }
54484
55921
  return found;
@@ -54512,29 +55949,14 @@ var Reinsert = class {
54512
55949
  }
54513
55950
  };
54514
55951
  var purgedEntityType = /* @__PURE__ */ __name((kind) => ["project", "board", "column", "card", "label", "page"].find((k) => k === kind) ?? "card", "purgedEntityType");
54515
- function toTrashEntryDTO(row) {
54516
- return {
54517
- id: row.id,
54518
- kind: row.kind,
54519
- entityId: row.entityId,
54520
- title: row.title,
54521
- location: row.location,
54522
- contents: row.contents,
54523
- bytes: row.bytes,
54524
- deletedBy: {
54525
- kind: row.actorKind,
54526
- id: (row.actorKind === "agent" ? row.actorTokenId : row.actorUserId) ?? "",
54527
- name: row.actorName
54528
- },
54529
- deletedAt: row.deletedAt.toISOString(),
54530
- expiresAt: row.expiresAt.toISOString()
54531
- };
54532
- }
54533
- __name(toTrashEntryDTO, "toTrashEntryDTO");
54534
55952
 
54535
55953
  // src/services/undo.ts
54536
55954
  var AT_END = 1e5;
54537
55955
  var MAX_CHANGES = 500;
55956
+ var MAX_LEFT = 50;
55957
+ var LEFT_TYPES = ["project", "board", "column", "label"];
55958
+ var LEFT_ACTIONS = ["created", "updated", "moved", "deleted"];
55959
+ var TRASH_TABLES = { project: "projects", board: "boards", column: "board_columns", label: "labels", page: "pages", card: "cards" };
54538
55960
  var CHUNK = 90;
54539
55961
  var LIGHT_COLUMNS = (() => {
54540
55962
  const body = inArray(history.kind, [...HISTORY_BODY_KINDS]);
@@ -54580,11 +56002,12 @@ var UndoService = class {
54580
56002
  async undo(actor, input2) {
54581
56003
  this.access.requireUser(actor);
54582
56004
  const data = parse3(undoInput, input2);
54583
- const rows = await this.entries(actor, data.ids, data.since);
56005
+ const { rows, anchor: anchor2, remaining } = await this.entries(actor, data.ids, data.since, data.until);
54584
56006
  const undoing = new Set(rows.map((r) => r.id));
56007
+ const told = anchor2 ? { remaining: remaining ?? 0, ...this.left(anchor2) } : {};
54585
56008
  const state = new State();
54586
56009
  const plan = rows.map((row) => this.planItem(row, this.check(row, undoing, state), undoing, state));
54587
- if (data.dryRun || data.conflicts === "ask" && plan.some((p) => p.status === "conflict")) return { applied: false, plan, undone: 0, skipped: 0, failed: 0 };
56010
+ if (data.dryRun || data.conflicts === "ask" && plan.some((p) => p.status === "conflict")) return { applied: false, plan, undone: 0, skipped: 0, failed: 0, ...told };
54588
56011
  let undone = 0;
54589
56012
  let skipped = 0;
54590
56013
  let failed = 0;
@@ -54610,7 +56033,7 @@ var UndoService = class {
54610
56033
  failed++;
54611
56034
  }
54612
56035
  }
54613
- return { applied: true, plan, undone, skipped, failed };
56036
+ return { applied: true, plan, undone, skipped, failed, ...told };
54614
56037
  }
54615
56038
  /** Puts a page's content or a card's description back as it was after a change, as a new change. */
54616
56039
  async restoreVersion(actor, entryId) {
@@ -54634,22 +56057,67 @@ var UndoService = class {
54634
56057
  rows(where) {
54635
56058
  return this.deps.db.select(LIGHT_COLUMNS).from(history).where(where).orderBy(desc(history.updatedAt), desc(sql`rowid`));
54636
56059
  }
54637
- /** The changes to undo, newest first: those asked for, or all their author did from one on. */
54638
- async entries(actor, ids, since) {
54639
- let rows = [];
56060
+ /**
56061
+ * The changes to undo, newest first: those asked for, or all their author did from one on (the
56062
+ * anchor), up to MAX_CHANGES at a time. Those older than `until` are the next batch, after the
56063
+ * one that ended there; `remaining` says how many are left beyond this one.
56064
+ */
56065
+ async entries(actor, ids, since, until) {
54640
56066
  if (ids) {
54641
- for (let i2 = 0; i2 < ids.length; i2 += CHUNK) rows.push(...await this.rows(inArray(history.id, ids.slice(i2, i2 + CHUNK))));
54642
- if (rows.length !== new Set(ids).size) throw notFound("History entry");
54643
- rows.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.seq - a.seq);
54644
- } else {
54645
- const [anchor2] = await this.rows(eq(history.id, since));
54646
- if (!anchor2) throw notFound("History entry");
54647
- const author = anchor2.actorKind === "agent" ? eq(history.actorTokenId, anchor2.actorTokenId ?? "") : and(eq(history.actorKind, "user"), eq(history.actorUserId, anchor2.actorUserId ?? ""));
54648
- const from = or(gt(history.updatedAt, anchor2.updatedAt), and(eq(history.updatedAt, anchor2.updatedAt), sql`rowid >= ${anchor2.seq}`));
54649
- rows = await this.rows(and(eq(history.workspaceId, anchor2.workspaceId), author, from)).limit(MAX_CHANGES);
54650
- }
54651
- for (const workspaceId of new Set(rows.map((r) => r.workspaceId))) await this.access.workspace(actor, workspaceId);
54652
- return rows;
56067
+ const rows2 = [];
56068
+ for (let i2 = 0; i2 < ids.length; i2 += CHUNK) rows2.push(...await this.rows(inArray(history.id, ids.slice(i2, i2 + CHUNK))));
56069
+ if (rows2.length !== new Set(ids).size) throw notFound("History entry");
56070
+ rows2.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.seq - a.seq);
56071
+ for (const workspaceId of new Set(rows2.map((r) => r.workspaceId))) await this.access.workspace(actor, workspaceId);
56072
+ return { rows: rows2 };
56073
+ }
56074
+ const [anchor2] = await this.rows(eq(history.id, since));
56075
+ if (!anchor2) throw notFound("History entry");
56076
+ await this.access.workspace(actor, anchor2.workspaceId);
56077
+ const author = anchor2.actorKind === "agent" ? eq(history.actorTokenId, anchor2.actorTokenId ?? "") : and(eq(history.actorKind, "user"), eq(history.actorUserId, anchor2.actorUserId ?? ""));
56078
+ const from = or(gt(history.updatedAt, anchor2.updatedAt), and(eq(history.updatedAt, anchor2.updatedAt), sql`rowid >= ${anchor2.seq}`));
56079
+ const before = /* @__PURE__ */ __name((row) => or(lt(history.updatedAt, row.updatedAt), and(eq(history.updatedAt, row.updatedAt), sql`rowid < ${row.seq}`)), "before");
56080
+ let end2;
56081
+ if (until) {
56082
+ ;
56083
+ [end2] = await this.rows(eq(history.id, until));
56084
+ if (!end2 || end2.workspaceId !== anchor2.workspaceId) throw notFound("History entry");
56085
+ }
56086
+ const scope = and(eq(history.workspaceId, anchor2.workspaceId), author, from, end2 ? before(end2) : void 0);
56087
+ const rows = await this.rows(scope).limit(MAX_CHANGES);
56088
+ const last = rows.at(-1);
56089
+ const remaining = rows.length < MAX_CHANGES || !last ? 0 : this.deps.db.select({ n: sql`count(*)` }).from(history).where(and(scope, before(last))).get()?.n ?? 0;
56090
+ return { rows, anchor: anchor2, remaining };
56091
+ }
56092
+ /**
56093
+ * What the anchor's author changed from it on in projects, boards, columns and labels: these
56094
+ * have no history, so undoing from it leaves them as they are, and says so. By what activity
56095
+ * tells, each thing once, with its name as the latest change left it and its key in the trash.
56096
+ */
56097
+ left(anchor2) {
56098
+ const author = anchor2.actorKind === "agent" ? sql`actor_kind = 'agent' AND actor_token_id = ${anchor2.actorTokenId ?? ""}` : sql`actor_kind = 'user' AND actor_user_id = ${anchor2.actorUserId ?? ""}`;
56099
+ const types = JSON.stringify(LEFT_TYPES);
56100
+ const scope = sql`workspace_id = ${anchor2.workspaceId} AND ${author} AND created_at >= ${anchor2.updatedAt.getTime()} AND entity_type IN (SELECT value FROM json_each(${types}))`;
56101
+ const found = this.deps.db.all(
56102
+ sql`SELECT g.entityType, g.entityId, g.actions,
56103
+ (SELECT summary FROM activity n WHERE n.workspace_id = ${anchor2.workspaceId} AND n.entity_id = g.entityId ORDER BY n.created_at DESC, n.rowid DESC LIMIT 1) AS title
56104
+ FROM (SELECT entity_type AS entityType, entity_id AS entityId, json_group_array(DISTINCT action) AS actions, min(rowid) AS first
56105
+ FROM activity WHERE ${scope} GROUP BY entity_type, entity_id) g
56106
+ ORDER BY g.first LIMIT ${MAX_LEFT + 1}`
56107
+ );
56108
+ const total = found.length > MAX_LEFT ? this.deps.db.get(sql`SELECT count(*) AS n FROM (SELECT 1 FROM activity WHERE ${scope} GROUP BY entity_type, entity_id)`)?.n ?? found.length : found.length;
56109
+ const left = found.slice(0, MAX_LEFT).map((r) => {
56110
+ const done = new Set(JSON.parse(r.actions).map((a) => a.slice(a.indexOf(".") + 1)));
56111
+ const trashKey2 = this.inTrash(anchor2.workspaceId, r.entityType, r.entityId);
56112
+ return {
56113
+ entityType: r.entityType,
56114
+ entityId: r.entityId,
56115
+ title: r.title ?? "",
56116
+ actions: LEFT_ACTIONS.filter((a) => done.has(a)),
56117
+ ...trashKey2 ? { trashKey: trashKey2 } : {}
56118
+ };
56119
+ });
56120
+ return { left, leftMore: total - left.length };
54653
56121
  }
54654
56122
  planItem(row, check3, undoing, state) {
54655
56123
  const table = row.entityType === "page" ? pages : cards;
@@ -54663,6 +56131,7 @@ var UndoService = class {
54663
56131
  entityTitle: title ?? (typeof row.meta.title === "string" ? row.meta.title : ""),
54664
56132
  status: check3.status,
54665
56133
  ...check3.reason ? { reason: check3.reason } : {},
56134
+ ...check3.trashKey ? { trashKey: check3.trashKey } : {},
54666
56135
  ...check3.status === "conflict" ? { changedBy: check3.by !== void 0 ? check3.by : this.changedSince(row, check3.exists === void 0, undoing, state), current: check3.current ?? null } : {}
54667
56136
  };
54668
56137
  }
@@ -54714,7 +56183,15 @@ var UndoService = class {
54714
56183
  laterChanges(row, isValue, undoing, state) {
54715
56184
  const author = /* @__PURE__ */ __name((r) => r.kind === "agent" ? `agent:${r.tokenId}` : `user:${r.userId}`, "author");
54716
56185
  const own2 = author({ kind: row.actorKind, userId: row.actorUserId, tokenId: row.actorTokenId });
54717
- return this.deps.db.select({ id: history.id, kind: history.actorKind, userId: history.actorUserId, tokenId: history.actorTokenId, name: history.actorName, meta: history.meta }).from(history).where(and(this.sameThing(row, isValue, state), or(gt(history.updatedAt, row.updatedAt), and(eq(history.updatedAt, row.updatedAt), sql`rowid > ${row.seq}`)))).orderBy(desc(history.updatedAt), desc(sql`rowid`)).all().filter((r) => !undoing.has(r.id) && !undoing.has(String(r.meta.undoOf)) && (isValue || author(r) !== own2));
56186
+ const after = /* @__PURE__ */ __name(() => or(gt(history.updatedAt, row.updatedAt), and(eq(history.updatedAt, row.updatedAt), sql`rowid > ${row.seq}`)), "after");
56187
+ const later = this.deps.db.select({ id: history.id, kind: history.actorKind, userId: history.actorUserId, tokenId: history.actorTokenId, name: history.actorName, meta: history.meta }).from(history).where(and(this.sameThing(row, isValue, state), after())).orderBy(desc(history.updatedAt), desc(sql`rowid`)).all().filter((r) => !undoing.has(r.id) && !undoing.has(String(r.meta.undoOf)));
56188
+ const undoneIds = [...new Set(later.map((r) => r.meta.undoOf).filter((v) => typeof v === "string"))];
56189
+ const theirs = /* @__PURE__ */ new Set();
56190
+ for (let i2 = 0; i2 < undoneIds.length; i2 += CHUNK) {
56191
+ const undone = this.deps.db.select({ id: history.id, kind: history.actorKind, userId: history.actorUserId, tokenId: history.actorTokenId }).from(history).where(and(inArray(history.id, undoneIds.slice(i2, i2 + CHUNK)), after())).all();
56192
+ for (const r of undone) if (author(r) === own2) theirs.add(r.id);
56193
+ }
56194
+ return later.filter((r) => !theirs.has(String(r.meta.undoOf)) && (isValue || author(r) !== own2));
54718
56195
  }
54719
56196
  /** Who changed it after this change, besides the changes being undone with it. */
54720
56197
  changedSince(row, isValue, undoing, state) {
@@ -54730,11 +56207,11 @@ var UndoService = class {
54730
56207
  * The rows of `table` that the trash entries being brought back keep, where `column` is
54731
56208
  * `value`: what they will be once back. Without their long texts, compared where they are kept.
54732
56209
  */
54733
- keptRows(restoring, table, column, value) {
56210
+ keptRows(restoring, table, column2, value) {
54734
56211
  const ids = [...restoring];
54735
56212
  const found = [];
54736
56213
  for (let i2 = 0; i2 < ids.length; i2 += CHUNK) {
54737
- const rows = this.deps.db.select({ trashId: trashRows.trashId, data: sql`json_remove(${trashRows.data}, '$.content', '$.description')` }).from(trashRows).where(and(inArray(trashRows.trashId, ids.slice(i2, i2 + CHUNK)), eq(trashRows.tableName, table), sql`json_extract(${trashRows.data}, ${`$.${column}`}) = ${value}`)).all();
56214
+ const rows = this.deps.db.select({ trashId: trashRows.trashId, data: sql`json_remove(${trashRows.data}, '$.content', '$.description')` }).from(trashRows).where(and(inArray(trashRows.trashId, ids.slice(i2, i2 + CHUNK)), eq(trashRows.tableName, table), sql`json_extract(${trashRows.data}, ${`$.${column2}`}) = ${value}`)).all();
54738
56215
  found.push(...rows.map((r) => ({ trashId: r.trashId, data: JSON.parse(r.data) })));
54739
56216
  }
54740
56217
  return found;
@@ -54743,11 +56220,20 @@ var UndoService = class {
54743
56220
  const id3 = typeof row.meta.trashId === "string" ? row.meta.trashId : null;
54744
56221
  return id3 !== null && Boolean(this.deps.db.select({ id: trash.id }).from(trash).where(eq(trash.id, id3)).get());
54745
56222
  }
56223
+ /** The key of `kind:id` in this workspace's trash, when it is there. */
56224
+ inTrash(workspaceId, kind, id3) {
56225
+ if (!id3) return null;
56226
+ const table = TRASH_TABLES[kind];
56227
+ const found = this.deps.db.get(
56228
+ sql`SELECT 1 AS found FROM trash_rows r JOIN trash t ON t.id = r.trash_id WHERE t.workspace_id = ${workspaceId} AND r.table_name = ${table} AND json_extract(r.data, '$.id') = ${id3} LIMIT 1`
56229
+ );
56230
+ return found ? `${kind}:${id3}` : null;
56231
+ }
54746
56232
  /**
54747
- * Where the page or card a deletion took away goes back, when that is not where it was:
54748
- * restoring puts it elsewhere if its place is gone by then (TrashService.place). By then, the
54749
- * newer changes being undone have brought back what they bring back (`state.restoring`).
54750
- * undefined: where it was; null: nowhere it fits.
56233
+ * Whether the page or card a deletion took away can go back where it was: undoing never puts
56234
+ * it anywhere else. Its place is there, or comes back with the newer changes being undone
56235
+ * (`state.restoring`); a card follows its column if that went to another board. Otherwise:
56236
+ * that place is in the trash (with its key there) or gone for good.
54751
56237
  */
54752
56238
  returnPlace(row, state) {
54753
56239
  const db = this.deps.db;
@@ -54755,21 +56241,23 @@ var UndoService = class {
54755
56241
  const [kept] = this.keptRows(/* @__PURE__ */ new Set([trashId]), row.entityType === "page" ? "pages" : "cards", "id", row.entityId);
54756
56242
  if (!kept) return void 0;
54757
56243
  const data = kept.data;
56244
+ const missing = /* @__PURE__ */ __name((kind, id3) => {
56245
+ const trashKey2 = this.inTrash(row.workspaceId, kind, id3);
56246
+ return trashKey2 ? { reason: "place_in_trash", trashKey: trashKey2 } : { reason: "place_gone" };
56247
+ }, "missing");
54758
56248
  if (row.entityType === "page") {
54759
56249
  const parentId = data.parent_id == null ? null : String(data.parent_id);
54760
- const parentThere = parentId !== null && (Boolean(db.get(sql`SELECT 1 AS found FROM pages WHERE id = ${parentId}`)) || this.keptRows(state.restoring, "pages", "id", parentId).length > 0);
54761
- if (parentThere) return void 0;
54762
- const project = db.get(sql`SELECT id FROM projects WHERE id = ${data.project_id}`)?.id ?? db.get(sql`SELECT id FROM projects WHERE workspace_id = ${row.workspaceId} ORDER BY position, id LIMIT 1`)?.id;
54763
- if (!project) return null;
54764
- return parentId === null && project === data.project_id ? void 0 : { projectId: project, parentId: null };
54765
- }
54766
- const column = db.get(sql`SELECT board_id FROM board_columns WHERE id = ${data.column_id}`);
54767
- if (column) return column.board_id === data.board_id ? void 0 : { boardId: column.board_id, columnId: String(data.column_id) };
54768
- const first = /* @__PURE__ */ __name((scope) => db.get(
54769
- sql`SELECT c.id, b.id AS board_id FROM board_columns c JOIN boards b ON b.id = c.board_id JOIN projects p ON p.id = b.project_id WHERE ${scope} ORDER BY p.position, p.id, b.position, b.id, c.position, c.id LIMIT 1`
54770
- ), "first");
54771
- const target = first(sql`c.board_id = ${data.board_id}`) ?? first(sql`c.workspace_id = ${row.workspaceId}`);
54772
- return target ? { boardId: target.board_id, columnId: target.id } : null;
56250
+ if (parentId !== null) {
56251
+ const there = Boolean(db.get(sql`SELECT 1 AS found FROM pages WHERE id = ${parentId}`)) || this.keptRows(state.restoring, "pages", "id", parentId).length > 0;
56252
+ return there ? void 0 : missing("page", parentId);
56253
+ }
56254
+ const projectId = String(data.project_id);
56255
+ return db.get(sql`SELECT 1 AS found FROM projects WHERE id = ${projectId}`) ? void 0 : missing("project", projectId);
56256
+ }
56257
+ const columnId = String(data.column_id);
56258
+ const column2 = db.get(sql`SELECT board_id FROM board_columns WHERE id = ${columnId}`);
56259
+ if (!column2) return missing("column", columnId);
56260
+ return column2.board_id === data.board_id ? void 0 : { boardId: column2.board_id, columnId };
54773
56261
  }
54774
56262
  /** How undoing this change stands, against `state`: now, and after the newer changes being undone. */
54775
56263
  check(row, undoing, state) {
@@ -54781,7 +56269,7 @@ var UndoService = class {
54781
56269
  const one = /* @__PURE__ */ __name((query) => query.get(), "one");
54782
56270
  const has = /* @__PURE__ */ __name((key, real2) => state.exists.get(key) ?? real2(), "has");
54783
56271
  const returning = /* @__PURE__ */ __name((id3) => [...state.restoring].some((trashId) => this.kept(trashId, id3) !== void 0), "returning");
54784
- const kept = /* @__PURE__ */ __name((table, id3, column = "id") => this.keptRows(state.restoring, table, column, id3), "kept");
56272
+ const kept = /* @__PURE__ */ __name((table, id3, column2 = "id") => this.keptRows(state.restoring, table, column2, id3), "kept");
54785
56273
  const text2 = /* @__PURE__ */ __name((v) => v == null ? null : String(v), "text");
54786
56274
  const date5 = /* @__PURE__ */ __name((v) => v == null ? null : new Date(Number(v)), "date");
54787
56275
  const entityKey = `${row.entityType}:${row.entityId}`;
@@ -54802,18 +56290,21 @@ var UndoService = class {
54802
56290
  if (status === "ready") state.exists.set(key, false);
54803
56291
  return { status, exists: false };
54804
56292
  }, "takeAway");
54805
- const value = /* @__PURE__ */ __name((current, same = (a, b) => a === b, place, key = fieldKey(row), back = before) => {
56293
+ const value = /* @__PURE__ */ __name((current, same = (a, b) => a === b, place, key = fieldKey(row), back = before, inTrash) => {
54806
56294
  const now = state.values.has(key) ? state.values.get(key) : current;
54807
56295
  if (same(now, back)) return { status: "unchanged" };
54808
- if (place && !place()) return { status: "impossible", reason: "place_gone" };
56296
+ if (place && !place()) {
56297
+ const trashKey2 = inTrash?.();
56298
+ return trashKey2 ? { status: "impossible", reason: "place_in_trash", trashKey: trashKey2 } : { status: "impossible", reason: "place_gone" };
56299
+ }
54809
56300
  const status = same(now, after) ? "ready" : "conflict";
54810
56301
  if (status === "ready") state.values.set(key, back);
54811
56302
  return { status, current: now };
54812
56303
  }, "value");
54813
- const body = /* @__PURE__ */ __name((table, column, trashId) => {
56304
+ const body = /* @__PURE__ */ __name((table, column2, trashId) => {
54814
56305
  const key = fieldKey(row);
54815
56306
  const ref = state.bodies.get(key);
54816
- const now = ref ? sql`(SELECT "before" FROM history WHERE id = ${ref})` : trashId ? sql`(SELECT json_extract(data, ${`$.${column}`}) FROM trash_rows WHERE trash_id = ${trashId} AND table_name = ${table} AND json_extract(data, '$.id') = ${row.entityId})` : sql`(SELECT ${sql.identifier(column)} FROM ${sql.identifier(table)} WHERE id = ${row.entityId})`;
56307
+ const now = ref ? sql`(SELECT "before" FROM history WHERE id = ${ref})` : trashId ? sql`(SELECT json_extract(data, ${`$.${column2}`}) FROM trash_rows WHERE trash_id = ${trashId} AND table_name = ${table} AND json_extract(data, '$.id') = ${row.entityId})` : sql`(SELECT ${sql.identifier(column2)} FROM ${sql.identifier(table)} WHERE id = ${row.entityId})`;
54817
56308
  const found = db.get(
54818
56309
  sql`SELECT ${now} IS h."before" AS isBefore, ${now} IS h."after" AS isAfter, substr(${now}, 1, 200) AS current FROM history h WHERE h.id = ${row.id}`
54819
56310
  );
@@ -54828,7 +56319,7 @@ var UndoService = class {
54828
56319
  case "card.deleted": {
54829
56320
  if (has(entityKey, () => entityExists)) return { status: "unchanged" };
54830
56321
  const place = this.returnPlace(row, state);
54831
- if (place === null) return { status: "impossible", reason: "place_gone" };
56322
+ if (place && "reason" in place) return { status: "impossible", ...place };
54832
56323
  const check3 = bringBack(entityKey, () => entityExists);
54833
56324
  if (check3.status === "ready" && place) state.values.set(`${row.entityId}|${row.entityType}.moved|`, place);
54834
56325
  return check3;
@@ -54856,7 +56347,14 @@ var UndoService = class {
54856
56347
  const id3 = back?.pageId ?? back?.cardId ?? "";
54857
56348
  return Boolean(one(db.select({ id: table.id }).from(table).where(and(eq(table.id, id3), eq(table.workspaceId, at.workspaceId))))) || kept(back?.pageId ? "pages" : "cards", id3).some(({ data }) => data.workspace_id === at.workspaceId);
54858
56349
  }, "there");
54859
- return value({ cardId: at.cardId, pageId: at.pageId }, (a, b) => fileAt(a) === fileAt(b), there, key);
56350
+ return value(
56351
+ { cardId: at.cardId, pageId: at.pageId },
56352
+ (a, b) => fileAt(a) === fileAt(b),
56353
+ there,
56354
+ key,
56355
+ before,
56356
+ () => this.inTrash(row.workspaceId, back?.pageId ? "page" : "card", back?.pageId ?? back?.cardId ?? null)
56357
+ );
54860
56358
  }
54861
56359
  }
54862
56360
  if (row.entityType === "page") {
@@ -54877,7 +56375,10 @@ var UndoService = class {
54877
56375
  { projectId: page.projectId, parentId: page.parentId },
54878
56376
  (a, b) => parentOf(a) === parentOf(b),
54879
56377
  // Its old parent: there, or coming back from the trash first.
54880
- () => target === null || Boolean(one(db.select({ id: pages.id }).from(pages).where(and(eq(pages.id, target ?? ""), eq(pages.projectId, page.projectId))))) || kept("pages", target ?? "").some(({ data }) => data.project_id === page.projectId)
56378
+ () => target === null || Boolean(one(db.select({ id: pages.id }).from(pages).where(and(eq(pages.id, target ?? ""), eq(pages.projectId, page.projectId))))) || kept("pages", target ?? "").some(({ data }) => data.project_id === page.projectId),
56379
+ fieldKey(row),
56380
+ before,
56381
+ () => this.inTrash(row.workspaceId, "page", target ?? null)
54881
56382
  );
54882
56383
  }
54883
56384
  }
@@ -54928,7 +56429,10 @@ var UndoService = class {
54928
56429
  { boardId: card.boardId, columnId: card.columnId },
54929
56430
  (a, b) => columnOf(a) === columnOf(b),
54930
56431
  // Its old column, on its board or another one of the same workspace.
54931
- () => Boolean(one(db.select({ id: columns.id }).from(columns).where(and(eq(columns.id, target ?? ""), eq(columns.workspaceId, card.workspaceId)))))
56432
+ () => Boolean(one(db.select({ id: columns.id }).from(columns).where(and(eq(columns.id, target ?? ""), eq(columns.workspaceId, card.workspaceId))))),
56433
+ key,
56434
+ before,
56435
+ () => this.inTrash(row.workspaceId, "column", target ?? null)
54932
56436
  );
54933
56437
  const toOtherBoard = before?.boardId !== void 0 && before.boardId !== place.boardId;
54934
56438
  if (check3.status !== "ready" || !toOtherBoard) return check3;
@@ -55141,6 +56645,7 @@ var UpdateService = class {
55141
56645
 
55142
56646
  // src/services/vault.ts
55143
56647
  var keyChanged = /* @__PURE__ */ __name(() => new AppError(409, "vault_key_changed", "The vault changed since it was opened here: open it again"), "keyChanged");
56648
+ var itemChanged = /* @__PURE__ */ __name(() => new AppError(409, "vault_item_changed", "This item changed in another tab or device since it was opened here"), "itemChanged");
55144
56649
  var VaultService = class {
55145
56650
  constructor(deps, access) {
55146
56651
  this.deps = deps;
@@ -55211,25 +56716,32 @@ var VaultService = class {
55211
56716
  /** Saves an item encrypted with the vault key the vault has now, checked and written at once. */
55212
56717
  async putItem(actor, itemId, input2) {
55213
56718
  this.guard(actor);
55214
- const { data, keyVersion: keyVersion2 } = parse3(vaultItemInput, input2);
56719
+ const { data, keyVersion: keyVersion2, baseUpdatedAt } = parse3(vaultItemInput, input2);
55215
56720
  const row = this.deps.db.transaction((tx) => {
55216
56721
  const vault = tx.select({ wrappedKey: vaults.wrappedKey, keyVersion: vaults.keyVersion }).from(vaults).where(eq(vaults.userId, actor.userId)).get();
55217
56722
  if (!vault) throw conflict("Set up the vault first");
55218
56723
  if (!vault.wrappedKey || vault.keyVersion !== keyVersion2) throw keyChanged();
55219
- const owner = tx.select({ userId: vaultItems.userId }).from(vaultItems).where(eq(vaultItems.id, itemId)).get();
56724
+ const owner = tx.select({ userId: vaultItems.userId, updatedAt: vaultItems.updatedAt }).from(vaultItems).where(eq(vaultItems.id, itemId)).get();
55220
56725
  if (owner && owner.userId !== actor.userId) throw notFound("Item");
56726
+ if (baseUpdatedAt !== void 0 && (owner ? owner.updatedAt.toISOString() : null) !== baseUpdatedAt) throw itemChanged();
55221
56727
  if (!owner) {
55222
56728
  const stored = tx.select({ n: count() }).from(vaultItems).where(eq(vaultItems.userId, actor.userId)).get();
55223
56729
  if ((stored?.n ?? 0) >= MAX_VAULT_ITEMS) throw new AppError(409, "vault_full", `The vault holds up to ${MAX_VAULT_ITEMS} items`);
55224
56730
  }
55225
- return tx.insert(vaultItems).values({ id: itemId, userId: actor.userId, data, keyVersion: keyVersion2 }).onConflictDoUpdate({ target: vaultItems.id, set: { data, keyVersion: keyVersion2, updatedAt: /* @__PURE__ */ new Date() }, where: eq(vaultItems.userId, actor.userId) }).returning().get();
56731
+ const updatedAt2 = new Date(Math.max(Date.now(), (owner?.updatedAt.getTime() ?? 0) + 1));
56732
+ return tx.insert(vaultItems).values({ id: itemId, userId: actor.userId, data, keyVersion: keyVersion2, updatedAt: updatedAt2 }).onConflictDoUpdate({ target: vaultItems.id, set: { data, keyVersion: keyVersion2, updatedAt: updatedAt2 }, where: eq(vaultItems.userId, actor.userId) }).returning().get();
55226
56733
  });
55227
56734
  return { id: row.id, data: row.data, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() };
55228
56735
  }
55229
- async deleteItem(actor, itemId) {
56736
+ /** `baseUpdatedAt`, as for putItem: refused when the item changed since this tab read it. */
56737
+ async deleteItem(actor, itemId, baseUpdatedAt) {
55230
56738
  this.guard(actor);
55231
- const [row] = await this.deps.db.delete(vaultItems).where(and(eq(vaultItems.id, itemId), eq(vaultItems.userId, actor.userId))).returning({ id: vaultItems.id });
55232
- if (!row) throw notFound("Item");
56739
+ this.deps.db.transaction((tx) => {
56740
+ const row = tx.select({ updatedAt: vaultItems.updatedAt }).from(vaultItems).where(and(eq(vaultItems.id, itemId), eq(vaultItems.userId, actor.userId))).get();
56741
+ if (!row) throw notFound("Item");
56742
+ if (baseUpdatedAt !== void 0 && row.updatedAt.toISOString() !== baseUpdatedAt) throw itemChanged();
56743
+ tx.delete(vaultItems).where(and(eq(vaultItems.id, itemId), eq(vaultItems.userId, actor.userId))).run();
56744
+ });
55233
56745
  }
55234
56746
  /** Irreversibly wipes the vault (used when both the master password and recovery key are lost). */
55235
56747
  async reset(actor) {
@@ -55709,7 +57221,9 @@ var OrqevioCopy = class extends DurableObject {
55709
57221
  app;
55710
57222
  constructor(ctx, env) {
55711
57223
  super(ctx, env);
55712
- this.config = workerEnv(env);
57224
+ const problem = workerConfigProblem(env);
57225
+ if (problem) console.error(`Orqevio can't serve requests: ${problem}`);
57226
+ this.config = workerEnv(problem ? { ...env, APP_URL: void 0 } : env);
55713
57227
  const db = drizzle(ctx.storage, { schema: schema_exports });
55714
57228
  this.services = createServices({
55715
57229
  db,
@@ -55797,10 +57311,17 @@ var OrqevioCopy = class extends DurableObject {
55797
57311
  };
55798
57312
 
55799
57313
  // src/worker/index.ts
57314
+ var logged = null;
55800
57315
  var TO_COPY = /^\/(?:api\/|mcp$|healthz$|oauth\/(?:register|token|revoke)$|\.well-known\/)/;
55801
57316
  var index_default = {
55802
57317
  async fetch(request, env) {
55803
57318
  const url2 = new URL(request.url);
57319
+ const problem = workerConfigProblem(env);
57320
+ if (problem) {
57321
+ if (logged !== problem) console.error(`Orqevio can't start: ${problem}`);
57322
+ logged = problem;
57323
+ return misconfigured(request, problem);
57324
+ }
55804
57325
  if (TO_COPY.test(url2.pathname)) return env.COPY.getByName("copy").fetch(request);
55805
57326
  const response = await env.ASSETS.fetch(request);
55806
57327
  const headers = new Headers(response.headers);