-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.ts
526 lines (423 loc) · 15.6 KB
/
index.ts
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
export { getEngineParent, setEngineParent } from './parent';
import { canInvoke } from '@ember/-internals/utils';
import Controller from '@ember/controller';
import Namespace from '@ember/application/namespace';
import { Registry } from '@ember/-internals/container';
import type { ResolverClass } from '@ember/-internals/container';
import DAG from 'dag-map';
import { assert } from '@ember/debug';
import ContainerDebugAdapter from '@ember/debug/container-debug-adapter';
import { get, set } from '@ember/object';
import type { EngineInstanceOptions } from '@ember/engine/instance';
import EngineInstance from '@ember/engine/instance';
import { RoutingService } from '@ember/routing/-internals';
import { ComponentLookup } from '@ember/-internals/views';
import { setupEngineRegistry } from '@ember/-internals/glimmer';
import { RegistryProxyMixin } from '@ember/-internals/runtime';
function props(obj: object) {
let properties = [];
for (let key in obj) {
properties.push(key);
}
return properties;
}
export interface Initializer<T> {
name: string;
initialize: (target: T) => void;
before?: string | string[];
after?: string | string[];
}
/**
@module @ember/engine
*/
/**
The `Engine` class contains core functionality for both applications and
engines.
Each engine manages a registry that's used for dependency injection and
exposed through `RegistryProxy`.
Engines also manage initializers and instance initializers.
Engines can spawn `EngineInstance` instances via `buildInstance()`.
@class Engine
@extends Ember.Namespace
@uses RegistryProxyMixin
@public
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Engine extends RegistryProxyMixin {}
class Engine extends Namespace.extend(RegistryProxyMixin) {
static initializers: Record<string, Initializer<Engine>> = Object.create(null);
static instanceInitializers: Record<string, Initializer<EngineInstance>> = Object.create(null);
/**
The goal of initializers should be to register dependencies and injections.
This phase runs once. Because these initializers may load code, they are
allowed to defer application readiness and advance it. If you need to access
the container or store you should use an InstanceInitializer that will be run
after all initializers and therefore after all code is loaded and the app is
ready.
Initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize`, all others are optional.
* `name` allows you to specify under which name the initializer is registered.
This must be a unique name, as trying to register two initializers with the
same name will result in an error.
```app/initializer/named-initializer.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Running namedInitializer!');
}
export default {
name: 'named-initializer',
initialize
};
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
An example of ordering initializers, we create an initializer named `first`:
```app/initializer/first.js
import { debug } from '@ember/debug';
export function initialize() {
debug('First initializer!');
}
export default {
name: 'first',
initialize
};
```
```bash
// DEBUG: First initializer!
```
We add another initializer named `second`, specifying that it should run
after the initializer named `first`:
```app/initializer/second.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Second initializer!');
}
export default {
name: 'second',
after: 'first',
initialize
};
```
```
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Afterwards we add a further initializer named `pre`, this time specifying
that it should run before the initializer named `first`:
```app/initializer/pre.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Pre initializer!');
}
export default {
name: 'pre',
before: 'first',
initialize
};
```
```bash
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Finally we add an initializer named `post`, specifying it should run after
both the `first` and the `second` initializers:
```app/initializer/post.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Post initializer!');
}
export default {
name: 'post',
after: ['first', 'second'],
initialize
};
```
```bash
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
// DEBUG: Post initializer!
```
* `initialize` is a callback function that receives one argument,
`application`, on which you can operate.
Example of using `application` to register an adapter:
```app/initializer/api-adapter.js
import ApiAdapter from '../utils/api-adapter';
export function initialize(application) {
application.register('api-adapter:main', ApiAdapter);
}
export default {
name: 'post',
after: ['first', 'second'],
initialize
};
```
@method initializer
@param initializer {Object}
@public
*/
static initializer = buildInitializerMethod('initializers', 'initializer');
/**
Instance initializers run after all initializers have run. Because
instance initializers run after the app is fully set up. We have access
to the store, container, and other items. However, these initializers run
after code has loaded and are not allowed to defer readiness.
Instance initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize`, all others are optional.
* `name` allows you to specify under which name the instanceInitializer is
registered. This must be a unique name, as trying to register two
instanceInitializer with the same name will result in an error.
```app/initializer/named-instance-initializer.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Running named-instance-initializer!');
}
export default {
name: 'named-instance-initializer',
initialize
};
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
* See Application.initializer for discussion on the usage of before
and after.
Example instanceInitializer to preload data into the store.
```app/initializer/preload-data.js
export function initialize(application) {
var userConfig, userConfigEncoded, store;
// We have a HTML escaped JSON representation of the user's basic
// configuration generated server side and stored in the DOM of the main
// index.html file. This allows the app to have access to a set of data
// without making any additional remote calls. Good for basic data that is
// needed for immediate rendering of the page. Keep in mind, this data,
// like all local models and data can be manipulated by the user, so it
// should not be relied upon for security or authorization.
// Grab the encoded data from the meta tag
userConfigEncoded = document.querySelector('head meta[name=app-user-config]').attr('content');
// Unescape the text, then parse the resulting JSON into a real object
userConfig = JSON.parse(unescape(userConfigEncoded));
// Lookup the store
store = application.lookup('service:store');
// Push the encoded JSON into the store
store.pushPayload(userConfig);
}
export default {
name: 'named-instance-initializer',
initialize
};
```
@method instanceInitializer
@param instanceInitializer
@public
*/
static instanceInitializer = buildInitializerMethod(
'instanceInitializers',
'instance initializer'
);
/**
This creates a registry with the default Ember naming conventions.
It also configures the registry:
* registered views are created every time they are looked up (they are
not singletons)
* registered templates are not factories; the registered value is
returned directly.
* the router receives the application as its `namespace` property
* all controllers receive the router as their `target` and `controllers`
properties
* all controllers receive the application as their `namespace` property
* the application view receives the application controller as its
`controller` property
* the application view receives the application template as its
`defaultTemplate` property
@method buildRegistry
@static
@param {Application} namespace the application for which to
build the registry
@return {Ember.Registry} the built registry
@private
*/
static buildRegistry(namespace: Engine) {
let registry = new Registry({
resolver: resolverFor(namespace),
});
registry.set = set;
registry.register('application:main', namespace, { instantiate: false });
commonSetupRegistry(registry);
setupEngineRegistry(registry);
return registry;
}
/**
Set this to provide an alternate class to `DefaultResolver`
@property resolver
@public
*/
declare Resolver: ResolverClass;
init(properties: object | undefined) {
super.init(properties);
this.buildRegistry();
}
/**
A private flag indicating whether an engine's initializers have run yet.
@private
@property _initializersRan
*/
_initializersRan = false;
/**
Ensure that initializers are run once, and only once, per engine.
@private
@method ensureInitializers
*/
ensureInitializers() {
if (!this._initializersRan) {
this.runInitializers();
this._initializersRan = true;
}
}
/**
Create an EngineInstance for this engine.
@public
@method buildInstance
@return {EngineInstance} the engine instance
*/
buildInstance(options: EngineInstanceOptions = {}): EngineInstance {
this.ensureInitializers();
return EngineInstance.create({ ...options, base: this });
}
/**
Build and configure the registry for the current engine.
@private
@method buildRegistry
@return {Ember.Registry} the configured registry
*/
buildRegistry() {
let registry = (this.__registry__ = (this.constructor as typeof Engine).buildRegistry(this));
return registry;
}
/**
@private
@method initializer
*/
initializer(initializer: Initializer<Engine>) {
(this.constructor as typeof Engine).initializer(initializer);
}
/**
@private
@method instanceInitializer
*/
instanceInitializer(initializer: Initializer<EngineInstance>) {
(this.constructor as typeof Engine).instanceInitializer(initializer);
}
/**
@private
@method runInitializers
*/
runInitializers() {
this._runInitializer(
'initializers',
(name: string, initializer: Initializer<this> | undefined) => {
assert(`No application initializer named '${name}'`, initializer);
initializer.initialize(this);
}
);
}
/**
@private
@since 1.12.0
@method runInstanceInitializers
*/
runInstanceInitializers<T extends EngineInstance>(instance: T) {
this._runInitializer(
'instanceInitializers',
(name: string, initializer: Initializer<T> | undefined) => {
assert(`No instance initializer named '${name}'`, initializer);
initializer.initialize(instance);
}
);
}
_runInitializer<
B extends 'initializers' | 'instanceInitializers',
T extends B extends 'initializers' ? Engine : EngineInstance
>(bucketName: B, cb: (name: string, initializer: Initializer<T> | undefined) => void) {
let initializersByName = get(this.constructor, bucketName) as Record<string, Initializer<T>>;
let initializers = props(initializersByName);
let graph = new DAG<Initializer<T>>();
let initializer;
for (let name of initializers) {
initializer = initializersByName[name];
assert(`missing ${bucketName}: ${name}`, initializer);
graph.add(initializer.name, initializer, initializer.before, initializer.after);
}
graph.topsort(cb);
}
}
/**
This function defines the default lookup rules for container lookups:
* templates are looked up on `Ember.TEMPLATES`
* other names are looked up on the application after classifying the name.
For example, `controller:post` looks up `App.PostController` by default.
* if the default lookup fails, look for registered classes on the container
This allows the application to register default injections in the container
that could be overridden by the normal naming convention.
@private
@method resolverFor
@param {Ember.Enginer} namespace the namespace to look for classes
@return {*} the resolved value for a given lookup
*/
function resolverFor(namespace: Engine) {
let ResolverClass = namespace.Resolver;
let props = { namespace };
return ResolverClass.create(props);
}
/** @internal */
export function buildInitializerMethod<
B extends 'initializers' | 'instanceInitializers',
T extends B extends 'initializers' ? Engine : EngineInstance
>(bucketName: B, humanName: string) {
return function (this: typeof Engine, initializer: Initializer<T>) {
// If this is the first initializer being added to a subclass, we are going to reopen the class
// to make sure we have a new `initializers` object, which extends from the parent class' using
// prototypal inheritance. Without this, attempting to add initializers to the subclass would
// pollute the parent class as well as other subclasses.
// SAFETY: The superclass may be an Engine, we don't call unless we confirmed it was ok.
let superclass = this.superclass as typeof Engine;
if (superclass[bucketName] !== undefined && superclass[bucketName] === this[bucketName]) {
let attrs = {
[bucketName]: Object.create(this[bucketName]),
};
this.reopenClass(attrs);
}
assert(
`The ${humanName} '${initializer.name}' has already been registered`,
!this[bucketName][initializer.name]
);
assert(
`An ${humanName} cannot be registered without an initialize function`,
canInvoke(initializer, 'initialize')
);
assert(
`An ${humanName} cannot be registered without a name property`,
initializer.name !== undefined
);
let initializers = (this as typeof Engine)[bucketName] as Record<string, Initializer<T>>;
initializers[initializer.name] = initializer;
};
}
function commonSetupRegistry(registry: Registry) {
registry.optionsForType('component', { singleton: false });
registry.optionsForType('view', { singleton: false });
registry.register('controller:basic', Controller, { instantiate: false });
// Register the routing service...
registry.register('service:-routing', RoutingService);
// DEBUGGING
registry.register('resolver-for-debugging:main', registry.resolver!, {
instantiate: false,
});
registry.register('container-debug-adapter:main', ContainerDebugAdapter);
registry.register('component-lookup:main', ComponentLookup);
}
export default Engine;