UNPKG

17.2 kBTypeScriptView Raw
1/**
2 * @license Angular v13.2.0
3 * (c) 2010-2022 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7import * as i0 from '@angular/core';
8import { ModuleWithProviders } from '@angular/core';
9import { Observable } from 'rxjs';
10
11/**
12 * @publicApi
13 */
14declare class NgswCommChannel {
15 private serviceWorker;
16 readonly worker: Observable<ServiceWorker>;
17 readonly registration: Observable<ServiceWorkerRegistration>;
18 readonly events: Observable<TypedEvent>;
19 constructor(serviceWorker: ServiceWorkerContainer | undefined);
20 postMessage(action: string, payload: Object): Promise<void>;
21 postMessageWithOperation(type: string, payload: Object, operationNonce: number): Promise<boolean>;
22 generateNonce(): number;
23 eventsOfType<T extends TypedEvent>(type: T['type'] | T['type'][]): Observable<T>;
24 nextEventOfType<T extends TypedEvent>(type: T['type']): Observable<T>;
25 waitForOperationCompleted(nonce: number): Promise<boolean>;
26 get isEnabled(): boolean;
27}
28
29/**
30 * @publicApi
31 */
32export declare class ServiceWorkerModule {
33 /**
34 * Register the given Angular Service Worker script.
35 *
36 * If `enabled` is set to `false` in the given options, the module will behave as if service
37 * workers are not supported by the browser, and the service worker will not be registered.
38 */
39 static register(script: string, opts?: SwRegistrationOptions): ModuleWithProviders<ServiceWorkerModule>;
40 static ɵfac: i0.ɵɵFactoryDeclaration<ServiceWorkerModule, never>;
41 static ɵmod: i0.ɵɵNgModuleDeclaration<ServiceWorkerModule, never, never, never>;
42 static ɵinj: i0.ɵɵInjectorDeclaration<ServiceWorkerModule>;
43}
44
45/**
46 * Subscribe and listen to
47 * [Web Push
48 * Notifications](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices) through
49 * Angular Service Worker.
50 *
51 * @usageNotes
52 *
53 * You can inject a `SwPush` instance into any component or service
54 * as a dependency.
55 *
56 * <code-example path="service-worker/push/module.ts" region="inject-sw-push"
57 * header="app.component.ts"></code-example>
58 *
59 * To subscribe, call `SwPush.requestSubscription()`, which asks the user for permission.
60 * The call returns a `Promise` with a new
61 * [`PushSubscription`](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription)
62 * instance.
63 *
64 * <code-example path="service-worker/push/module.ts" region="subscribe-to-push"
65 * header="app.component.ts"></code-example>
66 *
67 * A request is rejected if the user denies permission, or if the browser
68 * blocks or does not support the Push API or ServiceWorkers.
69 * Check `SwPush.isEnabled` to confirm status.
70 *
71 * Invoke Push Notifications by pushing a message with the following payload.
72 *
73 * ```ts
74 * {
75 * "notification": {
76 * "actions": NotificationAction[],
77 * "badge": USVString,
78 * "body": DOMString,
79 * "data": any,
80 * "dir": "auto"|"ltr"|"rtl",
81 * "icon": USVString,
82 * "image": USVString,
83 * "lang": DOMString,
84 * "renotify": boolean,
85 * "requireInteraction": boolean,
86 * "silent": boolean,
87 * "tag": DOMString,
88 * "timestamp": DOMTimeStamp,
89 * "title": DOMString,
90 * "vibrate": number[]
91 * }
92 * }
93 * ```
94 *
95 * Only `title` is required. See `Notification`
96 * [instance
97 * properties](https://developer.mozilla.org/en-US/docs/Web/API/Notification#Instance_properties).
98 *
99 * While the subscription is active, Service Worker listens for
100 * [PushEvent](https://developer.mozilla.org/en-US/docs/Web/API/PushEvent)
101 * occurrences and creates
102 * [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification)
103 * instances in response.
104 *
105 * Unsubscribe using `SwPush.unsubscribe()`.
106 *
107 * An application can subscribe to `SwPush.notificationClicks` observable to be notified when a user
108 * clicks on a notification. For example:
109 *
110 * <code-example path="service-worker/push/module.ts" region="subscribe-to-notification-clicks"
111 * header="app.component.ts"></code-example>
112 *
113 * You can read more on handling notification clicks in the [Service worker notifications
114 * guide](guide/service-worker-notifications).
115 *
116 * @see [Push Notifications](https://developers.google.com/web/fundamentals/codelabs/push-notifications/)
117 * @see [Angular Push Notifications](https://blog.angular-university.io/angular-push-notifications/)
118 * @see [MDN: Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)
119 * @see [MDN: Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API)
120 * @see [MDN: Web Push API Notifications best practices](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices)
121 *
122 * @publicApi
123 */
124export declare class SwPush {
125 private sw;
126 /**
127 * Emits the payloads of the received push notification messages.
128 */
129 readonly messages: Observable<object>;
130 /**
131 * Emits the payloads of the received push notification messages as well as the action the user
132 * interacted with. If no action was used the `action` property contains an empty string `''`.
133 *
134 * Note that the `notification` property does **not** contain a
135 * [Notification][Mozilla Notification] object but rather a
136 * [NotificationOptions](https://notifications.spec.whatwg.org/#dictdef-notificationoptions)
137 * object that also includes the `title` of the [Notification][Mozilla Notification] object.
138 *
139 * [Mozilla Notification]: https://developer.mozilla.org/en-US/docs/Web/API/Notification
140 */
141 readonly notificationClicks: Observable<{
142 action: string;
143 notification: NotificationOptions & {
144 title: string;
145 };
146 }>;
147 /**
148 * Emits the currently active
149 * [PushSubscription](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription)
150 * associated to the Service Worker registration or `null` if there is no subscription.
151 */
152 readonly subscription: Observable<PushSubscription | null>;
153 /**
154 * True if the Service Worker is enabled (supported by the browser and enabled via
155 * `ServiceWorkerModule`).
156 */
157 get isEnabled(): boolean;
158 private pushManager;
159 private subscriptionChanges;
160 constructor(sw: NgswCommChannel);
161 /**
162 * Subscribes to Web Push Notifications,
163 * after requesting and receiving user permission.
164 *
165 * @param options An object containing the `serverPublicKey` string.
166 * @returns A Promise that resolves to the new subscription object.
167 */
168 requestSubscription(options: {
169 serverPublicKey: string;
170 }): Promise<PushSubscription>;
171 /**
172 * Unsubscribes from Service Worker push notifications.
173 *
174 * @returns A Promise that is resolved when the operation succeeds, or is rejected if there is no
175 * active subscription or the unsubscribe operation fails.
176 */
177 unsubscribe(): Promise<void>;
178 private decodeBase64;
179 static ɵfac: i0.ɵɵFactoryDeclaration<SwPush, never>;
180 static ɵprov: i0.ɵɵInjectableDeclaration<SwPush>;
181}
182
183/**
184 * Token that can be used to provide options for `ServiceWorkerModule` outside of
185 * `ServiceWorkerModule.register()`.
186 *
187 * You can use this token to define a provider that generates the registration options at runtime,
188 * for example via a function call:
189 *
190 * {@example service-worker/registration-options/module.ts region="registration-options"
191 * header="app.module.ts"}
192 *
193 * @publicApi
194 */
195export declare abstract class SwRegistrationOptions {
196 /**
197 * Whether the ServiceWorker will be registered and the related services (such as `SwPush` and
198 * `SwUpdate`) will attempt to communicate and interact with it.
199 *
200 * Default: true
201 */
202 enabled?: boolean;
203 /**
204 * A URL that defines the ServiceWorker's registration scope; that is, what range of URLs it can
205 * control. It will be used when calling
206 * [ServiceWorkerContainer#register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
207 */
208 scope?: string;
209 /**
210 * Defines the ServiceWorker registration strategy, which determines when it will be registered
211 * with the browser.
212 *
213 * The default behavior of registering once the application stabilizes (i.e. as soon as there are
214 * no pending micro- and macro-tasks) is designed to register the ServiceWorker as soon as
215 * possible but without affecting the application's first time load.
216 *
217 * Still, there might be cases where you want more control over when the ServiceWorker is
218 * registered (for example, there might be a long-running timeout or polling interval, preventing
219 * the app from stabilizing). The available option are:
220 *
221 * - `registerWhenStable:<timeout>`: Register as soon as the application stabilizes (no pending
222 * micro-/macro-tasks) but no later than `<timeout>` milliseconds. If the app hasn't
223 * stabilized after `<timeout>` milliseconds (for example, due to a recurrent asynchronous
224 * task), the ServiceWorker will be registered anyway.
225 * If `<timeout>` is omitted, the ServiceWorker will only be registered once the app
226 * stabilizes.
227 * - `registerImmediately`: Register immediately.
228 * - `registerWithDelay:<timeout>`: Register with a delay of `<timeout>` milliseconds. For
229 * example, use `registerWithDelay:5000` to register the ServiceWorker after 5 seconds. If
230 * `<timeout>` is omitted, is defaults to `0`, which will register the ServiceWorker as soon
231 * as possible but still asynchronously, once all pending micro-tasks are completed.
232 * - An [Observable](guide/observables) factory function: A function that returns an `Observable`.
233 * The function will be used at runtime to obtain and subscribe to the `Observable` and the
234 * ServiceWorker will be registered as soon as the first value is emitted.
235 *
236 * Default: 'registerWhenStable:30000'
237 */
238 registrationStrategy?: string | (() => Observable<unknown>);
239}
240
241/**
242 * Subscribe to update notifications from the Service Worker, trigger update
243 * checks, and forcibly activate updates.
244 *
245 * @see {@link guide/service-worker-communications Service worker communication guide}
246 *
247 * @publicApi
248 */
249export declare class SwUpdate {
250 private sw;
251 /**
252 * Emits a `VersionDetectedEvent` event whenever a new version is detected on the server.
253 *
254 * Emits a `VersionInstallationFailedEvent` event whenever checking for or downloading a new
255 * version fails.
256 *
257 * Emits a `VersionReadyEvent` event whenever a new version has been downloaded and is ready for
258 * activation.
259 */
260 readonly versionUpdates: Observable<VersionEvent>;
261 /**
262 * Emits an `UpdateAvailableEvent` event whenever a new app version is available.
263 *
264 * @deprecated Use {@link versionUpdates} instead.
265 *
266 * The of behavior `available` can be rebuild by filtering for the `VersionReadyEvent`:
267 * ```
268 * import {filter, map} from 'rxjs/operators';
269 * // ...
270 * const updatesAvailable = swUpdate.versionUpdates.pipe(
271 * filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'),
272 * map(evt => ({
273 * type: 'UPDATE_AVAILABLE',
274 * current: evt.currentVersion,
275 * available: evt.latestVersion,
276 * })));
277 * ```
278 */
279 readonly available: Observable<UpdateAvailableEvent>;
280 /**
281 * Emits an `UpdateActivatedEvent` event whenever the app has been updated to a new version.
282 *
283 * @deprecated Use the return value of {@link SwUpdate#activateUpdate} instead.
284 *
285 */
286 readonly activated: Observable<UpdateActivatedEvent>;
287 /**
288 * Emits an `UnrecoverableStateEvent` event whenever the version of the app used by the service
289 * worker to serve this client is in a broken state that cannot be recovered from without a full
290 * page reload.
291 */
292 readonly unrecoverable: Observable<UnrecoverableStateEvent>;
293 /**
294 * True if the Service Worker is enabled (supported by the browser and enabled via
295 * `ServiceWorkerModule`).
296 */
297 get isEnabled(): boolean;
298 constructor(sw: NgswCommChannel);
299 /**
300 * Checks for an update and waits until the new version is downloaded from the server and ready
301 * for activation.
302 *
303 * @returns a promise that
304 * - resolves to `true` if a new version was found and is ready to be activated.
305 * - resolves to `false` if no new version was found
306 * - rejects if any error occurs
307 */
308 checkForUpdate(): Promise<boolean>;
309 /**
310 * Updates the current client (i.e. browser tab) to the latest version that is ready for
311 * activation.
312 *
313 * @returns a promise that
314 * - resolves to `true` if an update was activated successfully
315 * - resolves to `false` if no update was available (for example, the client was already on the
316 * latest version).
317 * - rejects if any error occurs
318 */
319 activateUpdate(): Promise<boolean>;
320 static ɵfac: i0.ɵɵFactoryDeclaration<SwUpdate, never>;
321 static ɵprov: i0.ɵɵInjectableDeclaration<SwUpdate>;
322}
323
324declare interface TypedEvent {
325 type: string;
326}
327
328/**
329 * An event emitted when the version of the app used by the service worker to serve this client is
330 * in a broken state that cannot be recovered from and a full page reload is required.
331 *
332 * For example, the service worker may not be able to retrieve a required resource, neither from the
333 * cache nor from the server. This could happen if a new version is deployed to the server and the
334 * service worker cache has been partially cleaned by the browser, removing some files of a previous
335 * app version but not all.
336 *
337 * @see {@link guide/service-worker-communications Service worker communication guide}
338 *
339 * @publicApi
340 */
341export declare interface UnrecoverableStateEvent {
342 type: 'UNRECOVERABLE_STATE';
343 reason: string;
344}
345
346/**
347 * An event emitted when a new version of the app has been downloaded and activated.
348 *
349 * @see {@link guide/service-worker-communications Service worker communication guide}
350 *
351 * @deprecated
352 * This event is only emitted by the deprecated {@link SwUpdate#activated}.
353 * Use the return value of {@link SwUpdate#activateUpdate} instead.
354 *
355 * @publicApi
356 */
357export declare interface UpdateActivatedEvent {
358 type: 'UPDATE_ACTIVATED';
359 previous?: {
360 hash: string;
361 appData?: Object;
362 };
363 current: {
364 hash: string;
365 appData?: Object;
366 };
367}
368
369/**
370 * An event emitted when a new version of the app is available.
371 *
372 * @see {@link guide/service-worker-communications Service worker communication guide}
373 *
374 * @deprecated
375 * This event is only emitted by the deprecated {@link SwUpdate#available}.
376 * Use the {@link VersionReadyEvent} instead, which is emitted by {@link SwUpdate#versionUpdates}.
377 * See {@link SwUpdate#available} docs for an example.
378 *
379 * @publicApi
380 */
381export declare interface UpdateAvailableEvent {
382 type: 'UPDATE_AVAILABLE';
383 current: {
384 hash: string;
385 appData?: Object;
386 };
387 available: {
388 hash: string;
389 appData?: Object;
390 };
391}
392
393/**
394 * An event emitted when the service worker has detected a new version of the app on the server and
395 * is about to start downloading it.
396 *
397 * @see {@link guide/service-worker-communications Service worker communication guide}
398 *
399 * @publicApi
400 */
401export declare interface VersionDetectedEvent {
402 type: 'VERSION_DETECTED';
403 version: {
404 hash: string;
405 appData?: object;
406 };
407}
408
409/**
410 * A union of all event types that can be emitted by
411 * {@link api/service-worker/SwUpdate#versionUpdates SwUpdate#versionUpdates}.
412 *
413 * @publicApi
414 */
415export declare type VersionEvent = VersionDetectedEvent | VersionInstallationFailedEvent | VersionReadyEvent;
416
417/**
418 * An event emitted when the installation of a new version failed.
419 * It may be used for logging/monitoring purposes.
420 *
421 * @see {@link guide/service-worker-communications Service worker communication guide}
422 *
423 * @publicApi
424 */
425export declare interface VersionInstallationFailedEvent {
426 type: 'VERSION_INSTALLATION_FAILED';
427 version: {
428 hash: string;
429 appData?: object;
430 };
431 error: string;
432}
433
434/**
435 * An event emitted when a new version of the app is available.
436 *
437 * @see {@link guide/service-worker-communications Service worker communication guide}
438 *
439 * @publicApi
440 */
441export declare interface VersionReadyEvent {
442 type: 'VERSION_READY';
443 currentVersion: {
444 hash: string;
445 appData?: object;
446 };
447 latestVersion: {
448 hash: string;
449 appData?: object;
450 };
451}
452
453export { }
454
\No newline at end of file