@donotdev/auth 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +6 -1
  2. package/dist/AuthStore.js +1 -1
  3. package/dist/authHelpers.js +1 -1
  4. package/dist/components/AccountLinking.js +1 -1
  5. package/dist/components/AuthFallback.js +1 -1
  6. package/dist/components/AuthPartnerButton.js +1 -1
  7. package/dist/components/DeleteAccountDialogs.js +1 -1
  8. package/dist/components/EmailLinkForm.js +1 -1
  9. package/dist/components/EmailPasswordForm.d.ts +4 -2
  10. package/dist/components/EmailPasswordForm.d.ts.map +1 -1
  11. package/dist/components/EmailPasswordForm.js +1 -1
  12. package/dist/components/EmailVerification.js +1 -1
  13. package/dist/components/Feature.js +1 -1
  14. package/dist/components/FeatureGuard.js +1 -1
  15. package/dist/components/FeaturePlaceholder.d.ts +3 -3
  16. package/dist/components/LoginModal.js +1 -1
  17. package/dist/components/MultipleAuthProviders.js +1 -1
  18. package/dist/constants.d.ts +9 -0
  19. package/dist/constants.d.ts.map +1 -1
  20. package/dist/emailAuth/fields.d.ts +65 -2
  21. package/dist/emailAuth/fields.d.ts.map +1 -1
  22. package/dist/emailAuth/fields.js +1 -1
  23. package/dist/emailAuth/flows.d.ts +182 -15
  24. package/dist/emailAuth/flows.d.ts.map +1 -1
  25. package/dist/emailAuth/flows.js +1 -1
  26. package/dist/emailAuth/rules.d.ts +33 -4
  27. package/dist/emailAuth/rules.d.ts.map +1 -1
  28. package/dist/emailAuth/rules.js +2 -2
  29. package/dist/hooks/useAuthMethodToggle.js +1 -1
  30. package/dist/hooks/useAuthPartner.js +1 -1
  31. package/dist/hooks/useAuthUsers.d.ts +34 -0
  32. package/dist/hooks/useAuthUsers.d.ts.map +1 -0
  33. package/dist/hooks/useAuthUsers.js +1 -0
  34. package/dist/hooks/useDeleteAccount.js +1 -1
  35. package/dist/hooks/useEmailLinkForm.js +1 -1
  36. package/dist/hooks/useGoogleOneTap.js +1 -1
  37. package/dist/index.d.ts +9 -5
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +1 -1
  40. package/dist/symbol-index.json +1 -1
  41. package/dist/tsconfig.tsbuildinfo +1 -1
  42. package/dist/useAuth.d.ts.map +1 -1
  43. package/dist/useAuth.js +1 -1
  44. package/guidelines/AUTH.md +66 -0
  45. package/package.json +5 -5
@@ -1,5 +1,6 @@
1
1
  import type { FormEvent } from 'react';
2
- import type { SignUpMetadata } from '@donotdev/core';
2
+ import type { AuthUser, SignUpMetadata } from '@donotdev/core';
3
+ import type { AuthT } from './rules';
3
4
  /** Field names the flows read from the submitted form. */
4
5
  export declare const AUTH_FIELD: {
5
6
  readonly EMAIL: "email";
@@ -7,6 +8,7 @@ export declare const AUTH_FIELD: {
7
8
  readonly CONFIRM_PASSWORD: "confirmPassword";
8
9
  readonly REMEMBER_ME: "rememberMe";
9
10
  readonly CONSENT: "consent";
11
+ readonly DISPLAY_NAME: "displayName";
10
12
  };
11
13
  /** Which flow a form runs. */
12
14
  export type EmailAuthMode = 'signin' | 'signup' | 'reset';
@@ -29,14 +31,40 @@ export interface EmailAuthFlowOptions {
29
31
  */
30
32
  captchaToken?: string | null;
31
33
  }
34
+ /** Options of {@link useEmailSignIn}. */
35
+ export interface EmailSignInOptions extends EmailAuthFlowOptions {
36
+ /**
37
+ * How a sign-in of an unconfirmed address ends (default `'toast'`).
38
+ * - `'toast'`: the form error, with a "Resend verification email" action.
39
+ * - `'code'`: the flow sends a fresh code (`sendEmailVerification`) and calls
40
+ * `onCodeSent`; the app shows the code step (`AuthCodeStep`). A rate-limited
41
+ * resend still calls `onCodeSent` (the code already sent stays valid); other
42
+ * resend errors are the form error.
43
+ */
44
+ confirmation?: EmailSignUpConfirmation;
45
+ /** Code mode: a fresh code was sent to this unconfirmed address; show the code step */
46
+ onCodeSent?: (email: string) => void;
47
+ }
32
48
  /** Outcome of a successful sign-up. */
33
49
  export interface EmailSignUpOutcome {
34
50
  /**
35
- * The address must be confirmed before the user can sign in (no session yet). The
36
- * flow already showed the "check your email" toast with Resend.
51
+ * The address must be confirmed before the user can sign in (no session yet).
52
+ * Toast mode: the flow already showed the "check your email" toast with Resend.
53
+ * Code mode: show the code step for `email`.
37
54
  */
38
55
  awaitingConfirmation: boolean;
56
+ /** The address that signed up (trimmed), e.g. for the code step */
57
+ email: string;
39
58
  }
59
+ /**
60
+ * How a sign-up that needs confirmation ends.
61
+ * - `'toast'`: a toast that stays until dismissed says to open the confirmation
62
+ * email, with Resend (the link in the email confirms).
63
+ * - `'code'`: no toast; the app shows the code step (`useEmailCodeConfirmation`).
64
+ * Needs a provider that implements `verifyEmailCode` (Supabase) and an email
65
+ * template that sends the code.
66
+ */
67
+ export type EmailSignUpConfirmation = 'toast' | 'code';
40
68
  /** Options of {@link useEmailSignUp}. */
41
69
  export interface EmailSignUpOptions extends Omit<EmailAuthFlowOptions, 'onSuccess'> {
42
70
  /** Called once sign-up succeeded: close the dialog / sheet here */
@@ -50,6 +78,20 @@ export interface EmailSignUpOptions extends Omit<EmailAuthFlowOptions, 'onSucces
50
78
  title: string;
51
79
  description?: string;
52
80
  };
81
+ /**
82
+ * How a sign-up that needs confirmation ends (default `'toast'`, see
83
+ * {@link EmailSignUpConfirmation}). Code mode, existing address: the provider sends
84
+ * no confirmation code, so the flow sends a password-reset email instead
85
+ * (fire-and-forget; the app words that template to cover "you already have an
86
+ * account"). Its failure is logged, never shown, never changes the outcome.
87
+ */
88
+ confirmation?: EmailSignUpConfirmation;
89
+ /**
90
+ * Apply the character-class rules to the new password (uppercase, lowercase, digit,
91
+ * special; default `true`). `false`: only the minimum length applies; the
92
+ * breached-password check stays.
93
+ */
94
+ passwordComposition?: boolean;
53
95
  }
54
96
  /** What a form needs from a flow: pass it to `AuthForm`. */
55
97
  export interface EmailAuthFlow {
@@ -75,12 +117,27 @@ export interface EmailAuthFlow {
75
117
  resendVerification: (email: string) => Promise<void>;
76
118
  /** Minimum new-password length (sign-up) */
77
119
  passwordMinLength: number;
120
+ /**
121
+ * The character-class rules apply to the new password (sign-up). Absent = `true`.
122
+ * `AuthPasswordField` shows the requirements checklist only then.
123
+ */
124
+ passwordComposition?: boolean;
78
125
  }
126
+ /**
127
+ * The email check of every flow: the translated "required" / "invalid" message, or
128
+ * `undefined` when `email` (already trimmed) is valid.
129
+ *
130
+ * @param t - Translate function of the `auth` namespace
131
+ * @param email - The trimmed address
132
+ * @returns The error message, or `undefined`
133
+ */
134
+ export declare const validateEmail: (t: AuthT, email: string) => string | undefined;
79
135
  /**
80
136
  * Email + password sign-in. Remember me is applied when the form renders
81
- * `AuthRememberMeField`; an unconfirmed address offers a resend.
137
+ * `AuthRememberMeField`. An unconfirmed address offers a resend, or with
138
+ * `confirmation: 'code'` gets a fresh code and `onCodeSent(email)` (show `AuthCodeStep`).
82
139
  *
83
- * @param options - Callbacks and CAPTCHA token
140
+ * @param options - Callbacks, CAPTCHA token, confirmation mode
84
141
  * @returns The flow, for `AuthForm`
85
142
  *
86
143
  * @example
@@ -95,26 +152,136 @@ export interface EmailAuthFlow {
95
152
  * </AuthForm>
96
153
  * ```
97
154
  */
98
- export declare function useEmailSignIn(options?: EmailAuthFlowOptions): EmailAuthFlow;
155
+ export declare function useEmailSignIn(options?: EmailSignInOptions): EmailAuthFlow;
99
156
  /**
100
- * Email + password sign-up. Password policy and breached-password check apply; the
101
- * confirmation field and consent are required when the form renders them.
157
+ * Email + password sign-up. Password policy (`passwordComposition: false` = length
158
+ * only) and breached-password check apply; the confirmation field and consent are
159
+ * required when the form renders them. `AuthNameField`, when rendered and filled, is
160
+ * stored trimmed as the user's display name (metadata `full_name`); never required.
102
161
  *
103
162
  * Anti-enumeration: an address that already has an account ends exactly like a new
104
- * one ("check your email"). When the provider asks for confirmation, `onSuccess` runs
105
- * and a toast that stays until dismissed tells the user to confirm, with Resend.
163
+ * one (`awaitingConfirmation: true`). When the provider asks for confirmation,
164
+ * `onSuccess` runs and then:
165
+ * - `confirmation: 'toast'` (default): a toast that stays until dismissed tells the
166
+ * user to confirm, with Resend;
167
+ * - `confirmation: 'code'`: nothing more; the app shows the code step for
168
+ * `outcome.email`. For an existing address the flow sends a password-reset
169
+ * email (`sendPasswordResetEmail`), fire-and-forget: a failure goes to
170
+ * `console.error`, never to the screen.
171
+ * A project that does not require confirmation signs the user in at once:
172
+ * `awaitingConfirmation: false`.
106
173
  *
107
- * @param options - Callbacks, CAPTCHA token, password minimum, extra metadata
174
+ * @param options - Callbacks, CAPTCHA token, password policy, extra metadata,
175
+ * confirmation mode
108
176
  * @returns The flow, for `AuthForm`
177
+ *
178
+ * @example
179
+ * ```tsx
180
+ * const [email, setEmail] = useState<string | null>(null);
181
+ * const flow = useEmailSignUp({
182
+ * confirmation: 'code',
183
+ * onSuccess: (outcome) => {
184
+ * if (outcome.awaitingConfirmation) setEmail(outcome.email);
185
+ * else close();
186
+ * },
187
+ * });
188
+ * ```
109
189
  */
110
190
  export declare function useEmailSignUp(options?: EmailSignUpOptions): EmailAuthFlow;
191
+ /** Options of {@link usePasswordResetRequest}. */
192
+ export interface PasswordResetRequestOptions extends EmailAuthFlowOptions {
193
+ /**
194
+ * Confirm with a toast that stays until dismissed (default `true`). `false`: no
195
+ * toast; render the "check your inbox" message inline from `flow.sent`.
196
+ * @default true
197
+ */
198
+ toast?: boolean;
199
+ }
200
+ /** The password-reset request flow: an {@link EmailAuthFlow} plus `sent`. */
201
+ export interface PasswordResetRequestFlow extends EmailAuthFlow {
202
+ /** The request went through (any address): `true` until the next submit */
203
+ sent: boolean;
204
+ }
111
205
  /**
112
206
  * Password-reset request. Anti-enumeration: the same outcome whether or not the address
113
- * has an account; `onSuccess` runs and a toast that stays until dismissed says to check
114
- * the inbox.
207
+ * has an account; `sent` turns `true`, `onSuccess` runs and a toast that stays until
208
+ * dismissed says to check the inbox (`toast: false`: no toast, the app shows the
209
+ * message inline from `sent`).
115
210
  *
116
- * @param options - Callbacks and CAPTCHA token
211
+ * @param options - Callbacks, CAPTCHA token, toast opt-out
117
212
  * @returns The flow, for `AuthForm`
118
213
  */
119
- export declare function usePasswordResetRequest(options?: EmailAuthFlowOptions): EmailAuthFlow;
214
+ export declare function usePasswordResetRequest(options?: PasswordResetRequestOptions): PasswordResetRequestFlow;
215
+ /** Options of {@link useEmailCodeConfirmation}. */
216
+ export interface EmailCodeConfirmationOptions {
217
+ /** The address that signed up (`EmailSignUpOutcome.email`) */
218
+ email: string;
219
+ /**
220
+ * Characters of the emailed code: match the provider (Supabase:
221
+ * `mailer_otp_length`).
222
+ * @default 6
223
+ */
224
+ length?: number;
225
+ /**
226
+ * Seconds before the code can be sent again. The countdown starts at mount: the
227
+ * sign-up just sent a code.
228
+ * @default 60
229
+ */
230
+ resendCooldownSeconds?: number;
231
+ /** Called with the signed-in user once the code is confirmed: close the sheet here */
232
+ onSuccess?: (user: AuthUser) => void;
233
+ /** Called with the provider error after a failed confirmation or resend */
234
+ onError?: (error: Error) => void;
235
+ }
236
+ /** What the code step needs from {@link useEmailCodeConfirmation}: pass it to `AuthCodeField`. */
237
+ export interface EmailCodeConfirmation {
238
+ /** The address the code was sent to */
239
+ email: string;
240
+ /** Characters of the code */
241
+ length: number;
242
+ /** The code typed so far */
243
+ code: string;
244
+ /** Update the typed code */
245
+ setCode: (code: string) => void;
246
+ /**
247
+ * Confirm the code (`code` by default; pass the value when it is not in state yet,
248
+ * e.g. from `onComplete`). A wrong or expired code clears the typed code.
249
+ */
250
+ submit: (code?: string) => Promise<void>;
251
+ /** A confirmation is in progress */
252
+ busy: boolean;
253
+ /** Translated message of the last failure (wrong / expired code, throttle, failed resend...), or `null` */
254
+ error: string | null;
255
+ /**
256
+ * Send a new code (no-op while `resendIn > 0`) and restart the countdown. No toast:
257
+ * success sets `resent`, a failure sets `error`.
258
+ */
259
+ resend: () => Promise<void>;
260
+ /** A new code was sent: `true` after a successful resend until the next submit or resend */
261
+ resent: boolean;
262
+ /** A resend is in progress */
263
+ resending: boolean;
264
+ /** Seconds left before `resend` is allowed (0 = allowed) */
265
+ resendIn: number;
266
+ /** The provider is ready (confirm and resend wait for it) */
267
+ ready: boolean;
268
+ }
269
+ /**
270
+ * The code step of a sign-up made with `useEmailSignUp({ confirmation: 'code' })`:
271
+ * the user types the emailed code, `useAuth('verifyEmailCode')` confirms it and signs
272
+ * the user in. Same client throttle as the email flows; wrong / expired code and rate
273
+ * limits get translated messages. Resend sends a new code with
274
+ * `useAuth('sendEmailVerification')` once the countdown is over. No toast: the
275
+ * outcome is state (`error`, `resent`) that `AuthCodeField` renders inline.
276
+ *
277
+ * @param options - Address, code length, resend cooldown, callbacks
278
+ * @returns The code step state, for `AuthCodeField`
279
+ *
280
+ * @example
281
+ * ```tsx
282
+ * const confirmation = useEmailCodeConfirmation({ email, length: 8, onSuccess: close });
283
+ * <AuthCodeField confirmation={confirmation} />
284
+ * ```
285
+ */
286
+ export declare function useEmailCodeConfirmation(options: EmailCodeConfirmationOptions): EmailCodeConfirmation;
120
287
  //# sourceMappingURL=flows.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/emailAuth/flows.tsx"],"names":[],"mappings":"AA0BA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGvC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAgBrD,0DAA0D;AAC1D,eAAO,MAAM,UAAU;;;;;;CAMb,CAAC;AAEX,8BAA8B;AAC9B,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAC;AAE1D,0DAA0D;AAC1D,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,oCAAoC;AACpC,MAAM,WAAW,oBAAoB;IACnC,oEAAoE;IACpE,SAAS,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AM,CAAC;IAC/B,sFAAsF;IACtF,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,KAAK,IAAI,CAAC;IACrC,2EAA2E;IAC3E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAED,kGAAkG;AAClG,MAAM,WAAW,qBAAqB;IACpC,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,6BAA6B;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC;;;OAGG;IACH,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,oCAAoC;IACpC,IAAI,EAAE,OAAO,CAAC;IACd,2GAA2G;IAC3G,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB;;;OAGG;IACH,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,4FAA4F;IAC5F,MAAM,EAAE,OAAO,CAAC;IAChB,8BAA8B;IAC9B,SAAS,EAAE,OAAO,CAAC;IACnB,4DAA4D;IAC5D,QAAQ,EAAE,MAAM,CAAC;IACjB,6DAA6D;IAC7D,KAAK,EAAE,OAAO,CAAC;CAChB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,4BAA4B,GACpC,qBAAqB,CA8FvB"}
@@ -1 +1 @@
1
- "use client";import{jsx as C}from"react/jsx-runtime";import{useEffect as F,useRef as V,useState as g}from"react";import{Button as q,ToastAction as x,toast as R}from"@donotdev/components";import{useTranslation as U}from"@donotdev/core";import{useAuth as E}from"../useAuth";import{DEFAULT_PASSWORD_MIN_LENGTH as O,authErrorMessage as W,isAlreadyRegisteredError as j,isBreachedPassword as B,isEmail as H,isRateLimitError as G,isUnconfirmedError as $,newPasswordError as z}from"./rules";const a={EMAIL:"email",PASSWORD:"password",CONFIRM_PASSWORD:"confirmPassword",REMEMBER_ME:"rememberMe",CONSENT:"consent"},J=6e4,K=5,Q=3e4;function X(){const e=V([]),[t,r]=g(null);return F(()=>{if(t===null)return;const s=setTimeout(()=>r(null),Math.max(0,t-Date.now()));return()=>clearTimeout(s)},[t]),{attempt:()=>{const s=Date.now();return t!==null&&s<t?Math.ceil((t-s)/1e3):(e.current=e.current.filter(u=>s-u<J),e.current.push(s),e.current.length>=K&&(e.current=[],r(s+Q)),0)},throttled:t!==null}}const Y=e=>e instanceof Error?e:new Error(String(e)),l=(e,t)=>{const r=e.get(t);return typeof r=="string"?r:""},T=(e,t)=>{const r=e.elements.namedItem(t);return r instanceof HTMLInputElement?r:void 0};function Z(){const{t:e}=U("auth");return(t,r,s)=>e(t,{defaultValue:r,...s})}function b(e,t){const r=Z(),s=E("isAvailable"),u=E("status"),m=E("sendEmailVerification"),f=X(),[c,o]=g(!1),[n,i]=g(null),[d,h]=g({}),[w,S]=g(null),v=t.captchaToken!==void 0&&!t.captchaToken,L=async p=>{try{await m(p),R("success",r("verificationSent","Verification email sent."))}catch(M){R("error",W(M,r))}};return{t:r,submit:async(p,M,N)=>{if(p.preventDefault(),c||v||!s)return;const P=p.currentTarget,A=new FormData(P),k=M(P,A);if(h(k),S(null),Object.keys(k).length>0){i(null);return}const I=f.attempt();if(I>0){i(r("errors.rate_limit_cooldown",`Too many attempts. Please wait ${I} seconds.`,{seconds:I}));return}i(null),o(!0);try{await N(P,A)}catch(y){e==="signin"&&$(y)&&S(l(A,a.EMAIL).trim()),i(W(y,r)),t.onError?.(Y(y))}finally{o(!1)}},flow:(p,M)=>({mode:e,onSubmit:p,busy:c,ready:s,unavailable:u==="degraded"||u==="error",blocked:v||f.throttled,error:n,fieldErrors:d,unconfirmedEmail:w,resendVerification:L,passwordMinLength:M}),resendVerification:L,setFieldErrors:h}}const _=(e,t)=>{if(t==="")return e("emailRequired","Email is required");if(!H(t))return e("emailInvalid","Invalid email address")},D=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));function ee(e={}){const t=b("signin",e),{t:r}=t,s=E("signInWithEmail"),u=E("setRememberMe"),m=E("canRememberMe"),f=c=>{t.submit(c,(o,n)=>D({email:_(r,l(n,a.EMAIL).trim()),password:l(n,a.PASSWORD)===""?r("passwordRequired","Password is required"):void 0}),async(o,n)=>{const i=T(o,a.REMEMBER_ME);i&&m()&&await u(i.checked);const d=await s(l(n,a.EMAIL).trim(),l(n,a.PASSWORD));if(!d?.success)throw new Error(d?.error??"Sign in failed");e.onSuccess?.()})};return t.flow(f,O)}function te(e={}){const t=b("signup",e),{t:r}=t,s=E("createUserWithEmail"),u=e.passwordMinLength??O,m=c=>{R({title:e.checkEmailMessage?.title??r("signup.success_title","Check your email"),description:e.checkEmailMessage?.description??r("signup.check_email","If an account was created, you will receive a confirmation email. Check your inbox and spam folder."),toastType:"success",duration:0,action:C(x,{asChild:!0,altText:r("resendEmail","Resend email"),children:C(q,{onClick:()=>{t.resendVerification(c)},children:r("resendEmail","Resend email")})})})},f=c=>{t.submit(c,(o,n)=>{const i=l(n,a.PASSWORD),d=o.elements.namedItem(a.CONFIRM_PASSWORD),h=T(o,a.CONSENT);return D({email:_(r,l(n,a.EMAIL).trim()),password:z(i,u,r)??void 0,confirmPassword:d&&l(n,a.CONFIRM_PASSWORD)!==i?r("confirmPasswordMismatch","Passwords do not match"):void 0,consent:h&&!h.checked?r("terms.required","Please accept the terms to continue"):void 0})},async(o,n)=>{const i=l(n,a.EMAIL).trim(),d=l(n,a.PASSWORD);if(await B(d)){t.setFieldErrors({password:r("errors.breached_password","This password has appeared in a data breach. Please choose a different password.")});return}const h=T(o,a.CONSENT)?.checked?{...e.metadata,gdpr_consent_at:new Date().toISOString()}:e.metadata;try{const w=await s(i,d,h);if(!w?.success)throw new Error(w?.error??"Sign up failed");const S=!w.user?.emailVerified;e.onSuccess?.({awaitingConfirmation:S}),S&&m(i)}catch(w){if(!j(w))throw w;e.onSuccess?.({awaitingConfirmation:!0}),m(i)}})};return t.flow(f,u)}function re(e={}){const t=b("reset",e),{t:r}=t,s=E("sendPasswordResetEmail"),u=m=>{t.submit(m,(f,c)=>D({email:_(r,l(c,a.EMAIL).trim())}),async(f,c)=>{try{await s(l(c,a.EMAIL).trim())}catch(o){if(G(o))throw o}e.onSuccess?.(),R({title:r("forgotPassword.sent","Password reset email sent"),description:r("forgotPassword.check_email_safe","If an account exists with this email, you will receive password reset instructions."),toastType:"success",duration:0})})};return t.flow(u,O)}export{a as AUTH_FIELD,ee as useEmailSignIn,te as useEmailSignUp,re as usePasswordResetRequest};
1
+ "use client";import{jsx as F}from"react/jsx-runtime";import{useEffect as U,useRef as V,useState as A}from"react";import{Button as G,ToastAction as K,toast as C}from"@donotdev/components";import{useTranslation as X}from"@donotdev/core";import{useAuth as S}from"../useAuth";import{DEFAULT_CONFIRMATION_CODE_LENGTH as z,DEFAULT_PASSWORD_MIN_LENGTH as L,DEFAULT_RESEND_COOLDOWN_SECONDS as J,authErrorMessage as q,codeErrorMessage as B,isAlreadyRegisteredError as Q,isBreachedPassword as Z,isEmail as ee,isRateLimitError as j,isUnconfirmedError as H,newPasswordError as te}from"./rules";const c={EMAIL:"email",PASSWORD:"password",CONFIRM_PASSWORD:"confirmPassword",REMEMBER_ME:"rememberMe",CONSENT:"consent",DISPLAY_NAME:"displayName"},re="full_name",ne=6e4,se=5,ie=3e4;function Y(){const e=V([]),[t,r]=A(null);return U(()=>{if(t===null)return;const n=setTimeout(()=>r(null),Math.max(0,t-Date.now()));return()=>clearTimeout(n)},[t]),{attempt:()=>{const n=Date.now();return t!==null&&n<t?Math.ceil((t-n)/1e3):(e.current=e.current.filter(E=>n-E<ne),e.current.push(n),e.current.length>=se&&(e.current=[],r(n+ie)),0)},throttled:t!==null}}const N=e=>e instanceof Error?e:new Error(String(e)),_=(e,t)=>{const r=e.get(t);return typeof r=="string"?r:""},v=(e,t)=>{const r=e.elements.namedItem(t);return r instanceof HTMLInputElement?r:void 0};function $(){const{t:e}=X("auth");return(t,r,f)=>e(t,{defaultValue:r,...f})}function W(e,t){const r=$(),f=S("isAvailable"),n=S("status"),E=S("sendEmailVerification"),u=Y(),[g,y]=A(!1),[m,i]=A(null),[w,l]=A({}),[s,o]=A(null),d=t.captchaToken!==void 0&&!t.captchaToken,h=async a=>{try{await E(a),C("success",r("verificationSent","Verification email sent."))}catch(M){C("error",q(M,r))}};return{t:r,submit:async(a,M,P)=>{if(a.preventDefault(),g||d||!f)return;const b=a.currentTarget,R=new FormData(b),p=M(b,R);if(l(p),o(null),Object.keys(p).length>0){i(null);return}const O=u.attempt();if(O>0){i(r("errors.rate_limit_cooldown",`Too many attempts. Please wait ${O} seconds.`,{seconds:O}));return}i(null),y(!0);try{await P(b,R)}catch(T){e==="signin"&&H(T)&&o(_(R,c.EMAIL).trim()),i(q(T,r)),t.onError?.(N(T))}finally{y(!1)}},flow:(a,M,P)=>({mode:e,onSubmit:a,busy:g,ready:f,unavailable:n==="degraded"||n==="error",blocked:d||u.throttled,error:m,fieldErrors:w,unconfirmedEmail:s,resendVerification:h,passwordMinLength:M,...P===void 0?{}:{passwordComposition:P}}),resendVerification:h,setFieldErrors:l}}const x=(e,t)=>{if(t==="")return e("emailRequired","Email is required");if(!ee(t))return e("emailInvalid","Invalid email address")},k=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));function de(e={}){const t=W("signin",e),{t:r}=t,f=S("signInWithEmail"),n=S("sendEmailVerification"),E=S("setRememberMe"),u=S("canRememberMe"),g=y=>{t.submit(y,(m,i)=>k({email:x(r,_(i,c.EMAIL).trim()),password:_(i,c.PASSWORD)===""?r("passwordRequired","Password is required"):void 0}),async(m,i)=>{const w=v(m,c.REMEMBER_ME);w&&u()&&await E(w.checked);const l=_(i,c.EMAIL).trim();try{const s=await f(l,_(i,c.PASSWORD));if(!s?.success)throw new Error(s?.error??"Sign in failed")}catch(s){if(e.confirmation!=="code"||!H(s))throw s;try{await n(l)}catch(o){if(!j(o))throw o}e.onCodeSent?.(l);return}e.onSuccess?.()})};return t.flow(g,L)}function fe(e={}){const t=W("signup",e),{t:r}=t,f=S("createUserWithEmail"),n=S("sendPasswordResetEmail"),E=e.passwordMinLength??L,u=e.confirmation??"toast",g=e.passwordComposition??!0,y=w=>{(async()=>{try{await n(w)}catch{}})()},m=w=>{C({title:e.checkEmailMessage?.title??r("signup.success_title","Check your email"),description:e.checkEmailMessage?.description??r("signup.check_email","If an account was created, you will receive a confirmation email. Check your inbox and spam folder."),toastType:"success",duration:0,action:F(K,{asChild:!0,altText:r("resendEmail","Resend email"),children:F(G,{onClick:()=>{t.resendVerification(w)},children:r("resendEmail","Resend email")})})})},i=w=>{t.submit(w,(l,s)=>{const o=_(s,c.PASSWORD),d=l.elements.namedItem(c.CONFIRM_PASSWORD),h=v(l,c.CONSENT);return k({email:x(r,_(s,c.EMAIL).trim()),password:te(o,E,r,g)??void 0,confirmPassword:d&&_(s,c.CONFIRM_PASSWORD)!==o?r("confirmPasswordMismatch","Passwords do not match"):void 0,consent:h&&!h.checked?r("terms.required","Please accept the terms to continue"):void 0})},async(l,s)=>{const o=_(s,c.EMAIL).trim(),d=_(s,c.PASSWORD);if(await Z(d)){t.setFieldErrors({password:r("errors.breached_password","This password has appeared in a data breach. Please choose a different password.")});return}const h=v(l,c.CONSENT),I=_(s,c.DISPLAY_NAME).trim(),D=h?.checked||I?{...e.metadata,...h?.checked?{gdpr_consent_at:new Date().toISOString()}:{},...I?{[re]:I}:{}}:e.metadata;try{const a=await f(o,d,D);if(!a?.success)throw new Error(a?.error??"Sign up failed");const M=!a.user?.emailVerified;e.onSuccess?.({awaitingConfirmation:M,email:o}),M&&u==="toast"&&m(o)}catch(a){if(!Q(a))throw a;e.onSuccess?.({awaitingConfirmation:!0,email:o}),u==="toast"?m(o):y(o)}})};return t.flow(i,E,e.passwordComposition)}function Ee(e={}){const t=W("reset",e),{t:r}=t,f=S("sendPasswordResetEmail"),[n,E]=A(!1),u=g=>{E(!1),t.submit(g,(y,m)=>k({email:x(r,_(m,c.EMAIL).trim())}),async(y,m)=>{try{await f(_(m,c.EMAIL).trim())}catch(i){if(j(i))throw i}E(!0),e.onSuccess?.(),e.toast!==!1&&C({title:r("forgotPassword.sent","Password reset email sent"),description:r("forgotPassword.check_email_safe","If an account exists with this email, you will receive password reset instructions."),toastType:"success",duration:0})})};return{...t.flow(u,L),sent:n}}function we(e){const t=$(),r=S("isAvailable"),f=S("verifyEmailCode"),n=S("sendEmailVerification"),E=Y(),u=e.length??z,g=e.resendCooldownSeconds??J,[y,m]=A(""),[i,w]=A(!1),[l,s]=A(!1),[o,d]=A(null),[h,I]=A(g),[D,a]=A(!1),M=V(!1);U(()=>{if(h<=0)return;const R=setTimeout(()=>I(p=>Math.max(0,p-1)),1e3);return()=>clearTimeout(R)},[h]);const P=async R=>{const p=(R??y).trim();if(M.current||!r)return;if(a(!1),p.length!==u){d(t("codeConfirmation.incomplete",`Enter the ${u}-digit code.`,{length:u}));return}const O=E.attempt();if(O>0){d(t("errors.rate_limit_cooldown",`Too many attempts. Please wait ${O} seconds.`,{seconds:O}));return}M.current=!0,d(null),w(!0);try{const T=await f(e.email,p);e.onSuccess?.(T)}catch(T){d(B(T,t)),m(""),e.onError?.(N(T))}finally{M.current=!1,w(!1)}},b=async()=>{if(!(h>0||l||!r)){s(!0),a(!1),d(null);try{await n(e.email),I(g),a(!0)}catch(R){d(B(R,t)),e.onError?.(N(R))}finally{s(!1)}}};return{email:e.email,length:u,code:y,setCode:m,submit:P,busy:i,error:o,resend:b,resending:l,resent:D,resendIn:h,ready:r}}export{c as AUTH_FIELD,we as useEmailCodeConfirmation,de as useEmailSignIn,fe as useEmailSignUp,Ee as usePasswordResetRequest,x as validateEmail};
@@ -2,7 +2,11 @@
2
2
  * @fileoverview Email auth rules
3
3
  * @description The rules every email/password flow shares, framework form or app form:
4
4
  * provider error -> user message, email format, new-password policy, breached-password
5
- * check (HaveIBeenPwned k-anonymity, NIST 800-63B).
5
+ * check (HaveIBeenPwned k-anonymity, NIST 800-63B), confirmation-code errors.
6
+ *
7
+ * Provider errors are recognised by their structured code first (the error's `code`,
8
+ * or the provider code `wrapAuthError` keeps in `details.originalCode`), then by
9
+ * their message.
6
10
  *
7
11
  * @version 0.1.0
8
12
  * @since 0.2.3
@@ -18,15 +22,40 @@ export declare function isEmail(email: string): boolean;
18
22
  export declare function isRateLimitError(error: unknown): boolean;
19
23
  /** Provider error: the address exists but was never confirmed. */
20
24
  export declare function isUnconfirmedError(error: unknown): boolean;
21
- /** Provider error: sign-up with an address that already has an account. */
25
+ /**
26
+ * Provider error: sign-up with an address that already has an account. Structured
27
+ * code first, message as the fallback (Supabase with confirmations on reports it as
28
+ * a fake user, which the provider turns into an "already exists" message).
29
+ */
22
30
  export declare function isAlreadyRegisteredError(error: unknown): boolean;
23
31
  /** User-facing message for a provider error (rate limit, credentials, network...). */
24
32
  export declare function authErrorMessage(error: unknown, t: AuthT): string;
33
+ /** Default number of characters of an emailed confirmation code. */
34
+ export declare const DEFAULT_CONFIRMATION_CODE_LENGTH = 6;
35
+ /** Default seconds before a confirmation code can be sent again. */
36
+ export declare const DEFAULT_RESEND_COOLDOWN_SECONDS = 60;
37
+ /** Provider error: the confirmation code is known to have expired. */
38
+ export declare function isCodeExpiredError(error: unknown): boolean;
39
+ /** Provider error: the confirmation code is wrong (or wrong or expired, see `otp_expired`). */
40
+ export declare function isInvalidCodeError(error: unknown): boolean;
41
+ /**
42
+ * User-facing message for a failed code confirmation or code resend: expired code,
43
+ * wrong code, rate limit (structured codes included), else `authErrorMessage`.
44
+ */
45
+ export declare function codeErrorMessage(error: unknown, t: AuthT): string;
25
46
  /**
26
47
  * First rule a new password breaks, or `null`. Policy: minimum length (8 by default),
27
- * one uppercase letter, one lowercase letter, one digit, one special character.
48
+ * then, unless `composition` is `false`, one uppercase letter, one lowercase letter,
49
+ * one digit, one special character.
50
+ *
51
+ * @param password - The new password
52
+ * @param minLength - Minimum length
53
+ * @param t - Translate function of the `auth` namespace
54
+ * @param composition - Apply the character-class rules (default `true`); `false` keeps
55
+ * only the empty check and the minimum length (NIST 800-63B: length over composition)
56
+ * @returns The message of the first broken rule, or `null`
28
57
  */
29
- export declare function newPasswordError(password: string, minLength: number, t: AuthT): string | null;
58
+ export declare function newPasswordError(password: string, minLength: number, t: AuthT, composition?: boolean): string | null;
30
59
  /**
31
60
  * Whether the password appears in a known breach (HaveIBeenPwned range API: only the
32
61
  * first 5 hex chars of the SHA-1 leave the browser). Fails open: an unreachable API
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../src/emailAuth/rules.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,iFAAiF;AACjF,MAAM,MAAM,KAAK,GAAG,CAClB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,MAAM,CAAC;AAEZ,gDAAgD;AAChD,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAI7C,+EAA+E;AAC/E,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE9C;AAKD,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAOxD;AAED,kEAAkE;AAClE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAO1D;AAED,2EAA2E;AAC3E,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAQhE;AA8CD,sFAAsF;AACtF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAMjE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,C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,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAiBjE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,CAAC,EAAE,KAAK,EACR,WAAW,UAAO,GACjB,MAAM,GAAG,IAAI,CAmCf;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAsB3E"}
@@ -1,2 +1,2 @@
1
- const l=8,d=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function u(e){return d.test(e)}const r=e=>(e instanceof Error?e.message:String(e)).toLowerCase();function o(e){const s=r(e);return s.includes("429")||s.includes("rate")||s.includes("too_many_requests")}function w(e){const s=r(e);return s.includes("email_not_confirmed")||s.includes("email not confirmed")||s.includes("auth/unverified-email")}function m(e){const s=r(e);return s.includes("already")||s.includes("exists")||s.includes("user_already_exists")||s.includes("auth/email-already-in-use")}const f=[{test:o,key:"errors.rate_limit",fallback:"Too many attempts. Please wait a moment and try again."},{test:e=>e.includes("email_not_confirmed")||e.includes("email not confirmed")||e.includes("auth/unverified-email"),key:"errors.email_not_confirmed",fallback:"Please verify your email before signing in."},{test:e=>e.includes("invalid_credentials")||e.includes("invalid login credentials")||e.includes("invalid-credential")||e.includes("auth/wrong-password")||e.includes("auth/user-not-found")||e.includes("invalid")&&e.includes("credential"),key:"errors.invalid_credentials",fallback:"Invalid email or password."},{test:e=>e.includes("weak_password")||e.includes("weak password")||e.includes("auth/weak-password"),key:"errors.weak_password",fallback:"Password is too weak. Please choose a stronger password."},{test:e=>e.includes("network")||e.includes("fetch"),key:"networkError",fallback:"Network error. Please check your connection and try again."}];function p(e,s){const a=r(e);for(const t of f)if(t.test(a))return s(t.key,t.fallback);return s("errorGeneric","Authentication failed. Please try again.")}function y(e,s,a){return e===""?a("passwordRequired","Password is required"):e.length<s?a("passwordMinLength",`Password must be at least ${s} characters`,{count:s}):/[A-Z]/.test(e)?/[a-z]/.test(e)?/[0-9]/.test(e)?/[^a-zA-Z0-9]/.test(e)?null:a("passwordRequirement.special","Password must contain at least one special character"):a("passwordRequirement.number","Password must contain at least one number"):a("passwordRequirement.lowercase","Password must contain at least one lowercase letter"):a("passwordRequirement.uppercase","Password must contain at least one uppercase letter")}async function k(e){try{const s=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(e)),a=Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("").toUpperCase(),t=a.slice(0,5),c=a.slice(5),i=await fetch(`https://api.pwnedpasswords.com/range/${t}`,{headers:{"Add-Padding":"true"},credentials:"omit"});return i.ok?(await i.text()).split(`
2
- `).some(n=>n.split(":")[0]?.trim()===c):!1}catch{return!1}}export{l as DEFAULT_PASSWORD_MIN_LENGTH,p as authErrorMessage,m as isAlreadyRegisteredError,k as isBreachedPassword,u as isEmail,o as isRateLimitError,w as isUnconfirmedError,y as newPasswordError};
1
+ const p=8,f=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function _(e){return f.test(e)}const a=e=>(e instanceof Error?e.message:String(e)).toLowerCase();function h(e){if(typeof e!="object"||e===null)return[];const s=[];if("code"in e&&typeof e.code=="string"&&s.push(e.code),"details"in e&&typeof e.details=="object"&&e.details){const t=e.details.originalCode;typeof t=="string"&&s.push(t)}return s}const i=(e,s)=>h(e).some(t=>s.has(t));function d(e){const s=a(e);return s.includes("429")||s.includes("rate")||s.includes("too_many_requests")}function y(e){const s=a(e);return s.includes("email_not_confirmed")||s.includes("email not confirmed")||s.includes("auth/unverified-email")}const k=new Set(["user_already_exists","email_exists","auth/email-already-in-use","already-exists"]);function g(e){if(i(e,k))return!0;const s=a(e);return s.includes("already")||s.includes("exists")||s.includes("user_already_exists")||s.includes("auth/email-already-in-use")}const E=[{test:d,key:"errors.rate_limit",fallback:"Too many attempts. Please wait a moment and try again."},{test:e=>e.includes("email_not_confirmed")||e.includes("email not confirmed")||e.includes("auth/unverified-email"),key:"errors.email_not_confirmed",fallback:"Please verify your email before signing in."},{test:e=>e.includes("invalid_credentials")||e.includes("invalid login credentials")||e.includes("invalid-credential")||e.includes("auth/wrong-password")||e.includes("auth/user-not-found")||e.includes("invalid")&&e.includes("credential"),key:"errors.invalid_credentials",fallback:"Invalid email or password."},{test:e=>e.includes("weak_password")||e.includes("weak password")||e.includes("auth/weak-password"),key:"errors.weak_password",fallback:"Password is too weak. Please choose a stronger password."},{test:e=>e.includes("network")||e.includes("fetch"),key:"networkError",fallback:"Network error. Please check your connection and try again."}];function c(e,s){const t=a(e);for(const r of E)if(r.test(t))return s(r.key,r.fallback);return s("errorGeneric","Authentication failed. Please try again.")}const v=6,x=60,P=new Set(["auth/expired-action-code"]),l=new Set(["otp_expired","auth/invalid-action-code","auth/invalid-verification-code"]),b=new Set(["over_request_rate_limit","over_email_send_rate_limit","auth/too-many-requests","rate-limit-exceeded"]);function u(e){if(i(e,P))return!0;if(i(e,l))return!1;const s=a(e);return s.includes("expired")&&!s.includes("invalid")}function m(e){if(i(e,l))return!0;const s=a(e);return s.includes("expired or is invalid")||s.includes("invalid")&&(s.includes("code")||s.includes("token")||s.includes("otp"))}function A(e,s){return u(e)?s("errors.code_expired","This code has expired. Request a new code."):m(e)?s("errors.invalid_code","This code is incorrect or has expired. Check the email or request a new code."):i(e,b)?s("errors.rate_limit","Too many attempts. Please wait a moment and try again."):c(e,s)}function S(e,s,t,r=!0){return e===""?t("passwordRequired","Password is required"):e.length<s?t("passwordMinLength",`Password must be at least ${s} characters`,{count:s}):r?/[A-Z]/.test(e)?/[a-z]/.test(e)?/[0-9]/.test(e)?/[^a-zA-Z0-9]/.test(e)?null:t("passwordRequirement.special","Password must contain at least one special character"):t("passwordRequirement.number","Password must contain at least one number"):t("passwordRequirement.lowercase","Password must contain at least one lowercase letter"):t("passwordRequirement.uppercase","Password must contain at least one uppercase letter"):null}async function R(e){try{const s=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(e)),t=Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("").toUpperCase(),r=t.slice(0,5),w=t.slice(5),o=await fetch(`https://api.pwnedpasswords.com/range/${r}`,{headers:{"Add-Padding":"true"},credentials:"omit"});return o.ok?(await o.text()).split(`
2
+ `).some(n=>n.split(":")[0]?.trim()===w):!1}catch{return!1}}export{v as DEFAULT_CONFIRMATION_CODE_LENGTH,p as DEFAULT_PASSWORD_MIN_LENGTH,x as DEFAULT_RESEND_COOLDOWN_SECONDS,c as authErrorMessage,A as codeErrorMessage,g as isAlreadyRegisteredError,R as isBreachedPassword,u as isCodeExpiredError,_ as isEmail,m as isInvalidCodeError,d as isRateLimitError,y as isUnconfirmedError,S as newPasswordError};
@@ -1 +1 @@
1
- "use client";import{useState as l,useCallback as t}from"react";function g({defaultValue:u="popup"}={}){const[o,e]=l(u),d=o==="redirect",r=o==="popup",i=t(()=>{e(p=>p==="redirect"?"popup":"redirect")},[]),s=t(()=>{e("redirect")},[]),a=t(()=>{e("popup")},[]),c=t(p=>{e(p?"redirect":"popup")},[]);return{isRedirectMode:d,isPopupMode:r,authMethod:o,toggleMode:i,setRedirectMode:s,setPopupMode:a,handleToggleChange:c}}export{g as useAuthMethodToggle};
1
+ "use client";import{useState as l,useCallback as t}from"react";function g({defaultValue:r="popup"}={}){const[o,e]=l(r),d=o==="redirect",u=o==="popup",i=t(()=>{e(p=>p==="redirect"?"popup":"redirect")},[]),s=t(()=>{e("redirect")},[]),a=t(()=>{e("popup")},[]),c=t(p=>{e(p?"redirect":"popup")},[]);return{isRedirectMode:d,isPopupMode:u,authMethod:o,toggleMode:i,setRedirectMode:s,setPopupMode:a,handleToggleChange:c}}export{g as useAuthMethodToggle};
@@ -1 +1 @@
1
- "use client";import{useCallback as a}from"react";import{useAuth as o}from"../useAuth";function w(t,g={}){const p=o("getPartnerState"),e=o("setPartnerState"),d=o("signInWithPartner"),i=o("partnerError"),{onSuccess:s,onError:l}=g,c=p(t),E=c==="authenticated",S=c==="loading",r=i?.partnerId===t,f=r&&i?.error?new Error(i.error):null,u=a(()=>{r&&e(t,"idle")},[r,t,e]),m=a(()=>{e(t,"loading")},[t,e]),A=a(()=>{e(t,"idle")},[t,e]),P=a(async I=>{r&&u();try{e(t,"loading");const n=await d(t,I);if(n===null){e(t,"idle");return}n&&s&&s(n)}catch(n){const h=n;e(t,"error",h),l&&l(h)}},[t,r,u,e,d,s,l]);return{partnerState:c,isAuthenticated:E,isAuthenticating:S,hasError:r,error:f,handleSignIn:P,clearError:u,setLoading:m,setIdle:A}}export{w as useAuthPartner};
1
+ "use client";import{useCallback as t}from"react";import{useAuth as o}from"../useAuth";function w(r,g={}){const p=o("getPartnerState"),e=o("setPartnerState"),d=o("signInWithPartner"),i=o("partnerError"),{onSuccess:s,onError:l}=g,c=p(r),E=c==="authenticated",S=c==="loading",n=i?.partnerId===r,f=n&&i?.error?new Error(i.error):null,u=t(()=>{n&&e(r,"idle")},[n,r,e]),m=t(()=>{e(r,"loading")},[r,e]),A=t(()=>{e(r,"idle")},[r,e]),P=t(async I=>{n&&u();try{e(r,"loading");const a=await d(r,I);if(a===null){e(r,"idle");return}a&&s&&s(a)}catch(a){const h=a;e(r,"error",h),l&&l(h)}},[r,n,u,e,d,s,l]);return{partnerState:c,isAuthenticated:E,isAuthenticating:S,hasError:n,error:f,handleSignIn:P,clearError:u,setLoading:m,setIdle:A}}export{w as useAuthPartner};
@@ -0,0 +1,34 @@
1
+ import type { AuthUserSummary } from '@donotdev/core';
2
+ /**
3
+ * Auth user list state
4
+ *
5
+ * @version 0.1.0
6
+ * @since 0.3.3
7
+ */
8
+ export interface AuthUsersState {
9
+ /** Every auth account; empty until loaded */
10
+ users: AuthUserSummary[];
11
+ /** True while auth initialises or the list loads */
12
+ loading: boolean;
13
+ /** Load failure (not an admin, server function not deployed, network) */
14
+ error: Error | null;
15
+ /** Load the list again */
16
+ reload: () => Promise<void>;
17
+ }
18
+ /**
19
+ * Lists every auth account for admin pages. Loads once when auth is ready; the
20
+ * provider calls its admin-only `listAuthUsers` server function, which the app deploys
21
+ * (`createListAuthUsers` for Supabase, `listAuthUsers` for Firebase, from
22
+ * `@donotdev/functions`). A non-admin gets `error`, never a partial list.
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * const { users, loading, error, reload } = useAuthUsers();
27
+ * ```
28
+ *
29
+ * @returns `{ users, loading, error, reload }`
30
+ * @version 0.1.0
31
+ * @since 0.3.3
32
+ */
33
+ export declare function useAuthUsers(): AuthUsersState;
34
+ //# sourceMappingURL=useAuthUsers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAuthUsers.d.ts","sourceRoot":"","sources":["../../src/hooks/useAuthUsers.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAMtD;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB,oDAAoD;IACpD,OAAO,EAAE,OAAO,CAAC;IACjB,yEAAyE;IACzE,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,0BAA0B;IAC1B,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,IAAI,cAAc,CAqC7C"}
@@ -0,0 +1 @@
1
+ "use client";import{useCallback as A,useEffect as p,useRef as E,useState as n}from"react";import{FEATURE_STATUS as I}from"@donotdev/core";import{useAuthStore as S}from"../AuthStore";import{useAuth as h}from"../useAuth";function U(){const a=h("listUsers"),e=S(t=>t.status===I.INITIALIZING),[i,l]=n([]),[f,o]=n(!1),[m,c]=n(null),r=E(0),u=A(async()=>{const t=++r.current;o(!0),c(null);try{const s=await a();t===r.current&&l(s)}catch(s){t===r.current&&c(s instanceof Error?s:new Error(String(s)))}finally{t===r.current&&o(!1)}},[a]);return p(()=>{if(!e)return u(),()=>{r.current++}},[e,u]),{users:i,loading:e||f,error:m,reload:u}}export{U as useAuthUsers};
@@ -1 +1 @@
1
- "use client";import{useState as l}from"react";import{useTranslation as D}from"@donotdev/core";import{useAuth as h}from"../useAuth";const f="deleteAccount.errors.",E=/^[A-Za-z0-9_-]+$/;function w(e){const s=typeof e=="object"&&e!==null&&"details"in e?e.details:void 0;return[s?.serverCode,s?.serverMessage,e instanceof Error?e.message:void 0].filter(o=>typeof o=="string"&&E.test(o))}function y(){const e=h("deleteAccount"),{t:s}=D("auth"),[o,t]=l(!1),[d,n]=l(!1),[m,c]=l(!1),[A,r]=l(null);return{showConfirmDialog:o,showPasswordDialog:d,isDeleting:m,error:A,startDeleteFlow:()=>{r(null),t(!0)},confirmDelete:async g=>{c(!0),r(null);try{await e(g),t(!1),n(!1)}catch(u){const a=u.message;if(a==="REQUIRES_PASSWORD")t(!1),n(!0);else if(a==="REAUTH_CANCELLED")t(!1),n(!1);else{const p=w(u).map(i=>s(`${f}${i}`)).find(i=>!i.startsWith(f));r(p??(a||"Failed to delete account"))}}finally{c(!1)}},cancel:()=>{t(!1),n(!1),r(null)}}}export{y as useDeleteAccount};
1
+ "use client";import{useState as l}from"react";import{useTranslation as g}from"@donotdev/core";import{useAuth as h}from"../useAuth";const f="deleteAccount.errors.",E=/^[A-Za-z0-9_-]+$/;function w(e){const s=typeof e=="object"&&e!==null&&"details"in e?e.details:void 0;return[s?.serverCode,s?.serverMessage,e instanceof Error?e.message:void 0].filter(o=>typeof o=="string"&&E.test(o))}function y(){const e=h("deleteAccount"),{t:s}=g("auth"),[o,t]=l(!1),[d,n]=l(!1),[m,c]=l(!1),[A,r]=l(null);return{showConfirmDialog:o,showPasswordDialog:d,isDeleting:m,error:A,startDeleteFlow:()=>{r(null),t(!0)},confirmDelete:async D=>{c(!0),r(null);try{await e(D),t(!1),n(!1)}catch(u){const a=u.message;if(a==="REQUIRES_PASSWORD")t(!1),n(!0);else if(a==="REAUTH_CANCELLED")t(!1),n(!1);else{const p=w(u).map(i=>s(`${f}${i}`)).find(i=>!i.startsWith(f));r(p??(a||"Failed to delete account"))}}finally{c(!1)}},cancel:()=>{t(!1),n(!1),r(null)}}}export{y as useDeleteAccount};
@@ -1 +1 @@
1
- "use client";import{useState as r,useCallback as l}from"react";import{handleError as I}from"@donotdev/core";import{useAuth as f}from"../useAuth";function w(g={}){const t=f("sendSignInLinkToEmail"),S=f("isAvailable"),{onSuccess:s,onError:o,actionCodeSettings:m}=g,[e,E]=r(""),[u,c]=r(!1),[h,d]=r(!1),[p,n]=r(null),i=e.trim().length>0&&e.includes("@"),k=i&&!u&&S,y=l(()=>{n(null)},[]),L=l(async v=>{if(v.preventDefault(),!i){n("Please enter a valid email address");return}c(!0),n(null);try{typeof window<"u"&&localStorage.setItem("emailForSignIn",e.trim()),await t(e.trim(),m),d(!0),s?.()}catch(a){const F=a instanceof Error?a.message:"Failed to send sign-in link";n(F),o?.(a),I(a)}finally{c(!1)}},[e,i,t,m,s,o]),b=l(()=>{d(!1),n(null)},[]);return{email:e,setEmail:E,isLoading:u,isSent:h,error:p,handleSendLink:L,handleResend:b,clearError:y,isValid:i,canSubmit:k}}export{w as useEmailLinkForm};
1
+ "use client";import{useState as r,useCallback as l}from"react";import{handleError as I}from"@donotdev/core";import{useAuth as f}from"../useAuth";function v(S={}){const t=f("sendSignInLinkToEmail"),g=f("isAvailable"),{onSuccess:s,onError:o,actionCodeSettings:m}=S,[e,E]=r(""),[u,c]=r(!1),[h,d]=r(!1),[p,n]=r(null),i=e.trim().length>0&&e.includes("@"),k=i&&!u&&g,y=l(()=>{n(null)},[]),L=l(async w=>{if(w.preventDefault(),!i){n("Please enter a valid email address");return}c(!0),n(null);try{typeof window<"u"&&localStorage.setItem("emailForSignIn",e.trim()),await t(e.trim(),m),d(!0),s?.()}catch(a){const F=a instanceof Error?a.message:"Failed to send sign-in link";n(F),o?.(a),I(a)}finally{c(!1)}},[e,i,t,m,s,o]),b=l(()=>{d(!1),n(null)},[]);return{email:e,setEmail:E,isLoading:u,isSent:h,error:p,handleSendLink:L,handleResend:b,clearError:y,isValid:i,canSubmit:k}}export{v as useEmailLinkForm};
@@ -1 +1 @@
1
- "use client";import{useState as G,useEffect as L,useRef as f,useCallback as j,startTransition as _,useMemo as B}from"react";import{useIsDark as te}from"@donotdev/components";import{handleError as g,getOAuthClientId as oe,getEnabledAuthPartners as re,isClient as ne,useTranslation as ae,useScriptLoader as ie}from"@donotdev/core";import{useAuth as J}from"../useAuth";import{useFedCM as se}from"./useFedCM";function ce({clientId:K,autoSelect:x=!0,cancelOnTapOutside:v=!0,promptParentId:y,disabled:l=!1,onSuccess:C,onError:i,allowedParentOrigins:z,cspNonce:S,clientOnly:R=!1}={}){const{t:n}=ae("auth"),T=J("user"),A=J("signInWithGoogleCredential"),I=te(),s=K||oe("google"),E=re().includes("google"),{isSupported:r,isReady:d,error:F,browserInfo:U}=se({checkGoogleServices:!0,onError:t=>{const o=g(t,{userMessage:n("auth.fedcmNotSupported","Your browser does not support Google One Tap"),context:{operation:"fedcm_detection"},severity:"warning"});i?.(o)}}),{isLoading:V,isLoaded:O,error:P,isReady:q,load:X,loadTriggered:Z}=ie("https://accounts.google.com/gsi/client",{enabled:E&&!!s&&!l&&d&&r,nonce:S,checkExisting:!0,isLoaded:()=>!!window.google?.accounts?.id,onError:t=>{const o=g(t,{userMessage:n("auth.googleScriptLoadError","Failed to load Google Identity Services"),context:{operation:"google_script_load"},severity:"error"});i?.(o)}}),[b,$]=G(!1),[N,W]=G(null),Q=f(null),a=f(!1),c=f(null),D=f(0),[H,p]=G(!1),m="gsi_hide_until",w=600*1e3,M=B(()=>E&&!!s&&!l&&!T&&r&&(R?b:!0)&&!H,[E,s,l,T,r,R,b,H]),ee=B(()=>!r&&d?new Error(n("auth.fedcmRequired","Google One Tap requires a modern browser (Chrome 116+ or Edge 116+)")):P||F||N,[P,F,N,r,d,n]),h=j(async t=>{try{if(!t||typeof t!="string")throw new Error("Invalid credential format");await A(t),_(()=>{C?.(t)})}catch(o){const e=g(o,{userMessage:n("auth.googleOneTapError","Google One Tap authentication failed"),context:{operation:"google_one_tap_signin",credentialLength:t?.length||0},severity:"error"});throw _(()=>{W(e)}),i?.(e),e}},[A,C,i,n]),k=j(()=>{if(!ne()||!q||!s||!window.google?.accounts?.id||!r||a.current)return;const t=Date.now();if(!(t-D.current<w&&D.current>0))try{a.current=!0,D.current=t;const o={client_id:s,callback:async e=>{try{await h(e.credential)}catch(Y){g(Y,{userMessage:"Google One Tap credential handling failed",context:{operation:"google_one_tap_callback"},severity:"error"})}},auto_select:x,cancel_on_tap_outside:v,context:"signin",ux_mode:"popup",itp_support:!0,state:I?"dark":"light",use_fedcm_for_prompt:!0,allowed_parent_origins:z,csp_nonce:S,moment_callback:e=>{const Y=e.getMomentType();if(e.isDisplayMoment?.()){if(!e.isDisplayed?.()&&e.getNotDisplayedReason){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}}else if(e.isSkippedMoment?.()){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}else if(e.isDismissedMoment?.()){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}}};y&&(o.prompt_parent_id=y),window.google.accounts.id.initialize(o),c.current&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{window.google?.accounts?.id?.prompt(e=>{e?.credential&&h(e.credential)}),c.current=null},100)}catch(o){const e=g(o,{userMessage:n("auth.googleOneTapInitError","Failed to initialize Google One Tap"),context:{operation:"google_one_tap_initialize",fedcmSupported:r},severity:"error"});_(()=>{W(e)}),i?.(e),a.current=!1}},[q,s,r,x,v,y,I,h,i,z,S,n]);return L(()=>{if(typeof window<"u"){_(()=>{$(!0)});try{const t=Number(localStorage.getItem(m)||0);p(t>Date.now())}catch{}}},[]),L(()=>{O&&!l&&M&&d&&k()},[O,l,M,d,k]),L(()=>()=>{c.current&&window.clearTimeout(c.current),a.current=!1},[]),{isLoaded:O,isLoading:V,error:ee,user:T,isDark:I,fedcmSupported:r,isHydrated:b,containerRef:Q,initialize:k,handleCredential:h,shouldShow:M,browserInfo:U,triggerLoad:X,loadTriggered:Z}}export{ce as useGoogleOneTap};
1
+ "use client";import{useState as G,useEffect as L,useRef as f,useCallback as j,startTransition as _,useMemo as B}from"react";import{useIsDark as oe}from"@donotdev/components";import{handleError as g,getOAuthClientId as te,getEnabledAuthPartners as re,isClient as ne,useTranslation as ae,useScriptLoader as ie}from"@donotdev/core";import{useAuth as J}from"../useAuth";import{useFedCM as se}from"./useFedCM";function ce({clientId:Q,autoSelect:x=!0,cancelOnTapOutside:v=!0,promptParentId:y,disabled:l=!1,onSuccess:C,onError:i,allowedParentOrigins:N,cspNonce:S,clientOnly:R=!1}={}){const{t:n}=ae("auth"),T=J("user"),A=J("signInWithGoogleCredential"),I=oe(),s=Q||te("google"),E=re().includes("google"),{isSupported:r,isReady:d,error:F,browserInfo:U}=se({checkGoogleServices:!0,onError:o=>{const t=g(o,{userMessage:n("auth.fedcmNotSupported","Your browser does not support Google One Tap"),context:{operation:"fedcm_detection"},severity:"warning"});i?.(t)}}),{isLoading:V,isLoaded:O,error:P,isReady:q,load:X,loadTriggered:Z}=ie("https://accounts.google.com/gsi/client",{enabled:E&&!!s&&!l&&d&&r,nonce:S,checkExisting:!0,isLoaded:()=>!!window.google?.accounts?.id,onError:o=>{const t=g(o,{userMessage:n("auth.googleScriptLoadError","Failed to load Google Identity Services"),context:{operation:"google_script_load"},severity:"error"});i?.(t)}}),[b,$]=G(!1),[z,Y]=G(null),K=f(null),a=f(!1),c=f(null),D=f(0),[H,p]=G(!1),m="gsi_hide_until",w=600*1e3,M=B(()=>E&&!!s&&!l&&!T&&r&&(R?b:!0)&&!H,[E,s,l,T,r,R,b,H]),ee=B(()=>!r&&d?new Error(n("auth.fedcmRequired","Google One Tap requires a modern browser (Chrome 116+ or Edge 116+)")):P||F||z,[P,F,z,r,d,n]),h=j(async o=>{try{if(!o||typeof o!="string")throw new Error("Invalid credential format");await A(o),_(()=>{C?.(o)})}catch(t){const e=g(t,{userMessage:n("auth.googleOneTapError","Google One Tap authentication failed"),context:{operation:"google_one_tap_signin",credentialLength:o?.length||0},severity:"error"});throw _(()=>{Y(e)}),i?.(e),e}},[A,C,i,n]),k=j(()=>{if(!ne()||!q||!s||!window.google?.accounts?.id||!r||a.current)return;const o=Date.now();if(!(o-D.current<w&&D.current>0))try{a.current=!0,D.current=o;const t={client_id:s,callback:async e=>{try{await h(e.credential)}catch(W){g(W,{userMessage:"Google One Tap credential handling failed",context:{operation:"google_one_tap_callback"},severity:"error"})}},auto_select:x,cancel_on_tap_outside:v,context:"signin",ux_mode:"popup",itp_support:!0,state:I?"dark":"light",use_fedcm_for_prompt:!0,allowed_parent_origins:N,csp_nonce:S,moment_callback:e=>{const W=e.getMomentType();if(e.isDisplayMoment?.()){if(!e.isDisplayed?.()&&e.getNotDisplayedReason){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}}else if(e.isSkippedMoment?.()){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}else if(e.isDismissedMoment?.()){a.current=!1;try{const u=Date.now()+w;localStorage.setItem(m,String(u)),p(!0)}catch{}}}};y&&(t.prompt_parent_id=y),window.google.accounts.id.initialize(t),c.current&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{window.google?.accounts?.id?.prompt(e=>{e?.credential&&h(e.credential)}),c.current=null},100)}catch(t){const e=g(t,{userMessage:n("auth.googleOneTapInitError","Failed to initialize Google One Tap"),context:{operation:"google_one_tap_initialize",fedcmSupported:r},severity:"error"});_(()=>{Y(e)}),i?.(e),a.current=!1}},[q,s,r,x,v,y,I,h,i,N,S,n]);return L(()=>{if(typeof window<"u"){_(()=>{$(!0)});try{const o=Number(localStorage.getItem(m)||0);p(o>Date.now())}catch{}}},[]),L(()=>{O&&!l&&M&&d&&k()},[O,l,M,d,k]),L(()=>()=>{c.current&&window.clearTimeout(c.current),a.current=!1},[]),{isLoaded:O,isLoading:V,error:ee,user:T,isDark:I,fedcmSupported:r,isHydrated:b,containerRef:K,initialize:k,handleCredential:h,shouldShow:M,browserInfo:U,triggerLoad:X,loadTriggered:Z}}export{ce as useGoogleOneTap};
package/dist/index.d.ts CHANGED
@@ -8,17 +8,21 @@
8
8
  export { useAuth } from './useAuth';
9
9
  export { useDeleteAccount } from './hooks/useDeleteAccount';
10
10
  export type { DeleteAccountState } from './hooks/useDeleteAccount';
11
+ export { useAuthUsers } from './hooks/useAuthUsers';
12
+ export type { AuthUsersState } from './hooks/useAuthUsers';
11
13
  export { getAuthState, subscribeToAuth } from './authHelpers';
12
14
  export { AuthPartnerButton, ConfirmDeleteDialog, FeatureGuard, GoogleOneTap, LoginModal, MultipleAuthProviders, // Added for AuthHeader and future LoginTemplate
13
15
  PasswordResetCallback, ReauthDialog, } from './components';
14
16
  export { default as EmailPasswordForm } from './components/EmailPasswordForm';
15
- export { AUTH_FIELD, useEmailSignIn, useEmailSignUp, usePasswordResetRequest, } from './emailAuth/flows';
16
- export type { AuthFieldErrors, EmailAuthFlow, EmailAuthFlowOptions, EmailAuthMode, EmailSignUpOptions, EmailSignUpOutcome, } from './emailAuth/flows';
17
- export { AuthConfirmPasswordField, AuthConsentField, AuthEmailField, AuthForm, AuthFormAlerts, AuthPasswordField, AuthRememberMeField, AuthSubmitButton, } from './emailAuth/fields';
18
- export type { AuthConsentFieldProps, AuthFormProps, AuthLegalDocument, AuthRememberMeFieldProps, AuthSubmitButtonProps, AuthTextFieldProps, } from './emailAuth/fields';
17
+ export { AUTH_FIELD, useEmailCodeConfirmation, useEmailSignIn, useEmailSignUp, usePasswordResetRequest, validateEmail, } from './emailAuth/flows';
18
+ export { DEFAULT_PASSWORD_MIN_LENGTH, isEmail, newPasswordError, } from './emailAuth/rules';
19
+ export type { AuthT } from './emailAuth/rules';
20
+ export type { AuthFieldErrors, EmailAuthFlow, EmailCodeConfirmation, EmailCodeConfirmationOptions, EmailSignUpConfirmation, EmailAuthFlowOptions, EmailAuthMode, EmailSignInOptions, EmailSignUpOptions, EmailSignUpOutcome, PasswordResetRequestFlow, PasswordResetRequestOptions, } from './emailAuth/flows';
21
+ export { AuthCodeField, AuthCodeStep, AuthConfirmPasswordField, AuthConsentField, AuthEmailField, AuthForm, AuthFormAlerts, AuthNameField, AuthPasswordField, AuthRememberMeField, AuthSubmitButton, } from './emailAuth/fields';
22
+ export type { AuthCodeFieldProps, AuthCodeStepProps, AuthConsentFieldProps, AuthFormProps, AuthLegalDocument, AuthNameFieldProps, AuthRememberMeFieldProps, AuthSubmitButtonProps, AuthTextFieldProps, } from './emailAuth/fields';
19
23
  export type { AuthError, // Explicitly import AuthError from core
20
24
  AuthUser as User, // Rename AuthUser to User for public API simplicity
21
- UserRole, SubscriptionTier, } from '@donotdev/core';
25
+ AuthUserSummary, UserRole, SubscriptionTier, } from '@donotdev/core';
22
26
  export { getAuthMethod, PARTNER_STATE, EMAIL_VERIFICATION_STATUS, } from './constants';
23
27
  export type { AuthMethod } from './constants';
24
28
  export type { AuthPartnerButtonProps, EmailPasswordFormProps, GoogleOneTapProps, LoginModalProps, } from './constants';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AAGH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,YAAY,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAGnE,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAG9D,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,qBAAqB,EAAE,gDAAgD;AACvE,qBAAqB,EACrB,YAAY,GACb,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM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AAI,IAAI,EAAE,oDAAoD;AACtE,eAAe,EACf,QAAQ,EACR,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EACL,aAAa,EACb,aAAa,EACb,yBAAyB,GAC1B,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAG9C,YAAY,EACV,sBAAsB,EACtB,sBAAsB,EACtB,iBAAiB,EACjB,eAAe,GAChB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AACrF,YAAY,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AACnE,YAAY,EACV,wBAAwB,EACxB,iBAAiB,GAClB,MAAM,mCAAmC,CAAC"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{useAuth as s}from"./useAuth";import{useDeleteAccount as a}from"./hooks/useDeleteAccount";import{getAuthState as e,subscribeToAuth as t}from"./authHelpers";import{AuthPartnerButton as o,ConfirmDeleteDialog as u,FeatureGuard as r,GoogleOneTap as i,LoginModal as A,MultipleAuthProviders as l,PasswordResetCallback as m,ReauthDialog as h}from"./components";import{default as d}from"./components/EmailPasswordForm";import{AUTH_FIELD as n,useEmailSignIn as F,useEmailSignUp as T,usePasswordResetRequest as E}from"./emailAuth/flows";import{AuthConfirmPasswordField as g,AuthConsentField as R,AuthEmailField as p,AuthForm as P,AuthFormAlerts as S,AuthPasswordField as f,AuthRememberMeField as I,AuthSubmitButton as b}from"./emailAuth/fields";import{getAuthMethod as C,PARTNER_STATE as D,EMAIL_VERIFICATION_STATUS as M}from"./constants";export{n as AUTH_FIELD,g as AuthConfirmPasswordField,R as AuthConsentField,p as AuthEmailField,P as AuthForm,S as AuthFormAlerts,o as AuthPartnerButton,f as AuthPasswordField,I as AuthRememberMeField,b as AuthSubmitButton,u as ConfirmDeleteDialog,M as EMAIL_VERIFICATION_STATUS,d as EmailPasswordForm,r as FeatureGuard,i as GoogleOneTap,A as LoginModal,l as MultipleAuthProviders,D as PARTNER_STATE,m as PasswordResetCallback,h as ReauthDialog,C as getAuthMethod,e as getAuthState,t as subscribeToAuth,s as useAuth,a as useDeleteAccount,F as useEmailSignIn,T as useEmailSignUp,E as usePasswordResetRequest};
1
+ import{useAuth as s}from"./useAuth";import{useDeleteAccount as a}from"./hooks/useDeleteAccount";import{useAuthUsers as e}from"./hooks/useAuthUsers";import{getAuthState as t,subscribeToAuth as o}from"./authHelpers";import{AuthPartnerButton as u,ConfirmDeleteDialog as r,FeatureGuard as i,GoogleOneTap as A,LoginModal as l,MultipleAuthProviders as m,PasswordResetCallback as d,ReauthDialog as h}from"./components";import{default as n}from"./components/EmailPasswordForm";import{AUTH_FIELD as E,useEmailCodeConfirmation as F,useEmailSignIn as T,useEmailSignUp as S,usePasswordResetRequest as p,validateEmail as P}from"./emailAuth/flows";import{DEFAULT_PASSWORD_MIN_LENGTH as C,isEmail as R,newPasswordError as f}from"./emailAuth/rules";import{AuthCodeField as g,AuthCodeStep as D,AuthConfirmPasswordField as I,AuthConsentField as _,AuthEmailField as w,AuthForm as M,AuthFormAlerts as b,AuthNameField as L,AuthPasswordField as N,AuthRememberMeField as U,AuthSubmitButton as c}from"./emailAuth/fields";import{getAuthMethod as G,PARTNER_STATE as O,EMAIL_VERIFICATION_STATUS as v}from"./constants";export{E as AUTH_FIELD,g as AuthCodeField,D as AuthCodeStep,I as AuthConfirmPasswordField,_ as AuthConsentField,w as AuthEmailField,M as AuthForm,b as AuthFormAlerts,L as AuthNameField,u as AuthPartnerButton,N as AuthPasswordField,U as AuthRememberMeField,c as AuthSubmitButton,r as ConfirmDeleteDialog,C as DEFAULT_PASSWORD_MIN_LENGTH,v as EMAIL_VERIFICATION_STATUS,n as EmailPasswordForm,i as FeatureGuard,A as GoogleOneTap,l as LoginModal,m as MultipleAuthProviders,O as PARTNER_STATE,d as PasswordResetCallback,h as ReauthDialog,G as getAuthMethod,t as getAuthState,R as isEmail,f as newPasswordError,o as subscribeToAuth,s as useAuth,e as useAuthUsers,a as useDeleteAccount,F as useEmailCodeConfirmation,T as useEmailSignIn,S as useEmailSignUp,p as usePasswordResetRequest,P as validateEmail};