2 * Copyright (c) 2019 The xterm.js authors. All rights reserved.
5 * This was heavily inspired from microsoft/vscode's dependency injection system (MIT).
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 *--------------------------------------------------------------------------------------------*/
12 import { IServiceIdentifier } from 'common/services/Services';
14 const DI_TARGET = 'di$target';
15 const DI_DEPENDENCIES = 'di$dependencies';
17 export const serviceRegistry: Map<string, IServiceIdentifier<any>> = new Map();
19 export function getServiceDependencies(ctor: any): { id: IServiceIdentifier<any>, index: number, optional: boolean }[] {
20 return ctor[DI_DEPENDENCIES] || [];
23 export function createDecorator<T>(id: string): IServiceIdentifier<T> {
24 if (serviceRegistry.has(id)) {
25 return serviceRegistry.get(id)!;
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');
33 storeServiceDependency(decorator, target, index);
36 decorator.toString = () => id;
38 serviceRegistry.set(id, decorator);
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 });
46 (target as any)[DI_DEPENDENCIES] = [{ id, index }];
47 (target as any)[DI_TARGET] = target;