@athenaintel/react 0.42.2 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (685) hide show
  1. package/README.md +225 -3
  2. package/dist/agent-runtime/src/answer-label.cjs +137 -0
  3. package/dist/agent-runtime/src/answer-label.cjs.map +1 -0
  4. package/dist/agent-runtime/src/answer-label.d.ts +104 -0
  5. package/dist/agent-runtime/src/answer-label.js +137 -0
  6. package/dist/agent-runtime/src/answer-label.js.map +1 -0
  7. package/dist/agent-runtime/src/answer-rows.cjs +180 -0
  8. package/dist/agent-runtime/src/answer-rows.cjs.map +1 -0
  9. package/dist/agent-runtime/src/answer-rows.d.ts +86 -0
  10. package/dist/agent-runtime/src/answer-rows.js +180 -0
  11. package/dist/agent-runtime/src/answer-rows.js.map +1 -0
  12. package/dist/agent-runtime/src/client-tool-bridge.cjs +15 -15
  13. package/dist/agent-runtime/src/client-tool-bridge.cjs.map +1 -1
  14. package/dist/agent-runtime/src/conversation-index.cjs +8 -8
  15. package/dist/agent-runtime/src/conversation-index.cjs.map +1 -1
  16. package/dist/agent-runtime/src/conversation-list-groups.d.ts +74 -0
  17. package/dist/agent-runtime/src/decision-checks.cjs +207 -0
  18. package/dist/agent-runtime/src/decision-checks.cjs.map +1 -0
  19. package/dist/agent-runtime/src/decision-checks.d.ts +142 -0
  20. package/dist/agent-runtime/src/decision-checks.js +207 -0
  21. package/dist/agent-runtime/src/decision-checks.js.map +1 -0
  22. package/dist/agent-runtime/src/desktop-handoff.d.ts +12 -0
  23. package/dist/agent-runtime/src/errors.cjs +18 -0
  24. package/dist/agent-runtime/src/errors.cjs.map +1 -1
  25. package/dist/agent-runtime/src/errors.d.ts +7 -0
  26. package/dist/agent-runtime/src/errors.js +18 -0
  27. package/dist/agent-runtime/src/errors.js.map +1 -1
  28. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +12 -0
  29. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  30. package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +6 -6
  31. package/dist/agent-runtime/src/generated/runconfig-contract.js +12 -0
  32. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  33. package/dist/agent-runtime/src/handoff-arrival.cjs +60 -0
  34. package/dist/agent-runtime/src/handoff-arrival.cjs.map +1 -0
  35. package/dist/agent-runtime/src/handoff-arrival.d.ts +46 -0
  36. package/dist/agent-runtime/src/handoff-arrival.js +60 -0
  37. package/dist/agent-runtime/src/handoff-arrival.js.map +1 -0
  38. package/dist/agent-runtime/src/index.d.ts +15 -8
  39. package/dist/agent-runtime/src/interrupts.cjs +43 -18
  40. package/dist/agent-runtime/src/interrupts.cjs.map +1 -1
  41. package/dist/agent-runtime/src/interrupts.d.ts +19 -2
  42. package/dist/agent-runtime/src/interrupts.js +28 -3
  43. package/dist/agent-runtime/src/interrupts.js.map +1 -1
  44. package/dist/agent-runtime/src/lane-history.cjs +8 -8
  45. package/dist/agent-runtime/src/lane-history.cjs.map +1 -1
  46. package/dist/agent-runtime/src/messages.cjs +43 -8
  47. package/dist/agent-runtime/src/messages.cjs.map +1 -1
  48. package/dist/agent-runtime/src/messages.d.ts +25 -3
  49. package/dist/agent-runtime/src/messages.js +43 -8
  50. package/dist/agent-runtime/src/messages.js.map +1 -1
  51. package/dist/agent-runtime/src/offline-status.cjs +36 -0
  52. package/dist/agent-runtime/src/offline-status.cjs.map +1 -0
  53. package/dist/agent-runtime/src/offline-status.d.ts +118 -3
  54. package/dist/agent-runtime/src/offline-status.js +36 -0
  55. package/dist/agent-runtime/src/offline-status.js.map +1 -0
  56. package/dist/agent-runtime/src/queue.cjs +0 -9
  57. package/dist/agent-runtime/src/queue.cjs.map +1 -1
  58. package/dist/agent-runtime/src/queue.js +0 -9
  59. package/dist/agent-runtime/src/queue.js.map +1 -1
  60. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs +9 -9
  61. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
  62. package/dist/agent-runtime/src/runtime-catalog.cjs +42 -0
  63. package/dist/agent-runtime/src/runtime-catalog.cjs.map +1 -0
  64. package/dist/agent-runtime/src/runtime-catalog.d.ts +35 -0
  65. package/dist/agent-runtime/src/runtime-catalog.js +42 -0
  66. package/dist/agent-runtime/src/runtime-catalog.js.map +1 -0
  67. package/dist/agent-runtime/src/runtime-messages.cjs.map +1 -1
  68. package/dist/agent-runtime/src/runtime-messages.d.ts +1 -1
  69. package/dist/agent-runtime/src/runtime-messages.js.map +1 -1
  70. package/dist/agent-runtime/src/runtime.d.ts +40 -0
  71. package/dist/agent-runtime/src/statewire-suspended.cjs +3 -3
  72. package/dist/agent-runtime/src/statewire-suspended.cjs.map +1 -1
  73. package/dist/agent-runtime/src/subagents.cjs +32 -2
  74. package/dist/agent-runtime/src/subagents.cjs.map +1 -1
  75. package/dist/agent-runtime/src/subagents.d.ts +9 -0
  76. package/dist/agent-runtime/src/subagents.js +30 -0
  77. package/dist/agent-runtime/src/subagents.js.map +1 -1
  78. package/dist/agent-runtime/src/thread-driver.cjs +67 -0
  79. package/dist/agent-runtime/src/thread-driver.cjs.map +1 -0
  80. package/dist/agent-runtime/src/thread-driver.d.ts +49 -0
  81. package/dist/agent-runtime/src/thread-driver.js +67 -0
  82. package/dist/agent-runtime/src/thread-driver.js.map +1 -0
  83. package/dist/agent-runtime/src/thread-handoff-flow-machine.d.ts +172 -0
  84. package/dist/agent-runtime/src/thread-handoff-protocol.d.ts +756 -0
  85. package/dist/agent-runtime/src/thread-handoff-qr.d.ts +11 -0
  86. package/dist/agent-runtime/src/thread-handoff.d.ts +3 -364
  87. package/dist/agent-runtime/src/thread-status.cjs +3 -3
  88. package/dist/agent-runtime/src/thread-status.cjs.map +1 -1
  89. package/dist/agent-runtime/src/tool-metadata.cjs +210 -33
  90. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  91. package/dist/agent-runtime/src/tool-metadata.d.ts +12 -0
  92. package/dist/agent-runtime/src/tool-metadata.js +210 -33
  93. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  94. package/dist/agent-runtime/src/tool-names.cjs +2 -0
  95. package/dist/agent-runtime/src/tool-names.cjs.map +1 -1
  96. package/dist/agent-runtime/src/tool-names.d.ts +2 -0
  97. package/dist/agent-runtime/src/tool-names.js +2 -0
  98. package/dist/agent-runtime/src/tool-names.js.map +1 -1
  99. package/dist/agent-runtime/src/types.d.ts +10 -2
  100. package/dist/agent-runtime/src/use-conversation-list.cjs +11 -11
  101. package/dist/agent-runtime/src/use-conversation-list.cjs.map +1 -1
  102. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.cjs +24 -19
  103. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.cjs.map +1 -1
  104. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.d.ts +2 -1
  105. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.js +6 -1
  106. package/dist/agent-runtime/src/use-deep-agent-chat-outbox.js.map +1 -1
  107. package/dist/agent-runtime/src/use-deep-agent-config.cjs +14 -14
  108. package/dist/agent-runtime/src/use-deep-agent-config.cjs.map +1 -1
  109. package/dist/agent-runtime/src/use-deep-agent-edit-submit.cjs +6 -6
  110. package/dist/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
  111. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs +16 -16
  112. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
  113. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +45 -45
  114. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  115. package/dist/agent-runtime/src/use-deep-agent-voice.cjs +572 -134
  116. package/dist/agent-runtime/src/use-deep-agent-voice.cjs.map +1 -1
  117. package/dist/agent-runtime/src/use-deep-agent-voice.d.ts +137 -10
  118. package/dist/agent-runtime/src/use-deep-agent-voice.js +514 -76
  119. package/dist/agent-runtime/src/use-deep-agent-voice.js.map +1 -1
  120. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +26 -26
  121. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
  122. package/dist/agent-runtime/src/use-historical-edit-attachments.cjs +4 -4
  123. package/dist/agent-runtime/src/use-historical-edit-attachments.cjs.map +1 -1
  124. package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +28 -26
  125. package/dist/agent-runtime/src/voice-media.cjs +117 -0
  126. package/dist/agent-runtime/src/voice-media.cjs.map +1 -0
  127. package/dist/agent-runtime/src/voice-media.d.ts +49 -0
  128. package/dist/agent-runtime/src/voice-media.js +117 -0
  129. package/dist/agent-runtime/src/voice-media.js.map +1 -0
  130. package/dist/agent-runtime/src/voice-wire-types.d.ts +32 -0
  131. package/dist/assets/AssetPanel.cjs +11 -11
  132. package/dist/assets/AssetPanel.cjs.map +1 -1
  133. package/dist/assets/AthenaAssetEmbed.cjs +11 -9
  134. package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
  135. package/dist/assets/AthenaAssetEmbed.d.ts +7 -0
  136. package/dist/assets/AthenaAssetEmbed.js +4 -2
  137. package/dist/assets/AthenaAssetEmbed.js.map +1 -1
  138. package/dist/assets/AthenaLayout.cjs +16 -16
  139. package/dist/assets/AthenaLayout.cjs.map +1 -1
  140. package/dist/assets/use-asset-content.cjs +4 -4
  141. package/dist/assets/use-asset-content.cjs.map +1 -1
  142. package/dist/assets/use-asset-embed.cjs +14 -7
  143. package/dist/assets/use-asset-embed.cjs.map +1 -1
  144. package/dist/assets/use-asset-embed.d.ts +11 -1
  145. package/dist/assets/use-asset-embed.js +10 -3
  146. package/dist/assets/use-asset-embed.js.map +1 -1
  147. package/dist/auth/AthenaAuthContext.cjs +3 -3
  148. package/dist/auth/AthenaAuthContext.cjs.map +1 -1
  149. package/dist/auth/AthenaAuthProvider.cjs +8 -8
  150. package/dist/auth/AthenaAuthProvider.cjs.map +1 -1
  151. package/dist/auth/AthenaCredentialSourceContext.cjs +5 -5
  152. package/dist/auth/AthenaCredentialSourceContext.cjs.map +1 -1
  153. package/dist/auth/AthenaSSOProvider.cjs +14 -14
  154. package/dist/auth/AthenaSSOProvider.cjs.map +1 -1
  155. package/dist/auth/credential-source.cjs +26 -13
  156. package/dist/auth/credential-source.cjs.map +1 -1
  157. package/dist/auth/credential-source.d.ts +8 -0
  158. package/dist/auth/credential-source.js +26 -13
  159. package/dist/auth/credential-source.js.map +1 -1
  160. package/dist/catalog/agent-model-options.cjs +25 -17
  161. package/dist/catalog/agent-model-options.cjs.map +1 -1
  162. package/dist/catalog/agent-model-options.d.ts +38 -5
  163. package/dist/catalog/agent-model-options.js +25 -17
  164. package/dist/catalog/agent-model-options.js.map +1 -1
  165. package/dist/catalog/channel-refusal.cjs +36 -0
  166. package/dist/catalog/channel-refusal.cjs.map +1 -0
  167. package/dist/catalog/channel-refusal.d.ts +29 -0
  168. package/dist/catalog/channel-refusal.js +36 -0
  169. package/dist/catalog/channel-refusal.js.map +1 -0
  170. package/dist/catalog/chat-pickers.cjs +60 -24
  171. package/dist/catalog/chat-pickers.cjs.map +1 -1
  172. package/dist/catalog/chat-pickers.d.ts +12 -2
  173. package/dist/catalog/chat-pickers.js +56 -20
  174. package/dist/catalog/chat-pickers.js.map +1 -1
  175. package/dist/catalog/runtime-catalog.cjs +89 -23
  176. package/dist/catalog/runtime-catalog.cjs.map +1 -1
  177. package/dist/catalog/runtime-catalog.d.ts +8 -2
  178. package/dist/catalog/runtime-catalog.js +83 -17
  179. package/dist/catalog/runtime-catalog.js.map +1 -1
  180. package/dist/catalog/use-athena-chat-mode.cjs +12 -12
  181. package/dist/catalog/use-athena-chat-mode.cjs.map +1 -1
  182. package/dist/chat/AthenaChat.cjs +155 -67
  183. package/dist/chat/AthenaChat.cjs.map +1 -1
  184. package/dist/chat/AthenaChat.d.ts +42 -2
  185. package/dist/chat/AthenaChat.js +106 -18
  186. package/dist/chat/AthenaChat.js.map +1 -1
  187. package/dist/chat/AthenaChatErrorBoundary.cjs +3 -3
  188. package/dist/chat/AthenaChatErrorBoundary.cjs.map +1 -1
  189. package/dist/chat/DrivingOnChip.cjs +23 -0
  190. package/dist/chat/DrivingOnChip.cjs.map +1 -0
  191. package/dist/chat/DrivingOnChip.d.ts +17 -0
  192. package/dist/chat/DrivingOnChip.js +23 -0
  193. package/dist/chat/DrivingOnChip.js.map +1 -0
  194. package/dist/chat/StatewireApprovalCard.cjs +125 -31
  195. package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
  196. package/dist/chat/StatewireApprovalCard.d.ts +73 -1
  197. package/dist/chat/StatewireApprovalCard.js +115 -21
  198. package/dist/chat/StatewireApprovalCard.js.map +1 -1
  199. package/dist/chat/StatewireClientToolBridge.cjs +2 -2
  200. package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
  201. package/dist/chat/StatewireQueuedMessages.cjs +25 -63
  202. package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
  203. package/dist/chat/StatewireQueuedMessages.d.ts +11 -13
  204. package/dist/chat/StatewireQueuedMessages.js +16 -54
  205. package/dist/chat/StatewireQueuedMessages.js.map +1 -1
  206. package/dist/chat/WaitingOnYouBanner.cjs +3 -3
  207. package/dist/chat/WaitingOnYouBanner.cjs.map +1 -1
  208. package/dist/chat/athena-chat-welcome.cjs +2 -2
  209. package/dist/chat/athena-chat-welcome.cjs.map +1 -1
  210. package/dist/chat/athena-citation-links.cjs +5 -5
  211. package/dist/chat/athena-citation-links.cjs.map +1 -1
  212. package/dist/chat/athena-composer-controls.cjs +26 -16
  213. package/dist/chat/athena-composer-controls.cjs.map +1 -1
  214. package/dist/chat/athena-composer-controls.d.ts +6 -0
  215. package/dist/chat/athena-composer-controls.js +26 -16
  216. package/dist/chat/athena-composer-controls.js.map +1 -1
  217. package/dist/chat/athena-turn-end-status.cjs +42 -0
  218. package/dist/chat/athena-turn-end-status.cjs.map +1 -0
  219. package/dist/chat/athena-turn-end-status.d.ts +24 -0
  220. package/dist/chat/athena-turn-end-status.js +42 -0
  221. package/dist/chat/athena-turn-end-status.js.map +1 -0
  222. package/dist/chat/browser-decision-check.cjs +131 -0
  223. package/dist/chat/browser-decision-check.cjs.map +1 -0
  224. package/dist/chat/browser-decision-check.d.ts +61 -0
  225. package/dist/chat/browser-decision-check.js +131 -0
  226. package/dist/chat/browser-decision-check.js.map +1 -0
  227. package/dist/chat/chat-outbox-rows.cjs +3 -3
  228. package/dist/chat/chat-outbox-rows.cjs.map +1 -1
  229. package/dist/chat/chat-voice-controls.cjs +93 -28
  230. package/dist/chat/chat-voice-controls.cjs.map +1 -1
  231. package/dist/chat/chat-voice-controls.d.ts +36 -2
  232. package/dist/chat/chat-voice-controls.js +89 -24
  233. package/dist/chat/chat-voice-controls.js.map +1 -1
  234. package/dist/chat/composer-keyboard-hint.cjs +5 -5
  235. package/dist/chat/composer-keyboard-hint.cjs.map +1 -1
  236. package/dist/chat/device-operation.cjs +29 -0
  237. package/dist/chat/device-operation.cjs.map +1 -0
  238. package/dist/chat/device-operation.d.ts +34 -0
  239. package/dist/chat/device-operation.js +29 -0
  240. package/dist/chat/device-operation.js.map +1 -0
  241. package/dist/chat/super-grouping/CollapsibleGroup.cjs +14 -14
  242. package/dist/chat/super-grouping/CollapsibleGroup.cjs.map +1 -1
  243. package/dist/chat/super-grouping/GroupedMessageParts.cjs +4 -4
  244. package/dist/chat/super-grouping/GroupedMessageParts.cjs.map +1 -1
  245. package/dist/chat/super-grouping/SuperGroupingCard.cjs +60 -38
  246. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  247. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +24 -4
  248. package/dist/chat/super-grouping/SuperGroupingCard.js +37 -15
  249. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  250. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs +32 -32
  251. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
  252. package/dist/chat/super-grouping/SuperGroupingTranscript.js +3 -3
  253. package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
  254. package/dist/chat/super-grouping/ToolTimeline.cjs +97 -37
  255. package/dist/chat/super-grouping/ToolTimeline.cjs.map +1 -1
  256. package/dist/chat/super-grouping/ToolTimeline.d.ts +14 -2
  257. package/dist/chat/super-grouping/ToolTimeline.js +94 -34
  258. package/dist/chat/super-grouping/ToolTimeline.js.map +1 -1
  259. package/dist/chat/super-grouping/activity-timeline.cjs +47 -12
  260. package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
  261. package/dist/chat/super-grouping/activity-timeline.d.ts +21 -0
  262. package/dist/chat/super-grouping/activity-timeline.js +47 -12
  263. package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
  264. package/dist/chat/super-grouping/grouping-function.cjs +4 -0
  265. package/dist/chat/super-grouping/grouping-function.cjs.map +1 -1
  266. package/dist/chat/super-grouping/grouping-function.d.ts +7 -0
  267. package/dist/chat/super-grouping/grouping-function.js +5 -1
  268. package/dist/chat/super-grouping/grouping-function.js.map +1 -1
  269. package/dist/chat/super-grouping/index.cjs +6 -0
  270. package/dist/chat/super-grouping/index.cjs.map +1 -1
  271. package/dist/chat/super-grouping/index.d.ts +6 -2
  272. package/dist/chat/super-grouping/index.js +7 -1
  273. package/dist/chat/super-grouping/index.js.map +1 -1
  274. package/dist/chat/super-grouping/timeline-step.cjs +61 -2
  275. package/dist/chat/super-grouping/timeline-step.cjs.map +1 -1
  276. package/dist/chat/super-grouping/timeline-step.d.ts +13 -1
  277. package/dist/chat/super-grouping/timeline-step.js +61 -2
  278. package/dist/chat/super-grouping/timeline-step.js.map +1 -1
  279. package/dist/chat/super-grouping/tool-part-placement.cjs +17 -0
  280. package/dist/chat/super-grouping/tool-part-placement.cjs.map +1 -0
  281. package/dist/chat/super-grouping/tool-part-placement.d.ts +22 -0
  282. package/dist/chat/super-grouping/tool-part-placement.js +17 -0
  283. package/dist/chat/super-grouping/tool-part-placement.js.map +1 -0
  284. package/dist/chat/thread-scroll-to-bottom.cjs +2 -2
  285. package/dist/chat/thread-scroll-to-bottom.cjs.map +1 -1
  286. package/dist/chat/thread-scroll-to-bottom.d.ts +10 -7
  287. package/dist/chat/thread-scroll-to-bottom.js +2 -2
  288. package/dist/chat/thread-scroll-to-bottom.js.map +1 -1
  289. package/dist/chat/tooltip-icon-button.cjs +2 -2
  290. package/dist/chat/tooltip-icon-button.cjs.map +1 -1
  291. package/dist/chat/use-athena-voice-live.cjs +11 -0
  292. package/dist/chat/use-athena-voice-live.cjs.map +1 -0
  293. package/dist/chat/use-athena-voice-live.d.ts +11 -0
  294. package/dist/chat/use-athena-voice-live.js +11 -0
  295. package/dist/chat/use-athena-voice-live.js.map +1 -0
  296. package/dist/chat/use-statewire-approval-request.cjs +56 -24
  297. package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
  298. package/dist/chat/use-statewire-approval-request.d.ts +33 -4
  299. package/dist/chat/use-statewire-approval-request.js +41 -9
  300. package/dist/chat/use-statewire-approval-request.js.map +1 -1
  301. package/dist/chat-ui/auth/sign-in-card.cjs +2 -2
  302. package/dist/chat-ui/auth/sign-in-card.cjs.map +1 -1
  303. package/dist/chat-ui/composer/tiptap-composer.cjs +138 -107
  304. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  305. package/dist/chat-ui/composer/tiptap-composer.d.ts +20 -4
  306. package/dist/chat-ui/composer/tiptap-composer.js +85 -54
  307. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  308. package/dist/chat-ui/header/conversation-history-panel.cjs +49 -23
  309. package/dist/chat-ui/header/conversation-history-panel.cjs.map +1 -1
  310. package/dist/chat-ui/header/conversation-history-panel.d.ts +12 -1
  311. package/dist/chat-ui/header/conversation-history-panel.js +38 -12
  312. package/dist/chat-ui/header/conversation-history-panel.js.map +1 -1
  313. package/dist/chat-ui/index.cjs +18 -0
  314. package/dist/chat-ui/index.cjs.map +1 -1
  315. package/dist/chat-ui/index.d.ts +7 -1
  316. package/dist/chat-ui/index.js +18 -0
  317. package/dist/chat-ui/index.js.map +1 -1
  318. package/dist/chat-ui/mentions/mention-chip.cjs +147 -38
  319. package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
  320. package/dist/chat-ui/mentions/mention-chip.d.ts +17 -1
  321. package/dist/chat-ui/mentions/mention-chip.js +146 -37
  322. package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
  323. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.cjs +10 -9
  324. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.cjs.map +1 -1
  325. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.js +3 -2
  326. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.js.map +1 -1
  327. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-popup.cjs +2 -2
  328. package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-popup.cjs.map +1 -1
  329. package/dist/chat-ui/mentions/suggestions/components/menu-list.cjs +29 -6
  330. package/dist/chat-ui/mentions/suggestions/components/menu-list.cjs.map +1 -1
  331. package/dist/chat-ui/mentions/suggestions/components/menu-list.d.ts +7 -1
  332. package/dist/chat-ui/mentions/suggestions/components/menu-list.js +25 -2
  333. package/dist/chat-ui/mentions/suggestions/components/menu-list.js.map +1 -1
  334. package/dist/chat-ui/mentions/suggestions/components/use-keyboard-navigation.cjs +2 -2
  335. package/dist/chat-ui/mentions/suggestions/components/use-keyboard-navigation.cjs.map +1 -1
  336. package/dist/chat-ui/mentions/suggestions/components/use-menu-navigation.cjs +2 -2
  337. package/dist/chat-ui/mentions/suggestions/components/use-menu-navigation.cjs.map +1 -1
  338. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +3 -3
  339. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
  340. package/dist/chat-ui/mentions/suggestions/data/orchestrator.cjs +56 -2
  341. package/dist/chat-ui/mentions/suggestions/data/orchestrator.cjs.map +1 -1
  342. package/dist/chat-ui/mentions/suggestions/data/orchestrator.d.ts +12 -0
  343. package/dist/chat-ui/mentions/suggestions/data/orchestrator.js +56 -2
  344. package/dist/chat-ui/mentions/suggestions/data/orchestrator.js.map +1 -1
  345. package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs +24 -3
  346. package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs.map +1 -1
  347. package/dist/chat-ui/mentions/suggestions/data/sources/index.d.ts +7 -0
  348. package/dist/chat-ui/mentions/suggestions/data/sources/index.js +24 -3
  349. package/dist/chat-ui/mentions/suggestions/data/sources/index.js.map +1 -1
  350. package/dist/chat-ui/mentions/suggestions/data/use-mention-suggestions.cjs +35 -13
  351. package/dist/chat-ui/mentions/suggestions/data/use-mention-suggestions.cjs.map +1 -1
  352. package/dist/chat-ui/mentions/suggestions/data/use-mention-suggestions.d.ts +15 -1
  353. package/dist/chat-ui/mentions/suggestions/data/use-mention-suggestions.js +28 -6
  354. package/dist/chat-ui/mentions/suggestions/data/use-mention-suggestions.js.map +1 -1
  355. package/dist/chat-ui/mentions/suggestions/data/use-menu-items.cjs +9 -6
  356. package/dist/chat-ui/mentions/suggestions/data/use-menu-items.cjs.map +1 -1
  357. package/dist/chat-ui/mentions/suggestions/data/use-menu-items.d.ts +3 -0
  358. package/dist/chat-ui/mentions/suggestions/data/use-menu-items.js +5 -2
  359. package/dist/chat-ui/mentions/suggestions/data/use-menu-items.js.map +1 -1
  360. package/dist/chat-ui/mentions/use-account-workspace-id.cjs +45 -10
  361. package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
  362. package/dist/chat-ui/mentions/use-account-workspace-id.d.ts +24 -1
  363. package/dist/chat-ui/mentions/use-account-workspace-id.js +46 -11
  364. package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
  365. package/dist/chat-ui/mentions/use-member-avatar.cjs +4 -4
  366. package/dist/chat-ui/mentions/use-member-avatar.cjs.map +1 -1
  367. package/dist/chat-ui/mentions/use-mention-asset.cjs +140 -0
  368. package/dist/chat-ui/mentions/use-mention-asset.cjs.map +1 -0
  369. package/dist/chat-ui/mentions/use-mention-asset.d.ts +16 -0
  370. package/dist/chat-ui/mentions/use-mention-asset.js +140 -0
  371. package/dist/chat-ui/mentions/use-mention-asset.js.map +1 -0
  372. package/dist/chat-ui/messages/answer-label.cjs +42 -0
  373. package/dist/chat-ui/messages/answer-label.cjs.map +1 -0
  374. package/dist/chat-ui/messages/answer-label.d.ts +33 -0
  375. package/dist/chat-ui/messages/answer-label.js +42 -0
  376. package/dist/chat-ui/messages/answer-label.js.map +1 -0
  377. package/dist/chat-ui/messages/arrival-animation.cjs +13 -0
  378. package/dist/chat-ui/messages/arrival-animation.cjs.map +1 -0
  379. package/dist/chat-ui/messages/arrival-animation.d.ts +14 -0
  380. package/dist/chat-ui/messages/arrival-animation.js +13 -0
  381. package/dist/chat-ui/messages/arrival-animation.js.map +1 -0
  382. package/dist/chat-ui/messages/continue-pill.cjs +5 -5
  383. package/dist/chat-ui/messages/continue-pill.cjs.map +1 -1
  384. package/dist/chat-ui/messages/handoff-arrival-divider.cjs +44 -0
  385. package/dist/chat-ui/messages/handoff-arrival-divider.cjs.map +1 -0
  386. package/dist/chat-ui/messages/handoff-arrival-divider.d.ts +17 -0
  387. package/dist/chat-ui/messages/handoff-arrival-divider.js +44 -0
  388. package/dist/chat-ui/messages/handoff-arrival-divider.js.map +1 -0
  389. package/dist/chat-ui/messages/message-actions-config.cjs +3 -3
  390. package/dist/chat-ui/messages/message-actions-config.cjs.map +1 -1
  391. package/dist/chat-ui/messages/message-components.cjs +8 -4
  392. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  393. package/dist/chat-ui/messages/message-components.js +5 -1
  394. package/dist/chat-ui/messages/message-components.js.map +1 -1
  395. package/dist/chat-ui/messages/message-images.cjs +66 -0
  396. package/dist/chat-ui/messages/message-images.cjs.map +1 -0
  397. package/dist/chat-ui/messages/message-images.d.ts +16 -0
  398. package/dist/chat-ui/messages/message-images.js +66 -0
  399. package/dist/chat-ui/messages/message-images.js.map +1 -0
  400. package/dist/chat-ui/messages/user-edit-composer.cjs +2 -2
  401. package/dist/chat-ui/messages/user-edit-composer.cjs.map +1 -1
  402. package/dist/chat-ui/messages/wake-marker.cjs +3 -3
  403. package/dist/chat-ui/messages/wake-marker.cjs.map +1 -1
  404. package/dist/chat-ui/rich-text/chat-link.cjs +7 -6
  405. package/dist/chat-ui/rich-text/chat-link.cjs.map +1 -1
  406. package/dist/chat-ui/rich-text/chat-link.d.ts +2 -3
  407. package/dist/chat-ui/rich-text/chat-link.js +6 -5
  408. package/dist/chat-ui/rich-text/chat-link.js.map +1 -1
  409. package/dist/chat-ui/rich-text/chat-message-body.cjs +8 -8
  410. package/dist/chat-ui/rich-text/chat-message-body.cjs.map +1 -1
  411. package/dist/chat-ui/rich-text/chat-node-views.cjs +7 -6
  412. package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -1
  413. package/dist/chat-ui/rich-text/chat-node-views.js +1 -0
  414. package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -1
  415. package/dist/chat-ui/rich-text/dom-output-spec.cjs +2 -2
  416. package/dist/chat-ui/rich-text/dom-output-spec.cjs.map +1 -1
  417. package/dist/chat-ui/statewire.cjs +3 -0
  418. package/dist/chat-ui/statewire.cjs.map +1 -1
  419. package/dist/chat-ui/statewire.d.ts +2 -1
  420. package/dist/chat-ui/statewire.js +3 -0
  421. package/dist/chat-ui/statewire.js.map +1 -1
  422. package/dist/chat-ui/thread/chat-thread-shell.cjs +43 -14
  423. package/dist/chat-ui/thread/chat-thread-shell.cjs.map +1 -1
  424. package/dist/chat-ui/thread/chat-thread-shell.d.ts +16 -2
  425. package/dist/chat-ui/thread/chat-thread-shell.js +35 -6
  426. package/dist/chat-ui/thread/chat-thread-shell.js.map +1 -1
  427. package/dist/chat-ui/thread/composer-send-or-stop.cjs +30 -20
  428. package/dist/chat-ui/thread/composer-send-or-stop.cjs.map +1 -1
  429. package/dist/chat-ui/thread/composer-send-or-stop.d.ts +8 -0
  430. package/dist/chat-ui/thread/composer-send-or-stop.js +29 -19
  431. package/dist/chat-ui/thread/composer-send-or-stop.js.map +1 -1
  432. package/dist/chat-ui/thread/statewire-history-edge.cjs +20 -21
  433. package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
  434. package/dist/chat-ui/thread/statewire-history-edge.js +3 -4
  435. package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
  436. package/dist/chat-ui/thread/thread-loading-overlay.cjs +5 -5
  437. package/dist/chat-ui/thread/thread-loading-overlay.cjs.map +1 -1
  438. package/dist/collab/client.cjs +40 -3
  439. package/dist/collab/client.cjs.map +1 -1
  440. package/dist/collab/client.d.ts +25 -0
  441. package/dist/collab/client.js +40 -3
  442. package/dist/collab/client.js.map +1 -1
  443. package/dist/collab/document-status.cjs +150 -0
  444. package/dist/collab/document-status.cjs.map +1 -0
  445. package/dist/collab/document-status.d.ts +68 -0
  446. package/dist/collab/document-status.js +150 -0
  447. package/dist/collab/document-status.js.map +1 -0
  448. package/dist/collab/index.cjs +7 -0
  449. package/dist/collab/index.cjs.map +1 -1
  450. package/dist/collab/index.d.ts +6 -1
  451. package/dist/collab/index.js +7 -0
  452. package/dist/collab/index.js.map +1 -1
  453. package/dist/collab/presence-react.cjs +11 -11
  454. package/dist/collab/presence-react.cjs.map +1 -1
  455. package/dist/collab/react.cjs +6 -6
  456. package/dist/collab/react.cjs.map +1 -1
  457. package/dist/composer/AttachmentContext.cjs +24 -11
  458. package/dist/composer/AttachmentContext.cjs.map +1 -1
  459. package/dist/composer/AttachmentContext.js +18 -5
  460. package/dist/composer/AttachmentContext.js.map +1 -1
  461. package/dist/composer/ComposerAttachmentPreview.cjs +78 -23
  462. package/dist/composer/ComposerAttachmentPreview.cjs.map +1 -1
  463. package/dist/composer/ComposerAttachmentPreview.d.ts +5 -3
  464. package/dist/composer/ComposerAttachmentPreview.js +79 -24
  465. package/dist/composer/ComposerAttachmentPreview.js.map +1 -1
  466. package/dist/composer/ComposerDropZone.cjs +7 -7
  467. package/dist/composer/ComposerDropZone.cjs.map +1 -1
  468. package/dist/composer/FileUploadButton.cjs +37 -22
  469. package/dist/composer/FileUploadButton.cjs.map +1 -1
  470. package/dist/composer/FileUploadButton.d.ts +6 -0
  471. package/dist/composer/FileUploadButton.js +34 -19
  472. package/dist/composer/FileUploadButton.js.map +1 -1
  473. package/dist/composer/QuoteContext.cjs +8 -8
  474. package/dist/composer/QuoteContext.cjs.map +1 -1
  475. package/dist/composer/composer-handoff.cjs +4 -4
  476. package/dist/composer/composer-handoff.cjs.map +1 -1
  477. package/dist/composer/useAppendToComposer.cjs +4 -4
  478. package/dist/composer/useAppendToComposer.cjs.map +1 -1
  479. package/dist/composer/useAttachFiles.cjs +23 -6
  480. package/dist/composer/useAttachFiles.cjs.map +1 -1
  481. package/dist/composer/useAttachFiles.d.ts +15 -7
  482. package/dist/composer/useAttachFiles.js +22 -5
  483. package/dist/composer/useAttachFiles.js.map +1 -1
  484. package/dist/composer/useComposerAttachment.cjs +4 -4
  485. package/dist/composer/useComposerAttachment.cjs.map +1 -1
  486. package/dist/composer/useFileUpload.cjs +21 -16
  487. package/dist/composer/useFileUpload.cjs.map +1 -1
  488. package/dist/composer/useFileUpload.d.ts +12 -0
  489. package/dist/composer/useFileUpload.js +12 -7
  490. package/dist/composer/useFileUpload.js.map +1 -1
  491. package/dist/composer/useReadComposerDraft.cjs +2 -2
  492. package/dist/composer/useReadComposerDraft.cjs.map +1 -1
  493. package/dist/composer/useSendMessage.cjs +4 -4
  494. package/dist/composer/useSendMessage.cjs.map +1 -1
  495. package/dist/diagnostics/useAthenaDiagnostics.cjs +4 -4
  496. package/dist/diagnostics/useAthenaDiagnostics.cjs.map +1 -1
  497. package/dist/dictation/audio-level-history.cjs +3 -3
  498. package/dist/dictation/audio-level-history.cjs.map +1 -1
  499. package/dist/dictation/dictation-controls.cjs +24 -20
  500. package/dist/dictation/dictation-controls.cjs.map +1 -1
  501. package/dist/dictation/dictation-controls.d.ts +6 -1
  502. package/dist/dictation/dictation-controls.js +24 -20
  503. package/dist/dictation/dictation-controls.js.map +1 -1
  504. package/dist/dictation/use-athena-dictation-engine.cjs +3 -3
  505. package/dist/dictation/use-athena-dictation-engine.cjs.map +1 -1
  506. package/dist/dictation/use-dictation.cjs +22 -22
  507. package/dist/dictation/use-dictation.cjs.map +1 -1
  508. package/dist/index.cjs +26 -2
  509. package/dist/index.cjs.map +1 -1
  510. package/dist/index.d.ts +15 -3
  511. package/dist/index.js +26 -2
  512. package/dist/index.js.map +1 -1
  513. package/dist/keryx-http/src/receive-only-socket.cjs +40 -0
  514. package/dist/keryx-http/src/receive-only-socket.cjs.map +1 -0
  515. package/dist/keryx-http/src/receive-only-socket.d.ts +27 -0
  516. package/dist/keryx-http/src/receive-only-socket.js +40 -0
  517. package/dist/keryx-http/src/receive-only-socket.js.map +1 -0
  518. package/dist/keryx-http/src/update-attributions.cjs +111 -0
  519. package/dist/keryx-http/src/update-attributions.cjs.map +1 -0
  520. package/dist/keryx-http/src/update-attributions.d.ts +75 -0
  521. package/dist/keryx-http/src/update-attributions.js +111 -0
  522. package/dist/keryx-http/src/update-attributions.js.map +1 -0
  523. package/dist/lib/owner-document.cjs +6 -6
  524. package/dist/lib/owner-document.cjs.map +1 -1
  525. package/dist/lib/use-athena-rest-query.cjs +4 -4
  526. package/dist/lib/use-athena-rest-query.cjs.map +1 -1
  527. package/dist/lib/use-document-active.cjs +4 -4
  528. package/dist/lib/use-document-active.cjs.map +1 -1
  529. package/dist/lib/use-prefers-reduced-motion.cjs +2 -2
  530. package/dist/lib/use-prefers-reduced-motion.cjs.map +1 -1
  531. package/dist/offline/offline-history.cjs +7 -7
  532. package/dist/offline/offline-history.cjs.map +1 -1
  533. package/dist/provider/AthenaContext.cjs +3 -3
  534. package/dist/provider/AthenaContext.cjs.map +1 -1
  535. package/dist/provider/AthenaProvider.cjs +116 -79
  536. package/dist/provider/AthenaProvider.cjs.map +1 -1
  537. package/dist/provider/AthenaProvider.js +40 -3
  538. package/dist/provider/AthenaProvider.js.map +1 -1
  539. package/dist/provider/PostHogProvider.cjs +2 -2
  540. package/dist/provider/PostHogProvider.cjs.map +1 -1
  541. package/dist/provider/agent-selection-context.cjs +2 -2
  542. package/dist/provider/agent-selection-context.cjs.map +1 -1
  543. package/dist/provider/chat-mode-context.cjs +2 -2
  544. package/dist/provider/chat-mode-context.cjs.map +1 -1
  545. package/dist/provider/session-persistence-context.cjs +10 -0
  546. package/dist/provider/session-persistence-context.cjs.map +1 -0
  547. package/dist/provider/session-persistence-context.d.ts +15 -0
  548. package/dist/provider/session-persistence-context.js +10 -0
  549. package/dist/provider/session-persistence-context.js.map +1 -0
  550. package/dist/provider/statewire-history-context.cjs +4 -4
  551. package/dist/provider/statewire-history-context.cjs.map +1 -1
  552. package/dist/provider/statewire-lifecycle-context.cjs +3 -3
  553. package/dist/provider/statewire-lifecycle-context.cjs.map +1 -1
  554. package/dist/provider/statewire-window-context.cjs +3 -3
  555. package/dist/provider/statewire-window-context.cjs.map +1 -1
  556. package/dist/provider/theme-style-context.cjs +3 -3
  557. package/dist/provider/theme-style-context.cjs.map +1 -1
  558. package/dist/react/package.json.cjs +1 -1
  559. package/dist/react/package.json.js +1 -1
  560. package/dist/references/src/tool-option-schemas.d.ts +0 -34
  561. package/dist/runtime/StatewireThreadConfigLaneSync.cjs +10 -10
  562. package/dist/runtime/StatewireThreadConfigLaneSync.cjs.map +1 -1
  563. package/dist/runtime/auth-refusal-restart.cjs +7 -7
  564. package/dist/runtime/auth-refusal-restart.cjs.map +1 -1
  565. package/dist/runtime/auth.cjs +13 -13
  566. package/dist/runtime/auth.cjs.map +1 -1
  567. package/dist/runtime/statewire-lifecycle.cjs +1 -0
  568. package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
  569. package/dist/runtime/statewire-lifecycle.d.ts +3 -1
  570. package/dist/runtime/statewire-lifecycle.js +2 -1
  571. package/dist/runtime/statewire-lifecycle.js.map +1 -1
  572. package/dist/runtime/statewire-server-lane-context.cjs +2 -2
  573. package/dist/runtime/statewire-server-lane-context.cjs.map +1 -1
  574. package/dist/runtime/statewire-session-lane.cjs +4 -4
  575. package/dist/runtime/statewire-session-lane.cjs.map +1 -1
  576. package/dist/runtime/useAthenaStatewireRuntime.cjs +10 -8
  577. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  578. package/dist/runtime/useAthenaStatewireRuntime.d.ts +2 -0
  579. package/dist/runtime/useAthenaStatewireRuntime.js +2 -0
  580. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  581. package/dist/styles.css +1 -1
  582. package/dist/threads/Inbox.cjs +8 -8
  583. package/dist/threads/Inbox.cjs.map +1 -1
  584. package/dist/threads/SessionList.cjs +9 -9
  585. package/dist/threads/SessionList.cjs.map +1 -1
  586. package/dist/threads/SessionsPage.cjs +11 -11
  587. package/dist/threads/SessionsPage.cjs.map +1 -1
  588. package/dist/threads/index-triggered-refresh.cjs +10 -10
  589. package/dist/threads/index-triggered-refresh.cjs.map +1 -1
  590. package/dist/threads/mark-viewed-thread-read.cjs +12 -12
  591. package/dist/threads/mark-viewed-thread-read.cjs.map +1 -1
  592. package/dist/threads/offline-session-list.cjs +3 -3
  593. package/dist/threads/offline-session-list.cjs.map +1 -1
  594. package/dist/threads/session-list-tab-share.cjs +5 -5
  595. package/dist/threads/session-list-tab-share.cjs.map +1 -1
  596. package/dist/threads/statewire-thread-list.cjs +55 -51
  597. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  598. package/dist/threads/statewire-thread-list.js +6 -2
  599. package/dist/threads/statewire-thread-list.js.map +1 -1
  600. package/dist/threads/thread-id-context.cjs +5 -5
  601. package/dist/threads/thread-id-context.cjs.map +1 -1
  602. package/dist/threads/use-athena-session-attention.cjs +2 -2
  603. package/dist/threads/use-athena-session-attention.cjs.map +1 -1
  604. package/dist/threads/use-athena-sessions.cjs +10 -10
  605. package/dist/threads/use-athena-sessions.cjs.map +1 -1
  606. package/dist/threads/use-athena-thread-model.cjs +3 -3
  607. package/dist/threads/use-athena-thread-model.cjs.map +1 -1
  608. package/dist/threads/use-rest-conversation-history.cjs +3 -3
  609. package/dist/threads/use-rest-conversation-history.cjs.map +1 -1
  610. package/dist/threads/use-statewire-conversation-history.cjs +8 -8
  611. package/dist/threads/use-statewire-conversation-history.cjs.map +1 -1
  612. package/dist/threads/use-thread-archive.cjs +9 -9
  613. package/dist/threads/use-thread-archive.cjs.map +1 -1
  614. package/dist/threads/use-thread-favorite.cjs +2 -2
  615. package/dist/threads/use-thread-favorite.cjs.map +1 -1
  616. package/dist/threads/use-thread-field-override.cjs +20 -20
  617. package/dist/threads/use-thread-field-override.cjs.map +1 -1
  618. package/dist/threads/use-thread-read-state.cjs +4 -4
  619. package/dist/threads/use-thread-read-state.cjs.map +1 -1
  620. package/dist/threads/use-thread-rename.cjs +2 -2
  621. package/dist/threads/use-thread-rename.cjs.map +1 -1
  622. package/dist/threads/useAthenaThreadManager.cjs +2 -2
  623. package/dist/threads/useAthenaThreadManager.cjs.map +1 -1
  624. package/dist/tools/NestedPtcMessages.cjs +6 -6
  625. package/dist/tools/NestedPtcMessages.cjs.map +1 -1
  626. package/dist/tools/append-document-tool-ui.cjs +7 -7
  627. package/dist/tools/append-document-tool-ui.cjs.map +1 -1
  628. package/dist/tools/file-tool-uis.cjs +2 -2
  629. package/dist/tools/file-tool-uis.cjs.map +1 -1
  630. package/dist/tools/misc-tool-uis.cjs +2 -2
  631. package/dist/tools/misc-tool-uis.cjs.map +1 -1
  632. package/dist/tools/primitives.cjs +6 -6
  633. package/dist/tools/primitives.cjs.map +1 -1
  634. package/dist/tools/read-asset-tool-ui.cjs +6 -6
  635. package/dist/tools/read-asset-tool-ui.cjs.map +1 -1
  636. package/dist/tools/subagent-task-tool-ui.cjs +21 -21
  637. package/dist/tools/subagent-task-tool-ui.cjs.map +1 -1
  638. package/dist/tools/test-recording-tool-uis.cjs +16 -16
  639. package/dist/tools/test-recording-tool-uis.cjs.map +1 -1
  640. package/dist/tools/todo-plan-store.cjs +4 -4
  641. package/dist/tools/todo-plan-store.cjs.map +1 -1
  642. package/dist/tools/tool-appearance.cjs +3 -3
  643. package/dist/tools/tool-appearance.cjs.map +1 -1
  644. package/dist/tools/tool-fallback.cjs +14 -14
  645. package/dist/tools/tool-fallback.cjs.map +1 -1
  646. package/dist/tools/tool-summary.cjs +0 -2
  647. package/dist/tools/tool-summary.cjs.map +1 -1
  648. package/dist/tools/tool-summary.js +0 -2
  649. package/dist/tools/tool-summary.js.map +1 -1
  650. package/dist/tools/tool-uis.cjs +74 -74
  651. package/dist/tools/tool-uis.cjs.map +1 -1
  652. package/dist/tools/use-elapsed-seconds.cjs +3 -3
  653. package/dist/tools/use-elapsed-seconds.cjs.map +1 -1
  654. package/dist/tools/write-todos-tool-ui.cjs +9 -9
  655. package/dist/tools/write-todos-tool-ui.cjs.map +1 -1
  656. package/dist/ui/image-viewer.cjs +382 -0
  657. package/dist/ui/image-viewer.cjs.map +1 -0
  658. package/dist/ui/image-viewer.d.ts +50 -0
  659. package/dist/ui/image-viewer.js +382 -0
  660. package/dist/ui/image-viewer.js.map +1 -0
  661. package/dist/voice/chat.cjs +6 -0
  662. package/dist/voice/chat.cjs.map +1 -1
  663. package/dist/voice/chat.d.ts +1 -1
  664. package/dist/voice/chat.js +8 -2
  665. package/dist/voice/livekit-join.cjs +52 -101
  666. package/dist/voice/livekit-join.cjs.map +1 -1
  667. package/dist/voice/livekit-join.d.ts +1 -6
  668. package/dist/voice/livekit-join.js +52 -101
  669. package/dist/voice/livekit-join.js.map +1 -1
  670. package/dist/voice/livekit.cjs.map +1 -1
  671. package/dist/voice/livekit.d.ts +11 -1
  672. package/dist/voice/livekit.js.map +1 -1
  673. package/dist/voice/use-athena-voice-session.cjs +34 -34
  674. package/dist/voice/use-athena-voice-session.cjs.map +1 -1
  675. package/dist/workbench/ComputerLiveDesktop.cjs +13 -13
  676. package/dist/workbench/ComputerLiveDesktop.cjs.map +1 -1
  677. package/dist/workbench/SessionWorkbench.cjs +22 -22
  678. package/dist/workbench/SessionWorkbench.cjs.map +1 -1
  679. package/dist/workbench/session-workbench-context.cjs +3 -3
  680. package/dist/workbench/session-workbench-context.cjs.map +1 -1
  681. package/dist/workbench/session-workbench-panes.cjs +8 -8
  682. package/dist/workbench/session-workbench-panes.cjs.map +1 -1
  683. package/dist/workbench/workbench-layout-context.cjs +3 -3
  684. package/dist/workbench/workbench-layout-context.cjs.map +1 -1
  685. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"use-asset-embed.js","sources":["../../src/assets/use-asset-embed.ts"],"sourcesContent":["import { QueryClient, QueryClientContext, useQuery } from '@tanstack/react-query';\nimport { useContext, useRef } from 'react';\nimport { deriveAthenaAppUrl } from '../lib/athena-urls';\nimport { keyPartFingerprint } from '../lib/use-athena-rest-query';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport type { AthenaAssetCitationReference } from './asset-embed-messages';\n\nexport interface UseAssetEmbedOptions {\n readOnly?: boolean;\n expiresInSeconds?: number;\n /** Native Olympus surface rendered by the iframe. Defaults to `full`. */\n displayMode?: 'minimal' | 'full';\n /**\n * Offer Quick Edit (⌘J, an AI rewrite of the selection) in a minimal embed, where the viewer\n * does not sign in: spreadsheets and Word documents, on an editable link (`readOnly: false`)\n * only. Its runs are billed to the asset's workspace under the link's creator, and each link has\n * its own hourly cap. The full mode's editors offer it to the signed-in person already. Defaults\n * to `false`.\n */\n allowQuickEdit?: boolean;\n}\n\nexport const DEFAULT_ASSET_EMBED_READ_ONLY = false;\nexport const DEFAULT_ASSET_EMBED_ALLOW_QUICK_EDIT = false;\nexport const DEFAULT_ASSET_EMBED_DISPLAY_MODE = 'full' as const;\n\nexport interface UseAssetEmbedResult {\n embedUrl: string | null;\n isLoading: boolean;\n error: string | null;\n}\n\nexport function buildAssetEmbedRequestBody({\n assetId,\n readOnly,\n expiresInSeconds,\n displayMode,\n allowQuickEdit = DEFAULT_ASSET_EMBED_ALLOW_QUICK_EDIT,\n}: {\n assetId: string;\n readOnly: boolean;\n expiresInSeconds: number;\n displayMode: 'minimal' | 'full';\n allowQuickEdit?: boolean;\n}) {\n return {\n asset_id: assetId,\n read_only: readOnly,\n expires_in_seconds: expiresInSeconds,\n display_mode: displayMode,\n // Sent only when asked: an agora that predates it is never handed an unknown field.\n ...(allowQuickEdit && { allow_quick_edit: true }),\n };\n}\n\n/**\n * The embed links' query client when the host provides none: one for the page, so every embed of\n * one asset, mode and identity shares one minted link until it expires.\n */\nconst embedQueryClient = new QueryClient();\n\nconst ATHENA_APP_HOSTNAMES = new Set(['app.athenaintel.com', 'staging-app.athenaintel.com']);\nconst ATHENA_PREVIEW_HOSTNAME_SUFFIX = '.previews.athenaintel.com';\nconst ATHENA_WORKSPACE_HOSTNAME_PATTERN = /^.+--(\\d+)\\.(?:app\\.athenaintel\\.com|staging-app\\.athenaintel\\.com)$/;\nconst OLYMPUS_WORKSPACE_PORT = '8082';\n\nconst getUrl = (value?: string | null): URL | null => {\n if (!value) {\n return null;\n }\n\n try {\n return new URL(value);\n } catch {\n return null;\n }\n};\n\nconst getCurrentOrigin = (): string | null => {\n if (typeof window === 'undefined') {\n return null;\n }\n\n return window.location.origin;\n};\n\nconst getOrigin = (value?: string | null): string | null => getUrl(value)?.origin ?? null;\n\nconst getAthenaWorkspacePort = (url: URL): string | null => {\n const match = url.hostname.toLowerCase().match(ATHENA_WORKSPACE_HOSTNAME_PATTERN);\n return match?.[1] ?? null;\n};\n\nconst isEmbedCapableAthenaHost = (url: URL): boolean => {\n const hostname = url.hostname.toLowerCase();\n\n if (ATHENA_APP_HOSTNAMES.has(hostname) || hostname.endsWith(ATHENA_PREVIEW_HOSTNAME_SUFFIX)) {\n return true;\n }\n\n return getAthenaWorkspacePort(url) === OLYMPUS_WORKSPACE_PORT;\n};\n\nconst shouldPreferDerivedEmbedAppUrl = ({\n appUrl,\n derivedAppUrl,\n currentOrigin,\n}: {\n appUrl: string;\n derivedAppUrl: string | null;\n currentOrigin?: string | null;\n}): boolean => {\n if (!derivedAppUrl) {\n return false;\n }\n\n const resolvedAppUrl = getUrl(appUrl);\n if (!resolvedAppUrl) {\n return true;\n }\n\n const workspacePort = getAthenaWorkspacePort(resolvedAppUrl);\n if (workspacePort && workspacePort !== OLYMPUS_WORKSPACE_PORT) {\n return true;\n }\n\n if (isEmbedCapableAthenaHost(resolvedAppUrl)) {\n return false;\n }\n\n const resolvedCurrentOrigin = getOrigin(currentOrigin ?? getCurrentOrigin());\n return !!resolvedCurrentOrigin && resolvedAppUrl.origin === resolvedCurrentOrigin;\n};\n\nconst resolveEmbedAppUrl = ({\n appUrl,\n backendUrl,\n currentOrigin,\n}: {\n appUrl?: string;\n backendUrl?: string | null;\n currentOrigin?: string | null;\n}): string | null => {\n const derivedAppUrl = deriveAthenaAppUrl({ backendUrl });\n\n if (!appUrl) {\n return derivedAppUrl;\n }\n\n if (shouldPreferDerivedEmbedAppUrl({ appUrl, derivedAppUrl, currentOrigin })) {\n return derivedAppUrl;\n }\n\n return appUrl;\n};\n\nexport function resolveAssetEmbedUrl({\n embedUrl,\n appUrl,\n backendUrl,\n currentOrigin,\n}: {\n embedUrl: string;\n appUrl?: string;\n backendUrl?: string | null;\n currentOrigin?: string | null;\n}): string {\n try {\n const resolvedEmbedUrl = new URL(embedUrl);\n if (!resolvedEmbedUrl.pathname.startsWith('/embed/')) {\n return embedUrl;\n }\n\n const embedAppUrl = resolveEmbedAppUrl({\n appUrl,\n backendUrl,\n currentOrigin,\n });\n if (!embedAppUrl) {\n return embedUrl;\n }\n\n const resolvedAppUrl = new URL(embedAppUrl);\n resolvedEmbedUrl.protocol = resolvedAppUrl.protocol;\n resolvedEmbedUrl.host = resolvedAppUrl.host;\n return resolvedEmbedUrl.toString();\n } catch {\n return embedUrl;\n }\n}\n\nfunction setFiniteNumberParam({ params, key, value }: { params: URLSearchParams; key: string; value: unknown }): void {\n if (typeof value === 'number' && Number.isFinite(value)) {\n params.set(key, String(value));\n }\n}\n\nfunction setNonEmptyStringParam({ params, key, value }: { params: URLSearchParams; key: string; value: unknown }): void {\n if (typeof value === 'string' && value.length > 0) {\n params.set(key, value);\n }\n}\n\n/** The SDK's own embed parameter: it marks the bridge, never a place, so no anchor writes it. */\nconst SDK_BRIDGE_PARAM = 'athena_sdk_bridge';\n\n/**\n * The pairs of an anchor given as its raw query — the string an Athena link, citation or search\n * result carries (`anchor=slide&slide_index=3&slide_id=…`, `anchor=time&time=0:42`), alone or\n * after the `?` of an asset ref (`asset_x?anchor=…`) — read as URL parameters, or `null` when the\n * string holds none, or a parameter with no name. The SDK never interprets the anchor: the embed\n * page parses it with the references grammar, so every kind of place travels as written.\n */\nfunction rawAnchorQueryPairs(query: string): Array<[string, string]> | null {\n const queryIndex = query.indexOf('?');\n const search = queryIndex === -1 ? query : query.slice(queryIndex + 1);\n const pairs = [...new URLSearchParams(search)].filter(([key]) => key !== SDK_BRIDGE_PARAM);\n if (pairs.length === 0 || pairs.some(([key]) => key.length === 0)) return null;\n return pairs;\n}\n\nfunction appendRawAnchorQuery({ params, query }: { params: URLSearchParams; query: string }): void {\n const pairs = rawAnchorQueryPairs(query);\n if (!pairs) return;\n // Verbatim: a key the URL already has is replaced, and a repeated key keeps every value.\n for (const [key] of pairs) params.delete(key);\n for (const [key, value] of pairs) params.append(key, value);\n}\n\nfunction appendTypedAnchorParams({\n params,\n anchor,\n}: {\n params: URLSearchParams;\n anchor: object & { type: string };\n}): void {\n switch (anchor.type) {\n case 'page':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'page',\n value: 'page' in anchor ? anchor.page : undefined,\n });\n break;\n case 'page_range':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'start_page',\n value: 'startPage' in anchor ? anchor.startPage : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'end_page',\n value: 'endPage' in anchor ? anchor.endPage : undefined,\n });\n break;\n case 'page_rect':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'page',\n value: 'page' in anchor ? anchor.page : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'x',\n value: 'x' in anchor ? anchor.x : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'y',\n value: 'y' in anchor ? anchor.y : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'width',\n value: 'width' in anchor ? anchor.width : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'height',\n value: 'height' in anchor ? anchor.height : undefined,\n });\n if (\n 'unit' in anchor &&\n (anchor.unit === 'percent' || anchor.unit === 'point')\n ) {\n params.set('unit', anchor.unit);\n }\n break;\n case 'page_text':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'page',\n value: 'page' in anchor ? anchor.page : undefined,\n });\n if ('text' in anchor && typeof anchor.text === 'string') {\n params.set('text', anchor.text);\n }\n // Optional context that disambiguates a repeated phrase, and the hash of\n // the cited unit's normalized text; the embed parses both with the shared\n // `@athenaintel/references` parser.\n setNonEmptyStringParam({ params, key: 'prefix', value: 'prefix' in anchor ? anchor.prefix : undefined });\n setNonEmptyStringParam({ params, key: 'suffix', value: 'suffix' in anchor ? anchor.suffix : undefined });\n setNonEmptyStringParam({ params, key: 'hash', value: 'hash' in anchor ? anchor.hash : undefined });\n break;\n // Sheet anchors ride the same query contract the embed page parses with\n // the shared `@athenaintel/references` parser.\n case 'sheet_cell':\n case 'sheet_range':\n case 'sheet_tab':\n case 'sheet_table':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'sheet_id',\n value: 'sheetId' in anchor ? anchor.sheetId : undefined,\n });\n if ('cell' in anchor && typeof anchor.cell === 'string') {\n params.set('cell', anchor.cell);\n }\n if ('range' in anchor && typeof anchor.range === 'string') {\n params.set('range', anchor.range);\n }\n if ('tableName' in anchor && typeof anchor.tableName === 'string') {\n params.set('table_name', anchor.tableName);\n }\n if ('fallbackRange' in anchor && typeof anchor.fallbackRange === 'string') {\n params.set('fallback_range', anchor.fallbackRange);\n }\n break;\n }\n}\n\n/**\n * Writes a citation's place into an embed URL: its anchor and its excerpt (the passage the embed\n * finds by its words — alone, when the citation names no anchor). The anchor is either its raw\n * query string, forwarded as written whatever kind of place it names, or one of the typed page and\n * sheet anchors. Athena on the web's Spaces links read the same grammar, so a host that opens a\n * cited place there writes it the same way.\n */\nexport function appendCitationReferenceParams({\n params,\n reference,\n}: {\n params: URLSearchParams;\n reference?: AthenaAssetCitationReference;\n}): void {\n const anchor = reference?.anchor;\n if (typeof anchor === 'string') {\n appendRawAnchorQuery({ params, query: anchor });\n } else if (anchor && typeof anchor === 'object' && 'type' in anchor && typeof anchor.type === 'string') {\n appendTypedAnchorParams({ params, anchor: { ...anchor, type: anchor.type } });\n }\n\n const excerpt = reference?.meta?.excerpt;\n if (typeof excerpt === 'string' && excerpt) {\n params.set('excerpt', excerpt);\n }\n}\n\nexport function buildSdkAssetEmbedUrl(embedUrl: string, reference?: AthenaAssetCitationReference): string {\n try {\n const url = new URL(embedUrl);\n url.searchParams.set('athena_sdk_bridge', '1');\n appendCitationReferenceParams({ params: url.searchParams, reference });\n return url.toString();\n } catch {\n return embedUrl;\n }\n}\n\nconst getJwtPayload = (token: string): Record<string, unknown> | null => {\n try {\n const payloadSegment = token.split('.')[1];\n if (!payloadSegment || typeof atob !== 'function') return null;\n const normalized = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');\n const payload: unknown = JSON.parse(\n atob(normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), '=')),\n );\n return payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport function getAssetEmbedAuthContext({ token, apiKey }: { token?: string | null; apiKey?: string }): string {\n if (!token) return apiKey ? `api-key:${apiKey}` : 'anonymous';\n\n const payload = getJwtPayload(token);\n const userId = payload?.user_id ?? payload?.sub;\n if (typeof userId !== 'string' || !userId) return `opaque-token:${token}`;\n\n return `jwt:${JSON.stringify({\n issuer: payload?.iss ?? null,\n userId,\n activeOrgId: payload?.active_org_id ?? payload?.org_id ?? null,\n workspaceId: payload?.workspace_id ?? null,\n orgMemberships: payload?.org_id_to_org_member_info ?? null,\n })}`;\n}\n\n/**\n * Hook to generate an embed URL for rendering an asset in an iframe.\n * Calls the Athena embed token endpoint through TanStack Query (the host's\n * QueryClient when there is one, else the page's embed client), keyed on the\n * asset, the mode and the identity.\n *\n * Note: The auth token is read via a ref and is intentionally NOT part\n * of the query key. PropelAuth and similar providers refresh the token value\n * periodically (e.g. on window focus), but the underlying session is the\n * same — minting again on every token rotation would force the iframe to\n * reload unnecessarily. The link is minted again only when the identity\n * (user or tenant), the asset or the mode changes.\n */\nexport function useAssetEmbed(\n assetId: string | null,\n options: UseAssetEmbedOptions & {\n backendUrl: string;\n appUrl?: string;\n apiKey?: string;\n token?: string | null;\n /**\n * Live token resolver (the provider's `config.getToken`) that renews the\n * held `token`: read before the embed-token request, and asked for a\n * renewed token (`force: true`) when the backend refuses it. Ignored when\n * no token is held, so the request always authenticates as the identity\n * the embed cache is keyed on.\n */\n getToken?: AthenaStatewireTokenGetter;\n } = {\n backendUrl: '',\n },\n): UseAssetEmbedResult {\n const {\n readOnly = DEFAULT_ASSET_EMBED_READ_ONLY,\n expiresInSeconds = 60 * 60 * 24 * 30,\n displayMode = DEFAULT_ASSET_EMBED_DISPLAY_MODE,\n allowQuickEdit = DEFAULT_ASSET_EMBED_ALLOW_QUICK_EDIT,\n backendUrl,\n appUrl,\n apiKey,\n token,\n getToken,\n } = options;\n // Keep the latest token in a ref so the query can read it without being\n // keyed on it: PropelAuth and similar providers rotate the token value.\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n // Stable across normal JWT rotations, but changes when the user or tenant\n // changes so a signed URL can never be reused across auth boundaries.\n const authContext = getAssetEmbedAuthContext({ token, apiKey });\n const enabled = Boolean(assetId && backendUrl);\n\n const query = useQuery(\n {\n queryKey: [\n 'athena-sdk',\n 'asset-embed',\n assetId,\n readOnly,\n displayMode,\n allowQuickEdit,\n // The identity, never the credential: an opaque token or a key is part of `authContext`.\n keyPartFingerprint(authContext),\n backendUrl,\n appUrl ?? '',\n ],\n queryFn: async ({ signal }): Promise<{ url: string; expiresAt: number }> => {\n // Derive the Athena API base from backendUrl before calling the embed endpoint.\n const apiBaseUrl = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n const heldToken = tokenRef.current;\n const res = await sendWithCredentialRenewal(\n { apiKey, token: heldToken, getToken: heldToken ? getTokenRef.current : undefined },\n (headers) =>\n fetch(`${apiBaseUrl}/api/embed/generate-token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify(\n buildAssetEmbedRequestBody({\n assetId: assetId ?? '',\n readOnly,\n expiresInSeconds,\n displayMode,\n allowQuickEdit,\n }),\n ),\n signal,\n }),\n );\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(`Failed to generate embed token (${res.status}): ${text}`);\n }\n const data: { embed_url: string; expires_at: number } = await res.json();\n return {\n url: resolveAssetEmbedUrl({ embedUrl: data.embed_url, appUrl, backendUrl }),\n expiresAt: data.expires_at,\n };\n },\n enabled,\n // A minted link is good until it expires; a new one would reload the frame, so it is never\n // minted again while the embed shows (no refetch on focus or reconnect) and never retried.\n staleTime: (cached) =>\n cached.state.data ? Math.max(0, cached.state.data.expiresAt * 1000 - Date.now()) : 0,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n retry: false,\n },\n useContext(QueryClientContext) ?? embedQueryClient,\n );\n\n return {\n embedUrl: enabled ? (query.data?.url ?? null) : null,\n isLoading: enabled && query.isLoading,\n error: enabled && query.error ? query.error.message : null,\n };\n}\n"],"names":[],"mappings":";;;;;AAuBO,MAAM,gCAAgC;AACtC,MAAM,uCAAuC;AAC7C,MAAM,mCAAmC;AAQzC,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,iBAAiB;AACnB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,OAAO;AAAA,IAAA;AAAA,IAET,WAAW,kBAAkB,KAAK;AAAA,EAAA;AAGpC,SAAO;AAAA,IACL,UAAU,YAAW,WAAM,SAAN,mBAAY,QAAO,OAAQ;AAAA,IAChD,WAAW,WAAW,MAAM;AAAA,IAC5B,OAAO,WAAW,MAAM,QAAQ,MAAM,MAAM,UAAU;AAAA,EAAA;AAE1D;"}
1
+ {"version":3,"file":"use-asset-embed.js","sources":["../../src/assets/use-asset-embed.ts"],"sourcesContent":["import { QueryClient, QueryClientContext, useQuery } from '@tanstack/react-query';\nimport { useContext, useRef } from 'react';\nimport { deriveAthenaAppUrl } from '../lib/athena-urls';\nimport { keyPartFingerprint } from '../lib/use-athena-rest-query';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport type { AthenaAssetCitationReference } from './asset-embed-messages';\n\nexport interface UseAssetEmbedOptions {\n readOnly?: boolean;\n expiresInSeconds?: number;\n /** Native Olympus surface rendered by the iframe. Defaults to `full`. */\n displayMode?: 'minimal' | 'full';\n /**\n * Offer Quick Edit (⌘J, an AI rewrite of the selection) in a minimal embed, where the viewer\n * does not sign in: spreadsheets and Word documents, on an editable link (`readOnly: false`)\n * only. Its runs are billed to the asset's workspace under the link's creator, and each link has\n * its own hourly cap. The full mode's editors offer it to the signed-in person already. Defaults\n * to `false`.\n */\n allowQuickEdit?: boolean;\n /**\n * Show the asset's comment threads, read-only, to everyone holding the link, a viewer who is not\n * signed in included. Without it, a minimal embed shows them only to a signed-in viewer who has\n * their own access to the asset (the bearer this component hands the iframe, or an Athena\n * session). No embed ever writes a comment. Defaults to `false`.\n */\n allowComments?: boolean;\n}\n\nexport const DEFAULT_ASSET_EMBED_READ_ONLY = false;\nexport const DEFAULT_ASSET_EMBED_ALLOW_QUICK_EDIT = false;\nexport const DEFAULT_ASSET_EMBED_ALLOW_COMMENTS = false;\nexport const DEFAULT_ASSET_EMBED_DISPLAY_MODE = 'full' as const;\n\nexport interface UseAssetEmbedResult {\n embedUrl: string | null;\n isLoading: boolean;\n error: string | null;\n}\n\nexport function buildAssetEmbedRequestBody({\n assetId,\n readOnly,\n expiresInSeconds,\n displayMode,\n allowQuickEdit = DEFAULT_ASSET_EMBED_ALLOW_QUICK_EDIT,\n allowComments = DEFAULT_ASSET_EMBED_ALLOW_COMMENTS,\n}: {\n assetId: string;\n readOnly: boolean;\n expiresInSeconds: number;\n displayMode: 'minimal' | 'full';\n allowQuickEdit?: boolean;\n allowComments?: boolean;\n}) {\n return {\n asset_id: assetId,\n read_only: readOnly,\n expires_in_seconds: expiresInSeconds,\n display_mode: displayMode,\n // Sent only when asked: an agora that predates it is never handed an unknown field.\n ...(allowQuickEdit && { allow_quick_edit: true }),\n ...(allowComments && { allow_comments: true }),\n };\n}\n\n/**\n * The embed links' query client when the host provides none: one for the page, so every embed of\n * one asset, mode and identity shares one minted link until it expires.\n */\nconst embedQueryClient = new QueryClient();\n\nconst ATHENA_APP_HOSTNAMES = new Set(['app.athenaintel.com', 'staging-app.athenaintel.com']);\nconst ATHENA_PREVIEW_HOSTNAME_SUFFIX = '.previews.athenaintel.com';\nconst ATHENA_WORKSPACE_HOSTNAME_PATTERN = /^.+--(\\d+)\\.(?:app\\.athenaintel\\.com|staging-app\\.athenaintel\\.com)$/;\nconst OLYMPUS_WORKSPACE_PORT = '8082';\n\nconst getUrl = (value?: string | null): URL | null => {\n if (!value) {\n return null;\n }\n\n try {\n return new URL(value);\n } catch {\n return null;\n }\n};\n\nconst getCurrentOrigin = (): string | null => {\n if (typeof window === 'undefined') {\n return null;\n }\n\n return window.location.origin;\n};\n\nconst getOrigin = (value?: string | null): string | null => getUrl(value)?.origin ?? null;\n\nconst getAthenaWorkspacePort = (url: URL): string | null => {\n const match = url.hostname.toLowerCase().match(ATHENA_WORKSPACE_HOSTNAME_PATTERN);\n return match?.[1] ?? null;\n};\n\nconst isEmbedCapableAthenaHost = (url: URL): boolean => {\n const hostname = url.hostname.toLowerCase();\n\n if (ATHENA_APP_HOSTNAMES.has(hostname) || hostname.endsWith(ATHENA_PREVIEW_HOSTNAME_SUFFIX)) {\n return true;\n }\n\n return getAthenaWorkspacePort(url) === OLYMPUS_WORKSPACE_PORT;\n};\n\nconst shouldPreferDerivedEmbedAppUrl = ({\n appUrl,\n derivedAppUrl,\n currentOrigin,\n}: {\n appUrl: string;\n derivedAppUrl: string | null;\n currentOrigin?: string | null;\n}): boolean => {\n if (!derivedAppUrl) {\n return false;\n }\n\n const resolvedAppUrl = getUrl(appUrl);\n if (!resolvedAppUrl) {\n return true;\n }\n\n const workspacePort = getAthenaWorkspacePort(resolvedAppUrl);\n if (workspacePort && workspacePort !== OLYMPUS_WORKSPACE_PORT) {\n return true;\n }\n\n if (isEmbedCapableAthenaHost(resolvedAppUrl)) {\n return false;\n }\n\n const resolvedCurrentOrigin = getOrigin(currentOrigin ?? getCurrentOrigin());\n return !!resolvedCurrentOrigin && resolvedAppUrl.origin === resolvedCurrentOrigin;\n};\n\nconst resolveEmbedAppUrl = ({\n appUrl,\n backendUrl,\n currentOrigin,\n}: {\n appUrl?: string;\n backendUrl?: string | null;\n currentOrigin?: string | null;\n}): string | null => {\n const derivedAppUrl = deriveAthenaAppUrl({ backendUrl });\n\n if (!appUrl) {\n return derivedAppUrl;\n }\n\n if (shouldPreferDerivedEmbedAppUrl({ appUrl, derivedAppUrl, currentOrigin })) {\n return derivedAppUrl;\n }\n\n return appUrl;\n};\n\nexport function resolveAssetEmbedUrl({\n embedUrl,\n appUrl,\n backendUrl,\n currentOrigin,\n}: {\n embedUrl: string;\n appUrl?: string;\n backendUrl?: string | null;\n currentOrigin?: string | null;\n}): string {\n try {\n const resolvedEmbedUrl = new URL(embedUrl);\n if (!resolvedEmbedUrl.pathname.startsWith('/embed/')) {\n return embedUrl;\n }\n\n const embedAppUrl = resolveEmbedAppUrl({\n appUrl,\n backendUrl,\n currentOrigin,\n });\n if (!embedAppUrl) {\n return embedUrl;\n }\n\n const resolvedAppUrl = new URL(embedAppUrl);\n resolvedEmbedUrl.protocol = resolvedAppUrl.protocol;\n resolvedEmbedUrl.host = resolvedAppUrl.host;\n return resolvedEmbedUrl.toString();\n } catch {\n return embedUrl;\n }\n}\n\nfunction setFiniteNumberParam({ params, key, value }: { params: URLSearchParams; key: string; value: unknown }): void {\n if (typeof value === 'number' && Number.isFinite(value)) {\n params.set(key, String(value));\n }\n}\n\nfunction setNonEmptyStringParam({ params, key, value }: { params: URLSearchParams; key: string; value: unknown }): void {\n if (typeof value === 'string' && value.length > 0) {\n params.set(key, value);\n }\n}\n\n/** The SDK's own embed parameter: it marks the bridge, never a place, so no anchor writes it. */\nconst SDK_BRIDGE_PARAM = 'athena_sdk_bridge';\n\n/**\n * The pairs of an anchor given as its raw query — the string an Athena link, citation or search\n * result carries (`anchor=slide&slide_index=3&slide_id=…`, `anchor=time&time=0:42`), alone or\n * after the `?` of an asset ref (`asset_x?anchor=…`) — read as URL parameters, or `null` when the\n * string holds none, or a parameter with no name. The SDK never interprets the anchor: the embed\n * page parses it with the references grammar, so every kind of place travels as written.\n */\nfunction rawAnchorQueryPairs(query: string): Array<[string, string]> | null {\n const queryIndex = query.indexOf('?');\n const search = queryIndex === -1 ? query : query.slice(queryIndex + 1);\n const pairs = [...new URLSearchParams(search)].filter(([key]) => key !== SDK_BRIDGE_PARAM);\n if (pairs.length === 0 || pairs.some(([key]) => key.length === 0)) return null;\n return pairs;\n}\n\nfunction appendRawAnchorQuery({ params, query }: { params: URLSearchParams; query: string }): void {\n const pairs = rawAnchorQueryPairs(query);\n if (!pairs) return;\n // Verbatim: a key the URL already has is replaced, and a repeated key keeps every value.\n for (const [key] of pairs) params.delete(key);\n for (const [key, value] of pairs) params.append(key, value);\n}\n\nfunction appendTypedAnchorParams({\n params,\n anchor,\n}: {\n params: URLSearchParams;\n anchor: object & { type: string };\n}): void {\n switch (anchor.type) {\n case 'page':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'page',\n value: 'page' in anchor ? anchor.page : undefined,\n });\n break;\n case 'page_range':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'start_page',\n value: 'startPage' in anchor ? anchor.startPage : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'end_page',\n value: 'endPage' in anchor ? anchor.endPage : undefined,\n });\n break;\n case 'page_rect':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'page',\n value: 'page' in anchor ? anchor.page : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'x',\n value: 'x' in anchor ? anchor.x : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'y',\n value: 'y' in anchor ? anchor.y : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'width',\n value: 'width' in anchor ? anchor.width : undefined,\n });\n setFiniteNumberParam({\n params,\n key: 'height',\n value: 'height' in anchor ? anchor.height : undefined,\n });\n if (\n 'unit' in anchor &&\n (anchor.unit === 'percent' || anchor.unit === 'point')\n ) {\n params.set('unit', anchor.unit);\n }\n break;\n case 'page_text':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'page',\n value: 'page' in anchor ? anchor.page : undefined,\n });\n if ('text' in anchor && typeof anchor.text === 'string') {\n params.set('text', anchor.text);\n }\n // Optional context that disambiguates a repeated phrase, and the hash of\n // the cited unit's normalized text; the embed parses both with the shared\n // `@athenaintel/references` parser.\n setNonEmptyStringParam({ params, key: 'prefix', value: 'prefix' in anchor ? anchor.prefix : undefined });\n setNonEmptyStringParam({ params, key: 'suffix', value: 'suffix' in anchor ? anchor.suffix : undefined });\n setNonEmptyStringParam({ params, key: 'hash', value: 'hash' in anchor ? anchor.hash : undefined });\n break;\n // Sheet anchors ride the same query contract the embed page parses with\n // the shared `@athenaintel/references` parser.\n case 'sheet_cell':\n case 'sheet_range':\n case 'sheet_tab':\n case 'sheet_table':\n params.set('anchor', anchor.type);\n setFiniteNumberParam({\n params,\n key: 'sheet_id',\n value: 'sheetId' in anchor ? anchor.sheetId : undefined,\n });\n if ('cell' in anchor && typeof anchor.cell === 'string') {\n params.set('cell', anchor.cell);\n }\n if ('range' in anchor && typeof anchor.range === 'string') {\n params.set('range', anchor.range);\n }\n if ('tableName' in anchor && typeof anchor.tableName === 'string') {\n params.set('table_name', anchor.tableName);\n }\n if ('fallbackRange' in anchor && typeof anchor.fallbackRange === 'string') {\n params.set('fallback_range', anchor.fallbackRange);\n }\n break;\n }\n}\n\n/**\n * Writes a citation's place into an embed URL: its anchor and its excerpt (the passage the embed\n * finds by its words — alone, when the citation names no anchor). The anchor is either its raw\n * query string, forwarded as written whatever kind of place it names, or one of the typed page and\n * sheet anchors. Athena on the web's Spaces links read the same grammar, so a host that opens a\n * cited place there writes it the same way.\n */\nexport function appendCitationReferenceParams({\n params,\n reference,\n}: {\n params: URLSearchParams;\n reference?: AthenaAssetCitationReference;\n}): void {\n const anchor = reference?.anchor;\n if (typeof anchor === 'string') {\n appendRawAnchorQuery({ params, query: anchor });\n } else if (anchor && typeof anchor === 'object' && 'type' in anchor && typeof anchor.type === 'string') {\n appendTypedAnchorParams({ params, anchor: { ...anchor, type: anchor.type } });\n }\n\n const excerpt = reference?.meta?.excerpt;\n if (typeof excerpt === 'string' && excerpt) {\n params.set('excerpt', excerpt);\n }\n}\n\nexport function buildSdkAssetEmbedUrl(embedUrl: string, reference?: AthenaAssetCitationReference): string {\n try {\n const url = new URL(embedUrl);\n url.searchParams.set('athena_sdk_bridge', '1');\n appendCitationReferenceParams({ params: url.searchParams, reference });\n return url.toString();\n } catch {\n return embedUrl;\n }\n}\n\nconst getJwtPayload = (token: string): Record<string, unknown> | null => {\n try {\n const payloadSegment = token.split('.')[1];\n if (!payloadSegment || typeof atob !== 'function') return null;\n const normalized = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');\n const payload: unknown = JSON.parse(\n atob(normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), '=')),\n );\n return payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n};\n\nexport function getAssetEmbedAuthContext({ token, apiKey }: { token?: string | null; apiKey?: string }): string {\n if (!token) return apiKey ? `api-key:${apiKey}` : 'anonymous';\n\n const payload = getJwtPayload(token);\n const userId = payload?.user_id ?? payload?.sub;\n if (typeof userId !== 'string' || !userId) return `opaque-token:${token}`;\n\n return `jwt:${JSON.stringify({\n issuer: payload?.iss ?? null,\n userId,\n activeOrgId: payload?.active_org_id ?? payload?.org_id ?? null,\n workspaceId: payload?.workspace_id ?? null,\n orgMemberships: payload?.org_id_to_org_member_info ?? null,\n })}`;\n}\n\n/**\n * Hook to generate an embed URL for rendering an asset in an iframe.\n * Calls the Athena embed token endpoint through TanStack Query (the host's\n * QueryClient when there is one, else the page's embed client), keyed on the\n * asset, the mode and the identity.\n *\n * Note: The auth token is read via a ref and is intentionally NOT part\n * of the query key. PropelAuth and similar providers refresh the token value\n * periodically (e.g. on window focus), but the underlying session is the\n * same — minting again on every token rotation would force the iframe to\n * reload unnecessarily. The link is minted again only when the identity\n * (user or tenant), the asset or the mode changes.\n */\nexport function useAssetEmbed(\n assetId: string | null,\n options: UseAssetEmbedOptions & {\n backendUrl: string;\n appUrl?: string;\n apiKey?: string;\n token?: string | null;\n /**\n * Live token resolver (the provider's `config.getToken`) that renews the\n * held `token`: read before the embed-token request, and asked for a\n * renewed token (`force: true`) when the backend refuses it. Ignored when\n * no token is held, so the request always authenticates as the identity\n * the embed cache is keyed on.\n */\n getToken?: AthenaStatewireTokenGetter;\n } = {\n backendUrl: '',\n },\n): UseAssetEmbedResult {\n const {\n readOnly = DEFAULT_ASSET_EMBED_READ_ONLY,\n expiresInSeconds = 60 * 60 * 24 * 30,\n displayMode = DEFAULT_ASSET_EMBED_DISPLAY_MODE,\n allowQuickEdit = DEFAULT_ASSET_EMBED_ALLOW_QUICK_EDIT,\n allowComments = DEFAULT_ASSET_EMBED_ALLOW_COMMENTS,\n backendUrl,\n appUrl,\n apiKey,\n token,\n getToken,\n } = options;\n // Keep the latest token in a ref so the query can read it without being\n // keyed on it: PropelAuth and similar providers rotate the token value.\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n // Stable across normal JWT rotations, but changes when the user or tenant\n // changes so a signed URL can never be reused across auth boundaries.\n const authContext = getAssetEmbedAuthContext({ token, apiKey });\n const enabled = Boolean(assetId && backendUrl);\n\n const query = useQuery(\n {\n queryKey: [\n 'athena-sdk',\n 'asset-embed',\n assetId,\n readOnly,\n displayMode,\n allowQuickEdit,\n allowComments,\n // The identity, never the credential: an opaque token or a key is part of `authContext`.\n keyPartFingerprint(authContext),\n backendUrl,\n appUrl ?? '',\n ],\n queryFn: async ({ signal }): Promise<{ url: string; expiresAt: number }> => {\n // Derive the Athena API base from backendUrl before calling the embed endpoint.\n const apiBaseUrl = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n const heldToken = tokenRef.current;\n const res = await sendWithCredentialRenewal(\n { apiKey, token: heldToken, getToken: heldToken ? getTokenRef.current : undefined },\n (headers) =>\n fetch(`${apiBaseUrl}/api/embed/generate-token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...headers },\n body: JSON.stringify(\n buildAssetEmbedRequestBody({\n assetId: assetId ?? '',\n readOnly,\n expiresInSeconds,\n displayMode,\n allowQuickEdit,\n allowComments,\n }),\n ),\n signal,\n }),\n );\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(`Failed to generate embed token (${res.status}): ${text}`);\n }\n const data: { embed_url: string; expires_at: number } = await res.json();\n return {\n url: resolveAssetEmbedUrl({ embedUrl: data.embed_url, appUrl, backendUrl }),\n expiresAt: data.expires_at,\n };\n },\n enabled,\n // A minted link is good until it expires; a new one would reload the frame, so it is never\n // minted again while the embed shows (no refetch on focus or reconnect) and never retried.\n staleTime: (cached) =>\n cached.state.data ? Math.max(0, cached.state.data.expiresAt * 1000 - Date.now()) : 0,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n retry: false,\n },\n useContext(QueryClientContext) ?? embedQueryClient,\n );\n\n return {\n embedUrl: enabled ? (query.data?.url ?? null) : null,\n isLoading: enabled && query.isLoading,\n error: enabled && query.error ? query.error.message : null,\n };\n}\n"],"names":[],"mappings":";;;;;AA8BO,MAAM,gCAAgC;AACtC,MAAM,uCAAuC;AAC7C,MAAM,qCAAqC;AAC3C,MAAM,mCAAmC;AAQzC,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,iBAAiB;AAAA,EACjB,gBAAgB;AAClB,GAOG;AACD,SAAO;AAAA,IACL,UAAU;AAAA,IACV,WAAW;AAAA,IACX,oBAAoB;AAAA,IACpB,cAAc;AAAA;AAAA,IAEd,GAAI,kBAAkB,EAAE,kBAAkB,KAAA;AAAA,IAC1C,GAAI,iBAAiB,EAAE,gBAAgB,KAAA;AAAA,EAAK;AAEhD;AAMA,MAAM,mBAAmB,IAAI,YAAA;AAE7B,MAAM,uBAAuB,oBAAI,IAAI,CAAC,uBAAuB,6BAA6B,CAAC;AAC3F,MAAM,iCAAiC;AACvC,MAAM,oCAAoC;AAC1C,MAAM,yBAAyB;AAE/B,MAAM,SAAS,CAAC,UAAsC;AACpD,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,MAAI;AACF,WAAO,IAAI,IAAI,KAAK;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,MAAM,mBAAmB,MAAqB;AAC5C,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,SAAS;AACzB;AAEA,MAAM,YAAY,CAAC,UAAA;;AAAyC,uBAAO,KAAK,MAAZ,mBAAe,WAAU;AAAA;AAErF,MAAM,yBAAyB,CAAC,QAA4B;AAC1D,QAAM,QAAQ,IAAI,SAAS,YAAA,EAAc,MAAM,iCAAiC;AAChF,UAAO,+BAAQ,OAAM;AACvB;AAEA,MAA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,IAAI,OAAO,MAAM,MAAM,EAAE;AAC5C,gBAAM,IAAI,MAAM,mCAAmC,IAAI,MAAM,MAAM,IAAI,EAAE;AAAA,QAC3E;AACA,cAAM,OAAkD,MAAM,IAAI,KAAA;AAClE,eAAO;AAAA,UACL,KAAK,qBAAqB,EAAE,UAAU,KAAK,WAAW,QAAQ,YAAY;AAAA,UAC1E,WAAW,KAAK;AAAA,QAAA;AAAA,MAEpB;AAAA,MACA;AAAA;AAAA;AAAA,MAGA,WAAW,CAAC,WACV,OAAO,MAAM,OAAO,KAAK,IAAI,GAAG,OAAO,MAAM,KAAK,YAAY,MAAO,KAAK,IAAA,CAAK,IAAI;AAAA,MACrF,sBAAsB;AAAA,MACtB,oBAAoB;AAAA,MACpB,OAAO;AAAA,IAAA;AAAA,IAET,WAAW,kBAAkB,KAAK;AAAA,EAAA;AAGpC,SAAO;AAAA,IACL,UAAU,YAAW,WAAM,SAAN,mBAAY,QAAO,OAAQ;AAAA,IAChD,WAAW,WAAW,MAAM;AAAA,IAC5B,OAAO,WAAW,MAAM,QAAQ,MAAM,MAAM,UAAU;AAAA,EAAA;AAE1D;"}
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const react = require("react");
4
- const AthenaAuthContext = react.createContext(null);
3
+ const require$$0 = require("react");
4
+ const AthenaAuthContext = require$$0.createContext(null);
5
5
  function useAthenaAuth() {
6
- const ctx = react.useContext(AthenaAuthContext);
6
+ const ctx = require$$0.useContext(AthenaAuthContext);
7
7
  if (!ctx) {
8
8
  throw new Error(
9
9
  "[AthenaSDK] useAthenaAuth must be used within an <AthenaAuthProvider>"
@@ -1 +1 @@
1
- {"version":3,"file":"AthenaAuthContext.cjs","sources":["../../src/auth/AthenaAuthContext.ts"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { AthenaAuthState } from './types';\n\n/**\n * Internal context used by `AthenaAuthProvider` to share auth state.\n * Consumed by `useAthenaAuth()` and automatically by `AthenaProvider`.\n */\nexport const AthenaAuthContext = createContext<AthenaAuthState | null>(null);\n\n/**\n * Read the current Athena auth state.\n *\n * Must be used inside an `<AthenaAuthProvider>`.\n *\n * @example\n * ```tsx\n * function UserMenu() {\n * const { user, isLoggedIn, logout } = useAthenaAuth();\n * if (!isLoggedIn) return null;\n * return (\n * <div>\n * <span>{user?.email}</span>\n * <button onClick={() => logout()}>Log out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useAthenaAuth(): AthenaAuthState {\n const ctx = useContext(AthenaAuthContext);\n if (!ctx) {\n throw new Error(\n '[AthenaSDK] useAthenaAuth must be used within an <AthenaAuthProvider>',\n );\n }\n return ctx;\n}\n"],"names":["createContext","useContext"],"mappings":";;;AAOO,MAAM,oBAAoBA,MAAAA,cAAsC,IAAI;AAqBpE,SAAS,gBAAiC;AAC/C,QAAM,MAAMC,MAAAA,WAAW,iBAAiB;AACxC,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACA,SAAO;AACT;;;"}
1
+ {"version":3,"file":"AthenaAuthContext.cjs","sources":["../../src/auth/AthenaAuthContext.ts"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { AthenaAuthState } from './types';\n\n/**\n * Internal context used by `AthenaAuthProvider` to share auth state.\n * Consumed by `useAthenaAuth()` and automatically by `AthenaProvider`.\n */\nexport const AthenaAuthContext = createContext<AthenaAuthState | null>(null);\n\n/**\n * Read the current Athena auth state.\n *\n * Must be used inside an `<AthenaAuthProvider>`.\n *\n * @example\n * ```tsx\n * function UserMenu() {\n * const { user, isLoggedIn, logout } = useAthenaAuth();\n * if (!isLoggedIn) return null;\n * return (\n * <div>\n * <span>{user?.email}</span>\n * <button onClick={() => logout()}>Log out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useAthenaAuth(): AthenaAuthState {\n const ctx = useContext(AthenaAuthContext);\n if (!ctx) {\n throw new Error(\n '[AthenaSDK] useAthenaAuth must be used within an <AthenaAuthProvider>',\n );\n }\n return ctx;\n}\n"],"names":["createContext","useContext"],"mappings":";;;AAOO,MAAM,oBAAoBA,WAAAA,cAAsC,IAAI;AAqBpE,SAAS,gBAAiC;AAC/C,QAAM,MAAMC,WAAAA,WAAW,iBAAiB;AACxC,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACA,SAAO;AACT;;;"}
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const jsxRuntime = require("react/jsx-runtime");
4
4
  const react = require("@propelauth/react");
5
- const react$1 = require("react");
5
+ const require$$0 = require("react");
6
6
  const AthenaAuthContext = require("./AthenaAuthContext.cjs");
7
7
  function propelAuthTokenGetter(read) {
8
8
  return async ({ force = false } = {}) => {
@@ -49,10 +49,10 @@ function patchHistoryForLocationTracking() {
49
49
  historyPatched = true;
50
50
  }
51
51
  function useCurrentHref() {
52
- const [href, setHref] = react$1.useState(
52
+ const [href, setHref] = require$$0.useState(
53
53
  typeof window !== "undefined" ? window.location.href : "/"
54
54
  );
55
- react$1.useEffect(() => {
55
+ require$$0.useEffect(() => {
56
56
  if (typeof window === "undefined") {
57
57
  return;
58
58
  }
@@ -78,13 +78,13 @@ function AthenaAuthBridge({
78
78
  }) {
79
79
  const authInfo = react.useAuthInfo();
80
80
  const logoutFn = react.useLogoutFunction();
81
- const logoutFnRef = react$1.useRef(logoutFn);
81
+ const logoutFnRef = require$$0.useRef(logoutFn);
82
82
  logoutFnRef.current = logoutFn;
83
- const prevAuthStateRef = react$1.useRef(null);
84
- const authInfoRef = react$1.useRef(authInfo);
83
+ const prevAuthStateRef = require$$0.useRef(null);
84
+ const authInfoRef = require$$0.useRef(authInfo);
85
85
  authInfoRef.current = authInfo;
86
- const [getToken] = react$1.useState(() => propelAuthTokenGetter(() => authInfoRef.current));
87
- const authState = react$1.useMemo(() => {
86
+ const [getToken] = require$$0.useState(() => propelAuthTokenGetter(() => authInfoRef.current));
87
+ const authState = require$$0.useMemo(() => {
88
88
  var _a, _b;
89
89
  if (authInfo.loading) {
90
90
  prevAuthStateRef.current = null;
@@ -1 +1 @@
1
- {"version":3,"file":"AthenaAuthProvider.cjs","sources":["../../src/auth/AthenaAuthProvider.tsx"],"sourcesContent":["import {\n RequiredAuthProvider,\n RedirectToLogin,\n useAuthInfo,\n useLogoutFunction,\n} from '@propelauth/react';\nimport type { ReactNode } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { AthenaAuthContext } from './AthenaAuthContext';\nimport type { AthenaAuthState, AthenaOrg, AthenaUser } from './types';\n\n/** The part of a PropelAuth `useAuthInfo()` snapshot the token getter reads. */\nexport interface PropelAuthTokenSnapshot {\n loading: boolean;\n isLoggedIn: boolean | undefined;\n accessToken: string | null | undefined;\n /** Absent on `@propelauth/react` releases that predate it. */\n refreshAuthInfo?: () => Promise<void>;\n /** Absent on `@propelauth/react` releases that predate it. */\n tokens?: { getAccessToken?: () => Promise<string | undefined> };\n}\n\n/**\n * The PropelAuth side of the SDK's credential source. `force` (the previous\n * token was refused) makes PropelAuth mint a new token first; either way the\n * token comes from PropelAuth's own `getAccessToken`, which renews one that is\n * about to expire. A failed renewal keeps the held token, so the caller's\n * attempt is refused by the host rather than failing in the client.\n */\nexport function propelAuthTokenGetter(\n read: () => PropelAuthTokenSnapshot,\n): AthenaStatewireTokenGetter {\n return async ({ force = false } = {}) => {\n const info = read();\n if (info.loading || !info.isLoggedIn) return null;\n if (force) {\n try {\n await info.refreshAuthInfo?.();\n } catch {\n // Keep the held token; the host decides.\n }\n }\n const latest = read();\n let fresh: string | undefined;\n try {\n fresh = await latest.tokens?.getAccessToken?.();\n } catch {\n fresh = undefined;\n }\n return fresh ?? (latest.isLoggedIn ? (latest.accessToken ?? null) : null);\n };\n}\n\n// ─── Props ────────────────────────────────────────────────────────────\n\nexport interface AthenaAuthProviderProps {\n children: ReactNode;\n\n /**\n * Your PropelAuth auth URL (e.g. `https://auth.yourdomain.com`).\n * Found in the PropelAuth dashboard under Frontend Integration.\n */\n authUrl: string;\n\n /**\n * Where to redirect after a successful login.\n * Defaults to the current page URL.\n */\n postLoginRedirectUrl?: string;\n\n /**\n * Custom element displayed while the auth state is loading.\n * Defaults to `null` (renders nothing).\n */\n displayWhileLoading?: ReactNode;\n}\n\nconst ATHENA_LOCATION_CHANGE_EVENT = 'athena:location-change';\nlet historyPatched = false;\n\nfunction patchHistoryForLocationTracking(): void {\n if (historyPatched || typeof window === 'undefined') {\n return;\n }\n\n const notifyLocationChange = () => {\n window.dispatchEvent(new Event(ATHENA_LOCATION_CHANGE_EVENT));\n };\n\n const originalPushState = window.history.pushState;\n window.history.pushState = function pushState(...args) {\n const result = originalPushState.apply(this, args);\n notifyLocationChange();\n return result;\n };\n\n const originalReplaceState = window.history.replaceState;\n window.history.replaceState = function replaceState(...args) {\n const result = originalReplaceState.apply(this, args);\n notifyLocationChange();\n return result;\n };\n\n historyPatched = true;\n}\n\nfunction useCurrentHref(): string {\n const [href, setHref] = useState(\n typeof window !== 'undefined' ? window.location.href : '/',\n );\n\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n\n patchHistoryForLocationTracking();\n\n const updateHref = () => {\n setHref(window.location.href);\n };\n\n updateHref();\n window.addEventListener('popstate', updateHref);\n window.addEventListener('hashchange', updateHref);\n window.addEventListener(ATHENA_LOCATION_CHANGE_EVENT, updateHref);\n\n return () => {\n window.removeEventListener('popstate', updateHref);\n window.removeEventListener('hashchange', updateHref);\n window.removeEventListener(ATHENA_LOCATION_CHANGE_EVENT, updateHref);\n };\n }, []);\n\n return href;\n}\n\n// ─── Internal Bridge ──────────────────────────────────────────────────\n\n/**\n * Reads PropelAuth state via hooks and maps it into the SDK's\n * `AthenaAuthState`, which is placed on `AthenaAuthContext`.\n */\nfunction AthenaAuthBridge({\n children,\n displayWhileLoading,\n}: {\n children: ReactNode;\n displayWhileLoading?: ReactNode;\n}) {\n const authInfo = useAuthInfo();\n const logoutFn = useLogoutFunction();\n const logoutFnRef = useRef(logoutFn);\n logoutFnRef.current = logoutFn;\n const prevAuthStateRef = useRef<AthenaAuthState | null>(null);\n const authInfoRef = useRef<PropelAuthTokenSnapshot>(authInfo);\n authInfoRef.current = authInfo;\n // One getter for the provider's lifetime: it reads the latest PropelAuth\n // snapshot, so its identity never changes and never re-renders consumers.\n const [getToken] = useState(() => propelAuthTokenGetter(() => authInfoRef.current));\n\n const authState: AthenaAuthState = useMemo(() => {\n if (authInfo.loading) {\n prevAuthStateRef.current = null;\n return {\n isLoggedIn: false,\n isLoading: true,\n user: null,\n accessToken: null,\n orgs: [],\n logout: async () => {},\n getToken,\n };\n }\n\n if (!authInfo.isLoggedIn) {\n prevAuthStateRef.current = null;\n return {\n isLoggedIn: false,\n isLoading: false,\n user: null,\n accessToken: null,\n orgs: [],\n logout: async (redirect = true) => logoutFnRef.current(redirect),\n getToken,\n };\n }\n\n // Referential stability: if the token and user identity haven't changed,\n // return the previous state object to prevent cascading context re-renders\n // from PropelAuth's focus-triggered token checks.\n const prev = prevAuthStateRef.current;\n if (\n prev?.isLoggedIn &&\n !prev.isLoading &&\n prev.accessToken === authInfo.accessToken &&\n prev.user?.userId === authInfo.user.userId\n ) {\n return prev;\n }\n\n const user: AthenaUser = {\n userId: authInfo.user.userId,\n email: authInfo.user.email,\n firstName: authInfo.user.firstName ?? undefined,\n lastName: authInfo.user.lastName ?? undefined,\n username: authInfo.user.username ?? undefined,\n pictureUrl: authInfo.user.pictureUrl ?? undefined,\n properties: authInfo.user.properties,\n };\n\n const orgs: AthenaOrg[] =\n authInfo.orgHelper?.getOrgs().map((org) => ({\n orgId: org.orgId,\n orgName: org.orgName,\n urlSafeOrgName: org.urlSafeOrgName,\n })) ?? [];\n\n const newState: AthenaAuthState = {\n isLoggedIn: true,\n isLoading: false,\n user,\n accessToken: authInfo.accessToken,\n orgs,\n logout: async (redirect = true) => logoutFnRef.current(redirect),\n getToken,\n };\n prevAuthStateRef.current = newState;\n return newState;\n // logoutFn intentionally excluded — captured via logoutFnRef for\n // referential stability while always calling the latest function.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [authInfo, getToken]);\n\n if (authState.isLoading) {\n return <>{displayWhileLoading ?? null}</>;\n }\n\n return (\n <AthenaAuthContext.Provider value={authState}>\n {children}\n </AthenaAuthContext.Provider>\n );\n}\n\n// ─── Public Provider ──────────────────────────────────────────────────\n\n/**\n * Wraps your app with Athena authentication powered by PropelAuth.\n *\n * Place this **above** `<AthenaProvider>` in the component tree.\n * When present, `AthenaProvider` will automatically use the access token\n * from this provider — no need to pass `token` or `apiKey` manually.\n *\n * @example\n * ```tsx\n * import { AthenaAuthProvider } from '@athenaintel/react/auth';\n * import { AthenaProvider, AthenaChat } from '@athenaintel/react';\n *\n * function App() {\n * return (\n * <AthenaAuthProvider authUrl=\"https://auth.yourdomain.com\">\n * <AthenaProvider>\n * <AthenaChat />\n * </AthenaProvider>\n * </AthenaAuthProvider>\n * );\n * }\n * ```\n */\nexport function AthenaAuthProvider({\n children,\n authUrl,\n postLoginRedirectUrl,\n displayWhileLoading,\n}: AthenaAuthProviderProps) {\n const currentHref = useCurrentHref();\n const redirectUrl = postLoginRedirectUrl ?? currentHref;\n\n return (\n <RequiredAuthProvider\n authUrl={authUrl}\n displayWhileLoading={\n displayWhileLoading ? <>{displayWhileLoading}</> : undefined\n }\n displayIfLoggedOut={<RedirectToLogin postLoginRedirectUrl={redirectUrl} />}\n >\n <AthenaAuthBridge displayWhileLoading={displayWhileLoading}>\n {children}\n </AthenaAuthBridge>\n </RequiredAuthProvider>\n );\n}\n"],"names":["useState","useEffect","useAuthInfo","useLogoutFunction","useRef","useMemo","jsx","Fragment","AthenaAuthContext","RequiredAuthProvider","RedirectToLogin"],"mappings":";;;;;;AA8BO,SAAS,sBACd,MAC4B;AAC5B,SAAO,OAAO,EAAE,QAAQ,MAAA,IA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BAAAA,IAACI,MAAAA,iBAAA,EAAgB,sBAAsB,YAAA,CAAa;AAAA,MAExE,UAAAJ,2BAAAA,IAAC,kBAAA,EAAiB,qBACf,SAAA,CACH;AAAA,IAAA;AAAA,EAAA;AAGN;;;"}
1
+ {"version":3,"file":"AthenaAuthProvider.cjs","sources":["../../src/auth/AthenaAuthProvider.tsx"],"sourcesContent":["import {\n RequiredAuthProvider,\n RedirectToLogin,\n useAuthInfo,\n useLogoutFunction,\n} from '@propelauth/react';\nimport type { ReactNode } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { AthenaAuthContext } from './AthenaAuthContext';\nimport type { AthenaAuthState, AthenaOrg, AthenaUser } from './types';\n\n/** The part of a PropelAuth `useAuthInfo()` snapshot the token getter reads. */\nexport interface PropelAuthTokenSnapshot {\n loading: boolean;\n isLoggedIn: boolean | undefined;\n accessToken: string | null | undefined;\n /** Absent on `@propelauth/react` releases that predate it. */\n refreshAuthInfo?: () => Promise<void>;\n /** Absent on `@propelauth/react` releases that predate it. */\n tokens?: { getAccessToken?: () => Promise<string | undefined> };\n}\n\n/**\n * The PropelAuth side of the SDK's credential source. `force` (the previous\n * token was refused) makes PropelAuth mint a new token first; either way the\n * token comes from PropelAuth's own `getAccessToken`, which renews one that is\n * about to expire. A failed renewal keeps the held token, so the caller's\n * attempt is refused by the host rather than failing in the client.\n */\nexport function propelAuthTokenGetter(\n read: () => PropelAuthTokenSnapshot,\n): AthenaStatewireTokenGetter {\n return async ({ force = false } = {}) => {\n const info = read();\n if (info.loading || !info.isLoggedIn) return null;\n if (force) {\n try {\n await info.refreshAuthInfo?.();\n } catch {\n // Keep the held token; the host decides.\n }\n }\n const latest = read();\n let fresh: string | undefined;\n try {\n fresh = await latest.tokens?.getAccessToken?.();\n } catch {\n fresh = undefined;\n }\n return fresh ?? (latest.isLoggedIn ? (latest.accessToken ?? null) : null);\n };\n}\n\n// ─── Props ────────────────────────────────────────────────────────────\n\nexport interface AthenaAuthProviderProps {\n children: ReactNode;\n\n /**\n * Your PropelAuth auth URL (e.g. `https://auth.yourdomain.com`).\n * Found in the PropelAuth dashboard under Frontend Integration.\n */\n authUrl: string;\n\n /**\n * Where to redirect after a successful login.\n * Defaults to the current page URL.\n */\n postLoginRedirectUrl?: string;\n\n /**\n * Custom element displayed while the auth state is loading.\n * Defaults to `null` (renders nothing).\n */\n displayWhileLoading?: ReactNode;\n}\n\nconst ATHENA_LOCATION_CHANGE_EVENT = 'athena:location-change';\nlet historyPatched = false;\n\nfunction patchHistoryForLocationTracking(): void {\n if (historyPatched || typeof window === 'undefined') {\n return;\n }\n\n const notifyLocationChange = () => {\n window.dispatchEvent(new Event(ATHENA_LOCATION_CHANGE_EVENT));\n };\n\n const originalPushState = window.history.pushState;\n window.history.pushState = function pushState(...args) {\n const result = originalPushState.apply(this, args);\n notifyLocationChange();\n return result;\n };\n\n const originalReplaceState = window.history.replaceState;\n window.history.replaceState = function replaceState(...args) {\n const result = originalReplaceState.apply(this, args);\n notifyLocationChange();\n return result;\n };\n\n historyPatched = true;\n}\n\nfunction useCurrentHref(): string {\n const [href, setHref] = useState(\n typeof window !== 'undefined' ? window.location.href : '/',\n );\n\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n\n patchHistoryForLocationTracking();\n\n const updateHref = () => {\n setHref(window.location.href);\n };\n\n updateHref();\n window.addEventListener('popstate', updateHref);\n window.addEventListener('hashchange', updateHref);\n window.addEventListener(ATHENA_LOCATION_CHANGE_EVENT, updateHref);\n\n return () => {\n window.removeEventListener('popstate', updateHref);\n window.removeEventListener('hashchange', updateHref);\n window.removeEventListener(ATHENA_LOCATION_CHANGE_EVENT, updateHref);\n };\n }, []);\n\n return href;\n}\n\n// ─── Internal Bridge ──────────────────────────────────────────────────\n\n/**\n * Reads PropelAuth state via hooks and maps it into the SDK's\n * `AthenaAuthState`, which is placed on `AthenaAuthContext`.\n */\nfunction AthenaAuthBridge({\n children,\n displayWhileLoading,\n}: {\n children: ReactNode;\n displayWhileLoading?: ReactNode;\n}) {\n const authInfo = useAuthInfo();\n const logoutFn = useLogoutFunction();\n const logoutFnRef = useRef(logoutFn);\n logoutFnRef.current = logoutFn;\n const prevAuthStateRef = useRef<AthenaAuthState | null>(null);\n const authInfoRef = useRef<PropelAuthTokenSnapshot>(authInfo);\n authInfoRef.current = authInfo;\n // One getter for the provider's lifetime: it reads the latest PropelAuth\n // snapshot, so its identity never changes and never re-renders consumers.\n const [getToken] = useState(() => propelAuthTokenGetter(() => authInfoRef.current));\n\n const authState: AthenaAuthState = useMemo(() => {\n if (authInfo.loading) {\n prevAuthStateRef.current = null;\n return {\n isLoggedIn: false,\n isLoading: true,\n user: null,\n accessToken: null,\n orgs: [],\n logout: async () => {},\n getToken,\n };\n }\n\n if (!authInfo.isLoggedIn) {\n prevAuthStateRef.current = null;\n return {\n isLoggedIn: false,\n isLoading: false,\n user: null,\n accessToken: null,\n orgs: [],\n logout: async (redirect = true) => logoutFnRef.current(redirect),\n getToken,\n };\n }\n\n // Referential stability: if the token and user identity haven't changed,\n // return the previous state object to prevent cascading context re-renders\n // from PropelAuth's focus-triggered token checks.\n const prev = prevAuthStateRef.current;\n if (\n prev?.isLoggedIn &&\n !prev.isLoading &&\n prev.accessToken === authInfo.accessToken &&\n prev.user?.userId === authInfo.user.userId\n ) {\n return prev;\n }\n\n const user: AthenaUser = {\n userId: authInfo.user.userId,\n email: authInfo.user.email,\n firstName: authInfo.user.firstName ?? undefined,\n lastName: authInfo.user.lastName ?? undefined,\n username: authInfo.user.username ?? undefined,\n pictureUrl: authInfo.user.pictureUrl ?? undefined,\n properties: authInfo.user.properties,\n };\n\n const orgs: AthenaOrg[] =\n authInfo.orgHelper?.getOrgs().map((org) => ({\n orgId: org.orgId,\n orgName: org.orgName,\n urlSafeOrgName: org.urlSafeOrgName,\n })) ?? [];\n\n const newState: AthenaAuthState = {\n isLoggedIn: true,\n isLoading: false,\n user,\n accessToken: authInfo.accessToken,\n orgs,\n logout: async (redirect = true) => logoutFnRef.current(redirect),\n getToken,\n };\n prevAuthStateRef.current = newState;\n return newState;\n // logoutFn intentionally excluded — captured via logoutFnRef for\n // referential stability while always calling the latest function.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [authInfo, getToken]);\n\n if (authState.isLoading) {\n return <>{displayWhileLoading ?? null}</>;\n }\n\n return (\n <AthenaAuthContext.Provider value={authState}>\n {children}\n </AthenaAuthContext.Provider>\n );\n}\n\n// ─── Public Provider ──────────────────────────────────────────────────\n\n/**\n * Wraps your app with Athena authentication powered by PropelAuth.\n *\n * Place this **above** `<AthenaProvider>` in the component tree.\n * When present, `AthenaProvider` will automatically use the access token\n * from this provider — no need to pass `token` or `apiKey` manually.\n *\n * @example\n * ```tsx\n * import { AthenaAuthProvider } from '@athenaintel/react/auth';\n * import { AthenaProvider, AthenaChat } from '@athenaintel/react';\n *\n * function App() {\n * return (\n * <AthenaAuthProvider authUrl=\"https://auth.yourdomain.com\">\n * <AthenaProvider>\n * <AthenaChat />\n * </AthenaProvider>\n * </AthenaAuthProvider>\n * );\n * }\n * ```\n */\nexport function AthenaAuthProvider({\n children,\n authUrl,\n postLoginRedirectUrl,\n displayWhileLoading,\n}: AthenaAuthProviderProps) {\n const currentHref = useCurrentHref();\n const redirectUrl = postLoginRedirectUrl ?? currentHref;\n\n return (\n <RequiredAuthProvider\n authUrl={authUrl}\n displayWhileLoading={\n displayWhileLoading ? <>{displayWhileLoading}</> : undefined\n }\n displayIfLoggedOut={<RedirectToLogin postLoginRedirectUrl={redirectUrl} />}\n >\n <AthenaAuthBridge displayWhileLoading={displayWhileLoading}>\n {children}\n </AthenaAuthBridge>\n </RequiredAuthProvider>\n );\n}\n"],"names":["useState","useEffect","useAuthInfo","useLogoutFunction","useRef","useMemo","jsx","Fragment","AthenaAuthContext","RequiredAuthProvider","RedirectToLogin"],"mappings":";;;;;;AA8BO,SAAS,sBACd,MAC4B;AAC5B,SAAO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IAAM;AAAA,MAErD,oBAAoBD,2BAAAA,IAACI,MAAAA,iBAAA,EAAgB,sBAAsB,YAAA,CAAa;AAAA,MAExE,UAAAJ,2BAAAA,IAAC,kBAAA,EAAiB,qBACf,SAAA,CACH;AAAA,IAAA;AAAA,EAAA;AAGN;;;"}
@@ -1,19 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const react = require("react");
4
- const AthenaCredentialSourceContext = react.createContext(null);
3
+ const require$$0 = require("react");
4
+ const AthenaCredentialSourceContext = require$$0.createContext(null);
5
5
  function useAthenaCredentialSource() {
6
- return react.useContext(AthenaCredentialSourceContext);
6
+ return require$$0.useContext(AthenaCredentialSourceContext);
7
7
  }
8
8
  function useAthenaCredentialIdentityEpoch() {
9
9
  const credentials = useAthenaCredentialSource();
10
- const subscribe = react.useCallback(
10
+ const subscribe = require$$0.useCallback(
11
11
  (onChange) => credentials ? credentials.subscribe(onChange) : () => {
12
12
  },
13
13
  [credentials]
14
14
  );
15
15
  const read = () => (credentials == null ? void 0 : credentials.identityEpoch()) ?? 0;
16
- return react.useSyncExternalStore(subscribe, read, read);
16
+ return require$$0.useSyncExternalStore(subscribe, read, read);
17
17
  }
18
18
  exports.AthenaCredentialSourceContext = AthenaCredentialSourceContext;
19
19
  exports.useAthenaCredentialIdentityEpoch = useAthenaCredentialIdentityEpoch;
@@ -1 +1 @@
1
- {"version":3,"file":"AthenaCredentialSourceContext.cjs","sources":["../../src/auth/AthenaCredentialSourceContext.ts"],"sourcesContent":["import { createContext, useCallback, useContext, useSyncExternalStore } from 'react';\nimport type { AthenaCredentialSource } from './credential-source';\n\n/**\n * The provider's credential source (see `createAthenaCredentialSource`), for\n * the SDK's own connections that must restart when a new token arrives.\n * Internal: hosts read tokens through `useAthenaConfig().getToken`.\n */\nexport const AthenaCredentialSourceContext = createContext<AthenaCredentialSource | null>(null);\n\nexport function useAthenaCredentialSource(): AthenaCredentialSource | null {\n return useContext(AthenaCredentialSourceContext);\n}\n\n/**\n * The credential source's identity epoch (see `identityEpoch`): a number that\n * changes when someone else signs in, not when a token is renewed. `0`\n * outside a provider.\n */\nexport function useAthenaCredentialIdentityEpoch(): number {\n const credentials = useAthenaCredentialSource();\n const subscribe = useCallback(\n (onChange: () => void) => (credentials ? credentials.subscribe(onChange) : () => {}),\n [credentials],\n );\n const read = () => credentials?.identityEpoch() ?? 0;\n return useSyncExternalStore(subscribe, read, read);\n}\n"],"names":["createContext","useContext","useCallback","useSyncExternalStore"],"mappings":";;;AAQO,MAAM,gCAAgCA,MAAAA,cAA6C,IAAI;AAEvF,SAAS,4BAA2D;AACzE,SAAOC,MAAAA,WAAW,6BAA6B;AACjD;AAOO,SAAS,mCAA2C;AACzD,QAAM,cAAc,0BAAA;AACpB,QAAM,YAAYC,MAAAA;AAAAA,IAChB,CAAC,aAA0B,cAAc,YAAY,UAAU,QAAQ,IAAI,MAAM;AAAA,IAAC;AAAA,IAClF,CAAC,WAAW;AAAA,EAAA;AAEd,QAAM,OAAO,OAAM,2CAAa,oBAAmB;AACnD,SAAOC,2BAAqB,WAAW,MAAM,IAAI;AACnD;;;;"}
1
+ {"version":3,"file":"AthenaCredentialSourceContext.cjs","sources":["../../src/auth/AthenaCredentialSourceContext.ts"],"sourcesContent":["import { createContext, useCallback, useContext, useSyncExternalStore } from 'react';\nimport type { AthenaCredentialSource } from './credential-source';\n\n/**\n * The provider's credential source (see `createAthenaCredentialSource`), for\n * the SDK's own connections that must restart when a new token arrives.\n * Internal: hosts read tokens through `useAthenaConfig().getToken`.\n */\nexport const AthenaCredentialSourceContext = createContext<AthenaCredentialSource | null>(null);\n\nexport function useAthenaCredentialSource(): AthenaCredentialSource | null {\n return useContext(AthenaCredentialSourceContext);\n}\n\n/**\n * The credential source's identity epoch (see `identityEpoch`): a number that\n * changes when someone else signs in, not when a token is renewed. `0`\n * outside a provider.\n */\nexport function useAthenaCredentialIdentityEpoch(): number {\n const credentials = useAthenaCredentialSource();\n const subscribe = useCallback(\n (onChange: () => void) => (credentials ? credentials.subscribe(onChange) : () => {}),\n [credentials],\n );\n const read = () => credentials?.identityEpoch() ?? 0;\n return useSyncExternalStore(subscribe, read, read);\n}\n"],"names":["createContext","useContext","useCallback","useSyncExternalStore"],"mappings":";;;AAQO,MAAM,gCAAgCA,WAAAA,cAA6C,IAAI;AAEvF,SAAS,4BAA2D;AACzE,SAAOC,WAAAA,WAAW,6BAA6B;AACjD;AAOO,SAAS,mCAA2C;AACzD,QAAM,cAAc,0BAAA;AACpB,QAAM,YAAYC,WAAAA;AAAAA,IAChB,CAAC,aAA0B,cAAc,YAAY,UAAU,QAAQ,IAAI,MAAM;AAAA,IAAC;AAAA,IAClF,CAAC,WAAW;AAAA,EAAA;AAEd,QAAM,OAAO,OAAM,2CAAa,oBAAmB;AACnD,SAAOC,gCAAqB,WAAW,MAAM,IAAI;AACnD;;;;"}
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const jsxRuntime = require("react/jsx-runtime");
4
4
  const reactQuery = require("@tanstack/react-query");
5
- const react = require("react");
5
+ const require$$0 = require("react");
6
6
  const athenaDiagnostics = require("../diagnostics/athena-diagnostics.cjs");
7
7
  const errors = require("../diagnostics/errors.cjs");
8
8
  const auth = require("../runtime/auth.cjs");
@@ -179,12 +179,12 @@ function AthenaSSOProvider({
179
179
  revalidateOnWindowFocus = false,
180
180
  retryPolicy = SSO_USERINFO_RETRY_POLICY
181
181
  }) {
182
- const [queryClient] = react.useState(() => new reactQuery.QueryClient());
183
- const retryPolicyRef = react.useRef(retryPolicy);
182
+ const [queryClient] = require$$0.useState(() => new reactQuery.QueryClient());
183
+ const retryPolicyRef = require$$0.useRef(retryPolicy);
184
184
  retryPolicyRef.current = retryPolicy;
185
- const onErrorRef = react.useRef(onError);
185
+ const onErrorRef = require$$0.useRef(onError);
186
186
  onErrorRef.current = onError;
187
- const ssoUrls = react.useMemo(
187
+ const ssoUrls = require$$0.useMemo(
188
188
  () => ({
189
189
  userInfo: resolveSSOUrl({
190
190
  baseUrl: ssoBaseUrl,
@@ -204,8 +204,8 @@ function AthenaSSOProvider({
204
204
  }),
205
205
  [ssoBaseUrl, ssoUserInfoUrl, ssoLoginUrl, ssoLogoutUrl]
206
206
  );
207
- const queryKey = react.useMemo(() => ["athena-sdk", "sso-session", ssoUrls.userInfo], [ssoUrls.userInfo]);
208
- const queryFn = react.useCallback(
207
+ const queryKey = require$$0.useMemo(() => ["athena-sdk", "sso-session", ssoUrls.userInfo], [ssoUrls.userInfo]);
208
+ const queryFn = require$$0.useCallback(
209
209
  async ({ signal }) => {
210
210
  var _a;
211
211
  try {
@@ -244,7 +244,7 @@ function AthenaSSOProvider({
244
244
  const loading = query.isPending;
245
245
  const reason = session ? null : (answer == null ? void 0 : answer.kind) === "no_session" ? answer.reason : query.isError ? "request_failed" : null;
246
246
  const signedOut = (answer == null ? void 0 : answer.kind) === "no_session" && answer.signedOut === true;
247
- react.useEffect(() => {
247
+ require$$0.useEffect(() => {
248
248
  if (!revalidateOnWindowFocus || typeof window === "undefined") {
249
249
  return;
250
250
  }
@@ -263,15 +263,15 @@ function AthenaSSOProvider({
263
263
  document.removeEventListener("visibilitychange", handleVisibilityChange);
264
264
  };
265
265
  }, [revalidateOnWindowFocus, queryClient, queryKey]);
266
- react.useEffect(() => {
266
+ require$$0.useEffect(() => {
267
267
  if (!loading && reason === "unauthenticated" && !signedOut && !displayOnError && typeof window !== "undefined") {
268
268
  window.location.assign(ssoUrls.login);
269
269
  }
270
270
  }, [loading, reason, signedOut, displayOnError, ssoUrls.login]);
271
- const retry = react.useCallback(() => {
271
+ const retry = require$$0.useCallback(() => {
272
272
  void queryClient.resetQueries({ queryKey });
273
273
  }, [queryClient, queryKey]);
274
- const logout = react.useCallback(async (redirectOnLogout = true) => {
274
+ const logout = require$$0.useCallback(async (redirectOnLogout = true) => {
275
275
  await queryClient.cancelQueries({ queryKey });
276
276
  try {
277
277
  await fetch(ssoUrls.logout, {
@@ -290,9 +290,9 @@ function AthenaSSOProvider({
290
290
  window.location.assign(ssoUrls.login);
291
291
  }
292
292
  }, [queryClient, queryKey, ssoUrls.login, ssoUrls.logout]);
293
- const sessionRef = react.useRef(session);
293
+ const sessionRef = require$$0.useRef(session);
294
294
  sessionRef.current = session;
295
- const getToken = react.useCallback(
295
+ const getToken = require$$0.useCallback(
296
296
  async ({ force = false } = {}) => {
297
297
  var _a;
298
298
  if (force) {
@@ -312,7 +312,7 @@ function AthenaSSOProvider({
312
312
  },
313
313
  [queryClient, queryKey, queryFn]
314
314
  );
315
- const authState = react.useMemo(() => {
315
+ const authState = require$$0.useMemo(() => {
316
316
  if (loading) {
317
317
  return {
318
318
  isLoggedIn: false,
@@ -1 +1 @@
1
- {"version":3,"file":"AthenaSSOProvider.cjs","sources":["../../src/auth/AthenaSSOProvider.tsx"],"sourcesContent":["import { QueryClient, useQuery } from '@tanstack/react-query';\nimport type { ReactNode } from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport {\n DEFAULT_MINT_RETRY_POLICY,\n getMintRetryDelay,\n isRetryableMintStatus,\n type MintRetryPolicy,\n} from '../runtime/auth';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { AthenaAuthContext } from './AthenaAuthContext';\nimport type {\n AthenaAuthState,\n AthenaOrg,\n AthenaSSOUserInfo,\n AthenaUser,\n} from './types';\n\n// ─── Props ────────────────────────────────────────────────────────────\n\nexport interface AthenaSSOProviderProps {\n children: ReactNode;\n\n /**\n * Base URL used to resolve the Athena SSO endpoints.\n *\n * When omitted, the provider defaults to same-origin relative paths:\n * `/api/sso/userinfo`, `/api/sso/initiate`, and `/api/sso/logout`.\n *\n * Use this when your frontend and backend live on different origins\n * (for example `https://app.example.com` + `https://api.example.com`).\n */\n ssoBaseUrl?: string;\n\n /**\n * Optional override for the SSO user-info endpoint that returns the\n * authenticated user's data and access token.\n *\n * The endpoint must return JSON matching `AthenaSSOUserInfo`:\n * ```json\n * {\n * \"user\": { \"user_id\": \"…\", \"email\": \"…\", … },\n * \"orgMemberInfos\": [{ \"orgId\": \"…\", \"orgName\": \"…\", \"urlSafeOrgName\": \"…\" }],\n * \"accessToken\": \"…\"\n * }\n * ```\n *\n * The request is sent with `credentials: 'include'` so that\n * session cookies are forwarded automatically.\n */\n ssoUserInfoUrl?: string;\n\n /**\n * Optional override for the URL to redirect the user to when no valid\n * SSO session exists.\n * This is typically the SSO initiation endpoint on your backend\n * (e.g. `https://api.yourdomain.com/api/sso/initiate`).\n */\n ssoLoginUrl?: string;\n\n /**\n * Optional override for the backend SSO logout endpoint.\n * Defaults to `/api/sso/logout` (or `${ssoBaseUrl}/api/sso/logout`).\n */\n ssoLogoutUrl?: string;\n\n /**\n * Custom element displayed while the SSO session is being verified.\n * Defaults to `null` (renders nothing).\n */\n displayWhileLoading?: ReactNode;\n\n /**\n * Shown when there is no session to sign the app in with: an element, or a\n * function that receives why (`reason`) and a `retry`, so the app can offer\n * sign-in only to a person who is signed out and a retry when the endpoint\n * could not answer (see `AthenaSSOFailure`).\n * If not provided, the user is automatically redirected to `ssoLoginUrl`\n * when the endpoint answers that there is no session.\n */\n displayOnError?: ReactNode | ((failure: AthenaSSOFailure) => ReactNode);\n\n /**\n * Called with the typed error (`auth_sso_failed`) when a session read gives\n * up. A nested `AthenaProvider`'s `onError` is not mounted while the first\n * read runs, so observe sign-in failures here.\n */\n onError?: (error: AthenaSdkError) => void;\n\n /**\n * Re-validate the SSO session when the window regains focus.\n * Disabled by default. When enabled, token expiry and user switching\n * are picked up without requiring a full page reload.\n */\n revalidateOnWindowFocus?: boolean;\n\n /** @internal Overrides how a session read retries; used by tests. */\n retryPolicy?: MintRetryPolicy;\n}\n\n/**\n * Why the provider has no session.\n *\n * - `unauthenticated`: the endpoint answered 401 or 403, or the person signed\n * out. Offer sign-in.\n * - `request_failed`: the endpoint did not answer usably. A network error, a\n * timeout, or a 5xx / 408 / 429 on every attempt of one read, or another\n * status. The person may well be signed in. Offer `retry`.\n * - `invalid_response`: it answered without a usable session.\n */\nexport type AthenaSSOFailureReason = 'unauthenticated' | 'invalid_response' | 'request_failed';\n\n/** What `displayOnError` receives when it is a function. */\nexport interface AthenaSSOFailure {\n reason: AthenaSSOFailureReason;\n /** Read the session again. `displayWhileLoading` shows meanwhile. */\n retry: () => void;\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * How one session read retries: the parent bridge's mint policy (Marathon's\n * `/api/sso/userinfo` and `/_athena/auth` mint the same credential), with a\n * longer wait per request, since every request mints and a slow answer is\n * still an answer.\n */\nconst SSO_USERINFO_RETRY_POLICY: MintRetryPolicy = {\n ...DEFAULT_MINT_RETRY_POLICY,\n timeoutMs: 10_000,\n};\n\n/** One userinfo request, classified. */\ntype UserInfoAttempt =\n | { kind: 'session'; data: AthenaSSOUserInfo }\n | { kind: 'unauthenticated' }\n | { kind: 'invalid_response' }\n /** A status it does not retry, or a 2xx whose body is not JSON. */\n | { kind: 'failed'; status: number }\n | {\n kind: 'transient';\n status: number | null;\n reason: 'status' | 'network' | 'timeout';\n cause?: unknown;\n };\n\nconst abortError = () => new DOMException('The session read was cancelled.', 'AbortError');\n\n/** One userinfo request. Throws an `AbortError` when `signal` cancels the read. */\nasync function readUserInfoOnce({\n url,\n signal,\n timeoutMs,\n}: {\n url: string;\n signal: AbortSignal;\n timeoutMs: number;\n}): Promise<UserInfoAttempt> {\n if (signal.aborted) throw abortError();\n const request = new AbortController();\n const cancel = () => request.abort();\n signal.addEventListener('abort', cancel, { once: true });\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n request.abort();\n }, timeoutMs);\n\n try {\n const response = await fetch(url, { credentials: 'include', signal: request.signal });\n if (response.status === 401 || response.status === 403) return { kind: 'unauthenticated' };\n if (!response.ok) {\n return isRetryableMintStatus(response.status)\n ? { kind: 'transient', status: response.status, reason: 'status' }\n : { kind: 'failed', status: response.status };\n }\n\n let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n if (signal.aborted) throw abortError();\n return timedOut\n ? { kind: 'transient', status: null, reason: 'timeout', cause: error }\n : { kind: 'failed', status: response.status };\n }\n return isValidSSOUserInfo(data) ? { kind: 'session', data } : { kind: 'invalid_response' };\n } catch (error) {\n if (signal.aborted) throw abortError();\n return { kind: 'transient', status: null, reason: timedOut ? 'timeout' : 'network', cause: error };\n } finally {\n clearTimeout(timer);\n signal.removeEventListener('abort', cancel);\n }\n}\n\n/**\n * What a read concluded, as the query holds it. A read that could not answer\n * throws instead (`request_failed`), so an earlier answer stays.\n */\ntype SessionAnswer =\n | { kind: 'session'; data: AthenaSSOUserInfo }\n | {\n kind: 'no_session';\n reason: Exclude<AthenaSSOFailureReason, 'request_failed'>;\n /** The person signed out here (`logout`), rather than the endpoint answering no session. */\n signedOut?: true;\n };\n\n/**\n * One session read: one bounded cycle of userinfo requests. A transient\n * failure is retried with `policy`'s capped, jittered backoff; a read that\n * gives up throws the typed error it reports. Throws an `AbortError` when\n * `signal` cancels the read.\n */\nasync function readSession({\n url,\n signal,\n policy,\n}: {\n url: string;\n signal: AbortSignal;\n policy: MintRetryPolicy;\n}): Promise<SessionAnswer> {\n const maxAttempts = Math.max(1, Math.floor(policy.maxAttempts));\n for (let attempts = 1; ; attempts += 1) {\n const attempt = await readUserInfoOnce({ url, signal, timeoutMs: policy.timeoutMs });\n\n if (attempt.kind === 'session') return { kind: 'session', data: attempt.data };\n if (attempt.kind === 'unauthenticated') return { kind: 'no_session', reason: 'unauthenticated' };\n if (attempt.kind === 'invalid_response') {\n console.error(\n '[AthenaSDK] Invalid SSO userinfo response: expected \"user.user_id\", \"user.email\", \"orgMemberInfos\", and \"accessToken\"',\n );\n return { kind: 'no_session', reason: 'invalid_response' };\n }\n\n if (attempt.kind === 'transient' && attempts < maxAttempts) {\n const delayMs = getMintRetryDelay({ retry: attempts, policy });\n athenaDiagnostics.emit('auth.sso.userinfo.retry', {\n level: 'warn',\n data: {\n status: attempt.status,\n reason: attempt.reason,\n attempt: attempts,\n max_attempts: maxAttempts,\n delay_ms: delayMs,\n },\n });\n await waitBeforeRetry({ delayMs, signal });\n continue;\n }\n\n throw sessionReadError({ url, attempt, attempts });\n }\n}\n\n/** The backoff between two requests of one read; cancelling the read ends it at once. */\nfunction waitBeforeRetry({ delayMs, signal }: { delayMs: number; signal: AbortSignal }): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(abortError());\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortError());\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, delayMs);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** The typed error a read reports when it gives up without an answer about the session. */\nfunction sessionReadError({\n url,\n attempt,\n attempts,\n}: {\n url: string;\n attempt: Extract<UserInfoAttempt, { kind: 'failed' | 'transient' }>;\n attempts: number;\n}): AthenaSdkError {\n if (attempt.kind === 'failed') {\n const unreadable = attempt.status >= 200 && attempt.status < 300;\n return new AthenaSdkError({\n code: 'auth_sso_failed',\n message: unreadable\n ? `The SSO session read (${url}) answered HTTP ${attempt.status} without a JSON body.`\n : `The SSO session read (${url}) answered HTTP ${attempt.status}.`,\n hint: 'Check that ssoBaseUrl / ssoUserInfoUrl point at the SSO userinfo endpoint.',\n status: attempt.status,\n context: { attempts, reason: unreadable ? 'invalid_body' : 'status' },\n });\n }\n const answer =\n attempt.status !== null\n ? `HTTP ${attempt.status}`\n : attempt.reason === 'timeout'\n ? 'a timeout'\n : 'a network error';\n return new AthenaSdkError({\n code: 'auth_sso_failed',\n message: `The SSO session read (${url}) failed ${attempts} time${attempts === 1 ? '' : 's'} (last: ${answer}).`,\n hint: 'The sign-in service did not answer; the person may still be signed in. Offer a retry (displayOnError receives retry).',\n ...(attempt.status !== null && { status: attempt.status }),\n ...(attempt.cause !== undefined && { cause: attempt.cause }),\n context: { attempts, reason: attempt.reason },\n });\n}\n\nconst DEFAULT_SSO_PATHS = {\n userInfo: '/api/sso/userinfo',\n login: '/api/sso/initiate',\n logout: '/api/sso/logout',\n} as const;\n\nconst trimTrailingSlash = (value: string): string => value.replace(/\\/+$/, '');\n\nfunction resolveSSOUrl({\n baseUrl,\n overrideUrl,\n defaultPath,\n}: {\n baseUrl?: string;\n overrideUrl?: string;\n defaultPath: string;\n}): string {\n if (overrideUrl) {\n return overrideUrl;\n }\n\n if (!baseUrl) {\n return defaultPath;\n }\n\n return `${trimTrailingSlash(baseUrl)}${defaultPath}`;\n}\n\nfunction isValidSSOUserInfo(data: unknown): data is AthenaSSOUserInfo {\n if (!data || typeof data !== 'object') {\n return false;\n }\n\n const candidate = data as {\n accessToken?: unknown;\n orgMemberInfos?: unknown;\n user?: {\n user_id?: unknown;\n email?: unknown;\n };\n };\n\n return (\n typeof candidate.accessToken === 'string' &&\n Array.isArray(candidate.orgMemberInfos) &&\n !!candidate.user &&\n typeof candidate.user.user_id === 'string' &&\n typeof candidate.user.email === 'string'\n );\n}\n\n/** Map the backend SSO response to the SDK's user/org types. */\nfunction mapSSOResponse(data: AthenaSSOUserInfo): {\n user: AthenaUser;\n orgs: AthenaOrg[];\n accessToken: string;\n} {\n const user: AthenaUser = {\n userId: data.user.user_id,\n email: data.user.email,\n firstName: data.user.first_name || undefined,\n lastName: data.user.last_name || undefined,\n username: data.user.username || undefined,\n pictureUrl: data.user.picture_url || undefined,\n properties: data.user.properties,\n };\n\n const orgs: AthenaOrg[] = data.orgMemberInfos.map((org) => ({\n orgId: org.orgId,\n orgName: org.orgName,\n urlSafeOrgName: org.urlSafeOrgName,\n }));\n\n return { user, orgs, accessToken: data.accessToken };\n}\n\n// ─── Provider ─────────────────────────────────────────────────────────\n\n/**\n * Wraps your app with Athena authentication powered by an external SSO\n * identity provider (e.g. Microsoft Entra / Azure AD, Okta, etc.).\n *\n * The SSO login flow is handled entirely by your backend. This provider\n * verifies the session by fetching `ssoUserInfoUrl` and exposes the\n * same `AthenaAuthState` context that `AthenaAuthProvider` (PropelAuth)\n * provides, so downstream components like `<AthenaProvider>` and\n * `useAthenaAuth()` work identically.\n *\n * Place this **above** `<AthenaProvider>` in the component tree.\n *\n * @example\n * ```tsx\n * import { AthenaSSOProvider } from '@athenaintel/react/auth';\n * import { AthenaProvider, AthenaChat } from '@athenaintel/react';\n *\n * function App() {\n * return (\n * <AthenaSSOProvider\n * ssoUserInfoUrl=\"https://api.yourdomain.com/api/sso/userinfo\"\n * ssoLoginUrl=\"https://api.yourdomain.com/api/sso/initiate\"\n * >\n * <AthenaProvider>\n * <AthenaChat />\n * </AthenaProvider>\n * </AthenaSSOProvider>\n * );\n * }\n * ```\n */\nexport function AthenaSSOProvider({\n children,\n ssoBaseUrl,\n ssoUserInfoUrl,\n ssoLoginUrl,\n ssoLogoutUrl,\n displayWhileLoading,\n displayOnError,\n onError,\n revalidateOnWindowFocus = false,\n retryPolicy = SSO_USERINFO_RETRY_POLICY,\n}: AthenaSSOProviderProps) {\n // The provider's own client, never a host's: the session holds an access\n // token, and a host may persist its query cache.\n const [queryClient] = useState(() => new QueryClient());\n const retryPolicyRef = useRef(retryPolicy);\n retryPolicyRef.current = retryPolicy;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n\n const ssoUrls = useMemo(\n () => ({\n userInfo: resolveSSOUrl({\n baseUrl: ssoBaseUrl,\n overrideUrl: ssoUserInfoUrl,\n defaultPath: DEFAULT_SSO_PATHS.userInfo,\n }),\n login: resolveSSOUrl({\n baseUrl: ssoBaseUrl,\n overrideUrl: ssoLoginUrl,\n defaultPath: DEFAULT_SSO_PATHS.login,\n }),\n logout: resolveSSOUrl({\n baseUrl: ssoBaseUrl,\n overrideUrl: ssoLogoutUrl,\n defaultPath: DEFAULT_SSO_PATHS.logout,\n }),\n }),\n [ssoBaseUrl, ssoUserInfoUrl, ssoLoginUrl, ssoLogoutUrl],\n );\n\n const queryKey = useMemo(() => ['athena-sdk', 'sso-session', ssoUrls.userInfo], [ssoUrls.userInfo]);\n\n // One read is one bounded cycle (`readSession`). A read that gives up\n // throws, so the query keeps the session an earlier read answered: a failed\n // background revalidation or renewal does not sign the person out.\n const queryFn = useCallback(\n async ({ signal }: { signal: AbortSignal }): Promise<SessionAnswer> => {\n try {\n return await readSession({ url: ssoUrls.userInfo, signal, policy: retryPolicyRef.current });\n } catch (readError) {\n if (readError instanceof AthenaSdkError) {\n athenaDiagnostics.emit('auth.sso.userinfo.error', { error: readError });\n try {\n onErrorRef.current?.(readError);\n } catch (callbackError) {\n console.error('[AthenaSDK] AthenaSSOProvider onError threw', callbackError);\n }\n }\n throw readError;\n }\n },\n [ssoUrls.userInfo],\n );\n\n const query = useQuery(\n {\n queryKey,\n queryFn,\n // `readSession` retries a transient failure itself, with the bridge's\n // policy; the query never retries on top of it, and reads while the\n // browser reports itself offline too, so that policy decides.\n retry: false,\n networkMode: 'always',\n staleTime: Number.POSITIVE_INFINITY,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n },\n queryClient,\n );\n\n const answer = query.data;\n const session = answer?.kind === 'session' ? answer.data : null;\n const loading = query.isPending;\n const reason: AthenaSSOFailureReason | null = session\n ? null\n : answer?.kind === 'no_session'\n ? answer.reason\n : query.isError\n ? 'request_failed'\n : null;\n const signedOut = answer?.kind === 'no_session' && answer.signedOut === true;\n\n useEffect(() => {\n if (!revalidateOnWindowFocus || typeof window === 'undefined') {\n return;\n }\n\n // A revalidation joins a read already in flight (a renewal, the first\n // read) instead of cancelling it.\n const revalidate = () => {\n void queryClient.refetchQueries({ queryKey }, { cancelRefetch: false });\n };\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'visible') {\n revalidate();\n }\n };\n\n window.addEventListener('focus', revalidate);\n document.addEventListener('visibilitychange', handleVisibilityChange);\n\n return () => {\n window.removeEventListener('focus', revalidate);\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n };\n }, [revalidateOnWindowFocus, queryClient, queryKey]);\n\n // Redirect to SSO login when the endpoint answered no session and no error\n // UI was provided. Signing out redirects by itself, when asked to.\n useEffect(() => {\n if (\n !loading &&\n reason === 'unauthenticated' &&\n !signedOut &&\n !displayOnError &&\n typeof window !== 'undefined'\n ) {\n window.location.assign(ssoUrls.login);\n }\n }, [loading, reason, signedOut, displayOnError, ssoUrls.login]);\n\n const retry = useCallback(() => {\n void queryClient.resetQueries({ queryKey });\n }, [queryClient, queryKey]);\n\n const logout = useCallback(async (redirectOnLogout = true) => {\n await queryClient.cancelQueries({ queryKey });\n\n try {\n await fetch(ssoUrls.logout, {\n method: 'POST',\n credentials: 'include',\n });\n } catch (logoutError) {\n console.error('[AthenaSDK] Failed to invalidate SSO session during logout', logoutError);\n }\n\n queryClient.setQueryData<SessionAnswer>(queryKey, {\n kind: 'no_session',\n reason: 'unauthenticated',\n signedOut: true,\n });\n\n if (redirectOnLogout && typeof window !== 'undefined') {\n window.location.assign(ssoUrls.login);\n }\n }, [queryClient, queryKey, ssoUrls.login, ssoUrls.logout]);\n\n // The SSO side of the SDK's credential source: `force` (the previous token\n // was refused) reads the session again for a new token, joining a read\n // already in flight; otherwise, or when that read has no session to hand\n // back, the held one is served.\n const sessionRef = useRef(session);\n sessionRef.current = session;\n const getToken = useCallback<AthenaStatewireTokenGetter>(\n async ({ force = false } = {}) => {\n if (force) {\n try {\n const renewed = await queryClient.fetchQuery({\n queryKey,\n queryFn,\n staleTime: 0,\n retry: false,\n networkMode: 'always',\n });\n if (renewed.kind === 'session') return renewed.data.accessToken;\n } catch {\n // The read gave up (already reported) or was cancelled.\n }\n }\n return sessionRef.current?.accessToken ?? null;\n },\n [queryClient, queryKey, queryFn],\n );\n\n const authState: AthenaAuthState = useMemo(() => {\n if (loading) {\n return {\n isLoggedIn: false,\n isLoading: true,\n user: null,\n accessToken: null,\n orgs: [],\n logout: async () => {},\n getToken,\n };\n }\n\n if (!session) {\n return {\n isLoggedIn: false,\n isLoading: false,\n user: null,\n accessToken: null,\n orgs: [],\n logout,\n getToken,\n };\n }\n\n const { user, orgs, accessToken } = mapSSOResponse(session);\n\n return {\n isLoggedIn: true,\n isLoading: false,\n user,\n accessToken,\n orgs,\n logout,\n getToken,\n };\n }, [loading, session, logout, getToken]);\n\n if (authState.isLoading) {\n return <>{displayWhileLoading ?? null}</>;\n }\n\n if (!authState.isLoggedIn) {\n if (typeof displayOnError === 'function') {\n return <>{displayOnError({ reason: reason ?? 'unauthenticated', retry })}</>;\n }\n return displayOnError ? <>{displayOnError}</> : null;\n }\n\n return (\n <AthenaAuthContext.Provider value={authState}>\n {children}\n </AthenaAuthContext.Provider>\n );\n}\n"],"names":["DEFAULT_MINT_RETRY_POLICY","isRetryableMintStatus","getMintRetryDelay","athenaDiagnostics","AthenaSdkError","useState","QueryClient","useRef","useMemo","useCallback","useQuery","useEffect","jsx","Fragment","AthenaAuthContext"],"mappings":";;;;;;;;;AAiIA,MAAM,4BAA6C;AAAA,EACjD,GAAGA,KAAAA;AAAAA,EACH,WAAW;AACb;AAgBA,MAAM,aAAa,MAAM,IAAI,aAAa,mCAAmC,YAAY;AAGzF,eAAe,iBAAiB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAI6B;AAC3B,MAAI,OAAO,QAAS,OAAM,WAAA;AAC1B,QAAM,UAAU,IAAI,gBAAA;AACpB,QAAM,SAAS,MAAM,QAAQ,MAAA;AAC7B,SAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,MAAM;AACvD,MAAI,WAAW;AACf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,YAAQ,MAAA;AAAA,EACV,GAAG,SAAS;AAEZ,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,KAAK,EAAE,aAAa,WAAW,QAAQ,QAAQ,QAAQ;AACpF,QAAI,SAAS,WAAW,OAAO,SAAS,WAAW,IAAK,QAAO,EAAE,MAAM,kBAAA;AACvE,QAAI,CAAC,SAAS,IAAI;AAChB,aAAOC,KAAAA,sBAAsB,S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,kBAAkB,UAAlB,EAA2B,OAAO,WAChC,UACH;AAEJ;;"}
1
+ {"version":3,"file":"AthenaSSOProvider.cjs","sources":["../../src/auth/AthenaSSOProvider.tsx"],"sourcesContent":["import { QueryClient, useQuery } from '@tanstack/react-query';\nimport type { ReactNode } from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport {\n DEFAULT_MINT_RETRY_POLICY,\n getMintRetryDelay,\n isRetryableMintStatus,\n type MintRetryPolicy,\n} from '../runtime/auth';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { AthenaAuthContext } from './AthenaAuthContext';\nimport type {\n AthenaAuthState,\n AthenaOrg,\n AthenaSSOUserInfo,\n AthenaUser,\n} from './types';\n\n// ─── Props ────────────────────────────────────────────────────────────\n\nexport interface AthenaSSOProviderProps {\n children: ReactNode;\n\n /**\n * Base URL used to resolve the Athena SSO endpoints.\n *\n * When omitted, the provider defaults to same-origin relative paths:\n * `/api/sso/userinfo`, `/api/sso/initiate`, and `/api/sso/logout`.\n *\n * Use this when your frontend and backend live on different origins\n * (for example `https://app.example.com` + `https://api.example.com`).\n */\n ssoBaseUrl?: string;\n\n /**\n * Optional override for the SSO user-info endpoint that returns the\n * authenticated user's data and access token.\n *\n * The endpoint must return JSON matching `AthenaSSOUserInfo`:\n * ```json\n * {\n * \"user\": { \"user_id\": \"…\", \"email\": \"…\", … },\n * \"orgMemberInfos\": [{ \"orgId\": \"…\", \"orgName\": \"…\", \"urlSafeOrgName\": \"…\" }],\n * \"accessToken\": \"…\"\n * }\n * ```\n *\n * The request is sent with `credentials: 'include'` so that\n * session cookies are forwarded automatically.\n */\n ssoUserInfoUrl?: string;\n\n /**\n * Optional override for the URL to redirect the user to when no valid\n * SSO session exists.\n * This is typically the SSO initiation endpoint on your backend\n * (e.g. `https://api.yourdomain.com/api/sso/initiate`).\n */\n ssoLoginUrl?: string;\n\n /**\n * Optional override for the backend SSO logout endpoint.\n * Defaults to `/api/sso/logout` (or `${ssoBaseUrl}/api/sso/logout`).\n */\n ssoLogoutUrl?: string;\n\n /**\n * Custom element displayed while the SSO session is being verified.\n * Defaults to `null` (renders nothing).\n */\n displayWhileLoading?: ReactNode;\n\n /**\n * Shown when there is no session to sign the app in with: an element, or a\n * function that receives why (`reason`) and a `retry`, so the app can offer\n * sign-in only to a person who is signed out and a retry when the endpoint\n * could not answer (see `AthenaSSOFailure`).\n * If not provided, the user is automatically redirected to `ssoLoginUrl`\n * when the endpoint answers that there is no session.\n */\n displayOnError?: ReactNode | ((failure: AthenaSSOFailure) => ReactNode);\n\n /**\n * Called with the typed error (`auth_sso_failed`) when a session read gives\n * up. A nested `AthenaProvider`'s `onError` is not mounted while the first\n * read runs, so observe sign-in failures here.\n */\n onError?: (error: AthenaSdkError) => void;\n\n /**\n * Re-validate the SSO session when the window regains focus.\n * Disabled by default. When enabled, token expiry and user switching\n * are picked up without requiring a full page reload.\n */\n revalidateOnWindowFocus?: boolean;\n\n /** @internal Overrides how a session read retries; used by tests. */\n retryPolicy?: MintRetryPolicy;\n}\n\n/**\n * Why the provider has no session.\n *\n * - `unauthenticated`: the endpoint answered 401 or 403, or the person signed\n * out. Offer sign-in.\n * - `request_failed`: the endpoint did not answer usably. A network error, a\n * timeout, or a 5xx / 408 / 429 on every attempt of one read, or another\n * status. The person may well be signed in. Offer `retry`.\n * - `invalid_response`: it answered without a usable session.\n */\nexport type AthenaSSOFailureReason = 'unauthenticated' | 'invalid_response' | 'request_failed';\n\n/** What `displayOnError` receives when it is a function. */\nexport interface AthenaSSOFailure {\n reason: AthenaSSOFailureReason;\n /** Read the session again. `displayWhileLoading` shows meanwhile. */\n retry: () => void;\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────\n\n/**\n * How one session read retries: the parent bridge's mint policy (Marathon's\n * `/api/sso/userinfo` and `/_athena/auth` mint the same credential), with a\n * longer wait per request, since every request mints and a slow answer is\n * still an answer.\n */\nconst SSO_USERINFO_RETRY_POLICY: MintRetryPolicy = {\n ...DEFAULT_MINT_RETRY_POLICY,\n timeoutMs: 10_000,\n};\n\n/** One userinfo request, classified. */\ntype UserInfoAttempt =\n | { kind: 'session'; data: AthenaSSOUserInfo }\n | { kind: 'unauthenticated' }\n | { kind: 'invalid_response' }\n /** A status it does not retry, or a 2xx whose body is not JSON. */\n | { kind: 'failed'; status: number }\n | {\n kind: 'transient';\n status: number | null;\n reason: 'status' | 'network' | 'timeout';\n cause?: unknown;\n };\n\nconst abortError = () => new DOMException('The session read was cancelled.', 'AbortError');\n\n/** One userinfo request. Throws an `AbortError` when `signal` cancels the read. */\nasync function readUserInfoOnce({\n url,\n signal,\n timeoutMs,\n}: {\n url: string;\n signal: AbortSignal;\n timeoutMs: number;\n}): Promise<UserInfoAttempt> {\n if (signal.aborted) throw abortError();\n const request = new AbortController();\n const cancel = () => request.abort();\n signal.addEventListener('abort', cancel, { once: true });\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n request.abort();\n }, timeoutMs);\n\n try {\n const response = await fetch(url, { credentials: 'include', signal: request.signal });\n if (response.status === 401 || response.status === 403) return { kind: 'unauthenticated' };\n if (!response.ok) {\n return isRetryableMintStatus(response.status)\n ? { kind: 'transient', status: response.status, reason: 'status' }\n : { kind: 'failed', status: response.status };\n }\n\n let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n if (signal.aborted) throw abortError();\n return timedOut\n ? { kind: 'transient', status: null, reason: 'timeout', cause: error }\n : { kind: 'failed', status: response.status };\n }\n return isValidSSOUserInfo(data) ? { kind: 'session', data } : { kind: 'invalid_response' };\n } catch (error) {\n if (signal.aborted) throw abortError();\n return { kind: 'transient', status: null, reason: timedOut ? 'timeout' : 'network', cause: error };\n } finally {\n clearTimeout(timer);\n signal.removeEventListener('abort', cancel);\n }\n}\n\n/**\n * What a read concluded, as the query holds it. A read that could not answer\n * throws instead (`request_failed`), so an earlier answer stays.\n */\ntype SessionAnswer =\n | { kind: 'session'; data: AthenaSSOUserInfo }\n | {\n kind: 'no_session';\n reason: Exclude<AthenaSSOFailureReason, 'request_failed'>;\n /** The person signed out here (`logout`), rather than the endpoint answering no session. */\n signedOut?: true;\n };\n\n/**\n * One session read: one bounded cycle of userinfo requests. A transient\n * failure is retried with `policy`'s capped, jittered backoff; a read that\n * gives up throws the typed error it reports. Throws an `AbortError` when\n * `signal` cancels the read.\n */\nasync function readSession({\n url,\n signal,\n policy,\n}: {\n url: string;\n signal: AbortSignal;\n policy: MintRetryPolicy;\n}): Promise<SessionAnswer> {\n const maxAttempts = Math.max(1, Math.floor(policy.maxAttempts));\n for (let attempts = 1; ; attempts += 1) {\n const attempt = await readUserInfoOnce({ url, signal, timeoutMs: policy.timeoutMs });\n\n if (attempt.kind === 'session') return { kind: 'session', data: attempt.data };\n if (attempt.kind === 'unauthenticated') return { kind: 'no_session', reason: 'unauthenticated' };\n if (attempt.kind === 'invalid_response') {\n console.error(\n '[AthenaSDK] Invalid SSO userinfo response: expected \"user.user_id\", \"user.email\", \"orgMemberInfos\", and \"accessToken\"',\n );\n return { kind: 'no_session', reason: 'invalid_response' };\n }\n\n if (attempt.kind === 'transient' && attempts < maxAttempts) {\n const delayMs = getMintRetryDelay({ retry: attempts, policy });\n athenaDiagnostics.emit('auth.sso.userinfo.retry', {\n level: 'warn',\n data: {\n status: attempt.status,\n reason: attempt.reason,\n attempt: attempts,\n max_attempts: maxAttempts,\n delay_ms: delayMs,\n },\n });\n await waitBeforeRetry({ delayMs, signal });\n continue;\n }\n\n throw sessionReadError({ url, attempt, attempts });\n }\n}\n\n/** The backoff between two requests of one read; cancelling the read ends it at once. */\nfunction waitBeforeRetry({ delayMs, signal }: { delayMs: number; signal: AbortSignal }): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(abortError());\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortError());\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, delayMs);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** The typed error a read reports when it gives up without an answer about the session. */\nfunction sessionReadError({\n url,\n attempt,\n attempts,\n}: {\n url: string;\n attempt: Extract<UserInfoAttempt, { kind: 'failed' | 'transient' }>;\n attempts: number;\n}): AthenaSdkError {\n if (attempt.kind === 'failed') {\n const unreadable = attempt.status >= 200 && attempt.status < 300;\n return new AthenaSdkError({\n code: 'auth_sso_failed',\n message: unreadable\n ? `The SSO session read (${url}) answered HTTP ${attempt.status} without a JSON body.`\n : `The SSO session read (${url}) answered HTTP ${attempt.status}.`,\n hint: 'Check that ssoBaseUrl / ssoUserInfoUrl point at the SSO userinfo endpoint.',\n status: attempt.status,\n context: { attempts, reason: unreadable ? 'invalid_body' : 'status' },\n });\n }\n const answer =\n attempt.status !== null\n ? `HTTP ${attempt.status}`\n : attempt.reason === 'timeout'\n ? 'a timeout'\n : 'a network error';\n return new AthenaSdkError({\n code: 'auth_sso_failed',\n message: `The SSO session read (${url}) failed ${attempts} time${attempts === 1 ? '' : 's'} (last: ${answer}).`,\n hint: 'The sign-in service did not answer; the person may still be signed in. Offer a retry (displayOnError receives retry).',\n ...(attempt.status !== null && { status: attempt.status }),\n ...(attempt.cause !== undefined && { cause: attempt.cause }),\n context: { attempts, reason: attempt.reason },\n });\n}\n\nconst DEFAULT_SSO_PATHS = {\n userInfo: '/api/sso/userinfo',\n login: '/api/sso/initiate',\n logout: '/api/sso/logout',\n} as const;\n\nconst trimTrailingSlash = (value: string): string => value.replace(/\\/+$/, '');\n\nfunction resolveSSOUrl({\n baseUrl,\n overrideUrl,\n defaultPath,\n}: {\n baseUrl?: string;\n overrideUrl?: string;\n defaultPath: string;\n}): string {\n if (overrideUrl) {\n return overrideUrl;\n }\n\n if (!baseUrl) {\n return defaultPath;\n }\n\n return `${trimTrailingSlash(baseUrl)}${defaultPath}`;\n}\n\nfunction isValidSSOUserInfo(data: unknown): data is AthenaSSOUserInfo {\n if (!data || typeof data !== 'object') {\n return false;\n }\n\n const candidate = data as {\n accessToken?: unknown;\n orgMemberInfos?: unknown;\n user?: {\n user_id?: unknown;\n email?: unknown;\n };\n };\n\n return (\n typeof candidate.accessToken === 'string' &&\n Array.isArray(candidate.orgMemberInfos) &&\n !!candidate.user &&\n typeof candidate.user.user_id === 'string' &&\n typeof candidate.user.email === 'string'\n );\n}\n\n/** Map the backend SSO response to the SDK's user/org types. */\nfunction mapSSOResponse(data: AthenaSSOUserInfo): {\n user: AthenaUser;\n orgs: AthenaOrg[];\n accessToken: string;\n} {\n const user: AthenaUser = {\n userId: data.user.user_id,\n email: data.user.email,\n firstName: data.user.first_name || undefined,\n lastName: data.user.last_name || undefined,\n username: data.user.username || undefined,\n pictureUrl: data.user.picture_url || undefined,\n properties: data.user.properties,\n };\n\n const orgs: AthenaOrg[] = data.orgMemberInfos.map((org) => ({\n orgId: org.orgId,\n orgName: org.orgName,\n urlSafeOrgName: org.urlSafeOrgName,\n }));\n\n return { user, orgs, accessToken: data.accessToken };\n}\n\n// ─── Provider ─────────────────────────────────────────────────────────\n\n/**\n * Wraps your app with Athena authentication powered by an external SSO\n * identity provider (e.g. Microsoft Entra / Azure AD, Okta, etc.).\n *\n * The SSO login flow is handled entirely by your backend. This provider\n * verifies the session by fetching `ssoUserInfoUrl` and exposes the\n * same `AthenaAuthState` context that `AthenaAuthProvider` (PropelAuth)\n * provides, so downstream components like `<AthenaProvider>` and\n * `useAthenaAuth()` work identically.\n *\n * Place this **above** `<AthenaProvider>` in the component tree.\n *\n * @example\n * ```tsx\n * import { AthenaSSOProvider } from '@athenaintel/react/auth';\n * import { AthenaProvider, AthenaChat } from '@athenaintel/react';\n *\n * function App() {\n * return (\n * <AthenaSSOProvider\n * ssoUserInfoUrl=\"https://api.yourdomain.com/api/sso/userinfo\"\n * ssoLoginUrl=\"https://api.yourdomain.com/api/sso/initiate\"\n * >\n * <AthenaProvider>\n * <AthenaChat />\n * </AthenaProvider>\n * </AthenaSSOProvider>\n * );\n * }\n * ```\n */\nexport function AthenaSSOProvider({\n children,\n ssoBaseUrl,\n ssoUserInfoUrl,\n ssoLoginUrl,\n ssoLogoutUrl,\n displayWhileLoading,\n displayOnError,\n onError,\n revalidateOnWindowFocus = false,\n retryPolicy = SSO_USERINFO_RETRY_POLICY,\n}: AthenaSSOProviderProps) {\n // The provider's own client, never a host's: the session holds an access\n // token, and a host may persist its query cache.\n const [queryClient] = useState(() => new QueryClient());\n const retryPolicyRef = useRef(retryPolicy);\n retryPolicyRef.current = retryPolicy;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n\n const ssoUrls = useMemo(\n () => ({\n userInfo: resolveSSOUrl({\n baseUrl: ssoBaseUrl,\n overrideUrl: ssoUserInfoUrl,\n defaultPath: DEFAULT_SSO_PATHS.userInfo,\n }),\n login: resolveSSOUrl({\n baseUrl: ssoBaseUrl,\n overrideUrl: ssoLoginUrl,\n defaultPath: DEFAULT_SSO_PATHS.login,\n }),\n logout: resolveSSOUrl({\n baseUrl: ssoBaseUrl,\n overrideUrl: ssoLogoutUrl,\n defaultPath: DEFAULT_SSO_PATHS.logout,\n }),\n }),\n [ssoBaseUrl, ssoUserInfoUrl, ssoLoginUrl, ssoLogoutUrl],\n );\n\n const queryKey = useMemo(() => ['athena-sdk', 'sso-session', ssoUrls.userInfo], [ssoUrls.userInfo]);\n\n // One read is one bounded cycle (`readSession`). A read that gives up\n // throws, so the query keeps the session an earlier read answered: a failed\n // background revalidation or renewal does not sign the person out.\n const queryFn = useCallback(\n async ({ signal }: { signal: AbortSignal }): Promise<SessionAnswer> => {\n try {\n return await readSession({ url: ssoUrls.userInfo, signal, policy: retryPolicyRef.current });\n } catch (readError) {\n if (readError instanceof AthenaSdkError) {\n athenaDiagnostics.emit('auth.sso.userinfo.error', { error: readError });\n try {\n onErrorRef.current?.(readError);\n } catch (callbackError) {\n console.error('[AthenaSDK] AthenaSSOProvider onError threw', callbackError);\n }\n }\n throw readError;\n }\n },\n [ssoUrls.userInfo],\n );\n\n const query = useQuery(\n {\n queryKey,\n queryFn,\n // `readSession` retries a transient failure itself, with the bridge's\n // policy; the query never retries on top of it, and reads while the\n // browser reports itself offline too, so that policy decides.\n retry: false,\n networkMode: 'always',\n staleTime: Number.POSITIVE_INFINITY,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n },\n queryClient,\n );\n\n const answer = query.data;\n const session = answer?.kind === 'session' ? answer.data : null;\n const loading = query.isPending;\n const reason: AthenaSSOFailureReason | null = session\n ? null\n : answer?.kind === 'no_session'\n ? answer.reason\n : query.isError\n ? 'request_failed'\n : null;\n const signedOut = answer?.kind === 'no_session' && answer.signedOut === true;\n\n useEffect(() => {\n if (!revalidateOnWindowFocus || typeof window === 'undefined') {\n return;\n }\n\n // A revalidation joins a read already in flight (a renewal, the first\n // read) instead of cancelling it.\n const revalidate = () => {\n void queryClient.refetchQueries({ queryKey }, { cancelRefetch: false });\n };\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'visible') {\n revalidate();\n }\n };\n\n window.addEventListener('focus', revalidate);\n document.addEventListener('visibilitychange', handleVisibilityChange);\n\n return () => {\n window.removeEventListener('focus', revalidate);\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n };\n }, [revalidateOnWindowFocus, queryClient, queryKey]);\n\n // Redirect to SSO login when the endpoint answered no session and no error\n // UI was provided. Signing out redirects by itself, when asked to.\n useEffect(() => {\n if (\n !loading &&\n reason === 'unauthenticated' &&\n !signedOut &&\n !displayOnError &&\n typeof window !== 'undefined'\n ) {\n window.location.assign(ssoUrls.login);\n }\n }, [loading, reason, signedOut, displayOnError, ssoUrls.login]);\n\n const retry = useCallback(() => {\n void queryClient.resetQueries({ queryKey });\n }, [queryClient, queryKey]);\n\n const logout = useCallback(async (redirectOnLogout = true) => {\n await queryClient.cancelQueries({ queryKey });\n\n try {\n await fetch(ssoUrls.logout, {\n method: 'POST',\n credentials: 'include',\n });\n } catch (logoutError) {\n console.error('[AthenaSDK] Failed to invalidate SSO session during logout', logoutError);\n }\n\n queryClient.setQueryData<SessionAnswer>(queryKey, {\n kind: 'no_session',\n reason: 'unauthenticated',\n signedOut: true,\n });\n\n if (redirectOnLogout && typeof window !== 'undefined') {\n window.location.assign(ssoUrls.login);\n }\n }, [queryClient, queryKey, ssoUrls.login, ssoUrls.logout]);\n\n // The SSO side of the SDK's credential source: `force` (the previous token\n // was refused) reads the session again for a new token, joining a read\n // already in flight; otherwise, or when that read has no session to hand\n // back, the held one is served.\n const sessionRef = useRef(session);\n sessionRef.current = session;\n const getToken = useCallback<AthenaStatewireTokenGetter>(\n async ({ force = false } = {}) => {\n if (force) {\n try {\n const renewed = await queryClient.fetchQuery({\n queryKey,\n queryFn,\n staleTime: 0,\n retry: false,\n networkMode: 'always',\n });\n if (renewed.kind === 'session') return renewed.data.accessToken;\n } catch {\n // The read gave up (already reported) or was cancelled.\n }\n }\n return sessionRef.current?.accessToken ?? null;\n },\n [queryClient, queryKey, queryFn],\n );\n\n const authState: AthenaAuthState = useMemo(() => {\n if (loading) {\n return {\n isLoggedIn: false,\n isLoading: true,\n user: null,\n accessToken: null,\n orgs: [],\n logout: async () => {},\n getToken,\n };\n }\n\n if (!session) {\n return {\n isLoggedIn: false,\n isLoading: false,\n user: null,\n accessToken: null,\n orgs: [],\n logout,\n getToken,\n };\n }\n\n const { user, orgs, accessToken } = mapSSOResponse(session);\n\n return {\n isLoggedIn: true,\n isLoading: false,\n user,\n accessToken,\n orgs,\n logout,\n getToken,\n };\n }, [loading, session, logout, getToken]);\n\n if (authState.isLoading) {\n return <>{displayWhileLoading ?? null}</>;\n }\n\n if (!authState.isLoggedIn) {\n if (typeof displayOnError === 'function') {\n return <>{displayOnError({ reason: reason ?? 'unauthenticated', retry })}</>;\n }\n return displayOnError ? <>{displayOnError}</> : null;\n }\n\n return (\n <AthenaAuthContext.Provider value={authState}>\n {children}\n </AthenaAuthContext.Provider>\n );\n}\n"],"names":["DEFAULT_MINT_RETRY_POLICY","isRetryableMintStatus","getMintRetryDelay","athenaDiagnostics","AthenaSdkError","useState","QueryClient","useRef","useMemo","useCallback","useQuery","useEffect","jsx","Fragment","AthenaAuthContext"],"mappings":";;;;;;;;;AAiIA,MAAM,4BAA6C;AAAA,EACjD,GAAGA,KAAAA;AAAAA,EACH,WAAW;AACb;AAgBA,MAAM,aAAa,MAAM,IAAI,aAAa,mCAAmC,YAAY;AAGzF,eAAe,iBAAiB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAI6B;AAC3B,MAAI,OAAO,QAAS,OAAM,WAAA;AAC1B,QAAM,UAAU,IAAI,gBAAA;AACpB,QAAM,SAAS,MAAM,QAAQ,MAAA;AAC7B,SAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,MAAM;AACvD,MAAI,WAAW;AACf,QAAM,QAAQ,WAAW,MAAM;AAC7B,eAAW;AACX,YAAQ,MAAA;AAAA,EACV,GAAG,SAAS;AAEZ,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,KAAK,EAAE,aAAa,WAAW,QAAQ,QAAQ,QAAQ;AACpF,QAAI,SAAS,WAAW,OAAO,SAAS,WAAW,IAAK,QAAO,EAAE,MAAM,kBAAA;AACvE,QAAI,CAAC,SAAS,IAAI;AAChB,aAAOC,KAAAA,sBAAsB,SAAS,MAAM,IACxC,EAAE,MAAM,aAAa,QAAQ,SAAS,QAAQ,QAAQ,aACtD,EAAE,MAAM,UAAU,QAAQ,SAAS,OAAA;AAAA,IACzC;AAEA,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,SAAS,KAAA;AAAA,IACxB,SAAS,OAAO;AACd,UAAI,OAAO,QAAS,OAAM,WAAA;AAC1B,aAAO,WACH,EAAE,MAAM,aAAa,QAAQ,MAAM,QAAQ,WAAW,OAAO,MAAA,IAC7D,EAAE,MAAM,UAAU,QAAQ,SAAS,OAAA;AAAA,IACzC;AACA,WAAO,mBAAmB,IAAI,IAAI,EAAE,MAAM,WAAW,KAAA,IAAS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A;AAAA,IAEJ;AAEA,QAAI,CAAC,SAAS;AACZ,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,MAAM;AAAA,QACN,aAAa;AAAA,QACb,MAAM,CAAA;AAAA,QACN;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ;AAEA,UAAM,EAAE,MAAM,MAAM,YAAA,IAAgB,eAAe,OAAO;AAE1D,WAAO;AAAA,MACL,YAAY;AAAA,MACZ,WAAW;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAC,SAAS,SAAS,QAAQ,QAAQ,CAAC;AAEvC,MAAI,UAAU,WAAW;AACvB,WAAOI,2BAAAA,IAAAC,WAAAA,UAAA,EAAG,iCAAuB,KAAA,CAAK;AAAA,EACxC;AAEA,MAAI,CAAC,UAAU,YAAY;AACzB,QAAI,OAAO,mBAAmB,YAAY;AACxC,aAAOD,+BAAAC,WAAAA,UAAA,EAAG,yBAAe,EAAE,QAAQ,UAAU,mBAAmB,MAAA,CAAO,EAAA,CAAE;AAAA,IAC3E;AACA,WAAO,iBAAiBD,2BAAAA,IAAAC,WAAAA,UAAA,EAAG,UAAA,eAAA,CAAe,IAAM;AAAA,EAClD;AAEA,wCACGC,kBAAAA,kBAAkB,UAAlB,EAA2B,OAAO,WAChC,UACH;AAEJ;;"}
@@ -1,29 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const TOKEN_EXPIRY_SKEW_MS = 3e4;
4
- function jwtExpiresAtMs(token) {
4
+ function jwtClaims(token) {
5
5
  const payload = token.split(".")[1];
6
6
  if (!payload) return null;
7
7
  try {
8
8
  const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
9
9
  const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
10
- const exp = JSON.parse(atob(padded)).exp;
11
- return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : null;
10
+ const claims = JSON.parse(atob(padded));
11
+ return typeof claims === "object" && claims !== null && !Array.isArray(claims) ? claims : null;
12
12
  } catch {
13
13
  return null;
14
14
  }
15
15
  }
16
+ function jwtExpiresAtMs(token) {
17
+ var _a;
18
+ const exp = (_a = jwtClaims(token)) == null ? void 0 : _a.exp;
19
+ return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : null;
20
+ }
16
21
  function jwtSubject(token) {
17
- const payload = token.split(".")[1];
18
- if (!payload) return null;
19
- try {
20
- const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
21
- const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
22
- const sub = JSON.parse(atob(padded)).sub;
23
- return typeof sub === "string" && sub.length > 0 ? sub : null;
24
- } catch {
25
- return null;
26
- }
22
+ var _a;
23
+ const sub = (_a = jwtClaims(token)) == null ? void 0 : _a.sub;
24
+ return typeof sub === "string" && sub.length > 0 ? sub : null;
25
+ }
26
+ function jwtScope(token) {
27
+ const claims = jwtClaims(token);
28
+ if (claims === null) return null;
29
+ const orgMember = claims.org_member_info;
30
+ const scope = [
31
+ ["workspace_id", claims.workspace_id],
32
+ ["org_id", claims.org_id],
33
+ [
34
+ "org_member_info.org_id",
35
+ typeof orgMember === "object" && orgMember !== null ? orgMember.org_id : void 0
36
+ ]
37
+ ].filter((entry) => typeof entry[1] === "string" && entry[1].length > 0).map(([claim, value]) => `${claim}=${value}`);
38
+ return scope.length > 0 ? scope.join("\0") : null;
27
39
  }
28
40
  function isTokenExpiring(token, now = Date.now()) {
29
41
  const expiresAt = jwtExpiresAtMs(token);
@@ -116,5 +128,6 @@ exports.TOKEN_EXPIRY_SKEW_MS = TOKEN_EXPIRY_SKEW_MS;
116
128
  exports.createAthenaCredentialSource = createAthenaCredentialSource;
117
129
  exports.isTokenExpiring = isTokenExpiring;
118
130
  exports.jwtExpiresAtMs = jwtExpiresAtMs;
131
+ exports.jwtScope = jwtScope;
119
132
  exports.jwtSubject = jwtSubject;
120
133
  //# sourceMappingURL=credential-source.cjs.map