wasm-rquickjs 0.3.3

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
Documentation
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import { ws_connect } from '__wasm_rquickjs_builtin/websocket_native';
import { Event as NodeEvent } from 'node:events';

// readyState constants
const CONNECTING = 0;
const OPEN = 1;
const CLOSING = 2;
const CLOSED = 3;

// Compute the byte length of a UTF-8 encoded string
function utf8ByteLength(str) {
    let len = 0;
    for (let i = 0; i < str.length; i++) {
        let code = str.charCodeAt(i);
        if (code <= 0x7f) {
            len += 1;
        } else if (code <= 0x7ff) {
            len += 2;
        } else if (code >= 0xd800 && code <= 0xdbff) {
            // Surrogate pair — 4 bytes for the full code point
            len += 4;
            i++; // skip low surrogate
        } else {
            len += 3;
        }
    }
    return len;
}

// Normalize URL scheme: http:// → ws://, https:// → wss://
function normalizeWebSocketUrl(url) {
    if (url.startsWith('http://')) {
        return 'ws://' + url.slice(7);
    }
    if (url.startsWith('https://')) {
        return 'wss://' + url.slice(8);
    }
    return url;
}

const MESSAGE_EVENT_STATE = Symbol('MessageEvent.state');

function getMessageEventState(event) {
    const state = event?.[MESSAGE_EVENT_STATE];
    if (!state) {
        throw new TypeError('Value of "this" must be of type MessageEvent');
    }
    return state;
}

class MessageEvent extends NodeEvent {
    constructor(type, eventInitDictOrData = {}, legacyOrigin = '') {
        const init = eventInitDictOrData && typeof eventInitDictOrData === 'object' && (
            Object.prototype.hasOwnProperty.call(eventInitDictOrData, 'data') ||
            Object.prototype.hasOwnProperty.call(eventInitDictOrData, 'origin') ||
            Object.prototype.hasOwnProperty.call(eventInitDictOrData, 'lastEventId') ||
            Object.prototype.hasOwnProperty.call(eventInitDictOrData, 'source') ||
            Object.prototype.hasOwnProperty.call(eventInitDictOrData, 'ports')
        ) ? eventInitDictOrData : { data: eventInitDictOrData, origin: legacyOrigin };

        super(type, init);
        Object.defineProperty(this, MESSAGE_EVENT_STATE, {
            value: {
                data: init.data === undefined ? null : init.data,
                origin: init.origin === undefined ? '' : String(init.origin),
                lastEventId: init.lastEventId === undefined ? '' : String(init.lastEventId),
                source: init.source === undefined ? null : init.source,
                ports: init.ports === undefined ? [] : [...init.ports],
            },
            enumerable: false,
        });
    }

    get data() { return getMessageEventState(this).data; }
    get origin() { return getMessageEventState(this).origin; }
    get lastEventId() { return getMessageEventState(this).lastEventId; }
    get source() { return getMessageEventState(this).source; }
    get ports() { return getMessageEventState(this).ports; }
}

class CloseEvent {
    constructor(code, reason, wasClean) {
        this.type = 'close';
        this.code = code;
        this.reason = reason;
        this.wasClean = wasClean;
    }
}

class ErrorEvent {
    constructor(message) {
        this.type = 'error';
        this.message = message || '';
    }
}

class WebSocket {
    static CONNECTING = CONNECTING;
    static OPEN = OPEN;
    static CLOSING = CLOSING;
    static CLOSED = CLOSED;

    constructor(url, protocols) {
        if (arguments.length === 0) {
            throw new TypeError("Failed to construct 'WebSocket': 1 argument required, but only 0 present.");
        }

        // Validate and normalize URL
        if (typeof url !== 'string') {
            url = String(url);
        }

        // Check for URL fragments — not allowed per spec
        if (url.indexOf('#') !== -1) {
            throw new DOMException(
                "Failed to construct 'WebSocket': The URL '" + url + "' contains a fragment identifier.",
                'SyntaxError'
            );
        }

        // Normalize http/https to ws/wss per spec
        url = normalizeWebSocketUrl(url);

        if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
            throw new DOMException(
                "Failed to construct 'WebSocket': The URL's scheme must be either 'ws', 'wss', 'http', or 'https'. '" + url + "' is not allowed.",
                'SyntaxError'
            );
        }
        this._url = url;

        // Normalize protocols
        if (protocols === undefined || protocols === null) {
            this._protocols = [];
        } else if (typeof protocols === 'string') {
            this._protocols = [protocols];
        } else if (Array.isArray(protocols)) {
            this._protocols = protocols.slice();
        } else {
            this._protocols = [String(protocols)];
        }

        // Check for duplicate protocols per spec
        const seen = new Set();
        for (const p of this._protocols) {
            if (seen.has(p)) {
                throw new DOMException(
                    "Failed to construct 'WebSocket': The subprotocol '" + p + "' is duplicated.",
                    'SyntaxError'
                );
            }
            seen.add(p);
        }

        this._readyState = CONNECTING;
        this._binaryType = 'blob';
        this._bufferedAmount = 0;
        this._extensions = '';
        this._protocol = '';
        this._connection = null;

        // Event handlers
        this._onopen = null;
        this._onmessage = null;
        this._onerror = null;
        this._onclose = null;
        this._listeners = {};

        // Receive loop control
        this._receiveLoopRunning = false;

        // Connect asynchronously (per spec, constructor returns immediately)
        this._connectAsync();
    }

    _connectAsync() {
        Promise.resolve().then(() => {
            try {
                this._connection = ws_connect(this._url, this._protocols);
                this._readyState = OPEN;
                if (this._protocols.length > 0) {
                    this._protocol = this._protocols[0];
                }
                this._dispatch('open', { type: 'open' });
                this._startReceiveLoop();
            } catch (e) {
                this._readyState = CLOSED;
                this._dispatch('error', new ErrorEvent(e.message || String(e)));
                this._dispatch('close', new CloseEvent(1006, '', false));
            }
        });
    }

    async _startReceiveLoop() {
        if (this._receiveLoopRunning) return;
        this._receiveLoopRunning = true;

        while (this._readyState === OPEN && this._connection) {
            try {
                // Native module returns [type, data] arrays (async, uses WASI pollables):
                //   ["text", string]
                //   ["binary", ArrayBuffer]
                //   ["closed", { code, reason }]
                //   ["error", string]
                const result = await this._connection.receive();
                const [type, data] = result;

                if (type === 'text') {
                    this._dispatch('message', new MessageEvent('message', data, this._url));
                } else if (type === 'binary') {
                    // Always deliver as ArrayBuffer; Blob is not available in QuickJS.
                    this._dispatch('message', new MessageEvent('message', data, this._url));
                } else if (type === 'closed') {
                    this._receiveLoopRunning = false;
                    if (this._readyState !== CLOSED) {
                        this._readyState = CLOSED;
                        const code = (data && data.code) || 1000;
                        const reason = (data && data.reason) || '';
                        this._dispatch('close', new CloseEvent(code, reason, true));
                    }
                    return;
                } else if (type === 'error') {
                    this._receiveLoopRunning = false;
                    if (this._readyState !== CLOSED) {
                        this._readyState = CLOSED;
                        this._dispatch('error', new ErrorEvent(data || 'Unknown error'));
                        this._dispatch('close', new CloseEvent(1006, '', false));
                    }
                    return;
                }
            } catch (e) {
                this._receiveLoopRunning = false;
                if (this._readyState !== CLOSED) {
                    this._readyState = CLOSED;
                    this._dispatch('error', new ErrorEvent(e.message || String(e)));
                    this._dispatch('close', new CloseEvent(1006, '', false));
                }
                return;
            }
        }

        this._receiveLoopRunning = false;
    }

    get url() { return this._url; }
    get readyState() { return this._readyState; }
    get bufferedAmount() { return this._bufferedAmount; }
    get extensions() { return this._extensions; }
    get protocol() { return this._protocol; }

    get binaryType() { return this._binaryType; }
    set binaryType(value) {
        if (value === 'blob' || value === 'arraybuffer') {
            this._binaryType = value;
        }
    }

    get onopen() { return this._onopen; }
    set onopen(fn) { this._onopen = typeof fn === 'function' ? fn : null; }

    get onmessage() { return this._onmessage; }
    set onmessage(fn) { this._onmessage = typeof fn === 'function' ? fn : null; }

    get onerror() { return this._onerror; }
    set onerror(fn) { this._onerror = typeof fn === 'function' ? fn : null; }

    get onclose() { return this._onclose; }
    set onclose(fn) { this._onclose = typeof fn === 'function' ? fn : null; }

    send(data) {
        if (this._readyState === CONNECTING) {
            throw new DOMException(
                "Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.",
                'InvalidStateError'
            );
        }
        if (this._readyState !== OPEN) {
            return;
        }

        try {
            if (typeof data === 'string') {
                this._bufferedAmount += utf8ByteLength(data);
                this._connection.send_text(data);
                this._bufferedAmount = 0;
            } else if (data instanceof ArrayBuffer) {
                this._bufferedAmount += data.byteLength;
                this._connection.send_binary(new Uint8Array(data));
                this._bufferedAmount = 0;
            } else if (ArrayBuffer.isView(data)) {
                this._bufferedAmount += data.byteLength;
                this._connection.send_binary(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
                this._bufferedAmount = 0;
            } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
                // Blob support: read as ArrayBuffer and send as binary
                const reader = new FileReader();
                reader.onload = () => {
                    if (this._readyState === OPEN && this._connection) {
                        try {
                            const buf = new Uint8Array(reader.result);
                            this._bufferedAmount += buf.byteLength;
                            this._connection.send_binary(buf);
                            this._bufferedAmount = 0;
                        } catch (e2) {
                            this._bufferedAmount = 0;
                            this._readyState = CLOSED;
                            this._dispatch('error', new ErrorEvent(e2.message || String(e2)));
                            this._dispatch('close', new CloseEvent(1006, '', false));
                        }
                    }
                };
                reader.readAsArrayBuffer(data);
            } else {
                // Fallback: coerce to string per spec
                const str = String(data);
                this._bufferedAmount += utf8ByteLength(str);
                this._connection.send_text(str);
                this._bufferedAmount = 0;
            }
        } catch (e) {
            this._bufferedAmount = 0;
            this._readyState = CLOSED;
            this._dispatch('error', new ErrorEvent(e.message || String(e)));
            this._dispatch('close', new CloseEvent(1006, '', false));
        }
    }

    close(code, reason) {
        if (this._readyState === CLOSING || this._readyState === CLOSED) {
            return;
        }

        if (code !== undefined && code !== null) {
            code = Number(code);
            if (code !== 1000 && (code < 3000 || code > 4999)) {
                throw new DOMException(
                    "Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999. " + code + " is neither.",
                    'InvalidAccessError'
                );
            }
        }

        if (reason !== undefined && reason !== null) {
            reason = String(reason);
            if (utf8ByteLength(reason) > 123) {
                throw new DOMException(
                    "Failed to execute 'close' on 'WebSocket': The close reason must not be greater than 123 UTF-8 bytes.",
                    'SyntaxError'
                );
            }
        }

        this._readyState = CLOSING;

        try {
            if (this._connection) {
                this._connection.close(
                    code !== undefined && code !== null ? code : undefined,
                    reason !== undefined && reason !== null ? reason : undefined
                );
            }
        } catch (_) {
            // Ignore close errors
        }

        this._readyState = CLOSED;
        this._connection = null;
        this._dispatch('close', new CloseEvent(code || 1000, reason || '', true));
    }

    addEventListener(type, listener, options) {
        if (typeof listener !== 'function') return;
        if (!this._listeners[type]) {
            this._listeners[type] = [];
        }
        // Prevent duplicate listeners with same reference (per EventTarget spec)
        if (this._listeners[type].indexOf(listener) !== -1) return;
        this._listeners[type].push(listener);
    }

    removeEventListener(type, listener) {
        if (!this._listeners[type]) return;
        this._listeners[type] = this._listeners[type].filter(l => l !== listener);
    }

    dispatchEvent(event) {
        this._dispatch(event.type, event);
        return true;
    }

    _dispatch(type, event) {
        // Call the on<type> handler
        const handler = this['_on' + type];
        if (typeof handler === 'function') {
            try { handler.call(this, event); } catch (_) {}
        }

        // Call addEventListener listeners
        const listeners = this._listeners[type];
        if (listeners) {
            for (const listener of listeners.slice()) {
                try { listener.call(this, event); } catch (_) {}
            }
        }
    }
}

// Instance-level constants on the prototype (per spec, instances also expose these)
WebSocket.prototype.CONNECTING = CONNECTING;
WebSocket.prototype.OPEN = OPEN;
WebSocket.prototype.CLOSING = CLOSING;
WebSocket.prototype.CLOSED = CLOSED;

// ===== WebSocketStream (promise/streams-based API) =====
// See https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream

class WebSocketStream {
    constructor(url, options) {
        if (arguments.length === 0) {
            throw new TypeError("Failed to construct 'WebSocketStream': 1 argument required, but only 0 present.");
        }

        if (typeof url !== 'string') {
            url = String(url);
        }

        if (url.indexOf('#') !== -1) {
            throw new DOMException(
                "Failed to construct 'WebSocketStream': The URL '" + url + "' contains a fragment identifier.",
                'SyntaxError'
            );
        }

        url = normalizeWebSocketUrl(url);

        if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
            throw new DOMException(
                "Failed to construct 'WebSocketStream': The URL's scheme must be either 'ws', 'wss', 'http', or 'https'. '" + url + "' is not allowed.",
                'SyntaxError'
            );
        }

        this._url = url;

        const protocols = (options && options.protocols) || [];
        this._protocols = Array.isArray(protocols) ? protocols.slice() : [String(protocols)];

        // Build the opened and closed promises
        let resolveOpened, rejectOpened;
        this._opened = new Promise((res, rej) => { resolveOpened = res; rejectOpened = rej; });

        let resolveClosed, rejectClosed;
        this._closed = new Promise((res, rej) => { resolveClosed = res; rejectClosed = rej; });

        this._connection = null;
        this._readableController = null;
        this._writableStarted = false;

        // Connect asynchronously
        Promise.resolve().then(() => {
            try {
                this._connection = ws_connect(this._url, this._protocols);
            } catch (e) {
                const err = new Error(e.message || String(e));
                rejectOpened(err);
                rejectClosed(err);
                return;
            }

            const conn = this._connection;
            const self = this;

            const readable = new ReadableStream({
                start(controller) {
                    self._readableController = controller;
                    self._pumpReadable(controller, resolveClosed, rejectClosed);
                },
                cancel() {
                    self._closeConnection(1000, '');
                }
            });

            const writable = new WritableStream({
                write(chunk) {
                    if (!conn) {
                        throw new Error('WebSocketStream is closed');
                    }
                    if (typeof chunk === 'string') {
                        conn.send_text(chunk);
                    } else if (chunk instanceof ArrayBuffer) {
                        conn.send_binary(new Uint8Array(chunk));
                    } else if (ArrayBuffer.isView(chunk)) {
                        conn.send_binary(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
                    } else {
                        conn.send_text(String(chunk));
                    }
                },
                close() {
                    self._closeConnection(1000, '');
                },
                abort(reason) {
                    self._closeConnection(1000, reason ? String(reason) : '');
                }
            });

            const negotiatedProtocol = this._protocols.length > 0 ? this._protocols[0] : '';

            resolveOpened({
                readable,
                writable,
                protocol: negotiatedProtocol,
                extensions: '',
            });
        });
    }

    async _pumpReadable(controller, resolveClosed, rejectClosed) {
        while (this._connection) {
            try {
                const result = await this._connection.receive();
                const [type, data] = result;

                if (type === 'text') {
                    controller.enqueue(data);
                } else if (type === 'binary') {
                    controller.enqueue(data);
                } else if (type === 'closed') {
                    const code = (data && data.code) || 1000;
                    const reason = (data && data.reason) || '';
                    controller.close();
                    resolveClosed({ closeCode: code, reason: reason });
                    return;
                } else if (type === 'error') {
                    const err = new Error(data || 'Unknown error');
                    controller.error(err);
                    rejectClosed(err);
                    return;
                }
            } catch (e) {
                const err = new Error(e.message || String(e));
                controller.error(err);
                rejectClosed(err);
                return;
            }
        }
    }

    _closeConnection(code, reason) {
        if (this._connection) {
            try {
                this._connection.close(code, reason);
            } catch (_) {}
            this._connection = null;
        }
    }

    get url() { return this._url; }
    get opened() { return this._opened; }
    get closed() { return this._closed; }

    close(options) {
        const code = (options && options.closeCode) || 1000;
        const reason = (options && options.reason) || '';
        this._closeConnection(code, reason);
    }
}

export { WebSocket, WebSocketStream, MessageEvent, CloseEvent, ErrorEvent };
export default WebSocket;