##// END OF EJS Templates
working on IoC configuration
cin -
r113:22cf333c0b34 ioc ts support
parent child
Show More
@@ -1,36 +1,36
1 1 import { ActivationContextInfo } from "./ActivationContext";
2 2
3 3 export class ActivationError {
4 4 activationStack: ActivationContextInfo[];
5 5
6 6 service: string;
7 7
8 8 innerException: any;
9 9
10 10 message: string;
11 11
12 constructor(service: string, activationStack: ActivationContextInfo[], innerException) {
12 constructor(service: string, activationStack: ActivationContextInfo[], innerException: any) {
13 13 this.message = "Failed to activate the service";
14 14 this.activationStack = activationStack;
15 15 this.service = service;
16 16 this.innerException = innerException;
17 17 }
18 18
19 19 toString() {
20 20 const parts = [this.message];
21 21 if (this.service)
22 22 parts.push("when activating: " + this.service.toString());
23 23
24 24 if (this.innerException)
25 25 parts.push("caused by: " + this.innerException.toString());
26 26
27 27 if (this.activationStack) {
28 28 parts.push("at");
29 29 this.activationStack
30 30 .forEach(x => parts.push(` ${x.name} ${x.service}`));
31 31
32 32 }
33 33
34 34 return parts.join("\n");
35 35 }
36 36 }
@@ -1,37 +1,37
1 1 import { Descriptor, isDescriptor } from "./interfaces";
2 2 import { ActivationContext } from "./ActivationContext";
3 3 import { isPrimitive } from "../safe";
4 4
5 export class AggregateDescriptor implements Descriptor {
6 _value: object;
5 export class AggregateDescriptor<T> implements Descriptor<T> {
6 _value: T;
7 7
8 constructor(value: object) {
8 constructor(value: T) {
9 9 this._value = value;
10 10 }
11 11
12 12 activate(context: ActivationContext) {
13 13 return this._parse(this._value, context, "$value");
14 14 }
15 15
16 16 // TODO: make async
17 _parse(value, context: ActivationContext, path: string) {
17 _parse(value: T, context: ActivationContext, path: string) {
18 18 if (isPrimitive(value))
19 19 return value;
20 20
21 21 if (isDescriptor(value))
22 22 return context.activate(value, path);
23 23
24 24 if (value instanceof Array)
25 25 return value.map((x, i) => this._parse(x, context, `${path}[${i}]`));
26 26
27 27 const t = {};
28 28 for (const p of Object.keys(value))
29 29 t[p] = this._parse(value[p], context, `${path}.${p}`);
30 30 return t;
31 31
32 32 }
33 33
34 34 toString() {
35 35 return "@walk";
36 36 }
37 37 }
@@ -1,348 +1,350
1 1 import {
2 2 ServiceRegistration,
3 3 TypeRegistration,
4 4 FactoryRegistration,
5 5 ServiceMap,
6 6 isDescriptor,
7 7 isDependencyRegistration,
8 8 DependencyRegistration,
9 9 ValueRegistration,
10 10 ActivationType,
11 11 isValueRegistration,
12 12 isTypeRegistration,
13 13 isFactoryRegistration
14 14 } from "./interfaces";
15 15
16 16 import { argumentNotEmptyString, isPrimitive, isPromise, delegate, argumentOfType, argumentNotNull, get } from "../safe";
17 17 import { AggregateDescriptor } from "./AggregateDescriptor";
18 18 import { ValueDescriptor } from "./ValueDescriptor";
19 19 import { Container } from "./Container";
20 20 import { ReferenceDescriptor } from "./ReferenceDescriptor";
21 21 import { TypeServiceDescriptor } from "./TypeServiceDescriptor";
22 22 import { FactoryServiceDescriptor } from "./FactoryServiceDescriptor";
23 23 import { TraceSource } from "../log/TraceSource";
24 24 import { ConfigError } from "./ConfigError";
25 25 import { Cancellation } from "../Cancellation";
26 26 import { makeResolver } from "./ResolverHelper";
27 27 import { ICancellation } from "../interfaces";
28 28
29 29 const trace = TraceSource.get("@implab/core/di/Configuration");
30 30
31 async function mapAll(data: object | any[], map?: (v, k) => any): Promise<any> {
31 async function mapAll(data: any | any[], map?: (v: any, k: keyof any) => any): Promise<any> {
32 32 if (data instanceof Array) {
33 33 return Promise.all(map ? data.map(map) : data);
34 34 } else {
35 35 const keys = Object.keys(data);
36 36
37 37 const o: any = {};
38 38
39 39 await Promise.all(keys.map(async k => {
40 40 const v = map ? map(data[k], k) : data[k];
41 41 o[k] = isPromise(v) ? await v : v;
42 42 }));
43 43
44 44 return o;
45 45 }
46 46 }
47 47
48 48 export type ModuleResolver = (moduleName: string, ct?: ICancellation) => any;
49 49
50 50 type _key = string | number;
51 51
52 52 export class Configuration {
53 53
54 54 _hasInnerDescriptors = false;
55 55
56 56 _container: Container;
57 57
58 58 _path: Array<_key>;
59 59
60 _configName: string;
60 _configName: string | undefined;
61 61
62 _require: ModuleResolver;
62 _require: ModuleResolver | undefined;
63 63
64 64 constructor(container: Container) {
65 65 argumentNotNull(container, "container");
66 66 this._container = container;
67 67 this._path = [];
68 68 }
69 69
70 70 async loadConfiguration(moduleName: string, contextRequire?: any, ct = Cancellation.none) {
71 71 argumentNotEmptyString(moduleName, "moduleName");
72 72
73 73 trace.log(
74 74 "loadConfiguration moduleName={0}, contextRequire={1}",
75 75 moduleName,
76 76 contextRequire ? typeof (contextRequire) : "<nil>"
77 77 );
78 78
79 79 this._configName = moduleName;
80 80
81 const r = await makeResolver(null, contextRequire);
81 const r = await makeResolver(undefined, contextRequire);
82 82
83 83 const config = await r(moduleName, ct);
84 84
85 85 await this._applyConfiguration(
86 86 config,
87 87 await makeResolver(moduleName, contextRequire),
88 88 ct
89 89 );
90 90 }
91 91
92 92 async applyConfiguration(data: object, contextRequire?: any, ct = Cancellation.none) {
93 93 argumentNotNull(data, "data");
94 94
95 95 await this._applyConfiguration(data, await makeResolver(void (0), contextRequire), ct);
96 96 }
97 97
98 98 async _applyConfiguration(data: object, resolver?: ModuleResolver, ct = Cancellation.none) {
99 99 trace.log("applyConfiguration");
100 100
101 101 this._configName = "$";
102 102
103 103 if (resolver)
104 104 this._require = resolver;
105 105
106 106 let services: ServiceMap;
107 107
108 108 try {
109 109 services = await this._visitRegistrations(data, "$");
110 110 } catch (e) {
111 111 throw this._makeError(e);
112 112 }
113 113
114 114 this._container.register(services);
115 115 }
116 116
117 _makeError(inner) {
117 _makeError(inner: any) {
118 118 const e = new ConfigError("Failed to load configuration", inner);
119 e.configName = this._configName;
119 e.configName = this._configName || "<inline>";
120 120 e.path = this._makePath();
121 121 return e;
122 122 }
123 123
124 124 _makePath() {
125 125 return this._path
126 126 .reduce(
127 127 (prev, cur) => typeof cur === "number" ?
128 128 `${prev}[${cur}]` :
129 129 `${prev}.${cur}`
130 130 )
131 131 .toString();
132 132 }
133 133
134 134 async _resolveType(moduleName: string, localName: string) {
135 135 trace.log("resolveType moduleName={0}, localName={1}", moduleName, localName);
136 136 try {
137 137 const m = await this._loadModule(moduleName);
138 138 return localName ? get(localName, m) : m;
139 139 } catch (e) {
140 140 trace.error("Failed to resolve type moduleName={0}, localName={1}", moduleName, localName);
141 141 throw e;
142 142 }
143 143 }
144 144
145 145 _loadModule(moduleName: string) {
146 146 trace.debug("loadModule {0}", moduleName);
147 if (!this._require)
148 throw new Error("Module loader isn't specified");
147 149
148 150 return this._require(moduleName);
149 151 }
150 152
151 async _visitRegistrations(data, name: _key) {
153 async _visitRegistrations(data: any, name: _key) {
152 154 this._enter(name);
153 155
154 156 if (data.constructor &&
155 157 data.constructor.prototype !== Object.prototype)
156 158 throw new Error("Configuration must be a simple object");
157 159
158 160 const o: ServiceMap = {};
159 161 const keys = Object.keys(data);
160 162
161 163 const services = await mapAll(data, async (v, k) => {
162 164 const d = await this._visit(v, k);
163 165 return isDescriptor(d) ? d : new AggregateDescriptor(d);
164 166 }) as ServiceMap;
165 167
166 168 this._leave();
167 169
168 170 return services;
169 171 }
170 172
171 _enter(name: _key) {
172 this._path.push(name);
173 _enter(name: keyof any) {
174 this._path.push(name.toString());
173 175 trace.debug(">{0}", name);
174 176 }
175 177
176 178 _leave() {
177 179 const name = this._path.pop();
178 180 trace.debug("<{0}", name);
179 181 }
180 182
181 async _visit(data, name: string) {
183 async _visit<T extends object>(data: T, name: keyof T) {
182 184 if (isPrimitive(data) || isDescriptor(data))
183 185 return data;
184 186
185 187 if (isDependencyRegistration(data)) {
186 188 return this._visitDependencyRegistration(data, name);
187 189 } else if (isValueRegistration(data)) {
188 190 return this._visitValueRegistration(data, name);
189 191 } else if (isTypeRegistration(data)) {
190 192 return this._visitTypeRegistration(data, name);
191 193 } else if (isFactoryRegistration(data)) {
192 194 return this._visitFactoryRegistration(data, name);
193 195 } else if (data instanceof Array) {
194 196 return this._visitArray(data, name);
195 197 }
196 198
197 199 return this._visitObject(data, name);
198 200 }
199 201
200 202 async _visitObject(data: object, name: _key) {
201 203 if (data.constructor &&
202 204 data.constructor.prototype !== Object.prototype)
203 205 return new ValueDescriptor(data);
204 206
205 207 this._enter(name);
206 208
207 209 const v = await mapAll(data, delegate(this, "_visit"));
208 210
209 211 // TODO: handle inline descriptors properly
210 212 // const ex = {
211 213 // activate(ctx) {
212 214 // const value = ctx.activate(this.prop, "prop");
213 215 // // some code
214 216 // },
215 217 // // will be turned to ReferenceDescriptor
216 218 // prop: { $dependency: "depName" }
217 219 // };
218 220
219 221 this._leave();
220 222 return v;
221 223 }
222 224
223 225 async _visitArray(data: any[], name: _key) {
224 226 if (data.constructor &&
225 227 data.constructor.prototype !== Array.prototype)
226 228 return new ValueDescriptor(data);
227 229
228 230 this._enter(name);
229 231
230 232 const v = await mapAll(data, delegate(this, "_visit"));
231 233 this._leave();
232 234
233 235 return v;
234 236 }
235 237
236 _makeServiceParams(data: ServiceRegistration) {
238 _makeServiceParams<T, P, S>(data: ServiceRegistration<T, P, S>) {
237 239 const opts: any = {
238 240 owner: this._container
239 241 };
240 242 if (data.services)
241 243 opts.services = this._visitRegistrations(data.services, "services");
242 244
243 245 if (data.inject) {
244 246 this._enter("inject");
245 247 opts.inject = mapAll(
246 248 data.inject instanceof Array ?
247 249 data.inject :
248 250 [data.inject],
249 251 delegate(this, "_visitObject")
250 252 );
251 253 this._leave();
252 254 }
253 255
254 256 if ("params" in data)
255 257 opts.params = data.params instanceof Array ?
256 258 this._visitArray(data.params, "params") :
257 259 this._visit(data.params, "params");
258 260
259 261 if (data.activation) {
260 262 if (typeof (data.activation) === "string") {
261 263 switch (data.activation.toLowerCase()) {
262 264 case "singleton":
263 265 opts.activation = ActivationType.Singleton;
264 266 break;
265 267 case "container":
266 268 opts.activation = ActivationType.Container;
267 269 break;
268 270 case "hierarchy":
269 271 opts.activation = ActivationType.Hierarchy;
270 272 break;
271 273 case "context":
272 274 opts.activation = ActivationType.Context;
273 275 break;
274 276 case "call":
275 277 opts.activation = ActivationType.Call;
276 278 break;
277 279 default:
278 280 throw new Error("Unknown activation type: " +
279 281 data.activation);
280 282 }
281 283 } else {
282 284 opts.activation = Number(data.activation);
283 285 }
284 286 }
285 287
286 288 if (data.cleanup)
287 289 opts.cleanup = data.cleanup;
288 290
289 291 return opts;
290 292 }
291 293
292 async _visitValueRegistration(data: ValueRegistration, name: _key) {
294 async _visitValueRegistration<T>(data: ValueRegistration<T>, name: _key) {
293 295 this._enter(name);
294 296 const d = data.parse ? new AggregateDescriptor(data.$value) : new ValueDescriptor(data.$value);
295 297 this._leave();
296 298 return d;
297 299 }
298 300
299 async _visitDependencyRegistration(data: DependencyRegistration, name: _key) {
301 async _visitDependencyRegistration<S, K extends keyof S>(data: DependencyRegistration<S, K>, name: keyof S) {
300 302 argumentNotEmptyString(data && data.$dependency, "data.$dependency");
301 303 this._enter(name);
302 const d = new ReferenceDescriptor({
304 const d = new ReferenceDescriptor<S, K>({
303 305 name: data.$dependency,
304 306 lazy: data.lazy,
305 307 optional: data.optional,
306 308 default: data.default,
307 309 services: data.services && await this._visitRegistrations(data.services, "services")
308 310 });
309 311 this._leave();
310 312 return d;
311 313 }
312 314
313 async _visitTypeRegistration(data: TypeRegistration, name: _key) {
315 async _visitTypeRegistration<T, P, S>(data: TypeRegistration<T, P, S>, name: _key) {
314 316 argumentNotNull(data.$type, "data.$type");
315 317 this._enter(name);
316 318
317 319 const opts = this._makeServiceParams(data);
318 320 if (data.$type instanceof Function) {
319 321 opts.type = data.$type;
320 322 } else {
321 323 const [moduleName, typeName] = data.$type.split(":", 2);
322 324 opts.type = this._resolveType(moduleName, typeName);
323 325 }
324 326
325 327 const d = new TypeServiceDescriptor(
326 328 await mapAll(opts)
327 329 );
328 330
329 331 this._leave();
330 332
331 333 return d;
332 334 }
333 335
334 async _visitFactoryRegistration(data: FactoryRegistration, name: _key) {
336 async _visitFactoryRegistration<T, P, S>(data: FactoryRegistration<T, P, S>, name: _key) {
335 337 argumentOfType(data.$factory, Function, "data.$factory");
336 338 this._enter(name);
337 339
338 340 const opts = this._makeServiceParams(data);
339 341 opts.factory = data.$factory;
340 342
341 343 const d = new FactoryServiceDescriptor(
342 344 await mapAll(opts)
343 345 );
344 346
345 347 this._leave();
346 348 return d;
347 349 }
348 350 }
@@ -1,100 +1,101
1 1 import { isNull, argumentNotEmptyString, each } from "../safe";
2 2 import { ActivationContext } from "./ActivationContext";
3 3 import { ServiceMap, Descriptor } from "./interfaces";
4 4 import { ActivationError } from "./ActivationError";
5 5
6 export interface ReferenceDescriptorParams {
7 name: string;
6 export interface ReferenceDescriptorParams<S, K extends keyof S> {
7 name: K;
8 8 lazy?: boolean;
9 9 optional?: boolean;
10 default?;
10 default?: S[K];
11 11 services?: ServiceMap;
12 12 }
13 13
14 export class ReferenceDescriptor implements Descriptor {
15 _name: string;
14 export class ReferenceDescriptor<S, K extends keyof S> implements Descriptor<S[K]> {
15 _name: K;
16 16
17 17 _lazy = false;
18 18
19 19 _optional = false;
20 20
21 21 _default: any;
22 22
23 23 _services: ServiceMap;
24 24
25 constructor(opts: ReferenceDescriptorParams) {
25 constructor(opts: ReferenceDescriptorParams<S, K>) {
26 26 argumentNotEmptyString(opts && opts.name, "opts.name");
27 27 this._name = opts.name;
28 28 this._lazy = !!opts.lazy;
29 29 this._optional = !!opts.optional;
30 30 this._default = opts.default;
31 this._services = opts.services;
31
32 this._services = opts.services || {};
32 33 }
33 34
34 35 activate(context: ActivationContext, name: string) {
35 36 // добавляСм сСрвисы
36 37 if (this._services) {
37 38 for (const p of Object.keys(this._services))
38 39 context.register(p, this._services[p]);
39 40 }
40 41
41 42 if (this._lazy) {
42 43 const saved = context.clone();
43 44
44 45 return (cfg: ServiceMap) => {
45 46 // Π·Π°Ρ‰ΠΈΡ‰Π°Π΅ΠΌ контСкст Π½Π° случай ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ Π² процСссС
46 47 // Π°ΠΊΡ‚ΠΈΠ²Π°Ρ†ΠΈΠΈ
47 48 const ct = saved.clone();
48 49 try {
49 50 if (cfg) {
50 51 for (const k in cfg)
51 52 ct.register(k, cfg[k]);
52 53 }
53 54
54 55 return this._optional ? ct.resolve(this._name, this._default) : ct
55 56 .resolve(this._name);
56 57 } catch (error) {
57 throw new ActivationError(this._name, ct.getStack(), error);
58 throw new ActivationError(this._name.toString(), ct.getStack(), error);
58 59 }
59 60 };
60 61 } else {
61 62 // добавляСм сСрвисы
62 63 if (this._services) {
63 64 for (const p of Object.keys(this._services))
64 65 context.register(p, this._services[p]);
65 66 }
66 67
67 68 const v = this._optional ?
68 69 context.resolve(this._name, this._default) :
69 70 context.resolve(this._name);
70 71
71 72 return v;
72 73 }
73 74 }
74 75
75 76 toString() {
76 77 const opts = [];
77 78 if (this._optional)
78 79 opts.push("optional");
79 80 if (this._lazy)
80 81 opts.push("lazy");
81 82
82 83 const parts = [
83 84 "@ref "
84 85 ];
85 86 if (opts.length) {
86 87 parts.push("{");
87 88 parts.push(opts.join());
88 89 parts.push("} ");
89 90 }
90 91
91 parts.push(this._name);
92 parts.push(this._name.toString());
92 93
93 94 if (!isNull(this._default)) {
94 95 parts.push(" = ");
95 96 parts.push(this._default);
96 97 }
97 98
98 99 return parts.join("");
99 100 }
100 101 }
@@ -1,17 +1,17
1 1 import { Descriptor } from "./interfaces";
2 2
3 export class ValueDescriptor implements Descriptor {
4 _value;
3 export class ValueDescriptor<T> implements Descriptor<T> {
4 _value: T;
5 5
6 constructor(value) {
6 constructor(value: T) {
7 7 this._value = value;
8 8 }
9 9
10 10 activate() {
11 11 return this._value;
12 12 }
13 13
14 14 toString() {
15 15 return `@type=${typeof this._value}`;
16 16 }
17 17 }
@@ -1,75 +1,75
1 import { isNull, isPrimitive } from "../safe";
1 import { isPrimitive } from "../safe";
2 2 import { ActivationContext } from "./ActivationContext";
3 3 import { Constructor, Factory } from "../interfaces";
4 4
5 export interface Descriptor {
6 activate(context: ActivationContext, name?: string);
5 export interface Descriptor<T = any> {
6 activate(context: ActivationContext, name?: string): T;
7 7 }
8 8
9 export function isDescriptor(x): x is Descriptor {
9 export function isDescriptor(x: any): x is Descriptor {
10 10 return (!isPrimitive(x)) &&
11 11 (x.activate instanceof Function);
12 12 }
13 13
14 export interface ServiceMap {
15 [s: string]: Descriptor;
14 export type ServiceMap<S = any> = {
15 [k in keyof S]: Descriptor<S[k]>;
16 16 }
17 17
18 18 export enum ActivationType {
19 19 Singleton = 1,
20 20 Container,
21 21 Hierarchy,
22 22 Context,
23 23 Call
24 24 }
25 25
26 export interface RegistrationWithServices {
27 services?: object;
26 export interface RegistrationWithServices<S> {
27 services?: ServiceMap<S>;
28 28 }
29 29
30 export interface ServiceRegistration extends RegistrationWithServices {
30 export interface ServiceRegistration<T, P, S> extends RegistrationWithServices<S> {
31 31
32 32 activation?: "singleton" | "container" | "hierarchy" | "context" | "call";
33 33
34 params?;
34 params?: P;
35 35
36 36 inject?: object | object[];
37 37
38 cleanup?: (instance) => void | string;
38 cleanup?: ((instance: T) => void) | string;
39 39 }
40 40
41 export interface TypeRegistration extends ServiceRegistration {
42 $type: string | Constructor;
41 export interface TypeRegistration<T, P, S> extends ServiceRegistration<T, P, S> {
42 $type: string | Constructor<T>;
43 43 }
44 44
45 export interface FactoryRegistration extends ServiceRegistration {
46 $factory: string | Factory;
45 export interface FactoryRegistration<T, P, S> extends ServiceRegistration<T, P, S> {
46 $factory: string | Factory<T>;
47 47 }
48 48
49 export interface ValueRegistration {
50 $value;
49 export interface ValueRegistration<T> {
50 $value: T;
51 51 parse?: boolean;
52 52 }
53 53
54 export interface DependencyRegistration extends RegistrationWithServices {
55 $dependency: string;
54 export interface DependencyRegistration<S, K extends keyof S> extends RegistrationWithServices<S> {
55 $dependency: K;
56 56 lazy?: boolean;
57 57 optional?: boolean;
58 default?;
58 default?: S[K];
59 59 }
60 60
61 export function isTypeRegistration(x): x is TypeRegistration {
61 export function isTypeRegistration(x: any): x is TypeRegistration<any, any, any> {
62 62 return (!isPrimitive(x)) && ("$type" in x);
63 63 }
64 64
65 export function isFactoryRegistration(x): x is FactoryRegistration {
65 export function isFactoryRegistration(x: any): x is FactoryRegistration<any, any, any> {
66 66 return (!isPrimitive(x)) && ("$factory" in x);
67 67 }
68 68
69 export function isValueRegistration(x): x is ValueRegistration {
69 export function isValueRegistration(x: any): x is ValueRegistration<any> {
70 70 return (!isPrimitive(x)) && ("$value" in x);
71 71 }
72 72
73 export function isDependencyRegistration(x): x is DependencyRegistration {
73 export function isDependencyRegistration(x: any): x is DependencyRegistration<any, string | number | symbol> {
74 74 return (!isPrimitive(x)) && ("$dependency" in x);
75 75 }
General Comments 0
You need to be logged in to leave comments. Login now