@arbidocs/blocks 0.5.29 → 0.5.30

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 (202) hide show
  1. package/dist/{ConnectedCallDock-FDGMFTS5.js → ConnectedCallDock-AWSOPETT.js} +12 -12
  2. package/dist/{ConnectedCallDock-FDGMFTS5.js.map → ConnectedCallDock-AWSOPETT.js.map} +1 -1
  3. package/dist/{ConnectedCallDock-ZIX2ZJCD.cjs → ConnectedCallDock-GM4KOBBS.cjs} +13 -13
  4. package/dist/{ConnectedCallDock-ZIX2ZJCD.cjs.map → ConnectedCallDock-GM4KOBBS.cjs.map} +1 -1
  5. package/dist/{ConnectedCallRoom-VJIHEJ4X.js → ConnectedCallRoom-JMB74KTV.js} +12 -12
  6. package/dist/{ConnectedCallRoom-VJIHEJ4X.js.map → ConnectedCallRoom-JMB74KTV.js.map} +1 -1
  7. package/dist/{ConnectedCallRoom-WZQVXDDW.cjs → ConnectedCallRoom-QE2MMJ6M.cjs} +13 -13
  8. package/dist/{ConnectedCallRoom-WZQVXDDW.cjs.map → ConnectedCallRoom-QE2MMJ6M.cjs.map} +1 -1
  9. package/dist/{ConnectedNativeDocxComparison-KSLSDAAP.cjs → ConnectedNativeDocxComparison-P7IHRMCS.cjs} +17 -17
  10. package/dist/{ConnectedNativeDocxComparison-KSLSDAAP.cjs.map → ConnectedNativeDocxComparison-P7IHRMCS.cjs.map} +1 -1
  11. package/dist/{ConnectedNativeDocxComparison-7ZC7BRY4.js → ConnectedNativeDocxComparison-T6JRDIMR.js} +16 -16
  12. package/dist/{ConnectedNativeDocxComparison-7ZC7BRY4.js.map → ConnectedNativeDocxComparison-T6JRDIMR.js.map} +1 -1
  13. package/dist/{ConnectedNativeDocxEditor-5E64Q7FX.cjs → ConnectedNativeDocxEditor-HBV5EJ63.cjs} +17 -17
  14. package/dist/{ConnectedNativeDocxEditor-5E64Q7FX.cjs.map → ConnectedNativeDocxEditor-HBV5EJ63.cjs.map} +1 -1
  15. package/dist/{ConnectedNativeDocxEditor-B5KDDPRY.js → ConnectedNativeDocxEditor-X6YNPGRL.js} +15 -15
  16. package/dist/{ConnectedNativeDocxEditor-B5KDDPRY.js.map → ConnectedNativeDocxEditor-X6YNPGRL.js.map} +1 -1
  17. package/dist/{ConnectedStreamedWordArtifact-RLU5VYGO.cjs → ConnectedStreamedWordArtifact-GYJEQO4M.cjs} +17 -17
  18. package/dist/ConnectedStreamedWordArtifact-GYJEQO4M.cjs.map +1 -0
  19. package/dist/{ConnectedStreamedWordArtifact-YCQSIGXL.js → ConnectedStreamedWordArtifact-X7R6PBRT.js} +16 -16
  20. package/dist/ConnectedStreamedWordArtifact-X7R6PBRT.js.map +1 -0
  21. package/dist/{WorkspaceTableView-BUWRSR42.cjs → WorkspaceTableView-FTQZJDRB.cjs} +10 -10
  22. package/dist/{WorkspaceTableView-BUWRSR42.cjs.map → WorkspaceTableView-FTQZJDRB.cjs.map} +1 -1
  23. package/dist/{WorkspaceTableView-62PJLX7V.js → WorkspaceTableView-NWRVACJL.js} +8 -8
  24. package/dist/{WorkspaceTableView-62PJLX7V.js.map → WorkspaceTableView-NWRVACJL.js.map} +1 -1
  25. package/dist/agents/index.cjs +373 -373
  26. package/dist/agents/index.js +11 -11
  27. package/dist/calls/index.cjs +39 -39
  28. package/dist/calls/index.js +7 -7
  29. package/dist/chat/index.cjs +167 -167
  30. package/dist/chat/index.js +9 -9
  31. package/dist/{chunk-CPJ2B3QQ.cjs → chunk-24Y36OK6.cjs} +9 -9
  32. package/dist/{chunk-CPJ2B3QQ.cjs.map → chunk-24Y36OK6.cjs.map} +1 -1
  33. package/dist/{chunk-XDFH6ONO.cjs → chunk-2DO5YPDH.cjs} +16 -16
  34. package/dist/{chunk-XDFH6ONO.cjs.map → chunk-2DO5YPDH.cjs.map} +1 -1
  35. package/dist/{chunk-GJI5PEGR.js → chunk-2JARBDEK.js} +4 -4
  36. package/dist/{chunk-GJI5PEGR.js.map → chunk-2JARBDEK.js.map} +1 -1
  37. package/dist/{chunk-HT62K3UO.cjs → chunk-3YVWAYXU.cjs} +4 -4
  38. package/dist/{chunk-HT62K3UO.cjs.map → chunk-3YVWAYXU.cjs.map} +1 -1
  39. package/dist/{chunk-EJSVRT3G.js → chunk-5VSMJ674.js} +56 -66
  40. package/dist/chunk-5VSMJ674.js.map +1 -0
  41. package/dist/{chunk-XGUN44A4.js → chunk-5XG7YD4V.js} +8 -8
  42. package/dist/{chunk-XGUN44A4.js.map → chunk-5XG7YD4V.js.map} +1 -1
  43. package/dist/{chunk-EVV32AXB.cjs → chunk-62G4HK7C.cjs} +6 -6
  44. package/dist/{chunk-EVV32AXB.cjs.map → chunk-62G4HK7C.cjs.map} +1 -1
  45. package/dist/{chunk-7U2DNPMZ.cjs → chunk-63FOCF46.cjs} +12 -12
  46. package/dist/{chunk-7U2DNPMZ.cjs.map → chunk-63FOCF46.cjs.map} +1 -1
  47. package/dist/{chunk-NIS5TLOM.cjs → chunk-6LVVW6VB.cjs} +4 -4
  48. package/dist/{chunk-NIS5TLOM.cjs.map → chunk-6LVVW6VB.cjs.map} +1 -1
  49. package/dist/{chunk-JS7KJRKG.js → chunk-75Z5AUMM.js} +3 -3
  50. package/dist/{chunk-JS7KJRKG.js.map → chunk-75Z5AUMM.js.map} +1 -1
  51. package/dist/{chunk-CRUCMRFC.cjs → chunk-76G2DAOF.cjs} +18 -18
  52. package/dist/{chunk-CRUCMRFC.cjs.map → chunk-76G2DAOF.cjs.map} +1 -1
  53. package/dist/{chunk-AHYSHKPL.cjs → chunk-7THRBD42.cjs} +57 -16
  54. package/dist/chunk-7THRBD42.cjs.map +1 -0
  55. package/dist/{chunk-SBHWRN2D.js → chunk-BBSXBABG.js} +3 -3
  56. package/dist/{chunk-SBHWRN2D.js.map → chunk-BBSXBABG.js.map} +1 -1
  57. package/dist/{chunk-WG2VDUEI.cjs → chunk-BVMPP574.cjs} +4 -4
  58. package/dist/{chunk-WG2VDUEI.cjs.map → chunk-BVMPP574.cjs.map} +1 -1
  59. package/dist/{chunk-3IRIITUW.cjs → chunk-BVXI7W7Z.cjs} +9 -9
  60. package/dist/{chunk-3IRIITUW.cjs.map → chunk-BVXI7W7Z.cjs.map} +1 -1
  61. package/dist/{chunk-EVYUYVH2.cjs → chunk-C5J74Y6N.cjs} +5 -5
  62. package/dist/{chunk-EVYUYVH2.cjs.map → chunk-C5J74Y6N.cjs.map} +1 -1
  63. package/dist/{chunk-WY626DNG.cjs → chunk-CGUDTSGI.cjs} +10 -10
  64. package/dist/{chunk-WY626DNG.cjs.map → chunk-CGUDTSGI.cjs.map} +1 -1
  65. package/dist/{chunk-WBCGVEJX.js → chunk-CMTAOVUX.js} +3 -3
  66. package/dist/{chunk-WBCGVEJX.js.map → chunk-CMTAOVUX.js.map} +1 -1
  67. package/dist/{chunk-OGADWN5L.js → chunk-DHTBHALC.js} +4 -4
  68. package/dist/{chunk-OGADWN5L.js.map → chunk-DHTBHALC.js.map} +1 -1
  69. package/dist/{chunk-UXIMEFEF.js → chunk-DWERY33L.js} +8 -8
  70. package/dist/{chunk-UXIMEFEF.js.map → chunk-DWERY33L.js.map} +1 -1
  71. package/dist/{chunk-A634VUNB.js → chunk-EPNJOP2M.js} +5 -5
  72. package/dist/{chunk-A634VUNB.js.map → chunk-EPNJOP2M.js.map} +1 -1
  73. package/dist/{chunk-4RMI6D64.cjs → chunk-EZLZ3MDU.cjs} +3 -3
  74. package/dist/{chunk-4RMI6D64.cjs.map → chunk-EZLZ3MDU.cjs.map} +1 -1
  75. package/dist/{chunk-3OKBEVP3.js → chunk-FAILAFD6.js} +3 -3
  76. package/dist/{chunk-3OKBEVP3.js.map → chunk-FAILAFD6.js.map} +1 -1
  77. package/dist/{chunk-OZSAQJO4.js → chunk-FODIZWMX.js} +3 -3
  78. package/dist/{chunk-OZSAQJO4.js.map → chunk-FODIZWMX.js.map} +1 -1
  79. package/dist/{chunk-V2GEULRG.cjs → chunk-GK35JEWW.cjs} +4 -4
  80. package/dist/{chunk-V2GEULRG.cjs.map → chunk-GK35JEWW.cjs.map} +1 -1
  81. package/dist/{chunk-52GITM4V.cjs → chunk-GNWQS6S4.cjs} +144 -154
  82. package/dist/{chunk-EJSVRT3G.js.map → chunk-GNWQS6S4.cjs.map} +1 -1
  83. package/dist/{chunk-R3HZBTE3.cjs → chunk-HMEP4EZ3.cjs} +4 -4
  84. package/dist/{chunk-R3HZBTE3.cjs.map → chunk-HMEP4EZ3.cjs.map} +1 -1
  85. package/dist/{chunk-5ETT7ZIO.js → chunk-IYKGI2DQ.js} +3 -3
  86. package/dist/{chunk-5ETT7ZIO.js.map → chunk-IYKGI2DQ.js.map} +1 -1
  87. package/dist/{chunk-3PQPA5K6.cjs → chunk-J4VP2PQJ.cjs} +28 -28
  88. package/dist/{chunk-3PQPA5K6.cjs.map → chunk-J4VP2PQJ.cjs.map} +1 -1
  89. package/dist/{chunk-TY76UEFK.js → chunk-JLJVEQFN.js} +6 -6
  90. package/dist/{chunk-TY76UEFK.js.map → chunk-JLJVEQFN.js.map} +1 -1
  91. package/dist/{chunk-G3MZ5S2Q.js → chunk-KYHDMUPW.js} +3 -3
  92. package/dist/{chunk-G3MZ5S2Q.js.map → chunk-KYHDMUPW.js.map} +1 -1
  93. package/dist/{chunk-DF2GSH4D.js → chunk-L2MMIC3S.js} +3 -3
  94. package/dist/{chunk-DF2GSH4D.js.map → chunk-L2MMIC3S.js.map} +1 -1
  95. package/dist/{chunk-46XON6PW.js → chunk-L4Q7FWBQ.js} +3 -3
  96. package/dist/{chunk-46XON6PW.js.map → chunk-L4Q7FWBQ.js.map} +1 -1
  97. package/dist/{chunk-OQCUIN6Z.cjs → chunk-M6N7XJH7.cjs} +5 -5
  98. package/dist/{chunk-OQCUIN6Z.cjs.map → chunk-M6N7XJH7.cjs.map} +1 -1
  99. package/dist/{chunk-MTHAQGJB.js → chunk-MNLMPH45.js} +3 -3
  100. package/dist/{chunk-MTHAQGJB.js.map → chunk-MNLMPH45.js.map} +1 -1
  101. package/dist/{chunk-W43S7COD.js → chunk-NBQNDHOW.js} +4 -4
  102. package/dist/{chunk-W43S7COD.js.map → chunk-NBQNDHOW.js.map} +1 -1
  103. package/dist/{chunk-7YGUUUL7.cjs → chunk-NF7CGYZF.cjs} +4 -4
  104. package/dist/{chunk-7YGUUUL7.cjs.map → chunk-NF7CGYZF.cjs.map} +1 -1
  105. package/dist/{chunk-DNGA25ZA.js → chunk-NI3O4UZL.js} +5 -5
  106. package/dist/{chunk-DNGA25ZA.js.map → chunk-NI3O4UZL.js.map} +1 -1
  107. package/dist/{chunk-T3JW5BYG.cjs → chunk-OSCWFBRD.cjs} +4 -4
  108. package/dist/{chunk-T3JW5BYG.cjs.map → chunk-OSCWFBRD.cjs.map} +1 -1
  109. package/dist/{chunk-TKOP6WMD.js → chunk-OYKITGTK.js} +4 -4
  110. package/dist/{chunk-TKOP6WMD.js.map → chunk-OYKITGTK.js.map} +1 -1
  111. package/dist/{chunk-2TB4UDBH.js → chunk-PKDGP6ZH.js} +3 -3
  112. package/dist/{chunk-2TB4UDBH.js.map → chunk-PKDGP6ZH.js.map} +1 -1
  113. package/dist/{chunk-AKW4JLHQ.cjs → chunk-PO2QI2OI.cjs} +4 -4
  114. package/dist/{chunk-AKW4JLHQ.cjs.map → chunk-PO2QI2OI.cjs.map} +1 -1
  115. package/dist/{chunk-4UREQY5X.js → chunk-Q56LAJRP.js} +4 -4
  116. package/dist/{chunk-4UREQY5X.js.map → chunk-Q56LAJRP.js.map} +1 -1
  117. package/dist/{chunk-SQAVWMGV.cjs → chunk-R6GIDWEH.cjs} +59 -59
  118. package/dist/{chunk-SQAVWMGV.cjs.map → chunk-R6GIDWEH.cjs.map} +1 -1
  119. package/dist/{chunk-KKBYWVEL.js → chunk-SLGRQMHW.js} +5 -5
  120. package/dist/{chunk-KKBYWVEL.js.map → chunk-SLGRQMHW.js.map} +1 -1
  121. package/dist/{chunk-LXB756TN.cjs → chunk-SN5VHPF4.cjs} +3 -3
  122. package/dist/{chunk-LXB756TN.cjs.map → chunk-SN5VHPF4.cjs.map} +1 -1
  123. package/dist/{chunk-CJWZYK5K.cjs → chunk-SVL2OM7T.cjs} +5 -5
  124. package/dist/{chunk-CJWZYK5K.cjs.map → chunk-SVL2OM7T.cjs.map} +1 -1
  125. package/dist/{chunk-SSRFSSIT.js → chunk-TGVBLXLV.js} +52 -17
  126. package/dist/chunk-TGVBLXLV.js.map +1 -0
  127. package/dist/{chunk-DV25UPJ7.js → chunk-THNTNAYI.js} +3 -3
  128. package/dist/{chunk-DV25UPJ7.js.map → chunk-THNTNAYI.js.map} +1 -1
  129. package/dist/{chunk-AYAWG2CM.js → chunk-TNWJPTDG.js} +3 -3
  130. package/dist/{chunk-AYAWG2CM.js.map → chunk-TNWJPTDG.js.map} +1 -1
  131. package/dist/{chunk-SN7X7C7H.cjs → chunk-UAMY7KHW.cjs} +5 -5
  132. package/dist/{chunk-SN7X7C7H.cjs.map → chunk-UAMY7KHW.cjs.map} +1 -1
  133. package/dist/{chunk-H72SWOUS.js → chunk-VTGRCJLP.js} +3 -3
  134. package/dist/{chunk-H72SWOUS.js.map → chunk-VTGRCJLP.js.map} +1 -1
  135. package/dist/{chunk-W5PKYJX5.cjs → chunk-W6DDSZUD.cjs} +14 -14
  136. package/dist/{chunk-W5PKYJX5.cjs.map → chunk-W6DDSZUD.cjs.map} +1 -1
  137. package/dist/{chunk-ZXXXLYZY.cjs → chunk-WG2IPVLA.cjs} +7 -7
  138. package/dist/{chunk-ZXXXLYZY.cjs.map → chunk-WG2IPVLA.cjs.map} +1 -1
  139. package/dist/{chunk-RWU3C4MK.js → chunk-WLWY43FR.js} +3 -3
  140. package/dist/{chunk-RWU3C4MK.js.map → chunk-WLWY43FR.js.map} +1 -1
  141. package/dist/{chunk-OZRGYS3J.js → chunk-X3LM4KRW.js} +3 -3
  142. package/dist/{chunk-OZRGYS3J.js.map → chunk-X3LM4KRW.js.map} +1 -1
  143. package/dist/{chunk-IZJ3BOJO.js → chunk-XMDIXNLW.js} +3 -3
  144. package/dist/{chunk-IZJ3BOJO.js.map → chunk-XMDIXNLW.js.map} +1 -1
  145. package/dist/{chunk-7FKVJUR4.js → chunk-Y6F6UF2W.js} +3 -3
  146. package/dist/{chunk-7FKVJUR4.js.map → chunk-Y6F6UF2W.js.map} +1 -1
  147. package/dist/{chunk-F72ZD5Q2.cjs → chunk-YD3RN2FY.cjs} +3 -3
  148. package/dist/{chunk-F72ZD5Q2.cjs.map → chunk-YD3RN2FY.cjs.map} +1 -1
  149. package/dist/{chunk-QHWDV2VB.cjs → chunk-YJJNDKA3.cjs} +6 -6
  150. package/dist/{chunk-QHWDV2VB.cjs.map → chunk-YJJNDKA3.cjs.map} +1 -1
  151. package/dist/{chunk-NZCAWWV4.cjs → chunk-YP643FYT.cjs} +4 -4
  152. package/dist/{chunk-NZCAWWV4.cjs.map → chunk-YP643FYT.cjs.map} +1 -1
  153. package/dist/{chunk-BBTHGWZO.cjs → chunk-ZUOU54X3.cjs} +5 -5
  154. package/dist/{chunk-BBTHGWZO.cjs.map → chunk-ZUOU54X3.cjs.map} +1 -1
  155. package/dist/citations/index.cjs +10 -10
  156. package/dist/citations/index.js +2 -2
  157. package/dist/collaboration/index.cjs +9 -9
  158. package/dist/collaboration/index.js +1 -1
  159. package/dist/connect/docx.cjs +19 -19
  160. package/dist/connect/docx.js +15 -15
  161. package/dist/connect/index.cjs +1885 -1856
  162. package/dist/connect/index.cjs.map +1 -1
  163. package/dist/connect/index.d.ts +1 -0
  164. package/dist/connect/index.js +686 -659
  165. package/dist/connect/index.js.map +1 -1
  166. package/dist/connect/viewer.cjs +83 -83
  167. package/dist/connect/viewer.js +18 -18
  168. package/dist/connection/ConnectedSettings.d.ts +1 -1
  169. package/dist/connection/dialogs/ConnectedGlobalDialogs.d.ts +26 -0
  170. package/dist/connection/dialogs/index.d.ts +1 -0
  171. package/dist/connection/files/upload/ConnectedUploadDropzone.d.ts +2 -1
  172. package/dist/connection/workspace-access/access-review.d.ts +6 -0
  173. package/dist/facts/index.cjs +60 -60
  174. package/dist/facts/index.js +7 -7
  175. package/dist/files/index.cjs +225 -225
  176. package/dist/files/index.js +5 -5
  177. package/dist/home/index.cjs +31 -31
  178. package/dist/home/index.js +6 -6
  179. package/dist/index.cjs +780 -756
  180. package/dist/index.d.ts +2 -1
  181. package/dist/index.js +27 -27
  182. package/dist/provider/dialog-registry.d.ts +85 -0
  183. package/dist/provider/environment.d.ts +11 -11
  184. package/dist/retrieval/index.cjs +4 -4
  185. package/dist/retrieval/index.js +2 -2
  186. package/dist/settings/index.cjs +156 -156
  187. package/dist/settings/index.js +3 -3
  188. package/dist/shell/index.cjs +42 -42
  189. package/dist/shell/index.js +4 -4
  190. package/dist/studio/index.cjs +18 -18
  191. package/dist/studio/index.js +10 -10
  192. package/dist/workflow-canvas/index.cjs +69 -69
  193. package/dist/workflow-canvas/index.js +14 -14
  194. package/dist/workspaces/index.cjs +29 -29
  195. package/dist/workspaces/index.js +4 -4
  196. package/node_modules/@arbidocs/coedit/package.json +1 -1
  197. package/package.json +5 -5
  198. package/dist/ConnectedStreamedWordArtifact-RLU5VYGO.cjs.map +0 -1
  199. package/dist/ConnectedStreamedWordArtifact-YCQSIGXL.js.map +0 -1
  200. package/dist/chunk-52GITM4V.cjs.map +0 -1
  201. package/dist/chunk-AHYSHKPL.cjs.map +0 -1
  202. package/dist/chunk-SSRFSSIT.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { ProjectReadout, ProjectBreakdown } from './chunk-RQKWYKZY.js';
3
- import { PlanBadge, QuotaMeter } from './chunk-OZRGYS3J.js';
3
+ import { PlanBadge, QuotaMeter } from './chunk-X3LM4KRW.js';
4
4
  import { UsageMeter } from './chunk-66TA5IBN.js';
5
5
  import { useHost } from './chunk-T4P237N6.js';
6
6
  import { useArbi, formatGbp, useUserSettings } from '@arbidocs/react';
@@ -421,5 +421,5 @@ function projectGroupBilling(project, { isOwned, stripeEnabled }) {
421
421
  }
422
422
 
423
423
  export { ADDON_BLOCK_AI_GBP, ANNUAL_PREMIUM_AI_NOTE, CAP_REACHED_MESSAGE, DEFAULT_SPEND_CAP_PENCE, FREE_AI_GBP, FREE_COLLABORATORS, FREE_STORAGE_MB, MAX_CHECKOUT_BLOCKS, MIN_AUTO_TOPUP_THRESHOLD_GBP, PAY_TODAY_UNPRICED, PLAN_CHOICE_PACKS, POSTCODE_COUNTRIES, PRO_AI_GBP, PRO_PACKS, PRO_STORAGE_GB, STORAGE_BLOCK_GB, SUGGESTED_DAILY_CAP_PER_USER, TAX_LOCATION_INVALID, USAGE_CAP_HELP, USAGE_CAP_LABEL, ZERO_BUDGET_MESSAGE, addStepCaption, addonCharge, addonPrice, addonSettingsBody, aiUsageResetTimestamp, apiErrorDetail, autoRoom, blocksLabel, budgetSavedMessage, calcSavingsPercent, checkoutBlockPriceText, checkoutItemsLabel, findProPrices, formatMoney, formatPeriodEnd, formatResetDate, getQuotaItems, isAddonBudgetZero, isProProject, money2, nextPeriodBody, nextRemovedBlockSize, packPrice, parseBudgetPounds, planBadgeView, planName, planNameForPacks, planPreviewLines, plusVat, proTierName, projectGroupBilling, quoteError, quoteParts, quoteTotalLine, reduceBounds, splitBlocks, stepLabel, taxDetail, totalWithTaxWord, useBillingSupport, useRewardBalance, useSelfExtId };
424
- //# sourceMappingURL=chunk-H72SWOUS.js.map
425
- //# sourceMappingURL=chunk-H72SWOUS.js.map
424
+ //# sourceMappingURL=chunk-VTGRCJLP.js.map
425
+ //# sourceMappingURL=chunk-VTGRCJLP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/connection/billing/support.ts","../src/connection/billing/plan-constants.ts","../src/connection/billing/quota-items.ts","../src/connection/billing/reward-balance.ts","../src/connection/billing/addon-pricing.ts","../src/connection/billing/api-error.ts","../src/connection/billing/tax-quote.ts","../src/connection/billing/plan-pricing.ts","../src/connection/billing/plan-badge.ts","../src/connection/workspace-list/projectBilling.tsx"],"names":["formatGbp","gbp"],"mappings":";;;;;;;;A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AAS,SAAA,EAAU;AACzC","file":"chunk-H72SWOUS.js","sourcesContent":["/**\n * What a host adds to the billing kit. Selling plans needs Stripe, which stays the host's: whether\n * this deployment sells plans (a publishable key is configured), and its embedded checkout. It is the\n * host configuration's `billing`; without it nothing is for sale: projects show their limits and\n * usage only.\n */\nimport type { ReactNode } from 'react'\nimport { useArbi } from '@arbidocs/react'\nimport { useHost } from '../../provider/host'\n\nexport interface BillingCheckoutSupport {\n /** Load the host's Stripe (lazily, when a checkout opens); `null` when it cannot. */\n load(): Promise<unknown> | null\n /** Stripe's embedded checkout for a session, on the loaded Stripe. */\n render(stripe: unknown, session: { clientSecret: string; onComplete: () => void }): ReactNode\n}\n\nexport interface BillingSupport {\n /** This deployment sells plans (Stripe is configured). */\n stripeEnabled: boolean\n checkout?: BillingCheckoutSupport\n /**\n * Add-on blocks the user just bought here, so the host does not announce them later as having\n * arrived on their own.\n */\n onAddonBlocksBought?: (projectExtId: string, blocks: { ai: number; storage: number }) => void\n}\n\nconst NOT_FOR_SALE: BillingSupport = { stripeEnabled: false }\n\nexport function useBillingSupport(): BillingSupport {\n return useHost().billing ?? NOT_FOR_SALE\n}\n\n/** The signed-in user's id (`usr-…`), to tell the projects they own from the others. */\nexport function useSelfExtId(): string | undefined {\n const arbi = useArbi()\n return arbi.isLoggedIn ? (arbi.user.identity()?.externalId ?? undefined) : undefined\n}\n","/** Pro's allowance per month (one licence) — must match the backend. Legacy multi-pack plans get it per pack.\n * The live numbers for an existing project come from `project.addons`; these are only for\n * describing the plan before a project exists (new-project dialog, upgrade picker). */\nexport const PRO_AI_GBP = 10\nexport const PRO_STORAGE_GB = 5\n\n/**\n * Add-on block sizes (£25 of AI usage or 25 GB), the same on every plan. Their prices come from the\n * products API (`addon_prices`) before a project exists, and from `project.addons` after.\n */\nexport const ADDON_BLOCK_AI_GBP = 25\nexport const STORAGE_BLOCK_GB = 25\n\n/** Default monthly usage cap for a new Pro project (pence); it limits automatic top-ups only. 0 = no automatic\n * top-ups, null = no limit. */\nexport const DEFAULT_SPEND_CAP_PENCE = 10000\n\n/** The automatic add-on triggers when less than this much AI usage (£) remains; the backend minimum. */\nexport const MIN_AUTO_TOPUP_THRESHOLD_GBP = 1\n\n/** Free-tier quotas — must match backend FREE_* constants in src/constants.py\n * (FREE_AI_GBP=1, FREE_STORAGE_GB=0.05 → 50 MB, FREE_COLLABORATORS=0). */\nexport const FREE_AI_GBP = 1\nexport const FREE_STORAGE_MB = 50\nexport const FREE_COLLABORATORS = 0\n\n/** Collaborator limits at or above this are \"unlimited\" (the backend reports 999 for Pro/dev). */\nexport const UNLIMITED_COLLABORATORS = 999\n\n/**\n * Suggested initial daily per-user AI usage cap (£), pre-filled when creating\n * a new project. The user can clear it to create a project with no cap.\n * Backend treats null as \"no enforcement\" — there is no server-side default.\n */\nexport const SUGGESTED_DAILY_CAP_PER_USER = 10\n","/**\n * Quota display — single source of truth.\n *\n * Builds the icon / label / formatted used-of-limit strings for a project's\n * quotas (AI usage in £, storage, collaborators). Shared by QuotaBadges and the\n * project tooltip so the numbers and units can never disagree (storage in GB on\n * plans of 1 GB or more, MB below).\n */\n\nimport { HardDrive, PoundSterling, Users } from 'lucide-react'\nimport { formatGbp } from '@arbidocs/react'\nimport type { QuotaMeterItem } from '../../settings'\nimport type { components } from '@arbidocs/client'\nimport { UNLIMITED_COLLABORATORS } from './plan-constants'\n\ntype Quotas = components['schemas']['ProjectResponse']['quotas']\n\nconst fmt = (v: number) => Math.round(v).toLocaleString('en-US')\n\n/** \"May 31, 2025\" — the one format every AI-usage-reset mention uses. */\nexport function formatResetDate(unixTimestamp: number | null | undefined): string | null {\n if (!unixTimestamp) return null\n const date = new Date(unixTimestamp * 1000)\n return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\n/**\n * When the project's AI usage allowance next resets, as a unix timestamp.\n * Pro projects report it directly (`addons.ai_usage_reset_at` — monthly, even on an\n * annual plan); monthly subscriptions otherwise reset with the billing period\n * (`current_period_end`); free projects reset on the backend-stamped signup\n * anniversary (`quotas.budget_reset_at`). Only a FUTURE date is returned — a stale\n * past stamp would read as a bug, not a promise.\n */\nexport function aiUsageResetTimestamp(project: {\n quotas?: { budget_reset_at?: number | null } | null\n current_period_end?: number | null\n plan_interval?: string | null\n addons?: { ai_usage_reset_at?: number | null } | null\n}): number | null {\n // An annual period end is a year away — never a monthly AI usage reset.\n const periodEnd = project.plan_interval === 'year' ? null : project.current_period_end\n const ts =\n project.addons?.ai_usage_reset_at ?? periodEnd ?? project.quotas?.budget_reset_at ?? null\n return ts && ts * 1000 > Date.now() ? ts : null\n}\n\n// Defensive: a quota field may be missing on partial/empty payloads — treat it\n// as 0 / 0 rather than crashing the whole row.\nconst quota = (q?: { used?: number; limit?: number }) => ({\n used: q?.used ?? 0,\n limit: q?.limit ?? 0,\n})\n/** GB from 1 GB plans up (\"2.4 GB\", \"5 GB\"), MB below (\"50 MB\"); `unit: false` drops the unit. */\nfunction storageText(gbValue: number, limitGb: number, unit = true): string {\n if (limitGb >= 1) {\n const n = Math.round(gbValue * 10) / 10\n return `${n.toLocaleString('en-US')}${unit ? ' GB' : ''}`\n }\n return `${fmt(gbValue * 1000)}${unit ? ' MB' : ''}`\n}\nconst pctOf = (used: number, limit: number) => (limit > 0 ? (used / limit) * 100 : 0)\n\nexport function getQuotaItems(quotas: Quotas): QuotaMeterItem[] {\n const aiUsage = quota(quotas?.ai_usage)\n const storage = quota(quotas?.storage_gb)\n const collaborators = quota(quotas?.collaborators)\n const unlimitedCollaborators = collaborators.limit >= UNLIMITED_COLLABORATORS\n return [\n {\n key: 'ai-usage',\n icon: PoundSterling,\n label: 'AI usage',\n used: formatGbp(aiUsage.used),\n usedOfLimit: `${formatGbp(aiUsage.used)} / ${formatGbp(aiUsage.limit)}`,\n pct: pctOf(aiUsage.used, aiUsage.limit),\n },\n {\n key: 'storage',\n icon: HardDrive,\n label: 'Storage',\n used: storageText(storage.used, storage.limit),\n usedOfLimit: `${storageText(storage.used, storage.limit, false)} / ${storageText(\n storage.limit,\n storage.limit\n )}`,\n pct: pctOf(storage.used, storage.limit),\n },\n {\n key: 'collaborators',\n icon: Users,\n label: 'Collaborators',\n used: fmt(collaborators.used),\n usedOfLimit: unlimitedCollaborators\n ? `${fmt(collaborators.used)} / Unlimited`\n : `${fmt(collaborators.used)} / ${fmt(collaborators.limit)}`,\n // Zero seats (Free) IS the cap: 0 / 0 shows a full destructive bar,\n // because you can't add anyone — the truth the upgrade door answers.\n // (Only when the quota is actually present; a missing field on a\n // partial payload stays an empty bar, not a false alarm.)\n pct: unlimitedCollaborators\n ? 0\n : quotas?.collaborators && collaborators.limit === 0\n ? 100\n : pctOf(collaborators.used, collaborators.limit),\n },\n ]\n}\n","/**\n * Reward-balance logic (hook + money formatter).\n *\n * A user's reward balance is their available account balance — a single GLOBAL per-user\n * number, the Stripe customer account balance mirrored read-only into\n * `settings.extra_discount`. It auto-applies to the user's NEXT invoice.\n *\n * \"Rewards\" is the broad concept: the balance can be fed by several sources (referral\n * reward is just one). The referral pricing surfaces of the billing kit\n * speak to the referral source specifically; this module owns the balance itself.\n */\n\nimport { useUserSettings } from '@arbidocs/react'\n\nexport interface RewardBalance {\n amount: number // minor units (e.g. pennies) of available account balance\n currency: string\n}\n\n/** The user's available reward balance (all sources), or null if none. */\nexport function useRewardBalance(): RewardBalance | null {\n const { data } = useUserSettings()\n // Backend mirrors this read-only as { amount, currency }; schema types it as a loose object.\n const ed = data?.extra_discount as { amount?: number; currency?: string } | null | undefined\n if (!ed || !ed.amount || ed.amount <= 0) return null\n return { amount: ed.amount, currency: ed.currency || 'gbp' }\n}\n\n/** Format minor units as a localized money string, e.g. `£20` (whole) or `£29.99`. */\nexport function formatMoney(cents: number, currency = 'gbp'): string {\n const value = cents / 100\n const isWhole = Number.isInteger(value)\n const c = currency.toLowerCase()\n const symbol =\n c === 'usd' ? '$' : c === 'gbp' ? '£' : c === 'eur' ? '€' : currency.toUpperCase() + ' '\n return `${symbol}${value.toLocaleString('en-US', {\n minimumFractionDigits: isWhole ? 0 : 2,\n maximumFractionDigits: isWhole ? 0 : 2,\n })}`\n}\n","/** Add-on block price helpers (VAT-inclusive pence from `project.addons`). */\n\nimport { formatGbp } from '@arbidocs/react'\nimport type { components } from '@arbidocs/client'\nimport type { AddonKind } from './useAddonPurchase'\nimport { formatMoney } from './reward-balance'\n\ntype ProjectAddons = components['schemas']['ProjectAddons']\n\nconst gbp = (pence: number) => formatMoney(pence, 'gbp')\n\n/** \"3 Nov 2026\". */\nexport function formatPeriodEnd(unix: number | null | undefined): string | null {\n if (!unix) return null\n return new Date(unix * 1000).toLocaleDateString('en-GB', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n })\n}\n\n/** What one more block of this kind costs right now, incl. UK VAT. */\nexport function addonPricePence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage' ? addons.ai_block_price_pence : addons.storage_block_price_pence\n}\n\n/** The same price ex VAT. */\nfunction addonPriceExVatPence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage'\n ? addons.ai_block_price_ex_vat_pence\n : addons.storage_block_price_ex_vat_pence\n}\n\n/**\n * The PUT /addons/settings body (the monthly usage cap and the automatic add-on trigger) from the current add-on\n * state with the given changes applied.\n */\nexport function addonSettingsBody(\n addons: ProjectAddons,\n change: Partial<{\n spend_cap_pence: number | null\n auto_topup_threshold_gbp: number\n }> = {}\n) {\n return {\n spend_cap_pence: addons.spend_cap_pence ?? null,\n auto_topup_threshold_gbp: addons.auto_topup_threshold_gbp,\n ...change,\n }\n}\n\n/**\n * Of `count` blocks of a kind, how many are on an earlier catalogue's price (legacy, at their old size: £10 of AI\n * usage or 10 GB) and how many on today's. A reduction removes today's blocks first, so the legacy ones are the\n * last kept.\n */\nexport function splitBlocks(\n kind: AddonKind,\n count: number,\n addons: ProjectAddons\n): { legacy: number; current: number } {\n const granted =\n (kind === 'ai_usage' ? addons.legacy_ai_blocks : addons.legacy_storage_blocks) ?? 0\n const legacy = Math.max(0, Math.min(granted, count))\n return { legacy, current: count - legacy }\n}\n\n/** One block's size: \"£25 of AI usage\" / \"25 GB\" (legacy: \"£10\" / \"10 GB\"). */\nfunction blockSize(kind: AddonKind, addons: ProjectAddons, legacy: boolean): string {\n if (kind === 'ai_usage') {\n return formatGbp(legacy ? (addons.legacy_block_ai_gbp ?? 10) : addons.block_ai_gbp)\n }\n return `${legacy ? (addons.legacy_block_storage_gb ?? 10) : addons.block_storage_gb} GB`\n}\n\n/**\n * \"2 × £25 of AI usage\", \"1 × £10 + 1 × £25 of AI usage\", \"1 × 10 GB + 2 × 25 GB\": `count` blocks of a kind, the\n * legacy ones (kept last on a reduction) at their old size.\n */\nexport function blocksLabel(kind: AddonKind, count: number, addons: ProjectAddons): string {\n const { legacy, current } = splitBlocks(kind, count, addons)\n const parts = [\n ...(legacy > 0 ? [`${legacy} × ${blockSize(kind, addons, true)}`] : []),\n ...(current > 0 || legacy === 0 ? [`${current} × ${blockSize(kind, addons, false)}`] : []),\n ]\n return `${parts.join(' + ')}${kind === 'ai_usage' ? ' of AI usage' : ''}`\n}\n\n/**\n * Bounds for \"Reduce from next period\": keep `min`..`current` blocks. `next` is what renews\n * now (a pending reduction, or the current count). Storage can't go below what usage needs.\n */\nexport function reduceBounds(\n kind: AddonKind,\n addons: ProjectAddons\n): { min: number; current: number; next: number } {\n const current = kind === 'ai_usage' ? addons.ai_blocks : addons.storage_blocks\n const pending = kind === 'ai_usage' ? addons.ai_blocks_next : addons.storage_blocks_next\n const min = kind === 'ai_usage' ? 0 : Math.min(addons.storage_blocks_min, current)\n return { min, current, next: pending ?? current }\n}\n\n/** One block's monthly-equivalent price ex VAT: AI usage and storage are priced separately. */\nfunction blockMonthlyExVatPence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage'\n ? addons.ai_block_monthly_ex_vat_pence\n : addons.storage_block_monthly_ex_vat_pence\n}\n\n/** What one block renews at per billing period, ex VAT (annual: 12 × the monthly price). */\nfunction blockPeriodExVatPence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage'\n ? addons.ai_block_period_ex_vat_pence\n : addons.storage_block_period_ex_vat_pence\n}\n\n/** What one add-on renews at: \"£25/month + VAT\" or \"£225/year + VAT\". */\nfunction blockRenewalShort(kind: AddonKind, addons: ProjectAddons, isAnnual: boolean): string {\n return `${gbp(blockPeriodExVatPence(kind, addons))}/${isAnnual ? 'year' : 'month'} + VAT`\n}\n\n/** The extra line annual plans show beside an AI usage add-on or upgrade price. */\nexport const ANNUAL_PREMIUM_AI_NOTE = 'No markup on Premium AI on annual plans'\n\n/** The confirm dialog's figures: charged now (incl. / ex VAT), what it covers until, then what renews. */\nexport function addonCharge(\n kind: AddonKind,\n addons: ProjectAddons,\n isAnnual: boolean,\n periodEnd: number | null | undefined\n): { now: string; nowExVat: string; nowVat: string; until: string | null; then: string } {\n return {\n now: gbp(addonPricePence(kind, addons)),\n nowExVat: gbp(addonPriceExVatPence(kind, addons)),\n nowVat: gbp(addonPricePence(kind, addons) - addonPriceExVatPence(kind, addons)),\n until: isAnnual ? formatPeriodEnd(periodEnd) : null,\n then: blockRenewalShort(kind, addons, isAnnual),\n }\n}\n\n/** Why automatic top-ups stopped (one line; the price of a step is on the Add button). */\nexport const CAP_REACHED_MESSAGE = 'Usage cap reached: no more automatic top-ups this month.'\n\n/** The £0 usage cap: no automatic top-ups (adding by hand still works). */\nexport const ZERO_BUDGET_MESSAGE = 'Automatic top-ups are off (£0 usage cap).'\n\n/** The usage cap's heading wherever it is edited or shown. */\nexport const USAGE_CAP_LABEL = 'Usage cap'\n\n/** What the usage cap means (in \"More info\"): £0 and \"No limit\" explained. */\nexport const USAGE_CAP_HELP =\n 'The most automatic top-ups (AI usage added when it runs low, storage added when an upload needs it) may ' +\n 'cost in a month. Adding or removing by hand is never limited by it; the plan and renewals are not counted. ' +\n '£0 = no automatic top-ups: AI usage and uploads stop at your allowance unless you add more. ' +\n 'No limit = no cap.'\n\n/** A £0 cap turns automatic top-ups off (manual adds still work). */\nexport function isAddonBudgetZero(addons: Pick<ProjectAddons, 'spend_cap_pence'>): boolean {\n return addons.spend_cap_pence === 0\n}\n\n/**\n * How much more of a resource automatic top-ups may add this month before the usage cap stops them, in the\n * resource's unit (£ of AI usage / GB): the whole blocks the cap left pays for at today's ex-VAT price. `null` =\n * no limit; 0 with a £0 cap or when not even one block fits.\n */\nexport function autoRoom(kind: AddonKind, addons: ProjectAddons): number | null {\n const left = addons.cap_left_pence\n if (left == null) return addons.spend_cap_pence === 0 ? 0 : null\n const price = addonPriceExVatPence(kind, addons)\n if (price <= 0) return 0\n const blocks = Math.floor(left / price)\n return blocks * (kind === 'ai_usage' ? addons.block_ai_gbp : addons.block_storage_gb)\n}\n\n/** The size of the block a one-step reduction removes from what renews (today's blocks go first). */\nexport function nextRemovedBlockSize(kind: AddonKind, addons: ProjectAddons): number {\n const { next } = reduceBounds(kind, addons)\n const { current } = splitBlocks(kind, next, addons)\n if (kind === 'ai_usage') {\n return current > 0 ? addons.block_ai_gbp : (addons.legacy_block_ai_gbp ?? 10)\n }\n return current > 0 ? addons.block_storage_gb : (addons.legacy_block_storage_gb ?? 10)\n}\n\n/**\n * Pounds typed into a usage cap field → pence. '' → the default (null); invalid → undefined.\n * Equal to the default is also sent as null (\"keep the default\").\n */\nexport function parseBudgetPounds(value: string): number | null | undefined {\n if (value.trim() === '') return null\n const n = Number(value)\n if (!Number.isFinite(n) || n < 0) return undefined\n return Math.round(n * 100)\n}\n\n/** Toast after saving the usage cap. */\nexport function budgetSavedMessage(capPence: number | null): string {\n if (capPence == null) return 'Usage cap: no limit'\n if (capPence === 0) return 'Usage cap: £0 (no automatic top-ups)'\n return `Usage cap: ${gbp(capPence)} a month`\n}\n\nconst gbText = (n: number) => `${Math.round(n * 10) / 10} GB`\n\n/** \"£25 of AI usage\" / \"25 GB\". */\nexport function stepLabel(kind: AddonKind, size: number): string {\n return kind === 'ai_usage' ? `${formatGbp(size)} of AI usage` : gbText(size)\n}\n\n/** The PUT /addons/next-period body that renews `keep` blocks of `kind` (the other kind unchanged). */\nexport function nextPeriodBody(kind: AddonKind, keep: number) {\n return kind === 'ai_usage'\n ? { ai_blocks: keep, storage_blocks: null }\n : { ai_blocks: null, storage_blocks: keep }\n}\n\n/**\n * The \"+\" step's price line, ex VAT: \"£25/month · today £25\" (annual: \"£18.75/month · today £150\");\n * storage, charged for the rest of the period: \"£25/month · prorated today £8.33\".\n */\nexport function addStepCaption(kind: AddonKind, addons: ProjectAddons): string {\n const now = gbp(addonPriceExVatPence(kind, addons))\n const today = kind === 'storage' ? `prorated today ${now}` : `today ${now}`\n return `${gbp(blockMonthlyExVatPence(kind, addons))}/month · ${today}`\n}\n","/**\n * The `detail` of a refused billing call: the response body's `detail` (a string, or the\n * `{code, message}` of a payment refusal), whether the error is an SDK `ArbiApiError` (body in\n * `apiError`) or the body itself.\n */\nexport function apiErrorDetail(error: unknown): unknown {\n const body = (error as { apiError?: unknown } | null)?.apiError ?? error\n return (body as { detail?: unknown } | null)?.detail\n}\n","/**\n * Tax-inclusive totals from the backend's Stripe Tax quotes (`TaxQuoteResponse`, plan-change\n * previews, add-on quotes): \"£48.00 incl. VAT (£40.00 + £8.00 VAT 20%)\", \"£40.00 · no VAT\n * (reverse charge)\", \"£40.00 · no tax\".\n */\n\nimport type { components } from '@arbidocs/client'\nimport { apiErrorDetail } from './api-error'\n\nexport type TaxQuote = components['schemas']['TaxQuoteResponse']\n\n/** Countries whose tax depends on the postcode: the field is shown up front. */\nexport const POSTCODE_COUNTRIES: readonly string[] = ['US', 'CA']\n\n/** The quote error that asks for a ZIP / postal code. */\nexport const TAX_LOCATION_INVALID = 'TAX_LOCATION_INVALID'\n\n/** \"£42.00\" — always pence, so the parts of a total add up on screen. */\nexport function money2(pence: number, currency = 'gbp'): string {\n const symbol = { gbp: '£', usd: '$', eur: '€' }[currency.toLowerCase()] ?? `${currency} `\n return `${symbol}${(pence / 100).toLocaleString('en-GB', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}`\n}\n\nexport interface TaxParts {\n subtotal: number\n tax: number\n total: number\n /** \"VAT 20%\"; null when no tax is due. */\n label?: string | null\n reverseCharge?: boolean\n}\n\n/** \"VAT\" for a VAT label, else \"tax\". */\nfunction taxKind(label: string | null | undefined): string {\n return /^vat\\b/i.test(label ?? '') ? 'VAT' : 'tax'\n}\n\n/** What follows the total: \"incl. VAT (£40.00 + £8.00 VAT 20%)\", \"· no VAT (reverse charge)\", \"· no tax\". */\nexport function taxDetail({ subtotal, tax, label, reverseCharge }: TaxParts): string {\n if (reverseCharge) return '· no VAT (reverse charge)'\n if (tax <= 0) return '· no tax'\n return `incl. ${taxKind(label)} (${money2(subtotal)} + ${money2(tax)} ${label ?? 'tax'})`\n}\n\n/** \"£48.00 incl. VAT (£40.00 + £8.00 VAT 20%)\", \"£40.00 · no VAT (reverse charge)\", \"£40.00 · no tax\". */\nexport function taxSummary(parts: TaxParts): string {\n return `${money2(parts.total)} ${taxDetail(parts)}`\n}\n\n/** \"£21.00 incl. VAT\" / \"£17.50\" — a total with only the word for its tax. */\nexport function totalWithTaxWord({ total, tax, label }: TaxParts): string {\n return tax > 0 ? `${money2(total)} incl. ${taxKind(label)}` : money2(total)\n}\n\n/** The parts of a quote response. */\nexport function quoteParts(quote: TaxQuote): TaxParts {\n return {\n subtotal: quote.subtotal_pence,\n tax: quote.tax_pence,\n total: quote.total_pence,\n label: quote.tax_label,\n reverseCharge: quote.reverse_charge,\n }\n}\n\n/** \"Total today £48.00 incl. VAT (£40.00 + £8.00 VAT 20%)\". */\nexport function quoteTotalLine(quote: TaxQuote): string {\n return `Total today ${taxSummary(quoteParts(quote))}`\n}\n\n/** The API error code (`detail.code`) and message, if any. */\nexport function quoteError(error: unknown): { code?: string; message?: string } {\n const detail = apiErrorDetail(error)\n if (detail && typeof detail === 'object') {\n const { code, message } = detail as { code?: unknown; message?: unknown }\n return {\n code: typeof code === 'string' ? code : undefined,\n message: typeof message === 'string' ? message : undefined,\n }\n }\n return { message: typeof detail === 'string' ? detail : undefined }\n}\n","/**\n * Pro plan price helpers. Prices come from Stripe via GET /v1/user/products (source of truth).\n * One plan is sold: Pro, one licence (£10 of AI usage + 5 GB a month). Each price lists\n * `pack_prices` for that one licence — `amount` incl. UK VAT and `amount_ex_vat` — and\n * `addon_prices` (one add-on block on that interval). Display them as-is.\n * Legacy subscriptions with several packs keep working; their name and price come from the project.\n */\n\nimport type { components } from '@arbidocs/client'\nimport { formatGbp } from '@arbidocs/react'\nimport { formatMoney } from './reward-balance'\nimport { formatPeriodEnd } from './addon-pricing'\nimport { taxSummary } from './tax-quote'\nimport { ADDON_BLOCK_AI_GBP, STORAGE_BLOCK_GB } from './plan-constants'\n\ntype PlanChangePreview = components['schemas']['PlanChangePreview']\ntype ProductPrice = components['schemas']['ProductPrice']\ntype ProductResponse = components['schemas']['ProductResponse']\ntype PackPrice = components['schemas']['PackPrice']\ntype AddonPrice = components['schemas']['AddonPrice']\n\nexport type PlanInterval = 'month' | 'year'\n\nconst gbp = (pence: number) => formatMoney(pence, 'gbp')\n\n/** The headline price: \"£40 + VAT\". */\nexport function plusVat(exVatPence: number, currency = 'gbp'): string {\n return `${formatMoney(exVatPence, currency)} + VAT`\n}\n\n/** The one licence Pro sells. Other pack counts exist only on legacy subscriptions (displayed, not sold). */\nexport const PRO_PACKS = 1\n\n/** A plan the pickers offer. */\nexport type PlanChoice = 'free' | 'pro'\n\n/** Packs per plan choice (0 = Free). */\nexport const PLAN_CHOICE_PACKS: Record<PlanChoice, number> = {\n free: 0,\n pro: PRO_PACKS,\n}\n\n/** \"Free\" (0), \"Pro\" (1), otherwise \"Pro ×N\" (a legacy multi-pack plan; the API's own name wins). */\nexport function planNameForPacks(packs: number | null | undefined): string {\n const n = packs ?? 0\n if (n <= 0) return 'Free'\n if (n === PRO_PACKS) return 'Pro'\n return `Pro ×${n}`\n}\n\n/** The plan-change panel's fixed lines, each with a test id. */\nexport interface PlanChangeLine {\n id: 'pay-today' | 'from' | 'current-until' | 'no-change' | 'awaiting-bank'\n text: string\n}\n\n/**\n * What a plan change costs, from the backend's Stripe invoice preview (taxed for the customer's\n * address), as fixed lines:\n * - \"Pay today £42.00 incl. VAT (£35.00 + £7.00 VAT 20%)\" (\"Pay today £0\" for a change that waits)\n * - \"From 16 Nov 2026: £210.00 incl. VAT (£175.00 + £35.00 VAT 20%) a month\"\n * - \"Current plan until 16 Nov 2026\" for a change that waits for the period end.\n * \"No change\" when the selection is what the project already has; \"Waiting for your bank\" while\n * an earlier upgrade payment awaits 3-D Secure.\n */\nexport function planPreviewLines(preview: PlanChangePreview): PlanChangeLine[] {\n if (preview.unchanged) return [{ id: 'no-change', text: 'No change' }]\n const date = formatPeriodEnd(preview.next_renewal_at)\n const cadence = preview.interval === 'year' ? 'year' : 'month'\n const lines: PlanChangeLine[] = [\n preview.awaiting_confirmation\n ? { id: 'awaiting-bank', text: 'Waiting for your bank' }\n : {\n id: 'pay-today',\n text: preview.effective_now\n ? `Pay today ${taxSummary({\n subtotal: preview.due_now_ex_vat_pence,\n tax: preview.due_now_tax_pence,\n total: preview.due_now_pence,\n label: preview.tax_label,\n })}`\n : `Pay today ${gbp(0)}`,\n },\n {\n id: 'from',\n text: `${date ? `From ${date}` : 'From renewal'}: ${taxSummary({\n subtotal: preview.next_renewal_ex_vat_pence,\n tax: preview.next_renewal_tax_pence,\n total: preview.next_renewal_pence,\n label: preview.tax_label,\n })} a ${cadence}`,\n },\n ]\n if (!preview.effective_now) {\n lines.push({ id: 'current-until', text: `Current plan until ${date ?? 'renewal'}` })\n }\n return lines\n}\n\n/** Stand-in for \"Pay today\" when the preview failed for an upgrade. */\nexport const PAY_TODAY_UNPRICED = 'Pay today: the difference for the rest of this period'\n\n/** One add-on block's price on this interval's plan price (`addon_prices`), if listed. */\nexport function addonPrice(\n price: ProductPrice | undefined,\n kind: 'ai_usage' | 'storage' = 'ai_usage'\n): AddonPrice | undefined {\n return price?.addon_prices?.find((p) => p.kind === kind)\n}\n\n/** Per add-on block of `kind` per month, ex VAT (annual plans: the monthly equivalent). */\nexport function addonMonthlyExVat(\n price: ProductPrice | undefined,\n kind: 'ai_usage' | 'storage' = 'ai_usage'\n): number | undefined {\n return addonPrice(price, kind)?.monthly_ex_vat\n}\n\n/** What a checkout buys: \"Pro\", \"Pro + 2 × £25 of AI usage + 1 × 25 GB\". */\nexport function checkoutItemsLabel(aiBlocks: number, storageBlocks: number): string {\n return [\n 'Pro',\n aiBlocks > 0 && `${aiBlocks} × ${formatGbp(ADDON_BLOCK_AI_GBP)} of AI usage`,\n storageBlocks > 0 && `${storageBlocks} × ${STORAGE_BLOCK_GB} GB`,\n ]\n .filter(Boolean)\n .join(' + ')\n}\n\n/** The price of `packs` packs on this interval's price, if Stripe lists it (only one licence is listed). */\nexport function packPrice(\n price: ProductPrice | undefined,\n packs: number = PRO_PACKS\n): PackPrice | undefined {\n return price?.pack_prices?.find((p) => p.packs === packs)\n}\n\nexport interface ProPrices {\n monthly?: ProductPrice\n annual?: ProductPrice\n}\n\n/** The Pro product's monthly and annual prices (default price per interval wins). */\nexport function findProPrices(products: ProductResponse[] | undefined): ProPrices {\n const prices = products?.[0]?.prices ?? []\n const pick = (interval: PlanInterval) =>\n prices.find((p) => p.interval === interval && p.default_price) ??\n prices.find((p) => p.interval === interval)\n return { monthly: pick('month'), annual: pick('year') }\n}\n\n/** Annual savings vs 12 × monthly, as a whole percent (e.g. £360 vs £480 → 25). */\nexport function calcSavingsPercent(\n monthlyPrice: ProductPrice | undefined,\n annualPrice: ProductPrice | undefined\n): number | null {\n const monthly = packPrice(monthlyPrice)?.amount ?? monthlyPrice?.amount\n const annual = packPrice(annualPrice)?.amount ?? annualPrice?.amount\n if (monthly == null || annual == null || monthly === 0) return null\n const savings = Math.round(((monthly * 12 - annual) / (monthly * 12)) * 100)\n return savings > 0 ? savings : null\n}\n\n/** Most add-on blocks of each kind a checkout may include (the backend's limit). */\nexport const MAX_CHECKOUT_BLOCKS = 100\n\n/** \"£25/month + VAT each\", annual: \"£225/year + VAT each\": one block on the chosen interval. */\nexport function checkoutBlockPriceText(\n price: ProductPrice | undefined,\n kind: 'ai_usage' | 'storage'\n): string | null {\n const block = addonPrice(price, kind)\n if (!block) return null\n const currency = price?.currency ?? 'gbp'\n return price?.interval === 'year'\n ? `${formatMoney(block.amount_ex_vat, currency)}/year + VAT each`\n : `${formatMoney(block.amount_ex_vat, currency)}/month + VAT each`\n}\n","import type { PlanBadgeProps } from '../../settings'\nimport type { components } from '@arbidocs/client'\nimport { planNameForPacks } from './plan-pricing'\n\ntype ProjectBillingFields = Pick<\n components['schemas']['ProjectResponse'],\n 'subscription' | 'plan_interval'\n> &\n Partial<Pick<components['schemas']['ProjectResponse'], 'packs' | 'addons'>>\n\n/** A project is on Pro when it has a billing interval (null = Free or checkout pending). */\nexport function isProProject(project: Pick<ProjectBillingFields, 'plan_interval'>): boolean {\n return project.plan_interval != null\n}\n\n/** \"Pro\", or a legacy multi-pack plan's name (\"Pro ×N\") — the API's name when it sends one (owner view). */\nexport function proTierName(project: ProjectBillingFields): string {\n return project.addons?.plan_name || planNameForPacks(Math.max(project.packs ?? 1, 1))\n}\n\n/** \"Free\", \"Pro monthly\", \"Pro annual\", \"Pro ×3 monthly\" (legacy) or \"Dev\" — the full plan name. */\nexport function planName(project: ProjectBillingFields): string {\n if (project.subscription === 'dev') return 'Dev'\n if (!isProProject(project)) return 'Free'\n return `${proTierName(project)} ${project.plan_interval === 'year' ? 'annual' : 'monthly'}`\n}\n\n/**\n * Maps a project's billing state to the `PlanBadge` block's label + tone.\n * Pro reads as accent, Free/dev as neutral, payment trouble or cancelling as pending.\n */\nexport function planBadgeView(\n project: ProjectBillingFields\n): Pick<PlanBadgeProps, 'label' | 'tone'> {\n const { subscription } = project\n const label =\n subscription === 'canceled'\n ? 'Cancelling'\n : subscription === 'dev'\n ? 'Dev'\n : isProProject(project)\n ? proTierName(project)\n : 'Free'\n\n const tone =\n subscription === 'dev'\n ? 'dev'\n : subscription === 'canceled' || subscription === 'past_due'\n ? 'pending'\n : isProProject(project)\n ? 'paid'\n : 'free'\n\n return { label, tone }\n}\n","/**\n * What a project's group in the workspace list says about the project itself: its plan badge (own\n * projects, where plans are sold), the usage readout beside its name, and the plan and limits\n * breakdown behind the name. One source for the cards' bands and the table's headings.\n */\nimport type { ReactNode } from 'react'\nimport type { LucideIcon } from 'lucide-react'\nimport type { components } from '@arbidocs/client'\nimport { UsageMeter } from '../../components/UsageMeter'\nimport { PlanBadge, QuotaMeter } from '../../settings'\nimport { ProjectBreakdown, ProjectReadout } from '../../home/ProjectBandParts'\nimport { planBadgeView } from '../billing/plan-badge'\nimport { getQuotaItems } from '../billing/quota-items'\n\ntype Project = components['schemas']['ProjectResponse']\n\nexport interface ProjectGroupBilling {\n /** The plan badge: own projects only, where plans are sold. */\n planBadge?: ReactNode\n /** Plan and usage, right after the name (projects with quotas). */\n readout?: ReactNode\n /** The plan and limits panel behind the name; meters for own projects only. */\n breakdown?: ReactNode\n}\n\nexport function projectGroupBilling(\n project: Project | undefined,\n { isOwned, stripeEnabled }: { isOwned: boolean; stripeEnabled: boolean }\n): ProjectGroupBilling {\n if (!project) return {}\n const planBadge = isOwned && stripeEnabled ? <PlanBadge {...planBadgeView(project)} /> : undefined\n const quotaItems = project.quotas ? getQuotaItems(project.quotas) : []\n const readout = project.quotas ? (\n <ProjectReadout\n plan={\n planBadge ? { badge: planBadge, testId: `project-tier-${project.external_id}` } : undefined\n }\n usage={{\n testId: `project-usage-${project.external_id}`,\n // Bare numbers without plans for sale: a glance beside the name, not the Plan & Usage detail.\n node: (\n <QuotaMeter\n items={quotaItems}\n size=\"sm\"\n showTooltips={false}\n showBars={stripeEnabled}\n showPercent={false}\n />\n ),\n }}\n />\n ) : (\n planBadge\n )\n const breakdown = (\n <ProjectBreakdown\n name={project.name}\n badge={planBadge}\n meters={\n isOwned\n ? quotaItems.map(({ key, icon, label, usedOfLimit, pct }) => (\n <UsageMeter\n key={key}\n icon={icon as LucideIcon}\n label={label}\n value={usedOfLimit}\n pct={pct}\n />\n ))\n : undefined\n }\n dailyCap={{\n label: 'Daily cap',\n value:\n project.daily_cap_per_user == null\n ? 'No limit'\n : project.daily_cap_per_user.toLocaleString('en-US'),\n }}\n />\n )\n return { planBadge, readout, breakdown }\n}\n"]}
1
+ {"version":3,"sources":["../src/connection/billing/support.ts","../src/connection/billing/plan-constants.ts","../src/connection/billing/quota-items.ts","../src/connection/billing/reward-balance.ts","../src/connection/billing/addon-pricing.ts","../src/connection/billing/api-error.ts","../src/connection/billing/tax-quote.ts","../src/connection/billing/plan-pricing.ts","../src/connection/billing/plan-badge.ts","../src/connection/workspace-list/projectBilling.tsx"],"names":["formatGbp","gbp"],"mappings":";;;;;;;;AA4BA,IAAM,YAAA,GAA+B,EAAE,aAAA,EAAe,KAAA,EAAM;AAErD,SAAS,iBAAA,GAAoC;AAClD,EAAA,OAAO,OAAA,GAAU,OAAA,IAAW,YAAA;AAC9B;AAGO,SAAS,YAAA,GAAmC;AACjD,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,OAAO,KAAK,UAAA,GAAc,IAAA,CAAK,KAAK,QAAA,EAAS,EAAG,cAAc,MAAA,GAAa,MAAA;AAC7E;;;ACnCO,IAAM,UAAA,GAAa;AACnB,IAAM,cAAA,GAAiB;AAMvB,IAAM,kBAAA,GAAqB;AAC3B,IAAM,gBAAA,GAAmB;AAIzB,IAAM,uBAAA,GAA0B;AAGhC,IAAM,4BAAA,GAA+B;AAIrC,IAAM,WAAA,GAAc;AACpB,IAAM,eAAA,GAAkB;AACxB,IAAM,kBAAA,GAAqB;AAG3B,IAAM,uBAAA,GAA0B,GAAA;AAOhC,IAAM,4BAAA,GAA+B;;;ACjB5C,IAAM,GAAA,GAAM,CAAC,CAAA,KAAc,IAAA,CAAK,MAAM,CAAC,CAAA,CAAE,eAAe,OAAO,CAAA;AAGxD,SAAS,gBAAgB,aAAA,EAAyD;AACvF,EAAA,IAAI,CAAC,eAAe,OAAO,IA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,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,WAAA,EAAa,GAAA,EAAI,qBACnD,GAAA;AAAA,QAAC,UAAA;AAAA,QAAA;AAAA,UAEC,IAAA;AAAA,UACA,KAAA;AAAA,UACA,KAAA,EAAO,WAAA;AAAA,UACP;AAAA,SAAA;AAAA,QAJK;AAAA,OAMR,CAAA,GACD,MAAA;AAAA,MAEN,QAAA,EAAU;AAAA,QACR,KAAA,EAAO,WAAA;AAAA,QACP,KAAA,EACE,QAAQ,kBAAA,IAAsB,IAAA,GAC1B,aACA,OAAA,CAAQ,kBAAA,CAAmB,eAAe,OAAO;AAAA;AACzD;AAAA,GACF;AAEF,EAAA,OAAO,EAAE,SAAA,EAAW,OAAA,EAAS,SAAA,EAAU;AACzC","file":"chunk-VTGRCJLP.js","sourcesContent":["/**\n * What a host adds to the billing kit. Selling plans needs Stripe, which stays the host's: whether\n * this deployment sells plans (a publishable key is configured), and its embedded checkout. It is the\n * host configuration's `billing`; without it nothing is for sale: projects show their limits and\n * usage only.\n */\nimport type { ReactNode } from 'react'\nimport { useArbi } from '@arbidocs/react'\nimport { useHost } from '../../provider/host'\n\nexport interface BillingCheckoutSupport {\n /** Load the host's Stripe (lazily, when a checkout opens); `null` when it cannot. */\n load(): Promise<unknown> | null\n /** Stripe's embedded checkout for a session, on the loaded Stripe. */\n render(stripe: unknown, session: { clientSecret: string; onComplete: () => void }): ReactNode\n}\n\nexport interface BillingSupport {\n /** This deployment sells plans (Stripe is configured). */\n stripeEnabled: boolean\n checkout?: BillingCheckoutSupport\n /**\n * Add-on blocks the user just bought here, so the host does not announce them later as having\n * arrived on their own.\n */\n onAddonBlocksBought?: (projectExtId: string, blocks: { ai: number; storage: number }) => void\n}\n\nconst NOT_FOR_SALE: BillingSupport = { stripeEnabled: false }\n\nexport function useBillingSupport(): BillingSupport {\n return useHost().billing ?? NOT_FOR_SALE\n}\n\n/** The signed-in user's id (`usr-…`), to tell the projects they own from the others. */\nexport function useSelfExtId(): string | undefined {\n const arbi = useArbi()\n return arbi.isLoggedIn ? (arbi.user.identity()?.externalId ?? undefined) : undefined\n}\n","/** Pro's allowance per month (one licence) — must match the backend. Legacy multi-pack plans get it per pack.\n * The live numbers for an existing project come from `project.addons`; these are only for\n * describing the plan before a project exists (new-project dialog, upgrade picker). */\nexport const PRO_AI_GBP = 10\nexport const PRO_STORAGE_GB = 5\n\n/**\n * Add-on block sizes (£25 of AI usage or 25 GB), the same on every plan. Their prices come from the\n * products API (`addon_prices`) before a project exists, and from `project.addons` after.\n */\nexport const ADDON_BLOCK_AI_GBP = 25\nexport const STORAGE_BLOCK_GB = 25\n\n/** Default monthly usage cap for a new Pro project (pence); it limits automatic top-ups only. 0 = no automatic\n * top-ups, null = no limit. */\nexport const DEFAULT_SPEND_CAP_PENCE = 10000\n\n/** The automatic add-on triggers when less than this much AI usage (£) remains; the backend minimum. */\nexport const MIN_AUTO_TOPUP_THRESHOLD_GBP = 1\n\n/** Free-tier quotas — must match backend FREE_* constants in src/constants.py\n * (FREE_AI_GBP=1, FREE_STORAGE_GB=0.05 → 50 MB, FREE_COLLABORATORS=0). */\nexport const FREE_AI_GBP = 1\nexport const FREE_STORAGE_MB = 50\nexport const FREE_COLLABORATORS = 0\n\n/** Collaborator limits at or above this are \"unlimited\" (the backend reports 999 for Pro/dev). */\nexport const UNLIMITED_COLLABORATORS = 999\n\n/**\n * Suggested initial daily per-user AI usage cap (£), pre-filled when creating\n * a new project. The user can clear it to create a project with no cap.\n * Backend treats null as \"no enforcement\" — there is no server-side default.\n */\nexport const SUGGESTED_DAILY_CAP_PER_USER = 10\n","/**\n * Quota display — single source of truth.\n *\n * Builds the icon / label / formatted used-of-limit strings for a project's\n * quotas (AI usage in £, storage, collaborators). Shared by QuotaBadges and the\n * project tooltip so the numbers and units can never disagree (storage in GB on\n * plans of 1 GB or more, MB below).\n */\n\nimport { HardDrive, PoundSterling, Users } from 'lucide-react'\nimport { formatGbp } from '@arbidocs/react'\nimport type { QuotaMeterItem } from '../../settings'\nimport type { components } from '@arbidocs/client'\nimport { UNLIMITED_COLLABORATORS } from './plan-constants'\n\ntype Quotas = components['schemas']['ProjectResponse']['quotas']\n\nconst fmt = (v: number) => Math.round(v).toLocaleString('en-US')\n\n/** \"May 31, 2025\" — the one format every AI-usage-reset mention uses. */\nexport function formatResetDate(unixTimestamp: number | null | undefined): string | null {\n if (!unixTimestamp) return null\n const date = new Date(unixTimestamp * 1000)\n return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\n/**\n * When the project's AI usage allowance next resets, as a unix timestamp.\n * Pro projects report it directly (`addons.ai_usage_reset_at` — monthly, even on an\n * annual plan); monthly subscriptions otherwise reset with the billing period\n * (`current_period_end`); free projects reset on the backend-stamped signup\n * anniversary (`quotas.budget_reset_at`). Only a FUTURE date is returned — a stale\n * past stamp would read as a bug, not a promise.\n */\nexport function aiUsageResetTimestamp(project: {\n quotas?: { budget_reset_at?: number | null } | null\n current_period_end?: number | null\n plan_interval?: string | null\n addons?: { ai_usage_reset_at?: number | null } | null\n}): number | null {\n // An annual period end is a year away — never a monthly AI usage reset.\n const periodEnd = project.plan_interval === 'year' ? null : project.current_period_end\n const ts =\n project.addons?.ai_usage_reset_at ?? periodEnd ?? project.quotas?.budget_reset_at ?? null\n return ts && ts * 1000 > Date.now() ? ts : null\n}\n\n// Defensive: a quota field may be missing on partial/empty payloads — treat it\n// as 0 / 0 rather than crashing the whole row.\nconst quota = (q?: { used?: number; limit?: number }) => ({\n used: q?.used ?? 0,\n limit: q?.limit ?? 0,\n})\n/** GB from 1 GB plans up (\"2.4 GB\", \"5 GB\"), MB below (\"50 MB\"); `unit: false` drops the unit. */\nfunction storageText(gbValue: number, limitGb: number, unit = true): string {\n if (limitGb >= 1) {\n const n = Math.round(gbValue * 10) / 10\n return `${n.toLocaleString('en-US')}${unit ? ' GB' : ''}`\n }\n return `${fmt(gbValue * 1000)}${unit ? ' MB' : ''}`\n}\nconst pctOf = (used: number, limit: number) => (limit > 0 ? (used / limit) * 100 : 0)\n\nexport function getQuotaItems(quotas: Quotas): QuotaMeterItem[] {\n const aiUsage = quota(quotas?.ai_usage)\n const storage = quota(quotas?.storage_gb)\n const collaborators = quota(quotas?.collaborators)\n const unlimitedCollaborators = collaborators.limit >= UNLIMITED_COLLABORATORS\n return [\n {\n key: 'ai-usage',\n icon: PoundSterling,\n label: 'AI usage',\n used: formatGbp(aiUsage.used),\n usedOfLimit: `${formatGbp(aiUsage.used)} / ${formatGbp(aiUsage.limit)}`,\n pct: pctOf(aiUsage.used, aiUsage.limit),\n },\n {\n key: 'storage',\n icon: HardDrive,\n label: 'Storage',\n used: storageText(storage.used, storage.limit),\n usedOfLimit: `${storageText(storage.used, storage.limit, false)} / ${storageText(\n storage.limit,\n storage.limit\n )}`,\n pct: pctOf(storage.used, storage.limit),\n },\n {\n key: 'collaborators',\n icon: Users,\n label: 'Collaborators',\n used: fmt(collaborators.used),\n usedOfLimit: unlimitedCollaborators\n ? `${fmt(collaborators.used)} / Unlimited`\n : `${fmt(collaborators.used)} / ${fmt(collaborators.limit)}`,\n // Zero seats (Free) IS the cap: 0 / 0 shows a full destructive bar,\n // because you can't add anyone — the truth the upgrade door answers.\n // (Only when the quota is actually present; a missing field on a\n // partial payload stays an empty bar, not a false alarm.)\n pct: unlimitedCollaborators\n ? 0\n : quotas?.collaborators && collaborators.limit === 0\n ? 100\n : pctOf(collaborators.used, collaborators.limit),\n },\n ]\n}\n","/**\n * Reward-balance logic (hook + money formatter).\n *\n * A user's reward balance is their available account balance — a single GLOBAL per-user\n * number, the Stripe customer account balance mirrored read-only into\n * `settings.extra_discount`. It auto-applies to the user's NEXT invoice.\n *\n * \"Rewards\" is the broad concept: the balance can be fed by several sources (referral\n * reward is just one). The referral pricing surfaces of the billing kit\n * speak to the referral source specifically; this module owns the balance itself.\n */\n\nimport { useUserSettings } from '@arbidocs/react'\n\nexport interface RewardBalance {\n amount: number // minor units (e.g. pennies) of available account balance\n currency: string\n}\n\n/** The user's available reward balance (all sources), or null if none. */\nexport function useRewardBalance(): RewardBalance | null {\n const { data } = useUserSettings()\n // Backend mirrors this read-only as { amount, currency }; schema types it as a loose object.\n const ed = data?.extra_discount as { amount?: number; currency?: string } | null | undefined\n if (!ed || !ed.amount || ed.amount <= 0) return null\n return { amount: ed.amount, currency: ed.currency || 'gbp' }\n}\n\n/** Format minor units as a localized money string, e.g. `£20` (whole) or `£29.99`. */\nexport function formatMoney(cents: number, currency = 'gbp'): string {\n const value = cents / 100\n const isWhole = Number.isInteger(value)\n const c = currency.toLowerCase()\n const symbol =\n c === 'usd' ? '$' : c === 'gbp' ? '£' : c === 'eur' ? '€' : currency.toUpperCase() + ' '\n return `${symbol}${value.toLocaleString('en-US', {\n minimumFractionDigits: isWhole ? 0 : 2,\n maximumFractionDigits: isWhole ? 0 : 2,\n })}`\n}\n","/** Add-on block price helpers (VAT-inclusive pence from `project.addons`). */\n\nimport { formatGbp } from '@arbidocs/react'\nimport type { components } from '@arbidocs/client'\nimport type { AddonKind } from './useAddonPurchase'\nimport { formatMoney } from './reward-balance'\n\ntype ProjectAddons = components['schemas']['ProjectAddons']\n\nconst gbp = (pence: number) => formatMoney(pence, 'gbp')\n\n/** \"3 Nov 2026\". */\nexport function formatPeriodEnd(unix: number | null | undefined): string | null {\n if (!unix) return null\n return new Date(unix * 1000).toLocaleDateString('en-GB', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n })\n}\n\n/** What one more block of this kind costs right now, incl. UK VAT. */\nexport function addonPricePence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage' ? addons.ai_block_price_pence : addons.storage_block_price_pence\n}\n\n/** The same price ex VAT. */\nfunction addonPriceExVatPence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage'\n ? addons.ai_block_price_ex_vat_pence\n : addons.storage_block_price_ex_vat_pence\n}\n\n/**\n * The PUT /addons/settings body (the monthly usage cap and the automatic add-on trigger) from the current add-on\n * state with the given changes applied.\n */\nexport function addonSettingsBody(\n addons: ProjectAddons,\n change: Partial<{\n spend_cap_pence: number | null\n auto_topup_threshold_gbp: number\n }> = {}\n) {\n return {\n spend_cap_pence: addons.spend_cap_pence ?? null,\n auto_topup_threshold_gbp: addons.auto_topup_threshold_gbp,\n ...change,\n }\n}\n\n/**\n * Of `count` blocks of a kind, how many are on an earlier catalogue's price (legacy, at their old size: £10 of AI\n * usage or 10 GB) and how many on today's. A reduction removes today's blocks first, so the legacy ones are the\n * last kept.\n */\nexport function splitBlocks(\n kind: AddonKind,\n count: number,\n addons: ProjectAddons\n): { legacy: number; current: number } {\n const granted =\n (kind === 'ai_usage' ? addons.legacy_ai_blocks : addons.legacy_storage_blocks) ?? 0\n const legacy = Math.max(0, Math.min(granted, count))\n return { legacy, current: count - legacy }\n}\n\n/** One block's size: \"£25 of AI usage\" / \"25 GB\" (legacy: \"£10\" / \"10 GB\"). */\nfunction blockSize(kind: AddonKind, addons: ProjectAddons, legacy: boolean): string {\n if (kind === 'ai_usage') {\n return formatGbp(legacy ? (addons.legacy_block_ai_gbp ?? 10) : addons.block_ai_gbp)\n }\n return `${legacy ? (addons.legacy_block_storage_gb ?? 10) : addons.block_storage_gb} GB`\n}\n\n/**\n * \"2 × £25 of AI usage\", \"1 × £10 + 1 × £25 of AI usage\", \"1 × 10 GB + 2 × 25 GB\": `count` blocks of a kind, the\n * legacy ones (kept last on a reduction) at their old size.\n */\nexport function blocksLabel(kind: AddonKind, count: number, addons: ProjectAddons): string {\n const { legacy, current } = splitBlocks(kind, count, addons)\n const parts = [\n ...(legacy > 0 ? [`${legacy} × ${blockSize(kind, addons, true)}`] : []),\n ...(current > 0 || legacy === 0 ? [`${current} × ${blockSize(kind, addons, false)}`] : []),\n ]\n return `${parts.join(' + ')}${kind === 'ai_usage' ? ' of AI usage' : ''}`\n}\n\n/**\n * Bounds for \"Reduce from next period\": keep `min`..`current` blocks. `next` is what renews\n * now (a pending reduction, or the current count). Storage can't go below what usage needs.\n */\nexport function reduceBounds(\n kind: AddonKind,\n addons: ProjectAddons\n): { min: number; current: number; next: number } {\n const current = kind === 'ai_usage' ? addons.ai_blocks : addons.storage_blocks\n const pending = kind === 'ai_usage' ? addons.ai_blocks_next : addons.storage_blocks_next\n const min = kind === 'ai_usage' ? 0 : Math.min(addons.storage_blocks_min, current)\n return { min, current, next: pending ?? current }\n}\n\n/** One block's monthly-equivalent price ex VAT: AI usage and storage are priced separately. */\nfunction blockMonthlyExVatPence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage'\n ? addons.ai_block_monthly_ex_vat_pence\n : addons.storage_block_monthly_ex_vat_pence\n}\n\n/** What one block renews at per billing period, ex VAT (annual: 12 × the monthly price). */\nfunction blockPeriodExVatPence(kind: AddonKind, addons: ProjectAddons): number {\n return kind === 'ai_usage'\n ? addons.ai_block_period_ex_vat_pence\n : addons.storage_block_period_ex_vat_pence\n}\n\n/** What one add-on renews at: \"£25/month + VAT\" or \"£225/year + VAT\". */\nfunction blockRenewalShort(kind: AddonKind, addons: ProjectAddons, isAnnual: boolean): string {\n return `${gbp(blockPeriodExVatPence(kind, addons))}/${isAnnual ? 'year' : 'month'} + VAT`\n}\n\n/** The extra line annual plans show beside an AI usage add-on or upgrade price. */\nexport const ANNUAL_PREMIUM_AI_NOTE = 'No markup on Premium AI on annual plans'\n\n/** The confirm dialog's figures: charged now (incl. / ex VAT), what it covers until, then what renews. */\nexport function addonCharge(\n kind: AddonKind,\n addons: ProjectAddons,\n isAnnual: boolean,\n periodEnd: number | null | undefined\n): { now: string; nowExVat: string; nowVat: string; until: string | null; then: string } {\n return {\n now: gbp(addonPricePence(kind, addons)),\n nowExVat: gbp(addonPriceExVatPence(kind, addons)),\n nowVat: gbp(addonPricePence(kind, addons) - addonPriceExVatPence(kind, addons)),\n until: isAnnual ? formatPeriodEnd(periodEnd) : null,\n then: blockRenewalShort(kind, addons, isAnnual),\n }\n}\n\n/** Why automatic top-ups stopped (one line; the price of a step is on the Add button). */\nexport const CAP_REACHED_MESSAGE = 'Usage cap reached: no more automatic top-ups this month.'\n\n/** The £0 usage cap: no automatic top-ups (adding by hand still works). */\nexport const ZERO_BUDGET_MESSAGE = 'Automatic top-ups are off (£0 usage cap).'\n\n/** The usage cap's heading wherever it is edited or shown. */\nexport const USAGE_CAP_LABEL = 'Usage cap'\n\n/** What the usage cap means (in \"More info\"): £0 and \"No limit\" explained. */\nexport const USAGE_CAP_HELP =\n 'The most automatic top-ups (AI usage added when it runs low, storage added when an upload needs it) may ' +\n 'cost in a month. Adding or removing by hand is never limited by it; the plan and renewals are not counted. ' +\n '£0 = no automatic top-ups: AI usage and uploads stop at your allowance unless you add more. ' +\n 'No limit = no cap.'\n\n/** A £0 cap turns automatic top-ups off (manual adds still work). */\nexport function isAddonBudgetZero(addons: Pick<ProjectAddons, 'spend_cap_pence'>): boolean {\n return addons.spend_cap_pence === 0\n}\n\n/**\n * How much more of a resource automatic top-ups may add this month before the usage cap stops them, in the\n * resource's unit (£ of AI usage / GB): the whole blocks the cap left pays for at today's ex-VAT price. `null` =\n * no limit; 0 with a £0 cap or when not even one block fits.\n */\nexport function autoRoom(kind: AddonKind, addons: ProjectAddons): number | null {\n const left = addons.cap_left_pence\n if (left == null) return addons.spend_cap_pence === 0 ? 0 : null\n const price = addonPriceExVatPence(kind, addons)\n if (price <= 0) return 0\n const blocks = Math.floor(left / price)\n return blocks * (kind === 'ai_usage' ? addons.block_ai_gbp : addons.block_storage_gb)\n}\n\n/** The size of the block a one-step reduction removes from what renews (today's blocks go first). */\nexport function nextRemovedBlockSize(kind: AddonKind, addons: ProjectAddons): number {\n const { next } = reduceBounds(kind, addons)\n const { current } = splitBlocks(kind, next, addons)\n if (kind === 'ai_usage') {\n return current > 0 ? addons.block_ai_gbp : (addons.legacy_block_ai_gbp ?? 10)\n }\n return current > 0 ? addons.block_storage_gb : (addons.legacy_block_storage_gb ?? 10)\n}\n\n/**\n * Pounds typed into a usage cap field → pence. '' → the default (null); invalid → undefined.\n * Equal to the default is also sent as null (\"keep the default\").\n */\nexport function parseBudgetPounds(value: string): number | null | undefined {\n if (value.trim() === '') return null\n const n = Number(value)\n if (!Number.isFinite(n) || n < 0) return undefined\n return Math.round(n * 100)\n}\n\n/** Toast after saving the usage cap. */\nexport function budgetSavedMessage(capPence: number | null): string {\n if (capPence == null) return 'Usage cap: no limit'\n if (capPence === 0) return 'Usage cap: £0 (no automatic top-ups)'\n return `Usage cap: ${gbp(capPence)} a month`\n}\n\nconst gbText = (n: number) => `${Math.round(n * 10) / 10} GB`\n\n/** \"£25 of AI usage\" / \"25 GB\". */\nexport function stepLabel(kind: AddonKind, size: number): string {\n return kind === 'ai_usage' ? `${formatGbp(size)} of AI usage` : gbText(size)\n}\n\n/** The PUT /addons/next-period body that renews `keep` blocks of `kind` (the other kind unchanged). */\nexport function nextPeriodBody(kind: AddonKind, keep: number) {\n return kind === 'ai_usage'\n ? { ai_blocks: keep, storage_blocks: null }\n : { ai_blocks: null, storage_blocks: keep }\n}\n\n/**\n * The \"+\" step's price line, ex VAT: \"£25/month · today £25\" (annual: \"£18.75/month · today £150\");\n * storage, charged for the rest of the period: \"£25/month · prorated today £8.33\".\n */\nexport function addStepCaption(kind: AddonKind, addons: ProjectAddons): string {\n const now = gbp(addonPriceExVatPence(kind, addons))\n const today = kind === 'storage' ? `prorated today ${now}` : `today ${now}`\n return `${gbp(blockMonthlyExVatPence(kind, addons))}/month · ${today}`\n}\n","/**\n * The `detail` of a refused billing call: the response body's `detail` (a string, or the\n * `{code, message}` of a payment refusal), whether the error is an SDK `ArbiApiError` (body in\n * `apiError`) or the body itself.\n */\nexport function apiErrorDetail(error: unknown): unknown {\n const body = (error as { apiError?: unknown } | null)?.apiError ?? error\n return (body as { detail?: unknown } | null)?.detail\n}\n","/**\n * Tax-inclusive totals from the backend's Stripe Tax quotes (`TaxQuoteResponse`, plan-change\n * previews, add-on quotes): \"£48.00 incl. VAT (£40.00 + £8.00 VAT 20%)\", \"£40.00 · no VAT\n * (reverse charge)\", \"£40.00 · no tax\".\n */\n\nimport type { components } from '@arbidocs/client'\nimport { apiErrorDetail } from './api-error'\n\nexport type TaxQuote = components['schemas']['TaxQuoteResponse']\n\n/** Countries whose tax depends on the postcode: the field is shown up front. */\nexport const POSTCODE_COUNTRIES: readonly string[] = ['US', 'CA']\n\n/** The quote error that asks for a ZIP / postal code. */\nexport const TAX_LOCATION_INVALID = 'TAX_LOCATION_INVALID'\n\n/** \"£42.00\" — always pence, so the parts of a total add up on screen. */\nexport function money2(pence: number, currency = 'gbp'): string {\n const symbol = { gbp: '£', usd: '$', eur: '€' }[currency.toLowerCase()] ?? `${currency} `\n return `${symbol}${(pence / 100).toLocaleString('en-GB', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n })}`\n}\n\nexport interface TaxParts {\n subtotal: number\n tax: number\n total: number\n /** \"VAT 20%\"; null when no tax is due. */\n label?: string | null\n reverseCharge?: boolean\n}\n\n/** \"VAT\" for a VAT label, else \"tax\". */\nfunction taxKind(label: string | null | undefined): string {\n return /^vat\\b/i.test(label ?? '') ? 'VAT' : 'tax'\n}\n\n/** What follows the total: \"incl. VAT (£40.00 + £8.00 VAT 20%)\", \"· no VAT (reverse charge)\", \"· no tax\". */\nexport function taxDetail({ subtotal, tax, label, reverseCharge }: TaxParts): string {\n if (reverseCharge) return '· no VAT (reverse charge)'\n if (tax <= 0) return '· no tax'\n return `incl. ${taxKind(label)} (${money2(subtotal)} + ${money2(tax)} ${label ?? 'tax'})`\n}\n\n/** \"£48.00 incl. VAT (£40.00 + £8.00 VAT 20%)\", \"£40.00 · no VAT (reverse charge)\", \"£40.00 · no tax\". */\nexport function taxSummary(parts: TaxParts): string {\n return `${money2(parts.total)} ${taxDetail(parts)}`\n}\n\n/** \"£21.00 incl. VAT\" / \"£17.50\" — a total with only the word for its tax. */\nexport function totalWithTaxWord({ total, tax, label }: TaxParts): string {\n return tax > 0 ? `${money2(total)} incl. ${taxKind(label)}` : money2(total)\n}\n\n/** The parts of a quote response. */\nexport function quoteParts(quote: TaxQuote): TaxParts {\n return {\n subtotal: quote.subtotal_pence,\n tax: quote.tax_pence,\n total: quote.total_pence,\n label: quote.tax_label,\n reverseCharge: quote.reverse_charge,\n }\n}\n\n/** \"Total today £48.00 incl. VAT (£40.00 + £8.00 VAT 20%)\". */\nexport function quoteTotalLine(quote: TaxQuote): string {\n return `Total today ${taxSummary(quoteParts(quote))}`\n}\n\n/** The API error code (`detail.code`) and message, if any. */\nexport function quoteError(error: unknown): { code?: string; message?: string } {\n const detail = apiErrorDetail(error)\n if (detail && typeof detail === 'object') {\n const { code, message } = detail as { code?: unknown; message?: unknown }\n return {\n code: typeof code === 'string' ? code : undefined,\n message: typeof message === 'string' ? message : undefined,\n }\n }\n return { message: typeof detail === 'string' ? detail : undefined }\n}\n","/**\n * Pro plan price helpers. Prices come from Stripe via GET /v1/user/products (source of truth).\n * One plan is sold: Pro, one licence (£10 of AI usage + 5 GB a month). Each price lists\n * `pack_prices` for that one licence — `amount` incl. UK VAT and `amount_ex_vat` — and\n * `addon_prices` (one add-on block on that interval). Display them as-is.\n * Legacy subscriptions with several packs keep working; their name and price come from the project.\n */\n\nimport type { components } from '@arbidocs/client'\nimport { formatGbp } from '@arbidocs/react'\nimport { formatMoney } from './reward-balance'\nimport { formatPeriodEnd } from './addon-pricing'\nimport { taxSummary } from './tax-quote'\nimport { ADDON_BLOCK_AI_GBP, STORAGE_BLOCK_GB } from './plan-constants'\n\ntype PlanChangePreview = components['schemas']['PlanChangePreview']\ntype ProductPrice = components['schemas']['ProductPrice']\ntype ProductResponse = components['schemas']['ProductResponse']\ntype PackPrice = components['schemas']['PackPrice']\ntype AddonPrice = components['schemas']['AddonPrice']\n\nexport type PlanInterval = 'month' | 'year'\n\nconst gbp = (pence: number) => formatMoney(pence, 'gbp')\n\n/** The headline price: \"£40 + VAT\". */\nexport function plusVat(exVatPence: number, currency = 'gbp'): string {\n return `${formatMoney(exVatPence, currency)} + VAT`\n}\n\n/** The one licence Pro sells. Other pack counts exist only on legacy subscriptions (displayed, not sold). */\nexport const PRO_PACKS = 1\n\n/** A plan the pickers offer. */\nexport type PlanChoice = 'free' | 'pro'\n\n/** Packs per plan choice (0 = Free). */\nexport const PLAN_CHOICE_PACKS: Record<PlanChoice, number> = {\n free: 0,\n pro: PRO_PACKS,\n}\n\n/** \"Free\" (0), \"Pro\" (1), otherwise \"Pro ×N\" (a legacy multi-pack plan; the API's own name wins). */\nexport function planNameForPacks(packs: number | null | undefined): string {\n const n = packs ?? 0\n if (n <= 0) return 'Free'\n if (n === PRO_PACKS) return 'Pro'\n return `Pro ×${n}`\n}\n\n/** The plan-change panel's fixed lines, each with a test id. */\nexport interface PlanChangeLine {\n id: 'pay-today' | 'from' | 'current-until' | 'no-change' | 'awaiting-bank'\n text: string\n}\n\n/**\n * What a plan change costs, from the backend's Stripe invoice preview (taxed for the customer's\n * address), as fixed lines:\n * - \"Pay today £42.00 incl. VAT (£35.00 + £7.00 VAT 20%)\" (\"Pay today £0\" for a change that waits)\n * - \"From 16 Nov 2026: £210.00 incl. VAT (£175.00 + £35.00 VAT 20%) a month\"\n * - \"Current plan until 16 Nov 2026\" for a change that waits for the period end.\n * \"No change\" when the selection is what the project already has; \"Waiting for your bank\" while\n * an earlier upgrade payment awaits 3-D Secure.\n */\nexport function planPreviewLines(preview: PlanChangePreview): PlanChangeLine[] {\n if (preview.unchanged) return [{ id: 'no-change', text: 'No change' }]\n const date = formatPeriodEnd(preview.next_renewal_at)\n const cadence = preview.interval === 'year' ? 'year' : 'month'\n const lines: PlanChangeLine[] = [\n preview.awaiting_confirmation\n ? { id: 'awaiting-bank', text: 'Waiting for your bank' }\n : {\n id: 'pay-today',\n text: preview.effective_now\n ? `Pay today ${taxSummary({\n subtotal: preview.due_now_ex_vat_pence,\n tax: preview.due_now_tax_pence,\n total: preview.due_now_pence,\n label: preview.tax_label,\n })}`\n : `Pay today ${gbp(0)}`,\n },\n {\n id: 'from',\n text: `${date ? `From ${date}` : 'From renewal'}: ${taxSummary({\n subtotal: preview.next_renewal_ex_vat_pence,\n tax: preview.next_renewal_tax_pence,\n total: preview.next_renewal_pence,\n label: preview.tax_label,\n })} a ${cadence}`,\n },\n ]\n if (!preview.effective_now) {\n lines.push({ id: 'current-until', text: `Current plan until ${date ?? 'renewal'}` })\n }\n return lines\n}\n\n/** Stand-in for \"Pay today\" when the preview failed for an upgrade. */\nexport const PAY_TODAY_UNPRICED = 'Pay today: the difference for the rest of this period'\n\n/** One add-on block's price on this interval's plan price (`addon_prices`), if listed. */\nexport function addonPrice(\n price: ProductPrice | undefined,\n kind: 'ai_usage' | 'storage' = 'ai_usage'\n): AddonPrice | undefined {\n return price?.addon_prices?.find((p) => p.kind === kind)\n}\n\n/** Per add-on block of `kind` per month, ex VAT (annual plans: the monthly equivalent). */\nexport function addonMonthlyExVat(\n price: ProductPrice | undefined,\n kind: 'ai_usage' | 'storage' = 'ai_usage'\n): number | undefined {\n return addonPrice(price, kind)?.monthly_ex_vat\n}\n\n/** What a checkout buys: \"Pro\", \"Pro + 2 × £25 of AI usage + 1 × 25 GB\". */\nexport function checkoutItemsLabel(aiBlocks: number, storageBlocks: number): string {\n return [\n 'Pro',\n aiBlocks > 0 && `${aiBlocks} × ${formatGbp(ADDON_BLOCK_AI_GBP)} of AI usage`,\n storageBlocks > 0 && `${storageBlocks} × ${STORAGE_BLOCK_GB} GB`,\n ]\n .filter(Boolean)\n .join(' + ')\n}\n\n/** The price of `packs` packs on this interval's price, if Stripe lists it (only one licence is listed). */\nexport function packPrice(\n price: ProductPrice | undefined,\n packs: number = PRO_PACKS\n): PackPrice | undefined {\n return price?.pack_prices?.find((p) => p.packs === packs)\n}\n\nexport interface ProPrices {\n monthly?: ProductPrice\n annual?: ProductPrice\n}\n\n/** The Pro product's monthly and annual prices (default price per interval wins). */\nexport function findProPrices(products: ProductResponse[] | undefined): ProPrices {\n const prices = products?.[0]?.prices ?? []\n const pick = (interval: PlanInterval) =>\n prices.find((p) => p.interval === interval && p.default_price) ??\n prices.find((p) => p.interval === interval)\n return { monthly: pick('month'), annual: pick('year') }\n}\n\n/** Annual savings vs 12 × monthly, as a whole percent (e.g. £360 vs £480 → 25). */\nexport function calcSavingsPercent(\n monthlyPrice: ProductPrice | undefined,\n annualPrice: ProductPrice | undefined\n): number | null {\n const monthly = packPrice(monthlyPrice)?.amount ?? monthlyPrice?.amount\n const annual = packPrice(annualPrice)?.amount ?? annualPrice?.amount\n if (monthly == null || annual == null || monthly === 0) return null\n const savings = Math.round(((monthly * 12 - annual) / (monthly * 12)) * 100)\n return savings > 0 ? savings : null\n}\n\n/** Most add-on blocks of each kind a checkout may include (the backend's limit). */\nexport const MAX_CHECKOUT_BLOCKS = 100\n\n/** \"£25/month + VAT each\", annual: \"£225/year + VAT each\": one block on the chosen interval. */\nexport function checkoutBlockPriceText(\n price: ProductPrice | undefined,\n kind: 'ai_usage' | 'storage'\n): string | null {\n const block = addonPrice(price, kind)\n if (!block) return null\n const currency = price?.currency ?? 'gbp'\n return price?.interval === 'year'\n ? `${formatMoney(block.amount_ex_vat, currency)}/year + VAT each`\n : `${formatMoney(block.amount_ex_vat, currency)}/month + VAT each`\n}\n","import type { PlanBadgeProps } from '../../settings'\nimport type { components } from '@arbidocs/client'\nimport { planNameForPacks } from './plan-pricing'\n\ntype ProjectBillingFields = Pick<\n components['schemas']['ProjectResponse'],\n 'subscription' | 'plan_interval'\n> &\n Partial<Pick<components['schemas']['ProjectResponse'], 'packs' | 'addons'>>\n\n/** A project is on Pro when it has a billing interval (null = Free or checkout pending). */\nexport function isProProject(project: Pick<ProjectBillingFields, 'plan_interval'>): boolean {\n return project.plan_interval != null\n}\n\n/** \"Pro\", or a legacy multi-pack plan's name (\"Pro ×N\") — the API's name when it sends one (owner view). */\nexport function proTierName(project: ProjectBillingFields): string {\n return project.addons?.plan_name || planNameForPacks(Math.max(project.packs ?? 1, 1))\n}\n\n/** \"Free\", \"Pro monthly\", \"Pro annual\", \"Pro ×3 monthly\" (legacy) or \"Dev\" — the full plan name. */\nexport function planName(project: ProjectBillingFields): string {\n if (project.subscription === 'dev') return 'Dev'\n if (!isProProject(project)) return 'Free'\n return `${proTierName(project)} ${project.plan_interval === 'year' ? 'annual' : 'monthly'}`\n}\n\n/**\n * Maps a project's billing state to the `PlanBadge` block's label + tone.\n * Pro reads as accent, Free/dev as neutral, payment trouble or cancelling as pending.\n */\nexport function planBadgeView(\n project: ProjectBillingFields\n): Pick<PlanBadgeProps, 'label' | 'tone'> {\n const { subscription } = project\n const label =\n subscription === 'canceled'\n ? 'Cancelling'\n : subscription === 'dev'\n ? 'Dev'\n : isProProject(project)\n ? proTierName(project)\n : 'Free'\n\n const tone =\n subscription === 'dev'\n ? 'dev'\n : subscription === 'canceled' || subscription === 'past_due'\n ? 'pending'\n : isProProject(project)\n ? 'paid'\n : 'free'\n\n return { label, tone }\n}\n","/**\n * What a project's group in the workspace list says about the project itself: its plan badge (own\n * projects, where plans are sold), the usage readout beside its name, and the plan and limits\n * breakdown behind the name. One source for the cards' bands and the table's headings.\n */\nimport type { ReactNode } from 'react'\nimport type { LucideIcon } from 'lucide-react'\nimport type { components } from '@arbidocs/client'\nimport { UsageMeter } from '../../components/UsageMeter'\nimport { PlanBadge, QuotaMeter } from '../../settings'\nimport { ProjectBreakdown, ProjectReadout } from '../../home/ProjectBandParts'\nimport { planBadgeView } from '../billing/plan-badge'\nimport { getQuotaItems } from '../billing/quota-items'\n\ntype Project = components['schemas']['ProjectResponse']\n\nexport interface ProjectGroupBilling {\n /** The plan badge: own projects only, where plans are sold. */\n planBadge?: ReactNode\n /** Plan and usage, right after the name (projects with quotas). */\n readout?: ReactNode\n /** The plan and limits panel behind the name; meters for own projects only. */\n breakdown?: ReactNode\n}\n\nexport function projectGroupBilling(\n project: Project | undefined,\n { isOwned, stripeEnabled }: { isOwned: boolean; stripeEnabled: boolean }\n): ProjectGroupBilling {\n if (!project) return {}\n const planBadge = isOwned && stripeEnabled ? <PlanBadge {...planBadgeView(project)} /> : undefined\n const quotaItems = project.quotas ? getQuotaItems(project.quotas) : []\n const readout = project.quotas ? (\n <ProjectReadout\n plan={\n planBadge ? { badge: planBadge, testId: `project-tier-${project.external_id}` } : undefined\n }\n usage={{\n testId: `project-usage-${project.external_id}`,\n // Bare numbers without plans for sale: a glance beside the name, not the Plan & Usage detail.\n node: (\n <QuotaMeter\n items={quotaItems}\n size=\"sm\"\n showTooltips={false}\n showBars={stripeEnabled}\n showPercent={false}\n />\n ),\n }}\n />\n ) : (\n planBadge\n )\n const breakdown = (\n <ProjectBreakdown\n name={project.name}\n badge={planBadge}\n meters={\n isOwned\n ? quotaItems.map(({ key, icon, label, usedOfLimit, pct }) => (\n <UsageMeter\n key={key}\n icon={icon as LucideIcon}\n label={label}\n value={usedOfLimit}\n pct={pct}\n />\n ))\n : undefined\n }\n dailyCap={{\n label: 'Daily cap',\n value:\n project.daily_cap_per_user == null\n ? 'No limit'\n : project.daily_cap_per_user.toLocaleString('en-US'),\n }}\n />\n )\n return { planBadge, readout, breakdown }\n}\n"]}
@@ -1,12 +1,12 @@
1
1
  "use client";
2
2
  'use strict';
3
3
 
4
- var chunkNZCAWWV4_cjs = require('./chunk-NZCAWWV4.cjs');
4
+ var chunkZUOU54X3_cjs = require('./chunk-ZUOU54X3.cjs');
5
+ var chunkYP643FYT_cjs = require('./chunk-YP643FYT.cjs');
5
6
  var chunkMB3S2ETI_cjs = require('./chunk-MB3S2ETI.cjs');
6
7
  var chunkZ2XZ2D4N_cjs = require('./chunk-Z2XZ2D4N.cjs');
7
8
  var chunkCQ2YSHIF_cjs = require('./chunk-CQ2YSHIF.cjs');
8
- var chunkBBTHGWZO_cjs = require('./chunk-BBTHGWZO.cjs');
9
- var chunkAHYSHKPL_cjs = require('./chunk-AHYSHKPL.cjs');
9
+ var chunk7THRBD42_cjs = require('./chunk-7THRBD42.cjs');
10
10
  var React = require('react');
11
11
  var jsxRuntime = require('react/jsx-runtime');
12
12
  var react = require('@arbidocs/react');
@@ -138,7 +138,7 @@ function WorkspaceDocumentReference({
138
138
  children,
139
139
  className = "inline-flex rounded-full border px-2 py-0.5 text-xs hover:bg-muted"
140
140
  }) {
141
- const { openDocument } = chunkAHYSHKPL_cjs.useBlocksEnvironment();
141
+ const { openDocument } = chunk7THRBD42_cjs.useBlocksEnvironment();
142
142
  return /* @__PURE__ */ jsxRuntime.jsx(
143
143
  "button",
144
144
  {
@@ -165,19 +165,19 @@ function MentionLink({ kind, id, text }) {
165
165
  );
166
166
  }
167
167
  function ExternalLink({ href, children }) {
168
- return /* @__PURE__ */ jsxRuntime.jsx(chunkBBTHGWZO_cjs.QuietLink, { href, kind: "external", children });
168
+ return /* @__PURE__ */ jsxRuntime.jsx(chunkZUOU54X3_cjs.QuietLink, { href, kind: "external", children });
169
169
  }
170
170
  function InternalDocLink({
171
171
  docId,
172
172
  href,
173
173
  children
174
174
  }) {
175
- const { openDocument } = chunkAHYSHKPL_cjs.useBlocksEnvironment();
175
+ const { openDocument } = chunk7THRBD42_cjs.useBlocksEnvironment();
176
176
  const workspaceId = useDocumentWorkspace();
177
177
  if (workspaceId) {
178
178
  return /* @__PURE__ */ jsxRuntime.jsx(WorkspaceDocumentReference, { workspaceId, docId, children });
179
179
  }
180
- return /* @__PURE__ */ jsxRuntime.jsx(chunkBBTHGWZO_cjs.QuietLink, { href, kind: "document", onOpen: () => openDocument(docId), children });
180
+ return /* @__PURE__ */ jsxRuntime.jsx(chunkZUOU54X3_cjs.QuietLink, { href, kind: "document", onOpen: () => openDocument(docId), children });
181
181
  }
182
182
  function DocumentChip({ docId }) {
183
183
  const render = react.useArbiHost().chat?.renderDocumentChip;
@@ -187,7 +187,7 @@ function DocumentChip({ docId }) {
187
187
  }
188
188
  function DefaultDocumentChip({ docId }) {
189
189
  const { data: doc } = react.useDocument(docId);
190
- const { openDocument } = chunkAHYSHKPL_cjs.useBlocksEnvironment();
190
+ const { openDocument } = chunk7THRBD42_cjs.useBlocksEnvironment();
191
191
  if (!doc)
192
192
  return /* @__PURE__ */ jsxRuntime.jsx(
193
193
  ui.EntityPill,
@@ -220,13 +220,13 @@ var conversationMarkdownComponents = {
220
220
  children,
221
221
  ...props
222
222
  }) {
223
- const deploymentDomain = chunkAHYSHKPL_cjs.useBlocksEnvironment().runtimeConfig.deploymentDomain;
223
+ const deploymentDomain = chunk7THRBD42_cjs.useBlocksEnvironment().runtimeConfig.deploymentDomain;
224
224
  const mention = shell.mentionFromHref(href);
225
225
  if (mention) {
226
226
  return /* @__PURE__ */ jsxRuntime.jsx(MentionLink, { kind: mention.kind, id: mention.id, text: childrenText(children) });
227
227
  }
228
228
  if (href?.startsWith("#") && !href.startsWith("#cite-")) {
229
- return /* @__PURE__ */ jsxRuntime.jsx(chunkBBTHGWZO_cjs.QuietLink, { href, kind: "anchor", children });
229
+ return /* @__PURE__ */ jsxRuntime.jsx(chunkZUOU54X3_cjs.QuietLink, { href, kind: "anchor", children });
230
230
  }
231
231
  if (!href || href.startsWith("#") || href.startsWith("cite:")) {
232
232
  return /* @__PURE__ */ jsxRuntime.jsx(ui.MarkdownLink, { href, ...props, children });
@@ -277,8 +277,8 @@ function OwnDocumentTools({ children }) {
277
277
  const arbi = react.useArbi();
278
278
  const queryClient = reactQuery.useQueryClient();
279
279
  const host = chunkMB3S2ETI_cjs.useHost().documentTools;
280
- const { user, ensureWorkspaceOpen } = chunkNZCAWWV4_cjs.useConnectedWorkspace();
281
- const { notify: environmentNotify, openDocument: openInHost } = chunkAHYSHKPL_cjs.useBlocksEnvironment();
280
+ const { user, ensureWorkspaceOpen } = chunkYP643FYT_cjs.useConnectedWorkspace();
281
+ const { notify: environmentNotify, openDocument: openInHost } = chunk7THRBD42_cjs.useBlocksEnvironment();
282
282
  const useEmailDocument = host?.useEmailDocument ?? NO_EMAIL;
283
283
  const emailDocument = useEmailDocument();
284
284
  const client = host?.client ?? (arbi.isLoggedIn ? arbi.getClient().fetch : null);
@@ -372,5 +372,5 @@ exports.useViewerDraftDocument = useViewerDraftDocument;
372
372
  exports.useViewerIsDetached = useViewerIsDetached;
373
373
  exports.useViewerPassageCitation = useViewerPassageCitation;
374
374
  exports.useViewerStreamingDocument = useViewerStreamingDocument;
375
- //# sourceMappingURL=chunk-W5PKYJX5.cjs.map
376
- //# sourceMappingURL=chunk-W5PKYJX5.cjs.map
375
+ //# sourceMappingURL=chunk-W6DDSZUD.cjs.map
376
+ //# sourceMappingURL=chunk-W6DDSZUD.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/chat/mermaid-normalize.ts","../src/connection/conversation/MermaidDiagram.tsx","../src/connection/conversation/DocumentWorkspaceContext.tsx","../src/connection/conversation/ConnectedMarkdown.tsx","../src/connection/viewer/ConnectedDocumentToolsProvider.tsx","../src/connection/viewer/support.ts"],"names":["useState","useId","useEffect","jsxs","jsx","createContext","useContext","useBlocksEnvironment","React","useArbiSession","MentionChip","QuietLink","useArbiHost","Fragment","useDocument","EntityPill","FileText","DocumentEntity","Mail","mentionFromHref","MarkdownLink","workspaceDocIdFromHref","MarkdownStreamingContext","MarkdownCode","rehypeDocEntityPills","useMemo","KitMarkdownRenderer","useOptionalDocumentTools","useArbi","useQueryClient","useHost","useConnectedWorkspace","useCallback","refreshDocuments","arbiQueryKeys","documentBytesKey","clientUpload","DocumentToolsProvider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsBO,SAAS,sBAAsB,MAAA,EAAwB;AAE5D,EAAA,IAAI,IAAA,CAAK,IAAA,CAAK,MAAM,CAAA,EAAG,OAAO,MAAA;AAE9B,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,KAAA,CAAM,gCAAgC,CAAA;AACjE,EAAA,IAAI,CAAC,aAAa,OAAO,MAAA;AAEzB,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,CAAC,CAAA,CAAE,OAAA,EAAQ;AACtC,EAAA,IAAI,OAAO,MAAA,CAAO,KAAA,CAAM,WAAA,CAAY,CAAC,EAAE,MAAM,CAAA;AAG7C,EAAA,IAAA,GAAO,IAAA,CAAK,OAAA,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":["/**\n * Defensive normalizer for single-line `graph` / `flowchart` Mermaid source.\n *\n * Some LLMs emit the entire diagram on one line. Mermaid's parser splits\n * statements on newlines, so a single-line graph fails outright. This helper\n * inserts newlines on safe statement boundaries so the diagram has a chance\n * of parsing. Only attempts normalization when:\n * 1. The source has no embedded newlines (i.e. is genuinely single-line), and\n * 2. The first directive is `graph` or `flowchart`.\n *\n * Other diagram types (sequenceDiagram, classDiagram, gantt, …) have very\n * different syntaxes — applying these heuristics to them would corrupt valid\n * input, so they're left untouched.\n *\n * Boundaries we split on:\n * - After the diagram-type header (`graph TD`, `flowchart LR`, …).\n * - Before each `style` / `classDef` / `class` / `linkStyle` / `click`\n * / `subgraph` keyword.\n * - Before/after `end` (closes a subgraph block).\n * - After a `]` (label close) that's followed by another node identifier\n * starting a new edge or node declaration.\n */\nexport function normalizeMermaidGraph(source: string): string {\n // Already multi-line — assume it's well-formed; don't touch it.\n if (/\\n/.test(source)) return source\n\n const headerMatch = source.match(/^\\s*(graph|flowchart)\\s+\\w+\\s+/)\n if (!headerMatch) return source\n\n const header = headerMatch[0].trimEnd()\n let body = source.slice(headerMatch[0].length)\n\n // Insert newline before keywords that always start a new statement.\n body = body.replace(/\\s+(style|classDef|class|linkStyle|click|subgraph)\\s/g, '\\n$1 ')\n\n // `end` closes a subgraph: put it on its own line, with a break after it\n // too so any trailing statements don't stay attached.\n body = body.replace(/\\s+end\\b\\s*/g, '\\nend\\n')\n\n // After a label close (`]`), if the next token looks like a Mermaid node id\n // followed by another `[` or `-->`, that's a new statement starting.\n body = body.replace(/\\]\\s+(?=[A-Za-z_][\\w-]*\\s*(?:\\[|-->))/g, ']\\n')\n\n // Collapse any accidental runs of blank lines we may have produced.\n body = body.replace(/\\n{2,}/g, '\\n')\n\n return `${header}\\n${body.trimStart()}`\n}\n","/**\n * MermaidDiagram Component\n *\n * Renders a Mermaid diagram from source code.\n * Used inside MarkdownRenderer to handle ```mermaid code blocks.\n * Lazy-loads the mermaid library to avoid bloating the initial bundle.\n */\n\nimport { useState, useEffect, useId } from 'react'\nimport { normalizeMermaidGraph } from '../../chat/mermaid-normalize'\n\ninterface MermaidDiagramProps {\n /** Mermaid diagram source code */\n chart: string\n}\n\n// Lazy-load and initialize mermaid once\nlet mermaidInstance: typeof import('mermaid').default | null = null\nlet mermaidLoadPromise: Promise<typeof import('mermaid').default> | null = null\n\nasync function getMermaid() {\n if (mermaidInstance) return mermaidInstance\n if (!mermaidLoadPromise) {\n mermaidLoadPromise = import('mermaid').then((mod) => {\n const m = mod.default\n m.initialize({\n startOnLoad: false,\n theme: 'default',\n securityLevel: 'strict',\n flowchart: { useMaxWidth: true, curve: 'basis' },\n })\n mermaidInstance = m\n return m\n })\n }\n return mermaidLoadPromise\n}\n\nexport function MermaidDiagram({ chart }: MermaidDiagramProps) {\n const [svg, setSvg] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const uniqueId = useId().replace(/:/g, '-')\n\n useEffect(() => {\n let cancelled = false\n\n async function render() {\n const mermaid = await getMermaid()\n const diagramId = `mermaid${uniqueId}`\n\n // Validate with parse() before render(). In Mermaid v11 a render() with\n // bad source can return a \"Syntax error in text\" bomb SVG instead of\n // throwing — and it appends DOM side-effects of its own — so a try/catch\n // around render() doesn't reliably catch failures and the bomb leaks\n // into the page (especially under React StrictMode where effects run\n // twice). parse() throws cleanly with no DOM side-effects.\n //\n // Defensive rescue: some LLMs emit single-line `graph`/`flowchart`\n // source. If the original parse fails, try a normalized variant. The\n // normalizer is a no-op on already-multi-line source and on non-graph\n // diagram types, so this only helps the bad-source case and never\n // corrupts valid input.\n let validSource: string | null = null\n let firstErr: unknown\n try {\n await mermaid.parse(chart)\n validSource = chart\n } catch (err) {\n firstErr = err\n const normalized = normalizeMermaidGraph(chart)\n if (normalized !== chart) {\n try {\n await mermaid.parse(normalized)\n validSource = normalized\n } catch (retryErr) {\n console.warn('Mermaid normalized parse also failed', retryErr)\n }\n }\n }\n\n if (cancelled) return\n\n if (!validSource) {\n console.warn('Mermaid parse failed, showing source', firstErr)\n setError('Failed to render diagram')\n setSvg(null)\n return\n }\n\n try {\n const { svg: renderedSvg } = await mermaid.render(diagramId, validSource)\n if (!cancelled) {\n setSvg(renderedSvg)\n setError(null)\n }\n } catch (renderErr) {\n if (!cancelled) {\n console.warn('Mermaid render failed despite parse success', renderErr)\n setError('Failed to render diagram')\n setSvg(null)\n }\n }\n }\n\n render()\n return () => {\n cancelled = true\n }\n }, [chart, uniqueId])\n\n if (error) {\n // Fall back to showing the raw source in a code block\n return (\n <div className=\"code-block\" data-testid=\"mermaid-error\">\n <div className=\"text-sm text-muted-foreground mb-1\">{error}</div>\n <code className=\"language-mermaid\">{chart}</code>\n </div>\n )\n }\n\n if (!svg) {\n return (\n <div\n className=\"flex items-center justify-center py-8 text-muted-foreground text-sm\"\n data-testid=\"mermaid-loading\"\n >\n Rendering diagram...\n </div>\n )\n }\n\n return (\n <div\n className=\"mermaid-diagram my-4 overflow-x-auto rounded-md border border-border bg-background p-4\"\n data-testid=\"mermaid-diagram\"\n dangerouslySetInnerHTML={{ __html: svg }}\n />\n )\n}\n","/**\n * The workspace a conversation's document references belong to, when it is not the open one: an\n * agent's direct-message thread runs in the agent's workspace, so the documents it names are there.\n * A reference then opens that workspace first (`openDocument(id, { workspaceId })`).\n */\n\nimport { createContext, useContext, type ReactNode } from 'react'\nimport { useBlocksEnvironment } from '../../provider/environment'\n\n/** The workspace of the documents referenced inside it (null: the open workspace). */\nexport const DocumentWorkspaceContext = createContext<string | null>(null)\nexport const useDocumentWorkspace = () => useContext(DocumentWorkspaceContext)\n\n/** A reference to a document of another workspace: opening it opens that workspace first. */\nexport function WorkspaceDocumentReference({\n workspaceId,\n docId,\n children,\n className = 'inline-flex rounded-full border px-2 py-0.5 text-xs hover:bg-muted',\n}: {\n workspaceId: string\n docId: string\n children?: ReactNode\n className?: string\n}) {\n const { openDocument } = useBlocksEnvironment()\n return (\n <button\n type=\"button\"\n className={className}\n onClick={() => openDocument(docId, { workspaceId })}\n >\n {children ?? docId}\n </button>\n )\n}\n","/**\n * The conversation's markdown: the kit's `MarkdownRenderer` (`@arbidocs/react`: sanitised HTML,\n * slugs, lazy KaTeX, streaming blocks, tables, code) with what a conversation adds: @mention chips,\n * workspace documents opening in the viewer, quiet external links, document and email pills (the\n * host's chips, `ArbiChatHost.renderDocumentChip` / `renderMailChip`) and Mermaid diagrams.\n */\nimport { useArbiHost, useArbiSession, useDocument } from '@arbidocs/react'\nimport { mentionFromHref, type MentionKind } from '@arbidocs/react/shell'\nimport {\n EntityPill,\n MarkdownCode,\n MarkdownLink,\n MarkdownRenderer as KitMarkdownRenderer,\n MarkdownStreamingContext,\n type MarkdownRendererProps as KitMarkdownRendererProps,\n DocumentEntity,\n} from '@arbidocs/react/ui'\nimport React, { useContext, useMemo } from 'react'\nimport { FileText, Mail } from 'lucide-react'\n\n/** The markdown element overrides, as the kit's renderer takes them. */\ntype Components = NonNullable<KitMarkdownRendererProps['components']>\nimport { MentionChip } from '../../chat/MentionMenu'\nimport { QuietLink } from '../../citations/QuietMarks'\nimport { rehypeDocEntityPills } from '../../chat/rehype-doc-entity-pills'\nimport { workspaceDocIdFromHref } from '../../chat/doc-links'\nimport { useBlocksEnvironment } from '../../provider/environment'\nimport { MermaidDiagram } from './MermaidDiagram'\nimport { useDocumentWorkspace, WorkspaceDocumentReference } from './DocumentWorkspaceContext'\n\n/** Plain text of a link's children (the `@Label` of a mention link). */\nfunction childrenText(children: React.ReactNode): string {\n return React.Children.toArray(children)\n .map((child) => (typeof child === 'string' || typeof child === 'number' ? String(child) : ''))\n .join('')\n}\n\n/** A mention chip; a mention of the reader stands out. */\nfunction MentionLink({ kind, id, text }: { kind: MentionKind; id: string; text: string }) {\n const currentUserId = useArbiSession().user?.external_id\n return (\n <MentionChip\n kind={kind}\n id={id}\n label={text.replace(/^@/, '')}\n isSelf={kind === 'user' && id === currentUserId}\n />\n )\n}\n\n/**\n * A link to elsewhere, as quiet text. Its menu (Open link / Copy link) is the deliberate step\n * the old confirmation dialog used to be; nothing opens until the menu's primary row is chosen.\n */\nexport function ExternalLink({ href, children }: React.ComponentPropsWithoutRef<'a'>) {\n return (\n <QuietLink href={href} kind=\"external\">\n {children}\n </QuietLink>\n )\n}\n\n/**\n * A workspace document referenced by a link's href rather than by its text.\n *\n * `rehypeDocEntityPills` turns a bare `doc-…` id into a pill, but it only walks\n * TEXT nodes — so `[NVDA DCF Valuation Report](…doc-abc12345…)`, which is how an\n * answer links an artifact it just saved, keeps the id in the href where the\n * plugin never looks. The link then fell through to `ExternalLink`, and opening\n * your own workspace document asked you to confirm an \"external link\" and\n * launched a new tab. It opens in the document viewer, like the pill and the\n * artifact card already do.\n */\nexport function InternalDocLink({\n docId,\n href,\n children,\n}: React.ComponentPropsWithoutRef<'a'> & { docId: string }) {\n const { openDocument } = useBlocksEnvironment()\n const workspaceId = useDocumentWorkspace()\n if (workspaceId) {\n return (\n <WorkspaceDocumentReference workspaceId={workspaceId} docId={docId}>\n {children}\n </WorkspaceDocumentReference>\n )\n }\n\n return (\n <QuietLink href={href} kind=\"document\" onOpen={() => openDocument(docId)}>\n {children}\n </QuietLink>\n )\n}\n\n/** A document of the workspace, as a pill: the host's chip, else the document entity. */\nexport function DocumentChip({ docId }: { docId: string }) {\n const render = useArbiHost().chat?.renderDocumentChip\n const workspaceId = useDocumentWorkspace()\n if (workspaceId) return <WorkspaceDocumentReference workspaceId={workspaceId} docId={docId} />\n return render ? <>{render(docId)}</> : <DefaultDocumentChip docId={docId} />\n}\n\nfunction DefaultDocumentChip({ docId }: { docId: string }) {\n const { data: doc } = useDocument(docId)\n const { openDocument } = useBlocksEnvironment()\n if (!doc)\n return (\n <EntityPill\n icon={<FileText className=\"w-3.5 h-3.5 flex-shrink-0\" />}\n label={docId}\n size=\"sm\"\n onClick={() => openDocument(docId)}\n data-testid=\"doc-entity-pill\"\n />\n )\n return (\n <DocumentEntity doc={doc} onClick={() => openDocument(docId)} data-testid=\"doc-entity-pill\" />\n )\n}\n\n/** An email of the person's mailbox, as a pill: the host's chip, else a plain \"Email\". */\nexport function MailChip({ mailId }: { mailId: string }) {\n const render = useArbiHost().chat?.renderMailChip\n if (render) return <>{render(mailId)}</>\n return (\n <EntityPill\n icon={<Mail className=\"w-3.5 h-3.5 flex-shrink-0\" />}\n label=\"Email\"\n size=\"sm\"\n data-testid=\"mail-entity-pill\"\n />\n )\n}\n\n/**\n * The conversation's overrides, layered on the kit's defaults. Module scope, so the reference is stable\n * and memoised markdown blocks do not re-parse.\n */\nconst conversationMarkdownComponents: Partial<Components> = {\n a: function ConversationMarkdownLink({\n href,\n children,\n ...props\n }: React.ComponentPropsWithoutRef<'a'>) {\n const deploymentDomain = useBlocksEnvironment().runtimeConfig.deploymentDomain\n // @mentions: `linkMentions` turned them into `#mention-<id>` links; draw them as chips.\n const mention = mentionFromHref(href)\n if (mention) {\n return <MentionLink kind={mention.kind} id={mention.id} text={childrenText(children)} />\n }\n // Bookmarks: in-page anchors are near-invisible text; the menu jumps or copies the place.\n if (href?.startsWith('#') && !href.startsWith('#cite-')) {\n return (\n <QuietLink href={href} kind=\"anchor\">\n {children}\n </QuietLink>\n )\n }\n // Citations, `cite:` references and bare links: the kit's link.\n if (!href || href.startsWith('#') || href.startsWith('cite:')) {\n return (\n <MarkdownLink href={href} {...props}>\n {children}\n </MarkdownLink>\n )\n }\n // A workspace document is not an external link, wherever it is hosted: it opens in the viewer.\n const docId = workspaceDocIdFromHref(href, deploymentDomain)\n if (docId) {\n return (\n <InternalDocLink docId={docId} href={href} {...props}>\n {children}\n </InternalDocLink>\n )\n }\n return (\n <ExternalLink href={href} {...props}>\n {children}\n </ExternalLink>\n )\n },\n code: function ConversationMarkdownCode(\n props: React.ComponentPropsWithoutRef<'code'> & { inline?: boolean }\n ) {\n const isStreaming = useContext(MarkdownStreamingContext)\n const { className, children } = props\n const language = /language-(\\w+)/.exec(className || '')?.[1]\n if (!language) {\n // Answers often backtick a bare doc id (`doc-f7b3eeb5`). The text-node pass skips code, so\n // the id would stay monospace text; show it as the document pill. Only a whole id (eight\n // alphanumerics): while streaming, a partial one (\"doc-e\") would be looked up and 404.\n const codeText = typeof children === 'string' ? children.trim() : ''\n if (/^doc-[a-zA-Z0-9]{8}$/.test(codeText)) return <DocumentChip docId={codeText} />\n if (/^eml-[a-zA-Z0-9]{8}$/.test(codeText)) return <MailChip mailId={codeText} />\n }\n // Mermaid lazy-loads its own bundle and re-renders SVG on every change. While streaming the\n // fence is almost always partial, so it stays a code block until generation completes.\n if (language === 'mermaid' && !isStreaming) {\n return <MermaidDiagram chart={String(children).replace(/\\n$/, '')} />\n }\n return <MarkdownCode {...props} />\n },\n span: ({ children, className, ...props }: React.ComponentPropsWithoutRef<'span'>) => {\n const docId = (props as Record<string, unknown>)['data-doc-id'] as string | undefined\n if (docId) return <DocumentChip docId={docId} />\n const mailId = (props as Record<string, unknown>)['data-mail-id'] as string | undefined\n if (mailId) return <MailChip mailId={mailId} />\n return (\n <span className={className} {...props}>\n {children}\n </span>\n )\n },\n}\n\n/** Bare `doc-…` / `eml-…` ids in text become `<span data-doc-id>` / `<span data-mail-id>` pills. */\nconst conversationRehypePlugins = [rehypeDocEntityPills]\n\nexport type ConnectedMarkdownProps = Omit<KitMarkdownRendererProps, 'rehypePlugins'>\n\n/**\n * The kit's renderer with the conversation's overrides; a caller's `components` (e.g. the citation\n * core's) still win over both.\n */\nfunction ConnectedMarkdownComponent({ components, ...props }: ConnectedMarkdownProps) {\n const merged = useMemo(\n () =>\n components\n ? { ...conversationMarkdownComponents, ...components }\n : conversationMarkdownComponents,\n [components]\n )\n return (\n <KitMarkdownRenderer {...props} components={merged} rehypePlugins={conversationRehypePlugins} />\n )\n}\n\nexport const ConnectedMarkdown = React.memo(ConnectedMarkdownComponent)\n","/**\n * The PDF document tools (markup, Freeze, signing, signature requests, productions) on the\n * signed-in session, for any host: the API client, the signed-in user, the host's notices and\n * document opening (`BlocksEnvironment`), and the shared caches a change refreshes. A host with its\n * own binding (its own lists to refresh, an XHR upload with progress, Mail) gives it as the host\n * configuration's `documentTools`, field by field. An enclosing `DocumentToolsProvider` (a dialog\n * with its own client) wins.\n */\n\nimport { useCallback, useMemo, type ReactNode } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { arbiQueryKeys, refreshDocuments, useArbi } from '@arbidocs/react'\nimport {\n DocumentToolsProvider,\n clientUpload,\n documentBytesKey,\n useOptionalDocumentTools,\n type DocumentChange,\n type DocumentToolsClient,\n type DocumentToolsEnvironment,\n type DocumentToolsNotify,\n type DocumentUploadRequest,\n} from '@arbidocs/react/document-tools'\nimport { useBlocksEnvironment } from '../../provider/environment'\nimport { useHost } from '../../provider/host'\nimport { useConnectedWorkspace } from '../ConnectionProvider'\n\n/** What a host binds of the document tools itself; each absent field is the kit's own. */\nexport interface DocumentToolsHost {\n /** The API client the tools call. Default: the host `arbi`'s. */\n client?: DocumentToolsClient\n /** The deployment domain keys are derived for (signing). Default: the host `arbi`'s. */\n deploymentDomain?: string\n /** Open a document or a version the tools made. Default: the environment's `openDocument`. */\n openDocument?: (documentRef: string) => void\n /** Refresh the host's lists after a change. Default: the shared document caches. */\n onDocumentsChanged?: DocumentToolsEnvironment['onDocumentsChanged']\n /** Upload a derived copy. Default: through the API client, into the open workspace. */\n uploadDocument?: DocumentToolsEnvironment['uploadDocument']\n /**\n * Where \"View certificate\" goes for a signature `reference` (e.g. the site's own verify page).\n * Default: the certificate link the API returns (on the deployment domain).\n */\n certificateUrl?: (reference: string) => string\n /** Email a document (a hook): absent, or returning nothing, when mail is not offered. */\n useEmailDocument?: () => ((documentRef: string) => void) | undefined\n}\n\nconst NO_EMAIL = () => undefined\n\nexport function ConnectedDocumentToolsProvider({ children }: { children: ReactNode }) {\n const enclosing = useOptionalDocumentTools()\n return enclosing ? <>{children}</> : <OwnDocumentTools>{children}</OwnDocumentTools>\n}\n\nfunction OwnDocumentTools({ children }: { children: ReactNode }) {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n const host = useHost().documentTools\n const { user, ensureWorkspaceOpen } = useConnectedWorkspace()\n const { notify: environmentNotify, openDocument: openInHost } = useBlocksEnvironment()\n const useEmailDocument = host?.useEmailDocument ?? NO_EMAIL\n const emailDocument = useEmailDocument()\n const client = host?.client ?? (arbi.isLoggedIn ? arbi.getClient().fetch : null)\n const signer = useMemo(\n () => (user ? { name: user.name, email: user.email, externalId: user.externalId } : null),\n [user]\n )\n const notify = useCallback<DocumentToolsNotify>(\n (message, kind, options) =>\n environmentNotify(message, kind, {\n description: options?.description,\n action: options?.action,\n }),\n [environmentNotify]\n )\n const ownDocumentsChanged = useCallback(\n async (ids: string[], change: DocumentChange) => {\n // The list carries each version's markup count and the copies; a signature or a saved\n // version is a new current version, with new versions and a new rendered PDF.\n const refresh: Promise<unknown>[] = [refreshDocuments(queryClient, arbi, ids)]\n if (change === 'signed' || change === 'version')\n for (const id of ids)\n refresh.push(\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documentVersions(id) }),\n queryClient.invalidateQueries({ queryKey: documentBytesKey(id) })\n )\n await Promise.all(refresh)\n },\n [queryClient, arbi]\n )\n // The server files an upload in the session's open workspace: re-assert it first.\n const ownUpload = useCallback(\n async (request: DocumentUploadRequest) => {\n if (!client) throw new Error('Sign in to save a copy.')\n await ensureWorkspaceOpen()\n return clientUpload(client)(request)\n },\n [client, ensureWorkspaceOpen]\n )\n const ownOpenDocument = useCallback((ref: string) => openInHost(ref), [openInHost])\n if (!client) return <>{children}</>\n return (\n <DocumentToolsProvider\n client={client}\n deploymentDomain={host?.deploymentDomain}\n user={signer}\n notify={notify}\n openDocument={host?.openDocument ?? ownOpenDocument}\n onDocumentsChanged={host?.onDocumentsChanged ?? ownDocumentsChanged}\n uploadDocument={host?.uploadDocument ?? ownUpload}\n emailDocument={emailDocument}\n certificateUrl={host?.certificateUrl}\n >\n {children}\n </DocumentToolsProvider>\n )\n}\n","/**\n * What a host adds to the connected document viewer. The viewer reads documents, versions, PDFs,\n * markup and signatures on the signed-in session by itself; these are the host's own things it\n * cannot know: documents the host makes on the client (an artifact streaming in from a chat, an\n * unsaved draft), the host's dialogs and workflows a document action opens, and how the host lays\n * the viewer out. It is the host configuration's `viewer`. Every field is optional: without one the\n * viewer offers less (no Translate button, no draft controls), never something that does nothing.\n * What changes while the viewer is open is read through hooks (`use…`).\n */\n\nimport type { ReactNode } from 'react'\nimport type { components } from '@arbidocs/client'\nimport { useHost } from '../../provider/host'\n\n/** A document's record, as the viewer reads it. */\nexport type ViewerDocumentRecord = components['schemas']['DocResponse']\n\n/** An artifact being generated in a chat, shown in the viewer as it streams. */\nexport interface ViewerStreamingDocument {\n title?: string | null\n /** The content so far (Markdown, or the html/react source of a live artifact). */\n content: string\n /** How it is carried: a document draft, a live `html` / `react` artifact, an `image`. */\n mode?: string | null\n isComplete: boolean\n}\n\n/** A document the user started on the client, with no backend record until it is saved. */\nexport interface ViewerDraftDocument {\n kind: 'text' | 'audio' | 'photo' | 'video'\n title?: string | null\n /** A text draft's starting content. */\n content?: string | null\n}\n\nexport interface DocumentViewerSupport {\n /** The artifact streaming in as this document, if one is (a hook). */\n useStreamingDocument?: (documentId: string) => ViewerStreamingDocument | undefined\n /** The unsaved draft with this client id, if there is one (a hook). */\n useDraftDocument?: (draftId: string) => ViewerDraftDocument | undefined\n /** A draft's kind (text, photo, audio, video), in place of the tabs. */\n renderDraftKind?: (draftId: string) => ReactNode\n /** A draft's name (editable), in place of the title. */\n renderDraftTitle?: (draftId: string) => ReactNode\n /** The recorder of a photo, audio or video draft: the whole body of the viewer. */\n renderCaptureDraft?: (draftId: string) => ReactNode\n /** A text draft was saved as `documentId`; the viewer shows it next. */\n onDraftSaved?: (draftId: string, documentId: string) => void\n /** The copy of a document kept on this device, for when the network is down. */\n loadOfflineCopy?: (document: ViewerDocumentRecord) => Promise<Blob | undefined>\n /** Documents related to the one open (near duplicates), beside its name. */\n renderRelated?: (document: ViewerDocumentRecord) => ReactNode\n /** A document as a pill (the comparison's other side). Default: its name. */\n renderDocumentPill?: (documentId: string) => ReactNode\n /** Open the host's share dialog for the document. Default: share it with the workspace. */\n share?: (document: { id: string; name: string | undefined; isPrivate: boolean }) => void\n /** Ask the assistant about a version (`doc-…@v2`) open read-only. Absent: not offered. */\n askAboutVersion?: (versionRef: string) => void\n /** Translate the document (or the version) on screen. Absent: not offered. */\n translate?: (documentRef: string) => void\n /** Start an image generation from the image on screen. Absent: not offered. */\n useImageAsReference?: (documentId: string) => void\n /**\n * A citation being edited elsewhere (a fact's sources, a field's) picks its passages in the text\n * view: clicks and selections there are handed to it (a hook). Absent: passages are not pickable.\n */\n usePassageCitation?: () => PassageCitation | undefined\n /** Open the document's passages in the host's navigator (a passage's menu). Absent: not offered. */\n openInNavigator?: (documentId: string) => void\n /** Start a new label or field in the host's editor (the passage tagging panel). Absent: not offered. */\n createTag?: () => void\n /** How dates read (versions, signatures). Default: `fmtDate`. */\n formatDate?: (iso: string) => string\n /** Whether the viewer is shown in another window, where PDF pages render without the page's web\n * fonts (a hook). */\n useIsDetached?: () => boolean\n}\n\n/** A passage picked for a citation: its chunk and, when known, its page. */\nexport interface PickedPassage {\n chunk_id: string\n page?: number\n}\n\n/** The citation a host is editing, as the text view sees it. */\nexport interface PassageCitation {\n /** The citation picking passages now, and the document it picks in; null when none is. */\n active: { documentId: string; key: string | null } | null\n /** Passages to light (a fact's cited passages while its sources are open). */\n highlighted: readonly string[]\n /** Passages added to the citation. */\n pick: (passages: PickedPassage[]) => void\n /** Passages taken off it. */\n unpick: (chunkIds: string[]) => void\n}\n\nconst NO_SUPPORT: DocumentViewerSupport = {}\n\nexport function useDocumentViewerSupport(): DocumentViewerSupport {\n return useHost().viewer ?? NO_SUPPORT\n}\n\nconst NONE = () => undefined\nconst ATTACHED = () => false\n\n/** The artifact streaming in as this document (none without the host's). */\nexport function useViewerStreamingDocument(\n documentId: string\n): ViewerStreamingDocument | undefined {\n const useStreaming = useDocumentViewerSupport().useStreamingDocument ?? NONE\n return useStreaming(documentId)\n}\n\n/** The unsaved draft with this id (none without the host's). */\nexport function useViewerDraftDocument(draftId: string): ViewerDraftDocument | undefined {\n const useDraft = useDocumentViewerSupport().useDraftDocument ?? NONE\n return useDraft(draftId)\n}\n\n/** The citation picking passages (none without the host's). */\nexport function useViewerPassageCitation(): PassageCitation | undefined {\n const useCitation = useDocumentViewerSupport().usePassageCitation ?? NONE\n return useCitation()\n}\n\n/** Whether the viewer is in another window (never without the host's). */\nexport function useViewerIsDetached(): boolean {\n const useDetached = useDocumentViewerSupport().useIsDetached ?? ATTACHED\n return useDetached()\n}\n"]}
1
+ {"version":3,"sources":["../src/chat/mermaid-normalize.ts","../src/connection/conversation/MermaidDiagram.tsx","../src/connection/conversation/DocumentWorkspaceContext.tsx","../src/connection/conversation/ConnectedMarkdown.tsx","../src/connection/viewer/ConnectedDocumentToolsProvider.tsx","../src/connection/viewer/support.ts"],"names":["useState","useId","useEffect","jsxs","jsx","createContext","useContext","useBlocksEnvironment","React","useArbiSession","MentionChip","QuietLink","useArbiHost","Fragment","useDocument","EntityPill","FileText","DocumentEntity","Mail","mentionFromHref","MarkdownLink","workspaceDocIdFromHref","MarkdownStreamingContext","MarkdownCode","rehypeDocEntityPills","useMemo","KitMarkdownRenderer","useOptionalDocumentTools","useArbi","useQueryClient","useHost","useConnectedWorkspace","useCallback","refreshDocuments","arbiQueryKeys","documentBytesKey","clientUpload","DocumentToolsProvider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsBO,SAAS,sBAAsB,MAAA,EAAwB;AAE5D,EAAA,IAAI,IAAA,CAAK,IAAA,CAAK,MAAM,CAAA,EAAG,OAAO,MAAA;AAE9B,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,KAAA,CAAM,gCAAgC,CAAA;AACjE,EAAA,IAAI,CAAC,aAAa,OAAO,MAAA;AAEzB,EAAA,MAAM,MAAA,GAAS,WAAA,CAAY,CAAC,CAAA,CAAE,OAAA,EAAQ;AACtC,EAAA,IAAI,OAAO,MAAA,CAAO,KAAA,CAAM,WAAA,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QAAA;AAChE,EAAA,OAAO,WAAA,EAAY;AACrB","file":"chunk-W6DDSZUD.cjs","sourcesContent":["/**\n * Defensive normalizer for single-line `graph` / `flowchart` Mermaid source.\n *\n * Some LLMs emit the entire diagram on one line. Mermaid's parser splits\n * statements on newlines, so a single-line graph fails outright. This helper\n * inserts newlines on safe statement boundaries so the diagram has a chance\n * of parsing. Only attempts normalization when:\n * 1. The source has no embedded newlines (i.e. is genuinely single-line), and\n * 2. The first directive is `graph` or `flowchart`.\n *\n * Other diagram types (sequenceDiagram, classDiagram, gantt, …) have very\n * different syntaxes — applying these heuristics to them would corrupt valid\n * input, so they're left untouched.\n *\n * Boundaries we split on:\n * - After the diagram-type header (`graph TD`, `flowchart LR`, …).\n * - Before each `style` / `classDef` / `class` / `linkStyle` / `click`\n * / `subgraph` keyword.\n * - Before/after `end` (closes a subgraph block).\n * - After a `]` (label close) that's followed by another node identifier\n * starting a new edge or node declaration.\n */\nexport function normalizeMermaidGraph(source: string): string {\n // Already multi-line — assume it's well-formed; don't touch it.\n if (/\\n/.test(source)) return source\n\n const headerMatch = source.match(/^\\s*(graph|flowchart)\\s+\\w+\\s+/)\n if (!headerMatch) return source\n\n const header = headerMatch[0].trimEnd()\n let body = source.slice(headerMatch[0].length)\n\n // Insert newline before keywords that always start a new statement.\n body = body.replace(/\\s+(style|classDef|class|linkStyle|click|subgraph)\\s/g, '\\n$1 ')\n\n // `end` closes a subgraph: put it on its own line, with a break after it\n // too so any trailing statements don't stay attached.\n body = body.replace(/\\s+end\\b\\s*/g, '\\nend\\n')\n\n // After a label close (`]`), if the next token looks like a Mermaid node id\n // followed by another `[` or `-->`, that's a new statement starting.\n body = body.replace(/\\]\\s+(?=[A-Za-z_][\\w-]*\\s*(?:\\[|-->))/g, ']\\n')\n\n // Collapse any accidental runs of blank lines we may have produced.\n body = body.replace(/\\n{2,}/g, '\\n')\n\n return `${header}\\n${body.trimStart()}`\n}\n","/**\n * MermaidDiagram Component\n *\n * Renders a Mermaid diagram from source code.\n * Used inside MarkdownRenderer to handle ```mermaid code blocks.\n * Lazy-loads the mermaid library to avoid bloating the initial bundle.\n */\n\nimport { useState, useEffect, useId } from 'react'\nimport { normalizeMermaidGraph } from '../../chat/mermaid-normalize'\n\ninterface MermaidDiagramProps {\n /** Mermaid diagram source code */\n chart: string\n}\n\n// Lazy-load and initialize mermaid once\nlet mermaidInstance: typeof import('mermaid').default | null = null\nlet mermaidLoadPromise: Promise<typeof import('mermaid').default> | null = null\n\nasync function getMermaid() {\n if (mermaidInstance) return mermaidInstance\n if (!mermaidLoadPromise) {\n mermaidLoadPromise = import('mermaid').then((mod) => {\n const m = mod.default\n m.initialize({\n startOnLoad: false,\n theme: 'default',\n securityLevel: 'strict',\n flowchart: { useMaxWidth: true, curve: 'basis' },\n })\n mermaidInstance = m\n return m\n })\n }\n return mermaidLoadPromise\n}\n\nexport function MermaidDiagram({ chart }: MermaidDiagramProps) {\n const [svg, setSvg] = useState<string | null>(null)\n const [error, setError] = useState<string | null>(null)\n const uniqueId = useId().replace(/:/g, '-')\n\n useEffect(() => {\n let cancelled = false\n\n async function render() {\n const mermaid = await getMermaid()\n const diagramId = `mermaid${uniqueId}`\n\n // Validate with parse() before render(). In Mermaid v11 a render() with\n // bad source can return a \"Syntax error in text\" bomb SVG instead of\n // throwing — and it appends DOM side-effects of its own — so a try/catch\n // around render() doesn't reliably catch failures and the bomb leaks\n // into the page (especially under React StrictMode where effects run\n // twice). parse() throws cleanly with no DOM side-effects.\n //\n // Defensive rescue: some LLMs emit single-line `graph`/`flowchart`\n // source. If the original parse fails, try a normalized variant. The\n // normalizer is a no-op on already-multi-line source and on non-graph\n // diagram types, so this only helps the bad-source case and never\n // corrupts valid input.\n let validSource: string | null = null\n let firstErr: unknown\n try {\n await mermaid.parse(chart)\n validSource = chart\n } catch (err) {\n firstErr = err\n const normalized = normalizeMermaidGraph(chart)\n if (normalized !== chart) {\n try {\n await mermaid.parse(normalized)\n validSource = normalized\n } catch (retryErr) {\n console.warn('Mermaid normalized parse also failed', retryErr)\n }\n }\n }\n\n if (cancelled) return\n\n if (!validSource) {\n console.warn('Mermaid parse failed, showing source', firstErr)\n setError('Failed to render diagram')\n setSvg(null)\n return\n }\n\n try {\n const { svg: renderedSvg } = await mermaid.render(diagramId, validSource)\n if (!cancelled) {\n setSvg(renderedSvg)\n setError(null)\n }\n } catch (renderErr) {\n if (!cancelled) {\n console.warn('Mermaid render failed despite parse success', renderErr)\n setError('Failed to render diagram')\n setSvg(null)\n }\n }\n }\n\n render()\n return () => {\n cancelled = true\n }\n }, [chart, uniqueId])\n\n if (error) {\n // Fall back to showing the raw source in a code block\n return (\n <div className=\"code-block\" data-testid=\"mermaid-error\">\n <div className=\"text-sm text-muted-foreground mb-1\">{error}</div>\n <code className=\"language-mermaid\">{chart}</code>\n </div>\n )\n }\n\n if (!svg) {\n return (\n <div\n className=\"flex items-center justify-center py-8 text-muted-foreground text-sm\"\n data-testid=\"mermaid-loading\"\n >\n Rendering diagram...\n </div>\n )\n }\n\n return (\n <div\n className=\"mermaid-diagram my-4 overflow-x-auto rounded-md border border-border bg-background p-4\"\n data-testid=\"mermaid-diagram\"\n dangerouslySetInnerHTML={{ __html: svg }}\n />\n )\n}\n","/**\n * The workspace a conversation's document references belong to, when it is not the open one: an\n * agent's direct-message thread runs in the agent's workspace, so the documents it names are there.\n * A reference then opens that workspace first (`openDocument(id, { workspaceId })`).\n */\n\nimport { createContext, useContext, type ReactNode } from 'react'\nimport { useBlocksEnvironment } from '../../provider/environment'\n\n/** The workspace of the documents referenced inside it (null: the open workspace). */\nexport const DocumentWorkspaceContext = createContext<string | null>(null)\nexport const useDocumentWorkspace = () => useContext(DocumentWorkspaceContext)\n\n/** A reference to a document of another workspace: opening it opens that workspace first. */\nexport function WorkspaceDocumentReference({\n workspaceId,\n docId,\n children,\n className = 'inline-flex rounded-full border px-2 py-0.5 text-xs hover:bg-muted',\n}: {\n workspaceId: string\n docId: string\n children?: ReactNode\n className?: string\n}) {\n const { openDocument } = useBlocksEnvironment()\n return (\n <button\n type=\"button\"\n className={className}\n onClick={() => openDocument(docId, { workspaceId })}\n >\n {children ?? docId}\n </button>\n )\n}\n","/**\n * The conversation's markdown: the kit's `MarkdownRenderer` (`@arbidocs/react`: sanitised HTML,\n * slugs, lazy KaTeX, streaming blocks, tables, code) with what a conversation adds: @mention chips,\n * workspace documents opening in the viewer, quiet external links, document and email pills (the\n * host's chips, `ArbiChatHost.renderDocumentChip` / `renderMailChip`) and Mermaid diagrams.\n */\nimport { useArbiHost, useArbiSession, useDocument } from '@arbidocs/react'\nimport { mentionFromHref, type MentionKind } from '@arbidocs/react/shell'\nimport {\n EntityPill,\n MarkdownCode,\n MarkdownLink,\n MarkdownRenderer as KitMarkdownRenderer,\n MarkdownStreamingContext,\n type MarkdownRendererProps as KitMarkdownRendererProps,\n DocumentEntity,\n} from '@arbidocs/react/ui'\nimport React, { useContext, useMemo } from 'react'\nimport { FileText, Mail } from 'lucide-react'\n\n/** The markdown element overrides, as the kit's renderer takes them. */\ntype Components = NonNullable<KitMarkdownRendererProps['components']>\nimport { MentionChip } from '../../chat/MentionMenu'\nimport { QuietLink } from '../../citations/QuietMarks'\nimport { rehypeDocEntityPills } from '../../chat/rehype-doc-entity-pills'\nimport { workspaceDocIdFromHref } from '../../chat/doc-links'\nimport { useBlocksEnvironment } from '../../provider/environment'\nimport { MermaidDiagram } from './MermaidDiagram'\nimport { useDocumentWorkspace, WorkspaceDocumentReference } from './DocumentWorkspaceContext'\n\n/** Plain text of a link's children (the `@Label` of a mention link). */\nfunction childrenText(children: React.ReactNode): string {\n return React.Children.toArray(children)\n .map((child) => (typeof child === 'string' || typeof child === 'number' ? String(child) : ''))\n .join('')\n}\n\n/** A mention chip; a mention of the reader stands out. */\nfunction MentionLink({ kind, id, text }: { kind: MentionKind; id: string; text: string }) {\n const currentUserId = useArbiSession().user?.external_id\n return (\n <MentionChip\n kind={kind}\n id={id}\n label={text.replace(/^@/, '')}\n isSelf={kind === 'user' && id === currentUserId}\n />\n )\n}\n\n/**\n * A link to elsewhere, as quiet text. Its menu (Open link / Copy link) is the deliberate step\n * the old confirmation dialog used to be; nothing opens until the menu's primary row is chosen.\n */\nexport function ExternalLink({ href, children }: React.ComponentPropsWithoutRef<'a'>) {\n return (\n <QuietLink href={href} kind=\"external\">\n {children}\n </QuietLink>\n )\n}\n\n/**\n * A workspace document referenced by a link's href rather than by its text.\n *\n * `rehypeDocEntityPills` turns a bare `doc-…` id into a pill, but it only walks\n * TEXT nodes — so `[NVDA DCF Valuation Report](…doc-abc12345…)`, which is how an\n * answer links an artifact it just saved, keeps the id in the href where the\n * plugin never looks. The link then fell through to `ExternalLink`, and opening\n * your own workspace document asked you to confirm an \"external link\" and\n * launched a new tab. It opens in the document viewer, like the pill and the\n * artifact card already do.\n */\nexport function InternalDocLink({\n docId,\n href,\n children,\n}: React.ComponentPropsWithoutRef<'a'> & { docId: string }) {\n const { openDocument } = useBlocksEnvironment()\n const workspaceId = useDocumentWorkspace()\n if (workspaceId) {\n return (\n <WorkspaceDocumentReference workspaceId={workspaceId} docId={docId}>\n {children}\n </WorkspaceDocumentReference>\n )\n }\n\n return (\n <QuietLink href={href} kind=\"document\" onOpen={() => openDocument(docId)}>\n {children}\n </QuietLink>\n )\n}\n\n/** A document of the workspace, as a pill: the host's chip, else the document entity. */\nexport function DocumentChip({ docId }: { docId: string }) {\n const render = useArbiHost().chat?.renderDocumentChip\n const workspaceId = useDocumentWorkspace()\n if (workspaceId) return <WorkspaceDocumentReference workspaceId={workspaceId} docId={docId} />\n return render ? <>{render(docId)}</> : <DefaultDocumentChip docId={docId} />\n}\n\nfunction DefaultDocumentChip({ docId }: { docId: string }) {\n const { data: doc } = useDocument(docId)\n const { openDocument } = useBlocksEnvironment()\n if (!doc)\n return (\n <EntityPill\n icon={<FileText className=\"w-3.5 h-3.5 flex-shrink-0\" />}\n label={docId}\n size=\"sm\"\n onClick={() => openDocument(docId)}\n data-testid=\"doc-entity-pill\"\n />\n )\n return (\n <DocumentEntity doc={doc} onClick={() => openDocument(docId)} data-testid=\"doc-entity-pill\" />\n )\n}\n\n/** An email of the person's mailbox, as a pill: the host's chip, else a plain \"Email\". */\nexport function MailChip({ mailId }: { mailId: string }) {\n const render = useArbiHost().chat?.renderMailChip\n if (render) return <>{render(mailId)}</>\n return (\n <EntityPill\n icon={<Mail className=\"w-3.5 h-3.5 flex-shrink-0\" />}\n label=\"Email\"\n size=\"sm\"\n data-testid=\"mail-entity-pill\"\n />\n )\n}\n\n/**\n * The conversation's overrides, layered on the kit's defaults. Module scope, so the reference is stable\n * and memoised markdown blocks do not re-parse.\n */\nconst conversationMarkdownComponents: Partial<Components> = {\n a: function ConversationMarkdownLink({\n href,\n children,\n ...props\n }: React.ComponentPropsWithoutRef<'a'>) {\n const deploymentDomain = useBlocksEnvironment().runtimeConfig.deploymentDomain\n // @mentions: `linkMentions` turned them into `#mention-<id>` links; draw them as chips.\n const mention = mentionFromHref(href)\n if (mention) {\n return <MentionLink kind={mention.kind} id={mention.id} text={childrenText(children)} />\n }\n // Bookmarks: in-page anchors are near-invisible text; the menu jumps or copies the place.\n if (href?.startsWith('#') && !href.startsWith('#cite-')) {\n return (\n <QuietLink href={href} kind=\"anchor\">\n {children}\n </QuietLink>\n )\n }\n // Citations, `cite:` references and bare links: the kit's link.\n if (!href || href.startsWith('#') || href.startsWith('cite:')) {\n return (\n <MarkdownLink href={href} {...props}>\n {children}\n </MarkdownLink>\n )\n }\n // A workspace document is not an external link, wherever it is hosted: it opens in the viewer.\n const docId = workspaceDocIdFromHref(href, deploymentDomain)\n if (docId) {\n return (\n <InternalDocLink docId={docId} href={href} {...props}>\n {children}\n </InternalDocLink>\n )\n }\n return (\n <ExternalLink href={href} {...props}>\n {children}\n </ExternalLink>\n )\n },\n code: function ConversationMarkdownCode(\n props: React.ComponentPropsWithoutRef<'code'> & { inline?: boolean }\n ) {\n const isStreaming = useContext(MarkdownStreamingContext)\n const { className, children } = props\n const language = /language-(\\w+)/.exec(className || '')?.[1]\n if (!language) {\n // Answers often backtick a bare doc id (`doc-f7b3eeb5`). The text-node pass skips code, so\n // the id would stay monospace text; show it as the document pill. Only a whole id (eight\n // alphanumerics): while streaming, a partial one (\"doc-e\") would be looked up and 404.\n const codeText = typeof children === 'string' ? children.trim() : ''\n if (/^doc-[a-zA-Z0-9]{8}$/.test(codeText)) return <DocumentChip docId={codeText} />\n if (/^eml-[a-zA-Z0-9]{8}$/.test(codeText)) return <MailChip mailId={codeText} />\n }\n // Mermaid lazy-loads its own bundle and re-renders SVG on every change. While streaming the\n // fence is almost always partial, so it stays a code block until generation completes.\n if (language === 'mermaid' && !isStreaming) {\n return <MermaidDiagram chart={String(children).replace(/\\n$/, '')} />\n }\n return <MarkdownCode {...props} />\n },\n span: ({ children, className, ...props }: React.ComponentPropsWithoutRef<'span'>) => {\n const docId = (props as Record<string, unknown>)['data-doc-id'] as string | undefined\n if (docId) return <DocumentChip docId={docId} />\n const mailId = (props as Record<string, unknown>)['data-mail-id'] as string | undefined\n if (mailId) return <MailChip mailId={mailId} />\n return (\n <span className={className} {...props}>\n {children}\n </span>\n )\n },\n}\n\n/** Bare `doc-…` / `eml-…` ids in text become `<span data-doc-id>` / `<span data-mail-id>` pills. */\nconst conversationRehypePlugins = [rehypeDocEntityPills]\n\nexport type ConnectedMarkdownProps = Omit<KitMarkdownRendererProps, 'rehypePlugins'>\n\n/**\n * The kit's renderer with the conversation's overrides; a caller's `components` (e.g. the citation\n * core's) still win over both.\n */\nfunction ConnectedMarkdownComponent({ components, ...props }: ConnectedMarkdownProps) {\n const merged = useMemo(\n () =>\n components\n ? { ...conversationMarkdownComponents, ...components }\n : conversationMarkdownComponents,\n [components]\n )\n return (\n <KitMarkdownRenderer {...props} components={merged} rehypePlugins={conversationRehypePlugins} />\n )\n}\n\nexport const ConnectedMarkdown = React.memo(ConnectedMarkdownComponent)\n","/**\n * The PDF document tools (markup, Freeze, signing, signature requests, productions) on the\n * signed-in session, for any host: the API client, the signed-in user, the host's notices and\n * document opening (`BlocksEnvironment`), and the shared caches a change refreshes. A host with its\n * own binding (its own lists to refresh, an XHR upload with progress, Mail) gives it as the host\n * configuration's `documentTools`, field by field. An enclosing `DocumentToolsProvider` (a dialog\n * with its own client) wins.\n */\n\nimport { useCallback, useMemo, type ReactNode } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { arbiQueryKeys, refreshDocuments, useArbi } from '@arbidocs/react'\nimport {\n DocumentToolsProvider,\n clientUpload,\n documentBytesKey,\n useOptionalDocumentTools,\n type DocumentChange,\n type DocumentToolsClient,\n type DocumentToolsEnvironment,\n type DocumentToolsNotify,\n type DocumentUploadRequest,\n} from '@arbidocs/react/document-tools'\nimport { useBlocksEnvironment } from '../../provider/environment'\nimport { useHost } from '../../provider/host'\nimport { useConnectedWorkspace } from '../ConnectionProvider'\n\n/** What a host binds of the document tools itself; each absent field is the kit's own. */\nexport interface DocumentToolsHost {\n /** The API client the tools call. Default: the host `arbi`'s. */\n client?: DocumentToolsClient\n /** The deployment domain keys are derived for (signing). Default: the host `arbi`'s. */\n deploymentDomain?: string\n /** Open a document or a version the tools made. Default: the environment's `openDocument`. */\n openDocument?: (documentRef: string) => void\n /** Refresh the host's lists after a change. Default: the shared document caches. */\n onDocumentsChanged?: DocumentToolsEnvironment['onDocumentsChanged']\n /** Upload a derived copy. Default: through the API client, into the open workspace. */\n uploadDocument?: DocumentToolsEnvironment['uploadDocument']\n /**\n * Where \"View certificate\" goes for a signature `reference` (e.g. the site's own verify page).\n * Default: the certificate link the API returns (on the deployment domain).\n */\n certificateUrl?: (reference: string) => string\n /** Email a document (a hook): absent, or returning nothing, when mail is not offered. */\n useEmailDocument?: () => ((documentRef: string) => void) | undefined\n}\n\nconst NO_EMAIL = () => undefined\n\nexport function ConnectedDocumentToolsProvider({ children }: { children: ReactNode }) {\n const enclosing = useOptionalDocumentTools()\n return enclosing ? <>{children}</> : <OwnDocumentTools>{children}</OwnDocumentTools>\n}\n\nfunction OwnDocumentTools({ children }: { children: ReactNode }) {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n const host = useHost().documentTools\n const { user, ensureWorkspaceOpen } = useConnectedWorkspace()\n const { notify: environmentNotify, openDocument: openInHost } = useBlocksEnvironment()\n const useEmailDocument = host?.useEmailDocument ?? NO_EMAIL\n const emailDocument = useEmailDocument()\n const client = host?.client ?? (arbi.isLoggedIn ? arbi.getClient().fetch : null)\n const signer = useMemo(\n () => (user ? { name: user.name, email: user.email, externalId: user.externalId } : null),\n [user]\n )\n const notify = useCallback<DocumentToolsNotify>(\n (message, kind, options) =>\n environmentNotify(message, kind, {\n description: options?.description,\n action: options?.action,\n }),\n [environmentNotify]\n )\n const ownDocumentsChanged = useCallback(\n async (ids: string[], change: DocumentChange) => {\n // The list carries each version's markup count and the copies; a signature or a saved\n // version is a new current version, with new versions and a new rendered PDF.\n const refresh: Promise<unknown>[] = [refreshDocuments(queryClient, arbi, ids)]\n if (change === 'signed' || change === 'version')\n for (const id of ids)\n refresh.push(\n queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documentVersions(id) }),\n queryClient.invalidateQueries({ queryKey: documentBytesKey(id) })\n )\n await Promise.all(refresh)\n },\n [queryClient, arbi]\n )\n // The server files an upload in the session's open workspace: re-assert it first.\n const ownUpload = useCallback(\n async (request: DocumentUploadRequest) => {\n if (!client) throw new Error('Sign in to save a copy.')\n await ensureWorkspaceOpen()\n return clientUpload(client)(request)\n },\n [client, ensureWorkspaceOpen]\n )\n const ownOpenDocument = useCallback((ref: string) => openInHost(ref), [openInHost])\n if (!client) return <>{children}</>\n return (\n <DocumentToolsProvider\n client={client}\n deploymentDomain={host?.deploymentDomain}\n user={signer}\n notify={notify}\n openDocument={host?.openDocument ?? ownOpenDocument}\n onDocumentsChanged={host?.onDocumentsChanged ?? ownDocumentsChanged}\n uploadDocument={host?.uploadDocument ?? ownUpload}\n emailDocument={emailDocument}\n certificateUrl={host?.certificateUrl}\n >\n {children}\n </DocumentToolsProvider>\n )\n}\n","/**\n * What a host adds to the connected document viewer. The viewer reads documents, versions, PDFs,\n * markup and signatures on the signed-in session by itself; these are the host's own things it\n * cannot know: documents the host makes on the client (an artifact streaming in from a chat, an\n * unsaved draft), the host's dialogs and workflows a document action opens, and how the host lays\n * the viewer out. It is the host configuration's `viewer`. Every field is optional: without one the\n * viewer offers less (no Translate button, no draft controls), never something that does nothing.\n * What changes while the viewer is open is read through hooks (`use…`).\n */\n\nimport type { ReactNode } from 'react'\nimport type { components } from '@arbidocs/client'\nimport { useHost } from '../../provider/host'\n\n/** A document's record, as the viewer reads it. */\nexport type ViewerDocumentRecord = components['schemas']['DocResponse']\n\n/** An artifact being generated in a chat, shown in the viewer as it streams. */\nexport interface ViewerStreamingDocument {\n title?: string | null\n /** The content so far (Markdown, or the html/react source of a live artifact). */\n content: string\n /** How it is carried: a document draft, a live `html` / `react` artifact, an `image`. */\n mode?: string | null\n isComplete: boolean\n}\n\n/** A document the user started on the client, with no backend record until it is saved. */\nexport interface ViewerDraftDocument {\n kind: 'text' | 'audio' | 'photo' | 'video'\n title?: string | null\n /** A text draft's starting content. */\n content?: string | null\n}\n\nexport interface DocumentViewerSupport {\n /** The artifact streaming in as this document, if one is (a hook). */\n useStreamingDocument?: (documentId: string) => ViewerStreamingDocument | undefined\n /** The unsaved draft with this client id, if there is one (a hook). */\n useDraftDocument?: (draftId: string) => ViewerDraftDocument | undefined\n /** A draft's kind (text, photo, audio, video), in place of the tabs. */\n renderDraftKind?: (draftId: string) => ReactNode\n /** A draft's name (editable), in place of the title. */\n renderDraftTitle?: (draftId: string) => ReactNode\n /** The recorder of a photo, audio or video draft: the whole body of the viewer. */\n renderCaptureDraft?: (draftId: string) => ReactNode\n /** A text draft was saved as `documentId`; the viewer shows it next. */\n onDraftSaved?: (draftId: string, documentId: string) => void\n /** The copy of a document kept on this device, for when the network is down. */\n loadOfflineCopy?: (document: ViewerDocumentRecord) => Promise<Blob | undefined>\n /** Documents related to the one open (near duplicates), beside its name. */\n renderRelated?: (document: ViewerDocumentRecord) => ReactNode\n /** A document as a pill (the comparison's other side). Default: its name. */\n renderDocumentPill?: (documentId: string) => ReactNode\n /** Open the host's share dialog for the document. Default: share it with the workspace. */\n share?: (document: { id: string; name: string | undefined; isPrivate: boolean }) => void\n /** Ask the assistant about a version (`doc-…@v2`) open read-only. Absent: not offered. */\n askAboutVersion?: (versionRef: string) => void\n /** Translate the document (or the version) on screen. Absent: not offered. */\n translate?: (documentRef: string) => void\n /** Start an image generation from the image on screen. Absent: not offered. */\n useImageAsReference?: (documentId: string) => void\n /**\n * A citation being edited elsewhere (a fact's sources, a field's) picks its passages in the text\n * view: clicks and selections there are handed to it (a hook). Absent: passages are not pickable.\n */\n usePassageCitation?: () => PassageCitation | undefined\n /** Open the document's passages in the host's navigator (a passage's menu). Absent: not offered. */\n openInNavigator?: (documentId: string) => void\n /** Start a new label or field in the host's editor (the passage tagging panel). Absent: not offered. */\n createTag?: () => void\n /** How dates read (versions, signatures). Default: `fmtDate`. */\n formatDate?: (iso: string) => string\n /** Whether the viewer is shown in another window, where PDF pages render without the page's web\n * fonts (a hook). */\n useIsDetached?: () => boolean\n}\n\n/** A passage picked for a citation: its chunk and, when known, its page. */\nexport interface PickedPassage {\n chunk_id: string\n page?: number\n}\n\n/** The citation a host is editing, as the text view sees it. */\nexport interface PassageCitation {\n /** The citation picking passages now, and the document it picks in; null when none is. */\n active: { documentId: string; key: string | null } | null\n /** Passages to light (a fact's cited passages while its sources are open). */\n highlighted: readonly string[]\n /** Passages added to the citation. */\n pick: (passages: PickedPassage[]) => void\n /** Passages taken off it. */\n unpick: (chunkIds: string[]) => void\n}\n\nconst NO_SUPPORT: DocumentViewerSupport = {}\n\nexport function useDocumentViewerSupport(): DocumentViewerSupport {\n return useHost().viewer ?? NO_SUPPORT\n}\n\nconst NONE = () => undefined\nconst ATTACHED = () => false\n\n/** The artifact streaming in as this document (none without the host's). */\nexport function useViewerStreamingDocument(\n documentId: string\n): ViewerStreamingDocument | undefined {\n const useStreaming = useDocumentViewerSupport().useStreamingDocument ?? NONE\n return useStreaming(documentId)\n}\n\n/** The unsaved draft with this id (none without the host's). */\nexport function useViewerDraftDocument(draftId: string): ViewerDraftDocument | undefined {\n const useDraft = useDocumentViewerSupport().useDraftDocument ?? NONE\n return useDraft(draftId)\n}\n\n/** The citation picking passages (none without the host's). */\nexport function useViewerPassageCitation(): PassageCitation | undefined {\n const useCitation = useDocumentViewerSupport().usePassageCitation ?? NONE\n return useCitation()\n}\n\n/** Whether the viewer is in another window (never without the host's). */\nexport function useViewerIsDetached(): boolean {\n const useDetached = useDocumentViewerSupport().useIsDetached ?? ATTACHED\n return useDetached()\n}\n"]}