UNPKG

2.14 kBPlain TextView Raw
1declare global {
2 var requirejs: {
3 _eak_seen: Object;
4 };
5}
6
7import Engine from '@ember/engine';
8import require from 'require';
9
10function resolveInitializer(moduleName: string) {
11 var module = require(moduleName, null, null, true);
12 if (!module) {
13 throw new Error(moduleName + ' must export an initializer.');
14 }
15 var initializer = module['default'];
16 if (!initializer) {
17 throw new Error(moduleName + ' must have a default export');
18 }
19 if (!initializer.name) {
20 initializer.name = moduleName.slice(moduleName.lastIndexOf('/') + 1);
21 }
22 return initializer;
23}
24
25function registerInitializers(app: typeof Engine, moduleNames: string[]) {
26 for (var i = 0; i < moduleNames.length; i++) {
27 app.initializer(resolveInitializer(moduleNames[i]));
28 }
29}
30
31function registerInstanceInitializers(app: typeof Engine, moduleNames: string[]) {
32 for (var i = 0; i < moduleNames.length; i++) {
33 app.instanceInitializer(resolveInitializer(moduleNames[i]));
34 }
35}
36
37function _endsWith(str: string, suffix: string): boolean {
38 return str.indexOf(suffix, str.length - suffix.length) !== -1;
39}
40
41/**
42 * Configure your application as it boots
43 */
44export default function loadInitializers(app: typeof Engine, prefix: string): void {
45 var initializerPrefix = prefix + '/initializers/';
46 var instanceInitializerPrefix = prefix + '/instance-initializers/';
47 var initializers = [];
48 var instanceInitializers = [];
49 // this is 2 pass because generally the first pass is the problem
50 // and is reduced, and resolveInitializer has potential to deopt
51 var moduleNames = Object.keys(requirejs._eak_seen);
52 for (var i = 0; i < moduleNames.length; i++) {
53 var moduleName = moduleNames[i];
54 if (moduleName.lastIndexOf(initializerPrefix, 0) === 0) {
55 if (!_endsWith(moduleName, '-test')) {
56 initializers.push(moduleName);
57 }
58 } else if (moduleName.lastIndexOf(instanceInitializerPrefix, 0) === 0) {
59 if (!_endsWith(moduleName, '-test')) {
60 instanceInitializers.push(moduleName);
61 }
62 }
63 }
64 registerInitializers(app, initializers);
65 registerInstanceInitializers(app, instanceInitializers);
66}