@smartcrab/react 0.1.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.
@@ -0,0 +1,341 @@
1
+ import type {
2
+ AuthenticatedSession,
3
+ BrowserAuthClient,
4
+ BrowserAuthError,
5
+ BrowserTransaction,
6
+ Outcome,
7
+ SocialProvider,
8
+ } from "@smartcrab/browser";
9
+ import { err, ok } from "@smartcrab/browser";
10
+
11
+ /**
12
+ * Headless sign-in state machine over the transaction API (design.md §16),
13
+ * shared by every React hook/headless component in this package.
14
+ *
15
+ * It is deliberately React-free: the hooks bind `subscribe`/`getSnapshot`
16
+ * with `useSyncExternalStore`, and the machine itself stays unit-testable
17
+ * without a renderer (react-dom is intentionally not a dependency here).
18
+ *
19
+ * Flow: idle → starting → awaiting_method → (email_challenge_sent |
20
+ * ceremony) → completing → signed_in. Any step can land in `failed`;
21
+ * `reset()` returns to `idle`. Social sign-in leaves the page via top-level
22
+ * redirect (design.md §22.3), so it has no terminal state here — after the
23
+ * redirect back, the app calls `client.handleHostedAuthorizationCallback`.
24
+ */
25
+
26
+ export type SignInFlowState =
27
+ | { readonly step: "idle" }
28
+ | { readonly step: "starting" }
29
+ | {
30
+ readonly step: "awaiting_method";
31
+ readonly transactionId: string;
32
+ readonly methods: BrowserTransaction["availableMethods"];
33
+ readonly expiresAt: string;
34
+ }
35
+ | {
36
+ readonly step: "email_challenge_sent";
37
+ readonly transactionId: string;
38
+ readonly challengeId: string;
39
+ readonly email: string;
40
+ readonly challengeExpiresAt: string;
41
+ }
42
+ | {
43
+ readonly step: "ceremony";
44
+ readonly transactionId: string;
45
+ readonly ceremony: "passkey_registration" | "passkey_authentication";
46
+ }
47
+ | { readonly step: "completing"; readonly transactionId: string }
48
+ | { readonly step: "signed_in"; readonly session: AuthenticatedSession }
49
+ | { readonly step: "failed"; readonly error: BrowserAuthError };
50
+
51
+ export type PendingAction =
52
+ | "begin"
53
+ | "send_email"
54
+ | "resend_email"
55
+ | "verify_email"
56
+ | "passkey"
57
+ | "social"
58
+ | "cancel"
59
+ | null;
60
+
61
+ /** useSyncExternalStore-compatible snapshot: referentially stable between emissions. */
62
+ export interface SignInFlowSnapshot {
63
+ readonly state: SignInFlowState;
64
+ readonly pendingAction: PendingAction;
65
+ }
66
+
67
+ /** A flow misuse (e.g. `verifyEmailCode` before any challenge was sent) — a caller bug, not a wire error. */
68
+ export interface InvalidFlowStateError {
69
+ readonly type: "invalid_flow_state";
70
+ readonly expected: string;
71
+ readonly actual: string;
72
+ }
73
+
74
+ export type SignInFlowError = BrowserAuthError | InvalidFlowStateError;
75
+
76
+ export type SignInFlowListener = (snapshot: SignInFlowSnapshot) => void;
77
+
78
+ /** The narrow slice of the browser client the flow drives (structural, so tests inject a fake). */
79
+ export type SignInFlowClient = Pick<
80
+ BrowserAuthClient,
81
+ | "createTransaction"
82
+ | "cancelTransaction"
83
+ | "startEmailOtp"
84
+ | "resendEmailOtp"
85
+ | "verifyEmailOtp"
86
+ | "startPasskeyRegistration"
87
+ | "startPasskeyAuthentication"
88
+ | "startSocialSignIn"
89
+ | "completeTransaction"
90
+ | "exchangeAuthorizationCode"
91
+ >;
92
+
93
+ export interface SignInFlow {
94
+ getSnapshot(): SignInFlowSnapshot;
95
+ subscribe(listener: SignInFlowListener): () => void;
96
+ /** Creates the transaction and moves to `awaiting_method`. */
97
+ begin(): Promise<Outcome<BrowserTransaction, SignInFlowError>>;
98
+ sendEmailCode(email: string): Promise<Outcome<{ challengeId: string }, SignInFlowError>>;
99
+ resendEmailCode(): Promise<Outcome<{ challengeId: string }, SignInFlowError>>;
100
+ /** Verifies the code, then completes the transaction and exchanges the code. */
101
+ verifyEmailCode(code: string): Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
102
+ /** Discoverable-credential passkey sign-in ceremony (design.md §17.2). */
103
+ signInWithPasskey(): Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
104
+ /** Passkey registration ceremony during sign-up (design.md §17.1). */
105
+ registerPasskey(input?: {
106
+ readonly name?: string;
107
+ }): Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
108
+ /** Starts social sign-in; performs a top-level redirect on success. */
109
+ signInWithSocial(
110
+ provider: SocialProvider,
111
+ ): Promise<Outcome<{ redirected: true }, SignInFlowError>>;
112
+ /** Best-effort server-side cancel, then back to `idle`. */
113
+ cancel(): Promise<Outcome<{ cancelled: true }, SignInFlowError>>;
114
+ /** Local-only reset (no server call). */
115
+ reset(): void;
116
+ }
117
+
118
+ const invalidState = (expected: string, actual: string): Outcome<never, SignInFlowError> =>
119
+ err({ type: "invalid_flow_state", expected, actual });
120
+
121
+ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
122
+ let snapshot: SignInFlowSnapshot = { state: { step: "idle" }, pendingAction: null };
123
+ const listeners = new Set<SignInFlowListener>();
124
+
125
+ const transition = (state: SignInFlowState, pendingAction: PendingAction = null): void => {
126
+ snapshot = { state, pendingAction };
127
+ for (const listener of listeners) {
128
+ listener(snapshot);
129
+ }
130
+ };
131
+
132
+ const fail = (error: BrowserAuthError): void => {
133
+ transition({ step: "failed", error });
134
+ };
135
+
136
+ /** complete → exchange, shared by every verify path (design.md §16.3). */
137
+ const finalize = async (
138
+ transactionId: string,
139
+ ): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
140
+ transition({ step: "completing", transactionId });
141
+ const completed = await client.completeTransaction(transactionId);
142
+ if (!completed.ok) {
143
+ fail(completed.error);
144
+ return completed;
145
+ }
146
+ const exchanged = await client.exchangeAuthorizationCode({
147
+ code: completed.value.authorization_code,
148
+ state: completed.value.state,
149
+ });
150
+ if (!exchanged.ok) {
151
+ fail(exchanged.error);
152
+ return exchanged;
153
+ }
154
+ transition({ step: "signed_in", session: exchanged.value });
155
+ return ok(exchanged.value);
156
+ };
157
+
158
+ const begin = async (): Promise<Outcome<BrowserTransaction, SignInFlowError>> => {
159
+ const { step } = snapshot.state;
160
+ if (step !== "idle" && step !== "failed") {
161
+ return invalidState("idle|failed", step);
162
+ }
163
+ transition({ step: "starting" }, "begin");
164
+ const outcome = await client.createTransaction();
165
+ if (!outcome.ok) {
166
+ fail(outcome.error);
167
+ return outcome;
168
+ }
169
+ transition({
170
+ step: "awaiting_method",
171
+ transactionId: outcome.value.transactionId,
172
+ methods: outcome.value.availableMethods,
173
+ expiresAt: outcome.value.expiresAt,
174
+ });
175
+ return outcome;
176
+ };
177
+
178
+ const sendEmailCode = async (
179
+ email: string,
180
+ ): Promise<Outcome<{ challengeId: string }, SignInFlowError>> => {
181
+ const state = snapshot.state;
182
+ if (state.step !== "awaiting_method") {
183
+ return invalidState("awaiting_method", state.step);
184
+ }
185
+ transition(state, "send_email");
186
+ const outcome = await client.startEmailOtp(state.transactionId, { email });
187
+ if (!outcome.ok) {
188
+ fail(outcome.error);
189
+ return outcome;
190
+ }
191
+ transition({
192
+ step: "email_challenge_sent",
193
+ transactionId: state.transactionId,
194
+ challengeId: outcome.value.challenge_id,
195
+ email,
196
+ challengeExpiresAt: outcome.value.expires_at,
197
+ });
198
+ return ok({ challengeId: outcome.value.challenge_id });
199
+ };
200
+
201
+ const resendEmailCode = async (): Promise<Outcome<{ challengeId: string }, SignInFlowError>> => {
202
+ const state = snapshot.state;
203
+ if (state.step !== "email_challenge_sent") {
204
+ return invalidState("email_challenge_sent", state.step);
205
+ }
206
+ transition(state, "resend_email");
207
+ const outcome = await client.resendEmailOtp(state.transactionId, {
208
+ challenge_id: state.challengeId,
209
+ });
210
+ if (!outcome.ok) {
211
+ fail(outcome.error);
212
+ return outcome;
213
+ }
214
+ // design.md §18.2: resend invalidates the prior code — adopt the new challenge.
215
+ transition({
216
+ ...state,
217
+ challengeId: outcome.value.challenge_id,
218
+ challengeExpiresAt: outcome.value.expires_at,
219
+ });
220
+ return ok({ challengeId: outcome.value.challenge_id });
221
+ };
222
+
223
+ const verifyEmailCode = async (
224
+ code: string,
225
+ ): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
226
+ const state = snapshot.state;
227
+ if (state.step !== "email_challenge_sent") {
228
+ return invalidState("email_challenge_sent", state.step);
229
+ }
230
+ transition(state, "verify_email");
231
+ const outcome = await client.verifyEmailOtp(state.transactionId, {
232
+ challenge_id: state.challengeId,
233
+ code,
234
+ });
235
+ if (!outcome.ok) {
236
+ fail(outcome.error);
237
+ return outcome;
238
+ }
239
+ return finalize(state.transactionId);
240
+ };
241
+
242
+ const signInWithPasskey = async (): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
243
+ const state = snapshot.state;
244
+ if (state.step !== "awaiting_method") {
245
+ return invalidState("awaiting_method", state.step);
246
+ }
247
+ transition(
248
+ { step: "ceremony", transactionId: state.transactionId, ceremony: "passkey_authentication" },
249
+ "passkey",
250
+ );
251
+ const outcome = await client.startPasskeyAuthentication(state.transactionId);
252
+ if (!outcome.ok) {
253
+ fail(outcome.error);
254
+ return outcome;
255
+ }
256
+ return finalize(state.transactionId);
257
+ };
258
+
259
+ const registerPasskey = async (input?: {
260
+ readonly name?: string;
261
+ }): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
262
+ const state = snapshot.state;
263
+ if (state.step !== "awaiting_method") {
264
+ return invalidState("awaiting_method", state.step);
265
+ }
266
+ transition(
267
+ { step: "ceremony", transactionId: state.transactionId, ceremony: "passkey_registration" },
268
+ "passkey",
269
+ );
270
+ const outcome = await client.startPasskeyRegistration(state.transactionId, input ?? {});
271
+ if (!outcome.ok) {
272
+ fail(outcome.error);
273
+ return outcome;
274
+ }
275
+ return finalize(state.transactionId);
276
+ };
277
+
278
+ const signInWithSocial = async (
279
+ provider: SocialProvider,
280
+ ): Promise<Outcome<{ redirected: true }, SignInFlowError>> => {
281
+ const state = snapshot.state;
282
+ if (state.step !== "awaiting_method") {
283
+ return invalidState("awaiting_method", state.step);
284
+ }
285
+ transition(state, "social");
286
+ const outcome = await client.startSocialSignIn(state.transactionId, provider);
287
+ if (!outcome.ok) {
288
+ fail(outcome.error);
289
+ return outcome;
290
+ }
291
+ // Success = the browser is navigating away (top-level redirect). The flow
292
+ // intentionally stays in `awaiting_method`: on the redirect back the page
293
+ // reloads and a fresh flow instance takes over.
294
+ transition(state);
295
+ return ok({ redirected: true });
296
+ };
297
+
298
+ const cancel = async (): Promise<Outcome<{ cancelled: true }, SignInFlowError>> => {
299
+ const state = snapshot.state;
300
+ const transactionId =
301
+ state.step === "awaiting_method" ||
302
+ state.step === "email_challenge_sent" ||
303
+ state.step === "ceremony" ||
304
+ state.step === "completing"
305
+ ? state.transactionId
306
+ : null;
307
+ if (transactionId === null) {
308
+ transition({ step: "idle" });
309
+ return ok({ cancelled: true });
310
+ }
311
+ transition(state, "cancel");
312
+ const outcome = await client.cancelTransaction(transactionId);
313
+ if (!outcome.ok) {
314
+ fail(outcome.error);
315
+ return outcome;
316
+ }
317
+ transition({ step: "idle" });
318
+ return ok({ cancelled: true });
319
+ };
320
+
321
+ const reset = (): void => {
322
+ transition({ step: "idle" });
323
+ };
324
+
325
+ return {
326
+ getSnapshot: () => snapshot,
327
+ subscribe: (listener) => {
328
+ listeners.add(listener);
329
+ return () => listeners.delete(listener);
330
+ },
331
+ begin,
332
+ sendEmailCode,
333
+ resendEmailCode,
334
+ verifyEmailCode,
335
+ signInWithPasskey,
336
+ registerPasskey,
337
+ signInWithSocial,
338
+ cancel,
339
+ reset,
340
+ };
341
+ };
@@ -0,0 +1,112 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import type { MeUser } from "@smartcrab/browser";
3
+ import { err, ok } from "@smartcrab/browser";
4
+ import { createUserProfileController } from "./user-controller.js";
5
+ import type { UserProfileClient, UserProfileSnapshot } from "./user-controller.js";
6
+
7
+ /**
8
+ * User profile controller tests (`useUser` backing). Renderer-free per the
9
+ * package's documented constraint (no react-dom / react-test-renderer).
10
+ */
11
+
12
+ const USER: MeUser = {
13
+ user_id: `usr_${"c".repeat(32)}`,
14
+ email: "user@example.com",
15
+ email_verified: true,
16
+ name: "Ada Lovelace",
17
+ avatar_url: null,
18
+ locale: "en-US",
19
+ timezone: "UTC",
20
+ status: "active",
21
+ created_at: "2026-08-02T08:10:00Z",
22
+ last_login_at: null,
23
+ };
24
+
25
+ const createClient = (): UserProfileClient => ({
26
+ getMe: vi.fn<UserProfileClient["getMe"]>(async () => ok(USER)),
27
+ updateMe: vi.fn<UserProfileClient["updateMe"]>(async () => ok({ ...USER, name: "Grace Hopper" })),
28
+ });
29
+
30
+ describe("createUserProfileController", () => {
31
+ test("load transitions idle → loading → loaded and notifies subscribers", async () => {
32
+ const client = createClient();
33
+ const controller = createUserProfileController(client);
34
+ const events: UserProfileSnapshot[] = [];
35
+ controller.subscribe((snapshot) => events.push(snapshot));
36
+
37
+ const outcome = await controller.load();
38
+ expect(outcome).toEqual({ ok: true, value: USER });
39
+ expect(controller.getSnapshot()).toEqual({ status: "loaded", user: USER, error: null });
40
+ expect(events.map((e) => e.status)).toEqual(["loading", "loaded"]);
41
+ });
42
+
43
+ test("concurrent loads dedupe to one request", async () => {
44
+ const client = createClient();
45
+ const controller = createUserProfileController(client);
46
+ const [a, b] = await Promise.all([controller.load(), controller.load()]);
47
+ expect(a.ok).toBe(true);
48
+ expect(b.ok).toBe(true);
49
+ expect(client.getMe).toHaveBeenCalledTimes(1);
50
+ });
51
+
52
+ test("not_authenticated resets to idle rather than an error state", async () => {
53
+ const client = createClient();
54
+ client.getMe = vi.fn<UserProfileClient["getMe"]>(async () =>
55
+ err({ type: "not_authenticated" }),
56
+ );
57
+ const controller = createUserProfileController(client);
58
+ const outcome = await controller.load();
59
+ expect(outcome).toEqual({ ok: false, error: { type: "not_authenticated" } });
60
+ expect(controller.getSnapshot()).toEqual({ status: "idle", user: null, error: null });
61
+ });
62
+
63
+ test("a server error keeps the previously loaded user in the snapshot", async () => {
64
+ const client = createClient();
65
+ const controller = createUserProfileController(client);
66
+ await controller.load();
67
+ client.getMe = vi.fn<UserProfileClient["getMe"]>(async () =>
68
+ err({ type: "network_error", message: "down", retryable: true }),
69
+ );
70
+ const outcome = await controller.load();
71
+ expect(outcome.ok).toBe(false);
72
+ const snapshot = controller.getSnapshot();
73
+ expect(snapshot.status).toBe("error");
74
+ expect(snapshot.user).toEqual(USER);
75
+ expect(snapshot.error).toMatchObject({ type: "network_error" });
76
+ });
77
+
78
+ test("update applies the patch and refreshes the cached profile", async () => {
79
+ const client = createClient();
80
+ const controller = createUserProfileController(client);
81
+ const outcome = await controller.update({ name: "Grace Hopper" });
82
+ expect(outcome.ok).toBe(true);
83
+ if (outcome.ok) expect(outcome.value.name).toBe("Grace Hopper");
84
+ expect(client.updateMe).toHaveBeenCalledWith({ name: "Grace Hopper" });
85
+ expect(controller.getSnapshot().user?.name).toBe("Grace Hopper");
86
+ });
87
+
88
+ test("update failure lands in error state", async () => {
89
+ const client = createClient();
90
+ client.updateMe = vi.fn<UserProfileClient["updateMe"]>(async () =>
91
+ err({
92
+ type: "problem_details",
93
+ problemType: "https://x/validation",
94
+ code: "validation_failed",
95
+ title: "Bad Request",
96
+ status: 400,
97
+ }),
98
+ );
99
+ const controller = createUserProfileController(client);
100
+ const outcome = await controller.update({ name: "x" });
101
+ expect(outcome.ok).toBe(false);
102
+ expect(controller.getSnapshot().status).toBe("error");
103
+ });
104
+
105
+ test("clear resets to idle", async () => {
106
+ const client = createClient();
107
+ const controller = createUserProfileController(client);
108
+ await controller.load();
109
+ controller.clear();
110
+ expect(controller.getSnapshot()).toEqual({ status: "idle", user: null, error: null });
111
+ });
112
+ });
@@ -0,0 +1,106 @@
1
+ import type {
2
+ BrowserAuthClient,
3
+ BrowserAuthError,
4
+ MeUpdateRequest,
5
+ MeUser,
6
+ Outcome,
7
+ } from "@smartcrab/browser";
8
+ import { err, ok } from "@smartcrab/browser";
9
+
10
+ /**
11
+ * Headless controller for the `/v1/me` profile surface (design.md §16.2).
12
+ * React-free so it is unit-testable without a renderer; `useUser` binds it.
13
+ */
14
+
15
+ export type UserProfileStatus = "idle" | "loading" | "loaded" | "error";
16
+
17
+ export interface UserProfileSnapshot {
18
+ readonly status: UserProfileStatus;
19
+ readonly user: MeUser | null;
20
+ readonly error: BrowserAuthError | null;
21
+ }
22
+
23
+ export type UserProfileListener = (snapshot: UserProfileSnapshot) => void;
24
+
25
+ export type UserProfileClient = Pick<BrowserAuthClient, "getMe" | "updateMe">;
26
+
27
+ export interface UserProfileController {
28
+ getSnapshot(): UserProfileSnapshot;
29
+ subscribe(listener: UserProfileListener): () => void;
30
+ /** (Re)loads the profile. A `not_authenticated` result resets to `idle`, not `error`. */
31
+ load(): Promise<Outcome<MeUser, BrowserAuthError>>;
32
+ /** Applies a profile patch (design.md §12.1: email changes go through the OTP flow, never here). */
33
+ update(patch: MeUpdateRequest): Promise<Outcome<MeUser, BrowserAuthError>>;
34
+ /** Drops the cached profile (e.g. on sign-out). */
35
+ clear(): void;
36
+ }
37
+
38
+ const IDLE: UserProfileSnapshot = { status: "idle", user: null, error: null };
39
+
40
+ export const createUserProfileController = (client: UserProfileClient): UserProfileController => {
41
+ let snapshot: UserProfileSnapshot = IDLE;
42
+ const listeners = new Set<UserProfileListener>();
43
+ // Concurrent load() calls share one in-flight request, mirroring the
44
+ // client's own refresh dedupe (design.md §21.7).
45
+ let inflight: Promise<Outcome<MeUser, BrowserAuthError>> | null = null;
46
+
47
+ const transition = (next: UserProfileSnapshot): void => {
48
+ snapshot = next;
49
+ for (const listener of listeners) {
50
+ listener(snapshot);
51
+ }
52
+ };
53
+
54
+ const load = (): Promise<Outcome<MeUser, BrowserAuthError>> => {
55
+ if (inflight !== null) return inflight;
56
+ const pending = (async (): Promise<Outcome<MeUser, BrowserAuthError>> => {
57
+ transition({ status: "loading", user: snapshot.user, error: null });
58
+ const outcome = await client.getMe();
59
+ if (!outcome.ok) {
60
+ if (outcome.error.type === "not_authenticated") {
61
+ transition(IDLE);
62
+ } else {
63
+ transition({ status: "error", user: snapshot.user, error: outcome.error });
64
+ }
65
+ return outcome;
66
+ }
67
+ transition({ status: "loaded", user: outcome.value, error: null });
68
+ return ok(outcome.value);
69
+ })();
70
+ inflight = pending;
71
+ const clearInflight = (): void => {
72
+ if (inflight === pending) inflight = null;
73
+ };
74
+ void pending.then(clearInflight, clearInflight);
75
+ return pending;
76
+ };
77
+
78
+ const update = async (patch: MeUpdateRequest): Promise<Outcome<MeUser, BrowserAuthError>> => {
79
+ const outcome = await client.updateMe(patch);
80
+ if (!outcome.ok) {
81
+ if (outcome.error.type === "not_authenticated") {
82
+ transition(IDLE);
83
+ return outcome;
84
+ }
85
+ transition({ status: "error", user: snapshot.user, error: outcome.error });
86
+ return err(outcome.error);
87
+ }
88
+ transition({ status: "loaded", user: outcome.value, error: null });
89
+ return ok(outcome.value);
90
+ };
91
+
92
+ const clear = (): void => {
93
+ transition(IDLE);
94
+ };
95
+
96
+ return {
97
+ getSnapshot: () => snapshot,
98
+ subscribe: (listener) => {
99
+ listeners.add(listener);
100
+ return () => listeners.delete(listener);
101
+ },
102
+ load,
103
+ update,
104
+ clear,
105
+ };
106
+ };