-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
72 lines (64 loc) · 1.81 KB
/
worker.js
File metadata and controls
72 lines (64 loc) · 1.81 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
// UUID generator API (v4).
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'X-Robots-Tag': 'noindex, nofollow'
};
function generateUuid() {
if (crypto?.randomUUID) {
return crypto.randomUUID();
}
// Fallback for environments without randomUUID.
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0'));
return (
`${hex[0]}${hex[1]}${hex[2]}${hex[3]}` +
`-${hex[4]}${hex[5]}` +
`-${hex[6]}${hex[7]}` +
`-${hex[8]}${hex[9]}` +
`-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`
);
}
function jsonResponse(data, status = 200) {
return new Response(JSON.stringify(data), {
status,
headers: {
'Content-Type': 'application/json; charset=utf-8',
...CORS_HEADERS
}
});
}
function textResponse(text, status = 200) {
return new Response(text, {
status,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
...CORS_HEADERS
}
});
}
export default {
async fetch(request) {
if (request.method === 'OPTIONS') {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
const url = new URL(request.url);
if (url.pathname === '/robots.txt') {
return textResponse('User-agent: *\nDisallow: /\n');
}
if (url.pathname === '/health') {
return jsonResponse({ status: 'ok' });
}
// GET and POST both return a freshly generated UUID.
const uuid = generateUuid();
const plain = url.searchParams.get('plain') === '1';
if (plain) {
return textResponse(uuid);
}
return jsonResponse({ uuid });
}
};