-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifecycle-node.js
576 lines (495 loc) · 18.4 KB
/
lifecycle-node.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*jshint evil: true */
/*global Promise: true */
'use strict';
var fs = require('fs'),
path = require('path');
if (typeof Promise === 'undefined') {
var Promise = require('./support/prim');
}
/**
* amodro-lifecycle 0.1.1 (c) 2015, The Dojo Foundation All Rights Reserved.
* MIT or new BSD license.
*/
function Lifecycle(parent) {
'use strict';
this.parent = parent;
this.top = parent ? parent.top : this;
this.modules = {};
this.instantiated = {};
this.registry = {};
this.waiting = {};
this.factoryTrees = [];
this.data = {};
}
(function() {
'use strict';
var hasOwn = Object.prototype.hasOwnProperty;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
// These helpers are useful when dealing with Lifecycle instance properties,
// matches what is used internally.
Lifecycle.hasProp = hasProp;
Lifecycle.getOwn = getOwn;
function moduleError(id, err) {
var newError = new Error(id + ' failed: ' + err);
newError.originalError = err;
throw newError;
}
function ensurePromise(value) {
if (!value || !value.then) {
return Promise.resolve(value);
}
return value;
}
function trace(instance, id, order, found, cycleDetected) {
var registeredEntry = instance.getRegistered(id);
// May already be defined, no longer in registry and that is OK. Another
// factoryTree took care of it.
if (!registeredEntry) {
return;
}
var deps = registeredEntry.registered.deps;
deps.forEach(function(depId) {
if (instance.isSpecialDep(depId)) {
return;
}
if (hasProp(found, depId)) {
if (!hasProp(cycleDetected, depId)) {
cycleDetected[depId] = true;
instance.cycleDetected(depId, order);
}
} else {
// A separate found map for each dependency, so that trees like this
// do not end up with baz executing before bar:
// foo -> bar, baz
// baz -> bar
// If the found map is shared, can end up with execution order:
// [baz, bar, foo], where bar should be before baz.
var depFound = {};
depFound[depId] = true;
Object.keys(found).forEach(function(key) {
depFound[key] = true;
});
order.unshift(depId);
trace(instance, depId, order, depFound, cycleDetected);
}
});
}
var fsIdCounter = 0;
Lifecycle.prototype = {
getWaiting: function(normalizedId) {
var waiting = getOwn(this.waiting, normalizedId);
if (!waiting) {
waiting = this.parent && this.parent.getWaiting(normalizedId);
}
return waiting || undefined;
},
removeWaiting: function(normalizedId) {
if (hasProp(this.waiting, normalizedId)) {
delete this.waiting[normalizedId];
} else if (this.parent) {
this.parent.removeWaiting(normalizedId);
}
},
getRegistered: function(normalizedId) {
var record,
registered = getOwn(this.registry, normalizedId);
if (registered) {
record = {
instance: this,
registered: registered
};
} else if (this.parent) {
record = this.parent.getRegistered(normalizedId);
}
return record;
},
removeRegistered: function(normalizedId) {
if (hasProp(this.registry, normalizedId)) {
delete this.registry[normalizedId];
} else if (this.parent) {
this.parent.removeRegistry(normalizedId);
}
},
/**
* Returns true if the loader contains a module for the module ID. It may
* not actually be defined yet though, may still in process of loading, so
* to get a handle on it, use async APIs to get to it.
* @param {String} normalizedId
* @return {Boolean}
*/
containsModule: function(normalizedId) {
return hasProp(this.modules, normalizedId) ||
hasProp(this.registry, normalizedId) ||
(this.parent && this.parent.containsModule(normalizedId));
},
/**
* Returns true if there is a module value for the given ID. The value may
* not be fully defined yet, for a module in a cycle.
* @param {String} normalizedId
* @return {Boolean}
*/
hasModule: function(normalizedId) {
return hasProp(this.modules, normalizedId) ||
(this.parent && this.parent.hasModule(normalizedId));
},
getModule: function(normalizedId, throwOnMiss) {
if (hasProp(this.modules, normalizedId)) {
return this.modules[normalizedId];
} else if (this.parent) {
return this.parent.getModule(normalizedId, throwOnMiss);
}
if (throwOnMiss) {
throw new Error(normalizedId + ' is not set yet.');
}
},
setModule: function(normalizedId, value, isTemp) {
if(!hasProp(this.instantiated, normalizedId)) {
this.modules[normalizedId] = value;
if (!isTemp) {
this.instantiated[normalizedId] = true;
}
}
return value;
},
removeModule: function(normalizedId) {
if (hasProp(this.modules, normalizedId) ||
hasProp(this.waiting, normalizedId) ||
hasProp(this.registry, normalizedId)) {
this.removeRegistered(normalizedId);
this.removeWaiting(normalizedId);
delete this.modules[normalizedId];
delete this.instantiated[normalizedId];
} else if (this.parent) {
return this.parent.removeModule(normalizedId);
}
},
/**
* Gets a mutable object that is specific to the normalizedId. Allows state
* coordination between lifecycle steps and overrides.
* @param {String} normalizedId
* @return {Object}
*/
getData: function(normalizedId) {
return this.data[normalizedId] || (this.data[normalizedId] = {});
},
/**
* Triggers loading and resolution of modules. Outside callers of this
* function should only pass id and refId. factoryTree is used
* internally to track recursive tracing of modules and proper cycle
* breaking.
* @param {String} id The string ID of the module
* @param {String} refId A reference module ID, used to normalize
* the id value to an absolute ID.
* @param {Array} [factoryTree] Used internally to track execution
* order based on dependency tree.
* @return {Promise} Promise, resolves to module ID value.
*/
useUnnormalized: function(id, refId, factoryTree) {
var normalizedId;
// Top level use calls may be loader plugin resources, so ask for depend
// hooks to determine if there are any other dependencies for the id
// before proceeding.
return ensurePromise(this.top.depend(refId, [id]))
.then(function() {
try {
normalizedId = this.top.normalize(id, refId);
} catch (e) {
moduleError(id + ', ' + refId, e);
}
return this.use(normalizedId, refId, factoryTree);
}.bind(this));
},
/**
* Triggers loading and resolution of modules after an ID has been
* normalized. Outside callers of this function should only pass id and
* refId. factoryTree is used internally to track recursive tracing of
* modules and proper cycle breaking.
* @param {String} normalizedId The normalized string ID of the module
* @param {String} refId A reference module ID, used to relate
* this use call to another module for cycle/dependency tracing.
* @param {Array} [factoryTree] Used internally to track execution
* order based on dependency tree.
* @return {Promise} Promise, resolves to module ID value.
*/
use: function(normalizedId, refId, factoryTree) {
var instantiated = false;
return Promise.resolve().then(function() {
// If already defined, just resturn the module.
if (hasProp(this.instantiated, normalizedId)) {
instantiated = true;
return;
}
if (!factoryTree) {
this.factoryTrees.push(factoryTree = {
desc: (refId || '[Top]') + ' asking for ' + normalizedId +
' (id' + (fsIdCounter++) + ')',
depCount: 0,
startRefId: refId,
startId: normalizedId,
depIds: {}
});
}
if (hasProp(factoryTree.depIds, normalizedId)) {
// Return from here, ID already known.
instantiated = true;
return;
} else {
factoryTree.depCount += 1;
factoryTree.depIds[normalizedId] = true;
}
// If already waiting on the module, then just wait for it.
var waiting;
try {
waiting = this.getWaiting(normalizedId);
} catch (e) {
moduleError(normalizedId, e);
}
if (waiting) {
return waiting;
}
// No waiting record, but could have a registered entry from a bulk
// module load, waiting for a top level dependency chain to activate
// and trace dependencies.
var record = this.getRegistered(normalizedId);
if (record) {
var registered = record.registered;
return (record.instance.waiting[normalizedId] =
record.instance.callDepend(normalizedId,
registered.deps,
factoryTree));
}
// Not already waiting or in registry, needs to be fetched/loaded.
var location = this.top.locate(normalizedId, 'js');
return this.top.load(normalizedId, refId, location, factoryTree);
}.bind(this))
.then(function() {
// If considered "instantiate" skip the dependency tracing for
// factoryTree. Could really be instantiated or a cycle that should
// be considered "instantiated" to resolve the cycle.
if (instantiated) {
return;
}
// Now that the module has had its deps normalized, use them all, and
// track them on the factoryTree. Need this to happen for every
// factoryTree that comes through to poperly get full dependency
// chain. But only needs to be done if module is still in registry
// waiting completion of full processing.
var record = this.getRegistered(normalizedId);
if (record) {
var deps = record.registered.deps;
if (!deps || !deps.length) {
return;
}
return Promise.all(deps.map(function(depId) {
return this.use(depId, normalizedId, factoryTree);
}.bind(this)));
}
}.bind(this))
.then(function() {
// If the ID was part of a factory sequence, indicate complete. It may
// not be if the module was already in modules.
if (factoryTree && !instantiated) {
this.factoryTreeDepComplete(factoryTree);
}
var value = this.getModule(normalizedId);
return value;
}.bind(this));
},
/**
* Used internally by lifecycle to complete the load of a resource. Results
* in a waiting promise set for the normalizedId.
* @param {String} normalizedId
* @param {String} location
* @param {Array} factoryTree
* @return {Promise}
*/
load: function(normalizedId, refId, location, factoryTree) {
return (this.waiting[normalizedId] =
ensurePromise(this.fetch(normalizedId, refId, location))
.then(function(source) {
try {
// Protect against fetch promise results being something like a
// module value, in the case of plugins.
if (typeof source === 'string' && source) {
source = this.translate(normalizedId, location, source);
}
// Some cases, like script tag-based loading, do not have source to
// parse, hidden by browser security restrictions from seeing the
// source.
if (typeof source === 'string' && source) {
this.parse(normalizedId, location, source);
}
var registered = getOwn(this.registry, normalizedId);
return this.top.callDepend(normalizedId,
registered.deps,
factoryTree);
} catch (e) {
moduleError(normalizedId, e);
}
}.bind(this)));
},
/**
* Use this to register a module for resolution without going through the
* load steps. Useful for cases like multiple inlined modules in a file,
* where they will not need to be loaded from the network.
* @param {String} normalizedId
* @param {Array} deps
* @param {Function} factory
*/
addToRegistry: function(normalizedId, deps, factory) {
// Favor this registry vs asking up the parent chain, to support local
// module definitions.
if (!hasProp(this.registry, normalizedId)) {
var entry = {
deps: deps,
factory: factory
};
this.registry[normalizedId] = entry;
}
},
/**
* Calls the depend function, then normalizes the dependency IDs before
* resolving.
* @param {String} normalizedId
* @param {Array} deps
* @return {Promise}
*/
callDepend: function(normalizedId, deps, factoryTree) {
if (!deps || !deps.length) {
return Promise.resolve([]);
}
return ensurePromise(this.depend(normalizedId, deps))
.then(function(deps) {
var normalizedDeps = deps.map(function(depId) {
return this.normalize(depId, normalizedId);
}.bind(this));
// The normalized reference ID could be undefined if a top level .use
// call outside of a module.
if (normalizedId) {
this.registry[normalizedId].deps = normalizedDeps;
}
return normalizedDeps;
}.bind(this));
},
/**
* Used internally. Should not be called directly. When a dependency
* loads, checks to see if a whole dependency chain is loaded, and if so,
* calls the factory functions based on the dependency order specified by
* tracing the dependencies for the ID that started the factoryTree.
* @param {Array} factoryTree
*/
factoryTreeDepComplete: function(factoryTree) {
factoryTree.depCount -= 1;
if (factoryTree.depCount !== 0) {
return;
}
// Sequences are now complete, execute factories for the dependency chain
// in the right order. Trace the dep tree to find the right order.
var startId = factoryTree.startId,
order = [startId],
found = {};
found[startId] = true;
// If a starting refId, could be something like a loader plugin that asked
// for a dynamic load of dependencies, which in turn could depend on the
// loader plugin resource. Allow breaking that chain here.
//todo: create test case to exercise this code.
if (factoryTree.startRefId) {
found[factoryTree.startRefId] = true;
}
trace(this, startId, order, found, {});
for (var i = 0; i < order.length; i++) {
var depId = order[i],
registeredEntry = this.getRegistered(depId);
//registered may not exist, dependency could have already been handled
//by a different factoryTree, and that is OK.
if (!registeredEntry) {
continue;
}
var registered = registeredEntry.registered;
try {
this.setModule(depId, this.instantiate(depId,
registered.deps,
registered.factory));
this.removeRegistered(depId);
this.removeWaiting(depId);
} catch (e) {
moduleError(depId, e);
}
}
// Clean up.
var index = this.factoryTrees.indexOf(factoryTree);
if (index !== -1) {
this.factoryTrees.splice(index, 1);
}
},
// Implement this if you want to log when cycles occur. If this method
// throws, it will put the loading into a failure state.
cycleDetected: function(id, cycleOrder) {
},
normalize: function(id, refId) {
// sync
return id;
},
locate: function(normalizedId, suggestedExtension) {
// sync
return normalizedId +
(suggestedExtension ? '.' + suggestedExtension : '');
},
fetch: function(normalizedId, refId, location) {
// async
return Promise.resolve('');
},
translate: function(normalizedId, location, source) {
// sync
return source;
},
/**
* Parse the source a of module. May not apply in some module situations,
* like AMD modules loaded via script tags, where the parse and script
* evaluation happens as part of fetch. Can be overridden if parsing should
* happen differently. For instance, in node, perhaps using the vm module to
* execute the script as a means of parsing it and resulting in registry
* entries.. Or for loader plugins, making sure the parsed result gets
* converted to registry entries in some way.
*
* If it is called and a previous lifecycle step has not done so, parse
* should result in a this.registry entry for the given module, if the
* module has dependencies and wants to export a specific module value.
*
* @param {String} normalizedId
* @param {String} location
* @param {String} source
*/
parse: function(normalizedId, location, source) {
/*jshint evil: true*/
// Sync
// This is just a placeholder so basic tests do something useful.
var lifecycle = this;
eval(source);
},
depend: function(normalizedId, deps) {
// async. deps are not normalized yet.
return Promise.resolve(deps);
},
instantiate: function(normalizedId, deps, factory) {
// sync
return factory(deps.map(function(dep) {
return this.getModule(dep);
}.bind(this)));
},
/**
* Some module systems have special dependencies, like the require,
* exports, module ones in AMD modules. That kind of loader can implement
* this method to avoid some of the noise with module logging and tracing.
*/
isSpecialDep: function(normalizedId) {
return false;
}
};
}());
module.exports = Lifecycle;