@authsome/ui-core 0.1.8 → 1.0.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/index.mjs DELETED
@@ -1,1734 +0,0 @@
1
- // src/types/auth.ts
2
- var AuthState = /* @__PURE__ */ ((AuthState2) => {
3
- AuthState2["AUTHENTICATED"] = "authenticated";
4
- AuthState2["UNAUTHENTICATED"] = "unauthenticated";
5
- AuthState2["LOADING"] = "loading";
6
- AuthState2["ERROR"] = "error";
7
- return AuthState2;
8
- })(AuthState || {});
9
- var AuthErrorType = /* @__PURE__ */ ((AuthErrorType2) => {
10
- AuthErrorType2["INVALID_CREDENTIALS"] = "invalid_credentials";
11
- AuthErrorType2["USER_NOT_FOUND"] = "user_not_found";
12
- AuthErrorType2["USER_ALREADY_EXISTS"] = "user_already_exists";
13
- AuthErrorType2["INVALID_TOKEN"] = "invalid_token";
14
- AuthErrorType2["TOKEN_EXPIRED"] = "token_expired";
15
- AuthErrorType2["NETWORK_ERROR"] = "network_error";
16
- AuthErrorType2["VALIDATION_ERROR"] = "validation_error";
17
- AuthErrorType2["MFA_REQUIRED"] = "mfa_required";
18
- AuthErrorType2["EMAIL_NOT_VERIFIED"] = "email_not_verified";
19
- AuthErrorType2["PHONE_NOT_VERIFIED"] = "phone_not_verified";
20
- AuthErrorType2["RATE_LIMIT_EXCEEDED"] = "rate_limit_exceeded";
21
- AuthErrorType2["UNKNOWN_ERROR"] = "unknown_error";
22
- return AuthErrorType2;
23
- })(AuthErrorType || {});
24
- var AuthError = class _AuthError extends Error {
25
- constructor(message, type = "unknown_error" /* UNKNOWN_ERROR */, options) {
26
- super(message);
27
- this.name = "AuthError";
28
- this.type = type;
29
- this.details = options?.details;
30
- this.code = options?.code;
31
- this.originalError = options?.originalError;
32
- if (Error.captureStackTrace) {
33
- Error.captureStackTrace(this, _AuthError);
34
- }
35
- }
36
- };
37
- var OAuthProvider = /* @__PURE__ */ ((OAuthProvider2) => {
38
- OAuthProvider2["GOOGLE"] = "google";
39
- OAuthProvider2["GITHUB"] = "github";
40
- OAuthProvider2["FACEBOOK"] = "facebook";
41
- OAuthProvider2["TWITTER"] = "twitter";
42
- OAuthProvider2["MICROSOFT"] = "microsoft";
43
- OAuthProvider2["APPLE"] = "apple";
44
- OAuthProvider2["LINKEDIN"] = "linkedin";
45
- OAuthProvider2["DISCORD"] = "discord";
46
- return OAuthProvider2;
47
- })(OAuthProvider || {});
48
- var TwoFactorMethod = /* @__PURE__ */ ((TwoFactorMethod2) => {
49
- TwoFactorMethod2["TOTP"] = "totp";
50
- TwoFactorMethod2["SMS"] = "sms";
51
- TwoFactorMethod2["EMAIL"] = "email";
52
- TwoFactorMethod2["BACKUP_CODE"] = "backup_code";
53
- return TwoFactorMethod2;
54
- })(TwoFactorMethod || {});
55
-
56
- // src/types/storage.ts
57
- var LocalStorageAdapter = class {
58
- getItem(key) {
59
- if (typeof window === "undefined") return null;
60
- return window.localStorage.getItem(key);
61
- }
62
- setItem(key, value) {
63
- if (typeof window === "undefined") return;
64
- window.localStorage.setItem(key, value);
65
- }
66
- removeItem(key) {
67
- if (typeof window === "undefined") return;
68
- window.localStorage.removeItem(key);
69
- }
70
- clear() {
71
- if (typeof window === "undefined") return;
72
- window.localStorage.clear();
73
- }
74
- };
75
- var SessionStorageAdapter = class {
76
- getItem(key) {
77
- if (typeof window === "undefined") return null;
78
- return window.sessionStorage.getItem(key);
79
- }
80
- setItem(key, value) {
81
- if (typeof window === "undefined") return;
82
- window.sessionStorage.setItem(key, value);
83
- }
84
- removeItem(key) {
85
- if (typeof window === "undefined") return;
86
- window.sessionStorage.removeItem(key);
87
- }
88
- clear() {
89
- if (typeof window === "undefined") return;
90
- window.sessionStorage.clear();
91
- }
92
- };
93
- var MemoryStorageAdapter = class {
94
- constructor() {
95
- this.store = /* @__PURE__ */ new Map();
96
- }
97
- getItem(key) {
98
- return this.store.get(key) ?? null;
99
- }
100
- setItem(key, value) {
101
- this.store.set(key, value);
102
- }
103
- removeItem(key) {
104
- this.store.delete(key);
105
- }
106
- clear() {
107
- this.store.clear();
108
- }
109
- };
110
-
111
- // src/types/observable.ts
112
- var Observable = class {
113
- constructor(initialValue) {
114
- this.listeners = /* @__PURE__ */ new Set();
115
- this.value = initialValue;
116
- }
117
- /**
118
- * Get current value
119
- */
120
- getValue() {
121
- return this.value;
122
- }
123
- /**
124
- * Set new value and notify listeners
125
- */
126
- setValue(newValue) {
127
- if (this.value !== newValue) {
128
- this.value = newValue;
129
- this.notify();
130
- }
131
- }
132
- /**
133
- * Update value with a function
134
- */
135
- update(updater) {
136
- this.setValue(updater(this.value));
137
- }
138
- /**
139
- * Subscribe to value changes
140
- */
141
- subscribe(listener) {
142
- this.listeners.add(listener);
143
- listener(this.value);
144
- return () => {
145
- this.listeners.delete(listener);
146
- };
147
- }
148
- /**
149
- * Notify all listeners
150
- */
151
- notify() {
152
- this.listeners.forEach((listener) => listener(this.value));
153
- }
154
- /**
155
- * Clear all listeners
156
- */
157
- clearListeners() {
158
- this.listeners.clear();
159
- }
160
- /**
161
- * Get number of listeners
162
- */
163
- getListenerCount() {
164
- return this.listeners.size;
165
- }
166
- };
167
-
168
- // src/utils/errors.ts
169
- function createAuthError(type, message, details, code) {
170
- return new AuthError(message, type, { details, code });
171
- }
172
- function isAuthError(error) {
173
- return error instanceof AuthError;
174
- }
175
- function toAuthError(error) {
176
- if (isAuthError(error)) {
177
- return error;
178
- }
179
- if (error instanceof Error) {
180
- return new AuthError(error.message, "unknown_error" /* UNKNOWN_ERROR */, {
181
- details: {
182
- originalError: error.name,
183
- stack: error.stack
184
- }
185
- });
186
- }
187
- if (typeof error === "string") {
188
- return new AuthError(error, "unknown_error" /* UNKNOWN_ERROR */);
189
- }
190
- return new AuthError(
191
- "An unknown error occurred",
192
- "unknown_error" /* UNKNOWN_ERROR */,
193
- { details: { error } }
194
- );
195
- }
196
- function isNetworkError(error) {
197
- if (error instanceof Error) {
198
- return error.name === "NetworkError" || error.message.includes("network") || error.message.includes("fetch");
199
- }
200
- return false;
201
- }
202
- function isUnauthenticatedError(error) {
203
- if (isAuthError(error)) {
204
- return error.type === "invalid_token" /* INVALID_TOKEN */ || error.type === "token_expired" /* TOKEN_EXPIRED */;
205
- }
206
- return false;
207
- }
208
- function isMFARequiredError(error) {
209
- if (isAuthError(error)) {
210
- return error.type === "mfa_required" /* MFA_REQUIRED */;
211
- }
212
- return false;
213
- }
214
-
215
- // src/locale/en.ts
216
- var enLocale = {
217
- common: {
218
- loading: "Loading...",
219
- submit: "Submit",
220
- cancel: "Cancel",
221
- continue: "Continue",
222
- back: "Back",
223
- or: "or",
224
- optional: "optional"
225
- },
226
- auth: {
227
- signIn: "Sign In",
228
- signUp: "Sign Up",
229
- signOut: "Sign Out",
230
- email: "Email",
231
- password: "Password",
232
- confirmPassword: "Confirm Password",
233
- username: "Username",
234
- phone: "Phone",
235
- rememberMe: "Remember me",
236
- forgotPassword: "Forgot password?",
237
- continueWith: "Continue with {provider}",
238
- orContinueWith: "Or continue with"
239
- },
240
- oauth: {
241
- google: "Google",
242
- github: "GitHub",
243
- microsoft: "Microsoft",
244
- facebook: "Facebook",
245
- apple: "Apple",
246
- discord: "Discord",
247
- twitter: "Twitter",
248
- linkedin: "LinkedIn",
249
- chooseProvider: "Choose Your Provider",
250
- signInPreferred: "Sign in with your preferred account"
251
- },
252
- magicLink: {
253
- sendLink: "Send magic link",
254
- checkEmail: "Check your email",
255
- linkSent: "Magic link sent! Check your email to continue.",
256
- enterEmail: "Enter your email to receive a magic link"
257
- },
258
- phone: {
259
- enterPhone: "Enter your phone number",
260
- sendCode: "Send code",
261
- enterCode: "Enter verification code",
262
- verifyPhone: "Verify phone number",
263
- codeLabel: "Verification code"
264
- },
265
- mfa: {
266
- required: "Two-factor authentication required",
267
- selectMethod: "Select verification method",
268
- verify: "Verify",
269
- enterCode: "Enter verification code",
270
- sms: "SMS",
271
- authenticator: "Authenticator app",
272
- email: "Email"
273
- },
274
- passkey: {
275
- signInWith: "Sign in with passkey",
276
- register: "Register passkey",
277
- usePasskey: "Use passkey"
278
- },
279
- signUp: {
280
- title: "Create Account",
281
- subtitle: "Get started with your account",
282
- haveAccount: "Already have an account?",
283
- signInLink: "Sign in",
284
- agreeToTerms: "I agree to the {terms}",
285
- terms: "terms and conditions"
286
- },
287
- signIn: {
288
- title: "Sign In",
289
- subtitle: "Enter your email to continue",
290
- noAccount: "Don't have an account?",
291
- signUpLink: "Sign up",
292
- enterEmail: "Enter your email to continue"
293
- },
294
- validation: {
295
- emailRequired: "Email is required",
296
- emailInvalid: "Invalid email address",
297
- passwordRequired: "Password is required",
298
- passwordTooShort: "Password must be at least {min} characters",
299
- passwordRequireUppercase: "Password must contain an uppercase letter",
300
- passwordRequireLowercase: "Password must contain a lowercase letter",
301
- passwordRequireNumber: "Password must contain a number",
302
- passwordRequireSpecial: "Password must contain a special character",
303
- passwordMismatch: "Passwords do not match",
304
- usernameRequired: "Username is required",
305
- usernameInvalid: "Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens",
306
- phoneRequired: "Phone number is required",
307
- phoneInvalid: "Invalid phone number",
308
- codeRequired: "Verification code is required",
309
- codeInvalid: "Invalid verification code",
310
- fieldRequired: "{field} is required",
311
- termsRequired: "You must agree to the terms and conditions"
312
- },
313
- errors: {
314
- invalidCredentials: "Invalid email or password",
315
- userNotFound: "User not found",
316
- userExists: "User already exists",
317
- invalidToken: "Invalid or expired token",
318
- tokenExpired: "Token has expired",
319
- networkError: "Network error. Please try again.",
320
- mfaRequired: "Two-factor authentication required",
321
- emailNotVerified: "Email not verified",
322
- phoneNotVerified: "Phone number not verified",
323
- rateLimitExceeded: "Too many attempts. Please try again later.",
324
- unknownError: "An unknown error occurred",
325
- generic: "Something went wrong. Please try again."
326
- },
327
- success: {
328
- signedIn: "Successfully signed in",
329
- signedUp: "Account created successfully",
330
- signedOut: "Successfully signed out",
331
- linkSent: "Link sent successfully",
332
- codeSent: "Verification code sent",
333
- verified: "Successfully verified",
334
- welcome: "Welcome, {name}!"
335
- },
336
- placeholders: {
337
- email: "john@example.com",
338
- password: "Enter your password",
339
- confirmPassword: "Confirm your password",
340
- username: "johndoe",
341
- phone: "+1234567890",
342
- code: "123456",
343
- fullName: "John Doe"
344
- }
345
- };
346
-
347
- // src/locale/utils.ts
348
- var defaultLocale = enLocale;
349
- function deepMerge(target, source) {
350
- const result = { ...target };
351
- for (const key in source) {
352
- if (source[key] !== void 0) {
353
- if (typeof source[key] === "object" && source[key] !== null && !Array.isArray(source[key]) && typeof result[key] === "object" && result[key] !== null) {
354
- result[key] = deepMerge(result[key], source[key]);
355
- } else {
356
- result[key] = source[key];
357
- }
358
- }
359
- }
360
- return result;
361
- }
362
- function createLocale(overrides) {
363
- if (!overrides) {
364
- return defaultLocale;
365
- }
366
- return deepMerge(defaultLocale, overrides);
367
- }
368
- function interpolate(template, values) {
369
- return template.replace(/\{(\w+)\}/g, (match, key) => {
370
- return values[key] !== void 0 ? String(values[key]) : match;
371
- });
372
- }
373
-
374
- // src/utils/validation.ts
375
- var EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
376
- var PHONE_REGEX = /^\+?[1-9]\d{1,14}$/;
377
- var USERNAME_REGEX = /^[a-zA-Z0-9_-]{3,30}$/;
378
- function validateEmail(email, locale) {
379
- const messages = locale?.validation || defaultLocale.validation;
380
- if (!email) {
381
- return { field: "email", message: messages.emailRequired };
382
- }
383
- if (!EMAIL_REGEX.test(email)) {
384
- return { field: "email", message: messages.emailInvalid };
385
- }
386
- return null;
387
- }
388
- function validatePassword(password, options = {}) {
389
- const {
390
- minLength = 8,
391
- requireUppercase = true,
392
- requireLowercase = true,
393
- requireNumber = true,
394
- requireSpecial = false,
395
- locale
396
- } = options;
397
- const messages = locale?.validation || defaultLocale.validation;
398
- if (!password) {
399
- return { field: "password", message: messages.passwordRequired };
400
- }
401
- if (password.length < minLength) {
402
- return {
403
- field: "password",
404
- message: interpolate(messages.passwordTooShort, { min: minLength.toString() })
405
- };
406
- }
407
- if (requireUppercase && !/[A-Z]/.test(password)) {
408
- return {
409
- field: "password",
410
- message: messages.passwordRequireUppercase
411
- };
412
- }
413
- if (requireLowercase && !/[a-z]/.test(password)) {
414
- return {
415
- field: "password",
416
- message: messages.passwordRequireLowercase
417
- };
418
- }
419
- if (requireNumber && !/\d/.test(password)) {
420
- return { field: "password", message: messages.passwordRequireNumber };
421
- }
422
- if (requireSpecial && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
423
- return {
424
- field: "password",
425
- message: messages.passwordRequireSpecial
426
- };
427
- }
428
- return null;
429
- }
430
- function validatePhone(phone, locale) {
431
- const messages = locale?.validation || defaultLocale.validation;
432
- if (!phone) {
433
- return { field: "phone", message: messages.phoneRequired };
434
- }
435
- if (!PHONE_REGEX.test(phone)) {
436
- return {
437
- field: "phone",
438
- message: messages.phoneInvalid
439
- };
440
- }
441
- return null;
442
- }
443
- function validateUsername(username, locale) {
444
- const messages = locale?.validation || defaultLocale.validation;
445
- if (!username) {
446
- return { field: "username", message: messages.usernameRequired };
447
- }
448
- if (!USERNAME_REGEX.test(username)) {
449
- return {
450
- field: "username",
451
- message: messages.usernameInvalid
452
- };
453
- }
454
- return null;
455
- }
456
- function validate2FACode(code, locale) {
457
- const messages = locale?.validation || defaultLocale.validation;
458
- if (!code) {
459
- return { field: "code", message: messages.codeRequired };
460
- }
461
- if (!/^\d{6}$/.test(code)) {
462
- return { field: "code", message: messages.codeInvalid };
463
- }
464
- return null;
465
- }
466
- function validateRequired(value, fieldName, locale) {
467
- const messages = locale?.validation || defaultLocale.validation;
468
- if (!value || typeof value === "string" && !value.trim()) {
469
- return {
470
- field: fieldName,
471
- message: interpolate(messages.fieldRequired, { field: fieldName })
472
- };
473
- }
474
- return null;
475
- }
476
-
477
- // src/utils/tokens.ts
478
- var TOKEN_KEY = "authsome_token";
479
- var REFRESH_TOKEN_KEY = "authsome_refresh_token";
480
- var TokenManager = class {
481
- constructor(storage = new LocalStorageAdapter()) {
482
- this.storage = storage;
483
- }
484
- /**
485
- * Get access token
486
- */
487
- async getToken() {
488
- return await Promise.resolve(this.storage.getItem(TOKEN_KEY));
489
- }
490
- /**
491
- * Set access token
492
- */
493
- async setToken(token) {
494
- await Promise.resolve(this.storage.setItem(TOKEN_KEY, token));
495
- }
496
- /**
497
- * Remove access token
498
- */
499
- async removeToken() {
500
- await Promise.resolve(this.storage.removeItem(TOKEN_KEY));
501
- }
502
- /**
503
- * Get refresh token
504
- */
505
- async getRefreshToken() {
506
- return await Promise.resolve(this.storage.getItem(REFRESH_TOKEN_KEY));
507
- }
508
- /**
509
- * Set refresh token
510
- */
511
- async setRefreshToken(token) {
512
- await Promise.resolve(this.storage.setItem(REFRESH_TOKEN_KEY, token));
513
- }
514
- /**
515
- * Remove refresh token
516
- */
517
- async removeRefreshToken() {
518
- await Promise.resolve(this.storage.removeItem(REFRESH_TOKEN_KEY));
519
- }
520
- /**
521
- * Clear all tokens
522
- */
523
- async clearTokens() {
524
- await this.removeToken();
525
- await this.removeRefreshToken();
526
- }
527
- /**
528
- * Check if token is expired
529
- */
530
- isTokenExpired(token) {
531
- try {
532
- const payload = this.decodeToken(token);
533
- if (!payload.exp) return false;
534
- const expiresAt = payload.exp * 1e3;
535
- const now = Date.now();
536
- return expiresAt - now < 6e4;
537
- } catch {
538
- return true;
539
- }
540
- }
541
- /**
542
- * Decode JWT token (without verification)
543
- */
544
- decodeToken(token) {
545
- const parts = token.split(".");
546
- if (parts.length !== 3) {
547
- throw new Error("Invalid token format");
548
- }
549
- const payload = parts[1];
550
- const decoded = atob(payload);
551
- return JSON.parse(decoded);
552
- }
553
- };
554
-
555
- // src/utils/cookies.ts
556
- function parseCookie(setCookieHeader) {
557
- if (!setCookieHeader) return null;
558
- const parts = setCookieHeader.split(";").map((p) => p.trim());
559
- if (parts.length === 0) return null;
560
- const [nameValue] = parts;
561
- const [name, value] = nameValue.split("=");
562
- if (!name || value === void 0) return null;
563
- const cookieData = { name, value };
564
- const options = {};
565
- for (let i = 1; i < parts.length; i++) {
566
- const part = parts[i];
567
- const lowerPart = part.toLowerCase();
568
- if (lowerPart === "httponly") {
569
- options.httpOnly = true;
570
- } else if (lowerPart === "secure") {
571
- options.secure = true;
572
- } else if (lowerPart.startsWith("path=")) {
573
- options.path = part.substring(5);
574
- } else if (lowerPart.startsWith("domain=")) {
575
- options.domain = part.substring(7);
576
- } else if (lowerPart.startsWith("max-age=")) {
577
- const maxAge = parseInt(part.substring(8), 10);
578
- if (!isNaN(maxAge)) {
579
- options.maxAge = maxAge;
580
- }
581
- } else if (lowerPart.startsWith("expires=")) {
582
- const expiresStr = part.substring(8);
583
- const expiresDate = new Date(expiresStr);
584
- if (!isNaN(expiresDate.getTime())) {
585
- options.expires = expiresDate;
586
- }
587
- } else if (lowerPart.startsWith("samesite=")) {
588
- const sameSiteValue = lowerPart.substring(9);
589
- if (sameSiteValue === "strict" || sameSiteValue === "lax" || sameSiteValue === "none") {
590
- options.sameSite = sameSiteValue;
591
- }
592
- }
593
- }
594
- if (Object.keys(options).length > 0) {
595
- cookieData.options = options;
596
- }
597
- return cookieData;
598
- }
599
- function extractCookiesFromHeaders(setCookieHeaders) {
600
- const headers = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders];
601
- const cookies = [];
602
- for (const header of headers) {
603
- const cookie = parseCookie(header);
604
- if (cookie) {
605
- cookies.push(cookie);
606
- }
607
- }
608
- return cookies;
609
- }
610
- function serializeCookie(cookie) {
611
- const parts = [`${cookie.name}=${cookie.value}`];
612
- if (cookie.options) {
613
- const opts = cookie.options;
614
- if (opts.path) {
615
- parts.push(`Path=${opts.path}`);
616
- }
617
- if (opts.domain) {
618
- parts.push(`Domain=${opts.domain}`);
619
- }
620
- if (opts.expires) {
621
- parts.push(`Expires=${opts.expires.toUTCString()}`);
622
- }
623
- if (opts.maxAge !== void 0) {
624
- parts.push(`Max-Age=${opts.maxAge}`);
625
- }
626
- if (opts.httpOnly) {
627
- parts.push("HttpOnly");
628
- }
629
- if (opts.secure) {
630
- parts.push("Secure");
631
- }
632
- if (opts.sameSite) {
633
- const sameSite = opts.sameSite.charAt(0).toUpperCase() + opts.sameSite.slice(1);
634
- parts.push(`SameSite=${sameSite}`);
635
- }
636
- }
637
- return parts.join("; ");
638
- }
639
- function parseCookieOptions(cookieHeader) {
640
- const cookies = {};
641
- if (!cookieHeader) return cookies;
642
- const pairs = cookieHeader.split(";").map((p) => p.trim());
643
- for (const pair of pairs) {
644
- const [name, value] = pair.split("=");
645
- if (name && value !== void 0) {
646
- cookies[name.trim()] = value.trim();
647
- }
648
- }
649
- return cookies;
650
- }
651
- function serializeCookies(cookies) {
652
- return Object.entries(cookies).map(([key, value]) => `${key}=${value}`).join("; ");
653
- }
654
-
655
- // src/adapters/base-provider.ts
656
- var BaseAuthProvider = class {
657
- constructor() {
658
- this.config = {};
659
- this.initialized = false;
660
- }
661
- /**
662
- * Initialize the provider
663
- */
664
- async initialize(config) {
665
- this.config = config;
666
- this.initialized = true;
667
- }
668
- /**
669
- * Ensure provider is initialized
670
- */
671
- ensureInitialized() {
672
- if (!this.initialized) {
673
- throw new Error(`Provider ${this.name} is not initialized`);
674
- }
675
- }
676
- /**
677
- * Make HTTP request
678
- */
679
- async request(url, options = {}) {
680
- const response = await fetch(url, {
681
- ...options,
682
- headers: {
683
- "Content-Type": "application/json",
684
- ...options.headers
685
- }
686
- });
687
- if (!response.ok) {
688
- const error = await response.json().catch(() => ({
689
- message: response.statusText
690
- }));
691
- throw error;
692
- }
693
- return response.json();
694
- }
695
- /**
696
- * Normalize error to AuthError
697
- */
698
- normalizeError(error) {
699
- return toAuthError(error);
700
- }
701
- };
702
-
703
- // src/client.ts
704
- var AuthClient = class {
705
- // Expose adapter for accessing provider-specific methods
706
- get adapter() {
707
- return this.provider;
708
- }
709
- constructor(config) {
710
- this.provider = config.provider;
711
- this.autoRefresh = config.autoRefresh ?? true;
712
- this.refreshInterval = config.refreshInterval ?? 5 * 60 * 1e3;
713
- this.state = new Observable({
714
- state: "loading" /* LOADING */,
715
- user: null,
716
- session: null,
717
- error: null,
718
- isAuthenticated: false,
719
- isLoading: true
720
- });
721
- }
722
- /**
723
- * Initialize the auth client
724
- */
725
- async initialize() {
726
- try {
727
- const user = await this.provider.getCurrentUser();
728
- const session = await this.provider.getCurrentSession();
729
- if (user && session) {
730
- this.updateState({
731
- state: "authenticated" /* AUTHENTICATED */,
732
- user,
733
- session,
734
- error: null,
735
- isAuthenticated: true,
736
- isLoading: false
737
- });
738
- if (this.autoRefresh) {
739
- this.startAutoRefresh();
740
- }
741
- } else {
742
- this.updateState({
743
- state: "unauthenticated" /* UNAUTHENTICATED */,
744
- user: null,
745
- session: null,
746
- error: null,
747
- isAuthenticated: false,
748
- isLoading: false
749
- });
750
- }
751
- } catch (error) {
752
- this.handleError(error);
753
- }
754
- }
755
- /**
756
- * Sign in with credentials
757
- */
758
- async signIn(request) {
759
- try {
760
- this.setLoading();
761
- const response = await this.provider.signIn(request);
762
- if (response.requiresTwoFactor) {
763
- this.updateState({
764
- state: "unauthenticated" /* UNAUTHENTICATED */,
765
- user: response.user,
766
- session: null,
767
- error: null,
768
- isAuthenticated: false,
769
- isLoading: false
770
- });
771
- return;
772
- }
773
- this.updateState({
774
- state: "authenticated" /* AUTHENTICATED */,
775
- user: response.user,
776
- session: response.session,
777
- error: null,
778
- isAuthenticated: true,
779
- isLoading: false
780
- });
781
- if (this.autoRefresh) {
782
- this.startAutoRefresh();
783
- }
784
- } catch (error) {
785
- this.handleError(error);
786
- }
787
- }
788
- /**
789
- * Sign up with credentials
790
- */
791
- async signUp(request) {
792
- try {
793
- this.setLoading();
794
- const response = await this.provider.signUp(request);
795
- this.updateState({
796
- state: "authenticated" /* AUTHENTICATED */,
797
- user: response.user,
798
- session: response.session,
799
- error: null,
800
- isAuthenticated: true,
801
- isLoading: false
802
- });
803
- if (this.autoRefresh) {
804
- this.startAutoRefresh();
805
- }
806
- } catch (error) {
807
- this.handleError(error);
808
- }
809
- }
810
- /**
811
- * Sign out
812
- */
813
- async signOut() {
814
- try {
815
- this.stopAutoRefresh();
816
- await this.provider.signOut();
817
- this.updateState({
818
- state: "unauthenticated" /* UNAUTHENTICATED */,
819
- user: null,
820
- session: null,
821
- error: null,
822
- isAuthenticated: false,
823
- isLoading: false
824
- });
825
- } catch (error) {
826
- this.handleError(error);
827
- }
828
- }
829
- /**
830
- * Update user profile
831
- */
832
- async updateUser(request) {
833
- try {
834
- const user = await this.provider.updateUser(request);
835
- const currentState = this.state.getValue();
836
- this.updateState({
837
- ...currentState,
838
- user
839
- });
840
- } catch (error) {
841
- this.handleError(error);
842
- }
843
- }
844
- /**
845
- * Change password
846
- */
847
- async changePassword(request) {
848
- try {
849
- await this.provider.changePassword(request);
850
- } catch (error) {
851
- throw this.provider.normalizeError(error);
852
- }
853
- }
854
- /**
855
- * Request password reset
856
- */
857
- async requestPasswordReset(request) {
858
- try {
859
- await this.provider.requestPasswordReset(request);
860
- } catch (error) {
861
- throw this.provider.normalizeError(error);
862
- }
863
- }
864
- /**
865
- * Confirm password reset
866
- */
867
- async confirmPasswordReset(request) {
868
- try {
869
- await this.provider.confirmPasswordReset(request);
870
- } catch (error) {
871
- throw this.provider.normalizeError(error);
872
- }
873
- }
874
- /**
875
- * Get OAuth sign in URL
876
- */
877
- async getOAuthUrl(request) {
878
- return this.provider.oauthSignIn(request);
879
- }
880
- /**
881
- * Handle OAuth callback
882
- */
883
- async handleOAuthCallback(request) {
884
- try {
885
- this.setLoading();
886
- const response = await this.provider.oauthCallback(request);
887
- this.updateState({
888
- state: "authenticated" /* AUTHENTICATED */,
889
- user: response.user,
890
- session: response.session,
891
- error: null,
892
- isAuthenticated: true,
893
- isLoading: false
894
- });
895
- if (this.autoRefresh) {
896
- this.startAutoRefresh();
897
- }
898
- } catch (error) {
899
- this.handleError(error);
900
- }
901
- }
902
- /**
903
- * Get available OAuth providers
904
- */
905
- async getOAuthProviders() {
906
- return this.provider.getOAuthProviders();
907
- }
908
- /**
909
- * Send magic link
910
- */
911
- async sendMagicLink(request) {
912
- try {
913
- await this.provider.sendMagicLink(request);
914
- } catch (error) {
915
- throw this.provider.normalizeError(error);
916
- }
917
- }
918
- /**
919
- * Verify magic link
920
- */
921
- async verifyMagicLink(request) {
922
- try {
923
- this.setLoading();
924
- const response = await this.provider.verifyMagicLink(request);
925
- this.updateState({
926
- state: "authenticated" /* AUTHENTICATED */,
927
- user: response.user,
928
- session: response.session,
929
- error: null,
930
- isAuthenticated: true,
931
- isLoading: false
932
- });
933
- if (this.autoRefresh) {
934
- this.startAutoRefresh();
935
- }
936
- } catch (error) {
937
- this.handleError(error);
938
- }
939
- }
940
- /**
941
- * Send phone verification code
942
- */
943
- async sendPhoneCode(request) {
944
- try {
945
- await this.provider.sendPhoneCode(request);
946
- } catch (error) {
947
- throw this.provider.normalizeError(error);
948
- }
949
- }
950
- /**
951
- * Verify phone code
952
- */
953
- async verifyPhoneCode(request) {
954
- try {
955
- this.setLoading();
956
- const response = await this.provider.verifyPhoneCode(request);
957
- this.updateState({
958
- state: "authenticated" /* AUTHENTICATED */,
959
- user: response.user,
960
- session: response.session,
961
- error: null,
962
- isAuthenticated: true,
963
- isLoading: false
964
- });
965
- if (this.autoRefresh) {
966
- this.startAutoRefresh();
967
- }
968
- } catch (error) {
969
- this.handleError(error);
970
- }
971
- }
972
- /**
973
- * Setup 2FA
974
- */
975
- async setupTwoFactor(request) {
976
- return this.provider.setupTwoFactor(request);
977
- }
978
- /**
979
- * Verify 2FA code
980
- */
981
- async verifyTwoFactor(request) {
982
- try {
983
- this.setLoading();
984
- const response = await this.provider.verifyTwoFactor(request);
985
- this.updateState({
986
- state: "authenticated" /* AUTHENTICATED */,
987
- user: response.user,
988
- session: response.session,
989
- error: null,
990
- isAuthenticated: true,
991
- isLoading: false
992
- });
993
- if (this.autoRefresh) {
994
- this.startAutoRefresh();
995
- }
996
- } catch (error) {
997
- this.handleError(error);
998
- }
999
- }
1000
- /**
1001
- * Disable 2FA
1002
- */
1003
- async disableTwoFactor() {
1004
- return this.provider.disableTwoFactor();
1005
- }
1006
- /**
1007
- * Get 2FA status
1008
- */
1009
- async getTwoFactorStatus() {
1010
- return this.provider.getTwoFactorStatus();
1011
- }
1012
- /**
1013
- * Register passkey
1014
- */
1015
- async registerPasskey(request) {
1016
- return this.provider.registerPasskey(request);
1017
- }
1018
- /**
1019
- * Authenticate with passkey
1020
- */
1021
- async authenticatePasskey(request) {
1022
- try {
1023
- this.setLoading();
1024
- const response = await this.provider.authenticatePasskey(request);
1025
- this.updateState({
1026
- state: "authenticated" /* AUTHENTICATED */,
1027
- user: response.user,
1028
- session: response.session,
1029
- error: null,
1030
- isAuthenticated: true,
1031
- isLoading: false
1032
- });
1033
- if (this.autoRefresh) {
1034
- this.startAutoRefresh();
1035
- }
1036
- } catch (error) {
1037
- this.handleError(error);
1038
- }
1039
- }
1040
- /**
1041
- * List passkeys
1042
- */
1043
- async listPasskeys() {
1044
- return this.provider.listPasskeys();
1045
- }
1046
- /**
1047
- * Delete passkey
1048
- */
1049
- async deletePasskey(credentialId) {
1050
- return this.provider.deletePasskey(credentialId);
1051
- }
1052
- /**
1053
- * Get all organizations the user belongs to
1054
- * Only available if the provider supports organizations
1055
- */
1056
- async getOrganizations() {
1057
- if (!this.provider.getOrganizations) {
1058
- throw this.createUnsupportedError("Organization support");
1059
- }
1060
- return this.provider.getOrganizations();
1061
- }
1062
- /**
1063
- * Get the currently active organization
1064
- * Only available if the provider supports organizations
1065
- */
1066
- async getActiveOrganization() {
1067
- if (!this.provider.getActiveOrganization) {
1068
- throw this.createUnsupportedError("Organization support");
1069
- }
1070
- return this.provider.getActiveOrganization();
1071
- }
1072
- /**
1073
- * Set the active organization and refresh user state
1074
- * Only available if the provider supports organizations
1075
- */
1076
- async setActiveOrganization(organizationId) {
1077
- if (!this.provider.setActiveOrganization) {
1078
- throw this.createUnsupportedError("Organization support");
1079
- }
1080
- await this.provider.setActiveOrganization(organizationId);
1081
- await this.refreshSession();
1082
- }
1083
- /**
1084
- * Get organization memberships with roles and permissions
1085
- * Only available if the provider supports organizations
1086
- */
1087
- async getOrganizationMemberships() {
1088
- if (!this.provider.getOrganizationMemberships) {
1089
- throw this.createUnsupportedError("Organization memberships");
1090
- }
1091
- return this.provider.getOrganizationMemberships();
1092
- }
1093
- /**
1094
- * Check if the provider supports organizations
1095
- */
1096
- supportsOrganizations() {
1097
- return !!(this.provider.getOrganizations && this.provider.getActiveOrganization && this.provider.setActiveOrganization);
1098
- }
1099
- /**
1100
- * Refresh session
1101
- */
1102
- async refreshSession() {
1103
- try {
1104
- const session = await this.provider.refreshSession();
1105
- const currentState = this.state.getValue();
1106
- this.updateState({
1107
- ...currentState,
1108
- session
1109
- });
1110
- } catch (error) {
1111
- console.warn("[AuthClient] Session refresh failed:", error);
1112
- }
1113
- }
1114
- /**
1115
- * Get current user
1116
- */
1117
- getUser() {
1118
- return this.state.getValue().user;
1119
- }
1120
- /**
1121
- * Get current session
1122
- */
1123
- getSession() {
1124
- return this.state.getValue().session;
1125
- }
1126
- /**
1127
- * Check if authenticated
1128
- */
1129
- isAuthenticated() {
1130
- return this.state.getValue().isAuthenticated;
1131
- }
1132
- /**
1133
- * Get current error
1134
- */
1135
- getError() {
1136
- return this.state.getValue().error;
1137
- }
1138
- /**
1139
- * Clear error
1140
- */
1141
- clearError() {
1142
- const currentState = this.state.getValue();
1143
- this.updateState({
1144
- ...currentState,
1145
- error: null
1146
- });
1147
- }
1148
- /**
1149
- * Subscribe to auth state changes
1150
- */
1151
- subscribe(listener) {
1152
- return this.state.subscribe(listener);
1153
- }
1154
- /**
1155
- * Cleanup resources
1156
- */
1157
- destroy() {
1158
- this.stopAutoRefresh();
1159
- this.state.clearListeners();
1160
- }
1161
- // Private methods
1162
- updateState(newState) {
1163
- this.state.setValue(newState);
1164
- }
1165
- setLoading() {
1166
- const currentState = this.state.getValue();
1167
- this.updateState({
1168
- ...currentState,
1169
- state: "loading" /* LOADING */,
1170
- isLoading: true,
1171
- error: null
1172
- });
1173
- }
1174
- handleError(error) {
1175
- const authError = this.provider.normalizeError(error);
1176
- const currentState = this.state.getValue();
1177
- this.updateState({
1178
- ...currentState,
1179
- state: "error" /* ERROR */,
1180
- error: authError,
1181
- isLoading: false
1182
- });
1183
- throw authError;
1184
- }
1185
- startAutoRefresh() {
1186
- this.stopAutoRefresh();
1187
- this.refreshTimer = setInterval(() => {
1188
- this.refreshSession();
1189
- }, this.refreshInterval);
1190
- }
1191
- stopAutoRefresh() {
1192
- if (this.refreshTimer) {
1193
- clearInterval(this.refreshTimer);
1194
- this.refreshTimer = void 0;
1195
- }
1196
- }
1197
- createUnsupportedError(feature) {
1198
- return {
1199
- name: "AuthError",
1200
- message: `${feature} is not available with this auth provider`,
1201
- type: "unknown_error" /* UNKNOWN_ERROR */
1202
- };
1203
- }
1204
- };
1205
-
1206
- // src/flows/types.ts
1207
- var FlowStep = /* @__PURE__ */ ((FlowStep2) => {
1208
- FlowStep2["SIGN_IN"] = "sign_in";
1209
- FlowStep2["SIGN_UP"] = "sign_up";
1210
- FlowStep2["EMAIL_PASSWORD_SIGN_IN"] = "email_password_sign_in";
1211
- FlowStep2["EMAIL_PASSWORD_SIGN_UP"] = "email_password_sign_up";
1212
- FlowStep2["OAUTH_SELECT"] = "oauth_select";
1213
- FlowStep2["OAUTH_CALLBACK"] = "oauth_callback";
1214
- FlowStep2["MAGIC_LINK_REQUEST"] = "magic_link_request";
1215
- FlowStep2["MAGIC_LINK_VERIFY"] = "magic_link_verify";
1216
- FlowStep2["MAGIC_LINK_SENT"] = "magic_link_sent";
1217
- FlowStep2["PHONE_REQUEST"] = "phone_request";
1218
- FlowStep2["PHONE_VERIFY"] = "phone_verify";
1219
- FlowStep2["USERNAME_SIGN_IN"] = "username_sign_in";
1220
- FlowStep2["USERNAME_SIGN_UP"] = "username_sign_up";
1221
- FlowStep2["PASSKEY_REGISTER"] = "passkey_register";
1222
- FlowStep2["PASSKEY_AUTHENTICATE"] = "passkey_authenticate";
1223
- FlowStep2["MFA_REQUIRED"] = "mfa_required";
1224
- FlowStep2["MFA_SETUP"] = "mfa_setup";
1225
- FlowStep2["MFA_VERIFY"] = "mfa_verify";
1226
- FlowStep2["MFA_SELECT_METHOD"] = "mfa_select_method";
1227
- FlowStep2["EMAIL_VERIFICATION_REQUIRED"] = "email_verification_required";
1228
- FlowStep2["EMAIL_VERIFICATION_SENT"] = "email_verification_sent";
1229
- FlowStep2["PHONE_VERIFICATION_REQUIRED"] = "phone_verification_required";
1230
- FlowStep2["PASSWORD_RESET_REQUEST"] = "password_reset_request";
1231
- FlowStep2["PASSWORD_RESET_SENT"] = "password_reset_sent";
1232
- FlowStep2["PASSWORD_RESET_CONFIRM"] = "password_reset_confirm";
1233
- FlowStep2["PASSWORD_CHANGE"] = "password_change";
1234
- FlowStep2["PROFILE_UPDATE"] = "profile_update";
1235
- FlowStep2["PROFILE_COMPLETE"] = "profile_complete";
1236
- FlowStep2["SUCCESS"] = "success";
1237
- FlowStep2["ERROR"] = "error";
1238
- FlowStep2["CANCELLED"] = "cancelled";
1239
- return FlowStep2;
1240
- })(FlowStep || {});
1241
- var FlowConfigType = /* @__PURE__ */ ((FlowConfigType2) => {
1242
- FlowConfigType2["SIMPLE_SIGN_IN"] = "simple_sign_in";
1243
- FlowConfigType2["SIMPLE_SIGN_UP"] = "simple_sign_up";
1244
- FlowConfigType2["SIGN_UP_WITH_EMAIL_VERIFICATION"] = "sign_up_with_email_verification";
1245
- FlowConfigType2["SIGN_IN_WITH_MFA"] = "sign_in_with_mfa";
1246
- FlowConfigType2["OAUTH_SIGN_IN"] = "oauth_sign_in";
1247
- FlowConfigType2["MAGIC_LINK_FLOW"] = "magic_link_flow";
1248
- FlowConfigType2["PHONE_AUTH_FLOW"] = "phone_auth_flow";
1249
- FlowConfigType2["COMPLETE_SIGN_UP_FLOW"] = "complete_sign_up_flow";
1250
- FlowConfigType2["SECURE_SIGN_IN_FLOW"] = "secure_sign_in_flow";
1251
- FlowConfigType2["PASSWORD_RESET_FLOW"] = "password_reset_flow";
1252
- FlowConfigType2["EMAIL_VERIFICATION_FLOW"] = "email_verification_flow";
1253
- FlowConfigType2["CUSTOM"] = "custom";
1254
- return FlowConfigType2;
1255
- })(FlowConfigType || {});
1256
- var FlowAction = /* @__PURE__ */ ((FlowAction2) => {
1257
- FlowAction2["START"] = "start";
1258
- FlowAction2["NEXT"] = "next";
1259
- FlowAction2["BACK"] = "back";
1260
- FlowAction2["CANCEL"] = "cancel";
1261
- FlowAction2["ERROR"] = "error";
1262
- FlowAction2["RESET"] = "reset";
1263
- return FlowAction2;
1264
- })(FlowAction || {});
1265
-
1266
- // src/flows/engine.ts
1267
- var FlowEngine = class {
1268
- constructor(config, initialState) {
1269
- this.history = [];
1270
- this.config = config;
1271
- this.state = {
1272
- currentStep: config.initialStep,
1273
- ...initialState
1274
- };
1275
- this.history.push(this.state.currentStep);
1276
- }
1277
- /**
1278
- * Get current flow state
1279
- */
1280
- getState() {
1281
- return { ...this.state };
1282
- }
1283
- /**
1284
- * Get current step
1285
- */
1286
- getCurrentStep() {
1287
- return this.state.currentStep;
1288
- }
1289
- /**
1290
- * Check if step is allowed in this flow
1291
- */
1292
- isStepAllowed(step) {
1293
- return this.config.allowedSteps.includes(step);
1294
- }
1295
- /**
1296
- * Transition to next step based on action
1297
- */
1298
- async transition(event) {
1299
- const { action, data, error } = event;
1300
- switch (action) {
1301
- case "start":
1302
- return this.handleStart(data);
1303
- case "next":
1304
- return this.handleNext(data);
1305
- case "back":
1306
- return this.handleBack();
1307
- case "cancel":
1308
- return this.handleCancel();
1309
- case "error":
1310
- return this.handleError(error);
1311
- case "reset":
1312
- return this.handleReset();
1313
- default:
1314
- throw new AuthError(
1315
- `Unknown flow action: ${action}`,
1316
- "validation_error" /* VALIDATION_ERROR */
1317
- );
1318
- }
1319
- }
1320
- /**
1321
- * Start or restart the flow
1322
- */
1323
- handleStart(data) {
1324
- this.state = {
1325
- currentStep: this.config.initialStep,
1326
- ...data
1327
- };
1328
- this.history = [this.state.currentStep];
1329
- if (this.config.onStepChange) {
1330
- this.config.onStepChange(this.state.currentStep, this.state);
1331
- }
1332
- return this.getState();
1333
- }
1334
- /**
1335
- * Move to next step
1336
- */
1337
- handleNext(data) {
1338
- this.state = {
1339
- ...this.state,
1340
- ...data,
1341
- previousStep: this.state.currentStep
1342
- };
1343
- const transitionConfig = this.config.transitions[this.state.currentStep];
1344
- if (!transitionConfig) {
1345
- throw new AuthError(
1346
- `No transition configured for step: ${this.state.currentStep}`,
1347
- "validation_error" /* VALIDATION_ERROR */
1348
- );
1349
- }
1350
- if (transitionConfig.conditions) {
1351
- for (const condition of transitionConfig.conditions) {
1352
- if (condition.when(this.state)) {
1353
- return this.moveToStep(condition.then);
1354
- }
1355
- }
1356
- }
1357
- if (transitionConfig.onSuccess) {
1358
- return this.moveToStep(transitionConfig.onSuccess);
1359
- }
1360
- throw new AuthError(
1361
- `No valid transition found for step: ${this.state.currentStep}`,
1362
- "validation_error" /* VALIDATION_ERROR */
1363
- );
1364
- }
1365
- /**
1366
- * Go back to previous step
1367
- */
1368
- handleBack() {
1369
- if (this.history.length < 2) {
1370
- throw new AuthError(
1371
- "Cannot go back - already at first step",
1372
- "validation_error" /* VALIDATION_ERROR */
1373
- );
1374
- }
1375
- this.history.pop();
1376
- const previousStep = this.history[this.history.length - 1];
1377
- const transitionConfig = this.config.transitions[this.state.currentStep];
1378
- const targetStep = transitionConfig?.onBack || previousStep;
1379
- return this.moveToStep(targetStep, false);
1380
- }
1381
- /**
1382
- * Cancel the flow
1383
- */
1384
- handleCancel() {
1385
- const transitionConfig = this.config.transitions[this.state.currentStep];
1386
- const targetStep = transitionConfig?.onCancel;
1387
- if (this.config.onCancel) {
1388
- this.config.onCancel(this.state);
1389
- }
1390
- if (targetStep) {
1391
- return this.moveToStep(targetStep);
1392
- }
1393
- this.state.currentStep = "cancelled";
1394
- return this.getState();
1395
- }
1396
- /**
1397
- * Handle error in flow
1398
- */
1399
- handleError(error) {
1400
- this.state.error = error;
1401
- const transitionConfig = this.config.transitions[this.state.currentStep];
1402
- const targetStep = transitionConfig?.onError;
1403
- if (this.config.onError) {
1404
- this.config.onError(error, this.state);
1405
- }
1406
- if (targetStep) {
1407
- return this.moveToStep(targetStep);
1408
- }
1409
- return this.getState();
1410
- }
1411
- /**
1412
- * Reset flow to initial state
1413
- */
1414
- handleReset() {
1415
- return this.handleStart();
1416
- }
1417
- /**
1418
- * Move to a specific step
1419
- */
1420
- moveToStep(step, addToHistory = true) {
1421
- if (!this.isStepAllowed(step)) {
1422
- throw new AuthError(
1423
- `Step ${step} is not allowed in this flow`,
1424
- "validation_error" /* VALIDATION_ERROR */
1425
- );
1426
- }
1427
- this.state.currentStep = step;
1428
- if (addToHistory) {
1429
- this.history.push(step);
1430
- }
1431
- if (this.config.onStepChange) {
1432
- this.config.onStepChange(step, this.state);
1433
- }
1434
- if (step === "success" && this.state.user && this.state.session) {
1435
- if (this.config.onComplete) {
1436
- this.config.onComplete(this.state.user, this.state.session);
1437
- }
1438
- }
1439
- return this.getState();
1440
- }
1441
- /**
1442
- * Get flow history
1443
- */
1444
- getHistory() {
1445
- return [...this.history];
1446
- }
1447
- /**
1448
- * Check if can go back
1449
- */
1450
- canGoBack() {
1451
- return this.history.length > 1;
1452
- }
1453
- };
1454
-
1455
- // src/flows/configs.ts
1456
- var simpleSignInFlow = {
1457
- name: "Simple Sign In",
1458
- description: "Basic email/password sign-in",
1459
- initialStep: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1460
- allowedSteps: [
1461
- "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1462
- "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */,
1463
- "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1464
- "password_reset_request" /* PASSWORD_RESET_REQUEST */,
1465
- "password_reset_sent" /* PASSWORD_RESET_SENT */,
1466
- "success" /* SUCCESS */,
1467
- "error" /* ERROR */
1468
- ],
1469
- transitions: {
1470
- ["email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */]: {
1471
- onSuccess: "success" /* SUCCESS */,
1472
- onError: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */
1473
- },
1474
- ["email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */]: {
1475
- onSuccess: "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1476
- onError: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */
1477
- },
1478
- ["email_verification_sent" /* EMAIL_VERIFICATION_SENT */]: {
1479
- onSuccess: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1480
- onError: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */
1481
- },
1482
- ["password_reset_request" /* PASSWORD_RESET_REQUEST */]: {
1483
- onSuccess: "password_reset_sent" /* PASSWORD_RESET_SENT */,
1484
- onBack: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */
1485
- },
1486
- ["password_reset_sent" /* PASSWORD_RESET_SENT */]: {
1487
- onSuccess: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */
1488
- }
1489
- }
1490
- };
1491
- var signInWithMFAFlow = {
1492
- name: "Sign In with MFA",
1493
- description: "Sign-in that handles MFA if enabled",
1494
- initialStep: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1495
- allowedSteps: [
1496
- "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1497
- "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */,
1498
- "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1499
- "mfa_required" /* MFA_REQUIRED */,
1500
- "mfa_select_method" /* MFA_SELECT_METHOD */,
1501
- "mfa_verify" /* MFA_VERIFY */,
1502
- "password_reset_request" /* PASSWORD_RESET_REQUEST */,
1503
- "password_reset_sent" /* PASSWORD_RESET_SENT */,
1504
- "success" /* SUCCESS */,
1505
- "error" /* ERROR */
1506
- ],
1507
- transitions: {
1508
- ["email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */]: {
1509
- onSuccess: "success" /* SUCCESS */,
1510
- onError: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1511
- conditions: [
1512
- {
1513
- when: (state) => state.mfaRequired === true,
1514
- then: "mfa_required" /* MFA_REQUIRED */
1515
- }
1516
- ]
1517
- },
1518
- ["email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */]: {
1519
- onSuccess: "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1520
- onError: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */
1521
- },
1522
- ["email_verification_sent" /* EMAIL_VERIFICATION_SENT */]: {
1523
- onSuccess: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */,
1524
- onError: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */
1525
- },
1526
- ["mfa_required" /* MFA_REQUIRED */]: {
1527
- onSuccess: "mfa_verify" /* MFA_VERIFY */,
1528
- conditions: [
1529
- {
1530
- when: (state) => (state.mfaMethods?.length || 0) > 1,
1531
- then: "mfa_select_method" /* MFA_SELECT_METHOD */
1532
- }
1533
- ]
1534
- },
1535
- ["mfa_select_method" /* MFA_SELECT_METHOD */]: {
1536
- onSuccess: "mfa_verify" /* MFA_VERIFY */,
1537
- onBack: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */
1538
- },
1539
- ["mfa_verify" /* MFA_VERIFY */]: {
1540
- onSuccess: "success" /* SUCCESS */,
1541
- onError: "mfa_verify" /* MFA_VERIFY */,
1542
- onBack: "mfa_select_method" /* MFA_SELECT_METHOD */
1543
- },
1544
- ["password_reset_request" /* PASSWORD_RESET_REQUEST */]: {
1545
- onSuccess: "password_reset_sent" /* PASSWORD_RESET_SENT */,
1546
- onBack: "email_password_sign_in" /* EMAIL_PASSWORD_SIGN_IN */
1547
- }
1548
- }
1549
- };
1550
- var completeSignUpFlow = {
1551
- name: "Complete Sign Up",
1552
- description: "Sign-up with email verification and profile completion",
1553
- initialStep: "email_password_sign_up" /* EMAIL_PASSWORD_SIGN_UP */,
1554
- allowedSteps: [
1555
- "email_password_sign_up" /* EMAIL_PASSWORD_SIGN_UP */,
1556
- "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */,
1557
- "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1558
- "profile_complete" /* PROFILE_COMPLETE */,
1559
- "success" /* SUCCESS */,
1560
- "error" /* ERROR */
1561
- ],
1562
- transitions: {
1563
- ["email_password_sign_up" /* EMAIL_PASSWORD_SIGN_UP */]: {
1564
- onSuccess: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */,
1565
- onError: "email_password_sign_up" /* EMAIL_PASSWORD_SIGN_UP */,
1566
- conditions: [
1567
- {
1568
- when: (state) => state.verificationRequired === false,
1569
- then: "profile_complete" /* PROFILE_COMPLETE */
1570
- }
1571
- ]
1572
- },
1573
- ["email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */]: {
1574
- onSuccess: "email_verification_sent" /* EMAIL_VERIFICATION_SENT */
1575
- },
1576
- ["email_verification_sent" /* EMAIL_VERIFICATION_SENT */]: {
1577
- onSuccess: "profile_complete" /* PROFILE_COMPLETE */
1578
- },
1579
- ["profile_complete" /* PROFILE_COMPLETE */]: {
1580
- onSuccess: "success" /* SUCCESS */,
1581
- onError: "profile_complete" /* PROFILE_COMPLETE */
1582
- }
1583
- }
1584
- };
1585
- var magicLinkFlow = {
1586
- name: "Magic Link",
1587
- description: "Passwordless authentication via email",
1588
- initialStep: "magic_link_request" /* MAGIC_LINK_REQUEST */,
1589
- allowedSteps: [
1590
- "magic_link_request" /* MAGIC_LINK_REQUEST */,
1591
- "magic_link_sent" /* MAGIC_LINK_SENT */,
1592
- "magic_link_verify" /* MAGIC_LINK_VERIFY */,
1593
- "success" /* SUCCESS */,
1594
- "error" /* ERROR */
1595
- ],
1596
- transitions: {
1597
- ["magic_link_request" /* MAGIC_LINK_REQUEST */]: {
1598
- onSuccess: "magic_link_sent" /* MAGIC_LINK_SENT */,
1599
- onError: "magic_link_request" /* MAGIC_LINK_REQUEST */
1600
- },
1601
- ["magic_link_sent" /* MAGIC_LINK_SENT */]: {
1602
- onSuccess: "magic_link_verify" /* MAGIC_LINK_VERIFY */
1603
- },
1604
- ["magic_link_verify" /* MAGIC_LINK_VERIFY */]: {
1605
- onSuccess: "success" /* SUCCESS */,
1606
- onError: "magic_link_request" /* MAGIC_LINK_REQUEST */
1607
- }
1608
- }
1609
- };
1610
- var phoneAuthFlow = {
1611
- name: "Phone Authentication",
1612
- description: "SMS-based authentication",
1613
- initialStep: "phone_request" /* PHONE_REQUEST */,
1614
- allowedSteps: [
1615
- "phone_request" /* PHONE_REQUEST */,
1616
- "phone_verify" /* PHONE_VERIFY */,
1617
- "success" /* SUCCESS */,
1618
- "error" /* ERROR */
1619
- ],
1620
- transitions: {
1621
- ["phone_request" /* PHONE_REQUEST */]: {
1622
- onSuccess: "phone_verify" /* PHONE_VERIFY */,
1623
- onError: "phone_request" /* PHONE_REQUEST */
1624
- },
1625
- ["phone_verify" /* PHONE_VERIFY */]: {
1626
- onSuccess: "success" /* SUCCESS */,
1627
- onError: "phone_verify" /* PHONE_VERIFY */,
1628
- onBack: "phone_request" /* PHONE_REQUEST */
1629
- }
1630
- }
1631
- };
1632
- var oauthSignInFlow = {
1633
- name: "OAuth Sign In",
1634
- description: "Third-party OAuth authentication",
1635
- initialStep: "oauth_select" /* OAUTH_SELECT */,
1636
- allowedSteps: [
1637
- "oauth_select" /* OAUTH_SELECT */,
1638
- "oauth_callback" /* OAUTH_CALLBACK */,
1639
- "success" /* SUCCESS */,
1640
- "error" /* ERROR */
1641
- ],
1642
- transitions: {
1643
- ["oauth_select" /* OAUTH_SELECT */]: {
1644
- onSuccess: "oauth_callback" /* OAUTH_CALLBACK */,
1645
- onError: "oauth_select" /* OAUTH_SELECT */
1646
- },
1647
- ["oauth_callback" /* OAUTH_CALLBACK */]: {
1648
- onSuccess: "success" /* SUCCESS */,
1649
- onError: "oauth_select" /* OAUTH_SELECT */
1650
- }
1651
- }
1652
- };
1653
- var passwordResetFlow = {
1654
- name: "Password Reset",
1655
- description: "Reset forgotten password",
1656
- initialStep: "password_reset_request" /* PASSWORD_RESET_REQUEST */,
1657
- allowedSteps: [
1658
- "password_reset_request" /* PASSWORD_RESET_REQUEST */,
1659
- "password_reset_sent" /* PASSWORD_RESET_SENT */,
1660
- "password_reset_confirm" /* PASSWORD_RESET_CONFIRM */,
1661
- "success" /* SUCCESS */,
1662
- "error" /* ERROR */
1663
- ],
1664
- transitions: {
1665
- ["password_reset_request" /* PASSWORD_RESET_REQUEST */]: {
1666
- onSuccess: "password_reset_sent" /* PASSWORD_RESET_SENT */,
1667
- onError: "password_reset_request" /* PASSWORD_RESET_REQUEST */
1668
- },
1669
- ["password_reset_sent" /* PASSWORD_RESET_SENT */]: {
1670
- onSuccess: "password_reset_confirm" /* PASSWORD_RESET_CONFIRM */
1671
- },
1672
- ["password_reset_confirm" /* PASSWORD_RESET_CONFIRM */]: {
1673
- onSuccess: "success" /* SUCCESS */,
1674
- onError: "password_reset_confirm" /* PASSWORD_RESET_CONFIRM */
1675
- }
1676
- }
1677
- };
1678
- var emailVerificationFlow = {
1679
- name: "Email Verification",
1680
- description: "Verify email address with code or link",
1681
- initialStep: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */,
1682
- allowedSteps: [
1683
- "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */,
1684
- "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1685
- "success" /* SUCCESS */,
1686
- "error" /* ERROR */
1687
- ],
1688
- transitions: {
1689
- ["email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */]: {
1690
- onSuccess: "email_verification_sent" /* EMAIL_VERIFICATION_SENT */,
1691
- onError: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */
1692
- },
1693
- ["email_verification_sent" /* EMAIL_VERIFICATION_SENT */]: {
1694
- onSuccess: "success" /* SUCCESS */,
1695
- onError: "email_verification_required" /* EMAIL_VERIFICATION_REQUIRED */
1696
- }
1697
- }
1698
- };
1699
- function getFlowConfig(type) {
1700
- switch (type) {
1701
- case "simple_sign_in" /* SIMPLE_SIGN_IN */:
1702
- return simpleSignInFlow;
1703
- case "sign_in_with_mfa" /* SIGN_IN_WITH_MFA */:
1704
- return signInWithMFAFlow;
1705
- case "complete_sign_up_flow" /* COMPLETE_SIGN_UP_FLOW */:
1706
- return completeSignUpFlow;
1707
- case "magic_link_flow" /* MAGIC_LINK_FLOW */:
1708
- return magicLinkFlow;
1709
- case "phone_auth_flow" /* PHONE_AUTH_FLOW */:
1710
- return phoneAuthFlow;
1711
- case "oauth_sign_in" /* OAUTH_SIGN_IN */:
1712
- return oauthSignInFlow;
1713
- case "password_reset_flow" /* PASSWORD_RESET_FLOW */:
1714
- return passwordResetFlow;
1715
- case "email_verification_flow" /* EMAIL_VERIFICATION_FLOW */:
1716
- return emailVerificationFlow;
1717
- default:
1718
- throw new Error(`Unknown flow type: ${type}`);
1719
- }
1720
- }
1721
- var predefinedFlows = {
1722
- ["simple_sign_in" /* SIMPLE_SIGN_IN */]: simpleSignInFlow,
1723
- ["sign_in_with_mfa" /* SIGN_IN_WITH_MFA */]: signInWithMFAFlow,
1724
- ["complete_sign_up_flow" /* COMPLETE_SIGN_UP_FLOW */]: completeSignUpFlow,
1725
- ["magic_link_flow" /* MAGIC_LINK_FLOW */]: magicLinkFlow,
1726
- ["phone_auth_flow" /* PHONE_AUTH_FLOW */]: phoneAuthFlow,
1727
- ["oauth_sign_in" /* OAUTH_SIGN_IN */]: oauthSignInFlow,
1728
- ["password_reset_flow" /* PASSWORD_RESET_FLOW */]: passwordResetFlow,
1729
- ["email_verification_flow" /* EMAIL_VERIFICATION_FLOW */]: emailVerificationFlow
1730
- };
1731
-
1732
- export { AuthClient, AuthError, AuthErrorType, AuthState, BaseAuthProvider, FlowAction, FlowConfigType, FlowEngine, FlowStep, LocalStorageAdapter, MemoryStorageAdapter, OAuthProvider, Observable, SessionStorageAdapter, TokenManager, TwoFactorMethod, completeSignUpFlow, createAuthError, createLocale, defaultLocale, emailVerificationFlow, extractCookiesFromHeaders, getFlowConfig, interpolate, isAuthError, isMFARequiredError, isNetworkError, isUnauthenticatedError, magicLinkFlow, oauthSignInFlow, parseCookie, parseCookieOptions, passwordResetFlow, phoneAuthFlow, predefinedFlows, serializeCookie, serializeCookies, signInWithMFAFlow, simpleSignInFlow, toAuthError, validate2FACode, validateEmail, validatePassword, validatePhone, validateRequired, validateUsername };
1733
- //# sourceMappingURL=index.mjs.map
1734
- //# sourceMappingURL=index.mjs.map