injeca 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Neko Ayaka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # Injeca
2
+
3
+ Pure function programming based dependency injection library
4
+
5
+ > Heavily inspired by [uber/fig](https://go.uber.org/fig) and [uber/dig](https://go.uber.org/dig) in Golang ecosystem.
6
+
7
+ [![npm version][npm-version-src]][npm-version-href]
8
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
9
+ [![bundle][bundle-src]][bundle-href]
10
+ [![JSDocs][jsdocs-src]][jsdocs-href]
11
+ [![License][license-src]][license-href]
12
+
13
+ ## Installation
14
+
15
+ ```sh
16
+ npm install injeca
17
+ pnpm add injeca
18
+ bun add injeca
19
+ ni injeca
20
+ yarn add injeca
21
+ ```
22
+
23
+ ## Basic usage
24
+
25
+ `injeca` ships with a global singleton container exposed as `injecta`. You can register
26
+ providers, declare their dependencies, and run invocations once everything is ready.
27
+
28
+ ```ts
29
+ import { createServer } from 'node:http'
30
+
31
+ import { injecta, lifecycle } from 'injeca'
32
+
33
+ // Providers return a value once and are cached inside the container.
34
+ const config = injecta.provide('config', () => ({ port: 3000 }))
35
+
36
+ const server = injecta.provide({
37
+ dependsOn: { config, lifecycle },
38
+ async build({ dependsOn }) {
39
+ const { config, lifecycle } = dependsOn
40
+ const app = createServer()
41
+
42
+ lifecycle.appHooks.onStart(() => app.listen(config.port))
43
+ lifecycle.appHooks.onStop(() => app.close())
44
+
45
+ return app
46
+ },
47
+ })
48
+
49
+ injecta.invoke({
50
+ dependsOn: { server },
51
+ async callback({ server }) {
52
+ // eslint-disable-next-line no-console
53
+ console.log('HTTP server ready:', await server.address())
54
+ },
55
+ })
56
+
57
+ await injecta.start()
58
+
59
+ process.once('SIGINT', async () => {
60
+ await injecta.stop()
61
+ })
62
+ ```
63
+
64
+ ### Manual containers
65
+
66
+ If you need multiple containers (for tests or per-request scopes), create them
67
+ explicitly and pass the container reference into `provide`, `invoke`, `start`, and
68
+ `stop`.
69
+
70
+ ```ts
71
+ import { createContainer, invoke, provide, start, stop } from 'injeca'
72
+
73
+ const container = createContainer()
74
+
75
+ const token = provide(container, 'token', () => crypto.randomUUID())
76
+
77
+ invoke(container, {
78
+ dependsOn: { token },
79
+ // eslint-disable-next-line no-console
80
+ callback: ({ token }) => console.log('token', token),
81
+ })
82
+
83
+ await start(container)
84
+ await stop(container)
85
+ ```
86
+
87
+ ## License
88
+
89
+ MIT
90
+
91
+ [npm-version-src]: https://img.shields.io/npm/v/injeca?style=flat&colorA=080f12&colorB=1fa669
92
+ [npm-version-href]: https://npmjs.com/package/injeca
93
+ [npm-downloads-src]: https://img.shields.io/npm/dm/injeca?style=flat&colorA=080f12&colorB=1fa669
94
+ [npm-downloads-href]: https://npmjs.com/package/injeca
95
+ [bundle-src]: https://img.shields.io/bundlephobia/minzip/injeca?style=flat&colorA=080f12&colorB=1fa669&label=minzip
96
+ [bundle-href]: https://bundlephobia.com/result?p=injeca
97
+ [license-src]: https://img.shields.io/github/license/moeru-ai/injeca.svg?style=flat&colorA=080f12&colorB=1fa669
98
+ [license-href]: https://github.com/moeru-ai/injeca/blob/main/LICENSE
99
+ [jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669
100
+ [jsdocs-href]: https://www.jsdocs.io/package/injeca
@@ -0,0 +1,25 @@
1
+ //#region src/builtin.ts
2
+ function buildLifecycle() {
3
+ const onStartHooks = [];
4
+ const onStopHooks = [];
5
+ return {
6
+ appHooks: {
7
+ onStart(hook) {
8
+ if (hook) onStartHooks.push(hook);
9
+ },
10
+ onStop(hook) {
11
+ if (hook) onStopHooks.push(hook);
12
+ }
13
+ },
14
+ emitOnStart: async () => {
15
+ for (const hook of onStartHooks) await hook();
16
+ },
17
+ emitOnStop: async () => {
18
+ for (const hook of onStopHooks) await hook();
19
+ }
20
+ };
21
+ }
22
+
23
+ //#endregion
24
+ export { buildLifecycle };
25
+ //# sourceMappingURL=builtin-BN5UvvMB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builtin-BN5UvvMB.mjs","names":["onStartHooks: (() => void | Promise<void>)[]","onStopHooks: (() => void | Promise<void>)[]"],"sources":["../src/builtin.ts"],"sourcesContent":["export interface LifecycleAppHooks {\n onStart: (hook: () => void | Promise<void>) => void\n onStop: (hook: () => void | Promise<void>) => void\n}\n\nexport interface Lifecycle {\n appHooks: LifecycleAppHooks\n}\n\nexport interface LifecycleTriggerable extends Lifecycle {\n emitOnStart: () => Promise<void>\n emitOnStop: () => Promise<void>\n}\n\nexport function buildLifecycle(): Lifecycle {\n const onStartHooks: (() => void | Promise<void>)[] = []\n const onStopHooks: (() => void | Promise<void>)[] = []\n\n const lifecycle: LifecycleTriggerable = {\n appHooks: {\n onStart(hook: () => void | Promise<void>) {\n if (hook) {\n onStartHooks.push(hook)\n }\n },\n onStop(hook: () => void | Promise<void>) {\n if (hook) {\n onStopHooks.push(hook)\n }\n },\n },\n emitOnStart: async () => {\n for (const hook of onStartHooks) {\n await hook()\n }\n },\n emitOnStop: async () => {\n for (const hook of onStopHooks) {\n await hook()\n }\n },\n }\n\n return lifecycle\n}\n"],"mappings":";AAcA,SAAgB,iBAA4B;CAC1C,MAAMA,eAA+C,EAAE;CACvD,MAAMC,cAA8C,EAAE;AA2BtD,QAzBwC;EACtC,UAAU;GACR,QAAQ,MAAkC;AACxC,QAAI,KACF,cAAa,KAAK,KAAK;;GAG3B,OAAO,MAAkC;AACvC,QAAI,KACF,aAAY,KAAK,KAAK;;GAG3B;EACD,aAAa,YAAY;AACvB,QAAK,MAAM,QAAQ,aACjB,OAAM,MAAM;;EAGhB,YAAY,YAAY;AACtB,QAAK,MAAM,QAAQ,YACjB,OAAM,MAAM;;EAGjB"}
@@ -0,0 +1,122 @@
1
+ import { Logg } from "@guiiai/logg";
2
+
3
+ //#region src/builtin.d.ts
4
+ interface LifecycleAppHooks {
5
+ onStart: (hook: () => void | Promise<void>) => void;
6
+ onStop: (hook: () => void | Promise<void>) => void;
7
+ }
8
+ interface Lifecycle {
9
+ appHooks: LifecycleAppHooks;
10
+ }
11
+ interface LifecycleTriggerable extends Lifecycle {
12
+ emitOnStart: () => Promise<void>;
13
+ emitOnStop: () => Promise<void>;
14
+ }
15
+ //#endregion
16
+ //#region src/logger.d.ts
17
+ interface Logger {
18
+ provide: (name: string, dependencies: string[]) => void;
19
+ invoke: (dependencies: string[]) => void;
20
+ beforeRun: (name: string) => void;
21
+ run: (name: string, duration: number) => void;
22
+ hookOnStart: (name: string) => void;
23
+ hookOnStartComplete: (name: string, duration: number) => void;
24
+ hookOnStop: (name: string) => void;
25
+ hookOnStopComplete: (name: string, duration: number) => void;
26
+ running: () => void;
27
+ }
28
+ interface LoggerOptions {
29
+ enabled?: boolean;
30
+ logger?: Logger;
31
+ }
32
+ declare function createDefaultLogger(): Logger;
33
+ declare function createLoggLogger(logg: Logg): Logger;
34
+ declare function createNoopLogger(): Logger;
35
+ //#endregion
36
+ //#region src/scoped.d.ts
37
+ type DependencyMap = Record<string, any>;
38
+ interface Container {
39
+ providers: Map<string, ProvideOptionObject<any, any>>;
40
+ instances: Map<string, any>;
41
+ lifecycleHooks: Map<string, LifecycleTriggerable>;
42
+ dependencyGraph: Map<string, string[]>;
43
+ invocations: InvokeOptionObject<any>[];
44
+ logger: Logger;
45
+ }
46
+ type BuildContext<D extends DependencyMap | undefined = undefined> = {
47
+ container: Container;
48
+ name: string;
49
+ } & (D extends undefined ? {
50
+ dependsOn?: unknown;
51
+ } : {
52
+ dependsOn: D;
53
+ });
54
+ type ResolveDependencyDeclaration<Deps extends Record<string, string | ProvidedKey<any, any, any>>> = { [K in keyof Deps]: Deps[K] extends ProvidedKey<any, infer T, any> ? T : any };
55
+ type ProvideOptionObject<T$1, D extends DependencyMap | undefined = undefined> = {
56
+ build: (context: BuildContext<D>) => T$1 | Promise<T$1>;
57
+ } & (D extends undefined ? {
58
+ dependsOn?: Record<string, never>;
59
+ } : {
60
+ dependsOn: { [K in keyof D]: string };
61
+ });
62
+ type ProvideOptionFunc<T$1, D extends DependencyMap | undefined = undefined> = (context: BuildContext<D>) => T$1 | Promise<T$1>;
63
+ type ProvideOption<T$1, D extends DependencyMap | undefined = undefined> = ProvideOptionObject<T$1, D> | ProvideOptionFunc<T$1, D>;
64
+ interface ProvideOptionObjectWithKeys<T$1, Deps extends Record<string, string | ProvidedKey<any, any, any>>> {
65
+ build: (context: BuildContext<ResolveDependencyDeclaration<Deps>>) => T$1 | Promise<T$1>;
66
+ dependsOn: Deps;
67
+ }
68
+ type ProvideOptionWithKeys<T$1, Deps extends Record<string, string | ProvidedKey<any, any, any>>> = ProvideOptionObjectWithKeys<T$1, Deps>;
69
+ type InvokeOptionObject<D extends DependencyMap | undefined = undefined> = {
70
+ callback: (dependencies: D) => void | Promise<void>;
71
+ } & (D extends undefined ? {
72
+ dependsOn?: Record<string, never>;
73
+ } : {
74
+ dependsOn: { [K in keyof D]: string };
75
+ });
76
+ type InvokeOptionFunc<D extends DependencyMap | undefined = undefined> = (dependencies: D) => void | Promise<void>;
77
+ type InvokeOption<D extends DependencyMap | undefined = undefined> = InvokeOptionObject<D> | InvokeOptionFunc<D>;
78
+ interface InvokeOptionObjectWithKeys<Deps extends Record<string, string | ProvidedKey<any, any, any>>> {
79
+ callback: (dependencies: ResolveDependencyDeclaration<Deps>) => void | Promise<void>;
80
+ dependsOn: Deps;
81
+ }
82
+ type InvokeOptionWithKeys<Deps extends Record<string, string | ProvidedKey<any, any, any>>> = InvokeOptionObjectWithKeys<Deps>;
83
+ declare const lifecycle: ProvidedKey<'lifecycle', Lifecycle, undefined>;
84
+ declare function createContainer(options?: LoggerOptions): Container;
85
+ interface ProvidedKey<Key, T$1, D extends DependencyMap | undefined> {
86
+ key: Key;
87
+ }
88
+ declare function provide<T$1, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(container: Container, name: Key, option: ProvideOptionWithKeys<T$1, Deps>): ProvidedKey<Key, T$1, ResolveDependencyDeclaration<Deps>>;
89
+ declare function provide<T$1, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(container: Container, option: ProvideOptionWithKeys<T$1, Deps> & {
90
+ autoNameStackIndex?: number;
91
+ }): ProvidedKey<Key, T$1, ResolveDependencyDeclaration<Deps>>;
92
+ declare function provide<D extends DependencyMap | undefined, T$1 = any, Key extends string = string>(container: Container, name: Key, option: ProvideOption<T$1, D>): ProvidedKey<Key, T$1, D>;
93
+ declare function provide<D extends DependencyMap | undefined, T$1 = any, Key extends string = string>(container: Container, option: ProvideOption<T$1, D> & {
94
+ autoNameStackIndex?: number;
95
+ }): ProvidedKey<Key, T$1, D>;
96
+ declare function invoke<Deps extends Record<string, string | ProvidedKey<any, any, any>>>(container: Container, option: InvokeOptionWithKeys<Deps>): void;
97
+ declare function invoke<D extends DependencyMap>(container: Container, option: InvokeOption<D>): void;
98
+ declare function start(container: Container): Promise<void>;
99
+ declare function stop(container: Container): Promise<void>;
100
+ //#endregion
101
+ //#region src/global.d.ts
102
+ declare function setLogger(logger: Logger): void;
103
+ declare function provide$1<T$1, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(name: Key, option: ProvideOptionWithKeys<T$1, Deps>): ProvidedKey<Key, T$1, ResolveDependencyDeclaration<Deps>>;
104
+ declare function provide$1<D extends DependencyMap | undefined, T$1 = any, Key extends string = string>(name: Key, option: ProvideOption<T$1, D>): ProvidedKey<Key, T$1, D>;
105
+ declare function provide$1<T$1, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(option: ProvideOptionWithKeys<T$1, Deps>): ProvidedKey<Key, T$1, ResolveDependencyDeclaration<Deps>>;
106
+ declare function provide$1<D extends DependencyMap | undefined, T$1 = any, Key extends string = string>(option: ProvideOption<T$1, D>): ProvidedKey<Key, T$1, D>;
107
+ declare function invoke$1<Deps extends Record<string, string | ProvidedKey<any, any, any>>>(option: InvokeOptionWithKeys<Deps>): void;
108
+ declare function invoke$1<D extends DependencyMap>(option: InvokeOption<D>): void;
109
+ declare function start$1(): Promise<void>;
110
+ declare function stop$1(): Promise<void>;
111
+ //#endregion
112
+ //#region src/index.d.ts
113
+ declare const injecta: {
114
+ provide: typeof provide$1;
115
+ invoke: typeof invoke$1;
116
+ start: typeof start$1;
117
+ stop: typeof stop$1;
118
+ setLogger: typeof setLogger;
119
+ };
120
+ //#endregion
121
+ export { type BuildContext, type Container, type DependencyMap, type InvokeOption, type InvokeOptionFunc, type InvokeOptionObject, type InvokeOptionObjectWithKeys, type InvokeOptionWithKeys, type Lifecycle, type Logger, type LoggerOptions, type ProvideOption, type ProvideOptionFunc, type ProvideOptionObject, type ProvideOptionObjectWithKeys, type ProvideOptionWithKeys, type ProvidedKey, type ResolveDependencyDeclaration, createContainer, createDefaultLogger, createLoggLogger, createNoopLogger, injecta, invoke, lifecycle, provide, start, stop };
122
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,272 @@
1
+ import ErrorStackParser from "error-stack-parser";
2
+ import { nanoid } from "nanoid";
3
+
4
+ //#region src/global.ts
5
+ let globalContainer = createContainer();
6
+ function setLogger(logger) {
7
+ globalContainer.logger = logger;
8
+ }
9
+ function provide$1(nameOrOption, option) {
10
+ if (option != null && typeof option === "function") return provide(globalContainer, nameOrOption, {
11
+ build: option,
12
+ autoNameStackIndex: 2
13
+ });
14
+ return provide(globalContainer, nameOrOption, {
15
+ ...option,
16
+ autoNameStackIndex: 2
17
+ });
18
+ }
19
+ function invoke$1(option) {
20
+ if (typeof option === "function") globalContainer.invocations.push({ callback: option });
21
+ else globalContainer.invocations.push(option);
22
+ }
23
+ function start$1() {
24
+ return start(globalContainer);
25
+ }
26
+ function stop$1() {
27
+ return stop(globalContainer);
28
+ }
29
+
30
+ //#endregion
31
+ //#region package.json
32
+ var name = "injeca";
33
+
34
+ //#endregion
35
+ //#region src/logger.ts
36
+ function formatDuration(ms) {
37
+ if (ms < 1) return `${(ms * 1e3).toFixed(3)}µs`;
38
+ if (ms < 1e3) return `${ms.toFixed(3)}ms`;
39
+ return `${(ms / 1e3).toFixed(3)}s`;
40
+ }
41
+ function createDefaultLogger() {
42
+ return {
43
+ provide: (name$1, dependencies) => {
44
+ const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(", ")})` : "";
45
+ console.log(`[${name$1}] PROVIDE ${name$1}${depsStr}`);
46
+ },
47
+ invoke: (dependencies) => {
48
+ const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(", ")})` : "";
49
+ console.log(`[${name}] INVOKE${depsStr}`);
50
+ },
51
+ beforeRun: (name$1) => {
52
+ console.log(`[${name$1}] BEFORE RUN provide: ${name$1}()`);
53
+ },
54
+ run: (name$1, duration) => {
55
+ console.log(`[${name$1}] RUN provide: ${name$1}() in ${formatDuration(duration)}`);
56
+ },
57
+ hookOnStart: (name$1) => {
58
+ console.log(`[${name$1}] HOOK OnStart ${name$1}() executing`);
59
+ },
60
+ hookOnStartComplete: (name$1, duration) => {
61
+ console.log(`[${name$1}] HOOK OnStart ${name$1}() ran successfully in ${formatDuration(duration)}`);
62
+ },
63
+ hookOnStop: (name$1) => {
64
+ console.log(`[${name$1}] HOOK OnStop ${name$1}() executing`);
65
+ },
66
+ hookOnStopComplete: (name$1, duration) => {
67
+ console.log(`[${name$1}] HOOK OnStop ${name$1}() ran successfully in ${formatDuration(duration)}`);
68
+ },
69
+ running: () => {
70
+ console.log(`[${name}] RUNNING`);
71
+ }
72
+ };
73
+ }
74
+ function createLoggLogger(logg) {
75
+ return {
76
+ provide: (name$1, dependencies) => {
77
+ const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(", ")})` : "";
78
+ logg.log(`PROVIDE ${name$1}${depsStr}`);
79
+ },
80
+ invoke: (dependencies) => {
81
+ const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(", ")})` : "";
82
+ logg.log(`INVOKE${depsStr}`);
83
+ },
84
+ beforeRun: (name$1) => {
85
+ logg.log(`BEFORE RUN provide: ${name$1}()`);
86
+ },
87
+ run: (name$1, duration) => {
88
+ logg.log(`RUN provide: ${name$1}() in ${formatDuration(duration)}`);
89
+ },
90
+ hookOnStart: (name$1) => {
91
+ logg.log(`HOOK OnStart ${name$1}() executing`);
92
+ },
93
+ hookOnStartComplete: (name$1, duration) => {
94
+ logg.log(`HOOK OnStart ${name$1}() ran successfully in ${formatDuration(duration)}`);
95
+ },
96
+ hookOnStop: (name$1) => {
97
+ logg.log(`HOOK OnStop ${name$1}() executing`);
98
+ },
99
+ hookOnStopComplete: (name$1, duration) => {
100
+ logg.log(`HOOK OnStop ${name$1}() ran successfully in ${formatDuration(duration)}`);
101
+ },
102
+ running: () => {
103
+ logg.log(`RUNNING`);
104
+ }
105
+ };
106
+ }
107
+ function createNoopLogger() {
108
+ return {
109
+ provide: () => {},
110
+ invoke: () => {},
111
+ beforeRun: () => {},
112
+ run: () => {},
113
+ hookOnStart: () => {},
114
+ hookOnStartComplete: () => {},
115
+ hookOnStop: () => {},
116
+ hookOnStopComplete: () => {},
117
+ running: () => {}
118
+ };
119
+ }
120
+
121
+ //#endregion
122
+ //#region src/scoped.ts
123
+ const lifecycle = { key: "lifecycle" };
124
+ function createContainer(options) {
125
+ const logger = options?.enabled === false ? createNoopLogger() : options?.logger ?? createDefaultLogger();
126
+ return {
127
+ providers: /* @__PURE__ */ new Map(),
128
+ instances: /* @__PURE__ */ new Map(),
129
+ lifecycleHooks: /* @__PURE__ */ new Map(),
130
+ dependencyGraph: /* @__PURE__ */ new Map(),
131
+ invocations: [],
132
+ logger
133
+ };
134
+ }
135
+ function normalizeName(nameOrProvidedKey) {
136
+ if (typeof nameOrProvidedKey === "object" && nameOrProvidedKey !== null && "key" in nameOrProvidedKey) return nameOrProvidedKey.key;
137
+ return nameOrProvidedKey;
138
+ }
139
+ function normalizeProvideOption(nameOrOption, option) {
140
+ if (typeof nameOrOption === "string") {
141
+ if (option == null || !("build" in option) && typeof option !== "function") throw new Error("When using provide(...) as named callback, the second argument must be either a valid ProvideOptionObject<T, D> or a ProvideOptionFunc<T, D>.");
142
+ if (typeof option === "function") return { build: option };
143
+ return option;
144
+ }
145
+ if (typeof nameOrOption === "object" && "key" in nameOrOption) {
146
+ if (option == null || !("build" in option) && typeof option !== "function") throw new Error("When using provide(...) as typed ProvideOptionWithKeys<T, D, Key> callback, the second argument must be either a valid ProvideOptionObject<T, D> or a ProvideOptionFunc<T, D>.");
147
+ if (typeof option === "function") return { build: option };
148
+ return option;
149
+ }
150
+ if (typeof nameOrOption === "function") return { build: nameOrOption };
151
+ return nameOrOption;
152
+ }
153
+ function provide(container, nameOrOption, option) {
154
+ const parentFile = ErrorStackParser.parse(/* @__PURE__ */ new Error("providing"))[option?.autoNameStackIndex ?? 1];
155
+ const name$1 = typeof nameOrOption === "string" ? nameOrOption : `${parentFile.fileName ?? `unknown-${nanoid()}`}:${parentFile.lineNumber ?? 0}:${parentFile.columnNumber ?? 0}`;
156
+ const providerObject = normalizeProvideOption(nameOrOption, option);
157
+ if (providerObject.dependsOn) {
158
+ const resolvedDependsOn = {};
159
+ for (const [key, value] of Object.entries(providerObject.dependsOn)) resolvedDependsOn[key] = normalizeName(value);
160
+ providerObject.dependsOn = resolvedDependsOn;
161
+ }
162
+ container.providers.set(name$1, providerObject);
163
+ const dependencies = providerObject.dependsOn ? Object.values(providerObject.dependsOn) : [];
164
+ container.logger.provide(name$1, dependencies);
165
+ container.dependencyGraph.set(name$1, dependencies);
166
+ return { key: name$1 };
167
+ }
168
+ function invoke(container, option) {
169
+ const invocationObject = typeof option === "function" ? { callback: option } : option;
170
+ if (invocationObject.dependsOn) {
171
+ const resolvedDependsOn = {};
172
+ for (const [key, value] of Object.entries(invocationObject.dependsOn)) resolvedDependsOn[key] = normalizeName(value);
173
+ invocationObject.dependsOn = resolvedDependsOn;
174
+ }
175
+ const dependencies = invocationObject.dependsOn ? Object.values(invocationObject.dependsOn) : [];
176
+ container.logger.invoke(dependencies);
177
+ container.invocations.push(invocationObject);
178
+ }
179
+ async function resolveInstance(container, name$1) {
180
+ if (container.instances.has(name$1)) return container.instances.get(name$1);
181
+ const provider = container.providers.get(name$1);
182
+ if (!provider) throw new Error(`No provider found for '${name$1}'`);
183
+ const resolvedDependencies = {};
184
+ let serviceLifecycle = null;
185
+ if (provider.dependsOn) for (const [key, depName] of Object.entries(provider.dependsOn)) if (depName === "lifecycle") {
186
+ const { buildLifecycle } = await import("./builtin-BN5UvvMB.mjs");
187
+ serviceLifecycle = buildLifecycle();
188
+ resolvedDependencies[key] = serviceLifecycle;
189
+ container.lifecycleHooks.set(name$1, serviceLifecycle);
190
+ } else resolvedDependencies[key] = await resolveInstance(container, depName);
191
+ const context = {
192
+ container,
193
+ dependsOn: resolvedDependencies,
194
+ name: name$1
195
+ };
196
+ container.logger.beforeRun(name$1);
197
+ const startTime = performance.now();
198
+ const instance = await provider.build(context);
199
+ const duration = performance.now() - startTime;
200
+ container.logger.run(name$1, duration);
201
+ container.instances.set(name$1, instance);
202
+ return instance;
203
+ }
204
+ function topologicalSort(dependencyGraph) {
205
+ const visited = /* @__PURE__ */ new Set();
206
+ const visiting = /* @__PURE__ */ new Set();
207
+ const result = [];
208
+ function visit(node) {
209
+ if (visiting.has(node)) throw new Error(`Circular dependency detected involving '${node}'`);
210
+ if (visited.has(node)) return;
211
+ visiting.add(node);
212
+ const dependencies = dependencyGraph.get(node) || [];
213
+ for (const dep of dependencies) visit(dep);
214
+ visiting.delete(node);
215
+ visited.add(node);
216
+ result.push(node);
217
+ }
218
+ for (const node of dependencyGraph.keys()) if (!visited.has(node)) visit(node);
219
+ return result;
220
+ }
221
+ async function startLifecycleHooks(container) {
222
+ const sortedServices = topologicalSort(container.dependencyGraph);
223
+ for (const serviceName of sortedServices) {
224
+ const lifecycle$1 = container.lifecycleHooks.get(serviceName);
225
+ if (lifecycle$1?.emitOnStart) {
226
+ container.logger.hookOnStart(serviceName);
227
+ const startTime = performance.now();
228
+ await lifecycle$1.emitOnStart();
229
+ const duration = performance.now() - startTime;
230
+ container.logger.hookOnStartComplete(serviceName, duration);
231
+ }
232
+ }
233
+ }
234
+ async function stopLifecycleHooks(container) {
235
+ const sortedServices = topologicalSort(container.dependencyGraph);
236
+ for (const serviceName of sortedServices.reverse()) {
237
+ const lifecycle$1 = container.lifecycleHooks.get(serviceName);
238
+ if (lifecycle$1?.emitOnStop) {
239
+ container.logger.hookOnStop(serviceName);
240
+ const startTime = performance.now();
241
+ await lifecycle$1.emitOnStop();
242
+ const duration = performance.now() - startTime;
243
+ container.logger.hookOnStopComplete(serviceName, duration);
244
+ }
245
+ }
246
+ }
247
+ async function start(container) {
248
+ await startLifecycleHooks(container);
249
+ for (const invocation of container.invocations) {
250
+ const resolvedDependencies = {};
251
+ if (invocation.dependsOn) for (const [key, depName] of Object.entries(invocation.dependsOn)) resolvedDependencies[key] = await resolveInstance(container, normalizeName(depName));
252
+ await invocation.callback(resolvedDependencies);
253
+ }
254
+ container.logger.running();
255
+ }
256
+ async function stop(container) {
257
+ await stopLifecycleHooks(container);
258
+ }
259
+
260
+ //#endregion
261
+ //#region src/index.ts
262
+ const injecta = {
263
+ provide: provide$1,
264
+ invoke: invoke$1,
265
+ start: start$1,
266
+ stop: stop$1,
267
+ setLogger
268
+ };
269
+
270
+ //#endregion
271
+ export { createContainer, createDefaultLogger, createLoggLogger, createNoopLogger, injecta, invoke, lifecycle, provide, start, stop };
272
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["provide","indexProvide","invoke","start","indexStart","stop","indexStop","name","lifecycle: ProvidedKey<'lifecycle', Lifecycle, undefined>","name","resolvedDependsOn: Record<string, string>","resolvedDependencies: Record<string, any>","serviceLifecycle: any","context: BuildContext<typeof provider.dependsOn>","result: string[]","lifecycle","globalProvide","globalInvoke","globalStart","globalStop","globalSetLogger"],"sources":["../src/global.ts","../package.json","../src/logger.ts","../src/scoped.ts","../src/index.ts"],"sourcesContent":["import type { DependencyMap, InvokeOption, InvokeOptionWithKeys, Logger, ProvideOption, ProvideOptionWithKeys, ResolveDependencyDeclaration } from '.'\nimport type { ProvidedKey } from './scoped'\n\nimport { createContainer, provide as indexProvide, start as indexStart, stop as indexStop } from '.'\n\nlet globalContainer = createContainer()\n\nexport function setLogger(logger: Logger) {\n globalContainer.logger = logger\n}\n\nexport function resetContainer() {\n globalContainer = createContainer()\n}\n\nexport function provide<T, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(name: Key, option: ProvideOptionWithKeys<T, Deps>): ProvidedKey<Key, T, ResolveDependencyDeclaration<Deps>>\nexport function provide<D extends DependencyMap | undefined, T = any, Key extends string = string>(name: Key, option: ProvideOption<T, D>): ProvidedKey<Key, T, D>\nexport function provide<T, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(option: ProvideOptionWithKeys<T, Deps>): ProvidedKey<Key, T, ResolveDependencyDeclaration<Deps>>\nexport function provide<D extends DependencyMap | undefined, T = any, Key extends string = string>(option: ProvideOption<T, D>): ProvidedKey<Key, T, D>\nexport function provide<D extends DependencyMap | undefined, T = any, Key extends string = string>(nameOrOption: Key | ProvideOption<T, D> | ProvideOptionWithKeys<T, any>, option?: ProvideOption<T, D> | ProvideOptionWithKeys<T, any>): ProvidedKey<Key, T, D> {\n if (option != null && typeof option === 'function') {\n return indexProvide(globalContainer, nameOrOption as any, { build: option, autoNameStackIndex: 2 } as any)\n }\n\n return indexProvide(globalContainer, nameOrOption as any, { ...option, autoNameStackIndex: 2 } as any)\n}\n\nexport function invoke<Deps extends Record<string, string | ProvidedKey<any, any, any>>>(option: InvokeOptionWithKeys<Deps>): void\nexport function invoke<D extends DependencyMap>(option: InvokeOption<D>): void\nexport function invoke<D extends DependencyMap>(option: InvokeOption<D> | InvokeOptionWithKeys<any>): void {\n if (typeof option === 'function') {\n globalContainer.invocations.push({ callback: option } as any)\n }\n else {\n globalContainer.invocations.push(option as any)\n }\n}\n\nexport function start(): Promise<void> {\n return indexStart(globalContainer)\n}\n\nexport function stop(): Promise<void> {\n return indexStop(globalContainer)\n}\n","{\n \"name\": \"injeca\",\n \"type\": \"module\",\n \"packageManager\": \"pnpm@10.22.0\",\n \"description\": \"Pure function programming based dependency injection library inspired by go.uber.org/fig and go.uber.org/dig.\",\n \"author\": {\n \"name\": \"Moeru AI Project AIRI Team\",\n \"email\": \"airi@moeru.ai\",\n \"url\": \"https://github.com/moeru-ai\"\n },\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/moeru-ai/injeca.git\"\n },\n \"exports\": {\n \".\": {\n \"type\": \"./dist/index.d.js\",\n \"default\": \"./dist/index.js\"\n }\n },\n \"files\": [\n \"README.md\",\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsdown\",\n \"test\": \"vitest --coverage\",\n \"test:run\": \"vitest run\",\n \"lint\": \"eslint --cache .\",\n \"lint:fix\": \"eslint --cache --fix .\",\n \"typecheck\": \"tsc --noEmit\",\n \"up\": \"taze -w -r -I -f && pnpm prune && pnpm dedupe\"\n },\n \"peerDependencies\": {\n \"@guiiai/logg\": \">= 1\",\n \"error-stack-parser\": \"^2.1.4\",\n \"nanoid\": \">=5\"\n },\n \"peerDependenciesMeta\": {\n \"@guiiai/logg\": {\n \"optional\": true\n }\n },\n \"devDependencies\": {\n \"@antfu/eslint-config\": \"^6.2.0\",\n \"@moeru/eslint-config\": \"0.1.0-beta.13\",\n \"@moeru/tsconfig\": \"0.1.0-beta.13\",\n \"@types/node\": \"^24.10.1\",\n \"bumpp\": \"^10.3.1\",\n \"eslint\": \"^9.39.1\",\n \"eslint-plugin-oxlint\": \"^1.28.0\",\n \"oxlint\": \"^1.28.0\",\n \"publint\": \"^0.3.15\",\n \"taze\": \"^19.9.0\",\n \"tsdown\": \"^0.16.4\",\n \"typescript\": \"^5.9.3\",\n \"unplugin-unused\": \"^0.5.6\",\n \"vite\": \"^7.2.2\",\n \"vitest\": \"^4.0.9\"\n }\n}\n","import type { Logg as LoggLogger } from '@guiiai/logg'\n\nimport { name } from '../package.json'\n\nexport interface Logger {\n provide: (name: string, dependencies: string[]) => void\n invoke: (dependencies: string[]) => void\n beforeRun: (name: string) => void\n run: (name: string, duration: number) => void\n hookOnStart: (name: string) => void\n hookOnStartComplete: (name: string, duration: number) => void\n hookOnStop: (name: string) => void\n hookOnStopComplete: (name: string, duration: number) => void\n running: () => void\n}\n\nexport interface LoggerOptions {\n enabled?: boolean\n logger?: Logger\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 1) {\n return `${(ms * 1000).toFixed(3)}µs`\n }\n if (ms < 1000) {\n return `${ms.toFixed(3)}ms`\n }\n return `${(ms / 1000).toFixed(3)}s`\n}\n\nexport function createDefaultLogger(): Logger {\n return {\n provide: (name: string, dependencies: string[]) => {\n const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(', ')})` : ''\n // eslint-disable-next-line no-console\n console.log(`[${name}] PROVIDE ${name}${depsStr}`)\n },\n\n invoke: (dependencies: string[]) => {\n const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(', ')})` : ''\n // eslint-disable-next-line no-console\n console.log(`[${name}] INVOKE${depsStr}`)\n },\n\n beforeRun: (name: string) => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] BEFORE RUN provide: ${name}()`)\n },\n\n run: (name: string, duration: number) => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] RUN provide: ${name}() in ${formatDuration(duration)}`)\n },\n\n hookOnStart: (name: string) => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] HOOK OnStart ${name}() executing`)\n },\n\n hookOnStartComplete: (name: string, duration: number) => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] HOOK OnStart ${name}() ran successfully in ${formatDuration(duration)}`)\n },\n\n hookOnStop: (name: string) => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] HOOK OnStop ${name}() executing`)\n },\n\n hookOnStopComplete: (name: string, duration: number) => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] HOOK OnStop ${name}() ran successfully in ${formatDuration(duration)}`)\n },\n\n running: () => {\n // eslint-disable-next-line no-console\n console.log(`[${name}] RUNNING`)\n },\n }\n}\n\nexport function createLoggLogger(logg: LoggLogger): Logger {\n return {\n provide: (name: string, dependencies: string[]) => {\n const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(', ')})` : ''\n logg.log(`PROVIDE ${name}${depsStr}`)\n },\n\n invoke: (dependencies: string[]) => {\n const depsStr = dependencies.length > 0 ? ` (depends on: ${dependencies.join(', ')})` : ''\n logg.log(`INVOKE${depsStr}`)\n },\n\n beforeRun: (name: string) => {\n logg.log(`BEFORE RUN provide: ${name}()`)\n },\n\n run: (name: string, duration: number) => {\n logg.log(`RUN provide: ${name}() in ${formatDuration(duration)}`)\n },\n\n hookOnStart: (name: string) => {\n logg.log(`HOOK OnStart ${name}() executing`)\n },\n\n hookOnStartComplete: (name: string, duration: number) => {\n logg.log(`HOOK OnStart ${name}() ran successfully in ${formatDuration(duration)}`)\n },\n\n hookOnStop: (name: string) => {\n logg.log(`HOOK OnStop ${name}() executing`)\n },\n\n hookOnStopComplete: (name: string, duration: number) => {\n logg.log(`HOOK OnStop ${name}() ran successfully in ${formatDuration(duration)}`)\n },\n\n running: () => {\n logg.log(`RUNNING`)\n },\n }\n}\n\nexport function createNoopLogger(): Logger {\n return {\n provide: () => {},\n invoke: () => {},\n beforeRun: () => {},\n run: () => {},\n hookOnStart: () => {},\n hookOnStartComplete: () => {},\n hookOnStop: () => {},\n hookOnStopComplete: () => {},\n running: () => {},\n }\n}\n","import type { Lifecycle, LifecycleTriggerable } from './builtin'\nimport type { Logger, LoggerOptions } from './logger'\n\nimport ErrorStackParser from 'error-stack-parser'\n\nimport { nanoid } from 'nanoid'\n\nimport { createDefaultLogger, createNoopLogger } from './logger'\n\nexport type DependencyMap = Record<string, any>\n\nexport interface Container {\n providers: Map<string, ProvideOptionObject<any, any>>\n instances: Map<string, any>\n lifecycleHooks: Map<string, LifecycleTriggerable>\n dependencyGraph: Map<string, string[]>\n invocations: InvokeOptionObject<any>[]\n logger: Logger\n}\n\nexport type BuildContext<D extends DependencyMap | undefined = undefined> = {\n container: Container\n name: string\n} & (D extends undefined ? { dependsOn?: unknown } : { dependsOn: D })\n\nexport type ResolveDependencyDeclaration<Deps extends Record<string, string | ProvidedKey<any, any, any>>> = {\n [K in keyof Deps]: Deps[K] extends ProvidedKey<any, infer T, any> ? T : any\n}\n\nexport type ProvideOptionObject<T, D extends DependencyMap | undefined = undefined> = { build: (context: BuildContext<D>) => T | Promise<T> } & (D extends undefined ? { dependsOn?: Record<string, never> } : { dependsOn: { [K in keyof D]: string } })\nexport type ProvideOptionFunc<T, D extends DependencyMap | undefined = undefined> = (context: BuildContext<D>) => T | Promise<T>\nexport type ProvideOption<T, D extends DependencyMap | undefined = undefined> = ProvideOptionObject<T, D> | ProvideOptionFunc<T, D>\n\nexport interface ProvideOptionObjectWithKeys<T, Deps extends Record<string, string | ProvidedKey<any, any, any>>> {\n build: (context: BuildContext<ResolveDependencyDeclaration<Deps>>) => T | Promise<T>\n dependsOn: Deps\n}\nexport type ProvideOptionWithKeys<T, Deps extends Record<string, string | ProvidedKey<any, any, any>>> = ProvideOptionObjectWithKeys<T, Deps>\n\nexport type InvokeOptionObject<D extends DependencyMap | undefined = undefined> = { callback: (dependencies: D) => void | Promise<void> } & (D extends undefined ? { dependsOn?: Record<string, never> } : { dependsOn: { [K in keyof D]: string } })\nexport type InvokeOptionFunc<D extends DependencyMap | undefined = undefined> = (dependencies: D) => void | Promise<void>\nexport type InvokeOption<D extends DependencyMap | undefined = undefined> = InvokeOptionObject<D> | InvokeOptionFunc<D>\n\nexport interface InvokeOptionObjectWithKeys<Deps extends Record<string, string | ProvidedKey<any, any, any>>> {\n callback: (dependencies: ResolveDependencyDeclaration<Deps>) => void | Promise<void>\n dependsOn: Deps\n}\nexport type InvokeOptionWithKeys<Deps extends Record<string, string | ProvidedKey<any, any, any>>> = InvokeOptionObjectWithKeys<Deps>\n\nexport const lifecycle: ProvidedKey<'lifecycle', Lifecycle, undefined> = { key: 'lifecycle' }\n\nexport function createContainer(options?: LoggerOptions): Container {\n const logger = options?.enabled === false\n ? createNoopLogger()\n : (options?.logger ?? createDefaultLogger())\n\n return {\n providers: new Map(),\n instances: new Map(),\n lifecycleHooks: new Map(),\n dependencyGraph: new Map(),\n invocations: [],\n logger,\n }\n}\n\n// eslint-disable-next-line unused-imports/no-unused-vars\nexport interface ProvidedKey<Key, T, D extends DependencyMap | undefined> {\n key: Key\n}\n\nexport function normalizeName(nameOrProvidedKey: string | ProvidedKey<any, any, any>): string {\n if (typeof nameOrProvidedKey === 'object' && nameOrProvidedKey !== null && 'key' in nameOrProvidedKey) {\n return (nameOrProvidedKey as ProvidedKey<any, any, any>).key as string\n }\n\n return nameOrProvidedKey as string\n}\n\nexport function normalizeProvideOption<D extends DependencyMap | undefined, T = any, Key extends string = string>(nameOrOption: Key | ProvidedKey<Key, T, D> | ProvideOption<T, D> | ProvideOptionWithKeys<T, any>, option?: (ProvideOption<T, D> | ProvideOptionWithKeys<T, any>) & { autoNameStackIndex?: number }): ProvideOptionObject<T, D> {\n if (typeof nameOrOption === 'string') {\n if (option == null || (!('build' in option) && typeof option !== 'function')) {\n throw new Error('When using provide(...) as named callback, the second argument must be either a valid ProvideOptionObject<T, D> or a ProvideOptionFunc<T, D>.')\n }\n if (typeof option === 'function') {\n return { build: option } as ProvideOptionObject<T, D>\n }\n\n return option as ProvideOptionObject<T, D>\n }\n if (typeof nameOrOption === 'object' && 'key' in nameOrOption) {\n if (option == null || (!('build' in option) && typeof option !== 'function')) {\n throw new Error('When using provide(...) as typed ProvideOptionWithKeys<T, D, Key> callback, the second argument must be either a valid ProvideOptionObject<T, D> or a ProvideOptionFunc<T, D>.')\n }\n if (typeof option === 'function') {\n return { build: option } as ProvideOptionObject<T, D>\n }\n\n return option as ProvideOptionObject<T, D>\n }\n\n if (typeof nameOrOption === 'function') {\n return { build: nameOrOption } as ProvideOptionObject<T, D>\n }\n\n return nameOrOption as ProvideOptionObject<T, D>\n}\n\nexport function provide<T, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(container: Container, name: Key, option: ProvideOptionWithKeys<T, Deps>): ProvidedKey<Key, T, ResolveDependencyDeclaration<Deps>>\nexport function provide<T, Key extends string, Deps extends Record<string, string | ProvidedKey<any, any, any>>>(container: Container, option: ProvideOptionWithKeys<T, Deps> & { autoNameStackIndex?: number }): ProvidedKey<Key, T, ResolveDependencyDeclaration<Deps>>\nexport function provide<D extends DependencyMap | undefined, T = any, Key extends string = string>(container: Container, name: Key, option: ProvideOption<T, D>): ProvidedKey<Key, T, D>\nexport function provide<D extends DependencyMap | undefined, T = any, Key extends string = string>(container: Container, option: ProvideOption<T, D> & { autoNameStackIndex?: number }): ProvidedKey<Key, T, D>\nexport function provide<D extends DependencyMap | undefined, T = any, Key extends string = string>(container: Container, nameOrOption: Key | ProvideOption<T, D> | ProvideOptionWithKeys<T, any>, option?: (ProvideOption<T, D> | ProvideOptionWithKeys<T, any>) & { autoNameStackIndex?: number }): ProvidedKey<Key, T, D> {\n const parentFile = ErrorStackParser.parse(new Error('providing'))[option?.autoNameStackIndex ?? 1]\n const name = typeof nameOrOption === 'string'\n ? nameOrOption\n : `${parentFile.fileName ?? `unknown-${nanoid()}`}:${parentFile.lineNumber ?? 0}:${parentFile.columnNumber ?? 0}`\n\n const providerObject = normalizeProvideOption<D, T, Key>(nameOrOption, option) as unknown as ProvideOptionObject<any, any>\n if (providerObject.dependsOn) {\n const resolvedDependsOn: Record<string, string> = {}\n for (const [key, value] of Object.entries(providerObject.dependsOn)) {\n resolvedDependsOn[key] = normalizeName(value)\n }\n\n providerObject.dependsOn = resolvedDependsOn\n }\n\n container.providers.set(name, providerObject)\n\n const dependencies = providerObject.dependsOn ? Object.values(providerObject.dependsOn) : []\n container.logger.provide(name, dependencies)\n container.dependencyGraph.set(name, dependencies)\n\n return { key: name } as ProvidedKey<Key, T, D>\n}\n\nexport function invoke<Deps extends Record<string, string | ProvidedKey<any, any, any>>>(container: Container, option: InvokeOptionWithKeys<Deps>): void\nexport function invoke<D extends DependencyMap>(container: Container, option: InvokeOption<D>): void\nexport function invoke<D extends DependencyMap>(container: Container, option: InvokeOption<D> | InvokeOptionWithKeys<any>): void {\n const invocationObject = typeof option === 'function'\n ? { callback: option } as InvokeOptionObject<any>\n : option as InvokeOptionObject<any>\n\n if (invocationObject.dependsOn) {\n const resolvedDependsOn: Record<string, string> = {}\n for (const [key, value] of Object.entries(invocationObject.dependsOn)) {\n resolvedDependsOn[key] = normalizeName(value)\n }\n\n invocationObject.dependsOn = resolvedDependsOn\n }\n\n const dependencies = invocationObject.dependsOn ? Object.values(invocationObject.dependsOn) : []\n\n container.logger.invoke(dependencies)\n container.invocations.push(invocationObject)\n}\n\nasync function resolveInstance<T>(container: Container, name: string): Promise<T> {\n if (container.instances.has(name)) {\n return container.instances.get(name) as T\n }\n\n const provider = container.providers.get(name)\n if (!provider) {\n throw new Error(`No provider found for '${name}'`)\n }\n\n const resolvedDependencies: Record<string, any> = {}\n let serviceLifecycle: any = null\n\n if (provider.dependsOn) {\n for (const [key, depName] of Object.entries(provider.dependsOn)) {\n if (depName === 'lifecycle') {\n // Create individual lifecycle instance for this service\n const { buildLifecycle } = await import('./builtin')\n serviceLifecycle = buildLifecycle()\n resolvedDependencies[key] = serviceLifecycle\n\n // Track this service's lifecycle\n container.lifecycleHooks.set(name, serviceLifecycle)\n }\n else {\n resolvedDependencies[key] = await resolveInstance(container, depName)\n }\n }\n }\n\n const context: BuildContext<typeof provider.dependsOn> = {\n container,\n dependsOn: resolvedDependencies,\n name,\n }\n\n container.logger.beforeRun(name)\n\n const startTime = performance.now()\n const instance = await provider.build(context)\n const duration = performance.now() - startTime\n\n container.logger.run(name, duration)\n\n container.instances.set(name, instance)\n\n return instance as T\n}\n\nfunction topologicalSort(dependencyGraph: Map<string, string[]>): string[] {\n const visited = new Set<string>()\n const visiting = new Set<string>()\n const result: string[] = []\n\n function visit(node: string) {\n if (visiting.has(node)) {\n throw new Error(`Circular dependency detected involving '${node}'`)\n }\n if (visited.has(node)) {\n return\n }\n\n visiting.add(node)\n const dependencies = dependencyGraph.get(node) || []\n for (const dep of dependencies) {\n visit(dep)\n }\n visiting.delete(node)\n visited.add(node)\n result.push(node)\n }\n\n for (const node of dependencyGraph.keys()) {\n if (!visited.has(node)) {\n visit(node)\n }\n }\n\n return result\n}\n\nexport async function startLifecycleHooks(container: Container): Promise<void> {\n const sortedServices = topologicalSort(container.dependencyGraph)\n\n for (const serviceName of sortedServices) {\n const lifecycle = container.lifecycleHooks.get(serviceName)\n if (lifecycle?.emitOnStart) {\n container.logger.hookOnStart(serviceName)\n\n const startTime = performance.now()\n await lifecycle.emitOnStart()\n const duration = performance.now() - startTime\n\n container.logger.hookOnStartComplete(serviceName, duration)\n }\n }\n}\n\nexport async function stopLifecycleHooks(container: Container): Promise<void> {\n const sortedServices = topologicalSort(container.dependencyGraph)\n\n // Shutdown in reverse order\n for (const serviceName of sortedServices.reverse()) {\n const lifecycle = container.lifecycleHooks.get(serviceName)\n if (lifecycle?.emitOnStop) {\n container.logger.hookOnStop(serviceName)\n\n const startTime = performance.now()\n await lifecycle.emitOnStop()\n const duration = performance.now() - startTime\n\n container.logger.hookOnStopComplete(serviceName, duration)\n }\n }\n}\n\nexport async function start(container: Container): Promise<void> {\n await startLifecycleHooks(container)\n\n for (const invocation of container.invocations) {\n const resolvedDependencies: Record<string, any> = {}\n\n if (invocation.dependsOn) {\n for (const [key, depName] of Object.entries(invocation.dependsOn)) {\n resolvedDependencies[key] = await resolveInstance(container, normalizeName(depName))\n }\n }\n\n await invocation.callback(resolvedDependencies)\n }\n\n container.logger.running()\n}\n\nexport async function stop(container: Container): Promise<void> {\n await stopLifecycleHooks(container)\n}\n","import {\n invoke as globalInvoke,\n provide as globalProvide,\n setLogger as globalSetLogger,\n start as globalStart,\n stop as globalStop,\n} from './global'\n\nexport type { Lifecycle } from './builtin'\n\nexport type { Logger, LoggerOptions } from './logger'\n\nexport {\n createDefaultLogger,\n createLoggLogger,\n createNoopLogger,\n} from './logger'\n\nexport {\n createContainer,\n invoke,\n lifecycle,\n provide,\n start,\n stop,\n} from './scoped'\nexport type {\n BuildContext,\n Container,\n DependencyMap,\n InvokeOption,\n InvokeOptionFunc,\n InvokeOptionObject,\n InvokeOptionObjectWithKeys,\n InvokeOptionWithKeys,\n ProvidedKey,\n ProvideOption,\n ProvideOptionFunc,\n ProvideOptionObject,\n ProvideOptionObjectWithKeys,\n ProvideOptionWithKeys,\n ResolveDependencyDeclaration,\n} from './scoped'\n\nexport const injecta = {\n provide: globalProvide,\n invoke: globalInvoke,\n start: globalStart,\n stop: globalStop,\n setLogger: globalSetLogger,\n}\n"],"mappings":";;;;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,eAAe,gBAAgB;EACxC,MAAMC,cAAY,UAAU,eAAe,IAAI,YAAY;AAC3D,MAAIA,aAAW,aAAa;AAC1B,aAAU,OAAO,YAAY,YAAY;GAEzC,MAAM,YAAY,YAAY,KAAK;AACnC,SAAMA,YAAU,aAAa;GAC7B,MAAM,WAAW,YAAY,KAAK,GAAG;AAErC,aAAU,OAAO,oBAAoB,aAAa,SAAS;;;;AAKjE,eAAsB,mBAAmB,WAAqC;CAC5E,MAAM,iBAAiB,gBAAgB,UAAU,gBAAgB;AAGjE,MAAK,MAAM,eAAe,eAAe,SAAS,EAAE;EAClD,MAAMA,cAAY,UAAU,eAAe,IAAI,YAAY;AAC3D,MAAIA,aAAW,YAAY;AACzB,aAAU,OAAO,WAAW,YAAY;GAExC,MAAM,YAAY,YAAY,KAAK;AACnC,SAAMA,YAAU,YAAY;GAC5B,MAAM,WAAW,YAAY,KAAK,GAAG;AAErC,aAAU,OAAO,mBAAmB,aAAa,SAAS;;;;AAKhE,eAAsB,MAAM,WAAqC;AAC/D,OAAM,oBAAoB,UAAU;AAEpC,MAAK,MAAM,cAAc,UAAU,aAAa;EAC9C,MAAMJ,uBAA4C,EAAE;AAEpD,MAAI,WAAW,UACb,MAAK,MAAM,CAAC,KAAK,YAAY,OAAO,QAAQ,WAAW,UAAU,CAC/D,sBAAqB,OAAO,MAAM,gBAAgB,WAAW,cAAc,QAAQ,CAAC;AAIxF,QAAM,WAAW,SAAS,qBAAqB;;AAGjD,WAAU,OAAO,SAAS;;AAG5B,eAAsB,KAAK,WAAqC;AAC9D,OAAM,mBAAmB,UAAU;;;;;AC1PrC,MAAa,UAAU;CACrB,SAASK;CACT,QAAQC;CACR,OAAOC;CACP,MAAMC;CACKC;CACZ"}
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "injeca",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "description": "Pure function programming based dependency injection library inspired by go.uber.org/fig and go.uber.org/dig.",
6
+ "author": {
7
+ "name": "Moeru AI Project AIRI Team",
8
+ "email": "airi@moeru.ai",
9
+ "url": "https://github.com/moeru-ai"
10
+ },
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/moeru-ai/injeca.git"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "type": "./dist/index.d.js",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "README.md",
24
+ "dist"
25
+ ],
26
+ "peerDependencies": {
27
+ "@guiiai/logg": ">= 1",
28
+ "error-stack-parser": "^2.1.4",
29
+ "nanoid": ">=5"
30
+ },
31
+ "peerDependenciesMeta": {
32
+ "@guiiai/logg": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "devDependencies": {
37
+ "@antfu/eslint-config": "^6.2.0",
38
+ "@moeru/eslint-config": "0.1.0-beta.13",
39
+ "@moeru/tsconfig": "0.1.0-beta.13",
40
+ "@types/node": "^24.10.1",
41
+ "bumpp": "^10.3.1",
42
+ "eslint": "^9.39.1",
43
+ "eslint-plugin-oxlint": "^1.28.0",
44
+ "oxlint": "^1.28.0",
45
+ "publint": "^0.3.15",
46
+ "taze": "^19.9.0",
47
+ "tsdown": "^0.16.4",
48
+ "typescript": "^5.9.3",
49
+ "unplugin-unused": "^0.5.6",
50
+ "vite": "^7.2.2",
51
+ "vitest": "^4.0.9"
52
+ },
53
+ "scripts": {
54
+ "build": "tsdown",
55
+ "test": "vitest --coverage",
56
+ "test:run": "vitest run",
57
+ "lint": "eslint --cache .",
58
+ "lint:fix": "eslint --cache --fix .",
59
+ "typecheck": "tsc --noEmit",
60
+ "up": "taze -w -r -I -f && pnpm prune && pnpm dedupe"
61
+ }
62
+ }