-
Notifications
You must be signed in to change notification settings - Fork 19
/
ngsw-worker.js
executable file
·1904 lines (1883 loc) · 68.3 KB
/
ngsw-worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(() => {
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/named-cache-storage.mjs
var NamedCacheStorage = class {
constructor(original, cacheNamePrefix) {
__publicField(this, "original");
__publicField(this, "cacheNamePrefix");
this.original = original;
this.cacheNamePrefix = cacheNamePrefix;
}
delete(cacheName) {
return this.original.delete(`${this.cacheNamePrefix}:${cacheName}`);
}
has(cacheName) {
return this.original.has(`${this.cacheNamePrefix}:${cacheName}`);
}
async keys() {
const prefix = `${this.cacheNamePrefix}:`;
const allCacheNames = await this.original.keys();
const ownCacheNames = allCacheNames.filter((name) => name.startsWith(prefix));
return ownCacheNames.map((name) => name.slice(prefix.length));
}
match(request, options) {
return this.original.match(request, options);
}
async open(cacheName) {
const cache = await this.original.open(`${this.cacheNamePrefix}:${cacheName}`);
return Object.assign(cache, { name: cacheName });
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/adapter.mjs
var Adapter = class {
constructor(scopeUrl, caches) {
__publicField(this, "scopeUrl");
__publicField(this, "caches");
__publicField(this, "origin");
this.scopeUrl = scopeUrl;
const parsedScopeUrl = this.parseUrl(this.scopeUrl);
this.origin = parsedScopeUrl.origin;
this.caches = new NamedCacheStorage(caches, `ngsw:${parsedScopeUrl.path}`);
}
newRequest(input, init) {
return new Request(input, init);
}
newResponse(body, init) {
return new Response(body, init);
}
newHeaders(headers) {
return new Headers(headers);
}
isClient(source) {
return source instanceof Client;
}
get time() {
return Date.now();
}
normalizeUrl(url) {
const parsed = this.parseUrl(url, this.scopeUrl);
return parsed.origin === this.origin ? parsed.path : url;
}
parseUrl(url, relativeTo) {
const parsed = !relativeTo ? new URL(url) : new URL(url, relativeTo);
return { origin: parsed.origin, path: parsed.pathname, search: parsed.search };
}
timeout(ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(), ms);
});
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/database.mjs
var NotFound = class {
constructor(table, key) {
__publicField(this, "table");
__publicField(this, "key");
this.table = table;
this.key = key;
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/db-cache.mjs
var CacheDatabase = class {
constructor(adapter2) {
__publicField(this, "adapter");
__publicField(this, "cacheNamePrefix", "db");
__publicField(this, "tables", /* @__PURE__ */ new Map());
this.adapter = adapter2;
}
"delete"(name) {
if (this.tables.has(name)) {
this.tables.delete(name);
}
return this.adapter.caches.delete(`${this.cacheNamePrefix}:${name}`);
}
async list() {
const prefix = `${this.cacheNamePrefix}:`;
const allCacheNames = await this.adapter.caches.keys();
const dbCacheNames = allCacheNames.filter((name) => name.startsWith(prefix));
return dbCacheNames.map((name) => name.slice(prefix.length));
}
async open(name, cacheQueryOptions) {
if (!this.tables.has(name)) {
const cache = await this.adapter.caches.open(`${this.cacheNamePrefix}:${name}`);
const table = new CacheTable(name, cache, this.adapter, cacheQueryOptions);
this.tables.set(name, table);
}
return this.tables.get(name);
}
};
var CacheTable = class {
constructor(name, cache, adapter2, cacheQueryOptions) {
__publicField(this, "name");
__publicField(this, "cache");
__publicField(this, "adapter");
__publicField(this, "cacheQueryOptions");
__publicField(this, "cacheName");
this.name = name;
this.cache = cache;
this.adapter = adapter2;
this.cacheQueryOptions = cacheQueryOptions;
this.cacheName = this.cache.name;
}
request(key) {
return this.adapter.newRequest("/" + key);
}
"delete"(key) {
return this.cache.delete(this.request(key), this.cacheQueryOptions);
}
keys() {
return this.cache.keys().then((requests) => requests.map((req) => req.url.slice(1)));
}
read(key) {
return this.cache.match(this.request(key), this.cacheQueryOptions).then((res) => {
if (res === void 0) {
return Promise.reject(new NotFound(this.name, key));
}
return res.json();
});
}
write(key, value) {
return this.cache.put(this.request(key), this.adapter.newResponse(JSON.stringify(value)));
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/api.mjs
var UpdateCacheStatus;
(function(UpdateCacheStatus2) {
UpdateCacheStatus2[UpdateCacheStatus2["NOT_CACHED"] = 0] = "NOT_CACHED";
UpdateCacheStatus2[UpdateCacheStatus2["CACHED_BUT_UNUSED"] = 1] = "CACHED_BUT_UNUSED";
UpdateCacheStatus2[UpdateCacheStatus2["CACHED"] = 2] = "CACHED";
})(UpdateCacheStatus || (UpdateCacheStatus = {}));
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/error.mjs
var SwCriticalError = class extends Error {
constructor() {
super(...arguments);
__publicField(this, "isCritical", true);
}
};
function errorToString(error) {
if (error instanceof Error) {
return `${error.message}
${error.stack}`;
} else {
return `${error}`;
}
}
var SwUnrecoverableStateError = class extends SwCriticalError {
constructor() {
super(...arguments);
__publicField(this, "isUnrecoverableState", true);
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/sha1.mjs
function sha1(str) {
const utf8 = str;
const words32 = stringToWords32(utf8, Endian.Big);
return _sha1(words32, utf8.length * 8);
}
function sha1Binary(buffer) {
const words32 = arrayBufferToWords32(buffer, Endian.Big);
return _sha1(words32, buffer.byteLength * 8);
}
function _sha1(words32, len) {
const w = [];
let [a, b, c, d, e] = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
words32[len >> 5] |= 128 << 24 - len % 32;
words32[(len + 64 >> 9 << 4) + 15] = len;
for (let i = 0; i < words32.length; i += 16) {
const [h0, h1, h2, h3, h4] = [a, b, c, d, e];
for (let j = 0; j < 80; j++) {
if (j < 16) {
w[j] = words32[i + j];
} else {
w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
const [f, k] = fk(j, b, c, d);
const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
[e, d, c, b, a] = [d, c, rol32(b, 30), a, temp];
}
[a, b, c, d, e] = [add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)];
}
return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
}
function add32(a, b) {
return add32to64(a, b)[1];
}
function add32to64(a, b) {
const low = (a & 65535) + (b & 65535);
const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
return [high >>> 16, high << 16 | low & 65535];
}
function rol32(a, count) {
return a << count | a >>> 32 - count;
}
var Endian;
(function(Endian2) {
Endian2[Endian2["Little"] = 0] = "Little";
Endian2[Endian2["Big"] = 1] = "Big";
})(Endian || (Endian = {}));
function fk(index, b, c, d) {
if (index < 20) {
return [b & c | ~b & d, 1518500249];
}
if (index < 40) {
return [b ^ c ^ d, 1859775393];
}
if (index < 60) {
return [b & c | b & d | c & d, 2400959708];
}
return [b ^ c ^ d, 3395469782];
}
function stringToWords32(str, endian) {
const size = str.length + 3 >>> 2;
const words32 = [];
for (let i = 0; i < size; i++) {
words32[i] = wordAt(str, i * 4, endian);
}
return words32;
}
function arrayBufferToWords32(buffer, endian) {
const size = buffer.byteLength + 3 >>> 2;
const words32 = [];
const view = new Uint8Array(buffer);
for (let i = 0; i < size; i++) {
words32[i] = wordAt(view, i * 4, endian);
}
return words32;
}
function byteAt(str, index) {
if (typeof str === "string") {
return index >= str.length ? 0 : str.charCodeAt(index) & 255;
} else {
return index >= str.byteLength ? 0 : str[index] & 255;
}
}
function wordAt(str, index, endian) {
let word = 0;
if (endian === Endian.Big) {
for (let i = 0; i < 4; i++) {
word += byteAt(str, index + i) << 24 - 8 * i;
}
} else {
for (let i = 0; i < 4; i++) {
word += byteAt(str, index + i) << 8 * i;
}
}
return word;
}
function words32ToByteString(words32) {
return words32.reduce((str, word) => str + word32ToByteString(word), "");
}
function word32ToByteString(word) {
let str = "";
for (let i = 0; i < 4; i++) {
str += String.fromCharCode(word >>> 8 * (3 - i) & 255);
}
return str;
}
function byteStringToHexString(str) {
let hex = "";
for (let i = 0; i < str.length; i++) {
const b = byteAt(str, i);
hex += (b >>> 4).toString(16) + (b & 15).toString(16);
}
return hex.toLowerCase();
}
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/assets.mjs
var AssetGroup = class {
constructor(scope2, adapter2, idle, config, hashes, db, cacheNamePrefix) {
__publicField(this, "scope");
__publicField(this, "adapter");
__publicField(this, "idle");
__publicField(this, "config");
__publicField(this, "hashes");
__publicField(this, "db");
__publicField(this, "inFlightRequests", /* @__PURE__ */ new Map());
__publicField(this, "urls", []);
__publicField(this, "patterns", []);
__publicField(this, "cache");
__publicField(this, "name");
__publicField(this, "metadata");
this.scope = scope2;
this.adapter = adapter2;
this.idle = idle;
this.config = config;
this.hashes = hashes;
this.db = db;
this.name = config.name;
this.urls = config.urls.map((url) => adapter2.normalizeUrl(url));
this.patterns = config.patterns.map((pattern) => new RegExp(pattern));
this.cache = adapter2.caches.open(`${cacheNamePrefix}:${config.name}:cache`);
this.metadata = this.db.open(`${cacheNamePrefix}:${config.name}:meta`, config.cacheQueryOptions);
}
async cacheStatus(url) {
const cache = await this.cache;
const meta = await this.metadata;
const req = this.adapter.newRequest(url);
const res = await cache.match(req, this.config.cacheQueryOptions);
if (res === void 0) {
return UpdateCacheStatus.NOT_CACHED;
}
try {
const data = await meta.read(req.url);
if (!data.used) {
return UpdateCacheStatus.CACHED_BUT_UNUSED;
}
} catch (_) {
}
return UpdateCacheStatus.CACHED;
}
async getCacheNames() {
const [cache, metadata] = await Promise.all([this.cache, this.metadata]);
return [cache.name, metadata.cacheName];
}
async handleFetch(req, _event) {
const url = this.adapter.normalizeUrl(req.url);
if (this.urls.indexOf(url) !== -1 || this.patterns.some((pattern) => pattern.test(url))) {
const cache = await this.cache;
let cachedResponse;
try {
cachedResponse = await cache.match(req, this.config.cacheQueryOptions);
} catch (error) {
throw new SwCriticalError(`Cache is throwing while looking for a match: ${error}`);
}
if (cachedResponse !== void 0) {
if (this.hashes.has(url)) {
return cachedResponse;
} else {
if (await this.needToRevalidate(req, cachedResponse)) {
this.idle.schedule(`revalidate(${cache.name}): ${req.url}`, async () => {
await this.fetchAndCacheOnce(req);
});
}
return cachedResponse;
}
}
const res = await this.fetchAndCacheOnce(this.newRequestWithMetadata(req.url, req));
return res.clone();
} else {
return null;
}
}
async needToRevalidate(req, res) {
if (res.headers.has("Cache-Control")) {
const cacheControl = res.headers.get("Cache-Control");
const cacheDirectives = cacheControl.split(",").map((v) => v.trim()).map((v) => v.split("="));
cacheDirectives.forEach((v) => v[0] = v[0].toLowerCase());
const maxAgeDirective = cacheDirectives.find((v) => v[0] === "max-age");
const cacheAge = maxAgeDirective ? maxAgeDirective[1] : void 0;
if (!cacheAge) {
return true;
}
try {
const maxAge = 1e3 * parseInt(cacheAge);
let ts;
try {
const metaTable = await this.metadata;
ts = (await metaTable.read(req.url)).ts;
} catch (e) {
const date = res.headers.get("Date");
if (date === null) {
return true;
}
ts = Date.parse(date);
}
const age = this.adapter.time - ts;
return age < 0 || age > maxAge;
} catch (e) {
return true;
}
} else if (res.headers.has("Expires")) {
const expiresStr = res.headers.get("Expires");
try {
return this.adapter.time > Date.parse(expiresStr);
} catch (e) {
return true;
}
} else {
return true;
}
}
async fetchFromCacheOnly(url) {
const cache = await this.cache;
const metaTable = await this.metadata;
const request = this.adapter.newRequest(url);
const response = await cache.match(request, this.config.cacheQueryOptions);
if (response === void 0) {
return null;
}
let metadata = void 0;
try {
metadata = await metaTable.read(request.url);
} catch (e) {
}
return { response, metadata };
}
async unhashedResources() {
const cache = await this.cache;
return (await cache.keys()).map((request) => this.adapter.normalizeUrl(request.url)).filter((url) => !this.hashes.has(url));
}
async fetchAndCacheOnce(req, used = true) {
if (this.inFlightRequests.has(req.url)) {
return this.inFlightRequests.get(req.url);
}
const fetchOp = this.fetchFromNetwork(req);
this.inFlightRequests.set(req.url, fetchOp);
try {
const res = await fetchOp;
if (!res.ok) {
throw new Error(`Response not Ok (fetchAndCacheOnce): request for ${req.url} returned response ${res.status} ${res.statusText}`);
}
try {
const cache = await this.cache;
await cache.put(req, res.clone());
if (!this.hashes.has(this.adapter.normalizeUrl(req.url))) {
const meta = { ts: this.adapter.time, used };
const metaTable = await this.metadata;
await metaTable.write(req.url, meta);
}
return res;
} catch (err) {
throw new SwCriticalError(`Failed to update the caches for request to '${req.url}' (fetchAndCacheOnce): ${errorToString(err)}`);
}
} finally {
this.inFlightRequests.delete(req.url);
}
}
async fetchFromNetwork(req, redirectLimit = 3) {
const res = await this.cacheBustedFetchFromNetwork(req);
if (res["redirected"] && !!res.url) {
if (redirectLimit === 0) {
throw new SwCriticalError(`Response hit redirect limit (fetchFromNetwork): request redirected too many times, next is ${res.url}`);
}
return this.fetchFromNetwork(this.newRequestWithMetadata(res.url, req), redirectLimit - 1);
}
return res;
}
async cacheBustedFetchFromNetwork(req) {
const url = this.adapter.normalizeUrl(req.url);
if (this.hashes.has(url)) {
const canonicalHash = this.hashes.get(url);
let response = await this.safeFetch(req);
let makeCacheBustedRequest = response.ok;
if (makeCacheBustedRequest) {
const fetchedHash = sha1Binary(await response.clone().arrayBuffer());
makeCacheBustedRequest = fetchedHash !== canonicalHash;
}
if (makeCacheBustedRequest) {
const cacheBustReq = this.newRequestWithMetadata(this.cacheBust(req.url), req);
response = await this.safeFetch(cacheBustReq);
if (response.ok) {
const cacheBustedHash = sha1Binary(await response.clone().arrayBuffer());
if (canonicalHash !== cacheBustedHash) {
throw new SwCriticalError(`Hash mismatch (cacheBustedFetchFromNetwork): ${req.url}: expected ${canonicalHash}, got ${cacheBustedHash} (after cache busting)`);
}
}
}
if (!response.ok && response.status === 404) {
throw new SwUnrecoverableStateError(`Failed to retrieve hashed resource from the server. (AssetGroup: ${this.config.name} | URL: ${url})`);
}
return response;
} else {
return this.safeFetch(req);
}
}
async maybeUpdate(updateFrom, req, cache) {
const url = this.adapter.normalizeUrl(req.url);
if (this.hashes.has(url)) {
const hash = this.hashes.get(url);
const res = await updateFrom.lookupResourceWithHash(url, hash);
if (res !== null) {
await cache.put(req, res);
return true;
}
}
return false;
}
newRequestWithMetadata(url, options) {
return this.adapter.newRequest(url, { headers: options.headers });
}
cacheBust(url) {
return url + (url.indexOf("?") === -1 ? "?" : "&") + "ngsw-cache-bust=" + Math.random();
}
async safeFetch(req) {
try {
return await this.scope.fetch(req);
} catch (e) {
return this.adapter.newResponse("", {
status: 504,
statusText: "Gateway Timeout"
});
}
}
};
var PrefetchAssetGroup = class extends AssetGroup {
async initializeFully(updateFrom) {
const cache = await this.cache;
await this.urls.reduce(async (previous, url) => {
await previous;
const req = this.adapter.newRequest(url);
let alreadyCached = false;
try {
alreadyCached = await cache.match(req, this.config.cacheQueryOptions) !== void 0;
} catch (error) {
throw new SwCriticalError(`Cache is throwing while looking for a match in a PrefetchAssetGroup: ${error}`);
}
if (alreadyCached) {
return;
}
if (updateFrom !== void 0 && await this.maybeUpdate(updateFrom, req, cache)) {
return;
}
await this.fetchAndCacheOnce(req, false);
}, Promise.resolve());
if (updateFrom !== void 0) {
const metaTable = await this.metadata;
await (await updateFrom.previouslyCachedResources()).filter((url) => this.urls.indexOf(url) !== -1 || this.patterns.some((pattern) => pattern.test(url))).reduce(async (previous, url) => {
await previous;
const req = this.adapter.newRequest(url);
const alreadyCached = await cache.match(req, this.config.cacheQueryOptions) !== void 0;
if (alreadyCached) {
return;
}
const res = await updateFrom.lookupResourceWithoutHash(url);
if (res === null || res.metadata === void 0) {
return;
}
await cache.put(req, res.response);
await metaTable.write(req.url, __spreadProps(__spreadValues({}, res.metadata), { used: false }));
}, Promise.resolve());
}
}
};
var LazyAssetGroup = class extends AssetGroup {
async initializeFully(updateFrom) {
if (updateFrom === void 0) {
return;
}
const cache = await this.cache;
await this.urls.reduce(async (previous, url) => {
await previous;
const req = this.adapter.newRequest(url);
let alreadyCached = false;
try {
alreadyCached = await cache.match(req, this.config.cacheQueryOptions) !== void 0;
} catch (error) {
throw new SwCriticalError(`Cache is throwing while looking for a match in a LazyAssetGroup: ${error}`);
}
if (alreadyCached) {
return;
}
const updated = await this.maybeUpdate(updateFrom, req, cache);
if (this.config.updateMode === "prefetch" && !updated) {
const cacheStatus = await updateFrom.recentCacheStatus(url);
if (cacheStatus !== UpdateCacheStatus.CACHED) {
return;
}
await this.fetchAndCacheOnce(req, false);
}
}, Promise.resolve());
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/data.mjs
var LruList = class {
constructor(state) {
__publicField(this, "state");
if (state === void 0) {
state = {
head: null,
tail: null,
map: {},
count: 0
};
}
this.state = state;
}
get size() {
return this.state.count;
}
pop() {
if (this.state.tail === null) {
return null;
}
const url = this.state.tail;
this.remove(url);
return url;
}
remove(url) {
const node = this.state.map[url];
if (node === void 0) {
return false;
}
if (this.state.head === url) {
if (node.next === null) {
this.state.head = null;
this.state.tail = null;
this.state.map = {};
this.state.count = 0;
return true;
}
const next = this.state.map[node.next];
next.previous = null;
this.state.head = next.url;
node.next = null;
delete this.state.map[url];
this.state.count--;
return true;
}
const previous = this.state.map[node.previous];
previous.next = node.next;
if (node.next !== null) {
this.state.map[node.next].previous = node.previous;
} else {
this.state.tail = node.previous;
}
node.next = null;
node.previous = null;
delete this.state.map[url];
this.state.count--;
return true;
}
accessed(url) {
if (this.state.head === url) {
return;
}
const node = this.state.map[url] || { url, next: null, previous: null };
if (this.state.map[url] !== void 0) {
this.remove(url);
}
if (this.state.head !== null) {
this.state.map[this.state.head].previous = url;
}
node.next = this.state.head;
this.state.head = url;
if (this.state.tail === null) {
this.state.tail = url;
}
this.state.map[url] = node;
this.state.count++;
}
};
var DataGroup = class {
constructor(scope2, adapter2, config, db, debugHandler, cacheNamePrefix) {
__publicField(this, "scope");
__publicField(this, "adapter");
__publicField(this, "config");
__publicField(this, "db");
__publicField(this, "debugHandler");
__publicField(this, "patterns");
__publicField(this, "cache");
__publicField(this, "_lru", null);
__publicField(this, "lruTable");
__publicField(this, "ageTable");
this.scope = scope2;
this.adapter = adapter2;
this.config = config;
this.db = db;
this.debugHandler = debugHandler;
this.patterns = config.patterns.map((pattern) => new RegExp(pattern));
this.cache = adapter2.caches.open(`${cacheNamePrefix}:${config.name}:cache`);
this.lruTable = this.db.open(`${cacheNamePrefix}:${config.name}:lru`, config.cacheQueryOptions);
this.ageTable = this.db.open(`${cacheNamePrefix}:${config.name}:age`, config.cacheQueryOptions);
}
async lru() {
if (this._lru === null) {
const table = await this.lruTable;
try {
this._lru = new LruList(await table.read("lru"));
} catch (e) {
this._lru = new LruList();
}
}
return this._lru;
}
async syncLru() {
if (this._lru === null) {
return;
}
const table = await this.lruTable;
try {
return table.write("lru", this._lru.state);
} catch (err) {
this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`);
}
}
async handleFetch(req, event) {
if (!this.patterns.some((pattern) => pattern.test(req.url))) {
return null;
}
const lru = await this.lru();
switch (req.method) {
case "OPTIONS":
return null;
case "GET":
case "HEAD":
switch (this.config.strategy) {
case "freshness":
return this.handleFetchWithFreshness(req, event, lru);
case "performance":
return this.handleFetchWithPerformance(req, event, lru);
default:
throw new Error(`Unknown strategy: ${this.config.strategy}`);
}
default:
const wasCached = lru.remove(req.url);
if (wasCached) {
await this.clearCacheForUrl(req.url);
}
await this.syncLru();
return this.safeFetch(req);
}
}
async handleFetchWithPerformance(req, event, lru) {
var _a;
const okToCacheOpaque = (_a = this.config.cacheOpaqueResponses) != null ? _a : false;
let res = null;
const fromCache = await this.loadFromCache(req, lru);
if (fromCache !== null) {
res = fromCache.res;
if (this.config.refreshAheadMs !== void 0 && fromCache.age >= this.config.refreshAheadMs) {
event.waitUntil(this.safeCacheResponse(req, this.safeFetch(req), lru, okToCacheOpaque));
}
}
if (res !== null) {
return res;
}
const [timeoutFetch, networkFetch] = this.networkFetchWithTimeout(req);
res = await timeoutFetch;
if (res === void 0) {
res = this.adapter.newResponse(null, { status: 504, statusText: "Gateway Timeout" });
event.waitUntil(this.safeCacheResponse(req, networkFetch, lru, okToCacheOpaque));
} else {
await this.safeCacheResponse(req, res, lru, okToCacheOpaque);
}
return res;
}
async handleFetchWithFreshness(req, event, lru) {
var _a;
const okToCacheOpaque = (_a = this.config.cacheOpaqueResponses) != null ? _a : true;
const [timeoutFetch, networkFetch] = this.networkFetchWithTimeout(req);
let res;
try {
res = await timeoutFetch;
} catch (e) {
res = void 0;
}
if (res === void 0) {
event.waitUntil(this.safeCacheResponse(req, networkFetch, lru, okToCacheOpaque));
const fromCache = await this.loadFromCache(req, lru);
res = fromCache !== null ? fromCache.res : null;
} else {
await this.safeCacheResponse(req, res, lru, okToCacheOpaque);
}
if (res !== null) {
return res;
}
return networkFetch;
}
networkFetchWithTimeout(req) {
if (this.config.timeoutMs !== void 0) {
const networkFetch = this.scope.fetch(req);
const safeNetworkFetch = (async () => {
try {
return await networkFetch;
} catch (e) {
return this.adapter.newResponse(null, {
status: 504,
statusText: "Gateway Timeout"
});
}
})();
const networkFetchUndefinedError = (async () => {
try {
return await networkFetch;
} catch (e) {
return void 0;
}
})();
const timeout = this.adapter.timeout(this.config.timeoutMs);
return [Promise.race([networkFetchUndefinedError, timeout]), safeNetworkFetch];
} else {
const networkFetch = this.safeFetch(req);
return [networkFetch, networkFetch];
}
}
async safeCacheResponse(req, resOrPromise, lru, okToCacheOpaque) {
try {
const res = await resOrPromise;
try {
await this.cacheResponse(req, res, lru, okToCacheOpaque);
} catch (err) {
this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).safeCacheResponse(${req.url}, status: ${res.status})`);
}
} catch (e) {
}
}
async loadFromCache(req, lru) {
const cache = await this.cache;
let res = await cache.match(req, this.config.cacheQueryOptions);
if (res !== void 0) {
try {
const ageTable = await this.ageTable;
const age = this.adapter.time - (await ageTable.read(req.url)).age;
if (age <= this.config.maxAge) {
lru.accessed(req.url);
return { res, age };
}
} catch (e) {
}
lru.remove(req.url);
await this.clearCacheForUrl(req.url);
await this.syncLru();
}
return null;
}
async cacheResponse(req, res, lru, okToCacheOpaque = false) {
if (!(res.ok || okToCacheOpaque && res.type === "opaque")) {
return;
}
if (lru.size >= this.config.maxSize) {
const evictedUrl = lru.pop();
if (evictedUrl !== null) {
await this.clearCacheForUrl(evictedUrl);
}
}
lru.accessed(req.url);
await (await this.cache).put(req, res.clone());
const ageTable = await this.ageTable;
await ageTable.write(req.url, { age: this.adapter.time });
await this.syncLru();
}
async cleanup() {
await Promise.all([
this.cache.then((cache) => this.adapter.caches.delete(cache.name)),
this.ageTable.then((table) => this.db.delete(table.name)),
this.lruTable.then((table) => this.db.delete(table.name))
]);
}
async getCacheNames() {
const [cache, ageTable, lruTable] = await Promise.all([
this.cache,
this.ageTable,
this.lruTable
]);
return [cache.name, ageTable.cacheName, lruTable.cacheName];
}
async clearCacheForUrl(url) {
const [cache, ageTable] = await Promise.all([this.cache, this.ageTable]);
await Promise.all([
cache.delete(this.adapter.newRequest(url, { method: "GET" }), this.config.cacheQueryOptions),
cache.delete(this.adapter.newRequest(url, { method: "HEAD" }), this.config.cacheQueryOptions),
ageTable.delete(url)
]);
}
async safeFetch(req) {
try {
return this.scope.fetch(req);
} catch (e) {
return this.adapter.newResponse(null, {
status: 504,
statusText: "Gateway Timeout"
});
}
}
};
// bazel-out/k8-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/app-version.mjs
var AppVersion = class {
constructor(scope2, adapter2, database, idle, debugHandler, manifest, manifestHash) {
__publicField(this, "scope");
__publicField(this, "adapter");
__publicField(this, "database");
__publicField(this, "debugHandler");
__publicField(this, "manifest");
__publicField(this, "manifestHash");
__publicField(this, "hashTable", /* @__PURE__ */ new Map());
__publicField(this, "assetGroups");
__publicField(this, "dataGroups");
__publicField(this, "navigationUrls");
__publicField(this, "indexUrl");
__publicField(this, "_okay", true);
this.scope = scope2;
this.adapter = adapter2;
this.database = database;
this.debugHandler = debugHandler;
this.manifest = manifest;
this.manifestHash = manifestHash;
this.indexUrl = this.adapter.normalizeUrl(this.manifest.index);
Object.keys(manifest.hashTable).forEach((url) => {
this.hashTable.set(adapter2.normalizeUrl(url), manifest.hashTable[url]);
});
const assetCacheNamePrefix = `${manifestHash}:assets`;
this.assetGroups = (manifest.assetGroups || []).map((config) => {
switch (config.installMode) {
case "prefetch":
return new PrefetchAssetGroup(scope2, adapter2, idle, config, this.hashTable, database, assetCacheNamePrefix);
case "lazy":
return new LazyAssetGroup(scope2, adapter2, idle, config, this.hashTable, database, assetCacheNamePrefix);
}
});
this.dataGroups = (manifest.dataGroups || []).map((config) => new DataGroup(scope2, adapter2, config, database, debugHandler, `${config.version}:data`));
const includeUrls = manifest.navigationUrls.filter((spec) => spec.positive);
const excludeUrls = manifest.navigationUrls.filter((spec) => !spec.positive);
this.navigationUrls = {
include: includeUrls.map((spec) => new RegExp(spec.regex)),
exclude: excludeUrls.map((spec) => new RegExp(spec.regex))
};
}
get okay() {
return this._okay;
}
async initializeFully(updateFrom) {
try {
await this.assetGroups.reduce(async (previous, group) => {
await previous;
return group.initializeFully(updateFrom);
}, Promise.resolve());
} catch (err) {
this._okay = false;
throw err;
}
}
async handleFetch(req, event) {
const asset = await this.assetGroups.reduce(async (potentialResponse, group) => {
const resp = await potentialResponse;
if (resp !== null) {
return resp;
}
return group.handleFetch(req, event);
}, Promise.resolve(null));
if (asset !== null) {
return asset;
}
const data = await this.dataGroups.reduce(async (potentialResponse, group) => {
const resp = await potentialResponse;
if (resp !== null) {
return resp;
}
return group.handleFetch(req, event);
}, Promise.resolve(null));
if (data !== null) {
return data;
}
if (this.adapter.normalizeUrl(req.url) !== this.indexUrl && this.isNavigationRequest(req)) {
if (this.manifest.navigationRequestStrategy === "freshness") {
try {
return await this.scope.fetch(req);
} catch (e) {
}
}
return this.handleFetch(this.adapter.newRequest(this.indexUrl), event);