@rdlabo/ionic-angular-kit 21.6.0 → 21.6.2
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 +65 -0
- package/fesm2022/rdlabo-ionic-angular-kit-app-update.mjs +7 -11
- package/fesm2022/rdlabo-ionic-angular-kit-app-update.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs +31 -44
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs +28 -32
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs +664 -353
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-printer.mjs +40 -27
- package/fesm2022/rdlabo-ionic-angular-kit-printer.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit.mjs +131 -150
- package/fesm2022/rdlabo-ionic-angular-kit.mjs.map +1 -1
- package/package.json +1 -1
- package/types/rdlabo-ionic-angular-kit-offline.d.ts +208 -84
package/README.md
CHANGED
|
@@ -495,6 +495,43 @@ provideOffline({
|
|
|
495
495
|
});
|
|
496
496
|
```
|
|
497
497
|
|
|
498
|
+
Products may make durable mutation saving device-configurable without disabling replica reads. Supply only the
|
|
499
|
+
durable preference adapter; Kit owns the concurrency-sensitive transition. It starts admission closed while loading,
|
|
500
|
+
gates every `enqueue` / `enqueuePrepared` / `enqueuePreparedBatch`, and routes matched HTTP writes to normal transport
|
|
501
|
+
while disabled. Disabling closes admission synchronously, waits for already accepted commits, flushes pending
|
|
502
|
+
commands, verifies an empty Outbox, and then persists `false`. A failed transition restores the last successfully
|
|
503
|
+
persisted state. Replacement and discard APIs remain available because they resolve existing commands rather than
|
|
504
|
+
create additional pending work.
|
|
505
|
+
|
|
506
|
+
```ts
|
|
507
|
+
@Injectable({ providedIn: 'root' })
|
|
508
|
+
class ProductMutationPersistenceAdapter implements OfflineMutationPersistenceAdapter {
|
|
509
|
+
readonly #settings = inject(ProductSettingsService);
|
|
510
|
+
|
|
511
|
+
loadEnabled(): Promise<boolean | null> {
|
|
512
|
+
return this.#settings.get('offlineMutationPersistence');
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
saveEnabled(enabled: boolean): Promise<void> {
|
|
516
|
+
return this.#settings.set('offlineMutationPersistence', enabled);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
provideOffline({
|
|
521
|
+
// repository/schema/executor/puller options omitted
|
|
522
|
+
mutationPersistence: {
|
|
523
|
+
adapter: ProductMutationPersistenceAdapter,
|
|
524
|
+
defaultEnabled: true,
|
|
525
|
+
},
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
const offline = inject(OfflineCoordinatorService);
|
|
529
|
+
await offline.mutationPersistence.setEnabled(false);
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
The product owns settings UI, labels, confirmation copy, and the storage key. Omitting `mutationPersistence` keeps
|
|
533
|
+
the historical always-enabled behavior. `readCacheOnly` applications do not expose this setting.
|
|
534
|
+
|
|
498
535
|
The native offline runtime uses `@capacitor-community/sqlite` on iOS and Android. Install the plugin in the app and
|
|
499
536
|
sync native projects:
|
|
500
537
|
|
|
@@ -551,6 +588,34 @@ provideOffline({
|
|
|
551
588
|
});
|
|
552
589
|
```
|
|
553
590
|
|
|
591
|
+
An explicit user-requested local reset must run before Angular and Kit initialize SQLite. Use the cold-start helpers
|
|
592
|
+
instead of reproducing the community plugin's encrypted connection lifecycle in every application. Kit never invokes
|
|
593
|
+
reset automatically after a storage error. The product must show destructive confirmation first and owns the marker key.
|
|
594
|
+
Only databases that use Kit's same encrypted secret-mode, connection-version-1, read/write lifecycle belong in
|
|
595
|
+
`kitCompatibleDatabaseNames`; delete differently configured databases and files in `additionalCleanup`. The marker is
|
|
596
|
+
removed only after every database and product cleanup succeeds, so a partial failure is retried on the next cold launch.
|
|
597
|
+
|
|
598
|
+
```ts
|
|
599
|
+
// Settings action
|
|
600
|
+
await requestOfflineLocalReset({
|
|
601
|
+
markerStore: Preferences,
|
|
602
|
+
markerKey: 'product:offline:reset',
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
// main.ts, before bootstrapApplication(...). Report reset failure but always continue startup.
|
|
606
|
+
await recoverOfflineLocalReset({
|
|
607
|
+
markerStore: Preferences,
|
|
608
|
+
markerKey: 'product:offline:reset',
|
|
609
|
+
sqliteConnection,
|
|
610
|
+
kitCompatibleDatabaseNames: ['product-offline', 'product-offline-media'],
|
|
611
|
+
additionalCleanup: removeOfflineMediaFiles,
|
|
612
|
+
}).catch((error: unknown) => {
|
|
613
|
+
console.error('Offline local reset failed; it will retry on the next launch.', error);
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
await bootstrapApplication(AppComponent, appConfig);
|
|
617
|
+
```
|
|
618
|
+
|
|
554
619
|
Replica identity follows the product database:
|
|
555
620
|
|
|
556
621
|
| Identity declaration | SQLite primary key | Row / executor identity |
|
|
@@ -18,15 +18,13 @@ class KitAppUpdateService {
|
|
|
18
18
|
if (!this.#updates.isEnabled || !this.#document.defaultView?.navigator.serviceWorker?.controller) {
|
|
19
19
|
return;
|
|
20
20
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
const checkForUpdate = async () => withTimeout(this.#updates.checkForUpdate(), UPDATE_CHECK_TIMEOUT_MS);
|
|
22
|
+
await checkForUpdate()
|
|
23
|
+
.then((available) => {
|
|
24
|
+
if (available)
|
|
24
25
|
this.#document.location?.reload();
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
catch (error) {
|
|
28
|
-
console.error('Angular service-worker update check failed', error);
|
|
29
|
-
}
|
|
26
|
+
})
|
|
27
|
+
.catch((error) => console.error('Angular service-worker update check failed', error));
|
|
30
28
|
}
|
|
31
29
|
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAppUpdateService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
32
30
|
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAppUpdateService, providedIn: 'root' }); }
|
|
@@ -44,9 +42,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
44
42
|
* rolling out because code already running in older application versions cannot gain this behavior retroactively.
|
|
45
43
|
*/
|
|
46
44
|
function provideKitAppUpdate() {
|
|
47
|
-
return makeEnvironmentProviders([
|
|
48
|
-
provideAppInitializer(() => inject(KitAppUpdateService).initialize()),
|
|
49
|
-
]);
|
|
45
|
+
return makeEnvironmentProviders([provideAppInitializer(() => inject(KitAppUpdateService).initialize())]);
|
|
50
46
|
}
|
|
51
47
|
function withTimeout(promise, timeoutMs) {
|
|
52
48
|
return new Promise((resolve, reject) => {
|
|
@@ -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, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\n\nconst UPDATE_CHECK_TIMEOUT_MS = 10_000;\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\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.#updates.isEnabled || !this.#document.defaultView?.navigator.serviceWorker?.controller) {\n return;\n }\n
|
|
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, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\n\nconst UPDATE_CHECK_TIMEOUT_MS = 10_000;\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\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.#updates.isEnabled || !this.#document.defaultView?.navigator.serviceWorker?.controller) {\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\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(): EnvironmentProviders {\n return makeEnvironmentProviders([provideAppInitializer(() => inject(KitAppUpdateService).initialize())]);\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":";;;;;AAKA,MAAM,uBAAuB,GAAG,MAAM;AAEtC;MAEa,mBAAmB,CAAA;AACrB,IAAA,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IACpC,eAAe,GAAyB,IAAI;;IAG5C,UAAU,GAAA;AACR,QAAA,IAAI,CAAC,eAAe,KAAK,IAAI,CAAC,WAAW,EAAE;QAC3C,OAAO,IAAI,CAAC,eAAe;IAC7B;AAEA,IAAA,MAAM,WAAW,GAAA;QACf,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,aAAa,EAAE,UAAU,EAAE;YAChG;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;+GArBW,mBAAmB,EAAA,IAAA,EA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23
23
|
return 'other';
|
|
24
24
|
};
|
|
25
|
+
/** Convert a possibly synchronously-throwing Promise producer into an explicit result. */
|
|
26
|
+
const settle = (operation) => {
|
|
27
|
+
const execute = async () => operation();
|
|
28
|
+
return execute().then((value) => ({ status: 'fulfilled', value }), (reason) => ({ status: 'rejected', reason }));
|
|
29
|
+
};
|
|
25
30
|
/**
|
|
26
31
|
* The shared 3-mode credential state machine (internal).
|
|
27
32
|
*
|
|
@@ -32,7 +37,7 @@ const classifyOAuthError = (e) => {
|
|
|
32
37
|
* identity payload, and it returns `true`.
|
|
33
38
|
*/
|
|
34
39
|
const applyOAuthCredential = async (auth, credential, mode, effects) => {
|
|
35
|
-
|
|
40
|
+
const result = await settle(async () => {
|
|
36
41
|
if (mode.mode === 'new') {
|
|
37
42
|
await signInWithCredential(auth, credential);
|
|
38
43
|
}
|
|
@@ -49,9 +54,9 @@ const applyOAuthCredential = async (auth, credential, mode, effects) => {
|
|
|
49
54
|
await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));
|
|
50
55
|
}
|
|
51
56
|
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
await effects.error(classifyOAuthError(
|
|
57
|
+
});
|
|
58
|
+
if (result.status === 'rejected') {
|
|
59
|
+
await effects.error(classifyOAuthError(result.reason), result.reason);
|
|
55
60
|
return false;
|
|
56
61
|
}
|
|
57
62
|
await effects.success();
|
|
@@ -87,27 +92,19 @@ const isFacebookCancellation = (error) => {
|
|
|
87
92
|
* hooks).
|
|
88
93
|
*/
|
|
89
94
|
const kitFacebookLogin = async (auth, options) => {
|
|
90
|
-
|
|
95
|
+
const execute = async () => {
|
|
91
96
|
await options.before?.();
|
|
92
97
|
const nonce = generateNonce();
|
|
93
|
-
|
|
94
|
-
let pluginError;
|
|
95
|
-
const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch((error) => {
|
|
96
|
-
pluginFailed = true;
|
|
97
|
-
pluginError = error;
|
|
98
|
-
return undefined;
|
|
99
|
-
});
|
|
98
|
+
const login = await settle(() => FacebookLogin.login({ permissions: options.permissions, nonce }));
|
|
100
99
|
await nextFrame();
|
|
101
|
-
if (
|
|
102
|
-
if (isFacebookCancellation(
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
await options.error?.('other', pluginError);
|
|
100
|
+
if (login.status === 'rejected') {
|
|
101
|
+
if (!isFacebookCancellation(login.reason))
|
|
102
|
+
await options.error?.('other', login.reason);
|
|
106
103
|
return { status: false };
|
|
107
104
|
}
|
|
108
|
-
|
|
105
|
+
const event = login.value;
|
|
106
|
+
if (!event?.accessToken?.token)
|
|
109
107
|
return { status: false };
|
|
110
|
-
}
|
|
111
108
|
const accessToken = event.accessToken.token;
|
|
112
109
|
const credential = Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'
|
|
113
110
|
? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })
|
|
@@ -117,10 +114,8 @@ const kitFacebookLogin = async (auth, options) => {
|
|
|
117
114
|
error: (category, error) => options.error?.(category, error),
|
|
118
115
|
});
|
|
119
116
|
return { status };
|
|
120
|
-
}
|
|
121
|
-
finally
|
|
122
|
-
await options.finally?.();
|
|
123
|
-
}
|
|
117
|
+
};
|
|
118
|
+
return execute().finally(() => options.finally?.());
|
|
124
119
|
};
|
|
125
120
|
/**
|
|
126
121
|
* Log out of the Facebook SDK (best-effort; errors are ignored).
|
|
@@ -151,13 +146,12 @@ const kitFacebookLogout = async () => {
|
|
|
151
146
|
* Every failure path (including popup errors) is routed through `onError`.
|
|
152
147
|
*/
|
|
153
148
|
const kitAppleLogin = async (auth, options) => {
|
|
154
|
-
|
|
149
|
+
const execute = async () => {
|
|
155
150
|
await options.before?.();
|
|
156
151
|
if (Capacitor.isNativePlatform()) {
|
|
157
152
|
const authorize = await SignInWithApple.authorize().catch(() => undefined);
|
|
158
|
-
if (!authorize)
|
|
153
|
+
if (!authorize)
|
|
159
154
|
return { status: false };
|
|
160
|
-
}
|
|
161
155
|
const r = authorize.response;
|
|
162
156
|
const response = {
|
|
163
157
|
user: r.user ?? null,
|
|
@@ -179,29 +173,24 @@ const kitAppleLogin = async (auth, options) => {
|
|
|
179
173
|
provider.addScope('email');
|
|
180
174
|
provider.addScope('name');
|
|
181
175
|
if (options.mode === 'credential') {
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
if (!user) {
|
|
185
|
-
throw new Error('kit social: no signed-in user to re-authenticate');
|
|
186
|
-
}
|
|
176
|
+
const operation = await settle(async () => {
|
|
177
|
+
const user = requireUser(auth);
|
|
187
178
|
await reauthenticateWithPopup(user, provider);
|
|
188
179
|
await linkWithCredential(user, EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password));
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
await options.error?.(classifyOAuthError(
|
|
180
|
+
});
|
|
181
|
+
if (operation.status === 'rejected') {
|
|
182
|
+
await options.error?.(classifyOAuthError(operation.reason), operation.reason);
|
|
192
183
|
return { status: false };
|
|
193
184
|
}
|
|
194
185
|
await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });
|
|
195
186
|
return { status: true };
|
|
196
187
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
}
|
|
201
|
-
catch (e) {
|
|
202
|
-
await options.error?.(classifyOAuthError(e), e);
|
|
188
|
+
const popup = await settle(() => options.mode === 'new' ? signInWithPopup(auth, provider) : linkWithPopup(requireUser(auth), provider));
|
|
189
|
+
if (popup.status === 'rejected') {
|
|
190
|
+
await options.error?.(classifyOAuthError(popup.reason), popup.reason);
|
|
203
191
|
return { status: false };
|
|
204
192
|
}
|
|
193
|
+
const result = popup.value;
|
|
205
194
|
const credential = OAuthProvider.credentialFromResult(result);
|
|
206
195
|
const response = {
|
|
207
196
|
...emptyAppleResponse(),
|
|
@@ -211,10 +200,8 @@ const kitAppleLogin = async (auth, options) => {
|
|
|
211
200
|
};
|
|
212
201
|
await options.success?.({ response, mode: options.mode });
|
|
213
202
|
return { status: true };
|
|
214
|
-
}
|
|
215
|
-
finally
|
|
216
|
-
await options.finally?.();
|
|
217
|
-
}
|
|
203
|
+
};
|
|
204
|
+
return execute().finally(() => options.finally?.());
|
|
218
205
|
};
|
|
219
206
|
const emptyAppleResponse = () => ({
|
|
220
207
|
user: null,
|
|
@@ -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\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/** 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 try {\n await options.before?.();\n const nonce = generateNonce();\n let pluginFailed = false;\n let pluginError: unknown;\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch((error: unknown) => {\n pluginFailed = true;\n pluginError = error;\n return undefined;\n });\n await nextFrame();\n if (pluginFailed) {\n if (isFacebookCancellation(pluginError)) {\n return { status: false };\n }\n await options.error?.('other', pluginError);\n return { status: false };\n }\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 try {\n await options.before?.();\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;AACvB,YAAA,MAAM,oBAAoB,CAAC,IAAI,EAAE,UAAU,CAAC;QAC9C;aAAO;AACL,YAAA,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW;YAC7B,IAAI,CAAC,IAAI,EAAE;AACT,gBAAA,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC;YAC1E;AACA,YAAA,IAAI,IAAI,CAAC,IAAI,K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zB;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;;AC1TD;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\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,IAA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AK,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;;ACvTD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
|
|
@@ -81,20 +81,19 @@ const KIT_DEFAULT_AUTH_TEXT = {
|
|
|
81
81
|
// `firebase` as a peerDependency so the app's single Firebase install is used everywhere; a second
|
|
82
82
|
// copy would make signOut/onAuthStateChanged against KIT_FIREBASE_AUTH a silent no-op.
|
|
83
83
|
/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */
|
|
84
|
-
const runAuthFlow =
|
|
85
|
-
|
|
84
|
+
const runAuthFlow = (op, hooks) => {
|
|
85
|
+
const execute = async () => {
|
|
86
86
|
await hooks?.before?.();
|
|
87
87
|
const result = await op();
|
|
88
88
|
await hooks?.success?.();
|
|
89
89
|
return result;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
90
|
+
};
|
|
91
|
+
return execute()
|
|
92
|
+
.catch(async (error) => {
|
|
93
|
+
await hooks?.error?.(error);
|
|
93
94
|
return null;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
await hooks?.finally?.();
|
|
97
|
-
}
|
|
95
|
+
})
|
|
96
|
+
.finally(() => hooks?.finally?.());
|
|
98
97
|
};
|
|
99
98
|
/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */
|
|
100
99
|
const runAuthFlowVoid = async (op, hooks) => {
|
|
@@ -133,22 +132,20 @@ const kitSignUp = (auth, email, password, hooks) => runAuthFlow(async () => {
|
|
|
133
132
|
* done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.
|
|
134
133
|
*/
|
|
135
134
|
const kitSignOut = async (auth, hooks, options) => {
|
|
136
|
-
|
|
135
|
+
const execute = async () => {
|
|
137
136
|
await hooks?.before?.();
|
|
138
|
-
if (options?.expectedUser !== undefined && auth.currentUser !== options.expectedUser)
|
|
137
|
+
if (options?.expectedUser !== undefined && auth.currentUser !== options.expectedUser)
|
|
139
138
|
return false;
|
|
140
|
-
}
|
|
141
139
|
await signOut(auth);
|
|
142
140
|
await hooks?.success?.();
|
|
143
141
|
return true;
|
|
144
|
-
}
|
|
145
|
-
|
|
142
|
+
};
|
|
143
|
+
return execute()
|
|
144
|
+
.catch(async (error) => {
|
|
146
145
|
await hooks?.error?.(error);
|
|
147
146
|
return false;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
await hooks?.finally?.();
|
|
151
|
-
}
|
|
147
|
+
})
|
|
148
|
+
.finally(() => hooks?.finally?.());
|
|
152
149
|
};
|
|
153
150
|
/** Send a password-reset email. `true` on success, `false` on failure. */
|
|
154
151
|
const kitSendPasswordReset = (auth, email, hooks) => runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);
|
|
@@ -253,9 +250,9 @@ const kitAuthState = (auth) => new Observable((subscriber) => onAuthStateChanged
|
|
|
253
250
|
* @returns the ID token, or `null` if there is no signed-in user
|
|
254
251
|
* @throws if the token fetch fails for a signed-in user
|
|
255
252
|
*/
|
|
256
|
-
const kitGetIdToken = (auth, forceRefresh = false) => {
|
|
253
|
+
const kitGetIdToken = async (auth, forceRefresh = false) => {
|
|
257
254
|
const user = auth.currentUser;
|
|
258
|
-
return user ? user.getIdToken(forceRefresh) :
|
|
255
|
+
return user ? user.getIdToken(forceRefresh) : null;
|
|
259
256
|
};
|
|
260
257
|
/**
|
|
261
258
|
* Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.
|
|
@@ -316,12 +313,12 @@ const kitReauthenticateThenMutate = async (auth, currentEmail, currentPassword,
|
|
|
316
313
|
if (!user) {
|
|
317
314
|
throw new KitReauthError('no current user');
|
|
318
315
|
}
|
|
319
|
-
|
|
316
|
+
const reauthenticate = async () => {
|
|
320
317
|
await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
throw new KitReauthError(
|
|
324
|
-
}
|
|
318
|
+
};
|
|
319
|
+
await reauthenticate().catch((error) => {
|
|
320
|
+
throw new KitReauthError(error);
|
|
321
|
+
});
|
|
325
322
|
await mutate(user);
|
|
326
323
|
};
|
|
327
324
|
/**
|
|
@@ -351,17 +348,16 @@ const kitReauthWithRetry = async (auth, currentEmail, options) => {
|
|
|
351
348
|
if (password === null) {
|
|
352
349
|
return false;
|
|
353
350
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
catch (e) {
|
|
359
|
-
if (kitIsWrongPasswordError(e)) {
|
|
351
|
+
const executeAttempt = async () => run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));
|
|
352
|
+
const attempt = await executeAttempt().then(() => ({ success: true }), (error) => ({ success: false, error }));
|
|
353
|
+
if (!attempt.success) {
|
|
354
|
+
if (kitIsWrongPasswordError(attempt.error)) {
|
|
360
355
|
wrongPasswordRetry = true;
|
|
361
356
|
continue;
|
|
362
357
|
}
|
|
363
|
-
throw
|
|
358
|
+
throw attempt.error instanceof KitReauthError && attempt.error.cause instanceof Error ? attempt.error.cause : attempt.error;
|
|
364
359
|
}
|
|
360
|
+
return true;
|
|
365
361
|
}
|
|
366
362
|
};
|
|
367
363
|
/**
|