-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathworker.js
More file actions
106 lines (88 loc) · 2.42 KB
/
worker.js
File metadata and controls
106 lines (88 loc) · 2.42 KB
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
import e404Html from './404.template.html'
const translations = {
'de': (await import('./translations/de.txt')).default,
'en': (await import('./translations/en.txt')).default,
'fr': (await import('./translations/fr.txt')).default,
'hi': (await import('./translations/hi.txt')).default,
}
// The above cannot put in a loop because Wrangler (2.11) chokes on imports with dynamic names.
const indexHtml = (await import('./index.template.html')).default
.replaceAll('\n', '')
.replaceAll(' ', '')
.replaceAll(': ', ':')
.replaceAll(';}', '}')
const translateHtml = (await import('./translate.template.html')).default
.replace('{{TEXT}}', translations['en']
.trim()
.replaceAll('<', '<')
.replaceAll('>', '>')
)
export default {
fetch,
}
async function fetch(request, env) {
const {pathname} = new URL(request.url)
let ip
if (env.isDev) {
ip = generateRandomIpv4OrIpv6Address()
}
else {
ip = request.headers.get('cf-connecting-ip')
}
let body = ''
let status = 200
const headers = new Headers()
headers.append('Content-Type', 'text/html; charset=utf-8')
headers.append('Strict-Transport-Security', 'max-age=33333333; includeSubDomains; preload')
switch (pathname) {
case '/':
body = transform(indexHtml, ip, getLang(request.headers.get('accept-language')))
break
case '/translate':
body = translateHtml
break
default:
status = 404
body = e404Html
}
return new Response(body, {
status,
headers,
})
}
function transform(html, ip, lang) {
const translationLines = translations[lang].split('\n')
html = html
.replace('{{LANG}}', lang)
.replaceAll(/\{\{LINE([0-9]+)\}\}/g, (all, p1) => {
return translationLines[p1 - 1]
})
.replaceAll('{{IP}}', ip)
.replace(' copyElement.value.length', ip.length)
return html
}
function getLang(header) {
if (!header) {
return 'en'
}
header = header.toLowerCase()
const langs = header.split(/(?:,|;)/)
for (let lang of langs) {
if (lang in translations) {
return lang
}
const [base] = lang.split('-')
if (base in translations) {
return base
}
}
return 'en'
}
function generateRandomIpv4OrIpv6Address() {
if (Math.random() < .5) {
return crypto.getRandomValues(new Uint8Array(4)).join('.')
}
else {
return Array.from(crypto.getRandomValues(new Uint16Array(8))).map((e) => e.toString(16)).join(':')
}
}