@arbidocs/blocks 0.5.124 → 0.5.125

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 (109) hide show
  1. package/dist/ConnectedCallDock-XJOYVVAH.cjs +6 -6
  2. package/dist/ConnectedCallRoom-CUDYAPQK.cjs +6 -6
  3. package/dist/{ConnectedNativeDocxComparison-QKHCYD6W.cjs → ConnectedNativeDocxComparison-7QQ55JIO.cjs} +12 -12
  4. package/dist/{ConnectedStreamedWordArtifact-AG62232A.cjs.map → ConnectedNativeDocxComparison-7QQ55JIO.cjs.map} +1 -1
  5. package/dist/{ConnectedPresentation-OV2KBOLK.cjs → ConnectedPresentation-L32JPRFI.cjs} +9 -9
  6. package/dist/{ConnectedPresentation-OV2KBOLK.cjs.map → ConnectedPresentation-L32JPRFI.cjs.map} +1 -1
  7. package/dist/{ConnectedProductionSetDialog-LHB4VQWC.cjs → ConnectedProductionSetDialog-4EAY6KAZ.cjs} +3 -3
  8. package/dist/{ConnectedProductionSetDialog-LHB4VQWC.cjs.map → ConnectedProductionSetDialog-4EAY6KAZ.cjs.map} +1 -1
  9. package/dist/{ConnectedSlidesTab-LUAGZ6FD.cjs → ConnectedSlidesTab-P7GGNUTO.cjs} +9 -9
  10. package/dist/{ConnectedSlidesTab-LUAGZ6FD.cjs.map → ConnectedSlidesTab-P7GGNUTO.cjs.map} +1 -1
  11. package/dist/{ConnectedStreamedWordArtifact-AG62232A.cjs → ConnectedStreamedWordArtifact-7NJ3N52V.cjs} +12 -12
  12. package/dist/{ConnectedNativeDocxComparison-QKHCYD6W.cjs.map → ConnectedStreamedWordArtifact-7NJ3N52V.cjs.map} +1 -1
  13. package/dist/{DocumentReviewCard-M53XFLI2.cjs → DocumentReviewCard-BFPOFQXI.cjs} +16 -16
  14. package/dist/{DocumentReviewCard-M53XFLI2.cjs.map → DocumentReviewCard-BFPOFQXI.cjs.map} +1 -1
  15. package/dist/{FilesViewerDialog-JWKNJLWG.cjs → FilesViewerDialog-MHUVEZ7M.cjs} +29 -29
  16. package/dist/{FilesViewerDialog-JWKNJLWG.cjs.map → FilesViewerDialog-MHUVEZ7M.cjs.map} +1 -1
  17. package/dist/{NativeDocxEditor-2LQY2CTV.cjs → NativeDocxEditor-SIRYPMBN.cjs} +6 -6
  18. package/dist/{NativeDocxEditor-2LQY2CTV.cjs.map → NativeDocxEditor-SIRYPMBN.cjs.map} +1 -1
  19. package/dist/{WorkspaceTableView-3XYAV4BV.cjs → WorkspaceTableView-MIFYXV3G.cjs} +8 -8
  20. package/dist/{WorkspaceTableView-3XYAV4BV.cjs.map → WorkspaceTableView-MIFYXV3G.cjs.map} +1 -1
  21. package/dist/agents/index.cjs +215 -215
  22. package/dist/ai-IEIR7SC2.cjs +3 -3
  23. package/dist/auth/index.cjs +1 -1
  24. package/dist/calls/index.cjs +2 -2
  25. package/dist/chat/index.cjs +6 -6
  26. package/dist/{chunk-GNZAH6UI.cjs → chunk-2K6IMIVL.cjs} +3 -3
  27. package/dist/{chunk-GNZAH6UI.cjs.map → chunk-2K6IMIVL.cjs.map} +1 -1
  28. package/dist/{chunk-CQQQIZU4.cjs → chunk-3UP32FM3.cjs} +5 -5
  29. package/dist/{chunk-CQQQIZU4.cjs.map → chunk-3UP32FM3.cjs.map} +1 -1
  30. package/dist/{chunk-QG2U2JGX.cjs → chunk-4LP5MJGQ.cjs} +4 -4
  31. package/dist/{chunk-QG2U2JGX.cjs.map → chunk-4LP5MJGQ.cjs.map} +1 -1
  32. package/dist/{chunk-BX6G2ZCI.cjs → chunk-6JMW3IJ2.cjs} +112 -87
  33. package/dist/chunk-6JMW3IJ2.cjs.map +1 -0
  34. package/dist/{chunk-XGM4VVNV.cjs → chunk-7RJZIPLE.cjs} +33 -33
  35. package/dist/{chunk-XGM4VVNV.cjs.map → chunk-7RJZIPLE.cjs.map} +1 -1
  36. package/dist/{chunk-7NLO7ASW.cjs → chunk-AISYXX4M.cjs} +4 -4
  37. package/dist/{chunk-7NLO7ASW.cjs.map → chunk-AISYXX4M.cjs.map} +1 -1
  38. package/dist/{chunk-5QERK4PK.cjs → chunk-AS6QZETU.cjs} +35 -35
  39. package/dist/{chunk-5QERK4PK.cjs.map → chunk-AS6QZETU.cjs.map} +1 -1
  40. package/dist/{chunk-V6MW7B4B.cjs → chunk-B3R62764.cjs} +6 -6
  41. package/dist/{chunk-V6MW7B4B.cjs.map → chunk-B3R62764.cjs.map} +1 -1
  42. package/dist/{chunk-VKH3BEZE.cjs → chunk-BLIO3B7Z.cjs} +3 -3
  43. package/dist/{chunk-VKH3BEZE.cjs.map → chunk-BLIO3B7Z.cjs.map} +1 -1
  44. package/dist/{chunk-3IH55CDE.cjs → chunk-CQ2RJYE2.cjs} +3 -3
  45. package/dist/{chunk-3IH55CDE.cjs.map → chunk-CQ2RJYE2.cjs.map} +1 -1
  46. package/dist/{chunk-MXBXZXXQ.cjs → chunk-ENOPKX7E.cjs} +3 -3
  47. package/dist/{chunk-MXBXZXXQ.cjs.map → chunk-ENOPKX7E.cjs.map} +1 -1
  48. package/dist/{chunk-2CSLFAGF.cjs → chunk-GAMRVB3I.cjs} +4 -3
  49. package/dist/chunk-GAMRVB3I.cjs.map +1 -0
  50. package/dist/chunk-IRGRMJPP.cjs +18 -0
  51. package/dist/{chunk-SDRYSLOX.cjs.map → chunk-IRGRMJPP.cjs.map} +1 -1
  52. package/dist/{chunk-ADDQKZ5I.cjs → chunk-J3FFSEKO.cjs} +4 -4
  53. package/dist/{chunk-ADDQKZ5I.cjs.map → chunk-J3FFSEKO.cjs.map} +1 -1
  54. package/dist/{chunk-ALK3PUUB.cjs → chunk-L6HTZIBD.cjs} +3 -3
  55. package/dist/{chunk-ALK3PUUB.cjs.map → chunk-L6HTZIBD.cjs.map} +1 -1
  56. package/dist/{chunk-OHHKBURG.cjs → chunk-OGK377NL.cjs} +33 -33
  57. package/dist/{chunk-OHHKBURG.cjs.map → chunk-OGK377NL.cjs.map} +1 -1
  58. package/dist/{chunk-T73BHNQX.cjs → chunk-OHWHYVKG.cjs} +3 -3
  59. package/dist/{chunk-T73BHNQX.cjs.map → chunk-OHWHYVKG.cjs.map} +1 -1
  60. package/dist/{chunk-MLA2BJ2Y.cjs → chunk-PSB64T43.cjs} +28 -28
  61. package/dist/{chunk-MLA2BJ2Y.cjs.map → chunk-PSB64T43.cjs.map} +1 -1
  62. package/dist/{chunk-COD5ENHK.cjs → chunk-PVJ5ODDB.cjs} +4 -4
  63. package/dist/{chunk-COD5ENHK.cjs.map → chunk-PVJ5ODDB.cjs.map} +1 -1
  64. package/dist/{chunk-7557LDAN.cjs → chunk-PWBRE7JA.cjs} +5 -5
  65. package/dist/{chunk-7557LDAN.cjs.map → chunk-PWBRE7JA.cjs.map} +1 -1
  66. package/dist/{chunk-7PN3YENO.cjs → chunk-QIK7E6VF.cjs} +4 -4
  67. package/dist/{chunk-7PN3YENO.cjs.map → chunk-QIK7E6VF.cjs.map} +1 -1
  68. package/dist/{chunk-H236SNEV.cjs → chunk-TSFNLY3K.cjs} +4 -4
  69. package/dist/{chunk-H236SNEV.cjs.map → chunk-TSFNLY3K.cjs.map} +1 -1
  70. package/dist/{chunk-YGBHY67W.cjs → chunk-UA7HOLAZ.cjs} +5 -5
  71. package/dist/{chunk-YGBHY67W.cjs.map → chunk-UA7HOLAZ.cjs.map} +1 -1
  72. package/dist/{chunk-KXIRVKCJ.cjs → chunk-UUENH4BJ.cjs} +3 -3
  73. package/dist/{chunk-KXIRVKCJ.cjs.map → chunk-UUENH4BJ.cjs.map} +1 -1
  74. package/dist/{chunk-E3L5DB5F.cjs → chunk-YOEP3I4V.cjs} +5 -5
  75. package/dist/{chunk-E3L5DB5F.cjs.map → chunk-YOEP3I4V.cjs.map} +1 -1
  76. package/dist/{chunk-EMRY62HS.cjs → chunk-YVO6Z5BS.cjs} +10 -10
  77. package/dist/{chunk-EMRY62HS.cjs.map → chunk-YVO6Z5BS.cjs.map} +1 -1
  78. package/dist/connect/docx.cjs +16 -16
  79. package/dist/connect/index.cjs +979 -979
  80. package/dist/connect/viewer.cjs +22 -22
  81. package/dist/connection/viewer/VersionDropdown.js +1 -1
  82. package/dist/connection/viewer/VersionDropdown.js.map +1 -1
  83. package/dist/connection/viewer/ViewerPdfPane.js +2 -0
  84. package/dist/connection/viewer/ViewerPdfPane.js.map +2 -2
  85. package/dist/connection/viewer/pdf/usePassageTextFallback.d.ts +12 -0
  86. package/dist/connection/viewer/pdf/usePassageTextFallback.js +30 -0
  87. package/dist/connection/viewer/pdf/usePassageTextFallback.js.map +7 -0
  88. package/dist/connection/viewer/pdf/usePdfPassageHighlights.js +2 -11
  89. package/dist/connection/viewer/pdf/usePdfPassageHighlights.js.map +2 -2
  90. package/dist/connection/viewer/useViewerTabs.js +13 -1
  91. package/dist/connection/viewer/useViewerTabs.js.map +2 -2
  92. package/dist/document-tools/index.cjs +20 -20
  93. package/dist/docx/DocxCommandMenu.js +2 -1
  94. package/dist/docx/DocxCommandMenu.js.map +2 -2
  95. package/dist/docx/index.cjs +38 -38
  96. package/dist/embed/index.cjs +19 -19
  97. package/dist/facts/index.cjs +64 -64
  98. package/dist/files/index.cjs +223 -223
  99. package/dist/index.cjs +521 -521
  100. package/dist/settings/index.cjs +146 -146
  101. package/dist/site/index.cjs +6 -6
  102. package/dist/studio/index.cjs +9 -9
  103. package/dist/styles.css +1 -1
  104. package/dist/workflow-canvas/index.cjs +34 -34
  105. package/node_modules/@arbidocs/coedit/package.json +1 -1
  106. package/package.json +5 -5
  107. package/dist/chunk-2CSLFAGF.cjs.map +0 -1
  108. package/dist/chunk-BX6G2ZCI.cjs.map +0 -1
  109. package/dist/chunk-SDRYSLOX.cjs +0 -18
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  'use strict';
3
3
 
4
- var chunk2CSLFAGF_cjs = require('./chunk-2CSLFAGF.cjs');
4
+ var chunkGAMRVB3I_cjs = require('./chunk-GAMRVB3I.cjs');
5
5
  var jsxRuntime = require('react/jsx-runtime');
6
6
 
7
7
  function StreamedWordArtifact({
@@ -15,7 +15,7 @@ function StreamedWordArtifact({
15
15
  }) {
16
16
  if (!busy && documentId) {
17
17
  return /* @__PURE__ */ jsxRuntime.jsx(
18
- chunk2CSLFAGF_cjs.NativeDocxEditor,
18
+ chunkGAMRVB3I_cjs.NativeDocxEditor,
19
19
  {
20
20
  adapter,
21
21
  documentId,
@@ -26,7 +26,7 @@ function StreamedWordArtifact({
26
26
  );
27
27
  }
28
28
  return /* @__PURE__ */ jsxRuntime.jsx(
29
- chunk2CSLFAGF_cjs.NativeDocxEditor,
29
+ chunkGAMRVB3I_cjs.NativeDocxEditor,
30
30
  {
31
31
  adapter,
32
32
  documentId: "stream-preview",
@@ -39,5 +39,5 @@ function StreamedWordArtifact({
39
39
  }
40
40
 
41
41
  exports.StreamedWordArtifact = StreamedWordArtifact;
42
- //# sourceMappingURL=chunk-YGBHY67W.cjs.map
43
- //# sourceMappingURL=chunk-YGBHY67W.cjs.map
42
+ //# sourceMappingURL=chunk-UA7HOLAZ.cjs.map
43
+ //# sourceMappingURL=chunk-UA7HOLAZ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/docx/StreamedWordArtifact.tsx"],"names":["jsx","NativeDocxEditor"],"mappings":";;;;;AAmBO,SAAS,oBAAA,CAAqB;AAAA,EACnC,OAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA,EAA8B;AAC5B,EAAA,IAAI,CAAC,QAAQ,UAAA,EAAY;AACvB,IAAA,uBACEA,cAAA;AAAA,MAACC,kCAAA;AAAA,MAAA;AAAA,QAEC,OAAA;AAAA,QACA,UAAA;AAAA,QACA,KAAA;AAAA,QACA;AAAA,OAAA;AAAA,MAJK;AAAA,KAKP;AAAA,EAEJ;AACA,EAAA,uBACED,cAAA;AAAA,IAACC,kCAAA;AAAA,IAAA;AAAA,MAEC,OAAA;AAAA,MACA,UAAA,EAAW,gBAAA;AAAA,MACX,KAAA;AAAA,MACA,YAAA,EAAa,EAAA;AAAA,MACb,MAAA,EAAQ,EAAE,OAAA,EAAS,IAAA,EAAM,KAAA;AAAM,KAAA;AAAA,IAL3B;AAAA,GAMN;AAEJ","file":"chunk-YGBHY67W.cjs","sourcesContent":["import { NativeDocxEditor, type NativeDocxAdapter } from './NativeDocxEditor'\n\nexport interface StreamedWordArtifactProps {\n adapter: NativeDocxAdapter\n /** Streamed Markdown, shown as a read-only preview while the draft is generated. */\n content: string\n title: string\n busy: boolean\n error?: string | null\n /** The DOCX draft the server stored for this generation (`doc-…`), once known. */\n documentId?: string\n onSaved?: (documentId: string) => void\n}\n\n/**\n * One drafting surface for an AI document draft. The server stores every draft as DOCX, so\n * this component never creates a document: it previews the streamed Markdown until generation\n * ends and the stored DOCX is known, then opens that DOCX in the live collaborative editor.\n */\nexport function StreamedWordArtifact({\n adapter,\n content,\n title,\n busy,\n error,\n documentId,\n onSaved,\n}: StreamedWordArtifactProps) {\n if (!busy && documentId) {\n return (\n <NativeDocxEditor\n key={documentId}\n adapter={adapter}\n documentId={documentId}\n title={title}\n onSaved={onSaved}\n />\n )\n }\n return (\n <NativeDocxEditor\n key=\"stream-preview\"\n adapter={adapter}\n documentId=\"stream-preview\"\n title={title}\n draftContent=\"\"\n stream={{ content, busy, error }}\n />\n )\n}\n"]}
1
+ {"version":3,"sources":["../src/docx/StreamedWordArtifact.tsx"],"names":["jsx","NativeDocxEditor"],"mappings":";;;;;AAmBO,SAAS,oBAAA,CAAqB;AAAA,EACnC,OAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA,EAA8B;AAC5B,EAAA,IAAI,CAAC,QAAQ,UAAA,EAAY;AACvB,IAAA,uBACEA,cAAA;AAAA,MAACC,kCAAA;AAAA,MAAA;AAAA,QAEC,OAAA;AAAA,QACA,UAAA;AAAA,QACA,KAAA;AAAA,QACA;AAAA,OAAA;AAAA,MAJK;AAAA,KAKP;AAAA,EAEJ;AACA,EAAA,uBACED,cAAA;AAAA,IAACC,kCAAA;AAAA,IAAA;AAAA,MAEC,OAAA;AAAA,MACA,UAAA,EAAW,gBAAA;AAAA,MACX,KAAA;AAAA,MACA,YAAA,EAAa,EAAA;AAAA,MACb,MAAA,EAAQ,EAAE,OAAA,EAAS,IAAA,EAAM,KAAA;AAAM,KAAA;AAAA,IAL3B;AAAA,GAMN;AAEJ","file":"chunk-UA7HOLAZ.cjs","sourcesContent":["import { NativeDocxEditor, type NativeDocxAdapter } from './NativeDocxEditor'\n\nexport interface StreamedWordArtifactProps {\n adapter: NativeDocxAdapter\n /** Streamed Markdown, shown as a read-only preview while the draft is generated. */\n content: string\n title: string\n busy: boolean\n error?: string | null\n /** The DOCX draft the server stored for this generation (`doc-…`), once known. */\n documentId?: string\n onSaved?: (documentId: string) => void\n}\n\n/**\n * One drafting surface for an AI document draft. The server stores every draft as DOCX, so\n * this component never creates a document: it previews the streamed Markdown until generation\n * ends and the stored DOCX is known, then opens that DOCX in the live collaborative editor.\n */\nexport function StreamedWordArtifact({\n adapter,\n content,\n title,\n busy,\n error,\n documentId,\n onSaved,\n}: StreamedWordArtifactProps) {\n if (!busy && documentId) {\n return (\n <NativeDocxEditor\n key={documentId}\n adapter={adapter}\n documentId={documentId}\n title={title}\n onSaved={onSaved}\n />\n )\n }\n return (\n <NativeDocxEditor\n key=\"stream-preview\"\n adapter={adapter}\n documentId=\"stream-preview\"\n title={title}\n draftContent=\"\"\n stream={{ content, busy, error }}\n />\n )\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  "use client";
2
2
  'use strict';
3
3
 
4
- var chunkE3Y7RI3J_cjs = require('./chunk-E3Y7RI3J.cjs');
5
4
  var chunkZ2XZ2D4N_cjs = require('./chunk-Z2XZ2D4N.cjs');
6
5
  var chunkMCXS6X37_cjs = require('./chunk-MCXS6X37.cjs');
7
6
  var chunk75BNMCUX_cjs = require('./chunk-75BNMCUX.cjs');
7
+ var chunkE3Y7RI3J_cjs = require('./chunk-E3Y7RI3J.cjs');
8
8
  var chunkTKHCIHE2_cjs = require('./chunk-TKHCIHE2.cjs');
9
9
  var React = require('react');
10
10
  var jsxRuntime = require('react/jsx-runtime');
@@ -284,5 +284,5 @@ exports.InternalDocLink = InternalDocLink;
284
284
  exports.MermaidDiagram = MermaidDiagram;
285
285
  exports.WorkspaceDocumentReference = WorkspaceDocumentReference;
286
286
  exports.useDocumentWorkspace = useDocumentWorkspace;
287
- //# sourceMappingURL=chunk-KXIRVKCJ.cjs.map
288
- //# sourceMappingURL=chunk-KXIRVKCJ.cjs.map
287
+ //# sourceMappingURL=chunk-UUENH4BJ.cjs.map
288
+ //# sourceMappingURL=chunk-UUENH4BJ.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"],"names":["useState","useId","useEffect","jsxs","jsx","createContext","useContext","useBlocksEnvironment","React","useArbiSession","MentionChip","QuietLink","useArbiHost","Fragment","useCompactChat","useDocument","EntityPill","FileText","DocumentEntity","Mail","mentionFromHref","MarkdownLink","workspaceDocIdFromHref","MarkdownStreamingContext","MarkdownCode","rehypeDocEntityPills","useMemo","KitMarkdownRenderer"],"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,K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EAAK,SAAA,EAAuB,GAAG,OAC7B,QAAA,EACH,CAAA;AAAA,EAEJ;AACF,CAAA;AAGA,IAAM,yBAAA,GAA4B,CAACqB,sCAAoB,CAAA;AAWvD,SAAS,0BAAA,CAA2B,EAAE,UAAA,EAAY,GAAG,OAAM,EAA2B;AACpF,EAAA,MAAM,MAAA,GAASC,aAAA;AAAA,IACb,MACE,UAAA,GACI,EAAE,GAAG,8BAAA,EAAgC,GAAG,YAAW,GACnD,8BAAA;AAAA,IACN,CAAC,UAAU;AAAA,GACb;AACA,EAAA,uBACEtB,eAACuB,mBAAA,EAAA,EAAqB,GAAG,OAAO,UAAA,EAAY,MAAA,EAAQ,eAAe,yBAAA,EAA2B,CAAA;AAElG;AAEO,IAAM,iBAAA,GAAoBnB,sBAAA,CAAM,IAAA,CAAK,0BAA0B","file":"chunk-KXIRVKCJ.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 getDocumentTitle,\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 { useCompactChat } from '../../chat/CompactChatContext'\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 compact = useCompactChat()\n const { data: doc } = useDocument(docId)\n const { openDocument } = useBlocksEnvironment()\n if (compact && doc)\n return (\n <button\n type=\"button\"\n className=\"inline text-left text-primary underline decoration-primary/30 underline-offset-2 hover:decoration-primary\"\n onClick={() => openDocument(docId)}\n >\n {getDocumentTitle(doc)}\n </button>\n )\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\". */\nfunction 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<\n KitMarkdownRendererProps,\n 'rehypePlugins' | 'allowHtml' | 'renderCitation'\n>\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"]}
1
+ {"version":3,"sources":["../src/chat/mermaid-normalize.ts","../src/connection/conversation/MermaidDiagram.tsx","../src/connection/conversation/DocumentWorkspaceContext.tsx","../src/connection/conversation/ConnectedMarkdown.tsx"],"names":["useState","useId","useEffect","jsxs","jsx","createContext","useContext","useBlocksEnvironment","React","useArbiSession","MentionChip","QuietLink","useArbiHost","Fragment","useCompactChat","useDocument","EntityPill","FileText","DocumentEntity","Mail","mentionFromHref","MarkdownLink","workspaceDocIdFromHref","MarkdownStreamingContext","MarkdownCode","rehypeDocEntityPills","useMemo","KitMarkdownRenderer"],"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,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AAChE,IAAA,IAAI,MAAA,EAAQ,uBAAOA,cAAAA,CAAC,YAAS,MAAA,EAAgB,CAAA;AAC7C,IAAA,uBACEA,cAAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAuB,GAAG,OAC7B,QAAA,EACH,CAAA;AAAA,EAEJ;AACF,CAAA;AAGA,IAAM,yBAAA,GAA4B,CAACqB,sCAAoB,CAAA;AAWvD,SAAS,0BAAA,CAA2B,EAAE,UAAA,EAAY,GAAG,OAAM,EAA2B;AACpF,EAAA,MAAM,MAAA,GAASC,aAAA;AAAA,IACb,MACE,UAAA,GACI,EAAE,GAAG,8BAAA,EAAgC,GAAG,YAAW,GACnD,8BAAA;AAAA,IACN,CAAC,UAAU;AAAA,GACb;AACA,EAAA,uBACEtB,eAACuB,mBAAA,EAAA,EAAqB,GAAG,OAAO,UAAA,EAAY,MAAA,EAAQ,eAAe,yBAAA,EAA2B,CAAA;AAElG;AAEO,IAAM,iBAAA,GAAoBnB,sBAAA,CAAM,IAAA,CAAK,0BAA0B","file":"chunk-UUENH4BJ.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 getDocumentTitle,\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 { useCompactChat } from '../../chat/CompactChatContext'\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 compact = useCompactChat()\n const { data: doc } = useDocument(docId)\n const { openDocument } = useBlocksEnvironment()\n if (compact && doc)\n return (\n <button\n type=\"button\"\n className=\"inline text-left text-primary underline decoration-primary/30 underline-offset-2 hover:decoration-primary\"\n onClick={() => openDocument(docId)}\n >\n {getDocumentTitle(doc)}\n </button>\n )\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\". */\nfunction 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<\n KitMarkdownRendererProps,\n 'rehypePlugins' | 'allowHtml' | 'renderCitation'\n>\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"]}
@@ -2,7 +2,7 @@
2
2
  'use strict';
3
3
 
4
4
  var chunkE5TPRRAW_cjs = require('./chunk-E5TPRRAW.cjs');
5
- var chunkT73BHNQX_cjs = require('./chunk-T73BHNQX.cjs');
5
+ var chunkOHWHYVKG_cjs = require('./chunk-OHWHYVKG.cjs');
6
6
  var chunkORELHENJ_cjs = require('./chunk-ORELHENJ.cjs');
7
7
  var chunk3YZKDCWY_cjs = require('./chunk-3YZKDCWY.cjs');
8
8
  var react = require('@arbidocs/react');
@@ -350,7 +350,7 @@ function planBadgeView(project) {
350
350
  }
351
351
  function projectGroupBilling(project, { isOwned, stripeEnabled }) {
352
352
  if (!project) return {};
353
- const planBadge = isOwned && stripeEnabled ? /* @__PURE__ */ jsxRuntime.jsx(chunkT73BHNQX_cjs.PlanBadge, { ...planBadgeView(project) }) : void 0;
353
+ const planBadge = isOwned && stripeEnabled ? /* @__PURE__ */ jsxRuntime.jsx(chunkOHWHYVKG_cjs.PlanBadge, { ...planBadgeView(project) }) : void 0;
354
354
  const quotaItems = project.quotas ? getQuotaItems(project.quotas) : [];
355
355
  const readout = project.quotas ? /* @__PURE__ */ jsxRuntime.jsx(
356
356
  chunkE5TPRRAW_cjs.ProjectReadout,
@@ -360,7 +360,7 @@ function projectGroupBilling(project, { isOwned, stripeEnabled }) {
360
360
  testId: `project-usage-${project.external_id}`,
361
361
  // Bare numbers without plans for sale: a glance beside the name, not the Plan & Usage detail.
362
362
  node: /* @__PURE__ */ jsxRuntime.jsx(
363
- chunkT73BHNQX_cjs.QuotaMeter,
363
+ chunkOHWHYVKG_cjs.QuotaMeter,
364
364
  {
365
365
  items: quotaItems,
366
366
  size: "sm",
@@ -451,5 +451,5 @@ exports.totalWithTaxWord = totalWithTaxWord;
451
451
  exports.useBillingSupport = useBillingSupport;
452
452
  exports.useRewardBalance = useRewardBalance;
453
453
  exports.useSelfExtId = useSelfExtId;
454
- //# sourceMappingURL=chunk-E3L5DB5F.cjs.map
455
- //# sourceMappingURL=chunk-E3L5DB5F.cjs.map
454
+ //# sourceMappingURL=chunk-YOEP3I4V.cjs.map
455
+ //# sourceMappingURL=chunk-YOEP3I4V.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/connection/billing/reward-balance.ts","../src/connection/billing/support.ts","../src/connection/billing/addon-pricing.ts","../src/connection/billing/plan-constants.ts","../src/connection/billing/quota-items.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":["useUserSettings","useHost","useArbi","formatGbp","PoundSterling","HardDrive","Users","gbp","jsx","PlanBadge","ProjectReadout","QuotaMeter","ProjectBreakdown","UsageMeter"],"mappings":";;;;;;;;;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,EAAO,SAAA;AAAA,MACP,MAAA,EACE,OAAA,GACI,UAAA,CAAW,GAAA,CAAI,CAAC,EAAE,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,WAAA,EAAa,GAAA,EAAI,qBACnDJ,cAAA;AAAA,QAACK,4BAAA;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-E3L5DB5F.cjs","sourcesContent":["/**\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({ refetchOnMount: 'always' })\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","/**\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\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","/** 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 credits\" / \"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 credits\", \"1 × £10 + 1 × £25 of AI credits\", \"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 credits' : ''}`\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 = 0\n return { min, current, next: pending ?? current }\n}\n\n/** One block's monthly-equivalent price ex VAT: AI credits 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 ex VAT\" or \"£225/year ex VAT\". */\nfunction blockRenewalShort(kind: AddonKind, addons: ProjectAddons, isAnnual: boolean): string {\n return `${gbp(blockPeriodExVatPence(kind, addons))}/${isAnnual ? 'year' : 'month'} ex VAT`\n}\n\n/** The extra line annual plans show beside an AI credits 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 = 'Auto-upgrade limit'\n\n/** Automatic-upgrade spending is separate from explicitly selected allowances. */\nexport const USAGE_CAP_HELP =\n 'Your auto-upgrade limit covers extra monthly spend beyond your selected plan and add-ons. ' +\n '£0 turns automatic upgrades off. You can adjust usage add-ons with + and −. ' +\n 'Additions show the charge before you confirm; reductions apply next billing period, ' +\n 'provided your storage and collaborators fit. Prices are ex VAT.'\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 credits / 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 = blockMonthlyExVatPence(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 credits\" / \"25 GB\". */\nexport function stepLabel(kind: AddonKind, size: number): string {\n return kind === 'ai_usage' ? `${formatGbp(size)} of AI credits` : 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","/** 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\nexport const PRO_COLLABORATORS = 1\nexport const COLLABORATOR_BLOCK_SIZE = 5\n\n/**\n * Add-on block sizes (£25 of AI credits 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 credits (£) 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 dev). */\nexport const UNLIMITED_COLLABORATORS = 999\n\n/**\n * Suggested initial daily per-user AI credits 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 credits 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 credits 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 credits 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 credits',\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 * 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 credits + 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'\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 ex VAT\". */\nexport function plusVat(exVatPence: number, currency = 'gbp'): string {\n return `${formatMoney(exVatPence, currency)} ex 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 credits + 1 × 25 GB\". */\nexport function checkoutItemsLabel(\n aiBlocks: number,\n storageBlocks: number,\n collaboratorBlocks = 0,\n price?: ProductPrice\n): string {\n const ai = addonPrice(price, 'ai_usage')?.ai_gbp\n const storage = addonPrice(price, 'storage')?.storage_gb\n const collaborators = price?.addon_prices?.find((p) => p.kind === 'collaborators')?.collaborators\n return [\n 'Pro',\n aiBlocks > 0 &&\n (ai != null\n ? `${aiBlocks} × ${formatGbp(ai)} of AI credits`\n : `${aiBlocks} AI credits add-ons`),\n storageBlocks > 0 &&\n (storage != null ? `${storageBlocks} × ${storage} GB` : `${storageBlocks} storage add-ons`),\n collaboratorBlocks > 0 &&\n (collaborators != null\n ? `${collaboratorBlocks * collaborators} extra collaborators`\n : `${collaboratorBlocks} collaborator add-ons`),\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 ex VAT each\", annual: \"£225/year ex 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 ex VAT each`\n : `${formatMoney(block.amount_ex_vat, currency)}/month ex 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 (project.subscription === 'suspended') return 'Subscription ended'\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 === 'suspended'\n ? 'Subscription ended'\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 === 'suspended' || 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/reward-balance.ts","../src/connection/billing/support.ts","../src/connection/billing/addon-pricing.ts","../src/connection/billing/plan-constants.ts","../src/connection/billing/quota-items.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":["useUserSettings","useHost","useArbi","form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AAA,mBACJH,cAAA;AAAA,IAACI,kCAAA;AAAA,IAAA;AAAA,MACC,MAAM,OAAA,CAAQ,IAAA;AAAA,MACd,KAAA,EAAO,SAAA;AAAA,MACP,MAAA,EACE,OAAA,GACI,UAAA,CAAW,GAAA,CAAI,CAAC,EAAE,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,WAAA,EAAa,GAAA,EAAI,qBACnDJ,cAAA;AAAA,QAACK,4BAAA;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-YOEP3I4V.cjs","sourcesContent":["/**\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({ refetchOnMount: 'always' })\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","/**\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\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","/** 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 credits\" / \"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 credits\", \"1 × £10 + 1 × £25 of AI credits\", \"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 credits' : ''}`\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 = 0\n return { min, current, next: pending ?? current }\n}\n\n/** One block's monthly-equivalent price ex VAT: AI credits 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 ex VAT\" or \"£225/year ex VAT\". */\nfunction blockRenewalShort(kind: AddonKind, addons: ProjectAddons, isAnnual: boolean): string {\n return `${gbp(blockPeriodExVatPence(kind, addons))}/${isAnnual ? 'year' : 'month'} ex VAT`\n}\n\n/** The extra line annual plans show beside an AI credits 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 = 'Auto-upgrade limit'\n\n/** Automatic-upgrade spending is separate from explicitly selected allowances. */\nexport const USAGE_CAP_HELP =\n 'Your auto-upgrade limit covers extra monthly spend beyond your selected plan and add-ons. ' +\n '£0 turns automatic upgrades off. You can adjust usage add-ons with + and −. ' +\n 'Additions show the charge before you confirm; reductions apply next billing period, ' +\n 'provided your storage and collaborators fit. Prices are ex VAT.'\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 credits / 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 = blockMonthlyExVatPence(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 credits\" / \"25 GB\". */\nexport function stepLabel(kind: AddonKind, size: number): string {\n return kind === 'ai_usage' ? `${formatGbp(size)} of AI credits` : 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","/** 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\nexport const PRO_COLLABORATORS = 1\nexport const COLLABORATOR_BLOCK_SIZE = 5\n\n/**\n * Add-on block sizes (£25 of AI credits 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 credits (£) 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 dev). */\nexport const UNLIMITED_COLLABORATORS = 999\n\n/**\n * Suggested initial daily per-user AI credits 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 credits 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 credits 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 credits 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 credits',\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 * 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 credits + 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'\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 ex VAT\". */\nexport function plusVat(exVatPence: number, currency = 'gbp'): string {\n return `${formatMoney(exVatPence, currency)} ex 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 credits + 1 × 25 GB\". */\nexport function checkoutItemsLabel(\n aiBlocks: number,\n storageBlocks: number,\n collaboratorBlocks = 0,\n price?: ProductPrice\n): string {\n const ai = addonPrice(price, 'ai_usage')?.ai_gbp\n const storage = addonPrice(price, 'storage')?.storage_gb\n const collaborators = price?.addon_prices?.find((p) => p.kind === 'collaborators')?.collaborators\n return [\n 'Pro',\n aiBlocks > 0 &&\n (ai != null\n ? `${aiBlocks} × ${formatGbp(ai)} of AI credits`\n : `${aiBlocks} AI credits add-ons`),\n storageBlocks > 0 &&\n (storage != null ? `${storageBlocks} × ${storage} GB` : `${storageBlocks} storage add-ons`),\n collaboratorBlocks > 0 &&\n (collaborators != null\n ? `${collaboratorBlocks * collaborators} extra collaborators`\n : `${collaboratorBlocks} collaborator add-ons`),\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 ex VAT each\", annual: \"£225/year ex 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 ex VAT each`\n : `${formatMoney(block.amount_ex_vat, currency)}/month ex 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 (project.subscription === 'suspended') return 'Subscription ended'\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 === 'suspended'\n ? 'Subscription ended'\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 === 'suspended' || 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,16 +1,16 @@
1
1
  "use client";
2
2
  'use strict';
3
3
 
4
+ var chunkZKKSTMMI_cjs = require('./chunk-ZKKSTMMI.cjs');
4
5
  var chunkUKOYN2WD_cjs = require('./chunk-UKOYN2WD.cjs');
6
+ var chunkBLIO3B7Z_cjs = require('./chunk-BLIO3B7Z.cjs');
7
+ var chunkBQOL4XNZ_cjs = require('./chunk-BQOL4XNZ.cjs');
5
8
  var chunkNY3YUCOW_cjs = require('./chunk-NY3YUCOW.cjs');
6
9
  var chunkORELHENJ_cjs = require('./chunk-ORELHENJ.cjs');
7
10
  var chunkSK6HQ46Q_cjs = require('./chunk-SK6HQ46Q.cjs');
8
- var chunkVKH3BEZE_cjs = require('./chunk-VKH3BEZE.cjs');
9
- var chunkBQOL4XNZ_cjs = require('./chunk-BQOL4XNZ.cjs');
10
- var chunkCQQQIZU4_cjs = require('./chunk-CQQQIZU4.cjs');
11
- var chunkZVEW3JBT_cjs = require('./chunk-ZVEW3JBT.cjs');
12
- var chunkZKKSTMMI_cjs = require('./chunk-ZKKSTMMI.cjs');
11
+ var chunk3UP32FM3_cjs = require('./chunk-3UP32FM3.cjs');
13
12
  var chunkVZOOGA47_cjs = require('./chunk-VZOOGA47.cjs');
13
+ var chunkZVEW3JBT_cjs = require('./chunk-ZVEW3JBT.cjs');
14
14
  var chunkULWRNGGE_cjs = require('./chunk-ULWRNGGE.cjs');
15
15
  var react = require('react');
16
16
  var reactDom = require('react-dom');
@@ -512,9 +512,9 @@ function workspaceActivityHeadline(item) {
512
512
  return item.status ? `${run} (${item.status.replace(/_/g, " ")})` : run;
513
513
  }
514
514
  default: {
515
- const headline = chunkCQQQIZU4_cjs.taskActivityHeadline(
515
+ const headline = chunk3UP32FM3_cjs.taskActivityHeadline(
516
516
  { kind: item.kind, detail: item.detail },
517
- chunkCQQQIZU4_cjs.DEFAULT_TASK_ACTIVITY_LABELS
517
+ chunk3UP32FM3_cjs.DEFAULT_TASK_ACTIVITY_LABELS
518
518
  );
519
519
  return `${headline} in ${thread}`;
520
520
  }
@@ -2058,7 +2058,7 @@ function ExtractEntitiesDialog({
2058
2058
  var KIT_CHUNK_LOADERS = [
2059
2059
  () => chunkZVEW3JBT_cjs.gridChunk.load(),
2060
2060
  () => chunkZKKSTMMI_cjs.calendarGridChunk.load(),
2061
- () => chunkVKH3BEZE_cjs.docxEditorChunk.load(),
2061
+ () => chunkBLIO3B7Z_cjs.docxEditorChunk.load(),
2062
2062
  () => import('@arbidocs/react/viewers/pdf').then((m) => m.pdfViewerChunk.load())
2063
2063
  ];
2064
2064
  async function preloadKitChunks() {
@@ -2117,5 +2117,5 @@ exports.tagsPageNouns = tagsPageNouns;
2117
2117
  exports.useTipsPlacement = useTipsPlacement;
2118
2118
  exports.workspaceActivityHeadline = workspaceActivityHeadline;
2119
2119
  exports.workspaceActivityTarget = workspaceActivityTarget;
2120
- //# sourceMappingURL=chunk-EMRY62HS.cjs.map
2121
- //# sourceMappingURL=chunk-EMRY62HS.cjs.map
2120
+ //# sourceMappingURL=chunk-YVO6Z5BS.cjs.map
2121
+ //# sourceMappingURL=chunk-YVO6Z5BS.cjs.map