@rdlabo/ionic-angular-kit 22.0.0-beta.pr99.sha950c83950d41 → 22.0.1-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,35 +8,39 @@ npm install @rdlabo/ionic-angular-kit
8
8
 
9
9
  ## Requirements
10
10
 
11
- | Package | Supported version |
12
- | ---------------------------------- | ----------------- |
13
- | Angular | 21.x–22.x |
14
- | Ionic Angular | 9.x |
15
- | RxJS | 7.8.x |
16
- | Capacitor core and feature plugins | 7.x–8.x |
17
- | iOS/iPadOS deployment target | 16.4 or later |
11
+ | Package | Supported version |
12
+ | ----------------------------------------------- | ----------------- |
13
+ | Angular | 21.x–22.x |
14
+ | Ionic Angular | 9.x |
15
+ | RxJS | 7.8.x |
16
+ | Capacitor Core, App, Haptics, Keyboard, Network | 7.x–8.x |
17
+ | iOS/iPadOS deployment target | 16.4 or later |
18
18
 
19
- Install `@ionic/storage-angular` when using storage. Other peers are feature-scoped: install only the Capacitor, Firebase, printing, or Live Update packages used by your selected entry points.
19
+ The core package declares `@ionic/storage-angular` and Capacitor Core, App, Haptics, Keyboard, and Network as required peers. Keep compatible versions installed even when an application uses only part of the core entry point. Native applications using `/offline` must additionally install and configure the `@capacitor-community/sqlite` major matching their Capacitor major; it is application-owned and is not installed by the kit.
20
+
21
+ Firebase, social login, Live Update, Preferences, Status Bar, in-app review, and printer/PDF dependencies are optional feature peers. Install only the dependencies used by the selected secondary entry points and follow each plugin's own compatibility range; some optional plugins support only Capacitor 8.
20
22
 
21
23
  ## Entry points
22
24
 
23
- | Import | Responsibility |
24
- | ----------------------------------------- | ------------------------------------------------------------------------------ |
25
- | `@rdlabo/ionic-angular-kit` | Storage, overlays, guards, HTTP, realtime, directives, keyboard, and utilities |
26
- | `@rdlabo/ionic-angular-kit/offline` | Scoped local replica, outbox, pull, replay, and request policies |
27
- | `@rdlabo/ionic-angular-kit/theme` | Persisted light/dark theme and native status bar sync |
28
- | `@rdlabo/ionic-angular-kit/forms` | Ionic error text and state classes for Angular Signal Forms |
29
- | `@rdlabo/ionic-angular-kit/review` | Throttled native in-app review requests |
30
- | `@rdlabo/ionic-angular-kit/printer` | DOM-to-PNG, Brother label, and PDF helpers |
31
- | `@rdlabo/ionic-angular-kit/auth-firebase` | Firebase dependency wiring and authentication flows |
32
- | `@rdlabo/ionic-angular-kit/app-update` | Atomic Angular service-worker update transitions |
33
- | `@rdlabo/ionic-angular-kit/live-update` | Capawesome Live Update readiness provider |
25
+ | Import | Responsibility |
26
+ | ----------------------------------------- | ---------------------------------------------------------------------------------- |
27
+ | `@rdlabo/ionic-angular-kit` | Storage, overlays, guards, HTTP, realtime, directives, keyboard, and utilities |
28
+ | `@rdlabo/ionic-angular-kit/offline` | **Experimental.** Scoped local replica, outbox, pull, replay, and request policies |
29
+ | `@rdlabo/ionic-angular-kit/theme` | Persisted light/dark theme and native status bar sync |
30
+ | `@rdlabo/ionic-angular-kit/forms` | Ionic error text and state classes for Angular Signal Forms |
31
+ | `@rdlabo/ionic-angular-kit/review` | Throttled native in-app review requests |
32
+ | `@rdlabo/ionic-angular-kit/printer` | DOM-to-PNG, Brother label, and PDF helpers |
33
+ | `@rdlabo/ionic-angular-kit/auth-firebase` | Firebase dependency wiring and authentication flows |
34
+ | `@rdlabo/ionic-angular-kit/app-update` | Atomic Angular service-worker update transitions |
35
+ | `@rdlabo/ionic-angular-kit/live-update` | Capawesome Live Update readiness provider |
34
36
 
35
37
  Secondary entry points isolate optional native and SDK dependencies from the core bundle.
36
38
 
39
+ The entire `/offline` entry point is experimental and is not covered by the kit's SemVer compatibility guarantee. Its public APIs, persistence schema, and synchronization behavior may change incompatibly in a minor or patch release before stabilization. Pin the kit to an exact version when adopting it, and review the migration guide before every upgrade.
40
+
37
41
  ## Configure only what you use
38
42
 
39
- Most features expose a provider whose callbacks keep routes, copy, credentials, and application side effects outside the kit. Start with [Storage and Overlays](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/storage-overlays), then add authentication, offline, or native features as your app needs them.
43
+ Most features expose a provider whose callbacks keep routes, copy, credentials, and application side effects outside the kit. Start with [Storage and Overlays](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/storage-overlays), then add authentication, offline, or native features as your app needs them. The [Offline and Realtime](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/offline-realtime) guide includes the required SQLite connection, provider/interceptor order, read strategies, durable Outbox flow, and repository concurrency rules.
40
44
 
41
45
  ## Documentation
42
46
 
@@ -46,5 +50,7 @@ Most features expose a provider whose callbacks keep routes, copy, credentials,
46
50
  - [Optional Features](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/optional-features)
47
51
 
48
52
  <!-- rdlabo-docs-omit -->
53
+
49
54
  **Full documentation:** [https://docs.rdlabo.dev/projects/ionic-angular-kit](https://docs.rdlabo.dev/projects/ionic-angular-kit)
55
+
50
56
  <!-- /rdlabo-docs-omit -->
@@ -1,9 +1,67 @@
1
1
  ## Scoped offline runtime
2
2
 
3
+ > **Experimental:** The entire `@rdlabo/ionic-angular-kit/offline` entry point is experimental and is not covered by the kit's SemVer compatibility guarantee. Its public APIs, persistence schema, and synchronization behavior may change incompatibly in a minor or patch release before stabilization. Pin the kit to an exact version when adopting it, and review the migration guide before every upgrade.
4
+
3
5
  The `/offline` entry point provides a user- and partition-scoped local replica, durable outbox, cursor-based delta pull, aggregate-ordered replay, optimistic mutation policies, and request-policy interception.
4
6
 
5
7
  Use `mode: 'readCacheOnly'` for external-source or HTTP caches. Synchronized mode uses encrypted `@capacitor-community/sqlite` on iOS and Android; it fails fast on the web because the current runtime has no cross-tab synchronization lock.
6
8
 
9
+ ### Install and provide the runtime
10
+
11
+ Provide Ionic Storage once for the kit's storage infrastructure. Web read-cache installations also use it as the offline repository. Native synchronized applications additionally own the Community SQLite connection passed to the kit. The SQLite install and native sync below are required only for synchronized iOS and Android applications:
12
+
13
+ ```sh
14
+ npm install @ionic/storage-angular @capacitor-community/sqlite@^8
15
+ npx cap sync
16
+ ```
17
+
18
+ The SQLite plugin major must match Capacitor: use `@capacitor-community/sqlite@^7` in a Capacitor 7 application and `@^8` in a Capacitor 8 application.
19
+
20
+ ```ts
21
+ import { provideHttpClient, withInterceptors } from '@angular/common/http';
22
+ import { importProvidersFrom } from '@angular/core';
23
+ import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';
24
+ import { IonicStorageModule } from '@ionic/storage-angular';
25
+ import { kitAuthInterceptor } from '@rdlabo/ionic-angular-kit';
26
+ import { offlineInterceptor, provideOffline } from '@rdlabo/ionic-angular-kit/offline';
27
+
28
+ const sqliteConnection = new SQLiteConnection(CapacitorSQLite);
29
+
30
+ export const appConfig = {
31
+ providers: [
32
+ importProvidersFrom(IonicStorageModule.forRoot({ name: '__kit_storage' })),
33
+ provideHttpClient(withInterceptors([offlineInterceptor, kitAuthInterceptor])),
34
+ provideOffline({
35
+ databaseName: 'product_offline',
36
+ replicaSchema,
37
+ sqliteConnection,
38
+ createEncryptionKey: () => secureKeyStore.getOrCreateOfflineKey(),
39
+ requestPolicies: [ProductReadPolicy],
40
+ mutationPolicies: [ProductMutationPolicy],
41
+ commandExecutor: ProductCommandExecutor,
42
+ replicaPuller: ProductReplicaPuller,
43
+ aggregateIntentProjector: ProductAggregateIntentProjector,
44
+ }),
45
+ ],
46
+ };
47
+ ```
48
+
49
+ Register `offlineInterceptor` before `kitAuthInterceptor`. Product adapters own URL and DTO mapping, replica schemas, encryption-key storage, server pull/command protocols, and optimistic projection. The kit owns persistence, session isolation, FIFO ordering, retries, and reconciliation. Set `databaseEncryption: false` only for an intentional plaintext native database; encryption is otherwise the default and requires `createEncryptionKey` on first open.
50
+
51
+ For `mode: 'readCacheOnly'`, omit mutation policies, the command executor, replica puller, and aggregate intent projector. Web supports this read-cache mode through Ionic Storage. Web synchronized mode is rejected until its repository can provide cross-context locking.
52
+
53
+ ```ts
54
+ provideOffline({
55
+ mode: 'readCacheOnly',
56
+ databaseName: 'product_cache',
57
+ databaseEncryption: false,
58
+ replicaSchema,
59
+ requestPolicies: [ProductReadPolicy],
60
+ });
61
+ ```
62
+
63
+ The web read-cache configuration does not import or pass Community SQLite. `databaseEncryption: false` is explicit because SQLCipher applies only to the native repository.
64
+
7
65
  Cold-start offline access restores only a manifest bound to a non-null authentication-provider subject. Remote work follows this order:
8
66
 
9
67
  1. Prepare the verified remote session.
@@ -13,6 +71,7 @@ Cold-start offline access restores only a manifest bound to a non-null authentic
13
71
  `createOfflineAuthBridge()` connects this ordering to `provideKitAuth()` while leaving consent, error UI, and credential exchange in the app.
14
72
 
15
73
  ```ts
74
+ import { provideKitAuth } from '@rdlabo/ionic-angular-kit';
16
75
  import { createOfflineAuthBridge, isOfflineFallbackError } from '@rdlabo/ionic-angular-kit/offline';
17
76
 
18
77
  provideKitAuth(() => ({
@@ -20,7 +79,7 @@ provideKitAuth(() => ({
20
79
  ...createOfflineAuthBridge({
21
80
  exchange: async (context) => exchangeCredential(context),
22
81
  currentAuthSubject: () => auth.currentSubject(),
23
- isUnavailableError,
82
+ isUnavailableError: isOfflineFallbackError,
24
83
  availability: () => auth.authorityAvailable$,
25
84
  }),
26
85
  redirects,
@@ -29,6 +88,62 @@ provideKitAuth(() => ({
29
88
 
30
89
  On explicit sign-out, clear `KitAuthAccessService` first, then await offline session cleanup so in-flight leases are invalidated before persisted user data is removed.
31
90
 
91
+ ### Read request strategies
92
+
93
+ An `OfflineRequestPolicy` resolves a matched GET to `kind: 'read'`, a `readLocal()` function, and an optional shared `projectResponse()` function. `readStrategy` controls settlement:
94
+
95
+ | Strategy | Behavior |
96
+ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
97
+ | `network-first` | Default. Uses transport first and falls back to the local response for an offline/unavailable transport error. |
98
+ | `local-first` | Starts local and remote work together, emits a usable local response first, then emits remote revalidation. |
99
+ | `fastest-first` | Emits whichever usable response settles first. A local winner is followed by remote revalidation; a remote winner cancels the slower local read. |
100
+ | `local-only` | Never starts HTTP transport. Use it for provisional identities that cannot exist remotely. |
101
+
102
+ `local-first` and a locally winning `fastest-first` can emit twice. Keep the HTTP observable subscribed through revalidation; `firstValueFrom()` and `take(1)` cancel the transport after the first emission. Use `offlineReadEmission()` and `shouldCommitOfflineCollection()` when UI state needs to distinguish a complete remote collection from an incomplete empty local snapshot.
103
+
104
+ `projectResponse(response, source)` runs for both remote and local responses. Persist only when `source === 'remote'`. Set `serializeResponseProjection: true` when the projector performs read-only derivation that must wait behind replica mutations. Do not enable it when the projector starts a replica mutation itself; use `OfflineSyncService.runSerializedReplicaMutation()` for a read/derive/write sequence instead.
105
+
106
+ ### Durable mutations and immediate generated creates
107
+
108
+ Mutation policies prepare the optimistic `HttpResponse`; the product implementation should enqueue the corresponding durable intent before returning it. `enqueue()` generates a UUID by default. Supply a stable `commandId` when product code must correlate the durable intent with surrounding work or immediately send a newly created generated identity. Kit preserves that ID across transport retries.
109
+
110
+ ```ts
111
+ import type { OfflineGeneratedCommandLocator } from '@rdlabo/ionic-angular-kit/offline';
112
+
113
+ const commandId = crypto.randomUUID();
114
+ const localId = crypto.randomUUID();
115
+
116
+ await offlineSync.enqueue(
117
+ {
118
+ commandId,
119
+ scopeId,
120
+ aggregateType: 'photo',
121
+ identity: { kind: 'generated', localId },
122
+ operation: 'create',
123
+ payload: createPayload,
124
+ },
125
+ { flush: false },
126
+ );
127
+
128
+ const locator = {
129
+ scopeId,
130
+ sourceKey: 'photo',
131
+ localId,
132
+ } satisfies OfflineGeneratedCommandLocator;
133
+
134
+ const remoteId = await offlineSync.sendGeneratedCommandNow(commandId, locator);
135
+ ```
136
+
137
+ The second argument has type `OfflineGeneratedCommandLocator`. `sendGeneratedCommandNow()` is deliberately limited to the first pending intent of a new generated aggregate with no confirmed baseline or remote ID. It skips the normal pre-send pull and commits the local acknowledgement. When it obtains a confirmed remote ID, it schedules authoritative pull reconciliation in the background. It returns `null` when transport is unavailable or no confirmed ID is produced. A terminal `blocked_auth`, `rejected`, or `conflict` result throws `OfflineImmediateCommandRejectedError`. Existing aggregates and later intents must use `flush()` so the pre-pull conflict barrier remains in place.
138
+
139
+ Command payloads must be losslessly JSON-serializable. Caller-owned command IDs must contain 1–255 characters and must not be reused during the application/server idempotency-retention period. Kit can reject only collisions with commands that are still retained locally; the server may still deduplicate a reused ID after its local command has been reconciled and removed.
140
+
141
+ ### Repository consistency boundary
142
+
143
+ Treat `OfflineSyncService` as the product mutation owner. For a product read/derive/write operation, use `runSerializedReplicaMutation()`. Inside its callback, use only the supplied repository and finish the write with that repository's `transactReplica()`; do not start a nested `OfflineSyncService` mutation or another coordinator lane. Commit replica rows, Outbox commands, cursors, and pull-attention changes together in that transaction.
144
+
145
+ For a read-only multi-query snapshot, use `repository.runReadSnapshot()` and perform all reads through the supplied reader. Do not mutate the repository or nest another `runReadSnapshot()` inside that callback. Direct `replaceCommand()`, `removeCommand()`, `putPullAttention()`, and `removePullAttention()` repository methods are deprecated; use the corresponding `putCommands`, `removeCommandIds`, `putPullAttentions`, and `removePullAttentions` fields of `transactReplica()`.
146
+
32
147
  ### Lazy authenticated routes
33
148
 
34
149
  Use `provideRouteScopedOffline()` when the offline runtime and product schema must not enter the
@@ -11,10 +11,29 @@ Applications that prefetch every executable application chunk can opt into a non
11
11
  provideKitAppUpdate({ strategy: 'background' });
12
12
  ```
13
13
 
14
- The background strategy reloads only before Angular completes its first render. A later update is left for the next natural page
15
- load so user input is not discarded. It never calls `activateUpdate()`, which could mix a running shell with lazy chunks from
16
- another version. An unrecoverable startup generation is retried once with `ngsw-bypass`; the current history state and an
17
- offline-safe loop guard are retained.
14
+ The existing background strategy reloads only before Angular completes its first render. A later update is left for the next
15
+ natural page load so user input is not discarded.
16
+
17
+ Applications can select the separate `confirm` strategy to offer an immediate, user-controlled update. The prompt runs after
18
+ the first render and in an Angular injection context. Resolve dependencies synchronously before crossing an async boundary.
19
+ Resolving `true` reloads into the complete downloaded version, `false` leaves it for the next natural page load, and `undefined`
20
+ retries later because the prompt could not be presented (for example, while another alert is active).
21
+
22
+ ```ts
23
+ provideKitAppUpdate({
24
+ strategy: 'confirm',
25
+ promptForUpdate: () =>
26
+ inject(KitOverlayController).tryAlertConfirm({
27
+ header: 'The latest version is ready',
28
+ message: 'Reload now to update?',
29
+ okText: 'Reload and update',
30
+ }),
31
+ });
32
+ ```
33
+
34
+ Neither non-blocking strategy calls `activateUpdate()`, which could mix a running shell with lazy chunks from another version.
35
+ An unrecoverable startup generation is retried once with `ngsw-bypass`; the current history state and an offline-safe loop guard
36
+ are retained.
18
37
 
19
38
  ## Theme and review
20
39
 
@@ -3,20 +3,34 @@
3
3
  Provide Ionic Storage once. `KitStorageService` initializes it lazily and every public operation waits for that initialization, so writes made immediately after service creation are not dropped.
4
4
 
5
5
  ```ts
6
- import { importProvidersFrom } from '@angular/core';
6
+ import { importProvidersFrom, type ApplicationConfig } from '@angular/core';
7
7
  import { IonicStorageModule } from '@ionic/storage-angular';
8
8
 
9
9
  export const appConfig: ApplicationConfig = {
10
- providers: [importProvidersFrom(IonicStorageModule.withConfig({ name: '__mydb' }))],
10
+ providers: [importProvidersFrom(IonicStorageModule.forRoot({ name: '__mydb' }))],
11
11
  };
12
12
  ```
13
13
 
14
14
  ```ts
15
- const storage = inject(KitStorageService);
15
+ import { inject, Injectable } from '@angular/core';
16
+ import { KitStorageService } from '@rdlabo/ionic-angular-kit';
16
17
 
17
- await storage.set('token', token);
18
- const saved = await storage.get<string>('token');
19
- await storage.remove('token');
18
+ @Injectable({ providedIn: 'root' })
19
+ export class TokenStore {
20
+ readonly #storage = inject(KitStorageService);
21
+
22
+ async save(token: string): Promise<void> {
23
+ await this.#storage.set('token', token);
24
+ }
25
+
26
+ get(): Promise<string | null> {
27
+ return this.#storage.get<string>('token');
28
+ }
29
+
30
+ remove(): Promise<void> {
31
+ return this.#storage.remove('token');
32
+ }
33
+ }
20
34
  ```
21
35
 
22
36
  `get<T>()` returns `null` for a missing key. `kitClearStoragePreservingKeys()` clears application data while restoring selected values such as the last authentication email or theme.
@@ -40,10 +54,7 @@ export class DetailPage {
40
54
  readonly item = input.required<Item>();
41
55
  }
42
56
 
43
- export const launchDetailPage = (
44
- overlay: KitOverlayController,
45
- props: { item: Item },
46
- ): Promise<DetailResult | undefined> =>
57
+ export const launchDetailPage = (overlay: KitOverlayController, props: { item: Item }): Promise<DetailResult | undefined> =>
47
58
  overlay.presentModal(DetailPage, props, { backdropDismiss: false });
48
59
  ```
49
60
 
@@ -1,12 +1,13 @@
1
1
  import { DOCUMENT } from '@angular/common';
2
2
  import * as i0 from '@angular/core';
3
- import { inject, Injectable, provideAppInitializer, afterNextRender, makeEnvironmentProviders } from '@angular/core';
3
+ import { inject, Injectable, makeEnvironmentProviders, provideAppInitializer, EnvironmentInjector, runInInjectionContext, afterNextRender } from '@angular/core';
4
4
  import { SwUpdate } from '@angular/service-worker';
5
5
  import { filter, take } from 'rxjs';
6
6
 
7
7
  const UPDATE_CHECK_TIMEOUT_MS = 10_000;
8
+ const UPDATE_PROMPT_RETRY_MS = 1_000;
8
9
  const UNRECOVERABLE_RELOAD_KEY = 'kit_sw_unrecoverable_reload';
9
- /** Checks for a complete Angular service-worker update before users can interact with the application. */
10
+ /** Coordinates complete Angular service-worker updates using blocking, background, or user-confirmed application. */
10
11
  class KitAppUpdateService {
11
12
  #document = inject(DOCUMENT);
12
13
  #updates = inject(SwUpdate);
@@ -14,6 +15,11 @@ class KitAppUpdateService {
14
15
  #backgroundStarted = false;
15
16
  #interactive = false;
16
17
  #reloading = false;
18
+ #updateReady = false;
19
+ #prompting = false;
20
+ #prompted = false;
21
+ #promptRetryScheduled = false;
22
+ #promptForUpdate;
17
23
  /** Runs one startup update check and reloads directly into a downloaded version when one is available. */
18
24
  initialize() {
19
25
  this.#initialization ??= this.#initialize();
@@ -33,13 +39,21 @@ class KitAppUpdateService {
33
39
  }
34
40
  /** Starts an update check that never blocks bootstrap or reloads after the application becomes interactive. */
35
41
  startBackground() {
42
+ this.#startNonBlocking();
43
+ }
44
+ /** Starts a non-blocking update check and asks after the first render before applying a ready update. */
45
+ startConfirm(promptForUpdate) {
46
+ this.#startNonBlocking(promptForUpdate);
47
+ }
48
+ #startNonBlocking(promptForUpdate) {
36
49
  if (this.#backgroundStarted || !this.#canCheckForUpdate()) {
37
50
  return;
38
51
  }
39
52
  this.#backgroundStarted = true;
53
+ this.#promptForUpdate = promptForUpdate;
40
54
  this.#updates.versionUpdates
41
55
  .pipe(filter((event) => event.type === 'VERSION_READY'), take(1))
42
- .subscribe(() => this.#reloadBeforeInteraction());
56
+ .subscribe(() => this.#handleUpdateReady());
43
57
  this.#updates.unrecoverable.pipe(take(1)).subscribe((event) => {
44
58
  console.error('Angular service-worker state is unrecoverable', event.reason);
45
59
  this.#recoverBeforeInteraction(event.reason);
@@ -48,7 +62,7 @@ class KitAppUpdateService {
48
62
  .checkForUpdate()
49
63
  .then((available) => {
50
64
  if (available) {
51
- this.#reloadBeforeInteraction();
65
+ this.#handleUpdateReady();
52
66
  }
53
67
  })
54
68
  .catch((error) => console.error('Angular service-worker update check failed', error));
@@ -59,6 +73,7 @@ class KitAppUpdateService {
59
73
  if (!this.#reloading) {
60
74
  this.#clearRecoveryBypass();
61
75
  }
76
+ this.#promptWhenReady();
62
77
  }
63
78
  #canCheckForUpdate() {
64
79
  return this.#updates.isEnabled && Boolean(this.#document.defaultView?.navigator.serviceWorker?.controller);
@@ -70,6 +85,59 @@ class KitAppUpdateService {
70
85
  this.#reloading = true;
71
86
  this.#document.location?.reload();
72
87
  }
88
+ #handleUpdateReady() {
89
+ if (!this.#promptForUpdate) {
90
+ this.#reloadBeforeInteraction();
91
+ return;
92
+ }
93
+ this.#updateReady = true;
94
+ this.#promptWhenReady();
95
+ }
96
+ #promptWhenReady() {
97
+ const promptForUpdate = this.#promptForUpdate;
98
+ if (!this.#interactive ||
99
+ !this.#updateReady ||
100
+ !promptForUpdate ||
101
+ this.#prompting ||
102
+ this.#prompted ||
103
+ this.#promptRetryScheduled ||
104
+ this.#reloading) {
105
+ return;
106
+ }
107
+ this.#prompting = true;
108
+ void runUpdatePrompt(promptForUpdate)
109
+ .then((confirmed) => {
110
+ this.#prompting = false;
111
+ if (confirmed === undefined) {
112
+ this.#schedulePromptRetry();
113
+ return;
114
+ }
115
+ this.#prompted = true;
116
+ this.#applyPromptResult(confirmed);
117
+ })
118
+ .catch((error) => {
119
+ this.#prompting = false;
120
+ this.#prompted = true;
121
+ console.error('Angular service-worker update prompt failed', error);
122
+ });
123
+ }
124
+ #schedulePromptRetry() {
125
+ if (this.#promptRetryScheduled || this.#prompted || this.#reloading) {
126
+ return;
127
+ }
128
+ this.#promptRetryScheduled = true;
129
+ globalThis.setTimeout(() => {
130
+ this.#promptRetryScheduled = false;
131
+ this.#promptWhenReady();
132
+ }, UPDATE_PROMPT_RETRY_MS);
133
+ }
134
+ #applyPromptResult(confirmed) {
135
+ if (!confirmed || this.#reloading) {
136
+ return;
137
+ }
138
+ this.#reloading = true;
139
+ this.#document.location?.reload();
140
+ }
73
141
  #recoverBeforeInteraction(reason) {
74
142
  const location = this.#document.location;
75
143
  if (this.#interactive || this.#reloading || !location) {
@@ -156,22 +224,46 @@ function clearFailure(storage) {
156
224
  }
157
225
  }
158
226
  /**
159
- * Provides a startup check that reloads into the latest complete web application version.
227
+ * Provides blocking, background, or user-confirmed adoption of complete Angular service-worker updates.
160
228
  *
161
229
  * @remarks
162
- * The check finishes before application bootstrap so a delayed update cannot discard user input. It times out rather
163
- * than preventing offline startup. API deployments must remain backward compatible while a newly adopted updater is
164
- * rolling out because code already running in older application versions cannot gain this behavior retroactively.
230
+ * The default `blocking` strategy checks before bootstrap and times out rather than preventing offline startup. The
231
+ * existing `background` strategy never delays bootstrap and reloads only before the first render. The opt-in `confirm`
232
+ * strategy also checks in the background, but waits until after the first render and reloads only with user approval.
233
+ * API deployments must remain backward compatible while an updater is rolling out because already-running older code
234
+ * cannot gain this behavior retroactively.
165
235
  */
166
236
  function provideKitAppUpdate(options = {}) {
167
- const initializer = options.strategy === 'background'
168
- ? provideAppInitializer(() => {
169
- const updates = inject(KitAppUpdateService);
170
- updates.startBackground();
171
- afterNextRender(() => updates.markInteractive());
172
- })
173
- : provideAppInitializer(() => inject(KitAppUpdateService).initialize());
174
- return makeEnvironmentProviders([initializer]);
237
+ if (options.strategy === 'confirm') {
238
+ const promptForUpdate = options.promptForUpdate;
239
+ if (typeof promptForUpdate !== 'function') {
240
+ throw new Error('provideKitAppUpdate confirm strategy requires promptForUpdate');
241
+ }
242
+ return makeEnvironmentProviders([
243
+ provideAppInitializer(() => {
244
+ const updates = inject(KitAppUpdateService);
245
+ const injector = inject(EnvironmentInjector);
246
+ updates.startConfirm(() => runInInjectionContext(injector, promptForUpdate));
247
+ afterNextRender(() => updates.markInteractive());
248
+ }),
249
+ ]);
250
+ }
251
+ if (options.promptForUpdate !== undefined) {
252
+ throw new Error('provideKitAppUpdate promptForUpdate is only valid with the confirm strategy');
253
+ }
254
+ if (options.strategy === 'background') {
255
+ return makeEnvironmentProviders([
256
+ provideAppInitializer(() => {
257
+ const updates = inject(KitAppUpdateService);
258
+ updates.startBackground();
259
+ afterNextRender(() => updates.markInteractive());
260
+ }),
261
+ ]);
262
+ }
263
+ return makeEnvironmentProviders([provideAppInitializer(() => inject(KitAppUpdateService).initialize())]);
264
+ }
265
+ async function runUpdatePrompt(promptForUpdate) {
266
+ return promptForUpdate();
175
267
  }
176
268
  function withTimeout(promise, timeoutMs) {
177
269
  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, 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,EAA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AAO,CAAC,eAAe,EAAE;YACzB,eAAe,CAAC,MAAM,OAAO,CAAC,eAAe,EAAE,CAAC;AAClD,QAAA,CAAC;AACH,UAAE,qBAAqB,CAAC,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC,UAAU,EAAE,CAAC;AAC3E,IAAA,OAAO,wBAAwB,CAAC,CAAC,WAAW,CAAC,CAAC;AAChD;AAEA,SAAS,WAAW,CAAI,OAAmB,EAAE,SAAiB,EAAA;IAC5D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAI;AACrC,QAAA,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,OAAO,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC;AACtE,QAAA,KAAK,OAAO,CAAC,IAAI,CACf,CAAC,KAAK,KAAI;AACR,YAAA,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;YAC5B,OAAO,CAAC,KAAK,CAAC;AAChB,QAAA,CAAC,EACD,CAAC,KAAc,KAAI;AACjB,YAAA,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;YAC5B,MAAM,CAAC,KAAK,YAAY,KAAK,GAAG,KAAK,GAAG,IAAI,KAAK,CAAC,MAAM,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,KAAK;IAClB,YAAY,GAAG,KAAK;IACpB,UAAU,GAAG,KAAK;IAClB,SAAS,GAAG,KAAK;IACjB,qBAAqB,GAAG,KAAK;AAC7B,IAAA,gBAAgB;;IAGhB,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;AACj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