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
import { decodeBase64, encodeBase64 } from "https://deno.land/std/encoding/base64.ts";
import Context from "https://deno.land/std@0.93.0/wasi/snapshot_preview1.ts";
/** Class representing a BufferResult. */
class BufferResult {
/**
* @member {Uint8Array}
*/
buffer: Uint8Array;
/**
* @member {boolean}
*/
isError = false;
/**
* Create a Buffer Result.
* @param {Uint8Array} buffer - the payload.
* @param {boolean} isError - is the result an error
*/
constructor(buffer: Uint8Array, isError: boolean) {
this.buffer = buffer;
this.isError = isError;
}
/**
* Convert buffer to string.
* @return {string} The string result.
*/
toString() {
return new TextDecoder("utf8").decode(this.buffer);
}
/**
* Convert buffer to Json object.
* @return {object} The JSON object result.
*/
toJson() {
return JSON.parse(new TextDecoder("utf8").decode(this.buffer));
}
}
function callHandlerWithString(
instance: WebAssembly.Instance,
payload: string,
) {
const bytes = new TextEncoder("utf8").encode(payload);
return callHandlerWithBytes(instance, bytes);
}
function callHandlerWithJson(instance: WebAssembly.Instance, payload: any) {
const bytes = new TextEncoder("utf8").encode(JSON.stringify(payload));
return callHandlerWithBytes(instance, bytes);
}
const MASK = 2n ** 32n - 1n;
function callHandlerWithBytes(
instance: WebAssembly.Instance,
bytes: Uint8Array,
) {
// Copy the contents of bytes payload into the module's memory
const ptr = instance.exports.alloc(bytes.length);
const mem = new Uint8Array(
instance.exports.memory["buffer"],
ptr,
bytes.length,
);
mem.set(new Uint8Array(bytes));
// Call `callHandler` and get a kind of pair of value
const pointerAndSize = instance.exports.callHandler(ptr, bytes.length);
const memory = instance.exports.memory;
const completeBufferFromMemory = new Uint8Array(memory.buffer);
// Extract the values of the pair
const ptrPosition = Number(pointerAndSize >> BigInt(32));
const stringSize = Number(pointerAndSize & MASK);
let extractedBuffer = completeBufferFromMemory.slice(
ptrPosition,
ptrPosition + stringSize,
);
return new BufferResult(
extractedBuffer.slice(1, stringSize),
extractedBuffer[0] === 69,
);
}
async function handleRequest(
instance: WebAssembly.Instance,
req: Request,
): Promise<Response> {
const resp = callHandlerWithJson(instance, {
url: req.url,
method: req.method,
body: encodeBase64(await req.text()),
headers: Object.fromEntries(req.headers.entries()),
});
if (resp.isError) {
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
v22
May 24, 2024