dealposbarcode 1.3.3 → 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2825 +0,0 @@
1
- (function () {
2
- 'use strict';
3
-
4
- /**
5
- * @license
6
- * Copyright Google LLC All Rights Reserved.
7
- *
8
- * Use of this source code is governed by an MIT-style license that can be
9
- * found in the LICENSE file at https://angular.io/license
10
- */
11
- /**
12
- * A wrapper around `CacheStorage` to allow interacting with caches more easily and consistently by:
13
- * - Adding a `name` property to all opened caches, which can be used to easily perform other
14
- * operations that require the cache name.
15
- * - Name-spacing cache names to avoid conflicts with other caches on the same domain.
16
- */
17
- class NamedCacheStorage {
18
- constructor(original, cacheNamePrefix) {
19
- this.original = original;
20
- this.cacheNamePrefix = cacheNamePrefix;
21
- }
22
- delete(cacheName) {
23
- return this.original.delete(`${this.cacheNamePrefix}:${cacheName}`);
24
- }
25
- has(cacheName) {
26
- return this.original.has(`${this.cacheNamePrefix}:${cacheName}`);
27
- }
28
- async keys() {
29
- const prefix = `${this.cacheNamePrefix}:`;
30
- const allCacheNames = await this.original.keys();
31
- const ownCacheNames = allCacheNames.filter(name => name.startsWith(prefix));
32
- return ownCacheNames.map(name => name.slice(prefix.length));
33
- }
34
- match(request, options) {
35
- return this.original.match(request, options);
36
- }
37
- async open(cacheName) {
38
- const cache = await this.original.open(`${this.cacheNamePrefix}:${cacheName}`);
39
- return Object.assign(cache, { name: cacheName });
40
- }
41
- }
42
-
43
- /**
44
- * @license
45
- * Copyright Google LLC All Rights Reserved.
46
- *
47
- * Use of this source code is governed by an MIT-style license that can be
48
- * found in the LICENSE file at https://angular.io/license
49
- */
50
- /**
51
- * Adapts the service worker to its runtime environment.
52
- *
53
- * Mostly, this is used to mock out identifiers which are otherwise read
54
- * from the global scope.
55
- */
56
- class Adapter {
57
- constructor(scopeUrl, caches) {
58
- this.scopeUrl = scopeUrl;
59
- const parsedScopeUrl = this.parseUrl(this.scopeUrl);
60
- // Determine the origin from the registration scope. This is used to differentiate between
61
- // relative and absolute URLs.
62
- this.origin = parsedScopeUrl.origin;
63
- // Use the baseHref in the cache name prefix to avoid clash of cache names for SWs with
64
- // different scopes on the same domain.
65
- this.caches = new NamedCacheStorage(caches, `ngsw:${parsedScopeUrl.path}`);
66
- }
67
- /**
68
- * Wrapper around the `Request` constructor.
69
- */
70
- newRequest(input, init) {
71
- return new Request(input, init);
72
- }
73
- /**
74
- * Wrapper around the `Response` constructor.
75
- */
76
- newResponse(body, init) {
77
- return new Response(body, init);
78
- }
79
- /**
80
- * Wrapper around the `Headers` constructor.
81
- */
82
- newHeaders(headers) {
83
- return new Headers(headers);
84
- }
85
- /**
86
- * Test if a given object is an instance of `Client`.
87
- */
88
- isClient(source) {
89
- return (source instanceof Client);
90
- }
91
- /**
92
- * Read the current UNIX time in milliseconds.
93
- */
94
- get time() {
95
- return Date.now();
96
- }
97
- /**
98
- * Get a normalized representation of a URL such as those found in the ServiceWorker's `ngsw.json`
99
- * configuration.
100
- *
101
- * More specifically:
102
- * 1. Resolve the URL relative to the ServiceWorker's scope.
103
- * 2. If the URL is relative to the ServiceWorker's own origin, then only return the path part.
104
- * Otherwise, return the full URL.
105
- *
106
- * @param url The raw request URL.
107
- * @return A normalized representation of the URL.
108
- */
109
- normalizeUrl(url) {
110
- // Check the URL's origin against the ServiceWorker's.
111
- const parsed = this.parseUrl(url, this.scopeUrl);
112
- return (parsed.origin === this.origin ? parsed.path : url);
113
- }
114
- /**
115
- * Parse a URL into its different parts, such as `origin`, `path` and `search`.
116
- */
117
- parseUrl(url, relativeTo) {
118
- // Workaround a Safari bug, see
119
- // https://github.com/angular/angular/issues/31061#issuecomment-503637978
120
- const parsed = !relativeTo ? new URL(url) : new URL(url, relativeTo);
121
- return { origin: parsed.origin, path: parsed.pathname, search: parsed.search };
122
- }
123
- /**
124
- * Wait for a given amount of time before completing a Promise.
125
- */
126
- timeout(ms) {
127
- return new Promise(resolve => {
128
- setTimeout(() => resolve(), ms);
129
- });
130
- }
131
- }
132
-
133
- /**
134
- * @license
135
- * Copyright Google LLC All Rights Reserved.
136
- *
137
- * Use of this source code is governed by an MIT-style license that can be
138
- * found in the LICENSE file at https://angular.io/license
139
- */
140
- /**
141
- * An error returned in rejected promises if the given key is not found in the table.
142
- */
143
- class NotFound {
144
- constructor(table, key) {
145
- this.table = table;
146
- this.key = key;
147
- }
148
- }
149
-
150
- /**
151
- * @license
152
- * Copyright Google LLC All Rights Reserved.
153
- *
154
- * Use of this source code is governed by an MIT-style license that can be
155
- * found in the LICENSE file at https://angular.io/license
156
- */
157
- /**
158
- * An implementation of a `Database` that uses the `CacheStorage` API to serialize
159
- * state within mock `Response` objects.
160
- */
161
- class CacheDatabase {
162
- constructor(adapter) {
163
- this.adapter = adapter;
164
- this.cacheNamePrefix = 'db';
165
- this.tables = new Map();
166
- }
167
- 'delete'(name) {
168
- if (this.tables.has(name)) {
169
- this.tables.delete(name);
170
- }
171
- return this.adapter.caches.delete(`${this.cacheNamePrefix}:${name}`);
172
- }
173
- async list() {
174
- const prefix = `${this.cacheNamePrefix}:`;
175
- const allCacheNames = await this.adapter.caches.keys();
176
- const dbCacheNames = allCacheNames.filter(name => name.startsWith(prefix));
177
- // Return the un-prefixed table names, so they can be used with other `CacheDatabase` methods
178
- // (for example, for opening/deleting a table).
179
- return dbCacheNames.map(name => name.slice(prefix.length));
180
- }
181
- async open(name, cacheQueryOptions) {
182
- if (!this.tables.has(name)) {
183
- const cache = await this.adapter.caches.open(`${this.cacheNamePrefix}:${name}`);
184
- const table = new CacheTable(name, cache, this.adapter, cacheQueryOptions);
185
- this.tables.set(name, table);
186
- }
187
- return this.tables.get(name);
188
- }
189
- }
190
- /**
191
- * A `Table` backed by a `Cache`.
192
- */
193
- class CacheTable {
194
- constructor(name, cache, adapter, cacheQueryOptions) {
195
- this.name = name;
196
- this.cache = cache;
197
- this.adapter = adapter;
198
- this.cacheQueryOptions = cacheQueryOptions;
199
- this.cacheName = this.cache.name;
200
- }
201
- request(key) {
202
- return this.adapter.newRequest('/' + key);
203
- }
204
- 'delete'(key) {
205
- return this.cache.delete(this.request(key), this.cacheQueryOptions);
206
- }
207
- keys() {
208
- return this.cache.keys().then(requests => requests.map(req => req.url.substr(1)));
209
- }
210
- read(key) {
211
- return this.cache.match(this.request(key), this.cacheQueryOptions).then(res => {
212
- if (res === undefined) {
213
- return Promise.reject(new NotFound(this.name, key));
214
- }
215
- return res.json();
216
- });
217
- }
218
- write(key, value) {
219
- return this.cache.put(this.request(key), this.adapter.newResponse(JSON.stringify(value)));
220
- }
221
- }
222
-
223
- /**
224
- * @license
225
- * Copyright Google LLC All Rights Reserved.
226
- *
227
- * Use of this source code is governed by an MIT-style license that can be
228
- * found in the LICENSE file at https://angular.io/license
229
- */
230
- var UpdateCacheStatus = /*@__PURE__*/ (function (UpdateCacheStatus) {
231
- UpdateCacheStatus[UpdateCacheStatus["NOT_CACHED"] = 0] = "NOT_CACHED";
232
- UpdateCacheStatus[UpdateCacheStatus["CACHED_BUT_UNUSED"] = 1] = "CACHED_BUT_UNUSED";
233
- UpdateCacheStatus[UpdateCacheStatus["CACHED"] = 2] = "CACHED";
234
- return UpdateCacheStatus;
235
- })({});
236
-
237
- /**
238
- * @license
239
- * Copyright Google LLC All Rights Reserved.
240
- *
241
- * Use of this source code is governed by an MIT-style license that can be
242
- * found in the LICENSE file at https://angular.io/license
243
- */
244
- class SwCriticalError extends Error {
245
- constructor() {
246
- super(...arguments);
247
- this.isCritical = true;
248
- }
249
- }
250
- function errorToString(error) {
251
- if (error instanceof Error) {
252
- return `${error.message}\n${error.stack}`;
253
- }
254
- else {
255
- return `${error}`;
256
- }
257
- }
258
- class SwUnrecoverableStateError extends SwCriticalError {
259
- constructor() {
260
- super(...arguments);
261
- this.isUnrecoverableState = true;
262
- }
263
- }
264
-
265
- /**
266
- * @license
267
- * Copyright Google LLC All Rights Reserved.
268
- *
269
- * Use of this source code is governed by an MIT-style license that can be
270
- * found in the LICENSE file at https://angular.io/license
271
- */
272
- /**
273
- * Compute the SHA1 of the given string
274
- *
275
- * see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
276
- *
277
- * WARNING: this function has not been designed not tested with security in mind.
278
- * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
279
- *
280
- * Borrowed from @angular/compiler/src/i18n/digest.ts
281
- */
282
- function sha1(str) {
283
- const utf8 = str;
284
- const words32 = stringToWords32(utf8, Endian.Big);
285
- return _sha1(words32, utf8.length * 8);
286
- }
287
- function sha1Binary(buffer) {
288
- const words32 = arrayBufferToWords32(buffer, Endian.Big);
289
- return _sha1(words32, buffer.byteLength * 8);
290
- }
291
- function _sha1(words32, len) {
292
- const w = [];
293
- let [a, b, c, d, e] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
294
- words32[len >> 5] |= 0x80 << (24 - len % 32);
295
- words32[((len + 64 >> 9) << 4) + 15] = len;
296
- for (let i = 0; i < words32.length; i += 16) {
297
- const [h0, h1, h2, h3, h4] = [a, b, c, d, e];
298
- for (let j = 0; j < 80; j++) {
299
- if (j < 16) {
300
- w[j] = words32[i + j];
301
- }
302
- else {
303
- w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
304
- }
305
- const [f, k] = fk(j, b, c, d);
306
- const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
307
- [e, d, c, b, a] = [d, c, rol32(b, 30), a, temp];
308
- }
309
- [a, b, c, d, e] = [add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)];
310
- }
311
- return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
312
- }
313
- function add32(a, b) {
314
- return add32to64(a, b)[1];
315
- }
316
- function add32to64(a, b) {
317
- const low = (a & 0xffff) + (b & 0xffff);
318
- const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
319
- return [high >>> 16, (high << 16) | (low & 0xffff)];
320
- }
321
- // Rotate a 32b number left `count` position
322
- function rol32(a, count) {
323
- return (a << count) | (a >>> (32 - count));
324
- }
325
- var Endian = /*@__PURE__*/ (function (Endian) {
326
- Endian[Endian["Little"] = 0] = "Little";
327
- Endian[Endian["Big"] = 1] = "Big";
328
- return Endian;
329
- })({});
330
- function fk(index, b, c, d) {
331
- if (index < 20) {
332
- return [(b & c) | (~b & d), 0x5a827999];
333
- }
334
- if (index < 40) {
335
- return [b ^ c ^ d, 0x6ed9eba1];
336
- }
337
- if (index < 60) {
338
- return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
339
- }
340
- return [b ^ c ^ d, 0xca62c1d6];
341
- }
342
- function stringToWords32(str, endian) {
343
- const size = (str.length + 3) >>> 2;
344
- const words32 = [];
345
- for (let i = 0; i < size; i++) {
346
- words32[i] = wordAt(str, i * 4, endian);
347
- }
348
- return words32;
349
- }
350
- function arrayBufferToWords32(buffer, endian) {
351
- const size = (buffer.byteLength + 3) >>> 2;
352
- const words32 = [];
353
- const view = new Uint8Array(buffer);
354
- for (let i = 0; i < size; i++) {
355
- words32[i] = wordAt(view, i * 4, endian);
356
- }
357
- return words32;
358
- }
359
- function byteAt(str, index) {
360
- if (typeof str === 'string') {
361
- return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
362
- }
363
- else {
364
- return index >= str.byteLength ? 0 : str[index] & 0xff;
365
- }
366
- }
367
- function wordAt(str, index, endian) {
368
- let word = 0;
369
- if (endian === Endian.Big) {
370
- for (let i = 0; i < 4; i++) {
371
- word += byteAt(str, index + i) << (24 - 8 * i);
372
- }
373
- }
374
- else {
375
- for (let i = 0; i < 4; i++) {
376
- word += byteAt(str, index + i) << 8 * i;
377
- }
378
- }
379
- return word;
380
- }
381
- function words32ToByteString(words32) {
382
- return words32.reduce((str, word) => str + word32ToByteString(word), '');
383
- }
384
- function word32ToByteString(word) {
385
- let str = '';
386
- for (let i = 0; i < 4; i++) {
387
- str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
388
- }
389
- return str;
390
- }
391
- function byteStringToHexString(str) {
392
- let hex = '';
393
- for (let i = 0; i < str.length; i++) {
394
- const b = byteAt(str, i);
395
- hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
396
- }
397
- return hex.toLowerCase();
398
- }
399
-
400
- /**
401
- * @license
402
- * Copyright Google LLC All Rights Reserved.
403
- *
404
- * Use of this source code is governed by an MIT-style license that can be
405
- * found in the LICENSE file at https://angular.io/license
406
- */
407
- /**
408
- * A group of assets that are cached in a `Cache` and managed by a given policy.
409
- *
410
- * Concrete classes derive from this base and specify the exact caching policy.
411
- */
412
- class AssetGroup {
413
- constructor(scope, adapter, idle, config, hashes, db, cacheNamePrefix) {
414
- this.scope = scope;
415
- this.adapter = adapter;
416
- this.idle = idle;
417
- this.config = config;
418
- this.hashes = hashes;
419
- this.db = db;
420
- /**
421
- * A deduplication cache, to make sure the SW never makes two network requests
422
- * for the same resource at once. Managed by `fetchAndCacheOnce`.
423
- */
424
- this.inFlightRequests = new Map();
425
- /**
426
- * Normalized resource URLs.
427
- */
428
- this.urls = [];
429
- /**
430
- * Regular expression patterns.
431
- */
432
- this.patterns = [];
433
- this.name = config.name;
434
- // Normalize the config's URLs to take the ServiceWorker's scope into account.
435
- this.urls = config.urls.map(url => adapter.normalizeUrl(url));
436
- // Patterns in the config are regular expressions disguised as strings. Breathe life into them.
437
- this.patterns = config.patterns.map(pattern => new RegExp(pattern));
438
- // This is the primary cache, which holds all of the cached requests for this group. If a
439
- // resource isn't in this cache, it hasn't been fetched yet.
440
- this.cache = adapter.caches.open(`${cacheNamePrefix}:${config.name}:cache`);
441
- // This is the metadata table, which holds specific information for each cached URL, such as
442
- // the timestamp of when it was added to the cache.
443
- this.metadata =
444
- this.db.open(`${cacheNamePrefix}:${config.name}:meta`, config.cacheQueryOptions);
445
- }
446
- async cacheStatus(url) {
447
- const cache = await this.cache;
448
- const meta = await this.metadata;
449
- const req = this.adapter.newRequest(url);
450
- const res = await cache.match(req, this.config.cacheQueryOptions);
451
- if (res === undefined) {
452
- return UpdateCacheStatus.NOT_CACHED;
453
- }
454
- try {
455
- const data = await meta.read(req.url);
456
- if (!data.used) {
457
- return UpdateCacheStatus.CACHED_BUT_UNUSED;
458
- }
459
- }
460
- catch (_) {
461
- // Error on the side of safety and assume cached.
462
- }
463
- return UpdateCacheStatus.CACHED;
464
- }
465
- /**
466
- * Return a list of the names of all caches used by this group.
467
- */
468
- async getCacheNames() {
469
- const [cache, metadata] = await Promise.all([
470
- this.cache,
471
- this.metadata,
472
- ]);
473
- return [cache.name, metadata.cacheName];
474
- }
475
- /**
476
- * Process a request for a given resource and return it, or return null if it's not available.
477
- */
478
- async handleFetch(req, _event) {
479
- const url = this.adapter.normalizeUrl(req.url);
480
- // Either the request matches one of the known resource URLs, one of the patterns for
481
- // dynamically matched URLs, or neither. Determine which is the case for this request in
482
- // order to decide how to handle it.
483
- if (this.urls.indexOf(url) !== -1 || this.patterns.some(pattern => pattern.test(url))) {
484
- // This URL matches a known resource. Either it's been cached already or it's missing, in
485
- // which case it needs to be loaded from the network.
486
- // Open the cache to check whether this resource is present.
487
- const cache = await this.cache;
488
- // Look for a cached response. If one exists, it can be used to resolve the fetch
489
- // operation.
490
- const cachedResponse = await cache.match(req, this.config.cacheQueryOptions);
491
- if (cachedResponse !== undefined) {
492
- // A response has already been cached (which presumably matches the hash for this
493
- // resource). Check whether it's safe to serve this resource from cache.
494
- if (this.hashes.has(url)) {
495
- // This resource has a hash, and thus is versioned by the manifest. It's safe to return
496
- // the response.
497
- return cachedResponse;
498
- }
499
- else {
500
- // This resource has no hash, and yet exists in the cache. Check how old this request is
501
- // to make sure it's still usable.
502
- if (await this.needToRevalidate(req, cachedResponse)) {
503
- this.idle.schedule(`revalidate(${cache.name}): ${req.url}`, async () => {
504
- await this.fetchAndCacheOnce(req);
505
- });
506
- }
507
- // In either case (revalidation or not), the cached response must be good.
508
- return cachedResponse;
509
- }
510
- }
511
- // No already-cached response exists, so attempt a fetch/cache operation. The original request
512
- // may specify things like credential inclusion, but for assets these are not honored in order
513
- // to avoid issues with opaque responses. The SW requests the data itself.
514
- const res = await this.fetchAndCacheOnce(this.adapter.newRequest(req.url));
515
- // If this is successful, the response needs to be cloned as it might be used to respond to
516
- // multiple fetch operations at the same time.
517
- return res.clone();
518
- }
519
- else {
520
- return null;
521
- }
522
- }
523
- /**
524
- * Some resources are cached without a hash, meaning that their expiration is controlled
525
- * by HTTP caching headers. Check whether the given request/response pair is still valid
526
- * per the caching headers.
527
- */
528
- async needToRevalidate(req, res) {
529
- // Three different strategies apply here:
530
- // 1) The request has a Cache-Control header, and thus expiration needs to be based on its age.
531
- // 2) The request has an Expires header, and expiration is based on the current timestamp.
532
- // 3) The request has no applicable caching headers, and must be revalidated.
533
- if (res.headers.has('Cache-Control')) {
534
- // Figure out if there is a max-age directive in the Cache-Control header.
535
- const cacheControl = res.headers.get('Cache-Control');
536
- const cacheDirectives = cacheControl
537
- // Directives are comma-separated within the Cache-Control header value.
538
- .split(',')
539
- // Make sure each directive doesn't have extraneous whitespace.
540
- .map(v => v.trim())
541
- // Some directives have values (like maxage and s-maxage)
542
- .map(v => v.split('='));
543
- // Lowercase all the directive names.
544
- cacheDirectives.forEach(v => v[0] = v[0].toLowerCase());
545
- // Find the max-age directive, if one exists.
546
- const maxAgeDirective = cacheDirectives.find(v => v[0] === 'max-age');
547
- const cacheAge = maxAgeDirective ? maxAgeDirective[1] : undefined;
548
- if (!cacheAge) {
549
- // No usable TTL defined. Must assume that the response is stale.
550
- return true;
551
- }
552
- try {
553
- const maxAge = 1000 * parseInt(cacheAge);
554
- // Determine the origin time of this request. If the SW has metadata on the request (which
555
- // it
556
- // should), it will have the time the request was added to the cache. If it doesn't for some
557
- // reason, the request may have a Date header which will serve the same purpose.
558
- let ts;
559
- try {
560
- // Check the metadata table. If a timestamp is there, use it.
561
- const metaTable = await this.metadata;
562
- ts = (await metaTable.read(req.url)).ts;
563
- }
564
- catch {
565
- // Otherwise, look for a Date header.
566
- const date = res.headers.get('Date');
567
- if (date === null) {
568
- // Unable to determine when this response was created. Assume that it's stale, and
569
- // revalidate it.
570
- return true;
571
- }
572
- ts = Date.parse(date);
573
- }
574
- const age = this.adapter.time - ts;
575
- return age < 0 || age > maxAge;
576
- }
577
- catch {
578
- // Assume stale.
579
- return true;
580
- }
581
- }
582
- else if (res.headers.has('Expires')) {
583
- // Determine if the expiration time has passed.
584
- const expiresStr = res.headers.get('Expires');
585
- try {
586
- // The request needs to be revalidated if the current time is later than the expiration
587
- // time, if it parses correctly.
588
- return this.adapter.time > Date.parse(expiresStr);
589
- }
590
- catch {
591
- // The expiration date failed to parse, so revalidate as a precaution.
592
- return true;
593
- }
594
- }
595
- else {
596
- // No way to evaluate staleness, so assume the response is already stale.
597
- return true;
598
- }
599
- }
600
- /**
601
- * Fetch the complete state of a cached resource, or return null if it's not found.
602
- */
603
- async fetchFromCacheOnly(url) {
604
- const cache = await this.cache;
605
- const metaTable = await this.metadata;
606
- // Lookup the response in the cache.
607
- const request = this.adapter.newRequest(url);
608
- const response = await cache.match(request, this.config.cacheQueryOptions);
609
- if (response === undefined) {
610
- // It's not found, return null.
611
- return null;
612
- }
613
- // Next, lookup the cached metadata.
614
- let metadata = undefined;
615
- try {
616
- metadata = await metaTable.read(request.url);
617
- }
618
- catch {
619
- // Do nothing, not found. This shouldn't happen, but it can be handled.
620
- }
621
- // Return both the response and any available metadata.
622
- return { response, metadata };
623
- }
624
- /**
625
- * Lookup all resources currently stored in the cache which have no associated hash.
626
- */
627
- async unhashedResources() {
628
- const cache = await this.cache;
629
- // Start with the set of all cached requests.
630
- return (await cache.keys())
631
- // Normalize their URLs.
632
- .map(request => this.adapter.normalizeUrl(request.url))
633
- // Exclude the URLs which have hashes.
634
- .filter(url => !this.hashes.has(url));
635
- }
636
- /**
637
- * Fetch the given resource from the network, and cache it if able.
638
- */
639
- async fetchAndCacheOnce(req, used = true) {
640
- // The `inFlightRequests` map holds information about which caching operations are currently
641
- // underway for known resources. If this request appears there, another "thread" is already
642
- // in the process of caching it, and this work should not be duplicated.
643
- if (this.inFlightRequests.has(req.url)) {
644
- // There is a caching operation already in progress for this request. Wait for it to
645
- // complete, and hopefully it will have yielded a useful response.
646
- return this.inFlightRequests.get(req.url);
647
- }
648
- // No other caching operation is being attempted for this resource, so it will be owned here.
649
- // Go to the network and get the correct version.
650
- const fetchOp = this.fetchFromNetwork(req);
651
- // Save this operation in `inFlightRequests` so any other "thread" attempting to cache it
652
- // will block on this chain instead of duplicating effort.
653
- this.inFlightRequests.set(req.url, fetchOp);
654
- // Make sure this attempt is cleaned up properly on failure.
655
- try {
656
- // Wait for a response. If this fails, the request will remain in `inFlightRequests`
657
- // indefinitely.
658
- const res = await fetchOp;
659
- // It's very important that only successful responses are cached. Unsuccessful responses
660
- // should never be cached as this can completely break applications.
661
- if (!res.ok) {
662
- throw new Error(`Response not Ok (fetchAndCacheOnce): request for ${req.url} returned response ${res.status} ${res.statusText}`);
663
- }
664
- try {
665
- // This response is safe to cache (as long as it's cloned). Wait until the cache operation
666
- // is complete.
667
- const cache = await this.cache;
668
- await cache.put(req, res.clone());
669
- // If the request is not hashed, update its metadata, especially the timestamp. This is
670
- // needed for future determination of whether this cached response is stale or not.
671
- if (!this.hashes.has(this.adapter.normalizeUrl(req.url))) {
672
- // Metadata is tracked for requests that are unhashed.
673
- const meta = { ts: this.adapter.time, used };
674
- const metaTable = await this.metadata;
675
- await metaTable.write(req.url, meta);
676
- }
677
- return res;
678
- }
679
- catch (err) {
680
- // Among other cases, this can happen when the user clears all data through the DevTools,
681
- // but the SW is still running and serving another tab. In that case, trying to write to the
682
- // caches throws an `Entry was not found` error.
683
- // If this happens the SW can no longer work correctly. This situation is unrecoverable.
684
- throw new SwCriticalError(`Failed to update the caches for request to '${req.url}' (fetchAndCacheOnce): ${errorToString(err)}`);
685
- }
686
- }
687
- finally {
688
- // Finally, it can be removed from `inFlightRequests`. This might result in a double-remove
689
- // if some other chain was already making this request too, but that won't hurt anything.
690
- this.inFlightRequests.delete(req.url);
691
- }
692
- }
693
- async fetchFromNetwork(req, redirectLimit = 3) {
694
- // Make a cache-busted request for the resource.
695
- const res = await this.cacheBustedFetchFromNetwork(req);
696
- // Check for redirected responses, and follow the redirects.
697
- if (res['redirected'] && !!res.url) {
698
- // If the redirect limit is exhausted, fail with an error.
699
- if (redirectLimit === 0) {
700
- throw new SwCriticalError(`Response hit redirect limit (fetchFromNetwork): request redirected too many times, next is ${res.url}`);
701
- }
702
- // Unwrap the redirect directly.
703
- return this.fetchFromNetwork(this.adapter.newRequest(res.url), redirectLimit - 1);
704
- }
705
- return res;
706
- }
707
- /**
708
- * Load a particular asset from the network, accounting for hash validation.
709
- */
710
- async cacheBustedFetchFromNetwork(req) {
711
- const url = this.adapter.normalizeUrl(req.url);
712
- // If a hash is available for this resource, then compare the fetched version with the
713
- // canonical hash. Otherwise, the network version will have to be trusted.
714
- if (this.hashes.has(url)) {
715
- // It turns out this resource does have a hash. Look it up. Unless the fetched version
716
- // matches this hash, it's invalid and the whole manifest may need to be thrown out.
717
- const canonicalHash = this.hashes.get(url);
718
- // Ideally, the resource would be requested with cache-busting to guarantee the SW gets
719
- // the freshest version. However, doing this would eliminate any chance of the response
720
- // being in the HTTP cache. Given that the browser has recently actively loaded the page,
721
- // it's likely that many of the responses the SW needs to cache are in the HTTP cache and
722
- // are fresh enough to use. In the future, this could be done by setting cacheMode to
723
- // *only* check the browser cache for a cached version of the resource, when cacheMode is
724
- // fully supported. For now, the resource is fetched directly, without cache-busting, and
725
- // if the hash test fails a cache-busted request is tried before concluding that the
726
- // resource isn't correct. This gives the benefit of acceleration via the HTTP cache
727
- // without the risk of stale data, at the expense of a duplicate request in the event of
728
- // a stale response.
729
- // Fetch the resource from the network (possibly hitting the HTTP cache).
730
- let response = await this.safeFetch(req);
731
- // Decide whether a cache-busted request is necessary. A cache-busted request is necessary
732
- // only if the request was successful but the hash of the retrieved contents does not match
733
- // the canonical hash from the manifest.
734
- let makeCacheBustedRequest = response.ok;
735
- if (makeCacheBustedRequest) {
736
- // The request was successful. A cache-busted request is only necessary if the hashes
737
- // don't match.
738
- // (Make sure to clone the response so it can be used later if it proves to be valid.)
739
- const fetchedHash = sha1Binary(await response.clone().arrayBuffer());
740
- makeCacheBustedRequest = (fetchedHash !== canonicalHash);
741
- }
742
- // Make a cache busted request to the network, if necessary.
743
- if (makeCacheBustedRequest) {
744
- // Hash failure, the version that was retrieved under the default URL did not have the
745
- // hash expected. This could be because the HTTP cache got in the way and returned stale
746
- // data, or because the version on the server really doesn't match. A cache-busting
747
- // request will differentiate these two situations.
748
- // TODO: handle case where the URL has parameters already (unlikely for assets).
749
- const cacheBustReq = this.adapter.newRequest(this.cacheBust(req.url));
750
- response = await this.safeFetch(cacheBustReq);
751
- // If the response was successful, check the contents against the canonical hash.
752
- if (response.ok) {
753
- // Hash the contents.
754
- // (Make sure to clone the response so it can be used later if it proves to be valid.)
755
- const cacheBustedHash = sha1Binary(await response.clone().arrayBuffer());
756
- // If the cache-busted version doesn't match, then the manifest is not an accurate
757
- // representation of the server's current set of files, and the SW should give up.
758
- if (canonicalHash !== cacheBustedHash) {
759
- throw new SwCriticalError(`Hash mismatch (cacheBustedFetchFromNetwork): ${req.url}: expected ${canonicalHash}, got ${cacheBustedHash} (after cache busting)`);
760
- }
761
- }
762
- }
763
- // At this point, `response` is either successful with a matching hash or is unsuccessful.
764
- // Before returning it, check whether it failed with a 404 status. This would signify an
765
- // unrecoverable state.
766
- if (!response.ok && (response.status === 404)) {
767
- throw new SwUnrecoverableStateError(`Failed to retrieve hashed resource from the server. (AssetGroup: ${this.config.name} | URL: ${url})`);
768
- }
769
- // Return the response (successful or unsuccessful).
770
- return response;
771
- }
772
- else {
773
- // This URL doesn't exist in our hash database, so it must be requested directly.
774
- return this.safeFetch(req);
775
- }
776
- }
777
- /**
778
- * Possibly update a resource, if it's expired and needs to be updated. A no-op otherwise.
779
- */
780
- async maybeUpdate(updateFrom, req, cache) {
781
- const url = this.adapter.normalizeUrl(req.url);
782
- // Check if this resource is hashed and already exists in the cache of a prior version.
783
- if (this.hashes.has(url)) {
784
- const hash = this.hashes.get(url);
785
- // Check the caches of prior versions, using the hash to ensure the correct version of
786
- // the resource is loaded.
787
- const res = await updateFrom.lookupResourceWithHash(url, hash);
788
- // If a previously cached version was available, copy it over to this cache.
789
- if (res !== null) {
790
- // Copy to this cache.
791
- await cache.put(req, res);
792
- // No need to do anything further with this resource, it's now cached properly.
793
- return true;
794
- }
795
- }
796
- // No up-to-date version of this resource could be found.
797
- return false;
798
- }
799
- /**
800
- * Construct a cache-busting URL for a given URL.
801
- */
802
- cacheBust(url) {
803
- return url + (url.indexOf('?') === -1 ? '?' : '&') + 'ngsw-cache-bust=' + Math.random();
804
- }
805
- async safeFetch(req) {
806
- try {
807
- return await this.scope.fetch(req);
808
- }
809
- catch {
810
- return this.adapter.newResponse('', {
811
- status: 504,
812
- statusText: 'Gateway Timeout',
813
- });
814
- }
815
- }
816
- }
817
- /**
818
- * An `AssetGroup` that prefetches all of its resources during initialization.
819
- */
820
- class PrefetchAssetGroup extends AssetGroup {
821
- async initializeFully(updateFrom) {
822
- // Open the cache which actually holds requests.
823
- const cache = await this.cache;
824
- // Cache all known resources serially. As this reduce proceeds, each Promise waits
825
- // on the last before starting the fetch/cache operation for the next request. Any
826
- // errors cause fall-through to the final Promise which rejects.
827
- await this.urls.reduce(async (previous, url) => {
828
- // Wait on all previous operations to complete.
829
- await previous;
830
- // Construct the Request for this url.
831
- const req = this.adapter.newRequest(url);
832
- // First, check the cache to see if there is already a copy of this resource.
833
- const alreadyCached = (await cache.match(req, this.config.cacheQueryOptions)) !== undefined;
834
- // If the resource is in the cache already, it can be skipped.
835
- if (alreadyCached) {
836
- return;
837
- }
838
- // If an update source is available.
839
- if (updateFrom !== undefined && await this.maybeUpdate(updateFrom, req, cache)) {
840
- return;
841
- }
842
- // Otherwise, go to the network and hopefully cache the response (if successful).
843
- await this.fetchAndCacheOnce(req, false);
844
- }, Promise.resolve());
845
- // Handle updating of unknown (unhashed) resources. This is only possible if there's
846
- // a source to update from.
847
- if (updateFrom !== undefined) {
848
- const metaTable = await this.metadata;
849
- // Select all of the previously cached resources. These are cached unhashed resources
850
- // from previous versions of the app, in any asset group.
851
- await (await updateFrom.previouslyCachedResources())
852
- // First, narrow down the set of resources to those which are handled by this group.
853
- // Either it's a known URL, or it matches a given pattern.
854
- .filter(url => this.urls.indexOf(url) !== -1 || this.patterns.some(pattern => pattern.test(url)))
855
- // Finally, process each resource in turn.
856
- .reduce(async (previous, url) => {
857
- await previous;
858
- const req = this.adapter.newRequest(url);
859
- // It's possible that the resource in question is already cached. If so,
860
- // continue to the next one.
861
- const alreadyCached = (await cache.match(req, this.config.cacheQueryOptions) !== undefined);
862
- if (alreadyCached) {
863
- return;
864
- }
865
- // Get the most recent old version of the resource.
866
- const res = await updateFrom.lookupResourceWithoutHash(url);
867
- if (res === null || res.metadata === undefined) {
868
- // Unexpected, but not harmful.
869
- return;
870
- }
871
- // Write it into the cache. It may already be expired, but it can still serve
872
- // traffic until it's updated (stale-while-revalidate approach).
873
- await cache.put(req, res.response);
874
- await metaTable.write(req.url, { ...res.metadata, used: false });
875
- }, Promise.resolve());
876
- }
877
- }
878
- }
879
- class LazyAssetGroup extends AssetGroup {
880
- async initializeFully(updateFrom) {
881
- // No action necessary if no update source is available - resources managed in this group
882
- // are all lazily loaded, so there's nothing to initialize.
883
- if (updateFrom === undefined) {
884
- return;
885
- }
886
- // Open the cache which actually holds requests.
887
- const cache = await this.cache;
888
- // Loop through the listed resources, caching any which are available.
889
- await this.urls.reduce(async (previous, url) => {
890
- // Wait on all previous operations to complete.
891
- await previous;
892
- // Construct the Request for this url.
893
- const req = this.adapter.newRequest(url);
894
- // First, check the cache to see if there is already a copy of this resource.
895
- const alreadyCached = (await cache.match(req, this.config.cacheQueryOptions)) !== undefined;
896
- // If the resource is in the cache already, it can be skipped.
897
- if (alreadyCached) {
898
- return;
899
- }
900
- const updated = await this.maybeUpdate(updateFrom, req, cache);
901
- if (this.config.updateMode === 'prefetch' && !updated) {
902
- // If the resource was not updated, either it was not cached before or
903
- // the previously cached version didn't match the updated hash. In that
904
- // case, prefetch update mode dictates that the resource will be updated,
905
- // except if it was not previously utilized. Check the status of the
906
- // cached resource to see.
907
- const cacheStatus = await updateFrom.recentCacheStatus(url);
908
- // If the resource is not cached, or was cached but unused, then it will be
909
- // loaded lazily.
910
- if (cacheStatus !== UpdateCacheStatus.CACHED) {
911
- return;
912
- }
913
- // Update from the network.
914
- await this.fetchAndCacheOnce(req, false);
915
- }
916
- }, Promise.resolve());
917
- }
918
- }
919
-
920
- /**
921
- * @license
922
- * Copyright Google LLC All Rights Reserved.
923
- *
924
- * Use of this source code is governed by an MIT-style license that can be
925
- * found in the LICENSE file at https://angular.io/license
926
- */
927
- /**
928
- * Manages an instance of `LruState` and moves URLs to the head of the
929
- * chain when requested.
930
- */
931
- class LruList {
932
- constructor(state) {
933
- if (state === undefined) {
934
- state = {
935
- head: null,
936
- tail: null,
937
- map: {},
938
- count: 0,
939
- };
940
- }
941
- this.state = state;
942
- }
943
- /**
944
- * The current count of URLs in the list.
945
- */
946
- get size() {
947
- return this.state.count;
948
- }
949
- /**
950
- * Remove the tail.
951
- */
952
- pop() {
953
- // If there is no tail, return null.
954
- if (this.state.tail === null) {
955
- return null;
956
- }
957
- const url = this.state.tail;
958
- this.remove(url);
959
- // This URL has been successfully evicted.
960
- return url;
961
- }
962
- remove(url) {
963
- const node = this.state.map[url];
964
- if (node === undefined) {
965
- return false;
966
- }
967
- // Special case if removing the current head.
968
- if (this.state.head === url) {
969
- // The node is the current head. Special case the removal.
970
- if (node.next === null) {
971
- // This is the only node. Reset the cache to be empty.
972
- this.state.head = null;
973
- this.state.tail = null;
974
- this.state.map = {};
975
- this.state.count = 0;
976
- return true;
977
- }
978
- // There is at least one other node. Make the next node the new head.
979
- const next = this.state.map[node.next];
980
- next.previous = null;
981
- this.state.head = next.url;
982
- node.next = null;
983
- delete this.state.map[url];
984
- this.state.count--;
985
- return true;
986
- }
987
- // The node is not the head, so it has a previous. It may or may not be the tail.
988
- // If it is not, then it has a next. First, grab the previous node.
989
- const previous = this.state.map[node.previous];
990
- // Fix the forward pointer to skip over node and go directly to node.next.
991
- previous.next = node.next;
992
- // node.next may or may not be set. If it is, fix the back pointer to skip over node.
993
- // If it's not set, then this node happened to be the tail, and the tail needs to be
994
- // updated to point to the previous node (removing the tail).
995
- if (node.next !== null) {
996
- // There is a next node, fix its back pointer to skip this node.
997
- this.state.map[node.next].previous = node.previous;
998
- }
999
- else {
1000
- // There is no next node - the accessed node must be the tail. Move the tail pointer.
1001
- this.state.tail = node.previous;
1002
- }
1003
- node.next = null;
1004
- node.previous = null;
1005
- delete this.state.map[url];
1006
- // Count the removal.
1007
- this.state.count--;
1008
- return true;
1009
- }
1010
- accessed(url) {
1011
- // When a URL is accessed, its node needs to be moved to the head of the chain.
1012
- // This is accomplished in two steps:
1013
- //
1014
- // 1) remove the node from its position within the chain.
1015
- // 2) insert the node as the new head.
1016
- //
1017
- // Sometimes, a URL is accessed which has not been seen before. In this case, step 1 can
1018
- // be skipped completely (which will grow the chain by one). Of course, if the node is
1019
- // already the head, this whole operation can be skipped.
1020
- if (this.state.head === url) {
1021
- // The URL is already in the head position, accessing it is a no-op.
1022
- return;
1023
- }
1024
- // Look up the node in the map, and construct a new entry if it's
1025
- const node = this.state.map[url] || { url, next: null, previous: null };
1026
- // Step 1: remove the node from its position within the chain, if it is in the chain.
1027
- if (this.state.map[url] !== undefined) {
1028
- this.remove(url);
1029
- }
1030
- // Step 2: insert the node at the head of the chain.
1031
- // First, check if there's an existing head node. If there is, it has previous: null.
1032
- // Its previous pointer should be set to the node we're inserting.
1033
- if (this.state.head !== null) {
1034
- this.state.map[this.state.head].previous = url;
1035
- }
1036
- // The next pointer of the node being inserted gets set to the old head, before the head
1037
- // pointer is updated to this node.
1038
- node.next = this.state.head;
1039
- // The new head is the new node.
1040
- this.state.head = url;
1041
- // If there is no tail, then this is the first node, and is both the head and the tail.
1042
- if (this.state.tail === null) {
1043
- this.state.tail = url;
1044
- }
1045
- // Set the node in the map of nodes (if the URL has been seen before, this is a no-op)
1046
- // and count the insertion.
1047
- this.state.map[url] = node;
1048
- this.state.count++;
1049
- }
1050
- }
1051
- /**
1052
- * A group of cached resources determined by a set of URL patterns which follow a LRU policy
1053
- * for caching.
1054
- */
1055
- class DataGroup {
1056
- constructor(scope, adapter, config, db, debugHandler, cacheNamePrefix) {
1057
- this.scope = scope;
1058
- this.adapter = adapter;
1059
- this.config = config;
1060
- this.db = db;
1061
- this.debugHandler = debugHandler;
1062
- /**
1063
- * Tracks the LRU state of resources in this cache.
1064
- */
1065
- this._lru = null;
1066
- this.patterns = config.patterns.map(pattern => new RegExp(pattern));
1067
- this.cache = adapter.caches.open(`${cacheNamePrefix}:${config.name}:cache`);
1068
- this.lruTable = this.db.open(`${cacheNamePrefix}:${config.name}:lru`, config.cacheQueryOptions);
1069
- this.ageTable = this.db.open(`${cacheNamePrefix}:${config.name}:age`, config.cacheQueryOptions);
1070
- }
1071
- /**
1072
- * Lazily initialize/load the LRU chain.
1073
- */
1074
- async lru() {
1075
- if (this._lru === null) {
1076
- const table = await this.lruTable;
1077
- try {
1078
- this._lru = new LruList(await table.read('lru'));
1079
- }
1080
- catch {
1081
- this._lru = new LruList();
1082
- }
1083
- }
1084
- return this._lru;
1085
- }
1086
- /**
1087
- * Sync the LRU chain to non-volatile storage.
1088
- */
1089
- async syncLru() {
1090
- if (this._lru === null) {
1091
- return;
1092
- }
1093
- const table = await this.lruTable;
1094
- try {
1095
- return table.write('lru', this._lru.state);
1096
- }
1097
- catch (err) {
1098
- // Writing lru cache table failed. This could be a result of a full storage.
1099
- // Continue serving clients as usual.
1100
- this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`);
1101
- // TODO: Better detect/handle full storage; e.g. using
1102
- // [navigator.storage](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorStorage/storage).
1103
- }
1104
- }
1105
- /**
1106
- * Process a fetch event and return a `Response` if the resource is covered by this group,
1107
- * or `null` otherwise.
1108
- */
1109
- async handleFetch(req, event) {
1110
- // Do nothing
1111
- if (!this.patterns.some(pattern => pattern.test(req.url))) {
1112
- return null;
1113
- }
1114
- // Lazily initialize the LRU cache.
1115
- const lru = await this.lru();
1116
- // The URL matches this cache. First, check whether this is a mutating request or not.
1117
- switch (req.method) {
1118
- case 'OPTIONS':
1119
- // Don't try to cache this - it's non-mutating, but is part of a mutating request.
1120
- // Most likely SWs don't even see this, but this guard is here just in case.
1121
- return null;
1122
- case 'GET':
1123
- case 'HEAD':
1124
- // Handle the request with whatever strategy was selected.
1125
- switch (this.config.strategy) {
1126
- case 'freshness':
1127
- return this.handleFetchWithFreshness(req, event, lru);
1128
- case 'performance':
1129
- return this.handleFetchWithPerformance(req, event, lru);
1130
- default:
1131
- throw new Error(`Unknown strategy: ${this.config.strategy}`);
1132
- }
1133
- default:
1134
- // This was a mutating request. Assume the cache for this URL is no longer valid.
1135
- const wasCached = lru.remove(req.url);
1136
- // If there was a cached entry, remove it.
1137
- if (wasCached) {
1138
- await this.clearCacheForUrl(req.url);
1139
- }
1140
- // Sync the LRU chain to non-volatile storage.
1141
- await this.syncLru();
1142
- // Finally, fall back on the network.
1143
- return this.safeFetch(req);
1144
- }
1145
- }
1146
- async handleFetchWithPerformance(req, event, lru) {
1147
- let res = null;
1148
- // Check the cache first. If the resource exists there (and is not expired), the cached
1149
- // version can be used.
1150
- const fromCache = await this.loadFromCache(req, lru);
1151
- if (fromCache !== null) {
1152
- res = fromCache.res;
1153
- // Check the age of the resource.
1154
- if (this.config.refreshAheadMs !== undefined && fromCache.age >= this.config.refreshAheadMs) {
1155
- event.waitUntil(this.safeCacheResponse(req, this.safeFetch(req), lru));
1156
- }
1157
- }
1158
- if (res !== null) {
1159
- return res;
1160
- }
1161
- // No match from the cache. Go to the network. Note that this is not an 'await'
1162
- // call, networkFetch is the actual Promise. This is due to timeout handling.
1163
- const [timeoutFetch, networkFetch] = this.networkFetchWithTimeout(req);
1164
- res = await timeoutFetch;
1165
- // Since fetch() will always return a response, undefined indicates a timeout.
1166
- if (res === undefined) {
1167
- // The request timed out. Return a Gateway Timeout error.
1168
- res = this.adapter.newResponse(null, { status: 504, statusText: 'Gateway Timeout' });
1169
- // Cache the network response eventually.
1170
- event.waitUntil(this.safeCacheResponse(req, networkFetch, lru));
1171
- }
1172
- else {
1173
- // The request completed in time, so cache it inline with the response flow.
1174
- await this.safeCacheResponse(req, res, lru);
1175
- }
1176
- return res;
1177
- }
1178
- async handleFetchWithFreshness(req, event, lru) {
1179
- // Start with a network fetch.
1180
- const [timeoutFetch, networkFetch] = this.networkFetchWithTimeout(req);
1181
- let res;
1182
- // If that fetch errors, treat it as a timed out request.
1183
- try {
1184
- res = await timeoutFetch;
1185
- }
1186
- catch {
1187
- res = undefined;
1188
- }
1189
- // If the network fetch times out or errors, fall back on the cache.
1190
- if (res === undefined) {
1191
- event.waitUntil(this.safeCacheResponse(req, networkFetch, lru, true));
1192
- // Ignore the age, the network response will be cached anyway due to the
1193
- // behavior of freshness.
1194
- const fromCache = await this.loadFromCache(req, lru);
1195
- res = (fromCache !== null) ? fromCache.res : null;
1196
- }
1197
- else {
1198
- await this.safeCacheResponse(req, res, lru, true);
1199
- }
1200
- // Either the network fetch didn't time out, or the cache yielded a usable response.
1201
- // In either case, use it.
1202
- if (res !== null) {
1203
- return res;
1204
- }
1205
- // No response in the cache. No choice but to fall back on the full network fetch.
1206
- return networkFetch;
1207
- }
1208
- networkFetchWithTimeout(req) {
1209
- // If there is a timeout configured, race a timeout Promise with the network fetch.
1210
- // Otherwise, just fetch from the network directly.
1211
- if (this.config.timeoutMs !== undefined) {
1212
- const networkFetch = this.scope.fetch(req);
1213
- const safeNetworkFetch = (async () => {
1214
- try {
1215
- return await networkFetch;
1216
- }
1217
- catch {
1218
- return this.adapter.newResponse(null, {
1219
- status: 504,
1220
- statusText: 'Gateway Timeout',
1221
- });
1222
- }
1223
- })();
1224
- const networkFetchUndefinedError = (async () => {
1225
- try {
1226
- return await networkFetch;
1227
- }
1228
- catch {
1229
- return undefined;
1230
- }
1231
- })();
1232
- // Construct a Promise<undefined> for the timeout.
1233
- const timeout = this.adapter.timeout(this.config.timeoutMs);
1234
- // Race that with the network fetch. This will either be a Response, or `undefined`
1235
- // in the event that the request errored or timed out.
1236
- return [Promise.race([networkFetchUndefinedError, timeout]), safeNetworkFetch];
1237
- }
1238
- else {
1239
- const networkFetch = this.safeFetch(req);
1240
- // Do a plain fetch.
1241
- return [networkFetch, networkFetch];
1242
- }
1243
- }
1244
- async safeCacheResponse(req, resOrPromise, lru, okToCacheOpaque) {
1245
- try {
1246
- const res = await resOrPromise;
1247
- try {
1248
- await this.cacheResponse(req, res, lru, okToCacheOpaque);
1249
- }
1250
- catch (err) {
1251
- // Saving the API response failed. This could be a result of a full storage.
1252
- // Since this data is cached lazily and temporarily, continue serving clients as usual.
1253
- this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).safeCacheResponse(${req.url}, status: ${res.status})`);
1254
- // TODO: Better detect/handle full storage; e.g. using
1255
- // [navigator.storage](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorStorage/storage).
1256
- }
1257
- }
1258
- catch {
1259
- // Request failed
1260
- // TODO: Handle this error somehow?
1261
- }
1262
- }
1263
- async loadFromCache(req, lru) {
1264
- // Look for a response in the cache. If one exists, return it.
1265
- const cache = await this.cache;
1266
- let res = await cache.match(req, this.config.cacheQueryOptions);
1267
- if (res !== undefined) {
1268
- // A response was found in the cache, but its age is not yet known. Look it up.
1269
- try {
1270
- const ageTable = await this.ageTable;
1271
- const age = this.adapter.time - (await ageTable.read(req.url)).age;
1272
- // If the response is young enough, use it.
1273
- if (age <= this.config.maxAge) {
1274
- // Successful match from the cache. Use the response, after marking it as having
1275
- // been accessed.
1276
- lru.accessed(req.url);
1277
- return { res, age };
1278
- }
1279
- // Otherwise, or if there was an error, assume the response is expired, and evict it.
1280
- }
1281
- catch {
1282
- // Some error getting the age for the response. Assume it's expired.
1283
- }
1284
- lru.remove(req.url);
1285
- await this.clearCacheForUrl(req.url);
1286
- // TODO: avoid duplicate in event of network timeout, maybe.
1287
- await this.syncLru();
1288
- }
1289
- return null;
1290
- }
1291
- /**
1292
- * Operation for caching the response from the server. This has to happen all
1293
- * at once, so that the cache and LRU tracking remain in sync. If the network request
1294
- * completes before the timeout, this logic will be run inline with the response flow.
1295
- * If the request times out on the server, an error will be returned but the real network
1296
- * request will still be running in the background, to be cached when it completes.
1297
- */
1298
- async cacheResponse(req, res, lru, okToCacheOpaque = false) {
1299
- // Only cache successful responses.
1300
- if (!(res.ok || (okToCacheOpaque && res.type === 'opaque'))) {
1301
- return;
1302
- }
1303
- // If caching this response would make the cache exceed its maximum size, evict something
1304
- // first.
1305
- if (lru.size >= this.config.maxSize) {
1306
- // The cache is too big, evict something.
1307
- const evictedUrl = lru.pop();
1308
- if (evictedUrl !== null) {
1309
- await this.clearCacheForUrl(evictedUrl);
1310
- }
1311
- }
1312
- // TODO: evaluate for possible race conditions during flaky network periods.
1313
- // Mark this resource as having been accessed recently. This ensures it won't be evicted
1314
- // until enough other resources are requested that it falls off the end of the LRU chain.
1315
- lru.accessed(req.url);
1316
- // Store the response in the cache (cloning because the browser will consume
1317
- // the body during the caching operation).
1318
- await (await this.cache).put(req, res.clone());
1319
- // Store the age of the cache.
1320
- const ageTable = await this.ageTable;
1321
- await ageTable.write(req.url, { age: this.adapter.time });
1322
- // Sync the LRU chain to non-volatile storage.
1323
- await this.syncLru();
1324
- }
1325
- /**
1326
- * Delete all of the saved state which this group uses to track resources.
1327
- */
1328
- async cleanup() {
1329
- // Remove both the cache and the database entries which track LRU stats.
1330
- await Promise.all([
1331
- this.cache.then(cache => this.adapter.caches.delete(cache.name)),
1332
- this.ageTable.then(table => this.db.delete(table.name)),
1333
- this.lruTable.then(table => this.db.delete(table.name)),
1334
- ]);
1335
- }
1336
- /**
1337
- * Return a list of the names of all caches used by this group.
1338
- */
1339
- async getCacheNames() {
1340
- const [cache, ageTable, lruTable] = await Promise.all([
1341
- this.cache,
1342
- this.ageTable,
1343
- this.lruTable,
1344
- ]);
1345
- return [cache.name, ageTable.cacheName, lruTable.cacheName];
1346
- }
1347
- /**
1348
- * Clear the state of the cache for a particular resource.
1349
- *
1350
- * This doesn't remove the resource from the LRU table, that is assumed to have
1351
- * been done already. This clears the GET and HEAD versions of the request from
1352
- * the cache itself, as well as the metadata stored in the age table.
1353
- */
1354
- async clearCacheForUrl(url) {
1355
- const [cache, ageTable] = await Promise.all([this.cache, this.ageTable]);
1356
- await Promise.all([
1357
- cache.delete(this.adapter.newRequest(url, { method: 'GET' }), this.config.cacheQueryOptions),
1358
- cache.delete(this.adapter.newRequest(url, { method: 'HEAD' }), this.config.cacheQueryOptions),
1359
- ageTable.delete(url),
1360
- ]);
1361
- }
1362
- async safeFetch(req) {
1363
- try {
1364
- return this.scope.fetch(req);
1365
- }
1366
- catch {
1367
- return this.adapter.newResponse(null, {
1368
- status: 504,
1369
- statusText: 'Gateway Timeout',
1370
- });
1371
- }
1372
- }
1373
- }
1374
-
1375
- /**
1376
- * @license
1377
- * Copyright Google LLC All Rights Reserved.
1378
- *
1379
- * Use of this source code is governed by an MIT-style license that can be
1380
- * found in the LICENSE file at https://angular.io/license
1381
- */
1382
- const BACKWARDS_COMPATIBILITY_NAVIGATION_URLS = [
1383
- { positive: true, regex: '^/.*$' },
1384
- { positive: false, regex: '^/.*\\.[^/]*$' },
1385
- { positive: false, regex: '^/.*__' },
1386
- ];
1387
- /**
1388
- * A specific version of the application, identified by a unique manifest
1389
- * as determined by its hash.
1390
- *
1391
- * Each `AppVersion` can be thought of as a published version of the app
1392
- * that can be installed as an update to any previously installed versions.
1393
- */
1394
- class AppVersion {
1395
- constructor(scope, adapter, database, idle, debugHandler, manifest, manifestHash) {
1396
- this.scope = scope;
1397
- this.adapter = adapter;
1398
- this.database = database;
1399
- this.debugHandler = debugHandler;
1400
- this.manifest = manifest;
1401
- this.manifestHash = manifestHash;
1402
- /**
1403
- * A Map of absolute URL paths (`/foo.txt`) to the known hash of their contents (if available).
1404
- */
1405
- this.hashTable = new Map();
1406
- /**
1407
- * The normalized URL to the file that serves as the index page to satisfy navigation requests.
1408
- * Usually this is `/index.html`.
1409
- */
1410
- this.indexUrl = this.adapter.normalizeUrl(this.manifest.index);
1411
- /**
1412
- * Tracks whether the manifest has encountered any inconsistencies.
1413
- */
1414
- this._okay = true;
1415
- // The hashTable within the manifest is an Object - convert it to a Map for easier lookups.
1416
- Object.keys(manifest.hashTable).forEach(url => {
1417
- this.hashTable.set(adapter.normalizeUrl(url), manifest.hashTable[url]);
1418
- });
1419
- // Process each `AssetGroup` declared in the manifest. Each declared group gets an `AssetGroup`
1420
- // instance created for it, of a type that depends on the configuration mode.
1421
- const assetCacheNamePrefix = `${manifestHash}:assets`;
1422
- this.assetGroups = (manifest.assetGroups || []).map(config => {
1423
- // Check the caching mode, which determines when resources will be fetched/updated.
1424
- switch (config.installMode) {
1425
- case 'prefetch':
1426
- return new PrefetchAssetGroup(scope, adapter, idle, config, this.hashTable, database, assetCacheNamePrefix);
1427
- case 'lazy':
1428
- return new LazyAssetGroup(scope, adapter, idle, config, this.hashTable, database, assetCacheNamePrefix);
1429
- }
1430
- });
1431
- // Process each `DataGroup` declared in the manifest.
1432
- this.dataGroups =
1433
- (manifest.dataGroups || [])
1434
- .map(config => new DataGroup(scope, adapter, config, database, debugHandler, `${config.version}:data`));
1435
- // This keeps backwards compatibility with app versions without navigation urls.
1436
- // Fix: https://github.com/angular/angular/issues/27209
1437
- manifest.navigationUrls = manifest.navigationUrls || BACKWARDS_COMPATIBILITY_NAVIGATION_URLS;
1438
- // Create `include`/`exclude` RegExps for the `navigationUrls` declared in the manifest.
1439
- const includeUrls = manifest.navigationUrls.filter(spec => spec.positive);
1440
- const excludeUrls = manifest.navigationUrls.filter(spec => !spec.positive);
1441
- this.navigationUrls = {
1442
- include: includeUrls.map(spec => new RegExp(spec.regex)),
1443
- exclude: excludeUrls.map(spec => new RegExp(spec.regex)),
1444
- };
1445
- }
1446
- get okay() {
1447
- return this._okay;
1448
- }
1449
- /**
1450
- * Fully initialize this version of the application. If this Promise resolves successfully, all
1451
- * required
1452
- * data has been safely downloaded.
1453
- */
1454
- async initializeFully(updateFrom) {
1455
- try {
1456
- // Fully initialize each asset group, in series. Starts with an empty Promise,
1457
- // and waits for the previous groups to have been initialized before initializing
1458
- // the next one in turn.
1459
- await this.assetGroups.reduce(async (previous, group) => {
1460
- // Wait for the previous groups to complete initialization. If there is a
1461
- // failure, this will throw, and each subsequent group will throw, until the
1462
- // whole sequence fails.
1463
- await previous;
1464
- // Initialize this group.
1465
- return group.initializeFully(updateFrom);
1466
- }, Promise.resolve());
1467
- }
1468
- catch (err) {
1469
- this._okay = false;
1470
- throw err;
1471
- }
1472
- }
1473
- async handleFetch(req, event) {
1474
- // Check the request against each `AssetGroup` in sequence. If an `AssetGroup` can't handle the
1475
- // request,
1476
- // it will return `null`. Thus, the first non-null response is the SW's answer to the request.
1477
- // So reduce
1478
- // the group list, keeping track of a possible response. If there is one, it gets passed
1479
- // through, and if
1480
- // not the next group is consulted to produce a candidate response.
1481
- const asset = await this.assetGroups.reduce(async (potentialResponse, group) => {
1482
- // Wait on the previous potential response. If it's not null, it should just be passed
1483
- // through.
1484
- const resp = await potentialResponse;
1485
- if (resp !== null) {
1486
- return resp;
1487
- }
1488
- // No response has been found yet. Maybe this group will have one.
1489
- return group.handleFetch(req, event);
1490
- }, Promise.resolve(null));
1491
- // The result of the above is the asset response, if there is any, or null otherwise. Return the
1492
- // asset
1493
- // response if there was one. If not, check with the data caching groups.
1494
- if (asset !== null) {
1495
- return asset;
1496
- }
1497
- // Perform the same reduction operation as above, but this time processing
1498
- // the data caching groups.
1499
- const data = await this.dataGroups.reduce(async (potentialResponse, group) => {
1500
- const resp = await potentialResponse;
1501
- if (resp !== null) {
1502
- return resp;
1503
- }
1504
- return group.handleFetch(req, event);
1505
- }, Promise.resolve(null));
1506
- // If the data caching group returned a response, go with it.
1507
- if (data !== null) {
1508
- return data;
1509
- }
1510
- // Next, check if this is a navigation request for a route. Detect circular
1511
- // navigations by checking if the request URL is the same as the index URL.
1512
- if (this.adapter.normalizeUrl(req.url) !== this.indexUrl && this.isNavigationRequest(req)) {
1513
- if (this.manifest.navigationRequestStrategy === 'freshness') {
1514
- // For navigation requests the freshness was configured. The request will always go trough
1515
- // the network and fallback to default `handleFetch` behavior in case of failure.
1516
- try {
1517
- return await this.scope.fetch(req);
1518
- }
1519
- catch {
1520
- // Navigation request failed - application is likely offline.
1521
- // Proceed forward to the default `handleFetch` behavior, where
1522
- // `indexUrl` will be requested and it should be available in the cache.
1523
- }
1524
- }
1525
- // This was a navigation request. Re-enter `handleFetch` with a request for
1526
- // the URL.
1527
- return this.handleFetch(this.adapter.newRequest(this.indexUrl), event);
1528
- }
1529
- return null;
1530
- }
1531
- /**
1532
- * Determine whether the request is a navigation request.
1533
- * Takes into account: Request mode, `Accept` header, `navigationUrls` patterns.
1534
- */
1535
- isNavigationRequest(req) {
1536
- if (req.mode !== 'navigate') {
1537
- return false;
1538
- }
1539
- if (!this.acceptsTextHtml(req)) {
1540
- return false;
1541
- }
1542
- const urlPrefix = this.scope.registration.scope.replace(/\/$/, '');
1543
- const url = req.url.startsWith(urlPrefix) ? req.url.substr(urlPrefix.length) : req.url;
1544
- const urlWithoutQueryOrHash = url.replace(/[?#].*$/, '');
1545
- return this.navigationUrls.include.some(regex => regex.test(urlWithoutQueryOrHash)) &&
1546
- !this.navigationUrls.exclude.some(regex => regex.test(urlWithoutQueryOrHash));
1547
- }
1548
- /**
1549
- * Check this version for a given resource with a particular hash.
1550
- */
1551
- async lookupResourceWithHash(url, hash) {
1552
- // Verify that this version has the requested resource cached. If not,
1553
- // there's no point in trying.
1554
- if (!this.hashTable.has(url)) {
1555
- return null;
1556
- }
1557
- // Next, check whether the resource has the correct hash. If not, any cached
1558
- // response isn't usable.
1559
- if (this.hashTable.get(url) !== hash) {
1560
- return null;
1561
- }
1562
- const cacheState = await this.lookupResourceWithoutHash(url);
1563
- return cacheState && cacheState.response;
1564
- }
1565
- /**
1566
- * Check this version for a given resource regardless of its hash.
1567
- */
1568
- lookupResourceWithoutHash(url) {
1569
- // Limit the search to asset groups, and only scan the cache, don't
1570
- // load resources from the network.
1571
- return this.assetGroups.reduce(async (potentialResponse, group) => {
1572
- const resp = await potentialResponse;
1573
- if (resp !== null) {
1574
- return resp;
1575
- }
1576
- // fetchFromCacheOnly() avoids any network fetches, and returns the
1577
- // full set of cache data, not just the Response.
1578
- return group.fetchFromCacheOnly(url);
1579
- }, Promise.resolve(null));
1580
- }
1581
- /**
1582
- * List all unhashed resources from all asset groups.
1583
- */
1584
- previouslyCachedResources() {
1585
- return this.assetGroups.reduce(async (resources, group) => (await resources).concat(await group.unhashedResources()), Promise.resolve([]));
1586
- }
1587
- async recentCacheStatus(url) {
1588
- return this.assetGroups.reduce(async (current, group) => {
1589
- const status = await current;
1590
- if (status === UpdateCacheStatus.CACHED) {
1591
- return status;
1592
- }
1593
- const groupStatus = await group.cacheStatus(url);
1594
- if (groupStatus === UpdateCacheStatus.NOT_CACHED) {
1595
- return status;
1596
- }
1597
- return groupStatus;
1598
- }, Promise.resolve(UpdateCacheStatus.NOT_CACHED));
1599
- }
1600
- /**
1601
- * Return a list of the names of all caches used by this version.
1602
- */
1603
- async getCacheNames() {
1604
- const allGroupCacheNames = await Promise.all([
1605
- ...this.assetGroups.map(group => group.getCacheNames()),
1606
- ...this.dataGroups.map(group => group.getCacheNames()),
1607
- ]);
1608
- return [].concat(...allGroupCacheNames);
1609
- }
1610
- /**
1611
- * Get the opaque application data which was provided with the manifest.
1612
- */
1613
- get appData() {
1614
- return this.manifest.appData || null;
1615
- }
1616
- /**
1617
- * Check whether a request accepts `text/html` (based on the `Accept` header).
1618
- */
1619
- acceptsTextHtml(req) {
1620
- const accept = req.headers.get('Accept');
1621
- if (accept === null) {
1622
- return false;
1623
- }
1624
- const values = accept.split(',');
1625
- return values.some(value => value.trim().toLowerCase() === 'text/html');
1626
- }
1627
- }
1628
-
1629
- /**
1630
- * @license
1631
- * Copyright Google LLC All Rights Reserved.
1632
- *
1633
- * Use of this source code is governed by an MIT-style license that can be
1634
- * found in the LICENSE file at https://angular.io/license
1635
- */
1636
- const SW_VERSION = '13.0.2';
1637
- const DEBUG_LOG_BUFFER_SIZE = 100;
1638
- class DebugHandler {
1639
- constructor(driver, adapter) {
1640
- this.driver = driver;
1641
- this.adapter = adapter;
1642
- // There are two debug log message arrays. debugLogA records new debugging messages.
1643
- // Once it reaches DEBUG_LOG_BUFFER_SIZE, the array is moved to debugLogB and a new
1644
- // array is assigned to debugLogA. This ensures that insertion to the debug log is
1645
- // always O(1) no matter the number of logged messages, and that the total number
1646
- // of messages in the log never exceeds 2 * DEBUG_LOG_BUFFER_SIZE.
1647
- this.debugLogA = [];
1648
- this.debugLogB = [];
1649
- }
1650
- async handleFetch(req) {
1651
- const [state, versions, idle] = await Promise.all([
1652
- this.driver.debugState(),
1653
- this.driver.debugVersions(),
1654
- this.driver.debugIdleState(),
1655
- ]);
1656
- const msgState = `NGSW Debug Info:
1657
-
1658
- Driver version: ${SW_VERSION}
1659
- Driver state: ${state.state} (${state.why})
1660
- Latest manifest hash: ${state.latestHash || 'none'}
1661
- Last update check: ${this.since(state.lastUpdateCheck)}`;
1662
- const msgVersions = versions
1663
- .map(version => `=== Version ${version.hash} ===
1664
-
1665
- Clients: ${version.clients.join(', ')}`)
1666
- .join('\n\n');
1667
- const msgIdle = `=== Idle Task Queue ===
1668
- Last update tick: ${this.since(idle.lastTrigger)}
1669
- Last update run: ${this.since(idle.lastRun)}
1670
- Task queue:
1671
- ${idle.queue.map(v => ' * ' + v).join('\n')}
1672
-
1673
- Debug log:
1674
- ${this.formatDebugLog(this.debugLogB)}
1675
- ${this.formatDebugLog(this.debugLogA)}
1676
- `;
1677
- return this.adapter.newResponse(`${msgState}
1678
-
1679
- ${msgVersions}
1680
-
1681
- ${msgIdle}`, { headers: this.adapter.newHeaders({ 'Content-Type': 'text/plain' }) });
1682
- }
1683
- since(time) {
1684
- if (time === null) {
1685
- return 'never';
1686
- }
1687
- let age = this.adapter.time - time;
1688
- const days = Math.floor(age / 86400000);
1689
- age = age % 86400000;
1690
- const hours = Math.floor(age / 3600000);
1691
- age = age % 3600000;
1692
- const minutes = Math.floor(age / 60000);
1693
- age = age % 60000;
1694
- const seconds = Math.floor(age / 1000);
1695
- const millis = age % 1000;
1696
- return '' + (days > 0 ? `${days}d` : '') + (hours > 0 ? `${hours}h` : '') +
1697
- (minutes > 0 ? `${minutes}m` : '') + (seconds > 0 ? `${seconds}s` : '') +
1698
- (millis > 0 ? `${millis}u` : '');
1699
- }
1700
- log(value, context = '') {
1701
- // Rotate the buffers if debugLogA has grown too large.
1702
- if (this.debugLogA.length === DEBUG_LOG_BUFFER_SIZE) {
1703
- this.debugLogB = this.debugLogA;
1704
- this.debugLogA = [];
1705
- }
1706
- // Convert errors to string for logging.
1707
- if (typeof value !== 'string') {
1708
- value = this.errorToString(value);
1709
- }
1710
- // Log the message.
1711
- this.debugLogA.push({ value, time: this.adapter.time, context });
1712
- }
1713
- errorToString(err) {
1714
- return `${err.name}(${err.message}, ${err.stack})`;
1715
- }
1716
- formatDebugLog(log) {
1717
- return log.map(entry => `[${this.since(entry.time)}] ${entry.value} ${entry.context}`)
1718
- .join('\n');
1719
- }
1720
- }
1721
-
1722
- /**
1723
- * @license
1724
- * Copyright Google LLC All Rights Reserved.
1725
- *
1726
- * Use of this source code is governed by an MIT-style license that can be
1727
- * found in the LICENSE file at https://angular.io/license
1728
- */
1729
- class IdleScheduler {
1730
- constructor(adapter, delay, maxDelay, debug) {
1731
- this.adapter = adapter;
1732
- this.delay = delay;
1733
- this.maxDelay = maxDelay;
1734
- this.debug = debug;
1735
- this.queue = [];
1736
- this.scheduled = null;
1737
- this.empty = Promise.resolve();
1738
- this.emptyResolve = null;
1739
- this.lastTrigger = null;
1740
- this.lastRun = null;
1741
- this.oldestScheduledAt = null;
1742
- }
1743
- async trigger() {
1744
- this.lastTrigger = this.adapter.time;
1745
- if (this.queue.length === 0) {
1746
- return;
1747
- }
1748
- if (this.scheduled !== null) {
1749
- this.scheduled.cancel = true;
1750
- }
1751
- const scheduled = {
1752
- cancel: false,
1753
- };
1754
- this.scheduled = scheduled;
1755
- // Ensure that no task remains pending for longer than `this.maxDelay` ms.
1756
- const now = this.adapter.time;
1757
- const maxDelay = Math.max(0, (this.oldestScheduledAt ?? now) + this.maxDelay - now);
1758
- const delay = Math.min(maxDelay, this.delay);
1759
- await this.adapter.timeout(delay);
1760
- if (scheduled.cancel) {
1761
- return;
1762
- }
1763
- this.scheduled = null;
1764
- await this.execute();
1765
- }
1766
- async execute() {
1767
- this.lastRun = this.adapter.time;
1768
- while (this.queue.length > 0) {
1769
- const queue = this.queue;
1770
- this.queue = [];
1771
- await queue.reduce(async (previous, task) => {
1772
- await previous;
1773
- try {
1774
- await task.run();
1775
- }
1776
- catch (err) {
1777
- this.debug.log(err, `while running idle task ${task.desc}`);
1778
- }
1779
- }, Promise.resolve());
1780
- }
1781
- if (this.emptyResolve !== null) {
1782
- this.emptyResolve();
1783
- this.emptyResolve = null;
1784
- }
1785
- this.empty = Promise.resolve();
1786
- this.oldestScheduledAt = null;
1787
- }
1788
- schedule(desc, run) {
1789
- this.queue.push({ desc, run });
1790
- if (this.emptyResolve === null) {
1791
- this.empty = new Promise(resolve => {
1792
- this.emptyResolve = resolve;
1793
- });
1794
- }
1795
- if (this.oldestScheduledAt === null) {
1796
- this.oldestScheduledAt = this.adapter.time;
1797
- }
1798
- }
1799
- get size() {
1800
- return this.queue.length;
1801
- }
1802
- get taskDescriptions() {
1803
- return this.queue.map(task => task.desc);
1804
- }
1805
- }
1806
-
1807
- /**
1808
- * @license
1809
- * Copyright Google LLC All Rights Reserved.
1810
- *
1811
- * Use of this source code is governed by an MIT-style license that can be
1812
- * found in the LICENSE file at https://angular.io/license
1813
- */
1814
- function hashManifest(manifest) {
1815
- return sha1(JSON.stringify(manifest));
1816
- }
1817
-
1818
- /**
1819
- * @license
1820
- * Copyright Google LLC All Rights Reserved.
1821
- *
1822
- * Use of this source code is governed by an MIT-style license that can be
1823
- * found in the LICENSE file at https://angular.io/license
1824
- */
1825
- function isMsgCheckForUpdates(msg) {
1826
- return msg.action === 'CHECK_FOR_UPDATES';
1827
- }
1828
- function isMsgActivateUpdate(msg) {
1829
- return msg.action === 'ACTIVATE_UPDATE';
1830
- }
1831
-
1832
- /**
1833
- * @license
1834
- * Copyright Google LLC All Rights Reserved.
1835
- *
1836
- * Use of this source code is governed by an MIT-style license that can be
1837
- * found in the LICENSE file at https://angular.io/license
1838
- */
1839
- const IDLE_DELAY = 5000;
1840
- const MAX_IDLE_DELAY = 30000;
1841
- const SUPPORTED_CONFIG_VERSION = 1;
1842
- const NOTIFICATION_OPTION_NAMES = [
1843
- 'actions', 'badge', 'body', 'data', 'dir', 'icon', 'image', 'lang', 'renotify',
1844
- 'requireInteraction', 'silent', 'tag', 'timestamp', 'title', 'vibrate'
1845
- ];
1846
- var DriverReadyState = /*@__PURE__*/ (function (DriverReadyState) {
1847
- // The SW is operating in a normal mode, responding to all traffic.
1848
- DriverReadyState[DriverReadyState["NORMAL"] = 0] = "NORMAL";
1849
- // The SW does not have a clean installation of the latest version of the app, but older
1850
- // cached versions are safe to use so long as they don't try to fetch new dependencies.
1851
- // This is a degraded state.
1852
- DriverReadyState[DriverReadyState["EXISTING_CLIENTS_ONLY"] = 1] = "EXISTING_CLIENTS_ONLY";
1853
- // The SW has decided that caching is completely unreliable, and is forgoing request
1854
- // handling until the next restart.
1855
- DriverReadyState[DriverReadyState["SAFE_MODE"] = 2] = "SAFE_MODE";
1856
- return DriverReadyState;
1857
- })({});
1858
- class Driver {
1859
- constructor(scope, adapter, db) {
1860
- // Set up all the event handlers that the SW needs.
1861
- this.scope = scope;
1862
- this.adapter = adapter;
1863
- this.db = db;
1864
- /**
1865
- * Tracks the current readiness condition under which the SW is operating. This controls
1866
- * whether the SW attempts to respond to some or all requests.
1867
- */
1868
- this.state = DriverReadyState.NORMAL;
1869
- this.stateMessage = '(nominal)';
1870
- /**
1871
- * Tracks whether the SW is in an initialized state or not. Before initialization,
1872
- * it's not legal to respond to requests.
1873
- */
1874
- this.initialized = null;
1875
- /**
1876
- * Maps client IDs to the manifest hash of the application version being used to serve
1877
- * them. If a client ID is not present here, it has not yet been assigned a version.
1878
- *
1879
- * If a ManifestHash appears here, it is also present in the `versions` map below.
1880
- */
1881
- this.clientVersionMap = new Map();
1882
- /**
1883
- * Maps manifest hashes to instances of `AppVersion` for those manifests.
1884
- */
1885
- this.versions = new Map();
1886
- /**
1887
- * The latest version fetched from the server.
1888
- *
1889
- * Valid after initialization has completed.
1890
- */
1891
- this.latestHash = null;
1892
- this.lastUpdateCheck = null;
1893
- /**
1894
- * Whether there is a check for updates currently scheduled due to navigation.
1895
- */
1896
- this.scheduledNavUpdateCheck = false;
1897
- /**
1898
- * Keep track of whether we have logged an invalid `only-if-cached` request.
1899
- * (See `.onFetch()` for details.)
1900
- */
1901
- this.loggedInvalidOnlyIfCachedRequest = false;
1902
- this.ngswStatePath = this.adapter.parseUrl('ngsw/state', this.scope.registration.scope).path;
1903
- // A promise resolving to the control DB table.
1904
- this.controlTable = this.db.open('control');
1905
- // The install event is triggered when the service worker is first installed.
1906
- this.scope.addEventListener('install', (event) => {
1907
- // SW code updates are separate from application updates, so code updates are
1908
- // almost as straightforward as restarting the SW. Because of this, it's always
1909
- // safe to skip waiting until application tabs are closed, and activate the new
1910
- // SW version immediately.
1911
- event.waitUntil(this.scope.skipWaiting());
1912
- });
1913
- // The activate event is triggered when this version of the service worker is
1914
- // first activated.
1915
- this.scope.addEventListener('activate', (event) => {
1916
- event.waitUntil((async () => {
1917
- // As above, it's safe to take over from existing clients immediately, since the new SW
1918
- // version will continue to serve the old application.
1919
- await this.scope.clients.claim();
1920
- // Once all clients have been taken over, we can delete caches used by old versions of
1921
- // `@angular/service-worker`, which are no longer needed. This can happen in the background.
1922
- this.idle.schedule('activate: cleanup-old-sw-caches', async () => {
1923
- try {
1924
- await this.cleanupOldSwCaches();
1925
- }
1926
- catch (err) {
1927
- // Nothing to do - cleanup failed. Just log it.
1928
- this.debugger.log(err, 'cleanupOldSwCaches @ activate: cleanup-old-sw-caches');
1929
- }
1930
- });
1931
- })());
1932
- // Rather than wait for the first fetch event, which may not arrive until
1933
- // the next time the application is loaded, the SW takes advantage of the
1934
- // activation event to schedule initialization. However, if this were run
1935
- // in the context of the 'activate' event, waitUntil() here would cause fetch
1936
- // events to block until initialization completed. Thus, the SW does a
1937
- // postMessage() to itself, to schedule a new event loop iteration with an
1938
- // entirely separate event context. The SW will be kept alive by waitUntil()
1939
- // within that separate context while initialization proceeds, while at the
1940
- // same time the activation event is allowed to resolve and traffic starts
1941
- // being served.
1942
- if (this.scope.registration.active !== null) {
1943
- this.scope.registration.active.postMessage({ action: 'INITIALIZE' });
1944
- }
1945
- });
1946
- // Handle the fetch, message, and push events.
1947
- this.scope.addEventListener('fetch', (event) => this.onFetch(event));
1948
- this.scope.addEventListener('message', (event) => this.onMessage(event));
1949
- this.scope.addEventListener('push', (event) => this.onPush(event));
1950
- this.scope.addEventListener('notificationclick', (event) => this.onClick(event));
1951
- // The debugger generates debug pages in response to debugging requests.
1952
- this.debugger = new DebugHandler(this, this.adapter);
1953
- // The IdleScheduler will execute idle tasks after a given delay.
1954
- this.idle = new IdleScheduler(this.adapter, IDLE_DELAY, MAX_IDLE_DELAY, this.debugger);
1955
- }
1956
- /**
1957
- * The handler for fetch events.
1958
- *
1959
- * This is the transition point between the synchronous event handler and the
1960
- * asynchronous execution that eventually resolves for respondWith() and waitUntil().
1961
- */
1962
- onFetch(event) {
1963
- const req = event.request;
1964
- const scopeUrl = this.scope.registration.scope;
1965
- const requestUrlObj = this.adapter.parseUrl(req.url, scopeUrl);
1966
- if (req.headers.has('ngsw-bypass') || /[?&]ngsw-bypass(?:[=&]|$)/i.test(requestUrlObj.search)) {
1967
- return;
1968
- }
1969
- // The only thing that is served unconditionally is the debug page.
1970
- if (requestUrlObj.path === this.ngswStatePath) {
1971
- // Allow the debugger to handle the request, but don't affect SW state in any other way.
1972
- event.respondWith(this.debugger.handleFetch(req));
1973
- return;
1974
- }
1975
- // If the SW is in a broken state where it's not safe to handle requests at all,
1976
- // returning causes the request to fall back on the network. This is preferred over
1977
- // `respondWith(fetch(req))` because the latter still shows in DevTools that the
1978
- // request was handled by the SW.
1979
- if (this.state === DriverReadyState.SAFE_MODE) {
1980
- // Even though the worker is in safe mode, idle tasks still need to happen so
1981
- // things like update checks, etc. can take place.
1982
- event.waitUntil(this.idle.trigger());
1983
- return;
1984
- }
1985
- // Although "passive mixed content" (like images) only produces a warning without a
1986
- // ServiceWorker, fetching it via a ServiceWorker results in an error. Let such requests be
1987
- // handled by the browser, since handling with the ServiceWorker would fail anyway.
1988
- // See https://github.com/angular/angular/issues/23012#issuecomment-376430187 for more details.
1989
- if (requestUrlObj.origin.startsWith('http:') && scopeUrl.startsWith('https:')) {
1990
- // Still, log the incident for debugging purposes.
1991
- this.debugger.log(`Ignoring passive mixed content request: Driver.fetch(${req.url})`);
1992
- return;
1993
- }
1994
- // When opening DevTools in Chrome, a request is made for the current URL (and possibly related
1995
- // resources, e.g. scripts) with `cache: 'only-if-cached'` and `mode: 'no-cors'`. These request
1996
- // will eventually fail, because `only-if-cached` is only allowed to be used with
1997
- // `mode: 'same-origin'`.
1998
- // This is likely a bug in Chrome DevTools. Avoid handling such requests.
1999
- // (See also https://github.com/angular/angular/issues/22362.)
2000
- // TODO(gkalpak): Remove once no longer necessary (i.e. fixed in Chrome DevTools).
2001
- if (req.cache === 'only-if-cached' && req.mode !== 'same-origin') {
2002
- // Log the incident only the first time it happens, to avoid spamming the logs.
2003
- if (!this.loggedInvalidOnlyIfCachedRequest) {
2004
- this.loggedInvalidOnlyIfCachedRequest = true;
2005
- this.debugger.log(`Ignoring invalid request: 'only-if-cached' can be set only with 'same-origin' mode`, `Driver.fetch(${req.url}, cache: ${req.cache}, mode: ${req.mode})`);
2006
- }
2007
- return;
2008
- }
2009
- // Past this point, the SW commits to handling the request itself. This could still
2010
- // fail (and result in `state` being set to `SAFE_MODE`), but even in that case the
2011
- // SW will still deliver a response.
2012
- event.respondWith(this.handleFetch(event));
2013
- }
2014
- /**
2015
- * The handler for message events.
2016
- */
2017
- onMessage(event) {
2018
- // Ignore message events when the SW is in safe mode, for now.
2019
- if (this.state === DriverReadyState.SAFE_MODE) {
2020
- return;
2021
- }
2022
- // If the message doesn't have the expected signature, ignore it.
2023
- const data = event.data;
2024
- if (!data || !data.action) {
2025
- return;
2026
- }
2027
- event.waitUntil((async () => {
2028
- // Initialization is the only event which is sent directly from the SW to itself, and thus
2029
- // `event.source` is not a `Client`. Handle it here, before the check for `Client` sources.
2030
- if (data.action === 'INITIALIZE') {
2031
- return this.ensureInitialized(event);
2032
- }
2033
- // Only messages from true clients are accepted past this point.
2034
- // This is essentially a typecast.
2035
- if (!this.adapter.isClient(event.source)) {
2036
- return;
2037
- }
2038
- // Handle the message and keep the SW alive until it's handled.
2039
- await this.ensureInitialized(event);
2040
- await this.handleMessage(data, event.source);
2041
- })());
2042
- }
2043
- onPush(msg) {
2044
- // Push notifications without data have no effect.
2045
- if (!msg.data) {
2046
- return;
2047
- }
2048
- // Handle the push and keep the SW alive until it's handled.
2049
- msg.waitUntil(this.handlePush(msg.data.json()));
2050
- }
2051
- onClick(event) {
2052
- // Handle the click event and keep the SW alive until it's handled.
2053
- event.waitUntil(this.handleClick(event.notification, event.action));
2054
- }
2055
- async ensureInitialized(event) {
2056
- // Since the SW may have just been started, it may or may not have been initialized already.
2057
- // `this.initialized` will be `null` if initialization has not yet been attempted, or will be a
2058
- // `Promise` which will resolve (successfully or unsuccessfully) if it has.
2059
- if (this.initialized !== null) {
2060
- return this.initialized;
2061
- }
2062
- // Initialization has not yet been attempted, so attempt it. This should only ever happen once
2063
- // per SW instantiation.
2064
- try {
2065
- this.initialized = this.initialize();
2066
- await this.initialized;
2067
- }
2068
- catch (error) {
2069
- // If initialization fails, the SW needs to enter a safe state, where it declines to respond
2070
- // to network requests.
2071
- this.state = DriverReadyState.SAFE_MODE;
2072
- this.stateMessage = `Initialization failed due to error: ${errorToString(error)}`;
2073
- throw error;
2074
- }
2075
- finally {
2076
- // Regardless if initialization succeeded, background tasks still need to happen.
2077
- event.waitUntil(this.idle.trigger());
2078
- }
2079
- }
2080
- async handleMessage(msg, from) {
2081
- if (isMsgCheckForUpdates(msg)) {
2082
- const action = this.checkForUpdate();
2083
- await this.completeOperation(from, action, msg.nonce);
2084
- }
2085
- else if (isMsgActivateUpdate(msg)) {
2086
- const action = this.updateClient(from);
2087
- await this.completeOperation(from, action, msg.nonce);
2088
- }
2089
- }
2090
- async handlePush(data) {
2091
- await this.broadcast({
2092
- type: 'PUSH',
2093
- data,
2094
- });
2095
- if (!data.notification || !data.notification.title) {
2096
- return;
2097
- }
2098
- const desc = data.notification;
2099
- let options = {};
2100
- NOTIFICATION_OPTION_NAMES.filter(name => desc.hasOwnProperty(name))
2101
- .forEach(name => options[name] = desc[name]);
2102
- await this.scope.registration.showNotification(desc['title'], options);
2103
- }
2104
- async handleClick(notification, action) {
2105
- notification.close();
2106
- const options = {};
2107
- // The filter uses `name in notification` because the properties are on the prototype so
2108
- // hasOwnProperty does not work here
2109
- NOTIFICATION_OPTION_NAMES.filter(name => name in notification)
2110
- .forEach(name => options[name] = notification[name]);
2111
- const notificationAction = action === '' || action === undefined ? 'default' : action;
2112
- const onActionClick = notification?.data?.onActionClick?.[notificationAction];
2113
- const urlToOpen = new URL(onActionClick?.url ?? '', this.scope.registration.scope).href;
2114
- switch (onActionClick?.operation) {
2115
- case 'openWindow':
2116
- await this.scope.clients.openWindow(urlToOpen);
2117
- break;
2118
- case 'focusLastFocusedOrOpen': {
2119
- let matchingClient = await this.getLastFocusedMatchingClient(this.scope);
2120
- if (matchingClient) {
2121
- await matchingClient?.focus();
2122
- }
2123
- else {
2124
- await this.scope.clients.openWindow(urlToOpen);
2125
- }
2126
- break;
2127
- }
2128
- case 'navigateLastFocusedOrOpen': {
2129
- let matchingClient = await this.getLastFocusedMatchingClient(this.scope);
2130
- if (matchingClient) {
2131
- matchingClient = await matchingClient.navigate(urlToOpen);
2132
- await matchingClient?.focus();
2133
- }
2134
- else {
2135
- await this.scope.clients.openWindow(urlToOpen);
2136
- }
2137
- break;
2138
- }
2139
- }
2140
- await this.broadcast({
2141
- type: 'NOTIFICATION_CLICK',
2142
- data: { action, notification: options },
2143
- });
2144
- }
2145
- async getLastFocusedMatchingClient(scope) {
2146
- const windowClients = await scope.clients.matchAll({ type: 'window' });
2147
- // As per the spec windowClients are `sorted in the most recently focused order`
2148
- return windowClients[0];
2149
- }
2150
- async completeOperation(client, promise, nonce) {
2151
- const response = { type: 'OPERATION_COMPLETED', nonce };
2152
- try {
2153
- client.postMessage({
2154
- ...response,
2155
- result: await promise,
2156
- });
2157
- }
2158
- catch (e) {
2159
- client.postMessage({
2160
- ...response,
2161
- error: e.toString(),
2162
- });
2163
- }
2164
- }
2165
- async updateClient(client) {
2166
- // Figure out which version the client is on. If it's not on the latest,
2167
- // it needs to be moved.
2168
- const existing = this.clientVersionMap.get(client.id);
2169
- if (existing === this.latestHash) {
2170
- // Nothing to do, this client is already on the latest version.
2171
- return false;
2172
- }
2173
- // Switch the client over.
2174
- let previous = undefined;
2175
- // Look up the application data associated with the existing version. If there
2176
- // isn't any, fall back on using the hash.
2177
- if (existing !== undefined) {
2178
- const existingVersion = this.versions.get(existing);
2179
- previous = this.mergeHashWithAppData(existingVersion.manifest, existing);
2180
- }
2181
- // Set the current version used by the client, and sync the mapping to disk.
2182
- this.clientVersionMap.set(client.id, this.latestHash);
2183
- await this.sync();
2184
- // Notify the client about this activation.
2185
- const current = this.versions.get(this.latestHash);
2186
- const notice = {
2187
- type: 'UPDATE_ACTIVATED',
2188
- previous,
2189
- current: this.mergeHashWithAppData(current.manifest, this.latestHash),
2190
- };
2191
- client.postMessage(notice);
2192
- return true;
2193
- }
2194
- async handleFetch(event) {
2195
- try {
2196
- // Ensure the SW instance has been initialized.
2197
- await this.ensureInitialized(event);
2198
- }
2199
- catch {
2200
- // Since the SW is already committed to responding to the currently active request,
2201
- // respond with a network fetch.
2202
- return this.safeFetch(event.request);
2203
- }
2204
- // On navigation requests, check for new updates.
2205
- if (event.request.mode === 'navigate' && !this.scheduledNavUpdateCheck) {
2206
- this.scheduledNavUpdateCheck = true;
2207
- this.idle.schedule('check-updates-on-navigation', async () => {
2208
- this.scheduledNavUpdateCheck = false;
2209
- await this.checkForUpdate();
2210
- });
2211
- }
2212
- // Decide which version of the app to use to serve this request. This is asynchronous as in
2213
- // some cases, a record will need to be written to disk about the assignment that is made.
2214
- const appVersion = await this.assignVersion(event);
2215
- let res = null;
2216
- try {
2217
- if (appVersion !== null) {
2218
- try {
2219
- // Handle the request. First try the AppVersion. If that doesn't work, fall back on the
2220
- // network.
2221
- res = await appVersion.handleFetch(event.request, event);
2222
- }
2223
- catch (err) {
2224
- if (err.isUnrecoverableState) {
2225
- await this.notifyClientsAboutUnrecoverableState(appVersion, err.message);
2226
- }
2227
- if (err.isCritical) {
2228
- // Something went wrong with handling the request from this version.
2229
- this.debugger.log(err, `Driver.handleFetch(version: ${appVersion.manifestHash})`);
2230
- await this.versionFailed(appVersion, err);
2231
- return this.safeFetch(event.request);
2232
- }
2233
- throw err;
2234
- }
2235
- }
2236
- // The response will be `null` only if no `AppVersion` can be assigned to the request or if
2237
- // the assigned `AppVersion`'s manifest doesn't specify what to do about the request.
2238
- // In that case, just fall back on the network.
2239
- if (res === null) {
2240
- return this.safeFetch(event.request);
2241
- }
2242
- // The `AppVersion` returned a usable response, so return it.
2243
- return res;
2244
- }
2245
- finally {
2246
- // Trigger the idle scheduling system. The Promise returned by `trigger()` will resolve after
2247
- // a specific amount of time has passed. If `trigger()` hasn't been called again by then (e.g.
2248
- // on a subsequent request), the idle task queue will be drained and the `Promise` won't
2249
- // be resolved until that operation is complete as well.
2250
- event.waitUntil(this.idle.trigger());
2251
- }
2252
- }
2253
- /**
2254
- * Attempt to quickly reach a state where it's safe to serve responses.
2255
- */
2256
- async initialize() {
2257
- // On initialization, all of the serialized state is read out of the 'control'
2258
- // table. This includes:
2259
- // - map of hashes to manifests of currently loaded application versions
2260
- // - map of client IDs to their pinned versions
2261
- // - record of the most recently fetched manifest hash
2262
- //
2263
- // If these values don't exist in the DB, then this is the either the first time
2264
- // the SW has run or the DB state has been wiped or is inconsistent. In that case,
2265
- // load a fresh copy of the manifest and reset the state from scratch.
2266
- const table = await this.controlTable;
2267
- // Attempt to load the needed state from the DB. If this fails, the catch {} block
2268
- // will populate these variables with freshly constructed values.
2269
- let manifests, assignments, latest;
2270
- try {
2271
- // Read them from the DB simultaneously.
2272
- [manifests, assignments, latest] = await Promise.all([
2273
- table.read('manifests'),
2274
- table.read('assignments'),
2275
- table.read('latest'),
2276
- ]);
2277
- // Make sure latest manifest is correctly installed. If not (e.g. corrupted data),
2278
- // it could stay locked in EXISTING_CLIENTS_ONLY or SAFE_MODE state.
2279
- if (!this.versions.has(latest.latest) && !manifests.hasOwnProperty(latest.latest)) {
2280
- this.debugger.log(`Missing manifest for latest version hash ${latest.latest}`, 'initialize: read from DB');
2281
- throw new Error(`Missing manifest for latest hash ${latest.latest}`);
2282
- }
2283
- // Successfully loaded from saved state. This implies a manifest exists, so
2284
- // the update check needs to happen in the background.
2285
- this.idle.schedule('init post-load (update)', async () => {
2286
- await this.checkForUpdate();
2287
- });
2288
- }
2289
- catch (_) {
2290
- // Something went wrong. Try to start over by fetching a new manifest from the
2291
- // server and building up an empty initial state.
2292
- const manifest = await this.fetchLatestManifest();
2293
- const hash = hashManifest(manifest);
2294
- manifests = { [hash]: manifest };
2295
- assignments = {};
2296
- latest = { latest: hash };
2297
- // Save the initial state to the DB.
2298
- await Promise.all([
2299
- table.write('manifests', manifests),
2300
- table.write('assignments', assignments),
2301
- table.write('latest', latest),
2302
- ]);
2303
- }
2304
- // At this point, either the state has been loaded successfully, or fresh state
2305
- // with a new copy of the manifest has been produced. At this point, the `Driver`
2306
- // can have its internals hydrated from the state.
2307
- // Schedule cleaning up obsolete caches in the background.
2308
- this.idle.schedule('init post-load (cleanup)', async () => {
2309
- await this.cleanupCaches();
2310
- });
2311
- // Initialize the `versions` map by setting each hash to a new `AppVersion` instance
2312
- // for that manifest.
2313
- Object.keys(manifests).forEach((hash) => {
2314
- const manifest = manifests[hash];
2315
- // If the manifest is newly initialized, an AppVersion may have already been
2316
- // created for it.
2317
- if (!this.versions.has(hash)) {
2318
- this.versions.set(hash, new AppVersion(this.scope, this.adapter, this.db, this.idle, this.debugger, manifest, hash));
2319
- }
2320
- });
2321
- // Map each client ID to its associated hash. Along the way, verify that the hash
2322
- // is still valid for that client ID. It should not be possible for a client to
2323
- // still be associated with a hash that was since removed from the state.
2324
- Object.keys(assignments).forEach((clientId) => {
2325
- const hash = assignments[clientId];
2326
- if (this.versions.has(hash)) {
2327
- this.clientVersionMap.set(clientId, hash);
2328
- }
2329
- else {
2330
- this.clientVersionMap.set(clientId, latest.latest);
2331
- this.debugger.log(`Unknown version ${hash} mapped for client ${clientId}, using latest instead`, `initialize: map assignments`);
2332
- }
2333
- });
2334
- // Set the latest version.
2335
- this.latestHash = latest.latest;
2336
- // Finally, assert that the latest version is in fact loaded.
2337
- if (!this.versions.has(latest.latest)) {
2338
- throw new Error(`Invariant violated (initialize): latest hash ${latest.latest} has no known manifest`);
2339
- }
2340
- // Finally, wait for the scheduling of initialization of all versions in the
2341
- // manifest. Ordinarily this just schedules the initializations to happen during
2342
- // the next idle period, but in development mode this might actually wait for the
2343
- // full initialization.
2344
- // If any of these initializations fail, versionFailed() will be called either
2345
- // synchronously or asynchronously to handle the failure and re-map clients.
2346
- await Promise.all(Object.keys(manifests).map(async (hash) => {
2347
- try {
2348
- // Attempt to schedule or initialize this version. If this operation is
2349
- // successful, then initialization either succeeded or was scheduled. If
2350
- // it fails, then full initialization was attempted and failed.
2351
- await this.scheduleInitialization(this.versions.get(hash));
2352
- }
2353
- catch (err) {
2354
- this.debugger.log(err, `initialize: schedule init of ${hash}`);
2355
- return false;
2356
- }
2357
- }));
2358
- }
2359
- lookupVersionByHash(hash, debugName = 'lookupVersionByHash') {
2360
- // The version should exist, but check just in case.
2361
- if (!this.versions.has(hash)) {
2362
- throw new Error(`Invariant violated (${debugName}): want AppVersion for ${hash} but not loaded`);
2363
- }
2364
- return this.versions.get(hash);
2365
- }
2366
- /**
2367
- * Decide which version of the manifest to use for the event.
2368
- */
2369
- async assignVersion(event) {
2370
- // First, check whether the event has a (non empty) client ID. If it does, the version may
2371
- // already be associated.
2372
- //
2373
- // NOTE: For navigation requests, we care about the `resultingClientId`. If it is undefined or
2374
- // the empty string (which is the case for sub-resource requests), we look at `clientId`.
2375
- const clientId = event.resultingClientId || event.clientId;
2376
- if (clientId) {
2377
- // Check if there is an assigned client id.
2378
- if (this.clientVersionMap.has(clientId)) {
2379
- // There is an assignment for this client already.
2380
- const hash = this.clientVersionMap.get(clientId);
2381
- let appVersion = this.lookupVersionByHash(hash, 'assignVersion');
2382
- // Ordinarily, this client would be served from its assigned version. But, if this
2383
- // request is a navigation request, this client can be updated to the latest
2384
- // version immediately.
2385
- if (this.state === DriverReadyState.NORMAL && hash !== this.latestHash &&
2386
- appVersion.isNavigationRequest(event.request)) {
2387
- // Update this client to the latest version immediately.
2388
- if (this.latestHash === null) {
2389
- throw new Error(`Invariant violated (assignVersion): latestHash was null`);
2390
- }
2391
- const client = await this.scope.clients.get(clientId);
2392
- if (client) {
2393
- await this.updateClient(client);
2394
- }
2395
- appVersion = this.lookupVersionByHash(this.latestHash, 'assignVersion');
2396
- }
2397
- // TODO: make sure the version is valid.
2398
- return appVersion;
2399
- }
2400
- else {
2401
- // This is the first time this client ID has been seen. Whether the SW is in a
2402
- // state to handle new clients depends on the current readiness state, so check
2403
- // that first.
2404
- if (this.state !== DriverReadyState.NORMAL) {
2405
- // It's not safe to serve new clients in the current state. It's possible that
2406
- // this is an existing client which has not been mapped yet (see below) but
2407
- // even if that is the case, it's invalid to make an assignment to a known
2408
- // invalid version, even if that assignment was previously implicit. Return
2409
- // undefined here to let the caller know that no assignment is possible at
2410
- // this time.
2411
- return null;
2412
- }
2413
- // It's safe to handle this request. Two cases apply. Either:
2414
- // 1) the browser assigned a client ID at the time of the navigation request, and
2415
- // this is truly the first time seeing this client, or
2416
- // 2) a navigation request came previously from the same client, but with no client
2417
- // ID attached. Browsers do this to avoid creating a client under the origin in
2418
- // the event the navigation request is just redirected.
2419
- //
2420
- // In case 1, the latest version can safely be used.
2421
- // In case 2, the latest version can be used, with the assumption that the previous
2422
- // navigation request was answered under the same version. This assumption relies
2423
- // on the fact that it's unlikely an update will come in between the navigation
2424
- // request and requests for subsequent resources on that page.
2425
- // First validate the current state.
2426
- if (this.latestHash === null) {
2427
- throw new Error(`Invariant violated (assignVersion): latestHash was null`);
2428
- }
2429
- // Pin this client ID to the current latest version, indefinitely.
2430
- this.clientVersionMap.set(clientId, this.latestHash);
2431
- await this.sync();
2432
- // Return the latest `AppVersion`.
2433
- return this.lookupVersionByHash(this.latestHash, 'assignVersion');
2434
- }
2435
- }
2436
- else {
2437
- // No client ID was associated with the request. This must be a navigation request
2438
- // for a new client. First check that the SW is accepting new clients.
2439
- if (this.state !== DriverReadyState.NORMAL) {
2440
- return null;
2441
- }
2442
- // Serve it with the latest version, and assume that the client will actually get
2443
- // associated with that version on the next request.
2444
- // First validate the current state.
2445
- if (this.latestHash === null) {
2446
- throw new Error(`Invariant violated (assignVersion): latestHash was null`);
2447
- }
2448
- // Return the latest `AppVersion`.
2449
- return this.lookupVersionByHash(this.latestHash, 'assignVersion');
2450
- }
2451
- }
2452
- async fetchLatestManifest(ignoreOfflineError = false) {
2453
- const res = await this.safeFetch(this.adapter.newRequest('ngsw.json?ngsw-cache-bust=' + Math.random()));
2454
- if (!res.ok) {
2455
- if (res.status === 404) {
2456
- await this.deleteAllCaches();
2457
- await this.scope.registration.unregister();
2458
- }
2459
- else if ((res.status === 503 || res.status === 504) && ignoreOfflineError) {
2460
- return null;
2461
- }
2462
- throw new Error(`Manifest fetch failed! (status: ${res.status})`);
2463
- }
2464
- this.lastUpdateCheck = this.adapter.time;
2465
- return res.json();
2466
- }
2467
- async deleteAllCaches() {
2468
- const cacheNames = await this.adapter.caches.keys();
2469
- await Promise.all(cacheNames.map(name => this.adapter.caches.delete(name)));
2470
- }
2471
- /**
2472
- * Schedule the SW's attempt to reach a fully prefetched state for the given AppVersion
2473
- * when the SW is not busy and has connectivity. This returns a Promise which must be
2474
- * awaited, as under some conditions the AppVersion might be initialized immediately.
2475
- */
2476
- async scheduleInitialization(appVersion) {
2477
- const initialize = async () => {
2478
- try {
2479
- await appVersion.initializeFully();
2480
- }
2481
- catch (err) {
2482
- this.debugger.log(err, `initializeFully for ${appVersion.manifestHash}`);
2483
- await this.versionFailed(appVersion, err);
2484
- }
2485
- };
2486
- // TODO: better logic for detecting localhost.
2487
- if (this.scope.registration.scope.indexOf('://localhost') > -1) {
2488
- return initialize();
2489
- }
2490
- this.idle.schedule(`initialization(${appVersion.manifestHash})`, initialize);
2491
- }
2492
- async versionFailed(appVersion, err) {
2493
- // This particular AppVersion is broken. First, find the manifest hash.
2494
- const broken = Array.from(this.versions.entries()).find(([hash, version]) => version === appVersion);
2495
- if (broken === undefined) {
2496
- // This version is no longer in use anyway, so nobody cares.
2497
- return;
2498
- }
2499
- const brokenHash = broken[0];
2500
- // The specified version is broken and new clients should not be served from it. However, it is
2501
- // deemed even riskier to switch the existing clients to a different version or to the network.
2502
- // Therefore, we keep clients on their current version (even if broken) and ensure that no new
2503
- // clients will be assigned to it.
2504
- // TODO: notify affected apps.
2505
- // The action taken depends on whether the broken manifest is the active (latest) or not.
2506
- // - If the broken version is not the latest, no further action is necessary, since new clients
2507
- // will be assigned to the latest version anyway.
2508
- // - If the broken version is the latest, the SW cannot accept new clients (but can continue to
2509
- // service old ones).
2510
- if (this.latestHash === brokenHash) {
2511
- // The latest manifest is broken. This means that new clients are at the mercy of the network,
2512
- // but caches continue to be valid for previous versions. This is unfortunate but unavoidable.
2513
- this.state = DriverReadyState.EXISTING_CLIENTS_ONLY;
2514
- this.stateMessage = `Degraded due to: ${errorToString(err)}`;
2515
- }
2516
- }
2517
- async setupUpdate(manifest, hash) {
2518
- try {
2519
- const newVersion = new AppVersion(this.scope, this.adapter, this.db, this.idle, this.debugger, manifest, hash);
2520
- // Firstly, check if the manifest version is correct.
2521
- if (manifest.configVersion !== SUPPORTED_CONFIG_VERSION) {
2522
- await this.deleteAllCaches();
2523
- await this.scope.registration.unregister();
2524
- throw new Error(`Invalid config version: expected ${SUPPORTED_CONFIG_VERSION}, got ${manifest.configVersion}.`);
2525
- }
2526
- // Cause the new version to become fully initialized. If this fails, then the
2527
- // version will not be available for use.
2528
- await newVersion.initializeFully(this);
2529
- // Install this as an active version of the app.
2530
- this.versions.set(hash, newVersion);
2531
- // Future new clients will use this hash as the latest version.
2532
- this.latestHash = hash;
2533
- // If we are in `EXISTING_CLIENTS_ONLY` mode (meaning we didn't have a clean copy of the last
2534
- // latest version), we can now recover to `NORMAL` mode and start accepting new clients.
2535
- if (this.state === DriverReadyState.EXISTING_CLIENTS_ONLY) {
2536
- this.state = DriverReadyState.NORMAL;
2537
- this.stateMessage = '(nominal)';
2538
- }
2539
- await this.sync();
2540
- await this.notifyClientsAboutVersionReady(manifest, hash);
2541
- }
2542
- catch (e) {
2543
- await this.notifyClientsAboutVersionInstallationFailed(manifest, hash, e);
2544
- throw e;
2545
- }
2546
- }
2547
- async checkForUpdate() {
2548
- let hash = '(unknown)';
2549
- try {
2550
- const manifest = await this.fetchLatestManifest(true);
2551
- if (manifest === null) {
2552
- // Client or server offline. Unable to check for updates at this time.
2553
- // Continue to service clients (existing and new).
2554
- this.debugger.log('Check for update aborted. (Client or server offline.)');
2555
- return false;
2556
- }
2557
- hash = hashManifest(manifest);
2558
- // Check whether this is really an update.
2559
- if (this.versions.has(hash)) {
2560
- return false;
2561
- }
2562
- await this.notifyClientsAboutVersionDetected(manifest, hash);
2563
- await this.setupUpdate(manifest, hash);
2564
- return true;
2565
- }
2566
- catch (err) {
2567
- this.debugger.log(err, `Error occurred while updating to manifest ${hash}`);
2568
- this.state = DriverReadyState.EXISTING_CLIENTS_ONLY;
2569
- this.stateMessage = `Degraded due to failed initialization: ${errorToString(err)}`;
2570
- return false;
2571
- }
2572
- }
2573
- /**
2574
- * Synchronize the existing state to the underlying database.
2575
- */
2576
- async sync() {
2577
- const table = await this.controlTable;
2578
- // Construct a serializable map of hashes to manifests.
2579
- const manifests = {};
2580
- this.versions.forEach((version, hash) => {
2581
- manifests[hash] = version.manifest;
2582
- });
2583
- // Construct a serializable map of client ids to version hashes.
2584
- const assignments = {};
2585
- this.clientVersionMap.forEach((hash, clientId) => {
2586
- assignments[clientId] = hash;
2587
- });
2588
- // Record the latest entry. Since this is a sync which is necessarily happening after
2589
- // initialization, latestHash should always be valid.
2590
- const latest = {
2591
- latest: this.latestHash,
2592
- };
2593
- // Synchronize all of these.
2594
- await Promise.all([
2595
- table.write('manifests', manifests),
2596
- table.write('assignments', assignments),
2597
- table.write('latest', latest),
2598
- ]);
2599
- }
2600
- async cleanupCaches() {
2601
- try {
2602
- // Query for all currently active clients, and list the client IDs. This may skip some clients
2603
- // in the browser back-forward cache, but not much can be done about that.
2604
- const activeClients = new Set((await this.scope.clients.matchAll()).map(client => client.id));
2605
- // A simple list of client IDs that the SW has kept track of. Subtracting `activeClients` from
2606
- // this list will result in the set of client IDs which are being tracked but are no longer
2607
- // used in the browser, and thus can be cleaned up.
2608
- const knownClients = Array.from(this.clientVersionMap.keys());
2609
- // Remove clients in the `clientVersionMap` that are no longer active.
2610
- const obsoleteClients = knownClients.filter(id => !activeClients.has(id));
2611
- obsoleteClients.forEach(id => this.clientVersionMap.delete(id));
2612
- // Next, determine the set of versions which are still used. All others can be removed.
2613
- const usedVersions = new Set(this.clientVersionMap.values());
2614
- // Collect all obsolete versions by filtering out used versions from the set of all versions.
2615
- const obsoleteVersions = Array.from(this.versions.keys())
2616
- .filter(version => !usedVersions.has(version) && version !== this.latestHash);
2617
- // Remove all the versions which are no longer used.
2618
- obsoleteVersions.forEach(version => this.versions.delete(version));
2619
- // Commit all the changes to the saved state.
2620
- await this.sync();
2621
- // Delete all caches that are no longer needed.
2622
- const allCaches = await this.adapter.caches.keys();
2623
- const usedCaches = new Set(await this.getCacheNames());
2624
- const cachesToDelete = allCaches.filter(name => !usedCaches.has(name));
2625
- await Promise.all(cachesToDelete.map(name => this.adapter.caches.delete(name)));
2626
- }
2627
- catch (err) {
2628
- // Oh well? Not much that can be done here. These caches will be removed on the next attempt
2629
- // or when the SW revs its format version, which happens from time to time.
2630
- this.debugger.log(err, 'cleanupCaches');
2631
- }
2632
- }
2633
- /**
2634
- * Delete caches that were used by older versions of `@angular/service-worker` to avoid running
2635
- * into storage quota limitations imposed by browsers.
2636
- * (Since at this point the SW has claimed all clients, it is safe to remove those caches.)
2637
- */
2638
- async cleanupOldSwCaches() {
2639
- // This is an exceptional case, where we need to interact with caches that would not be
2640
- // generated by this ServiceWorker (but by old versions of it). Use the native `CacheStorage`
2641
- // directly.
2642
- const caches = this.adapter.caches.original;
2643
- const cacheNames = await caches.keys();
2644
- const oldSwCacheNames = cacheNames.filter(name => /^ngsw:(?!\/)/.test(name));
2645
- await Promise.all(oldSwCacheNames.map(name => caches.delete(name)));
2646
- }
2647
- /**
2648
- * Determine if a specific version of the given resource is cached anywhere within the SW,
2649
- * and fetch it if so.
2650
- */
2651
- lookupResourceWithHash(url, hash) {
2652
- return Array
2653
- // Scan through the set of all cached versions, valid or otherwise. It's safe to do such
2654
- // lookups even for invalid versions as the cached version of a resource will have the
2655
- // same hash regardless.
2656
- .from(this.versions.values())
2657
- // Reduce the set of versions to a single potential result. At any point along the
2658
- // reduction, if a response has already been identified, then pass it through, as no
2659
- // future operation could change the response. If no response has been found yet, keep
2660
- // checking versions until one is or until all versions have been exhausted.
2661
- .reduce(async (prev, version) => {
2662
- // First, check the previous result. If a non-null result has been found already, just
2663
- // return it.
2664
- if (await prev !== null) {
2665
- return prev;
2666
- }
2667
- // No result has been found yet. Try the next `AppVersion`.
2668
- return version.lookupResourceWithHash(url, hash);
2669
- }, Promise.resolve(null));
2670
- }
2671
- async lookupResourceWithoutHash(url) {
2672
- await this.initialized;
2673
- const version = this.versions.get(this.latestHash);
2674
- return version ? version.lookupResourceWithoutHash(url) : null;
2675
- }
2676
- async previouslyCachedResources() {
2677
- await this.initialized;
2678
- const version = this.versions.get(this.latestHash);
2679
- return version ? version.previouslyCachedResources() : [];
2680
- }
2681
- async recentCacheStatus(url) {
2682
- const version = this.versions.get(this.latestHash);
2683
- return version ? version.recentCacheStatus(url) : UpdateCacheStatus.NOT_CACHED;
2684
- }
2685
- mergeHashWithAppData(manifest, hash) {
2686
- return {
2687
- hash,
2688
- appData: manifest.appData,
2689
- };
2690
- }
2691
- async notifyClientsAboutUnrecoverableState(appVersion, reason) {
2692
- const broken = Array.from(this.versions.entries()).find(([hash, version]) => version === appVersion);
2693
- if (broken === undefined) {
2694
- // This version is no longer in use anyway, so nobody cares.
2695
- return;
2696
- }
2697
- const brokenHash = broken[0];
2698
- const affectedClients = Array.from(this.clientVersionMap.entries())
2699
- .filter(([clientId, hash]) => hash === brokenHash)
2700
- .map(([clientId]) => clientId);
2701
- await Promise.all(affectedClients.map(async (clientId) => {
2702
- const client = await this.scope.clients.get(clientId);
2703
- if (client) {
2704
- client.postMessage({ type: 'UNRECOVERABLE_STATE', reason });
2705
- }
2706
- }));
2707
- }
2708
- async notifyClientsAboutVersionInstallationFailed(manifest, hash, error) {
2709
- await this.initialized;
2710
- const clients = await this.scope.clients.matchAll();
2711
- await Promise.all(clients.map(async (client) => {
2712
- // Send a notice.
2713
- client.postMessage({
2714
- type: 'VERSION_INSTALLATION_FAILED',
2715
- version: this.mergeHashWithAppData(manifest, hash),
2716
- error: errorToString(error),
2717
- });
2718
- }));
2719
- }
2720
- async notifyClientsAboutVersionDetected(manifest, hash) {
2721
- await this.initialized;
2722
- const clients = await this.scope.clients.matchAll();
2723
- await Promise.all(clients.map(async (client) => {
2724
- // Firstly, determine which version this client is on.
2725
- const version = this.clientVersionMap.get(client.id);
2726
- if (version === undefined) {
2727
- // Unmapped client - assume it's the latest.
2728
- return;
2729
- }
2730
- // Send a notice.
2731
- client.postMessage({ type: 'VERSION_DETECTED', version: this.mergeHashWithAppData(manifest, hash) });
2732
- }));
2733
- }
2734
- async notifyClientsAboutVersionReady(manifest, hash) {
2735
- await this.initialized;
2736
- const clients = await this.scope.clients.matchAll();
2737
- await Promise.all(clients.map(async (client) => {
2738
- // Firstly, determine which version this client is on.
2739
- const version = this.clientVersionMap.get(client.id);
2740
- if (version === undefined) {
2741
- // Unmapped client - assume it's the latest.
2742
- return;
2743
- }
2744
- if (version === this.latestHash) {
2745
- // Client is already on the latest version, no need for a notification.
2746
- return;
2747
- }
2748
- const current = this.versions.get(version);
2749
- // Send a notice.
2750
- const notice = {
2751
- type: 'VERSION_READY',
2752
- currentVersion: this.mergeHashWithAppData(current.manifest, version),
2753
- latestVersion: this.mergeHashWithAppData(manifest, hash),
2754
- };
2755
- client.postMessage(notice);
2756
- }));
2757
- }
2758
- async broadcast(msg) {
2759
- const clients = await this.scope.clients.matchAll();
2760
- clients.forEach(client => {
2761
- client.postMessage(msg);
2762
- });
2763
- }
2764
- async debugState() {
2765
- return {
2766
- state: DriverReadyState[this.state],
2767
- why: this.stateMessage,
2768
- latestHash: this.latestHash,
2769
- lastUpdateCheck: this.lastUpdateCheck,
2770
- };
2771
- }
2772
- async debugVersions() {
2773
- // Build list of versions.
2774
- return Array.from(this.versions.keys()).map(hash => {
2775
- const version = this.versions.get(hash);
2776
- const clients = Array.from(this.clientVersionMap.entries())
2777
- .filter(([clientId, version]) => version === hash)
2778
- .map(([clientId, version]) => clientId);
2779
- return {
2780
- hash,
2781
- manifest: version.manifest,
2782
- clients,
2783
- status: '',
2784
- };
2785
- });
2786
- }
2787
- async debugIdleState() {
2788
- return {
2789
- queue: this.idle.taskDescriptions,
2790
- lastTrigger: this.idle.lastTrigger,
2791
- lastRun: this.idle.lastRun,
2792
- };
2793
- }
2794
- async safeFetch(req) {
2795
- try {
2796
- return await this.scope.fetch(req);
2797
- }
2798
- catch (err) {
2799
- this.debugger.log(err, `Driver.fetch(${req.url})`);
2800
- return this.adapter.newResponse(null, {
2801
- status: 504,
2802
- statusText: 'Gateway Timeout',
2803
- });
2804
- }
2805
- }
2806
- async getCacheNames() {
2807
- const controlTable = await this.controlTable;
2808
- const appVersions = Array.from(this.versions.values());
2809
- const appVersionCacheNames = await Promise.all(appVersions.map(version => version.getCacheNames()));
2810
- return [controlTable.cacheName].concat(...appVersionCacheNames);
2811
- }
2812
- }
2813
-
2814
- /**
2815
- * @license
2816
- * Copyright Google LLC All Rights Reserved.
2817
- *
2818
- * Use of this source code is governed by an MIT-style license that can be
2819
- * found in the LICENSE file at https://angular.io/license
2820
- */
2821
- const scope = self;
2822
- const adapter = new Adapter(scope.registration.scope, self.caches);
2823
- new Driver(scope, adapter, new CacheDatabase(adapter));
2824
-
2825
- })();