-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathoffline.ts
88 lines (65 loc) · 2.29 KB
/
offline.ts
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
namespace $ {
export class $mol_offline extends $mol_service_plugin_cache {
static blocked_urls = [
'//cse.google.com/adsense/search/async-ads.js'
]
static override blocked( request: Request ) {
const normalized_url = request.url.replace( /^https?:/, '' )
return this.blocked_urls.includes(normalized_url)
}
static override activate() {
this.$.$mol_service_worker.claim()
}
static override need_modify(request: Request) {
if( request.method !== 'GET' ) return false
if( !/^https?:/.test( request.url ) ) return false
if( /\?/.test( request.url ) ) return false
if( request.cache === 'no-store' ) return false
return true
}
protected static fetch(request: Request, fallback_header?: string) {
const raw = this.$.$mol_fetch.response(request).native
if (raw.status < 400) return raw
if (! this.corp() && ! fallback_header) return raw
const response = raw.clone()
const headers = response.headers
if ( this.corp() ) {
headers.set( 'Cross-Origin-Embedder-Policy', 'require-corp' )
headers.set( 'Cross-Origin-Opener-Policy', 'same-origin' )
}
if (fallback_header) {
headers.set( '$mol_offline_remote_status', `${fallback_header} $mol_offline fallback to cache`)
}
return response
}
static corp() { return false }
static override modify(request: Request) {
let fallback_header
const html = request.mode === 'navigate'
const cache = request.cache
if (cache === 'reload' || ( cache === 'no-cache' && ! html ) ) {
if (cache === 'reload') {
// F5 + Disable cache
request = new ($mol_wire_sync(Request))(request, { cache: 'no-cache' })
}
// fetch with fallback to cache if statuses not match
try {
const response = this.fetch(request)
if (response.status < 400) return response
fallback_header = response.statusText || `HTTP Error ${ response.status }`
} catch (err) {
if ( $mol_promise_like(err) ) $mol_fail_hidden(err)
fallback_header = (err as Error).message || 'Fetch error'
}
}
if (cache !== 'force-cache') {
request = new ($mol_wire_sync(Request))(request, { cache: 'force-cache' })
}
const cached = this.fetch(request, fallback_header)
return cached
}
}
export namespace $mol_service_plugin {
export let $mol_offline = $.$mol_offline
}
}