##// END OF EJS Templates
ts code cleanup, linting
cin -
r39:ed82314aa5c8 di-typescript
parent child
Show More
@@ -40,7 +40,7 export class Cancellation implements ICa
40 40 else
41 41 this._cbs.push(cb);
42 42
43 let me = this;
43 const me = this;
44 44 return {
45 45 destroy() {
46 46 me._unregister(cb);
@@ -51,7 +51,7 export class Cancellation implements ICa
51 51
52 52 private _unregister(cb) {
53 53 if(this._cbs) {
54 let i = this._cbs.indexOf(cb);
54 const i = this._cbs.indexOf(cb);
55 55 if ( i>=0 )
56 56 this._cbs.splice(i,1);
57 57 }
@@ -63,7 +63,6 export class Cancellation implements ICa
63 63
64 64 this._reason = (reason = reason || new Error("Operation cancelled"));
65 65
66
67 66 if (this._cbs) {
68 67 this._cbs.forEach(cb => cb(reason));
69 68 this._cbs = null;
@@ -86,4 +85,4 export class Cancellation implements ICa
86 85 return destroyed;
87 86 }
88 87 };
89 } No newline at end of file
88 }
@@ -1,23 +1,18
1 import { IObservable, IDestroyable, ICancellation } from './interfaces';
2 import { Cancellation } from './Cancellation'
3 import { argumentNotNull } from './safe';
4
1 import { IObservable, IDestroyable, ICancellation } from "./interfaces";
2 import { Cancellation } from "./Cancellation";
3 import { argumentNotNull } from "./safe";
5 4
6 interface Handler<T> {
7 (x: T): void
8 }
5 type Handler<T> = (x: T) => void;
9 6
10 interface Initializer<T> {
11 (notify: Handler<T>, error?: (e: any) => void, complete?: () => void): void;
12 }
7 type Initializer<T> = (notify: Handler<T>, error?: (e: any) => void, complete?: () => void) => void;
13 8
14 9 // TODO: think about to move this interfaces.ts and make it public
15 10 interface IObserver<T> {
16 next(event: T): void
11 next(event: T): void;
17 12
18 error(e: any): void
13 error(e: any): void;
19 14
20 complete(): void
15 complete(): void;
21 16 }
22 17
23 18 const noop = () => {};
@@ -27,10 +22,9 export class Observable<T> implements IO
27 22
28 23 private _observers = new Array<IObserver<T>>();
29 24
25 private _complete: boolean;
30 26
31 private _complete: boolean
32
33 private _error: any
27 private _error: any;
34 28
35 29 constructor(func?: Initializer<T>) {
36 30 if (func)
@@ -54,10 +48,10 export class Observable<T> implements IO
54 48 on(next: Handler<T>, error?: Handler<any>, complete?: () => void): IDestroyable {
55 49 argumentNotNull(next, "next");
56 50
57 let me = this;
51 const me = this;
58 52
59 let observer: IObserver<T> & IDestroyable = {
60 next: next,
53 const observer: IObserver<T> & IDestroyable = {
54 next,
61 55 error: error ? error.bind(null) : noop,
62 56 complete: complete ? complete.bind(null) : noop,
63 57
@@ -68,7 +62,6 export class Observable<T> implements IO
68 62
69 63 this._addObserver(observer);
70 64
71
72 65 return observer;
73 66 }
74 67
@@ -95,14 +88,14 export class Observable<T> implements IO
95 88 */
96 89 next(ct: ICancellation = Cancellation.none): Promise<T> {
97 90 return new Promise<T>((resolve, reject) => {
98 let observer: IObserver<T> = {
91 const observer: IObserver<T> = {
99 92 next: resolve,
100 93 error: reject,
101 94 complete: () => reject("No more events are available")
102 95 };
103 96
104 97 if (this._addOnce(observer) && ct.isSupported()) {
105 ct.register((e) => {
98 ct.register(e => {
106 99 this._removeOnce(observer);
107 100 reject(e);
108 101 });
@@ -131,48 +124,44 export class Observable<T> implements IO
131 124 }
132 125
133 126 private _removeOnce(d: IObserver<T>) {
134 let i = this._once.indexOf(d);
127 const i = this._once.indexOf(d);
135 128 if (i >= 0)
136 129 this._once.splice(i, 1);
137 130 }
138 131
139 132 private _removeObserver(d: IObserver<T>) {
140 let i = this._observers.indexOf(d);
133 const i = this._observers.indexOf(d);
141 134 if (i >= 0)
142 135 this._observers.splice(i, 1);
143 136 }
144 137
145 138 private _notify(guard: (observer: IObserver<T>) => void) {
146 if (this._once.length) {
147 for (let i = 0; i < this._once.length; i++)
148 guard(this._once[i]);
139 this._once.forEach(guard);
149 140 this._once = [];
150 }
151 141
152 for (let i = 0; i < this._observers.length; i++)
153 guard(this._observers[i]);
142 this._observers.forEach(guard);
154 143 }
155 144
156 145 protected _notifyNext(evt: T) {
157 let guard = (observer: IObserver<T>) => {
146 const guard = (observer: IObserver<T>) => {
158 147 try {
159 148 observer.next(evt);
160 149 } catch (e) {
161 150 this.onObserverException(e);
162 151 }
163 }
152 };
164 153
165 154 this._notify(guard);
166 155 }
167 156
168 157 protected _notifyError(e: any) {
169 let guard = (observer: IObserver<T>) => {
158 const guard = (observer: IObserver<T>) => {
170 159 try {
171 160 observer.error(e);
172 161 } catch (e) {
173 162 this.onObserverException(e);
174 163 }
175 }
164 };
176 165
177 166 this._notify(guard);
178 167 this._observers = [];
@@ -180,16 +169,16 export class Observable<T> implements IO
180 169 }
181 170
182 171 protected _notifyCompleted() {
183 let guard = (observer: IObserver<T>) => {
172 const guard = (observer: IObserver<T>) => {
184 173 try {
185 174 observer.complete();
186 175 } catch (e) {
187 176 this.onObserverException(e);
188 177 }
189 }
178 };
190 179
191 180 this._notify(guard);
192 181 this._observers = [];
193 182 this._complete = true;
194 183 }
195 } No newline at end of file
184 }
@@ -8,7 +8,7
8 8
9 9 declare var window: any;
10 10
11 let _window: any = 'undefined' !== typeof window ? window : null;
11 const _window: any = "undefined" !== typeof window ? window : null;
12 12
13 13 // Unique ID creation requires a high quality random # generator. We
14 14 // feature
@@ -19,14 +19,14 let _rng;
19 19
20 20 function setupBrowser() {
21 21 // Allow for MSIE11 msCrypto
22 let _crypto = _window.crypto || _window.msCrypto;
22 const _crypto = _window.crypto || _window.msCrypto;
23 23
24 24 if (!_rng && _crypto && _crypto.getRandomValues) {
25 25 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
26 26 //
27 27 // Moderately fast, high quality
28 28 try {
29 let _rnds8 = new Uint8Array(16);
29 const _rnds8 = new Uint8Array(16);
30 30 _rng = function whatwgRNG() {
31 31 _crypto.getRandomValues(_rnds8);
32 32 return _rnds8;
@@ -41,9 +41,9 function setupBrowser() {
41 41 // If all else fails, use Math.random(). It's fast, but is of
42 42 // unspecified
43 43 // quality.
44 let _rnds = new Array(16);
45 _rng = function () {
46 for (var i = 0, r; i < 16; i++) {
44 const _rnds = new Array(16);
45 _rng = () => {
46 for (let i = 0, r; i < 16; i++) {
47 47 if ((i & 0x03) === 0) {
48 48 r = Math.random() * 0x100000000;
49 49 }
@@ -52,7 +52,7 function setupBrowser() {
52 52
53 53 return _rnds;
54 54 };
55 if ('undefined' !== typeof console && console.warn) {
55 if ("undefined" !== typeof console && console.warn) {
56 56 console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()");
57 57 }
58 58 }
@@ -63,12 +63,10 function setupNode() {
63 63 // http://nodejs.org/docs/v0.6.2/api/crypto.html
64 64 //
65 65 // Moderately fast, high quality
66 if ('function' === typeof require) {
66 if ("function" === typeof require) {
67 67 try {
68 let _rb = require('crypto').randomBytes;
69 _rng = _rb && function () {
70 return _rb(16);
71 };
68 const _rb = require("crypto").randomBytes;
69 _rng = _rb && (() => _rb(16));
72 70 _rng();
73 71 } catch (e) { /**/ }
74 72 }
@@ -81,22 +79,22 if (_window) {
81 79 }
82 80
83 81 // Buffer class to use
84 let BufferClass = ('function' === typeof Buffer) ? Buffer : Array;
82 const BufferClass = ("function" === typeof Buffer) ? Buffer : Array;
85 83
86 84 // Maps for number <-> hex string conversion
87 let _byteToHex = [];
88 let _hexToByte = {};
85 const _byteToHex = [];
86 const _hexToByte = {};
89 87 for (let i = 0; i < 256; i++) {
90 88 _byteToHex[i] = (i + 0x100).toString(16).substr(1);
91 89 _hexToByte[_byteToHex[i]] = i;
92 90 }
93 91
94 92 // **`parse()` - Parse a UUID into it's component bytes**
95 function _parse(s, buf?, offset?): Array<string> {
96 let i = (buf && offset) || 0, ii = 0;
93 export function _parse(s, buf?, offset?): Array<string> {
94 const i = (buf && offset) || 0; let ii = 0;
97 95
98 96 buf = buf || [];
99 s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
97 s.toLowerCase().replace(/[0-9a-f]{2}/g, oct => {
100 98 if (ii < 16) { // Don't overflow!
101 99 buf[i + ii++] = _hexToByte[oct];
102 100 }
@@ -112,11 +110,11 function _parse(s, buf?, offset?): Array
112 110
113 111 // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
114 112 function _unparse(buf, offset?): string {
115 let i = offset || 0, bth = _byteToHex;
113 let i = offset || 0; const bth = _byteToHex;
116 114 return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] +
117 bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' +
118 bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] +
119 bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] +
115 bth[buf[i++]] + "-" + bth[buf[i++]] + bth[buf[i++]] + "-" +
116 bth[buf[i++]] + bth[buf[i++]] + "-" + bth[buf[i++]] +
117 bth[buf[i++]] + "-" + bth[buf[i++]] + bth[buf[i++]] +
120 118 bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]];
121 119 }
122 120
@@ -126,11 +124,11 function _unparse(buf, offset?): string
126 124 // and http://docs.python.org/library/uuid.html
127 125
128 126 // random #'s we need to init node and clockseq
129 let _seedBytes = _rng();
127 const _seedBytes = _rng();
130 128
131 129 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit =
132 130 // 1)
133 let _nodeId = [
131 const _nodeId = [
134 132 _seedBytes[0] | 0x01,
135 133 _seedBytes[1],
136 134 _seedBytes[2],
@@ -143,12 +141,12 let _nodeId = [
143 141 let _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
144 142
145 143 // Previous uuid creation time
146 let _lastMSecs = 0, _lastNSecs = 0;
144 let _lastMSecs = 0; let _lastNSecs = 0;
147 145
148 146 // See https://github.com/broofa/node-uuid for API details
149 function _v1(options?, buf?, offset?): string {
147 export function _v1(options?, buf?, offset?): string {
150 148 let i = buf && offset || 0;
151 let b = buf || [];
149 const b = buf || [];
152 150
153 151 options = options || {};
154 152
@@ -170,7 +168,7 function _v1(options?, buf?, offset?): s
170 168 let nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;
171 169
172 170 // Time since last uuid creation (in msecs)
173 let dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs) / 10000;
171 const dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs) / 10000;
174 172
175 173 // Per 4.2.1.2, Bump clockseq on clock regression
176 174 if (dt < 0 && options.clockseq == null) {
@@ -187,7 +185,7 function _v1(options?, buf?, offset?): s
187 185 // Per 4.2.1.2 Throw error if too many uuids are requested
188 186 if (nsecs >= 10000) {
189 187 throw new Error(
190 'uuid.v1(): Can\'t create more than 10M uuids/sec');
188 "uuid.v1(): Can't create more than 10M uuids/sec");
191 189 }
192 190
193 191 _lastMSecs = msecs;
@@ -198,14 +196,14 function _v1(options?, buf?, offset?): s
198 196 msecs += 12219292800000;
199 197
200 198 // `time_low`
201 let tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
199 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
202 200 b[i++] = tl >>> 24 & 0xff;
203 201 b[i++] = tl >>> 16 & 0xff;
204 202 b[i++] = tl >>> 8 & 0xff;
205 203 b[i++] = tl & 0xff;
206 204
207 205 // `time_mid`
208 let tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
206 const tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
209 207 b[i++] = tmh >>> 8 & 0xff;
210 208 b[i++] = tmh & 0xff;
211 209
@@ -220,7 +218,7 function _v1(options?, buf?, offset?): s
220 218 b[i++] = clockseq & 0xff;
221 219
222 220 // `node`
223 let node = options.node || _nodeId;
221 const node = options.node || _nodeId;
224 222 for (let n = 0; n < 6; n++) {
225 223 b[i + n] = node[n];
226 224 }
@@ -231,17 +229,17 function _v1(options?, buf?, offset?): s
231 229 // **`v4()` - Generate random UUID**
232 230
233 231 // See https://github.com/broofa/node-uuid for API details
234 function _v4(options?, buf?, offset?): string {
232 export function _v4(options?, buf?, offset?): string {
235 233 // Deprecated - 'format' argument, as supported in v1.2
236 let i = buf && offset || 0;
234 const i = buf && offset || 0;
237 235
238 if (typeof (options) === 'string') {
239 buf = (options === 'binary') ? new BufferClass(16) : null;
236 if (typeof (options) === "string") {
237 buf = (options === "binary") ? new BufferClass(16) : null;
240 238 options = null;
241 239 }
242 240 options = options || {};
243 241
244 let rnds = options.random || (options.rng || _rng)();
242 const rnds = options.random || (options.rng || _rng)();
245 243
246 244 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
247 245 rnds[6] = (rnds[6] & 0x0f) | 0x40;
@@ -266,5 +264,4 export namespace Uuid {
266 264 export const v1 = _v1;
267 265 export const empty = "00000000-0000-0000-0000-000000000000";
268 266 export const parse = _parse;
269 export const unparse = _unparse;
270 } No newline at end of file
267 }
@@ -3,28 +3,26 import { argumentNotNull, argumentNotEmp
3 3 import { Descriptor, ServiceMap, isDescriptor } from "./interfaces";
4 4 import { Container } from "./Container";
5 5
6 let trace = TraceSource.get("di");
6 const trace = TraceSource.get("@implab/core/di/ActivationContext");
7 7
8 export class ActivationContextInfo {
9 name: string
8 export interface ActivationContextInfo {
9 name: string;
10 10
11 service: string
11 service: Descriptor;
12 12
13 scope: ServiceMap
13 scope: ServiceMap;
14 14 }
15 15
16 export class ActivationContext {
17 _cache: object;
16 18
17 export class ActivationContext {
18 _cache: object
19
20 _services: ServiceMap
19 _services: ServiceMap;
21 20
22 _stack: ActivationContextInfo[]
21 _stack: ActivationContextInfo[];
23 22
24 _visited: any
23 _visited: object;
25 24
26 container: any
27
25 container: Container;
28 26
29 27 constructor(container: Container, services: ServiceMap, cache?: object, visited?) {
30 28 argumentNotNull(container, "container");
@@ -38,13 +36,13 export class ActivationContext {
38 36 }
39 37
40 38 getService(name, def?): any {
41 let d = this._services[name];
39 const d = this._services[name];
42 40
43 41 if (!d)
44 42 if (arguments.length > 1)
45 43 return def;
46 44 else
47 throw new Error("Service '" + name + "' not found");
45 throw new Error(`Service ${name} not found`);
48 46
49 47 return d.activate(this, name);
50 48 }
@@ -68,47 +66,43 export class ActivationContext {
68 66 this._cache,
69 67 this._visited
70 68 );
71
72 69 }
73 70
74 has(id) {
71 has(id: string) {
75 72 return id in this._cache;
76 73 }
77 74
78 get(id) {
75 get(id: string) {
79 76 return this._cache[id];
80 77 }
81 78
82 store(id, value) {
79 store(id: string, value) {
83 80 return (this._cache[id] = value);
84 81 }
85 82
86 parse(data: any, name) {
87 var me = this;
83 parse(data: object, name: string) {
88 84 if (isPrimitive(data))
89 85 return data;
90 86
91 87 if (isDescriptor(data)) {
92 88 return data.activate(this, name);
93 89 } else if (data instanceof Array) {
94 me.enter(name);
95 var v = data.map(function (x, i) {
96 return me.parse(x, "." + i);
97 });
98 me.leave();
90 this.enter(name);
91 const v = data.map( (x, i) => this.parse(x, `[${i}]`));
92 this.leave();
99 93 return v;
100 94 } else {
101 me.enter(name);
102 var result = {};
103 for (var p in data)
104 result[p] = me.parse(data[p], "." + p);
105 me.leave();
95 this.enter(name);
96 const result = {};
97 for (const p in data)
98 result[p] = this.parse(data[p], "." + p);
99 this.leave();
106 100 return result;
107 101 }
108 102 }
109 103
110 visit(id) {
111 var count = this._visited[id] || 0;
104 visit(id: string) {
105 const count = this._visited[id] || 0;
112 106 this._visited[id] = count + 1;
113 107 return count;
114 108 }
@@ -117,12 +111,12 export class ActivationContext {
117 111 return this._stack.slice().reverse();
118 112 }
119 113
120 enter(name, d?, localize?) {
114 enter(name: string, d?: Descriptor, localize?: boolean) {
121 115 if (trace.isLogEnabled())
122 116 trace.log("enter " + name + " " + (d || "") +
123 117 (localize ? " localize" : ""));
124 118 this._stack.push({
125 name: name,
119 name,
126 120 service: d,
127 121 scope: this._services
128 122 });
@@ -131,10 +125,10 export class ActivationContext {
131 125 }
132 126
133 127 leave() {
134 var ctx = this._stack.pop();
128 const ctx = this._stack.pop();
135 129 this._services = ctx.scope;
136 130
137 131 if (trace.isLogEnabled())
138 132 trace.log("leave " + ctx.name + " " + (ctx.service || ""));
139 133 }
140 } No newline at end of file
134 }
@@ -1,13 +1,13
1 1 import { ActivationContextInfo } from "./ActivationContext";
2 2
3 3 export class ActivationError {
4 activationStack: ActivationContextInfo[]
4 activationStack: ActivationContextInfo[];
5 5
6 service: string
6 service: string;
7 7
8 innerException: any
8 innerException: any;
9 9
10 message: string
10 message: string;
11 11
12 12 constructor(service: string, activationStack: ActivationContextInfo[], innerException) {
13 13 this.message = "Failed to activate the service";
@@ -17,7 +17,7 export class ActivationError {
17 17 }
18 18
19 19 toString() {
20 var parts = [this.message];
20 const parts = [this.message];
21 21 if (this.service)
22 22 parts.push("when activating: " + this.service.toString());
23 23
@@ -26,12 +26,11 export class ActivationError {
26 26
27 27 if (this.activationStack) {
28 28 parts.push("at");
29 this.activationStack.forEach(function (x) {
30 parts.push(" " + x.name + " " +
31 (x.service ? x.service.toString() : ""));
32 });
29 this.activationStack
30 .forEach(x => parts.push(` ${x.name} ${x.service ? x.service.toString() : ""}`));
31
33 32 }
34 33
35 34 return parts.join("\n");
36 35 }
37 } No newline at end of file
36 }
@@ -1,11 +1,11
1 1 import { Descriptor } from "./interfaces";
2 2 import { ActivationContext } from "./ActivationContext";
3 3
4 export class AggregateDescriptor<T> implements Descriptor {
5 _value: T;
4 export class AggregateDescriptor implements Descriptor {
5 _value: object;
6 6
7 constructor(value: T) {
8
7 constructor(value: object) {
8 this._value = value;
9 9 }
10 10
11 11 activate(context: ActivationContext, name: string) {
@@ -18,7 +18,7 export class AggregateDescriptor<T> impl
18 18 isInstanceCreated(): boolean {
19 19 return false;
20 20 }
21 getInstance(): T {
22 throw new Error("Not supported exception");
21 getInstance(): any {
22 throw new Error("Not supported");
23 23 }
24 24 }
@@ -176,10 +176,6 export class Container {
176 176 owner: this
177 177 };
178 178
179 function guard<T>(fn: () => PromiseLike<T>) {
180 return fn();
181 }
182
183 179 if (data.$type) {
184 180 if (data.$type instanceof Function)
185 181 opts.type = data.$type;
@@ -202,7 +198,7 export class Container {
202 198 if (data.inject instanceof Array)
203 199 opts.inject = await Promise.all(data.inject.map(x => this._parseObject(x, resolver)));
204 200 else
205 opts.inject = this._parseObject(data.inject, resolver);
201 opts.inject = [await this._parseObject(data.inject, resolver)];
206 202
207 203 if (data.params)
208 204 opts.params = this._parse(data.params, resolver);
@@ -240,7 +236,7 export class Container {
240 236 return new ServiceDescriptor(opts);
241 237 }
242 238
243 _parseObject(data: any, typemap) {
239 _parseObject(data: object, resolver: ModuleResolverBase) {
244 240 if (data.constructor &&
245 241 data.constructor.prototype !== Object.prototype)
246 242 return new ValueDescriptor(data);
@@ -248,16 +244,16 export class Container {
248 244 const o = {};
249 245
250 246 for (const p in data)
251 o[p] = this._parse(data[p], typemap);
247 o[p] = this._parse(data[p], resolver);
252 248
253 249 return o;
254 250 }
255 251
256 _parseArray(data, typemap) {
252 _parseArray(data: Array<any>, resolver: ModuleResolverBase) {
257 253 if (data.constructor &&
258 254 data.constructor.prototype !== Array.prototype)
259 255 return new ValueDescriptor(data);
260 256
261 return data.map(x => this._parse(x, typemap));
257 return data.map(x => this._parse(x, resolver));
262 258 }
263 259 }
@@ -4,15 +4,15 import { ServiceMap, Descriptor } from "
4 4 import { ActivationError } from "./ActivationError";
5 5
6 6 export class ReferenceDescriptor implements Descriptor {
7 _name: string
7 _name: string;
8 8
9 _lazy = false
9 _lazy = false;
10 10
11 _optional = false
11 _optional = false;
12 12
13 _default: any
13 _default: any;
14 14
15 _services: ServiceMap
15 _services: ServiceMap;
16 16
17 17 constructor(name: string, lazy: boolean, optional: boolean, def, services: ServiceMap) {
18 18 argumentNotEmptyString(name, "name");
@@ -24,45 +24,51 export class ReferenceDescriptor impleme
24 24 }
25 25
26 26 activate(context: ActivationContext, name: string) {
27 var me = this;
28 27
29 context.enter(name, this, true);
28 if (this._lazy) {
29 // сохраняем контекст активации
30 context = context.clone();
30 31
31 32 // добавляем сервисы
32 if (me._services) {
33 for (var p in me._services) {
34 var sv = me._services[p];
35 context.register(p, sv);
36 }
33 if (this._services) {
34 for (const p of Object.keys(this._services))
35 context.register(p, this._services[p]);
37 36 }
38 37
39 if (me._lazy) {
40 // сохраняем контекст активации
41 context = context.clone();
42 return function (cfg: ServiceMap) {
38 return (cfg: ServiceMap) => {
43 39 // защищаем контекст на случай исключения в процессе
44 40 // активации
45 var ct = context.clone();
41 const ct = context.clone();
46 42 try {
47 if (cfg)
48 for(let k in cfg)
49 ct.register(k, cfg[v]);
43 if (cfg) {
44 for (const k in cfg)
45 ct.register(k, cfg[k]);
46 }
50 47
51 return me._optional ? ct.getService(me._name, me._default) : ct
52 .getService(me._name);
48 return this._optional ? ct.getService(this._name, this._default) : ct
49 .getService(this._name);
53 50 } catch (error) {
54 throw new ActivationError(me._name, ct.getStack(), error);
51 throw new ActivationError(this._name, ct.getStack(), error);
55 52 }
56 53 };
54 } else {
55 context.enter(name, this, !!this._services);
56
57 // добавляем сервисы
58 if (this._services) {
59 for (const p of Object.keys(this._services))
60 context.register(p, this._services[p]);
57 61 }
58 62
59 var v = me._optional ?
60 context.getService(me._name, me._default) :
61 context.getService(me._name);
63 const v = this._optional ?
64 context.getService(this._name, this._default) :
65 context.getService(this._name);
62 66
63 67 context.leave();
68
64 69 return v;
65 70 }
71 }
66 72
67 73 isInstanceCreated() {
68 74 return false;
@@ -73,13 +79,13 export class ReferenceDescriptor impleme
73 79 }
74 80
75 81 toString() {
76 var opts = [];
82 const opts = [];
77 83 if (this._optional)
78 84 opts.push("optional");
79 85 if (this._lazy)
80 86 opts.push("lazy");
81 87
82 var parts = [
88 const parts = [
83 89 "@ref "
84 90 ];
85 91 if (opts.length) {
@@ -97,4 +103,4 export class ReferenceDescriptor impleme
97 103
98 104 return parts.join("");
99 105 }
100 } No newline at end of file
106 }
@@ -1,8 +1,8
1 1 import { ActivationContext } from "./ActivationContext";
2 import { Descriptor, ActivationType, ServiceMap, Constructor, Factory } from "./interfaces";
2 import { Descriptor, ActivationType, ServiceMap } from "./interfaces";
3 3 import { Container } from "./Container";
4 import { argumentNotNull, isPrimitive, oid } from "../safe";
5 import { ClientResponse } from "http";
4 import { argumentNotNull, isPrimitive, oid, isPromise } from "../safe";
5 import { Constructor, Factory } from "../interfaces";
6 6
7 7 let cacheId = 0;
8 8
@@ -12,12 +12,12 function injectMethod(target, method, co
12 12 throw new Error("Method '" + method + "' not found");
13 13
14 14 if (args instanceof Array)
15 m.apply(target, context.parse(args, "." + method));
15 return m.apply(target, context.parse(args, "." + method));
16 16 else
17 m.call(target, context.parse(args, "." + method));
17 return m.call(target, context.parse(args, "." + method));
18 18 }
19 19
20 function makeClenupCallback(target, method: (instance) => void | string) {
20 function makeClenupCallback(target, method: ((instance) => void) | string) {
21 21 if (typeof (method) === "string") {
22 22 return () => {
23 23 target[method]();
@@ -29,26 +29,26 function makeClenupCallback(target, meth
29 29 }
30 30 }
31 31
32 export interface ServiceDescriptorParams<T = {}> {
32 export interface ServiceDescriptorParams {
33 33 activation?: ActivationType;
34 34
35 35 owner: Container;
36 36
37 type?: Constructor<T>;
37 type?: Constructor;
38 38
39 factory?: Factory<T>;
39 factory?: Factory;
40 40
41 41 params?;
42 42
43 inject?;
43 inject?: object[];
44 44
45 45 services?: ServiceMap;
46 46
47 cleanup?: (instance: T) => void | string;
47 cleanup?: ((x) => void) | string;
48 48 }
49 49
50 export class ServiceDescriptor<T = {}> implements Descriptor {
51 _instance: T = null;
50 export class ServiceDescriptor implements Descriptor {
51 _instance;
52 52
53 53 _hasInstance = false;
54 54
@@ -56,21 +56,21 export class ServiceDescriptor<T = {}> i
56 56
57 57 _services: ServiceMap;
58 58
59 _type: Constructor<T> = null;
59 _type: Constructor = null;
60 60
61 _factory: Factory<T> = null;
61 _factory: Factory = null;
62 62
63 63 _params;
64 64
65 _inject: Array<object>;
65 _inject: object[];
66 66
67 _cleanup: (instance: T) => void;
67 _cleanup: ((x) => void) | string;
68 68
69 69 _cacheId: any;
70 70
71 71 _owner: Container;
72 72
73 constructor(opts: ServiceDescriptorParams<T>) {
73 constructor(opts: ServiceDescriptorParams) {
74 74 argumentNotNull(opts, "opts");
75 75 argumentNotNull(opts.owner, "owner");
76 76
@@ -90,7 +90,7 export class ServiceDescriptor<T = {}> i
90 90 this._params = opts.params;
91 91
92 92 if (opts.inject)
93 this._inject = opts.inject instanceof Array ? opts.inject : [opts.inject];
93 this._inject = opts.inject;
94 94
95 95 if (opts.services)
96 96 this._services = opts.services;
@@ -219,9 +219,17 export class ServiceDescriptor<T = {}> i
219 219
220 220 if (!this._factory) {
221 221 const ctor = this._type;
222 if (this._params && this._params.length) {
222 223 this._factory = (...args) => {
223 return new ctor(...args);
224 const t = Object.create(ctor.prototype);
225 const inst = ctor.apply(t, args);
226 return isPrimitive(inst) ? t : inst;
224 227 };
228 } else {
229 this._factory = () => {
230 return new ctor();
231 };
232 }
225 233 }
226 234
227 235 if (this._params === undefined) {
@@ -1,23 +1,23
1 1 import { Descriptor } from "./interfaces";
2 2 import { ActivationContext } from "./ActivationContext";
3 3
4 export class ValueDescriptor<T> implements Descriptor {
5 _value: T
4 export class ValueDescriptor implements Descriptor {
5 _value;
6 6
7 constructor(value: T) {
7 constructor(value) {
8 8 this._value = value;
9 9 }
10 10
11 11 activate(context: ActivationContext, name: string) {
12 12 context.enter(name);
13 let v = this._value;
13 const v = this._value;
14 14 context.leave();
15 15 return v;
16 16 }
17 17 isInstanceCreated(): boolean {
18 18 return true;
19 19 }
20 getInstance(): T {
20 getInstance() {
21 21 return this._value;
22 22 }
23 } No newline at end of file
23 }
@@ -1,5 +1,6
1 1 import { isNull } from "../safe";
2 2 import { ActivationContext } from "./ActivationContext";
3 import { Constructor, Factory } from "../interfaces";
3 4
4 5 export interface Descriptor {
5 6 activate(context: ActivationContext, name?: string);
@@ -7,10 +8,6 export interface Descriptor {
7 8 getInstance();
8 9 }
9 10
10 export type Constructor<T = {}> = new (...args: any[]) => T;
11
12 export type Factory<T = {}> = (...args: any[]) => T;
13
14 11 export function isDescriptor(instance): instance is Descriptor {
15 12 return (!isNull(instance)) &&
16 13 ("activate" in instance);
@@ -1,3 +1,7
1 export type Constructor<T = {}> = new (...args: any[]) => T;
2
3 export type Factory<T = {}> = (...args: any[]) => T;
4
1 5 export interface IDestroyable {
2 6 destroy();
3 7 }
@@ -73,4 +77,4 export interface ICancellable {
73 77 export interface IObservable<T> {
74 78 on(next: (x:T) => void, error?: (e:any) => void, complete?:() => void): IDestroyable;
75 79 next(ct?: ICancellation) : Promise<T>;
76 } No newline at end of file
80 }
@@ -1,7 +1,7
1 1 let _nextOid = 0;
2 2 const _oid = Symbol("__oid");
3 3
4 export function oid(instance: object) {
4 export function oid(instance: object): string {
5 5 if (isNull(instance))
6 6 return null;
7 7
@@ -52,6 +52,10 export function isString(val) {
52 52 return typeof (val) === "string" || val instanceof String;
53 53 }
54 54
55 export function isPromise(val): val is PromiseLike<any> {
56 return "then" in val && val.then instanceof Function;
57 }
58
55 59 export function isNullOrEmptyString(str) {
56 60 if (str === null || str === undefined ||
57 61 ((typeof (str) === "string" || str instanceof String) && str.length === 0))
@@ -229,18 +233,17 export function pmap(items, cb) {
229 233 argumentNotNull(cb, "cb");
230 234
231 235 if (items && items.then instanceof Function)
232 return items.then(function (data) {
233 return pmap(data, cb);
234 });
236 return items.then(data => pmap(data, cb));
235 237
236 238 if (isNull(items) || !items.length)
237 239 return items;
238 240
239 var i = 0,
240 result = [];
241 let i = 0;
242 const result = [];
241 243
242 244 function next() {
243 var r, ri;
245 let r;
246 let ri;
244 247
245 248 function chain(x) {
246 249 result[ri] = x;
@@ -251,7 +254,7 export function pmap(items, cb) {
251 254 r = cb(items[i], i);
252 255 ri = i;
253 256 i++;
254 if (r && r.then) {
257 if (isPromise(r)) {
255 258 return r.then(chain);
256 259 } else {
257 260 result[ri] = r;
@@ -276,12 +279,10 export function pmap(items, cb) {
276 279 * обещание, либо первый элемент.
277 280 * @async
278 281 */
279 export function first(sequence: any, cb: Function, err: Function) {
282 export function first(sequence, cb: (x) => any, err: (x) => any) {
280 283 if (sequence) {
281 if (sequence.then instanceof Function) {
282 return sequence.then(function (res) {
283 return first(res, cb, err);
284 }, err);
284 if (isPromise(sequence)) {
285 return sequence.then(res => first(res, cb, err));
285 286 } else if (sequence && "length" in sequence) {
286 287 if (sequence.length === 0) {
287 288 if (err)
@@ -299,7 +300,7 export function first(sequence: any, cb:
299 300 throw new Error("The sequence is required");
300 301 }
301 302
302 export function destroy(d: any) {
303 if (d && 'destroy' in d)
303 export function destroy(d) {
304 if (d && "destroy" in d)
304 305 d.destroy();
305 } No newline at end of file
306 }
@@ -1,3 +1,3
1 //define(["./ActivatableTests", "./trace-test", "./TraceSourceTests", "./CancellationTests"]);
1 define(["./ActivatableTests", "./trace-test", "./TraceSourceTests", "./CancellationTests"]);
2 2 //define(["./CancellationTests"]);
3 define(["./ObservableTests"]); No newline at end of file
3 //define(["./ObservableTests"]); No newline at end of file
@@ -1,13 +1,13
1 import * as tape from 'tape';
2 import * as uuid from '@implab/core/Uuid';
1 import * as tape from "tape";
2 import { Uuid } from "@implab/core/Uuid";
3 3
4 tape('simple', function(t){
4 tape("simple", t => {
5 5 t.pass("sync assert");
6 6 setTimeout(() => {
7 7 t.pass("async assert");
8 t.comment(uuid());
9 t.ok(uuid() != uuid());
8 t.comment(Uuid());
9 t.ok(Uuid() !== Uuid());
10 10 // end should be called after the last assertion
11 11 t.end();
12 12 }, 100);
13 }); No newline at end of file
13 });
@@ -1,6 +1,6
1 1 {
2 2 "compilerOptions": {
3 "target": "es5",
3 "target": "es3",
4 4 "module": "amd",
5 5 "sourceMap": true,
6 6 "outDir" : "build/dist",
@@ -1,12 +1,12
1 1 {
2 2 "compilerOptions": {
3 "target": "es5",
3 "target": "es3",
4 4 "module": "amd",
5 5 "sourceMap": true,
6 6 "outDir" : "build/test",
7 7 "moduleResolution": "node",
8 8 "lib": [
9 "ES2015"
9 "es2015"
10 10 ]
11 11 },
12 12 "include" : [
General Comments 0
You need to be logged in to leave comments. Login now