@alepha/ui 0.36.0 → 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.
- package/dist/account/$pageAccount.d.ts +1 -1
- package/dist/account/$pageAccount.d.ts.map +1 -1
- package/dist/account/$pageAccount.js.map +1 -1
- package/dist/account/AccountDisplay.d.ts +13 -0
- package/dist/account/AccountDisplay.d.ts.map +1 -0
- package/dist/account/AccountDisplay.js +48 -0
- package/dist/account/AccountDisplay.js.map +1 -0
- package/dist/account/AccountProfile.d.ts.map +1 -1
- package/dist/account/AccountProfile.js +14 -10
- package/dist/account/AccountProfile.js.map +1 -1
- package/dist/account/AccountRouter.d.ts +6 -6
- package/dist/account/AccountRouter.d.ts.map +1 -1
- package/dist/account/index.d.ts +5 -0
- package/dist/account/index.d.ts.map +1 -1
- package/dist/account/index.js +2 -1
- package/dist/admin/$pageAdmin.d.ts +1 -1
- package/dist/admin/$pageAdmin.d.ts.map +1 -1
- package/dist/admin/$pageAdmin.js.map +1 -1
- package/dist/admin/AdminAudits.js.map +1 -1
- package/dist/admin/AdminJobDetail.js.map +1 -1
- package/dist/admin/AdminJobs.js.map +1 -1
- package/dist/admin/AdminNotifications.js.map +1 -1
- package/dist/admin/AdminRouter.d.ts +14 -14
- package/dist/admin/AdminRouter.d.ts.map +1 -1
- package/dist/admin/AdminUserDetail.js.map +1 -1
- package/dist/admin/AdminUsers.js.map +1 -1
- package/dist/admin/ParameterHistoryItem.js.map +1 -1
- package/dist/ai/AiChat.d.ts +26 -39
- package/dist/ai/AiChat.d.ts.map +1 -1
- package/dist/ai/AiChat.js +65 -123
- package/dist/ai/AiChat.js.map +1 -1
- package/dist/ai/AiChatDock.d.ts +23 -0
- package/dist/ai/AiChatDock.d.ts.map +1 -0
- package/dist/ai/AiChatDock.js +90 -0
- package/dist/ai/AiChatDock.js.map +1 -0
- package/dist/ai/AiChatDockSlot.d.ts +15 -0
- package/dist/ai/AiChatDockSlot.d.ts.map +1 -0
- package/dist/ai/AiChatDockSlot.js +20 -0
- package/dist/ai/AiChatDockSlot.js.map +1 -0
- package/dist/ai/AiChatLauncher.d.ts +17 -0
- package/dist/ai/AiChatLauncher.d.ts.map +1 -0
- package/dist/ai/AiChatLauncher.js +42 -0
- package/dist/ai/AiChatLauncher.js.map +1 -0
- package/dist/ai/AiChatMessage.d.ts +7 -1
- package/dist/ai/AiChatMessage.d.ts.map +1 -1
- package/dist/ai/AiChatMessage.js +27 -7
- package/dist/ai/AiChatMessage.js.map +1 -1
- package/dist/ai/AiChatPanel.d.ts +71 -0
- package/dist/ai/AiChatPanel.d.ts.map +1 -0
- package/dist/ai/AiChatPanel.js +143 -0
- package/dist/ai/AiChatPanel.js.map +1 -0
- package/dist/ai/index.d.ts +8 -4
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +5 -1
- package/dist/ai/useAiChat.d.ts +17 -0
- package/dist/ai/useAiChat.d.ts.map +1 -1
- package/dist/ai/useAiChat.js +38 -17
- package/dist/ai/useAiChat.js.map +1 -1
- package/dist/auth/AuthLogin.d.ts +9 -0
- package/dist/auth/AuthLogin.d.ts.map +1 -1
- package/dist/auth/AuthLogin.js +2 -2
- package/dist/auth/AuthLogin.js.map +1 -1
- package/dist/auth/AuthRegister.d.ts +4 -1
- package/dist/auth/AuthRegister.d.ts.map +1 -1
- package/dist/auth/AuthRegister.js +1 -1
- package/dist/auth/AuthRegister.js.map +1 -1
- package/dist/auth/AuthResetPassword.d.ts +8 -0
- package/dist/auth/AuthResetPassword.d.ts.map +1 -1
- package/dist/auth/AuthResetPassword.js +2 -2
- package/dist/auth/AuthResetPassword.js.map +1 -1
- package/dist/auth/AuthRouter.d.ts +4 -4
- package/dist/auth/AuthRouter.d.ts.map +1 -1
- package/dist/core/Badge.d.ts.map +1 -1
- package/dist/core/Badge.js +7 -3
- package/dist/core/Badge.js.map +1 -1
- package/dist/core/Collapsible.d.ts +50 -0
- package/dist/core/Collapsible.d.ts.map +1 -0
- package/dist/core/Collapsible.js +70 -0
- package/dist/core/Collapsible.js.map +1 -0
- package/dist/core/Combobox.d.ts +7 -1
- package/dist/core/Combobox.d.ts.map +1 -1
- package/dist/core/Combobox.js +2 -2
- package/dist/core/Combobox.js.map +1 -1
- package/dist/core/PaneRail.d.ts +24 -7
- package/dist/core/PaneRail.d.ts.map +1 -1
- package/dist/core/PaneRail.js +24 -19
- package/dist/core/PaneRail.js.map +1 -1
- package/dist/core/Stepper.d.ts +36 -0
- package/dist/core/Stepper.d.ts.map +1 -0
- package/dist/core/Stepper.js +54 -0
- package/dist/core/Stepper.js.map +1 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +3 -1
- package/dist/core/useToast.js +13 -13
- package/dist/core/useToast.js.map +1 -1
- package/dist/form/AutoForm.d.ts.map +1 -1
- package/dist/form/AutoForm.js +29 -0
- package/dist/form/AutoForm.js.map +1 -1
- package/dist/form/AutoFormErrorPopover.js +13 -3
- package/dist/form/AutoFormErrorPopover.js.map +1 -1
- package/dist/form/Control.d.ts +14 -1
- package/dist/form/Control.d.ts.map +1 -1
- package/dist/form/Control.js +12 -2
- package/dist/form/Control.js.map +1 -1
- package/dist/form/ControlDate.d.ts.map +1 -1
- package/dist/form/ControlDate.js +3 -0
- package/dist/form/ControlDate.js.map +1 -1
- package/dist/form/ControlDateRange.d.ts +12 -1
- package/dist/form/ControlDateRange.d.ts.map +1 -1
- package/dist/form/ControlDateRange.js +11 -1
- package/dist/form/ControlDateRange.js.map +1 -1
- package/dist/form/ControlNumber.d.ts.map +1 -1
- package/dist/form/ControlNumber.js +2 -0
- package/dist/form/ControlNumber.js.map +1 -1
- package/dist/form/ControlObject.d.ts.map +1 -1
- package/dist/form/ControlObject.js +15 -1
- package/dist/form/ControlObject.js.map +1 -1
- package/dist/form/ControlPassword.d.ts +4 -0
- package/dist/form/ControlPassword.d.ts.map +1 -1
- package/dist/form/ControlPassword.js +1 -0
- package/dist/form/ControlPassword.js.map +1 -1
- package/dist/form/ControlSelect.d.ts +23 -1
- package/dist/form/ControlSelect.d.ts.map +1 -1
- package/dist/form/ControlSelect.js +5 -0
- package/dist/form/ControlSelect.js.map +1 -1
- package/dist/form/ControlSelectCombobox.d.ts +11 -1
- package/dist/form/ControlSelectCombobox.d.ts.map +1 -1
- package/dist/form/ControlSelectCombobox.js +9 -1
- package/dist/form/ControlSelectCombobox.js.map +1 -1
- package/dist/form/ControlUpload.d.ts.map +1 -1
- package/dist/form/ControlUpload.js +1 -0
- package/dist/form/ControlUpload.js.map +1 -1
- package/dist/form/FormField.d.ts +5 -0
- package/dist/form/FormField.d.ts.map +1 -1
- package/dist/form/FormField.js +7 -0
- package/dist/form/FormField.js.map +1 -1
- package/dist/i18n/fr/uiFr.d.ts.map +1 -1
- package/dist/i18n/fr/uiFr.js +15 -0
- package/dist/i18n/fr/uiFr.js.map +1 -1
- package/dist/shell/$pageNav.d.ts +2 -2
- package/dist/shell/$pageNav.d.ts.map +1 -1
- package/dist/shell/$pageNav.js.map +1 -1
- package/dist/shell/AppShell.d.ts +6 -0
- package/dist/shell/AppShell.d.ts.map +1 -1
- package/dist/shell/AppShell.js +31 -27
- package/dist/shell/AppShell.js.map +1 -1
- package/dist/shell/ButtonSettings.d.ts +6 -2
- package/dist/shell/ButtonSettings.d.ts.map +1 -1
- package/dist/shell/ButtonSettings.js +17 -3
- package/dist/shell/ButtonSettings.js.map +1 -1
- package/dist/shell/ButtonSettingsVisionMenuItem.d.ts +16 -0
- package/dist/shell/ButtonSettingsVisionMenuItem.d.ts.map +1 -0
- package/dist/shell/ButtonSettingsVisionMenuItem.js +24 -0
- package/dist/shell/ButtonSettingsVisionMenuItem.js.map +1 -0
- package/dist/shell/ButtonVision.d.ts +28 -0
- package/dist/shell/ButtonVision.d.ts.map +1 -0
- package/dist/shell/ButtonVision.js +46 -0
- package/dist/shell/ButtonVision.js.map +1 -0
- package/dist/shell/index.d.ts +6 -3
- package/dist/shell/index.d.ts.map +1 -1
- package/dist/shell/index.js +2 -1
- package/dist/styles.css +57 -0
- package/dist/table/DataTable.d.ts.map +1 -1
- package/dist/table/DataTable.js +29 -4
- package/dist/table/DataTable.js.map +1 -1
- package/dist/table/DataTableColumnPicker.d.ts.map +1 -1
- package/dist/table/DataTableColumnPicker.js +1 -0
- package/dist/table/DataTableColumnPicker.js.map +1 -1
- package/dist/table/DataTableFilterBar.d.ts +1 -1
- package/dist/table/DataTableFilterBar.d.ts.map +1 -1
- package/dist/table/DataTableFilterBar.js +5 -108
- package/dist/table/DataTableFilterBar.js.map +1 -1
- package/dist/table/DataTableHeaderFilter.d.ts +51 -0
- package/dist/table/DataTableHeaderFilter.d.ts.map +1 -0
- package/dist/table/DataTableHeaderFilter.js +113 -0
- package/dist/table/DataTableHeaderFilter.js.map +1 -0
- package/dist/table/DataTableHeaderRow.d.ts +7 -0
- package/dist/table/DataTableHeaderRow.d.ts.map +1 -1
- package/dist/table/DataTableHeaderRow.js +92 -74
- package/dist/table/DataTableHeaderRow.js.map +1 -1
- package/dist/table/DataTableTabs.d.ts +42 -0
- package/dist/table/DataTableTabs.d.ts.map +1 -0
- package/dist/table/DataTableTabs.js +55 -0
- package/dist/table/DataTableTabs.js.map +1 -0
- package/dist/table/dataTableBaseProps.d.ts +12 -0
- package/dist/table/dataTableBaseProps.d.ts.map +1 -1
- package/dist/table/dataTablePersistence.d.ts.map +1 -1
- package/dist/table/dataTablePersistence.js +4 -2
- package/dist/table/dataTablePersistence.js.map +1 -1
- package/dist/table/dataTableTypes.d.ts +18 -0
- package/dist/table/dataTableTypes.d.ts.map +1 -1
- package/dist/table/index.d.ts +5 -2
- package/dist/table/index.d.ts.map +1 -1
- package/dist/table/index.js +2 -1
- package/dist/table/useDataTableColumns.d.ts.map +1 -1
- package/dist/table/useDataTableColumns.js +1 -0
- package/dist/table/useDataTableColumns.js.map +1 -1
- package/dist/table/useDataTableFilterModel.d.ts +110 -0
- package/dist/table/useDataTableFilterModel.d.ts.map +1 -0
- package/dist/table/useDataTableFilterModel.js +154 -0
- package/dist/table/useDataTableFilterModel.js.map +1 -0
- package/docs/packages-alepha-ui-account.md +4 -0
- package/docs/packages-alepha-ui-ai.md +5 -5
- package/docs/packages-alepha-ui-shell.md +4 -3
- package/docs/packages-alepha-ui-table.md +4 -2
- package/package.json +8 -8
- package/src/account/$pageAccount.tsx +5 -4
- package/src/account/AccountDisplay.tsx +58 -0
- package/src/account/AccountProfile.tsx +30 -42
- package/src/account/__tests__/AccountProfile.browser.spec.tsx +141 -0
- package/src/account/__tests__/AccountRecoveryCodes.browser.spec.tsx +1 -1
- package/src/account/index.ts +5 -0
- package/src/admin/$pageAdmin.tsx +5 -4
- package/src/admin/AdminAudits.tsx +1 -1
- package/src/admin/AdminJobDetail.tsx +1 -1
- package/src/admin/AdminJobs.tsx +1 -1
- package/src/admin/AdminNotifications.tsx +1 -1
- package/src/admin/AdminUserDetail.tsx +1 -1
- package/src/admin/AdminUsers.tsx +1 -1
- package/src/admin/ParameterHistoryItem.tsx +1 -1
- package/src/admin/__tests__/AdminFilesUsageCard.browser.spec.tsx +17 -9
- package/src/ai/AiChat.tsx +94 -183
- package/src/ai/AiChatDock.tsx +129 -0
- package/src/ai/AiChatDockSlot.tsx +23 -0
- package/src/ai/AiChatLauncher.tsx +58 -0
- package/src/ai/AiChatMessage.tsx +48 -9
- package/src/ai/AiChatPanel.tsx +252 -0
- package/src/ai/__tests__/AiChat.browser.spec.tsx +197 -5
- package/src/ai/index.ts +8 -4
- package/src/ai/useAiChat.ts +80 -14
- package/src/auth/AuthLogin.tsx +19 -4
- package/src/auth/AuthRegister.tsx +6 -3
- package/src/auth/AuthResetPassword.tsx +18 -8
- package/src/auth/__tests__/AuthCancel.browser.spec.tsx +129 -0
- package/src/core/Badge.tsx +7 -3
- package/src/core/Collapsible.tsx +95 -0
- package/src/core/Combobox.tsx +11 -3
- package/src/core/PaneRail.tsx +36 -20
- package/src/core/Stepper.tsx +118 -0
- package/src/core/__tests__/Badge.browser.spec.tsx +5 -5
- package/src/core/__tests__/Collapsible.browser.spec.tsx +88 -0
- package/src/core/__tests__/PaneRail.browser.spec.tsx +48 -0
- package/src/core/__tests__/Stepper.browser.spec.tsx +39 -0
- package/src/core/__tests__/primitiveSlots.spec.ts +7 -0
- package/src/core/index.ts +15 -0
- package/src/form/AutoForm.tsx +32 -0
- package/src/form/AutoFormErrorPopover.tsx +27 -6
- package/src/form/Control.tsx +22 -0
- package/src/form/ControlDate.tsx +3 -0
- package/src/form/ControlDateRange.tsx +87 -58
- package/src/form/ControlNumber.tsx +2 -0
- package/src/form/ControlObject.tsx +20 -1
- package/src/form/ControlPassword.tsx +5 -0
- package/src/form/ControlSelect.tsx +32 -1
- package/src/form/ControlSelectCombobox.tsx +82 -56
- package/src/form/ControlUpload.tsx +1 -0
- package/src/form/FormField.tsx +23 -1
- package/src/form/__tests__/ControlFieldErrors.browser.spec.tsx +253 -0
- package/src/form/__tests__/ControlValidateMode.browser.spec.tsx +217 -0
- package/src/form/__tests__/ControlVariantErrors.browser.spec.tsx +133 -0
- package/src/i18n/fr/uiFr.ts +19 -1
- package/src/markdown/css.d.ts +11 -0
- package/src/shell/$pageNav.tsx +6 -4
- package/src/shell/AppShell.tsx +7 -0
- package/src/shell/ButtonSettings.tsx +20 -5
- package/src/shell/ButtonSettingsVisionMenuItem.tsx +40 -0
- package/src/shell/ButtonVision.tsx +73 -0
- package/src/shell/__tests__/ButtonSettings.browser.spec.tsx +42 -2
- package/src/shell/__tests__/ButtonVision.browser.spec.tsx +73 -0
- package/src/shell/__tests__/visionTokens.spec.ts +104 -0
- package/src/shell/index.ts +6 -3
- package/src/styles.css +57 -0
- package/src/table/DataTable.tsx +52 -4
- package/src/table/DataTableColumnPicker.tsx +3 -0
- package/src/table/DataTableFilterBar.tsx +18 -191
- package/src/table/DataTableHeaderFilter.tsx +156 -0
- package/src/table/DataTableHeaderRow.tsx +78 -40
- package/src/table/DataTableTabs.tsx +114 -0
- package/src/table/__tests__/DataTableHeaderFilter.browser.spec.tsx +174 -0
- package/src/table/__tests__/DataTableStaleColumns.browser.spec.tsx +80 -0
- package/src/table/__tests__/DataTableTabs.browser.spec.tsx +72 -0
- package/src/table/dataTableBaseProps.ts +12 -0
- package/src/table/dataTablePersistence.ts +11 -5
- package/src/table/dataTableTypes.ts +18 -0
- package/src/table/index.ts +9 -2
- package/src/table/useDataTableColumns.ts +1 -0
- package/src/table/useDataTableFilterModel.tsx +240 -0
package/dist/ai/useAiChat.js
CHANGED
|
@@ -34,6 +34,7 @@ const useAiChat = (options = {}) => {
|
|
|
34
34
|
const [pending, setPending] = useState();
|
|
35
35
|
const [error, setError] = useState();
|
|
36
36
|
const idRef = useRef(options.conversationId);
|
|
37
|
+
const deniedRef = useRef(/* @__PURE__ */ new Set());
|
|
37
38
|
const counter = useRef(0);
|
|
38
39
|
const push = useCallback((item) => {
|
|
39
40
|
counter.current += 1;
|
|
@@ -44,6 +45,20 @@ const useAiChat = (options = {}) => {
|
|
|
44
45
|
}]);
|
|
45
46
|
}, []);
|
|
46
47
|
/**
|
|
48
|
+
* The page context a turn carries: the route, and the innermost page's
|
|
49
|
+
* name and data. Sent on a chat and on every resume, since the server's
|
|
50
|
+
* `allow` reads it to decide what the assistant is offered.
|
|
51
|
+
*/
|
|
52
|
+
const pageContext = useCallback(() => {
|
|
53
|
+
const stack = alepha.store.get(aiContextAtom) ?? [];
|
|
54
|
+
const innermost = stack[stack.length - 1];
|
|
55
|
+
return {
|
|
56
|
+
route: router.pathname,
|
|
57
|
+
page: innermost?.page,
|
|
58
|
+
data: innermost?.data
|
|
59
|
+
};
|
|
60
|
+
}, [alepha, router]);
|
|
61
|
+
/**
|
|
47
62
|
* Run a client tool the turn paused on, and return its result. A failure
|
|
48
63
|
* is a result too: the model reads it and recovers.
|
|
49
64
|
*/
|
|
@@ -96,6 +111,7 @@ const useAiChat = (options = {}) => {
|
|
|
96
111
|
const consume = useCallback(async (first, signal) => {
|
|
97
112
|
let stream = first;
|
|
98
113
|
let ranTools = false;
|
|
114
|
+
const succeeded = [];
|
|
99
115
|
while (stream) {
|
|
100
116
|
let text = "";
|
|
101
117
|
let clientCall;
|
|
@@ -109,12 +125,14 @@ const useAiChat = (options = {}) => {
|
|
|
109
125
|
} else if (event.type === "tool_call") setActivity(event.name);
|
|
110
126
|
else if (event.type === "tool_result") {
|
|
111
127
|
ranTools = true;
|
|
128
|
+
if (!event.isError && event.name) succeeded.push(event.name);
|
|
112
129
|
setActivity(void 0);
|
|
113
130
|
push({
|
|
114
131
|
role: "tool",
|
|
115
132
|
content: "",
|
|
116
133
|
name: event.name,
|
|
117
|
-
isError: event.isError
|
|
134
|
+
isError: event.isError,
|
|
135
|
+
denied: Boolean(event.callId && deniedRef.current.has(event.callId))
|
|
118
136
|
});
|
|
119
137
|
} else if (event.type === "confirm") setPending({
|
|
120
138
|
callId: event.callId ?? "",
|
|
@@ -129,10 +147,12 @@ const useAiChat = (options = {}) => {
|
|
|
129
147
|
kind: "client_tool"
|
|
130
148
|
};
|
|
131
149
|
else if (event.type === "error") setError(event.message ?? event.name ?? "The assistant failed");
|
|
132
|
-
|
|
150
|
+
const cut = event.type === "end" && event.reason === "length";
|
|
151
|
+
if (text && (event.type === "tool_call" || event.type === "end") || cut) {
|
|
133
152
|
push({
|
|
134
153
|
role: "assistant",
|
|
135
|
-
content: text
|
|
154
|
+
content: text,
|
|
155
|
+
...cut ? { cut } : {}
|
|
136
156
|
});
|
|
137
157
|
text = "";
|
|
138
158
|
setStreaming("");
|
|
@@ -142,6 +162,7 @@ const useAiChat = (options = {}) => {
|
|
|
142
162
|
stream = void 0;
|
|
143
163
|
if (ranTools) {
|
|
144
164
|
for (const key of options.invalidates ?? []) queries.invalidate(key);
|
|
165
|
+
if (succeeded.length) options.onToolsRan?.(succeeded.splice(0));
|
|
145
166
|
ranTools = false;
|
|
146
167
|
}
|
|
147
168
|
if (clientCall && idRef.current) {
|
|
@@ -150,7 +171,8 @@ const useAiChat = (options = {}) => {
|
|
|
150
171
|
params: { id: idRef.current },
|
|
151
172
|
body: {
|
|
152
173
|
callId: clientCall.callId,
|
|
153
|
-
result
|
|
174
|
+
result,
|
|
175
|
+
context: pageContext()
|
|
154
176
|
}
|
|
155
177
|
}, { request: { signal } });
|
|
156
178
|
}
|
|
@@ -160,7 +182,9 @@ const useAiChat = (options = {}) => {
|
|
|
160
182
|
push,
|
|
161
183
|
runClientTool,
|
|
162
184
|
queries,
|
|
163
|
-
options.invalidates
|
|
185
|
+
options.invalidates,
|
|
186
|
+
options.onToolsRan,
|
|
187
|
+
pageContext
|
|
164
188
|
]);
|
|
165
189
|
const send = useAction({
|
|
166
190
|
handler: async ({ signal }, message) => {
|
|
@@ -169,40 +193,35 @@ const useAiChat = (options = {}) => {
|
|
|
169
193
|
role: "user",
|
|
170
194
|
content: message
|
|
171
195
|
});
|
|
172
|
-
const stack = alepha.store.get(aiContextAtom) ?? [];
|
|
173
|
-
const innermost = stack[stack.length - 1];
|
|
174
196
|
const stream = await api.chat({ body: {
|
|
175
197
|
conversationId: idRef.current,
|
|
176
198
|
message,
|
|
177
199
|
assistant: options.assistant,
|
|
178
|
-
context:
|
|
179
|
-
route: router.pathname,
|
|
180
|
-
page: innermost?.page,
|
|
181
|
-
data: innermost?.data
|
|
182
|
-
}
|
|
200
|
+
context: pageContext()
|
|
183
201
|
} }, { request: { signal } });
|
|
184
202
|
await consume(stream, signal);
|
|
185
203
|
},
|
|
186
204
|
onError: (cause) => setError(cause.message)
|
|
187
205
|
}, [
|
|
188
206
|
api,
|
|
189
|
-
alepha,
|
|
190
207
|
consume,
|
|
191
208
|
options.assistant,
|
|
192
209
|
push,
|
|
193
|
-
|
|
210
|
+
pageContext
|
|
194
211
|
]);
|
|
195
212
|
const answer = useAction({
|
|
196
213
|
handler: async ({ signal }, decision) => {
|
|
197
214
|
if (!pending || !idRef.current) return;
|
|
198
215
|
setError(void 0);
|
|
199
216
|
const callId = pending.callId;
|
|
217
|
+
if (decision === "deny") deniedRef.current.add(callId);
|
|
200
218
|
setPending(void 0);
|
|
201
219
|
const stream = await api.resume({
|
|
202
220
|
params: { id: idRef.current },
|
|
203
221
|
body: {
|
|
204
222
|
callId,
|
|
205
|
-
decision
|
|
223
|
+
decision,
|
|
224
|
+
context: pageContext()
|
|
206
225
|
}
|
|
207
226
|
}, { request: { signal } });
|
|
208
227
|
await consume(stream, signal);
|
|
@@ -211,7 +230,8 @@ const useAiChat = (options = {}) => {
|
|
|
211
230
|
}, [
|
|
212
231
|
api,
|
|
213
232
|
consume,
|
|
214
|
-
pending
|
|
233
|
+
pending,
|
|
234
|
+
pageContext
|
|
215
235
|
]);
|
|
216
236
|
const open = useAction({
|
|
217
237
|
handler: async (_ctx, id) => {
|
|
@@ -230,7 +250,8 @@ const useAiChat = (options = {}) => {
|
|
|
230
250
|
role: message.role,
|
|
231
251
|
content: message.content,
|
|
232
252
|
name: message.name,
|
|
233
|
-
isError: message.isError
|
|
253
|
+
isError: message.isError,
|
|
254
|
+
denied: message.role === "tool" && message.content === "Denied by the user."
|
|
234
255
|
})));
|
|
235
256
|
setPending(detail.conversation.pendingCall);
|
|
236
257
|
},
|
package/dist/ai/useAiChat.js.map
CHANGED
|
@@ -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 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 });\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 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 })),\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\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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,QAAQ,QAAQ,MAAM;EAC9B;EACA,UAAU,UAAU,SAAS,MAAM,OAAO;CAC5C,GACA;EAAC;EAAK;EAAS;CAAO,CACxB;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;GACnB,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,SA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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"}
|
package/dist/auth/AuthLogin.d.ts
CHANGED
|
@@ -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;
|
|
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"}
|
package/dist/auth/AuthLogin.js
CHANGED
|
@@ -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 just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AgB,mBAAmB;SAClD,WAAU;SAET,UAAA,GAAG,qBAAqB,EAAE,SAAS,UAAU,CAAC;QAC9C,CAAA;OACF;;KAEM;;GACT,CAAA;GACN,oBAAC,QAAD;IAAQ,SAAQ;IAAU,cAAc;IAAO,QAAQ,oBAAC,KAAD,EAAG,MAAK,IAAK,CAAA;IACjE,UAAA,GAAG,qBAAqB,EAAE,SAAS,SAAS,CAAC;GACxC,CAAA;EACL;;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"}
|
|
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}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,MAAa,aAAa,UAA0B;CAClD,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,UAAe;CAC9B,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,UAA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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,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAK/B,OAAO,KAAK,EACV,WAAW,EAGZ,MAAM,kBAAkB,CAAC;AAO1B,OAAO,EACL,KAAK,SAAS,EAMf,MAAM,OAAO,CAAC;AAkBf,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB
|
|
1
|
+
{"version":3,"file":"AuthRegister.d.ts","sourceRoot":"","sources":["../../src/auth/AuthRegister.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAK/B,OAAO,KAAK,EACV,WAAW,EAGZ,MAAM,kBAAkB,CAAC;AAO1B,OAAO,EACL,KAAK,SAAS,EAMf,MAAM,OAAO,CAAC;AAkBf,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB;;;;;;;;;OASG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC5B;;;;;;;;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,UAA0B;CAC3C,MAAM,SAAS,UAAU;CACzB,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,iBAAiB,MAAM,YAAY;CACzC,MAAM,CAAC,cAAc,mBAAmB,SAA6B;CACrE,MAAM,aAAa,OAAqC,IAAI;CAG5D,MAAM,kBAAkB,OAA2B,KAAA,CAAS;CAC5D,gBAAgB;EACd,gBAAgB,UAAU;CAC5B,GAAG,CAAC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R,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,eACA,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"}
|
|
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.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D;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;
|
|
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
|
]
|