##// END OF EJS Templates
corrected code to support ts strict mode...
corrected code to support ts strict mode safe.ts - more tight typings - added notImplemented stub function - added fork funtion - added keys function (like Object.keys but extracts keys type) - added isKeyof typeguard - added 'primitive' union type added EventProvider for the observable

File last commit:

r115:691199f665e0 ioc ts support
r115:691199f665e0 ioc ts support
Show More
Configuration.ts
350 lines | 10.8 KiB | video/mp2t | TypeScriptLexer
/ src / main / ts / di / Configuration.ts
cin
changed the project structure
r49 import {
ServiceRegistration,
TypeRegistration,
FactoryRegistration,
ServiceMap,
isDescriptor,
isDependencyRegistration,
DependencyRegistration,
ValueRegistration,
ActivationType,
isValueRegistration,
isTypeRegistration,
cin
corrected code to support ts strict mode...
r115 isFactoryRegistration,
PartialServiceMap
cin
changed the project structure
r49 } from "./interfaces";
import { argumentNotEmptyString, isPrimitive, isPromise, delegate, argumentOfType, argumentNotNull, get } from "../safe";
import { AggregateDescriptor } from "./AggregateDescriptor";
import { ValueDescriptor } from "./ValueDescriptor";
import { Container } from "./Container";
import { ReferenceDescriptor } from "./ReferenceDescriptor";
import { TypeServiceDescriptor } from "./TypeServiceDescriptor";
import { FactoryServiceDescriptor } from "./FactoryServiceDescriptor";
import { TraceSource } from "../log/TraceSource";
import { ConfigError } from "./ConfigError";
import { Cancellation } from "../Cancellation";
cin
working on support commonjs modules format
r59 import { makeResolver } from "./ResolverHelper";
import { ICancellation } from "../interfaces";
cin
changed the project structure
r49
const trace = TraceSource.get("@implab/core/di/Configuration");
cin
corrected code to support ts strict mode...
r115 async function mapAll(data: any[], map?: (v: any, k: number) => any): Promise<any[]>;
async function mapAll(data: any, map?: (v: any, k: string) => any): Promise<any>;
async function mapAll(data: any, map?: (v: any, k: any) => any): Promise<any> {
cin
changed the project structure
r49 if (data instanceof Array) {
return Promise.all(map ? data.map(map) : data);
} else {
const keys = Object.keys(data);
const o: any = {};
await Promise.all(keys.map(async k => {
const v = map ? map(data[k], k) : data[k];
o[k] = isPromise(v) ? await v : v;
}));
return o;
}
}
cin
working on support commonjs modules format
r59 export type ModuleResolver = (moduleName: string, ct?: ICancellation) => any;
cin
changed the project structure
r49
cin
working on IoC configuration
r114 export class Configuration<S> {
cin
changed the project structure
r49
_hasInnerDescriptors = false;
cin
working on IoC configuration
r114 _container: Container<S>;
cin
changed the project structure
r49
cin
working on IoC configuration
r114 _path: Array<string>;
cin
changed the project structure
r49
cin
working on IoC configuration
r113 _configName: string | undefined;
cin
changed the project structure
r49
cin
working on IoC configuration
r113 _require: ModuleResolver | undefined;
cin
changed the project structure
r49
cin
working on IoC configuration
r114 constructor(container: Container<S>) {
cin
Added safe.delay...
r76 argumentNotNull(container, "container");
cin
changed the project structure
r49 this._container = container;
this._path = [];
}
cin
working on support commonjs modules format
r59 async loadConfiguration(moduleName: string, contextRequire?: any, ct = Cancellation.none) {
cin
working version...
r51 argumentNotEmptyString(moduleName, "moduleName");
cin
working on support commonjs modules format
r59
cin
Added support for commonjs module format, all tests are pass.
r60 trace.log(
"loadConfiguration moduleName={0}, contextRequire={1}",
moduleName,
contextRequire ? typeof (contextRequire) : "<nil>"
);
cin
working on support commonjs modules format
r59
this._configName = moduleName;
cin
working on IoC configuration
r113 const r = await makeResolver(undefined, contextRequire);
cin
working version...
r51
cin
working on support commonjs modules format
r59 const config = await r(moduleName, ct);
await this._applyConfiguration(
config,
cin
fixed "singleton" activation type handling in container configuration...
r65 await makeResolver(moduleName, contextRequire),
cin
working on support commonjs modules format
r59 ct
);
cin
working version...
r51 }
cin
fixed "singleton" activation type handling in container configuration...
r65 async applyConfiguration(data: object, contextRequire?: any, ct = Cancellation.none) {
cin
changed the project structure
r49 argumentNotNull(data, "data");
cin
fixed "singleton" activation type handling in container configuration...
r65 await this._applyConfiguration(data, await makeResolver(void (0), contextRequire), ct);
cin
working on support commonjs modules format
r59 }
async _applyConfiguration(data: object, resolver?: ModuleResolver, ct = Cancellation.none) {
cin
changed the project structure
r49 trace.log("applyConfiguration");
this._configName = "$";
cin
tests moved under src/ folder...
r50 if (resolver)
this._require = resolver;
cin
changed the project structure
r49
cin
corrected code to support ts strict mode...
r115 let services: PartialServiceMap<S>;
cin
changed the project structure
r49
try {
services = await this._visitRegistrations(data, "$");
} catch (e) {
throw this._makeError(e);
}
this._container.register(services);
}
cin
working on IoC configuration
r113 _makeError(inner: any) {
cin
changed the project structure
r49 const e = new ConfigError("Failed to load configuration", inner);
cin
working on IoC configuration
r113 e.configName = this._configName || "<inline>";
cin
changed the project structure
r49 e.path = this._makePath();
return e;
}
_makePath() {
return this._path
.reduce(
(prev, cur) => typeof cur === "number" ?
`${prev}[${cur}]` :
`${prev}.${cur}`
)
.toString();
}
async _resolveType(moduleName: string, localName: string) {
trace.log("resolveType moduleName={0}, localName={1}", moduleName, localName);
try {
const m = await this._loadModule(moduleName);
return localName ? get(localName, m) : m;
} catch (e) {
trace.error("Failed to resolve type moduleName={0}, localName={1}", moduleName, localName);
throw e;
}
}
cin
working on support commonjs modules format
r59 _loadModule(moduleName: string) {
cin
changed the project structure
r49 trace.debug("loadModule {0}", moduleName);
cin
working on IoC configuration
r113 if (!this._require)
throw new Error("Module loader isn't specified");
cin
changed the project structure
r49
cin
working on support commonjs modules format
r59 return this._require(moduleName);
cin
changed the project structure
r49 }
cin
working on IoC configuration
r114 async _visitRegistrations(data: any, name: string) {
cin
changed the project structure
r49 this._enter(name);
if (data.constructor &&
data.constructor.prototype !== Object.prototype)
throw new Error("Configuration must be a simple object");
cin
corrected code to support ts strict mode...
r115 const o: PartialServiceMap<S> = {};
cin
changed the project structure
r49 const keys = Object.keys(data);
const services = await mapAll(data, async (v, k) => {
cin
working on IoC configuration
r114 const d = await this._visit(v, k.toString());
cin
changed the project structure
r49 return isDescriptor(d) ? d : new AggregateDescriptor(d);
cin
corrected code to support ts strict mode...
r115 }) as PartialServiceMap<S>;
cin
changed the project structure
r49
this._leave();
return services;
}
cin
corrected code to support ts strict mode...
r115 _enter(name: string) {
cin
working on IoC configuration
r113 this._path.push(name.toString());
cin
changed the project structure
r49 trace.debug(">{0}", name);
}
_leave() {
const name = this._path.pop();
trace.debug("<{0}", name);
}
cin
corrected code to support ts strict mode...
r115 async _visit<T>(data: T, name: string): Promise<any> {
cin
changed the project structure
r49 if (isPrimitive(data) || isDescriptor(data))
return data;
cin
working on IoC configuration
r114 if (isDependencyRegistration<S>(data)) {
cin
changed the project structure
r49 return this._visitDependencyRegistration(data, name);
} else if (isValueRegistration(data)) {
return this._visitValueRegistration(data, name);
} else if (isTypeRegistration(data)) {
return this._visitTypeRegistration(data, name);
} else if (isFactoryRegistration(data)) {
return this._visitFactoryRegistration(data, name);
} else if (data instanceof Array) {
return this._visitArray(data, name);
}
cin
working on IoC configuration
r114 return this._visitObject(data as T & object, name);
cin
changed the project structure
r49 }
cin
working on IoC configuration
r114 async _visitObject<T extends object>(data: T, name: string) {
cin
changed the project structure
r49 if (data.constructor &&
data.constructor.prototype !== Object.prototype)
return new ValueDescriptor(data);
this._enter(name);
const v = await mapAll(data, delegate(this, "_visit"));
// TODO: handle inline descriptors properly
// const ex = {
// activate(ctx) {
// const value = ctx.activate(this.prop, "prop");
// // some code
// },
// // will be turned to ReferenceDescriptor
// prop: { $dependency: "depName" }
// };
this._leave();
return v;
}
cin
working on IoC configuration
r114 async _visitArray(data: any[], name: string) {
cin
changed the project structure
r49 if (data.constructor &&
data.constructor.prototype !== Array.prototype)
return new ValueDescriptor(data);
this._enter(name);
const v = await mapAll(data, delegate(this, "_visit"));
this._leave();
return v;
}
cin
working on IoC configuration
r114 _makeServiceParams<T, P>(data: ServiceRegistration<T, P, S>) {
cin
changed the project structure
r49 const opts: any = {
owner: this._container
};
if (data.services)
opts.services = this._visitRegistrations(data.services, "services");
if (data.inject) {
cin
fixed "singleton" activation type handling in container configuration...
r65 this._enter("inject");
cin
changed the project structure
r49 opts.inject = mapAll(
data.inject instanceof Array ?
data.inject :
[data.inject],
delegate(this, "_visitObject")
);
this._leave();
}
if ("params" in data)
opts.params = data.params instanceof Array ?
this._visitArray(data.params, "params") :
this._visit(data.params, "params");
if (data.activation) {
if (typeof (data.activation) === "string") {
switch (data.activation.toLowerCase()) {
case "singleton":
opts.activation = ActivationType.Singleton;
break;
case "container":
opts.activation = ActivationType.Container;
break;
case "hierarchy":
opts.activation = ActivationType.Hierarchy;
break;
case "context":
opts.activation = ActivationType.Context;
break;
case "call":
opts.activation = ActivationType.Call;
break;
default:
throw new Error("Unknown activation type: " +
data.activation);
}
} else {
opts.activation = Number(data.activation);
}
}
if (data.cleanup)
opts.cleanup = data.cleanup;
return opts;
}
cin
working on IoC configuration
r114 async _visitValueRegistration<T>(data: ValueRegistration<T>, name: string) {
cin
changed the project structure
r49 this._enter(name);
const d = data.parse ? new AggregateDescriptor(data.$value) : new ValueDescriptor(data.$value);
this._leave();
return d;
}
cin
working on IoC configuration
r114 async _visitDependencyRegistration<K extends keyof S>(data: DependencyRegistration<S, K>, name: string) {
cin
changed the project structure
r49 argumentNotEmptyString(data && data.$dependency, "data.$dependency");
this._enter(name);
cin
working on IoC configuration
r113 const d = new ReferenceDescriptor<S, K>({
cin
changed the project structure
r49 name: data.$dependency,
lazy: data.lazy,
optional: data.optional,
default: data.default,
services: data.services && await this._visitRegistrations(data.services, "services")
});
this._leave();
return d;
}
cin
working on IoC configuration
r114 async _visitTypeRegistration<T, P>(data: TypeRegistration<T, P, S>, name: string) {
cin
changed the project structure
r49 argumentNotNull(data.$type, "data.$type");
this._enter(name);
const opts = this._makeServiceParams(data);
if (data.$type instanceof Function) {
opts.type = data.$type;
} else {
const [moduleName, typeName] = data.$type.split(":", 2);
opts.type = this._resolveType(moduleName, typeName);
}
const d = new TypeServiceDescriptor(
await mapAll(opts)
);
this._leave();
return d;
}
cin
working on IoC configuration
r114 async _visitFactoryRegistration<T, P>(data: FactoryRegistration<T, P, S>, name: string) {
cin
fixed "singleton" activation type handling in container configuration...
r65 argumentOfType(data.$factory, Function, "data.$factory");
cin
changed the project structure
r49 this._enter(name);
const opts = this._makeServiceParams(data);
cin
fixed "singleton" activation type handling in container configuration...
r65 opts.factory = data.$factory;
cin
changed the project structure
r49
const d = new FactoryServiceDescriptor(
await mapAll(opts)
);
this._leave();
return d;
}
}