-
Notifications
You must be signed in to change notification settings - Fork 3
/
dsw.js
2033 lines (1826 loc) · 88.6 KB
/
dsw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const PWASettings = {
"dswVersion": 1.0,
"applyImmediately": true,
"appShell": [
"/vibe.js/index.html?homescreen=1",
"/vibe.js/images/table.jpg",
"/vibe.js/images/vib.png",
"/vibe.js/images/nasc-logo.png",
"/vibe.js/images/cellphone.png",
"/vibe.js/audios/vibrate-sound.mp3"
],
"enforceSSL": false,
"keepUnusedCaches": false,
"dswRules": {
"images": {
"match": { "extension": ["jpg", "gif", "png", "jpeg", "webp"] },
"apply": {
"cache": {
"name": "cachedImages",
"version": "1"
}
}
},
"statics": {
"match": { "extension": ["js", "css"] },
"strategy": "fastest",
"apply": {
"cache": {
"name": "static-files",
"version": "1",
"expires": "1h"
}
}
},
"static-html": {
"match": [
{ "extension": ["html"] },
{ "path": "/$" }
],
"strategy": "fastest",
"apply": {
"cache": {
"name": "static-html-files",
"version": "1"
}
}
},
"pageNotFound": {
"match": {
"status": [404]
},
"apply": {
"fetch": "/vibe.js/not-found.html"
}
},
"imageNotFound": {
"match": {
"status": [404, 500],
"extension": ["jpg", "gif", "png", "jpeg", "webp"]
},
"apply": {
"fetch": "/vibe.js/404.jpg"
}
}
}
};
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function getBestMatchingRX(str, expressions) {
var bestMatchingRX = void 0;
var bestMatchingGroupSize = Number.MAX_SAFE_INTEGER;
var bestMatchingGroup = void 0;
expressions.forEach(function (currentRX) {
var regex = new RegExp(currentRX.rx);
var groups = str.match(regex);
if (groups && groups.length < bestMatchingGroupSize) {
bestMatchingRX = currentRX;
bestMatchingGroupSize = groups.length;
bestMatchingGroup = groups;
}
});
return bestMatchingRX ? {
rule: bestMatchingRX,
matching: bestMatchingGroup
} : false;
}
exports.default = getBestMatchingRX;
},{}],2:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _indexeddbManager = require('./indexeddb-manager.js');
var _indexeddbManager2 = _interopRequireDefault(_indexeddbManager);
var _utils = require('./utils.js');
var _utils2 = _interopRequireDefault(_utils);
var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_CACHE_NAME = 'defaultDSWCached';
var CACHE_CREATED_DBNAME = 'cacheCreatedTime';
var DEFAULT_CACHE_VERSION = null;
var DSWManager = void 0,
PWASettings = void 0,
goFetch = void 0;
// finds the real size of an utf-8 string
function lengthInUtf8Bytes(str) {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
var parseExpiration = function parseExpiration(rule, expires) {
var duration = expires || -1;
if (typeof duration == 'string') {
// let's use a formated string to know the expiration time
var sizes = {
s: 1,
m: 60,
h: 3600,
d: 86400,
w: 604800,
M: 2592000,
Y: 31449600
};
var size = duration.slice(-1),
val = duration.slice(0, -1);
if (sizes[size]) {
duration = val * sizes[size];
} else {
_logger2.default.warn('Invalid duration ' + duration, rule);
duration = -1;
}
}
if (duration >= 0) {
return parseInt(duration, 10) * 1000;
} else {
return 0;
}
};
var cacheManager = {
setup: function setup(DSWMan, PWASet, ftch) {
PWASettings = PWASet;
DSWManager = DSWMan;
goFetch = ftch;
DEFAULT_CACHE_VERSION = PWASettings.dswVersion || '1';
_indexeddbManager2.default.setup(cacheManager);
// we will also create an IndexedDB to store the cache creationDates
// for rules that have cash expiration
_indexeddbManager2.default.create({
version: 1,
name: CACHE_CREATED_DBNAME,
key: 'url'
});
},
registeredCaches: [],
createDB: function createDB(db) {
return _indexeddbManager2.default.create(db);
},
// Delete all the unused caches for the new version of the Service Worker
deleteUnusedCaches: function deleteUnusedCaches(keepUnused) {
if (!keepUnused) {
return caches.keys().then(function (keys) {
cacheManager.registeredCaches;
return Promise.all(keys.map(function (key) {
if (cacheManager.registeredCaches.indexOf(key) < 0) {
return caches.delete(key);
}
}));
});
}
},
// return a name for a default rule or the name for cache using the version
// and a separator
mountCacheId: function mountCacheId(rule) {
if (typeof rule == 'string') {
return rule;
}
var cacheConf = rule ? rule.action.cache : false;
if (cacheConf) {
return (cacheConf.name || DEFAULT_CACHE_NAME) + '::' + (cacheConf.version || DEFAULT_CACHE_VERSION);
}
return DEFAULT_CACHE_NAME + '::' + DEFAULT_CACHE_VERSION;
},
register: function register(rule) {
cacheManager.registeredCaches.push(cacheManager.mountCacheId(rule));
},
// just a different method signature, for .add
put: function put(rule, request, response) {
return cacheManager.add(request, typeof rule == 'string' ? rule : cacheManager.mountCacheId(rule), response, rule);
},
add: function add(request, cacheId, response, rule) {
cacheId = cacheId || cacheManager.mountCacheId(rule);
return new Promise(function (resolve, reject) {
function addIt(response) {
if (response.status == 200 || response.type == 'opaque') {
caches.open(cacheId).then(function (cache) {
// adding to cache
var opts = response.type == 'opaque' ? { mode: 'no-cors' } : {};
request = _utils2.default.createRequest(request, opts);
if (request.method != 'POST') {
(function () {
var cacheData = {};
if (rule && rule.action && rule.action.cache) {
cacheData = rule.action.cache;
} else {
cacheData = {
name: cacheId,
version: cacheId.split('::')[1]
};
}
var clonedResponse = void 0;
if (response.bodyUsed) {
// sometimes, due to different flows, the
// request body may have been already used
// In this case, we use cache.add instead
// of cache.put
cache.add(request).then(function (cached) {
DSWManager.traceStep(request, 'Added to cache', { cacheData: cacheData });
}).catch(function (err) {
_logger2.default.error('Could not save into cache', err);
});
} else {
clonedResponse = response.clone();
DSWManager.traceStep(request, 'Added to cache', { cacheData: cacheData });
cache.put(request, clonedResponse);
}
})();
}
resolve(response);
// in case it is supposed to expire
if (rule && rule.action && rule.action.cache && rule.action.cache.expires) {
// saves the current time for further validation
cacheManager.setExpiringTime(request, rule || cacheId, rule.action.cache.expires);
}
}).catch(function (err) {
_logger2.default.error('Could not save into cache', err);
resolve(response);
});
} else {
reject(response);
}
}
if (!response) {
fetch(goFetch(null, request)).then(addIt).catch(function (err) {
DSWManager.traceStep(request, 'Fetch failed');
_logger2.default.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
reject(response);
});
} else {
addIt(response);
}
});
},
setExpiringTime: function setExpiringTime(request, rule) {
var expiresAt = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2];
if (typeof expiresAt == 'string') {
expiresAt = parseExpiration(rule, expiresAt);
}
_indexeddbManager2.default.addOrUpdate({
url: request.url || request,
dateAdded: new Date().getTime(),
expiresAt: expiresAt
}, CACHE_CREATED_DBNAME);
},
hasExpired: function hasExpired(request) {
return new Promise(function (resolve, reject) {
_indexeddbManager2.default.find(CACHE_CREATED_DBNAME, 'url', request.url || request).then(function (r) {
if (r && new Date().getTime() > r.dateAdded + r.expiresAt) {
resolve(true);
} else {
resolve(false);
}
}).catch(function (_) {
resolve(false);
});
});
},
get: function get(rule, request, event, matching, forceFromCache) {
var actionType = Object.keys(rule.action)[0],
url = request.url || request,
pathName = new URL(url).pathname;
// requests to / should be cached by default
if (rule.action.cache !== false && (pathName == '/' || pathName.match(/^\/index\.([a-z0-9]+)/i))) {
rule.action.cache = rule.action.cache || {};
}
var opts = rule.options || {};
opts.headers = opts.headers || new Headers();
actionType = actionType.toLowerCase();
// let's allow an idb alias for indexeddb...maybe we could move it to a
// separated structure
actionType = actionType == 'idb' ? 'indexeddb' : actionType;
// cache may expire...if so, we will use this verification afterwards
var verifyCache = void 0;
if (rule.action.cache && rule.action.cache.expires) {
verifyCache = cacheManager.hasExpired(request);
} else {
// if it will not expire, we just use it as a resolved promise
verifyCache = Promise.resolve();
}
switch (actionType) {
case 'bypass':
{
// if it is a bypass action (no rule shall be applied, at all)
if (rule.action[actionType] == 'request') {
// it may be of type request
// and we will simple allow it to go ahead
// this also means we will NOT treat any result from it
//logger.info('Bypassing request, going for the network for', request.url);
var treatResponse = function treatResponse(response) {
if (response.status >= 200 && response.status < 300) {
DSWManager.traceStep(request, 'Request bypassed');
return response;
} else {
DSWManager.traceStep(request, 'Bypassed request failed and was ignored');
var resp = new Response(''); // ignored
return resp;
}
};
// here we will use a "raw" fetch, instead of goFetch, which would
// create a new Request and define propreties to it
return fetch(goFetch(null, event.request)).then(treatResponse).catch(treatResponse);
} else {
// or of type 'ignore' (or anything else, actually)
// and we will simply output nothing, as if ignoring both the
// request and response
DSWManager.traceStep(request, 'Bypassed request');
actionType = 'output';
rule.action[actionType] = '';
}
}
case 'output':
{
DSWManager.traceStep(request, 'Responding with string output', { output: (rule.action[actionType] + '').substring(0, 180) });
return new Response(_utils2.default.applyMatch(matching, rule.action[actionType]));
}
case 'indexeddb':
{
return new Promise(function (resolve, reject) {
// function to be used after fetching
function treatFetch(response) {
if (response && response.status == 200) {
// with success or not(saving it), we resolve it
var done = function done(err) {
if (err) {
DSWManager.traceStep(request, 'Could not save response into IndexedDB', { err: err });
} else {
DSWManager.traceStep(request, 'Response object saved into IndexedDB');
}
resolve(response);
};
// store it in the indexedDB
_indexeddbManager2.default.save(rule.name, response.clone(), request, rule).then(done).catch(done); // if failed saving, we still have the reponse to deliver
} else {
// if it failed, we can look for a fallback
url = request.url;
pathName = new URL(url).pathname;
DSWManager.traceStep(request, 'Fetch failed', {
url: request.url,
status: response.status,
statusText: response.statusText
});
return DSWManager.treatBadPage(response, pathName, event);
}
}
// let's look for it in our cache, and then in the database
// (we use the cache, just so we can user)
_indexeddbManager2.default.get(rule.name, request).then(function (result) {
// if we did have it in the indexedDB
if (result) {
// we use it
return treatFetch(result);
} else {
// if it was not stored, let's fetch it
//request = DSWManager.createRequest(request, event, matching);
return goFetch(rule, request, event, matching).then(treatFetch).catch(treatFetch);
}
});
});
}
case 'redirect':
case 'fetch':
{
request = DSWManager.createRedirect(rule.action.fetch || rule.action.redirect, event, matching);
url = request.url;
pathName = new URL(url).pathname;
// keep going to be treated with the cache case
}
case 'cache':
{
var cacheId = void 0;
if (rule.action.cache) {
cacheId = cacheManager.mountCacheId(rule);
}
// lets verify if the cache is expired or not
return verifyCache.then(function (expired) {
var lookForCache = void 0;
if (expired && !forceFromCache) {
// in case it has expired, it resolves automatically
// with no results from cache
DSWManager.traceStep(event.request, 'Cache was expired');
lookForCache = Promise.resolve();
//logger.info('Cache expired for ', request.url);
} else {
// if not expired, let's look for it!
lookForCache = caches.match(request);
}
// look for the request in the cache
return lookForCache.then(function (result) {
// if it does not exist (cache could not be verified)
if (result && result.status != 200) {
DSWManager.traceStep(event.request, 'Fetch failed', {
url: request.url,
status: result.status,
statusText: result.statusText
});
// if it has expired in cache, failed requests for
// updates should return the previously cached data
// even if it has expired
if (expired) {
DSWManager.traceStep(request, 'Forcing ' + (expired ? 'expired ' : '') + 'result from cache');
// the true argument flag means it should come from cache, anyways
return cacheManager.get(rule, request, event, matching, true);
}
// look for rules that match for the request and its status
(DSWManager.rules[result.status] || []).some(function (cur, idx) {
if (pathName.match(cur.rx)) {
// if a rule matched for the status and request
// and it tries to fetch a different source
if (cur.action.fetch || cur.action.redirect) {
DSWManager.traceStep(event.request, 'Found fallback for failure', {
rule: cur,
url: request.url
});
// problematic requests should
result = goFetch(rule, request, event, matching);
return true; // stopping the loop
}
}
});
// we, then, return the promise of the failed result(for it
// could not be loaded and was not in cache)
return result;
} else {
// We will return the result, if successful, or
// fetch an anternative resource(or redirect)
// and treat both success and failure with the
// same "callback"
// In case it is a redirect, we also set the header to 302
// and really change the url of the response.
if (result) {
// when it comes from a redirect, we let the browser know about it
// or else...we simply return the result itself
if (request.url == event.request.url) {
DSWManager.traceStep(event.request, 'Result from cache', {
url: event.request.url
});
return result;
} else {
// coming from a redirect
DSWManager.traceStep(event.request, 'Must redirect', {
from: event.request.url,
to: request.url
}, false, {
url: request.url,
id: request.requestId,
steps: request.traceSteps
});
return Response.redirect(request.url, 302);
}
} else if (actionType == 'redirect') {
// if this is supposed to redirect
DSWManager.traceStep(event.request, 'Must redirect', {
from: event.request.url,
to: request.url
});
return Response.redirect(request.url, 302);
} else {
// this is a "normal" request, let's deliver it
// but we will be using a new Request with some info
// to allow browsers to understand redirects in case
// it must be redirected later on
var treatFetch = function treatFetch(response) {
if (response.type == 'opaque') {
// if it is a opaque response, let it go!
if (rule.action.cache !== false) {
DSWManager.traceStep(event.request, 'Added to cache (opaque)');
return cacheManager.add(_utils2.default.createRequest(request, { mode: request.mode || 'no-cors' }), cacheManager.mountCacheId(rule), response, rule);
}
return response;
}
if (!response.status) {
response.status = 404;
}
// after retrieving it, we cache it
// if it was ok
if (response.status == 200) {
DSWManager.traceStep(event.request, 'Received result OK (200)');
// if cache is not false, it will be added to cache
if (rule.action.cache !== false) {
// let's save it into cache
DSWManager.traceStep(event.request, 'Saving into cache');
return cacheManager.add(request, cacheManager.mountCacheId(rule), response, rule);
} else {
return response;
}
} else {
// if it had expired, but could not be retrieved
// from network, let's give its cache a chance!
DSWManager.traceStep(event.request, 'Failed fetching');
if (expired) {
_logger2.default.warn('Cache for ', request.url || request, 'had expired, but the updated version could not be retrieved from the network!\n', 'Delivering the outdated cached data');
DSWManager.traceStep(event.request, 'Used expired cache', { note: 'Failed fetching, loading from cache even though it was expired' });
return cacheManager.get(rule, request, event, matching, true);
}
// otherwise...let's see if there is a fallback
// for the 404 requisition
return DSWManager.treatBadPage(response, pathName, event);
}
};
DSWManager.traceStep(event.request, 'Must fetch', {
url: request.url,
method: request.method
});
return goFetch(rule, request, event, matching).then(treatFetch).catch(treatFetch);
}
}
}); // end lookForCache
}); // end verifyCache
}
default:
{
// also used in fetch actions
return event;
}
}
}
};
exports.default = cacheManager;
},{"./indexeddb-manager.js":4,"./logger.js":5,"./utils.js":8}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = require('./utils.js');
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var origin = location.origin;
function goFetch(rule, request, event, matching) {
var tmpUrl = rule ? rule.action.fetch || rule.action.redirect : '';
if (typeof request == 'string') {
request = location.origin + request;
}
if (!tmpUrl) {
tmpUrl = request.url || request;
}
var originalUrl = tmpUrl;
var sameOrigin = new URL(tmpUrl).origin == origin;
// if there are group variables in the matching expression
tmpUrl = _utils2.default.applyMatch(matching, tmpUrl);
// if no rule is passed
if (request && !rule) {
// we will just create a simple request to be used "anywhere"
var req = new Request(tmpUrl, {
method: request.method || 'GET',
headers: request.headers || {},
mode: request.mode || (sameOrigin ? 'cors' : 'no-cors'),
cache: 'default',
redirect: 'manual'
});
if (request.body) {
req.body = request.body;
}
req.requestId = (event ? event.request : request).requestId;
req.traceSteps = (event ? event.request : request).traceSteps;
return req;
}
var actionType = Object.keys(rule.action)[0];
var opts = rule.options || {};
opts.headers = opts.headers || new Headers();
// if the cache options is false, we force it not to be cached
if (rule.action.cache === false) {
opts.headers.append('pragma', 'no-cache');
opts.headers.append('cache-control', 'no-store,no-cache');
tmpUrl = tmpUrl + (tmpUrl.indexOf('?') > 0 ? '&' : '?') + new Date().getTime();
}
// we will create a new request to be used, based on what has been
// defined by the rule or current request
var reqConfig = {
method: opts.method || request.method,
headers: opts || request.headers,
mode: actionType == 'redirect' ? request.mode || 'same-origin' : 'cors',
redirect: actionType == 'redirect' ? 'manual' : request.redirect
};
// if (request.credentials && request.credentials != 'omit') {
// reqConfig.credentials = request.credentials;
// }
// if the host is not the same
if (!sameOrigin) {
// we set it to an opaque request
reqConfig.mode = request.mode || 'no-cors';
}
request = new Request(tmpUrl || request.url, reqConfig);
request.requestId = (event ? event.request : request).requestId;
request.traceSteps = (event ? event.request : request).traceSteps;
if (actionType == 'redirect') {
// if this is supposed to redirect
return Response.redirect(request.url, 302);
} else {
// if this is a "normal" request, let's deliver it
// but we will be using a new Request with some info
// to allow browsers to understand redirects in case
// it must be redirected later on
return fetch(request, opts);
}
}
exports.default = goFetch;
},{"./utils.js":8}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_DB_NAME = 'defaultDSWDB';
var INDEXEDDB_REQ_IDS = 'indexeddb-id-request';
var dbs = {};
var cacheManager;
function getObjectStore(dbName) {
var mode = arguments.length <= 1 || arguments[1] === undefined ? 'readwrite' : arguments[1];
var db = dbs[dbName],
tx = void 0;
if (db) {
tx = db.transaction(dbName, mode);
return tx.objectStore(dbName);
}
return false;
}
var indexedDBManager = {
setup: function setup(cm) {
cacheManager = cm;
},
create: function create(config) {
return new Promise(function (resolve, reject) {
var request = indexedDB.open(config.name || DEFAULT_DB_NAME, parseInt(config.version, 10) || undefined);
function dataBaseReady(db, dbName, resolve) {
db.onversionchange = function (event) {
db.close();
_logger2.default.log('There is a new version of the database(IndexedDB) for ' + config.name);
};
if (!dbs[dbName]) {
dbs[dbName] = db;
}
resolve(config);
}
request.onerror = function (event) {
reject('Could not open the database (indexedDB) for ' + config.name);
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
var baseData = {};
if (config.key) {
baseData.keyPath = config.key;
}
if (!config.key || config.autoIncrement) {
baseData.autoIncrement = true;
}
if (config.version) {
baseData.version = config.version;
} else {
baseData.version = 1;
}
if (event.oldVersion && event.oldVersion < baseData.version) {
// in case there already is a store with that name
// with a previous version
db.deleteObjectStore(config.name);
} else if (event.oldVersion === 0) {
(function () {
// if it is the first time it is creating it
var objectStore = db.createObjectStore(config.name, baseData);
// in case there are indexes defined, we create them
if (config.indexes) {
config.indexes.forEach(function (index) {
if (typeof index == 'string') {
objectStore.createIndex(index, index, {});
} else {
objectStore.createIndex(index.name, index.path || index.name, index.options);
}
});
}
// we will also make the key, an index
objectStore.createIndex(config.key, config.key, { unique: true });
})();
}
dataBaseReady(db, config.name, resolve);
};
request.onsuccess = function (event) {
var db = event.target.result;
dataBaseReady(db, config.name, resolve);
};
});
},
get: function get(dbName, request) {
return new Promise(function (resolve, reject) {
// We will actuallly look for its IDs in cache, to use them to find
// the real, complete object in the indexedDB
caches.match(request).then(function (result) {
if (result) {
result.json().then(function (obj) {
// if the request was in cache, we now have got
// the id=value for the indexes(keys) to look for,
// in the indexedDB!
var store = getObjectStore(dbName),
index = store ? store.index(obj.key) : false,
getter = index ? index.get(obj.value) : false;
// in case we did get the content from indexedDB
// let's create a new Response out of it!
if (getter) {
getter.onsuccess = function (event) {
resolve(new Response(JSON.stringify(event.target.result), {
headers: { 'Content-Type': 'application/json' }
}));
};
getter.onerror = function (event) {
// if we did not find it (or faced a problem) in
// indexeddb, we leave it to the network
resolve();
};
} else {
// in case it failed for some reason
// we leave it and allow it to be requested
resolve();
}
});
} else {
resolve();
}
});
});
},
find: function find(dbName, key, value) {
return new Promise(function (resolve, reject) {
var store = getObjectStore(dbName);
if (store) {
var index = store.index(key),
getter = index.get(value);
getter.onsuccess = function (event) {
resolve(event.target.result);
};
getter.onerror = function (event) {
reject();
};
} else {
resolve();
}
});
},
addOrUpdate: function addOrUpdate(obj, dbName) {
return new Promise(function (resolve, reject) {
var store = getObjectStore(dbName);
if (store) {
var req = store.put(obj);
req.onsuccess = function addOrUpdateSuccess() {
resolve(obj);
};
req.onerror = function addOrUpdateError(err) {
resolve(obj);
};
} else {
resolve({});
}
});
},
save: function save(dbName, data, request, rule) {
return new Promise(function (resolve, reject) {
data.json().then(function (obj) {
var store = getObjectStore(dbName),
req = void 0;
if (store) {
req = store.add(obj);
// We will use the CacheAPI to store, in cache, only the IDs for
// the given object
req.onsuccess = function () {
var tmp = {};
var key = rule.action.indexedDB.key || 'id';
tmp.key = key;
tmp.value = obj[key];
cacheManager.put(INDEXEDDB_REQ_IDS, request, new Response(JSON.stringify(tmp), {
headers: { 'Content-Type': 'application/json' }
}));
resolve();
};
req.onerror = function (event) {
reject('Failed saving to the indexedDB!', this.error);
};
} else {
reject('Failed saving into indexedDB!');
}
}).catch(function (err) {
_logger2.default.error('Failed saving into indexedDB!\n', err.message, err);
reject('Failed saving into indexedDB!');
});
});
}
};
exports.default = indexedDBManager;
},{"./logger.js":5}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var TYPES = {
log: '[ LG ] :: ',
info: '[ INFO ] :: ',
warn: '[ WARN ] :: ',
error: '[ FAIL ] :: ',
track: '[ STEP ] :: '
};
var logger = {
info: function info() {
var args = [].slice.call(arguments);
args.unshift('color: blue');
args.unshift('%c ' + TYPES.info);
console.info.apply(console, args);
},
log: function log() {
var args = [].slice.call(arguments);
args.unshift('color: gray');
args.unshift('%c ' + TYPES.log);
console.log.apply(console, args);
},
warn: function warn() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold; color: yellow; text-shadow: 0 0 1px black;');
args.unshift('%c ' + TYPES.warn);
console.warn.apply(console, args);
},
error: function error() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold; color: red');
args.unshift('%c ' + TYPES.error);
console.error.apply(console, args);
},
track: function track() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold');
args.unshift('%c ' + TYPES.track);
console.debug.apply(console, args);
}
};
exports.default = logger;
},{}],6:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
var _bestMatchingRx = require('./best-matching-rx.js');
var _bestMatchingRx2 = _interopRequireDefault(_bestMatchingRx);
var _cacheManager = require('./cache-manager.js');
var _cacheManager2 = _interopRequireDefault(_cacheManager);
var _goFetch = require('./go-fetch.js');
var _goFetch2 = _interopRequireDefault(_goFetch);
var _strategies = require('./strategies.js');
var _strategies2 = _interopRequireDefault(_strategies);
var _utils = require('./utils.js');
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// TODO: should pre-cache or cache in the first load, some of the page's already sources (like css, js or images), or tell the user it supports offline usage, only in the next reload
var isInSWScope = false;
var isInTest = typeof global.it === 'function';
var DSW = { version: '1.10.2' };
var REQUEST_TIME_LIMIT = 5000;
var REGISTRATION_TIMEOUT = 12000;
var DEFAULT_NOTIF_DURATION = 6000;
// this try/catch is used simply to figure out the current scope
try {
var SWScope = ServiceWorkerGlobalScope;
if (self instanceof ServiceWorkerGlobalScope) {
isInSWScope = true;
}
} catch (e) {/* nothing...just had to find out the scope */}
if (isInSWScope) {