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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,51 @@
1
1
  # @rdlabo/ionic-angular-kit
2
2
 
3
- `@rdlabo/ionic-angular-kit` provides shared application infrastructure for Ionic Angular applications. It keeps product-specific screens, domain policy, and translations in the consuming app.
3
+ `@rdlabo/ionic-angular-kit` provides typed storage, typed overlays, and Ionic Signal Forms adapters for Ionic Angular applications. Product-specific screens, domain policy, and translations stay in the consuming app.
4
4
 
5
5
  ```sh
6
6
  npm install @rdlabo/ionic-angular-kit
7
7
  ```
8
8
 
9
+ ## First try: save a preference
10
+
11
+ In an existing Ionic Angular application, merge the Ionic Storage provider into your existing app config. Do not replace other providers.
12
+
13
+ ```ts
14
+ import { importProvidersFrom, type ApplicationConfig } from '@angular/core';
15
+ import { IonicStorageModule } from '@ionic/storage-angular';
16
+
17
+ export const appConfig: ApplicationConfig = {
18
+ providers: [importProvidersFrom(IonicStorageModule.forRoot({ name: '__mydb' }))],
19
+ };
20
+ ```
21
+
22
+ Then add this standalone component:
23
+
24
+ ```ts
25
+ import { Component, inject, signal } from '@angular/core';
26
+ import { IonButton } from '@ionic/angular';
27
+ import { disableHandler, KitStorageService } from '@rdlabo/ionic-angular-kit';
28
+
29
+ @Component({
30
+ selector: 'app-preferences-demo',
31
+ imports: [IonButton],
32
+ template: `<ion-button type="button" (click)="disableHandler($event, save())">Save preference</ion-button>
33
+ <p>{{ result() }}</p>`,
34
+ })
35
+ export class PreferencesDemo {
36
+ private readonly storage = inject(KitStorageService);
37
+ readonly result = signal('');
38
+ readonly disableHandler = disableHandler;
39
+
40
+ async save(): Promise<void> {
41
+ await this.storage.set('theme', 'dark');
42
+ this.result.set((await this.storage.get<string>('theme')) ?? '');
43
+ }
44
+ }
45
+ ```
46
+
47
+ Render `<app-preferences-demo>` on an existing page (import `PreferencesDemo` into that standalone page's `imports`). Click Save preference — `dark` appears. `KitStorageService` initializes storage automatically; no manual initialization is required.
48
+
9
49
  ## Requirements
10
50
 
11
51
  | Package | Supported version |
@@ -20,19 +60,23 @@ The core package declares `@ionic/storage-angular` and Capacitor Core, App, Hapt
20
60
 
21
61
  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.
22
62
 
63
+ The `/auth-firebase/google` entry point uses `@capawesome/capacitor-google-sign-in` 0.1.x and therefore requires Capacitor 8. Applications remaining on Capacitor 7 can continue to use the core Kit and other compatible entry points, but cannot use this Google entry point.
64
+
23
65
  ## Entry points
24
66
 
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 |
67
+ | Import | Responsibility |
68
+ | ------------------------------------------------ | ---------------------------------------------------------------------------------- |
69
+ | `@rdlabo/ionic-angular-kit` | Storage, overlays, guards, HTTP, realtime, directives, keyboard, and utilities |
70
+ | `@rdlabo/ionic-angular-kit/offline` | **Experimental.** Scoped local replica, outbox, pull, replay, and request policies |
71
+ | `@rdlabo/ionic-angular-kit/theme` | Persisted light/dark theme and native status bar sync |
72
+ | `@rdlabo/ionic-angular-kit/forms` | Ionic error text and state classes for Angular Signal Forms |
73
+ | `@rdlabo/ionic-angular-kit/review` | Throttled native in-app review requests |
74
+ | `@rdlabo/ionic-angular-kit/printer` | DOM-to-PNG, Brother label, and PDF helpers |
75
+ | `@rdlabo/ionic-angular-kit/auth-firebase` | Firebase dependency wiring and authentication flows |
76
+ | `@rdlabo/ionic-angular-kit/auth-firebase/google` | Google popup/native sign-in, Firebase session linking, and logout |
77
+ | `@rdlabo/ionic-angular-kit/auth-firebase/social` | Apple and Facebook Firebase social-auth helpers |
78
+ | `@rdlabo/ionic-angular-kit/app-update` | Atomic Angular service-worker update transitions |
79
+ | `@rdlabo/ionic-angular-kit/live-update` | Capawesome Live Update readiness provider |
36
80
 
37
81
  Secondary entry points isolate optional native and SDK dependencies from the core bundle.
38
82
 
@@ -40,11 +84,13 @@ The entire `/offline` entry point is experimental and is not covered by the kit'
40
84
 
41
85
  ## Configure only what you use
42
86
 
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.
87
+ 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) and [Forms](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/forms).
44
88
 
45
89
  ## Documentation
46
90
 
47
91
  - [Storage and Overlays](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/storage-overlays)
92
+ - [Forms](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/forms)
93
+ - [Check your Kit integration with ESLint](./docs/eslint.md)
48
94
  - [Authentication and HTTP](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/auth-http)
49
95
  - [Offline and Realtime](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/offline-realtime)
50
96
  - [Optional Features](https://docs.rdlabo.dev/projects/ionic-angular-kit/docs/optional-features)
package/docs/auth-http.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ## Access capability
2
2
 
3
- `provideKitAuth()` configures functional route guards for `user`, `confirm`, `required`, `anonymous`, and `unavailable` authentication states. Redirect routes and application side effects remain in the app.
3
+ `provideKitAuth()` configures functional route guards for `user`, `confirm`, `required`, `anonymous`, and `unavailable` authentication states. Redirect routes and application side effects remain in the app. `AuthService` in the examples below is application-owned; supply your own `authState` observable and optional lifecycle callbacks.
4
4
 
5
5
  `KitAuthAccessService` publishes what the current session may do:
6
6
 
@@ -13,23 +13,74 @@
13
13
  An authoritative `required` result is signed out and must not become offline access. Only an `unavailable` transport result may activate a previously verified local session.
14
14
 
15
15
  ```ts
16
- provideKitAuth(() => ({
17
- authState: () => inject(AuthService).state$,
18
- redirects: {
19
- whenAuthorized: '/home',
20
- whenConfirming: '/auth/confirm',
21
- whenNotConfirming: '/auth/signin',
22
- whenUnauthorized: '/auth',
23
- },
24
- isUnavailableError: (error) => isOfflineFallbackError(error),
25
- }));
16
+ import { inject } from '@angular/core';
17
+ import type { Routes } from '@angular/router';
18
+ import {
19
+ kitRequireAuthorizedGuard,
20
+ kitRequireConfirmingGuard,
21
+ kitRequiredUnauthorizedGuard,
22
+ provideKitAuth,
23
+ } from '@rdlabo/ionic-angular-kit';
24
+ import { AuthService } from './auth.service';
25
+
26
+ provideKitAuth(() => {
27
+ const auth = inject(AuthService);
28
+ return {
29
+ authState: () => auth.state$,
30
+ redirects: {
31
+ whenAuthorized: '/home',
32
+ whenConfirming: '/auth/confirm',
33
+ whenNotConfirming: '/auth/signin',
34
+ whenUnauthorized: '/auth',
35
+ },
36
+ };
37
+ });
38
+
39
+ export const routes: Routes = [
40
+ { path: 'auth/signin', canActivate: [kitRequiredUnauthorizedGuard], loadComponent: () => import('./signin.page').then((m) => m.SigninPage) },
41
+ { path: 'auth/confirm', canActivate: [kitRequireConfirmingGuard], loadComponent: () => import('./confirm.page').then((m) => m.ConfirmPage) },
42
+ { path: 'home', canActivate: [kitRequireAuthorizedGuard], loadComponent: () => import('./home.page').then((m) => m.HomePage) },
43
+ ];
26
44
  ```
27
45
 
28
46
  Use `kitRequiredUnauthorizedGuard`, `kitRequireConfirmingGuard`, and `kitRequireAuthorizedGuard` in route definitions. A protected asynchronous decision suspends previously published remote capability until the current authorization lease succeeds.
29
47
 
30
48
  ## HTTP policy
31
49
 
32
- `provideKitHttp()` configures `kitAuthInterceptor` for credential injection, bypass rules, transient failure handling, and application error hooks.
50
+ `provideKitHttp()` configures `kitAuthInterceptor` for credential injection, bypass rules, transient failure handling, and application error hooks. Register the interceptor separately with `provideHttpClient`. Only `getAuthHeaders` is required; every other hook is optional and application-owned.
51
+
52
+ ```ts
53
+ import { provideHttpClient, withInterceptors } from '@angular/common/http';
54
+ import { inject } from '@angular/core';
55
+ import type { ApplicationConfig } from '@angular/core';
56
+ import { kitAuthInterceptor, provideKitAuth, provideKitHttp } from '@rdlabo/ionic-angular-kit';
57
+ import { AuthService } from './auth.service';
58
+
59
+ export const appConfig: ApplicationConfig = {
60
+ providers: [
61
+ provideHttpClient(withInterceptors([kitAuthInterceptor])),
62
+ provideKitAuth(() => {
63
+ const auth = inject(AuthService);
64
+ return {
65
+ authState: () => auth.state$,
66
+ redirects: {
67
+ whenAuthorized: '/home',
68
+ whenConfirming: '/auth/confirm',
69
+ whenNotConfirming: '/auth/signin',
70
+ whenUnauthorized: '/auth',
71
+ },
72
+ };
73
+ }),
74
+ provideKitHttp(() => {
75
+ const auth = inject(AuthService);
76
+ return {
77
+ getAuthHeaders: async () => ({ Authorization: `Bearer ${await auth.token()}` }),
78
+ onUnauthorized: () => auth.signOut(),
79
+ };
80
+ }),
81
+ ],
82
+ };
83
+ ```
33
84
 
34
85
  Automatic retry is limited to `GET`, `HEAD`, `OPTIONS`, or requests carrying an `Idempotency-Key`. Ordinary writes are never retried automatically. Retries cover transient statuses `0`, `408`, `429`, `502`, `503`, and `504`, and honor `Retry-After`.
35
86
 
package/docs/eslint.md ADDED
@@ -0,0 +1,113 @@
1
+ ---
2
+ title: Check your Kit integration with ESLint
3
+ ---
4
+
5
+ Keep modal launchers, async action handlers, and form errors consistent as your Ionic Angular app grows. `@rdlabo/eslint-plugin-rules` checks the call patterns that work with `@rdlabo/ionic-angular-kit`.
6
+
7
+ ## Enable the checks you use
8
+
9
+ In an Ionic Angular 9 app with Angular / Angular ESLint 21–22 configured:
10
+
11
+ ```sh
12
+ npm install --save-dev @rdlabo/eslint-plugin-rules@22
13
+ ```
14
+
15
+ Merge these entries into `eslint.config.mjs`, retaining your existing checks. They enable four focused rules; choose the ones that match the Kit features in your app.
16
+
17
+ ```js
18
+ import tseslint from 'typescript-eslint';
19
+ import angular from 'angular-eslint';
20
+ import rdlabo from '@rdlabo/eslint-plugin-rules';
21
+
22
+ export default tseslint.config(
23
+ {
24
+ files: ['**/*.ts'],
25
+ languageOptions: { parser: tseslint.parser },
26
+ processor: angular.processInlineTemplates,
27
+ plugins: { '@rdlabo/rules': rdlabo },
28
+ rules: {
29
+ '@rdlabo/rules/deny-overlay-create': 'error',
30
+ '@rdlabo/rules/prefer-modal-launcher': 'error',
31
+ },
32
+ },
33
+ {
34
+ files: ['**/*.html'],
35
+ languageOptions: { parser: angular.templateParser },
36
+ plugins: { '@rdlabo/rules': rdlabo },
37
+ rules: {
38
+ '@rdlabo/rules/prefer-disable-handler': 'error',
39
+ '@rdlabo/rules/require-ion-error-text': 'error',
40
+ },
41
+ },
42
+ );
43
+ ```
44
+
45
+ These rules are also included in `rdlabo.configs.recommended`.
46
+
47
+ ## Keep modal creation in a launcher
48
+
49
+ `deny-overlay-create` reports `.create()` calls on `ModalController` and `PopoverController`. `prefer-modal-launcher` checks that `presentModal` calls live in `launch*` functions.
50
+
51
+ With `overlay` and `DetailPage` from your [overlay setup](./storage-overlays.md), this is reported:
52
+
53
+ ```ts
54
+ export const openDetail = () => overlay.presentModal(DetailPage);
55
+ ```
56
+
57
+ Use a launcher:
58
+
59
+ ```ts
60
+ export const launchDetail = () => overlay.presentModal(DetailPage);
61
+ ```
62
+
63
+ ## Keep async actions wrapped
64
+
65
+ `prefer-disable-handler` reports an unwrapped action:
66
+
67
+ ```html
68
+ <ion-button type="button" (click)="vm.refresh()">Refresh</ion-button>
69
+ ```
70
+
71
+ Expose the Kit's `disableHandler` helper on your component or ViewModel, then pass the event and async work:
72
+
73
+ ```ts
74
+ import { disableHandler } from '@rdlabo/ionic-angular-kit';
75
+
76
+ // Inside the component or ViewModel:
77
+ readonly disableHandler = disableHandler;
78
+ ```
79
+
80
+ ```html
81
+ <ion-button type="button" (click)="vm.disableHandler($event, vm.refresh())">Refresh</ion-button>
82
+ ```
83
+
84
+ The rule checks the wrapper call, not the async work's behavior. Keep submit actions on the form's `(submit)` with `ion-button type="submit"`.
85
+
86
+ ## Match the Signal Forms adapter
87
+
88
+ By default, `require-ion-error-text` requires an error text source on Ionic controls with `[formField]`.
89
+
90
+ For Angular 22 apps using [Kit Signal Forms](./forms.md), import `FormField` and `KitIonicFormField` in each relevant component and install `provideKitIonicSignalForms()`. Then override this entry in the HTML config's `rules`:
91
+
92
+ ```js
93
+ '@rdlabo/rules/require-ion-error-text': [
94
+ 'error',
95
+ { formFieldProvidesErrorText: true },
96
+ ],
97
+ ```
98
+
99
+ This option declares that the adapter supplies error text; ESLint does not verify the adapter's imports or providers.
100
+
101
+ ## Add ViewModel policy when you use it
102
+
103
+ If your app uses a `ViewModelStore` architecture, add [require-viewmodel](https://docs.rdlabo.dev/projects/eslint-plugin-rules/docs/rules/require-viewmodel) and [no-component-writable-signal](https://docs.rdlabo.dev/projects/eslint-plugin-rules/docs/rules/no-component-writable-signal). Configure them around your app's ViewModel base; `ViewModelStore` is not a Kit export.
104
+
105
+ ## Run it in CI
106
+
107
+ After installing dependencies, run locally and in CI:
108
+
109
+ ```sh
110
+ npx eslint 'src/**/*.{ts,html}' --max-warnings 0
111
+ ```
112
+
113
+ Adjust the source path for your app. See [ESLint configuration](https://docs.rdlabo.dev/projects/eslint-plugin-rules/docs/configuration) for the complete recommended policy and [rule options](https://docs.rdlabo.dev/projects/eslint-plugin-rules/docs/rules) for other conventions.
package/docs/forms.md CHANGED
@@ -2,27 +2,38 @@
2
2
 
3
3
  This entry point targets Angular 22 Signal Forms.
4
4
 
5
- Import Angular's `FormField` together with the kit adapter in each standalone component that binds Signal Forms to Ionic controls.
5
+ Register the adapter once at bootstrap, then bind Signal Forms to Ionic controls with Angular's `FormField` and `KitIonicFormField`:
6
6
 
7
7
  ```ts
8
- import { FormField } from '@angular/forms/signals';
9
- import { KitIonicFormField } from '@rdlabo/ionic-angular-kit/forms';
8
+ import { Component, signal } from '@angular/core';
9
+ import type { ApplicationConfig } from '@angular/core';
10
+ import { FormField, form, required, email, maxLength } from '@angular/forms/signals';
11
+ import { IonInput } from '@ionic/angular';
12
+ import { KitIonicFormField, provideKitIonicSignalForms } from '@rdlabo/ionic-angular-kit/forms';
13
+
14
+ export const appConfig: ApplicationConfig = {
15
+ providers: [provideKitIonicSignalForms()],
16
+ };
10
17
 
11
18
  @Component({
12
- imports: [FormField, KitIonicFormField],
19
+ selector: 'app-profile',
20
+ imports: [FormField, KitIonicFormField, IonInput],
21
+ template: `
22
+ <ion-input label="Name" [formField]="profileForm.name"></ion-input>
23
+ <ion-input label="Email" type="email" [formField]="profileForm.email"></ion-input>
24
+ `,
13
25
  })
14
- export class ProfilePage {}
26
+ export class ProfilePage {
27
+ readonly profile = signal({ name: '', email: '' });
28
+ readonly profileForm = form(this.profile, (path) => {
29
+ required(path.name);
30
+ email(path.email);
31
+ maxLength(path.name, 200);
32
+ });
33
+ }
15
34
  ```
16
35
 
17
- The adapter copies the first non-empty explicit validation message to Ionic's `errorText` property for `ion-input`, `ion-textarea`, `ion-select`, `ion-checkbox`, `ion-radio-group`, and `ion-toggle`. When Angular's validator does not provide a message, the adapter derives a generic English message from the validation error `kind` and its constraint metadata. Built-in validators therefore need no message configuration:
18
-
19
- ```ts
20
- readonly profileForm = form(this.profile, (path) => {
21
- required(path.name);
22
- email(path.email);
23
- maxLength(path.name, 200);
24
- });
25
- ```
36
+ Leave a required field empty and blur it — Ionic shows `errorText`, and the control becomes invalid and touched. The adapter copies the first non-empty explicit validation message to `errorText` for `ion-input`, `ion-textarea`, `ion-select`, `ion-checkbox`, `ion-radio-group`, and `ion-toggle`. When Angular's validator does not provide a message, the adapter derives a generic English message from the validation error `kind` and its constraint metadata. Built-in validators therefore need no message configuration.
26
37
 
27
38
  Unknown custom error kinds fall back to `Enter a valid value.`. Keep business-rule failures outside field validation. An explicit validation message still takes precedence for compatibility, and an explicit `errorText` or `[errorText]` binding prevents the adapter from being instantiated.
28
39
 
@@ -34,6 +45,7 @@ import { KIT_SIGNAL_FORM_ERROR_MESSAGE_RESOLVER } from '@rdlabo/ionic-angular-ki
34
45
 
35
46
  export const appConfig: ApplicationConfig = {
36
47
  providers: [
48
+ provideKitIonicSignalForms(),
37
49
  {
38
50
  provide: KIT_SIGNAL_FORM_ERROR_MESSAGE_RESOLVER,
39
51
  useValue: (error: ValidationError) => localizedMessageFor(error),
@@ -42,25 +54,6 @@ export const appConfig: ApplicationConfig = {
42
54
  };
43
55
  ```
44
56
 
45
- Install the state-class configuration once at application bootstrap:
46
-
47
- ```ts
48
- import { provideKitIonicSignalForms } from '@rdlabo/ionic-angular-kit/forms';
49
-
50
- export const appConfig: ApplicationConfig = {
51
- providers: [provideKitIonicSignalForms()],
52
- };
53
- ```
54
-
55
57
  Angular does not merge multiple `provideSignalFormsConfig` class configurations. If the application provides its own configuration, combine all required class mappings in one provider instead of registering both providers and relying on their order.
56
58
 
57
- When using `@rdlabo/eslint-plugin-rules`, enable its adapter-aware mode only after every relevant standalone component has imported the adapter:
58
-
59
- ```js
60
- {
61
- files: ['**/*.html'],
62
- rules: {
63
- '@rdlabo/rules/require-ion-error-text': ['error', { formFieldProvidesErrorText: true }],
64
- },
65
- }
66
- ```
59
+ For the matching lint configuration, see [Check your Kit integration with ESLint](./eslint.md).
@@ -157,8 +157,9 @@ import type { CanActivateFn, Routes } from '@angular/router';
157
157
  import { OfflineRouteInitializerService, provideRouteScopedOffline } from '@rdlabo/ionic-angular-kit/offline';
158
158
 
159
159
  const offlineReadyGuard: CanActivateFn = async () => {
160
+ const offlineRouteInitializer = inject(OfflineRouteInitializerService);
160
161
  await recoverProductOwnedLocalReset();
161
- await inject(OfflineRouteInitializerService).initialize();
162
+ await offlineRouteInitializer.initialize();
162
163
  return true;
163
164
  };
164
165
 
@@ -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
 
@@ -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) => {