@rdlabo/ionic-angular-kit 0.0.23 → 0.0.24

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/README.md CHANGED
@@ -552,12 +552,12 @@ await BrotherPrint.printImage({ ...settings, port: channel.port, channelInfo: ch
552
552
 
553
553
  ### Firebase auth (`@rdlabo/ionic-angular-kit/auth-firebase`)
554
554
 
555
- A secondary entry point so only apps that use it pull in `@angular/fire` and `firebase`. It exists to **isolate `@angular/fire`**: the SDK is touched in exactly one place — the DI provider — so apps import `KIT_FIREBASE_AUTH` and call these functions, never `@angular/fire` directly. That keeps the eventual `@angular/fire` → modular `firebase/auth` swap provider-local.
555
+ A secondary entry point so only apps that use it pull in `firebase` (declared as an optional peer dependency — install `firebase` in the app). It exists to **isolate the Firebase SDK**: `firebase/auth` is initialized in exactly one place — the DI provider — so apps import `KIT_FIREBASE_AUTH` and call these functions, never wiring `firebase/auth` themselves. The kit uses the vanilla modular `firebase/auth` SDK directly (no `@angular/fire`).
556
556
 
557
557
  **Design principle: the kit performs no UI.** Every function runs the Firebase operation and nothing else; loading overlays, prompts and error alerts are app side effects. The flow functions take the uniform lifecycle hooks `{ before, success, error, finally }` and, rather than throwing, resolve value flows to `null` and boolean flows to `false`, handing the raw error to the `error` hook so the app presents it from its own dictionary. For anything the functions don't express, drop down to `firebase/auth` directly.
558
558
 
559
559
  ```typescript
560
- // app.config.ts — @angular/fire lives only here
560
+ // app.config.ts — Firebase is initialized only here
561
561
  provideKitFirebase({ firebaseConfig: environment.firebase }),
562
562
  provideKitFirebaseAnalytics(),
563
563
  ```
@@ -1,4 +1,4 @@
1
- import { signInWithCredential, linkWithCredential, reauthenticateWithCredential, EmailAuthProvider, OAuthProvider, FacebookAuthProvider, reauthenticateWithPopup, signInWithPopup, linkWithPopup } from '@angular/fire/auth';
1
+ import { signInWithCredential, linkWithCredential, reauthenticateWithCredential, EmailAuthProvider, OAuthProvider, FacebookAuthProvider, reauthenticateWithPopup, signInWithPopup, linkWithPopup } from 'firebase/auth';
2
2
  import { Capacitor } from '@capacitor/core';
3
3
  import { FacebookLogin } from '@capacitor-community/facebook-login';
4
4
  import { SignInWithApple } from '@capacitor-community/apple-sign-in';
@@ -172,10 +172,7 @@ const kitAppleLogin = async (auth, options) => {
172
172
  }
173
173
  let result;
174
174
  try {
175
- result =
176
- options.mode === 'new'
177
- ? await signInWithPopup(auth, provider)
178
- : await linkWithPopup(requireUser(auth), provider);
175
+ result = options.mode === 'new' ? await signInWithPopup(auth, provider) : await linkWithPopup(requireUser(auth), provider);
179
176
  }
180
177
  catch (e) {
181
178
  await options.error?.(classifyOAuthError(e), e);
@@ -1 +1 @@
1
- {"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-social.mjs","sources":["../../../projects/kit/auth-firebase/social/src/kit-social.ts","../../../projects/kit/auth-firebase/social/src/public-api.ts","../../../projects/kit/auth-firebase/social/src/rdlabo-ionic-angular-kit-auth-firebase-social.ts"],"sourcesContent":["import type { Auth, AuthCredential } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n FacebookAuthProvider,\n linkWithCredential,\n linkWithPopup,\n OAuthProvider,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from '@angular/fire/auth';\nimport { Capacitor } from '@capacitor/core';\nimport { FacebookLogin } from '@capacitor-community/facebook-login';\nimport { SignInWithApple } from '@capacitor-community/apple-sign-in';\n\n/** How a social-credential failure is classified for the app's error hook. */\nexport type KitOAuthErrorCategory = 'already-in-use' | 'cancelled' | 'other';\n\n/** The mode a social login runs in. */\nexport type KitOAuthModeName = 'new' | 'link' | 'credential';\n\n/**\n * The mode discriminator. `'credential'` links an email/password to the (re-authenticated) social\n * account, so it requires the new email/password; `'new'` / `'link'` do not.\n */\nexport type KitOAuthMode =\n | { mode: 'new' }\n | { mode: 'link' }\n | { mode: 'credential'; emailLogin: { email: string; password: string } };\n\n/**\n * The apple identity payload handed to the `success` hook for the backend call. Populated from the\n * native plugin on device, or synthesized from the popup result on the web.\n */\nexport interface KitAppleResponse {\n user: string | null;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n identityToken: string | null;\n authorizationCode: string | null;\n}\n\n/**\n * The uniform lifecycle hooks for a social flow — the same `before / success / error / finally`\n * shape as {@link KitFirebaseAuthService}'s hooks, so a call site reads the same everywhere. All are\n * optional; the kit renders nothing itself.\n *\n * @typeParam Info - the identity payload handed to {@link success} (Facebook access token / Apple\n * response), so an app can notify its backend and give feedback in one place.\n *\n * @remarks\n * `before` runs before the plugin login starts, `success` after the mode's Firebase op succeeds\n * (carrying the identity payload — do the backend call and the toast here), `error` on a classified\n * failure (`'cancelled'` is passed through so the app can stay silent on a user cancel), and\n * `finally` always. The kit swallows none of these errors.\n */\ninterface KitSocialHooks<Info> {\n before?: () => void | Promise<unknown>;\n success?: (info: Info) => void | Promise<unknown>;\n error?: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Options for {@link kitFacebookLogin}. */\nexport type KitFacebookLoginOptions = KitOAuthMode &\n KitSocialHooks<{ accessToken: string; mode: KitOAuthModeName }> & {\n /** Facebook permissions to request. */\n permissions: string[];\n };\n\n/** Options for {@link kitAppleLogin}. */\nexport type KitAppleLoginOptions = KitOAuthMode & KitSocialHooks<{ response: KitAppleResponse; mode: KitOAuthModeName }>;\n\n/** Generate a random nonce for the Facebook OIDC (Limited Login) flow. */\nconst generateNonce = (length = 16): string => {\n const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let nonce = '';\n for (let i = 0; i < length; i++) {\n nonce += charset[Math.floor(Math.random() * charset.length)];\n }\n return nonce;\n};\n\nconst classifyOAuthError = (e: unknown): KitOAuthErrorCategory => {\n const code = (e as { code?: string } | undefined)?.code;\n if (code === 'auth/credential-already-in-use') {\n return 'already-in-use';\n }\n if (code === 'auth/user-cancelled') {\n return 'cancelled';\n }\n return 'other';\n};\n\n/**\n * The shared 3-mode credential state machine (internal).\n *\n * @remarks\n * `new` signs in with the credential, `link` links it, `credential` re-authenticates with the social\n * credential and then links an email/password. Any Firebase error is classified and handed to\n * `error` (returning `false`); on success the app's `success` hook (backend + feedback) runs with the\n * identity payload, and it returns `true`.\n */\nconst applyOAuthCredential = async (\n auth: Auth,\n credential: AuthCredential,\n mode: KitOAuthMode,\n effects: {\n success: () => void | Promise<unknown>;\n error: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n },\n): Promise<boolean> => {\n try {\n if (mode.mode === 'new') {\n await signInWithCredential(auth, credential);\n } else {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link/re-authenticate');\n }\n if (mode.mode === 'link') {\n await linkWithCredential(user, credential);\n } else {\n await reauthenticateWithCredential(user, credential);\n await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));\n }\n }\n } catch (e) {\n await effects.error(classifyOAuthError(e), e);\n return false;\n }\n await effects.success();\n return true;\n};\n\n/** Await one animation frame where available (iOS WebView crash workaround; no-op off-browser). */\nconst nextFrame = (): Promise<void> =>\n new Promise<void>((resolve) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => resolve());\n } else {\n resolve();\n }\n });\n\n/**\n * Facebook login / link, bundled: native plugin → credential → the shared 3-mode state machine.\n *\n * @remarks\n * On iOS the credential is built from the OIDC token with a nonce (`OAuthProvider('facebook.com')`);\n * elsewhere from the access token (`FacebookAuthProvider`). Returns `{ status: false }` on a\n * cancelled/failed plugin login or a handled Firebase error (the app was already notified via the\n * hooks).\n */\nexport const kitFacebookLogin = async (\n auth: Auth,\n options: KitFacebookLoginOptions,\n): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n const nonce = generateNonce();\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch(() => undefined);\n await nextFrame();\n if (!event || !event.accessToken?.token) {\n return { status: false };\n }\n const accessToken = event.accessToken.token;\n const credential: AuthCredential =\n Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'\n ? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })!\n : FacebookAuthProvider.credential(accessToken);\n\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ accessToken, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n } finally {\n await options.finally?.();\n }\n};\n\n/**\n * Log out of the Facebook SDK (best-effort; errors are ignored).\n *\n * @remarks\n * Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives\n * here to keep the `@capacitor-community/facebook-login` import out of the app.\n * Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs\n * \"called without an access token\" on web and native rejects for email/password users.\n */\nexport const kitFacebookLogout = async (): Promise<void> => {\n const session = await FacebookLogin.getCurrentAccessToken().catch(() => null);\n if (!session?.accessToken?.token) {\n return;\n }\n await FacebookLogin.logout().catch(() => undefined);\n};\n\n/**\n * Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.\n *\n * @remarks\n * - **Native**: `SignInWithApple.authorize()` → `OAuthProvider('apple.com')` credential → the shared\n * 3-mode state machine.\n * - **Web**: `signInWithPopup` / `linkWithPopup` (with `email`/`name` scopes), or, for `credential`,\n * `reauthenticateWithPopup` then link the email/password. The identity payload for the backend is\n * synthesized from the popup result.\n *\n * Every failure path (including popup errors) is routed through `onError`.\n */\nexport const kitAppleLogin = async (auth: Auth, options: KitAppleLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) {\n return { status: false };\n }\n const r = authorize.response;\n const response: KitAppleResponse = {\n user: r.user ?? null,\n email: r.email ?? null,\n givenName: r.givenName ?? null,\n familyName: r.familyName ?? null,\n identityToken: r.identityToken ?? null,\n authorizationCode: r.authorizationCode ?? null,\n };\n const credential = new OAuthProvider('apple.com').credential({ idToken: response.identityToken ?? undefined })!;\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ response, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n }\n\n // Web: the popup performs the sign-in/link itself.\n const provider = new OAuthProvider('apple.com');\n provider.addScope('email');\n provider.addScope('name');\n\n if (options.mode === 'credential') {\n const user = auth.currentUser;\n try {\n if (!user) {\n throw new Error('kit social: no signed-in user to re-authenticate');\n }\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(\n user,\n EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password),\n );\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n let result;\n try {\n result =\n options.mode === 'new'\n ? await signInWithPopup(auth, provider)\n : await linkWithPopup(requireUser(auth), provider);\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n const credential = OAuthProvider.credentialFromResult(result);\n const response: KitAppleResponse = {\n ...emptyAppleResponse(),\n email: result.user?.email ?? null,\n identityToken: credential?.idToken ?? null,\n authorizationCode: credential?.accessToken ?? null,\n };\n await options.success?.({ response, mode: options.mode });\n return { status: true };\n } finally {\n await options.finally?.();\n }\n};\n\nconst emptyAppleResponse = (): KitAppleResponse => ({\n user: null,\n email: null,\n givenName: null,\n familyName: null,\n identityToken: null,\n authorizationCode: null,\n});\n\nconst requireUser = (auth: Auth) => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link');\n }\n return user;\n};\n","// Social login (Facebook / Apple). Its own entry point so only apps that use it pull in the native\n// plugins `@capacitor-community/facebook-login` and `@capacitor-community/apple-sign-in`; the core\n// `auth-firebase` entry stays free of them.\n//\n// Public surface is curated: two bundled flows plus their option types. The nonce util, the error\n// classifier and the 3-mode credential state machine are internal implementation details.\nexport * from './kit-social';\n","/**\n * Generated bundle index. Do not edit.\n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jC,YAAA,aAAa,EAAE,UAAU,EAAE,OAAO,IAAI,IAAI;AAC1C,YAAA,iBAAiB,EAAE,UAAU,EAAE,WAAW,IAAI,IAAI;SACnD;AACD,QAAA,MAAM,OAAO,CAAC,OAAO,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;AACzD,QAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE;IACzB;YAAU;AACR,QAAA,MAAM,OAAO,CAAC,OAAO,IAAI;IAC3B;AACF;AAEA,MAAM,kBAAkB,GAAG,OAAyB;AAClD,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,KAAK,EAAE,IAAI;AACX,IAAA,SAAS,EAAE,IAAI;AACf,IAAA,UAAU,EAAE,IAAI;AAChB,IAAA,aAAa,EAAE,IAAI;AACnB,IAAA,iBAAiB,EAAE,IAAI;AACxB,CAAA,CAAC;AAEF,MAAM,WAAW,GAAG,CAAC,IAAU,KAAI;AACjC,IAAA,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW;IAC7B,IAAI,CAAC,IAAI,EAAE;AACT,QAAA,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC;IAC1D;AACA,IAAA,OAAO,IAAI;AACb,CAAC;;AC7SD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
1
+ {"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-social.mjs","sources":["../../../projects/kit/auth-firebase/social/src/kit-social.ts","../../../projects/kit/auth-firebase/social/src/public-api.ts","../../../projects/kit/auth-firebase/social/src/rdlabo-ionic-angular-kit-auth-firebase-social.ts"],"sourcesContent":["import type { Auth, AuthCredential } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n FacebookAuthProvider,\n linkWithCredential,\n linkWithPopup,\n OAuthProvider,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from 'firebase/auth';\nimport { Capacitor } from '@capacitor/core';\nimport { FacebookLogin } from '@capacitor-community/facebook-login';\nimport { SignInWithApple } from '@capacitor-community/apple-sign-in';\n\n/** How a social-credential failure is classified for the app's error hook. */\nexport type KitOAuthErrorCategory = 'already-in-use' | 'cancelled' | 'other';\n\n/** The mode a social login runs in. */\nexport type KitOAuthModeName = 'new' | 'link' | 'credential';\n\n/**\n * The mode discriminator. `'credential'` links an email/password to the (re-authenticated) social\n * account, so it requires the new email/password; `'new'` / `'link'` do not.\n */\nexport type KitOAuthMode = { mode: 'new' } | { mode: 'link' } | { mode: 'credential'; emailLogin: { email: string; password: string } };\n\n/**\n * The apple identity payload handed to the `success` hook for the backend call. Populated from the\n * native plugin on device, or synthesized from the popup result on the web.\n */\nexport interface KitAppleResponse {\n user: string | null;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n identityToken: string | null;\n authorizationCode: string | null;\n}\n\n/**\n * The uniform lifecycle hooks for a social flow — the same `before / success / error / finally`\n * shape as {@link KitFirebaseAuthService}'s hooks, so a call site reads the same everywhere. All are\n * optional; the kit renders nothing itself.\n *\n * @typeParam Info - the identity payload handed to {@link success} (Facebook access token / Apple\n * response), so an app can notify its backend and give feedback in one place.\n *\n * @remarks\n * `before` runs before the plugin login starts, `success` after the mode's Firebase op succeeds\n * (carrying the identity payload — do the backend call and the toast here), `error` on a classified\n * failure (`'cancelled'` is passed through so the app can stay silent on a user cancel), and\n * `finally` always. The kit swallows none of these errors.\n */\ninterface KitSocialHooks<Info> {\n before?: () => void | Promise<unknown>;\n success?: (info: Info) => void | Promise<unknown>;\n error?: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Options for {@link kitFacebookLogin}. */\nexport type KitFacebookLoginOptions = KitOAuthMode &\n KitSocialHooks<{ accessToken: string; mode: KitOAuthModeName }> & {\n /** Facebook permissions to request. */\n permissions: string[];\n };\n\n/** Options for {@link kitAppleLogin}. */\nexport type KitAppleLoginOptions = KitOAuthMode & KitSocialHooks<{ response: KitAppleResponse; mode: KitOAuthModeName }>;\n\n/** Generate a random nonce for the Facebook OIDC (Limited Login) flow. */\nconst generateNonce = (length = 16): string => {\n const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let nonce = '';\n for (let i = 0; i < length; i++) {\n nonce += charset[Math.floor(Math.random() * charset.length)];\n }\n return nonce;\n};\n\nconst classifyOAuthError = (e: unknown): KitOAuthErrorCategory => {\n const code = (e as { code?: string } | undefined)?.code;\n if (code === 'auth/credential-already-in-use') {\n return 'already-in-use';\n }\n if (code === 'auth/user-cancelled') {\n return 'cancelled';\n }\n return 'other';\n};\n\n/**\n * The shared 3-mode credential state machine (internal).\n *\n * @remarks\n * `new` signs in with the credential, `link` links it, `credential` re-authenticates with the social\n * credential and then links an email/password. Any Firebase error is classified and handed to\n * `error` (returning `false`); on success the app's `success` hook (backend + feedback) runs with the\n * identity payload, and it returns `true`.\n */\nconst applyOAuthCredential = async (\n auth: Auth,\n credential: AuthCredential,\n mode: KitOAuthMode,\n effects: {\n success: () => void | Promise<unknown>;\n error: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n },\n): Promise<boolean> => {\n try {\n if (mode.mode === 'new') {\n await signInWithCredential(auth, credential);\n } else {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link/re-authenticate');\n }\n if (mode.mode === 'link') {\n await linkWithCredential(user, credential);\n } else {\n await reauthenticateWithCredential(user, credential);\n await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));\n }\n }\n } catch (e) {\n await effects.error(classifyOAuthError(e), e);\n return false;\n }\n await effects.success();\n return true;\n};\n\n/** Await one animation frame where available (iOS WebView crash workaround; no-op off-browser). */\nconst nextFrame = (): Promise<void> =>\n new Promise<void>((resolve) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => resolve());\n } else {\n resolve();\n }\n });\n\n/**\n * Facebook login / link, bundled: native plugin → credential → the shared 3-mode state machine.\n *\n * @remarks\n * On iOS the credential is built from the OIDC token with a nonce (`OAuthProvider('facebook.com')`);\n * elsewhere from the access token (`FacebookAuthProvider`). Returns `{ status: false }` on a\n * cancelled/failed plugin login or a handled Firebase error (the app was already notified via the\n * hooks).\n */\nexport const kitFacebookLogin = async (auth: Auth, options: KitFacebookLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n const nonce = generateNonce();\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch(() => undefined);\n await nextFrame();\n if (!event || !event.accessToken?.token) {\n return { status: false };\n }\n const accessToken = event.accessToken.token;\n const credential: AuthCredential =\n Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'\n ? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })!\n : FacebookAuthProvider.credential(accessToken);\n\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ accessToken, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n } finally {\n await options.finally?.();\n }\n};\n\n/**\n * Log out of the Facebook SDK (best-effort; errors are ignored).\n *\n * @remarks\n * Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives\n * here to keep the `@capacitor-community/facebook-login` import out of the app.\n * Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs\n * \"called without an access token\" on web and native rejects for email/password users.\n */\nexport const kitFacebookLogout = async (): Promise<void> => {\n const session = await FacebookLogin.getCurrentAccessToken().catch(() => null);\n if (!session?.accessToken?.token) {\n return;\n }\n await FacebookLogin.logout().catch(() => undefined);\n};\n\n/**\n * Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.\n *\n * @remarks\n * - **Native**: `SignInWithApple.authorize()` → `OAuthProvider('apple.com')` credential → the shared\n * 3-mode state machine.\n * - **Web**: `signInWithPopup` / `linkWithPopup` (with `email`/`name` scopes), or, for `credential`,\n * `reauthenticateWithPopup` then link the email/password. The identity payload for the backend is\n * synthesized from the popup result.\n *\n * Every failure path (including popup errors) is routed through `onError`.\n */\nexport const kitAppleLogin = async (auth: Auth, options: KitAppleLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) {\n return { status: false };\n }\n const r = authorize.response;\n const response: KitAppleResponse = {\n user: r.user ?? null,\n email: r.email ?? null,\n givenName: r.givenName ?? null,\n familyName: r.familyName ?? null,\n identityToken: r.identityToken ?? null,\n authorizationCode: r.authorizationCode ?? null,\n };\n const credential = new OAuthProvider('apple.com').credential({ idToken: response.identityToken ?? undefined })!;\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ response, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n }\n\n // Web: the popup performs the sign-in/link itself.\n const provider = new OAuthProvider('apple.com');\n provider.addScope('email');\n provider.addScope('name');\n\n if (options.mode === 'credential') {\n const user = auth.currentUser;\n try {\n if (!user) {\n throw new Error('kit social: no signed-in user to re-authenticate');\n }\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n let result;\n try {\n result = options.mode === 'new' ? await signInWithPopup(auth, provider) : await linkWithPopup(requireUser(auth), provider);\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n const credential = OAuthProvider.credentialFromResult(result);\n const response: KitAppleResponse = {\n ...emptyAppleResponse(),\n email: result.user?.email ?? null,\n identityToken: credential?.idToken ?? null,\n authorizationCode: credential?.accessToken ?? null,\n };\n await options.success?.({ response, mode: options.mode });\n return { status: true };\n } finally {\n await options.finally?.();\n }\n};\n\nconst emptyAppleResponse = (): KitAppleResponse => ({\n user: null,\n email: null,\n givenName: null,\n familyName: null,\n identityToken: null,\n authorizationCode: null,\n});\n\nconst requireUser = (auth: Auth) => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link');\n }\n return user;\n};\n","// Social login (Facebook / Apple). Its own entry point so only apps that use it pull in the native\n// plugins `@capacitor-community/facebook-login` and `@capacitor-community/apple-sign-in`; the core\n// `auth-firebase` entry stays free of them.\n//\n// Public surface is curated: two bundled flows plus their option types. The nonce util, the error\n// classifier and the 3-mode credential state machine are internal implementation details.\nexport * from './kit-social';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AAwEA;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,KAAY;IAC5C,MAAM,OAAO,GAAG,gEAAgE;IAChF,IAAI,KAAK,GAAG,EAAE;AACd,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AAC/B,QAAA,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC9D;AACA,IAAA,OAAO,KAAK;AACd,CAAC;AAED,MAAM,kBAAkB,GAAG,CAAC,CAAU,KAA2B;AAC/D,IAAA,MAAM,IAAI,GAAI,CAAmC,EAAE,IAAI;AACvD,IAAA,IAAI,IAAI,KAAK,gCAAgC,EAAE;AAC7C,QAAA,OAAO,gBAAgB;IACzB;AACA,IAAA,IAAI,IAAI,KAAK,qBAAqB,EAAE;AAClC,QAAA,OAAO,WAAW;IACpB;AACA,IAAA,OAAO,OAAO;AAChB,CAAC;AAED;;;;;;;;AAQG;AACH,MAAM,oBAAoB,GAAG,OAC3B,IAAU,EACV,UAA0B,EAC1B,IAAkB,EAClB,OAGC,KACmB;AACpB,IAAA,IAAI;AACF,QAAA,IAAI,IAAI,CAAC,IAAI,KAAK,KAAK,EAAE;A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jectionToken, makeEnvironmentProviders } from '@angular/core';
2
2
  import { Capacitor } from '@capacitor/core';
3
- import { provideFirebaseApp, initializeApp, getApp } from '@angular/fire/app';
4
- import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, sendEmailVerification, signOut, sendPasswordResetEmail, unlink, updateEmail, updatePassword, signInAnonymously, linkWithCredential, EmailAuthProvider, onAuthStateChanged, reauthenticateWithCredential } from '@angular/fire/auth';
5
- import { provideAnalytics, getAnalytics } from '@angular/fire/analytics';
3
+ import { getApps, getApp, initializeApp } from 'firebase/app';
4
+ import { initializeAuth, indexedDBLocalPersistence, getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, sendEmailVerification, signOut, sendPasswordResetEmail, unlink, updateEmail, updatePassword, signInAnonymously, linkWithCredential, EmailAuthProvider, onAuthStateChanged, reauthenticateWithCredential } from 'firebase/auth';
5
+ import { getAnalytics } from 'firebase/analytics';
6
6
  import { Observable } from 'rxjs';
7
7
 
8
8
  /**
9
9
  * DI token for the Firebase `Auth` instance.
10
10
  *
11
11
  * @remarks
12
- * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the
13
- * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned
14
- * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}
15
- * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.
12
+ * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of importing `getAuth()` in the app, so the
13
+ * Firebase SDK wiring stays isolated inside the kit: only {@link provideKitFirebase} (which binds
14
+ * this token) touches initialization; every consumer keeps injecting `KIT_FIREBASE_AUTH`.
16
15
  *
17
- * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —
18
- * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).
16
+ * The value is a `firebase/auth` `Auth` — the SDK type is exposed directly, not re-abstracted.
19
17
  */
20
18
  const KIT_FIREBASE_AUTH = new InjectionToken('@rdlabo/ionic-angular-kit:firebase-auth');
19
+ /** Initialize (or reuse) the Firebase app for the kit's config. */
20
+ const kitFirebaseApp = (config) => (getApps().length ? getApp() : initializeApp(config.firebaseConfig));
21
21
  /**
22
22
  * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.
23
23
  *
24
24
  * @remarks
25
- * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its
26
- * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the
27
- * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from
28
- * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web
29
- * it uses the default (`getAuth`).
25
+ * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` with one call.
26
+ * Firebase is initialized eagerly with the vanilla `firebase/app` + `firebase/auth` SDK (no
27
+ * `@angular/fire`), and the resulting `Auth` is bound to {@link KIT_FIREBASE_AUTH}. On a native
28
+ * platform the persistence uses `indexedDBLocalPersistence`; on the web it uses the default
29
+ * (`getAuth`). Apps inject {@link KIT_FIREBASE_AUTH} and call the kit's flow functions, keeping the
30
+ * Firebase SDK isolated inside the kit.
30
31
  *
31
32
  * @example
32
33
  * ```ts
@@ -35,19 +36,22 @@ const KIT_FIREBASE_AUTH = new InjectionToken('@rdlabo/ionic-angular-kit:firebase
35
36
  * });
36
37
  * ```
37
38
  */
38
- const provideKitFirebase = (config) => makeEnvironmentProviders([
39
- provideFirebaseApp(() => initializeApp(config.firebaseConfig)),
40
- provideAuth(() => Capacitor.isNativePlatform()
41
- ? initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })
42
- : getAuth()),
43
- // Expose @angular/fire's Auth instance under the kit token; phase 3 rebinds this to a
44
- // firebase/auth instance without touching any consumer.
45
- { provide: KIT_FIREBASE_AUTH, useExisting: Auth },
46
- ]);
39
+ const provideKitFirebase = (config) => {
40
+ const app = kitFirebaseApp(config);
41
+ const auth = Capacitor.isNativePlatform() ? initializeAuth(app, { persistence: indexedDBLocalPersistence }) : getAuth(app);
42
+ return makeEnvironmentProviders([{ provide: KIT_FIREBASE_AUTH, useValue: auth }]);
43
+ };
47
44
  /**
48
45
  * Wire Firebase Analytics into the application (optional; only the apps that use it call this).
46
+ *
47
+ * @remarks
48
+ * Analytics is initialized eagerly against the already-initialized Firebase app, so this must be
49
+ * called after (or alongside) {@link provideKitFirebase}.
49
50
  */
50
- const provideKitFirebaseAnalytics = () => makeEnvironmentProviders([provideAnalytics(() => getAnalytics())]);
51
+ const provideKitFirebaseAnalytics = () => {
52
+ getAnalytics(getApp());
53
+ return makeEnvironmentProviders([]);
54
+ };
51
55
 
52
56
  /** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */
53
57
  const KIT_DEFAULT_AUTH_TEXT = {
@@ -73,9 +77,9 @@ const KIT_DEFAULT_AUTH_TEXT = {
73
77
  fallbackError: { header: 'エラー', message: '処理に失敗しました' },
74
78
  };
75
79
 
76
- // Ops must come from @angular/fire/auth — not root `firebase/auth`. @angular/fire 21 rc bundles
77
- // firebase@12 while apps often pin firebase@11; calling the wrong copy's signOut/onAuthStateChanged
78
- // against KIT_FIREBASE_AUTH is a silent no-op (logout appears broken fleet-wide).
80
+ // Ops and KIT_FIREBASE_AUTH must resolve to the *same* `firebase/auth` copy. The kit declares
81
+ // `firebase` as a peerDependency so the app's single Firebase install is used everywhere; a second
82
+ // copy would make signOut/onAuthStateChanged against KIT_FIREBASE_AUTH a silent no-op.
79
83
  /** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */
80
84
  const runAuthFlow = async (op, hooks) => {
81
85
  await hooks?.before?.();
@@ -164,8 +168,8 @@ const kitSendEmailVerification = (auth, hooks) => runAuthFlowVoid(async () => {
164
168
  *
165
169
  * @remarks
166
170
  * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the
167
- * same `@angular/fire/auth` module as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch
168
- * cannot silently no-op.
171
+ * same `firebase/auth` copy as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch cannot
172
+ * silently no-op.
169
173
  */
170
174
  const kitUpdateEmail = async (user, newEmail) => {
171
175
  await updateEmail(user, newEmail);
@@ -207,15 +211,14 @@ const kitLinkEmailPassword = (auth, email, password, hooks) => runAuthFlow(async
207
211
  await linked.user.reload();
208
212
  return linked.user;
209
213
  }, hooks);
210
- // Ops come from `@angular/fire/auth` (same firebase copy as KIT_FIREBASE_AUTH). Types stay on
211
- // `firebase/auth` so apps never import the SDK for covered operations.
214
+ // Ops and types come from `firebase/auth` (the single peer-installed copy shared with
215
+ // KIT_FIREBASE_AUTH) so apps never import the SDK for covered operations.
212
216
  /**
213
217
  * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).
214
218
  *
215
219
  * @remarks
216
- * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s
217
- * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on
218
- * teardown.
220
+ * Wraps `firebase/auth`'s `onAuthStateChanged` so consumers get an rxjs stream without pulling in
221
+ * `rxfire`. Emits the current value on subscribe and completes its listener on teardown.
219
222
  *
220
223
  * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)
221
224
  */
@@ -370,10 +373,9 @@ const kitResolveAuthStatus = (user, options) => {
370
373
  return verified ? 'user' : 'confirm';
371
374
  };
372
375
 
373
- // Firebase auth: the flow library for the fleet. `@angular/fire` is used in *one* place only — the
374
- // DI provider (kit-firebase-provider.ts) — so the planned `@angular/fire` → `firebase/auth` swap is
375
- // provider-local. Apps inject `KIT_FIREBASE_AUTH` and call these pure flow functions, never importing
376
- // the SDK for the covered operations.
376
+ // Firebase auth: the flow library for the fleet. The `firebase/auth` SDK is initialized in *one*
377
+ // place only — the DI provider (kit-firebase-provider.ts). Apps inject `KIT_FIREBASE_AUTH` and call
378
+ // these pure flow functions, never importing the SDK for the covered operations.
377
379
  //
378
380
  // The public surface is intentionally curated: dependency wiring plus pure flow functions (each
379
381
  // pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the
@@ -1 +1 @@
1
- {"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase.mjs","sources":["../../../projects/kit/auth-firebase/src/kit-firebase-provider.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth-config.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth.ts","../../../projects/kit/auth-firebase/src/public-api.ts","../../../projects/kit/auth-firebase/src/rdlabo-ionic-angular-kit-auth-firebase.ts"],"sourcesContent":["import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { FirebaseOptions } from '@angular/fire/app';\nimport { getApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';\nimport { Auth, getAuth, indexedDBLocalPersistence, initializeAuth, provideAuth } from '@angular/fire/auth';\nimport { getAnalytics, provideAnalytics } from '@angular/fire/analytics';\nimport type { Auth as FirebaseAuth } from 'firebase/auth';\n\n/**\n * DI token for the Firebase `Auth` instance.\n *\n * @remarks\n * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the\n * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned\n * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}\n * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.\n *\n * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —\n * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).\n */\nexport const KIT_FIREBASE_AUTH = new InjectionToken<FirebaseAuth>('@rdlabo/ionic-angular-kit:firebase-auth');\n\n/** Configuration for {@link provideKitFirebase}. */\nexport interface KitFirebaseConfig {\n /** The Firebase project options (`apiKey`, `authDomain`, `projectId`, …). */\n readonly firebaseConfig: FirebaseOptions;\n}\n\n/**\n * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.\n *\n * @remarks\n * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its\n * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the\n * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from\n * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web\n * it uses the default (`getAuth`).\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [provideKitFirebase({ firebaseConfig: environment.firebase })],\n * });\n * ```\n */\nexport const provideKitFirebase = (config: KitFirebaseConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n provideFirebaseApp(() => initializeApp(config.firebaseConfig)),\n provideAuth(() =>\n Capacitor.isNativePlatform()\n ? initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })\n : getAuth(),\n ),\n // Expose @angular/fire's Auth instance under the kit token; phase 3 rebinds this to a\n // firebase/auth instance without touching any consumer.\n { provide: KIT_FIREBASE_AUTH, useExisting: Auth },\n ]);\n\n/**\n * Wire Firebase Analytics into the application (optional; only the apps that use it call this).\n */\nexport const provideKitFirebaseAnalytics = (): EnvironmentProviders =>\n makeEnvironmentProviders([provideAnalytics(() => getAnalytics())]);\n","/** A user-facing message (alert header + body). */\nexport interface KitAuthMessage {\n readonly header: string;\n readonly message: string;\n}\n\n/**\n * The fleet's canonical Firebase auth error dictionary: error `code` → message, plus a fallback for\n * unmapped codes.\n *\n * @remarks\n * The kit does *not* present errors itself (that's an app side effect). This is offered as an\n * importable constant so an app can render its error alert from a shared, canonical source instead of\n * re-declaring the same five messages. Apps that need `$localize` (i18n) keep their own dictionary;\n * JA-only apps can import {@link KIT_DEFAULT_AUTH_TEXT} and spread it, overriding the odd code.\n *\n * @example\n * ```ts\n * import { KIT_DEFAULT_AUTH_TEXT } from '@rdlabo/ionic-angular-kit/auth-firebase';\n *\n * const AUTH_ERRORS = { ...KIT_DEFAULT_AUTH_TEXT.errors, 'auth/wrong-password': { header: '…', message: '…' } };\n * presentError(code: string) {\n * const msg = AUTH_ERRORS[code] ?? KIT_DEFAULT_AUTH_TEXT.fallbackError;\n * return this.overlay.alertClose(msg);\n * }\n * ```\n */\nexport interface KitAuthText {\n /** Firebase error `code` → message. */\n readonly errors: Readonly<Record<string, KitAuthMessage>>;\n /** Shown when an error has no matching `code`. */\n readonly fallbackError: KitAuthMessage;\n}\n\n/** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */\nexport const KIT_DEFAULT_AUTH_TEXT: KitAuthText = {\n errors: {\n 'auth/invalid-email': { header: 'メールアドレスが間違っています', message: 'メールアドレスのフォーマットが間違っています。ご確認ください。' },\n 'auth/user-not-found': {\n header: 'ユーザが見つかりません',\n message: '入力いただいたユーザは存在しません。登録されていないメールアドレスか、すでに退会しています。',\n },\n 'auth/wrong-password': {\n header: 'パスワードが間違っています',\n message: '入力いただいたパスワードが間違っているか、このユーザはFacebookログインを利用しており、パスワードログインを有効にしていません。',\n },\n 'auth/weak-password': {\n header: '脆弱性があります',\n message: 'パスワードは最低でも6文字以上のものをご利用ください。大文字小文字数字が混在しているとセキュリティを高めることにつながります。',\n },\n 'auth/email-already-in-use': {\n header: 'ユーザが存在しています',\n message: 'このメールアドレスを利用してすでにユーザが作成されています。ログイン画面に戻って、ログインください。',\n },\n },\n fallbackError: { header: 'エラー', message: '処理に失敗しました' },\n};\n","import type { Auth, User, UserCredential } from 'firebase/auth';\nexport type { User, UserCredential } from 'firebase/auth';\n// Ops must come from @angular/fire/auth — not root `firebase/auth`. @angular/fire 21 rc bundles\n// firebase@12 while apps often pin firebase@11; calling the wrong copy's signOut/onAuthStateChanged\n// against KIT_FIREBASE_AUTH is a silent no-op (logout appears broken fleet-wide).\nimport {\n createUserWithEmailAndPassword,\n EmailAuthProvider,\n linkWithCredential,\n onAuthStateChanged,\n reauthenticateWithCredential,\n sendEmailVerification,\n sendPasswordResetEmail,\n signInAnonymously,\n signInWithEmailAndPassword,\n signOut,\n unlink,\n updateEmail,\n updatePassword,\n} from '@angular/fire/auth';\nimport { Observable } from 'rxjs';\n\n/**\n * Uniform lifecycle hooks for the bundled email/password auth flows — where the app hangs its own\n * side effects on a flow.\n *\n * @remarks\n * The kit performs the Firebase operation and renders nothing itself. `before` runs before the op,\n * `success` on success, `error` on failure (with the raw error — the app presents it, from its own\n * dictionary), and `finally` always. Failures are *not* thrown: value flows resolve to `null` and\n * boolean flows to `false`. Return values are awaited and ignored.\n *\n * @example\n * ```ts\n * kitSignIn(auth, email, password, {\n * error: (e) => this.presentAuthError(e), // app's own error dictionary\n * success: () => this.nav.navigateRoot('/'),\n * });\n * ```\n */\nexport interface KitAuthHooks {\n before?: () => void | Promise<unknown>;\n success?: () => void | Promise<unknown>;\n error?: (error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */\nconst runAuthFlow = async <T>(op: () => Promise<T>, hooks?: KitAuthHooks): Promise<T | null> => {\n await hooks?.before?.();\n try {\n const result = await op();\n await hooks?.success?.();\n return result;\n } catch (e) {\n await hooks?.error?.(e);\n return null;\n } finally {\n await hooks?.finally?.();\n }\n};\n\n/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */\nconst runAuthFlowVoid = async (op: () => Promise<void>, hooks?: KitAuthHooks): Promise<boolean> => {\n const result = await runAuthFlow(async () => {\n await op();\n return true as const;\n }, hooks);\n return result === true;\n};\n\n/**\n * Sign in with email and password.\n *\n * @remarks\n * Bundles the Firebase op so the app never imports `signInWithEmailAndPassword` directly (the SDK\n * stays isolated in the kit). Resolves the credential, or `null` on failure (handed to the `error`\n * hook).\n */\nexport const kitSignIn = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> => runAuthFlow(() => signInWithEmailAndPassword(auth, email, password), hooks);\n\n/**\n * Create an account and send the verification email.\n *\n * @remarks\n * Bundles the two-step \"create → send verification\" sequence. Resolves the credential, or `null` on\n * failure. Any success toast is the caller's, via the `success` hook.\n */\nexport const kitSignUp = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await createUserWithEmailAndPassword(auth, email, password);\n await sendEmailVerification(credential.user);\n return credential;\n }, hooks);\n\n/**\n * Sign out.\n *\n * @remarks\n * App-specific cleanup (clearing stores, toasts, navigation, third-party logout) is the caller's,\n * done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.\n */\nexport const kitSignOut = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => signOut(auth), hooks);\n\n/** Send a password-reset email. `true` on success, `false` on failure. */\nexport const kitSendPasswordReset = (auth: Auth, email: string, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);\n\n/**\n * Unlink a linked auth provider (e.g. `'facebook.com'`, `'apple.com'`) from the current user.\n *\n * @remarks\n * Exposed from the core (not `/social`) so an app can unlink without importing `unlink` from\n * `firebase/auth` directly — keeping the invariant that the SDK is only imported inside the kit. Any\n * app-specific step around it (e.g. a backend DELETE before unlinking) goes in the `before` hook.\n * Resolves the updated `User`, or `null` on failure (including when there is no signed-in user).\n */\nexport const kitUnlinkProvider = (auth: Auth, providerId: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(() => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitUnlinkProvider: no signed-in user');\n }\n return unlink(user, providerId);\n }, hooks);\n\n/**\n * (Re-)send the verification email to the signed-in user (a no-op when signed out).\n *\n * @remarks\n * `true` on success (including the signed-out no-op), `false` on failure.\n */\nexport const kitSendEmailVerification = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(async () => {\n const user = auth.currentUser;\n if (user) {\n await sendEmailVerification(user);\n }\n }, hooks);\n\n/**\n * Change the signed-in user's email and send a verification message to the new address.\n *\n * @remarks\n * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the\n * same `@angular/fire/auth` module as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch\n * cannot silently no-op.\n */\nexport const kitUpdateEmail = async (user: User, newEmail: string): Promise<void> => {\n await updateEmail(user, newEmail);\n await sendEmailVerification(user);\n};\n\n/**\n * Change the signed-in user's password.\n *\n * @remarks\n * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication).\n */\nexport const kitUpdatePassword = async (user: User, newPassword: string): Promise<void> => {\n await updatePassword(user, newPassword);\n};\n\n/**\n * Sign in anonymously.\n *\n * @remarks\n * Reloads the user after sign-in so `isAnonymous` and provider data are fresh. Resolves the\n * credential, or `null` on failure (handed to the `error` hook).\n */\nexport const kitSignInAnonymously = (auth: Auth, hooks?: KitAuthHooks): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await signInAnonymously(auth);\n await credential.user.reload();\n return credential;\n }, hooks);\n\n/**\n * Link an email/password credential to the current user (e.g. upgrade an anonymous account).\n *\n * @remarks\n * Reloads the linked user before resolving. Resolves the updated `User`, or `null` on failure.\n */\nexport const kitLinkEmailPassword = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<User | null> =>\n runAuthFlow(async () => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitLinkEmailPassword: no signed-in user');\n }\n const linked = await linkWithCredential(user, EmailAuthProvider.credential(email, password));\n await linked.user.reload();\n return linked.user;\n }, hooks);\n\n// Ops come from `@angular/fire/auth` (same firebase copy as KIT_FIREBASE_AUTH). Types stay on\n// `firebase/auth` so apps never import the SDK for covered operations.\n\n/**\n * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).\n *\n * @remarks\n * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s\n * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on\n * teardown.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n */\nexport const kitAuthState = (auth: Auth): Observable<User | null> =>\n new Observable<User | null>((subscriber) =>\n onAuthStateChanged(\n auth,\n (user) => subscriber.next(user),\n (err) => subscriber.error(err),\n ),\n );\n\n/**\n * The current user's ID token, or `null` when signed out.\n *\n * @remarks\n * For building `Authorization` / bearer headers in interceptors and services. Failure to fetch a\n * token is **thrown, not swallowed** — the caller decides the fallback (e.g. an empty header) as its\n * own side effect, so the kit never silently hides an auth failure.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n * @param forceRefresh - force a token refresh (default `false`)\n * @returns the ID token, or `null` if there is no signed-in user\n * @throws if the token fetch fails for a signed-in user\n */\nexport const kitGetIdToken = (auth: Auth, forceRefresh = false): Promise<string | null> => {\n const user = auth.currentUser;\n return user ? user.getIdToken(forceRefresh) : Promise.resolve(null);\n};\n\n/**\n * Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.\n *\n * @remarks\n * Carries the underlying Firebase error as {@link cause}. A re-auth failure is not always a wrong\n * password (it can be a lockout, an offline network, or an expired session) — use\n * {@link kitIsWrongPasswordError} to tell them apart.\n */\nexport class KitReauthError extends Error {\n constructor(cause?: unknown) {\n super('re-authentication failed');\n this.name = 'KitReauthError';\n this.cause = cause;\n }\n}\n\n/**\n * Firebase error codes that mean \"the current password was wrong\".\n *\n * @remarks\n * Any other re-auth failure (lockout, offline, expired session) must NOT be treated as a wrong\n * password. With email enumeration protection (Firebase v10+) a wrong password is reported as\n * `auth/invalid-credential` rather than `auth/wrong-password`, so both are listed.\n */\nexport const KIT_WRONG_PASSWORD_CODES: ReadonlySet<string> = new Set([\n 'auth/wrong-password',\n 'auth/invalid-credential',\n 'auth/invalid-login-credentials',\n 'auth/missing-password',\n]);\n\n/**\n * Whether an error (typically a {@link KitReauthError}) represents a wrong current password.\n *\n * @param e - the caught error\n */\nexport const kitIsWrongPasswordError = (e: unknown): boolean => {\n const cause = e instanceof KitReauthError ? e.cause : e;\n const code = (cause as { code?: string } | undefined)?.code;\n return code !== undefined && KIT_WRONG_PASSWORD_CODES.has(code);\n};\n\n/**\n * Re-authenticate the current user with their email/password, then run a sensitive mutation.\n *\n * @remarks\n * The one non-trivial mechanic every app cloned before changing email/password: build the\n * `EmailAuthProvider` credential, `reauthenticateWithCredential`, and only on success run `mutate`.\n * Pure — no DI, no UI. A re-auth failure throws {@link KitReauthError}; `mutate`'s own error\n * propagates unwrapped.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param currentPassword - the current password (for the re-auth credential)\n * @param mutate - the change to run once re-authenticated, receiving the current `User`\n * @throws {@link KitReauthError} if there is no signed-in user or re-authentication fails\n */\nexport const kitReauthenticateThenMutate = async (\n auth: Auth,\n currentEmail: string,\n currentPassword: string,\n mutate: (user: User) => Promise<void>,\n): Promise<void> => {\n const user = auth.currentUser;\n if (!user) {\n throw new KitReauthError('no current user');\n }\n try {\n await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));\n } catch (e) {\n throw new KitReauthError(e);\n }\n await mutate(user);\n};\n\n/**\n * The app-supplied side effects for {@link kitReauthWithRetry}.\n *\n * @remarks\n * The kit owns the *control flow* but generates no UI; every user-facing effect (the prompt, the\n * loading overlay) is a callback the app implements, rendering from its own dictionary.\n */\nexport interface KitReauthWithRetryOptions {\n /**\n * Present the current-password prompt.\n *\n * @remarks\n * A side effect — the app presents whatever it likes (e.g. an `ion-alert` with a masked input and\n * dictionary text). Receives `true` when re-prompting after a wrong password.\n *\n * @returns the entered password, or `null` if the user cancels/dismisses\n */\n prompt: (wrongPasswordRetry: boolean) => Promise<string | null>;\n /**\n * The sensitive change to run once re-authenticated.\n *\n * @remarks\n * Keep this pure — just the Firebase op(s) (e.g. `updatePassword(user, next)`). Loading and other\n * UI are side effects handled by {@link withLoading}, not here.\n */\n mutate: (user: User) => Promise<void>;\n /**\n * Wrap the re-authentication + mutation with a loading indicator (a side effect).\n *\n * @remarks\n * Optional. Runs only after a password is entered, around each attempt — so no loading flashes on a\n * cancelled prompt, and it re-shows on a wrong-password retry. The app implements it (e.g.\n * present/dismiss an `ion-loading`).\n */\n withLoading?: (run: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Run the fleet's canonical \"confirm current password → change\" flow, re-prompting in place on a\n * wrong password.\n *\n * @remarks\n * Owns the drift-prone *control flow* (the retry loop, the wrong-password classification every app\n * once got wrong, and when to show loading) while generating **no UI** — the prompt and the loading\n * overlay are {@link KitReauthWithRetryOptions | side-effect callbacks} the app supplies. On a wrong\n * password the loop re-prompts instead of dropping the user out of the flow. Any non-wrong-password\n * re-auth failure (lockout, offline, expired session) and any error from `mutate` are re-thrown —\n * re-auth failures unwrapped to the underlying Firebase error so the caller's error dictionary can\n * read its `code`.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param options - the pure mutation plus the app's prompt / loading side effects\n * @returns `true` if the mutation completed, `false` if the user cancelled\n * @throws the underlying Firebase error on a non-wrong-password failure, or `mutate`'s own error\n */\nexport const kitReauthWithRetry = async (\n auth: Auth,\n currentEmail: string,\n options: KitReauthWithRetryOptions,\n): Promise<boolean> => {\n const run = options.withLoading ?? ((fn) => fn());\n let wrongPasswordRetry = false;\n for (;;) {\n const password = await options.prompt(wrongPasswordRetry);\n if (password === null) {\n return false;\n }\n try {\n await run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));\n return true;\n } catch (e) {\n if (kitIsWrongPasswordError(e)) {\n wrongPasswordRetry = true;\n continue;\n }\n throw e instanceof KitReauthError && e.cause instanceof Error ? e.cause : e;\n }\n }\n};\n\n/** The fleet's 3-state auth status derived from the Firebase user. */\nexport type KitAuthStatus = 'user' | 'confirm' | 'required';\n\n/** Options for {@link kitResolveAuthStatus}. */\nexport interface KitResolveAuthStatusOptions {\n /**\n * Provider IDs that count as verified even without `emailVerified` — a social login (e.g.\n * `'facebook.com'`, `'apple.com'`) has no email-verification step but is a real, trusted account.\n */\n readonly verifiedProviders?: readonly string[];\n /**\n * Extra predicate to treat a signed-in user as fully authed regardless of verification — for an\n * e2e bypass or an anonymous-allowed app. Receives the current user.\n */\n readonly allowWhen?: (user: User) => boolean;\n}\n\n/**\n * Classify a Firebase user into the fleet's 3-state auth status.\n *\n * @remarks\n * `null` (signed out) → `'required'`. A signed-in user is `'user'` when their email is verified, OR\n * they signed in with one of `verifiedProviders`, OR `allowWhen` returns true; otherwise `'confirm'`\n * (signed in but unverified). This is only the shared classification — app-specific side effects\n * around it (reloading the user to refresh `emailVerified`, caching a token) stay in the app.\n *\n * @example\n * ```ts\n * kitResolveAuthStatus(user, {\n * verifiedProviders: ['facebook.com', 'apple.com'],\n * allowWhen: () => environment.e2e,\n * });\n * ```\n */\nexport const kitResolveAuthStatus = (user: User | null, options?: KitResolveAuthStatusOptions): KitAuthStatus => {\n if (user === null) {\n return 'required';\n }\n const verifiedByProvider =\n options?.verifiedProviders?.some((id) => user.providerData.some((p) => p.providerId === id)) ?? false;\n const verified = user.emailVerified || verifiedByProvider || (options?.allowWhen?.(user) ?? false);\n return verified ? 'user' : 'confirm';\n};\n","// Firebase auth: the flow library for the fleet. `@angular/fire` is used in *one* place only — the\n// DI provider (kit-firebase-provider.ts) — so the planned `@angular/fire` → `firebase/auth` swap is\n// provider-local. Apps inject `KIT_FIREBASE_AUTH` and call these pure flow functions, never importing\n// the SDK for the covered operations.\n//\n// The public surface is intentionally curated: dependency wiring plus pure flow functions (each\n// pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the\n// no-throw null/false contract). The re-auth mechanics (kitReauthenticateThenMutate / KitReauthError\n// / KIT_WRONG_PASSWORD_CODES / kitIsWrongPasswordError) are internal details of `kitReauthWithRetry`\n// and are not exported.\n\n// Dependency isolation (DI wiring + the Auth token + analytics).\nexport * from './kit-firebase-provider';\n\n// The canonical error dictionary — an importable constant for apps to render their own error alert.\nexport { KIT_DEFAULT_AUTH_TEXT } from './kit-firebase-auth-config';\nexport type { KitAuthText, KitAuthMessage } from './kit-firebase-auth-config';\n\n// Adapters + pure flow functions.\nexport {\n kitAuthState,\n kitGetIdToken,\n kitResolveAuthStatus,\n kitSignIn,\n kitSignUp,\n kitSignOut,\n kitSendPasswordReset,\n kitSendEmailVerification,\n kitUpdateEmail,\n kitUpdatePassword,\n kitSignInAnonymously,\n kitLinkEmailPassword,\n kitUnlinkProvider,\n kitReauthWithRetry,\n} from './kit-firebase-auth';\nexport type {\n KitAuthHooks,\n KitAuthStatus,\n KitResolveAuthStatusOptions,\n KitReauthWithRetryOptions,\n User,\n UserCredential,\n} from './kit-firebase-auth';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;AASA;;;;;;;;;;;AAWG;MACU,iBAAiB,GAAG,IAAI,cAAc,CAAe,yCAAyC;AAQ3G;;;;;;;;;;;;;;;;AAgBG;AACI,MAAM,kBAAkB,GAAG,CAAC,MAAyB,KAC1D,wBAAwB,CAAC;IACvB,kBAAkB,CAAC,MAAM,aAAa,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAC9D,IAAA,WAAW,CAAC,MACV,SAAS,CAAC,gBAAgB;UACtB,cAAc,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,yBAAyB,EAAE;UACnE,OAAO,EAAE,CACd;;;AAGD,IAAA,EAAE,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,IAAI,EAAE;AAClD,CAAA;AAEH;;AAEG;MACU,2BAA2B,GAAG,MACzC,wBAAwB,CAAC,CAAC,gBAAgB,CAAC,MAAM,YAAY,EAAE,CAAC,CAAC;;AC7BnE;AACO,MAAM,qBAAqB,GAAgB;AAChD,IAAA,MAAM,EAAE;QACN,oBAAoB,EAAE,EAAE,MAAM,EAAE,iBAAiB,EAAE,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ACtB,OAAO,EAAE,iBAAiB,EAAE,IAAI,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,KAAK;AACvG,IAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,IAAI,kBAAkB,KAAK,OAAO,EAAE,SAAS,GAAG,IAAI,CAAC,IAAI,KAAK,CAAC;IAClG,OAAO,QAAQ,GAAG,MAAM,GAAG,SAAS;AACtC;;AChcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;ACXA;;AAEG;;;;"}
1
+ {"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase.mjs","sources":["../../../projects/kit/auth-firebase/src/kit-firebase-provider.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth-config.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth.ts","../../../projects/kit/auth-firebase/src/public-api.ts","../../../projects/kit/auth-firebase/src/rdlabo-ionic-angular-kit-auth-firebase.ts"],"sourcesContent":["import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { FirebaseApp, FirebaseOptions } from 'firebase/app';\nimport { getApp, getApps, initializeApp } from 'firebase/app';\nimport type { Auth as FirebaseAuth } from 'firebase/auth';\nimport { getAuth, indexedDBLocalPersistence, initializeAuth } from 'firebase/auth';\nimport { getAnalytics } from 'firebase/analytics';\n\n/**\n * DI token for the Firebase `Auth` instance.\n *\n * @remarks\n * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of importing `getAuth()` in the app, so the\n * Firebase SDK wiring stays isolated inside the kit: only {@link provideKitFirebase} (which binds\n * this token) touches initialization; every consumer keeps injecting `KIT_FIREBASE_AUTH`.\n *\n * The value is a `firebase/auth` `Auth` — the SDK type is exposed directly, not re-abstracted.\n */\nexport const KIT_FIREBASE_AUTH = new InjectionToken<FirebaseAuth>('@rdlabo/ionic-angular-kit:firebase-auth');\n\n/** Configuration for {@link provideKitFirebase}. */\nexport interface KitFirebaseConfig {\n /** The Firebase project options (`apiKey`, `authDomain`, `projectId`, …). */\n readonly firebaseConfig: FirebaseOptions;\n}\n\n/** Initialize (or reuse) the Firebase app for the kit's config. */\nconst kitFirebaseApp = (config: KitFirebaseConfig): FirebaseApp => (getApps().length ? getApp() : initializeApp(config.firebaseConfig));\n\n/**\n * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.\n *\n * @remarks\n * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` with one call.\n * Firebase is initialized eagerly with the vanilla `firebase/app` + `firebase/auth` SDK (no\n * `@angular/fire`), and the resulting `Auth` is bound to {@link KIT_FIREBASE_AUTH}. On a native\n * platform the persistence uses `indexedDBLocalPersistence`; on the web it uses the default\n * (`getAuth`). Apps inject {@link KIT_FIREBASE_AUTH} and call the kit's flow functions, keeping the\n * Firebase SDK isolated inside the kit.\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [provideKitFirebase({ firebaseConfig: environment.firebase })],\n * });\n * ```\n */\nexport const provideKitFirebase = (config: KitFirebaseConfig): EnvironmentProviders => {\n const app = kitFirebaseApp(config);\n const auth = Capacitor.isNativePlatform() ? initializeAuth(app, { persistence: indexedDBLocalPersistence }) : getAuth(app);\n return makeEnvironmentProviders([{ provide: KIT_FIREBASE_AUTH, useValue: auth }]);\n};\n\n/**\n * Wire Firebase Analytics into the application (optional; only the apps that use it call this).\n *\n * @remarks\n * Analytics is initialized eagerly against the already-initialized Firebase app, so this must be\n * called after (or alongside) {@link provideKitFirebase}.\n */\nexport const provideKitFirebaseAnalytics = (): EnvironmentProviders => {\n getAnalytics(getApp());\n return makeEnvironmentProviders([]);\n};\n","/** A user-facing message (alert header + body). */\nexport interface KitAuthMessage {\n readonly header: string;\n readonly message: string;\n}\n\n/**\n * The fleet's canonical Firebase auth error dictionary: error `code` → message, plus a fallback for\n * unmapped codes.\n *\n * @remarks\n * The kit does *not* present errors itself (that's an app side effect). This is offered as an\n * importable constant so an app can render its error alert from a shared, canonical source instead of\n * re-declaring the same five messages. Apps that need `$localize` (i18n) keep their own dictionary;\n * JA-only apps can import {@link KIT_DEFAULT_AUTH_TEXT} and spread it, overriding the odd code.\n *\n * @example\n * ```ts\n * import { KIT_DEFAULT_AUTH_TEXT } from '@rdlabo/ionic-angular-kit/auth-firebase';\n *\n * const AUTH_ERRORS = { ...KIT_DEFAULT_AUTH_TEXT.errors, 'auth/wrong-password': { header: '…', message: '…' } };\n * presentError(code: string) {\n * const msg = AUTH_ERRORS[code] ?? KIT_DEFAULT_AUTH_TEXT.fallbackError;\n * return this.overlay.alertClose(msg);\n * }\n * ```\n */\nexport interface KitAuthText {\n /** Firebase error `code` → message. */\n readonly errors: Readonly<Record<string, KitAuthMessage>>;\n /** Shown when an error has no matching `code`. */\n readonly fallbackError: KitAuthMessage;\n}\n\n/** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */\nexport const KIT_DEFAULT_AUTH_TEXT: KitAuthText = {\n errors: {\n 'auth/invalid-email': { header: 'メールアドレスが間違っています', message: 'メールアドレスのフォーマットが間違っています。ご確認ください。' },\n 'auth/user-not-found': {\n header: 'ユーザが見つかりません',\n message: '入力いただいたユーザは存在しません。登録されていないメールアドレスか、すでに退会しています。',\n },\n 'auth/wrong-password': {\n header: 'パスワードが間違っています',\n message: '入力いただいたパスワードが間違っているか、このユーザはFacebookログインを利用しており、パスワードログインを有効にしていません。',\n },\n 'auth/weak-password': {\n header: '脆弱性があります',\n message: 'パスワードは最低でも6文字以上のものをご利用ください。大文字小文字数字が混在しているとセキュリティを高めることにつながります。',\n },\n 'auth/email-already-in-use': {\n header: 'ユーザが存在しています',\n message: 'このメールアドレスを利用してすでにユーザが作成されています。ログイン画面に戻って、ログインください。',\n },\n },\n fallbackError: { header: 'エラー', message: '処理に失敗しました' },\n};\n","import type { Auth, User, UserCredential } from 'firebase/auth';\nexport type { User, UserCredential } from 'firebase/auth';\n// Ops and KIT_FIREBASE_AUTH must resolve to the *same* `firebase/auth` copy. The kit declares\n// `firebase` as a peerDependency so the app's single Firebase install is used everywhere; a second\n// copy would make signOut/onAuthStateChanged against KIT_FIREBASE_AUTH a silent no-op.\nimport {\n createUserWithEmailAndPassword,\n EmailAuthProvider,\n linkWithCredential,\n onAuthStateChanged,\n reauthenticateWithCredential,\n sendEmailVerification,\n sendPasswordResetEmail,\n signInAnonymously,\n signInWithEmailAndPassword,\n signOut,\n unlink,\n updateEmail,\n updatePassword,\n} from 'firebase/auth';\nimport { Observable } from 'rxjs';\n\n/**\n * Uniform lifecycle hooks for the bundled email/password auth flows — where the app hangs its own\n * side effects on a flow.\n *\n * @remarks\n * The kit performs the Firebase operation and renders nothing itself. `before` runs before the op,\n * `success` on success, `error` on failure (with the raw error — the app presents it, from its own\n * dictionary), and `finally` always. Failures are *not* thrown: value flows resolve to `null` and\n * boolean flows to `false`. Return values are awaited and ignored.\n *\n * @example\n * ```ts\n * kitSignIn(auth, email, password, {\n * error: (e) => this.presentAuthError(e), // app's own error dictionary\n * success: () => this.nav.navigateRoot('/'),\n * });\n * ```\n */\nexport interface KitAuthHooks {\n before?: () => void | Promise<unknown>;\n success?: () => void | Promise<unknown>;\n error?: (error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */\nconst runAuthFlow = async <T>(op: () => Promise<T>, hooks?: KitAuthHooks): Promise<T | null> => {\n await hooks?.before?.();\n try {\n const result = await op();\n await hooks?.success?.();\n return result;\n } catch (e) {\n await hooks?.error?.(e);\n return null;\n } finally {\n await hooks?.finally?.();\n }\n};\n\n/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */\nconst runAuthFlowVoid = async (op: () => Promise<void>, hooks?: KitAuthHooks): Promise<boolean> => {\n const result = await runAuthFlow(async () => {\n await op();\n return true as const;\n }, hooks);\n return result === true;\n};\n\n/**\n * Sign in with email and password.\n *\n * @remarks\n * Bundles the Firebase op so the app never imports `signInWithEmailAndPassword` directly (the SDK\n * stays isolated in the kit). Resolves the credential, or `null` on failure (handed to the `error`\n * hook).\n */\nexport const kitSignIn = (auth: Auth, email: string, password: string, hooks?: KitAuthHooks): Promise<UserCredential | null> =>\n runAuthFlow(() => signInWithEmailAndPassword(auth, email, password), hooks);\n\n/**\n * Create an account and send the verification email.\n *\n * @remarks\n * Bundles the two-step \"create → send verification\" sequence. Resolves the credential, or `null` on\n * failure. Any success toast is the caller's, via the `success` hook.\n */\nexport const kitSignUp = (auth: Auth, email: string, password: string, hooks?: KitAuthHooks): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await createUserWithEmailAndPassword(auth, email, password);\n await sendEmailVerification(credential.user);\n return credential;\n }, hooks);\n\n/**\n * Sign out.\n *\n * @remarks\n * App-specific cleanup (clearing stores, toasts, navigation, third-party logout) is the caller's,\n * done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.\n */\nexport const kitSignOut = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> => runAuthFlowVoid(() => signOut(auth), hooks);\n\n/** Send a password-reset email. `true` on success, `false` on failure. */\nexport const kitSendPasswordReset = (auth: Auth, email: string, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);\n\n/**\n * Unlink a linked auth provider (e.g. `'facebook.com'`, `'apple.com'`) from the current user.\n *\n * @remarks\n * Exposed from the core (not `/social`) so an app can unlink without importing `unlink` from\n * `firebase/auth` directly — keeping the invariant that the SDK is only imported inside the kit. Any\n * app-specific step around it (e.g. a backend DELETE before unlinking) goes in the `before` hook.\n * Resolves the updated `User`, or `null` on failure (including when there is no signed-in user).\n */\nexport const kitUnlinkProvider = (auth: Auth, providerId: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(() => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitUnlinkProvider: no signed-in user');\n }\n return unlink(user, providerId);\n }, hooks);\n\n/**\n * (Re-)send the verification email to the signed-in user (a no-op when signed out).\n *\n * @remarks\n * `true` on success (including the signed-out no-op), `false` on failure.\n */\nexport const kitSendEmailVerification = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(async () => {\n const user = auth.currentUser;\n if (user) {\n await sendEmailVerification(user);\n }\n }, hooks);\n\n/**\n * Change the signed-in user's email and send a verification message to the new address.\n *\n * @remarks\n * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the\n * same `firebase/auth` copy as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch cannot\n * silently no-op.\n */\nexport const kitUpdateEmail = async (user: User, newEmail: string): Promise<void> => {\n await updateEmail(user, newEmail);\n await sendEmailVerification(user);\n};\n\n/**\n * Change the signed-in user's password.\n *\n * @remarks\n * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication).\n */\nexport const kitUpdatePassword = async (user: User, newPassword: string): Promise<void> => {\n await updatePassword(user, newPassword);\n};\n\n/**\n * Sign in anonymously.\n *\n * @remarks\n * Reloads the user after sign-in so `isAnonymous` and provider data are fresh. Resolves the\n * credential, or `null` on failure (handed to the `error` hook).\n */\nexport const kitSignInAnonymously = (auth: Auth, hooks?: KitAuthHooks): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await signInAnonymously(auth);\n await credential.user.reload();\n return credential;\n }, hooks);\n\n/**\n * Link an email/password credential to the current user (e.g. upgrade an anonymous account).\n *\n * @remarks\n * Reloads the linked user before resolving. Resolves the updated `User`, or `null` on failure.\n */\nexport const kitLinkEmailPassword = (auth: Auth, email: string, password: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(async () => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitLinkEmailPassword: no signed-in user');\n }\n const linked = await linkWithCredential(user, EmailAuthProvider.credential(email, password));\n await linked.user.reload();\n return linked.user;\n }, hooks);\n\n// Ops and types come from `firebase/auth` (the single peer-installed copy shared with\n// KIT_FIREBASE_AUTH) so apps never import the SDK for covered operations.\n\n/**\n * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).\n *\n * @remarks\n * Wraps `firebase/auth`'s `onAuthStateChanged` so consumers get an rxjs stream without pulling in\n * `rxfire`. Emits the current value on subscribe and completes its listener on teardown.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n */\nexport const kitAuthState = (auth: Auth): Observable<User | null> =>\n new Observable<User | null>((subscriber) =>\n onAuthStateChanged(\n auth,\n (user) => subscriber.next(user),\n (err) => subscriber.error(err),\n ),\n );\n\n/**\n * The current user's ID token, or `null` when signed out.\n *\n * @remarks\n * For building `Authorization` / bearer headers in interceptors and services. Failure to fetch a\n * token is **thrown, not swallowed** — the caller decides the fallback (e.g. an empty header) as its\n * own side effect, so the kit never silently hides an auth failure.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n * @param forceRefresh - force a token refresh (default `false`)\n * @returns the ID token, or `null` if there is no signed-in user\n * @throws if the token fetch fails for a signed-in user\n */\nexport const kitGetIdToken = (auth: Auth, forceRefresh = false): Promise<string | null> => {\n const user = auth.currentUser;\n return user ? user.getIdToken(forceRefresh) : Promise.resolve(null);\n};\n\n/**\n * Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.\n *\n * @remarks\n * Carries the underlying Firebase error as {@link cause}. A re-auth failure is not always a wrong\n * password (it can be a lockout, an offline network, or an expired session) — use\n * {@link kitIsWrongPasswordError} to tell them apart.\n */\nexport class KitReauthError extends Error {\n constructor(cause?: unknown) {\n super('re-authentication failed');\n this.name = 'KitReauthError';\n this.cause = cause;\n }\n}\n\n/**\n * Firebase error codes that mean \"the current password was wrong\".\n *\n * @remarks\n * Any other re-auth failure (lockout, offline, expired session) must NOT be treated as a wrong\n * password. With email enumeration protection (Firebase v10+) a wrong password is reported as\n * `auth/invalid-credential` rather than `auth/wrong-password`, so both are listed.\n */\nexport const KIT_WRONG_PASSWORD_CODES: ReadonlySet<string> = new Set([\n 'auth/wrong-password',\n 'auth/invalid-credential',\n 'auth/invalid-login-credentials',\n 'auth/missing-password',\n]);\n\n/**\n * Whether an error (typically a {@link KitReauthError}) represents a wrong current password.\n *\n * @param e - the caught error\n */\nexport const kitIsWrongPasswordError = (e: unknown): boolean => {\n const cause = e instanceof KitReauthError ? e.cause : e;\n const code = (cause as { code?: string } | undefined)?.code;\n return code !== undefined && KIT_WRONG_PASSWORD_CODES.has(code);\n};\n\n/**\n * Re-authenticate the current user with their email/password, then run a sensitive mutation.\n *\n * @remarks\n * The one non-trivial mechanic every app cloned before changing email/password: build the\n * `EmailAuthProvider` credential, `reauthenticateWithCredential`, and only on success run `mutate`.\n * Pure — no DI, no UI. A re-auth failure throws {@link KitReauthError}; `mutate`'s own error\n * propagates unwrapped.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param currentPassword - the current password (for the re-auth credential)\n * @param mutate - the change to run once re-authenticated, receiving the current `User`\n * @throws {@link KitReauthError} if there is no signed-in user or re-authentication fails\n */\nexport const kitReauthenticateThenMutate = async (\n auth: Auth,\n currentEmail: string,\n currentPassword: string,\n mutate: (user: User) => Promise<void>,\n): Promise<void> => {\n const user = auth.currentUser;\n if (!user) {\n throw new KitReauthError('no current user');\n }\n try {\n await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));\n } catch (e) {\n throw new KitReauthError(e);\n }\n await mutate(user);\n};\n\n/**\n * The app-supplied side effects for {@link kitReauthWithRetry}.\n *\n * @remarks\n * The kit owns the *control flow* but generates no UI; every user-facing effect (the prompt, the\n * loading overlay) is a callback the app implements, rendering from its own dictionary.\n */\nexport interface KitReauthWithRetryOptions {\n /**\n * Present the current-password prompt.\n *\n * @remarks\n * A side effect — the app presents whatever it likes (e.g. an `ion-alert` with a masked input and\n * dictionary text). Receives `true` when re-prompting after a wrong password.\n *\n * @returns the entered password, or `null` if the user cancels/dismisses\n */\n prompt: (wrongPasswordRetry: boolean) => Promise<string | null>;\n /**\n * The sensitive change to run once re-authenticated.\n *\n * @remarks\n * Keep this pure — just the Firebase op(s) (e.g. `updatePassword(user, next)`). Loading and other\n * UI are side effects handled by {@link withLoading}, not here.\n */\n mutate: (user: User) => Promise<void>;\n /**\n * Wrap the re-authentication + mutation with a loading indicator (a side effect).\n *\n * @remarks\n * Optional. Runs only after a password is entered, around each attempt — so no loading flashes on a\n * cancelled prompt, and it re-shows on a wrong-password retry. The app implements it (e.g.\n * present/dismiss an `ion-loading`).\n */\n withLoading?: (run: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Run the fleet's canonical \"confirm current password → change\" flow, re-prompting in place on a\n * wrong password.\n *\n * @remarks\n * Owns the drift-prone *control flow* (the retry loop, the wrong-password classification every app\n * once got wrong, and when to show loading) while generating **no UI** — the prompt and the loading\n * overlay are {@link KitReauthWithRetryOptions | side-effect callbacks} the app supplies. On a wrong\n * password the loop re-prompts instead of dropping the user out of the flow. Any non-wrong-password\n * re-auth failure (lockout, offline, expired session) and any error from `mutate` are re-thrown —\n * re-auth failures unwrapped to the underlying Firebase error so the caller's error dictionary can\n * read its `code`.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param options - the pure mutation plus the app's prompt / loading side effects\n * @returns `true` if the mutation completed, `false` if the user cancelled\n * @throws the underlying Firebase error on a non-wrong-password failure, or `mutate`'s own error\n */\nexport const kitReauthWithRetry = async (auth: Auth, currentEmail: string, options: KitReauthWithRetryOptions): Promise<boolean> => {\n const run = options.withLoading ?? ((fn) => fn());\n let wrongPasswordRetry = false;\n for (;;) {\n const password = await options.prompt(wrongPasswordRetry);\n if (password === null) {\n return false;\n }\n try {\n await run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));\n return true;\n } catch (e) {\n if (kitIsWrongPasswordError(e)) {\n wrongPasswordRetry = true;\n continue;\n }\n throw e instanceof KitReauthError && e.cause instanceof Error ? e.cause : e;\n }\n }\n};\n\n/** The fleet's 3-state auth status derived from the Firebase user. */\nexport type KitAuthStatus = 'user' | 'confirm' | 'required';\n\n/** Options for {@link kitResolveAuthStatus}. */\nexport interface KitResolveAuthStatusOptions {\n /**\n * Provider IDs that count as verified even without `emailVerified` — a social login (e.g.\n * `'facebook.com'`, `'apple.com'`) has no email-verification step but is a real, trusted account.\n */\n readonly verifiedProviders?: readonly string[];\n /**\n * Extra predicate to treat a signed-in user as fully authed regardless of verification — for an\n * e2e bypass or an anonymous-allowed app. Receives the current user.\n */\n readonly allowWhen?: (user: User) => boolean;\n}\n\n/**\n * Classify a Firebase user into the fleet's 3-state auth status.\n *\n * @remarks\n * `null` (signed out) → `'required'`. A signed-in user is `'user'` when their email is verified, OR\n * they signed in with one of `verifiedProviders`, OR `allowWhen` returns true; otherwise `'confirm'`\n * (signed in but unverified). This is only the shared classification — app-specific side effects\n * around it (reloading the user to refresh `emailVerified`, caching a token) stay in the app.\n *\n * @example\n * ```ts\n * kitResolveAuthStatus(user, {\n * verifiedProviders: ['facebook.com', 'apple.com'],\n * allowWhen: () => environment.e2e,\n * });\n * ```\n */\nexport const kitResolveAuthStatus = (user: User | null, options?: KitResolveAuthStatusOptions): KitAuthStatus => {\n if (user === null) {\n return 'required';\n }\n const verifiedByProvider = options?.verifiedProviders?.some((id) => user.providerData.some((p) => p.providerId === id)) ?? false;\n const verified = user.emailVerified || verifiedByProvider || (options?.allowWhen?.(user) ?? false);\n return verified ? 'user' : 'confirm';\n};\n","// Firebase auth: the flow library for the fleet. The `firebase/auth` SDK is initialized in *one*\n// place only — the DI provider (kit-firebase-provider.ts). Apps inject `KIT_FIREBASE_AUTH` and call\n// these pure flow functions, never importing the SDK for the covered operations.\n//\n// The public surface is intentionally curated: dependency wiring plus pure flow functions (each\n// pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the\n// no-throw null/false contract). The re-auth mechanics (kitReauthenticateThenMutate / KitReauthError\n// / KIT_WRONG_PASSWORD_CODES / kitIsWrongPasswordError) are internal details of `kitReauthWithRetry`\n// and are not exported.\n\n// Dependency isolation (DI wiring + the Auth token + analytics).\nexport * from './kit-firebase-provider';\n\n// The canonical error dictionary — an importable constant for apps to render their own error alert.\nexport { KIT_DEFAULT_AUTH_TEXT } from './kit-firebase-auth-config';\nexport type { KitAuthText, KitAuthMessage } from './kit-firebase-auth-config';\n\n// Adapters + pure flow functions.\nexport {\n kitAuthState,\n kitGetIdToken,\n kitResolveAuthStatus,\n kitSignIn,\n kitSignUp,\n kitSignOut,\n kitSendPasswordReset,\n kitSendEmailVerification,\n kitUpdateEmail,\n kitUpdatePassword,\n kitSignInAnonymously,\n kitLinkEmailPassword,\n kitUnlinkProvider,\n kitReauthWithRetry,\n} from './kit-firebase-auth';\nexport type {\n KitAuthHooks,\n KitAuthStatus,\n KitResolveAuthStatusOptions,\n KitReauthWithRetryOptions,\n User,\n UserCredential,\n} from './kit-firebase-auth';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;AASA;;;;;;;;;AASG;MACU,iBAAiB,GAAG,IAAI,cAAc,CAAe,yCAAyC;AAQ3G;AACA,MAAM,cAAc,GAAG,CAAC,MAAyB,MAAmB,OAAO,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,aAAa,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAEvI;;;;;;;;;;;;;;;;;AAiBG;AACI,MAAM,kBAAkB,GAAG,CAAC,MAAyB,KAA0B;AACpF,IAAA,MAAM,GAAG,GAAG,cAAc,CAAC,MAAM,CAAC;IAClC,MAAM,IAAI,GAAG,SAAS,CAAC,gBAAgB,EAAE,GAAG,cAAc,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,yBAAyB,EAAE,CAAC,GAAG,OAAO,CAAC,GAAG,CA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,uBAAuB,CAAC,CAAC,CAAC,EAAE;gBAC9B,kBAAkB,GAAG,IAAI;gBACzB;YACF;AACA,YAAA,MAAM,CAAC,YAAY,cAAc,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;QAC7E;IACF;AACF;AAmBA;;;;;;;;;;;;;;;;AAgBG;MACU,oBAAoB,GAAG,CAAC,IAAiB,EAAE,OAAqC,KAAmB;AAC9G,IAAA,IAAI,IAAI,KAAK,IAAI,EAAE;AACjB,QAAA,OAAO,UAAU;IACnB;AACA,IAAA,MAAM,kBAAkB,GAAG,OAAO,EAAE,iBAAiB,EAAE,IAAI,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,KAAK;AAChI,IAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,IAAI,kBAAkB,KAAK,OAAO,EAAE,SAAS,GAAG,IAAI,CAAC,IAAI,KAAK,CAAC;IAClG,OAAO,QAAQ,GAAG,MAAM,GAAG,SAAS;AACtC;;AC3aA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;ACVA;;AAEG;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"rdlabo-ionic-angular-kit.mjs","sources":["../../../projects/kit/src/lib/storage/kit-storage.service.ts","../../../projects/kit/src/lib/storage/kit-auth-email-store.ts","../../../projects/kit/src/lib/overlay/overlay-config.ts","../../../projects/kit/src/lib/utils/haptics.ts","../../../projects/kit/src/lib/overlay/kit-overlay.controller.ts","../../../projects/kit/src/lib/overlay/kit-loading.controller.ts","../../../projects/kit/src/lib/overlay/kit-reload-alert.controller.ts","../../../projects/kit/src/lib/overlay/kit-auth-failed-alert.ts","../../../projects/kit/src/lib/overlay/kit-language-action-sheet.ts","../../../projects/kit/src/lib/directives/auth-input.directive.ts","../../../projects/kit/src/lib/keyboard/kit-keyboard.ts","../../../projects/kit/src/lib/auth/auth-guards.ts","../../../projects/kit/src/lib/http/kit-http.interceptor.ts","../../../projects/kit/src/lib/utils/array.ts","../../../projects/kit/src/lib/utils/object.ts","../../../projects/kit/src/lib/utils/dom.ts","../../../projects/kit/src/lib/utils/ionic-scroll-event.ts","../../../projects/kit/src/lib/utils/ionic-view-enter.ts","../../../projects/kit/src/public-api.ts","../../../projects/kit/src/rdlabo-ionic-angular-kit.ts"],"sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { Storage } from '@ionic/storage-angular';\n\n/**\n * Thin, typed wrapper around `@ionic/storage-angular`.\n *\n * Starts `create()` exactly once and stores the resulting ready Promise. Every operation awaits\n * that Promise before touching the underlying store, so calls made before initialization completes\n * are queued rather than dropped.\n *\n * @remarks\n * A naive wrapper that reads the store synchronously would silently no-op (or throw) when invoked\n * before `create()` resolves, losing early writes. Awaiting the one-time ready Promise on every\n * operation removes that race without forcing callers to coordinate initialization themselves.\n *\n * @example\n * ```ts\n * constructor(private readonly storage: KitStorageService) {}\n *\n * async ngOnInit(): Promise<void> {\n * await this.storage.set('token', 'abc123');\n * const token = await this.storage.get<string>('token');\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitStorageService {\n /** One-time `create()` ready Promise; awaited before every operation so early calls are not lost. */\n readonly #ready: Promise<Storage> = inject(Storage).create();\n\n /**\n * Persist a value under the given key.\n *\n * @typeParam T - type of the value being stored\n * @param key - key to store the value under\n * @param value - value to persist; overwrites any existing value for the key\n * @returns a Promise that resolves once the value has been written\n * @example\n * ```ts\n * await storage.set('user', { id: 1, name: 'Ada' });\n * ```\n */\n async set<T>(key: string, value: T): Promise<void> {\n await (await this.#ready).set(key, value);\n }\n\n /**\n * Read the value stored under the given key.\n *\n * @typeParam T - expected type of the stored value\n * @param key - key to read\n * @returns the stored value, or `null` when the key is absent\n * @example\n * ```ts\n * const user = await storage.get<{ id: number }>('user');\n * ```\n */\n async get<T>(key: string): Promise<T | null> {\n return (await (await this.#ready).get(key)) ?? null;\n }\n\n /**\n * Remove the value stored under the given key.\n *\n * @param key - key to remove; a no-op when the key is absent\n * @returns a Promise that resolves once the key has been removed\n */\n async remove(key: string): Promise<void> {\n await (await this.#ready).remove(key);\n }\n\n /**\n * Remove every key/value pair from the store.\n *\n * @returns a Promise that resolves once the store has been emptied\n */\n async clear(): Promise<void> {\n await (await this.#ready).clear();\n }\n\n /**\n * List every key currently present in the store.\n *\n * @returns an array of all stored keys\n */\n async keys(): Promise<string[]> {\n return (await this.#ready).keys();\n }\n}\n","/**\n * Remember the email a user last entered on the sign-in form so the field can be prefilled next\n * time (the password is never stored).\n *\n * @remarks\n * Storage-agnostic: the helpers take a minimal async key/value store that {@link KitStorageService}\n * satisfies structurally, so they stay pure and unit-testable without DI. `kitRememberEmail`\n * **validates the address before persisting** — a malformed or partial string is silently ignored,\n * so a garbage entry (or a fat-fingered attempt) never becomes the next prefill. A well-formed email\n * that later fails to sign in is still remembered by design: the user simply re-enters/corrects it.\n *\n * These live in the main entry (next to {@link KitStorageService}) rather than in `auth-firebase`,\n * so the `KitAutofillDirective` can consume them without the main entry depending on the Firebase\n * entry.\n */\n\n/** Minimal async key/value store — structurally satisfied by `KitStorageService`. */\nexport interface KitEmailStore {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n remove(key: string): Promise<void>;\n}\n\n/** Storage key under which the last entered sign-in email is kept. */\nexport const KIT_LAST_AUTH_EMAIL_KEY = 'kit:last-auth-email';\n\n/**\n * Angular's `Validators.email` pattern — a pragmatic, RFC-5322-inspired address check. Kept in sync\n * with `@angular/forms` so a value we persist would also pass the form's own email validation.\n */\nconst EMAIL_REGEXP =\n /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(?:\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\n\n/** Whether `email` is a well-formed address (matches `@angular/forms` `Validators.email`). */\nexport const kitIsValidEmail = (email: string): boolean => EMAIL_REGEXP.test(email);\n\n/**\n * Persist the entered email for next time — but only when it is a well-formed address.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @param email - the entered email; ignored (not stored) when malformed\n * @returns `true` when the value passed validation and was stored, `false` when it was ignored\n */\nexport const kitRememberEmail = async (store: KitEmailStore, email: string): Promise<boolean> => {\n if (!kitIsValidEmail(email)) {\n return false;\n }\n await store.set(KIT_LAST_AUTH_EMAIL_KEY, email);\n return true;\n};\n\n/**\n * Recall the last remembered email.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @returns the stored email, or `null` when none has been remembered\n */\nexport const kitRecallEmail = (store: KitEmailStore): Promise<string | null> =>\n store.get<string>(KIT_LAST_AUTH_EMAIL_KEY);\n\n/**\n * Forget the remembered email.\n *\n * @remarks\n * Called when the user intentionally clears or invalidates the field, so a stale prefill is not\n * resurrected next time.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n */\nexport const kitForgetEmail = (store: KitEmailStore): Promise<void> =>\n store.remove(KIT_LAST_AUTH_EMAIL_KEY);\n","import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\n\n/**\n * User-visible button labels consumed by `KitOverlayController`.\n *\n * @remarks\n * The kit deliberately ships no i18n strings of its own and has no hard dependency on\n * `@angular/localize`. The consuming application always provides these labels: multilingual apps\n * pass `$localize`-resolved strings, single-language apps pass plain literals.\n */\nexport interface KitLabels {\n /** Text for the \"close\" button used by alerts and toasts. */\n readonly close: string;\n /** Text for the \"cancel\" button used by confirmation alerts. */\n readonly cancel: string;\n}\n\n/**\n * Overlay configuration injected via `provideKitOverlay()`.\n *\n * @remarks\n * All fields are required; the consuming application must supply a complete configuration.\n */\nexport interface KitOverlayConfig {\n /** Button labels used across the overlays presented by `KitOverlayController`. */\n readonly labels: KitLabels;\n}\n\n/**\n * Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.\n *\n * @remarks\n * Provide it through {@link provideKitOverlay} rather than registering it directly.\n */\nexport const KIT_OVERLAY_CONFIG = new InjectionToken<KitOverlayConfig>('@rdlabo/ionic-angular-kit:overlay');\n\n/**\n * Wire `KitOverlayController` into the application by providing its button labels.\n *\n * @param config - overlay configuration, including the button labels to inject\n * @returns environment providers to add to the application's provider list\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideKitOverlay({ labels: { close: $localize`Close`, cancel: $localize`Cancel` } }),\n * ],\n * });\n * ```\n */\nexport const provideKitOverlay = (config: KitOverlayConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_OVERLAY_CONFIG, useValue: config }]);\n","import { Capacitor } from '@capacitor/core';\nimport { Haptics, ImpactStyle } from '@capacitor/haptics';\n\n/**\n * Trigger native haptic impact feedback.\n *\n * Delegates to `@capacitor/haptics` `Haptics.impact()` when running on a native platform. On the\n * web (or any non-native platform) it is a no-op and resolves without doing anything.\n *\n * @remarks\n * This haptic side effect was previously bundled implicitly into toast/modal presentation. It has\n * been decoupled into this explicit function so callers opt in to the feedback deliberately, rather\n * than receiving it as a hidden side effect of presenting UI.\n *\n * @param style - The impact intensity to play. Defaults to {@link ImpactStyle.Light}.\n * @returns A promise that resolves once the feedback has been requested (immediately on the web).\n * @example\n * ```ts\n * import { ImpactStyle } from '@capacitor/haptics';\n *\n * // Light tap (default)\n * await kitImpact();\n *\n * // Stronger feedback, e.g. on a confirming action\n * await kitImpact(ImpactStyle.Heavy);\n * ```\n */\nexport const kitImpact = async (style: ImpactStyle = ImpactStyle.Light): Promise<void> => {\n if (Capacitor.isNativePlatform()) {\n await Haptics.impact({ style });\n }\n};\n","import { inject, Injectable } from '@angular/core';\nimport type { InputSignalWithTransform } from '@angular/core';\nimport type { ModalOptions, PopoverOptions, ToastOptions } from '@ionic/angular/standalone';\nimport { AlertController, ModalController, PopoverController, ToastController } from '@ionic/angular/standalone';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Capacitor } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\nimport { kitImpact } from '../utils/haptics';\n\n/**\n * Options for {@link KitOverlayController.presentModal}.\n *\n * @remarks\n * Extends Ionic's `ModalOptions` but omits `component` and `componentProps`, which are passed as\n * dedicated arguments instead.\n */\nexport interface KitModalPresentOptions extends Omit<ModalOptions, 'component' | 'componentProps'> {\n /**\n * When `true`, expand the sheet to its maximum breakpoint while the native keyboard is shown.\n *\n * @remarks\n * Only has an effect on native platforms; ignored on the web.\n */\n watchKeyboard?: boolean;\n}\n\n/**\n * Optional static metadata a modal component may declare to make {@link KitOverlayController.presentModal}\n * type-safe in its dismiss data: the value passed to `dismiss()` is inferred from `modalReturn`.\n *\n * @remarks\n * Props do *not* need to be declared here — {@link KitOverlayController.presentModal} infers them directly\n * from the component's `input()` fields (see {@link ModalPropsOf}), so `input()` stays the single source of\n * truth and can never drift from a hand-written declaration. Only the dismiss-data shape, which has no\n * counterpart on the component, is declared — as a `declare static modalReturn` phantom type with no runtime\n * value, so it adds nothing to the bundle.\n *\n * @example\n * ```ts\n * export class EditPage {\n * declare static modalReturn: { saved: boolean };\n * readonly id = input.required<number>(); // props are inferred from here\n * readonly note = input<string>(); // default-less input() → optional prop\n * }\n *\n * // Caller — `id` is required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\nexport interface ModalMetadata<R = unknown> {\n /** Shape of the data the modal resolves with when dismissed. */\n modalReturn?: R;\n}\n\n/**\n * Write type of a signal `input()` field (unwraps `input.required`, `input()` and transform inputs).\n *\n * @remarks\n * Matched with `any` (not `unknown`): `InputSignalWithTransform`'s `TransformT` is contravariant, so\n * `InputSignal<number>` is not assignable to `InputSignalWithTransform<unknown, unknown>`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InputWriteType<F> = F extends InputSignalWithTransform<any, infer W> ? W : never;\n\n/** Instance type of a component constructor; `never` for non-class components (string / HTMLElement refs). */\ntype InstanceOf<C> = C extends abstract new (...args: never[]) => infer I ? I : never;\n\n/** Keys of the `input()` signal fields on a component instance. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InputFieldKeys<I> = { [K in keyof I]-?: I[K] extends InputSignalWithTransform<any, any> ? K : never }[keyof I];\n\n/**\n * Props object inferred from a component's `input()` fields. Required vs. optional is decided by the write\n * type: `input.required<T>()` / `input<T>(default)` yield `T` (no `undefined`) → required prop, while a\n * default-less `input<T>()` yields `T | undefined` → optional prop.\n *\n * @remarks\n * Angular's types cannot distinguish `input.required<T>()` from a defaulted `input<T>(default)` — both are\n * `InputSignal<T>` — so a defaulted input is (safely) treated as required. Declare inputs you want to omit at\n * the call site as default-less `input<T>()`.\n */\ntype ModalPropsOf<I> = { [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? never : K]: InputWriteType<I[K]> } & {\n [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? K : never]?: InputWriteType<I[K]>;\n};\n\n/** `input()` keys whose write type excludes `undefined` (required / defaulted inputs). Empty when none. */\ntype RequiredInputKeys<I> = { [K in InputFieldKeys<I>]: undefined extends InputWriteType<I[K]> ? never : K }[InputFieldKeys<I>];\n\n/**\n * Dismiss-data type inferred from a component's static {@link ModalMetadata.modalReturn}. A component that\n * declares no `modalReturn` resolves to `void`: it is treated as returning no dismiss data, so the compiler\n * rejects any attempt to read the result. Declare `modalReturn` on modals that do resolve with data.\n */\ntype ModalReturnOf<C> = C extends { modalReturn: infer R } ? R : void;\n\n/** Loose trailing args (optional, untyped props) — used when a component exposes no signal `input()` fields. */\ntype LooseModalPresentArgs = [componentProps?: ModalOptions['componentProps'], options?: KitModalPresentOptions];\n\n/**\n * Trailing `presentModal` args derived from a component's `input()` fields: props are inferred and typed via\n * {@link ModalPropsOf}. When the component declares at least one required input the props argument is required;\n * when every input is optional the props argument itself is optional. Components with no signal inputs (plain\n * classes, `@Input()`-decorator components, or non-class refs) fall back to loose, untyped props.\n */\ntype ModalPresentArgs<C, I = InstanceOf<C>> = [I] extends [never]\n ? LooseModalPresentArgs\n : [InputFieldKeys<I>] extends [never]\n ? LooseModalPresentArgs\n : [RequiredInputKeys<I>] extends [never]\n ? [componentProps?: ModalPropsOf<I>, options?: KitModalPresentOptions]\n : [componentProps: ModalPropsOf<I>, options?: KitModalPresentOptions];\n\nconst BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX = 8;\n\n/**\n * Returns a visible `ion-tab-bar` suitable for anchoring a bottom toast above it.\n *\n * Skips `slot=\"top\"` bars (e.g. airlec desktop layout) and prefers the bar closest to the viewport bottom\n * when multiple candidates exist.\n */\nfunction findVisibleBottomTabBar(): HTMLElement | undefined {\n let best: HTMLElement | undefined;\n let bestBottom = -1;\n\n for (const tabBar of Array.from(document.querySelectorAll('ion-tab-bar'))) {\n if (!(tabBar instanceof HTMLElement)) continue;\n if (tabBar.getAttribute('slot') === 'top') continue;\n\n const rect = tabBar.getBoundingClientRect();\n if (rect.height <= 0) continue;\n\n const slot = tabBar.getAttribute('slot');\n const isBottom =\n slot === 'bottom' ||\n (slot === null && rect.bottom >= window.innerHeight - BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX);\n if (!isBottom) continue;\n\n if (rect.bottom > bestBottom) {\n bestBottom = rect.bottom;\n best = tabBar;\n }\n }\n\n return best;\n}\n\n/**\n * Options for {@link KitOverlayController.alertClose}.\n */\nexport interface KitAlertCloseOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /** Optional alert sub-header text shown beneath the header. */\n subHeader?: string;\n}\n\n/**\n * Options for {@link KitOverlayController.alertConfirm}.\n *\n * @remarks\n * Extends {@link KitAlertCloseOptions} with the confirm-button text.\n */\nexport interface KitAlertConfirmOptions extends KitAlertCloseOptions {\n /**\n * Text for the OK (confirm) button.\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n */\n okText: string;\n}\n\n/**\n * Attach a native keyboard listener that grows the modal to its maximum breakpoint when the\n * keyboard appears.\n *\n * @param modal - the presented modal element to resize\n * @returns a listener handle; on non-native platforms a no-op handle whose `remove()` does nothing\n * @internal\n */\nconst watchModalKeyboard = async (modal: HTMLIonModalElement): Promise<PluginListenerHandle> => {\n if (!Capacitor.isNativePlatform()) {\n return { remove: async () => undefined };\n }\n return Keyboard.addListener('keyboardDidShow', () => modal.setCurrentBreakpoint(1));\n};\n\n/**\n * Ergonomic wrapper that consolidates Ionic's overlay controllers (Modal / Toast / Alert).\n *\n * @remarks\n * Folds the repetitive create → present → onDidDismiss sequence into single calls and returns the\n * relevant result directly. It holds no application-specific policy such as navigation; compose\n * those concerns on the consuming side.\n *\n * @example\n * ```ts\n * constructor(private readonly overlay: KitOverlayController) {}\n *\n * async edit(): Promise<void> {\n * const result = await this.overlay.presentModal(EditPage, { id: 1 });\n * if (result) {\n * await this.overlay.presentToast({ message: 'Saved' });\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitOverlayController {\n readonly #modalCtrl = inject(ModalController);\n readonly #popoverCtrl = inject(PopoverController);\n readonly #toastCtrl = inject(ToastController);\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n\n /**\n * Guards against stacking alerts: while one {@link alertClose} / {@link alertConfirm} is on screen,\n * a concurrent call resolves immediately (close: no-op, confirm: `false`) instead of presenting a\n * second alert on top of the first. Shared across both methods so a confirm cannot stack over a close.\n */\n #alertPresenting = false;\n\n /**\n * Present a modal and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the modal is dismissed\n * @param component - the component to render inside the modal\n * @param componentProps - props to pass to the modal component\n * @param options - additional modal options, including {@link KitModalPresentOptions.watchKeyboard}\n * @returns the dismiss data, or `undefined` when the modal is dismissed without data\n * @remarks\n * Presenting a modal triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentPopover} and {@link presentToast}.\n *\n * Props are inferred from the component's `input()` fields (see {@link ModalPropsOf}): required inputs\n * become required props, so the compiler rejects a call that omits them. The return type is inferred from\n * a static `modalReturn` (see {@link ModalMetadata}); a component with no `modalReturn` resolves to `void`\n * — the modal is treated as returning no dismiss data.\n * @example\n * ```ts\n * // Inferred — `id` required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\n presentModal<C extends ModalOptions['component']>(component: C, ...args: ModalPresentArgs<C>): Promise<ModalReturnOf<C> | undefined>;\n async presentModal(\n component: ModalOptions['component'],\n componentProps?: ModalOptions['componentProps'],\n options: KitModalPresentOptions = {},\n ): Promise<unknown> {\n void kitImpact();\n const { watchKeyboard, ...modalOptions } = options;\n const modal = await this.#modalCtrl.create({ component, componentProps, ...modalOptions });\n await modal.present();\n const handle = watchKeyboard ? await watchModalKeyboard(modal) : null;\n const { data } = await modal.onDidDismiss<unknown>();\n await handle?.remove();\n return data;\n }\n\n /**\n * Present a popover and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the popover is dismissed\n * @param component - the component to render inside the popover\n * @param componentProps - props to pass to the popover component\n * @param options - additional popover options (for example `event` to anchor it, or `cssClass`)\n * @returns the dismiss data, or `undefined` when the popover is dismissed without data\n * @remarks\n * Presenting a popover triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentModal} and {@link presentToast}.\n * @example\n * ```ts\n * const choice = await overlay.presentPopover<MenuChoice>(MenuPopover, { items }, { event });\n * ```\n */\n async presentPopover<O = unknown>(\n component: PopoverOptions['component'],\n componentProps?: PopoverOptions['componentProps'],\n options: Omit<PopoverOptions, 'component' | 'componentProps'> = {},\n ): Promise<O | undefined> {\n void kitImpact();\n const popover = await this.#popoverCtrl.create({ component, componentProps, ...options });\n await popover.present();\n const { data } = await popover.onDidDismiss<O>();\n return data;\n }\n\n /**\n * Present a toast using kit defaults that the caller may override.\n *\n * @remarks\n * Defaults to a bottom position, a 2000ms duration, a vertical swipe gesture, and a close button\n * from the configured labels; any of these can be overridden via `options`. Presenting a toast\n * also triggers light native haptic feedback as an intentional kit UX choice.\n *\n * Bottom is the fleet-wide default (top left the toast fighting the tab bar and the keyboard).\n * For a bottom toast with no explicit `positionAnchor`, if a visible bottom `ion-tab-bar` is present the\n * toast is automatically anchored above it (Ionic places a bottom toast above its `positionAnchor`),\n * so the toast never sits behind the tabs. Bars with `slot=\"top\"` are ignored (desktop layouts that move\n * tabs to the header). Avoiding the on-screen keyboard is handled by the native keyboard resize — the\n * anchored/bottom toast rides the shrinking viewport above the keyboard;\n * Ionic itself has no toast keyboard-avoidance option. An app can override either via `options`.\n *\n * @param options - Ionic toast options that override the kit defaults\n * @returns the presented toast element\n * @example\n * ```ts\n * await overlay.presentToast({ message: 'Copied to clipboard' });\n * ```\n */\n async presentToast(options: ToastOptions): Promise<HTMLIonToastElement> {\n void kitImpact();\n const merged: ToastOptions = {\n position: 'bottom',\n duration: 2000,\n buttons: [this.#labels.close],\n swipeGesture: 'vertical',\n ...options,\n };\n // Anchor a bottom toast above the tab bar when a bottom bar is visibly present and the caller did not\n // set an explicit anchor, so the toast clears the tabs (and rides the keyboard-resized viewport).\n if (merged.position === 'bottom' && merged.positionAnchor === undefined) {\n const tabBar = findVisibleBottomTabBar();\n if (tabBar) {\n merged.positionAnchor = tabBar;\n }\n }\n const toast = await this.#toastCtrl.create(merged);\n await toast.present();\n return toast;\n }\n\n /**\n * Present a notification alert with a single \"close\" button and wait for it to be dismissed.\n *\n * @param options - alert content (header, message, optional sub-header)\n * @returns a Promise that resolves once the alert has been dismissed\n * @remarks\n * No-ops when another alert is already presenting (see {@link alertClose} / {@link alertConfirm}\n * stacking guard).\n * @example\n * ```ts\n * await overlay.alertClose({ header: 'Done', message: 'Your changes were saved.' });\n * ```\n */\n async alertClose(options: KitAlertCloseOptions): Promise<void> {\n if (this.#alertPresenting) {\n return;\n }\n this.#alertPresenting = true;\n try {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [this.#labels.close],\n });\n await alert.present();\n await alert.onWillDismiss();\n } finally {\n this.#alertPresenting = false;\n }\n }\n\n /**\n * Present a confirmation alert with cancel and OK buttons.\n *\n * @param options - alert content plus the OK button text via {@link KitAlertConfirmOptions.okText}\n * @returns `true` when the user presses OK, `false` otherwise (cancel or backdrop dismissal)\n * @example\n * ```ts\n * const ok = await overlay.alertConfirm({\n * header: 'Delete item?',\n * message: 'This cannot be undone.',\n * okText: 'Delete',\n * });\n * if (ok) {\n * await remove();\n * }\n * ```\n * @remarks\n * Returns `false` immediately when another alert is already presenting (see {@link alertClose} /\n * {@link alertConfirm} stacking guard).\n */\n async alertConfirm(options: KitAlertConfirmOptions): Promise<boolean> {\n if (this.#alertPresenting) {\n return false;\n }\n this.#alertPresenting = true;\n try {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n { text: options.okText, role: 'confirm' },\n ],\n });\n await alert.present();\n const { role } = await alert.onWillDismiss();\n return role === 'confirm';\n } finally {\n this.#alertPresenting = false;\n }\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport type { LoadingOptions } from '@ionic/angular/standalone';\nimport { LoadingController } from '@ionic/angular/standalone';\n\n/**\n * Reference-counted wrapper around Ionic's `LoadingController` that keeps at most one loading\n * indicator on screen across concurrent async work.\n *\n * @remarks\n * Each {@link presentLoading} increments a counter and each {@link dismissLoading} decrements it; the\n * indicator is presented on the `0 → 1` transition and dismissed on the `N → 0` transition. This\n * removes the flicker / \"stuck spinner\" bugs that come from every service calling\n * `LoadingController.create/dismiss` independently.\n *\n * All operations are serialized through an internal promise chain, so a `create → present` sequence\n * can never interleave with a concurrent `dismiss`. That is what makes the counter race-safe: a\n * dismiss that arrives while the indicator is still being presented runs *after* `present()` settles\n * and therefore tears the element down instead of leaving it orphaned on screen.\n *\n * Always pair every `presentLoading()` with exactly one `dismissLoading()` — a `try/finally` is the\n * safest shape.\n *\n * @example\n * ```ts\n * constructor(private readonly loading: KitLoadingController) {}\n *\n * async save(): Promise<void> {\n * await this.loading.presentLoading({ message: 'Saving…' });\n * try {\n * await this.api.save();\n * } finally {\n * await this.loading.dismissLoading();\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitLoadingController {\n readonly #loadingCtrl = inject(LoadingController);\n\n /** Outstanding {@link presentLoading} calls not yet balanced by {@link dismissLoading}. */\n #count = 0;\n\n /** The single presented loading element, or `null` when none is on screen. */\n #loading: HTMLIonLoadingElement | null = null;\n\n /**\n * Serializes present/dismiss operations. Each call chains onto this promise, runs after the\n * previous operation has fully settled, then reads {@link #count} and acts accordingly.\n */\n #queue: Promise<void> = Promise.resolve();\n\n /**\n * Show the loading indicator, or join the one already on screen.\n *\n * @param options - Ionic loading options; only applied by the call that actually creates the\n * indicator (the `0 → 1` transition). Ignored while an indicator is already present.\n * @returns a Promise that resolves once the indicator is on screen (or immediately when one already is)\n */\n async presentLoading(options: LoadingOptions = {}): Promise<void> {\n this.#count++;\n try {\n await this.#enqueue(async () => {\n // Create only on the transition into \"something is loading\"; concurrent callers ride the same\n // element. Re-check the count in case a dismiss already balanced this call while queued.\n if (this.#count > 0 && this.#loading === null) {\n const loading = await this.#loadingCtrl.create(options);\n await loading.present();\n this.#loading = loading;\n }\n });\n } catch (error) {\n // Roll back the reference this call took: a failed create/present must not leave the counter\n // elevated, otherwise a later cycle never reaches N → 0 and the spinner stays stuck on screen.\n this.#count--;\n throw error;\n }\n }\n\n /**\n * Release one reference; dismiss the indicator once the last reference is gone.\n *\n * @returns a Promise that resolves once the reference is released (and the indicator dismissed if\n * this was the last one). No-ops when the counter is already at zero.\n */\n async dismissLoading(): Promise<void> {\n if (this.#count === 0) {\n return;\n }\n this.#count--;\n await this.#enqueue(async () => {\n // Tear down only when the last consumer is gone. Because this runs after any in-flight\n // present() has settled (via the queue), there is never an orphaned loading element.\n if (this.#count === 0 && this.#loading !== null) {\n const loading = this.#loading;\n this.#loading = null;\n await loading.dismiss();\n }\n });\n }\n\n /**\n * Append `task` to the serialization chain and return its completion.\n *\n * @remarks\n * The stored chain swallows rejections so a single failing operation cannot wedge every future\n * overlay; the returned promise still rejects so the caller observes the error.\n */\n #enqueue(task: () => Promise<void>): Promise<void> {\n const run = this.#queue.then(task);\n this.#queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AlertController } from '@ionic/angular/standalone';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\n\n/**\n * Content for {@link KitReloadAlertController.present}.\n */\nexport interface KitReloadAlertOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /**\n * Text for the reload (confirm) button, e.g. \"リフレッシュ\".\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n * The cancel button uses the configured {@link KitLabels.cancel}.\n */\n okText: string;\n}\n\n/**\n * The fleet's canonical \"network error → offer to reload\" alert, as a stateful controller.\n *\n * @remarks\n * Consolidates the good-UX variant that had drifted across the fleet into one behavior:\n *\n * - **De-dup** — never stacks; a second {@link present} while an alert is already shown is a no-op.\n * - **Backdrop lock** — `backdropDismiss: false`, so a critical network error can't be dismissed by\n * an accidental backdrop tap; the user consciously chooses cancel or reload.\n * - **Auto-dismiss on reconnect** — the presented alert is tracked, so {@link dismiss} (called from a\n * later successful response) clears a now-stale error alert instead of leaving it on screen.\n * - **Reload on confirm** — the confirm button calls `location.reload()`.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n; the\n * cancel button reuses {@link KitOverlayConfig.labels}. Because it performs navigation\n * (`location.reload()`) and holds state, it is a dedicated controller rather than part of\n * {@link KitOverlayController}, which stays free of navigation policy.\n *\n * @example\n * ```ts\n * // In an HTTP interceptor:\n * const reload = inject(KitReloadAlertController);\n * // ...on a network-class error while connected:\n * await reload.present({ header: 'ネットワークエラー', message: `…(${status})`, okText: 'リフレッシュ' });\n * // ...on any later successful response:\n * await reload.dismiss();\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitReloadAlertController {\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n #alert: HTMLIonAlertElement | null = null;\n\n /**\n * Present the reload alert, unless one is already on screen.\n *\n * @param options - alert content plus the reload-button text\n * @returns a Promise that resolves once the alert has been presented (or immediately if suppressed)\n */\n async present(options: KitReloadAlertOptions): Promise<void> {\n // この controller 経由でも直書き ion-alert でも、多重表示しない。\n if (this.#alert || document.querySelector('ion-alert')) {\n return;\n }\n const alert = await this.#alertCtrl.create({\n header: options.header,\n message: options.message,\n backdropDismiss: false,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n {\n text: options.okText,\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n this.#alert = alert;\n void alert.onDidDismiss().then(() => {\n // 別の present で置き換わっていない限り、追跡を解除する。\n if (this.#alert === alert) {\n this.#alert = null;\n }\n });\n await alert.present();\n }\n\n /**\n * Dismiss the tracked reload alert if one is showing.\n *\n * @remarks\n * Typically called from a later successful response so a stale \"network error\" alert clears once\n * connectivity is restored. A no-op when nothing is showing.\n *\n * @returns a Promise that resolves once the alert has been dismissed (or immediately if none)\n */\n async dismiss(): Promise<void> {\n const alert = this.#alert;\n this.#alert = null;\n await alert?.dismiss();\n }\n}\n","import type { AlertController } from '@ionic/angular/standalone';\n\n/**\n * Content for {@link kitPresentAuthFailedAlert}.\n */\nexport interface KitAuthFailedAlertOptions {\n /** Alert header, e.g. \"ログインできませんでした\". */\n header: string;\n /** Optional sub-header; typically the short server error code/name. */\n subHeader?: string;\n /** Alert body message; typically the server-provided detail. */\n message: string;\n /** Text for the single close button, e.g. \"閉じる\". */\n closeText: string;\n}\n\n/**\n * Present the fleet's canonical \"sign-in / token exchange failed\" alert.\n *\n * @remarks\n * Folds together the alert every token-exchange app duplicated verbatim when a startup re-login\n * fails: an informative alert (header + optional server error as sub-header + detail message) with a\n * single close button that reloads the app (`location.reload()`) so the user restarts cleanly. The\n * caller is still responsible for signing the user out around this call.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n. Kept\n * as a standalone helper (taking the `AlertController`) rather than a method on\n * {@link KitOverlayController}, which holds no navigation policy such as `location.reload()`.\n *\n * @param alertCtrl - Ionic's `AlertController`\n * @param options - alert content plus the close-button text\n * @returns a Promise that resolves once the alert has been presented\n * @example\n * ```ts\n * onAuthorized: async () => {\n * const logged = await auth.tokenLogin().catch(async (e) => {\n * await kitPresentAuthFailedAlert(alertCtrl, {\n * header: 'ログインできませんでした',\n * subHeader: e.error.error,\n * message: e.error.detail,\n * closeText: '閉じる',\n * });\n * await auth.signOut();\n * return undefined;\n * });\n * // ...\n * };\n * ```\n */\nexport const kitPresentAuthFailedAlert = async (\n alertCtrl: AlertController,\n options: KitAuthFailedAlertOptions,\n): Promise<void> => {\n const alert = await alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n {\n text: options.closeText,\n role: 'cancel',\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n await alert.present();\n};\n","import { ActionSheetController } from '@ionic/angular/standalone';\n\n/** One selectable language in {@link kitPresentLanguageActionSheet}. */\nexport interface KitLanguageOption {\n /** Button label shown to the user (e.g. `English`, `日本語`). */\n readonly text: string;\n /** Locale identifier returned when this option is chosen (e.g. `en-US`, `ja`). */\n readonly data: string;\n}\n\n/**\n * Options for {@link kitPresentLanguageActionSheet}.\n *\n * @remarks\n * The kit ships no strings or URLs of its own: labels, the locale list, and the redirect-URL mapping\n * are all supplied by the caller, so a multilingual app passes `$localize`-resolved text and its own\n * per-locale build paths.\n */\nexport interface KitLanguageActionSheetOptions {\n /** Action-sheet header text. */\n readonly header: string;\n /** Selectable languages, in display order. */\n readonly locales: readonly KitLanguageOption[];\n /** Text for the cancel button. */\n readonly cancelText: string;\n /** The currently active locale; selecting the same value is a no-op. Normalize before passing. */\n readonly currentLocale: string;\n /** The current in-app path (e.g. `router.url`), stashed so the app can restore it after the reload. */\n readonly currentPath: string;\n /** `sessionStorage` key under which {@link currentPath} is stored. */\n readonly pathnameStorageKey: string;\n /** Maps a chosen locale to the URL to navigate to (the app's per-locale build entry point). */\n readonly buildRedirectUrl: (locale: string) => string;\n /** Gate for the redirect — pass `false` (e.g. outside production) to present without navigating. */\n readonly enabled: boolean;\n}\n\n/**\n * Present a language picker and, on a new selection, reload the app at that locale's entry point.\n *\n * @remarks\n * A plain function (the `ActionSheetController` is passed in, so nothing is injected) that unifies the\n * language-switch flow duplicated across apps. On a changed selection while {@link enabled} it stashes\n * the current path in `sessionStorage` (so the app can return the user to where they were), records the\n * chosen locale in `localStorage` under `'locale'`, and calls `window.location.replace()` with the\n * app-provided URL. Because it performs navigation, it is a standalone helper rather than part of a\n * controller (mirroring `kitPresentReloadAlert` / `kitPresentAuthFailedAlert`). Centralizing it means a\n * future improvement to the switch flow lands in every app at once.\n *\n * @param actionSheetCtrl - the Ionic `ActionSheetController`\n * @param options - labels, locale list, and redirect configuration; see {@link KitLanguageActionSheetOptions}\n * @returns a Promise that resolves once presented (and, on a new selection, after the reload is triggered)\n * @example\n * ```ts\n * await kitPresentLanguageActionSheet(inject(ActionSheetController), {\n * header: $localize`言語設定`,\n * locales: [{ text: 'English', data: 'en-US' }, { text: '日本語', data: 'ja' }],\n * cancelText: $localize`キャンセル`,\n * currentLocale: normalizedLocale,\n * currentPath: this.#router.url,\n * pathnameStorageKey: StorageKeyEnum.pathnameBeforeRedirect,\n * buildRedirectUrl: (locale) => location.origin + (localePath[locale.toLowerCase()] ?? '/index.html'),\n * enabled: environment.production,\n * });\n * ```\n */\nexport const kitPresentLanguageActionSheet = async (\n actionSheetCtrl: ActionSheetController,\n options: KitLanguageActionSheetOptions,\n): Promise<void> => {\n const actionSheet = await actionSheetCtrl.create({\n header: options.header,\n buttons: [\n ...options.locales.map((locale) => ({ text: locale.text, data: locale.data })),\n { text: options.cancelText, role: 'cancel' },\n ],\n });\n await actionSheet.present();\n\n const { data } = await actionSheet.onDidDismiss();\n if (options.enabled && data && data !== options.currentLocale) {\n sessionStorage.setItem(options.pathnameStorageKey, options.currentPath);\n localStorage.setItem('locale', data);\n window.location.replace(options.buildRedirectUrl(data));\n }\n};\n","import type { OnInit } from '@angular/core';\nimport { computed, Directive, ElementRef, HostListener, inject, Injector, input } from '@angular/core';\nimport { FORM_FIELD } from '@angular/forms/signals';\nimport { Capacitor } from '@capacitor/core';\nimport { KitStorageService } from '../storage/kit-storage.service';\nimport { kitForgetEmail, kitIsValidEmail, kitRecallEmail, kitRememberEmail } from '../storage/kit-auth-email-store';\n\n/**\n * The mode of {@link KitAuthInputDirective}.\n *\n * - `'autofill'` — iOS autofill propagation only (use on the password input).\n * - `'email'` — sign-in email: prefill from storage + remember on change + forget when cleared.\n * - `'email-remember'` — sign-up email: remember on change only (no prefill, no forget).\n */\nexport type KitAuthInputMode = 'autofill' | 'email' | 'email-remember';\n\n/**\n * Input conveniences for an `ion-input` in a sign-in / sign-up form, applied via the `kitAuthInput`\n * attribute. The mode is a typed union so a typo is a compile-time error.\n *\n * 1. **iOS autofill propagation (always on, every mode).** On iOS, when the browser autofills an\n * `ion-input` (e.g. a saved password) the value is written to the underlying native `<input>`\n * but the `change` event is not forwarded to the host `ion-input`, so the Angular form model\n * never sees it. This directive mirrors the first inner-input `change` back onto the host,\n * restoring two-way binding. It is a no-op on every other platform.\n *\n * 2. **Remember / prefill the email (`'email'` and `'email-remember'`).**\n * - `'email'` (sign-in) — on init recalls the last entered email and, *only while the field is\n * still empty*, seeds it via the bound Signal Forms field, so a browser/OS autofill the user\n * actually picks always wins over the prefill. On every committed change (`ionChange`) it\n * remembers a well-formed address, or **forgets** the stored one when the field is cleared\n * (empty after trim) or holds an invalid address — the user intentionally removing the prefill.\n * - `'email-remember'` (sign-up) — remembers a well-formed address on change, but never prefills\n * and never forgets. So the first-sign-up address is captured without pre-populating a\n * stranger's email into a new-account form, and clearing the field does not wipe an email\n * remembered elsewhere.\n *\n * A well-formed email is persisted even if it later fails to sign in — by design; the user simply\n * re-enters it. A malformed/partial entry is never stored (see {@link kitRememberEmail}).\n *\n * @example\n * ```html\n * <!-- sign-in email: iOS autofill + prefill + remember/forget -->\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email\" [formField]=\"form.email\" />\n * <!-- sign-up email: remember only -->\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email-remember\" [formField]=\"form.email\" />\n * <!-- password: iOS autofill propagation only -->\n * <ion-input type=\"password\" autocomplete=\"current-password\" kitAuthInput=\"autofill\" [formField]=\"form.password\" />\n * ```\n *\n * @remarks\n * Prefill writes through the Signal Forms `FORM_FIELD` bound on the same element; with no such field\n * (e.g. `ngModel` / reactive forms) prefill is skipped — remember/forget still work off the DOM\n * event. Storage is resolved lazily so the iOS mirror still works in apps without `@ionic/storage`.\n */\n@Directive({\n selector: '[kitAuthInput]',\n standalone: true,\n})\nexport class KitAuthInputDirective implements OnInit {\n readonly #el = inject(ElementRef);\n readonly #injector = inject(Injector);\n /** The Signal Forms field bound on this same element, if any (used to seed the prefill). */\n readonly #field = inject(FORM_FIELD, { optional: true, self: true });\n\n /** Mode selector; see {@link KitAuthInputMode}. */\n readonly kitAuthInput = input<KitAuthInputMode>('autofill');\n\n constructor() {}\n\n /**\n * Register the iOS autofill workaround and, in `'email'` mode, seed the field from storage.\n */\n ngOnInit(): void {\n if (this.#prefills()) {\n void this.#prefillEmail();\n }\n if (Capacitor.getPlatform() !== 'ios') {\n return;\n }\n setTimeout(() => {\n try {\n this.#el.nativeElement.children[0].addEventListener(\n 'change',\n (e: Event) => {\n this.#el.nativeElement.value = (e.target as HTMLInputElement).value;\n },\n {\n capture: false,\n once: true,\n passive: true,\n },\n );\n } catch {\n /* empty */\n }\n }, 100); // Need some time for the ion-input to create the input element\n }\n\n /**\n * On every committed change (`ionChange`): remember a well-formed email, or — only in the\n * prefilling `'email'` (sign-in) mode — forget the stored one when the field is cleared or invalid,\n * which is the user intentionally removing the prefill. `'email-remember'` never forgets, so\n * editing the sign-up field cannot wipe an email remembered from sign-in.\n */\n @HostListener('ionChange', ['$event'])\n onIonChange(event: Event): void {\n if (!this.#remembers()) {\n return;\n }\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const value = (event as CustomEvent<{ value?: string | null }>).detail?.value ?? '';\n if (value.trim().length > 0 && kitIsValidEmail(value)) {\n void kitRememberEmail(storage, value);\n } else if (this.#forgetsOnClear()) {\n void kitForgetEmail(storage);\n }\n }\n\n /** Whether this instance persists the entered email (`'email'` or `'email-remember'`). */\n readonly #remembers = computed(() => {\n const mode = this.kitAuthInput();\n return mode === 'email' || mode === 'email-remember';\n });\n\n /** Whether this instance prefills the field from storage (`'email'` only). */\n readonly #prefills = computed(() => this.kitAuthInput() === 'email');\n\n /** Whether clearing/invalidating the field forgets the stored email (`'email'` only). */\n readonly #forgetsOnClear = computed(() => this.kitAuthInput() === 'email');\n\n /** Resolve `KitStorageService` lazily; returns `null` when storage is not configured. */\n #resolveStorage(): KitStorageService | null {\n try {\n return this.#injector.get(KitStorageService);\n } catch {\n return null;\n }\n }\n\n /**\n * Seed the bound field with the remembered email, but only while it is still empty — so a value\n * the browser/OS autofills during the async recall is not clobbered.\n */\n async #prefillEmail(): Promise<void> {\n const field = this.#field;\n if (!field) {\n return;\n }\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const last = await kitRecallEmail(storage);\n const state = field.state();\n if (last && !state.value()) {\n state.value.set(last);\n }\n }\n}\n","import type { ElementRef } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\n\n/**\n * How {@link kitKeyboardInit} adjusts the target element when the native keyboard appears.\n *\n * - `transform` — CSS `translateY(-keyboardHeight + safeAreaBottom)` for a smooth iOS animation\n * (typical for an `ion-footer`).\n * - `offset` — set the `--offset-bottom` custom property to the negative keyboard height.\n * - `keyboard-offset` — set the `--padding-bottom` custom property to the keyboard height.\n */\nexport type KitKeyboardAdjust = 'transform' | 'offset' | 'keyboard-offset';\n\nconst keyboardWillShow = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillShow', (info) => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n // https://github.com/ionic-team/ionic-framework/blob/main/core/src/components/footer/footer.tsx\n elementRef.nativeElement.classList.remove('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.add('show-keyboard');\n // SSR-safe: this callback only runs on a native keyboard event, so the global `document` /\n // `window` are never touched on the server (kitKeyboardInit returns early when not native).\n const bodyStyleDeclaration = window.getComputedStyle(document.querySelector('body') as Element);\n const safeArea = parseInt(bodyStyleDeclaration.getPropertyValue('--ion-safe-area-bottom'), 10);\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 420ms';\n elementRef.nativeElement.style.willChange = 'transform';\n requestAnimationFrame(\n () => (elementRef.nativeElement.style.transform = `translateY(${info.keyboardHeight * -1 + safeArea}px)`),\n );\n } else if (type === 'offset') {\n requestAnimationFrame(() => {\n const keyboardOffset = elementRef.nativeElement.style.getPropertyValue('--keyboard-offset');\n if (!keyboardOffset || parseInt(keyboardOffset, 10) === 0) {\n elementRef.nativeElement.style.setProperty('--offset-bottom', `${info.keyboardHeight * -1}px`);\n }\n });\n } else {\n requestAnimationFrame(() => {\n const keyboardOffset = elementRef.nativeElement.style.getPropertyValue('--keyboard-offset');\n if (!keyboardOffset || parseInt(keyboardOffset, 10) === 0) {\n elementRef.nativeElement.style.setProperty('--padding-bottom', `${info.keyboardHeight}px`);\n }\n });\n }\n });\n\nconst keyboardWillHide = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillHide', () => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n elementRef.nativeElement.classList.add('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.remove('show-keyboard');\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 0ms';\n elementRef.nativeElement.style.transform = `translateY(0px)`;\n elementRef.nativeElement.style.willChange = 'transform';\n } else if (type === 'offset') {\n elementRef.nativeElement.style.setProperty('--offset-bottom', '0px');\n } else {\n elementRef.nativeElement.style.setProperty('--padding-bottom', '0px');\n }\n });\n\nconst keyboardDidShow = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidShow', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\nconst keyboardDidHide = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidHide', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\n/**\n * Register native keyboard listeners that reposition an element when the keyboard shows/hides.\n *\n * @remarks\n * A plain function — no DI needed (it reads the platform from `Capacitor` and uses the global\n * `document`), so a component calls it directly instead of injecting a controller. SSR-safe: the\n * global `document` / `window` are only read inside native keyboard-event callbacks, which never\n * fire on the server — the `Capacitor.isNativePlatform()` guard returns `[]` first, and nothing is\n * touched at module load. A no-op on non-native platforms (returns `[]`). On native it handles the\n * iOS/Android differences (Android\n * only toggles the `footer-toolbar-padding` class on an `ion-footer` for the `transform` mode,\n * working around an Ionic footer bug). The caller owns the returned handles and must `remove()`\n * them when the view is destroyed.\n *\n * @param elementRef - The element to reposition (e.g. an `ion-footer`).\n * @param type - The adjustment strategy; see {@link KitKeyboardAdjust}.\n * @returns The registered listener handles (empty on non-native platforms).\n * @example\n * ```ts\n * export class ComposePage {\n * readonly #footer = viewChild.required<ElementRef>('footer');\n * #handles: PluginListenerHandle[] = [];\n *\n * async ngAfterViewInit() {\n * this.#handles = await kitKeyboardInit(this.#footer(), 'transform');\n * }\n * ngOnDestroy() {\n * this.#handles.forEach((h) => h.remove());\n * }\n * }\n * ```\n */\nexport const kitKeyboardInit = async (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle[]> => {\n if (!Capacitor.isNativePlatform()) {\n return [];\n }\n return [\n await keyboardWillShow(elementRef, type),\n await keyboardWillHide(elementRef, type),\n await keyboardDidShow(elementRef),\n await keyboardDidHide(elementRef),\n ];\n};\n","import type { EnvironmentProviders } from '@angular/core';\nimport { inject, InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport type { CanActivateFn, RouterStateSnapshot, UrlTree } from '@angular/router';\nimport { Router } from '@angular/router';\nimport { NavController } from '@ionic/angular/standalone';\nimport type { Observable } from 'rxjs';\nimport { map, mergeMap } from 'rxjs/operators';\n\n/**\n * Discriminated set of authentication states the guards react to.\n *\n * @remarks\n * The application is responsible for emitting these values through {@link KitAuthConfig.authState}.\n * An application that does not use a value (for example email confirmation) simply never emits it.\n *\n * - `user` — fully authenticated and verified.\n * - `confirm` — awaiting email confirmation.\n * - `required` — not authenticated.\n * - `anonymous` — signed in anonymously; the user can still be guided toward full registration.\n */\nexport type KitAuthState = 'user' | 'confirm' | 'required' | 'anonymous';\n\n/**\n * Redirect targets (route paths) used by the guards when access is denied.\n *\n * @remarks\n * Every field is required and must be provided per application, because the guards have no\n * knowledge of the host application's route layout.\n */\nexport interface KitAuthRedirects {\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is already authenticated (`user`). */\n readonly whenAuthorized: string;\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is awaiting email confirmation (`confirm`). */\n readonly whenConfirming: string;\n /** Used by {@link kitRequireConfirmingGuard}: where to navigate when the state is not `confirm`. */\n readonly whenNotConfirming: string;\n /** Used by {@link kitRequireAuthorizedGuard}: where to navigate when the state is not `user` and the fallback is not allowed. */\n readonly whenUnauthorized: string;\n}\n\n/**\n * Configuration consumed by the authentication guards, injected through {@link provideKitAuth}.\n *\n * @remarks\n * `authState` and `redirects` are required. The `onAuthorized` / `onUnauthenticated` hooks are\n * optional and default to allowing the authenticated user through (`true`) and falling through to\n * the default redirect (`false`) respectively, so an app only supplies the ones with real logic.\n */\nexport interface KitAuthConfig {\n /**\n * Source of the current authentication state.\n *\n * @remarks\n * Typically backed by the application's own auth service (for example `AuthService.isAuth()`).\n *\n * @returns A stream of {@link KitAuthState} values.\n */\n authState(): Observable<KitAuthState>;\n /**\n * Application-specific work that runs in {@link kitRequireAuthorizedGuard} after the state is confirmed to be `user`.\n *\n * @remarks\n * Typical responsibilities include token login, permission checks, terms-of-service acceptance,\n * or restoring a previously requested redirect. Optional; defaults to `true` (allow activation).\n *\n * @param state - The router state snapshot of the route being activated.\n * @returns `true` to allow activation, or a `UrlTree` to perform a custom redirect.\n */\n onAuthorized?(state: RouterStateSnapshot): Promise<boolean | UrlTree>;\n /**\n * Fallback that runs in {@link kitRequireAuthorizedGuard} when the state is `required` (not authenticated).\n *\n * @remarks\n * For example, attempt an anonymous sign-in and allow the route. Optional; defaults to `false`\n * (fall through to the default `whenUnauthorized` redirect).\n *\n * @param state - The router state snapshot of the route being activated.\n * @returns `true` to allow activation, a `UrlTree` for a custom redirect, or `false` to use the default redirect.\n */\n onUnauthenticated?(state: RouterStateSnapshot): Promise<boolean | UrlTree>;\n /** Redirect targets used by the guards. */\n redirects: KitAuthRedirects;\n}\n\n/**\n * Injection token that carries the {@link KitAuthConfig} to the authentication guards.\n */\nexport const KIT_AUTH_CONFIG = new InjectionToken<KitAuthConfig>('@rdlabo/ionic-angular-kit:auth');\n\n/**\n * Wire the authentication guard configuration into the application's dependency injection.\n *\n * @remarks\n * The factory runs inside an injection context, so it may call `inject()` (for example\n * `inject(AuthService)`) to build the configuration.\n *\n * @param configFactory - Factory that returns the {@link KitAuthConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * provideKitAuth(() => {\n * const auth = inject(AuthService);\n * return {\n * // onAuthorized / onUnauthenticated are optional (default: allow / fall through to redirect).\n * authState: () => auth.isAuth(),\n * redirects: {\n * whenAuthorized: '/',\n * whenConfirming: '/auth/confirm',\n * whenNotConfirming: '/auth/signin',\n * whenUnauthorized: 'auth',\n * },\n * };\n * });\n * ```\n */\nexport const provideKitAuth = (configFactory: () => KitAuthConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_AUTH_CONFIG, useFactory: configFactory }]);\n\n/**\n * Guard that requires the user to be unauthenticated (for example sign-in or sign-up pages).\n *\n * @remarks\n * Allows the `required` and `anonymous` states (an anonymous user is permitted to proceed to a\n * registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and a user\n * awaiting confirmation (`confirm`) is sent to `whenConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'signin', component: SigninPage, canActivate: [kitRequiredUnauthorizedGuard] }];\n * ```\n */\nexport const kitRequiredUnauthorizedGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n\n return authState().pipe(\n map((data) => {\n if (data === 'user') {\n navCtrl.setDirection('root');\n router.navigate([redirects.whenAuthorized]);\n return false;\n } else if (data === 'confirm') {\n router.navigate([redirects.whenConfirming]);\n return false;\n }\n // 'required' | 'anonymous'\n return true;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be awaiting email confirmation (`confirm`).\n *\n * @remarks\n * Any other state triggers a redirect: an `anonymous` user is sent to the authenticated area\n * (`whenAuthorized`), and every remaining state is sent to `whenNotConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'confirm', component: ConfirmPage, canActivate: [kitRequireConfirmingGuard] }];\n * ```\n */\nexport const kitRequireConfirmingGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n\n return authState().pipe(\n map((data) => {\n if (data === 'confirm') {\n return true;\n }\n navCtrl.setDirection('root');\n router.navigate([data === 'anonymous' ? redirects.whenAuthorized : redirects.whenNotConfirming]);\n return false;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be fully authenticated (`user`).\n *\n * @remarks\n * - `user` — runs {@link KitAuthConfig.onAuthorized} (token login, permission checks, and so on).\n * - `anonymous` — allowed as-is, for applications that permit anonymous browsing.\n * - `required` / `confirm` — runs {@link KitAuthConfig.onUnauthenticated}; if it resolves to `false`,\n * the user is redirected to `whenUnauthorized`.\n *\n * @param _route - The activated route snapshot (unused).\n * @param state - The router state snapshot, forwarded to the configuration hooks.\n * @returns A stream emitting the activation result: `true`, a `UrlTree`, or `false` after a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'home', component: HomePage, canActivate: [kitRequireAuthorizedGuard] }];\n * ```\n */\nexport const kitRequireAuthorizedGuard: CanActivateFn = (_route, state) => {\n const { authState, onAuthorized, onUnauthenticated, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n\n return authState().pipe(\n mergeMap(async (data) => {\n if (data === 'user') {\n // 既定は「許可」。tokenLogin / 権限確認等が必要なアプリだけ onAuthorized を渡す。\n return onAuthorized ? onAuthorized(state) : true;\n }\n if (data === 'anonymous') {\n return true;\n }\n // 既定は false(whenUnauthorized へ)。匿名ログイン等のフォールバックが要るアプリだけ渡す。\n const fallback = onUnauthenticated ? await onUnauthenticated(state) : false;\n if (fallback !== false) {\n return fallback;\n }\n navCtrl.setDirection('root');\n router.navigate([redirects.whenUnauthorized]);\n return false;\n }),\n );\n};\n","import type { EnvironmentProviders } from '@angular/core';\nimport { inject, InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport type { HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Network } from '@capacitor/network';\nimport type { Observable } from 'rxjs';\nimport { from, retry, throwError, timer } from 'rxjs';\nimport { catchError, map, mergeMap, tap, timeout } from 'rxjs/operators';\n\n/**\n * HTTP methods that are safe to retry automatically.\n *\n * @remarks\n * Non-idempotent methods (`POST` / `PATCH` / `DELETE`) are never auto-retried, because a response\n * lost *after* the server processed the write would be replayed into a duplicate write (\"saved twice\n * from one tap\"). A non-idempotent request that is genuinely safe to replay opts in by carrying an\n * `Idempotency-Key` header (which the server must honor).\n *\n * @internal\n */\nconst RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'];\n\n/**\n * Transient HTTP statuses worth retrying: `0` (network/transport failure), `408` (request timeout),\n * `429` (rate limited), and the `502` / `503` / `504` gateway-availability family. Every other status\n * is thrown immediately — a whitelist is safer than a blacklist for deciding what to replay.\n *\n * @internal\n */\nconst RETRYABLE_STATUSES = [0, 408, 429, 502, 503, 504];\n\n/**\n * Maximum number of automatic retries for a retryable request.\n *\n * @internal\n */\nconst MAX_RETRIES = 2;\n\n/**\n * Fleet-wide per-request timeout. A request with no response within this window fails with a\n * synthetic `408` (a {@link RETRYABLE_STATUSES | retryable status}). Deliberately generous — it\n * catches a genuinely hung request (dead server) without cutting off legitimately slow work such as\n * a large upload or an AI generation. `timeout({ each })` resets on every emission, so a streaming\n * response that keeps emitting is unaffected.\n *\n * @internal\n */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Parse a `Retry-After` header (delta-seconds or an HTTP-date) into milliseconds, or `null` when it\n * is absent or unparseable.\n *\n * @internal\n */\nconst parseRetryAfterMs = (error: HttpErrorResponse): number | null => {\n const header = error.headers?.get('Retry-After');\n if (!header) {\n return null;\n }\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const dateMs = Date.parse(header);\n return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());\n};\n\n/**\n * Configuration that customizes the behavior of {@link kitAuthInterceptor}, injected through {@link provideKitHttp}.\n *\n * @remarks\n * The interceptor fixes the retry policy and control flow; only the hooks below are app-specific:\n *\n * - Retries only {@link RETRYABLE_METHODS | idempotent methods} (or a request bearing an\n * `Idempotency-Key`) on a {@link RETRYABLE_STATUSES | transient status}, up to {@link MAX_RETRIES}\n * times with a short jittered backoff (honoring `Retry-After`). Writes are never auto-retried.\n * - When the device is offline it fails fast to {@link KitHttpConfig.offlineFallback} instead of\n * waiting out the retries.\n * - On a final error it classifies by status and calls the matching hook (see each hook below).\n *\n * Only {@link KitHttpConfig.getAuthHeaders} is required — it has no safe default. Every other hook is\n * optional and defaults to a no-op (or `{}` / `false` / `null` as appropriate), so an app configures\n * only the behavior that actually differs from the canonical baseline.\n */\nexport interface KitHttpConfig {\n /**\n * Produce authentication and metadata headers for the outgoing request.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values, resolved asynchronously.\n */\n getAuthHeaders(request: HttpRequest<unknown>): Promise<Record<string, string>>;\n /**\n * Produce additional headers for the outgoing request.\n *\n * @remarks\n * Optional; defaults to adding no extra headers.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values; return `{}` when none are needed.\n */\n buildExtraHeaders?(request: HttpRequest<unknown>): Record<string, string>;\n /**\n * Treat an otherwise-successful response as an error.\n *\n * @remarks\n * Optional. Some backends use a 2xx status (for example `204` / `206`) to signal a condition the\n * app wants to surface as an error rather than a success. Return `true` to throw the response so it\n * flows through the error path; the status is not in {@link RETRYABLE_STATUSES}, so it is not\n * retried and propagates to the caller. Defaults to treating every 2xx as a success.\n *\n * @param response - The successful `HttpResponse` about to be delivered.\n * @returns `true` to reject the response as an error.\n */\n treatAsError?(response: HttpResponse<unknown>): boolean;\n /**\n * Called for every successful response that completed an actual network round trip.\n *\n * @remarks\n * Responses synthesized by {@link KitHttpConfig.offlineFallback} are produced after `catchError`\n * and therefore never reach this hook, so it observes genuine successes only. A typical use is to\n * reset an \"offline\" flag once connectivity is restored. Optional; defaults to a no-op.\n *\n * @param event - The successful `HttpResponse`.\n */\n onResponse?(event: HttpResponse<unknown>): void;\n /**\n * Decide whether to pass the request straight through, skipping auth, retry, and error handling.\n *\n * @remarks\n * Useful for external URLs such as S3 or a CDN. Optional; defaults to `false` (never bypass).\n *\n * @param request - The outgoing request.\n * @returns `true` to bypass the interceptor pipeline.\n */\n bypass?(request: HttpRequest<unknown>): boolean;\n /**\n * Provide an offline short-circuit when a request fails.\n *\n * @remarks\n * Returning a non-null observable replaces the error with that response (for example a queued\n * offline result). Optional; defaults to `null` (no fallback, normal error handling proceeds).\n *\n * @param request - The request that failed (after headers were applied).\n * @param error - The error response that triggered the fallback.\n * @returns A replacement event stream, or `null` for no fallback.\n */\n offlineFallback?(request: HttpRequest<unknown>, error: HttpErrorResponse): Observable<HttpEvent<unknown>> | null;\n /**\n * Side effect to run on a `401` response (for example an expired token).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `401`.\n */\n onUnauthorized?(request: HttpRequest<unknown>): void;\n /**\n * Side effect to run on a `403` response (a permission error).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `403`.\n */\n onForbidden?(request: HttpRequest<unknown>): void;\n /**\n * UX hook for a genuine network / transport failure (status `0`) while the device reports itself\n * connected — i.e. the server is unreachable rather than the phone being offline.\n *\n * @remarks\n * Optional; defaults to a no-op. Narrow by design: it fires only for status `0` (not for `404`,\n * `429`, `5xx`, …, which have their own hooks), so a \"connection lost, reload?\" prompt is not shown\n * for server-side problems. When the device is offline it is not called at all — `offlineFallback`\n * owns that path. The kit ships {@link KitReloadAlertController} as the canonical implementation\n * (with de-dup so concurrent failures show a single alert, and auto-dismiss on reconnect).\n *\n * @param status - The HTTP status code (`0`), or a string descriptor for non-HTTP failures.\n * @returns Optionally a promise to await before continuing.\n */\n onNetworkError?(status: number | string): Promise<void> | void;\n /**\n * UX hook for a transient server-availability failure (`502` / `503` / `504`), fired after retries\n * are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op. Distinct from {@link KitHttpConfig.onNetworkError} — the device's\n * connection is fine, the server is momentarily unavailable — so the app can say \"server busy, try\n * again shortly\" rather than prompt a reload.\n *\n * @param status - `502`, `503`, or `504`.\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onServerBusy?(status: number, retryAfterSeconds?: number): void;\n /**\n * UX hook for a `429 Too Many Requests` response, fired after retries are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onRateLimited?(retryAfterSeconds?: number): void;\n /**\n * UX hook for `400` / `422` / `500` responses that carry a server-provided message.\n *\n * @remarks\n * Optional; defaults to a no-op. Note that the message comes straight from the API; prefer a\n * user-facing `userMessage` / `code` in your error contract over showing a raw developer message.\n *\n * @param message - The message extracted from the error body.\n */\n onServerError?(message: string): void;\n /**\n * Side effect for a failure while *producing* the auth headers (`getAuthHeaders` rejected).\n *\n * @remarks\n * Optional; defaults to a no-op. Because the request is never sent in this case, it does not reach\n * the response-error hooks; classify it here (for example a failed token refresh) so it does not\n * fail silently.\n *\n * @param request - The request whose headers could not be produced.\n * @param error - The error thrown by `getAuthHeaders`.\n */\n onAuthError?(request: HttpRequest<unknown>, error: unknown): void;\n}\n\n/**\n * Injection token that carries the {@link KitHttpConfig} to {@link kitAuthInterceptor}.\n */\nexport const KIT_HTTP_CONFIG = new InjectionToken<KitHttpConfig>('@rdlabo/ionic-angular-kit:http');\n\n/**\n * Wire the {@link kitAuthInterceptor} configuration into the application's dependency injection.\n *\n * @remarks\n * Register the interceptor itself separately via `provideHttpClient(withInterceptors([kitAuthInterceptor]))`.\n * The factory runs inside an injection context, so it may call `inject()`.\n *\n * @param configFactory - Factory that returns the {@link KitHttpConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideHttpClient(withInterceptors([kitAuthInterceptor])),\n * provideKitHttp(() => {\n * const auth = inject(AuthService);\n * const reload = inject(KitReloadAlertController);\n * return {\n * // Only getAuthHeaders is required; every other hook is optional and defaults to a no-op.\n * getAuthHeaders: async () => ({ Authorization: `Bearer ${await auth.token()}` }),\n * onUnauthorized: () => auth.signOut(),\n * onNetworkError: (status) =>\n * reload.present({ header: 'Network error', message: `Reload? (${status})`, okText: 'Reload' }),\n * onResponse: () => void reload.dismiss(),\n * };\n * }),\n * ],\n * });\n * ```\n */\nexport const provideKitHttp = (configFactory: () => KitHttpConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_HTTP_CONFIG, useFactory: configFactory }]);\n\n/**\n * Classify a final (post-retry) error and invoke the matching {@link KitHttpConfig} hook.\n *\n * @internal\n */\nconst dispatchError = (config: KitHttpConfig, req: HttpRequest<unknown>, error: HttpErrorResponse): void => {\n const status = error.status;\n const retryAfterMs = parseRetryAfterMs(error);\n const retryAfterSeconds = retryAfterMs === null ? undefined : Math.round(retryAfterMs / 1000);\n\n if (status === 401) {\n config.onUnauthorized?.(req);\n } else if (status === 403) {\n config.onForbidden?.(req);\n } else if (status === 0) {\n // Genuine network/transport failure. Only surface it when the device is actually connected\n // (server unreachable); when offline, offlineFallback owns the UX — a reload prompt won't help.\n void Network.getStatus().then((network) => {\n if (network.connected) {\n config.onNetworkError?.(status);\n }\n });\n } else if (status === 429) {\n config.onRateLimited?.(retryAfterSeconds);\n } else if ([502, 503, 504].includes(status)) {\n config.onServerBusy?.(status, retryAfterSeconds);\n } else if ([400, 422, 500].includes(status) && error.error?.message) {\n config.onServerError?.(error.error.message);\n }\n // Every other status (404, 418, …) is left to the caller — no generic alert.\n};\n\n/**\n * Canonical functional HTTP interceptor that applies authentication, retries, and error handling.\n *\n * @remarks\n * Behavior, driven by the injected {@link KitHttpConfig}:\n *\n * 1. Requests for which `bypass` returns `true` are forwarded untouched.\n * 2. If `getAuthHeaders` rejects, `onAuthError` is called and the request is not sent.\n * 3. Otherwise the headers from `getAuthHeaders` and `buildExtraHeaders` are merged onto a cloned request.\n * 4. On failure the request is retried up to {@link MAX_RETRIES} times, but **only** when the device\n * is online, the method is a {@link RETRYABLE_METHODS | retryable method} (or carries an\n * `Idempotency-Key`), and the status is a {@link RETRYABLE_STATUSES | transient status}. The\n * backoff is `retryCount * 500ms` plus up to 250ms of jitter, or the server's `Retry-After`.\n * When the device is offline it stops retrying immediately.\n * 5. On the final error, `offlineFallback` is consulted first; otherwise the error is classified by\n * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→\n * `onNetworkError` (when connected), `429`→`onRateLimited`, `502`/`503`/`504`→`onServerBusy`, and\n * `400`/`422`/`500` with a body message→`onServerError`.\n *\n * @param request - The outgoing request.\n * @param next - The next handler in the interceptor chain.\n * @returns A stream of HTTP events for the (possibly modified, retried, or replaced) request.\n *\n * @example\n * ```ts\n * provideHttpClient(withInterceptors([kitAuthInterceptor]));\n * ```\n */\nexport const kitAuthInterceptor: HttpInterceptorFn = (request, next) => {\n const config = inject(KIT_HTTP_CONFIG);\n\n if (config.bypass?.(request)) {\n return next(request);\n }\n\n return from(Promise.resolve(config.getAuthHeaders(request))).pipe(\n catchError((headerError: unknown) => {\n // getAuthHeaders failed → the request is never sent; classify it instead of failing silently.\n config.onAuthError?.(request, headerError);\n return throwError(() => headerError);\n }),\n mergeMap((authHeaders) => {\n const req = request.clone({ setHeaders: { ...authHeaders, ...config.buildExtraHeaders?.(request) } });\n const retryable = RETRYABLE_METHODS.includes(req.method) || req.headers.has('Idempotency-Key');\n\n const base = next(req).pipe(\n timeout({\n each: DEFAULT_TIMEOUT_MS,\n with: () => throwError(() => new HttpErrorResponse({ status: 408, statusText: 'Request Timeout', url: req.url })),\n }),\n );\n\n return base.pipe(\n map((event) => {\n // A backend may signal an error condition with a 2xx status (e.g. 204/206); surface it as an error.\n if (event instanceof HttpResponse && config.treatAsError?.(event)) {\n throw event;\n }\n return event;\n }),\n retry({\n count: MAX_RETRIES,\n delay: (error: HttpErrorResponse, retryCount: number) =>\n from(Network.getStatus()).pipe(\n mergeMap((network) => {\n // Offline → don't wait out the retries; fail fast so offlineFallback can take over.\n if (!network.connected) {\n return throwError(() => error);\n }\n // Only replay idempotent requests, and only on a transient status.\n if (!retryable || !RETRYABLE_STATUSES.includes(error.status)) {\n return throwError(() => error);\n }\n // Short linear backoff (500ms, 1000ms, …) plus jitter to de-correlate a fleet of\n // clients reconnecting at once; the server's Retry-After wins when present.\n const backoff = parseRetryAfterMs(error) ?? retryCount * 500 + Math.random() * 250;\n return timer(backoff);\n }),\n ),\n }),\n tap((event) => {\n if (event instanceof HttpResponse) {\n config.onResponse?.(event);\n }\n }),\n catchError((error: HttpErrorResponse) => {\n const fallback = config.offlineFallback?.(req, error);\n if (fallback) {\n return fallback;\n }\n dispatchError(config, req, error);\n return throwError(() => error);\n }),\n );\n }),\n );\n};\n","/**\n * Merge a newly fetched page of items into an existing list by id, keeping the result sorted.\n *\n * Items are merged by the numeric `key` field. On a duplicate `key` the item from `arrayNew` wins\n * and replaces the one in `arrayOld`. Old items whose `key` falls *inside* the window spanned by\n * `arrayNew` (between its first and last `key`) are dropped, since the freshly fetched page is the\n * authoritative copy of that window; old items *outside* the window are kept. The merged items are\n * finally sorted by `key`, ascending or descending according to `order`.\n *\n * The algorithm is:\n * 1. If both inputs are empty, return an empty array.\n * 2. Read the first (`lead`) and last (`last`) `key` values of `arrayNew` as the bounds of the\n * page's window. Keep the old items whose `key` lies *outside* that window (at or beyond the\n * extremes) and drop those strictly inside it, handling both a high-to-low page (`lead > last`)\n * and a low-to-high page (`lead < last`). A single-value page (`lead === last`) keeps all old items.\n * 3. Remove old items whose `key` already exists in `arrayNew` (new wins on duplicates).\n * 4. Concatenate `arrayNew` with the surviving old items and sort by `key` in the requested\n * direction.\n *\n * @remarks\n * Designed for infinite-scroll / paginated list merging, where each fetched page may overlap the\n * previously held items and the server returns a contiguous, ordered window of records. The `key`\n * field is treated as a number for range comparison and sorting.\n *\n * @typeParam T - Element type of both arrays. Its `key` property must be a numeric value.\n * @param arrayOld - The previously accumulated list. May be empty or nullish-safe (empty when falsy).\n * @param arrayNew - The newly fetched page of items; its `key` range defines the window that its own\n * items replace, and its items take precedence on duplicates.\n * @param key - The property of `T` used as the unique, numeric id for matching, range filtering, and sorting.\n * @param order - Sort direction by `key`: `'ASC'` for ascending or `'DESC'` for descending. Defaults to `'DESC'`.\n * @param secondaryKey - Optional second property for extra de-duplication. When provided, any\n * surviving old item whose `secondaryKey` value matches that of *any* new item is dropped before\n * the `key` merge. Useful when a record keeps a stable `key` but its secondary identity changes\n * between pages (e.g. items keyed by `id` but also grouped by `parentId`). Omit to skip this step.\n * @returns A new array containing `arrayNew` merged with the out-of-window, non-duplicate old items, sorted by `key`.\n * @example\n * ```ts\n * interface Post {\n * id: number;\n * title: string;\n * }\n *\n * const loaded: Post[] = [\n * { id: 30, title: 'c' },\n * { id: 20, title: 'b' },\n * { id: 10, title: 'a' },\n * ];\n * const nextPage: Post[] = [\n * { id: 20, title: 'b (updated)' },\n * { id: 15, title: 'a.5' },\n * ];\n *\n * // Descending merge: id 30 lies above the new page's [15, 20] window so it is kept; id 20 is\n * // inside the window and is replaced by the new value; id 10 lies below the window and is kept.\n * const merged = arrayConcatById(loaded, nextPage, 'id', 'DESC');\n * // => [{ id: 30, title: 'c' }, { id: 20, title: 'b (updated)' }, { id: 15, title: 'a.5' }, { id: 10, title: 'a' }]\n * ```\n */\nexport const arrayConcatById = <T>(\n arrayOld: T[],\n arrayNew: T[],\n key: keyof T,\n order: 'ASC' | 'DESC' = 'DESC',\n secondaryKey?: keyof T,\n): T[] => {\n if (!arrayNew.length && !arrayOld.length) {\n return [];\n }\n const lead = arrayNew[0][key] as number;\n const last = arrayNew[arrayNew.length - 1][key] as number;\n\n const filteredOld = (arrayOld || []).filter((vol) => {\n const value = vol[key] as number;\n return (lead > last && (value >= lead || value <= last)) || (lead < last && (value <= lead || value >= last)) || lead === last;\n });\n\n const secondaryFilteredOld = secondaryKey\n ? filteredOld.filter((vol) => !arrayNew.some((element) => element[secondaryKey] === vol[secondaryKey]))\n : filteredOld;\n\n const oldData = secondaryFilteredOld.filter((vol) => !arrayNew.some((element) => element[key] === vol[key]));\n const data = arrayNew.concat(oldData);\n\n const direction = order === 'ASC' ? 1 : -1;\n return data.sort((a, b) => {\n const x = a[key] as number;\n const y = b[key] as number;\n if (x > y) {\n return direction;\n }\n if (x < y) {\n return direction * -1;\n }\n return 0;\n });\n};\n","/**\n * Order-independent deep equality check.\n *\n * @remarks\n * Returns `true` when `a` and `b` serialize to the same value after their (nested) object entries are\n * sorted by key, so property order does not affect the result. Intended for cheap \"did this state\n * object change?\" comparisons.\n *\n * Caveats of the JSON-serialization approach: values that JSON drops or coerces (`undefined`,\n * functions, `NaN`, `Date`, `Map`/`Set`) are compared by their serialized form, and array element\n * order is treated as significant (arrays are not reordered in a meaningful way). Use a structural\n * deep-equal library when those cases matter.\n *\n * @param a - First object.\n * @param b - Second object.\n * @returns `true` when the two objects are deeply equal ignoring key order.\n * @example\n * ```ts\n * objectEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // => true\n * objectEqual({ a: 1 }, { a: 2 }); // => false\n * ```\n */\nexport const objectEqual = (a: object, b: object): boolean => {\n if (Object.is(a, b)) {\n return true;\n }\n const sortDeep = (obj: unknown): unknown => {\n if (typeof obj !== 'object' || !obj) {\n return undefined;\n }\n return Object.entries(obj)\n .sort()\n .map(([entryKey, value]) => [entryKey, typeof value === 'object' ? sortDeep(value) : value]);\n };\n return JSON.stringify(sortDeep(a)) === JSON.stringify(sortDeep(b));\n};\n","/**\n * Disable the button that triggered an event while an async operation runs, re-enabling it after.\n *\n * @remarks\n * Prevents the common double-submit / double-tap bug: the `event.target` button is disabled, the\n * work is awaited, and the button is re-enabled — even if the work rejects (the rejection is\n * swallowed here so the button always recovers; handle errors inside `work` if you need to react).\n *\n * @param event - The DOM event whose `target` is the button to disable (e.g. a click event).\n * @param work - The async operation to run while the button is disabled.\n * @returns A Promise that resolves once the work has settled and the button has been re-enabled.\n * @example\n * ```ts\n * async submit(event: Event): Promise<void> {\n * await disableHandler(event, this.save());\n * }\n * ```\n */\nexport const disableHandler = async (event: Event, work: Promise<void | boolean>): Promise<void> => {\n const target = event.target as HTMLButtonElement;\n target.disabled = true;\n await work.catch((): undefined => undefined);\n target.disabled = false;\n};\n","import { WritableSignal } from '@angular/core';\n\n/**\n * Toggle the `disabled` flag of a signal-held `ion-infinite-scroll` / `ion-refresher` element.\n *\n * @remarks\n * A tiny pure helper for the common pattern of stashing the completing scroll/refresher element in a\n * signal (e.g. captured from the event) and later enabling/disabling it — for instance disabling\n * infinite scroll once the last page has loaded. A no-op when the signal holds no element.\n *\n * @param completeEvent - a writable signal holding the infinite-scroll / refresher element (or nullish)\n * @param disabled - the value to set on the element's `disabled` property\n * @example\n * ```ts\n * const infinite = signal<HTMLIonInfiniteScrollElement | null>(null);\n * // ...on ionInfinite: infinite.set(ev.target); ...when no more pages:\n * kitChangeEventDisabled(infinite, true);\n * ```\n */\nexport const kitChangeEventDisabled = (\n completeEvent: WritableSignal<HTMLIonInfiniteScrollElement | HTMLIonRefresherElement | null | undefined>,\n disabled: boolean,\n): void => {\n const event = completeEvent();\n if (event) {\n event.disabled = disabled;\n }\n};\n","import { ElementRef } from '@angular/core';\nimport { Observable, startWith } from 'rxjs';\n\n/**\n * Observe an Ionic page's \"is currently entered\" state from its lifecycle DOM events.\n *\n * @remarks\n * Emits `true` on `ionViewDidEnter` and `false` on `ionViewWillEnter` / `ionViewWillLeave`, seeded\n * with `false` via `startWith`. Useful to pause/resume work (timers, video, expensive rendering)\n * while a page is off-screen in Ionic's stack navigation, without wiring the four lifecycle hooks by\n * hand. The listeners are removed when the Observable is unsubscribed.\n *\n * @param el - an `ElementRef` for the page host element (the `ion-page`)\n * @returns an Observable that emits whether the page is currently entered\n * @example\n * ```ts\n * export class FeedPage {\n * readonly #host = inject(ElementRef);\n * readonly isEntered = toSignal(kitCreateDidEnter(this.#host), { initialValue: false });\n * }\n * ```\n */\nexport const kitCreateDidEnter = (el: ElementRef): Observable<boolean> => {\n return new Observable<boolean>((observer) => {\n const willEnter = () => observer.next(false);\n const didEnter = () => observer.next(true);\n const willLeave = () => observer.next(false);\n\n el.nativeElement.addEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.addEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.addEventListener('ionViewWillLeave', willLeave);\n\n return () => {\n el.nativeElement.removeEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.removeEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.removeEventListener('ionViewWillLeave', willLeave);\n };\n }).pipe(startWith(false));\n};\n","/*\n * Public API Surface of @rdlabo/ionic-angular-kit\n */\n\n// Storage: typed wrapper around the platform key/value store.\nexport * from './lib/storage/kit-storage.service';\n// Remember/recall the last entered sign-in email (validated; storage-agnostic helpers).\nexport * from './lib/storage/kit-auth-email-store';\n\n// Overlay: wrapper around the Ionic Modal / Toast / Alert controllers.\nexport * from './lib/overlay/overlay-config';\nexport * from './lib/overlay/kit-overlay.controller';\nexport * from './lib/overlay/kit-loading.controller';\nexport * from './lib/overlay/kit-reload-alert.controller';\nexport * from './lib/overlay/kit-auth-failed-alert';\nexport * from './lib/overlay/kit-language-action-sheet';\n\n// Directives.\nexport * from './lib/directives/auth-input.directive';\n\n// Keyboard: native keyboard reposition listeners.\nexport * from './lib/keyboard/kit-keyboard';\n\n// Theme (`@rdlabo/ionic-angular-kit/theme`), Review (`.../review`), Printer (`.../printer`) and\n// Firebase auth (`.../auth-firebase`) are separate secondary entry points so their heavy native peers\n// (status-bar / in-app-review+preferences / brotherprint+dom-to-image / @angular/fire+firebase) are\n// only pulled in by apps that import those subpaths.\n\n// Auth: functional route guards.\nexport * from './lib/auth/auth-guards';\n\n// HTTP: functional interceptor.\nexport * from './lib/http/kit-http.interceptor';\n\n// Utils: framework-agnostic pure helpers.\nexport * from './lib/utils/haptics';\nexport * from './lib/utils/array';\nexport * from './lib/utils/object';\nexport * from './lib/utils/dom';\nexport * from './lib/utils/ionic-scroll-event';\nexport * from './lib/utils/ionic-view-enter';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;AAqBG;MAIU,iBAAiB,CAAA;;IAEnB,MAAM,GAAqB,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE;AAE5D;;;;;;;;;;;AAWG;AACH,IAAA,MAAM,GAAG,CAAI,GAAW,EAAE,KAAQ,EAAA;AAChC,QAAA,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC;IAC3C;AAEA;;;;;;;;;;AAUG;IACH,MAAM,GAAG,CAAI,GAAW,EAAA;AACtB,QAAA,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;IACrD;AAEA;;;;;AAKG;IACH,MAAM,MAAM,CAAC,GAAW,EAAA;QACtB,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC;IACvC;AAEA;;;;AAIG;AACH,IAAA,MAAM,KAAK,GAAA;QACT,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE;IACnC;AAEA;;;;AAIG;AACH,IAAA,MAAM,IAAI,GAAA;QACR,OAAO,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE;IACnC;+GA7DW,iBAAiB,EAAA,IAAA,EAAA,EAAA,EAAA,MAAA,EAAA,EAAA,CAAA,eAAA,CAAA,UAAA,EAAA,CAAA,CAAA;AAAjB,IAAA,SAAA,IAAA,CAAA,KAAA,GAAA,EAAA,CAAA,qBAAA,CAA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":3,"file":"rdlabo-ionic-angular-kit.mjs","sources":["../../../projects/kit/src/lib/storage/kit-storage.service.ts","../../../projects/kit/src/lib/storage/kit-auth-email-store.ts","../../../projects/kit/src/lib/overlay/overlay-config.ts","../../../projects/kit/src/lib/utils/haptics.ts","../../../projects/kit/src/lib/overlay/kit-overlay.controller.ts","../../../projects/kit/src/lib/overlay/kit-loading.controller.ts","../../../projects/kit/src/lib/overlay/kit-reload-alert.controller.ts","../../../projects/kit/src/lib/overlay/kit-auth-failed-alert.ts","../../../projects/kit/src/lib/overlay/kit-language-action-sheet.ts","../../../projects/kit/src/lib/directives/auth-input.directive.ts","../../../projects/kit/src/lib/keyboard/kit-keyboard.ts","../../../projects/kit/src/lib/auth/auth-guards.ts","../../../projects/kit/src/lib/http/kit-http.interceptor.ts","../../../projects/kit/src/lib/utils/array.ts","../../../projects/kit/src/lib/utils/object.ts","../../../projects/kit/src/lib/utils/dom.ts","../../../projects/kit/src/lib/utils/ionic-scroll-event.ts","../../../projects/kit/src/lib/utils/ionic-view-enter.ts","../../../projects/kit/src/public-api.ts","../../../projects/kit/src/rdlabo-ionic-angular-kit.ts"],"sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { Storage } from '@ionic/storage-angular';\n\n/**\n * Thin, typed wrapper around `@ionic/storage-angular`.\n *\n * Starts `create()` exactly once and stores the resulting ready Promise. Every operation awaits\n * that Promise before touching the underlying store, so calls made before initialization completes\n * are queued rather than dropped.\n *\n * @remarks\n * A naive wrapper that reads the store synchronously would silently no-op (or throw) when invoked\n * before `create()` resolves, losing early writes. Awaiting the one-time ready Promise on every\n * operation removes that race without forcing callers to coordinate initialization themselves.\n *\n * @example\n * ```ts\n * constructor(private readonly storage: KitStorageService) {}\n *\n * async ngOnInit(): Promise<void> {\n * await this.storage.set('token', 'abc123');\n * const token = await this.storage.get<string>('token');\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitStorageService {\n /** One-time `create()` ready Promise; awaited before every operation so early calls are not lost. */\n readonly #ready: Promise<Storage> = inject(Storage).create();\n\n /**\n * Persist a value under the given key.\n *\n * @typeParam T - type of the value being stored\n * @param key - key to store the value under\n * @param value - value to persist; overwrites any existing value for the key\n * @returns a Promise that resolves once the value has been written\n * @example\n * ```ts\n * await storage.set('user', { id: 1, name: 'Ada' });\n * ```\n */\n async set<T>(key: string, value: T): Promise<void> {\n await (await this.#ready).set(key, value);\n }\n\n /**\n * Read the value stored under the given key.\n *\n * @typeParam T - expected type of the stored value\n * @param key - key to read\n * @returns the stored value, or `null` when the key is absent\n * @example\n * ```ts\n * const user = await storage.get<{ id: number }>('user');\n * ```\n */\n async get<T>(key: string): Promise<T | null> {\n return (await (await this.#ready).get(key)) ?? null;\n }\n\n /**\n * Remove the value stored under the given key.\n *\n * @param key - key to remove; a no-op when the key is absent\n * @returns a Promise that resolves once the key has been removed\n */\n async remove(key: string): Promise<void> {\n await (await this.#ready).remove(key);\n }\n\n /**\n * Remove every key/value pair from the store.\n *\n * @returns a Promise that resolves once the store has been emptied\n */\n async clear(): Promise<void> {\n await (await this.#ready).clear();\n }\n\n /**\n * List every key currently present in the store.\n *\n * @returns an array of all stored keys\n */\n async keys(): Promise<string[]> {\n return (await this.#ready).keys();\n }\n}\n","/**\n * Remember the email a user last entered on the sign-in form so the field can be prefilled next\n * time (the password is never stored).\n *\n * @remarks\n * Storage-agnostic: the helpers take a minimal async key/value store that {@link KitStorageService}\n * satisfies structurally, so they stay pure and unit-testable without DI. `kitRememberEmail`\n * **validates the address before persisting** — a malformed or partial string is silently ignored,\n * so a garbage entry (or a fat-fingered attempt) never becomes the next prefill. A well-formed email\n * that later fails to sign in is still remembered by design: the user simply re-enters/corrects it.\n *\n * These live in the main entry (next to {@link KitStorageService}) rather than in `auth-firebase`,\n * so the `KitAutofillDirective` can consume them without the main entry depending on the Firebase\n * entry.\n */\n\n/** Minimal async key/value store — structurally satisfied by `KitStorageService`. */\nexport interface KitEmailStore {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n remove(key: string): Promise<void>;\n}\n\n/** Storage key under which the last entered sign-in email is kept. */\nexport const KIT_LAST_AUTH_EMAIL_KEY = 'kit:last-auth-email';\n\n/**\n * Angular's `Validators.email` pattern — a pragmatic, RFC-5322-inspired address check. Kept in sync\n * with `@angular/forms` so a value we persist would also pass the form's own email validation.\n */\nconst EMAIL_REGEXP =\n /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(?:\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\n\n/** Whether `email` is a well-formed address (matches `@angular/forms` `Validators.email`). */\nexport const kitIsValidEmail = (email: string): boolean => EMAIL_REGEXP.test(email);\n\n/**\n * Persist the entered email for next time — but only when it is a well-formed address.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @param email - the entered email; ignored (not stored) when malformed\n * @returns `true` when the value passed validation and was stored, `false` when it was ignored\n */\nexport const kitRememberEmail = async (store: KitEmailStore, email: string): Promise<boolean> => {\n if (!kitIsValidEmail(email)) {\n return false;\n }\n await store.set(KIT_LAST_AUTH_EMAIL_KEY, email);\n return true;\n};\n\n/**\n * Recall the last remembered email.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @returns the stored email, or `null` when none has been remembered\n */\nexport const kitRecallEmail = (store: KitEmailStore): Promise<string | null> =>\n store.get<string>(KIT_LAST_AUTH_EMAIL_KEY);\n\n/**\n * Forget the remembered email.\n *\n * @remarks\n * Called when the user intentionally clears or invalidates the field, so a stale prefill is not\n * resurrected next time.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n */\nexport const kitForgetEmail = (store: KitEmailStore): Promise<void> =>\n store.remove(KIT_LAST_AUTH_EMAIL_KEY);\n","import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\n\n/**\n * User-visible button labels consumed by `KitOverlayController`.\n *\n * @remarks\n * The kit deliberately ships no i18n strings of its own and has no hard dependency on\n * `@angular/localize`. The consuming application always provides these labels: multilingual apps\n * pass `$localize`-resolved strings, single-language apps pass plain literals.\n */\nexport interface KitLabels {\n /** Text for the \"close\" button used by alerts and toasts. */\n readonly close: string;\n /** Text for the \"cancel\" button used by confirmation alerts. */\n readonly cancel: string;\n}\n\n/**\n * Overlay configuration injected via `provideKitOverlay()`.\n *\n * @remarks\n * All fields are required; the consuming application must supply a complete configuration.\n */\nexport interface KitOverlayConfig {\n /** Button labels used across the overlays presented by `KitOverlayController`. */\n readonly labels: KitLabels;\n}\n\n/**\n * Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.\n *\n * @remarks\n * Provide it through {@link provideKitOverlay} rather than registering it directly.\n */\nexport const KIT_OVERLAY_CONFIG = new InjectionToken<KitOverlayConfig>('@rdlabo/ionic-angular-kit:overlay');\n\n/**\n * Wire `KitOverlayController` into the application by providing its button labels.\n *\n * @param config - overlay configuration, including the button labels to inject\n * @returns environment providers to add to the application's provider list\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideKitOverlay({ labels: { close: $localize`Close`, cancel: $localize`Cancel` } }),\n * ],\n * });\n * ```\n */\nexport const provideKitOverlay = (config: KitOverlayConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_OVERLAY_CONFIG, useValue: config }]);\n","import { Capacitor } from '@capacitor/core';\nimport { Haptics, ImpactStyle } from '@capacitor/haptics';\n\n/**\n * Trigger native haptic impact feedback.\n *\n * Delegates to `@capacitor/haptics` `Haptics.impact()` when running on a native platform. On the\n * web (or any non-native platform) it is a no-op and resolves without doing anything.\n *\n * @remarks\n * This haptic side effect was previously bundled implicitly into toast/modal presentation. It has\n * been decoupled into this explicit function so callers opt in to the feedback deliberately, rather\n * than receiving it as a hidden side effect of presenting UI.\n *\n * @param style - The impact intensity to play. Defaults to {@link ImpactStyle.Light}.\n * @returns A promise that resolves once the feedback has been requested (immediately on the web).\n * @example\n * ```ts\n * import { ImpactStyle } from '@capacitor/haptics';\n *\n * // Light tap (default)\n * await kitImpact();\n *\n * // Stronger feedback, e.g. on a confirming action\n * await kitImpact(ImpactStyle.Heavy);\n * ```\n */\nexport const kitImpact = async (style: ImpactStyle = ImpactStyle.Light): Promise<void> => {\n if (Capacitor.isNativePlatform()) {\n await Haptics.impact({ style });\n }\n};\n","import { inject, Injectable } from '@angular/core';\nimport type { InputSignalWithTransform } from '@angular/core';\nimport type { ModalOptions, PopoverOptions, ToastOptions } from '@ionic/angular/standalone';\nimport { AlertController, ModalController, PopoverController, ToastController } from '@ionic/angular/standalone';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Capacitor } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\nimport { kitImpact } from '../utils/haptics';\n\n/**\n * Options for {@link KitOverlayController.presentModal}.\n *\n * @remarks\n * Extends Ionic's `ModalOptions` but omits `component` and `componentProps`, which are passed as\n * dedicated arguments instead.\n */\nexport interface KitModalPresentOptions extends Omit<ModalOptions, 'component' | 'componentProps'> {\n /**\n * When `true`, expand the sheet to its maximum breakpoint while the native keyboard is shown.\n *\n * @remarks\n * Only has an effect on native platforms; ignored on the web.\n */\n watchKeyboard?: boolean;\n}\n\n/**\n * Optional static metadata a modal component may declare to make {@link KitOverlayController.presentModal}\n * type-safe in its dismiss data: the value passed to `dismiss()` is inferred from `modalReturn`.\n *\n * @remarks\n * Props do *not* need to be declared here — {@link KitOverlayController.presentModal} infers them directly\n * from the component's `input()` fields (see {@link ModalPropsOf}), so `input()` stays the single source of\n * truth and can never drift from a hand-written declaration. Only the dismiss-data shape, which has no\n * counterpart on the component, is declared — as a `declare static modalReturn` phantom type with no runtime\n * value, so it adds nothing to the bundle.\n *\n * @example\n * ```ts\n * export class EditPage {\n * declare static modalReturn: { saved: boolean };\n * readonly id = input.required<number>(); // props are inferred from here\n * readonly note = input<string>(); // default-less input() → optional prop\n * }\n *\n * // Caller — `id` is required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\nexport interface ModalMetadata<R = unknown> {\n /** Shape of the data the modal resolves with when dismissed. */\n modalReturn?: R;\n}\n\n/**\n * Write type of a signal `input()` field (unwraps `input.required`, `input()` and transform inputs).\n *\n * @remarks\n * Matched with `any` (not `unknown`): `InputSignalWithTransform`'s `TransformT` is contravariant, so\n * `InputSignal<number>` is not assignable to `InputSignalWithTransform<unknown, unknown>`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InputWriteType<F> = F extends InputSignalWithTransform<any, infer W> ? W : never;\n\n/** Instance type of a component constructor; `never` for non-class components (string / HTMLElement refs). */\ntype InstanceOf<C> = C extends abstract new (...args: never[]) => infer I ? I : never;\n\n/** Keys of the `input()` signal fields on a component instance. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InputFieldKeys<I> = { [K in keyof I]-?: I[K] extends InputSignalWithTransform<any, any> ? K : never }[keyof I];\n\n/**\n * Props object inferred from a component's `input()` fields. Required vs. optional is decided by the write\n * type: `input.required<T>()` / `input<T>(default)` yield `T` (no `undefined`) → required prop, while a\n * default-less `input<T>()` yields `T | undefined` → optional prop.\n *\n * @remarks\n * Angular's types cannot distinguish `input.required<T>()` from a defaulted `input<T>(default)` — both are\n * `InputSignal<T>` — so a defaulted input is (safely) treated as required. Declare inputs you want to omit at\n * the call site as default-less `input<T>()`.\n */\ntype ModalPropsOf<I> = { [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? never : K]: InputWriteType<I[K]> } & {\n [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? K : never]?: InputWriteType<I[K]>;\n};\n\n/** `input()` keys whose write type excludes `undefined` (required / defaulted inputs). Empty when none. */\ntype RequiredInputKeys<I> = { [K in InputFieldKeys<I>]: undefined extends InputWriteType<I[K]> ? never : K }[InputFieldKeys<I>];\n\n/**\n * Dismiss-data type inferred from a component's static {@link ModalMetadata.modalReturn}. A component that\n * declares no `modalReturn` resolves to `void`: it is treated as returning no dismiss data, so the compiler\n * rejects any attempt to read the result. Declare `modalReturn` on modals that do resolve with data.\n */\ntype ModalReturnOf<C> = C extends { modalReturn: infer R } ? R : void;\n\n/** Loose trailing args (optional, untyped props) — used when a component exposes no signal `input()` fields. */\ntype LooseModalPresentArgs = [componentProps?: ModalOptions['componentProps'], options?: KitModalPresentOptions];\n\n/**\n * Trailing `presentModal` args derived from a component's `input()` fields: props are inferred and typed via\n * {@link ModalPropsOf}. When the component declares at least one required input the props argument is required;\n * when every input is optional the props argument itself is optional. Components with no signal inputs (plain\n * classes, `@Input()`-decorator components, or non-class refs) fall back to loose, untyped props.\n */\ntype ModalPresentArgs<C, I = InstanceOf<C>> = [I] extends [never]\n ? LooseModalPresentArgs\n : [InputFieldKeys<I>] extends [never]\n ? LooseModalPresentArgs\n : [RequiredInputKeys<I>] extends [never]\n ? [componentProps?: ModalPropsOf<I>, options?: KitModalPresentOptions]\n : [componentProps: ModalPropsOf<I>, options?: KitModalPresentOptions];\n\nconst BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX = 8;\n\n/**\n * Returns a visible `ion-tab-bar` suitable for anchoring a bottom toast above it.\n *\n * Skips `slot=\"top\"` bars (e.g. airlec desktop layout) and prefers the bar closest to the viewport bottom\n * when multiple candidates exist.\n */\nfunction findVisibleBottomTabBar(): HTMLElement | undefined {\n let best: HTMLElement | undefined;\n let bestBottom = -1;\n\n for (const tabBar of Array.from(document.querySelectorAll('ion-tab-bar'))) {\n if (!(tabBar instanceof HTMLElement)) continue;\n if (tabBar.getAttribute('slot') === 'top') continue;\n\n const rect = tabBar.getBoundingClientRect();\n if (rect.height <= 0) continue;\n\n const slot = tabBar.getAttribute('slot');\n const isBottom =\n slot === 'bottom' ||\n (slot === null && rect.bottom >= window.innerHeight - BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX);\n if (!isBottom) continue;\n\n if (rect.bottom > bestBottom) {\n bestBottom = rect.bottom;\n best = tabBar;\n }\n }\n\n return best;\n}\n\n/**\n * Options for {@link KitOverlayController.alertClose}.\n */\nexport interface KitAlertCloseOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /** Optional alert sub-header text shown beneath the header. */\n subHeader?: string;\n}\n\n/**\n * Options for {@link KitOverlayController.alertConfirm}.\n *\n * @remarks\n * Extends {@link KitAlertCloseOptions} with the confirm-button text.\n */\nexport interface KitAlertConfirmOptions extends KitAlertCloseOptions {\n /**\n * Text for the OK (confirm) button.\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n */\n okText: string;\n}\n\n/**\n * Attach a native keyboard listener that grows the modal to its maximum breakpoint when the\n * keyboard appears.\n *\n * @param modal - the presented modal element to resize\n * @returns a listener handle; on non-native platforms a no-op handle whose `remove()` does nothing\n * @internal\n */\nconst watchModalKeyboard = async (modal: HTMLIonModalElement): Promise<PluginListenerHandle> => {\n if (!Capacitor.isNativePlatform()) {\n return { remove: async () => undefined };\n }\n return Keyboard.addListener('keyboardDidShow', () => modal.setCurrentBreakpoint(1));\n};\n\n/**\n * Ergonomic wrapper that consolidates Ionic's overlay controllers (Modal / Toast / Alert).\n *\n * @remarks\n * Folds the repetitive create → present → onDidDismiss sequence into single calls and returns the\n * relevant result directly. It holds no application-specific policy such as navigation; compose\n * those concerns on the consuming side.\n *\n * @example\n * ```ts\n * constructor(private readonly overlay: KitOverlayController) {}\n *\n * async edit(): Promise<void> {\n * const result = await this.overlay.presentModal(EditPage, { id: 1 });\n * if (result) {\n * await this.overlay.presentToast({ message: 'Saved' });\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitOverlayController {\n readonly #modalCtrl = inject(ModalController);\n readonly #popoverCtrl = inject(PopoverController);\n readonly #toastCtrl = inject(ToastController);\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n\n /**\n * Guards against stacking alerts: while one {@link alertClose} / {@link alertConfirm} is on screen,\n * a concurrent call resolves immediately (close: no-op, confirm: `false`) instead of presenting a\n * second alert on top of the first. Shared across both methods so a confirm cannot stack over a close.\n */\n #alertPresenting = false;\n\n /**\n * Present a modal and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the modal is dismissed\n * @param component - the component to render inside the modal\n * @param componentProps - props to pass to the modal component\n * @param options - additional modal options, including {@link KitModalPresentOptions.watchKeyboard}\n * @returns the dismiss data, or `undefined` when the modal is dismissed without data\n * @remarks\n * Presenting a modal triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentPopover} and {@link presentToast}.\n *\n * Props are inferred from the component's `input()` fields (see {@link ModalPropsOf}): required inputs\n * become required props, so the compiler rejects a call that omits them. The return type is inferred from\n * a static `modalReturn` (see {@link ModalMetadata}); a component with no `modalReturn` resolves to `void`\n * — the modal is treated as returning no dismiss data.\n * @example\n * ```ts\n * // Inferred — `id` required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\n presentModal<C extends ModalOptions['component']>(component: C, ...args: ModalPresentArgs<C>): Promise<ModalReturnOf<C> | undefined>;\n async presentModal(\n component: ModalOptions['component'],\n componentProps?: ModalOptions['componentProps'],\n options: KitModalPresentOptions = {},\n ): Promise<unknown> {\n void kitImpact();\n const { watchKeyboard, ...modalOptions } = options;\n const modal = await this.#modalCtrl.create({ component, componentProps, ...modalOptions });\n await modal.present();\n const handle = watchKeyboard ? await watchModalKeyboard(modal) : null;\n const { data } = await modal.onDidDismiss<unknown>();\n await handle?.remove();\n return data;\n }\n\n /**\n * Present a popover and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the popover is dismissed\n * @param component - the component to render inside the popover\n * @param componentProps - props to pass to the popover component\n * @param options - additional popover options (for example `event` to anchor it, or `cssClass`)\n * @returns the dismiss data, or `undefined` when the popover is dismissed without data\n * @remarks\n * Presenting a popover triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentModal} and {@link presentToast}.\n * @example\n * ```ts\n * const choice = await overlay.presentPopover<MenuChoice>(MenuPopover, { items }, { event });\n * ```\n */\n async presentPopover<O = unknown>(\n component: PopoverOptions['component'],\n componentProps?: PopoverOptions['componentProps'],\n options: Omit<PopoverOptions, 'component' | 'componentProps'> = {},\n ): Promise<O | undefined> {\n void kitImpact();\n const popover = await this.#popoverCtrl.create({ component, componentProps, ...options });\n await popover.present();\n const { data } = await popover.onDidDismiss<O>();\n return data;\n }\n\n /**\n * Present a toast using kit defaults that the caller may override.\n *\n * @remarks\n * Defaults to a bottom position, a 2000ms duration, a vertical swipe gesture, and a close button\n * from the configured labels; any of these can be overridden via `options`. Presenting a toast\n * also triggers light native haptic feedback as an intentional kit UX choice.\n *\n * Bottom is the fleet-wide default (top left the toast fighting the tab bar and the keyboard).\n * For a bottom toast with no explicit `positionAnchor`, if a visible bottom `ion-tab-bar` is present the\n * toast is automatically anchored above it (Ionic places a bottom toast above its `positionAnchor`),\n * so the toast never sits behind the tabs. Bars with `slot=\"top\"` are ignored (desktop layouts that move\n * tabs to the header). Avoiding the on-screen keyboard is handled by the native keyboard resize — the\n * anchored/bottom toast rides the shrinking viewport above the keyboard;\n * Ionic itself has no toast keyboard-avoidance option. An app can override either via `options`.\n *\n * @param options - Ionic toast options that override the kit defaults\n * @returns the presented toast element\n * @example\n * ```ts\n * await overlay.presentToast({ message: 'Copied to clipboard' });\n * ```\n */\n async presentToast(options: ToastOptions): Promise<HTMLIonToastElement> {\n void kitImpact();\n const merged: ToastOptions = {\n position: 'bottom',\n duration: 2000,\n buttons: [this.#labels.close],\n swipeGesture: 'vertical',\n ...options,\n };\n // Anchor a bottom toast above the tab bar when a bottom bar is visibly present and the caller did not\n // set an explicit anchor, so the toast clears the tabs (and rides the keyboard-resized viewport).\n if (merged.position === 'bottom' && merged.positionAnchor === undefined) {\n const tabBar = findVisibleBottomTabBar();\n if (tabBar) {\n merged.positionAnchor = tabBar;\n }\n }\n const toast = await this.#toastCtrl.create(merged);\n await toast.present();\n return toast;\n }\n\n /**\n * Present a notification alert with a single \"close\" button and wait for it to be dismissed.\n *\n * @param options - alert content (header, message, optional sub-header)\n * @returns a Promise that resolves once the alert has been dismissed\n * @remarks\n * No-ops when another alert is already presenting (see {@link alertClose} / {@link alertConfirm}\n * stacking guard).\n * @example\n * ```ts\n * await overlay.alertClose({ header: 'Done', message: 'Your changes were saved.' });\n * ```\n */\n async alertClose(options: KitAlertCloseOptions): Promise<void> {\n if (this.#alertPresenting) {\n return;\n }\n this.#alertPresenting = true;\n try {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [this.#labels.close],\n });\n await alert.present();\n await alert.onWillDismiss();\n } finally {\n this.#alertPresenting = false;\n }\n }\n\n /**\n * Present a confirmation alert with cancel and OK buttons.\n *\n * @param options - alert content plus the OK button text via {@link KitAlertConfirmOptions.okText}\n * @returns `true` when the user presses OK, `false` otherwise (cancel or backdrop dismissal)\n * @example\n * ```ts\n * const ok = await overlay.alertConfirm({\n * header: 'Delete item?',\n * message: 'This cannot be undone.',\n * okText: 'Delete',\n * });\n * if (ok) {\n * await remove();\n * }\n * ```\n * @remarks\n * Returns `false` immediately when another alert is already presenting (see {@link alertClose} /\n * {@link alertConfirm} stacking guard).\n */\n async alertConfirm(options: KitAlertConfirmOptions): Promise<boolean> {\n if (this.#alertPresenting) {\n return false;\n }\n this.#alertPresenting = true;\n try {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n { text: options.okText, role: 'confirm' },\n ],\n });\n await alert.present();\n const { role } = await alert.onWillDismiss();\n return role === 'confirm';\n } finally {\n this.#alertPresenting = false;\n }\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport type { LoadingOptions } from '@ionic/angular/standalone';\nimport { LoadingController } from '@ionic/angular/standalone';\n\n/**\n * Reference-counted wrapper around Ionic's `LoadingController` that keeps at most one loading\n * indicator on screen across concurrent async work.\n *\n * @remarks\n * Each {@link presentLoading} increments a counter and each {@link dismissLoading} decrements it; the\n * indicator is presented on the `0 → 1` transition and dismissed on the `N → 0` transition. This\n * removes the flicker / \"stuck spinner\" bugs that come from every service calling\n * `LoadingController.create/dismiss` independently.\n *\n * All operations are serialized through an internal promise chain, so a `create → present` sequence\n * can never interleave with a concurrent `dismiss`. That is what makes the counter race-safe: a\n * dismiss that arrives while the indicator is still being presented runs *after* `present()` settles\n * and therefore tears the element down instead of leaving it orphaned on screen.\n *\n * Always pair every `presentLoading()` with exactly one `dismissLoading()` — a `try/finally` is the\n * safest shape.\n *\n * @example\n * ```ts\n * constructor(private readonly loading: KitLoadingController) {}\n *\n * async save(): Promise<void> {\n * await this.loading.presentLoading({ message: 'Saving…' });\n * try {\n * await this.api.save();\n * } finally {\n * await this.loading.dismissLoading();\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitLoadingController {\n readonly #loadingCtrl = inject(LoadingController);\n\n /** Outstanding {@link presentLoading} calls not yet balanced by {@link dismissLoading}. */\n #count = 0;\n\n /** The single presented loading element, or `null` when none is on screen. */\n #loading: HTMLIonLoadingElement | null = null;\n\n /**\n * Serializes present/dismiss operations. Each call chains onto this promise, runs after the\n * previous operation has fully settled, then reads {@link #count} and acts accordingly.\n */\n #queue: Promise<void> = Promise.resolve();\n\n /**\n * Show the loading indicator, or join the one already on screen.\n *\n * @param options - Ionic loading options; only applied by the call that actually creates the\n * indicator (the `0 → 1` transition). Ignored while an indicator is already present.\n * @returns a Promise that resolves once the indicator is on screen (or immediately when one already is)\n */\n async presentLoading(options: LoadingOptions = {}): Promise<void> {\n this.#count++;\n try {\n await this.#enqueue(async () => {\n // Create only on the transition into \"something is loading\"; concurrent callers ride the same\n // element. Re-check the count in case a dismiss already balanced this call while queued.\n if (this.#count > 0 && this.#loading === null) {\n const loading = await this.#loadingCtrl.create(options);\n await loading.present();\n this.#loading = loading;\n }\n });\n } catch (error) {\n // Roll back the reference this call took: a failed create/present must not leave the counter\n // elevated, otherwise a later cycle never reaches N → 0 and the spinner stays stuck on screen.\n this.#count--;\n throw error;\n }\n }\n\n /**\n * Release one reference; dismiss the indicator once the last reference is gone.\n *\n * @returns a Promise that resolves once the reference is released (and the indicator dismissed if\n * this was the last one). No-ops when the counter is already at zero.\n */\n async dismissLoading(): Promise<void> {\n if (this.#count === 0) {\n return;\n }\n this.#count--;\n await this.#enqueue(async () => {\n // Tear down only when the last consumer is gone. Because this runs after any in-flight\n // present() has settled (via the queue), there is never an orphaned loading element.\n if (this.#count === 0 && this.#loading !== null) {\n const loading = this.#loading;\n this.#loading = null;\n await loading.dismiss();\n }\n });\n }\n\n /**\n * Append `task` to the serialization chain and return its completion.\n *\n * @remarks\n * The stored chain swallows rejections so a single failing operation cannot wedge every future\n * overlay; the returned promise still rejects so the caller observes the error.\n */\n #enqueue(task: () => Promise<void>): Promise<void> {\n const run = this.#queue.then(task);\n this.#queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AlertController } from '@ionic/angular/standalone';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\n\n/**\n * Content for {@link KitReloadAlertController.present}.\n */\nexport interface KitReloadAlertOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /**\n * Text for the reload (confirm) button, e.g. \"リフレッシュ\".\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n * The cancel button uses the configured {@link KitLabels.cancel}.\n */\n okText: string;\n}\n\n/**\n * The fleet's canonical \"network error → offer to reload\" alert, as a stateful controller.\n *\n * @remarks\n * Consolidates the good-UX variant that had drifted across the fleet into one behavior:\n *\n * - **De-dup** — never stacks; a second {@link present} while an alert is already shown is a no-op.\n * - **Backdrop lock** — `backdropDismiss: false`, so a critical network error can't be dismissed by\n * an accidental backdrop tap; the user consciously chooses cancel or reload.\n * - **Auto-dismiss on reconnect** — the presented alert is tracked, so {@link dismiss} (called from a\n * later successful response) clears a now-stale error alert instead of leaving it on screen.\n * - **Reload on confirm** — the confirm button calls `location.reload()`.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n; the\n * cancel button reuses {@link KitOverlayConfig.labels}. Because it performs navigation\n * (`location.reload()`) and holds state, it is a dedicated controller rather than part of\n * {@link KitOverlayController}, which stays free of navigation policy.\n *\n * @example\n * ```ts\n * // In an HTTP interceptor:\n * const reload = inject(KitReloadAlertController);\n * // ...on a network-class error while connected:\n * await reload.present({ header: 'ネットワークエラー', message: `…(${status})`, okText: 'リフレッシュ' });\n * // ...on any later successful response:\n * await reload.dismiss();\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitReloadAlertController {\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n #alert: HTMLIonAlertElement | null = null;\n\n /**\n * Present the reload alert, unless one is already on screen.\n *\n * @param options - alert content plus the reload-button text\n * @returns a Promise that resolves once the alert has been presented (or immediately if suppressed)\n */\n async present(options: KitReloadAlertOptions): Promise<void> {\n // この controller 経由でも直書き ion-alert でも、多重表示しない。\n if (this.#alert || document.querySelector('ion-alert')) {\n return;\n }\n const alert = await this.#alertCtrl.create({\n header: options.header,\n message: options.message,\n backdropDismiss: false,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n {\n text: options.okText,\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n this.#alert = alert;\n void alert.onDidDismiss().then(() => {\n // 別の present で置き換わっていない限り、追跡を解除する。\n if (this.#alert === alert) {\n this.#alert = null;\n }\n });\n await alert.present();\n }\n\n /**\n * Dismiss the tracked reload alert if one is showing.\n *\n * @remarks\n * Typically called from a later successful response so a stale \"network error\" alert clears once\n * connectivity is restored. A no-op when nothing is showing.\n *\n * @returns a Promise that resolves once the alert has been dismissed (or immediately if none)\n */\n async dismiss(): Promise<void> {\n const alert = this.#alert;\n this.#alert = null;\n await alert?.dismiss();\n }\n}\n","import type { AlertController } from '@ionic/angular/standalone';\n\n/**\n * Content for {@link kitPresentAuthFailedAlert}.\n */\nexport interface KitAuthFailedAlertOptions {\n /** Alert header, e.g. \"ログインできませんでした\". */\n header: string;\n /** Optional sub-header; typically the short server error code/name. */\n subHeader?: string;\n /** Alert body message; typically the server-provided detail. */\n message: string;\n /** Text for the single close button, e.g. \"閉じる\". */\n closeText: string;\n}\n\n/**\n * Present the fleet's canonical \"sign-in / token exchange failed\" alert.\n *\n * @remarks\n * Folds together the alert every token-exchange app duplicated verbatim when a startup re-login\n * fails: an informative alert (header + optional server error as sub-header + detail message) with a\n * single close button that reloads the app (`location.reload()`) so the user restarts cleanly. The\n * caller is still responsible for signing the user out around this call.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n. Kept\n * as a standalone helper (taking the `AlertController`) rather than a method on\n * {@link KitOverlayController}, which holds no navigation policy such as `location.reload()`.\n *\n * @param alertCtrl - Ionic's `AlertController`\n * @param options - alert content plus the close-button text\n * @returns a Promise that resolves once the alert has been presented\n * @example\n * ```ts\n * onAuthorized: async () => {\n * const logged = await auth.tokenLogin().catch(async (e) => {\n * await kitPresentAuthFailedAlert(alertCtrl, {\n * header: 'ログインできませんでした',\n * subHeader: e.error.error,\n * message: e.error.detail,\n * closeText: '閉じる',\n * });\n * await auth.signOut();\n * return undefined;\n * });\n * // ...\n * };\n * ```\n */\nexport const kitPresentAuthFailedAlert = async (\n alertCtrl: AlertController,\n options: KitAuthFailedAlertOptions,\n): Promise<void> => {\n const alert = await alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n {\n text: options.closeText,\n role: 'cancel',\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n await alert.present();\n};\n","import { ActionSheetController } from '@ionic/angular/standalone';\n\n/** One selectable language in {@link kitPresentLanguageActionSheet}. */\nexport interface KitLanguageOption {\n /** Button label shown to the user (e.g. `English`, `日本語`). */\n readonly text: string;\n /** Locale identifier returned when this option is chosen (e.g. `en-US`, `ja`). */\n readonly data: string;\n}\n\n/**\n * Options for {@link kitPresentLanguageActionSheet}.\n *\n * @remarks\n * The kit ships no strings or URLs of its own: labels, the locale list, and the redirect-URL mapping\n * are all supplied by the caller, so a multilingual app passes `$localize`-resolved text and its own\n * per-locale build paths.\n */\nexport interface KitLanguageActionSheetOptions {\n /** Action-sheet header text. */\n readonly header: string;\n /** Selectable languages, in display order. */\n readonly locales: readonly KitLanguageOption[];\n /** Text for the cancel button. */\n readonly cancelText: string;\n /** The currently active locale; selecting the same value is a no-op. Normalize before passing. */\n readonly currentLocale: string;\n /** The current in-app path (e.g. `router.url`), stashed so the app can restore it after the reload. */\n readonly currentPath: string;\n /** `sessionStorage` key under which {@link currentPath} is stored. */\n readonly pathnameStorageKey: string;\n /** Maps a chosen locale to the URL to navigate to (the app's per-locale build entry point). */\n readonly buildRedirectUrl: (locale: string) => string;\n /** Gate for the redirect — pass `false` (e.g. outside production) to present without navigating. */\n readonly enabled: boolean;\n}\n\n/**\n * Present a language picker and, on a new selection, reload the app at that locale's entry point.\n *\n * @remarks\n * A plain function (the `ActionSheetController` is passed in, so nothing is injected) that unifies the\n * language-switch flow duplicated across apps. On a changed selection while {@link enabled} it stashes\n * the current path in `sessionStorage` (so the app can return the user to where they were), records the\n * chosen locale in `localStorage` under `'locale'`, and calls `window.location.replace()` with the\n * app-provided URL. Because it performs navigation, it is a standalone helper rather than part of a\n * controller (mirroring `kitPresentReloadAlert` / `kitPresentAuthFailedAlert`). Centralizing it means a\n * future improvement to the switch flow lands in every app at once.\n *\n * @param actionSheetCtrl - the Ionic `ActionSheetController`\n * @param options - labels, locale list, and redirect configuration; see {@link KitLanguageActionSheetOptions}\n * @returns a Promise that resolves once presented (and, on a new selection, after the reload is triggered)\n * @example\n * ```ts\n * await kitPresentLanguageActionSheet(inject(ActionSheetController), {\n * header: $localize`言語設定`,\n * locales: [{ text: 'English', data: 'en-US' }, { text: '日本語', data: 'ja' }],\n * cancelText: $localize`キャンセル`,\n * currentLocale: normalizedLocale,\n * currentPath: this.#router.url,\n * pathnameStorageKey: StorageKeyEnum.pathnameBeforeRedirect,\n * buildRedirectUrl: (locale) => location.origin + (localePath[locale.toLowerCase()] ?? '/index.html'),\n * enabled: environment.production,\n * });\n * ```\n */\nexport const kitPresentLanguageActionSheet = async (\n actionSheetCtrl: ActionSheetController,\n options: KitLanguageActionSheetOptions,\n): Promise<void> => {\n const actionSheet = await actionSheetCtrl.create({\n header: options.header,\n buttons: [\n ...options.locales.map((locale) => ({ text: locale.text, data: locale.data })),\n { text: options.cancelText, role: 'cancel' },\n ],\n });\n await actionSheet.present();\n\n const { data } = await actionSheet.onDidDismiss();\n if (options.enabled && data && data !== options.currentLocale) {\n sessionStorage.setItem(options.pathnameStorageKey, options.currentPath);\n localStorage.setItem('locale', data);\n window.location.replace(options.buildRedirectUrl(data));\n }\n};\n","import type { OnInit } from '@angular/core';\nimport { computed, Directive, ElementRef, HostListener, inject, Injector, input } from '@angular/core';\nimport { FORM_FIELD } from '@angular/forms/signals';\nimport { Capacitor } from '@capacitor/core';\nimport { KitStorageService } from '../storage/kit-storage.service';\nimport { kitForgetEmail, kitIsValidEmail, kitRecallEmail, kitRememberEmail } from '../storage/kit-auth-email-store';\n\n/**\n * The mode of {@link KitAuthInputDirective}.\n *\n * - `'autofill'` — iOS autofill propagation only (use on the password input).\n * - `'email'` — sign-in email: prefill from storage + remember on change + forget when cleared.\n * - `'email-remember'` — sign-up email: remember on change only (no prefill, no forget).\n */\nexport type KitAuthInputMode = 'autofill' | 'email' | 'email-remember';\n\n/**\n * Input conveniences for an `ion-input` in a sign-in / sign-up form, applied via the `kitAuthInput`\n * attribute. The mode is a typed union so a typo is a compile-time error.\n *\n * 1. **iOS autofill propagation (always on, every mode).** On iOS, when the browser autofills an\n * `ion-input` (e.g. a saved password) the value is written to the underlying native `<input>`\n * but the `change` event is not forwarded to the host `ion-input`, so the Angular form model\n * never sees it. This directive mirrors the first inner-input `change` back onto the host,\n * restoring two-way binding. It is a no-op on every other platform.\n *\n * 2. **Remember / prefill the email (`'email'` and `'email-remember'`).**\n * - `'email'` (sign-in) — on init recalls the last entered email and, *only while the field is\n * still empty*, seeds it via the bound Signal Forms field, so a browser/OS autofill the user\n * actually picks always wins over the prefill. On every committed change (`ionChange`) it\n * remembers a well-formed address, or **forgets** the stored one when the field is cleared\n * (empty after trim) or holds an invalid address — the user intentionally removing the prefill.\n * - `'email-remember'` (sign-up) — remembers a well-formed address on change, but never prefills\n * and never forgets. So the first-sign-up address is captured without pre-populating a\n * stranger's email into a new-account form, and clearing the field does not wipe an email\n * remembered elsewhere.\n *\n * A well-formed email is persisted even if it later fails to sign in — by design; the user simply\n * re-enters it. A malformed/partial entry is never stored (see {@link kitRememberEmail}).\n *\n * @example\n * ```html\n * <!-- sign-in email: iOS autofill + prefill + remember/forget -->\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email\" [formField]=\"form.email\" />\n * <!-- sign-up email: remember only -->\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email-remember\" [formField]=\"form.email\" />\n * <!-- password: iOS autofill propagation only -->\n * <ion-input type=\"password\" autocomplete=\"current-password\" kitAuthInput=\"autofill\" [formField]=\"form.password\" />\n * ```\n *\n * @remarks\n * Prefill writes through the Signal Forms `FORM_FIELD` bound on the same element; with no such field\n * (e.g. `ngModel` / reactive forms) prefill is skipped — remember/forget still work off the DOM\n * event. Storage is resolved lazily so the iOS mirror still works in apps without `@ionic/storage`.\n */\n@Directive({\n selector: '[kitAuthInput]',\n standalone: true,\n})\nexport class KitAuthInputDirective implements OnInit {\n readonly #el = inject(ElementRef);\n readonly #injector = inject(Injector);\n /** The Signal Forms field bound on this same element, if any (used to seed the prefill). */\n readonly #field = inject(FORM_FIELD, { optional: true, self: true });\n\n /** Mode selector; see {@link KitAuthInputMode}. */\n readonly kitAuthInput = input<KitAuthInputMode>('autofill');\n\n constructor() {}\n\n /**\n * Register the iOS autofill workaround and, in `'email'` mode, seed the field from storage.\n */\n ngOnInit(): void {\n if (this.#prefills()) {\n void this.#prefillEmail();\n }\n if (Capacitor.getPlatform() !== 'ios') {\n return;\n }\n setTimeout(() => {\n try {\n this.#el.nativeElement.children[0].addEventListener(\n 'change',\n (e: Event) => {\n this.#el.nativeElement.value = (e.target as HTMLInputElement).value;\n },\n {\n capture: false,\n once: true,\n passive: true,\n },\n );\n } catch {\n /* empty */\n }\n }, 100); // Need some time for the ion-input to create the input element\n }\n\n /**\n * On every committed change (`ionChange`): remember a well-formed email, or — only in the\n * prefilling `'email'` (sign-in) mode — forget the stored one when the field is cleared or invalid,\n * which is the user intentionally removing the prefill. `'email-remember'` never forgets, so\n * editing the sign-up field cannot wipe an email remembered from sign-in.\n */\n @HostListener('ionChange', ['$event'])\n onIonChange(event: Event): void {\n if (!this.#remembers()) {\n return;\n }\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const value = (event as CustomEvent<{ value?: string | null }>).detail?.value ?? '';\n if (value.trim().length > 0 && kitIsValidEmail(value)) {\n void kitRememberEmail(storage, value);\n } else if (this.#forgetsOnClear()) {\n void kitForgetEmail(storage);\n }\n }\n\n /** Whether this instance persists the entered email (`'email'` or `'email-remember'`). */\n readonly #remembers = computed(() => {\n const mode = this.kitAuthInput();\n return mode === 'email' || mode === 'email-remember';\n });\n\n /** Whether this instance prefills the field from storage (`'email'` only). */\n readonly #prefills = computed(() => this.kitAuthInput() === 'email');\n\n /** Whether clearing/invalidating the field forgets the stored email (`'email'` only). */\n readonly #forgetsOnClear = computed(() => this.kitAuthInput() === 'email');\n\n /** Resolve `KitStorageService` lazily; returns `null` when storage is not configured. */\n #resolveStorage(): KitStorageService | null {\n try {\n return this.#injector.get(KitStorageService);\n } catch {\n return null;\n }\n }\n\n /**\n * Seed the bound field with the remembered email, but only while it is still empty — so a value\n * the browser/OS autofills during the async recall is not clobbered.\n */\n async #prefillEmail(): Promise<void> {\n const field = this.#field;\n if (!field) {\n return;\n }\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const last = await kitRecallEmail(storage);\n const state = field.state();\n if (last && !state.value()) {\n state.value.set(last);\n }\n }\n}\n","import type { ElementRef } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\n\n/**\n * How {@link kitKeyboardInit} adjusts the target element when the native keyboard appears.\n *\n * - `transform` — CSS `translateY(-keyboardHeight + safeAreaBottom)` for a smooth iOS animation\n * (typical for an `ion-footer`).\n * - `offset` — set the `--offset-bottom` custom property to the negative keyboard height.\n * - `keyboard-offset` — set the `--padding-bottom` custom property to the keyboard height.\n */\nexport type KitKeyboardAdjust = 'transform' | 'offset' | 'keyboard-offset';\n\nconst keyboardWillShow = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillShow', (info) => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n // https://github.com/ionic-team/ionic-framework/blob/main/core/src/components/footer/footer.tsx\n elementRef.nativeElement.classList.remove('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.add('show-keyboard');\n // SSR-safe: this callback only runs on a native keyboard event, so the global `document` /\n // `window` are never touched on the server (kitKeyboardInit returns early when not native).\n const bodyStyleDeclaration = window.getComputedStyle(document.querySelector('body') as Element);\n const safeArea = parseInt(bodyStyleDeclaration.getPropertyValue('--ion-safe-area-bottom'), 10);\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 420ms';\n elementRef.nativeElement.style.willChange = 'transform';\n requestAnimationFrame(\n () => (elementRef.nativeElement.style.transform = `translateY(${info.keyboardHeight * -1 + safeArea}px)`),\n );\n } else if (type === 'offset') {\n requestAnimationFrame(() => {\n const keyboardOffset = elementRef.nativeElement.style.getPropertyValue('--keyboard-offset');\n if (!keyboardOffset || parseInt(keyboardOffset, 10) === 0) {\n elementRef.nativeElement.style.setProperty('--offset-bottom', `${info.keyboardHeight * -1}px`);\n }\n });\n } else {\n requestAnimationFrame(() => {\n const keyboardOffset = elementRef.nativeElement.style.getPropertyValue('--keyboard-offset');\n if (!keyboardOffset || parseInt(keyboardOffset, 10) === 0) {\n elementRef.nativeElement.style.setProperty('--padding-bottom', `${info.keyboardHeight}px`);\n }\n });\n }\n });\n\nconst keyboardWillHide = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillHide', () => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n elementRef.nativeElement.classList.add('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.remove('show-keyboard');\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 0ms';\n elementRef.nativeElement.style.transform = `translateY(0px)`;\n elementRef.nativeElement.style.willChange = 'transform';\n } else if (type === 'offset') {\n elementRef.nativeElement.style.setProperty('--offset-bottom', '0px');\n } else {\n elementRef.nativeElement.style.setProperty('--padding-bottom', '0px');\n }\n });\n\nconst keyboardDidShow = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidShow', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\nconst keyboardDidHide = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidHide', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\n/**\n * Register native keyboard listeners that reposition an element when the keyboard shows/hides.\n *\n * @remarks\n * A plain function — no DI needed (it reads the platform from `Capacitor` and uses the global\n * `document`), so a component calls it directly instead of injecting a controller. SSR-safe: the\n * global `document` / `window` are only read inside native keyboard-event callbacks, which never\n * fire on the server — the `Capacitor.isNativePlatform()` guard returns `[]` first, and nothing is\n * touched at module load. A no-op on non-native platforms (returns `[]`). On native it handles the\n * iOS/Android differences (Android\n * only toggles the `footer-toolbar-padding` class on an `ion-footer` for the `transform` mode,\n * working around an Ionic footer bug). The caller owns the returned handles and must `remove()`\n * them when the view is destroyed.\n *\n * @param elementRef - The element to reposition (e.g. an `ion-footer`).\n * @param type - The adjustment strategy; see {@link KitKeyboardAdjust}.\n * @returns The registered listener handles (empty on non-native platforms).\n * @example\n * ```ts\n * export class ComposePage {\n * readonly #footer = viewChild.required<ElementRef>('footer');\n * #handles: PluginListenerHandle[] = [];\n *\n * async ngAfterViewInit() {\n * this.#handles = await kitKeyboardInit(this.#footer(), 'transform');\n * }\n * ngOnDestroy() {\n * this.#handles.forEach((h) => h.remove());\n * }\n * }\n * ```\n */\nexport const kitKeyboardInit = async (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle[]> => {\n if (!Capacitor.isNativePlatform()) {\n return [];\n }\n return [\n await keyboardWillShow(elementRef, type),\n await keyboardWillHide(elementRef, type),\n await keyboardDidShow(elementRef),\n await keyboardDidHide(elementRef),\n ];\n};\n","import type { EnvironmentProviders } from '@angular/core';\nimport { inject, InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport type { CanActivateFn, RouterStateSnapshot, UrlTree } from '@angular/router';\nimport { Router } from '@angular/router';\nimport { NavController } from '@ionic/angular/standalone';\nimport type { Observable } from 'rxjs';\nimport { map, mergeMap } from 'rxjs/operators';\n\n/**\n * Discriminated set of authentication states the guards react to.\n *\n * @remarks\n * The application is responsible for emitting these values through {@link KitAuthConfig.authState}.\n * An application that does not use a value (for example email confirmation) simply never emits it.\n *\n * - `user` — fully authenticated and verified.\n * - `confirm` — awaiting email confirmation.\n * - `required` — not authenticated.\n * - `anonymous` — signed in anonymously; the user can still be guided toward full registration.\n */\nexport type KitAuthState = 'user' | 'confirm' | 'required' | 'anonymous';\n\n/**\n * Redirect targets (route paths) used by the guards when access is denied.\n *\n * @remarks\n * Every field is required and must be provided per application, because the guards have no\n * knowledge of the host application's route layout.\n */\nexport interface KitAuthRedirects {\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is already authenticated (`user`). */\n readonly whenAuthorized: string;\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is awaiting email confirmation (`confirm`). */\n readonly whenConfirming: string;\n /** Used by {@link kitRequireConfirmingGuard}: where to navigate when the state is not `confirm`. */\n readonly whenNotConfirming: string;\n /** Used by {@link kitRequireAuthorizedGuard}: where to navigate when the state is not `user` and the fallback is not allowed. */\n readonly whenUnauthorized: string;\n}\n\n/**\n * Configuration consumed by the authentication guards, injected through {@link provideKitAuth}.\n *\n * @remarks\n * `authState` and `redirects` are required. The `onAuthorized` / `onUnauthenticated` hooks are\n * optional and default to allowing the authenticated user through (`true`) and falling through to\n * the default redirect (`false`) respectively, so an app only supplies the ones with real logic.\n */\nexport interface KitAuthConfig {\n /**\n * Source of the current authentication state.\n *\n * @remarks\n * Typically backed by the application's own auth service (for example `AuthService.isAuth()`).\n *\n * @returns A stream of {@link KitAuthState} values.\n */\n authState(): Observable<KitAuthState>;\n /**\n * Application-specific work that runs in {@link kitRequireAuthorizedGuard} after the state is confirmed to be `user`.\n *\n * @remarks\n * Typical responsibilities include token login, permission checks, terms-of-service acceptance,\n * or restoring a previously requested redirect. Optional; defaults to `true` (allow activation).\n *\n * @param state - The router state snapshot of the route being activated.\n * @returns `true` to allow activation, or a `UrlTree` to perform a custom redirect.\n */\n onAuthorized?(state: RouterStateSnapshot): Promise<boolean | UrlTree>;\n /**\n * Fallback that runs in {@link kitRequireAuthorizedGuard} when the state is `required` (not authenticated).\n *\n * @remarks\n * For example, attempt an anonymous sign-in and allow the route. Optional; defaults to `false`\n * (fall through to the default `whenUnauthorized` redirect).\n *\n * @param state - The router state snapshot of the route being activated.\n * @returns `true` to allow activation, a `UrlTree` for a custom redirect, or `false` to use the default redirect.\n */\n onUnauthenticated?(state: RouterStateSnapshot): Promise<boolean | UrlTree>;\n /** Redirect targets used by the guards. */\n redirects: KitAuthRedirects;\n}\n\n/**\n * Injection token that carries the {@link KitAuthConfig} to the authentication guards.\n */\nexport const KIT_AUTH_CONFIG = new InjectionToken<KitAuthConfig>('@rdlabo/ionic-angular-kit:auth');\n\n/**\n * Wire the authentication guard configuration into the application's dependency injection.\n *\n * @remarks\n * The factory runs inside an injection context, so it may call `inject()` (for example\n * `inject(AuthService)`) to build the configuration.\n *\n * @param configFactory - Factory that returns the {@link KitAuthConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * provideKitAuth(() => {\n * const auth = inject(AuthService);\n * return {\n * // onAuthorized / onUnauthenticated are optional (default: allow / fall through to redirect).\n * authState: () => auth.isAuth(),\n * redirects: {\n * whenAuthorized: '/',\n * whenConfirming: '/auth/confirm',\n * whenNotConfirming: '/auth/signin',\n * whenUnauthorized: 'auth',\n * },\n * };\n * });\n * ```\n */\nexport const provideKitAuth = (configFactory: () => KitAuthConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_AUTH_CONFIG, useFactory: configFactory }]);\n\n/**\n * Guard that requires the user to be unauthenticated (for example sign-in or sign-up pages).\n *\n * @remarks\n * Allows the `required` and `anonymous` states (an anonymous user is permitted to proceed to a\n * registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and a user\n * awaiting confirmation (`confirm`) is sent to `whenConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'signin', component: SigninPage, canActivate: [kitRequiredUnauthorizedGuard] }];\n * ```\n */\nexport const kitRequiredUnauthorizedGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n\n return authState().pipe(\n map((data) => {\n if (data === 'user') {\n navCtrl.setDirection('root');\n router.navigate([redirects.whenAuthorized]);\n return false;\n } else if (data === 'confirm') {\n router.navigate([redirects.whenConfirming]);\n return false;\n }\n // 'required' | 'anonymous'\n return true;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be awaiting email confirmation (`confirm`).\n *\n * @remarks\n * Any other state triggers a redirect: an `anonymous` user is sent to the authenticated area\n * (`whenAuthorized`), and every remaining state is sent to `whenNotConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'confirm', component: ConfirmPage, canActivate: [kitRequireConfirmingGuard] }];\n * ```\n */\nexport const kitRequireConfirmingGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n\n return authState().pipe(\n map((data) => {\n if (data === 'confirm') {\n return true;\n }\n navCtrl.setDirection('root');\n router.navigate([data === 'anonymous' ? redirects.whenAuthorized : redirects.whenNotConfirming]);\n return false;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be fully authenticated (`user`).\n *\n * @remarks\n * - `user` — runs {@link KitAuthConfig.onAuthorized} (token login, permission checks, and so on).\n * - `anonymous` — allowed as-is, for applications that permit anonymous browsing.\n * - `required` / `confirm` — runs {@link KitAuthConfig.onUnauthenticated}; if it resolves to `false`,\n * the user is redirected to `whenUnauthorized`.\n *\n * @param _route - The activated route snapshot (unused).\n * @param state - The router state snapshot, forwarded to the configuration hooks.\n * @returns A stream emitting the activation result: `true`, a `UrlTree`, or `false` after a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'home', component: HomePage, canActivate: [kitRequireAuthorizedGuard] }];\n * ```\n */\nexport const kitRequireAuthorizedGuard: CanActivateFn = (_route, state) => {\n const { authState, onAuthorized, onUnauthenticated, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n\n return authState().pipe(\n mergeMap(async (data) => {\n if (data === 'user') {\n // 既定は「許可」。tokenLogin / 権限確認等が必要なアプリだけ onAuthorized を渡す。\n return onAuthorized ? onAuthorized(state) : true;\n }\n if (data === 'anonymous') {\n return true;\n }\n // 既定は false(whenUnauthorized へ)。匿名ログイン等のフォールバックが要るアプリだけ渡す。\n const fallback = onUnauthenticated ? await onUnauthenticated(state) : false;\n if (fallback !== false) {\n return fallback;\n }\n navCtrl.setDirection('root');\n router.navigate([redirects.whenUnauthorized]);\n return false;\n }),\n );\n};\n","import type { EnvironmentProviders } from '@angular/core';\nimport { inject, InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport type { HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Network } from '@capacitor/network';\nimport type { Observable } from 'rxjs';\nimport { from, retry, throwError, timer } from 'rxjs';\nimport { catchError, map, mergeMap, tap, timeout } from 'rxjs/operators';\n\n/**\n * HTTP methods that are safe to retry automatically.\n *\n * @remarks\n * Non-idempotent methods (`POST` / `PATCH` / `DELETE`) are never auto-retried, because a response\n * lost *after* the server processed the write would be replayed into a duplicate write (\"saved twice\n * from one tap\"). A non-idempotent request that is genuinely safe to replay opts in by carrying an\n * `Idempotency-Key` header (which the server must honor).\n *\n * @internal\n */\nconst RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'];\n\n/**\n * Transient HTTP statuses worth retrying: `0` (network/transport failure), `408` (request timeout),\n * `429` (rate limited), and the `502` / `503` / `504` gateway-availability family. Every other status\n * is thrown immediately — a whitelist is safer than a blacklist for deciding what to replay.\n *\n * @internal\n */\nconst RETRYABLE_STATUSES = [0, 408, 429, 502, 503, 504];\n\n/**\n * Maximum number of automatic retries for a retryable request.\n *\n * @internal\n */\nconst MAX_RETRIES = 2;\n\n/**\n * Fleet-wide per-request timeout. A request with no response within this window fails with a\n * synthetic `408` (a {@link RETRYABLE_STATUSES | retryable status}). Deliberately generous — it\n * catches a genuinely hung request (dead server) without cutting off legitimately slow work such as\n * a large upload or an AI generation. `timeout({ each })` resets on every emission, so a streaming\n * response that keeps emitting is unaffected.\n *\n * @internal\n */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Parse a `Retry-After` header (delta-seconds or an HTTP-date) into milliseconds, or `null` when it\n * is absent or unparseable.\n *\n * @internal\n */\nconst parseRetryAfterMs = (error: HttpErrorResponse): number | null => {\n const header = error.headers?.get('Retry-After');\n if (!header) {\n return null;\n }\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const dateMs = Date.parse(header);\n return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());\n};\n\n/**\n * Configuration that customizes the behavior of {@link kitAuthInterceptor}, injected through {@link provideKitHttp}.\n *\n * @remarks\n * The interceptor fixes the retry policy and control flow; only the hooks below are app-specific:\n *\n * - Retries only {@link RETRYABLE_METHODS | idempotent methods} (or a request bearing an\n * `Idempotency-Key`) on a {@link RETRYABLE_STATUSES | transient status}, up to {@link MAX_RETRIES}\n * times with a short jittered backoff (honoring `Retry-After`). Writes are never auto-retried.\n * - When the device is offline it fails fast to {@link KitHttpConfig.offlineFallback} instead of\n * waiting out the retries.\n * - On a final error it classifies by status and calls the matching hook (see each hook below).\n *\n * Only {@link KitHttpConfig.getAuthHeaders} is required — it has no safe default. Every other hook is\n * optional and defaults to a no-op (or `{}` / `false` / `null` as appropriate), so an app configures\n * only the behavior that actually differs from the canonical baseline.\n */\nexport interface KitHttpConfig {\n /**\n * Produce authentication and metadata headers for the outgoing request.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values, resolved asynchronously.\n */\n getAuthHeaders(request: HttpRequest<unknown>): Promise<Record<string, string>>;\n /**\n * Produce additional headers for the outgoing request.\n *\n * @remarks\n * Optional; defaults to adding no extra headers.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values; return `{}` when none are needed.\n */\n buildExtraHeaders?(request: HttpRequest<unknown>): Record<string, string>;\n /**\n * Treat an otherwise-successful response as an error.\n *\n * @remarks\n * Optional. Some backends use a 2xx status (for example `204` / `206`) to signal a condition the\n * app wants to surface as an error rather than a success. Return `true` to throw the response so it\n * flows through the error path; the status is not in {@link RETRYABLE_STATUSES}, so it is not\n * retried and propagates to the caller. Defaults to treating every 2xx as a success.\n *\n * @param response - The successful `HttpResponse` about to be delivered.\n * @returns `true` to reject the response as an error.\n */\n treatAsError?(response: HttpResponse<unknown>): boolean;\n /**\n * Called for every successful response that completed an actual network round trip.\n *\n * @remarks\n * Responses synthesized by {@link KitHttpConfig.offlineFallback} are produced after `catchError`\n * and therefore never reach this hook, so it observes genuine successes only. A typical use is to\n * reset an \"offline\" flag once connectivity is restored. Optional; defaults to a no-op.\n *\n * @param event - The successful `HttpResponse`.\n */\n onResponse?(event: HttpResponse<unknown>): void;\n /**\n * Decide whether to pass the request straight through, skipping auth, retry, and error handling.\n *\n * @remarks\n * Useful for external URLs such as S3 or a CDN. Optional; defaults to `false` (never bypass).\n *\n * @param request - The outgoing request.\n * @returns `true` to bypass the interceptor pipeline.\n */\n bypass?(request: HttpRequest<unknown>): boolean;\n /**\n * Provide an offline short-circuit when a request fails.\n *\n * @remarks\n * Returning a non-null observable replaces the error with that response (for example a queued\n * offline result). Optional; defaults to `null` (no fallback, normal error handling proceeds).\n *\n * @param request - The request that failed (after headers were applied).\n * @param error - The error response that triggered the fallback.\n * @returns A replacement event stream, or `null` for no fallback.\n */\n offlineFallback?(request: HttpRequest<unknown>, error: HttpErrorResponse): Observable<HttpEvent<unknown>> | null;\n /**\n * Side effect to run on a `401` response (for example an expired token).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `401`.\n */\n onUnauthorized?(request: HttpRequest<unknown>): void;\n /**\n * Side effect to run on a `403` response (a permission error).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `403`.\n */\n onForbidden?(request: HttpRequest<unknown>): void;\n /**\n * UX hook for a genuine network / transport failure (status `0`) while the device reports itself\n * connected — i.e. the server is unreachable rather than the phone being offline.\n *\n * @remarks\n * Optional; defaults to a no-op. Narrow by design: it fires only for status `0` (not for `404`,\n * `429`, `5xx`, …, which have their own hooks), so a \"connection lost, reload?\" prompt is not shown\n * for server-side problems. When the device is offline it is not called at all — `offlineFallback`\n * owns that path. The kit ships {@link KitReloadAlertController} as the canonical implementation\n * (with de-dup so concurrent failures show a single alert, and auto-dismiss on reconnect).\n *\n * @param status - The HTTP status code (`0`), or a string descriptor for non-HTTP failures.\n * @returns Optionally a promise to await before continuing.\n */\n onNetworkError?(status: number | string): Promise<void> | void;\n /**\n * UX hook for a transient server-availability failure (`502` / `503` / `504`), fired after retries\n * are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op. Distinct from {@link KitHttpConfig.onNetworkError} — the device's\n * connection is fine, the server is momentarily unavailable — so the app can say \"server busy, try\n * again shortly\" rather than prompt a reload.\n *\n * @param status - `502`, `503`, or `504`.\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onServerBusy?(status: number, retryAfterSeconds?: number): void;\n /**\n * UX hook for a `429 Too Many Requests` response, fired after retries are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onRateLimited?(retryAfterSeconds?: number): void;\n /**\n * UX hook for `400` / `422` / `500` responses that carry a server-provided message.\n *\n * @remarks\n * Optional; defaults to a no-op. Note that the message comes straight from the API; prefer a\n * user-facing `userMessage` / `code` in your error contract over showing a raw developer message.\n *\n * @param message - The message extracted from the error body.\n */\n onServerError?(message: string): void;\n /**\n * Side effect for a failure while *producing* the auth headers (`getAuthHeaders` rejected).\n *\n * @remarks\n * Optional; defaults to a no-op. Because the request is never sent in this case, it does not reach\n * the response-error hooks; classify it here (for example a failed token refresh) so it does not\n * fail silently.\n *\n * @param request - The request whose headers could not be produced.\n * @param error - The error thrown by `getAuthHeaders`.\n */\n onAuthError?(request: HttpRequest<unknown>, error: unknown): void;\n}\n\n/**\n * Injection token that carries the {@link KitHttpConfig} to {@link kitAuthInterceptor}.\n */\nexport const KIT_HTTP_CONFIG = new InjectionToken<KitHttpConfig>('@rdlabo/ionic-angular-kit:http');\n\n/**\n * Wire the {@link kitAuthInterceptor} configuration into the application's dependency injection.\n *\n * @remarks\n * Register the interceptor itself separately via `provideHttpClient(withInterceptors([kitAuthInterceptor]))`.\n * The factory runs inside an injection context, so it may call `inject()`.\n *\n * @param configFactory - Factory that returns the {@link KitHttpConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideHttpClient(withInterceptors([kitAuthInterceptor])),\n * provideKitHttp(() => {\n * const auth = inject(AuthService);\n * const reload = inject(KitReloadAlertController);\n * return {\n * // Only getAuthHeaders is required; every other hook is optional and defaults to a no-op.\n * getAuthHeaders: async () => ({ Authorization: `Bearer ${await auth.token()}` }),\n * onUnauthorized: () => auth.signOut(),\n * onNetworkError: (status) =>\n * reload.present({ header: 'Network error', message: `Reload? (${status})`, okText: 'Reload' }),\n * onResponse: () => void reload.dismiss(),\n * };\n * }),\n * ],\n * });\n * ```\n */\nexport const provideKitHttp = (configFactory: () => KitHttpConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_HTTP_CONFIG, useFactory: configFactory }]);\n\n/**\n * Classify a final (post-retry) error and invoke the matching {@link KitHttpConfig} hook.\n *\n * @internal\n */\nconst dispatchError = (config: KitHttpConfig, req: HttpRequest<unknown>, error: HttpErrorResponse): void => {\n const status = error.status;\n const retryAfterMs = parseRetryAfterMs(error);\n const retryAfterSeconds = retryAfterMs === null ? undefined : Math.round(retryAfterMs / 1000);\n\n if (status === 401) {\n config.onUnauthorized?.(req);\n } else if (status === 403) {\n config.onForbidden?.(req);\n } else if (status === 0) {\n // Genuine network/transport failure. Only surface it when the device is actually connected\n // (server unreachable); when offline, offlineFallback owns the UX — a reload prompt won't help.\n void Network.getStatus().then((network) => {\n if (network.connected) {\n config.onNetworkError?.(status);\n }\n });\n } else if (status === 429) {\n config.onRateLimited?.(retryAfterSeconds);\n } else if ([502, 503, 504].includes(status)) {\n config.onServerBusy?.(status, retryAfterSeconds);\n } else if ([400, 422, 500].includes(status) && error.error?.message) {\n config.onServerError?.(error.error.message);\n }\n // Every other status (404, 418, …) is left to the caller — no generic alert.\n};\n\n/**\n * Canonical functional HTTP interceptor that applies authentication, retries, and error handling.\n *\n * @remarks\n * Behavior, driven by the injected {@link KitHttpConfig}:\n *\n * 1. Requests for which `bypass` returns `true` are forwarded untouched.\n * 2. If `getAuthHeaders` rejects, `onAuthError` is called and the request is not sent.\n * 3. Otherwise the headers from `getAuthHeaders` and `buildExtraHeaders` are merged onto a cloned request.\n * 4. On failure the request is retried up to {@link MAX_RETRIES} times, but **only** when the device\n * is online, the method is a {@link RETRYABLE_METHODS | retryable method} (or carries an\n * `Idempotency-Key`), and the status is a {@link RETRYABLE_STATUSES | transient status}. The\n * backoff is `retryCount * 500ms` plus up to 250ms of jitter, or the server's `Retry-After`.\n * When the device is offline it stops retrying immediately.\n * 5. On the final error, `offlineFallback` is consulted first; otherwise the error is classified by\n * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→\n * `onNetworkError` (when connected), `429`→`onRateLimited`, `502`/`503`/`504`→`onServerBusy`, and\n * `400`/`422`/`500` with a body message→`onServerError`.\n *\n * @param request - The outgoing request.\n * @param next - The next handler in the interceptor chain.\n * @returns A stream of HTTP events for the (possibly modified, retried, or replaced) request.\n *\n * @example\n * ```ts\n * provideHttpClient(withInterceptors([kitAuthInterceptor]));\n * ```\n */\nexport const kitAuthInterceptor: HttpInterceptorFn = (request, next) => {\n const config = inject(KIT_HTTP_CONFIG);\n\n if (config.bypass?.(request)) {\n return next(request);\n }\n\n return from(Promise.resolve(config.getAuthHeaders(request))).pipe(\n catchError((headerError: unknown) => {\n // getAuthHeaders failed → the request is never sent; classify it instead of failing silently.\n config.onAuthError?.(request, headerError);\n return throwError(() => headerError);\n }),\n mergeMap((authHeaders) => {\n const req = request.clone({ setHeaders: { ...authHeaders, ...config.buildExtraHeaders?.(request) } });\n const retryable = RETRYABLE_METHODS.includes(req.method) || req.headers.has('Idempotency-Key');\n\n const base = next(req).pipe(\n timeout({\n each: DEFAULT_TIMEOUT_MS,\n with: () => throwError(() => new HttpErrorResponse({ status: 408, statusText: 'Request Timeout', url: req.url })),\n }),\n );\n\n return base.pipe(\n map((event) => {\n // A backend may signal an error condition with a 2xx status (e.g. 204/206); surface it as an error.\n if (event instanceof HttpResponse && config.treatAsError?.(event)) {\n throw event;\n }\n return event;\n }),\n retry({\n count: MAX_RETRIES,\n delay: (error: HttpErrorResponse, retryCount: number) =>\n from(Network.getStatus()).pipe(\n mergeMap((network) => {\n // Offline → don't wait out the retries; fail fast so offlineFallback can take over.\n if (!network.connected) {\n return throwError(() => error);\n }\n // Only replay idempotent requests, and only on a transient status.\n if (!retryable || !RETRYABLE_STATUSES.includes(error.status)) {\n return throwError(() => error);\n }\n // Short linear backoff (500ms, 1000ms, …) plus jitter to de-correlate a fleet of\n // clients reconnecting at once; the server's Retry-After wins when present.\n const backoff = parseRetryAfterMs(error) ?? retryCount * 500 + Math.random() * 250;\n return timer(backoff);\n }),\n ),\n }),\n tap((event) => {\n if (event instanceof HttpResponse) {\n config.onResponse?.(event);\n }\n }),\n catchError((error: HttpErrorResponse) => {\n const fallback = config.offlineFallback?.(req, error);\n if (fallback) {\n return fallback;\n }\n dispatchError(config, req, error);\n return throwError(() => error);\n }),\n );\n }),\n );\n};\n","/**\n * Merge a newly fetched page of items into an existing list by id, keeping the result sorted.\n *\n * Items are merged by the numeric `key` field. On a duplicate `key` the item from `arrayNew` wins\n * and replaces the one in `arrayOld`. Old items whose `key` falls *inside* the window spanned by\n * `arrayNew` (between its first and last `key`) are dropped, since the freshly fetched page is the\n * authoritative copy of that window; old items *outside* the window are kept. The merged items are\n * finally sorted by `key`, ascending or descending according to `order`.\n *\n * The algorithm is:\n * 1. If both inputs are empty, return an empty array.\n * 2. Read the first (`lead`) and last (`last`) `key` values of `arrayNew` as the bounds of the\n * page's window. Keep the old items whose `key` lies *outside* that window (at or beyond the\n * extremes) and drop those strictly inside it, handling both a high-to-low page (`lead > last`)\n * and a low-to-high page (`lead < last`). A single-value page (`lead === last`) keeps all old items.\n * 3. Remove old items whose `key` already exists in `arrayNew` (new wins on duplicates).\n * 4. Concatenate `arrayNew` with the surviving old items and sort by `key` in the requested\n * direction.\n *\n * @remarks\n * Designed for infinite-scroll / paginated list merging, where each fetched page may overlap the\n * previously held items and the server returns a contiguous, ordered window of records. The `key`\n * field is treated as a number for range comparison and sorting.\n *\n * @typeParam T - Element type of both arrays. Its `key` property must be a numeric value.\n * @param arrayOld - The previously accumulated list. May be empty or nullish-safe (empty when falsy).\n * @param arrayNew - The newly fetched page of items; its `key` range defines the window that its own\n * items replace, and its items take precedence on duplicates.\n * @param key - The property of `T` used as the unique, numeric id for matching, range filtering, and sorting.\n * @param order - Sort direction by `key`: `'ASC'` for ascending or `'DESC'` for descending. Defaults to `'DESC'`.\n * @param secondaryKey - Optional second property for extra de-duplication. When provided, any\n * surviving old item whose `secondaryKey` value matches that of *any* new item is dropped before\n * the `key` merge. Useful when a record keeps a stable `key` but its secondary identity changes\n * between pages (e.g. items keyed by `id` but also grouped by `parentId`). Omit to skip this step.\n * @returns A new array containing `arrayNew` merged with the out-of-window, non-duplicate old items, sorted by `key`.\n * @example\n * ```ts\n * interface Post {\n * id: number;\n * title: string;\n * }\n *\n * const loaded: Post[] = [\n * { id: 30, title: 'c' },\n * { id: 20, title: 'b' },\n * { id: 10, title: 'a' },\n * ];\n * const nextPage: Post[] = [\n * { id: 20, title: 'b (updated)' },\n * { id: 15, title: 'a.5' },\n * ];\n *\n * // Descending merge: id 30 lies above the new page's [15, 20] window so it is kept; id 20 is\n * // inside the window and is replaced by the new value; id 10 lies below the window and is kept.\n * const merged = arrayConcatById(loaded, nextPage, 'id', 'DESC');\n * // => [{ id: 30, title: 'c' }, { id: 20, title: 'b (updated)' }, { id: 15, title: 'a.5' }, { id: 10, title: 'a' }]\n * ```\n */\nexport const arrayConcatById = <T>(\n arrayOld: T[],\n arrayNew: T[],\n key: keyof T,\n order: 'ASC' | 'DESC' = 'DESC',\n secondaryKey?: keyof T,\n): T[] => {\n if (!arrayNew.length && !arrayOld.length) {\n return [];\n }\n const lead = arrayNew[0][key] as number;\n const last = arrayNew[arrayNew.length - 1][key] as number;\n\n const filteredOld = (arrayOld || []).filter((vol) => {\n const value = vol[key] as number;\n return (lead > last && (value >= lead || value <= last)) || (lead < last && (value <= lead || value >= last)) || lead === last;\n });\n\n const secondaryFilteredOld = secondaryKey\n ? filteredOld.filter((vol) => !arrayNew.some((element) => element[secondaryKey] === vol[secondaryKey]))\n : filteredOld;\n\n const oldData = secondaryFilteredOld.filter((vol) => !arrayNew.some((element) => element[key] === vol[key]));\n const data = arrayNew.concat(oldData);\n\n const direction = order === 'ASC' ? 1 : -1;\n return data.sort((a, b) => {\n const x = a[key] as number;\n const y = b[key] as number;\n if (x > y) {\n return direction;\n }\n if (x < y) {\n return direction * -1;\n }\n return 0;\n });\n};\n","/**\n * Order-independent deep equality check.\n *\n * @remarks\n * Returns `true` when `a` and `b` serialize to the same value after their (nested) object entries are\n * sorted by key, so property order does not affect the result. Intended for cheap \"did this state\n * object change?\" comparisons.\n *\n * Caveats of the JSON-serialization approach: values that JSON drops or coerces (`undefined`,\n * functions, `NaN`, `Date`, `Map`/`Set`) are compared by their serialized form, and array element\n * order is treated as significant (arrays are not reordered in a meaningful way). Use a structural\n * deep-equal library when those cases matter.\n *\n * @param a - First object.\n * @param b - Second object.\n * @returns `true` when the two objects are deeply equal ignoring key order.\n * @example\n * ```ts\n * objectEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // => true\n * objectEqual({ a: 1 }, { a: 2 }); // => false\n * ```\n */\nexport const objectEqual = (a: object, b: object): boolean => {\n if (Object.is(a, b)) {\n return true;\n }\n const sortDeep = (obj: unknown): unknown => {\n if (typeof obj !== 'object' || !obj) {\n return undefined;\n }\n return Object.entries(obj)\n .sort()\n .map(([entryKey, value]) => [entryKey, typeof value === 'object' ? sortDeep(value) : value]);\n };\n return JSON.stringify(sortDeep(a)) === JSON.stringify(sortDeep(b));\n};\n","/**\n * Disable the button that triggered an event while an async operation runs, re-enabling it after.\n *\n * @remarks\n * Prevents the common double-submit / double-tap bug: the `event.target` button is disabled, the\n * work is awaited, and the button is re-enabled — even if the work rejects (the rejection is\n * swallowed here so the button always recovers; handle errors inside `work` if you need to react).\n *\n * @param event - The DOM event whose `target` is the button to disable (e.g. a click event).\n * @param work - The async operation to run while the button is disabled.\n * @returns A Promise that resolves once the work has settled and the button has been re-enabled.\n * @example\n * ```ts\n * async submit(event: Event): Promise<void> {\n * await disableHandler(event, this.save());\n * }\n * ```\n */\nexport const disableHandler = async (event: Event, work: Promise<void | boolean>): Promise<void> => {\n const target = event.target as HTMLButtonElement;\n target.disabled = true;\n await work.catch((): undefined => undefined);\n target.disabled = false;\n};\n","import { WritableSignal } from '@angular/core';\n\n/**\n * Toggle the `disabled` flag of a signal-held `ion-infinite-scroll` / `ion-refresher` element.\n *\n * @remarks\n * A tiny pure helper for the common pattern of stashing the completing scroll/refresher element in a\n * signal (e.g. captured from the event) and later enabling/disabling it — for instance disabling\n * infinite scroll once the last page has loaded. A no-op when the signal holds no element.\n *\n * @param completeEvent - a writable signal holding the infinite-scroll / refresher element (or nullish)\n * @param disabled - the value to set on the element's `disabled` property\n * @example\n * ```ts\n * const infinite = signal<HTMLIonInfiniteScrollElement | null>(null);\n * // ...on ionInfinite: infinite.set(ev.target); ...when no more pages:\n * kitChangeEventDisabled(infinite, true);\n * ```\n */\nexport const kitChangeEventDisabled = (\n completeEvent: WritableSignal<HTMLIonInfiniteScrollElement | HTMLIonRefresherElement | null | undefined>,\n disabled: boolean,\n): void => {\n const event = completeEvent();\n if (event) {\n event.disabled = disabled;\n }\n};\n","import { ElementRef } from '@angular/core';\nimport { Observable, startWith } from 'rxjs';\n\n/**\n * Observe an Ionic page's \"is currently entered\" state from its lifecycle DOM events.\n *\n * @remarks\n * Emits `true` on `ionViewDidEnter` and `false` on `ionViewWillEnter` / `ionViewWillLeave`, seeded\n * with `false` via `startWith`. Useful to pause/resume work (timers, video, expensive rendering)\n * while a page is off-screen in Ionic's stack navigation, without wiring the four lifecycle hooks by\n * hand. The listeners are removed when the Observable is unsubscribed.\n *\n * @param el - an `ElementRef` for the page host element (the `ion-page`)\n * @returns an Observable that emits whether the page is currently entered\n * @example\n * ```ts\n * export class FeedPage {\n * readonly #host = inject(ElementRef);\n * readonly isEntered = toSignal(kitCreateDidEnter(this.#host), { initialValue: false });\n * }\n * ```\n */\nexport const kitCreateDidEnter = (el: ElementRef): Observable<boolean> => {\n return new Observable<boolean>((observer) => {\n const willEnter = () => observer.next(false);\n const didEnter = () => observer.next(true);\n const willLeave = () => observer.next(false);\n\n el.nativeElement.addEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.addEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.addEventListener('ionViewWillLeave', willLeave);\n\n return () => {\n el.nativeElement.removeEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.removeEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.removeEventListener('ionViewWillLeave', willLeave);\n };\n }).pipe(startWith(false));\n};\n","/*\n * Public API Surface of @rdlabo/ionic-angular-kit\n */\n\n// Storage: typed wrapper around the platform key/value store.\nexport * from './lib/storage/kit-storage.service';\n// Remember/recall the last entered sign-in email (validated; storage-agnostic helpers).\nexport * from './lib/storage/kit-auth-email-store';\n\n// Overlay: wrapper around the Ionic Modal / Toast / Alert controllers.\nexport * from './lib/overlay/overlay-config';\nexport * from './lib/overlay/kit-overlay.controller';\nexport * from './lib/overlay/kit-loading.controller';\nexport * from './lib/overlay/kit-reload-alert.controller';\nexport * from './lib/overlay/kit-auth-failed-alert';\nexport * from './lib/overlay/kit-language-action-sheet';\n\n// Directives.\nexport * from './lib/directives/auth-input.directive';\n\n// Keyboard: native keyboard reposition listeners.\nexport * from './lib/keyboard/kit-keyboard';\n\n// Theme (`@rdlabo/ionic-angular-kit/theme`), Review (`.../review`), Printer (`.../printer`) and\n// Firebase auth (`.../auth-firebase`) are separate secondary entry points so their heavy native peers\n// (status-bar / in-app-review+preferences / brotherprint+dom-to-image / firebase) are\n// only pulled in by apps that import those subpaths.\n\n// Auth: functional route guards.\nexport * from './lib/auth/auth-guards';\n\n// HTTP: functional interceptor.\nexport * from './lib/http/kit-http.interceptor';\n\n// Utils: framework-agnostic pure helpers.\nexport * from './lib/utils/haptics';\nexport * from './lib/utils/array';\nexport * from './lib/utils/object';\nexport * from './lib/utils/dom';\nexport * from './lib/utils/ionic-scroll-event';\nexport * from './lib/utils/ionic-view-enter';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;AAqBG;MAIU,iBAAiB,CAAA;;IAEnB,MAAM,GAAqB,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE;AAE5D;;;;;;;;;;;AAWG;AACH,IAAA,MAAM,GAAG,CAAI,GAAW,EAAE,KAAQ,EAAA;AAChC,QAAA,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC;IAC3C;AAEA;;;;;;;;;;AAUG;IACH,MAAM,GAAG,CAAI,GAAW,EAAA;AACtB,QAAA,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;IACrD;AAEA;;;;;AAKG;IACH,MAAM,MAAM,CAAC,GAAW,EAAA;QACtB,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAA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B,EAAE,SAAS,CAAC;AAEhE,QAAA,OAAO,MAAK;YACV,EAAE,CAAC,aAAa,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,SAAS,CAAC;YACnE,EAAE,CAAC,aAAa,CAAC,mBAAmB,CAAC,iBAAiB,EAAE,QAAQ,CAAC;YACjE,EAAE,CAAC,aAAa,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,SAAS,CAAC;AACrE,QAAA,CAAC;IACH,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC3B;;ACtCA;;AAEG;AAEH;;ACJA;;AAEG;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdlabo/ionic-angular-kit",
3
- "version": "0.0.23",
3
+ "version": "0.0.24",
4
4
  "peerDependencies": {
5
5
  "@angular/common": "^21.0.0",
6
6
  "@angular/core": "^21.0.0",
@@ -20,9 +20,13 @@
20
20
  "@capacitor-community/apple-sign-in": "*",
21
21
  "@rdlabo/capacitor-brotherprint": ">=6.0.0 <9.0.0",
22
22
  "dom-to-image-more": "^3.0.0",
23
+ "firebase": ">=11 <13",
23
24
  "rxjs": "^7.8.0"
24
25
  },
25
26
  "peerDependenciesMeta": {
27
+ "firebase": {
28
+ "optional": true
29
+ },
26
30
  "@capawesome/capacitor-live-update": {
27
31
  "optional": true
28
32
  },
@@ -49,7 +53,6 @@
49
53
  }
50
54
  },
51
55
  "dependencies": {
52
- "@angular/fire": "21.0.0-rc.0",
53
56
  "tslib": "^2.3.0"
54
57
  },
55
58
  "sideEffects": false,
@@ -1,5 +1,5 @@
1
1
  import { InjectionToken, EnvironmentProviders } from '@angular/core';
2
- import { FirebaseOptions } from '@angular/fire/app';
2
+ import { FirebaseOptions } from 'firebase/app';
3
3
  import { Auth, User, UserCredential } from 'firebase/auth';
4
4
  export { User, UserCredential } from 'firebase/auth';
5
5
  import { Observable } from 'rxjs';
@@ -8,13 +8,11 @@ import { Observable } from 'rxjs';
8
8
  * DI token for the Firebase `Auth` instance.
9
9
  *
10
10
  * @remarks
11
- * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the
12
- * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned
13
- * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}
14
- * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.
11
+ * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of importing `getAuth()` in the app, so the
12
+ * Firebase SDK wiring stays isolated inside the kit: only {@link provideKitFirebase} (which binds
13
+ * this token) touches initialization; every consumer keeps injecting `KIT_FIREBASE_AUTH`.
15
14
  *
16
- * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —
17
- * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).
15
+ * The value is a `firebase/auth` `Auth` — the SDK type is exposed directly, not re-abstracted.
18
16
  */
19
17
  declare const KIT_FIREBASE_AUTH: InjectionToken<Auth>;
20
18
  /** Configuration for {@link provideKitFirebase}. */
@@ -26,11 +24,12 @@ interface KitFirebaseConfig {
26
24
  * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.
27
25
  *
28
26
  * @remarks
29
- * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its
30
- * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the
31
- * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from
32
- * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web
33
- * it uses the default (`getAuth`).
27
+ * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` with one call.
28
+ * Firebase is initialized eagerly with the vanilla `firebase/app` + `firebase/auth` SDK (no
29
+ * `@angular/fire`), and the resulting `Auth` is bound to {@link KIT_FIREBASE_AUTH}. On a native
30
+ * platform the persistence uses `indexedDBLocalPersistence`; on the web it uses the default
31
+ * (`getAuth`). Apps inject {@link KIT_FIREBASE_AUTH} and call the kit's flow functions, keeping the
32
+ * Firebase SDK isolated inside the kit.
34
33
  *
35
34
  * @example
36
35
  * ```ts
@@ -42,6 +41,10 @@ interface KitFirebaseConfig {
42
41
  declare const provideKitFirebase: (config: KitFirebaseConfig) => EnvironmentProviders;
43
42
  /**
44
43
  * Wire Firebase Analytics into the application (optional; only the apps that use it call this).
44
+ *
45
+ * @remarks
46
+ * Analytics is initialized eagerly against the already-initialized Firebase app, so this must be
47
+ * called after (or alongside) {@link provideKitFirebase}.
45
48
  */
46
49
  declare const provideKitFirebaseAnalytics: () => EnvironmentProviders;
47
50
 
@@ -153,8 +156,8 @@ declare const kitSendEmailVerification: (auth: Auth, hooks?: KitAuthHooks) => Pr
153
156
  *
154
157
  * @remarks
155
158
  * For use inside {@link kitReauthWithRetry}'s `mutate` callback (after re-authentication). Uses the
156
- * same `@angular/fire/auth` module as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch
157
- * cannot silently no-op.
159
+ * same `firebase/auth` copy as {@link KIT_FIREBASE_AUTH} so the dual-firebase-sdk mismatch cannot
160
+ * silently no-op.
158
161
  */
159
162
  declare const kitUpdateEmail: (user: User, newEmail: string) => Promise<void>;
160
163
  /**
@@ -183,9 +186,8 @@ declare const kitLinkEmailPassword: (auth: Auth, email: string, password: string
183
186
  * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).
184
187
  *
185
188
  * @remarks
186
- * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s
187
- * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on
188
- * teardown.
189
+ * Wraps `firebase/auth`'s `onAuthStateChanged` so consumers get an rxjs stream without pulling in
190
+ * `rxfire`. Emits the current value on subscribe and completes its listener on teardown.
189
191
  *
190
192
  * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)
191
193
  */