@alepha/ui 0.36.1 → 0.37.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 (288) hide show
  1. package/dist/account/$pageAccount.d.ts +1 -1
  2. package/dist/account/$pageAccount.d.ts.map +1 -1
  3. package/dist/account/$pageAccount.js.map +1 -1
  4. package/dist/account/AccountDisplay.d.ts +13 -0
  5. package/dist/account/AccountDisplay.d.ts.map +1 -0
  6. package/dist/account/AccountDisplay.js +48 -0
  7. package/dist/account/AccountDisplay.js.map +1 -0
  8. package/dist/account/AccountProfile.d.ts.map +1 -1
  9. package/dist/account/AccountProfile.js +14 -10
  10. package/dist/account/AccountProfile.js.map +1 -1
  11. package/dist/account/AccountRouter.d.ts +6 -6
  12. package/dist/account/AccountRouter.d.ts.map +1 -1
  13. package/dist/account/index.d.ts +5 -0
  14. package/dist/account/index.d.ts.map +1 -1
  15. package/dist/account/index.js +2 -1
  16. package/dist/admin/$pageAdmin.d.ts +1 -1
  17. package/dist/admin/$pageAdmin.d.ts.map +1 -1
  18. package/dist/admin/$pageAdmin.js.map +1 -1
  19. package/dist/admin/AdminAudits.js.map +1 -1
  20. package/dist/admin/AdminJobDetail.js.map +1 -1
  21. package/dist/admin/AdminJobs.js.map +1 -1
  22. package/dist/admin/AdminNotifications.js.map +1 -1
  23. package/dist/admin/AdminRouter.d.ts +14 -14
  24. package/dist/admin/AdminRouter.d.ts.map +1 -1
  25. package/dist/admin/AdminUserDetail.js.map +1 -1
  26. package/dist/admin/AdminUsers.js.map +1 -1
  27. package/dist/admin/ParameterHistoryItem.js.map +1 -1
  28. package/dist/ai/AiChat.d.ts +26 -39
  29. package/dist/ai/AiChat.d.ts.map +1 -1
  30. package/dist/ai/AiChat.js +65 -123
  31. package/dist/ai/AiChat.js.map +1 -1
  32. package/dist/ai/AiChatDock.d.ts +23 -0
  33. package/dist/ai/AiChatDock.d.ts.map +1 -0
  34. package/dist/ai/AiChatDock.js +90 -0
  35. package/dist/ai/AiChatDock.js.map +1 -0
  36. package/dist/ai/AiChatDockSlot.d.ts +15 -0
  37. package/dist/ai/AiChatDockSlot.d.ts.map +1 -0
  38. package/dist/ai/AiChatDockSlot.js +20 -0
  39. package/dist/ai/AiChatDockSlot.js.map +1 -0
  40. package/dist/ai/AiChatLauncher.d.ts +17 -0
  41. package/dist/ai/AiChatLauncher.d.ts.map +1 -0
  42. package/dist/ai/AiChatLauncher.js +42 -0
  43. package/dist/ai/AiChatLauncher.js.map +1 -0
  44. package/dist/ai/AiChatMessage.d.ts +6 -0
  45. package/dist/ai/AiChatMessage.d.ts.map +1 -1
  46. package/dist/ai/AiChatMessage.js +20 -4
  47. package/dist/ai/AiChatMessage.js.map +1 -1
  48. package/dist/ai/AiChatPanel.d.ts +71 -0
  49. package/dist/ai/AiChatPanel.d.ts.map +1 -0
  50. package/dist/ai/AiChatPanel.js +143 -0
  51. package/dist/ai/AiChatPanel.js.map +1 -0
  52. package/dist/ai/index.d.ts +8 -4
  53. package/dist/ai/index.d.ts.map +1 -1
  54. package/dist/ai/index.js +5 -1
  55. package/dist/ai/useAiChat.d.ts +12 -0
  56. package/dist/ai/useAiChat.d.ts.map +1 -1
  57. package/dist/ai/useAiChat.js +32 -15
  58. package/dist/ai/useAiChat.js.map +1 -1
  59. package/dist/auth/AuthLogin.d.ts +9 -0
  60. package/dist/auth/AuthLogin.d.ts.map +1 -1
  61. package/dist/auth/AuthLogin.js +2 -2
  62. package/dist/auth/AuthLogin.js.map +1 -1
  63. package/dist/auth/AuthRegister.d.ts +4 -1
  64. package/dist/auth/AuthRegister.d.ts.map +1 -1
  65. package/dist/auth/AuthRegister.js +1 -1
  66. package/dist/auth/AuthRegister.js.map +1 -1
  67. package/dist/auth/AuthResetPassword.d.ts +8 -0
  68. package/dist/auth/AuthResetPassword.d.ts.map +1 -1
  69. package/dist/auth/AuthResetPassword.js +2 -2
  70. package/dist/auth/AuthResetPassword.js.map +1 -1
  71. package/dist/auth/AuthRouter.d.ts +4 -4
  72. package/dist/auth/AuthRouter.d.ts.map +1 -1
  73. package/dist/core/Badge.d.ts.map +1 -1
  74. package/dist/core/Badge.js +7 -3
  75. package/dist/core/Badge.js.map +1 -1
  76. package/dist/core/Collapsible.d.ts +50 -0
  77. package/dist/core/Collapsible.d.ts.map +1 -0
  78. package/dist/core/Collapsible.js +70 -0
  79. package/dist/core/Collapsible.js.map +1 -0
  80. package/dist/core/Combobox.d.ts +7 -1
  81. package/dist/core/Combobox.d.ts.map +1 -1
  82. package/dist/core/Combobox.js +2 -2
  83. package/dist/core/Combobox.js.map +1 -1
  84. package/dist/core/PaneRail.d.ts +24 -7
  85. package/dist/core/PaneRail.d.ts.map +1 -1
  86. package/dist/core/PaneRail.js +24 -19
  87. package/dist/core/PaneRail.js.map +1 -1
  88. package/dist/core/Stepper.d.ts +36 -0
  89. package/dist/core/Stepper.d.ts.map +1 -0
  90. package/dist/core/Stepper.js +54 -0
  91. package/dist/core/Stepper.js.map +1 -0
  92. package/dist/core/index.d.ts +2 -0
  93. package/dist/core/index.d.ts.map +1 -1
  94. package/dist/core/index.js +3 -1
  95. package/dist/core/useToast.js +13 -13
  96. package/dist/core/useToast.js.map +1 -1
  97. package/dist/form/AutoForm.d.ts.map +1 -1
  98. package/dist/form/AutoForm.js +29 -0
  99. package/dist/form/AutoForm.js.map +1 -1
  100. package/dist/form/AutoFormErrorPopover.js +13 -3
  101. package/dist/form/AutoFormErrorPopover.js.map +1 -1
  102. package/dist/form/Control.d.ts +14 -1
  103. package/dist/form/Control.d.ts.map +1 -1
  104. package/dist/form/Control.js +12 -2
  105. package/dist/form/Control.js.map +1 -1
  106. package/dist/form/ControlDate.d.ts.map +1 -1
  107. package/dist/form/ControlDate.js +3 -0
  108. package/dist/form/ControlDate.js.map +1 -1
  109. package/dist/form/ControlDateRange.d.ts +12 -1
  110. package/dist/form/ControlDateRange.d.ts.map +1 -1
  111. package/dist/form/ControlDateRange.js +11 -1
  112. package/dist/form/ControlDateRange.js.map +1 -1
  113. package/dist/form/ControlNumber.d.ts.map +1 -1
  114. package/dist/form/ControlNumber.js +2 -0
  115. package/dist/form/ControlNumber.js.map +1 -1
  116. package/dist/form/ControlObject.d.ts.map +1 -1
  117. package/dist/form/ControlObject.js +15 -1
  118. package/dist/form/ControlObject.js.map +1 -1
  119. package/dist/form/ControlPassword.d.ts +4 -0
  120. package/dist/form/ControlPassword.d.ts.map +1 -1
  121. package/dist/form/ControlPassword.js +1 -0
  122. package/dist/form/ControlPassword.js.map +1 -1
  123. package/dist/form/ControlSelect.d.ts +23 -1
  124. package/dist/form/ControlSelect.d.ts.map +1 -1
  125. package/dist/form/ControlSelect.js +5 -0
  126. package/dist/form/ControlSelect.js.map +1 -1
  127. package/dist/form/ControlSelectCombobox.d.ts +11 -1
  128. package/dist/form/ControlSelectCombobox.d.ts.map +1 -1
  129. package/dist/form/ControlSelectCombobox.js +9 -1
  130. package/dist/form/ControlSelectCombobox.js.map +1 -1
  131. package/dist/form/ControlUpload.d.ts.map +1 -1
  132. package/dist/form/ControlUpload.js +1 -0
  133. package/dist/form/ControlUpload.js.map +1 -1
  134. package/dist/form/FormField.d.ts +5 -0
  135. package/dist/form/FormField.d.ts.map +1 -1
  136. package/dist/form/FormField.js +7 -0
  137. package/dist/form/FormField.js.map +1 -1
  138. package/dist/i18n/fr/uiFr.d.ts.map +1 -1
  139. package/dist/i18n/fr/uiFr.js +14 -0
  140. package/dist/i18n/fr/uiFr.js.map +1 -1
  141. package/dist/shell/$pageNav.d.ts +2 -2
  142. package/dist/shell/$pageNav.d.ts.map +1 -1
  143. package/dist/shell/$pageNav.js.map +1 -1
  144. package/dist/shell/AppShell.d.ts +6 -0
  145. package/dist/shell/AppShell.d.ts.map +1 -1
  146. package/dist/shell/AppShell.js +31 -27
  147. package/dist/shell/AppShell.js.map +1 -1
  148. package/dist/shell/ButtonSettings.d.ts +6 -2
  149. package/dist/shell/ButtonSettings.d.ts.map +1 -1
  150. package/dist/shell/ButtonSettings.js +17 -3
  151. package/dist/shell/ButtonSettings.js.map +1 -1
  152. package/dist/shell/ButtonSettingsVisionMenuItem.d.ts +16 -0
  153. package/dist/shell/ButtonSettingsVisionMenuItem.d.ts.map +1 -0
  154. package/dist/shell/ButtonSettingsVisionMenuItem.js +24 -0
  155. package/dist/shell/ButtonSettingsVisionMenuItem.js.map +1 -0
  156. package/dist/shell/ButtonVision.d.ts +28 -0
  157. package/dist/shell/ButtonVision.d.ts.map +1 -0
  158. package/dist/shell/ButtonVision.js +46 -0
  159. package/dist/shell/ButtonVision.js.map +1 -0
  160. package/dist/shell/index.d.ts +6 -3
  161. package/dist/shell/index.d.ts.map +1 -1
  162. package/dist/shell/index.js +2 -1
  163. package/dist/styles.css +57 -0
  164. package/dist/table/DataTable.d.ts.map +1 -1
  165. package/dist/table/DataTable.js +29 -4
  166. package/dist/table/DataTable.js.map +1 -1
  167. package/dist/table/DataTableColumnPicker.d.ts.map +1 -1
  168. package/dist/table/DataTableColumnPicker.js +1 -0
  169. package/dist/table/DataTableColumnPicker.js.map +1 -1
  170. package/dist/table/DataTableFilterBar.d.ts +1 -1
  171. package/dist/table/DataTableFilterBar.d.ts.map +1 -1
  172. package/dist/table/DataTableFilterBar.js +5 -108
  173. package/dist/table/DataTableFilterBar.js.map +1 -1
  174. package/dist/table/DataTableHeaderFilter.d.ts +51 -0
  175. package/dist/table/DataTableHeaderFilter.d.ts.map +1 -0
  176. package/dist/table/DataTableHeaderFilter.js +113 -0
  177. package/dist/table/DataTableHeaderFilter.js.map +1 -0
  178. package/dist/table/DataTableHeaderRow.d.ts +7 -0
  179. package/dist/table/DataTableHeaderRow.d.ts.map +1 -1
  180. package/dist/table/DataTableHeaderRow.js +92 -74
  181. package/dist/table/DataTableHeaderRow.js.map +1 -1
  182. package/dist/table/DataTableTabs.d.ts +42 -0
  183. package/dist/table/DataTableTabs.d.ts.map +1 -0
  184. package/dist/table/DataTableTabs.js +55 -0
  185. package/dist/table/DataTableTabs.js.map +1 -0
  186. package/dist/table/dataTableBaseProps.d.ts +12 -0
  187. package/dist/table/dataTableBaseProps.d.ts.map +1 -1
  188. package/dist/table/dataTablePersistence.d.ts.map +1 -1
  189. package/dist/table/dataTablePersistence.js +4 -2
  190. package/dist/table/dataTablePersistence.js.map +1 -1
  191. package/dist/table/dataTableTypes.d.ts +18 -0
  192. package/dist/table/dataTableTypes.d.ts.map +1 -1
  193. package/dist/table/index.d.ts +5 -2
  194. package/dist/table/index.d.ts.map +1 -1
  195. package/dist/table/index.js +2 -1
  196. package/dist/table/useDataTableColumns.d.ts.map +1 -1
  197. package/dist/table/useDataTableColumns.js +1 -0
  198. package/dist/table/useDataTableColumns.js.map +1 -1
  199. package/dist/table/useDataTableFilterModel.d.ts +110 -0
  200. package/dist/table/useDataTableFilterModel.d.ts.map +1 -0
  201. package/dist/table/useDataTableFilterModel.js +154 -0
  202. package/dist/table/useDataTableFilterModel.js.map +1 -0
  203. package/docs/packages-alepha-ui-account.md +4 -0
  204. package/docs/packages-alepha-ui-ai.md +5 -5
  205. package/docs/packages-alepha-ui-shell.md +4 -3
  206. package/docs/packages-alepha-ui-table.md +4 -2
  207. package/package.json +8 -8
  208. package/src/account/$pageAccount.tsx +5 -4
  209. package/src/account/AccountDisplay.tsx +58 -0
  210. package/src/account/AccountProfile.tsx +30 -42
  211. package/src/account/__tests__/AccountProfile.browser.spec.tsx +141 -0
  212. package/src/account/__tests__/AccountRecoveryCodes.browser.spec.tsx +1 -1
  213. package/src/account/index.ts +5 -0
  214. package/src/admin/$pageAdmin.tsx +5 -4
  215. package/src/admin/AdminAudits.tsx +1 -1
  216. package/src/admin/AdminJobDetail.tsx +1 -1
  217. package/src/admin/AdminJobs.tsx +1 -1
  218. package/src/admin/AdminNotifications.tsx +1 -1
  219. package/src/admin/AdminUserDetail.tsx +1 -1
  220. package/src/admin/AdminUsers.tsx +1 -1
  221. package/src/admin/ParameterHistoryItem.tsx +1 -1
  222. package/src/admin/__tests__/AdminFilesUsageCard.browser.spec.tsx +17 -9
  223. package/src/ai/AiChat.tsx +94 -183
  224. package/src/ai/AiChatDock.tsx +129 -0
  225. package/src/ai/AiChatDockSlot.tsx +23 -0
  226. package/src/ai/AiChatLauncher.tsx +58 -0
  227. package/src/ai/AiChatMessage.tsx +36 -2
  228. package/src/ai/AiChatPanel.tsx +252 -0
  229. package/src/ai/__tests__/AiChat.browser.spec.tsx +187 -5
  230. package/src/ai/index.ts +8 -4
  231. package/src/ai/useAiChat.ts +63 -14
  232. package/src/auth/AuthLogin.tsx +19 -4
  233. package/src/auth/AuthRegister.tsx +6 -3
  234. package/src/auth/AuthResetPassword.tsx +18 -8
  235. package/src/auth/__tests__/AuthCancel.browser.spec.tsx +129 -0
  236. package/src/core/Badge.tsx +7 -3
  237. package/src/core/Collapsible.tsx +95 -0
  238. package/src/core/Combobox.tsx +11 -3
  239. package/src/core/PaneRail.tsx +36 -20
  240. package/src/core/Stepper.tsx +118 -0
  241. package/src/core/__tests__/Badge.browser.spec.tsx +5 -5
  242. package/src/core/__tests__/Collapsible.browser.spec.tsx +88 -0
  243. package/src/core/__tests__/PaneRail.browser.spec.tsx +48 -0
  244. package/src/core/__tests__/Stepper.browser.spec.tsx +39 -0
  245. package/src/core/__tests__/primitiveSlots.spec.ts +7 -0
  246. package/src/core/index.ts +15 -0
  247. package/src/form/AutoForm.tsx +32 -0
  248. package/src/form/AutoFormErrorPopover.tsx +27 -6
  249. package/src/form/Control.tsx +22 -0
  250. package/src/form/ControlDate.tsx +3 -0
  251. package/src/form/ControlDateRange.tsx +87 -58
  252. package/src/form/ControlNumber.tsx +2 -0
  253. package/src/form/ControlObject.tsx +20 -1
  254. package/src/form/ControlPassword.tsx +5 -0
  255. package/src/form/ControlSelect.tsx +32 -1
  256. package/src/form/ControlSelectCombobox.tsx +82 -56
  257. package/src/form/ControlUpload.tsx +1 -0
  258. package/src/form/FormField.tsx +23 -1
  259. package/src/form/__tests__/ControlFieldErrors.browser.spec.tsx +253 -0
  260. package/src/form/__tests__/ControlValidateMode.browser.spec.tsx +217 -0
  261. package/src/form/__tests__/ControlVariantErrors.browser.spec.tsx +133 -0
  262. package/src/i18n/fr/uiFr.ts +18 -1
  263. package/src/markdown/css.d.ts +11 -0
  264. package/src/shell/$pageNav.tsx +6 -4
  265. package/src/shell/AppShell.tsx +7 -0
  266. package/src/shell/ButtonSettings.tsx +20 -5
  267. package/src/shell/ButtonSettingsVisionMenuItem.tsx +40 -0
  268. package/src/shell/ButtonVision.tsx +73 -0
  269. package/src/shell/__tests__/ButtonSettings.browser.spec.tsx +42 -2
  270. package/src/shell/__tests__/ButtonVision.browser.spec.tsx +73 -0
  271. package/src/shell/__tests__/visionTokens.spec.ts +104 -0
  272. package/src/shell/index.ts +6 -3
  273. package/src/styles.css +57 -0
  274. package/src/table/DataTable.tsx +52 -4
  275. package/src/table/DataTableColumnPicker.tsx +3 -0
  276. package/src/table/DataTableFilterBar.tsx +18 -191
  277. package/src/table/DataTableHeaderFilter.tsx +156 -0
  278. package/src/table/DataTableHeaderRow.tsx +78 -40
  279. package/src/table/DataTableTabs.tsx +114 -0
  280. package/src/table/__tests__/DataTableHeaderFilter.browser.spec.tsx +174 -0
  281. package/src/table/__tests__/DataTableStaleColumns.browser.spec.tsx +80 -0
  282. package/src/table/__tests__/DataTableTabs.browser.spec.tsx +72 -0
  283. package/src/table/dataTableBaseProps.ts +12 -0
  284. package/src/table/dataTablePersistence.ts +11 -5
  285. package/src/table/dataTableTypes.ts +18 -0
  286. package/src/table/index.ts +9 -2
  287. package/src/table/useDataTableColumns.ts +1 -0
  288. package/src/table/useDataTableFilterModel.tsx +240 -0
@@ -1 +1 @@
1
- {"version":3,"file":"useAiChat.js","names":[],"sources":["../../src/ai/useAiChat.ts"],"sourcesContent":["import type {\n AiController,\n AiMessageResource,\n AiPendingCallResource,\n AiStreamEvent,\n} from \"alepha/api/ai\";\nimport {\n type RunResult,\n useAction,\n useAlepha,\n useClient,\n useQueryClient,\n} from \"alepha/react\";\nimport { useRouter } from \"alepha/react/router\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport { aiContextAtom } from \"./aiContextAtom.ts\";\nimport { AiFormRegistry } from \"./AiFormRegistry.ts\";\n\n/**\n * The state and actions of an assistant conversation, without any UI: what\n * `<AiChat />` is built on, for an app that wants its own.\n *\n * - `send(message)` starts a turn in the current conversation (a new one\n * first), with the current route and the innermost `useAiContext()`.\n * - A turn that pauses on a mutation sets `pending`; `approve()` or `deny()`\n * answers it with the call id only, never the input: the server runs the\n * input it stored.\n * - A turn that pauses on a client tool runs it here and resumes with its\n * result, on its own: `navigate` (by page name, through the typed router),\n * `fillForm` (only a form offered with `useAiContext({ form })`, never\n * submitted), and any `clientTools` the app passes.\n * - `open(id)` loads a stored conversation; `open()` starts a new one.\n *\n * Every action resolves a `RunResult` and never rejects, as `useAction` does.\n */\nexport const useAiChat = (options: UseAiChatOptions = {}): UseAiChat => {\n const api = useClient<AiController>();\n const alepha = useAlepha();\n const forms = useMemo(() => AiFormRegistry.of(alepha), [alepha]);\n const router = useRouter<any>();\n const queries = useQueryClient();\n const [conversationId, setConversationId] = useState<string | undefined>(\n options.conversationId,\n );\n const [items, setItems] = useState<AiChatItem[]>([]);\n const [streaming, setStreaming] = useState(\"\");\n const [activity, setActivity] = useState<string | undefined>();\n const [pending, setPending] = useState<AiPendingCallResource | undefined>();\n const [error, setError] = useState<string | undefined>();\n // The id the next request uses, ahead of the render that shows it.\n const idRef = useRef<string | undefined>(options.conversationId);\n // Calls the user denied, so their result reads as cancelled, not failed.\n const deniedRef = useRef(new Set<string>());\n const counter = useRef(0);\n\n const push = useCallback((item: Omit<AiChatItem, \"id\">) => {\n counter.current += 1;\n const id = `local-${counter.current}`;\n setItems((current) => [...current, { id, ...item }]);\n }, []);\n\n /**\n * Run a client tool the turn paused on, and return its result. A failure\n * is a result too: the model reads it and recovers.\n */\n const runClientTool = useCallback(\n async (name: string, input: Record<string, unknown>) => {\n try {\n if (options.clientTools?.[name]) {\n return { ok: true, result: await options.clientTools[name](input) };\n }\n if (name === \"navigate\") {\n await router.push(String(input.page), {\n params: (input.params as Record<string, string>) ?? {},\n });\n return { ok: true, page: input.page };\n }\n if (name === \"fillForm\") {\n const stack = alepha.store.get(aiContextAtom) ?? [];\n const formId = stack.findLast((it) => it.formId)?.formId;\n const form = formId ? forms.get(formId) : undefined;\n if (!form) {\n return {\n ok: false,\n error: \"No form on this page accepts being filled.\",\n };\n }\n return {\n ok: true,\n ...forms.fill(\n form,\n (input.values as Record<string, unknown>) ?? {},\n ),\n submitted: false,\n };\n }\n return { ok: false, error: `Unknown client tool '${name}'.` };\n } catch (cause) {\n return {\n ok: false,\n error: cause instanceof Error ? cause.message : String(cause),\n };\n }\n },\n [alepha, forms, router, options.clientTools],\n );\n\n /**\n * Read one stream to its end, then follow a client-tool pause with a\n * resume, until the turn stops or waits on the user.\n */\n const consume = useCallback(\n async (\n first: AsyncIterable<AiStreamEvent>,\n signal: AbortSignal,\n ): Promise<void> => {\n let stream: AsyncIterable<AiStreamEvent> | undefined = first;\n let ranTools = false;\n while (stream) {\n let text = \"\";\n let clientCall: AiPendingCallResource | undefined;\n for await (const event of stream) {\n if (event.type === \"conversation\" && event.conversationId) {\n idRef.current = event.conversationId;\n setConversationId(event.conversationId);\n } else if (event.type === \"text\" && event.text) {\n text += event.text;\n setStreaming(text);\n } else if (event.type === \"tool_call\") {\n setActivity(event.name);\n } else if (event.type === \"tool_result\") {\n ranTools = true;\n setActivity(undefined);\n push({\n role: \"tool\",\n content: \"\",\n name: event.name,\n isError: event.isError,\n denied: Boolean(\n event.callId && deniedRef.current.has(event.callId),\n ),\n });\n } else if (event.type === \"confirm\") {\n setPending({\n callId: event.callId ?? \"\",\n name: event.name ?? \"\",\n input: event.input ?? {},\n kind: \"confirm\",\n });\n } else if (event.type === \"client_tool\") {\n clientCall = {\n callId: event.callId ?? \"\",\n name: event.name ?? \"\",\n input: event.input ?? {},\n kind: \"client_tool\",\n };\n } else if (event.type === \"error\") {\n setError(event.message ?? event.name ?? \"The assistant failed\");\n }\n if (text && (event.type === \"tool_call\" || event.type === \"end\")) {\n push({ role: \"assistant\", content: text });\n text = \"\";\n setStreaming(\"\");\n }\n }\n setActivity(undefined);\n stream = undefined;\n if (ranTools) {\n // What the assistant ran may have changed what the page shows.\n for (const key of options.invalidates ?? []) {\n queries.invalidate(key);\n }\n ranTools = false;\n }\n if (clientCall && idRef.current) {\n const result = await runClientTool(clientCall.name, clientCall.input);\n stream = await api.resume(\n {\n params: { id: idRef.current },\n body: { callId: clientCall.callId, result },\n },\n { request: { signal } },\n );\n }\n }\n },\n [api, push, runClientTool, queries, options.invalidates],\n );\n\n const send = useAction<[message: string]>(\n {\n handler: async ({ signal }, message) => {\n setError(undefined);\n push({ role: \"user\", content: message });\n const stack = alepha.store.get(aiContextAtom) ?? [];\n const innermost = stack[stack.length - 1];\n const stream = await api.chat(\n {\n body: {\n conversationId: idRef.current,\n message,\n assistant: options.assistant,\n context: {\n route: router.pathname,\n page: innermost?.page,\n data: innermost?.data,\n },\n },\n },\n { request: { signal } },\n );\n await consume(stream, signal);\n },\n onError: (cause) => setError(cause.message),\n },\n [api, alepha, consume, options.assistant, push, router],\n );\n\n const answer = useAction<[decision: \"approve\" | \"deny\"]>(\n {\n handler: async ({ signal }, decision) => {\n if (!pending || !idRef.current) {\n return;\n }\n setError(undefined);\n const callId = pending.callId;\n if (decision === \"deny\") {\n deniedRef.current.add(callId);\n }\n setPending(undefined);\n const stream = await api.resume(\n { params: { id: idRef.current }, body: { callId, decision } },\n { request: { signal } },\n );\n await consume(stream, signal);\n },\n onError: (cause) => setError(cause.message),\n },\n [api, consume, pending],\n );\n\n const open = useAction<[id?: string]>(\n {\n handler: async (_ctx, id) => {\n setError(undefined);\n setStreaming(\"\");\n setPending(undefined);\n idRef.current = id;\n setConversationId(id);\n if (!id) {\n setItems([]);\n return;\n }\n const detail = await api.getConversation({ params: { id } });\n setItems(\n detail.messages.map((message: AiMessageResource) => ({\n id: message.id,\n role: message.role,\n content: message.content,\n name: message.name,\n isError: message.isError,\n // `alepha/ai`'s AI_CALL_DENIED: a stored denial keeps this text.\n denied:\n message.role === \"tool\" &&\n message.content === \"Denied by the user.\",\n })),\n );\n setPending(detail.conversation.pendingCall);\n },\n onError: (cause) => setError(cause.message),\n },\n [api],\n );\n\n /**\n * End the running turn: abort the request, keep what already streamed.\n */\n const stop = () => {\n send.cancel();\n answer.cancel();\n setActivity(undefined);\n if (streaming) {\n push({ role: \"assistant\", content: streaming });\n }\n setStreaming(\"\");\n };\n\n return {\n conversationId,\n items,\n streaming,\n activity,\n pending,\n error,\n loading: send.loading || answer.loading || open.loading,\n send: (message) => send.run(message),\n approve: () => answer.run(\"approve\"),\n deny: () => answer.run(\"deny\"),\n open: (id) => open.run(id),\n stop,\n };\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Options of {@link useAiChat}.\n */\nexport interface UseAiChatOptions {\n /**\n * The `$ai` to talk to, when the app declares several.\n */\n assistant?: string;\n /**\n * A stored conversation to continue.\n */\n conversationId?: string;\n /**\n * Query keys to invalidate after a turn ran a tool, so the page re-reads\n * what the assistant may have changed (`[[\"notes\"]]`).\n */\n invalidates?: unknown[][];\n /**\n * The app's own client tools, by name, beside `navigate` and `fillForm`.\n * The result goes back to the model.\n */\n clientTools?: Record<string, (input: Record<string, unknown>) => unknown>;\n}\n\n/**\n * One line of the conversation as shown.\n */\nexport interface AiChatItem {\n id: string;\n role: \"user\" | \"assistant\" | \"tool\";\n content: string;\n /**\n * The tool, on a `tool` line.\n */\n name?: string;\n isError?: boolean;\n /**\n * A `tool` line the user refused on its confirmation card: an error to the\n * model, a cancellation to the user.\n */\n denied?: boolean;\n}\n\n/**\n * What {@link useAiChat} returns.\n */\nexport interface UseAiChat {\n conversationId?: string;\n items: AiChatItem[];\n /**\n * The assistant's reply as it streams, before it lands in `items`.\n */\n streaming: string;\n /**\n * The tool running right now, for a progress line.\n */\n activity?: string;\n /**\n * The mutation waiting for the user, with the input the server stored.\n */\n pending?: AiPendingCallResource;\n error?: string;\n loading: boolean;\n send: (message: string) => Promise<RunResult<void>>;\n approve: () => Promise<RunResult<void>>;\n deny: () => Promise<RunResult<void>>;\n open: (id?: string) => Promise<RunResult<void>>;\n /**\n * End the running turn and keep what already streamed.\n */\n stop: () => void;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,aAAa,UAA4B,CAAC,MAAiB;CACtE,MAAM,MAAM,UAAwB;CACpC,MAAM,SAAS,UAAU;CACzB,MAAM,QAAQ,cAAc,eAAe,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC;CAC/D,MAAM,SAAS,UAAe;CAC9B,MAAM,UAAU,eAAe;CAC/B,MAAM,CAAC,gBAAgB,qBAAqB,SAC1C,QAAQ,cACV;CACA,MAAM,CAAC,OAAO,YAAY,SAAuB,CAAC,CAAC;CACnD,MAAM,CAAC,WAAW,gBAAgB,SAAS,EAAE;CAC7C,MAAM,CAAC,UAAU,eAAe,SAA6B;CAC7D,MAAM,CAAC,SAAS,cAAc,SAA4C;CAC1E,MAAM,CAAC,OAAO,YAAY,SAA6B;CAEvD,MAAM,QAAQ,OAA2B,QAAQ,cAAc;CAE/D,MAAM,YAAY,uBAAO,IAAI,IAAY,CAAC;CAC1C,MAAM,UAAU,OAAO,CAAC;CAExB,MAAM,OAAO,aAAa,SAAiC;EACzD,QAAQ,WAAW;EACnB,MAAM,KAAK,SAAS,QAAQ;EAC5B,UAAU,YAAY,CAAC,GAAG,SAAS;GAAE;GAAI,GAAG;EAAK,CAAC,CAAC;CACrD,GAAG,CAAC,CAAC;;;;;CAML,MAAM,gBAAgB,YACpB,OAAO,MAAc,UAAmC;EACtD,IAAI;GACF,IAAI,QAAQ,cAAc,OACxB,OAAO;IAAE,IAAI;IAAM,QAAQ,MAAM,QAAQ,YAAY,KAAK,CAAC,KAAK;GAAE;GAEpE,IAAI,SAAS,YAAY;IACvB,MAAM,OAAO,KAAK,OAAO,MAAM,IAAI,GAAG,EACp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,QAAQ,SAAS,UACjB,QAAQ,YAAY;GACxB,EAAE,CACJ;GACA,WAAW,OAAO,aAAa,WAAW;EAC5C;EACA,UAAU,UAAU,SAAS,MAAM,OAAO;CAC5C,GACA,CAAC,GAAG,CACN;;;;CAKA,MAAM,aAAa;EACjB,KAAK,OAAO;EACZ,OAAO,OAAO;EACd,YAAY,KAAA,CAAS;EACrB,IAAI,WACF,KAAK;GAAE,MAAM;GAAa,SAAS;EAAU,CAAC;EAEhD,aAAa,EAAE;CACjB;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,KAAK,WAAW,OAAO,WAAW,KAAK;EAChD,OAAO,YAAY,KAAK,IAAI,OAAO;EACnC,eAAe,OAAO,IAAI,SAAS;EACnC,YAAY,OAAO,IAAI,MAAM;EAC7B,OAAO,OAAO,KAAK,IAAI,EAAE;EACzB;CACF;AACF"}
1
+ {"version":3,"file":"useAiChat.js","names":[],"sources":["../../src/ai/useAiChat.ts"],"sourcesContent":["import type {\n AiController,\n AiMessageResource,\n AiPendingCallResource,\n AiStreamEvent,\n} from \"alepha/api/ai\";\nimport {\n type RunResult,\n useAction,\n useAlepha,\n useClient,\n useQueryClient,\n} from \"alepha/react\";\nimport { useRouter } from \"alepha/react/router\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport { aiContextAtom } from \"./aiContextAtom.ts\";\nimport { AiFormRegistry } from \"./AiFormRegistry.ts\";\n\n/**\n * The state and actions of an assistant conversation, without any UI: what\n * `<AiChat />` is built on, for an app that wants its own.\n *\n * - `send(message)` starts a turn in the current conversation (a new one\n * first), with the current route and the innermost `useAiContext()`.\n * - A turn that pauses on a mutation sets `pending`; `approve()` or `deny()`\n * answers it with the call id only, never the input: the server runs the\n * input it stored.\n * - A turn that pauses on a client tool runs it here and resumes with its\n * result, on its own: `navigate` (by page name, through the typed router),\n * `fillForm` (only a form offered with `useAiContext({ form })`, never\n * submitted), and any `clientTools` the app passes.\n * - `open(id)` loads a stored conversation; `open()` starts a new one.\n *\n * Every action resolves a `RunResult` and never rejects, as `useAction` does.\n */\nexport const useAiChat = (options: UseAiChatOptions = {}): UseAiChat => {\n const api = useClient<AiController>();\n const alepha = useAlepha();\n const forms = useMemo(() => AiFormRegistry.of(alepha), [alepha]);\n const router = useRouter<any>();\n const queries = useQueryClient();\n const [conversationId, setConversationId] = useState<string | undefined>(\n options.conversationId,\n );\n const [items, setItems] = useState<AiChatItem[]>([]);\n const [streaming, setStreaming] = useState(\"\");\n const [activity, setActivity] = useState<string | undefined>();\n const [pending, setPending] = useState<AiPendingCallResource | undefined>();\n const [error, setError] = useState<string | undefined>();\n // The id the next request uses, ahead of the render that shows it.\n const idRef = useRef<string | undefined>(options.conversationId);\n // Calls the user denied, so their result reads as cancelled, not failed.\n const deniedRef = useRef(new Set<string>());\n const counter = useRef(0);\n\n const push = useCallback((item: Omit<AiChatItem, \"id\">) => {\n counter.current += 1;\n const id = `local-${counter.current}`;\n setItems((current) => [...current, { id, ...item }]);\n }, []);\n\n /**\n * The page context a turn carries: the route, and the innermost page's\n * name and data. Sent on a chat and on every resume, since the server's\n * `allow` reads it to decide what the assistant is offered.\n */\n const pageContext = useCallback(() => {\n const stack = alepha.store.get(aiContextAtom) ?? [];\n const innermost = stack[stack.length - 1];\n return {\n route: router.pathname,\n page: innermost?.page,\n data: innermost?.data,\n };\n }, [alepha, router]);\n\n /**\n * Run a client tool the turn paused on, and return its result. A failure\n * is a result too: the model reads it and recovers.\n */\n const runClientTool = useCallback(\n async (name: string, input: Record<string, unknown>) => {\n try {\n if (options.clientTools?.[name]) {\n return { ok: true, result: await options.clientTools[name](input) };\n }\n if (name === \"navigate\") {\n await router.push(String(input.page), {\n params: (input.params as Record<string, string>) ?? {},\n });\n return { ok: true, page: input.page };\n }\n if (name === \"fillForm\") {\n const stack = alepha.store.get(aiContextAtom) ?? [];\n const formId = stack.findLast((it) => it.formId)?.formId;\n const form = formId ? forms.get(formId) : undefined;\n if (!form) {\n return {\n ok: false,\n error: \"No form on this page accepts being filled.\",\n };\n }\n return {\n ok: true,\n ...forms.fill(\n form,\n (input.values as Record<string, unknown>) ?? {},\n ),\n submitted: false,\n };\n }\n return { ok: false, error: `Unknown client tool '${name}'.` };\n } catch (cause) {\n return {\n ok: false,\n error: cause instanceof Error ? cause.message : String(cause),\n };\n }\n },\n [alepha, forms, router, options.clientTools],\n );\n\n /**\n * Read one stream to its end, then follow a client-tool pause with a\n * resume, until the turn stops or waits on the user.\n */\n const consume = useCallback(\n async (\n first: AsyncIterable<AiStreamEvent>,\n signal: AbortSignal,\n ): Promise<void> => {\n let stream: AsyncIterable<AiStreamEvent> | undefined = first;\n let ranTools = false;\n const succeeded: string[] = [];\n while (stream) {\n let text = \"\";\n let clientCall: AiPendingCallResource | undefined;\n for await (const event of stream) {\n if (event.type === \"conversation\" && event.conversationId) {\n idRef.current = event.conversationId;\n setConversationId(event.conversationId);\n } else if (event.type === \"text\" && event.text) {\n text += event.text;\n setStreaming(text);\n } else if (event.type === \"tool_call\") {\n setActivity(event.name);\n } else if (event.type === \"tool_result\") {\n ranTools = true;\n if (!event.isError && event.name) {\n succeeded.push(event.name);\n }\n setActivity(undefined);\n push({\n role: \"tool\",\n content: \"\",\n name: event.name,\n isError: event.isError,\n denied: Boolean(\n event.callId && deniedRef.current.has(event.callId),\n ),\n });\n } else if (event.type === \"confirm\") {\n setPending({\n callId: event.callId ?? \"\",\n name: event.name ?? \"\",\n input: event.input ?? {},\n kind: \"confirm\",\n });\n } else if (event.type === \"client_tool\") {\n clientCall = {\n callId: event.callId ?? \"\",\n name: event.name ?? \"\",\n input: event.input ?? {},\n kind: \"client_tool\",\n };\n } else if (event.type === \"error\") {\n setError(event.message ?? event.name ?? \"The assistant failed\");\n }\n // The model ran out of output tokens (or of steps): the reply is\n // marked, so it reads as cut short and not as a finished answer.\n const cut = event.type === \"end\" && event.reason === \"length\";\n if (\n (text && (event.type === \"tool_call\" || event.type === \"end\")) ||\n cut\n ) {\n push({ role: \"assistant\", content: text, ...(cut ? { cut } : {}) });\n text = \"\";\n setStreaming(\"\");\n }\n }\n setActivity(undefined);\n stream = undefined;\n if (ranTools) {\n // What the assistant ran may have changed what the page shows.\n for (const key of options.invalidates ?? []) {\n queries.invalidate(key);\n }\n if (succeeded.length) {\n options.onToolsRan?.(succeeded.splice(0));\n }\n ranTools = false;\n }\n if (clientCall && idRef.current) {\n const result = await runClientTool(clientCall.name, clientCall.input);\n stream = await api.resume(\n {\n params: { id: idRef.current },\n body: {\n callId: clientCall.callId,\n result,\n context: pageContext(),\n },\n },\n { request: { signal } },\n );\n }\n }\n },\n [\n api,\n push,\n runClientTool,\n queries,\n options.invalidates,\n options.onToolsRan,\n pageContext,\n ],\n );\n\n const send = useAction<[message: string]>(\n {\n handler: async ({ signal }, message) => {\n setError(undefined);\n push({ role: \"user\", content: message });\n const stream = await api.chat(\n {\n body: {\n conversationId: idRef.current,\n message,\n assistant: options.assistant,\n context: pageContext(),\n },\n },\n { request: { signal } },\n );\n await consume(stream, signal);\n },\n onError: (cause) => setError(cause.message),\n },\n [api, consume, options.assistant, push, pageContext],\n );\n\n const answer = useAction<[decision: \"approve\" | \"deny\"]>(\n {\n handler: async ({ signal }, decision) => {\n if (!pending || !idRef.current) {\n return;\n }\n setError(undefined);\n const callId = pending.callId;\n if (decision === \"deny\") {\n deniedRef.current.add(callId);\n }\n setPending(undefined);\n const stream = await api.resume(\n {\n params: { id: idRef.current },\n body: { callId, decision, context: pageContext() },\n },\n { request: { signal } },\n );\n await consume(stream, signal);\n },\n onError: (cause) => setError(cause.message),\n },\n [api, consume, pending, pageContext],\n );\n\n const open = useAction<[id?: string]>(\n {\n handler: async (_ctx, id) => {\n setError(undefined);\n setStreaming(\"\");\n setPending(undefined);\n idRef.current = id;\n setConversationId(id);\n if (!id) {\n setItems([]);\n return;\n }\n const detail = await api.getConversation({ params: { id } });\n setItems(\n detail.messages.map((message: AiMessageResource) => ({\n id: message.id,\n role: message.role,\n content: message.content,\n name: message.name,\n isError: message.isError,\n // `alepha/ai`'s AI_CALL_DENIED: a stored denial keeps this text.\n denied:\n message.role === \"tool\" &&\n message.content === \"Denied by the user.\",\n })),\n );\n setPending(detail.conversation.pendingCall);\n },\n onError: (cause) => setError(cause.message),\n },\n [api],\n );\n\n /**\n * End the running turn: abort the request, keep what already streamed.\n */\n const stop = () => {\n send.cancel();\n answer.cancel();\n setActivity(undefined);\n if (streaming) {\n push({ role: \"assistant\", content: streaming });\n }\n setStreaming(\"\");\n };\n\n return {\n conversationId,\n items,\n streaming,\n activity,\n pending,\n error,\n loading: send.loading || answer.loading || open.loading,\n send: (message) => send.run(message),\n approve: () => answer.run(\"approve\"),\n deny: () => answer.run(\"deny\"),\n open: (id) => open.run(id),\n stop,\n };\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Options of {@link useAiChat}.\n */\nexport interface UseAiChatOptions {\n /**\n * The `$ai` to talk to, when the app declares several.\n */\n assistant?: string;\n /**\n * A stored conversation to continue.\n */\n conversationId?: string;\n /**\n * Query keys to invalidate after a turn ran a tool, so the page re-reads\n * what the assistant may have changed (`[[\"notes\"]]`).\n */\n invalidates?: unknown[][];\n /**\n * Called after a stream in which tools ran, with the names of those that\n * succeeded, for what `invalidates` cannot reach: a page whose data its\n * route loaders fill re-runs them (`router.invalidate()`) after a write.\n */\n onToolsRan?: (names: string[]) => void;\n /**\n * The app's own client tools, by name, beside `navigate` and `fillForm`.\n * The result goes back to the model.\n */\n clientTools?: Record<string, (input: Record<string, unknown>) => unknown>;\n}\n\n/**\n * One line of the conversation as shown.\n */\nexport interface AiChatItem {\n id: string;\n role: \"user\" | \"assistant\" | \"tool\";\n content: string;\n /**\n * The tool, on a `tool` line.\n */\n name?: string;\n isError?: boolean;\n /**\n * A `tool` line the user refused on its confirmation card: an error to the\n * model, a cancellation to the user.\n */\n denied?: boolean;\n /**\n * An `assistant` line the model did not finish: the turn ended on its\n * output limit (`reason: \"length\"`). Known for a reply streamed in this\n * session only; a stored conversation does not keep it.\n */\n cut?: boolean;\n}\n\n/**\n * What {@link useAiChat} returns.\n */\nexport interface UseAiChat {\n conversationId?: string;\n items: AiChatItem[];\n /**\n * The assistant's reply as it streams, before it lands in `items`.\n */\n streaming: string;\n /**\n * The tool running right now, for a progress line.\n */\n activity?: string;\n /**\n * The mutation waiting for the user, with the input the server stored.\n */\n pending?: AiPendingCallResource;\n error?: string;\n loading: boolean;\n send: (message: string) => Promise<RunResult<void>>;\n approve: () => Promise<RunResult<void>>;\n deny: () => Promise<RunResult<void>>;\n open: (id?: string) => Promise<RunResult<void>>;\n /**\n * End the running turn and keep what already streamed.\n */\n stop: () => void;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,aAAa,UAA4B,CAAC,MAAiB;CACtE,MAAM,MAAM,UAAwB;CACpC,MAAM,SAAS,UAAU;CACzB,MAAM,QAAQ,cAAc,eAAe,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC;CAC/D,MAAM,SAAS,UAAe;CAC9B,MAAM,UAAU,eAAe;CAC/B,MAAM,CAAC,gBAAgB,qBAAqB,SAC1C,QAAQ,cACV;CACA,MAAM,CAAC,OAAO,YAAY,SAAuB,CAAC,CAAC;CACnD,MAAM,CAAC,WAAW,gBAAgB,SAAS,EAAE;CAC7C,MAAM,CAAC,UAAU,eAAe,SAA6B;CAC7D,MAAM,CAAC,SAAS,cAAc,SAA4C;CAC1E,MAAM,CAAC,OAAO,YAAY,SAA6B;CAEvD,MAAM,QAAQ,OAA2B,QAAQ,cAAc;CAE/D,MAAM,YAAY,uBAAO,IAAI,IAAY,CAAC;CAC1C,MAAM,UAAU,OAAO,CAAC;CAExB,MAAM,OAAO,aAAa,SAAiC;EACzD,QAAQ,WAAW;EACnB,MAAM,KAAK,SAAS,QAAQ;EAC5B,UAAU,YAAY,CAAC,GAAG,SAAS;GAAE;GAAI,GAAG;EAAK,CAAC,CAAC;CACrD,GAAG,CAAC,CAAC;;;;;;CAOL,MAAM,cAAc,k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,GACA,EAAE,SAAS,EAAE,OAAO,EAAE,CACxB;GACA,MAAM,QAAQ,QAAQ,MAAM;EAC9B;EACA,UAAU,UAAU,SAAS,MAAM,OAAO;CAC5C,GACA;EAAC;EAAK;EAAS;EAAS;CAAW,CACrC;CAEA,MAAM,OAAO,UACX;EACE,SAAS,OAAO,MAAM,OAAO;GAC3B,SAAS,KAAA,CAAS;GAClB,aAAa,EAAE;GACf,WAAW,KAAA,CAAS;GACpB,MAAM,UAAU;GAChB,kBAAkB,EAAE;GACpB,IAAI,CAAC,IAAI;IACP,SAAS,CAAC,CAAC;IACX;GACF;GACA,MAAM,SAAS,MAAM,IAAI,gBAAgB,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC;GAC3D,SACE,OAAO,SAAS,KAAK,aAAgC;IACnD,IAAI,QAAQ;IACZ,MAAM,QAAQ;IACd,SAAS,QAAQ;IACjB,MAAM,QAAQ;IACd,SAAS,QAAQ;IAEjB,QACE,QAAQ,SAAS,UACjB,QAAQ,YAAY;GACxB,EAAE,CACJ;GACA,WAAW,OAAO,aAAa,WAAW;EAC5C;EACA,UAAU,UAAU,SAAS,MAAM,OAAO;CAC5C,GACA,CAAC,GAAG,CACN;;;;CAKA,MAAM,aAAa;EACjB,KAAK,OAAO;EACZ,OAAO,OAAO;EACd,YAAY,KAAA,CAAS;EACrB,IAAI,WACF,KAAK;GAAE,MAAM;GAAa,SAAS;EAAU,CAAC;EAEhD,aAAa,EAAE;CACjB;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,KAAK,WAAW,OAAO,WAAW,KAAK;EAChD,OAAO,YAAY,KAAK,IAAI,OAAO;EACnC,eAAe,OAAO,IAAI,SAAS;EACnC,YAAY,OAAO,IAAI,MAAM;EAC7B,OAAO,OAAO,KAAK,IAAI,EAAE;EACzB;CACF;AACF"}
@@ -35,6 +35,15 @@ export interface AuthLoginProps {
35
35
  * component (e.g. with light/dark variants or an animation).
36
36
  */
37
37
  logo?: ReactNode;
38
+ /**
39
+ * Where the "Cancel" link under the form leads. Defaults to "/".
40
+ *
41
+ * Pass `false` to hide the link, for an application where every page
42
+ * needs an account: there "/" only leads back to this page. It is
43
+ * intentionally decoupled from the post-auth `?redirect=` target, which is
44
+ * a protected destination the visitor has not reached yet.
45
+ */
46
+ cancelPath?: string | false;
38
47
  }
39
48
  export declare const AuthLogin: (props: AuthLoginProps) => React.JSX.Element;
40
49
  //# sourceMappingURL=AuthLogin.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AuthLogin.d.ts","sourceRoot":"","sources":["../../src/auth/AuthLogin.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAK/B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAWpD,OAAO,EAAE,KAAK,SAAS,EAAqB,MAAM,OAAO,CAAC;AAW1D,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IAC/B;;;;OAIG;IACH,UAAU,CAAC,EAAE;QACX,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,OAAO,CAAC,EAAE,SAAS,CAAC;KACrB,CAAC;IACF;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;CAClB;AAED,eAAO,MAAM,SAAS,UAAW,cAAc,sBA8U9C,CAAC"}
1
+ {"version":3,"file":"AuthLogin.d.ts","sourceRoot":"","sources":["../../src/auth/AuthLogin.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAK/B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAWpD,OAAO,EAAE,KAAK,SAAS,EAAqB,MAAM,OAAO,CAAC;AAW1D,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IAC/B;;;;OAIG;IACH,UAAU,CAAC,EAAE;QACX,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,OAAO,CAAC,EAAE,SAAS,CAAC;KACrB,CAAC;IACF;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CAC7B;AAED,eAAO,MAAM,SAAS,UAAW,cAAc,sBAoV9C,CAAC"}
@@ -193,10 +193,10 @@ const AuthLogin = (props) => {
193
193
  ]
194
194
  })
195
195
  }),
196
- /* @__PURE__ */ jsx(Button, {
196
+ props.cancelPath !== false && /* @__PURE__ */ jsx(Button, {
197
197
  variant: "minimal",
198
198
  nativeButton: false,
199
- render: /* @__PURE__ */ jsx("a", { href: "/" }),
199
+ render: /* @__PURE__ */ jsx("a", { href: props.cancelPath ?? "/" }),
200
200
  children: tr("auth.login.cancel", { default: "Cancel" })
201
201
  })
202
202
  ]
@@ -1 +1 @@
1
- {"version":3,"file":"AuthLogin.js","names":[],"sources":["../../src/auth/AuthLogin.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { AlephaError, SchemaValidationError, z } from \"alepha\";\nimport type { RealmConfig } from \"alepha/api/users\";\nimport {\n type MfaChallenge,\n MfaRequiredError,\n useAuth,\n} from \"alepha/react/auth\";\nimport { FormValidationError, useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { HttpError, isHttpError } from \"alepha/server\";\nimport { AlertCircle, Mail, User } from \"lucide-react\";\nimport { type ReactNode, useMemo, useState } from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { BrandIcon } from \"../core/BrandIcon.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Separator } from \"../core/Separator.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { AuthMfaStep } from \"./AuthMfaStep.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\n\nexport interface AuthLoginProps {\n /**\n * Realm configuration (credential providers + OAuth buttons that render).\n */\n realmConfig: RealmConfig;\n /**\n * Route to the registration page. When set, a \"Sign up\" link is shown.\n */\n registerPath?: string;\n /**\n * Route to the password-reset flow. When set, a \"Forgot password?\" link is shown.\n */\n resetPasswordPath?: string;\n /**\n * Layout variant.\n * - `centered` (default): single column, form centered on the viewport.\n * - `split`: two-pane on `lg`+ — branded background panel on the left, form on the right. Collapses to centered on small screens.\n */\n variant?: \"centered\" | \"split\";\n /**\n * Background panel configuration for the `split` variant. Ignored for `centered`.\n * - `src`: image URL. When omitted, a neutral dot pattern is rendered.\n * - `overlay`: optional content drawn over the background (logo, tagline).\n */\n background?: {\n src?: string;\n overlay?: ReactNode;\n };\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n}\n\nexport const AuthLogin = (props: AuthLoginProps) => {\n const auth = useAuth();\n const router = useRouter();\n const { tr } = useI18n();\n const redirect = safeRedirect(router.query.redirect);\n const error = router.query.error;\n\n /**\n * Set once the password has been accepted and a second factor is owed.\n * While it is set, the code step replaces the credentials form.\n */\n const [challenge, setChallenge] = useState<MfaChallenge>();\n\n const credentialsProvider = props.realmConfig.authenticationMethods.find(\n (it) => it.type === \"CREDENTIALS\",\n );\n const settings = props.realmConfig.settings;\n\n const loginMethods = useMemo(() => {\n const methods: string[] = [];\n // `username: \"email\"` means the username is auto-derived from the email\n // server-side and never typed by the user — it's not a separate login\n // method from the user's perspective.\n if (settings.username !== \"none\" && settings.username !== \"email\") {\n methods.push(\"username\");\n }\n if (settings.email !== \"none\") methods.push(\"email\");\n if (settings.phoneNumber !== \"none\") methods.push(\"phone\");\n return methods;\n }, [settings]);\n\n const identifierLabel = useMemo(() => {\n if (loginMethods.length <= 1) {\n const m = loginMethods[0];\n if (m === \"email\") return tr(\"auth.login.email\", { default: \"Email\" });\n if (m === \"phone\")\n return tr(\"auth.login.phone\", { default: \"Phone number\" });\n return tr(\"auth.login.username\", { default: \"Username\" });\n }\n return tr(\"auth.login.identifier\", {\n default: \"Username, email or phone\",\n });\n }, [loginMethods, tr]);\n\n // Mail icon when the identifier is purely an email; otherwise default user icon.\n const identifierIcon =\n loginMethods.length === 1 && loginMethods[0] === \"email\" ? Mail : User;\n\n // Pick the most-precise HTML autocomplete hint so password managers and\n // browser autofill (especially iOS Keychain) pair the identifier with the\n // saved password reliably. Mixed configs fall back to `username` — the\n // WHATWG-canonical hint for \"the account identifier\".\n const identifierAutoComplete =\n loginMethods.length === 1\n ? loginMethods[0] === \"email\"\n ? \"email\"\n : loginMethods[0] === \"phone\"\n ? \"tel\"\n : \"username\"\n : \"username\";\n\n const form = useForm({\n schema: z.object({\n identifier: z.string().min(1),\n password: z.string().min(settings.passwordPolicy?.minLength || 6),\n }),\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n if (!credentialsProvider) {\n throw new AlephaError(\"Credentials provider not configured\");\n }\n try {\n await auth.login(credentialsProvider.name, {\n username: data.identifier,\n password: data.password,\n realm: props.realmConfig.realmName,\n });\n // `force: true` recreates the whole page state so every parent-layout\n // loader re-runs against the now-authenticated user. Without it, an\n // SPA push to a sibling under the same layout reuses the cached layout\n // layer and skips its loader — leaving `user`-gated bootstrap data\n // (e.g. the campaign list) stale/empty after sign-in.\n await router.push(safeRedirect(router.query.redirect), {\n force: true,\n });\n } catch (err) {\n // The password was right and the realm wants a second factor. Not a\n // failure: swap the form for the code step and carry on.\n if (err instanceof MfaRequiredError) {\n setChallenge(err.data);\n return;\n }\n // A 401 from the password grant is a refused password. Matched on the\n // status rather than on `INVALID_CREDENTIALS`, so any refusal of the\n // grant lands on the password field instead of the alert.\n if (isHttpError(err, 401)) {\n throw new FormValidationError({\n message: tr(\"auth.login.invalid\", {\n default: \"Invalid identifier or password\",\n }),\n path: \"/password\",\n });\n }\n // Other 4xx are intentional, user-facing API errors — surface as-is.\n if (err instanceof HttpError && err.status < 500) {\n throw err;\n }\n // 5xx / unexpected: never show internals to the user. Log the real\n // cause and surface a generic message.\n console.error(\"Login failed:\", err);\n throw new FormValidationError({\n message: tr(\"auth.login.error\", {\n default: \"Something went wrong. Please try again.\",\n }),\n path: \"/password\",\n });\n }\n },\n });\n\n const externalMethods = props.realmConfig.authenticationMethods.filter(\n (m) => m.type !== \"CREDENTIALS\",\n );\n\n // Autofocus the identifier field on mount - but only when credentials is the\n // *sole* login method. With OAuth/external buttons present we don't steal\n // focus (and trigger the browser's autofill popup) from a user who came to\n // click \"Continue with ...\".\n const autoFocusIdentifier = !!credentialsProvider && !externalMethods.length;\n\n const formState = useFormState(form, [\"error\", \"loading\"]);\n const formError =\n formState.error && !(formState.error instanceof SchemaValidationError)\n ? formState.error.message\n : undefined;\n const showDivider =\n !challenge && credentialsProvider && externalMethods.length > 0;\n // Propagate BOTH realm and the post-auth redirect to the register / reset\n // links — dropping `redirect` here strands a user who signs up mid-flow\n // (e.g. an OIDC authorize continuation) on the home page. Mirrors the\n // login-link construction in auth-register.\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const linkQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = linkQ ? `?${linkQ}` : \"\";\n\n const variant = props.variant ?? \"centered\";\n\n const formColumn = (\n <div className=\"flex w-full max-w-sm flex-col items-center gap-4\">\n {props.logo ??\n (settings.logoUrl ? (\n <img\n src={settings.logoUrl}\n alt={settings.displayName || props.realmConfig.realmName}\n className=\"bg-muted size-16 rounded-xl border object-cover shadow-sm\"\n />\n ) : null)}\n <Card className=\"w-full\">\n <CardContent className=\"flex flex-col gap-4\">\n {(settings.displayName || settings.description) && (\n <div className=\"flex flex-col items-center gap-1\">\n {settings.displayName && (\n <h2 className=\"text-center text-lg font-semibold\">\n {settings.displayName}\n </h2>\n )}\n {settings.description && (\n <p className=\"text-muted-foreground text-center text-sm\">\n {settings.description}\n </p>\n )}\n </div>\n )}\n\n {(error || formError) && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{error || formError}</AlertDescription>\n </Alert>\n )}\n\n {challenge && (\n <AuthMfaStep\n challenge={challenge}\n onVerified={async () => {\n await router.push(safeRedirect(router.query.redirect), {\n force: true,\n });\n }}\n onCancel={() => setChallenge(undefined)}\n />\n )}\n\n {!challenge && credentialsProvider && (\n <form {...form.props} className=\"flex flex-col gap-4\">\n <Control\n label={identifierLabel}\n input={form.input.identifier}\n icon={identifierIcon}\n autoComplete={identifierAutoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- a caller-requested autofocus, see `autoFocus` in form/Control.tsx\n autoFocus={autoFocusIdentifier}\n />\n <Control\n label={tr(\"auth.login.password\", {\n default: \"Password\",\n })}\n input={form.input.password}\n password\n />\n <Button type=\"submit\" loading={formState.loading}>\n {tr(\"auth.login.submit\", { default: \"Sign in\" })}\n </Button>\n {settings.resetPasswordAllowed && (\n <a\n href={`${props.resetPasswordPath ?? \"/auth/reset-password\"}${realmQuery}`}\n className=\"text-muted-foreground hover:text-foreground text-center text-sm underline-offset-4 hover:underline\"\n >\n {tr(\"auth.login.forgot\", {\n default: \"Forgot password?\",\n })}\n </a>\n )}\n </form>\n )}\n\n {showDivider && (\n <div className=\"flex items-center gap-3\">\n <Separator className=\"flex-1\" />\n <span className=\"text-muted-foreground text-xs\">\n {tr(\"auth.login.or\", { default: \"OR\" })}\n </span>\n <Separator className=\"flex-1\" />\n </div>\n )}\n\n {!challenge && externalMethods.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n {externalMethods.map((method) => {\n const provider =\n method.name.charAt(0).toUpperCase() + method.name.slice(1);\n return (\n <Button\n key={method.name}\n variant=\"outlined\"\n onClick={() =>\n auth.login(method.name, {\n redirect,\n realm: props.realmConfig.realmName,\n })\n }\n >\n <BrandIcon provider={method.name} />\n {tr(\"auth.login.continueWith\", {\n default: `Continue with ${provider}`,\n args: [provider],\n })}\n </Button>\n );\n })}\n </div>\n )}\n\n {!challenge && settings.registrationAllowed && (\n <p className=\"text-muted-foreground text-center text-sm\">\n {tr(\"auth.login.noAccount\", {\n default: \"Don't have an account?\",\n })}{\" \"}\n <a\n href={`${props.registerPath ?? \"/auth/register\"}${realmQuery}`}\n className=\"text-foreground underline-offset-4 hover:underline\"\n >\n {tr(\"auth.login.signUp\", { default: \"Sign up\" })}\n </a>\n </p>\n )}\n </CardContent>\n </Card>\n <Button variant=\"minimal\" nativeButton={false} render={<a href=\"/\" />}>\n {tr(\"auth.login.cancel\", { default: \"Cancel\" })}\n </Button>\n </div>\n );\n\n if (variant === \"split\") {\n const bgSrc = props.background?.src;\n const dotPattern =\n \"url(\\\"data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23000000'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E\\\")\";\n return (\n <div className=\"flex min-h-svh\">\n <div\n className=\"bg-muted relative hidden flex-col items-center justify-center overflow-hidden p-16 lg:flex lg:w-1/2\"\n style={\n bgSrc\n ? {\n backgroundImage: `url(${JSON.stringify(bgSrc)})`,\n backgroundSize: \"cover\",\n backgroundPosition: \"center\",\n }\n : undefined\n }\n >\n {!bgSrc && (\n <div\n aria-hidden\n className=\"absolute inset-0 opacity-[0.04] dark:opacity-[0.08]\"\n style={{ backgroundImage: dotPattern }}\n />\n )}\n {props.background?.overlay && (\n <div className=\"relative z-10\">{props.background.overlay}</div>\n )}\n </div>\n <div className=\"bg-background flex flex-1 items-center justify-center p-6\">\n {formColumn}\n </div>\n </div>\n );\n }\n\n return (\n <div className=\"flex min-h-svh flex-1 items-center justify-center p-6\">\n {formColumn}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+DA,MAAa,aAAa,UAA0B;CAClD,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,UAAU;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,WAAW,aAAa,OAAO,MAAM,QAAQ;CACnD,MAAM,QAAQ,OAAO,MAAM;;;;;CAM3B,MAAM,CAAC,WAAW,gBAAgB,SAAuB;CAEzD,MAAM,sBAAsB,MAAM,YAAY,sBAAsB,MACjE,OAAO,GAAG,SAAS,aACtB;CACA,MAAM,WAAW,MAAM,YAAY;CAEnC,MAAM,eAAe,cAAc;EACjC,MAAM,UAAoB,CAAC;EAI3B,IAAI,SAAS,aAAa,UAAU,SAAS,aAAa,SACxD,QAAQ,KAAK,UAAU;EAEzB,IAAI,SAAS,UAAU,QAAQ,QAAQ,KAAK,OAAO;EACnD,IAAI,SAAS,gBAAgB,QAAQ,QAAQ,KAAK,OAAO;EACzD,OAAO;CACT,GAAG,CAAC,QAAQ,CAAC;CAEb,MAAM,kBAAkB,cAAc;EACpC,IAAI,aAAa,UAAU,GAAG;GAC5B,MAAM,IAA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BAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,CACF;;CAET;CAEA,OACE,oBAAC,OAAD;EAAK,WAAU;EACZ,UAAA;CACE,CAAA;AAET"}
1
+ {"version":3,"file":"AuthLogin.js","names":[],"sources":["../../src/auth/AuthLogin.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { AlephaError, SchemaValidationError, z } from \"alepha\";\nimport type { RealmConfig } from \"alepha/api/users\";\nimport {\n type MfaChallenge,\n MfaRequiredError,\n useAuth,\n} from \"alepha/react/auth\";\nimport { FormValidationError, useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { HttpError, isHttpError } from \"alepha/server\";\nimport { AlertCircle, Mail, User } from \"lucide-react\";\nimport { type ReactNode, useMemo, useState } from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { BrandIcon } from \"../core/BrandIcon.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Separator } from \"../core/Separator.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { AuthMfaStep } from \"./AuthMfaStep.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\n\nexport interface AuthLoginProps {\n /**\n * Realm configuration (credential providers + OAuth buttons that render).\n */\n realmConfig: RealmConfig;\n /**\n * Route to the registration page. When set, a \"Sign up\" link is shown.\n */\n registerPath?: string;\n /**\n * Route to the password-reset flow. When set, a \"Forgot password?\" link is shown.\n */\n resetPasswordPath?: string;\n /**\n * Layout variant.\n * - `centered` (default): single column, form centered on the viewport.\n * - `split`: two-pane on `lg`+ — branded background panel on the left, form on the right. Collapses to centered on small screens.\n */\n variant?: \"centered\" | \"split\";\n /**\n * Background panel configuration for the `split` variant. Ignored for `centered`.\n * - `src`: image URL. When omitted, a neutral dot pattern is rendered.\n * - `overlay`: optional content drawn over the background (logo, tagline).\n */\n background?: {\n src?: string;\n overlay?: ReactNode;\n };\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n /**\n * Where the \"Cancel\" link under the form leads. Defaults to \"/\".\n *\n * Pass `false` to hide the link, for an application where every page\n * needs an account: there \"/\" only leads back to this page. It is\n * intentionally decoupled from the post-auth `?redirect=` target, which is\n * a protected destination the visitor has not reached yet.\n */\n cancelPath?: string | false;\n}\n\nexport const AuthLogin = (props: AuthLoginProps) => {\n const auth = useAuth();\n const router = useRouter<any>();\n const { tr } = useI18n();\n const redirect = safeRedirect(router.query.redirect);\n const error = router.query.error;\n\n /**\n * Set once the password has been accepted and a second factor is owed.\n * While it is set, the code step replaces the credentials form.\n */\n const [challenge, setChallenge] = useState<MfaChallenge>();\n\n const credentialsProvider = props.realmConfig.authenticationMethods.find(\n (it) => it.type === \"CREDENTIALS\",\n );\n const settings = props.realmConfig.settings;\n\n const loginMethods = useMemo(() => {\n const methods: string[] = [];\n // `username: \"email\"` means the username is auto-derived from the email\n // server-side and never typed by the user — it's not a separate login\n // method from the user's perspective.\n if (settings.username !== \"none\" && settings.username !== \"email\") {\n methods.push(\"username\");\n }\n if (settings.email !== \"none\") methods.push(\"email\");\n if (settings.phoneNumber !== \"none\") methods.push(\"phone\");\n return methods;\n }, [settings]);\n\n const identifierLabel = useMemo(() => {\n if (loginMethods.length <= 1) {\n const m = loginMethods[0];\n if (m === \"email\") return tr(\"auth.login.email\", { default: \"Email\" });\n if (m === \"phone\")\n return tr(\"auth.login.phone\", { default: \"Phone number\" });\n return tr(\"auth.login.username\", { default: \"Username\" });\n }\n return tr(\"auth.login.identifier\", {\n default: \"Username, email or phone\",\n });\n }, [loginMethods, tr]);\n\n // Mail icon when the identifier is purely an email; otherwise default user icon.\n const identifierIcon =\n loginMethods.length === 1 && loginMethods[0] === \"email\" ? Mail : User;\n\n // Pick the most-precise HTML autocomplete hint so password managers and\n // browser autofill (especially iOS Keychain) pair the identifier with the\n // saved password reliably. Mixed configs fall back to `username` — the\n // WHATWG-canonical hint for \"the account identifier\".\n const identifierAutoComplete =\n loginMethods.length === 1\n ? loginMethods[0] === \"email\"\n ? \"email\"\n : loginMethods[0] === \"phone\"\n ? \"tel\"\n : \"username\"\n : \"username\";\n\n const form = useForm({\n schema: z.object({\n identifier: z.string().min(1),\n password: z.string().min(settings.passwordPolicy?.minLength || 6),\n }),\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n if (!credentialsProvider) {\n throw new AlephaError(\"Credentials provider not configured\");\n }\n try {\n await auth.login(credentialsProvider.name, {\n username: data.identifier,\n password: data.password,\n realm: props.realmConfig.realmName,\n });\n // `force: true` recreates the whole page state so every parent-layout\n // loader re-runs against the now-authenticated user. Without it, an\n // SPA push to a sibling under the same layout reuses the cached layout\n // layer and skips its loader — leaving `user`-gated bootstrap data\n // (e.g. the campaign list) stale/empty after sign-in.\n await router.push(safeRedirect(router.query.redirect), {\n force: true,\n });\n } catch (err) {\n // The password was right and the realm wants a second factor. Not a\n // failure: swap the form for the code step and carry on.\n if (err instanceof MfaRequiredError) {\n setChallenge(err.data);\n return;\n }\n // A 401 from the password grant is a refused password. Matched on the\n // status rather than on `INVALID_CREDENTIALS`, so any refusal of the\n // grant lands on the password field instead of the alert.\n if (isHttpError(err, 401)) {\n throw new FormValidationError({\n message: tr(\"auth.login.invalid\", {\n default: \"Invalid identifier or password\",\n }),\n path: \"/password\",\n });\n }\n // Other 4xx are intentional, user-facing API errors — surface as-is.\n if (err instanceof HttpError && err.status < 500) {\n throw err;\n }\n // 5xx / unexpected: never show internals to the user. Log the real\n // cause and surface a generic message.\n console.error(\"Login failed:\", err);\n throw new FormValidationError({\n message: tr(\"auth.login.error\", {\n default: \"Something went wrong. Please try again.\",\n }),\n path: \"/password\",\n });\n }\n },\n });\n\n const externalMethods = props.realmConfig.authenticationMethods.filter(\n (m) => m.type !== \"CREDENTIALS\",\n );\n\n // Autofocus the identifier field on mount - but only when credentials is the\n // *sole* login method. With OAuth/external buttons present we don't steal\n // focus (and trigger the browser's autofill popup) from a user who came to\n // click \"Continue with ...\".\n const autoFocusIdentifier = !!credentialsProvider && !externalMethods.length;\n\n const formState = useFormState(form, [\"error\", \"loading\"]);\n const formError =\n formState.error && !(formState.error instanceof SchemaValidationError)\n ? formState.error.message\n : undefined;\n const showDivider =\n !challenge && credentialsProvider && externalMethods.length > 0;\n // Propagate BOTH realm and the post-auth redirect to the register / reset\n // links — dropping `redirect` here strands a user who signs up mid-flow\n // (e.g. an OIDC authorize continuation) on the home page. Mirrors the\n // login-link construction in auth-register.\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const linkQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = linkQ ? `?${linkQ}` : \"\";\n\n const variant = props.variant ?? \"centered\";\n\n const formColumn = (\n <div className=\"flex w-full max-w-sm flex-col items-center gap-4\">\n {props.logo ??\n (settings.logoUrl ? (\n <img\n src={settings.logoUrl}\n alt={settings.displayName || props.realmConfig.realmName}\n className=\"bg-muted size-16 rounded-xl border object-cover shadow-sm\"\n />\n ) : null)}\n <Card className=\"w-full\">\n <CardContent className=\"flex flex-col gap-4\">\n {(settings.displayName || settings.description) && (\n <div className=\"flex flex-col items-center gap-1\">\n {settings.displayName && (\n <h2 className=\"text-center text-lg font-semibold\">\n {settings.displayName}\n </h2>\n )}\n {settings.description && (\n <p className=\"text-muted-foreground text-center text-sm\">\n {settings.description}\n </p>\n )}\n </div>\n )}\n\n {(error || formError) && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{error || formError}</AlertDescription>\n </Alert>\n )}\n\n {challenge && (\n <AuthMfaStep\n challenge={challenge}\n onVerified={async () => {\n await router.push(safeRedirect(router.query.redirect), {\n force: true,\n });\n }}\n onCancel={() => setChallenge(undefined)}\n />\n )}\n\n {!challenge && credentialsProvider && (\n <form {...form.props} className=\"flex flex-col gap-4\">\n <Control\n label={identifierLabel}\n input={form.input.identifier}\n icon={identifierIcon}\n autoComplete={identifierAutoComplete}\n // oxlint-disable-next-line jsx-a11y/no-autofocus -- a caller-requested autofocus, see `autoFocus` in form/Control.tsx\n autoFocus={autoFocusIdentifier}\n />\n <Control\n label={tr(\"auth.login.password\", {\n default: \"Password\",\n })}\n input={form.input.password}\n password\n />\n <Button type=\"submit\" loading={formState.loading}>\n {tr(\"auth.login.submit\", { default: \"Sign in\" })}\n </Button>\n {settings.resetPasswordAllowed && (\n <a\n href={`${props.resetPasswordPath ?? \"/auth/reset-password\"}${realmQuery}`}\n className=\"text-muted-foreground hover:text-foreground text-center text-sm underline-offset-4 hover:underline\"\n >\n {tr(\"auth.login.forgot\", {\n default: \"Forgot password?\",\n })}\n </a>\n )}\n </form>\n )}\n\n {showDivider && (\n <div className=\"flex items-center gap-3\">\n <Separator className=\"flex-1\" />\n <span className=\"text-muted-foreground text-xs\">\n {tr(\"auth.login.or\", { default: \"OR\" })}\n </span>\n <Separator className=\"flex-1\" />\n </div>\n )}\n\n {!challenge && externalMethods.length > 0 && (\n <div className=\"flex flex-col gap-2\">\n {externalMethods.map((method) => {\n const provider =\n method.name.charAt(0).toUpperCase() + method.name.slice(1);\n return (\n <Button\n key={method.name}\n variant=\"outlined\"\n onClick={() =>\n auth.login(method.name, {\n redirect,\n realm: props.realmConfig.realmName,\n })\n }\n >\n <BrandIcon provider={method.name} />\n {tr(\"auth.login.continueWith\", {\n default: `Continue with ${provider}`,\n args: [provider],\n })}\n </Button>\n );\n })}\n </div>\n )}\n\n {!challenge && settings.registrationAllowed && (\n <p className=\"text-muted-foreground text-center text-sm\">\n {tr(\"auth.login.noAccount\", {\n default: \"Don't have an account?\",\n })}{\" \"}\n <a\n href={`${props.registerPath ?? \"/auth/register\"}${realmQuery}`}\n className=\"text-foreground underline-offset-4 hover:underline\"\n >\n {tr(\"auth.login.signUp\", { default: \"Sign up\" })}\n </a>\n </p>\n )}\n </CardContent>\n </Card>\n {props.cancelPath !== false && (\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={props.cancelPath ?? \"/\"} />}\n >\n {tr(\"auth.login.cancel\", { default: \"Cancel\" })}\n </Button>\n )}\n </div>\n );\n\n if (variant === \"split\") {\n const bgSrc = props.background?.src;\n const dotPattern =\n \"url(\\\"data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23000000'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E\\\")\";\n return (\n <div className=\"flex min-h-svh\">\n <div\n className=\"bg-muted relative hidden flex-col items-center justify-center overflow-hidden p-16 lg:flex lg:w-1/2\"\n style={\n bgSrc\n ? {\n backgroundImage: `url(${JSON.stringify(bgSrc)})`,\n backgroundSize: \"cover\",\n backgroundPosition: \"center\",\n }\n : undefined\n }\n >\n {!bgSrc && (\n <div\n aria-hidden\n className=\"absolute inset-0 opacity-[0.04] dark:opacity-[0.08]\"\n style={{ backgroundImage: dotPattern }}\n />\n )}\n {props.background?.overlay && (\n <div className=\"relative z-10\">{props.background.overlay}</div>\n )}\n </div>\n <div className=\"bg-background flex flex-1 items-center justify-center p-6\">\n {formColumn}\n </div>\n </div>\n );\n }\n\n return (\n <div className=\"flex min-h-svh flex-1 items-center justify-center p-6\">\n {formColumn}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,WAAU;SAET,UAAA,GAAG,qBAAqB,EAAE,SAAS,UAAU,CAAC;QAC9C,CAAA;OACF;;KAEM;;GACT,CAAA;GACL,MAAM,eAAe,SACpB,oBAAC,QAAD;IACE,SAAQ;IACR,cAAc;IACd,QAAQ,oBAAC,KAAD,EAAG,MAAM,MAAM,cAAc,IAAM,CAAA;IAE1C,UAAA,GAAG,qBAAqB,EAAE,SAAS,SAAS,CAAC;GACxC,CAAA;EAEP;;CAGP,IAAI,YAAY,SAAS;EACvB,MAAM,QAAQ,MAAM,YAAY;EAGhC,OACE,qBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACE,qBAAC,OAAD;IACE,WAAU;IACV,OACE,QACI;KACE,iBAAiB,OAAO,KAAK,UAAU,KAAK,EAAE;KAC9C,gBAAgB;KAChB,oBAAoB;IACtB,IACA,KAAA;IATR,UAAA,CAYG,CAAC,SACA,oBAAC,OAAD;KACE,eAAA;KACA,WAAU;KACV,OAAO,EAAE,iBAAiB,mWAAW;IACtC,CAAA,GAEF,MAAM,YAAY,WACjB,oBAAC,OAAD;KAAK,WAAU;KAAiB,UAAA,MAAM,WAAW;IAAa,CAAA,CAE7D;GACL,CAAA,GAAA,oBAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,CACF;;CAET;CAEA,OACE,oBAAC,OAAD;EAAK,WAAU;EACZ,UAAA;CACE,CAAA;AAET"}
@@ -28,8 +28,11 @@ export interface AuthRegisterProps {
28
28
  * an unauthenticated registration must land somewhere public (home), not the
29
29
  * protected destination the user was *heading* to — which would only bounce
30
30
  * them back to this page.
31
+ *
32
+ * Pass `false` to hide the link, for an application where every page
33
+ * needs an account.
31
34
  */
32
- cancelPath?: string;
35
+ cancelPath?: string | false;
33
36
  /**
34
37
  * Render the form even though `settings.registrationAllowed` is `false`.
35
38
  *
@@ -1 +1 @@
1
- {"version":3,"file":"AuthRegister.d.ts","sourceRoot":"","sources":["../../src/auth/AuthRegister.tsx"],"names":[],"mappings":"AAAA,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;;;;OAQG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,eAAO,MAAM,YAAY,UAAW,iBAAiB,sBA8YpD,CAAC"}
@@ -281,7 +281,7 @@ const AuthRegister = (props) => {
281
281
  })
282
282
  })
283
283
  }),
284
- !isVerifying && /* @__PURE__ */ jsx(Button, {
284
+ !isVerifying && props.cancelPath !== false && /* @__PURE__ */ jsx(Button, {
285
285
  variant: "minimal",
286
286
  nativeButton: false,
287
287
  render: /* @__PURE__ */ jsx("a", { href: props.cancelPath ?? "/" }),
@@ -1 +1 @@
1
- {"version":3,"file":"AuthRegister.js","names":[],"sources":["../../src/auth/AuthRegister.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { SchemaValidationError, z } from \"alepha\";\nimport type {\n RealmConfig,\n RegistrationIntentResponse,\n UserController,\n} from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useAuth } from \"alepha/react/auth\";\nimport { useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { AlertCircle } from \"lucide-react\";\nimport {\n type ReactNode,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Label } from \"../core/Label.tsx\";\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSeparator,\n InputOTPSlot,\n} from \"../otp/InputOTP.tsx\";\nimport { AuthRegisterCentered } from \"./AuthRegisterCentered.tsx\";\nimport { AuthRegisterFormPhase } from \"./AuthRegisterFormPhase.tsx\";\nimport { AuthRegisterRealmLogo } from \"./AuthRegisterRealmLogo.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\nimport type { TurnstileWidgetHandle } from \"./TurnstileWidget.tsx\";\n\nexport interface AuthRegisterProps {\n /**\n * Realm configuration (drives required fields, verification step, OAuth buttons).\n */\n realmConfig: RealmConfig;\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n /**\n * Route to the login page. When set, a \"Sign in\" link is shown.\n */\n loginPath?: string;\n /**\n * Optional banner rendered above the registration form (form phase only).\n * Used to contextualize the flow when the user arrives via a CTA, e.g.\n * \"Before creating a campaign, create an account.\"\n */\n message?: ReactNode;\n /**\n * Where the \"Cancel\" button abandons to. Defaults to \"/\". This is\n * intentionally decoupled from the post-auth `?redirect=` target: cancelling\n * an unauthenticated registration must land somewhere public (home), not the\n * protected destination the user was *heading* to — which would only bounce\n * them back to this page.\n */\n cancelPath?: string;\n /**\n * Render the form even though `settings.registrationAllowed` is `false`.\n *\n * For a visitor the application has already vouched for out of band - an\n * invitation link, a signup code - who would otherwise meet the closed\n * alert and stop. Presentation only: the server decides, through the\n * realm's `isPreAuthorized` seam, and refuses this submit like any other if\n * {@link preAuthToken} does not hold up.\n */\n preAuthorized?: boolean;\n /**\n * Pre-fill the email field and stop it being edited.\n *\n * Set it alongside {@link preAuthToken}, which is bound to one address:\n * letting the field be typed over only produces a server-side refusal the\n * visitor cannot act on.\n */\n lockedEmail?: string;\n /**\n * The application's opaque proof that this address may register into a\n * closed realm. Passed through to the register request untouched.\n */\n preAuthToken?: string;\n /**\n * Where a successful registration lands, overriding `?redirect=`.\n *\n * A prop rather than a URL param because the submit handler is built ONCE,\n * at mount, and closes over whatever `redirect` was then: a page that\n * decides the destination and seeds the query afterwards has already\n * missed it, and the user lands on the default with nothing to explain\n * why. A prop is read on the render that builds the handler.\n *\n * Sanitised like the query value, since the two are the same kind of thing.\n */\n redirect?: string;\n}\n\nexport const AuthRegister = (props: AuthRegisterProps) => {\n const auth = useAuth();\n const userCtrl = useClient<UserController>();\n const router = useRouter();\n const { tr } = useI18n();\n const redirect = safeRedirect(props.redirect ?? router.query.redirect);\n // Surface upstream auth errors (e.g. failed OAuth callback redirects with\n // `?error=...`) — same pattern as AuthLogin. Without this the user lands on\n // a fresh-looking registration page with no clue why.\n const queryError =\n typeof router.query.error === \"string\" ? router.query.error : undefined;\n\n const [state, setState] = useState<State>({ phase: \"form\" });\n const [emailCode, setEmailCode] = useState(\"\");\n const [phoneCode, setPhoneCode] = useState(\"\");\n const [verifyError, setVerifyError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n const captchaSiteKey = props.realmConfig.captchaSiteKey;\n const [captchaToken, setCaptchaToken] = useState<string | undefined>();\n const captchaRef = useRef<TurnstileWidgetHandle | null>(null);\n // The handler reads the token the widget issued last through a ref, so a\n // submit never posts a token captured by an earlier render.\n const captchaTokenRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n captchaTokenRef.current = captchaToken;\n }, [captchaToken]);\n\n const credentialsProvider = props.realmConfig.authenticationMethods.find(\n (it) => it.type === \"CREDENTIALS\",\n );\n const settings = props.realmConfig.settings;\n // The realm decides, unless the application has already vouched for this\n // particular visitor. Both halves are presentation: the gate is\n // `RegistrationService`, which refuses a submit that the seam does not\n // recognise however the form got rendered.\n const allowed =\n props.preAuthorized === true || settings.registrationAllowed !== false;\n\n const schema = useMemo(() => {\n // Optionality is decided as each field is built, because that is the only\n // thing the form reads: `FormModel` derives both the required marker and\n // the pre-submit check from `z.schema.requiredInputKeys(schema)`, which asks\n // whether the field is optional or defaulted.\n //\n // This used to declare every field optional and then push the configured\n // names onto the array returned by `z.schema.requiredInputKeys(s)` , a TypeBox\n // habit, where a JSON Schema's `required` was a live array hanging off the\n // schema. The zod implementation computes a fresh array from the shape, so\n // the pushes mutated a detached value and vanished: a realm with\n // `email: \"required\"` still rendered Email with no asterisk and let an\n // empty one through to the server.\n const names = settings.firstNameLastName === \"required\";\n const shape = {\n firstName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n username:\n settings.username === \"required\"\n ? z.text({ trim: true, pattern: settings.usernameRegExp })\n : z.text({ trim: true, pattern: settings.usernameRegExp }).optional(),\n email: settings.email === \"required\" ? z.email() : z.email().optional(),\n phoneNumber:\n settings.phoneNumber === \"required\" ? z.e164() : z.e164().optional(),\n password: z.string().min(settings.passwordPolicy?.minLength ?? 8),\n };\n\n // The runtime shape varies with the realm, but the *type* must not: every\n // consumer below reads `data.email`, `data.username` and the rest as\n // possibly-absent. Widening to the all-optional shape keeps one stable\n // type instead of a union of eight.\n return z.object(shape) as unknown as ReturnType<typeof registerFormSchema>;\n }, [settings]);\n\n const form = useForm({\n schema,\n // A locked address is the form's starting value, not a field the visitor\n // fills. It arrives before mount (the page resolves the token in its\n // loader), which is what lets `useForm` anchor it here.\n initialValues: props.lockedEmail ? { email: props.lockedEmail } : undefined,\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n try {\n const intent = await userCtrl.createRegistrationIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n firstName: data.firstName,\n lastName: data.lastName,\n username: data.username,\n // The locked address wins over whatever the field holds: it is\n // the one the token is bound to, and a disabled input is a\n // presentation fact rather than a guarantee.\n email: props.lockedEmail ?? data.email,\n phoneNumber: data.phoneNumber,\n password: data.password,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n preAuthToken: props.preAuthToken,\n },\n });\n const identifier =\n data.username ?? props.lockedEmail ?? data.email ?? data.phoneNumber;\n if (\n intent.expectEmailVerification ||\n intent.expectPhoneVerification ||\n intent.expectCaptcha\n ) {\n setState({\n phase: \"verification\",\n intent,\n credentials: identifier\n ? { identifier, password: data.password }\n : undefined,\n });\n return;\n }\n await userCtrl.createUserFromIntent({\n body: { intentId: intent.intentId },\n });\n if (identifier && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: identifier,\n password: data.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n // Turnstile tokens are single-use — force a fresh challenge so the\n // user can retry after a server-side failure.\n captchaRef.current?.reset();\n throw err;\n }\n },\n });\n\n const formState = useFormState(form, [\"error\", \"values\", \"loading\"]);\n const formError =\n formState.error && !(formState.error instanceof SchemaValidationError)\n ? formState.error.message\n : undefined;\n const passwordValue = String(formState.values?.password ?? \"\");\n\n const firstFieldId =\n (settings.firstNameLastName !== \"none\" && form.input.firstName?.props.id) ||\n (settings.username !== \"none\" &&\n settings.username !== \"email\" &&\n form.input.username?.props.id) ||\n (settings.email !== \"none\" && form.input.email?.props.id) ||\n (settings.phoneNumber !== \"none\" && form.input.phoneNumber?.props.id) ||\n form.input.password.props.id;\n\n useEffect(() => {\n if (state.phase !== \"form\" || !firstFieldId) return;\n const el = document.getElementById(\n String(firstFieldId),\n ) as HTMLInputElement | null;\n el?.focus();\n }, [state.phase, firstFieldId]);\n\n const handleVerify = async () => {\n if (!state.intent) return;\n setSubmitting(true);\n setVerifyError(null);\n try {\n await userCtrl.createUserFromIntent({\n body: {\n intentId: state.intent.intentId,\n emailCode: state.intent.expectEmailVerification\n ? emailCode\n : undefined,\n phoneCode: state.intent.expectPhoneVerification\n ? phoneCode\n : undefined,\n },\n });\n if (state.credentials && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: state.credentials.identifier,\n password: state.credentials.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n setVerifyError(\n err instanceof Error\n ? err.message\n : tr(\"auth.register.verifyFailed\", {\n default: \"Verification failed\",\n }),\n );\n } finally {\n setSubmitting(false);\n }\n };\n\n // Query appended to the \"already have an account? sign in\" link: the realm,\n // plus the post-auth redirect (`?redirect=`) so signing in returns the user\n // to wherever registering would have sent them (it's dropped otherwise).\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const loginQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = loginQ ? `?${loginQ}` : \"\";\n\n const externalMethods = props.realmConfig.authenticationMethods.filter(\n (m) => m.type !== \"CREDENTIALS\",\n );\n const showDivider = credentialsProvider && externalMethods.length > 0;\n const isVerifying = state.phase === \"verification\" && state.intent;\n const canSubmitVerify =\n !isVerifying ||\n ((!state.intent!.expectEmailVerification || emailCode.length === 6) &&\n (!state.intent!.expectPhoneVerification || phoneCode.length === 6));\n\n const contentRef = useRef<HTMLDivElement>(null);\n const [contentHeight, setContentHeight] = useState<number | undefined>(\n undefined,\n );\n useLayoutEffect(() => {\n const el = contentRef.current;\n if (!el) return;\n setContentHeight(el.scrollHeight);\n const ro = new ResizeObserver(() => {\n setContentHeight(el.scrollHeight);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n return (\n <AuthRegisterCentered>\n {props.logo ?? (\n <AuthRegisterRealmLogo\n settings={settings}\n realmName={props.realmConfig.realmName}\n />\n )}\n <Card className=\"w-full\">\n <CardContent\n className=\"overflow-hidden p-0 transition-[height] duration-300 ease-out\"\n style={\n contentHeight !== undefined ? { height: contentHeight } : undefined\n }\n >\n <div ref={contentRef}>\n <div\n key={state.phase}\n className=\"animate-in fade-in flex flex-col gap-4 px-6 duration-300\"\n >\n {isVerifying ? (\n <>\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.register.verifyTitle\", {\n default: \"Verify your account\",\n })}\n </h2>\n <p className=\"text-muted-foreground text-center text-sm\">\n {tr(\"auth.register.verifyHint\", {\n default:\n \"Please enter the verification code(s) sent to you.\",\n })}\n </p>\n {verifyError && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{verifyError}</AlertDescription>\n </Alert>\n )}\n {state.intent!.expectEmailVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"emailCode\">\n {tr(\"auth.register.emailCode\", {\n default: \"Email verification code\",\n })}\n </Label>\n <InputOTP\n id=\"emailCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={emailCode}\n onChange={setEmailCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n {state.intent!.expectPhoneVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"phoneCode\">\n {tr(\"auth.register.phoneCode\", {\n default: \"Phone verification code\",\n })}\n </Label>\n <InputOTP\n id=\"phoneCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={phoneCode}\n onChange={setPhoneCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n <Button\n onClick={handleVerify}\n loading={submitting}\n disabled={!canSubmitVerify}\n >\n {tr(\"auth.register.verifySubmit\", {\n default: \"Complete registration\",\n })}\n </Button>\n <Button\n variant=\"minimal\"\n onClick={() => setState({ phase: \"form\" })}\n >\n {tr(\"auth.register.verifyBack\", {\n default: \"Back to registration\",\n })}\n </Button>\n </>\n ) : (\n <AuthRegisterFormPhase\n allowed={allowed}\n form={form}\n formError={formError ?? queryError}\n loading={formState.loading}\n passwordValue={passwordValue}\n settings={settings}\n realmName={props.realmConfig.realmName}\n credentialsProvider={credentialsProvider}\n externalMethods={externalMethods}\n showDivider={showDivider}\n redirect={redirect}\n loginPath={props.loginPath}\n realmQuery={realmQuery}\n auth={auth}\n captchaSiteKey={captchaSiteKey}\n captchaToken={captchaToken}\n captchaRef={captchaRef}\n onCaptchaToken={setCaptchaToken}\n message={props.message}\n lockedEmail={props.lockedEmail}\n />\n )}\n </div>\n </div>\n </CardContent>\n </Card>\n {!isVerifying && (\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={props.cancelPath ?? \"/\"} />}\n >\n {tr(\"auth.register.cancel\", { default: \"Cancel\" })}\n </Button>\n )}\n </AuthRegisterCentered>\n );\n};\n\ntype Phase = \"form\" | \"verification\";\n\ninterface State {\n phase: Phase;\n intent?: RegistrationIntentResponse;\n credentials?: { identifier: string; password: string };\n}\n\n/**\n * The reference shape of the registration form, with every configurable field\n * optional.\n *\n * `AuthRegister` builds its real schema from the realm settings, so which\n * fields are optional changes per realm. This exists purely to give that\n * schema one stable TypeScript type: the handler reads `data.email`,\n * `data.username` and `data.phoneNumber` as possibly-absent regardless of what\n * a given realm requires, which is the correct type for code that has to\n * compile against all of them.\n */\nconst registerFormSchema = () =>\n z.object({\n firstName: z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: z.text({ trim: true, maxLength: 100 }).optional(),\n username: z.text({ trim: true }).optional(),\n email: z.email().optional(),\n phoneNumber: z.e164().optional(),\n password: z.string(),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2GA,MAAa,gBAAgB,UAA6B;CACxD,MAAM,OAAO,QAAQ;CACrB,MAAM,WAAW,UAA0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B"}
1
+ {"version":3,"file":"AuthRegister.js","names":[],"sources":["../../src/auth/AuthRegister.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { SchemaValidationError, z } from \"alepha\";\nimport type {\n RealmConfig,\n RegistrationIntentResponse,\n UserController,\n} from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useAuth } from \"alepha/react/auth\";\nimport { useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { AlertCircle } from \"lucide-react\";\nimport {\n type ReactNode,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Label } from \"../core/Label.tsx\";\nimport {\n InputOTP,\n InputOTPGroup,\n InputOTPSeparator,\n InputOTPSlot,\n} from \"../otp/InputOTP.tsx\";\nimport { AuthRegisterCentered } from \"./AuthRegisterCentered.tsx\";\nimport { AuthRegisterFormPhase } from \"./AuthRegisterFormPhase.tsx\";\nimport { AuthRegisterRealmLogo } from \"./AuthRegisterRealmLogo.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\nimport type { TurnstileWidgetHandle } from \"./TurnstileWidget.tsx\";\n\nexport interface AuthRegisterProps {\n /**\n * Realm configuration (drives required fields, verification step, OAuth buttons).\n */\n realmConfig: RealmConfig;\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n /**\n * Route to the login page. When set, a \"Sign in\" link is shown.\n */\n loginPath?: string;\n /**\n * Optional banner rendered above the registration form (form phase only).\n * Used to contextualize the flow when the user arrives via a CTA, e.g.\n * \"Before creating a campaign, create an account.\"\n */\n message?: ReactNode;\n /**\n * Where the \"Cancel\" button abandons to. Defaults to \"/\". This is\n * intentionally decoupled from the post-auth `?redirect=` target: cancelling\n * an unauthenticated registration must land somewhere public (home), not the\n * protected destination the user was *heading* to — which would only bounce\n * them back to this page.\n *\n * Pass `false` to hide the link, for an application where every page\n * needs an account.\n */\n cancelPath?: string | false;\n /**\n * Render the form even though `settings.registrationAllowed` is `false`.\n *\n * For a visitor the application has already vouched for out of band - an\n * invitation link, a signup code - who would otherwise meet the closed\n * alert and stop. Presentation only: the server decides, through the\n * realm's `isPreAuthorized` seam, and refuses this submit like any other if\n * {@link preAuthToken} does not hold up.\n */\n preAuthorized?: boolean;\n /**\n * Pre-fill the email field and stop it being edited.\n *\n * Set it alongside {@link preAuthToken}, which is bound to one address:\n * letting the field be typed over only produces a server-side refusal the\n * visitor cannot act on.\n */\n lockedEmail?: string;\n /**\n * The application's opaque proof that this address may register into a\n * closed realm. Passed through to the register request untouched.\n */\n preAuthToken?: string;\n /**\n * Where a successful registration lands, overriding `?redirect=`.\n *\n * A prop rather than a URL param because the submit handler is built ONCE,\n * at mount, and closes over whatever `redirect` was then: a page that\n * decides the destination and seeds the query afterwards has already\n * missed it, and the user lands on the default with nothing to explain\n * why. A prop is read on the render that builds the handler.\n *\n * Sanitised like the query value, since the two are the same kind of thing.\n */\n redirect?: string;\n}\n\nexport const AuthRegister = (props: AuthRegisterProps) => {\n const auth = useAuth();\n const userCtrl = useClient<UserController>();\n const router = useRouter<any>();\n const { tr } = useI18n();\n const redirect = safeRedirect(props.redirect ?? router.query.redirect);\n // Surface upstream auth errors (e.g. failed OAuth callback redirects with\n // `?error=...`) — same pattern as AuthLogin. Without this the user lands on\n // a fresh-looking registration page with no clue why.\n const queryError =\n typeof router.query.error === \"string\" ? router.query.error : undefined;\n\n const [state, setState] = useState<State>({ phase: \"form\" });\n const [emailCode, setEmailCode] = useState(\"\");\n const [phoneCode, setPhoneCode] = useState(\"\");\n const [verifyError, setVerifyError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n const captchaSiteKey = props.realmConfig.captchaSiteKey;\n const [captchaToken, setCaptchaToken] = useState<string | undefined>();\n const captchaRef = useRef<TurnstileWidgetHandle | null>(null);\n // The handler reads the token the widget issued last through a ref, so a\n // submit never posts a token captured by an earlier render.\n const captchaTokenRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n captchaTokenRef.current = captchaToken;\n }, [captchaToken]);\n\n const credentialsProvider = props.realmConfig.authenticationMethods.find(\n (it) => it.type === \"CREDENTIALS\",\n );\n const settings = props.realmConfig.settings;\n // The realm decides, unless the application has already vouched for this\n // particular visitor. Both halves are presentation: the gate is\n // `RegistrationService`, which refuses a submit that the seam does not\n // recognise however the form got rendered.\n const allowed =\n props.preAuthorized === true || settings.registrationAllowed !== false;\n\n const schema = useMemo(() => {\n // Optionality is decided as each field is built, because that is the only\n // thing the form reads: `FormModel` derives both the required marker and\n // the pre-submit check from `z.schema.requiredInputKeys(schema)`, which asks\n // whether the field is optional or defaulted.\n //\n // This used to declare every field optional and then push the configured\n // names onto the array returned by `z.schema.requiredInputKeys(s)` , a TypeBox\n // habit, where a JSON Schema's `required` was a live array hanging off the\n // schema. The zod implementation computes a fresh array from the shape, so\n // the pushes mutated a detached value and vanished: a realm with\n // `email: \"required\"` still rendered Email with no asterisk and let an\n // empty one through to the server.\n const names = settings.firstNameLastName === \"required\";\n const shape = {\n firstName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: names\n ? z.text({ trim: true, maxLength: 100 })\n : z.text({ trim: true, maxLength: 100 }).optional(),\n username:\n settings.username === \"required\"\n ? z.text({ trim: true, pattern: settings.usernameRegExp })\n : z.text({ trim: true, pattern: settings.usernameRegExp }).optional(),\n email: settings.email === \"required\" ? z.email() : z.email().optional(),\n phoneNumber:\n settings.phoneNumber === \"required\" ? z.e164() : z.e164().optional(),\n password: z.string().min(settings.passwordPolicy?.minLength ?? 8),\n };\n\n // The runtime shape varies with the realm, but the *type* must not: every\n // consumer below reads `data.email`, `data.username` and the rest as\n // possibly-absent. Widening to the all-optional shape keeps one stable\n // type instead of a union of eight.\n return z.object(shape) as unknown as ReturnType<typeof registerFormSchema>;\n }, [settings]);\n\n const form = useForm({\n schema,\n // A locked address is the form's starting value, not a field the visitor\n // fills. It arrives before mount (the page resolves the token in its\n // loader), which is what lets `useForm` anchor it here.\n initialValues: props.lockedEmail ? { email: props.lockedEmail } : undefined,\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n try {\n const intent = await userCtrl.createRegistrationIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n firstName: data.firstName,\n lastName: data.lastName,\n username: data.username,\n // The locked address wins over whatever the field holds: it is\n // the one the token is bound to, and a disabled input is a\n // presentation fact rather than a guarantee.\n email: props.lockedEmail ?? data.email,\n phoneNumber: data.phoneNumber,\n password: data.password,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n preAuthToken: props.preAuthToken,\n },\n });\n const identifier =\n data.username ?? props.lockedEmail ?? data.email ?? data.phoneNumber;\n if (\n intent.expectEmailVerification ||\n intent.expectPhoneVerification ||\n intent.expectCaptcha\n ) {\n setState({\n phase: \"verification\",\n intent,\n credentials: identifier\n ? { identifier, password: data.password }\n : undefined,\n });\n return;\n }\n await userCtrl.createUserFromIntent({\n body: { intentId: intent.intentId },\n });\n if (identifier && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: identifier,\n password: data.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n // Turnstile tokens are single-use — force a fresh challenge so the\n // user can retry after a server-side failure.\n captchaRef.current?.reset();\n throw err;\n }\n },\n });\n\n const formState = useFormState(form, [\"error\", \"values\", \"loading\"]);\n const formError =\n formState.error && !(formState.error instanceof SchemaValidationError)\n ? formState.error.message\n : undefined;\n const passwordValue = String(formState.values?.password ?? \"\");\n\n const firstFieldId =\n (settings.firstNameLastName !== \"none\" && form.input.firstName?.props.id) ||\n (settings.username !== \"none\" &&\n settings.username !== \"email\" &&\n form.input.username?.props.id) ||\n (settings.email !== \"none\" && form.input.email?.props.id) ||\n (settings.phoneNumber !== \"none\" && form.input.phoneNumber?.props.id) ||\n form.input.password.props.id;\n\n useEffect(() => {\n if (state.phase !== \"form\" || !firstFieldId) return;\n const el = document.getElementById(\n String(firstFieldId),\n ) as HTMLInputElement | null;\n el?.focus();\n }, [state.phase, firstFieldId]);\n\n const handleVerify = async () => {\n if (!state.intent) return;\n setSubmitting(true);\n setVerifyError(null);\n try {\n await userCtrl.createUserFromIntent({\n body: {\n intentId: state.intent.intentId,\n emailCode: state.intent.expectEmailVerification\n ? emailCode\n : undefined,\n phoneCode: state.intent.expectPhoneVerification\n ? phoneCode\n : undefined,\n },\n });\n if (state.credentials && credentialsProvider) {\n await auth.login(credentialsProvider.name, {\n username: state.credentials.identifier,\n password: state.credentials.password,\n realm: props.realmConfig.realmName,\n });\n }\n // `force: true` so parent-layout loaders re-run against the freshly\n // authenticated user — see the note in AuthLogin.tsx.\n await router.push(redirect, { force: true });\n } catch (err) {\n setVerifyError(\n err instanceof Error\n ? err.message\n : tr(\"auth.register.verifyFailed\", {\n default: \"Verification failed\",\n }),\n );\n } finally {\n setSubmitting(false);\n }\n };\n\n // Query appended to the \"already have an account? sign in\" link: the realm,\n // plus the post-auth redirect (`?redirect=`) so signing in returns the user\n // to wherever registering would have sent them (it's dropped otherwise).\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const loginQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = loginQ ? `?${loginQ}` : \"\";\n\n const externalMethods = props.realmConfig.authenticationMethods.filter(\n (m) => m.type !== \"CREDENTIALS\",\n );\n const showDivider = credentialsProvider && externalMethods.length > 0;\n const isVerifying = state.phase === \"verification\" && state.intent;\n const canSubmitVerify =\n !isVerifying ||\n ((!state.intent!.expectEmailVerification || emailCode.length === 6) &&\n (!state.intent!.expectPhoneVerification || phoneCode.length === 6));\n\n const contentRef = useRef<HTMLDivElement>(null);\n const [contentHeight, setContentHeight] = useState<number | undefined>(\n undefined,\n );\n useLayoutEffect(() => {\n const el = contentRef.current;\n if (!el) return;\n setContentHeight(el.scrollHeight);\n const ro = new ResizeObserver(() => {\n setContentHeight(el.scrollHeight);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n return (\n <AuthRegisterCentered>\n {props.logo ?? (\n <AuthRegisterRealmLogo\n settings={settings}\n realmName={props.realmConfig.realmName}\n />\n )}\n <Card className=\"w-full\">\n <CardContent\n className=\"overflow-hidden p-0 transition-[height] duration-300 ease-out\"\n style={\n contentHeight !== undefined ? { height: contentHeight } : undefined\n }\n >\n <div ref={contentRef}>\n <div\n key={state.phase}\n className=\"animate-in fade-in flex flex-col gap-4 px-6 duration-300\"\n >\n {isVerifying ? (\n <>\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.register.verifyTitle\", {\n default: \"Verify your account\",\n })}\n </h2>\n <p className=\"text-muted-foreground text-center text-sm\">\n {tr(\"auth.register.verifyHint\", {\n default:\n \"Please enter the verification code(s) sent to you.\",\n })}\n </p>\n {verifyError && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{verifyError}</AlertDescription>\n </Alert>\n )}\n {state.intent!.expectEmailVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"emailCode\">\n {tr(\"auth.register.emailCode\", {\n default: \"Email verification code\",\n })}\n </Label>\n <InputOTP\n id=\"emailCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={emailCode}\n onChange={setEmailCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n {state.intent!.expectPhoneVerification && (\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"phoneCode\">\n {tr(\"auth.register.phoneCode\", {\n default: \"Phone verification code\",\n })}\n </Label>\n <InputOTP\n id=\"phoneCode\"\n maxLength={6}\n autoComplete=\"one-time-code\"\n\n value={phoneCode}\n onChange={setPhoneCode}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n </InputOTPGroup>\n <InputOTPSeparator />\n <InputOTPGroup>\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n )}\n <Button\n onClick={handleVerify}\n loading={submitting}\n disabled={!canSubmitVerify}\n >\n {tr(\"auth.register.verifySubmit\", {\n default: \"Complete registration\",\n })}\n </Button>\n <Button\n variant=\"minimal\"\n onClick={() => setState({ phase: \"form\" })}\n >\n {tr(\"auth.register.verifyBack\", {\n default: \"Back to registration\",\n })}\n </Button>\n </>\n ) : (\n <AuthRegisterFormPhase\n allowed={allowed}\n form={form}\n formError={formError ?? queryError}\n loading={formState.loading}\n passwordValue={passwordValue}\n settings={settings}\n realmName={props.realmConfig.realmName}\n credentialsProvider={credentialsProvider}\n externalMethods={externalMethods}\n showDivider={showDivider}\n redirect={redirect}\n loginPath={props.loginPath}\n realmQuery={realmQuery}\n auth={auth}\n captchaSiteKey={captchaSiteKey}\n captchaToken={captchaToken}\n captchaRef={captchaRef}\n onCaptchaToken={setCaptchaToken}\n message={props.message}\n lockedEmail={props.lockedEmail}\n />\n )}\n </div>\n </div>\n </CardContent>\n </Card>\n {!isVerifying && props.cancelPath !== false && (\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={props.cancelPath ?? \"/\"} />}\n >\n {tr(\"auth.register.cancel\", { default: \"Cancel\" })}\n </Button>\n )}\n </AuthRegisterCentered>\n );\n};\n\ntype Phase = \"form\" | \"verification\";\n\ninterface State {\n phase: Phase;\n intent?: RegistrationIntentResponse;\n credentials?: { identifier: string; password: string };\n}\n\n/**\n * The reference shape of the registration form, with every configurable field\n * optional.\n *\n * `AuthRegister` builds its real schema from the realm settings, so which\n * fields are optional changes per realm. This exists purely to give that\n * schema one stable TypeScript type: the handler reads `data.email`,\n * `data.username` and `data.phoneNumber` as possibly-absent regardless of what\n * a given realm requires, which is the correct type for code that has to\n * compile against all of them.\n */\nconst registerFormSchema = () =>\n z.object({\n firstName: z.text({ trim: true, maxLength: 100 }).optional(),\n lastName: z.text({ trim: true, maxLength: 100 }).optional(),\n username: z.text({ trim: true }).optional(),\n email: z.email().optional(),\n phoneNumber: z.e164().optional(),\n password: z.string(),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8GA,MAAa,gBAAgB,UAA6B;CACxD,MAAM,OAAO,QAAQ;CACrB,MAAM,WAAW,UAA0B;CAC3C,MAAM,SAAS,UAAe;CAC9B,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,WAAW,aAAa,MAAM,YAAY,OAAO,MAAM,QAAQ;CAIrE,MAAM,aACJ,OAAO,OAAO,MAAM,UAAU,WAAW,OAAO,MAAM,QAAQ,KAAA;CAEhE,MAAM,CAAC,OAAO,YAAY,SAAgB,EAAE,OAAO,OAAO,CAAC;CAC3D,MAAM,CAAC,WAAW,gBAAgB,SAAS,EAAE;CAC7C,MAAM,CAAC,WAAW,gBAAgB,SAAS,EAAE;CAC7C,MAAM,CAAC,aAAa,kBAAkB,SAAwB,IAAI;CAClE,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAElD,MAAM,iBAAi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AAA;SACP;QACP,CAAA,CAAA;;OAEP,oBAAC,QAAD;QACE,SAAS;QACT,SAAS;QACT,UAAU,CAAC;QAEV,UAAA,GAAG,8BAA8B,EAChC,SAAS,wBACX,CAAC;OACK,CAAA;OACR,oBAAC,QAAD;QACE,SAAQ;QACR,eAAe,SAAS,EAAE,OAAO,OAAO,CAAC;QAExC,UAAA,GAAG,4BAA4B,EAC9B,SAAS,uBACX,CAAC;OACK,CAAA;MACR,EAAA,CAAA,IAEF,oBAAC,uBAAD;OACW;OACH;OACN,WAAW,aAAa;OACxB,SAAS,UAAU;OACJ;OACL;OACV,WAAW,MAAM,YAAY;OACR;OACJ;OACJ;OACH;OACV,WAAW,MAAM;OACL;OACN;OACU;OACF;OACF;OACZ,gBAAgB;OAChB,SAAS,MAAM;OACf,aAAa,MAAM;MACpB,CAAA;KAEA,GA1HE,MAAM,KA0HR;IACF,CAAA;GACM,CAAA;EACT,CAAA;EACL,CAAC,eAAe,MAAM,eAAe,SACpC,oBAAC,QAAD;GACE,SAAQ;GACR,cAAc;GACd,QAAQ,oBAAC,KAAD,EAAG,MAAM,MAAM,cAAc,IAAM,CAAA;GAE1C,UAAA,GAAG,wBAAwB,EAAE,SAAS,SAAS,CAAC;EAC3C,CAAA;CAEU,EAAA,CAAA;AAE1B"}
@@ -16,6 +16,14 @@ export interface AuthResetPasswordProps {
16
16
  * component (e.g. with light/dark variants or an animation).
17
17
  */
18
18
  logo?: ReactNode;
19
+ /**
20
+ * Where the "Cancel" link under the form leads. Defaults to the
21
+ * `?redirect=` target of the URL, else "/".
22
+ *
23
+ * Pass `false` to hide the link, for an application where every page
24
+ * needs an account: there the default only leads back to sign-in.
25
+ */
26
+ cancelPath?: string | false;
19
27
  }
20
28
  export declare const AuthResetPassword: (props: AuthResetPasswordProps) => React.JSX.Element;
21
29
  //# sourceMappingURL=AuthResetPassword.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AuthResetPassword.d.ts","sourceRoot":"","sources":["../../src/auth/AuthResetPassword.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAK/B,OAAO,KAAK,EAEV,WAAW,EAEZ,MAAM,kBAAkB,CAAC;AAO1B,OAAO,EAAE,KAAK,SAAS,EAA+B,MAAM,OAAO,CAAC;AAepE,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;CAClB;AAWD,eAAO,MAAM,iBAAiB,UAAW,sBAAsB,sBAuX9D,CAAC"}
1
+ {"version":3,"file":"AuthResetPassword.d.ts","sourceRoot":"","sources":["../../src/auth/AuthResetPassword.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAK/B,OAAO,KAAK,EAEV,WAAW,EAEZ,MAAM,kBAAkB,CAAC;AAO1B,OAAO,EAAE,KAAK,SAAS,EAA+B,MAAM,OAAO,CAAC;AAepE,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CAC7B;AAWD,eAAO,MAAM,iBAAiB,UAAW,sBAAsB,sBAyX9D,CAAC"}
@@ -272,10 +272,10 @@ const AuthResetPassword = (props) => {
272
272
  })] })]
273
273
  })
274
274
  }),
275
- /* @__PURE__ */ jsx(Button, {
275
+ props.cancelPath !== false && /* @__PURE__ */ jsx(Button, {
276
276
  variant: "minimal",
277
277
  nativeButton: false,
278
- render: /* @__PURE__ */ jsx("a", { href: redirect }),
278
+ render: /* @__PURE__ */ jsx("a", { href: props.cancelPath ?? redirect }),
279
279
  children: tr("auth.reset.cancel", { default: "Cancel" })
280
280
  })
281
281
  ]
@@ -1 +1 @@
1
- {"version":3,"file":"AuthResetPassword.js","names":[],"sources":["../../src/auth/AuthResetPassword.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { AlephaError, SchemaValidationError, z } from \"alepha\";\nimport type {\n PasswordResetIntentResponse,\n RealmConfig,\n UserController,\n} from \"alepha/api/users\";\nimport { resetPasswordRequestSchema } from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { AlertCircle, CheckCircle2, Info } from \"lucide-react\";\nimport { type ReactNode, useEffect, useRef, useState } from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Label } from \"../core/Label.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { iconFor } from \"../form/iconHint.tsx\";\nimport { InputOTP, InputOTPGroup, InputOTPSlot } from \"../otp/InputOTP.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\nimport {\n TurnstileWidget,\n type TurnstileWidgetHandle,\n} from \"./TurnstileWidget.tsx\";\n\nexport interface AuthResetPasswordProps {\n /**\n * Realm configuration (controls verification channel and password rules).\n */\n realmConfig: RealmConfig;\n /**\n * Route to the login page, used after a successful reset.\n */\n loginPath?: string;\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n}\n\ntype Step = \"email\" | \"code\" | \"password\" | \"success\";\n\ninterface State {\n step: Step;\n intent?: PasswordResetIntentResponse;\n email?: string;\n code?: string;\n}\n\nexport const AuthResetPassword = (props: AuthResetPasswordProps) => {\n const router = useRouter();\n const { tr } = useI18n();\n const userCtrl = useClient<UserController>();\n const [state, setState] = useState<State>({ step: \"email\" });\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n const [code, setCode] = useState(\"\");\n const redirect = safeRedirect(router.query.redirect);\n\n const settings = props.realmConfig.settings;\n const allowed = settings?.resetPasswordAllowed !== false;\n // Keep BOTH realm and the post-auth redirect on the \"back to sign in\"\n // links so a reset started mid-flow (OIDC continuation) resumes after\n // login. Mirrors auth-login / auth-register.\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const linkQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = linkQ ? `?${linkQ}` : \"\";\n\n /**\n * Captcha, mirroring the registration screen.\n *\n * `createPasswordResetIntent` rejects a request with no token whenever the\n * realm sets `captchaRequired` — it sends mail in our name, so it is gated\n * exactly like registration. Without a widget here the screen could not\n * satisfy that gate at all and every reset answered 400.\n */\n const captchaSiteKey = props.realmConfig.captchaSiteKey;\n const [captchaToken, setCaptchaToken] = useState<string | undefined>();\n const captchaRef = useRef<TurnstileWidgetHandle | null>(null);\n /*\n * The handler reads the token the widget issued last through a ref, so a\n * submit never posts a token captured by an earlier render. Same shape as\n * `AuthRegister.tsx`.\n */\n const captchaTokenRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n captchaTokenRef.current = captchaToken;\n }, [captchaToken]);\n\n /**\n * Turnstile tokens are single-use, and both the first send and every resend\n * hit the same gated endpoint. Drop the spent token and re-arm the widget\n * so the next request carries a fresh one rather than a replay the server\n * will refuse.\n */\n const consumeCaptcha = () => {\n if (!captchaSiteKey) return;\n setCaptchaToken(undefined);\n captchaRef.current?.reset();\n };\n\n const emailForm = useForm({\n schema: resetPasswordRequestSchema,\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n setError(null);\n try {\n const intent = await userCtrl.createPasswordResetIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n email: data.email,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n },\n });\n setState({ step: \"code\", intent, email: data.email });\n } finally {\n consumeCaptcha();\n }\n },\n });\n\n const passwordForm = useForm(\n {\n schema: z.object({\n password: z.string().min(8),\n confirmPassword: z.string().min(8),\n }),\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n if (data.password !== data.confirmPassword) {\n throw new AlephaError(\n tr(\"auth.reset.passwordsMismatch\", {\n default: \"Passwords do not match\",\n }),\n );\n }\n if (!state.intent || !state.code) {\n throw new AlephaError(\n tr(\"auth.reset.invalidState\", { default: \"Invalid reset state\" }),\n );\n }\n await userCtrl.completePasswordReset({\n body: {\n intentId: state.intent.intentId,\n code: state.code,\n newPassword: data.password,\n },\n });\n setState({ step: \"success\" });\n },\n },\n [state.intent, state.code],\n );\n\n const emailState = useFormState(emailForm, [\"loading\", \"error\"]);\n const passwordState = useFormState(passwordForm, [\"loading\", \"error\"]);\n const emailSubmitting = emailState.loading;\n const passwordSubmitting = passwordState.loading;\n // A handler that throws (mismatched passwords, a wrong code, a refused\n // captcha) lands in the form's error state, not in `error`; reading only\n // `loading` showed nothing at all after a failed submit.\n const submitError = [passwordState.error, emailState.error].find(\n (err) => err && !(err instanceof SchemaValidationError),\n )?.message;\n\n const handleCodeSubmit = () => {\n if (code.length === 6) {\n setState((s) => ({ ...s, step: \"password\", code }));\n }\n };\n\n const handleResend = async () => {\n if (!state.email) return;\n setSubmitting(true);\n setError(null);\n try {\n const intent = await userCtrl.createPasswordResetIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n email: state.email,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n },\n });\n setState((s) => ({ ...s, intent }));\n } catch (e) {\n setError(\n e instanceof Error\n ? e.message\n : tr(\"auth.reset.resendFailed\", {\n default: \"Failed to resend code\",\n }),\n );\n } finally {\n setSubmitting(false);\n consumeCaptcha();\n }\n };\n\n return (\n <div className=\"flex min-h-svh flex-1 items-center justify-center p-6\">\n <div className=\"flex w-full max-w-sm flex-col items-center gap-4\">\n {props.logo ??\n (settings?.logoUrl ? (\n <img\n src={settings.logoUrl}\n alt={settings.displayName || props.realmConfig.realmName}\n className=\"bg-muted size-16 rounded-xl border object-cover shadow-sm\"\n />\n ) : null)}\n <Card className=\"w-full\">\n <CardContent className=\"flex flex-col gap-4\">\n {(error ?? submitError) && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{error ?? submitError}</AlertDescription>\n </Alert>\n )}\n {!allowed ? (\n <>\n <Alert>\n <AlertCircle className=\"size-4\" />\n <AlertDescription>\n {tr(\"auth.reset.disabled\", {\n default:\n \"Password reset is not available. Please contact your administrator.\",\n })}\n </AlertDescription>\n </Alert>\n <Button\n render={\n <a\n href={`${props.loginPath ?? \"/auth/login\"}${realmQuery}`}\n />\n }\n >\n {tr(\"auth.reset.backToSignIn\", {\n default: \"Back to sign in\",\n })}\n </Button>\n </>\n ) : state.step === \"email\" ? (\n <form {...emailForm.props} className=\"flex flex-col gap-4\">\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.reset.title\", { default: \"Reset password\" })}\n </h2>\n <p className=\"text-muted-foreground text-sm\">\n {tr(\"auth.reset.emailHint\", {\n default: \"Enter your email address to reset your password\",\n })}\n </p>\n <Control\n label={tr(\"auth.reset.email\", { default: \"Email\" })}\n input={emailForm.input.email}\n icon={iconFor(\"email\")}\n />\n {captchaSiteKey && (\n <TurnstileWidget\n ref={captchaRef}\n siteKey={captchaSiteKey}\n onToken={setCaptchaToken}\n className=\"flex justify-center\"\n />\n )}\n <Button\n type=\"submit\"\n loading={emailSubmitting}\n disabled={!!captchaSiteKey && !captchaToken}\n >\n {tr(\"auth.reset.sendCode\", {\n default: \"Send verification code\",\n })}\n </Button>\n </form>\n ) : state.step === \"code\" ? (\n <div className=\"flex flex-col gap-4\">\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.reset.title\", { default: \"Reset password\" })}\n </h2>\n <Alert>\n <Info className=\"size-4\" />\n <AlertDescription>\n {tr(\"auth.reset.codeSent\", {\n default: \"We've sent a verification code to your email.\",\n })}\n </AlertDescription>\n </Alert>\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"code\">\n {tr(\"auth.reset.codeLabel\", {\n default: \"Enter the 6-digit code\",\n })}\n </Label>\n <InputOTP\n id=\"code\"\n maxLength={6}\n\n value={code}\n onChange={(value) => setCode(value.replace(/\\D/g, \"\"))}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n <Button onClick={handleCodeSubmit} disabled={code.length !== 6}>\n {tr(\"auth.reset.continue\", { default: \"Continue\" })}\n </Button>\n {/* Resend calls the same gated endpoint as the first send,\n and the token that got us here is already spent — so this\n step needs its own challenge rather than reusing one. */}\n {captchaSiteKey && (\n <TurnstileWidget\n ref={captchaRef}\n siteKey={captchaSiteKey}\n onToken={setCaptchaToken}\n className=\"flex justify-center\"\n />\n )}\n <Button\n variant=\"minimal\"\n onClick={handleResend}\n loading={submitting}\n disabled={!!captchaSiteKey && !captchaToken}\n >\n {tr(\"auth.reset.resend\", { default: \"Resend code\" })}\n </Button>\n </div>\n ) : state.step === \"password\" ? (\n <form {...passwordForm.props} className=\"flex flex-col gap-4\">\n {/* Hidden identifier so password managers know which saved\n credential the new password belongs to. Without it,\n Safari/Chrome won't offer to update the existing entry. */}\n {state.email && (\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value={state.email}\n readOnly\n hidden\n />\n )}\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.reset.title\", { default: \"Reset password\" })}\n </h2>\n <p className=\"text-muted-foreground text-sm\">\n {tr(\"auth.reset.newPasswordHint\", {\n default: \"Create your new password\",\n })}\n </p>\n <Control\n label={tr(\"auth.reset.newPassword\", {\n default: \"New password\",\n })}\n input={passwordForm.input.password}\n password\n autoComplete=\"new-password\"\n />\n <Control\n label={tr(\"auth.reset.confirmPassword\", {\n default: \"Confirm password\",\n })}\n input={passwordForm.input.confirmPassword}\n password\n autoComplete=\"new-password\"\n />\n <Button type=\"submit\" loading={passwordSubmitting}>\n {tr(\"auth.reset.setPassword\", {\n default: \"Set new password\",\n })}\n </Button>\n </form>\n ) : (\n <>\n <Alert>\n <CheckCircle2 className=\"size-4\" />\n <AlertDescription>\n {tr(\"auth.reset.success\", {\n default: \"Your password has been reset successfully.\",\n })}\n </AlertDescription>\n </Alert>\n <Button\n render={\n <a\n href={`${props.loginPath ?? \"/auth/login\"}${realmQuery}`}\n />\n }\n >\n {tr(\"auth.reset.backToSignIn\", {\n default: \"Back to sign in\",\n })}\n </Button>\n </>\n )}\n </CardContent>\n </Card>\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={redirect} />}\n >\n {tr(\"auth.reset.cancel\", { default: \"Cancel\" })}\n </Button>\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyDA,MAAa,qBAAqB,UAAkC;CAClE,MAAM,SAAS,UAAU;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,WAAW,UAA0B;CAC3C,MAAM,CAAC,OAAO,YAAY,SAAgB,EAAE,MAAM,QAAQ,CAAC;CAC3D,MAAM,CAAC,OAAO,YAAY,SAAwB,IAAI;CACtD,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,CAAC,MAAM,WAAW,SAAS,EAAE;CACnC,MAA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BAAC,kBAAD,EAAA,UACG,GAAG,sBAAsB,EACxB,SAAS,6CACX,CAAC,EACe,CAAA,CACb,EAAA,CAAA,GACP,oBAAC,QAAD;OACE,QACE,oBAAC,KAAD,EACE,MAAM,GAAG,MAAM,aAAa,gBAAgB,aAC7C,CAAA;OAGF,UAAA,GAAG,2BAA2B,EAC7B,SAAS,kBACX,CAAC;MACK,CAAA,CACR,EAAA,CAAA,CAEO;;IACT,CAAA;IACN,oBAAC,QAAD;KACE,SAAQ;KACR,cAAc;KACd,QAAQ,oBAAC,KAAD,EAAG,MAAM,SAAW,CAAA;KAE3B,UAAA,GAAG,qBAAqB,EAAE,SAAS,SAAS,CAAC;IACxC,CAAA;GACL;;CACF,CAAA;AAET"}
1
+ {"version":3,"file":"AuthResetPassword.js","names":[],"sources":["../../src/auth/AuthResetPassword.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { AlephaError, SchemaValidationError, z } from \"alepha\";\nimport type {\n PasswordResetIntentResponse,\n RealmConfig,\n UserController,\n} from \"alepha/api/users\";\nimport { resetPasswordRequestSchema } from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useForm, useFormState } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useRouter } from \"alepha/react/router\";\nimport { AlertCircle, CheckCircle2, Info } from \"lucide-react\";\nimport { type ReactNode, useEffect, useRef, useState } from \"react\";\n\nimport { Alert, AlertDescription } from \"../core/Alert.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { Card, CardContent } from \"../core/Card.tsx\";\nimport { Label } from \"../core/Label.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { iconFor } from \"../form/iconHint.tsx\";\nimport { InputOTP, InputOTPGroup, InputOTPSlot } from \"../otp/InputOTP.tsx\";\nimport { safeRedirect } from \"./safeRedirect.ts\";\nimport {\n TurnstileWidget,\n type TurnstileWidgetHandle,\n} from \"./TurnstileWidget.tsx\";\n\nexport interface AuthResetPasswordProps {\n /**\n * Realm configuration (controls verification channel and password rules).\n */\n realmConfig: RealmConfig;\n /**\n * Route to the login page, used after a successful reset.\n */\n loginPath?: string;\n /**\n * Custom logo node, rendered above the form. When provided, it replaces\n * the default `settings.logoUrl` <img>. Use this to inject a branded\n * component (e.g. with light/dark variants or an animation).\n */\n logo?: ReactNode;\n /**\n * Where the \"Cancel\" link under the form leads. Defaults to the\n * `?redirect=` target of the URL, else \"/\".\n *\n * Pass `false` to hide the link, for an application where every page\n * needs an account: there the default only leads back to sign-in.\n */\n cancelPath?: string | false;\n}\n\ntype Step = \"email\" | \"code\" | \"password\" | \"success\";\n\ninterface State {\n step: Step;\n intent?: PasswordResetIntentResponse;\n email?: string;\n code?: string;\n}\n\nexport const AuthResetPassword = (props: AuthResetPasswordProps) => {\n const router = useRouter<any>();\n const { tr } = useI18n();\n const userCtrl = useClient<UserController>();\n const [state, setState] = useState<State>({ step: \"email\" });\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n const [code, setCode] = useState(\"\");\n const redirect = safeRedirect(router.query.redirect);\n\n const settings = props.realmConfig.settings;\n const allowed = settings?.resetPasswordAllowed !== false;\n // Keep BOTH realm and the post-auth redirect on the \"back to sign in\"\n // links so a reset started mid-flow (OIDC continuation) resumes after\n // login. Mirrors auth-login / auth-register.\n const realmBit = props.realmConfig.realmName\n ? `realm=${encodeURIComponent(props.realmConfig.realmName)}`\n : \"\";\n const redirectBit =\n typeof router.query.redirect === \"string\" && router.query.redirect\n ? `redirect=${encodeURIComponent(router.query.redirect)}`\n : \"\";\n const linkQ = [realmBit, redirectBit].filter(Boolean).join(\"&\");\n const realmQuery = linkQ ? `?${linkQ}` : \"\";\n\n /**\n * Captcha, mirroring the registration screen.\n *\n * `createPasswordResetIntent` rejects a request with no token whenever the\n * realm sets `captchaRequired` — it sends mail in our name, so it is gated\n * exactly like registration. Without a widget here the screen could not\n * satisfy that gate at all and every reset answered 400.\n */\n const captchaSiteKey = props.realmConfig.captchaSiteKey;\n const [captchaToken, setCaptchaToken] = useState<string | undefined>();\n const captchaRef = useRef<TurnstileWidgetHandle | null>(null);\n /*\n * The handler reads the token the widget issued last through a ref, so a\n * submit never posts a token captured by an earlier render. Same shape as\n * `AuthRegister.tsx`.\n */\n const captchaTokenRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n captchaTokenRef.current = captchaToken;\n }, [captchaToken]);\n\n /**\n * Turnstile tokens are single-use, and both the first send and every resend\n * hit the same gated endpoint. Drop the spent token and re-arm the widget\n * so the next request carries a fresh one rather than a replay the server\n * will refuse.\n */\n const consumeCaptcha = () => {\n if (!captchaSiteKey) return;\n setCaptchaToken(undefined);\n captchaRef.current?.reset();\n };\n\n const emailForm = useForm({\n schema: resetPasswordRequestSchema,\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n setError(null);\n try {\n const intent = await userCtrl.createPasswordResetIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n email: data.email,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n },\n });\n setState({ step: \"code\", intent, email: data.email });\n } finally {\n consumeCaptcha();\n }\n },\n });\n\n const passwordForm = useForm(\n {\n schema: z.object({\n password: z.string().min(8),\n confirmPassword: z.string().min(8),\n }),\n // Handled here: every error this form throws is rendered by the page itself,\n // under its field or in the alert above the form. Without an `onError`,\n // a mounted `ActionErrorToaster` toasted the same sentence a second time.\n onError: () => {},\n handler: async (data) => {\n if (data.password !== data.confirmPassword) {\n throw new AlephaError(\n tr(\"auth.reset.passwordsMismatch\", {\n default: \"Passwords do not match\",\n }),\n );\n }\n if (!state.intent || !state.code) {\n throw new AlephaError(\n tr(\"auth.reset.invalidState\", { default: \"Invalid reset state\" }),\n );\n }\n await userCtrl.completePasswordReset({\n body: {\n intentId: state.intent.intentId,\n code: state.code,\n newPassword: data.password,\n },\n });\n setState({ step: \"success\" });\n },\n },\n [state.intent, state.code],\n );\n\n const emailState = useFormState(emailForm, [\"loading\", \"error\"]);\n const passwordState = useFormState(passwordForm, [\"loading\", \"error\"]);\n const emailSubmitting = emailState.loading;\n const passwordSubmitting = passwordState.loading;\n // A handler that throws (mismatched passwords, a wrong code, a refused\n // captcha) lands in the form's error state, not in `error`; reading only\n // `loading` showed nothing at all after a failed submit.\n const submitError = [passwordState.error, emailState.error].find(\n (err) => err && !(err instanceof SchemaValidationError),\n )?.message;\n\n const handleCodeSubmit = () => {\n if (code.length === 6) {\n setState((s) => ({ ...s, step: \"password\", code }));\n }\n };\n\n const handleResend = async () => {\n if (!state.email) return;\n setSubmitting(true);\n setError(null);\n try {\n const intent = await userCtrl.createPasswordResetIntent({\n query: { userRealmName: props.realmConfig.realmName },\n body: {\n email: state.email,\n captchaToken: captchaSiteKey ? captchaTokenRef.current : undefined,\n },\n });\n setState((s) => ({ ...s, intent }));\n } catch (e) {\n setError(\n e instanceof Error\n ? e.message\n : tr(\"auth.reset.resendFailed\", {\n default: \"Failed to resend code\",\n }),\n );\n } finally {\n setSubmitting(false);\n consumeCaptcha();\n }\n };\n\n return (\n <div className=\"flex min-h-svh flex-1 items-center justify-center p-6\">\n <div className=\"flex w-full max-w-sm flex-col items-center gap-4\">\n {props.logo ??\n (settings?.logoUrl ? (\n <img\n src={settings.logoUrl}\n alt={settings.displayName || props.realmConfig.realmName}\n className=\"bg-muted size-16 rounded-xl border object-cover shadow-sm\"\n />\n ) : null)}\n <Card className=\"w-full\">\n <CardContent className=\"flex flex-col gap-4\">\n {(error ?? submitError) && (\n <Alert variant=\"destructive\">\n <AlertCircle className=\"size-4\" />\n <AlertDescription>{error ?? submitError}</AlertDescription>\n </Alert>\n )}\n {!allowed ? (\n <>\n <Alert>\n <AlertCircle className=\"size-4\" />\n <AlertDescription>\n {tr(\"auth.reset.disabled\", {\n default:\n \"Password reset is not available. Please contact your administrator.\",\n })}\n </AlertDescription>\n </Alert>\n <Button\n render={\n <a\n href={`${props.loginPath ?? \"/auth/login\"}${realmQuery}`}\n />\n }\n >\n {tr(\"auth.reset.backToSignIn\", {\n default: \"Back to sign in\",\n })}\n </Button>\n </>\n ) : state.step === \"email\" ? (\n <form {...emailForm.props} className=\"flex flex-col gap-4\">\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.reset.title\", { default: \"Reset password\" })}\n </h2>\n <p className=\"text-muted-foreground text-sm\">\n {tr(\"auth.reset.emailHint\", {\n default: \"Enter your email address to reset your password\",\n })}\n </p>\n <Control\n label={tr(\"auth.reset.email\", { default: \"Email\" })}\n input={emailForm.input.email}\n icon={iconFor(\"email\")}\n />\n {captchaSiteKey && (\n <TurnstileWidget\n ref={captchaRef}\n siteKey={captchaSiteKey}\n onToken={setCaptchaToken}\n className=\"flex justify-center\"\n />\n )}\n <Button\n type=\"submit\"\n loading={emailSubmitting}\n disabled={!!captchaSiteKey && !captchaToken}\n >\n {tr(\"auth.reset.sendCode\", {\n default: \"Send verification code\",\n })}\n </Button>\n </form>\n ) : state.step === \"code\" ? (\n <div className=\"flex flex-col gap-4\">\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.reset.title\", { default: \"Reset password\" })}\n </h2>\n <Alert>\n <Info className=\"size-4\" />\n <AlertDescription>\n {tr(\"auth.reset.codeSent\", {\n default: \"We've sent a verification code to your email.\",\n })}\n </AlertDescription>\n </Alert>\n <div className=\"flex flex-col items-center gap-2\">\n <Label htmlFor=\"code\">\n {tr(\"auth.reset.codeLabel\", {\n default: \"Enter the 6-digit code\",\n })}\n </Label>\n <InputOTP\n id=\"code\"\n maxLength={6}\n\n value={code}\n onChange={(value) => setCode(value.replace(/\\D/g, \"\"))}\n >\n <InputOTPGroup>\n <InputOTPSlot index={0} />\n <InputOTPSlot index={1} />\n <InputOTPSlot index={2} />\n <InputOTPSlot index={3} />\n <InputOTPSlot index={4} />\n <InputOTPSlot index={5} />\n </InputOTPGroup>\n </InputOTP>\n </div>\n <Button onClick={handleCodeSubmit} disabled={code.length !== 6}>\n {tr(\"auth.reset.continue\", { default: \"Continue\" })}\n </Button>\n {/* Resend calls the same gated endpoint as the first send,\n and the token that got us here is already spent — so this\n step needs its own challenge rather than reusing one. */}\n {captchaSiteKey && (\n <TurnstileWidget\n ref={captchaRef}\n siteKey={captchaSiteKey}\n onToken={setCaptchaToken}\n className=\"flex justify-center\"\n />\n )}\n <Button\n variant=\"minimal\"\n onClick={handleResend}\n loading={submitting}\n disabled={!!captchaSiteKey && !captchaToken}\n >\n {tr(\"auth.reset.resend\", { default: \"Resend code\" })}\n </Button>\n </div>\n ) : state.step === \"password\" ? (\n <form {...passwordForm.props} className=\"flex flex-col gap-4\">\n {/* Hidden identifier so password managers know which saved\n credential the new password belongs to. Without it,\n Safari/Chrome won't offer to update the existing entry. */}\n {state.email && (\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value={state.email}\n readOnly\n hidden\n />\n )}\n <h2 className=\"text-center text-lg font-semibold\">\n {tr(\"auth.reset.title\", { default: \"Reset password\" })}\n </h2>\n <p className=\"text-muted-foreground text-sm\">\n {tr(\"auth.reset.newPasswordHint\", {\n default: \"Create your new password\",\n })}\n </p>\n <Control\n label={tr(\"auth.reset.newPassword\", {\n default: \"New password\",\n })}\n input={passwordForm.input.password}\n password\n autoComplete=\"new-password\"\n />\n <Control\n label={tr(\"auth.reset.confirmPassword\", {\n default: \"Confirm password\",\n })}\n input={passwordForm.input.confirmPassword}\n password\n autoComplete=\"new-password\"\n />\n <Button type=\"submit\" loading={passwordSubmitting}>\n {tr(\"auth.reset.setPassword\", {\n default: \"Set new password\",\n })}\n </Button>\n </form>\n ) : (\n <>\n <Alert>\n <CheckCircle2 className=\"size-4\" />\n <AlertDescription>\n {tr(\"auth.reset.success\", {\n default: \"Your password has been reset successfully.\",\n })}\n </AlertDescription>\n </Alert>\n <Button\n render={\n <a\n href={`${props.loginPath ?? \"/auth/login\"}${realmQuery}`}\n />\n }\n >\n {tr(\"auth.reset.backToSignIn\", {\n default: \"Back to sign in\",\n })}\n </Button>\n </>\n )}\n </CardContent>\n </Card>\n {props.cancelPath !== false && (\n <Button\n variant=\"minimal\"\n nativeButton={false}\n render={<a href={props.cancelPath ?? redirect} />}\n >\n {tr(\"auth.reset.cancel\", { default: \"Cancel\" })}\n </Button>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiEA,MAAa,qBAAqB,UAAkC;CAClE,MAAM,SAAS,UAAe;CAC9B,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,WAAW,UAA0B;CAC3C,MAAM,CAAC,OAAO,YAAY,SAAgB,EAAE,MAAM,QAAQ,CAAC;CAC3D,MAAM,CAAC,OAAO,YAAY,SAAwB,IAAI;CACtD,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,CAAC,MAAM,WAAW,SAAS,EAAE;CACnC,MAAM,WAAW,aAAa,OAAO,MAAM,QAAQ;CAEnD,MAAM,WAAW,MAAM,YAAY;CACnC,MAAM,UAAU,UAAU,yBAAyB;CAWnD,MAAM,QAAQ,CAPG,MAAM,YAAY,YAC/B,SAAS,mBAAmB,MAAM,YAAY,SAAS,MACvD,IAEF,OAAO,OAAO,MAAM,aAAa,YAAY,OAAO,MAAM,WACtD,YAAY,mBAAmB,OAAO,MAAM,QAAQ,MACpD,EAC8B,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;CAC9D,MAAM,aAAa,QAAQ,IAAI,UAAU;;;;;;;;;CAUzC,MAAM,iBAAiB,MAAM,YAAY;CACzC,MAAM,CAAC,cAAc,mBAAmB,SAA6B;CACrE,MAAM,aAAa,OAAqC,IAAI;CAM5D,MAAM,kBAAkB,OAA2B,KAAA,CAAS;CAC5D,gBAAgB;EACd,gBAAgB,UAAU;CAC5B,GAAG,CAAC,YAAY,CAAC;;;;;;;CAQjB,MAAM,uBAAuB;EAC3B,IAAI,CAAC,gBAAgB;EACrB,gBAA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