-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlink.js
More file actions
69 lines (59 loc) · 2.21 KB
/
Copy pathlink.js
File metadata and controls
69 lines (59 loc) · 2.21 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
// TileLoom link play: the entire game state travels inside the URL fragment,
// compressed with deflate and base64url-encoded. No server involved.
'use strict';
const LinkGame = (() => {
function b64encode(bytes) {
let bin = '';
for (let i = 0; i < bytes.length; i += 0x8000) {
bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
}
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function b64decode(str) {
const bin = atob(str.replace(/-/g, '+').replace(/_/g, '/'));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
async function compress(text) {
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw'));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
async function decompress(bytes) {
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
return new Response(stream).text();
}
// Returns a payload string: 'c<base64url>' (compressed) or 'r<base64url>'
async function encodeState(state) {
const json = JSON.stringify(state);
if (typeof CompressionStream !== 'undefined') {
try {
return 'c' + b64encode(await compress(json));
} catch (e) { /* fall through to raw */ }
}
return 'r' + b64encode(new TextEncoder().encode(json));
}
// Returns the decoded state object, or null if the payload is invalid
async function decodeState(payload) {
try {
const bytes = b64decode(payload.slice(1));
const json = payload[0] === 'c'
? await decompress(bytes)
: new TextDecoder().decode(bytes);
const s = JSON.parse(json);
if (!s || !Array.isArray(s.board) || !Array.isArray(s.players) ||
s.players.length !== 2) return null;
return s;
} catch (e) {
return null;
}
}
function urlFor(payload) {
return location.origin + location.pathname + '#g=' + payload;
}
function payloadFromLocation() {
const m = location.hash.match(/^#g=(.+)$/);
return m ? m[1] : null;
}
return { encodeState, decodeState, urlFor, payloadFromLocation };
})();