forked from eskema/alphaama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcash.js
115 lines (97 loc) · 2.09 KB
/
cash.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
/*
alphaama
cash
cache service worker
*/
const cash =
{
def:
{
id:'cash',
ls:
[
'/',
'/index.html',
'/site.webmanifest',
'/stuff/420.html',
'/stuff/font.otf',
'/stuff/font.otf.woff2',
'/stuff/favicon-32x32.png',
'/stuff/favicon-16x16.png',
'/stuff/safari-pinned-tab.svg',
'/stuff/android-chrome-192x192.png',
'/stuff/android-chrome-512x512.png',
'/stuff/apple-touch-icon.png',
'/aa/aa.js'
]
}
};
// if we have the request cached, serve that,
// if not, then fetch, cache and serve it
cash.flow =async e=>
{
let res = await caches.match(e.request);
if (res) return res;
res = await e.preloadResponse;
if (res && res.ok)
{
cash.put(e.request,res.clone());
return res
}
try
{
res = await fetch(e.request);
cash.put(e.request,res.clone());
return res
}
catch (er)
{
res = await caches.match('/');
if (res) return res;
return new Response('wut?',{status:408,headers:{'Content-Type':'text/plain'}});
}
};
addEventListener('fetch',e=>{e.respondWith(cash.flow(e))});
// cache ops
cash.get =async a=>
{
const cache = await caches.open(cash.def.id);
const results = await cache.matchAll(a);
postMessage(results);
};
cash.add =async a=>
{
const cache = await caches.open(cash.def.id);
await cache.addAll(a);
};
cash.put =async(k,res)=>
{
if (typeof k === 'object' && k.url && k.url.startsWith('chrome')) return;
const cache = await caches.open(cash.def.id);
await cache.put(k,res);
};
cash.rm =async key=>
{
const cache = await caches.open(cash.def.id);
cache.delete(key)
};
cash.clear =async()=>
{
const cache = await caches.open(cash.def.id);
const results = await cache.matchAll([]);
for (const res of results) cash.rm(res);
};
onactivate =e=>
{
e.waitUntil(async()=>
{
if (registration.navigationPreload)
await registration.navigationPreload.enable()
})
};
oninstall =e=>{e.waitUntil(cash.add(cash.def.ls))};
onmessage =e=>
{
const ops = e.data;
for (const k in ops) if (cash.hasOwnProperty(k)) cash[k](ops[k])
};