/
framework-configuration.js
350 lines (296 loc) · 11.1 KB
/
framework-configuration.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
/*eslint no-unused-vars:0, no-cond-assign:0*/
import * as TheLogManager from 'aurelia-logging';
import {ViewEngine} from 'aurelia-templating';
import {join} from 'aurelia-path';
import {Container} from 'aurelia-dependency-injection';
const logger = TheLogManager.getLogger('aurelia');
function runTasks(config, tasks) {
let current;
let next = () => {
if (current = tasks.shift()) {
return Promise.resolve(current(config)).then(next);
}
return Promise.resolve();
};
return next();
}
function loadPlugin(config, loader, info) {
logger.debug(`Loading plugin ${info.moduleId}.`);
config.resourcesRelativeTo = info.resourcesRelativeTo;
let id = info.moduleId; // General plugins installed/configured by the end user.
if(info.resourcesRelativeTo.length > 1 ) { // In case of bootstrapper installed plugins like `aurelia-templating-resources` or `aurelia-history-browser`.
return loader.normalize(info.moduleId, info.resourcesRelativeTo[1])
.then(id=> {
return _loadPlugin(id);
});
}
return _loadPlugin(id);
function _loadPlugin(id) {
return loader.loadModule(id).then(m => {
if ('configure' in m) {
return Promise.resolve(m.configure(config, info.config || {})).then(() => {
config.resourcesRelativeTo = null;
logger.debug(`Configured plugin ${info.moduleId}.`);
});
}
config.resourcesRelativeTo = null;
logger.debug(`Loaded plugin ${info.moduleId}.`);
});
}
}
function loadResources(aurelia, resourcesToLoad, appResources) {
let viewEngine = aurelia.container.get(ViewEngine);
return Promise.all(
Object.keys(resourcesToLoad)
.map(n => _normalize(resourcesToLoad[n])))
.then(loads => {
let names = [], importIds = [];
loads.forEach(l => {
names.push(undefined);
importIds.push(l.importId)
});
return viewEngine.importViewResources(importIds, names, appResources);
});
function _normalize(load) {
return aurelia.loader.normalize(load.moduleId, load.relativeTo)
.then(normalized => {
return {
name : load.moduleId,
importId : normalized
};
})
}
}
function assertProcessed(plugins) {
if (plugins.processed) {
throw new Error('This config instance has already been applied. To load more plugins or global resources, create a new FrameworkConfiguration instance.');
}
}
/**
* Manages configuring the aurelia framework instance.
*/
export class FrameworkConfiguration {
/**
* The root DI container used by the application.
*/
container: Container;
/**
* The aurelia instance.
*/
aurelia: Aurelia;
/**
* Creates an instance of FrameworkConfiguration.
* @param aurelia An instance of Aurelia.
*/
constructor(aurelia: Aurelia) {
this.aurelia = aurelia;
this.container = aurelia.container;
this.info = [];
this.processed = false;
this.preTasks = [];
this.postTasks = [];
this.resourcesToLoad = {};
this.preTask(() => aurelia.loader.normalize('aurelia-bootstrapper').then(name => this.bootstrapperName = name));
this.postTask(() => loadResources(aurelia, this.resourcesToLoad, aurelia.resources));
}
/**
* Adds an existing object to the framework's dependency injection container.
* @param type The object type of the dependency that the framework will inject.
* @param instance The existing instance of the dependency that the framework will inject.
* @return Returns the current FrameworkConfiguration instance.
*/
instance(type: any, instance: any): FrameworkConfiguration {
this.container.registerInstance(type, instance);
return this;
}
/**
* Adds a singleton to the framework's dependency injection container.
* @param type The object type of the dependency that the framework will inject.
* @param implementation The constructor function of the dependency that the framework will inject.
* @return Returns the current FrameworkConfiguration instance.
*/
singleton(type: any, implementation?: Function): FrameworkConfiguration {
this.container.registerSingleton(type, implementation);
return this;
}
/**
* Adds a transient to the framework's dependency injection container.
* @param type The object type of the dependency that the framework will inject.
* @param implementation The constructor function of the dependency that the framework will inject.
* @return Returns the current FrameworkConfiguration instance.
*/
transient(type: any, implementation?: Function): FrameworkConfiguration {
this.container.registerTransient(type, implementation);
return this;
}
/**
* Adds an async function that runs before the plugins are run.
* @param task The function to run before start.
* @return Returns the current FrameworkConfiguration instance.
*/
preTask(task: Function): FrameworkConfiguration {
assertProcessed(this);
this.preTasks.push(task);
return this;
}
/**
* Adds an async function that runs after the plugins are run.
* @param task The function to run after start.
* @return Returns the current FrameworkConfiguration instance.
*/
postTask(task: Function): FrameworkConfiguration {
assertProcessed(this);
this.postTasks.push(task);
return this;
}
/**
* Configures an internal feature plugin before Aurelia starts.
* @param plugin The folder for the internal plugin to configure (expects an index.js in that folder).
* @param config The configuration for the specified plugin.
* @return Returns the current FrameworkConfiguration instance.
*/
feature(plugin: string, config?: any): FrameworkConfiguration {
return this.plugin({ moduleId: plugin + '/index', resourcesRelativeTo: [plugin, ''], config: config || {} });
}
/**
* Adds globally available view resources to be imported into the Aurelia framework.
* @param resources The relative module id to the resource. (Relative to the plugin's installer.)
* @return Returns the current FrameworkConfiguration instance.
*/
globalResources(resources: string|string[]): FrameworkConfiguration {
assertProcessed(this);
let toAdd = Array.isArray(resources) ? resources : arguments;
let resource;
let path;
let resourcesRelativeTo = this.resourcesRelativeTo || '';
for (let i = 0, ii = toAdd.length; i < ii; ++i) {
resource = toAdd[i];
if (typeof resource !== 'string') {
throw new Error(`Invalid resource path [${resource}]. Resources must be specified as relative module IDs.`);
}
let parent = resourcesRelativeTo[0];
let grandParent = resourcesRelativeTo[1];
let name = resource;
if (resource.startsWith('./') && parent !== '') {
name = parent + resource.substr(1);
}
this.resourcesToLoad[name] = { moduleId: name, relativeTo: grandParent };
}
return this;
}
/**
* Renames a global resource that was imported.
* @param resourcePath The path to the resource.
* @param newName The new name.
* @return Returns the current FrameworkConfiguration instance.
*/
globalName(resourcePath: string, newName: string): FrameworkConfiguration {
assertProcessed(this);
this.resourcesToLoad[resourcePath] = { moduleId: newName, relativeTo: '' };
return this;
}
/**
* Configures an external, 3rd party plugin before Aurelia starts.
* @param plugin The ID of the 3rd party plugin to configure.
* @param config The configuration for the specified plugin.
* @return Returns the current FrameworkConfiguration instance.
*/
plugin(plugin: string, config?: any): FrameworkConfiguration {
assertProcessed(this);
if (typeof (plugin) === 'string') {
return this.plugin({ moduleId: plugin, resourcesRelativeTo: [plugin, ''], config: config || {} });
}
this.info.push(plugin);
return this;
}
_addNormalizedPlugin(name, config) {
let plugin = { moduleId: name, resourcesRelativeTo: [name, ''], config: config || {} };
this.plugin(plugin);
this.preTask(() => {
let relativeTo = [name, this.bootstrapperName];
plugin.moduleId = name;
plugin.resourcesRelativeTo = relativeTo;
return Promise.resolve();
});
return this;
}
/**
* Plugs in the default binding language from aurelia-templating-binding.
* @return Returns the current FrameworkConfiguration instance.
*/
defaultBindingLanguage(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-templating-binding');
}
/**
* Plugs in the router from aurelia-templating-router.
* @return Returns the current FrameworkConfiguration instance.
*/
router(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-templating-router');
}
/**
* Plugs in the default history implementation from aurelia-history-browser.
* @return Returns the current FrameworkConfiguration instance.
*/
history(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-history-browser');
}
/**
* Plugs in the default templating resources (if, repeat, show, compose, etc.) from aurelia-templating-resources.
* @return Returns the current FrameworkConfiguration instance.
*/
defaultResources(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-templating-resources');
}
/**
* Plugs in the event aggregator from aurelia-event-aggregator.
* @return Returns the current FrameworkConfiguration instance.
*/
eventAggregator(): FrameworkConfiguration {
return this._addNormalizedPlugin('aurelia-event-aggregator');
}
/**
* Sets up the Aurelia configuration. This is equivalent to calling `.defaultBindingLanguage().defaultResources().history().router().eventAggregator();`
* @return Returns the current FrameworkConfiguration instance.
*/
standardConfiguration(): FrameworkConfiguration {
return this.defaultBindingLanguage().defaultResources().history().router().eventAggregator();
}
/**
* Plugs in the ConsoleAppender and sets the log level to debug.
* @return {FrameworkConfiguration} Returns the current FrameworkConfiguration instance.
*/
developmentLogging(): FrameworkConfiguration {
this.preTask(() => {
return this.aurelia.loader.normalize('aurelia-logging-console', this.bootstrapperName).then(name => {
return this.aurelia.loader.loadModule(name).then(m => {
TheLogManager.addAppender(new m.ConsoleAppender());
TheLogManager.setLevel(TheLogManager.logLevel.debug);
});
});
});
return this;
}
/**
* Loads and configures the plugins registered with this instance.
* @return Returns a promise which resolves when all plugins are loaded and configured.
*/
apply(): Promise<void> {
if (this.processed) {
return Promise.resolve();
}
return runTasks(this, this.preTasks).then(() => {
let loader = this.aurelia.loader;
let info = this.info;
let current;
let next = () => {
if (current = info.shift()) {
return loadPlugin(this, loader, current).then(next);
}
this.processed = true;
return Promise.resolve();
};
return next().then(() => runTasks(this, this.postTasks));
});
}
}