UNPKG

26.4 kBJavaScriptView Raw
1/**
2 * @license Angular v10.2.3
3 * (c) 2010-2020 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7(function (global, factory) {
8 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
9 typeof define === 'function' && define.amd ? define('@angular/service-worker/config', ['exports'], factory) :
10 (global = global || self, factory((global.ng = global.ng || {}, global.ng.serviceWorker = global.ng.serviceWorker || {}, global.ng.serviceWorker.config = {})));
11}(this, (function (exports) { 'use strict';
12
13 /*! *****************************************************************************
14 Copyright (c) Microsoft Corporation.
15
16 Permission to use, copy, modify, and/or distribute this software for any
17 purpose with or without fee is hereby granted.
18
19 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25 PERFORMANCE OF THIS SOFTWARE.
26 ***************************************************************************** */
27 /* global Reflect, Promise */
28 var extendStatics = function (d, b) {
29 extendStatics = Object.setPrototypeOf ||
30 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31 function (d, b) { for (var p in b)
32 if (b.hasOwnProperty(p))
33 d[p] = b[p]; };
34 return extendStatics(d, b);
35 };
36 function __extends(d, b) {
37 extendStatics(d, b);
38 function __() { this.constructor = d; }
39 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40 }
41 var __assign = function () {
42 __assign = Object.assign || function __assign(t) {
43 for (var s, i = 1, n = arguments.length; i < n; i++) {
44 s = arguments[i];
45 for (var p in s)
46 if (Object.prototype.hasOwnProperty.call(s, p))
47 t[p] = s[p];
48 }
49 return t;
50 };
51 return __assign.apply(this, arguments);
52 };
53 function __rest(s, e) {
54 var t = {};
55 for (var p in s)
56 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
57 t[p] = s[p];
58 if (s != null && typeof Object.getOwnPropertySymbols === "function")
59 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
60 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
61 t[p[i]] = s[p[i]];
62 }
63 return t;
64 }
65 function __decorate(decorators, target, key, desc) {
66 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
67 if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
68 r = Reflect.decorate(decorators, target, key, desc);
69 else
70 for (var i = decorators.length - 1; i >= 0; i--)
71 if (d = decorators[i])
72 r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
73 return c > 3 && r && Object.defineProperty(target, key, r), r;
74 }
75 function __param(paramIndex, decorator) {
76 return function (target, key) { decorator(target, key, paramIndex); };
77 }
78 function __metadata(metadataKey, metadataValue) {
79 if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
80 return Reflect.metadata(metadataKey, metadataValue);
81 }
82 function __awaiter(thisArg, _arguments, P, generator) {
83 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
84 return new (P || (P = Promise))(function (resolve, reject) {
85 function fulfilled(value) { try {
86 step(generator.next(value));
87 }
88 catch (e) {
89 reject(e);
90 } }
91 function rejected(value) { try {
92 step(generator["throw"](value));
93 }
94 catch (e) {
95 reject(e);
96 } }
97 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
98 step((generator = generator.apply(thisArg, _arguments || [])).next());
99 });
100 }
101 function __generator(thisArg, body) {
102 var _ = { label: 0, sent: function () { if (t[0] & 1)
103 throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
104 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
105 function verb(n) { return function (v) { return step([n, v]); }; }
106 function step(op) {
107 if (f)
108 throw new TypeError("Generator is already executing.");
109 while (_)
110 try {
111 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
112 return t;
113 if (y = 0, t)
114 op = [op[0] & 2, t.value];
115 switch (op[0]) {
116 case 0:
117 case 1:
118 t = op;
119 break;
120 case 4:
121 _.label++;
122 return { value: op[1], done: false };
123 case 5:
124 _.label++;
125 y = op[1];
126 op = [0];
127 continue;
128 case 7:
129 op = _.ops.pop();
130 _.trys.pop();
131 continue;
132 default:
133 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
134 _ = 0;
135 continue;
136 }
137 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
138 _.label = op[1];
139 break;
140 }
141 if (op[0] === 6 && _.label < t[1]) {
142 _.label = t[1];
143 t = op;
144 break;
145 }
146 if (t && _.label < t[2]) {
147 _.label = t[2];
148 _.ops.push(op);
149 break;
150 }
151 if (t[2])
152 _.ops.pop();
153 _.trys.pop();
154 continue;
155 }
156 op = body.call(thisArg, _);
157 }
158 catch (e) {
159 op = [6, e];
160 y = 0;
161 }
162 finally {
163 f = t = 0;
164 }
165 if (op[0] & 5)
166 throw op[1];
167 return { value: op[0] ? op[1] : void 0, done: true };
168 }
169 }
170 var __createBinding = Object.create ? (function (o, m, k, k2) {
171 if (k2 === undefined)
172 k2 = k;
173 Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
174 }) : (function (o, m, k, k2) {
175 if (k2 === undefined)
176 k2 = k;
177 o[k2] = m[k];
178 });
179 function __exportStar(m, exports) {
180 for (var p in m)
181 if (p !== "default" && !exports.hasOwnProperty(p))
182 __createBinding(exports, m, p);
183 }
184 function __values(o) {
185 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
186 if (m)
187 return m.call(o);
188 if (o && typeof o.length === "number")
189 return {
190 next: function () {
191 if (o && i >= o.length)
192 o = void 0;
193 return { value: o && o[i++], done: !o };
194 }
195 };
196 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
197 }
198 function __read(o, n) {
199 var m = typeof Symbol === "function" && o[Symbol.iterator];
200 if (!m)
201 return o;
202 var i = m.call(o), r, ar = [], e;
203 try {
204 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
205 ar.push(r.value);
206 }
207 catch (error) {
208 e = { error: error };
209 }
210 finally {
211 try {
212 if (r && !r.done && (m = i["return"]))
213 m.call(i);
214 }
215 finally {
216 if (e)
217 throw e.error;
218 }
219 }
220 return ar;
221 }
222 function __spread() {
223 for (var ar = [], i = 0; i < arguments.length; i++)
224 ar = ar.concat(__read(arguments[i]));
225 return ar;
226 }
227 function __spreadArrays() {
228 for (var s = 0, i = 0, il = arguments.length; i < il; i++)
229 s += arguments[i].length;
230 for (var r = Array(s), k = 0, i = 0; i < il; i++)
231 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
232 r[k] = a[j];
233 return r;
234 }
235 ;
236 function __await(v) {
237 return this instanceof __await ? (this.v = v, this) : new __await(v);
238 }
239 function __asyncGenerator(thisArg, _arguments, generator) {
240 if (!Symbol.asyncIterator)
241 throw new TypeError("Symbol.asyncIterator is not defined.");
242 var g = generator.apply(thisArg, _arguments || []), i, q = [];
243 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
244 function verb(n) { if (g[n])
245 i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
246 function resume(n, v) { try {
247 step(g[n](v));
248 }
249 catch (e) {
250 settle(q[0][3], e);
251 } }
252 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
253 function fulfill(value) { resume("next", value); }
254 function reject(value) { resume("throw", value); }
255 function settle(f, v) { if (f(v), q.shift(), q.length)
256 resume(q[0][0], q[0][1]); }
257 }
258 function __asyncDelegator(o) {
259 var i, p;
260 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
261 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
262 }
263 function __asyncValues(o) {
264 if (!Symbol.asyncIterator)
265 throw new TypeError("Symbol.asyncIterator is not defined.");
266 var m = o[Symbol.asyncIterator], i;
267 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
268 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
269 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
270 }
271 function __makeTemplateObject(cooked, raw) {
272 if (Object.defineProperty) {
273 Object.defineProperty(cooked, "raw", { value: raw });
274 }
275 else {
276 cooked.raw = raw;
277 }
278 return cooked;
279 }
280 ;
281 var __setModuleDefault = Object.create ? (function (o, v) {
282 Object.defineProperty(o, "default", { enumerable: true, value: v });
283 }) : function (o, v) {
284 o["default"] = v;
285 };
286 function __importStar(mod) {
287 if (mod && mod.__esModule)
288 return mod;
289 var result = {};
290 if (mod != null)
291 for (var k in mod)
292 if (Object.hasOwnProperty.call(mod, k))
293 __createBinding(result, mod, k);
294 __setModuleDefault(result, mod);
295 return result;
296 }
297 function __importDefault(mod) {
298 return (mod && mod.__esModule) ? mod : { default: mod };
299 }
300 function __classPrivateFieldGet(receiver, privateMap) {
301 if (!privateMap.has(receiver)) {
302 throw new TypeError("attempted to get private field on non-instance");
303 }
304 return privateMap.get(receiver);
305 }
306 function __classPrivateFieldSet(receiver, privateMap, value) {
307 if (!privateMap.has(receiver)) {
308 throw new TypeError("attempted to set private field on non-instance");
309 }
310 privateMap.set(receiver, value);
311 return value;
312 }
313
314 /**
315 * @license
316 * Copyright Google LLC All Rights Reserved.
317 *
318 * Use of this source code is governed by an MIT-style license that can be
319 * found in the LICENSE file at https://angular.io/license
320 */
321 var PARSE_TO_PAIRS = /([0-9]+[^0-9]+)/g;
322 var PAIR_SPLIT = /^([0-9]+)([dhmsu]+)$/;
323 function parseDurationToMs(duration) {
324 var matches = [];
325 var array;
326 while ((array = PARSE_TO_PAIRS.exec(duration)) !== null) {
327 matches.push(array[0]);
328 }
329 return matches
330 .map(function (match) {
331 var res = PAIR_SPLIT.exec(match);
332 if (res === null) {
333 throw new Error("Not a valid duration: " + match);
334 }
335 var factor = 0;
336 switch (res[2]) {
337 case 'd':
338 factor = 86400000;
339 break;
340 case 'h':
341 factor = 3600000;
342 break;
343 case 'm':
344 factor = 60000;
345 break;
346 case 's':
347 factor = 1000;
348 break;
349 case 'u':
350 factor = 1;
351 break;
352 default:
353 throw new Error("Not a valid duration unit: " + res[2]);
354 }
355 return parseInt(res[1]) * factor;
356 })
357 .reduce(function (total, value) { return total + value; }, 0);
358 }
359
360 /**
361 * @license
362 * Copyright Google LLC All Rights Reserved.
363 *
364 * Use of this source code is governed by an MIT-style license that can be
365 * found in the LICENSE file at https://angular.io/license
366 */
367 var QUESTION_MARK = '[^/]';
368 var WILD_SINGLE = '[^/]*';
369 var WILD_OPEN = '(?:.+\\/)?';
370 var TO_ESCAPE_BASE = [
371 { replace: /\./g, with: '\\.' },
372 { replace: /\+/g, with: '\\+' },
373 { replace: /\*/g, with: WILD_SINGLE },
374 ];
375 var TO_ESCAPE_WILDCARD_QM = __spread(TO_ESCAPE_BASE, [
376 { replace: /\?/g, with: QUESTION_MARK },
377 ]);
378 var TO_ESCAPE_LITERAL_QM = __spread(TO_ESCAPE_BASE, [
379 { replace: /\?/g, with: '\\?' },
380 ]);
381 function globToRegex(glob, literalQuestionMark) {
382 if (literalQuestionMark === void 0) { literalQuestionMark = false; }
383 var toEscape = literalQuestionMark ? TO_ESCAPE_LITERAL_QM : TO_ESCAPE_WILDCARD_QM;
384 var segments = glob.split('/').reverse();
385 var regex = '';
386 while (segments.length > 0) {
387 var segment = segments.pop();
388 if (segment === '**') {
389 if (segments.length > 0) {
390 regex += WILD_OPEN;
391 }
392 else {
393 regex += '.*';
394 }
395 }
396 else {
397 var processed = toEscape.reduce(function (segment, escape) { return segment.replace(escape.replace, escape.with); }, segment);
398 regex += processed;
399 if (segments.length > 0) {
400 regex += '\\/';
401 }
402 }
403 }
404 return regex;
405 }
406
407 var DEFAULT_NAVIGATION_URLS = [
408 '/**',
409 '!/**/*.*',
410 '!/**/*__*',
411 '!/**/*__*/**',
412 ];
413 /**
414 * Consumes service worker configuration files and processes them into control files.
415 *
416 * @publicApi
417 */
418 var Generator = /** @class */ (function () {
419 function Generator(fs, baseHref) {
420 this.fs = fs;
421 this.baseHref = baseHref;
422 }
423 Generator.prototype.process = function (config) {
424 return __awaiter(this, void 0, void 0, function () {
425 var unorderedHashTable, assetGroups;
426 return __generator(this, function (_a) {
427 switch (_a.label) {
428 case 0:
429 unorderedHashTable = {};
430 return [4 /*yield*/, this.processAssetGroups(config, unorderedHashTable)];
431 case 1:
432 assetGroups = _a.sent();
433 return [2 /*return*/, {
434 configVersion: 1,
435 timestamp: Date.now(),
436 appData: config.appData,
437 index: joinUrls(this.baseHref, config.index),
438 assetGroups: assetGroups,
439 dataGroups: this.processDataGroups(config),
440 hashTable: withOrderedKeys(unorderedHashTable),
441 navigationUrls: processNavigationUrls(this.baseHref, config.navigationUrls),
442 }];
443 }
444 });
445 });
446 };
447 Generator.prototype.processAssetGroups = function (config, hashTable) {
448 return __awaiter(this, void 0, void 0, function () {
449 var seenMap;
450 var _this = this;
451 return __generator(this, function (_a) {
452 seenMap = new Set();
453 return [2 /*return*/, Promise.all((config.assetGroups || []).map(function (group) { return __awaiter(_this, void 0, void 0, function () {
454 var fileMatcher, allFiles, matchedFiles;
455 var _this = this;
456 return __generator(this, function (_a) {
457 switch (_a.label) {
458 case 0:
459 if (group.resources.versionedFiles) {
460 throw new Error("Asset-group '" + group.name + "' in 'ngsw-config.json' uses the 'versionedFiles' option, " +
461 'which is no longer supported. Use \'files\' instead.');
462 }
463 fileMatcher = globListToMatcher(group.resources.files || []);
464 return [4 /*yield*/, this.fs.list('/')];
465 case 1:
466 allFiles = _a.sent();
467 matchedFiles = allFiles.filter(fileMatcher).filter(function (file) { return !seenMap.has(file); }).sort();
468 matchedFiles.forEach(function (file) { return seenMap.add(file); });
469 // Add the hashes.
470 return [4 /*yield*/, matchedFiles.reduce(function (previous, file) { return __awaiter(_this, void 0, void 0, function () {
471 var hash;
472 return __generator(this, function (_a) {
473 switch (_a.label) {
474 case 0: return [4 /*yield*/, previous];
475 case 1:
476 _a.sent();
477 return [4 /*yield*/, this.fs.hash(file)];
478 case 2:
479 hash = _a.sent();
480 hashTable[joinUrls(this.baseHref, file)] = hash;
481 return [2 /*return*/];
482 }
483 });
484 }); }, Promise.resolve())];
485 case 2:
486 // Add the hashes.
487 _a.sent();
488 return [2 /*return*/, {
489 name: group.name,
490 installMode: group.installMode || 'prefetch',
491 updateMode: group.updateMode || group.installMode || 'prefetch',
492 cacheQueryOptions: buildCacheQueryOptions(group.cacheQueryOptions),
493 urls: matchedFiles.map(function (url) { return joinUrls(_this.baseHref, url); }),
494 patterns: (group.resources.urls || []).map(function (url) { return urlToRegex(url, _this.baseHref, true); }),
495 }];
496 }
497 });
498 }); }))];
499 });
500 });
501 };
502 Generator.prototype.processDataGroups = function (config) {
503 var _this = this;
504 return (config.dataGroups || []).map(function (group) {
505 return {
506 name: group.name,
507 patterns: group.urls.map(function (url) { return urlToRegex(url, _this.baseHref, true); }),
508 strategy: group.cacheConfig.strategy || 'performance',
509 maxSize: group.cacheConfig.maxSize,
510 maxAge: parseDurationToMs(group.cacheConfig.maxAge),
511 timeoutMs: group.cacheConfig.timeout && parseDurationToMs(group.cacheConfig.timeout),
512 cacheQueryOptions: buildCacheQueryOptions(group.cacheQueryOptions),
513 version: group.version !== undefined ? group.version : 1,
514 };
515 });
516 };
517 return Generator;
518 }());
519 function processNavigationUrls(baseHref, urls) {
520 if (urls === void 0) { urls = DEFAULT_NAVIGATION_URLS; }
521 return urls.map(function (url) {
522 var positive = !url.startsWith('!');
523 url = positive ? url : url.substr(1);
524 return { positive: positive, regex: "^" + urlToRegex(url, baseHref) + "$" };
525 });
526 }
527 function globListToMatcher(globs) {
528 var patterns = globs.map(function (pattern) {
529 if (pattern.startsWith('!')) {
530 return {
531 positive: false,
532 regex: new RegExp('^' + globToRegex(pattern.substr(1)) + '$'),
533 };
534 }
535 else {
536 return {
537 positive: true,
538 regex: new RegExp('^' + globToRegex(pattern) + '$'),
539 };
540 }
541 });
542 return function (file) { return matches(file, patterns); };
543 }
544 function matches(file, patterns) {
545 var res = patterns.reduce(function (isMatch, pattern) {
546 if (pattern.positive) {
547 return isMatch || pattern.regex.test(file);
548 }
549 else {
550 return isMatch && !pattern.regex.test(file);
551 }
552 }, false);
553 return res;
554 }
555 function urlToRegex(url, baseHref, literalQuestionMark) {
556 if (!url.startsWith('/') && url.indexOf('://') === -1) {
557 // Prefix relative URLs with `baseHref`.
558 // Strip a leading `.` from a relative `baseHref` (e.g. `./foo/`), since it would result in an
559 // incorrect regex (matching a literal `.`).
560 url = joinUrls(baseHref.replace(/^\.(?=\/)/, ''), url);
561 }
562 return globToRegex(url, literalQuestionMark);
563 }
564 function joinUrls(a, b) {
565 if (a.endsWith('/') && b.startsWith('/')) {
566 return a + b.substr(1);
567 }
568 else if (!a.endsWith('/') && !b.startsWith('/')) {
569 return a + '/' + b;
570 }
571 return a + b;
572 }
573 function withOrderedKeys(unorderedObj) {
574 var orderedObj = {};
575 Object.keys(unorderedObj).sort().forEach(function (key) { return orderedObj[key] = unorderedObj[key]; });
576 return orderedObj;
577 }
578 function buildCacheQueryOptions(inOptions) {
579 return Object.assign({ ignoreVary: true }, inOptions);
580 }
581
582 /**
583 * @license
584 * Copyright Google LLC All Rights Reserved.
585 *
586 * Use of this source code is governed by an MIT-style license that can be
587 * found in the LICENSE file at https://angular.io/license
588 */
589
590 /**
591 * @license
592 * Copyright Google LLC All Rights Reserved.
593 *
594 * Use of this source code is governed by an MIT-style license that can be
595 * found in the LICENSE file at https://angular.io/license
596 */
597
598 /**
599 * Generated bundle index. Do not edit.
600 */
601
602 exports.Generator = Generator;
603
604 Object.defineProperty(exports, '__esModule', { value: true });
605
606})));
607//# sourceMappingURL=service-worker-config.umd.js.map