@andrew_l/ioc 0.3.22 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +29 -27
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +88 -132
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -8
- package/dist/index.cjs +0 -170
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -44
- package/dist/index.d.ts +0 -44
package/dist/index.d.mts
CHANGED
|
@@ -1,37 +1,39 @@
|
|
|
1
|
-
import { AnyFunction } from
|
|
2
|
-
|
|
1
|
+
import { AnyFunction } from "@andrew_l/toolkit";
|
|
3
2
|
type Factory = any;
|
|
4
3
|
interface SetupOptions {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
4
|
+
pathRoot?: string;
|
|
5
|
+
/**
|
|
6
|
+
* Absolute or relative path where generated type file will be saved
|
|
7
|
+
*/
|
|
8
|
+
typeOutput?: string;
|
|
9
|
+
/**
|
|
10
|
+
* Absolute or relative glob patterns to auto-import service files
|
|
11
|
+
*/
|
|
12
|
+
autoImportPatterns?: string[];
|
|
13
|
+
/**
|
|
14
|
+
* Should generate type file
|
|
15
|
+
*/
|
|
16
|
+
generateTypes?: boolean;
|
|
18
17
|
}
|
|
19
18
|
declare const _default: {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
19
|
+
get<T>(id: string): T;
|
|
20
|
+
set(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean): void;
|
|
21
|
+
override(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean, constructorPath?: string): void;
|
|
22
|
+
isSet(id: string): boolean;
|
|
23
|
+
clear(): void;
|
|
24
|
+
setup({
|
|
25
|
+
pathRoot,
|
|
26
|
+
generateTypes,
|
|
27
|
+
autoImportPatterns,
|
|
28
|
+
typeOutput
|
|
29
|
+
}?: SetupOptions | undefined): Promise<void>;
|
|
30
|
+
importServices(autoImportPatterns: string[]): Promise<void>;
|
|
31
|
+
writeTypes(outputFilePath: string): Promise<void>;
|
|
28
32
|
};
|
|
29
|
-
|
|
30
33
|
/**
|
|
31
34
|
* This interface can be augmented by users to add types to ioc
|
|
32
35
|
*/
|
|
33
|
-
interface IocMap {
|
|
34
|
-
}
|
|
36
|
+
interface IocMap {}
|
|
35
37
|
/**
|
|
36
38
|
* Get instance of service
|
|
37
39
|
* @example
|
|
@@ -40,5 +42,5 @@ interface IocMap {
|
|
|
40
42
|
* @group Main
|
|
41
43
|
*/
|
|
42
44
|
declare function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
|
|
43
|
-
|
|
44
45
|
export { type IocMap, _default as ServiceContainer, ioc };
|
|
46
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["factory","Factory","constructorName","constructorPath","instance","pathRoot","typeOutput","autoImportPatterns","generateTypes","get","T","id","set","AnyFunction","factoryOrClassReference","buildInstantly","override","isSet","clear","setup","SetupOptions","Promise","importServices","writeTypes","outputFilePath","Key","IocMap","id"],"sources":["../src/ServiceContainer.d.ts","../src/ioc.d.ts"],"mappings":";KACY,OAAA;AAAA,UAOK,YAAA;EACbK,QAAAA;EADyB;;;EAKzBC,UAAAA;EAQAE;;AAAa;EAJbD,kBAAAA;EAeH;;;EAXGC,aAAAA;AAAAA;AAAAA,cAEU,QAAA;EACVC,GAAAA,IAAOE,EAAAA,WAAa,CAAA;EACpBC,GAAAA,CAAID,EAAAA,UAAYG,uBAAAA,EAAyB,OAAA,GAAU,WAAA,EAAaC,cAAAA;EAChEC,QAAAA,CAASL,EAAAA,UAAYG,uBAAAA,EAAyB,OAAA,GAAU,WAAA,EAAaC,cAAAA,YAA0BZ,eAAAA;EAC/Fc,KAAAA,CAAMN,EAAAA;EACNO,KAAAA;EACAC,KAAAA;IAAQd,QAAAA;IAAUG,aAAAA;IAAeD,kBAAAA;IAAoBD;EAAAA,IAAgB,YAAA,eAA2B,OAAA;EAChGgB,cAAAA,CAAef,kBAAAA,aAA+B,OAAA;EAC9CgB,UAAAA,CAAWC,cAAAA,WAAyB,OAAA;AAAA;;;AA9BxC;UCEU,MAAA;;ADFS;AAOnB;;;;;iBCIwB,GAAA,mBAAsB,MAAA,EAAQG,EAAAA,EAAI,GAAA,GAAM,MAAA,CAAO,GAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,96 +1,69 @@
|
|
|
1
|
-
import crypto from
|
|
2
|
-
import { globSync } from
|
|
3
|
-
import fs from
|
|
4
|
-
import path from
|
|
5
|
-
import {
|
|
6
|
-
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { globSync } from "node:fs";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { captureStackTrace, logger } from "@andrew_l/toolkit";
|
|
7
6
|
const storage = /* @__PURE__ */ new Map();
|
|
8
7
|
const log = logger("IOC");
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
await this.writeTypes(typeOutput);
|
|
69
|
-
}
|
|
70
|
-
},
|
|
71
|
-
async importServices(autoImportPatterns) {
|
|
72
|
-
for (const pattern of autoImportPatterns) {
|
|
73
|
-
for (const filePath of globSync(pattern)) {
|
|
74
|
-
await import(filePath);
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
},
|
|
78
|
-
async writeTypes(outputFilePath) {
|
|
79
|
-
const typesDefinitions = [];
|
|
80
|
-
const outputFolderPath = path.dirname(outputFilePath);
|
|
81
|
-
for (const [
|
|
82
|
-
key,
|
|
83
|
-
{ constructorName, constructorPath }
|
|
84
|
-
] of storage.entries()) {
|
|
85
|
-
if (!constructorName || !constructorPath) continue;
|
|
86
|
-
typesDefinitions.push(
|
|
87
|
-
`"${key}": import('./${path.relative(
|
|
88
|
-
outputFolderPath,
|
|
89
|
-
constructorPath
|
|
90
|
-
)}').${constructorName};`
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
const typesContent = `/* eslint-disable */
|
|
8
|
+
var ServiceContainer_default = {
|
|
9
|
+
get(id) {
|
|
10
|
+
const service = storage.get(id);
|
|
11
|
+
if (!service) throw new Error(`No service is registered for [${id}]`);
|
|
12
|
+
if (!service.instance) {
|
|
13
|
+
service.instance = service.factory?.();
|
|
14
|
+
service.factory = void 0;
|
|
15
|
+
}
|
|
16
|
+
return service.instance;
|
|
17
|
+
},
|
|
18
|
+
set(id, factoryOrClassReference, buildInstantly = false) {
|
|
19
|
+
if (this.isSet(id)) throw new Error(`Service [${id}] is already registered`);
|
|
20
|
+
let constructorPath;
|
|
21
|
+
try {
|
|
22
|
+
constructorPath = extractFilePathFromStack(captureStackTrace(this.set));
|
|
23
|
+
} catch (_) {}
|
|
24
|
+
this.override(id, factoryOrClassReference, buildInstantly, constructorPath);
|
|
25
|
+
},
|
|
26
|
+
override(id, factoryOrClassReference, buildInstantly = false, constructorPath) {
|
|
27
|
+
const factory = getFactory(factoryOrClassReference);
|
|
28
|
+
storage.set(id, {
|
|
29
|
+
factory: buildInstantly ? void 0 : factory,
|
|
30
|
+
instance: buildInstantly ? factory() : void 0,
|
|
31
|
+
constructorName: getConstructorName(factoryOrClassReference),
|
|
32
|
+
constructorPath
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
isSet(id) {
|
|
36
|
+
return storage.has(id);
|
|
37
|
+
},
|
|
38
|
+
clear() {
|
|
39
|
+
storage.clear();
|
|
40
|
+
},
|
|
41
|
+
async setup({ pathRoot = process.cwd(), generateTypes = false, autoImportPatterns = ["./services/*/**/*.service.{js,mjs,ts,mts,cts}"], typeOutput = "./ioc.d.ts" } = {}) {
|
|
42
|
+
typeOutput = path.isAbsolute(typeOutput) ? typeOutput : path.join(pathRoot, typeOutput);
|
|
43
|
+
if (!typeOutput.endsWith(".d.ts")) typeOutput = path.join(typeOutput, "ioc.d.ts");
|
|
44
|
+
autoImportPatterns = autoImportPatterns.map((servicePath) => {
|
|
45
|
+
return path.isAbsolute(servicePath) ? servicePath : path.join(pathRoot, servicePath);
|
|
46
|
+
});
|
|
47
|
+
log.debug("Setup", {
|
|
48
|
+
pathRoot,
|
|
49
|
+
generateTypes,
|
|
50
|
+
autoImportPatterns,
|
|
51
|
+
typeOutput
|
|
52
|
+
});
|
|
53
|
+
await this.importServices(autoImportPatterns);
|
|
54
|
+
if (generateTypes) await this.writeTypes(typeOutput);
|
|
55
|
+
},
|
|
56
|
+
async importServices(autoImportPatterns) {
|
|
57
|
+
for (const pattern of autoImportPatterns) for (const filePath of globSync(pattern)) await import(filePath);
|
|
58
|
+
},
|
|
59
|
+
async writeTypes(outputFilePath) {
|
|
60
|
+
const typesDefinitions = [];
|
|
61
|
+
const outputFolderPath = path.dirname(outputFilePath);
|
|
62
|
+
for (const [key, { constructorName, constructorPath }] of storage.entries()) {
|
|
63
|
+
if (!constructorName || !constructorPath) continue;
|
|
64
|
+
typesDefinitions.push(`"${key}": import('./${path.relative(outputFolderPath, constructorPath)}').${constructorName};`);
|
|
65
|
+
}
|
|
66
|
+
const typesContent = `/* eslint-disable */
|
|
94
67
|
/* prettier-ignore */
|
|
95
68
|
// @ts-nocheck
|
|
96
69
|
// Generated by @andrew_l/ioc
|
|
@@ -104,58 +77,41 @@ declare module '@andrew_l/ioc' {
|
|
|
104
77
|
|
|
105
78
|
function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
|
|
106
79
|
}`;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
`// hash:${newHash}
|
|
114
|
-
${typesContent}
|
|
115
|
-
`
|
|
116
|
-
);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
80
|
+
const newHash = crypto.createHmac("sha256", "").update(typesContent).digest("hex");
|
|
81
|
+
if (newHash !== await getHashFromTypeFile(outputFilePath)) {
|
|
82
|
+
log.warn("Types file has been updated.");
|
|
83
|
+
await fs.writeFile(outputFilePath, `// hash:${newHash}\n${typesContent}\n`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
119
86
|
};
|
|
120
87
|
function extractFilePathFromStack(stack) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
if (!result.startsWith("file://")) {
|
|
129
|
-
result = "file://" + result;
|
|
130
|
-
}
|
|
131
|
-
result = new URL(result).pathname.split(":")[0];
|
|
132
|
-
if (result.endsWith(".ts")) {
|
|
133
|
-
result = result.slice(0, -3) + ".js";
|
|
134
|
-
}
|
|
135
|
-
return result;
|
|
88
|
+
let result = stack.split("\n")[0].slice(7).replace("<anonymous>", "").trim();
|
|
89
|
+
if (result.startsWith("(")) result = result.slice(1);
|
|
90
|
+
if (result.endsWith(")")) result = result.slice(0, -1);
|
|
91
|
+
if (!result.startsWith("file://")) result = "file://" + result;
|
|
92
|
+
result = new URL(result).pathname.split(":")[0];
|
|
93
|
+
if (result.endsWith(".ts")) result = result.slice(0, -3) + ".js";
|
|
94
|
+
return result;
|
|
136
95
|
}
|
|
137
96
|
function isConstructable(obj) {
|
|
138
|
-
|
|
97
|
+
return !!obj.prototype && !!obj.prototype.constructor.name;
|
|
139
98
|
}
|
|
140
99
|
function getFactory(factoryOrClassReference) {
|
|
141
|
-
|
|
100
|
+
return isConstructable(factoryOrClassReference) ? () => new factoryOrClassReference() : factoryOrClassReference;
|
|
142
101
|
}
|
|
143
102
|
function getConstructorName(factoryOrClassReference) {
|
|
144
|
-
|
|
103
|
+
return isConstructable(factoryOrClassReference) ? factoryOrClassReference.prototype.constructor.name : String(factoryOrClassReference).match(/new\s(\w+)\(/)?.[1] || "";
|
|
145
104
|
}
|
|
146
105
|
async function getHashFromTypeFile(filePath) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
return null;
|
|
153
|
-
}
|
|
106
|
+
try {
|
|
107
|
+
return (await fs.readFile(filePath, { encoding: "utf8" })).split("\n").at(0)?.split("hash:")[1] || null;
|
|
108
|
+
} catch (_) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
154
111
|
}
|
|
155
|
-
|
|
156
112
|
function ioc(id) {
|
|
157
|
-
|
|
113
|
+
return ServiceContainer_default.get(id);
|
|
158
114
|
}
|
|
115
|
+
export { ServiceContainer_default as ServiceContainer, ioc };
|
|
159
116
|
|
|
160
|
-
|
|
161
|
-
//# sourceMappingURL=index.mjs.map
|
|
117
|
+
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/ServiceContainer.ts","../src/ioc.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport { globSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { type AnyFunction, captureStackTrace, logger } from '@andrew_l/toolkit';\n\nexport type Factory = any;\n\nexport type Service = {\n factory?: Factory;\n constructorName?: string;\n constructorPath?: string;\n instance: any;\n};\n\nexport interface SetupOptions {\n pathRoot?: string;\n\n /**\n * Absolute or relative path where generated type file will be saved\n */\n typeOutput?: string;\n\n /**\n * Absolute or relative glob patterns to auto-import service files\n */\n autoImportPatterns?: string[];\n\n /**\n * Should generate type file\n */\n generateTypes?: boolean;\n}\n\nconst storage = new Map<string, Service>();\n\nconst log = logger('IOC');\n\nexport default {\n get<T>(id: string): T {\n const service = storage.get(id);\n\n if (!service) {\n throw new Error(`No service is registered for [${id}]`);\n }\n\n if (!service.instance) {\n service.instance = service.factory?.();\n service.factory = undefined;\n }\n\n return service.instance;\n },\n\n set(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n ) {\n if (this.isSet(id)) {\n throw new Error(`Service [${id}] is already registered`);\n }\n\n let constructorPath: string | undefined;\n\n try {\n constructorPath = extractFilePathFromStack(captureStackTrace(this.set));\n } catch (_) {}\n\n this.override(id, factoryOrClassReference, buildInstantly, constructorPath);\n },\n\n override(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n constructorPath?: string,\n ) {\n const factory: Factory = getFactory(factoryOrClassReference);\n\n storage.set(id, {\n factory: buildInstantly ? undefined : factory,\n instance: buildInstantly ? factory() : undefined,\n constructorName: getConstructorName(factoryOrClassReference),\n constructorPath,\n });\n },\n\n isSet(id: string): boolean {\n return storage.has(id);\n },\n\n clear() {\n storage.clear();\n },\n\n async setup({\n pathRoot = process.cwd(),\n generateTypes = false,\n autoImportPatterns = ['./services/*/**/*.service.{js,mjs,ts,mts,cts}'],\n typeOutput = './ioc.d.ts',\n }: SetupOptions | undefined = {}) {\n typeOutput = path.isAbsolute(typeOutput)\n ? typeOutput\n : path.join(pathRoot, typeOutput);\n\n if (!typeOutput.endsWith('.d.ts')) {\n typeOutput = path.join(typeOutput, 'ioc.d.ts');\n }\n\n autoImportPatterns = autoImportPatterns.map(servicePath => {\n return path.isAbsolute(servicePath)\n ? servicePath\n : path.join(pathRoot, servicePath);\n });\n\n log.debug('Setup', {\n pathRoot,\n generateTypes,\n autoImportPatterns,\n typeOutput,\n });\n\n await this.importServices(autoImportPatterns);\n\n if (generateTypes) {\n await this.writeTypes(typeOutput);\n }\n },\n\n async importServices(autoImportPatterns: string[]) {\n for (const pattern of autoImportPatterns) {\n for (const filePath of globSync(pattern)) {\n await import(filePath);\n }\n }\n },\n\n async writeTypes(outputFilePath: string) {\n const typesDefinitions: string[] = [];\n const outputFolderPath = path.dirname(outputFilePath);\n\n for (const [\n key,\n { constructorName, constructorPath },\n ] of storage.entries()) {\n if (!constructorName || !constructorPath) continue;\n\n typesDefinitions.push(\n `\"${key}\": import('./${path.relative(\n outputFolderPath,\n constructorPath,\n )}').${constructorName};`,\n );\n }\n\n const typesContent = `/* eslint-disable */\n/* prettier-ignore */\n// @ts-nocheck\n// Generated by @andrew_l/ioc\n\nexport {};\n\ndeclare module '@andrew_l/ioc' {\n\tinterface IocMap {\n\t\t${typesDefinitions.sort().join('\\n\\t\\t')}\n\t}\n\n\tfunction ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];\n}`;\n\n const newHash = crypto\n .createHmac('sha256', '')\n .update(typesContent)\n .digest('hex');\n\n const oldHash = await getHashFromTypeFile(outputFilePath);\n\n if (newHash !== oldHash) {\n log.warn('Types file has been updated.');\n\n await fs.writeFile(\n outputFilePath,\n `// hash:${newHash}\\n${typesContent}\\n`,\n );\n }\n },\n};\n\nfunction extractFilePathFromStack(stack: string): string {\n let result = stack.split('\\n')[0].slice(7).replace('<anonymous>', '').trim();\n\n if (result.startsWith('(')) {\n result = result.slice(1);\n }\n\n if (result.endsWith(')')) {\n result = result.slice(0, -1);\n }\n\n if (!result.startsWith('file://')) {\n result = 'file://' + result;\n }\n\n result = new URL(result).pathname.split(':')[0];\n\n if (result.endsWith('.ts')) {\n result = result.slice(0, -3) + '.js';\n }\n return result;\n}\n\nfunction isConstructable(obj: any): obj is Function {\n // https://stackoverflow.com/a/46320004\n return !!obj.prototype && !!obj.prototype.constructor.name;\n}\n\nfunction getFactory(factoryOrClassReference: Factory | AnyFunction): Factory {\n return isConstructable(factoryOrClassReference)\n ? () => new factoryOrClassReference()\n : factoryOrClassReference;\n}\n\nfunction getConstructorName(\n factoryOrClassReference: Factory | AnyFunction,\n): string {\n return isConstructable(factoryOrClassReference)\n ? factoryOrClassReference.prototype.constructor.name\n : String(factoryOrClassReference).match(/new\\s(\\w+)\\(/)?.[1] || '';\n}\n\nasync function getHashFromTypeFile(filePath: string): Promise<string | null> {\n try {\n const content = await fs.readFile(filePath, { encoding: 'utf8' });\n const lastLine = content.split('\\n').at(0);\n\n return lastLine?.split('hash:')[1] || null;\n } catch (_) {\n return null;\n }\n}\n","import ServiceContainer from './ServiceContainer';\n\n/**\n * This interface can be augmented by users to add types to ioc\n */\ninterface IocMap {}\n\n/**\n * Get instance of service\n * @example\n * const userService ioc('UserService');\n *\n * @group Main\n */\nexport function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key] {\n return ServiceContainer.get(id as any) as any;\n}\nexport type { IocMap };\n"],"names":[],"mappings":";;;;;;AAmCA,MAAM,OAAA,uBAAc,GAAA,EAAqB;AAEzC,MAAM,GAAA,GAAM,OAAO,KAAK,CAAA;AAExB,yBAAe;AAAA,EACb,IAAO,EAAA,EAAe;AACpB,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA;AAE9B,IAAA,IAAI,CAAC,OAAA,EAAS;AACZ,MAAA,MAAM,IAAI,KAAA,CAAM,CAA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A,GAAI,CAAC,CAAA,IAAK,EAAA;AACpE;AAEA,eAAe,oBAAoB,QAAA,EAA0C;AAC3E,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAU,MAAM,EAAA,CAAG,QAAA,CAAS,UAAU,EAAE,QAAA,EAAU,QAAQ,CAAA;AAChE,IAAA,MAAM,WAAW,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,GAAG,CAAC,CAAA;AAEzC,IAAA,OAAO,QAAA,EAAU,KAAA,CAAM,OAAO,CAAA,CAAE,CAAC,CAAA,IAAK,IAAA;AAAA,EACxC,SAAS,CAAA,EAAG;AACV,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;ACnOO,SAAS,IAA8B,EAAA,EAAsB;AAClE,EAAA,OAAO,gBAAA,CAAiB,IAAI,EAAS,CAAA;AACvC;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["ServiceContainer"],"sources":["../src/ServiceContainer.ts","../src/ioc.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport { globSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { type AnyFunction, captureStackTrace, logger } from '@andrew_l/toolkit';\n\nexport type Factory = any;\n\nexport type Service = {\n factory?: Factory;\n constructorName?: string;\n constructorPath?: string;\n instance: any;\n};\n\nexport interface SetupOptions {\n pathRoot?: string;\n\n /**\n * Absolute or relative path where generated type file will be saved\n */\n typeOutput?: string;\n\n /**\n * Absolute or relative glob patterns to auto-import service files\n */\n autoImportPatterns?: string[];\n\n /**\n * Should generate type file\n */\n generateTypes?: boolean;\n}\n\nconst storage = new Map<string, Service>();\n\nconst log = logger('IOC');\n\nexport default {\n get<T>(id: string): T {\n const service = storage.get(id);\n\n if (!service) {\n throw new Error(`No service is registered for [${id}]`);\n }\n\n if (!service.instance) {\n service.instance = service.factory?.();\n service.factory = undefined;\n }\n\n return service.instance;\n },\n\n set(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n ) {\n if (this.isSet(id)) {\n throw new Error(`Service [${id}] is already registered`);\n }\n\n let constructorPath: string | undefined;\n\n try {\n constructorPath = extractFilePathFromStack(captureStackTrace(this.set));\n } catch (_) {}\n\n this.override(id, factoryOrClassReference, buildInstantly, constructorPath);\n },\n\n override(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n constructorPath?: string,\n ) {\n const factory: Factory = getFactory(factoryOrClassReference);\n\n storage.set(id, {\n factory: buildInstantly ? undefined : factory,\n instance: buildInstantly ? factory() : undefined,\n constructorName: getConstructorName(factoryOrClassReference),\n constructorPath,\n });\n },\n\n isSet(id: string): boolean {\n return storage.has(id);\n },\n\n clear() {\n storage.clear();\n },\n\n async setup({\n pathRoot = process.cwd(),\n generateTypes = false,\n autoImportPatterns = ['./services/*/**/*.service.{js,mjs,ts,mts,cts}'],\n typeOutput = './ioc.d.ts',\n }: SetupOptions | undefined = {}) {\n typeOutput = path.isAbsolute(typeOutput)\n ? typeOutput\n : path.join(pathRoot, typeOutput);\n\n if (!typeOutput.endsWith('.d.ts')) {\n typeOutput = path.join(typeOutput, 'ioc.d.ts');\n }\n\n autoImportPatterns = autoImportPatterns.map(servicePath => {\n return path.isAbsolute(servicePath)\n ? servicePath\n : path.join(pathRoot, servicePath);\n });\n\n log.debug('Setup', {\n pathRoot,\n generateTypes,\n autoImportPatterns,\n typeOutput,\n });\n\n await this.importServices(autoImportPatterns);\n\n if (generateTypes) {\n await this.writeTypes(typeOutput);\n }\n },\n\n async importServices(autoImportPatterns: string[]) {\n for (const pattern of autoImportPatterns) {\n for (const filePath of globSync(pattern)) {\n await import(filePath);\n }\n }\n },\n\n async writeTypes(outputFilePath: string) {\n const typesDefinitions: string[] = [];\n const outputFolderPath = path.dirname(outputFilePath);\n\n for (const [\n key,\n { constructorName, constructorPath },\n ] of storage.entries()) {\n if (!constructorName || !constructorPath) continue;\n\n typesDefinitions.push(\n `\"${key}\": import('./${path.relative(\n outputFolderPath,\n constructorPath,\n )}').${constructorName};`,\n );\n }\n\n const typesContent = `/* eslint-disable */\n/* prettier-ignore */\n// @ts-nocheck\n// Generated by @andrew_l/ioc\n\nexport {};\n\ndeclare module '@andrew_l/ioc' {\n\tinterface IocMap {\n\t\t${typesDefinitions.sort().join('\\n\\t\\t')}\n\t}\n\n\tfunction ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];\n}`;\n\n const newHash = crypto\n .createHmac('sha256', '')\n .update(typesContent)\n .digest('hex');\n\n const oldHash = await getHashFromTypeFile(outputFilePath);\n\n if (newHash !== oldHash) {\n log.warn('Types file has been updated.');\n\n await fs.writeFile(\n outputFilePath,\n `// hash:${newHash}\\n${typesContent}\\n`,\n );\n }\n },\n};\n\nfunction extractFilePathFromStack(stack: string): string {\n let result = stack.split('\\n')[0].slice(7).replace('<anonymous>', '').trim();\n\n if (result.startsWith('(')) {\n result = result.slice(1);\n }\n\n if (result.endsWith(')')) {\n result = result.slice(0, -1);\n }\n\n if (!result.startsWith('file://')) {\n result = 'file://' + result;\n }\n\n result = new URL(result).pathname.split(':')[0];\n\n if (result.endsWith('.ts')) {\n result = result.slice(0, -3) + '.js';\n }\n return result;\n}\n\nfunction isConstructable(obj: any): obj is Function {\n // https://stackoverflow.com/a/46320004\n return !!obj.prototype && !!obj.prototype.constructor.name;\n}\n\nfunction getFactory(factoryOrClassReference: Factory | AnyFunction): Factory {\n return isConstructable(factoryOrClassReference)\n ? () => new factoryOrClassReference()\n : factoryOrClassReference;\n}\n\nfunction getConstructorName(\n factoryOrClassReference: Factory | AnyFunction,\n): string {\n return isConstructable(factoryOrClassReference)\n ? factoryOrClassReference.prototype.constructor.name\n : String(factoryOrClassReference).match(/new\\s(\\w+)\\(/)?.[1] || '';\n}\n\nasync function getHashFromTypeFile(filePath: string): Promise<string | null> {\n try {\n const content = await fs.readFile(filePath, { encoding: 'utf8' });\n const lastLine = content.split('\\n').at(0);\n\n return lastLine?.split('hash:')[1] || null;\n } catch (_) {\n return null;\n }\n}\n","import ServiceContainer from './ServiceContainer';\n\n/**\n * This interface can be augmented by users to add types to ioc\n */\ninterface IocMap {}\n\n/**\n * Get instance of service\n * @example\n * const userService ioc('UserService');\n *\n * @group Main\n */\nexport function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key] {\n return ServiceContainer.get(id as any) as any;\n}\nexport type { IocMap };\n"],"mappings":";;;;;AAmCA,MAAM,0BAAU,IAAI,IAAqB;AAEzC,MAAM,MAAM,OAAO,KAAK;AAExB,IAAA,2BAAe;CACb,IAAO,IAAe;EACpB,MAAM,UAAU,QAAQ,IAAI,EAAE;EAE9B,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,iCAAiC,GAAG,EAAE;EAGxD,IAAI,CAAC,QAAQ,UAAU;GACrB,QAAQ,WAAW,QAAQ,UAAU;GACrC,QAAQ,UAAU,KAAA;EACpB;EAEA,OAAO,QAAQ;CACjB;CAEA,IACE,IACA,yBACA,iBAA0B,OAC1B;EACA,IAAI,KAAK,MAAM,EAAE,GACf,MAAM,IAAI,MAAM,YAAY,GAAG,wBAAwB;EAGzD,IAAI;EAEJ,IAAI;GACF,kBAAkB,yBAAyB,kBAAkB,KAAK,GAAG,CAAC;EACxE,SAAS,GAAG,CAAC;EAEb,KAAK,SAAS,IAAI,yBAAyB,gBAAgB,eAAe;CAC5E;CAEA,SACE,IACA,yBACA,iBAA0B,OAC1B,iBACA;EACA,MAAM,UAAmB,WAAW,uBAAuB;EAE3D,QAAQ,IAAI,IAAI;GACd,SAAS,iBAAiB,KAAA,IAAY;GACtC,UAAU,iBAAiB,QAAQ,IAAI,KAAA;GACvC,iBAAiB,mBAAmB,uBAAuB;GAC3D;EACF,CAAC;CACH;CAEA,MAAM,IAAqB;EACzB,OAAO,QAAQ,IAAI,EAAE;CACvB;CAEA,QAAQ;EACN,QAAQ,MAAM;CAChB;CAEA,MAAM,MAAM,EACV,WAAW,QAAQ,IAAI,GACvB,gBAAgB,OAChB,qBAAqB,CAAC,+CAA+C,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E,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,eAAe,EAAE,CAAC,CAAC,KAAK;CAE3E,IAAI,OAAO,WAAW,GAAG,GACvB,SAAS,OAAO,MAAM,CAAC;CAGzB,IAAI,OAAO,SAAS,GAAG,GACrB,SAAS,OAAO,MAAM,GAAG,EAAE;CAG7B,IAAI,CAAC,OAAO,WAAW,SAAS,GAC9B,SAAS,YAAY;CAGvB,SAAS,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC;CAE7C,IAAI,OAAO,SAAS,KAAK,GACvB,SAAS,OAAO,MAAM,GAAG,EAAE,IAAI;CAEjC,OAAO;AACT;AAEA,SAAS,gBAAgB,KAA2B;CAElD,OAAO,CAAC,CAAC,IAAI,aAAa,CAAC,CAAC,IAAI,UAAU,YAAY;AACxD;AAEA,SAAS,WAAW,yBAAyD;CAC3E,OAAO,gBAAgB,uBAAuB,UACpC,IAAI,wBAAwB,IAClC;AACN;AAEA,SAAS,mBACP,yBACQ;CACR,OAAO,gBAAgB,uBAAuB,IAC1C,wBAAwB,UAAU,YAAY,OAC9C,OAAO,uBAAuB,CAAC,CAAC,MAAM,cAAc,CAAC,GAAG,MAAM;AACpE;AAEA,eAAe,oBAAoB,UAA0C;CAC3E,IAAI;EAIF,QAFiB,MADK,GAAG,SAAS,UAAU,EAAE,UAAU,OAAO,CAAC,EAAA,CACvC,MAAM,IAAI,CAAC,CAAC,GAAG,CAE1B,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC,MAAM;CACxC,SAAS,GAAG;EACV,OAAO;CACT;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrew_l/ioc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Pretty simple IOC Container.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -19,26 +19,27 @@
|
|
|
19
19
|
"exports": {
|
|
20
20
|
".": {
|
|
21
21
|
"import": "./dist/index.mjs",
|
|
22
|
-
"require": "./dist/index.
|
|
22
|
+
"require": "./dist/index.mjs",
|
|
23
|
+
"types": "./dist/index.d.mts"
|
|
23
24
|
}
|
|
24
25
|
},
|
|
25
|
-
"main": "./dist/index.
|
|
26
|
-
"types": "./dist/index.d.
|
|
26
|
+
"main": "./dist/index.mjs",
|
|
27
|
+
"types": "./dist/index.d.mts",
|
|
27
28
|
"files": [
|
|
28
29
|
"dist"
|
|
29
30
|
],
|
|
30
31
|
"devDependencies": {
|
|
31
32
|
"@types/node": "22.10.5",
|
|
32
|
-
"
|
|
33
|
-
"
|
|
33
|
+
"obuild": "^0.4.37",
|
|
34
|
+
"typescript": "6.0.3",
|
|
34
35
|
"vitest": "^3.2.4"
|
|
35
36
|
},
|
|
36
37
|
"dependencies": {
|
|
37
|
-
"@andrew_l/toolkit": "0.
|
|
38
|
+
"@andrew_l/toolkit": "0.4.1"
|
|
38
39
|
},
|
|
39
40
|
"scripts": {
|
|
40
41
|
"check-types": "tsc --noEmit",
|
|
41
|
-
"build": "
|
|
42
|
+
"build": "obuild",
|
|
42
43
|
"test": "echo todo",
|
|
43
44
|
"test:watch": "vitest watch --typecheck"
|
|
44
45
|
}
|
package/dist/index.cjs
DELETED
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const crypto = require('node:crypto');
|
|
4
|
-
const node_fs = require('node:fs');
|
|
5
|
-
const fs = require('node:fs/promises');
|
|
6
|
-
const path = require('node:path');
|
|
7
|
-
const toolkit = require('@andrew_l/toolkit');
|
|
8
|
-
|
|
9
|
-
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
10
|
-
|
|
11
|
-
const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto);
|
|
12
|
-
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
|
|
13
|
-
const path__default = /*#__PURE__*/_interopDefaultCompat(path);
|
|
14
|
-
|
|
15
|
-
const storage = /* @__PURE__ */ new Map();
|
|
16
|
-
const log = toolkit.logger("IOC");
|
|
17
|
-
const ServiceContainer = {
|
|
18
|
-
get(id) {
|
|
19
|
-
const service = storage.get(id);
|
|
20
|
-
if (!service) {
|
|
21
|
-
throw new Error(`No service is registered for [${id}]`);
|
|
22
|
-
}
|
|
23
|
-
if (!service.instance) {
|
|
24
|
-
service.instance = service.factory?.();
|
|
25
|
-
service.factory = void 0;
|
|
26
|
-
}
|
|
27
|
-
return service.instance;
|
|
28
|
-
},
|
|
29
|
-
set(id, factoryOrClassReference, buildInstantly = false) {
|
|
30
|
-
if (this.isSet(id)) {
|
|
31
|
-
throw new Error(`Service [${id}] is already registered`);
|
|
32
|
-
}
|
|
33
|
-
let constructorPath;
|
|
34
|
-
try {
|
|
35
|
-
constructorPath = extractFilePathFromStack(toolkit.captureStackTrace(this.set));
|
|
36
|
-
} catch (_) {
|
|
37
|
-
}
|
|
38
|
-
this.override(id, factoryOrClassReference, buildInstantly, constructorPath);
|
|
39
|
-
},
|
|
40
|
-
override(id, factoryOrClassReference, buildInstantly = false, constructorPath) {
|
|
41
|
-
const factory = getFactory(factoryOrClassReference);
|
|
42
|
-
storage.set(id, {
|
|
43
|
-
factory: buildInstantly ? void 0 : factory,
|
|
44
|
-
instance: buildInstantly ? factory() : void 0,
|
|
45
|
-
constructorName: getConstructorName(factoryOrClassReference),
|
|
46
|
-
constructorPath
|
|
47
|
-
});
|
|
48
|
-
},
|
|
49
|
-
isSet(id) {
|
|
50
|
-
return storage.has(id);
|
|
51
|
-
},
|
|
52
|
-
clear() {
|
|
53
|
-
storage.clear();
|
|
54
|
-
},
|
|
55
|
-
async setup({
|
|
56
|
-
pathRoot = process.cwd(),
|
|
57
|
-
generateTypes = false,
|
|
58
|
-
autoImportPatterns = ["./services/*/**/*.service.{js,mjs,ts,mts,cts}"],
|
|
59
|
-
typeOutput = "./ioc.d.ts"
|
|
60
|
-
} = {}) {
|
|
61
|
-
typeOutput = path__default.isAbsolute(typeOutput) ? typeOutput : path__default.join(pathRoot, typeOutput);
|
|
62
|
-
if (!typeOutput.endsWith(".d.ts")) {
|
|
63
|
-
typeOutput = path__default.join(typeOutput, "ioc.d.ts");
|
|
64
|
-
}
|
|
65
|
-
autoImportPatterns = autoImportPatterns.map((servicePath) => {
|
|
66
|
-
return path__default.isAbsolute(servicePath) ? servicePath : path__default.join(pathRoot, servicePath);
|
|
67
|
-
});
|
|
68
|
-
log.debug("Setup", {
|
|
69
|
-
pathRoot,
|
|
70
|
-
generateTypes,
|
|
71
|
-
autoImportPatterns,
|
|
72
|
-
typeOutput
|
|
73
|
-
});
|
|
74
|
-
await this.importServices(autoImportPatterns);
|
|
75
|
-
if (generateTypes) {
|
|
76
|
-
await this.writeTypes(typeOutput);
|
|
77
|
-
}
|
|
78
|
-
},
|
|
79
|
-
async importServices(autoImportPatterns) {
|
|
80
|
-
for (const pattern of autoImportPatterns) {
|
|
81
|
-
for (const filePath of node_fs.globSync(pattern)) {
|
|
82
|
-
await import(filePath);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
},
|
|
86
|
-
async writeTypes(outputFilePath) {
|
|
87
|
-
const typesDefinitions = [];
|
|
88
|
-
const outputFolderPath = path__default.dirname(outputFilePath);
|
|
89
|
-
for (const [
|
|
90
|
-
key,
|
|
91
|
-
{ constructorName, constructorPath }
|
|
92
|
-
] of storage.entries()) {
|
|
93
|
-
if (!constructorName || !constructorPath) continue;
|
|
94
|
-
typesDefinitions.push(
|
|
95
|
-
`"${key}": import('./${path__default.relative(
|
|
96
|
-
outputFolderPath,
|
|
97
|
-
constructorPath
|
|
98
|
-
)}').${constructorName};`
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
|
-
const typesContent = `/* eslint-disable */
|
|
102
|
-
/* prettier-ignore */
|
|
103
|
-
// @ts-nocheck
|
|
104
|
-
// Generated by @andrew_l/ioc
|
|
105
|
-
|
|
106
|
-
export {};
|
|
107
|
-
|
|
108
|
-
declare module '@andrew_l/ioc' {
|
|
109
|
-
interface IocMap {
|
|
110
|
-
${typesDefinitions.sort().join("\n ")}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
|
|
114
|
-
}`;
|
|
115
|
-
const newHash = crypto__default.createHmac("sha256", "").update(typesContent).digest("hex");
|
|
116
|
-
const oldHash = await getHashFromTypeFile(outputFilePath);
|
|
117
|
-
if (newHash !== oldHash) {
|
|
118
|
-
log.warn("Types file has been updated.");
|
|
119
|
-
await fs__default.writeFile(
|
|
120
|
-
outputFilePath,
|
|
121
|
-
`// hash:${newHash}
|
|
122
|
-
${typesContent}
|
|
123
|
-
`
|
|
124
|
-
);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
function extractFilePathFromStack(stack) {
|
|
129
|
-
let result = stack.split("\n")[0].slice(7).replace("<anonymous>", "").trim();
|
|
130
|
-
if (result.startsWith("(")) {
|
|
131
|
-
result = result.slice(1);
|
|
132
|
-
}
|
|
133
|
-
if (result.endsWith(")")) {
|
|
134
|
-
result = result.slice(0, -1);
|
|
135
|
-
}
|
|
136
|
-
if (!result.startsWith("file://")) {
|
|
137
|
-
result = "file://" + result;
|
|
138
|
-
}
|
|
139
|
-
result = new URL(result).pathname.split(":")[0];
|
|
140
|
-
if (result.endsWith(".ts")) {
|
|
141
|
-
result = result.slice(0, -3) + ".js";
|
|
142
|
-
}
|
|
143
|
-
return result;
|
|
144
|
-
}
|
|
145
|
-
function isConstructable(obj) {
|
|
146
|
-
return !!obj.prototype && !!obj.prototype.constructor.name;
|
|
147
|
-
}
|
|
148
|
-
function getFactory(factoryOrClassReference) {
|
|
149
|
-
return isConstructable(factoryOrClassReference) ? () => new factoryOrClassReference() : factoryOrClassReference;
|
|
150
|
-
}
|
|
151
|
-
function getConstructorName(factoryOrClassReference) {
|
|
152
|
-
return isConstructable(factoryOrClassReference) ? factoryOrClassReference.prototype.constructor.name : String(factoryOrClassReference).match(/new\s(\w+)\(/)?.[1] || "";
|
|
153
|
-
}
|
|
154
|
-
async function getHashFromTypeFile(filePath) {
|
|
155
|
-
try {
|
|
156
|
-
const content = await fs__default.readFile(filePath, { encoding: "utf8" });
|
|
157
|
-
const lastLine = content.split("\n").at(0);
|
|
158
|
-
return lastLine?.split("hash:")[1] || null;
|
|
159
|
-
} catch (_) {
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function ioc(id) {
|
|
165
|
-
return ServiceContainer.get(id);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
exports.ServiceContainer = ServiceContainer;
|
|
169
|
-
exports.ioc = ioc;
|
|
170
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/ServiceContainer.ts","../src/ioc.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport { globSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { type AnyFunction, captureStackTrace, logger } from '@andrew_l/toolkit';\n\nexport type Factory = any;\n\nexport type Service = {\n factory?: Factory;\n constructorName?: string;\n constructorPath?: string;\n instance: any;\n};\n\nexport interface SetupOptions {\n pathRoot?: string;\n\n /**\n * Absolute or relative path where generated type file will be saved\n */\n typeOutput?: string;\n\n /**\n * Absolute or relative glob patterns to auto-import service files\n */\n autoImportPatterns?: string[];\n\n /**\n * Should generate type file\n */\n generateTypes?: boolean;\n}\n\nconst storage = new Map<string, Service>();\n\nconst log = logger('IOC');\n\nexport default {\n get<T>(id: string): T {\n const service = storage.get(id);\n\n if (!service) {\n throw new Error(`No service is registered for [${id}]`);\n }\n\n if (!service.instance) {\n service.instance = service.factory?.();\n service.factory = undefined;\n }\n\n return service.instance;\n },\n\n set(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n ) {\n if (this.isSet(id)) {\n throw new Error(`Service [${id}] is already registered`);\n }\n\n let constructorPath: string | undefined;\n\n try {\n constructorPath = extractFilePathFromStack(captureStackTrace(this.set));\n } catch (_) {}\n\n this.override(id, factoryOrClassReference, buildInstantly, constructorPath);\n },\n\n override(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n constructorPath?: string,\n ) {\n const factory: Factory = getFactory(factoryOrClassReference);\n\n storage.set(id, {\n factory: buildInstantly ? undefined : factory,\n instance: buildInstantly ? factory() : undefined,\n constructorName: getConstructorName(factoryOrClassReference),\n constructorPath,\n });\n },\n\n isSet(id: string): boolean {\n return storage.has(id);\n },\n\n clear() {\n storage.clear();\n },\n\n async setup({\n pathRoot = process.cwd(),\n generateTypes = false,\n autoImportPatterns = ['./services/*/**/*.service.{js,mjs,ts,mts,cts}'],\n typeOutput = './ioc.d.ts',\n }: SetupOptions | undefined = {}) {\n typeOutput = path.isAbsolute(typeOutput)\n ? typeOutput\n : path.join(pathRoot, typeOutput);\n\n if (!typeOutput.endsWith('.d.ts')) {\n typeOutput = path.join(typeOutput, 'ioc.d.ts');\n }\n\n autoImportPatterns = autoImportPatterns.map(servicePath => {\n return path.isAbsolute(servicePath)\n ? servicePath\n : path.join(pathRoot, servicePath);\n });\n\n log.debug('Setup', {\n pathRoot,\n generateTypes,\n autoImportPatterns,\n typeOutput,\n });\n\n await this.importServices(autoImportPatterns);\n\n if (generateTypes) {\n await this.writeTypes(typeOutput);\n }\n },\n\n async importServices(autoImportPatterns: string[]) {\n for (const pattern of autoImportPatterns) {\n for (const filePath of globSync(pattern)) {\n await import(filePath);\n }\n }\n },\n\n async writeTypes(outputFilePath: string) {\n const typesDefinitions: string[] = [];\n const outputFolderPath = path.dirname(outputFilePath);\n\n for (const [\n key,\n { constructorName, constructorPath },\n ] of storage.entries()) {\n if (!constructorName || !constructorPath) continue;\n\n typesDefinitions.push(\n `\"${key}\": import('./${path.relative(\n outputFolderPath,\n constructorPath,\n )}').${constructorName};`,\n );\n }\n\n const typesContent = `/* eslint-disable */\n/* prettier-ignore */\n// @ts-nocheck\n// Generated by @andrew_l/ioc\n\nexport {};\n\ndeclare module '@andrew_l/ioc' {\n\tinterface IocMap {\n\t\t${typesDefinitions.sort().join('\\n\\t\\t')}\n\t}\n\n\tfunction ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];\n}`;\n\n const newHash = crypto\n .createHmac('sha256', '')\n .update(typesContent)\n .digest('hex');\n\n const oldHash = await getHashFromTypeFile(outputFilePath);\n\n if (newHash !== oldHash) {\n log.warn('Types file has been updated.');\n\n await fs.writeFile(\n outputFilePath,\n `// hash:${newHash}\\n${typesContent}\\n`,\n );\n }\n },\n};\n\nfunction extractFilePathFromStack(stack: string): string {\n let result = stack.split('\\n')[0].slice(7).replace('<anonymous>', '').trim();\n\n if (result.startsWith('(')) {\n result = result.slice(1);\n }\n\n if (result.endsWith(')')) {\n result = result.slice(0, -1);\n }\n\n if (!result.startsWith('file://')) {\n result = 'file://' + result;\n }\n\n result = new URL(result).pathname.split(':')[0];\n\n if (result.endsWith('.ts')) {\n result = result.slice(0, -3) + '.js';\n }\n return result;\n}\n\nfunction isConstructable(obj: any): obj is Function {\n // https://stackoverflow.com/a/46320004\n return !!obj.prototype && !!obj.prototype.constructor.name;\n}\n\nfunction getFactory(factoryOrClassReference: Factory | AnyFunction): Factory {\n return isConstructable(factoryOrClassReference)\n ? () => new factoryOrClassReference()\n : factoryOrClassReference;\n}\n\nfunction getConstructorName(\n factoryOrClassReference: Factory | AnyFunction,\n): string {\n return isConstructable(factoryOrClassReference)\n ? factoryOrClassReference.prototype.constructor.name\n : String(factoryOrClassReference).match(/new\\s(\\w+)\\(/)?.[1] || '';\n}\n\nasync function getHashFromTypeFile(filePath: string): Promise<string | null> {\n try {\n const content = await fs.readFile(filePath, { encoding: 'utf8' });\n const lastLine = content.split('\\n').at(0);\n\n return lastLine?.split('hash:')[1] || null;\n } catch (_) {\n return null;\n }\n}\n","import ServiceContainer from './ServiceContainer';\n\n/**\n * This interface can be augmented by users to add types to ioc\n */\ninterface IocMap {}\n\n/**\n * Get instance of service\n * @example\n * const userService ioc('UserService');\n *\n * @group Main\n */\nexport function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key] {\n return ServiceContainer.get(id as any) as any;\n}\nexport type { IocMap };\n"],"names":["logger","captureStackTrace","path","globSync","crypto","fs"],"mappings":";;;;;;;;;;;;;;AAmCA,MAAM,OAAA,uBAAc,GAAA,EAAqB;AAEzC,MAAM,GAAA,GAAMA,eAAO,KAAK,CAAA;AAExB,yBAAe;AAAA,EACb,IAAO,EAAA,EAAe;AACpB,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA;AAE9B,IAAA,IAAI,CAAC,OAAA,EAAS;AACZ,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,8BAAA,EAAiC,EAAE,CAAA,CAAA,CAAG,CAAA;AAAA,IACxD;AAEA,IAAA,IAAI,CAAC,QAAQ,QAAA,EAAU;AACrB,MAAA,OAAA,CAAQ,QAAA,GAAW,QAAQ,OAAA,IAAU;AACrC,MAAA,OAAA,CAAQ,OAAA,GAAU,MAAA;AAAA,IACpB;AAEA,IAAA,OAAO,OAAA,CAAQ,QAAA;AAAA,EACjB,CAAA;AAAA,EAEA,GAAA,CACE,EAAA,EACA,uBAAA,EACA,cAAA,GAA0B,KAAA,EAC1B;AACA,IAAA,IAAI,IAAA,CAAK,KAAA,CAAM,EAAE,CAAA,EAAG;AAClB,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,SAAA,EAAY,EAAE,CAAA,uBAAA,CAAyB,CAAA;AAAA,IACzD;AAEA,IAAA,IAAI,eAAA;AAEJ,IAAA,IAAI;AACF,MAAA,eAAA,GAAkB,wBAAA,CAAyBC,yBAAA,CAAkB,IAAA,CAAK,GAAG,CAAC,CAAA;AAAA,IACxE,SAAS,CAAA,EAAG;A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ory = any;
|
|
4
|
-
interface SetupOptions {
|
|
5
|
-
pathRoot?: string;
|
|
6
|
-
/**
|
|
7
|
-
* Absolute or relative path where generated type file will be saved
|
|
8
|
-
*/
|
|
9
|
-
typeOutput?: string;
|
|
10
|
-
/**
|
|
11
|
-
* Absolute or relative glob patterns to auto-import service files
|
|
12
|
-
*/
|
|
13
|
-
autoImportPatterns?: string[];
|
|
14
|
-
/**
|
|
15
|
-
* Should generate type file
|
|
16
|
-
*/
|
|
17
|
-
generateTypes?: boolean;
|
|
18
|
-
}
|
|
19
|
-
declare const _default: {
|
|
20
|
-
get<T>(id: string): T;
|
|
21
|
-
set(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean): void;
|
|
22
|
-
override(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean, constructorPath?: string): void;
|
|
23
|
-
isSet(id: string): boolean;
|
|
24
|
-
clear(): void;
|
|
25
|
-
setup({ pathRoot, generateTypes, autoImportPatterns, typeOutput, }?: SetupOptions | undefined): Promise<void>;
|
|
26
|
-
importServices(autoImportPatterns: string[]): Promise<void>;
|
|
27
|
-
writeTypes(outputFilePath: string): Promise<void>;
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* This interface can be augmented by users to add types to ioc
|
|
32
|
-
*/
|
|
33
|
-
interface IocMap {
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Get instance of service
|
|
37
|
-
* @example
|
|
38
|
-
* const userService ioc('UserService');
|
|
39
|
-
*
|
|
40
|
-
* @group Main
|
|
41
|
-
*/
|
|
42
|
-
declare function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
|
|
43
|
-
|
|
44
|
-
export { type IocMap, _default as ServiceContainer, ioc };
|
package/dist/index.d.ts
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { AnyFunction } from '@andrew_l/toolkit';
|
|
2
|
-
|
|
3
|
-
type Factory = any;
|
|
4
|
-
interface SetupOptions {
|
|
5
|
-
pathRoot?: string;
|
|
6
|
-
/**
|
|
7
|
-
* Absolute or relative path where generated type file will be saved
|
|
8
|
-
*/
|
|
9
|
-
typeOutput?: string;
|
|
10
|
-
/**
|
|
11
|
-
* Absolute or relative glob patterns to auto-import service files
|
|
12
|
-
*/
|
|
13
|
-
autoImportPatterns?: string[];
|
|
14
|
-
/**
|
|
15
|
-
* Should generate type file
|
|
16
|
-
*/
|
|
17
|
-
generateTypes?: boolean;
|
|
18
|
-
}
|
|
19
|
-
declare const _default: {
|
|
20
|
-
get<T>(id: string): T;
|
|
21
|
-
set(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean): void;
|
|
22
|
-
override(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean, constructorPath?: string): void;
|
|
23
|
-
isSet(id: string): boolean;
|
|
24
|
-
clear(): void;
|
|
25
|
-
setup({ pathRoot, generateTypes, autoImportPatterns, typeOutput, }?: SetupOptions | undefined): Promise<void>;
|
|
26
|
-
importServices(autoImportPatterns: string[]): Promise<void>;
|
|
27
|
-
writeTypes(outputFilePath: string): Promise<void>;
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* This interface can be augmented by users to add types to ioc
|
|
32
|
-
*/
|
|
33
|
-
interface IocMap {
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Get instance of service
|
|
37
|
-
* @example
|
|
38
|
-
* const userService ioc('UserService');
|
|
39
|
-
*
|
|
40
|
-
* @group Main
|
|
41
|
-
*/
|
|
42
|
-
declare function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
|
|
43
|
-
|
|
44
|
-
export { type IocMap, _default as ServiceContainer, ioc };
|