@ayanaware/bento
Version:
Modular runtime framework designed to solve complex tasks
78 lines • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReferenceManager = void 0;
const errors_1 = require("@ayanaware/errors");
/**
* ReferenceManager associates constructors with a id
*/
class ReferenceManager {
constructor() {
this.references = new Map();
this.rewrites = new Map();
}
/**
* Resolves the name of the given entity.
* If the given entity is already a string, the same string will be returned.
*
* @param reference Reference
* @param error Throw Error on resolve failure
*
* @returns Entity Name or null
*/
resolve(reference, error = false) {
let name;
if (typeof reference === 'string') {
name = reference;
}
else if (reference != null) {
if (typeof reference === 'function' && this.references.has(reference))
name = this.references.get(reference);
else if (typeof reference === 'object' && Object.prototype.hasOwnProperty.call(reference, 'name'))
name = reference.name;
}
// Rewrites
while (this.rewrites.has(name) && name !== this.rewrites.get(name)) {
name = this.rewrites.get(name);
}
if (!name && error)
throw new errors_1.IllegalStateError('Reference is not registered, or does not have a name');
return name;
}
/**
* Registers an entity in a reference map so the type can be used instead of the entity name.
* This only works if the entity has a constructor function.
*
* @param entity The entity to be registered
*/
add(entity, name) {
if (entity.constructor != null && entity.constructor !== Object) {
this.references.set(entity.constructor, name || entity.name);
}
}
/**
* Removes an entity from the reference map.
* This only works if the entity has a constructor function.
*
* @param entity The entity to be removed
*/
remove(entity) {
const name = this.references.get(entity.constructor);
this.references.delete(entity.constructor);
if (this.rewrites.has(name))
this.rewrites.delete(name);
// TODO: Walk rewrites, to prevent a multi rewrite from staying
}
addRewrite(entity, rewrite) {
const name = this.resolve(entity);
if (name)
this.rewrites.set(name, rewrite);
// TODO: Proactivly update old rewrites, ie hello => world, world => new. We should go back and update hello => new
}
removeRewrite(entity) {
const name = this.resolve(entity);
if (name)
this.rewrites.delete(name);
}
}
exports.ReferenceManager = ReferenceManager;
//# sourceMappingURL=ReferenceManager.js.map