-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
container.js
851 lines (647 loc) · 22.7 KB
/
container.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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
import Ember from 'ember-metal/core'; // Ember.assert
import emberKeys from "ember-metal/keys";
import dictionary from 'ember-metal/dictionary';
// A lightweight container that helps to assemble and decouple components.
// Public api for the container is still in flux.
// The public api, specified on the application namespace should be considered the stable api.
function Container(parent) {
this.parent = parent;
this.children = [];
this.resolver = parent && parent.resolver || function() {};
this.registry = dictionary(parent ? parent.registry : null);
this.cache = dictionary(parent ? parent.cache : null);
this.factoryCache = dictionary(parent ? parent.factoryCache : null);
this.resolveCache = dictionary(parent ? parent.resolveCache : null);
this.typeInjections = dictionary(parent ? parent.typeInjections : null);
this.injections = dictionary(null);
this.normalizeCache = dictionary(null);
this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null);
this.factoryInjections = dictionary(null);
this._options = dictionary(parent ? parent._options : null);
this._typeOptions = dictionary(parent ? parent._typeOptions : null);
}
Container.prototype = {
/**
@property parent
@type Container
@default null
*/
parent: null,
/**
@property children
@type Array
@default []
*/
children: null,
/**
@property resolver
@type function
*/
resolver: null,
/**
@property registry
@type InheritingDict
*/
registry: null,
/**
@property cache
@type InheritingDict
*/
cache: null,
/**
@property typeInjections
@type InheritingDict
*/
typeInjections: null,
/**
@property injections
@type Object
@default {}
*/
injections: null,
/**
@private
@property _options
@type InheritingDict
@default null
*/
_options: null,
/**
@private
@property _typeOptions
@type InheritingDict
*/
_typeOptions: null,
/**
Returns a new child of the current container. These children are configured
to correctly inherit from the current container.
@method child
@return {Container}
*/
child: function() {
var container = new Container(this);
this.children.push(container);
return container;
},
/**
Sets a key-value pair on the current container. If a parent container,
has the same key, once set on a child, the parent and child will diverge
as expected.
@method set
@param {Object} object
@param {String} key
@param {any} value
*/
set: function(object, key, value) {
object[key] = value;
},
/**
Registers a factory for later injection.
Example:
```javascript
var container = new Container();
container.register('model:user', Person, {singleton: false });
container.register('fruit:favorite', Orange);
container.register('communication:main', Email, {singleton: false});
```
@method register
@param {String} fullName
@param {Function} factory
@param {Object} options
*/
register: function(fullName, factory, options) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (factory === undefined) {
throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`');
}
var normalizedName = this.normalize(fullName);
if (normalizedName in this.cache) {
throw new Error('Cannot re-register: `' + fullName +'`, as it has already been looked up.');
}
this.registry[normalizedName] = factory;
this._options[normalizedName] = (options || {});
},
/**
Unregister a fullName
```javascript
var container = new Container();
container.register('model:user', User);
container.lookup('model:user') instanceof User //=> true
container.unregister('model:user')
container.lookup('model:user') === undefined //=> true
```
@method unregister
@param {String} fullName
*/
unregister: function(fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
var normalizedName = this.normalize(fullName);
delete this.registry[normalizedName];
delete this.cache[normalizedName];
delete this.factoryCache[normalizedName];
delete this.resolveCache[normalizedName];
delete this._options[normalizedName];
},
/**
Given a fullName return the corresponding factory.
By default `resolve` will retrieve the factory from
its container's registry.
```javascript
var container = new Container();
container.register('api:twitter', Twitter);
container.resolve('api:twitter') // => Twitter
```
Optionally the container can be provided with a custom resolver.
If provided, `resolve` will first provide the custom resolver
the opportunity to resolve the fullName, otherwise it will fallback
to the registry.
```javascript
var container = new Container();
container.resolver = function(fullName) {
// lookup via the module system of choice
};
// the twitter factory is added to the module system
container.resolve('api:twitter') // => Twitter
```
@method resolve
@param {String} fullName
@return {Function} fullName's factory
*/
resolve: function(fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
return resolve(this, this.normalize(fullName));
},
/**
A hook that can be used to describe how the resolver will
attempt to find the factory.
For example, the default Ember `.describe` returns the full
class name (including namespace) where Ember's resolver expects
to find the `fullName`.
@method describe
@param {String} fullName
@return {string} described fullName
*/
describe: function(fullName) {
return fullName;
},
/**
A hook to enable custom fullName normalization behaviour
@method normalizeFullName
@param {String} fullName
@return {string} normalized fullName
*/
normalizeFullName: function(fullName) {
return fullName;
},
/**
normalize a fullName based on the applications conventions
@method normalize
@param {String} fullName
@return {string} normalized fullName
*/
normalize: function(fullName) {
return this.normalizeCache[fullName] || (
this.normalizeCache[fullName] = this.normalizeFullName(fullName)
);
},
/**
@method makeToString
@param {any} factory
@param {string} fullName
@return {function} toString function
*/
makeToString: function(factory, fullName) {
return factory.toString();
},
/**
Given a fullName return a corresponding instance.
The default behaviour is for lookup to return a singleton instance.
The singleton is scoped to the container, allowing multiple containers
to all have their own locally scoped singletons.
```javascript
var container = new Container();
container.register('api:twitter', Twitter);
var twitter = container.lookup('api:twitter');
twitter instanceof Twitter; // => true
// by default the container will return singletons
var twitter2 = container.lookup('api:twitter');
twitter2 instanceof Twitter; // => true
twitter === twitter2; //=> true
```
If singletons are not wanted an optional flag can be provided at lookup.
```javascript
var container = new Container();
container.register('api:twitter', Twitter);
var twitter = container.lookup('api:twitter', { singleton: false });
var twitter2 = container.lookup('api:twitter', { singleton: false });
twitter === twitter2; //=> false
```
@method lookup
@param {String} fullName
@param {Object} options
@return {any}
*/
lookup: function(fullName, options) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
return lookup(this, this.normalize(fullName), options);
},
/**
Given a fullName return the corresponding factory.
@method lookupFactory
@param {String} fullName
@return {any}
*/
lookupFactory: function(fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
return factoryFor(this, this.normalize(fullName));
},
/**
Given a fullName check if the container is aware of its factory
or singleton instance.
@method has
@param {String} fullName
@return {Boolean}
*/
has: function(fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
return has(this, this.normalize(fullName));
},
/**
Allow registering options for all factories of a type.
```javascript
var container = new Container();
// if all of type `connection` must not be singletons
container.optionsForType('connection', { singleton: false });
container.register('connection:twitter', TwitterConnection);
container.register('connection:facebook', FacebookConnection);
var twitter = container.lookup('connection:twitter');
var twitter2 = container.lookup('connection:twitter');
twitter === twitter2; // => false
var facebook = container.lookup('connection:facebook');
var facebook2 = container.lookup('connection:facebook');
facebook === facebook2; // => false
```
@method optionsForType
@param {String} type
@param {Object} options
*/
optionsForType: function(type, options) {
if (this.parent) { illegalChildOperation('optionsForType'); }
this._typeOptions[type] = options;
},
/**
@method options
@param {String} type
@param {Object} options
*/
options: function(type, options) {
this.optionsForType(type, options);
},
/**
Used only via `injection`.
Provides a specialized form of injection, specifically enabling
all objects of one type to be injected with a reference to another
object.
For example, provided each object of type `controller` needed a `router`.
one would do the following:
```javascript
var container = new Container();
container.register('router:main', Router);
container.register('controller:user', UserController);
container.register('controller:post', PostController);
container.typeInjection('controller', 'router', 'router:main');
var user = container.lookup('controller:user');
var post = container.lookup('controller:post');
user.router instanceof Router; //=> true
post.router instanceof Router; //=> true
// both controllers share the same router
user.router === post.router; //=> true
```
@private
@method typeInjection
@param {String} type
@param {String} property
@param {String} fullName
*/
typeInjection: function(type, property, fullName) {
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (this.parent) { illegalChildOperation('typeInjection'); }
var fullNameType = fullName.split(':')[0];
if (fullNameType === type) {
throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s). Register the `' + fullName + '` as a different type and perform the typeInjection.');
}
addTypeInjection(this.typeInjections, type, property, fullName);
},
/**
Defines injection rules.
These rules are used to inject dependencies onto objects when they
are instantiated.
Two forms of injections are possible:
* Injecting one fullName on another fullName
* Injecting one fullName on a type
Example:
```javascript
var container = new Container();
container.register('source:main', Source);
container.register('model:user', User);
container.register('model:post', Post);
// injecting one fullName on another fullName
// eg. each user model gets a post model
container.injection('model:user', 'post', 'model:post');
// injecting one fullName on another type
container.injection('model', 'source', 'source:main');
var user = container.lookup('model:user');
var post = container.lookup('model:post');
user.source instanceof Source; //=> true
post.source instanceof Source; //=> true
user.post instanceof Post; //=> true
// and both models share the same source
user.source === post.source; //=> true
```
@method injection
@param {String} factoryName
@param {String} property
@param {String} injectionName
*/
injection: function(fullName, property, injectionName) {
if (this.parent) { illegalChildOperation('injection'); }
validateFullName(injectionName);
var normalizedInjectionName = this.normalize(injectionName);
if (fullName.indexOf(':') === -1) {
return this.typeInjection(fullName, property, normalizedInjectionName);
}
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
var normalizedName = this.normalize(fullName);
if (this.cache[normalizedName]) {
throw new Error("Attempted to register an injection for a type that has already been looked up. ('" + normalizedName + "', '" + property + "', '" + injectionName + "')");
}
addInjection(this.injections, normalizedName, property, normalizedInjectionName);
},
/**
Used only via `factoryInjection`.
Provides a specialized form of injection, specifically enabling
all factory of one type to be injected with a reference to another
object.
For example, provided each factory of type `model` needed a `store`.
one would do the following:
```javascript
var container = new Container();
container.register('store:main', SomeStore);
container.factoryTypeInjection('model', 'store', 'store:main');
var store = container.lookup('store:main');
var UserFactory = container.lookupFactory('model:user');
UserFactory.store instanceof SomeStore; //=> true
```
@private
@method factoryTypeInjection
@param {String} type
@param {String} property
@param {String} fullName
*/
factoryTypeInjection: function(type, property, fullName) {
if (this.parent) { illegalChildOperation('factoryTypeInjection'); }
addTypeInjection(this.factoryTypeInjections, type, property, this.normalize(fullName));
},
/**
Defines factory injection rules.
Similar to regular injection rules, but are run against factories, via
`Container#lookupFactory`.
These rules are used to inject objects onto factories when they
are looked up.
Two forms of injections are possible:
* Injecting one fullName on another fullName
* Injecting one fullName on a type
Example:
```javascript
var container = new Container();
container.register('store:main', Store);
container.register('store:secondary', OtherStore);
container.register('model:user', User);
container.register('model:post', Post);
// injecting one fullName on another type
container.factoryInjection('model', 'store', 'store:main');
// injecting one fullName on another fullName
container.factoryInjection('model:post', 'secondaryStore', 'store:secondary');
var UserFactory = container.lookupFactory('model:user');
var PostFactory = container.lookupFactory('model:post');
var store = container.lookup('store:main');
UserFactory.store instanceof Store; //=> true
UserFactory.secondaryStore instanceof OtherStore; //=> false
PostFactory.store instanceof Store; //=> true
PostFactory.secondaryStore instanceof OtherStore; //=> true
// and both models share the same source instance
UserFactory.store === PostFactory.store; //=> true
```
@method factoryInjection
@param {String} factoryName
@param {String} property
@param {String} injectionName
*/
factoryInjection: function(fullName, property, injectionName) {
if (this.parent) { illegalChildOperation('injection'); }
var normalizedName = this.normalize(fullName);
var normalizedInjectionName = this.normalize(injectionName);
validateFullName(injectionName);
if (fullName.indexOf(':') === -1) {
return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName);
}
Ember.assert('fullName must be a proper full name', validateFullName(fullName));
if (this.factoryCache[normalizedName]) {
throw new Error('Attempted to register a factoryInjection for a type that has already ' +
'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')');
}
addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName);
},
/**
A depth first traversal, destroying the container, its descendant containers and all
their managed objects.
@method destroy
*/
destroy: function() {
for (var i = 0, length = this.children.length; i < length; i++) {
this.children[i].destroy();
}
this.children = [];
eachDestroyable(this, function(item) {
item.destroy();
});
this.parent = undefined;
this.isDestroyed = true;
},
/**
@method reset
*/
reset: function() {
for (var i = 0, length = this.children.length; i < length; i++) {
resetCache(this.children[i]);
}
resetCache(this);
}
};
function resolve(container, normalizedName) {
var cached = container.resolveCache[normalizedName];
if (cached) { return cached; }
var resolved = container.resolver(normalizedName) || container.registry[normalizedName];
container.resolveCache[normalizedName] = resolved;
return resolved;
}
function has(container, fullName){
if (container.cache[fullName]) {
return true;
}
return !!container.resolve(fullName);
}
function lookup(container, fullName, options) {
options = options || {};
if (container.cache[fullName] && options.singleton !== false) {
return container.cache[fullName];
}
var value = instantiate(container, fullName);
if (value === undefined) { return; }
if (isSingleton(container, fullName) && options.singleton !== false) {
container.cache[fullName] = value;
}
return value;
}
function illegalChildOperation(operation) {
throw new Error(operation + ' is not currently supported on child containers');
}
function isSingleton(container, fullName) {
var singleton = option(container, fullName, 'singleton');
return singleton !== false;
}
function buildInjections(container, injections) {
var hash = {};
if (!injections) { return hash; }
var injection, injectable;
for (var i = 0, length = injections.length; i < length; i++) {
injection = injections[i];
injectable = lookup(container, injection.fullName);
if (injectable !== undefined) {
hash[injection.property] = injectable;
} else {
throw new Error('Attempting to inject an unknown injection: `' + injection.fullName + '`');
}
}
return hash;
}
function option(container, fullName, optionName) {
var options = container._options[fullName];
if (options && options[optionName] !== undefined) {
return options[optionName];
}
var type = fullName.split(':')[0];
options = container._typeOptions[type];
if (options) {
return options[optionName];
}
}
function factoryFor(container, fullName) {
var cache = container.factoryCache;
if (cache[fullName]) {
return cache[fullName];
}
var factory = container.resolve(fullName);
if (factory === undefined) { return; }
var type = fullName.split(':')[0];
if (!factory || typeof factory.extend !== 'function' || (!Ember.MODEL_FACTORY_INJECTIONS && type === 'model')) {
// TODO: think about a 'safe' merge style extension
// for now just fallback to create time injection
cache[fullName] = factory;
return factory;
} else {
var injections = injectionsFor(container, fullName);
var factoryInjections = factoryInjectionsFor(container, fullName);
factoryInjections._toString = container.makeToString(factory, fullName);
var injectedFactory = factory.extend(injections);
injectedFactory.reopenClass(factoryInjections);
cache[fullName] = injectedFactory;
return injectedFactory;
}
}
function injectionsFor(container, fullName) {
var splitName = fullName.split(':');
var type = splitName[0];
var injections = [];
injections = injections.concat(container.typeInjections[type] || []);
injections = injections.concat(container.injections[fullName] || []);
injections = buildInjections(container, injections);
injections._debugContainerKey = fullName;
injections.container = container;
return injections;
}
function factoryInjectionsFor(container, fullName) {
var splitName = fullName.split(':');
var type = splitName[0];
var factoryInjections = [];
factoryInjections = factoryInjections.concat(container.factoryTypeInjections[type] || []);
factoryInjections = factoryInjections.concat(container.factoryInjections[fullName] || []);
factoryInjections = buildInjections(container, factoryInjections);
factoryInjections._debugContainerKey = fullName;
return factoryInjections;
}
function instantiate(container, fullName) {
var factory = factoryFor(container, fullName);
if (option(container, fullName, 'instantiate') === false) {
return factory;
}
if (factory) {
if (typeof factory.create !== 'function') {
throw new Error('Failed to create an instance of \'' + fullName + '\'. ' +
'Most likely an improperly defined class or an invalid module export.');
}
if (typeof factory.extend === 'function') {
// assume the factory was extendable and is already injected
return factory.create();
} else {
// assume the factory was extendable
// to create time injections
// TODO: support new'ing for instantiation and merge injections for pure JS Functions
return factory.create(injectionsFor(container, fullName));
}
}
}
function eachDestroyable(container, callback) {
var cache = container.cache;
var keys = emberKeys(cache);
var key, value;
for (var i = 0, l = keys.length; i < l; i++) {
key = keys[i];
value = cache[key];
if (option(container, key, 'instantiate') !== false) {
callback(value);
}
}
}
function resetCache(container) {
eachDestroyable(container, function(value) {
value.destroy();
});
container.cache.dict = dictionary(null);
}
function addTypeInjection(rules, type, property, fullName) {
var injections = rules[type];
if (!injections) {
injections = [];
rules[type] = injections;
}
injections.push({
property: property,
fullName: fullName
});
}
var VALID_FULL_NAME_REGEXP = /^[^:]+.+:[^:]+$/;
function validateFullName(fullName) {
if (!VALID_FULL_NAME_REGEXP.test(fullName)) {
throw new TypeError('Invalid Fullname, expected: `type:name` got: ' + fullName);
}
return true;
}
function addInjection(rules, factoryName, property, injectionName) {
var injections = rules[factoryName] = rules[factoryName] || [];
injections.push({
property: property,
fullName: injectionName
});
}
export default Container;