-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModuleManager.js
337 lines (302 loc) · 12.4 KB
/
ModuleManager.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
'use strict';
/**
* KLF Require Core
* Written by Kristian Oye
* Date: August 13, 2024
*
* @version 1.0.0
*/
/// <reference path="index.d.ts" />
const PathUtil = require('./util/PathUtil'),
{ DetailLevelString, LogDetailLevel } = require('./Constants'),
{ EventEmitter } = require('events'),
AstBuilder = require('./ast/AstBuilder'),
GeneratorBase = require('./ast/generators/GeneratorBase'),
ExtensionLoader = require('./loader/ExtensionLoader'),
path = require('path'),
fs = require('fs');
const ConfigUtil = require('./util/ConfigUtil');
const ObjectUtil = require('./util/ObjectUtil');
/**
* @implements {KLF}
*/
class ModuleManager extends EventEmitter {
/**
* Construct an extension-specific loader object
* @param {KLF.IModuleManager} settings Settings to initialize this loader
*/
constructor(settings = {}) {
super();
/** @type {KLF.LogDetailLevel} */
this.debug = typeof settings.debug === 'number' ? settings.debug : LogDetailLevel.tryParse(settings.debug || activeConfig.debug, LogDetailLevel.Error);
this.settings = settings;
this.components = {
AstBuilder,
GeneratorBase,
ExtensionLoader,
...this.builderTypes,
...this.generatorTypes,
...settings.loaders
};
}
/**
*
* @param {Partial<KLF>} config
*/
applyConfigChange(config) {
try {
this.emit('configChangeStart', config);
this.settings = ConfigUtil.mergeConfigs({}, this.settings, config);
}
catch (err) {
this.log(`Failed to update active configuration; Error = ${err}`, LogDetailLevel.Error);
}
}
bootstrap() {
for (const [loaderId, loaderType] of Object.entries(this.loaders.instanceTypes)) {
this.log(`Creating runtime instance of ${loaderId}`, LogDetailLevel.Debug);
}
}
get builderTypes() {
const result = {};
for (const [id, entry] of Object.entries(this.settings.ast.builders)) {
result[id] = entry.type;
}
return result;
}
get generatorTypes() {
const result = {};
for (const [id, entry] of Object.entries(this.settings.ast.generators)) {
result[id] = entry.type;
}
return result;
}
get loaders() {
const result = {};
for (const [id, entry] of Object.entries(this.settings.loaders)) {
result[id] = entry.type;
}
return result;
}
/**
* Configure an extension
* @param {KLF.IExtensionLoader} loader The extension configuration
* @returns
*/
configureLoader(loader) {
if (loader.extensions.length > 0) {
for (const ext of loader.extensions) {
const
key = ext.charAt(0) === '.' ? ext : '.' + ext,
originalRequire = Module._extensions[key];
if (typeof originalRequire === 'undefined') {
this.log(`This NodeJS runtime does not recognize extension ${key}, but we will try and make it understand`, LogDetailLevel.Debug);
}
loader.addDefaultLoader(key, originalRequire);
/**
* Load a module
* @param {Module} module
* @param {string} filename The module file to load
*/
Module._extensions[key] = (module, filename) => {
/** send the request back to the built-in handler */
const defer = (module, filename, message, detailLevel, arg = {}) => {
this.log(message, detailLevel, arg);
this.emit('deferred', { module, filename, message, ...arg });
return originalRequire(module, filename);
};
try {
if (loader.enabled) {
loader.log(`Starting load process for ${filename} using ${loader.name}`, LogDetailLevel.Verbose);
if (!loader.require(module, filename)) {
if (typeof originalRequire === 'function')
defer(module, filename, `Loader ${loader.name} is deferring ${filename} to built-in require()`, LogDetailLevel.Debug, { module, filename, loader });
else {
this.log(`Loader ${this.name} was unable to load ${filename} and there is no fallback for ${key}!!!`, LogDetailLevel.Error, { module, filename, loader });
this.emit('failure', { module, filename, message: 'No reason given by loader' });
return false;
}
}
else /* we did our job */
return true;
}
defer(module, filename, `Skipping load process for ${filename} using ${loader.name} [loader disabled]`, LogDetailLevel.Verbose);
}
catch (error) {
defer(module, filename, `Loader ${loader.name} failed to load ${filename}: Error: ${error}`, LogDetailLevel.Error, { filename, error, module });
}
};
}
}
else {
this.log(`Loader ${loader.name} does not provide any extensions and will do nothing`, LogDetailLevel.Warning, { loader });
}
}
/**
* Get the default/startup configuration
* @returns {Partial<KLF.IModuleManager>}
*/
static getDefaultConfig() {
/** @type {Partial<KLF.IModuleManager>} */
const config = {
debug: LogDetailLevel.None,
enabled: false,
exclude: [
...PathUtil.locateNodeModulesDirectory()
],
include: [
],
ast: {},
loaders: {}
};
AstBuilder.enumerateBuiltinTypes(config);
ExtensionLoader.enumerateBuiltinTypes(config);
return config;
}
/**
* Check to see if the given type might be useful in our system
* @param {any} type The type to inspect
* @returns True if the component is a known subtype
*/
isUsefulComponent(type) {
if (ObjectUtil.isClass(type))
return type.prototype instanceof AstBuilder
|| type.prototype instanceof this.settings.ast.baseGeneratorType
|| type.prototype instanceof ExtensionLoader;
else
return false;
}
/**
* Record a message in the log
* @param {string} message The message to record
* @param {KLF.LogDetailLevel} detailLevel The sensitivity of the message
* @param {boolean} ignoreConfig If true, then this message is sent to the console even if it exceeds our logging threshold
* @param {object} args Any additional arguments to pass
*/
log(message, detailLevel, ignoreConfig = false, args = undefined) {
if (typeof ignoreConfig === 'object') {
if (typeof args !== 'object')
args = ignoreConfig;
ignoreConfig = false;
}
const debugLevel = DetailLevelString[detailLevel];
const output = `+[${debugLevel}]: ${message}`;
/** @type {KLF.LogMessageEventArgs} */
const logArgs = { detailLevel, message, args, timestamp: Date.now(), ...args };
if (this.debug >= detailLevel || ignoreConfig) {
console.log(output);
}
if (typeof this.onLogMessage === 'function') {
this.onLogMessage.call(extConfig, logArgs);
}
this.emit('logging', logArgs);
}
/**
* Run module code through the pipeline and return the finished source to Node
* @param {string} filename The filename of the module being loaded
* @param {string} source The source text read in from the filename
* @returns {string | false} Returns the modified source or false if the parsing failed
*/
runPipeline(filename, source) {
}
}
const manager = new ModuleManager(ModuleManager.getDefaultConfig());
class ModuleManagerSafeWrapper extends EventEmitter {
constructor() {
super();
}
get enabled() { return manager.settings.enabled; }
set enabled(flag) { manager.settings.enabled = flag === true; }
/**
* Hook for extending component types
* @param {ExtendTypesCallback} callback The callback executed to extend types
* @returns
*/
extendTypes(callback) {
const newType = callback({ ...manager.components });
if (typeof newType === 'object') {
for (const [name, typeDef] of Object.entries(newType)) {
this.registerComponent(typeDef, name);
}
}
else if (ObjectUtil.isClass(newType))
this.registerComponent(newType);
return this;
}
log(...args) {
return manager.log(...args);
}
on(...args) {
this.on(...args);
}
/**
* Register a new component
* @param {KLF.IComponent} type The type to register
* @param {string?} altName An alternate name for the type
* @returns Reference to this object
*/
registerComponent(type, altName) {
if (manager.isUsefulComponent(type)) {
const parentTypeName = ObjectUtil.parentClassName(type);
const altTypeName = typeof altName === 'string' && altName.trim();
/** @type {KLF.IComponentEntry} */
const existingParentDef = parentTypeName in manager.components && manager.components[parentTypeName];
const existingNamedDef = type.name in manager.components && manager.components[type.name];
/** @type {KLF.IComponentEntry} */
const newEntry = {
type,
name: type.name,
config: { ...(typeof type.getDefaultConfig === 'function' && type.getDefaultConfig(manager.settings) || {}) }
};
if (false === type.name in manager.components) {
manager.components[type.name] = type;
}
if (existingParentDef) {
manager.components[parentTypeName] = type;
}
if (altTypeName && altTypeName !== type.name)
manager.components[altTypeName] = type;
const updateTypeInfo = (targetConfig, newEntry) => {
if (existingParentDef) {
const existingConfig = targetConfig[parentTypeName] || {};
if (false === type.prototype instanceof existingParentDef)
this.log(`registerComponent: Cannot redefine ${type.name} since it does not inherit from the existing type`,
LogDetailLevel.Warning,
{ existingType: existingParentDef.type, newType: type });
else if (existingNamedDef && false === type.prototype instanceof existingNamedDef)
this.log(`registerComponent: Cannot redefine ${type.name} since it does not inherit from the existing type`,
LogDetailLevel.Warning,
{ existingType: existingParentDef.type, newType: type });
else
targetConfig[parentTypeName] = { ...existingConfig, ...newEntry };
}
else
targetConfig[type.name] = newEntry;
};
if (type.prototype instanceof GeneratorBase)
updateTypeInfo(manager.settings.ast.generators, newEntry);
else if (type.prototype instanceof AstBuilder)
updateTypeInfo(manager.settings.ast.builders, newEntry);
else if (type.prototype instanceof ExtensionLoader)
updateTypeInfo(manager.loaders, newEntry);
return this;
}
}
/**
* Allow the user to update the configuration
* @param {KLF.ExtendConfigCallback} callback The changes to apply to the config
* @returns
*/
updateConfig(callback) {
const newConfig = callback(manager.settings, { LogDetailLevel });
if (typeof newConfig === 'object') {
manager.applyConfigChange(newConfig);
}
}
}
const wrapper = new ModuleManagerSafeWrapper();
Object.seal(wrapper);
module.exports = {
ModuleManager: manager,
ModuleManagerWrapper: wrapper
};