PageSourceSearch

https://www.genotek.ru/ngsw-worker.js

js genotek.ru collected 2026-09-27 20:55:38 UTC 67,992 bytes, 1,863 lines download raw bytes

1(() => {
2  var __defProp = Object.defineProperty;
3  var __defProps = Object.defineProperties;
4  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6  var __hasOwnProp = Object.prototype.hasOwnProperty;
7  var __propIsEnum = Object.prototype.propertyIsEnumerable;
8  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9  var __spreadValues = (a, b) => {
10    for (var prop in b || (b = {}))
11      if (__hasOwnProp.call(b, prop))
12        __defNormalProp(a, prop, b[prop]);
13    if (__getOwnPropSymbols)
14      for (var prop of __getOwnPropSymbols(b)) {
15        if (__propIsEnum.call(b, prop))
16          __defNormalProp(a, prop, b[prop]);
17      }
18    return a;
19  };
20  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
22  
22// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/named-cache-storage.mjs
23  var NamedCacheStorage = class {
24    constructor(original, cacheNamePrefix) {
25      this.original = original;
26      this.cacheNamePrefix = cacheNamePrefix;
27    }
28    delete(cacheName) {
29      return this.original.delete(`${this.cacheNamePrefix}:${cacheName}`);
30    }
31    has(cacheName) {
32      return this.original.has(`${this.cacheNamePrefix}:${cacheName}`);
33    }
34    async keys() {
35      const prefix = `${this.cacheNamePrefix}:`;
36      const allCacheNames = await this.original.keys();
37      const ownCacheNames = allCacheNames.filter((name) => name.startsWith(prefix));
38      return ownCacheNames.map((name) => name.slice(prefix.length));
39    }
40    match(request, options) {
41      return this.original.match(request, options);
42    }
43    async open(cacheName) {
44      const cache = await this.original.open(`${this.cacheNamePrefix}:${cacheName}`);
45      return Object.assign(cache, { name: cacheName });
46    }
47  };
48
49  
49// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/adapter.mjs
50  var Adapter = class {
51    constructor(scopeUrl, caches) {
52      this.scopeUrl = scopeUrl;
53      const parsedScopeUrl = this.parseUrl(this.scopeUrl);
54      this.origin = parsedScopeUrl.origin;
55      this.caches = new NamedCacheStorage(caches, `ngsw:${parsedScopeUrl.path}`);
56    }
57    newRequest(input, init) {
58      return new Request(input, init);
59    }
60    newResponse(body, init) {
61      return new Response(body, init);
62    }
63    newHeaders(headers) {
64      return new Headers(headers);
65    }
66    isClient(source) {
67      return source instanceof Client;
68    }
69    get time() {
70      return Date.now();
71    }
72    normalizeUrl(url) {
73      const parsed = this.parseUrl(url, this.scopeUrl);
74      return parsed.origin === this.origin ? parsed.path : url;
75    }
76    parseUrl(url, relativeTo) {
77      const parsed = !relativeTo ? new URL(url) : new URL(url, relativeTo);
78      return { origin: parsed.origin, path: parsed.pathname, search: parsed.search };
79    }
80    timeout(ms) {
81      return new Promise((resolve) => {
82        setTimeout(() => resolve(), ms);
83      });
84    }
85  };
86
87  
87// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/database.mjs
88  var NotFound = class {
89    constructor(table, key) {
90      this.table = table;
91      this.key = key;
92    }
93  };
94
95  
95// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/db-cache.mjs
96  var CacheDatabase = class {
97    constructor(adapter2) {
98      this.adapter = adapter2;
99      this.cacheNamePrefix = "db";
100      this.tables = /* @__PURE__ */ new Map();
101    }
102    "delete"(name) {
103      if (this.tables.has(name)) {
104        this.tables.delete(name);
105      }
106      return this.adapter.caches.delete(`${this.cacheNamePrefix}:${name}`);
107    }
108    async list() {
109      const prefix = `${this.cacheNamePrefix}:`;
110      const allCacheNames = await this.adapter.caches.keys();
111      const dbCacheNames = allCacheNames.filter((name) => name.startsWith(prefix));
112      return dbCacheNames.map((name) => name.slice(prefix.length));
113    }
114    async open(name, cacheQueryOptions) {
115      if (!this.tables.has(name)) {
116        const cache = await this.adapter.caches.open(`${this.cacheNamePrefix}:${name}`);
117        const table = new CacheTable(name, cache, this.adapter, cacheQueryOptions);
118        this.tables.set(name, table);
119      }
120      return this.tables.get(name);
121    }
122  };
123  var CacheTable = class {
124    constructor(name, cache, adapter2, cacheQueryOptions) {
125      this.name = name;
126      this.cache = cache;
127      this.adapter = adapter2;
128      this.cacheQueryOptions = cacheQueryOptions;
129      this.cacheName = this.cache.name;
130    }
131    request(key) {
132      return this.adapter.newRequest("/" + key);
133    }
134    "delete"(key) {
135      return this.cache.delete(this.request(key), this.cacheQueryOptions);
136    }
137    keys() {
138      return this.cache.keys().then((requests) => requests.map((req) => req.url.slice(1)));
139    }
140    read(key) {
141      return this.cache.match(this.request(key), this.cacheQueryOptions).then((res) => {
142        if (res === void 0) {
143          return Promise.reject(new NotFound(this.name, key));
144        }
145        return res.json();
146      });
147    }
148    write(key, value) {
149      return this.cache.put(this.request(key), this.adapter.newResponse(JSON.stringify(value)));
150    }
151  };
152
153  
153// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/api.mjs
154  var UpdateCacheStatus;
155  (function(UpdateCacheStatus2) {
156    UpdateCacheStatus2[UpdateCacheStatus2["NOT_CACHED"] = 0] = "NOT_CACHED";
157    UpdateCacheStatus2[UpdateCacheStatus2["CACHED_BUT_UNUSED"] = 1] = "CACHED_BUT_UNUSED";
158    UpdateCacheStatus2[UpdateCacheStatus2["CACHED"] = 2] = "CACHED";
159  })(UpdateCacheStatus || (UpdateCacheStatus = {}));
160
161  
161// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/error.mjs
162  var SwCriticalError = class extends Error {
163    constructor() {
164      super(...arguments);
165      this.isCritical = true;
166    }
167  };
168  function errorToString(error) {
169    if (error instanceof Error) {
170      return `${error.message}
171${error.stack}`;
172    } else {
173      return `${error}`;
174    }
175  }
176  var SwUnrecoverableStateError = class extends SwCriticalError {
177    constructor() {
178      super(...arguments);
179      this.isUnrecoverableState = true;
180    }
181  };
182
183  
183// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/sha1.mjs
184  function sha1(str) {
185    const utf8 = str;
186    const words32 = stringToWords32(utf8, Endian.Big);
187    return _sha1(words32, utf8.length * 8);
188  }
189  function sha1Binary(buffer) {
190    const words32 = arrayBufferToWords32(buffer, Endian.Big);
191    return _sha1(words32, buffer.byteLength * 8);
192  }
193  function _sha1(words32, len) {
194    const w = [];
195    let [a, b, c, d, e] = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
196    words32[len >> 5] |= 128 << 24 - len % 32;
197    words32[(len + 64 >> 9 << 4) + 15] = len;
198    for (let i = 0; i < words32.length; i += 16) {
199      const [h0, h1, h2, h3, h4] = [a, b, c, d, e];
200      for (let j = 0; j < 80; j++) {
201        if (j < 16) {
202          w[j] = words32[i + j];
203        } else {
204          w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
205        }
206        const [f, k] = fk(j, b, c, d);
207        const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
208        [e, d, c, b, a] = [d, c, rol32(b, 30), a, temp];
209      }
210      [a, b, c, d, e] = [add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)];
211    }
212    return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
213  }
214  function add32(a, b) {
215    return add32to64(a, b)[1];
216  }
217  function add32to64(a, b) {
218    const low = (a & 65535) + (b & 65535);
219    const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
220    return [high >>> 16, high << 16 | low & 65535];
221  }
222  function rol32(a, count) {
223    return a << count | a >>> 32 - count;
224  }
225  var Endian;
226  (function(Endian2) {
227    Endian2[Endian2["Little"] = 0] = "Little";
228    Endian2[Endian2["Big"] = 1] = "Big";
229  })(Endian || (Endian = {}));
230  function fk(index, b, c, d) {
231    if (index < 20) {
232      return [b & c | ~b & d, 1518500249];
233    }
234    if (index < 40) {
235      return [b ^ c ^ d, 1859775393];
236    }
237    if (index < 60) {
238      return [b & c | b & d | c & d, 2400959708];
239    }
240    return [b ^ c ^ d, 3395469782];
241  }
242  function stringToWords32(str, endian) {
243    const size = str.length + 3 >>> 2;
244    const words32 = [];
245    for (let i = 0; i < size; i++) {
246      words32[i] = wordAt(str, i * 4, endian);
247    }
248    return words32;
249  }
250  function arrayBufferToWords32(buffer, endian) {
251    const size = buffer.byteLength + 3 >>> 2;
252    const words32 = [];
253    const view = new Uint8Array(buffer);
254    for (let i = 0; i < size; i++) {
255      words32[i] = wordAt(view, i * 4, endian);
256    }
257    return words32;
258  }
259  function byteAt(str, index) {
260    if (typeof str === "string") {
261      return index >= str.length ? 0 : str.charCodeAt(index) & 255;
262    } else {
263      return index >= str.byteLength ? 0 : str[index] & 255;
264    }
265  }
266  function wordAt(str, index, endian) {
267    let word = 0;
268    if (endian === Endian.Big) {
269      for (let i = 0; i < 4; i++) {
270        word += byteAt(str, index + i) << 24 - 8 * i;
271      }
272    } else {
273      for (let i = 0; i < 4; i++) {
274        word += byteAt(str, index + i) << 8 * i;
275      }
276    }
277    return word;
278  }
279  function words32ToByteString(words32) {
280    return words32.reduce((str, word) => str + word32ToByteString(word), "");
281  }
282  function word32ToByteString(word) {
283    let str = "";
284    for (let i = 0; i < 4; i++) {
285      str += String.fromCharCode(word >>> 8 * (3 - i) & 255);
286    }
287    return str;
288  }
289  function byteStringToHexString(str) {
290    let hex = "";
291    for (let i = 0; i < str.length; i++) {
292      const b = byteAt(str, i);
293      hex += (b >>> 4).toString(16) + (b & 15).toString(16);
294    }
295    return hex.toLowerCase();
296  }
297
298  
298// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/assets.mjs
299  var AssetGroup = class {
300    constructor(scope2, adapter2, idle, config, hashes, db, cacheNamePrefix) {
301      this.scope = scope2;
302      this.adapter = adapter2;
303      this.idle = idle;
304      this.config = config;
305      this.hashes = hashes;
306      this.db = db;
307      this.inFlightRequests = /* @__PURE__ */ new Map();
308      this.urls = [];
309      this.patterns = [];
310      this.name = config.name;
311      this.urls = config.urls.map((url) => adapter2.normalizeUrl(url));
312      this.patterns = config.patterns.map((pattern) => new RegExp(pattern));
313      this.cache = adapter2.caches.open(`${cacheNamePrefix}:${config.name}:cache`);
314      this.metadata = this.db.open(`${cacheNamePrefix}:${config.name}:meta`, config.cacheQueryOptions);
315    }
316    async cacheStatus(url) {
317      const cache = await this.cache;
318      const meta = await this.metadata;
319      const req = this.adapter.newRequest(url);
320      const res = await cache.match(req, this.config.cacheQueryOptions);
321      if (res === void 0) {
322        return UpdateCacheStatus.NOT_CACHED;
323      }
324      try {
325        const data = await meta.read(req.url);
326        if (!data.used) {
327          return UpdateCacheStatus.CACHED_BUT_UNUSED;
328        }
329      } catch (_) {
330      }
331      return UpdateCacheStatus.CACHED;
332    }
333    async getCacheNames() {
334      const [cache, metadata] = await Promise.all([this.cache, this.metadata]);
335      return [cache.name, metadata.cacheName];
336    }
337    async handleFetch(req, _event) {
338      const url = this.adapter.normalizeUrl(req.url);
339      if (this.urls.indexOf(url) !== -1 || this.patterns.some((pattern) => pattern.test(url))) {
340        const cache = await this.cache;
341        let cachedResponse;
342        try {
343          cachedResponse = await cache.match(req, this.config.cacheQueryOptions);
344        } catch (error) {
345          throw new SwCriticalError(`Cache is throwing while looking for a match: ${error}`);
346        }
347        if (cachedResponse !== void 0) {
348          if (this.hashes.has(url)) {
349            return cachedResponse;
350          } else {
351            if (await this.needToRevalidate(req, cachedResponse)) {
352              this.idle.schedule(`revalidate(${cache.name}): ${req.url}`, async () => {
353                await this.fetchAndCacheOnce(req);
354              });
355            }
356            return cachedResponse;
357          }
358        }
359        const res = await this.fetchAndCacheOnce(this.newRequestWithMetadata(req.url, req));
360        return res.clone();
361      } else {
362        return null;
363      }
364    }
365    async needToRevalidate(req, res) {
366      if (res.headers.has("Cache-Control")) {
367        const cacheControl = res.headers.get("Cache-Control");
368        const cacheDirectives = cacheControl.split(",").map((v) => v.trim()).map((v) => v.split("="));
369        cacheDirectives.forEach((v) => v[0] = v[0].toLowerCase());
370        const maxAgeDirective = cacheDirectives.find((v) => v[0] === "max-age");
371        const cacheAge = maxAgeDirective ? maxAgeDirective[1] : void 0;
372        if (!cacheAge) {
373          return true;
374        }
375        try {
376          const maxAge = 1e3 * parseInt(cacheAge);
377          let ts;
378          try {
379            const metaTable = await this.metadata;
380            ts = (await metaTable.read(req.url)).ts;
381          } catch (e) {
382            const date = res.headers.get("Date");
383            if (date === null) {
384              return true;
385            }
386            ts = Date.parse(date);
387          }
388          const age = this.adapter.time - ts;
389          return age < 0 || age > maxAge;
390        } catch (e) {
391          return true;
392        }
393      } else if (res.headers.has("Expires")) {
394        const expiresStr = res.headers.get("Expires");
395        try {
396          return this.adapter.time > Date.parse(expiresStr);
397        } catch (e) {
398          return true;
399        }
400      } else {
401        return true;
402      }
403    }
404    async fetchFromCacheOnly(url) {
405      const cache = await this.cache;
406      const metaTable = await this.metadata;
407      const request = this.adapter.newRequest(url);
408      const response = await cache.match(request, this.config.cacheQueryOptions);
409      if (response === void 0) {
410        return null;
411      }
412      let metadata = void 0;
413      try {
414        metadata = await metaTable.read(request.url);
415      } catch (e) {
416      }
417      return { response, metadata };
418    }
419    async unhashedResources() {
420      const cache = await this.cache;
421      return (await cache.keys()).map((request) => this.adapter.normalizeUrl(request.url)).filter((url) => !this.hashes.has(url));
422    }
423    async fetchAndCacheOnce(req, used = true) {
424      if (this.inFlightRequests.has(req.url)) {
425        return this.inFlightRequests.get(req.url);
426      }
427      const fetchOp = this.fetchFromNetwork(req);
428      this.inFlightRequests.set(req.url, fetchOp);
429      try {
430        const res = await fetchOp;
431        if (!res.ok) {
432          throw new Error(`Response not Ok (fetchAndCacheOnce): request for ${req.url} returned response ${res.status} ${res.statusText}`);
433        }
434        try {
435          const cache = await this.cache;
436          await cache.put(req, res.clone());
437          if (!this.hashes.has(this.adapter.normalizeUrl(req.url))) {
438            const meta = { ts: this.adapter.time, used };
439            const metaTable = await this.metadata;
440            await metaTable.write(req.url, meta);
441          }
442          return res;
443        } catch (err) {
444          throw new SwCriticalError(`Failed to update the caches for request to '${req.url}' (fetchAndCacheOnce): ${errorToString(err)}`);
445        }
446      } finally {
447        this.inFlightRequests.delete(req.url);
448      }
449    }
450    async fetchFromNetwork(req, redirectLimit = 3) {
451      const res = await this.cacheBustedFetchFromNetwork(req);
452      if (res["redirected"] && !!res.url) {
453        if (redirectLimit === 0) {
454          throw new SwCriticalError(`Response hit redirect limit (fetchFromNetwork): request redirected too many times, next is ${res.url}`);
455        }
456        return this.fetchFromNetwork(this.newRequestWithMetadata(res.url, req), redirectLimit - 1);
457      }
458      return res;
459    }
460    async cacheBustedFetchFromNetwork(req) {
461      const url = this.adapter.normalizeUrl(req.url);
462      if (this.hashes.has(url)) {
463        const canonicalHash = this.hashes.get(url);
464        let response = await this.safeFetch(req);
465        let makeCacheBustedRequest = response.ok;
466        if (makeCacheBustedRequest) {
467          const fetchedHash = sha1Binary(await response.clone().arrayBuffer());
468          makeCacheBustedRequest = fetchedHash !== canonicalHash;
469        }
470        if (makeCacheBustedRequest) {
471          const cacheBustReq = this.newRequestWithMetadata(this.cacheBust(req.url), req);
472          response = await this.safeFetch(cacheBustReq);
473          if (response.ok) {
474            const cacheBustedHash = sha1Binary(await response.clone().arrayBuffer());
475            if (canonicalHash !== cacheBustedHash) {
476              throw new SwCriticalError(`Hash mismatch (cacheBustedFetchFromNetwork): ${req.url}: expected ${canonicalHash}, got ${cacheBustedHash} (after cache busting)`);
477            }
478          }
479        }
480        if (!response.ok && response.status === 404) {
481          throw new SwUnrecoverableStateError(`Failed to retrieve hashed resource from the server. (AssetGroup: ${this.config.name} | URL: ${url})`);
482        }
483        return response;
484      } else {
485        return this.safeFetch(req);
486      }
487    }
488    async maybeUpdate(updateFrom, req, cache) {
489      const url = this.adapter.normalizeUrl(req.url);
490      if (this.hashes.has(url)) {
491        const hash = this.hashes.get(url);
492        const res = await updateFrom.lookupResourceWithHash(url, hash);
493        if (res !== null) {
494          await cache.put(req, res);
495          return true;
496        }
497      }
498      return false;
499    }
500    newRequestWithMetadata(url, options) {
501      return this.adapter.newRequest(url, { headers: options.headers });
502    }
503    cacheBust(url) {
504      return url + (url.indexOf("?") === -1 ? "?" : "&") + "ngsw-cache-bust=" + Math.random();
505    }
506    async safeFetch(req) {
507      try {
508        return await this.scope.fetch(req);
509      } catch (e) {
510        return this.adapter.newResponse("", {
511          status: 504,
512          statusText: "Gateway Timeout"
513        });
514      }
515    }
516  };
517  var PrefetchAssetGroup = class extends AssetGroup {
518    async initializeFully(updateFrom) {
519      const cache = await this.cache;
520      await this.urls.reduce(async (previous, url) => {
521        await previous;
522        const req = this.adapter.newRequest(url);
523        let alreadyCached = false;
524        try {
525          alreadyCached = await cache.match(req, this.config.cacheQueryOptions) !== void 0;
526        } catch (error) {
527          throw new SwCriticalError(`Cache is throwing while looking for a match in a PrefetchAssetGroup: ${error}`);
528        }
529        if (alreadyCached) {
530          return;
531        }
532        if (updateFrom !== void 0 && await this.maybeUpdate(updateFrom, req, cache)) {
533          return;
534        }
535        await this.fetchAndCacheOnce(req, false);
536      }, Promise.resolve());
537      if (updateFrom !== void 0) {
538        const metaTable = await this.metadata;
539        await (await updateFrom.previouslyCachedResources()).filter((url) => this.urls.indexOf(url) !== -1 || this.patterns.some((pattern) => pattern.test(url))).reduce(async (previous, url) => {
540          await previous;
541          const req = this.adapter.newRequest(url);
542          const alreadyCached = await cache.match(req, this.config.cacheQueryOptions) !== void 0;
543          if (alreadyCached) {
544            return;
545          }
546          const res = await updateFrom.lookupResourceWithoutHash(url);
547          if (res === null || res.metadata === void 0) {
548            return;
549          }
550          await cache.put(req, res.response);
551          await metaTable.write(req.url, __spreadProps(__spreadValues({}, res.metadata), { used: false }));
552        }, Promise.resolve());
553      }
554    }
555  };
556  var LazyAssetGroup = class extends AssetGroup {
557    async initializeFully(updateFrom) {
558      if (updateFrom === void 0) {
559        return;
560      }
561      const cache = await this.cache;
562      await this.urls.reduce(async (previous, url) => {
563        await previous;
564        const req = this.adapter.newRequest(url);
565        let alreadyCached = false;
566        try {
567          alreadyCached = await cache.match(req, this.config.cacheQueryOptions) !== void 0;
568        } catch (error) {
569          throw new SwCriticalError(`Cache is throwing while looking for a match in a LazyAssetGroup: ${error}`);
570        }
571        if (alreadyCached) {
572          return;
573        }
574        const updated = await this.maybeUpdate(updateFrom, req, cache);
575        if (this.config.updateMode === "prefetch" && !updated) {
576          const cacheStatus = await updateFrom.recentCacheStatus(url);
577          if (cacheStatus !== UpdateCacheStatus.CACHED) {
578            return;
579          }
580          await this.fetchAndCacheOnce(req, false);
581        }
582      }, Promise.resolve());
583    }
584  };
585
586  
586// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/data.mjs
587  var LruList = class {
588    constructor(state) {
589      if (state === void 0) {
590        state = {
591          head: null,
592          tail: null,
593          map: {},
594          count: 0
595        };
596      }
597      this.state = state;
598    }
599    get size() {
600      return this.state.count;
601    }
602    pop() {
603      if (this.state.tail === null) {
604        return null;
605      }
606      const url = this.state.tail;
607      this.remove(url);
608      return url;
609    }
610    remove(url) {
611      const node = this.state.map[url];
612      if (node === void 0) {
613        return false;
614      }
615      if (this.state.head === url) {
616        if (node.next === null) {
617          this.state.head = null;
618          this.state.tail = null;
619          this.state.map = {};
620          this.state.count = 0;
621          return true;
622        }
623        const next = this.state.map[node.next];
624        next.previous = null;
625        this.state.head = next.url;
626        node.next = null;
627        delete this.state.map[url];
628        this.state.count--;
629        return true;
630      }
631      const previous = this.state.map[node.previous];
632      previous.next = node.next;
633      if (node.next !== null) {
634        this.state.map[node.next].previous = node.previous;
635      } else {
636        this.state.tail = node.previous;
637      }
638      node.next = null;
639      node.previous = null;
640      delete this.state.map[url];
641      this.state.count--;
642      return true;
643    }
644    accessed(url) {
645      if (this.state.head === url) {
646        return;
647      }
648      const node = this.state.map[url] || { url, next: null, previous: null };
649      if (this.state.map[url] !== void 0) {
650        this.remove(url);
651      }
652      if (this.state.head !== null) {
653        this.state.map[this.state.head].previous = url;
654      }
655      node.next = this.state.head;
656      this.state.head = url;
657      if (this.state.tail === null) {
658        this.state.tail = url;
659      }
660      this.state.map[url] = node;
661      this.state.count++;
662    }
663  };
664  var DataGroup = class {
665    constructor(scope2, adapter2, config, db, debugHandler, cacheNamePrefix) {
666      this.scope = scope2;
667      this.adapter = adapter2;
668      this.config = config;
669      this.db = db;
670      this.debugHandler = debugHandler;
671      this._lru = null;
672      this.patterns = config.patterns.map((pattern) => new RegExp(pattern));
673      this.cache = adapter2.caches.open(`${cacheNamePrefix}:${config.name}:cache`);
674      this.lruTable = this.db.open(`${cacheNamePrefix}:${config.name}:lru`, config.cacheQueryOptions);
675      this.ageTable = this.db.open(`${cacheNamePrefix}:${config.name}:age`, config.cacheQueryOptions);
676    }
677    async lru() {
678      if (this._lru === null) {
679        const table = await this.lruTable;
680        try {
681          this._lru = new LruList(await table.read("lru"));
682        } catch (e) {
683          this._lru = new LruList();
684        }
685      }
686      return this._lru;
687    }
688    async syncLru() {
689      if (this._lru === null) {
690        return;
691      }
692      const table = await this.lruTable;
693      try {
694        return table.write("lru", this._lru.state);
695      } catch (err) {
696        this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).syncLru()`);
697      }
698    }
699    async handleFetch(req, event) {
700      if (!this.patterns.some((pattern) => pattern.test(req.url))) {
701        return null;
702      }
703      const lru = await this.lru();
704      switch (req.method) {
705        case "OPTIONS":
706          return null;
707        case "GET":
708        case "HEAD":
709          switch (this.config.strategy) {
710            case "freshness":
711              return this.handleFetchWithFreshness(req, event, lru);
712            case "performance":
713              return this.handleFetchWithPerformance(req, event, lru);
714            default:
715              throw new Error(`Unknown strategy: ${this.config.strategy}`);
716          }
717        default:
718          const wasCached = lru.remove(req.url);
719          if (wasCached) {
720            await this.clearCacheForUrl(req.url);
721          }
722          await this.syncLru();
723          return this.safeFetch(req);
724      }
725    }
726    async handleFetchWithPerformance(req, event, lru) {
727      var _a;
728      const okToCacheOpaque = (_a = this.config.cacheOpaqueResponses) != null ? _a : false;
729      let res = null;
730      const fromCache = await this.loadFromCache(req, lru);
731      if (fromCache !== null) {
732        res = fromCache.res;
733        if (this.config.refreshAheadMs !== void 0 && fromCache.age >= this.config.refreshAheadMs) {
734          event.waitUntil(this.safeCacheResponse(req, this.safeFetch(req), lru, okToCacheOpaque));
735        }
736      }
737      if (res !== null) {
738        return res;
739      }
740      const [timeoutFetch, networkFetch] = this.networkFetchWithTimeout(req);
741      res = await timeoutFetch;
742      if (res === void 0) {
743        res = this.adapter.newResponse(null, { status: 504, statusText: "Gateway Timeout" });
744        event.waitUntil(this.safeCacheResponse(req, networkFetch, lru, okToCacheOpaque));
745      } else {
746        await this.safeCacheResponse(req, res, lru, okToCacheOpaque);
747      }
748      return res;
749    }
750    async handleFetchWithFreshness(req, event, lru) {
751      var _a;
752      const okToCacheOpaque = (_a = this.config.cacheOpaqueResponses) != null ? _a : true;
753      const [timeoutFetch, networkFetch] = this.networkFetchWithTimeout(req);
754      let res;
755      try {
756        res = await timeoutFetch;
757      } catch (e) {
758        res = void 0;
759      }
760      if (res === void 0) {
761        event.waitUntil(this.safeCacheResponse(req, networkFetch, lru, okToCacheOpaque));
762        const fromCache = await this.loadFromCache(req, lru);
763        res = fromCache !== null ? fromCache.res : null;
764      } else {
765        await this.safeCacheResponse(req, res, lru, okToCacheOpaque);
766      }
767      if (res !== null) {
768        return res;
769      }
770      return networkFetch;
771    }
772    networkFetchWithTimeout(req) {
773      if (this.config.timeoutMs !== void 0) {
774        const networkFetch = this.scope.fetch(req);
775        const safeNetworkFetch = (async () => {
776          try {
777            return await networkFetch;
778          } catch (e) {
779            return this.adapter.newResponse(null, {
780              status: 504,
781              statusText: "Gateway Timeout"
782            });
783          }
784        })();
785        const networkFetchUndefinedError = (async () => {
786          try {
787            return await networkFetch;
788          } catch (e) {
789            return void 0;
790          }
791        })();
792        const timeout = this.adapter.timeout(this.config.timeoutMs);
793        return [Promise.race([networkFetchUndefinedError, timeout]), safeNetworkFetch];
794      } else {
795        const networkFetch = this.safeFetch(req);
796        return [networkFetch, networkFetch];
797      }
798    }
799    async safeCacheResponse(req, resOrPromise, lru, okToCacheOpaque) {
800      try {
801        const res = await resOrPromise;
802        try {
803          await this.cacheResponse(req, res, lru, okToCacheOpaque);
804        } catch (err) {
805          this.debugHandler.log(err, `DataGroup(${this.config.name}@${this.config.version}).safeCacheResponse(${req.url}, status: ${res.status})`);
806        }
807      } catch (e) {
808      }
809    }
810    async loadFromCache(req, lru) {
811      const cache = await this.cache;
812      let res = await cache.match(req, this.config.cacheQueryOptions);
813      if (res !== void 0) {
814        try {
815          const ageTable = await this.ageTable;
816          const age = this.adapter.time - (await ageTable.read(req.url)).age;
817          if (age <= this.config.maxAge) {
818            lru.accessed(req.url);
819            return { res, age };
820          }
821        } catch (e) {
822        }
823        lru.remove(req.url);
824        await this.clearCacheForUrl(req.url);
825        await this.syncLru();
826      }
827      return null;
828    }
829    async cacheResponse(req, res, lru, okToCacheOpaque = false) {
830      if (!(res.ok || okToCacheOpaque && res.type === "opaque")) {
831        return;
832      }
833      if (lru.size >= this.config.maxSize) {
834        const evictedUrl = lru.pop();
835        if (evictedUrl !== null) {
836          await this.clearCacheForUrl(evictedUrl);
837        }
838      }
839      lru.accessed(req.url);
840      await (await this.cache).put(req, res.clone());
841      const ageTable = await this.ageTable;
842      await ageTable.write(req.url, { age: this.adapter.time });
843      await this.syncLru();
844    }
845    async cleanup() {
846      await Promise.all([
847        this.cache.then((cache) => this.adapter.caches.delete(cache.name)),
848        this.ageTable.then((table) => this.db.delete(table.name)),
849        this.lruTable.then((table) => this.db.delete(table.name))
850      ]);
851    }
852    async getCacheNames() {
853      const [cache, ageTable, lruTable] = await Promise.all([
854        this.cache,
855        this.ageTable,
856        this.lruTable
857      ]);
858      return [cache.name, ageTable.cacheName, lruTable.cacheName];
859    }
860    async clearCacheForUrl(url) {
861      const [cache, ageTable] = await Promise.all([this.cache, this.ageTable]);
862      await Promise.all([
863        cache.delete(this.adapter.newRequest(url, { method: "GET" }), this.config.cacheQueryOptions),
864        cache.delete(this.adapter.newRequest(url, { method: "HEAD" }), this.config.cacheQueryOptions),
865        ageTable.delete(url)
866      ]);
867    }
868    async safeFetch(req) {
869      try {
870        return this.scope.fetch(req);
871      } catch (e) {
872        return this.adapter.newResponse(null, {
873          status: 504,
874          statusText: "Gateway Timeout"
875        });
876      }
877    }
878  };
879
880  
880// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/app-version.mjs
881  var BACKWARDS_COMPATIBILITY_NAVIGATION_URLS = [
882    { positive: true, regex: "^/.*$" },
883    { positive: false, regex: "^/.*\\.[^/]*$" },
884    { positive: false, regex: "^/.*__" }
885  ];
886  var AppVersion = class {
887    get okay() {
888      return this._okay;
889    }
890    constructor(scope2, adapter2, database, idle, debugHandler, manifest, manifestHash) {
891      this.scope = scope2;
892      this.adapter = adapter2;
893      this.database = database;
894      this.debugHandler = debugHandler;
895      this.manifest = manifest;
896      this.manifestHash = manifestHash;
897      this.hashTable = /* @__PURE__ */ new Map();
898      this._okay = true;
899      this.indexUrl = this.adapter.normalizeUrl(this.manifest.index);
900      Object.keys(manifest.hashTable).forEach((url) => {
901        this.hashTable.set(adapter2.normalizeUrl(url), manifest.hashTable[url]);
902      });
903      const assetCacheNamePrefix = `${manifestHash}:assets`;
904      this.assetGroups = (manifest.assetGroups || []).map((config) => {
905        switch (config.installMode) {
906          case "prefetch":
907            return new PrefetchAssetGroup(scope2, adapter2, idle, config, this.hashTable, database, assetCacheNamePrefix);
908          case "lazy":
909            return new LazyAssetGroup(scope2, adapter2, idle, config, this.hashTable, database, assetCacheNamePrefix);
910        }
911      });
912      this.dataGroups = (manifest.dataGroups || []).map((config) => new DataGroup(scope2, adapter2, config, database, debugHandler, `${config.version}:data`));
913      manifest.navigationUrls = manifest.navigationUrls || BACKWARDS_COMPATIBILITY_NAVIGATION_URLS;
914      const includeUrls = manifest.navigationUrls.filter((spec) => spec.positive);
915      const excludeUrls = manifest.navigationUrls.filter((spec) => !spec.positive);
916      this.navigationUrls = {
917        include: includeUrls.map((spec) => new RegExp(spec.regex)),
918        exclude: excludeUrls.map((spec) => new RegExp(spec.regex))
919      };
920    }
921    async initializeFully(updateFrom) {
922      try {
923        await this.assetGroups.reduce(async (previous, group) => {
924          await previous;
925          return group.initializeFully(updateFrom);
926        }, Promise.resolve());
927      } catch (err) {
928        this._okay = false;
929        throw err;
930      }
931    }
932    async handleFetch(req, event) {
933      const asset = await this.assetGroups.reduce(async (potentialResponse, group) => {
934        const resp = await potentialResponse;
935        if (resp !== null) {
936          return resp;
937        }
938        return group.handleFetch(req, event);
939      }, Promise.resolve(null));
940      if (asset !== null) {
941        return asset;
942      }
943      const data = await this.dataGroups.reduce(async (potentialResponse, group) => {
944        const resp = await potentialResponse;
945        if (resp !== null) {
946          return resp;
947        }
948        return group.handleFetch(req, event);
949      }, Promise.resolve(null));
950      if (data !== null) {
951        return data;
952      }
953      if (this.adapter.normalizeUrl(req.url) !== this.indexUrl && this.isNavigationRequest(req)) {
954        if (this.manifest.navigationRequestStrategy === "freshness") {
955          try {
956            return await this.scope.fetch(req);
957          } catch (e) {
958          }
959        }
960        return this.handleFetch(this.adapter.newRequest(this.indexUrl), event);
961      }
962      return null;
963    }
964    isNavigationRequest(req) {
965      if (req.method !== "GET" || req.mode !== "navigate") {
966        return false;
967      }
968      if (!this.acceptsTextHtml(req)) {
969        return false;
970      }
971      const urlPrefix = this.scope.registration.scope.replace(/\/$/, "");
972      const url = req.url.startsWith(urlPrefix) ? req.url.slice(urlPrefix.length) : req.url;
973      const urlWithoutQueryOrHash = url.replace(/[?#].*$/, "");
974      return this.navigationUrls.include.some((regex) => regex.test(urlWithoutQueryOrHash)) && !this.navigationUrls.exclude.some((regex) => regex.test(urlWithoutQueryOrHash));
975    }
976    async lookupResourceWithHash(url, hash) {
977      if (!this.hashTable.has(url)) {
978        return null;
979      }
980      if (this.hashTable.get(url) !== hash) {
981        return null;
982      }
983      const cacheState = await this.lookupResourceWithoutHash(url);
984      return cacheState && cacheState.response;
985    }
986    lookupResourceWithoutHash(url) {
987      return this.assetGroups.reduce(async (potentialResponse, group) => {
988        const resp = await potentialResponse;
989        if (resp !== null) {
990          return resp;
991        }
992        return group.fetchFromCacheOnly(url);
993      }, Promise.resolve(null));
994    }
995    previouslyCachedResources() {
996      return this.assetGroups.reduce(async (resources, group) => (await resources).concat(await group.unhashedResources()), Promise.resolve([]));
997    }
998    async recentCacheStatus(url) {
999      return this.assetGroups.reduce(async (current, group) => {
1000        const status = await current;
1001        if (status === UpdateCacheStatus.CACHED) {
1002          return status;
1003        }
1004        const groupStatus = await group.cacheStatus(url);
1005        if (groupStatus === UpdateCacheStatus.NOT_CACHED) {
1006          return status;
1007        }
1008        return groupStatus;
1009      }, Promise.resolve(UpdateCacheStatus.NOT_CACHED));
1010    }
1011    async getCacheNames() {
1012      const allGroupCacheNames = await Promise.all([
1013        ...this.assetGroups.map((group) => group.getCacheNames()),
1014        ...this.dataGroups.map((group) => group.getCacheNames())
1015      ]);
1016      return [].concat(...allGroupCacheNames);
1017    }
1018    get appData() {
1019      return this.manifest.appData || null;
1020    }
1021    acceptsTextHtml(req) {
1022      const accept = req.headers.get("Accept");
1023      if (accept === null) {
1024        return false;
1025      }
1026      const values = accept.split(",");
1027      return values.some((value) => value.trim().toLowerCase() === "text/html");
1028    }
1029  };
1030
1031  
1031// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/debug.mjs
1032  var SW_VERSION = "17.3.12";
1033  var DEBUG_LOG_BUFFER_SIZE = 100;
1034  var DebugHandler = class {
1035    constructor(driver, adapter2) {
1036      this.driver = driver;
1037      this.adapter = adapter2;
1038      this.debugLogA = [];
1039      this.debugLogB = [];
1040    }
1041    async handleFetch(req) {
1042      const [state, versions, idle] = await Promise.all([
1043        this.driver.debugState(),
1044        this.driver.debugVersions(),
1045        this.driver.debugIdleState()
1046      ]);
1047      const msgState = `NGSW Debug Info:
1048
1049Driver version: ${SW_VERSION}
1050Driver state: ${state.state} (${state.why})
1051Latest manifest hash: ${state.latestHash || "none"}
1052Last update check: ${this.since(state.lastUpdateCheck)}`;
1053      const msgVersions = versions.map((version) => `=== Version ${version.hash} ===
1054
1055Clients: ${version.clients.join(", ")}`).join("\n\n");
1056      const msgIdle = `=== Idle Task Queue ===
1057Last update tick: ${this.since(idle.lastTrigger)}
1058Last update run: ${this.since(idle.lastRun)}
1059Task queue:
1060${idle.queue.map((v) => " * " + v).join("\n")}
1061
1062Debug log:
1063${this.formatDebugLog(this.debugLogB)}
1064${this.formatDebugLog(this.debugLogA)}
1065`;
1066      return this.adapter.newResponse(`${msgState}
1067
1068${msgVersions}
1069
1070${msgIdle}`, { headers: this.adapter.newHeaders({ "Content-Type": "text/plain" }) });
1071    }
1072    since(time) {
1073      if (time === null) {
1074        return "never";
1075      }
1076      let age = this.adapter.time - time;
1077      const days = Math.floor(age / 864e5);
1078      age = age % 864e5;
1079      const hours = Math.floor(age / 36e5);
1080      age = age % 36e5;
1081      const minutes = Math.floor(age / 6e4);
1082      age = age % 6e4;
1083      const seconds = Math.floor(age / 1e3);
1084      const millis = age % 1e3;
1085      return (days > 0 ? `${days}d` : "") + (hours > 0 ? `${hours}h` : "") + (minutes > 0 ? `${minutes}m` : "") + (seconds > 0 ? `${seconds}s` : "") + (millis > 0 ? `${millis}u` : "");
1086    }
1087    log(value, context = "") {
1088      if (this.debugLogA.length === DEBUG_LOG_BUFFER_SIZE) {
1089        this.debugLogB = this.debugLogA;
1090        this.debugLogA = [];
1091      }
1092      if (typeof value !== "string") {
1093        value = this.errorToString(value);
1094      }
1095      this.debugLogA.push({ value, time: this.adapter.time, context });
1096    }
1097    errorToString(err) {
1098      return `${err.name}(${err.message}, ${err.stack})`;
1099    }
1100    formatDebugLog(log) {
1101      return log.map((entry) => `[${this.since(entry.time)}] ${entry.value} ${entry.context}`).join("\n");
1102    }
1103  };
1104
1105  
1105// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/idle.mjs
1106  var IdleScheduler = class {
1107    constructor(adapter2, delay, maxDelay, debug) {
1108      this.adapter = adapter2;
1109      this.delay = delay;
1110      this.maxDelay = maxDelay;
1111      this.debug = debug;
1112      this.queue = [];
1113      this.scheduled = null;
1114      this.empty = Promise.resolve();
1115      this.emptyResolve = null;
1116      this.lastTrigger = null;
1117      this.lastRun = null;
1118      this.oldestScheduledAt = null;
1119    }
1120    async trigger() {
1121      var _a;
1122      this.lastTrigger = this.adapter.time;
1123      if (this.queue.length === 0) {
1124        return;
1125      }
1126      if (this.scheduled !== null) {
1127        this.scheduled.cancel = true;
1128      }
1129      const scheduled = {
1130        cancel: false
1131      };
1132      this.scheduled = scheduled;
1133      const now = this.adapter.time;
1134      const maxDelay = Math.max(0, ((_a = this.oldestScheduledAt) != null ? _a : now) + this.maxDelay - now);
1135      const delay = Math.min(maxDelay, this.delay);
1136      await this.adapter.timeout(delay);
1137      if (scheduled.cancel) {
1138        return;
1139      }
1140      this.scheduled = null;
1141      await this.execute();
1142    }
1143    async execute() {
1144      this.lastRun = this.adapter.time;
1145      while (this.queue.length > 0) {
1146        const queue = this.queue;
1147        this.queue = [];
1148        await queue.reduce(async (previous, task) => {
1149          await previous;
1150          try {
1151            await task.run();
1152          } catch (err) {
1153            this.debug.log(err, `while running idle task ${task.desc}`);
1154          }
1155        }, Promise.resolve());
1156      }
1157      if (this.emptyResolve !== null) {
1158        this.emptyResolve();
1159        this.emptyResolve = null;
1160      }
1161      this.empty = Promise.resolve();
1162      this.oldestScheduledAt = null;
1163    }
1164    schedule(desc, run) {
1165      this.queue.push({ desc, run });
1166      if (this.emptyResolve === null) {
1167        this.empty = new Promise((resolve) => {
1168          this.emptyResolve = resolve;
1169        });
1170      }
1171      if (this.oldestScheduledAt === null) {
1172        this.oldestScheduledAt = this.adapter.time;
1173      }
1174    }
1175    get size() {
1176      return this.queue.length;
1177    }
1178    get taskDescriptions() {
1179      return this.queue.map((task) => task.desc);
1180    }
1181  };
1182
1183  
1183// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/manifest.mjs
1184  function hashManifest(manifest) {
1185    return sha1(JSON.stringify(manifest));
1186  }
1187
1188  
1188// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/msg.mjs
1189  function isMsgCheckForUpdates(msg) {
1190    return msg.action === "CHECK_FOR_UPDATES";
1191  }
1192  function isMsgActivateUpdate(msg) {
1193    return msg.action === "ACTIVATE_UPDATE";
1194  }
1195
1196  
1196// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/src/driver.mjs
1197  var IDLE_DELAY = 5e3;
1198  var MAX_IDLE_DELAY = 3e4;
1199  var SUPPORTED_CONFIG_VERSION = 1;
1200  var NOTIFICATION_OPTION_NAMES = [
1201    "actions",
1202    "badge",
1203    "body",
1204    "data",
1205    "dir",
1206    "icon",
1207    "image",
1208    "lang",
1209    "renotify",
1210    "requireInteraction",
1211    "silent",
1212    "tag",
1213    "timestamp",
1214    "title",
1215    "vibrate"
1216  ];
1217  var DriverReadyState;
1218  (function(DriverReadyState2) {
1219    DriverReadyState2[DriverReadyState2["NORMAL"] = 0] = "NORMAL";
1220    DriverReadyState2[DriverReadyState2["EXISTING_CLIENTS_ONLY"] = 1] = "EXISTING_CLIENTS_ONLY";
1221    DriverReadyState2[DriverReadyState2["SAFE_MODE"] = 2] = "SAFE_MODE";
1222  })(DriverReadyState || (DriverReadyState = {}));
1223  var Driver = class {
1224    constructor(scope2, adapter2, db) {
1225      this.scope = scope2;
1226      this.adapter = adapter2;
1227      this.db = db;
1228      this.state = DriverReadyState.NORMAL;
1229      this.stateMessage = "(nominal)";
1230      this.initialized = null;
1231      this.clientVersionMap = /* @__PURE__ */ new Map();
1232      this.versions = /* @__PURE__ */ new Map();
1233      this.latestHash = null;
1234      this.lastUpdateCheck = null;
1235      this.scheduledNavUpdateCheck = false;
1236      this.loggedInvalidOnlyIfCachedRequest = false;
1237      this.controlTable = this.db.open("control");
1238      this.ngswStatePath = this.adapter.parseUrl("ngsw/state", this.scope.registration.scope).path;
1239      this.scope.addEventListener("install", (event) => {
1240        event.waitUntil(this.scope.skipWaiting());
1241      });
1242      this.scope.addEventListener("activate", (event) => {
1243        event.waitUntil((async () => {
1244          await this.scope.clients.claim();
1245          this.idle.schedule("activate: cleanup-old-sw-caches", async () => {
1246            try {
1247              await this.cleanupOldSwCaches();
1248            } catch (err) {
1249              this.debugger.log(err, "cleanupOldSwCaches @ activate: cleanup-old-sw-caches");
1250            }
1251          });
1252        })());
1253        if (this.scope.registration.active !== null) {
1254          this.scope.registration.active.postMessage({ action: "INITIALIZE" });
1255        }
1256      });
1257      this.scope.addEventListener("fetch", (event) => this.onFetch(event));
1258      this.scope.addEventListener("message", (event) => this.onMessage(event));
1259      this.scope.addEventListener("push", (event) => this.onPush(event));
1260      this.scope.addEventListener("notificationclick", (event) => this.onClick(event));
1261      this.debugger = new DebugHandler(this, this.adapter);
1262      this.idle = new IdleScheduler(this.adapter, IDLE_DELAY, MAX_IDLE_DELAY, this.debugger);
1263    }
1264    onFetch(event) {
1265      const req = event.request;
1266      const scopeUrl = this.scope.registration.scope;
1267      const requestUrlObj = this.adapter.parseUrl(req.url, scopeUrl);
1268      if (req.headers.has("ngsw-bypass") || /[?&]ngsw-bypass(?:[=&]|$)/i.test(requestUrlObj.search)) {
1269        return;
1270      }
1271      if (requestUrlObj.path === this.ngswStatePath) {
1272        event.respondWith(this.debugger.handleFetch(req));
1273        return;
1274      }
1275      if (this.state === DriverReadyState.SAFE_MODE) {
1276        event.waitUntil(this.idle.trigger());
1277        return;
1278      }
1279      if (requestUrlObj.origin.startsWith("http:") && scopeUrl.startsWith("https:")) {
1280        this.debugger.log(`Ignoring passive mixed content request: Driver.fetch(${req.url})`);
1281        return;
1282      }
1283      if (req.cache === "only-if-cached" && req.mode !== "same-origin") {
1284        if (!this.loggedInvalidOnlyIfCachedRequest) {
1285          this.loggedInvalidOnlyIfCachedRequest = true;
1286          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})`);
1287        }
1288        return;
1289      }
1290      event.respondWith(this.handleFetch(event));
1291    }
1292    onMessage(event) {
1293      if (this.state === DriverReadyState.SAFE_MODE) {
1294        return;
1295      }
1296      const data = event.data;
1297      if (!data || !data.action) {
1298        return;
1299      }
1300      event.waitUntil((async () => {
1301        if (data.action === "INITIALIZE") {
1302          return this.ensureInitialized(event);
1303        }
1304        if (!this.adapter.isClient(event.source)) {
1305          return;
1306        }
1307        await this.ensureInitialized(event);
1308        await this.handleMessage(data, event.source);
1309      })());
1310    }
1311    onPush(msg) {
1312      if (!msg.data) {
1313        return;
1314      }
1315      msg.waitUntil(this.handlePush(msg.data.json()));
1316    }
1317    onClick(event) {
1318      event.waitUntil(this.handleClick(event.notification, event.action));
1319    }
1320    async ensureInitialized(event) {
1321      if (this.initialized !== null) {
1322        return this.initialized;
1323      }
1324      try {
1325        this.initialized = this.initialize();
1326        await this.initialized;
1327      } catch (error) {
1328        this.state = DriverReadyState.SAFE_MODE;
1329        this.stateMessage = `Initialization failed due to error: ${errorToString(error)}`;
1330        throw error;
1331      } finally {
1332        event.waitUntil(this.idle.trigger());
1333      }
1334    }
1335    async handleMessage(msg, from) {
1336      if (isMsgCheckForUpdates(msg)) {
1337        const action = this.checkForUpdate();
1338        await this.completeOperation(from, action, msg.nonce);
1339      } else if (isMsgActivateUpdate(msg)) {
1340        const action = this.updateClient(from);
1341        await this.completeOperation(from, action, msg.nonce);
1342      }
1343    }
1344    async handlePush(data) {
1345      await this.broadcast({
1346        type: "PUSH",
1347        data
1348      });
1349      if (!data.notification || !data.notification.title) {
1350        return;
1351      }
1352      const desc = data.notification;
1353      let options = {};
1354      NOTIFICATION_OPTION_NAMES.filter((name) => desc.hasOwnProperty(name)).forEach((name) => options[name] = desc[name]);
1355      await this.scope.registration.showNotification(desc["title"], options);
1356    }
1357    async handleClick(notification, action) {
1358      var _a, _b, _c;
1359      notification.close();
1360      const options = {};
1361      NOTIFICATION_OPTION_NAMES.filter((name) => name in notification).forEach((name) => options[name] = notification[name]);
1362      const notificationAction = action === "" || action === void 0 ? "default" : action;
1363      const onActionClick = (_b = (_a = notification == null ? void 0 : notification.data) == null ? void 0 : _a.onActionClick) == null ? void 0 : _b[notificationAction];
1364      const urlToOpen = new URL((_c = onActionClick == null ? void 0 : onActionClick.url) != null ? _c : "", this.scope.registration.scope).href;
1365      switch (onActionClick == null ? void 0 : onActionClick.operation) {
1366        case "openWindow":
1367          await this.scope.clients.openWindow(urlToOpen);
1368          break;
1369        case "focusLastFocusedOrOpen": {
1370          let matchingClient = await this.getLastFocusedMatchingClient(this.scope);
1371          if (matchingClient) {
1372            await (matchingClient == null ? void 0 : matchingClient.focus());
1373          } else {
1374            await this.scope.clients.openWindow(urlToOpen);
1375          }
1376          break;
1377        }
1378        case "navigateLastFocusedOrOpen": {
1379          let matchingClient = await this.getLastFocusedMatchingClient(this.scope);
1380          if (matchingClient) {
1381            matchingClient = await matchingClient.navigate(urlToOpen);
1382            await (matchingClient == null ? void 0 : matchingClient.focus());
1383          } else {
1384            await this.scope.clients.openWindow(urlToOpen);
1385          }
1386          break;
1387        }
1388        case "sendRequest": {
1389          await this.scope.fetch(urlToOpen);
1390          break;
1391        }
1392        default:
1393          break;
1394      }
1395      await this.broadcast({
1396        type: "NOTIFICATION_CLICK",
1397        data: { action, notification: options }
1398      });
1399    }
1400    async getLastFocusedMatchingClient(scope2) {
1401      const windowClients = await scope2.clients.matchAll({ type: "window" });
1402      return windowClients[0];
1403    }
1404    async completeOperation(client, promise, nonce) {
1405      const response = { type: "OPERATION_COMPLETED", nonce };
1406      try {
1407        client.postMessage(__spreadProps(__spreadValues({}, response), {
1408          result: await promise
1409        }));
1410      } catch (e) {
1411        client.postMessage(__spreadProps(__spreadValues({}, response), {
1412          error: e.toString()
1413        }));
1414      }
1415    }
1416    async updateClient(client) {
1417      const existing = this.clientVersionMap.get(client.id);
1418      if (existing === this.latestHash) {
1419        return false;
1420      }
1421      let previous = void 0;
1422      if (existing !== void 0) {
1423        const existingVersion = this.versions.get(existing);
1424        previous = this.mergeHashWithAppData(existingVersion.manifest, existing);
1425      }
1426      this.clientVersionMap.set(client.id, this.latestHash);
1427      await this.sync();
1428      const current = this.versions.get(this.latestHash);
1429      return true;
1430    }
1431    async handleFetch(event) {
1432      try {
1433        await this.ensureInitialized(event);
1434      } catch (e) {
1435        return this.safeFetch(event.request);
1436      }
1437      if (event.request.mode === "navigate" && !this.scheduledNavUpdateCheck) {
1438        this.scheduledNavUpdateCheck = true;
1439        this.idle.schedule("check-updates-on-navigation", async () => {
1440          this.scheduledNavUpdateCheck = false;
1441          await this.checkForUpdate();
1442        });
1443      }
1444      const appVersion = await this.assignVersion(event);
1445      let res = null;
1446      try {
1447        if (appVersion !== null) {
1448          try {
1449            res = await appVersion.handleFetch(event.request, event);
1450          } catch (err) {
1451            if (err.isUnrecoverableState) {
1452              await this.notifyClientsAboutUnrecoverableState(appVersion, err.message);
1453            }
1454            if (err.isCritical) {
1455              this.debugger.log(err, `Driver.handleFetch(version: ${appVersion.manifestHash})`);
1456              await this.versionFailed(appVersion, err);
1457              return this.safeFetch(event.request);
1458            }
1459            throw err;
1460          }
1461        }
1462        if (res === null) {
1463          return this.safeFetch(event.request);
1464        }
1465        return res;
1466      } finally {
1467        event.waitUntil(this.idle.trigger());
1468      }
1469    }
1470    async initialize() {
1471      const table = await this.controlTable;
1472      let manifests, assignments, latest;
1473      try {
1474        [manifests, assignments, latest] = await Promise.all([
1475          table.read("manifests"),
1476          table.read("assignments"),
1477          table.read("latest")
1478        ]);
1479        if (!this.versions.has(latest.latest) && !manifests.hasOwnProperty(latest.latest)) {
1480          this.debugger.log(`Missing manifest for latest version hash ${latest.latest}`, "initialize: read from DB");
1481          throw new Error(`Missing manifest for latest hash ${latest.latest}`);
1482        }
1483        this.idle.schedule("init post-load (update)", async () => {
1484          await this.checkForUpdate();
1485        });
1486      } catch (_) {
1487        const manifest = await this.fetchLatestManifest();
1488        const hash = hashManifest(manifest);
1489        manifests = { [hash]: manifest };
1490        assignments = {};
1491        latest = { latest: hash };
1492        await Promise.all([
1493          table.write("manifests", manifests),
1494          table.write("assignments", assignments),
1495          table.write("latest", latest)
1496        ]);
1497      }
1498      this.idle.schedule("init post-load (cleanup)", async () => {
1499        await this.cleanupCaches();
1500      });
1501      Object.keys(manifests).forEach((hash) => {
1502        const manifest = manifests[hash];
1503        if (!this.versions.has(hash)) {
1504          this.versions.set(hash, new AppVersion(this.scope, this.adapter, this.db, this.idle, this.debugger, manifest, hash));
1505        }
1506      });
1507      Object.keys(assignments).forEach((clientId) => {
1508        const hash = assignments[clientId];
1509        if (this.versions.has(hash)) {
1510          this.clientVersionMap.set(clientId, hash);
1511        } else {
1512          this.clientVersionMap.set(clientId, latest.latest);
1513          this.debugger.log(`Unknown version ${hash} mapped for client ${clientId}, using latest instead`, `initialize: map assignments`);
1514        }
1515      });
1516      this.latestHash = latest.latest;
1517      if (!this.versions.has(latest.latest)) {
1518        throw new Error(`Invariant violated (initialize): latest hash ${latest.latest} has no known manifest`);
1519      }
1520      await Promise.all(Object.keys(manifests).map(async (hash) => {
1521        try {
1522          await this.scheduleInitialization(this.versions.get(hash));
1523        } catch (err) {
1524          this.debugger.log(err, `initialize: schedule init of ${hash}`);
1525        }
1526      }));
1527    }
1528    lookupVersionByHash(hash, debugName = "lookupVersionByHash") {
1529      if (!this.versions.has(hash)) {
1530        throw new Error(`Invariant violated (${debugName}): want AppVersion for ${hash} but not loaded`);
1531      }
1532      return this.versions.get(hash);
1533    }
1534    async assignVersion(event) {
1535      const clientId = event.resultingClientId || event.clientId;
1536      if (clientId) {
1537        if (this.clientVersionMap.has(clientId)) {
1538          const hash = this.clientVersionMap.get(clientId);
1539          let appVersion = this.lookupVersionByHash(hash, "assignVersion");
1540          if (this.state === DriverReadyState.NORMAL && hash !== this.latestHash && appVersion.isNavigationRequest(event.request)) {
1541            if (this.latestHash === null) {
1542              throw new Error(`Invariant violated (assignVersion): latestHash was null`);
1543            }
1544            const client = await this.scope.clients.get(clientId);
1545            if (client) {
1546              await this.updateClient(client);
1547            }
1548            appVersion = this.lookupVersionByHash(this.latestHash, "assignVersion");
1549          }
1550          return appVersion;
1551        } else {
1552          if (this.state !== DriverReadyState.NORMAL) {
1553            return null;
1554          }
1555          if (this.latestHash === null) {
1556            throw new Error(`Invariant violated (assignVersion): latestHash was null`);
1557          }
1558          this.clientVersionMap.set(clientId, this.latestHash);
1559          await this.sync();
1560          return this.lookupVersionByHash(this.latestHash, "assignVersion");
1561        }
1562      } else {
1563        if (this.state !== DriverReadyState.NORMAL) {
1564          return null;
1565        }
1566        if (this.latestHash === null) {
1567          throw new Error(`Invariant violated (assignVersion): latestHash was null`);
1568        }
1569        return this.lookupVersionByHash(this.latestHash, "assignVersion");
1570      }
1571    }
1572    async fetchLatestManifest(ignoreOfflineError = false) {
1573      const res = await this.safeFetch(this.adapter.newRequest("ngsw.json?ngsw-cache-bust=" + Math.random()));
1574      if (!res.ok) {
1575        if (res.status === 404) {
1576          await this.deleteAllCaches();
1577          await this.scope.registration.unregister();
1578        } else if ((res.status === 503 || res.status === 504) && ignoreOfflineError) {
1579          return null;
1580        }
1581        throw new Error(`Manifest fetch failed! (status: ${res.status})`);
1582      }
1583      this.lastUpdateCheck = this.adapter.time;
1584      return res.json();
1585    }
1586    async deleteAllCaches() {
1587      const cacheNames = await this.adapter.caches.keys();
1588      await Promise.all(cacheNames.map((name) => this.adapter.caches.delete(name)));
1589    }
1590    async scheduleInitialization(appVersion) {
1591      const initialize = async () => {
1592        try {
1593          await appVersion.initializeFully();
1594        } catch (err) {
1595          this.debugger.log(err, `initializeFully for ${appVersion.manifestHash}`);
1596          await this.versionFailed(appVersion, err);
1597        }
1598      };
1599      if (this.scope.registration.scope.indexOf("://localhost") > -1) {
1600        return initialize();
1601      }
1602      this.idle.schedule(`initialization(${appVersion.manifestHash})`, initialize);
1603    }
1604    async versionFailed(appVersion, err) {
1605      const broken = Array.from(this.versions.entries()).find(([hash, version]
1605) => version === appVersion);
1606      if (broken === void 0) {
1607        return;
1608      }
1609      const brokenHash = broken[0];
1610      if (this.latestHash === brokenHash) {
1611        this.state = DriverReadyState.EXISTING_CLIENTS_ONLY;
1612        this.stateMessage = `Degraded due to: ${errorToString(err)}`;
1613      }
1614    }
1615    async setupUpdate(manifest, hash) {
1616      try {
1617        const newVersion = new AppVersion(this.scope, this.adapter, this.db, this.idle, this.debugger, manifest, hash);
1618        if (manifest.configVersion !== SUPPORTED_CONFIG_VERSION) {
1619          await this.deleteAllCaches();
1620          await this.scope.registration.unregister();
1621          throw new Error(`Invalid config version: expected ${SUPPORTED_CONFIG_VERSION}, got ${manifest.configVersion}.`);
1622        }
1623        await newVersion.initializeFully(this);
1624        this.versions.set(hash, newVersion);
1625        this.latestHash = hash;
1626        if (this.state === DriverReadyState.EXISTING_CLIENTS_ONLY) {
1627          this.state = DriverReadyState.NORMAL;
1628          this.stateMessage = "(nominal)";
1629        }
1630        await this.sync();
1631        await this.notifyClientsAboutVersionReady(manifest, hash);
1632      } catch (e) {
1633        await this.notifyClientsAboutVersionInstallationFailed(manifest, hash, e);
1634        throw e;
1635      }
1636    }
1637    async checkForUpdate() {
1638      let hash = "(unknown)";
1639      try {
1640        const manifest = await this.fetchLatestManifest(true);
1641        if (manifest === null) {
1642          this.debugger.log("Check for update aborted. (Client or server offline.)");
1643          return false;
1644        }
1645        hash = hashManifest(manifest);
1646        if (this.versions.has(hash)) {
1647          await this.notifyClientsAboutNoNewVersionDetected(manifest, hash);
1648          return false;
1649        }
1650        await this.notifyClientsAboutVersionDetected(manifest, hash);
1651        await this.setupUpdate(manifest, hash);
1652        return true;
1653      } catch (err) {
1654        this.debugger.log(err, `Error occurred while updating to manifest ${hash}`);
1655        this.state = DriverReadyState.EXISTING_CLIENTS_ONLY;
1656        this.stateMessage = `Degraded due to failed initialization: ${errorToString(err)}`;
1657        return false;
1658      }
1659    }
1660    async sync() {
1661      const table = await this.controlTable;
1662      const manifests = {};
1663      this.versions.forEach((version, hash) => {
1664        manifests[hash] = version.manifest;
1665      });
1666      const assignments = {};
1667      this.clientVersionMap.forEach((hash, clientId) => {
1668        assignments[clientId] = hash;
1669      });
1670      const latest = {
1671        latest: this.latestHash
1672      };
1673      await Promise.all([
1674        table.write("manifests", manifests),
1675        table.write("assignments", assignments),
1676        table.write("latest", latest)
1677      ]);
1678    }
1679    async cleanupCaches() {
1680      try {
1681        const activeClients = new Set((await this.scope.clients.matchAll()).map((client) => client.id));
1682        const knownClients = Array.from(this.clientVersionMap.keys());
1683        const obsoleteClients = knownClients.filter((id) => !activeClients.has(id));
1684        obsoleteClients.forEach((id) => this.clientVersionMap.delete(id));
1685        const usedVersions = new Set(this.clientVersionMap.values());
1686        const obsoleteVersions = Array.from(this.versions.keys()).filter((version) => !usedVersions.has(version) && version !== this.latestHash);
1687        obsoleteVersions.forEach((version) => this.versions.delete(version));
1688        await this.sync();
1689        const allCaches = await this.adapter.caches.keys();
1690        const usedCaches = new Set(await this.getCacheNames());
1691        const cachesToDelete = allCaches.filter((name) => !usedCaches.has(name));
1692        await Promise.all(cachesToDelete.map((name) => this.adapter.caches.delete(name)));
1693      } catch (err) {
1694        this.debugger.log(err, "cleanupCaches");
1695      }
1696    }
1697    async cleanupOldSwCaches() {
1698      const caches = this.adapter.caches.original;
1699      const cacheNames = await caches.keys();
1700      const oldSwCacheNames = cacheNames.filter((name) => /^ngsw:(?!\/)/.test(name));
1701      await Promise.all(oldSwCacheNames.map((name) => caches.delete(name)));
1702    }
1703    lookupResourceWithHash(url, hash) {
1704      return Array.from(this.versions.values()).reduce(async (prev, version) => {
1705        if (await prev !== null) {
1706          return prev;
1707        }
1708        return version.lookupResourceWithHash(url, hash);
1709      }, Promise.resolve(null));
1710    }
1711    async lookupResourceWithoutHash(url) {
1712      await this.initialized;
1713      const version = this.versions.get(this.latestHash);
1714      return version ? version.lookupResourceWithoutHash(url) : null;
1715    }
1716    async previouslyCachedResources() {
1717      await this.initialized;
1718      const version = this.versions.get(this.latestHash);
1719      return version ? version.previouslyCachedResources() : [];
1720    }
1721    async recentCacheStatus(url) {
1722      const version = this.versions.get(this.latestHash);
1723      return version ? version.recentCacheStatus(url) : UpdateCacheStatus.NOT_CACHED;
1724    }
1725    mergeHashWithAppData(manifest, hash) {
1726      return {
1727        hash,
1728        appData: manifest.appData
1729      };
1730    }
1731    async notifyClientsAboutUnrecoverableState(appVersion, reason) {
1732      const broken = Array.from(this.versions.entries()).find(([hash, version]) => version === appVersion);
1733      if (broken === void 0) {
1734        return;
1735      }
1736      const brokenHash = broken[0];
1737      const affectedClients = Array.from(this.clientVersionMap.entries()).filter(([clientId, hash]) => hash === brokenHash).map(([clientId]) => clientId);
1738      await Promise.all(affectedClients.map(async (clientId) => {
1739        const client = await this.scope.clients.get(clientId);
1740        if (client) {
1741          client.postMessage({ type: "UNRECOVERABLE_STATE", reason });
1742        }
1743      }));
1744    }
1745    async notifyClientsAboutVersionInstallationFailed(manifest, hash, error) {
1746      await this.initialized;
1747      const clients = await this.scope.clients.matchAll();
1748      await Promise.all(clients.map(async (client) => {
1749        client.postMessage({
1750          type: "VERSION_INSTALLATION_FAILED",
1751          version: this.mergeHashWithAppData(manifest, hash),
1752          error: errorToString(error)
1753        });
1754      }));
1755    }
1756    async notifyClientsAboutNoNewVersionDetected(manifest, hash) {
1757      await this.initialized;
1758      const clients = await this.scope.clients.matchAll();
1759      await Promise.all(clients.map(async (client) => {
1760        client.postMessage({
1761          type: "NO_NEW_VERSION_DETECTED",
1762          version: this.mergeHashWithAppData(manifest, hash)
1763        });
1764      }));
1765    }
1766    async notifyClientsAboutVersionDetected(manifest, hash) {
1767      await this.initialized;
1768      const clients = await this.scope.clients.matchAll();
1769      await Promise.all(clients.map(async (client) => {
1770        const version = this.clientVersionMap.get(client.id);
1771        if (version === void 0) {
1772          return;
1773        }
1774        client.postMessage({
1775          type: "VERSION_DETECTED",
1776          version: this.mergeHashWithAppData(manifest, hash)
1777        });
1778      }));
1779    }
1780    async notifyClientsAboutVersionReady(manifest, hash) {
1781      await this.initialized;
1782      const clients = await this.scope.clients.matchAll();
1783      await Promise.all(clients.map(async (client) => {
1784        const version = this.clientVersionMap.get(client.id);
1785        if (version === void 0) {
1786          return;
1787        }
1788        if (version === this.latestHash) {
1789          return;
1790        }
1791        const current = this.versions.get(version);
1792        const notice = {
1793          type: "VERSION_READY",
1794          currentVersion: this.mergeHashWithAppData(current.manifest, version),
1795          latestVersion: this.mergeHashWithAppData(manifest, hash)
1796        };
1797        client.postMessage(notice);
1798      }));
1799    }
1800    async broadcast(msg) {
1801      const clients = await this.scope.clients.matchAll();
1802      clients.forEach((client) => {
1803        client.postMessage(msg);
1804      });
1805    }
1806    async debugState() {
1807      return {
1808        state: DriverReadyState[this.state],
1809        why: this.stateMessage,
1810        latestHash: this.latestHash,
1811        lastUpdateCheck: this.lastUpdateCheck
1812      };
1813    }
1814    async debugVersions() {
1815      return Array.from(this.versions.keys()).map((hash) => {
1816        const version = this.versions.get(hash);
1817        const clients = Array.from(this.clientVersionMap.entries()).filter(([clientId, version2]) => version2 === hash).map(([clientId, version2]) => clientId);
1818        return {
1819          hash,
1820          manifest: version.manifest,
1821          clients,
1822          status: ""
1823        };
1824      });
1825    }
1826    async debugIdleState() {
1827      return {
1828        queue: this.idle.taskDescriptions,
1829        lastTrigger: this.idle.lastTrigger,
1830        lastRun: this.idle.lastRun
1831      };
1832    }
1833    async safeFetch(req) {
1834      try {
1835        return await this.scope.fetch(req);
1836      } catch (err) {
1837        this.debugger.log(err, `Driver.fetch(${req.url})`);
1838        return this.adapter.newResponse(null, {
1839          status: 504,
1840          statusText: "Gateway Timeout"
1841        });
1842      }
1843    }
1844    async getCacheNames() {
1845      const controlTable = await this.controlTable;
1846      const appVersions = Array.from(this.versions.values());
1847      const appVersionCacheNames = await Promise.all(appVersions.map((version) => version.getCacheNames()));
1848      return [controlTable.cacheName].concat(...appVersionCacheNames);
1849    }
1850  };
1851
1852  
1852// bazel-out/darwin_arm64-fastbuild-ST-2e5f3376adb5/bin/packages/service-worker/worker/main.mjs
1853  var scope = self;
1854  var adapter = new Adapter(scope.registration.scope, self.caches);
1855  new Driver(scope, adapter, new CacheDatabase(adapter));
1856})();
1857/**
1858 * @license
1859 * Copyright Google LLC All Rights Reserved.
1860 *
1861 * Use of this source code is governed by an MIT-style license that can be
1862 * found in the LICENSE file at https://angular.io/license
1863 */

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.