-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhmr.js
528 lines (464 loc) · 21.6 KB
/
hmr.js
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
//////////////////// HMR BEGIN ////////////////////
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Original Author: Flux Xu @fluxxu
*/
/*
A note about the environment that this code runs in...
assumed globals:
- `module` (from Node.js module system and webpack)
assumed in scope after injection into the Elm IIFE:
- `scope` (has an 'Elm' property which contains the public Elm API)
- various functions defined by Elm which we have to hook such as `_Platform_initialize` and `_Scheduler_binding`
*/
if (module.hot) {
(function () {
"use strict";
//polyfill for IE: https://github.com/fluxxu/elm-hot-loader/issues/16
if (typeof Object.assign != 'function') {
Object.assign = function (target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
// Elm 0.19.1 introduced a '$' prefix at the beginning of the symbols it emits,
// and we check for `Maybe.Just` because we expect it to be present in all Elm programs.
var elmVersion;
if (typeof elm$core$Maybe$Just !== 'undefined')
elmVersion = '0.19.0';
else if (typeof $elm$core$Maybe$Just !== 'undefined')
elmVersion = '0.19.1';
else
throw new Error("Could not determine Elm version");
function elmSymbol(symbol) {
try {
switch (elmVersion) {
case '0.19.0':
return eval(symbol);
case '0.19.1':
return eval('$' + symbol);
default:
throw new Error('Cannot resolve ' + symbol + '. Elm version unknown!')
}
} catch (e) {
if (e instanceof ReferenceError) {
return undefined;
} else {
throw e;
}
}
}
var instances = module.hot.data
? module.hot.data.instances || {}
: {};
var uid = module.hot.data
? module.hot.data.uid || 0
: 0;
if (Object.keys(instances).length === 0) {
log("[elm-hot] Enabled");
}
var cancellers = [];
// These 2 variables act as dynamically-scoped variables which are set only when the
// Elm module's hooked init function is called.
var initializingInstance = null;
var swappingInstance = null;
module.hot.accept();
module.hot.dispose(function (data) {
data.instances = instances;
data.uid = uid;
// Cleanup pending async tasks
// First, make sure that no new tasks can be started until we finish replacing the code
_Scheduler_binding = function () {
return _Scheduler_fail(new Error('[elm-hot] Inactive Elm instance.'))
};
// Second, kill pending tasks belonging to the old instance
if (cancellers.length) {
log('[elm-hot] Killing ' + cancellers.length + ' running processes...');
try {
cancellers.forEach(function (cancel) {
cancel();
});
} catch (e) {
console.warn('[elm-hot] Kill process error: ' + e.message);
}
}
});
function log(message) {
if (module.hot.verbose) {
console.log(message)
}
}
function getId() {
return ++uid;
}
function findPublicModules(parent, path) {
var modules = [];
for (var key in parent) {
var child = parent[key];
var currentPath = path ? path + '.' + key : key;
if ('init' in child) {
modules.push({
path: currentPath,
module: child
});
} else {
modules = modules.concat(findPublicModules(child, currentPath));
}
}
return modules;
}
function registerInstance(domNode, flags, path, portSubscribes, portSends) {
var id = getId();
var instance = {
id: id,
path: path,
domNode: domNode,
flags: flags,
portSubscribes: portSubscribes,
portSends: portSends,
lastState: null // last Elm app state (root model)
};
return instances[id] = instance
}
function isFullscreenApp() {
// Returns true if the Elm app will take over the entire DOM body.
return typeof elmSymbol("elm$browser$Browser$application") !== 'undefined'
|| typeof elmSymbol("elm$browser$Browser$document") !== 'undefined';
}
function wrapDomNode(node) {
// When embedding an Elm app into a specific DOM node, Elm will replace the provided
// DOM node with the Elm app's content. When the Elm app is compiled normally, the
// original DOM node is reused (its attributes and content changes, but the object
// in memory remains the same). But when compiled using `--debug`, Elm will completely
// destroy the original DOM node and instead replace it with 2 brand new nodes: one
// for your Elm app's content and the other for the Elm debugger UI. In this case,
// if you held a reference to the DOM node provided for embedding, it would be orphaned
// after Elm module initialization.
//
// So in order to make both cases consistent and isolate us from changes in how Elm
// does this, we will insert a dummy node to wrap the node for embedding and hold
// a reference to the dummy node.
//
// We will also put a tag on the dummy node so that the Elm developer knows who went
// behind their back and rudely put stuff in their DOM.
var dummyNode = document.createElement("div");
dummyNode.setAttribute("data-elm-hot", "true");
dummyNode.style.height = "inherit";
var parentNode = node.parentNode;
parentNode.replaceChild(dummyNode, node);
dummyNode.appendChild(node);
return dummyNode;
}
function wrapPublicModule(path, module) {
var originalInit = module.init;
if (originalInit) {
module.init = function (args) {
var elm;
var portSubscribes = {};
var portSends = {};
var domNode = null;
var flags = null;
if (typeof args !== 'undefined') {
// normal case
domNode = args['node'] && !isFullscreenApp()
? wrapDomNode(args['node'])
: document.body;
flags = args['flags'];
} else {
// rare case: Elm allows init to be called without any arguments at all
domNode = document.body;
flags = undefined
}
initializingInstance = registerInstance(domNode, flags, path, portSubscribes, portSends);
elm = originalInit(args);
wrapPorts(elm, portSubscribes, portSends);
initializingInstance = null;
return elm;
};
} else {
console.error("Could not find a public module to wrap at path " + path)
}
}
function swap(Elm, instance) {
log('[elm-hot] Hot-swapping module: ' + instance.path);
swappingInstance = instance;
// remove from the DOM everything that had been created by the old Elm app
var containerNode = instance.domNode;
while (containerNode.lastChild) {
containerNode.removeChild(containerNode.lastChild);
}
var m = getAt(instance.path.split('.'), Elm);
var elm;
if (m) {
// prepare to initialize the new Elm module
var args = {flags: instance.flags};
if (containerNode === document.body) {
// fullscreen case: no additional args needed
} else {
// embed case: provide a new node for Elm to use
var nodeForEmbed = document.createElement("div");
containerNode.appendChild(nodeForEmbed);
args['node'] = nodeForEmbed;
}
elm = m.init(args);
Object.keys(instance.portSubscribes).forEach(function (portName) {
if (portName in elm.ports && 'subscribe' in elm.ports[portName]) {
var handlers = instance.portSubscribes[portName];
if (!handlers.length) {
return;
}
log('[elm-hot] Reconnect ' + handlers.length + ' handler(s) to port \''
+ portName + '\' (' + instance.path + ').');
handlers.forEach(function (handler) {
elm.ports[portName].subscribe(handler);
});
} else {
delete instance.portSubscribes[portName];
log('[elm-hot] Port was removed: ' + portName);
}
});
Object.keys(instance.portSends).forEach(function (portName) {
if (portName in elm.ports && 'send' in elm.ports[portName]) {
log('[elm-hot] Replace old port send with the new send');
instance.portSends[portName] = elm.ports[portName].send;
} else {
delete instance.portSends[portName];
log('[elm-hot] Port was removed: ' + portName);
}
});
} else {
log('[elm-hot] Module was removed: ' + instance.path);
}
swappingInstance = null;
}
function wrapPorts(elm, portSubscribes, portSends) {
var portNames = Object.keys(elm.ports || {});
//hook ports
if (portNames.length) {
// hook outgoing ports
portNames
.filter(function (name) {
return 'subscribe' in elm.ports[name];
})
.forEach(function (portName) {
var port = elm.ports[portName];
var subscribe = port.subscribe;
var unsubscribe = port.unsubscribe;
elm.ports[portName] = Object.assign(port, {
subscribe: function (handler) {
log('[elm-hot] ports.' + portName + '.subscribe called.');
if (!portSubscribes[portName]) {
portSubscribes[portName] = [handler];
} else {
//TODO handle subscribing to single handler more than once?
portSubscribes[portName].push(handler);
}
return subscribe.call(port, handler);
},
unsubscribe: function (handler) {
log('[elm-hot] ports.' + portName + '.unsubscribe called.');
var list = portSubscribes[portName];
if (list && list.indexOf(handler) !== -1) {
list.splice(list.lastIndexOf(handler), 1);
} else {
console.warn('[elm-hot] ports.' + portName + '.unsubscribe: handler not subscribed');
}
return unsubscribe.call(port, handler);
}
});
});
// hook incoming ports
portNames
.filter(function (name) {
return 'send' in elm.ports[name];
})
.forEach(function (portName) {
var port = elm.ports[portName];
portSends[portName] = port.send;
elm.ports[portName] = Object.assign(port, {
send: function (val) {
return portSends[portName].call(port, val);
}
});
});
}
return portSubscribes;
}
/*
Breadth-first search for a `Browser.Navigation.Key` in the user's app model.
Returns the key and keypath or null if not found.
*/
function findNavKey(rootModel) {
var queue = [];
if (isDebuggerModel(rootModel)) {
/*
Extract the user's app model from the Elm Debugger's model. The Elm debugger
can hold multiple references to the user's model (e.g. in its "history"). So
we must be careful to only search within the "state" part of the Debugger.
*/
queue.push({value: rootModel['state'], keypath: ['state']});
} else {
queue.push({value: rootModel, keypath: []});
}
while (queue.length !== 0) {
var item = queue.shift();
if (typeof item.value === "undefined" || item.value === null) {
continue;
}
// The nav key is identified by a runtime tag added by the elm-hot injector.
if (item.value.hasOwnProperty("elm-hot-nav-key")) {
// found it!
return item;
}
if (typeof item.value !== "object") {
continue;
}
for (var propName in item.value) {
if (!item.value.hasOwnProperty(propName)) continue;
var newKeypath = item.keypath.slice();
newKeypath.push(propName);
queue.push({value: item.value[propName], keypath: newKeypath})
}
}
return null;
}
function isDebuggerModel(model) {
// Up until elm/browser 1.0.2, the Elm debugger could be identified by a
// property named "expando". But in version 1.0.2 that was renamed to "expandoModel"
return model
&& (model.hasOwnProperty("expando") || model.hasOwnProperty("expandoModel"))
&& model.hasOwnProperty("state");
}
function getAt(keyPath, obj) {
return keyPath.reduce(function (xs, x) {
return (xs && xs[x]) ? xs[x] : null
}, obj)
}
function removeNavKeyListeners(navKey) {
window.removeEventListener('popstate', navKey.value);
window.navigator.userAgent.indexOf('Trident') < 0 || window.removeEventListener('hashchange', navKey.value);
}
// hook program creation
var initialize = _Platform_initialize;
_Platform_initialize = function (flagDecoder, args, init, update, subscriptions, stepperBuilder) {
var instance = initializingInstance || swappingInstance;
var tryFirstRender = !!swappingInstance;
var hookedInit = function (args) {
var initialStateTuple = init(args);
if (swappingInstance) {
var oldModel = swappingInstance.lastState;
var newModel = initialStateTuple.a;
if (typeof elmSymbol("elm$browser$Browser$application") !== 'undefined') {
var oldKeyLoc = findNavKey(oldModel);
// attempt to find the Browser.Navigation.Key in the newly-constructed model
// and bring it along with the rest of the old data.
var newKeyLoc = findNavKey(newModel);
var error = null;
if (newKeyLoc === null) {
error = "could not find Browser.Navigation.Key in the new app model";
} else if (oldKeyLoc === null) {
error = "could not find Browser.Navigation.Key in the old app model.";
} else if (newKeyLoc.keypath.toString() !== oldKeyLoc.keypath.toString()) {
error = "the location of the Browser.Navigation.Key in the model has changed.";
} else {
// remove event listeners attached to the old nav key
removeNavKeyListeners(oldKeyLoc.value);
// insert the new nav key into the old model in the exact same location
var parentKeyPath = oldKeyLoc.keypath.slice(0, -1);
var lastSegment = oldKeyLoc.keypath.slice(-1)[0];
var oldParent = getAt(parentKeyPath, oldModel);
oldParent[lastSegment] = newKeyLoc.value;
}
if (error !== null) {
console.error("[elm-hot] Hot-swapping " + instance.path + " not possible: " + error);
oldModel = newModel;
}
}
// the heart of the app state hot-swap
initialStateTuple.a = oldModel;
// ignore any Cmds returned by the init during hot-swap
initialStateTuple.b = elmSymbol("elm$core$Platform$Cmd$none");
} else {
// capture the initial state for later
initializingInstance.lastState = initialStateTuple.a;
}
return initialStateTuple
};
var hookedStepperBuilder = function (sendToApp, model) {
var result;
// first render may fail if shape of model changed too much
if (tryFirstRender) {
tryFirstRender = false;
try {
result = stepperBuilder(sendToApp, model)
} catch (e) {
throw new Error('[elm-hot] Hot-swapping ' + instance.path +
' is not possible, please reload page. Error: ' + e.message)
}
} else {
result = stepperBuilder(sendToApp, model)
}
return function (nextModel, isSync) {
if (instance) {
// capture the state after every step so that later we can restore from it during a hot-swap
instance.lastState = nextModel
}
return result(nextModel, isSync)
}
};
return initialize(flagDecoder, args, hookedInit, update, subscriptions, hookedStepperBuilder)
};
// hook process creation
var originalBinding = _Scheduler_binding;
_Scheduler_binding = function (originalCallback) {
return originalBinding(function () {
// start the scheduled process, which may return a cancellation function.
var cancel = originalCallback.apply(this, arguments);
if (cancel) {
cancellers.push(cancel);
return function () {
cancellers.splice(cancellers.indexOf(cancel), 1);
return cancel();
};
}
return cancel;
});
};
scope['_elm_hot_loader_init'] = function (Elm) {
// swap instances
var removedInstances = [];
for (var id in instances) {
var instance = instances[id];
if (instance.domNode.parentNode) {
swap(Elm, instance);
} else {
removedInstances.push(id);
}
}
removedInstances.forEach(function (id) {
delete instance[id];
});
// wrap all public modules
var publicModules = findPublicModules(Elm);
publicModules.forEach(function (m) {
wrapPublicModule(m.path, m.module);
});
}
})();
scope['_elm_hot_loader_init'](scope['Elm']);
}
//////////////////// HMR END ////////////////////