olum-compiler 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,347 @@
1
+ /**
2
+ * websocket.js — standalone single-file WebSocket server (RFC 6455)
3
+ * Minimal replacement for the `ws` package's server side, using only node
4
+ * built-ins (http, crypto, events). Cross-platform by construction.
5
+ *
6
+ * Covered (same API shape as ws@8.21.0):
7
+ * const WebSocket = require("./websocket");
8
+ * const wss = new WebSocket.Server({ port }); // or { server } / { noServer: true }
9
+ * wss.on("listening" | "connection" | "error" | "close" | "headers", ...)
10
+ * ws.send(data, [cb]) / ws.ping() / ws.close(code, reason) / ws.terminate()
11
+ * ws.on("message" | "close" | "error" | "ping" | "pong", ...)
12
+ *
13
+ * Not included: the client-side WebSocket(url) constructor (browsers provide
14
+ * their own) and the permessage-deflate extension (never negotiated, so
15
+ * clients transparently fall back to uncompressed frames per the RFC).
16
+ */
17
+ "use strict";
18
+
19
+ const crypto = require("crypto");
20
+ const http = require("http");
21
+ const { EventEmitter } = require("events");
22
+
23
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // fixed magic value from RFC 6455 §1.3
24
+ const EMPTY = Buffer.alloc(0);
25
+
26
+ const CONNECTING = 0;
27
+ const OPEN = 1;
28
+ const CLOSING = 2;
29
+ const CLOSED = 3;
30
+
31
+ // build one server→client frame: FIN set, no mask (RFC 6455 §5.1: servers must not mask)
32
+ function encodeFrame(opcode, payload) {
33
+ const len = payload.length;
34
+ let header;
35
+
36
+ if (len < 126) {
37
+ header = Buffer.allocUnsafe(2);
38
+ header[1] = len;
39
+ } else if (len < 65536) {
40
+ header = Buffer.allocUnsafe(4);
41
+ header[1] = 126;
42
+ header.writeUInt16BE(len, 2);
43
+ } else {
44
+ header = Buffer.allocUnsafe(10);
45
+ header[1] = 127;
46
+ header.writeUInt32BE(Math.floor(len / 2 ** 32), 2);
47
+ header.writeUInt32BE(len >>> 0, 6);
48
+ }
49
+
50
+ header[0] = 0x80 | opcode; // FIN + opcode
51
+ return Buffer.concat([header, payload]);
52
+ }
53
+
54
+ function toBuffer(data) {
55
+ if (Buffer.isBuffer(data)) return data;
56
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
57
+ if (data instanceof ArrayBuffer) return Buffer.from(data);
58
+ return Buffer.from(String(data));
59
+ }
60
+
61
+ class WebSocket extends EventEmitter {
62
+ constructor(socket) {
63
+ super();
64
+
65
+ this._socket = socket;
66
+ this._buffer = EMPTY;
67
+ this._fragments = [];
68
+ this._fragmentOpcode = 0;
69
+ this._closeSent = false;
70
+ this._closeReceived = false;
71
+ this._closeCode = 1006; // abnormal closure unless a close frame says otherwise
72
+ this._closeReason = EMPTY;
73
+ this.readyState = OPEN;
74
+
75
+ socket.setNoDelay(true);
76
+ socket.on("data", chunk => this._parse(chunk));
77
+ // upgraded sockets are half-open: when the peer stops sending without a
78
+ // close frame, end our side too so the tcp socket can actually close
79
+ socket.on("end", () => {
80
+ this.readyState = CLOSING;
81
+ socket.end();
82
+ });
83
+ socket.on("error", err => {
84
+ this.emit("error", err);
85
+ socket.destroy();
86
+ });
87
+ socket.on("close", () => {
88
+ this.readyState = CLOSED;
89
+ this.emit("close", this._closeCode, this._closeReason);
90
+ });
91
+ }
92
+
93
+ // ------------------------------------------------------------ outgoing
94
+ send(data, options, cb) {
95
+ if (typeof options === "function") {
96
+ cb = options;
97
+ options = {};
98
+ }
99
+
100
+ if (this.readyState !== OPEN) {
101
+ // match ws: sending on a closed socket is a no-op unless a callback wants the error
102
+ if (cb) {
103
+ const err = new Error("WebSocket is not open: readyState " + this.readyState);
104
+ process.nextTick(cb, err);
105
+ }
106
+ return;
107
+ }
108
+
109
+ const isBinary = typeof data !== "string";
110
+ this._socket.write(encodeFrame(isBinary ? 0x2 : 0x1, toBuffer(data)), cb);
111
+ }
112
+
113
+ ping(data) {
114
+ if (this.readyState === OPEN) this._socket.write(encodeFrame(0x9, toBuffer(data == null ? EMPTY : data)));
115
+ }
116
+
117
+ pong(data) {
118
+ if (this.readyState === OPEN) this._socket.write(encodeFrame(0xa, toBuffer(data == null ? EMPTY : data)));
119
+ }
120
+
121
+ close(code, reason) {
122
+ if (this.readyState !== OPEN && this.readyState !== CLOSING) return;
123
+ this._sendClose(code === undefined ? 1000 : code, reason == null ? EMPTY : toBuffer(reason));
124
+ // if the client never answers with its own close frame, force-drop the tcp socket
125
+ const timer = setTimeout(() => this._socket.destroy(), 30000);
126
+ if (timer.unref) timer.unref();
127
+ }
128
+
129
+ terminate() {
130
+ this._socket.destroy();
131
+ }
132
+
133
+ _sendClose(code, reason) {
134
+ if (this._closeSent) return;
135
+ this._closeSent = true;
136
+ this.readyState = CLOSING;
137
+
138
+ let payload = EMPTY;
139
+ if (code !== undefined) {
140
+ payload = Buffer.allocUnsafe(2 + reason.length);
141
+ payload.writeUInt16BE(code, 0);
142
+ reason.copy(payload, 2);
143
+ }
144
+ this._socket.write(encodeFrame(0x8, payload));
145
+ // close handshake complete → shut down the tcp stream
146
+ if (this._closeReceived) this._socket.end();
147
+ }
148
+
149
+ // ------------------------------------------------------------ incoming
150
+ _abort(code) {
151
+ // protocol violation: send close frame with the given code and cut the connection
152
+ this._closeCode = code;
153
+ this._sendClose(code, EMPTY);
154
+ this._socket.end();
155
+ }
156
+
157
+ _parse(chunk) {
158
+ this._buffer = this._buffer.length === 0 ? chunk : Buffer.concat([this._buffer, chunk]);
159
+
160
+ while (true) {
161
+ const buf = this._buffer;
162
+ if (buf.length < 2) return;
163
+
164
+ const fin = (buf[0] & 0x80) !== 0;
165
+ const rsv = buf[0] & 0x70;
166
+ const opcode = buf[0] & 0x0f;
167
+ const masked = (buf[1] & 0x80) !== 0;
168
+ let length = buf[1] & 0x7f;
169
+ let offset = 2;
170
+
171
+ // no extension negotiated → RSV bits must be 0; clients must always mask
172
+ if (rsv !== 0 || !masked) return this._abort(1002);
173
+
174
+ if (length === 126) {
175
+ if (buf.length < 4) return;
176
+ length = buf.readUInt16BE(2);
177
+ offset = 4;
178
+ } else if (length === 127) {
179
+ if (buf.length < 10) return;
180
+ const length64 = buf.readBigUInt64BE(2);
181
+ if (length64 > BigInt(Number.MAX_SAFE_INTEGER)) return this._abort(1009);
182
+ length = Number(length64);
183
+ offset = 10;
184
+ }
185
+
186
+ if (length > 100 * 1024 * 1024) return this._abort(1009); // same default max payload as ws
187
+
188
+ if (buf.length < offset + 4 + length) return;
189
+ const mask = buf.slice(offset, offset + 4);
190
+ offset += 4;
191
+
192
+ const payload = buf.slice(offset, offset + length);
193
+ for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
194
+
195
+ this._buffer = buf.slice(offset + length);
196
+ this._handleFrame(fin, opcode, payload);
197
+ if (this.readyState === CLOSED) return;
198
+ }
199
+ }
200
+
201
+ _handleFrame(fin, opcode, payload) {
202
+ // control frames (§5.5): never fragmented, payload ≤ 125
203
+ if (opcode >= 0x8) {
204
+ if (!fin || payload.length > 125) return this._abort(1002);
205
+
206
+ if (opcode === 0x8) {
207
+ this._closeReceived = true;
208
+ let code = 1005; // no status received
209
+ let reason = EMPTY;
210
+ if (payload.length >= 2) {
211
+ code = payload.readUInt16BE(0);
212
+ reason = payload.slice(2);
213
+ } else if (payload.length === 1) {
214
+ return this._abort(1002);
215
+ }
216
+ this._closeCode = code === 1005 ? 1000 : code;
217
+ this._closeReason = reason;
218
+ this._sendClose(payload.length >= 2 ? code : undefined, reason); // echo close per §5.5.1
219
+ this._socket.end();
220
+ } else if (opcode === 0x9) {
221
+ this.pong(payload); // §5.5.2: a ping must be answered with an identical pong
222
+ this.emit("ping", payload);
223
+ } else if (opcode === 0xa) {
224
+ this.emit("pong", payload);
225
+ } else {
226
+ this._abort(1002);
227
+ }
228
+ return;
229
+ }
230
+
231
+ // data frames: 0x1 text, 0x2 binary, 0x0 continuation of a fragmented message
232
+ if (opcode === 0x1 || opcode === 0x2) {
233
+ if (this._fragments.length > 0) return this._abort(1002); // new message before finishing the last
234
+ if (fin) return this.emit("message", payload, opcode === 0x2);
235
+ this._fragmentOpcode = opcode;
236
+ this._fragments.push(payload);
237
+ } else if (opcode === 0x0) {
238
+ if (this._fragments.length === 0) return this._abort(1002); // continuation with nothing to continue
239
+ this._fragments.push(payload);
240
+ if (fin) {
241
+ const message = Buffer.concat(this._fragments);
242
+ const isBinary = this._fragmentOpcode === 0x2;
243
+ this._fragments = [];
244
+ this.emit("message", message, isBinary);
245
+ }
246
+ } else {
247
+ this._abort(1002); // unknown opcode
248
+ }
249
+ }
250
+ }
251
+
252
+ WebSocket.CONNECTING = CONNECTING;
253
+ WebSocket.OPEN = OPEN;
254
+ WebSocket.CLOSING = CLOSING;
255
+ WebSocket.CLOSED = CLOSED;
256
+
257
+ class WebSocketServer extends EventEmitter {
258
+ constructor(options = {}, callback) {
259
+ super();
260
+
261
+ this.clients = new Set();
262
+
263
+ if (options.server) {
264
+ this._server = options.server;
265
+ this._ownServer = false;
266
+ } else if (options.noServer) {
267
+ this._server = null;
268
+ this._ownServer = false;
269
+ } else {
270
+ // plain http requests get the same answer ws gives: 426 Upgrade Required
271
+ this._server = http.createServer((req, res) => {
272
+ const body = http.STATUS_CODES[426];
273
+ res.writeHead(426, { "Content-Length": body.length, "Content-Type": "text/plain" });
274
+ res.end(body);
275
+ });
276
+ this._ownServer = true;
277
+ this._server.listen(options.port, options.host, options.backlog, callback);
278
+ }
279
+
280
+ if (this._server) {
281
+ this._server.on("listening", () => this.emit("listening"));
282
+ this._server.on("error", err => this.emit("error", err));
283
+ this._server.on("upgrade", (req, socket, head) => {
284
+ this.handleUpgrade(req, socket, head, ws => this.emit("connection", ws, req));
285
+ });
286
+ }
287
+ }
288
+
289
+ address() {
290
+ return this._server && this._server.address();
291
+ }
292
+
293
+ handleUpgrade(req, socket, head, callback) {
294
+ socket.on("error", () => socket.destroy());
295
+
296
+ const key = req.headers["sec-websocket-key"];
297
+ const version = +req.headers["sec-websocket-version"];
298
+ const upgrade = (req.headers.upgrade || "").split(/, */).some(p => p.toLowerCase() === "websocket");
299
+
300
+ if (req.method !== "GET" || !upgrade || !key || (version !== 13 && version !== 8)) {
301
+ const body = http.STATUS_CODES[400];
302
+ socket.write(
303
+ "HTTP/1.1 400 Bad Request\r\n" +
304
+ "Connection: close\r\n" +
305
+ "Content-Type: text/plain\r\n" +
306
+ `Content-Length: ${body.length}\r\n\r\n` +
307
+ body
308
+ );
309
+ socket.destroy();
310
+ return;
311
+ }
312
+
313
+ // RFC 6455 §4.2.2: accept key proves the server actually speaks websocket
314
+ const accept = crypto.createHash("sha1").update(key + GUID).digest("base64");
315
+ const headers = [
316
+ "HTTP/1.1 101 Switching Protocols",
317
+ "Upgrade: websocket",
318
+ "Connection: Upgrade",
319
+ `Sec-WebSocket-Accept: ${accept}`,
320
+ ];
321
+
322
+ this.emit("headers", headers, req);
323
+ socket.write(headers.concat("\r\n").join("\r\n"));
324
+
325
+ const ws = new WebSocket(socket);
326
+ if (head && head.length > 0) ws._parse(head); // bytes the client sent before we attached
327
+
328
+ this.clients.add(ws);
329
+ ws.on("close", () => this.clients.delete(ws));
330
+ callback(ws);
331
+ }
332
+
333
+ close(cb) {
334
+ for (const ws of this.clients) ws.terminate();
335
+ const done = () => {
336
+ this.emit("close");
337
+ if (cb) cb();
338
+ };
339
+ if (this._ownServer) this._server.close(done);
340
+ else process.nextTick(done);
341
+ }
342
+ }
343
+
344
+ module.exports = WebSocket;
345
+ module.exports.WebSocket = WebSocket;
346
+ module.exports.Server = WebSocketServer;
347
+ module.exports.WebSocketServer = WebSocketServer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "olum-compiler",
3
- "version": "0.8.5",
3
+ "version": "0.9.0",
4
4
  "description": "A module for compiling/bundling olumjs projects",
5
5
  "main": "bin/index.js",
6
6
  "bin": {
@@ -25,11 +25,7 @@
25
25
  "node": ">=14"
26
26
  },
27
27
  "dependencies": {
28
- "chokidar": "^3.5.3",
29
- "cross-spawn": "^7.0.3",
30
- "esprima": "^4.0.1",
31
- "jsdom": "^19.0.0",
32
- "magic-string": "^0.26.7",
33
- "ws": "^8.5.0"
28
+ "acorn": "^8.17.0",
29
+ "jsdom": "^19.0.0"
34
30
  }
35
31
  }