@caboodle-tech/node-simple-server 2.0.1 → 4.0.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,153 @@
1
+ <!-- Code injected by Node Simple Server. -->
2
+ <script type="text/javascript">
3
+ // <![CDATA[
4
+ if ("WebSocket" in window) {
5
+ NSS_WS = (() => {
6
+ /** Expose the random page ID that was assigned to this page. */
7
+ const getId = () => {
8
+ return pageId;
9
+ };
10
+
11
+ /** Register a function or functions to call when this page receives a WebSocket message. */
12
+ const registerCallback = (func) => {
13
+ if (whatIs(func) === "function") {
14
+ callbacks.push(func);
15
+ }
16
+ };
17
+
18
+ /** Attempt to reestablish a connection to the WebSocket server. */
19
+ const restart = () => {
20
+ const http = new XMLHttpRequest();
21
+ http.onerror = function (e) {
22
+ // Ignore the error in browsers that respect that.
23
+ };
24
+ // Attempt a reconnect.
25
+ http.onreadystatechange = () => {
26
+ if (http.readyState === 4) {
27
+ if (http.status >= 200 && http.status < 400) {
28
+ window.location.reload();
29
+ }
30
+ }
31
+ };
32
+ http.open("GET", window.location.href);
33
+ http.send();
34
+ // Keep attempting to reconnect unless told not to.
35
+ if (autoRestart) {
36
+ if (restartAttempts < 10) {
37
+ restartAttempts += 1;
38
+ }
39
+ clearInterval(restartInterval);
40
+ restartInterval = setInterval(restart, 3000 * restartAttempts);
41
+ }
42
+ };
43
+
44
+ /** Send a WebSocket message to the WebSocket server. */
45
+ const send = (message) => {
46
+ if (ready && socket.readyState === WebSocket.OPEN) {
47
+ socket.send(JSON.stringify({
48
+ message,
49
+ type: whatIs(message)
50
+ }));
51
+ return;
52
+ }
53
+ console.warn("Node Simple Server: The WebSocket is not ready or the connection was closed.");
54
+ };
55
+
56
+ /** Generate a random unique ID for this page; will be registered in the back-end. */
57
+ const uid = () => {
58
+ return Math.random().toString(16).slice(2);
59
+ };
60
+
61
+ /** Remove a callback function previously registered with registerCallback(). */
62
+ const unregisterCallback = (func) => {
63
+ for (let i = 0; i < callbacks.length; i++) {
64
+ if (callbacks[i] == func) {
65
+ callbacks.splice(i, 1);
66
+ }
67
+ }
68
+ };
69
+
70
+ /**
71
+ * The fastest way to get the actual type of anything in JavaScript.
72
+ *
73
+ * {@link https://jsbench.me/ruks9jljcu/2 | See benchmarks}.
74
+ *
75
+ * @param {*} unknown Anything you wish to check the type of.
76
+ * @return {string|undefined} The type in lowercase of the unknown value passed in or undefined.
77
+ */
78
+ const whatIs = (unknown) => {
79
+ try {
80
+ return ({}).toString.call(unknown).match(/\s([^\]]+)/)[1].toLowerCase();
81
+ } catch (e) { return undefined; }
82
+ };
83
+
84
+ // NSS_WS internal global variables.
85
+ let autoRestart = true;
86
+ const callbacks = [];
87
+ let counterInterval = null;
88
+ const pageId = uid();
89
+ let ready = false;
90
+ let restartAttempts = 0;
91
+ let restartInterval = null;
92
+
93
+ // Socket specific variables.
94
+ const protocol = window.location.protocol === "http:" ? "ws://" : "wss://";
95
+ const address = protocol + window.location.host + window.location.pathname + "/ws?id=" + pageId;
96
+ const socket = new WebSocket(address);
97
+
98
+ // Respond to messages the socket receives.
99
+ socket.onmessage = (evt) => {
100
+ const msgObj = JSON.parse(evt.data); // NSS uses a standard messaging object.
101
+ switch (msgObj.message) {
102
+ case "close":
103
+ ready = false;
104
+ break;
105
+ case "disableAutoRestart":
106
+ autoRestart = false;
107
+ clearInterval(restartInterval);
108
+ clearInterval(counterInterval);
109
+ break;
110
+ case 'ping':
111
+ send('pong');
112
+ break;
113
+ case "reload":
114
+ window.location.reload();
115
+ break;
116
+ default:
117
+ if (callbacks.length > 0) {
118
+ for (let i = 0; i < callbacks.length; i++) {
119
+ callbacks[i](msgObj);
120
+ }
121
+ return;
122
+ }
123
+ console.log(`Received from WebSocket: ${msgObj.message}`);
124
+ }
125
+ };
126
+
127
+ // Mark the script as not ready when the websocket connection is closed.
128
+ socket.addEventListener("close", () => {
129
+ ready = false;
130
+ if (autoRestart) {
131
+ restartInterval = setInterval(restart, 3000);
132
+ }
133
+ });
134
+
135
+ // Mark the script as ready when a websocket connection is established.
136
+ socket.addEventListener("open", () => {
137
+ ready = true;
138
+ });
139
+
140
+ // Expose some of NSS_WS methods.
141
+ return {
142
+ getId,
143
+ registerCallback,
144
+ send,
145
+ unregisterCallback,
146
+ whatIs
147
+ };
148
+ })();
149
+ } else {
150
+ console.error("Node Simple Server: This Browser does NOT support WebSockets.");
151
+ }
152
+ // ]]>
153
+ </script>
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@caboodle-tech/node-simple-server",
3
- "version": "2.0.1",
3
+ "version": "4.0.0",
4
4
  "description": "Node Simple Server (NSS): A small but effective node based server for development sites, customizable live reloading, and websocket support built-in.",
5
5
  "main": "bin/nss.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1",
8
8
  "example": "node ./examples/run.js",
9
+ "example:production": "node ./examples/run.js production",
9
10
  "example:website": "node ./examples/run.js website",
10
11
  "example:websocket": "node ./examples/run.js websocket"
11
12
  },
@@ -22,7 +23,9 @@
22
23
  "Reloading",
23
24
  "Callback",
24
25
  "Functions",
25
- "WebSocket"
26
+ "WebSocket",
27
+ "Internal",
28
+ "Applications"
26
29
  ],
27
30
  "author": "Christopher Keers <source[at]caboodle.tech>",
28
31
  "contributors": [