@rdlabo/ionic-angular-kit 22.0.0 → 22.0.1-beta.pr105.sha55308d6acf67

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.
@@ -1 +1 @@
1
- {"version":3,"file":"rdlabo-ionic-angular-kit-app-update.mjs","sources":["../../../projects/kit/app-update/src/lib/kit-app-update.provider.ts","../../../projects/kit/app-update/src/public-api.ts","../../../projects/kit/app-update/src/rdlabo-ionic-angular-kit-app-update.ts"],"sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport type { EnvironmentProviders } from '@angular/core';\nimport { Injectable, afterNextRender, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport type { UnrecoverableStateEvent, VersionEvent } from '@angular/service-worker';\nimport { filter, take } from 'rxjs';\n\nconst UPDATE_CHECK_TIMEOUT_MS = 10_000;\nconst UNRECOVERABLE_RELOAD_KEY = 'kit_sw_unrecoverable_reload';\n\n/** Configuration for Angular service-worker application updates. */\nexport interface KitAppUpdateOptions {\n /** `blocking` preserves startup safety; `background` never delays bootstrap and reloads only before interaction. */\n strategy?: 'blocking' | 'background';\n}\n\n/** Checks for a complete Angular service-worker update before users can interact with the application. */\n@Injectable({ providedIn: 'root' })\nexport class KitAppUpdateService {\n readonly #document = inject(DOCUMENT);\n readonly #updates = inject(SwUpdate);\n #initialization: Promise<void> | null = null;\n #backgroundStarted = false;\n #interactive = false;\n #reloading = false;\n\n /** Runs one startup update check and reloads directly into a downloaded version when one is available. */\n initialize(): Promise<void> {\n this.#initialization ??= this.#initialize();\n return this.#initialization;\n }\n\n async #initialize(): Promise<void> {\n if (!this.#canCheckForUpdate()) {\n return;\n }\n const checkForUpdate = async (): Promise<boolean | undefined> => withTimeout(this.#updates.checkForUpdate(), UPDATE_CHECK_TIMEOUT_MS);\n await checkForUpdate()\n .then((available) => {\n if (available) this.#document.location?.reload();\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Starts an update check that never blocks bootstrap or reloads after the application becomes interactive. */\n startBackground(): void {\n if (this.#backgroundStarted || !this.#canCheckForUpdate()) {\n return;\n }\n this.#backgroundStarted = true;\n this.#updates.versionUpdates\n .pipe(\n filter((event: VersionEvent) => event.type === 'VERSION_READY'),\n take(1),\n )\n .subscribe(() => this.#reloadBeforeInteraction());\n this.#updates.unrecoverable.pipe(take(1)).subscribe((event: UnrecoverableStateEvent) => {\n console.error('Angular service-worker state is unrecoverable', event.reason);\n this.#recoverBeforeInteraction(event.reason);\n });\n void this.#updates\n .checkForUpdate()\n .then((available) => {\n if (available) {\n this.#reloadBeforeInteraction();\n }\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Marks the first rendered application as interactive. Used by the provider's render hook. */\n markInteractive(): void {\n this.#interactive = true;\n if (!this.#reloading) {\n this.#clearRecoveryBypass();\n }\n }\n\n #canCheckForUpdate(): boolean {\n return this.#updates.isEnabled && Boolean(this.#document.defaultView?.navigator.serviceWorker?.controller);\n }\n\n #reloadBeforeInteraction(): void {\n if (this.#interactive || this.#reloading) {\n return;\n }\n this.#reloading = true;\n this.#document.location?.reload();\n }\n\n #recoverBeforeInteraction(reason: string): void {\n const location = this.#document.location;\n if (this.#interactive || this.#reloading || !location) {\n return;\n }\n const url = new URL(location.href);\n if (url.searchParams.has('sw_reload')) {\n return;\n }\n const storage = this.#document.defaultView?.sessionStorage;\n const remembered = rememberFailure(storage, reason);\n if (remembered === 'same') {\n return;\n }\n url.searchParams.set('ngsw-bypass', 'true');\n url.searchParams.set('sw_reload', '1');\n this.#reloading = true;\n location.replace(url.toString());\n }\n\n #clearRecoveryBypass(): void {\n const location = this.#document.location;\n const history = this.#document.defaultView?.history;\n if (!location || !history) {\n return;\n }\n const url = new URL(location.href);\n if (!url.searchParams.has('sw_reload')) {\n return;\n }\n url.searchParams.delete('ngsw-bypass');\n const storage = this.#document.defaultView?.sessionStorage;\n if (readFailure(storage)) {\n url.searchParams.delete('sw_reload');\n clearFailure(storage);\n }\n history.replaceState(history.state, '', url.toString());\n }\n}\n\nfunction rememberFailure(storage: Storage | undefined, reason: string): 'stored' | 'same' | 'unavailable' {\n if (!storage) {\n return 'unavailable';\n }\n let existing: string | null;\n try {\n existing = storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return 'unavailable';\n }\n if (existing === reason) {\n return 'same';\n }\n try {\n storage.setItem(UNRECOVERABLE_RELOAD_KEY, reason);\n return 'stored';\n } catch {\n return 'unavailable';\n }\n}\n\nfunction readFailure(storage: Storage | undefined): string | null {\n if (!storage) {\n return null;\n }\n try {\n return storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return null;\n }\n}\n\nfunction clearFailure(storage: Storage | undefined): void {\n try {\n storage?.removeItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n // A retained value only suppresses the same recovery reason in this tab.\n }\n}\n\n/**\n * Provides a startup check that reloads into the latest complete web application version.\n *\n * @remarks\n * The check finishes before application bootstrap so a delayed update cannot discard user input. It times out rather\n * than preventing offline startup. API deployments must remain backward compatible while a newly adopted updater is\n * rolling out because code already running in older application versions cannot gain this behavior retroactively.\n */\nexport function provideKitAppUpdate(options: KitAppUpdateOptions = {}): EnvironmentProviders {\n const initializer =\n options.strategy === 'background'\n ? provideAppInitializer(() => {\n const updates = inject(KitAppUpdateService);\n updates.startBackground();\n afterNextRender(() => updates.markInteractive());\n })\n : provideAppInitializer(() => inject(KitAppUpdateService).initialize());\n return makeEnvironmentProviders([initializer]);\n}\n\nfunction withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => resolve(undefined), timeoutMs);\n void promise.then(\n (value) => {\n window.clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n window.clearTimeout(timeout);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n","/** Automatic startup updates for Angular service-worker web applications. */\nexport * from './lib/kit-app-update.provider';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;AAOA,MAAM,uBAAuB,GAAG,MAAM;AACtC,MAAM,wBAAwB,GAAG,6BAA6B;AAQ9D;MAEa,mBAAmB,CAAA;AACrB,IAAA,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IACpC,eAAe,GAAyB,IAAI;IAC5C,kBAAkB,GAAG,KAAK;IAC1B,YAAY,GAAG,KAAK;IACpB,UAAU,GAAG,KAAK;;IAGlB,UAAU,GAAA;AACR,QAAA,IAAI,CAAC,eAAe,KAAK,IAAI,CAAC,WAAW,EAAE;QAC3C,OAAO,IAAI,CAAC,eAAe;IAC7B;AAEA,IAAA,MAAM,WAAW,GAAA;AACf,QAAA,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE;YAC9B;QACF;AACA,QAAA,MAAM,cAAc,GAAG,YAA0C,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAE,uBAAuB,CAAC;AACrI,QAAA,MAAM,cAAc;AACjB,aAAA,IAAI,CAAC,CAAC,SAAS,KAAI;AAClB,YAAA,IAAI,SAAS;AAAE,gBAAA,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE;AAClD,QAAA,CAAC;AACA,aAAA,KAAK,CAAC,CAAC,KAAc,KAAK,OAAO,CAAC,KAAK,CAAC,4CAA4C,EAAE,KAAK,CAAC,CAAC;IAClG;;IAGA,eAAe,GAAA;QACb,IAAI,IAAI,CAAC,kBAAkB,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE;YACzD;QACF;AACA,QAAA,IAAI,CAAC,kBAAkB,GAAG,IAAI;QAC9B,IAAI,CAAC,QAAQ,CAAC;AACX,aAAA,IAAI,CACH,MAAM,CAAC,CAAC,KAAmB,KAAK,KA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AAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACnE,QAAA,CAAC,CACF;AACH,IAAA,CAAC,CAAC;AACJ;;AC5MA;;ACAA;;AAEG;;;;"}
1
+ {"version":3,"file":"rdlabo-ionic-angular-kit-app-update.mjs","sources":["../../../projects/kit/app-update/src/lib/kit-app-update.provider.ts","../../../projects/kit/app-update/src/public-api.ts","../../../projects/kit/app-update/src/rdlabo-ionic-angular-kit-app-update.ts"],"sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport type { EnvironmentProviders } from '@angular/core';\nimport {\n EnvironmentInjector,\n Injectable,\n afterNextRender,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n runInInjectionContext,\n} from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport type { UnrecoverableStateEvent, VersionEvent } from '@angular/service-worker';\nimport { filter, take } from 'rxjs';\n\nconst UPDATE_CHECK_TIMEOUT_MS = 10_000;\nconst UPDATE_PROMPT_RETRY_MS = 1_000;\nconst UNRECOVERABLE_RELOAD_KEY = 'kit_sw_unrecoverable_reload';\n\n/** Asks whether a downloaded service-worker update should be applied now. `undefined` requests a later retry. */\nexport type KitAppUpdatePrompt = () => Promise<boolean | undefined>;\n\n/** Existing configuration for startup-blocking or background service-worker updates. */\nexport interface KitAppUpdateOptions {\n strategy?: 'blocking' | 'background';\n}\n\n/** Uses a non-blocking update check and asks the user before reloading. */\nexport interface KitConfirmAppUpdateOptions {\n strategy: 'confirm';\n /**\n * Runs after the first render when a complete update is ready.\n *\n * Resolve `true` to reload, `false` when the user explicitly defers, or `undefined` when UI could not be presented and\n * should be retried. The provider supplies an Angular injection context only for the callback's synchronous execution,\n * so resolve injected dependencies before crossing an async boundary.\n */\n promptForUpdate: KitAppUpdatePrompt;\n}\n\n/** Configuration accepted by {@link provideKitAppUpdate}. */\nexport type KitAppUpdateProviderOptions = (KitAppUpdateOptions & { promptForUpdate?: never }) | KitConfirmAppUpdateOptions;\n\n/** Coordinates complete Angular service-worker updates using blocking, background, or user-confirmed application. */\n@Injectable({ providedIn: 'root' })\nexport class KitAppUpdateService {\n readonly #document = inject(DOCUMENT);\n readonly #updates = inject(SwUpdate);\n #initialization: Promise<void> | null = null;\n #backgroundStarted = false;\n #interactive = false;\n #reloading = false;\n #updateReady = false;\n #prompting = false;\n #prompted = false;\n #promptRetryScheduled = false;\n #promptForUpdate: KitAppUpdatePrompt | undefined;\n\n /** Runs one startup update check and reloads directly into a downloaded version when one is available. */\n initialize(): Promise<void> {\n this.#initialization ??= this.#initialize();\n return this.#initialization;\n }\n\n async #initialize(): Promise<void> {\n if (!this.#canCheckForUpdate()) {\n return;\n }\n const checkForUpdate = async (): Promise<boolean | undefined> => withTimeout(this.#updates.checkForUpdate(), UPDATE_CHECK_TIMEOUT_MS);\n await checkForUpdate()\n .then((available) => {\n if (available) this.#document.location?.reload();\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Starts an update check that never blocks bootstrap or reloads after the application becomes interactive. */\n startBackground(): void {\n this.#startNonBlocking();\n }\n\n /** Starts a non-blocking update check and asks after the first render before applying a ready update. */\n startConfirm(promptForUpdate: KitAppUpdatePrompt): void {\n this.#startNonBlocking(promptForUpdate);\n }\n\n #startNonBlocking(promptForUpdate?: KitAppUpdatePrompt): void {\n if (this.#backgroundStarted || !this.#canCheckForUpdate()) {\n return;\n }\n this.#backgroundStarted = true;\n this.#promptForUpdate = promptForUpdate;\n this.#updates.versionUpdates\n .pipe(\n filter((event: VersionEvent) => event.type === 'VERSION_READY'),\n take(1),\n )\n .subscribe(() => this.#handleUpdateReady());\n this.#updates.unrecoverable.pipe(take(1)).subscribe((event: UnrecoverableStateEvent) => {\n console.error('Angular service-worker state is unrecoverable', event.reason);\n this.#recoverBeforeInteraction(event.reason);\n });\n void this.#updates\n .checkForUpdate()\n .then((available) => {\n if (available) {\n this.#handleUpdateReady();\n }\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Marks the first rendered application as interactive. Used by the provider's render hook. */\n markInteractive(): void {\n this.#interactive = true;\n if (!this.#reloading) {\n this.#clearRecoveryBypass();\n }\n this.#promptWhenReady();\n }\n\n #canCheckForUpdate(): boolean {\n return this.#updates.isEnabled && Boolean(this.#document.defaultView?.navigator.serviceWorker?.controller);\n }\n\n #reloadBeforeInteraction(): void {\n if (this.#interactive || this.#reloading) {\n return;\n }\n this.#reloading = true;\n this.#document.location?.reload();\n }\n\n #handleUpdateReady(): void {\n if (!this.#promptForUpdate) {\n this.#reloadBeforeInteraction();\n return;\n }\n this.#updateReady = true;\n this.#promptWhenReady();\n }\n\n #promptWhenReady(): void {\n const promptForUpdate = this.#promptForUpdate;\n if (\n !this.#interactive ||\n !this.#updateReady ||\n !promptForUpdate ||\n this.#prompting ||\n this.#prompted ||\n this.#promptRetryScheduled ||\n this.#reloading\n ) {\n return;\n }\n this.#prompting = true;\n void runUpdatePrompt(promptForUpdate)\n .then((confirmed) => {\n this.#prompting = false;\n if (confirmed === undefined) {\n this.#schedulePromptRetry();\n return;\n }\n this.#prompted = true;\n this.#applyPromptResult(confirmed);\n })\n .catch((error: unknown) => {\n this.#prompting = false;\n this.#prompted = true;\n console.error('Angular service-worker update prompt failed', error);\n });\n }\n\n #schedulePromptRetry(): void {\n if (this.#promptRetryScheduled || this.#prompted || this.#reloading) {\n return;\n }\n this.#promptRetryScheduled = true;\n globalThis.setTimeout(() => {\n this.#promptRetryScheduled = false;\n this.#promptWhenReady();\n }, UPDATE_PROMPT_RETRY_MS);\n }\n\n #applyPromptResult(confirmed: boolean): void {\n if (!confirmed || this.#reloading) {\n return;\n }\n this.#reloading = true;\n this.#document.location?.reload();\n }\n\n #recoverBeforeInteraction(reason: string): void {\n const location = this.#document.location;\n if (this.#interactive || this.#reloading || !location) {\n return;\n }\n const url = new URL(location.href);\n if (url.searchParams.has('sw_reload')) {\n return;\n }\n const storage = this.#document.defaultView?.sessionStorage;\n const remembered = rememberFailure(storage, reason);\n if (remembered === 'same') {\n return;\n }\n url.searchParams.set('ngsw-bypass', 'true');\n url.searchParams.set('sw_reload', '1');\n this.#reloading = true;\n location.replace(url.toString());\n }\n\n #clearRecoveryBypass(): void {\n const location = this.#document.location;\n const history = this.#document.defaultView?.history;\n if (!location || !history) {\n return;\n }\n const url = new URL(location.href);\n if (!url.searchParams.has('sw_reload')) {\n return;\n }\n url.searchParams.delete('ngsw-bypass');\n const storage = this.#document.defaultView?.sessionStorage;\n if (readFailure(storage)) {\n url.searchParams.delete('sw_reload');\n clearFailure(storage);\n }\n history.replaceState(history.state, '', url.toString());\n }\n}\n\nfunction rememberFailure(storage: Storage | undefined, reason: string): 'stored' | 'same' | 'unavailable' {\n if (!storage) {\n return 'unavailable';\n }\n let existing: string | null;\n try {\n existing = storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return 'unavailable';\n }\n if (existing === reason) {\n return 'same';\n }\n try {\n storage.setItem(UNRECOVERABLE_RELOAD_KEY, reason);\n return 'stored';\n } catch {\n return 'unavailable';\n }\n}\n\nfunction readFailure(storage: Storage | undefined): string | null {\n if (!storage) {\n return null;\n }\n try {\n return storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return null;\n }\n}\n\nfunction clearFailure(storage: Storage | undefined): void {\n try {\n storage?.removeItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n // A retained value only suppresses the same recovery reason in this tab.\n }\n}\n\n/**\n * Provides blocking, background, or user-confirmed adoption of complete Angular service-worker updates.\n *\n * @remarks\n * The default `blocking` strategy checks before bootstrap and times out rather than preventing offline startup. The\n * existing `background` strategy never delays bootstrap and reloads only before the first render. The opt-in `confirm`\n * strategy also checks in the background, but waits until after the first render and reloads only with user approval.\n * API deployments must remain backward compatible while an updater is rolling out because already-running older code\n * cannot gain this behavior retroactively.\n */\nexport function provideKitAppUpdate(options: KitAppUpdateProviderOptions = {}): EnvironmentProviders {\n if (options.strategy === 'confirm') {\n const promptForUpdate = options.promptForUpdate;\n if (typeof promptForUpdate !== 'function') {\n throw new Error('provideKitAppUpdate confirm strategy requires promptForUpdate');\n }\n return makeEnvironmentProviders([\n provideAppInitializer(() => {\n const updates = inject(KitAppUpdateService);\n const injector = inject(EnvironmentInjector);\n updates.startConfirm(() => runInInjectionContext(injector, promptForUpdate));\n afterNextRender(() => updates.markInteractive());\n }),\n ]);\n }\n if (options.promptForUpdate !== undefined) {\n throw new Error('provideKitAppUpdate promptForUpdate is only valid with the confirm strategy');\n }\n if (options.strategy === 'background') {\n return makeEnvironmentProviders([\n provideAppInitializer(() => {\n const updates = inject(KitAppUpdateService);\n updates.startBackground();\n afterNextRender(() => updates.markInteractive());\n }),\n ]);\n }\n return makeEnvironmentProviders([provideAppInitializer(() => inject(KitAppUpdateService).initialize())]);\n}\n\nasync function runUpdatePrompt(promptForUpdate: KitAppUpdatePrompt): Promise<boolean | undefined> {\n return promptForUpdate();\n}\n\nfunction withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => resolve(undefined), timeoutMs);\n void promise.then(\n (value) => {\n window.clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n window.clearTimeout(timeout);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n","/** Automatic startup updates for Angular service-worker web applications. */\nexport * from './lib/kit-app-update.provider';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;AAeA,MAAM,uBAAuB,GAAG,MAAM;AACtC,MAAM,sBAAsB,GAAG,KAAK;AACpC,MAAM,wBAAwB,GAAG,6BAA6B;AA0B9D;MAEa,mBAAmB,CAAA;AACrB,IAAA,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IACpC,eAAe,GAAyB,IAAI;IAC5C,kBAAkB,GAAG,KAAK;IAC1B,YAAY,GAAG,KAAK;IACpB,UAAU,GAAG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AAC;AACJ;;AC1UA;;ACAA;;AAEG;;;;"}
@@ -0,0 +1,125 @@
1
+ import { GoogleSignIn, ErrorCode } from '@capawesome/capacitor-google-sign-in';
2
+ import { Capacitor } from '@capacitor/core';
3
+ import { GoogleAuthProvider, reauthenticateWithPopup, linkWithCredential, EmailAuthProvider, signInWithPopup, linkWithPopup, signInWithCredential, reauthenticateWithCredential } from 'firebase/auth';
4
+
5
+ let initialization;
6
+ const initialize = (clientId) => {
7
+ if (!clientId) {
8
+ return Promise.reject(new Error('kit Google login: client ID is not configured'));
9
+ }
10
+ if (initialization?.clientId === clientId)
11
+ return initialization.promise;
12
+ const promise = GoogleSignIn.initialize({ clientId }).catch((error) => {
13
+ if (initialization?.promise === promise)
14
+ initialization = undefined;
15
+ throw error;
16
+ });
17
+ initialization = { clientId, promise };
18
+ return promise;
19
+ };
20
+ const requireUser = (auth) => {
21
+ if (!auth.currentUser)
22
+ throw new Error('kit Google login: no signed-in Firebase user');
23
+ return auth.currentUser;
24
+ };
25
+ const assertCurrentUser = (auth, user) => {
26
+ if (auth.currentUser !== user) {
27
+ throw new Error('kit Google login: Firebase user changed');
28
+ }
29
+ };
30
+ const classify = (error) => {
31
+ const code = error?.code;
32
+ if (code === 'auth/credential-already-in-use')
33
+ return 'already-in-use';
34
+ if (code === ErrorCode.SignInCanceled ||
35
+ code === 'auth/user-cancelled' ||
36
+ code === 'auth/popup-closed-by-user' ||
37
+ code === 'auth/cancelled-popup-request')
38
+ return 'cancelled';
39
+ return 'other';
40
+ };
41
+ const kitGoogleLogin = async (auth, options) => {
42
+ const execute = async () => {
43
+ await options.before?.();
44
+ const expectedUser = auth.currentUser;
45
+ let idToken;
46
+ let user;
47
+ if (Capacitor.getPlatform() === 'web') {
48
+ const provider = new GoogleAuthProvider();
49
+ if (options.mode === 'reauthenticate') {
50
+ user = requireUser(auth);
51
+ const result = await reauthenticateWithPopup(user, provider);
52
+ idToken = GoogleAuthProvider.credentialFromResult(result)?.idToken ?? '';
53
+ assertCurrentUser(auth, user);
54
+ await options.success?.({ idToken, mode: options.mode, user });
55
+ assertCurrentUser(auth, user);
56
+ return;
57
+ }
58
+ if (options.mode === 'credential') {
59
+ user = requireUser(auth);
60
+ await reauthenticateWithPopup(user, provider);
61
+ assertCurrentUser(auth, user);
62
+ await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));
63
+ assertCurrentUser(auth, user);
64
+ await options.success?.({ idToken: '', mode: options.mode, user });
65
+ assertCurrentUser(auth, user);
66
+ return;
67
+ }
68
+ const result = options.mode === 'new' ? await signInWithPopup(auth, provider) : await linkWithPopup(requireUser(auth), provider);
69
+ const credential = GoogleAuthProvider.credentialFromResult(result);
70
+ if (!credential?.idToken)
71
+ throw new Error('kit Google login: ID token is missing');
72
+ idToken = credential.idToken;
73
+ user = result.user;
74
+ }
75
+ else {
76
+ await initialize(options.clientId);
77
+ idToken = (await GoogleSignIn.signIn()).idToken;
78
+ const credential = GoogleAuthProvider.credential(idToken);
79
+ if (options.mode === 'new')
80
+ user = (await signInWithCredential(auth, credential)).user;
81
+ else {
82
+ user = requireUser(auth);
83
+ if (user !== expectedUser)
84
+ throw new Error('kit Google login: Firebase user changed');
85
+ if (options.mode === 'link')
86
+ await linkWithCredential(user, credential);
87
+ else if (options.mode === 'reauthenticate') {
88
+ await reauthenticateWithCredential(user, credential);
89
+ assertCurrentUser(auth, user);
90
+ await options.success?.({ idToken, mode: options.mode, user });
91
+ assertCurrentUser(auth, user);
92
+ return;
93
+ }
94
+ else {
95
+ await reauthenticateWithCredential(user, credential);
96
+ assertCurrentUser(auth, user);
97
+ await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));
98
+ assertCurrentUser(auth, user);
99
+ await options.success?.({ idToken, mode: options.mode, user });
100
+ assertCurrentUser(auth, user);
101
+ return;
102
+ }
103
+ }
104
+ }
105
+ assertCurrentUser(auth, user);
106
+ await options.exchange?.(idToken, user);
107
+ assertCurrentUser(auth, user);
108
+ await options.success?.({ idToken, mode: options.mode, user });
109
+ assertCurrentUser(auth, user);
110
+ };
111
+ return execute()
112
+ .then(() => ({ status: true }), async (error) => {
113
+ await options.error?.(classify(error), error);
114
+ return { status: false };
115
+ })
116
+ .finally(() => options.finally?.());
117
+ };
118
+ const kitGoogleLogout = () => GoogleSignIn.signOut().catch(() => undefined);
119
+
120
+ /**
121
+ * Generated bundle index. Do not edit.
122
+ */
123
+
124
+ export { kitGoogleLogin, kitGoogleLogout };
125
+ //# sourceMappingURL=rdlabo-ionic-angular-kit-auth-firebase-google.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-google.mjs","sources":["../../../projects/kit/auth-firebase/google/src/kit-google.ts","../../../projects/kit/auth-firebase/google/src/rdlabo-ionic-angular-kit-auth-firebase-google.ts"],"sourcesContent":["import { ErrorCode, GoogleSignIn } from '@capawesome/capacitor-google-sign-in';\nimport { Capacitor } from '@capacitor/core';\nimport type { Auth, User } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n GoogleAuthProvider,\n linkWithCredential,\n linkWithPopup,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from 'firebase/auth';\n\nexport type KitGoogleLoginMode =\n | { mode: 'new' }\n | { mode: 'link' }\n | { mode: 'reauthenticate' }\n | { mode: 'credential'; emailLogin: { email: string; password: string } };\nexport type KitGoogleErrorCategory = 'already-in-use' | 'cancelled' | 'other';\nexport type KitGoogleLoginOptions = KitGoogleLoginMode & {\n clientId: string;\n before?: () => void | Promise<unknown>;\n exchange?: (idToken: string, user: User) => void | Promise<unknown>;\n success?: (info: { idToken: string; mode: KitGoogleLoginMode['mode']; user: User }) => void | Promise<unknown>;\n error?: (category: KitGoogleErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n};\n\nlet initialization: { clientId: string; promise: Promise<void> } | undefined;\nconst initialize = (clientId: string): Promise<void> => {\n if (!clientId) {\n return Promise.reject(new Error('kit Google login: client ID is not configured'));\n }\n if (initialization?.clientId === clientId) return initialization.promise;\n const promise = GoogleSignIn.initialize({ clientId }).catch((error: unknown) => {\n if (initialization?.promise === promise) initialization = undefined;\n throw error;\n });\n initialization = { clientId, promise };\n return promise;\n};\n\nconst requireUser = (auth: Auth): User => {\n if (!auth.currentUser) throw new Error('kit Google login: no signed-in Firebase user');\n return auth.currentUser;\n};\n\nconst assertCurrentUser = (auth: Auth, user: User): void => {\n if (auth.currentUser !== user) {\n throw new Error('kit Google login: Firebase user changed');\n }\n};\n\nconst classify = (error: unknown): KitGoogleErrorCategory => {\n const code = (error as { code?: string } | null)?.code;\n if (code === 'auth/credential-already-in-use') return 'already-in-use';\n if (\n code === ErrorCode.SignInCanceled ||\n code === 'auth/user-cancelled' ||\n code === 'auth/popup-closed-by-user' ||\n code === 'auth/cancelled-popup-request'\n )\n return 'cancelled';\n return 'other';\n};\n\nexport const kitGoogleLogin = async (auth: Auth, options: KitGoogleLoginOptions): Promise<{ status: boolean }> => {\n const execute = async (): Promise<void> => {\n await options.before?.();\n const expectedUser = auth.currentUser;\n let idToken: string;\n let user: User;\n if (Capacitor.getPlatform() === 'web') {\n const provider = new GoogleAuthProvider();\n if (options.mode === 'reauthenticate') {\n user = requireUser(auth);\n const result = await reauthenticateWithPopup(user, provider);\n idToken = GoogleAuthProvider.credentialFromResult(result)?.idToken ?? '';\n assertCurrentUser(auth, user);\n await options.success?.({ idToken, mode: options.mode, user });\n assertCurrentUser(auth, user);\n return;\n }\n if (options.mode === 'credential') {\n user = requireUser(auth);\n await reauthenticateWithPopup(user, provider);\n assertCurrentUser(auth, user);\n await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));\n assertCurrentUser(auth, user);\n await options.success?.({ idToken: '', mode: options.mode, user });\n assertCurrentUser(auth, user);\n return;\n }\n const result = options.mode === 'new' ? await signInWithPopup(auth, provider) : await linkWithPopup(requireUser(auth), provider);\n const credential = GoogleAuthProvider.credentialFromResult(result);\n if (!credential?.idToken) throw new Error('kit Google login: ID token is missing');\n idToken = credential.idToken;\n user = result.user;\n } else {\n await initialize(options.clientId);\n idToken = (await GoogleSignIn.signIn()).idToken;\n const credential = GoogleAuthProvider.credential(idToken);\n if (options.mode === 'new') user = (await signInWithCredential(auth, credential)).user;\n else {\n user = requireUser(auth);\n if (user !== expectedUser) throw new Error('kit Google login: Firebase user changed');\n if (options.mode === 'link') await linkWithCredential(user, credential);\n else if (options.mode === 'reauthenticate') {\n await reauthenticateWithCredential(user, credential);\n assertCurrentUser(auth, user);\n await options.success?.({ idToken, mode: options.mode, user });\n assertCurrentUser(auth, user);\n return;\n } else {\n await reauthenticateWithCredential(user, credential);\n assertCurrentUser(auth, user);\n await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));\n assertCurrentUser(auth, user);\n await options.success?.({ idToken, mode: options.mode, user });\n assertCurrentUser(auth, user);\n return;\n }\n }\n }\n assertCurrentUser(auth, user);\n await options.exchange?.(idToken, user);\n assertCurrentUser(auth, user);\n await options.success?.({ idToken, mode: options.mode, user });\n assertCurrentUser(auth, user);\n };\n return execute()\n .then(\n () => ({ status: true }),\n async (error: unknown) => {\n await options.error?.(classify(error), error);\n return { status: false };\n },\n )\n .finally(() => options.finally?.());\n};\n\nexport const kitGoogleLogout = (): Promise<void> => GoogleSignIn.signOut().catch(() => undefined);\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;AA6BA,IAAI,cAAwE;AAC5E,MAAM,UAAU,GAAG,CAAC,QAAgB,KAAmB;IACrD,IAAI,CAAC,QAAQ,EAAE;QACb,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnF;AACA,IAAA,IAAI,cAAc,EAAE,QAAQ,KAAK,QAAQ;QAAE,OAAO,cAAc,CAAC,OAAO;AACxE,IAAA,MAAM,OAAO,G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OAAO,CAAC,MAAM,OAAO,CAAC,OAAO,IAAI,CAAC;AACvC;AAEO,MAAM,eAAe,GAAG,MAAqB,YAAY,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,MAAM,SAAS;;AC9IhG;;AAEG;;;;"}
@@ -17,7 +17,7 @@ const classifyOAuthError = (e) => {
17
17
  if (code === 'auth/credential-already-in-use') {
18
18
  return 'already-in-use';
19
19
  }
20
- if (code === 'auth/user-cancelled') {
20
+ if (code === 'auth/user-cancelled' || code === 'auth/popup-closed-by-user' || code === 'auth/cancelled-popup-request') {
21
21
  return 'cancelled';
22
22
  }
23
23
  return 'other';
@@ -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 '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\ntype Settled<T> = { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown };\n\n/** Convert a possibly synchronously-throwing Promise producer into an explicit result. */\nconst settle = <T>(operation: () => Promise<T>): Promise<Settled<T>> => {\n const execute = async (): Promise<T> => operation();\n return execute().then(\n (value) => ({ status: 'fulfilled', value }),\n (reason: unknown) => ({ status: 'rejected', reason }),\n );\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 const result = await settle(async () => {\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 });\n if (result.status === 'rejected') {\n await effects.error(classifyOAuthError(result.reason), result.reason);\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/** Web plugin cancellation shape: the login promise rejects with a response whose token is null. */\nconst isFacebookCancellation = (error: unknown): boolean => {\n if (typeof error !== 'object' || error === null || !('accessToken' in error)) {\n return false;\n }\n const { accessToken } = error;\n if (typeof accessToken !== 'object' || accessToken === null || !('token' in accessToken)) {\n return false;\n }\n return accessToken.token === null;\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 const execute = async (): Promise<{ status: boolean }> => {\n await options.before?.();\n const nonce = generateNonce();\n const login = await settle(() => FacebookLogin.login({ permissions: options.permissions, nonce }));\n await nextFrame();\n if (login.status === 'rejected') {\n if (!isFacebookCancellation(login.reason)) await options.error?.('other', login.reason);\n return { status: false };\n }\n const event = login.value;\n if (!event?.accessToken?.token) return { status: false };\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 };\n return execute().finally(() => options.finally?.());\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 const execute = async (): Promise<{ status: boolean }> => {\n await options.before?.();\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) return { status: false };\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 operation = await settle(async () => {\n const user = requireUser(auth);\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));\n });\n if (operation.status === 'rejected') {\n await options.error?.(classifyOAuthError(operation.reason), operation.reason);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n const popup = await settle(() =>\n options.mode === 'new' ? signInWithPopup(auth, provider) : linkWithPopup(requireUser(auth), provider),\n );\n if (popup.status === 'rejected') {\n await options.error?.(classifyOAuthError(popup.reason), popup.reason);\n return { status: false };\n }\n const result = popup.value;\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 };\n return execute().finally(() => options.finally?.());\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,OA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AAM,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;;ACvTD;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' || code === 'auth/popup-closed-by-user' || code === 'auth/cancelled-popup-request') {\n return 'cancelled';\n }\n return 'other';\n};\n\ntype Settled<T> = { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown };\n\n/** Convert a possibly synchronously-throwing Promise producer into an explicit result. */\nconst settle = <T>(operation: () => Promise<T>): Promise<Settled<T>> => {\n const execute = async (): Promise<T> => operation();\n return execute().then(\n (value) => ({ status: 'fulfilled', value }),\n (reason: unknown) => ({ status: 'rejected', reason }),\n );\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 const result = await settle(async () => {\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 });\n if (result.status === 'rejected') {\n await effects.error(classifyOAuthError(result.reason), result.reason);\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/** Web plugin cancellation shape: the login promise rejects with a response whose token is null. */\nconst isFacebookCancellation = (error: unknown): boolean => {\n if (typeof error !== 'object' || error === null || !('accessToken' in error)) {\n return false;\n }\n const { accessToken } = error;\n if (typeof accessToken !== 'object' || accessToken === null || !('token' in accessToken)) {\n return false;\n }\n return accessToken.token === null;\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 const execute = async (): Promise<{ status: boolean }> => {\n await options.before?.();\n const nonce = generateNonce();\n const login = await settle(() => FacebookLogin.login({ permissions: options.permissions, nonce }));\n await nextFrame();\n if (login.status === 'rejected') {\n if (!isFacebookCancellation(login.reason)) await options.error?.('other', login.reason);\n return { status: false };\n }\n const event = login.value;\n if (!event?.accessToken?.token) return { status: false };\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 };\n return execute().finally(() => options.finally?.());\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 const execute = async (): Promise<{ status: boolean }> => {\n await options.before?.();\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) return { status: false };\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 operation = await settle(async () => {\n const user = requireUser(auth);\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));\n });\n if (operation.status === 'rejected') {\n await options.error?.(classifyOAuthError(operation.reason), operation.reason);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n const popup = await settle(() =>\n options.mode === 'new' ? signInWithPopup(auth, provider) : linkWithPopup(requireUser(auth), provider),\n );\n if (popup.status === 'rejected') {\n await options.error?.(classifyOAuthError(popup.reason), popup.reason);\n return { status: false };\n }\n const result = popup.value;\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 };\n return execute().finally(() => options.finally?.());\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,IAAI,IAAI,KAAK,2BAA2B,IAAI,IAAI,KAAK,8BAA8B,EAAE;AACrH,QAAA,OAAO,WAAW;IACpB;AACA,IAAA,OAAO,OAAO;AAChB,CAAC;AAID;AACA,MAAM,MAAM,GAAG,CAAI,S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M,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;;ACvTD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
@@ -941,22 +941,36 @@ class OfflineReplicaTransientWriteError extends Error {
941
941
  this.name = 'OfflineReplicaTransientWriteError';
942
942
  }
943
943
  }
944
- function normalizeOfflineReplicaTransientWriteError(error) {
945
- if (error instanceof OfflineReplicaTransientWriteError)
946
- return error;
944
+ function transientSqliteLockReason(error) {
947
945
  const code = typeof error === 'object' && error !== null && typeof error.code === 'string'
948
946
  ? error.code.toUpperCase()
949
947
  : '';
950
948
  const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
951
949
  const normalizedMessage = message.toUpperCase();
952
950
  if (code.includes('SQLITE_BUSY') || normalizedMessage.includes('SQLITE_BUSY')) {
953
- return new OfflineReplicaTransientWriteError('sqlite_busy', message || 'SQLite is busy.', { cause: error });
951
+ return 'sqlite_busy';
954
952
  }
955
953
  if (code.includes('SQLITE_LOCKED') ||
956
954
  normalizedMessage.includes('SQLITE_LOCKED') ||
957
955
  message.includes('database is locked') ||
958
956
  message.includes('database table is locked')) {
959
- return new OfflineReplicaTransientWriteError('sqlite_locked', message || 'SQLite database is locked.', { cause: error });
957
+ return 'sqlite_locked';
958
+ }
959
+ return null;
960
+ }
961
+ /** Returns whether SQLite reported a transient busy/locked condition in any supported error shape. */
962
+ function isTransientSqliteLockError(error) {
963
+ return error instanceof OfflineReplicaTransientWriteError
964
+ ? error.reason === 'sqlite_busy' || error.reason === 'sqlite_locked'
965
+ : transientSqliteLockReason(error) !== null;
966
+ }
967
+ function normalizeOfflineReplicaTransientWriteError(error) {
968
+ if (error instanceof OfflineReplicaTransientWriteError)
969
+ return error;
970
+ const reason = transientSqliteLockReason(error);
971
+ if (reason) {
972
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
973
+ return new OfflineReplicaTransientWriteError(reason, message || (reason === 'sqlite_busy' ? 'SQLite is busy.' : 'SQLite database is locked.'), { cause: error });
960
974
  }
961
975
  return error;
962
976
  }
@@ -5771,6 +5785,7 @@ async function createRandomOfflineEncryptionKey() {
5771
5785
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
5772
5786
  }
5773
5787
  const settledSqliteOperation = async () => undefined;
5788
+ const COMMUNITY_SQLITE_OPEN_RETRY_DELAYS_MS = [50, 150, 300];
5774
5789
  const communitySqliteDrivers = new WeakMap();
5775
5790
  function sqliteErrorMessage(error) {
5776
5791
  if (error instanceof Error)
@@ -5780,6 +5795,17 @@ function sqliteErrorMessage(error) {
5780
5795
  }
5781
5796
  return String(error);
5782
5797
  }
5798
+ async function openCommunitySqliteDatabase(database) {
5799
+ for (const delayMs of COMMUNITY_SQLITE_OPEN_RETRY_DELAYS_MS) {
5800
+ const result = await database.open().then(() => ({ ok: true }), (error) => ({ ok: false, error }));
5801
+ if (result.ok)
5802
+ return;
5803
+ if (!isTransientSqliteLockError(result.error))
5804
+ throw result.error;
5805
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
5806
+ }
5807
+ await database.open();
5808
+ }
5783
5809
  function normalizeCommunitySqliteDatabaseName(database) {
5784
5810
  return database.endsWith('.db') ? database.slice(0, -3) : database;
5785
5811
  }
@@ -5862,7 +5888,7 @@ function createCommunitySqliteDriver(connection, encrypted = COMMUNITY_SQLITE_EN
5862
5888
  const opening = (async () => {
5863
5889
  await ensureSecret(createEncryptionKey);
5864
5890
  const value = await createReloadSafeCommunitySqliteDatabase(connection, databaseName, encrypted);
5865
- await value.open();
5891
+ await openCommunitySqliteDatabase(value);
5866
5892
  databases.set(databaseKey, value);
5867
5893
  return value;
5868
5894
  })();