| 1 |
/** |
| 2 |
* Copyright (c) 2019 The xterm.js authors. All rights reserved. |
| 3 |
* @license MIT |
| 4 |
* |
| 5 |
* This was heavily inspired from microsoft/vscode's dependency injection system (MIT). |
| 6 |
*/ |
| 7 |
/*--------------------------------------------------------------------------------------------- |
| 8 |
* Copyright (c) Microsoft Corporation. All rights reserved. |
| 9 |
* Licensed under the MIT License. See License.txt in the project root for license information. |
| 10 |
*--------------------------------------------------------------------------------------------*/ |
| 11 |
|
| 12 |
import { IServiceIdentifier } from 'common/services/Services'; |
| 13 |
|
| 14 |
const DI_TARGET = 'di$target'; |
| 15 |
const DI_DEPENDENCIES = 'di$dependencies'; |
| 16 |
|
| 17 |
export const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map(); |
| 18 |
|
| 19 |
export function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] { |
| 20 |
return ctor[DI_DEPENDENCIES] || []; |
| 21 |
} |
| 22 |
|
| 23 |
export function createDecorator<T>(id: string): IServiceIdentifier<T> { |
| 24 |
if (serviceRegistry.has(id)) { |
| 25 |
return serviceRegistry.get(id)!; |
| 26 |
} |
| 27 |
|
| 28 |
const decorator: any = function (target: Function, key: string, index: number): any { |
| 29 |
if (arguments.length !== 3) { |
| 30 |
throw new Error('@IServiceName-decorator can only be used to decorate a parameter'); |
| 31 |
} |
| 32 |
|
| 33 |
storeServiceDependency(decorator, target, index); |
| 34 |
}; |
| 35 |
|
| 36 |
decorator._id = id; |
| 37 |
|
| 38 |
serviceRegistry.set(id, decorator); |
| 39 |
return decorator; |
| 40 |
} |
| 41 |
|
| 42 |
function storeServiceDependency(id: Function, target: Function, index: number): void { |
| 43 |
if ((target as any)[DI_TARGET] === target) { |
| 44 |
(target as any)[DI_DEPENDENCIES].push({ id, index }); |
| 45 |
} else { |
| 46 |
(target as any)[DI_DEPENDENCIES] = [{ id, index }]; |
| 47 |
(target as any)[DI_TARGET] = target; |
| 48 |
} |
| 49 |
} |