forked from bigskysoftware/_hyperscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventsource.js
More file actions
246 lines (214 loc) · 7.84 KB
/
eventsource.js
File metadata and controls
246 lines (214 loc) · 7.84 KB
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
///=========================================================================
/// This module provides the EventSource (SSE) feature for hyperscript
///=========================================================================
/// <reference path="./_hyperscript.js" />
/// <reference path="./eventsource.d.ts" />
(function (self, factory) {
const plugin = factory(self)
if (typeof exports === 'object' && typeof exports['nodeName'] !== 'string') {
module.exports = plugin
} else {
if ('_hyperscript' in self) self._hyperscript.use(plugin)
}
})(typeof self !== 'undefined' ? self : this, self => {
/**
* @param {import("./_hyperscript.js").Hyperscript} _hyperscript
*/
return _hyperscript => {
_hyperscript.addFeature("eventsource", function (parser, runtime, tokens) {
if (tokens.matchToken("eventsource")) {
var urlElement;
var withCredentials = false;
// Get the name we'll assign to this EventSource in the hyperscript context
/** @type {string} */
var name = parser.requireElement("dotOrColonPath", tokens).evaluate();
var nameSpace = name.split(".");
var eventSourceName = nameSpace.pop();
// Get the URL of the EventSource
if (tokens.matchToken("from")) {
urlElement = parser.requireElement("stringLike", tokens);
}
// Get option to connect with/without credentials
if (tokens.matchToken("with")) {
if (tokens.matchToken("credentials")) {
withCredentials = true;
}
}
/** @type {EventSourceStub} */
var stub = {
eventSource: null,
listeners: [],
retryCount: 0,
closed: false,
reconnectTimeout: null,
open: function (url) {
// calculate default values for URL argument.
if (url == undefined) {
if (stub.eventSource != null && stub.eventSource.url != undefined) {
url = stub.eventSource.url;
} else {
throw "no url defined for EventSource.";
}
}
// Guard multiple opens on the same EventSource
if (stub.eventSource != null) {
// If we're opening a new URL, then close the old one first.
if (url != stub.eventSource.url) {
stub.eventSource.close();
} else if (stub.eventSource.readyState != EventSource.CLOSED) {
// Otherwise, we already have the right connection open, so there's nothing left to do.
return;
}
}
// Mark as not explicitly closed (allow reconnection)
stub.closed = false;
// Open the EventSource and get ready to populate event handlers
stub.eventSource = new EventSource(url, {
withCredentials: withCredentials,
});
// On successful connection. Reset retry count.
stub.eventSource.addEventListener("open", function (event) {
stub.retryCount = 0;
});
// On connection error, use exponential backoff to retry
stub.eventSource.addEventListener("error", function (event) {
// Close the EventSource to prevent the browser's native auto-reconnect,
// which does not use backoff and can cause rapid-fire retries.
stub.eventSource.close();
// Only reconnect if the user has not explicitly called close()
if (!stub.closed) {
stub.retryCount = Math.min(7, stub.retryCount + 1);
var timeout = Math.random() * Math.pow(2, stub.retryCount) * 500;
stub.reconnectTimeout = window.setTimeout(stub.open, timeout);
}
});
// Add event listeners
for (var index = 0; index < stub.listeners.length; index++) {
var item = stub.listeners[index];
stub.eventSource.addEventListener(item.type, item.handler, item.options);
}
},
close: function () {
stub.closed = true;
if (stub.reconnectTimeout != null) {
window.clearTimeout(stub.reconnectTimeout);
stub.reconnectTimeout = null;
}
if (stub.eventSource != undefined) {
stub.eventSource.close();
}
stub.retryCount = 0;
},
addEventListener: function (type, handler, options) {
stub.listeners.push({
type: type,
handler: handler,
options: options,
});
if (stub.eventSource != null) {
stub.eventSource.addEventListener(type, handler, options);
}
},
};
// Create the "feature" that will be returned by this function.
/** @type {EventSourceFeature} */
var feature = {
name: eventSourceName,
object: stub,
install: function (target) {
runtime.assignToNamespace(target, nameSpace, eventSourceName, stub);
},
};
// Parse each event listener and add it into the list
while (tokens.matchToken("on")) {
// get event name
var eventName = parser.requireElement("stringLike", tokens, "Expected event name").evaluate(); // OK to evaluate this in real-time?
// default encoding is "" (autodetect)
var encoding = "";
// look for alternate encoding
if (tokens.matchToken("as")) {
encoding = parser.requireElement("stringLike", tokens, "Expected encoding type").evaluate(); // Ok to evaluate this in real time?
}
// get command list for this event handler
var commandList = parser.requireElement("commandList", tokens);
addImplicitReturnToCommandList(commandList);
tokens.requireToken("end");
// Save the event listener into the feature. This lets us
// connect listeners to new EventSources if we have to reconnect.
stub.listeners.push({
type: eventName,
handler: makeHandler(encoding, commandList),
});
}
tokens.requireToken("end");
// If we have a URL element, then connect to the remote server now.
// Otherwise, we can connect later with a call to .open()
if (urlElement != undefined) {
stub.open(urlElement.evaluate());
}
// Success!
return feature;
////////////////////////////////////////////
// ADDITIONAL HELPER FUNCTIONS HERE...
////////////////////////////////////////////
/**
* Makes an eventHandler function that can execute the correct hyperscript commands
* This is outside of the main loop so that closures don't cause us to run the wrong commands.
*
* @param {string} encoding
* @param {*} commandList
* @returns {EventHandlerNonNull}
*/
function makeHandler(encoding, commandList) {
return function (evt) {
var data = decode(evt["data"], encoding);
var context = runtime.makeContext(stub, feature, stub);
context.event = evt;
context.result = data;
commandList.execute(context);
};
}
/**
* Decodes/Unmarshals a string based on the selected encoding. If the
* encoding is not recognized, attempts to auto-detect based on its content
*
* @param {string} data - The original data to be decoded
* @param {string} encoding - The method that the data is currently encoded ("string", "json", or unknown)
* @returns {string} - The decoded data
*/
function decode(data, encoding) {
// Force JSON encoding
if (encoding == "json") {
return JSON.parse(data);
}
// Otherwise, return the data without modification
return data;
}
/**
* Adds a "HALT" command to the commandList.
* TODO: This seems like something that could be optimized:
* maybe the parser could do automatically,
* or could be a public function in the parser available to everyone,
* or the command-executer-thingy could just handle nulls implicitly.
*
* @param {*} commandList
* @returns void
*/
function addImplicitReturnToCommandList(commandList) {
if (commandList.next) {
return addImplicitReturnToCommandList(commandList.next);
}
commandList.next = {
type: "implicitReturn",
op: function (/** @type {Context} */ _context) {
return runtime.HALT;
},
execute: function (/** @type {Context} */ _context) {
// do nothing
},
};
}
}
});
}
})