olum-compiler 0.8.6 → 0.9.2
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.
- package/bin/compiler.js +1 -1
- package/bin/dev.js +1 -1
- package/bin/index.js +4 -1
- package/bin/watcher.js +1 -1
- package/lib/chokidar.js +344 -0
- package/lib/cross-spawn.js +318 -0
- package/lib/getImports.js +2 -2
- package/lib/helpers.js +17 -6
- package/lib/jsParser.js +1 -0
- package/lib/magic-string.js +213 -0
- package/lib/parser.js +13 -5
- package/lib/sourcemap.js +1 -1
- package/lib/websocket.js +347 -0
- package/package.json +3 -7
package/lib/getImports.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const
|
|
1
|
+
const acorn = require("acorn");
|
|
2
2
|
const { isFullArr } = require("./helpers");
|
|
3
3
|
// FYI: it ignores the comments by default beacuse it's based on lexial environment not based on regex
|
|
4
4
|
function getImports(str) {
|
|
5
5
|
let finalImports = [];
|
|
6
|
-
let arr =
|
|
6
|
+
let arr = acorn.parse(str, { ecmaVersion: "latest", sourceType: "module" }).body;
|
|
7
7
|
arr.forEach((obj) => {
|
|
8
8
|
if (obj.type === "ImportDeclaration") {
|
|
9
9
|
if (obj.specifiers) {
|
package/lib/helpers.js
CHANGED
|
@@ -16,7 +16,7 @@ const hasForwardSlash = (paths) => paths.find((item) => /\//g.test(item));
|
|
|
16
16
|
const hasSlash = (paths) => paths.find((item) => /\//g.test(item) || /\\/g.test(item));
|
|
17
17
|
const stringToBase64 = (str) => Buffer.from(str).toString('base64');
|
|
18
18
|
const base64ToString = (base64) => Buffer.from(base64, 'base64').toString('ascii');
|
|
19
|
-
const
|
|
19
|
+
const acorn = require("acorn");
|
|
20
20
|
|
|
21
21
|
function isUpper(char) {
|
|
22
22
|
const upperChar = char.toUpperCase();
|
|
@@ -372,8 +372,8 @@ function createScopeHandler({ stateProps, hasState, propsTobeExcluded, jsAttrs:
|
|
|
372
372
|
|
|
373
373
|
// get methods names
|
|
374
374
|
function getGlobalMethods(str) {
|
|
375
|
-
return
|
|
376
|
-
.parse(str, { sourceType: "module" })
|
|
375
|
+
return acorn
|
|
376
|
+
.parse(str, { ecmaVersion: "latest", sourceType: "module" })
|
|
377
377
|
.body.map((obj) => {
|
|
378
378
|
if (obj.type === "FunctionDeclaration") return obj.id.name;
|
|
379
379
|
if (
|
|
@@ -395,8 +395,8 @@ function getGlobalMethods(str) {
|
|
|
395
395
|
|
|
396
396
|
// get props names
|
|
397
397
|
function getGlobalProps(str) {
|
|
398
|
-
return
|
|
399
|
-
.parse(str, { sourceType: "module" })
|
|
398
|
+
return acorn
|
|
399
|
+
.parse(str, { ecmaVersion: "latest", sourceType: "module" })
|
|
400
400
|
.body.map((obj) => {
|
|
401
401
|
if (
|
|
402
402
|
obj.type === "VariableDeclaration" &&
|
|
@@ -663,7 +663,6 @@ ${routes
|
|
|
663
663
|
];`;
|
|
664
664
|
}
|
|
665
665
|
|
|
666
|
-
// todo: move it to olum-router and bind it from there to window
|
|
667
666
|
const routerParamsParser = `<script>
|
|
668
667
|
/**
|
|
669
668
|
* Extract route params from a file path and pathname.
|
|
@@ -714,6 +713,17 @@ const routerParamsParser = `<script>
|
|
|
714
713
|
}
|
|
715
714
|
</script>`;
|
|
716
715
|
|
|
716
|
+
const libsMap = {
|
|
717
|
+
development: {
|
|
718
|
+
olum: "/node_modules/olum/dist/olum.js",
|
|
719
|
+
router: "/node_modules/olum-router/dist/router.js"
|
|
720
|
+
},
|
|
721
|
+
production: {
|
|
722
|
+
olum: "olum",
|
|
723
|
+
router: "olum-router"
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
717
727
|
module.exports.isNum = isNum;
|
|
718
728
|
module.exports.id = id;
|
|
719
729
|
module.exports.isUpper = isUpper;
|
|
@@ -740,3 +750,4 @@ module.exports.generateRouteManifest = generateRouteManifest;
|
|
|
740
750
|
module.exports.generateImports = generateImports;
|
|
741
751
|
module.exports.generateRoutes = generateRoutes;
|
|
742
752
|
module.exports.routerParamsParser = routerParamsParser;
|
|
753
|
+
module.exports.libsMap = libsMap;
|
package/lib/jsParser.js
CHANGED
|
@@ -22,6 +22,7 @@ function jsParser(str) {
|
|
|
22
22
|
|
|
23
23
|
content = content.replace(/(<script.*>)/, "");
|
|
24
24
|
content = content.replace(/(<\/script>)$/, "");
|
|
25
|
+
content = content.replace(/onMount\(/, "var mounted = onMount("); // handle onMount hook if imported -- wrape it to another name (mounted) to continue the old flow
|
|
25
26
|
// content = content.replace(exportDefault, "").trim();
|
|
26
27
|
// return "__isInitial__: true,\n__render__(obj, prop) { olum.lifeCycle.render(obj, prop); },\n" + content;
|
|
27
28
|
content = content.replace(/const state/g, "var state"); // todo make this solid
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* magic-string.js — standalone single-file source map generator
|
|
3
|
+
* Minimal replacement for the `magic-string` package (v0.30.21), using only
|
|
4
|
+
* node built-ins. This project (lib/sourcemap.js) only ever builds an
|
|
5
|
+
* IDENTITY map — `new MagicString(str)` with zero edits, then
|
|
6
|
+
* `generateMap({ source, file, includeContent })` — so that surface is ported
|
|
7
|
+
* faithfully (byte-identical output, including the VLQ `mappings`, JSON key
|
|
8
|
+
* order and `toString()`/`toUrl()`):
|
|
9
|
+
*
|
|
10
|
+
* const MagicString = require("./magic-string");
|
|
11
|
+
* const map = new MagicString(code).generateMap({ source, file, includeContent, hires });
|
|
12
|
+
* map.mappings / map.toString() / map.toUrl()
|
|
13
|
+
*
|
|
14
|
+
* Supported: generateMap / generateDecodedMap with options
|
|
15
|
+
* `source`, `file`, `includeContent`, `hires` (true | "boundary" | falsy).
|
|
16
|
+
*
|
|
17
|
+
* KNOWN LIMITATIONS vs the real magic-string (future maintenance):
|
|
18
|
+
* The string EDITING api (overwrite, update, appendLeft/Right, prepend,
|
|
19
|
+
* append, remove, move, indent, trim, slice, clone, addSourcemapLocation,
|
|
20
|
+
* Bundle, ...) is NOT implemented — those methods throw with a clear message
|
|
21
|
+
* instead of failing silently. If the compiler ever needs to transform code
|
|
22
|
+
* while tracking mappings (e.g. the sourcemap.js TODO about mapping html
|
|
23
|
+
* above the script tag), either extend this file's char-walk in
|
|
24
|
+
* generateDecodedMap to consume an edit list, or reinstall the real package.
|
|
25
|
+
*/
|
|
26
|
+
"use strict";
|
|
27
|
+
|
|
28
|
+
// ------------------------------------------------ base64 VLQ (sourcemap-codec)
|
|
29
|
+
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
30
|
+
|
|
31
|
+
function encodeVlq(num) {
|
|
32
|
+
num = num < 0 ? (-num << 1) | 1 : num << 1;
|
|
33
|
+
let out = "";
|
|
34
|
+
do {
|
|
35
|
+
let digit = num & 31;
|
|
36
|
+
num >>>= 5;
|
|
37
|
+
if (num > 0) digit |= 32; // continuation bit
|
|
38
|
+
out += BASE64[digit];
|
|
39
|
+
} while (num > 0);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// encode decoded mappings ([[ [genCol, srcIdx, srcLine, srcCol, name?], ...], ...])
|
|
44
|
+
// into the standard delta-encoded VLQ string: fields are relative to the
|
|
45
|
+
// previous segment; generated column resets per line, the rest carry over
|
|
46
|
+
function encodeMappings(decoded) {
|
|
47
|
+
let sourceIndex = 0;
|
|
48
|
+
let sourceLine = 0;
|
|
49
|
+
let sourceColumn = 0;
|
|
50
|
+
let nameIndex = 0;
|
|
51
|
+
|
|
52
|
+
return decoded
|
|
53
|
+
.map(line => {
|
|
54
|
+
let genColumn = 0;
|
|
55
|
+
return line
|
|
56
|
+
.map(segment => {
|
|
57
|
+
let out = encodeVlq(segment[0] - genColumn);
|
|
58
|
+
genColumn = segment[0];
|
|
59
|
+
if (segment.length > 1) {
|
|
60
|
+
out += encodeVlq(segment[1] - sourceIndex) + encodeVlq(segment[2] - sourceLine) + encodeVlq(segment[3] - sourceColumn);
|
|
61
|
+
sourceIndex = segment[1];
|
|
62
|
+
sourceLine = segment[2];
|
|
63
|
+
sourceColumn = segment[3];
|
|
64
|
+
}
|
|
65
|
+
if (segment.length === 5) {
|
|
66
|
+
out += encodeVlq(segment[4] - nameIndex);
|
|
67
|
+
nameIndex = segment[4];
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
})
|
|
71
|
+
.join(",");
|
|
72
|
+
})
|
|
73
|
+
.join(";");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// path of `to` relative to `from`'s directory (magic-string's own helper)
|
|
77
|
+
function getRelativePath(from, to) {
|
|
78
|
+
const fromParts = from.split(/[/\\]/);
|
|
79
|
+
const toParts = to.split(/[/\\]/);
|
|
80
|
+
|
|
81
|
+
fromParts.pop(); // get dirname
|
|
82
|
+
|
|
83
|
+
while (fromParts[0] === toParts[0]) {
|
|
84
|
+
fromParts.shift();
|
|
85
|
+
toParts.shift();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (fromParts.length) {
|
|
89
|
+
let i = fromParts.length;
|
|
90
|
+
while (i--) fromParts[i] = "..";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return fromParts.concat(toParts).join("/");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// --------------------------------------------------------------- SourceMap
|
|
97
|
+
class SourceMap {
|
|
98
|
+
constructor(properties) {
|
|
99
|
+
this.version = 3;
|
|
100
|
+
this.file = properties.file;
|
|
101
|
+
this.sources = properties.sources;
|
|
102
|
+
this.sourcesContent = properties.sourcesContent;
|
|
103
|
+
this.names = properties.names;
|
|
104
|
+
this.mappings = encodeMappings(properties.mappings);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
toString() {
|
|
108
|
+
return JSON.stringify(this); // undefined keys (file, sourcesContent) drop out
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
toUrl() {
|
|
112
|
+
return "data:application/json;charset=utf-8;base64," + Buffer.from(this.toString(), "utf-8").toString("base64");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// -------------------------------------------------------------- MagicString
|
|
117
|
+
const wordRegex = /\w/;
|
|
118
|
+
|
|
119
|
+
class MagicString {
|
|
120
|
+
constructor(string, options = {}) {
|
|
121
|
+
this.original = string;
|
|
122
|
+
this.filename = options.filename;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
toString() {
|
|
126
|
+
return this.original;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
get length() {
|
|
130
|
+
return this.original.length;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// identity mapping: walk the original char by char, mirroring magic-string's
|
|
134
|
+
// Mappings.addUneditedChunk — a segment at the first char of every line
|
|
135
|
+
// (every char for hires: true, word boundaries for hires: "boundary");
|
|
136
|
+
// lines with no characters get no segment
|
|
137
|
+
generateDecodedMap(options = {}) {
|
|
138
|
+
const hires = options.hires;
|
|
139
|
+
const mappings = [];
|
|
140
|
+
let line = [];
|
|
141
|
+
let genColumn = 0;
|
|
142
|
+
let sourceLine = 0;
|
|
143
|
+
let sourceColumn = 0;
|
|
144
|
+
let first = true;
|
|
145
|
+
let inBoundary = false;
|
|
146
|
+
|
|
147
|
+
for (let i = 0; i < this.original.length; i++) {
|
|
148
|
+
if (this.original[i] === "\n") {
|
|
149
|
+
mappings.push(line);
|
|
150
|
+
line = [];
|
|
151
|
+
genColumn = 0;
|
|
152
|
+
sourceLine += 1;
|
|
153
|
+
sourceColumn = 0;
|
|
154
|
+
first = true;
|
|
155
|
+
inBoundary = false;
|
|
156
|
+
} else {
|
|
157
|
+
if (hires || first) {
|
|
158
|
+
const segment = [genColumn, 0, sourceLine, sourceColumn];
|
|
159
|
+
if (hires === "boundary") {
|
|
160
|
+
// one segment per word, plus one for every non-word char
|
|
161
|
+
if (wordRegex.test(this.original[i])) {
|
|
162
|
+
if (!inBoundary) {
|
|
163
|
+
line.push(segment);
|
|
164
|
+
inBoundary = true;
|
|
165
|
+
}
|
|
166
|
+
} else {
|
|
167
|
+
line.push(segment);
|
|
168
|
+
inBoundary = false;
|
|
169
|
+
}
|
|
170
|
+
} else {
|
|
171
|
+
line.push(segment);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
sourceColumn += 1;
|
|
175
|
+
genColumn += 1;
|
|
176
|
+
first = false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
mappings.push(line);
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
|
|
183
|
+
sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
|
|
184
|
+
sourcesContent: options.includeContent ? [this.original] : undefined,
|
|
185
|
+
names: [],
|
|
186
|
+
mappings,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
generateMap(options) {
|
|
191
|
+
return new SourceMap(this.generateDecodedMap(options));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// editing api is intentionally absent — fail loudly, not silently
|
|
196
|
+
for (const method of [
|
|
197
|
+
"addSourcemapLocation", "append", "appendLeft", "appendRight", "clone", "indent",
|
|
198
|
+
"insertLeft", "insertRight", "move", "overwrite", "prepend", "prependLeft",
|
|
199
|
+
"prependRight", "remove", "replace", "replaceAll", "reset", "slice", "snip",
|
|
200
|
+
"trim", "trimEnd", "trimStart", "trimLines", "update",
|
|
201
|
+
]) {
|
|
202
|
+
MagicString.prototype[method] = function () {
|
|
203
|
+
throw new Error(
|
|
204
|
+
`MagicString#${method}() is not implemented in the standalone lib/magic-string.js — ` +
|
|
205
|
+
"only identity source map generation (generateMap) is supported. " +
|
|
206
|
+
"See the header comment for how to extend it, or reinstall the real magic-string package."
|
|
207
|
+
);
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
module.exports = MagicString;
|
|
212
|
+
module.exports.default = MagicString;
|
|
213
|
+
module.exports.SourceMap = SourceMap;
|
package/lib/parser.js
CHANGED
|
@@ -5,7 +5,7 @@ const jsParser = require("./jsParser");
|
|
|
5
5
|
const getImports = require("./getImports");
|
|
6
6
|
const toJs = require("./toJs");
|
|
7
7
|
const path = require("path");
|
|
8
|
-
const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, minifyJS } = require("./helpers");
|
|
8
|
+
const { isFullArr, id, createScopeHandler, getGlobalMethods, getGlobalProps, minifyJS, libsMap } = require("./helpers");
|
|
9
9
|
const createSourceMap = require("./sourcemap");
|
|
10
10
|
|
|
11
11
|
const parser = (str, counter, filePath) => {
|
|
@@ -27,6 +27,14 @@ const parser = (str, counter, filePath) => {
|
|
|
27
27
|
if (imports) {
|
|
28
28
|
const importRegex = /(import)(\s+)?(?!from)/g;
|
|
29
29
|
imports.forEach((item) => {
|
|
30
|
+
// resolve imported libs: olum, olum-router
|
|
31
|
+
if (/from\s+(['"])olum\1/.test(item.statement)) {
|
|
32
|
+
item.statement = item.statement.replace(new RegExp(item.regex, ""), `from "${libsMap[process.env.NODE_ENV].olum}"`)
|
|
33
|
+
}
|
|
34
|
+
if (/from\s+(['"])olum-router\1/.test(item.statement)) {
|
|
35
|
+
item.statement = item.statement.replace(new RegExp(item.regex, ""), `from "${libsMap[process.env.NODE_ENV].olum}"`)
|
|
36
|
+
}
|
|
37
|
+
|
|
30
38
|
if (item.type && item.type == "noFrom") js = js.replace(new RegExp(item.regex, "gm"), "");
|
|
31
39
|
if (!item.type) js = js.replace(new RegExp(item.regex, "g"), "*/");
|
|
32
40
|
});
|
|
@@ -54,8 +62,8 @@ const parser = (str, counter, filePath) => {
|
|
|
54
62
|
let hasMounted = false;
|
|
55
63
|
let hasUnMounted = false;
|
|
56
64
|
|
|
57
|
-
const methodsTobeExcluded = ["mounted", "unMounted"];
|
|
58
|
-
const propsTobeExcluded = ["watcher"];
|
|
65
|
+
const methodsTobeExcluded = ["mounted", "unMounted", "onMount"];
|
|
66
|
+
const propsTobeExcluded = ["watcher", "mounted"];
|
|
59
67
|
|
|
60
68
|
globalProps = getGlobalProps(js);
|
|
61
69
|
globalMethods = getGlobalMethods(js);
|
|
@@ -158,8 +166,8 @@ const parser = (str, counter, filePath) => {
|
|
|
158
166
|
incomingPropsProxy: props,
|
|
159
167
|
${isDev ? `stateProps: ${hasState ? "state" : "null"},` : ""}
|
|
160
168
|
hooks: {
|
|
161
|
-
mounted:
|
|
162
|
-
unMounted:
|
|
169
|
+
mounted: typeof mounted !== "undefined" ? mounted : null,
|
|
170
|
+
unMounted: null,
|
|
163
171
|
isMounted: false,
|
|
164
172
|
isUnMounted: false,
|
|
165
173
|
}
|
package/lib/sourcemap.js
CHANGED
package/lib/websocket.js
ADDED
|
@@ -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;
|