siringa 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.md ADDED
@@ -0,0 +1,211 @@
1
+ # Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
6
+
7
+ ##### TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ ### 1. Definitions.
10
+
11
+ "**License**" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "**Licensor**" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "**Legal Entity**" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "**control**" means **(i)** the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, _or_ **(ii)** ownership of fifty percent (50%) or more of
23
+ the outstanding shares, _or_ **(iii)** beneficial ownership of such
24
+ entity.
25
+
26
+ "**You**" (or "**Your**") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "**Source**" form shall mean the preferred form for making
30
+ modifications, including but not limited to software source code,
31
+ documentation source, and configuration files.
32
+
33
+ "**Object**" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but not
35
+ limited to compiled object code, generated documentation, and
36
+ conversions to other media types.
37
+
38
+ "**Work**" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work (an example
41
+ is provided in the Appendix below).
42
+
43
+ "**Derivative Works**" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "**Contribution**" shall mean any work of authorship, including the
52
+ original version of the Work and any modifications or additions to that
53
+ Work or Derivative Works thereof, that is intentionally submitted to
54
+ Licensor for inclusion in the Work by the copyright owner or by an
55
+ individual or Legal Entity authorized to submit on behalf of the
56
+ copyright owner. For the purposes of this definition, "**submitted**"
57
+ means any form of electronic, verbal, or written communication sent to
58
+ the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "**Not a
64
+ Contribution**".
65
+
66
+ "**Contributor**" shall mean Licensor and any individual or Legal Entity
67
+ on behalf of whom a Contribution has been received by Licensor and
68
+ subsequently incorporated within the Work.
69
+
70
+ ### 2. Grant of Copyright License.
71
+
72
+ Subject to the terms and conditions of this License, each Contributor
73
+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
74
+ royalty-free, irrevocable copyright license to reproduce, prepare
75
+ Derivative Works of, publicly display, publicly perform, sublicense,
76
+ and distribute the Work and such Derivative Works in Source or Object
77
+ form.
78
+
79
+ ### 3. Grant of Patent License.
80
+
81
+ Subject to the terms and conditions of this License, each Contributor
82
+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
83
+ royalty-free, irrevocable (except as stated in this section) patent
84
+ license to make, have made, use, offer to sell, sell, import, and
85
+ otherwise transfer the Work, where such license applies only to those
86
+ patent claims licensable by such Contributor that are necessarily
87
+ infringed by their Contribution(s) alone or by combination of their
88
+ Contribution(s) with the Work to which such Contribution(s) was
89
+ submitted. If You institute patent litigation against any entity
90
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
91
+ the Work or a Contribution incorporated within the Work constitutes
92
+ direct or contributory patent infringement, then any patent licenses
93
+ granted to You under this License for that Work shall terminate as of
94
+ the date such litigation is filed.
95
+
96
+ ### 4. Redistribution.
97
+
98
+ You may reproduce and distribute copies of the Work or Derivative Works
99
+ thereof in any medium, with or without modifications, and in Source or
100
+ Object form, provided that You meet the following conditions:
101
+
102
+ <ol type="a">
103
+ <li>You must give any other recipients of the Work or Derivative Works
104
+ a copy of this License; and
105
+ <li>You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+ <li>You must retain, in the Source form of any Derivative Works that
108
+ You distribute, all copyright, patent, trademark, and attribution
109
+ notices from the Source form of the Work, excluding those notices
110
+ that do not pertain to any part of the Derivative Works; and
111
+ <li>If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained within
114
+ such NOTICE file, excluding those notices that do not pertain to any
115
+ part of the Derivative Works, in at least one of the following
116
+ places: within a NOTICE text file distributed as part of the
117
+ Derivative Works; within the Source form or documentation, if
118
+ provided along with the Derivative Works; or, within a display
119
+ generated by the Derivative Works, if and wherever such third-party
120
+ notices normally appear. The contents of the NOTICE file are for
121
+ informational purposes only and do not modify the License. You may
122
+ add Your own attribution notices within Derivative Works that You
123
+ distribute, alongside or as an addendum to the NOTICE text from the
124
+ Work, provided that such additional attribution notices cannot be
125
+ construed as modifying the License.
126
+ </ol>
127
+
128
+ You may add Your own copyright statement to Your modifications and may
129
+ provide additional or different license terms and conditions for use,
130
+ reproduction, or distribution of Your modifications, or for any such
131
+ Derivative Works as a whole, provided Your use, reproduction, and
132
+ distribution of the Work otherwise complies with the conditions stated
133
+ in this License.
134
+
135
+ ### 5. Submission of Contributions.
136
+
137
+ Unless You explicitly state otherwise, any Contribution intentionally
138
+ submitted for inclusion in the Work by You to the Licensor shall be
139
+ under the terms and conditions of this License, without any additional
140
+ terms or conditions. Notwithstanding the above, nothing herein shall
141
+ supersede or modify the terms of any separate license agreement you may
142
+ have executed with Licensor regarding such Contributions.
143
+
144
+ ### 6. Trademarks.
145
+
146
+ This License does not grant permission to use the trade names,
147
+ trademarks, service marks, or product names of the Licensor, except as
148
+ required for reasonable and customary use in describing the origin of
149
+ the Work and reproducing the content of the NOTICE file.
150
+
151
+ ### 7. Disclaimer of Warranty.
152
+
153
+ Unless required by applicable law or agreed to in writing, Licensor
154
+ provides the Work (and each Contributor provides its Contributions) on
155
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
156
+ express or implied, including, without limitation, any warranties or
157
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
158
+ A PARTICULAR PURPOSE. You are solely responsible for determining the
159
+ appropriateness of using or redistributing the Work and assume any risks
160
+ associated with Your exercise of permissions under this License.
161
+
162
+ ### 8. Limitation of Liability.
163
+
164
+ In no event and under no legal theory, whether in tort (including
165
+ negligence), contract, or otherwise, unless required by applicable law
166
+ (such as deliberate and grossly negligent acts) or agreed to in writing,
167
+ shall any Contributor be liable to You for damages, including any
168
+ direct, indirect, special, incidental, or consequential damages of any
169
+ character arising as a result of this License or out of the use or
170
+ inability to use the Work (including but not limited to damages for loss
171
+ of goodwill, work stoppage, computer failure or malfunction, or any and
172
+ all other commercial damages or losses), even if such Contributor has
173
+ been advised of the possibility of such damages.
174
+
175
+ ### 9. Accepting Warranty or Additional Liability.
176
+
177
+ While redistributing the Work or Derivative Works thereof, You may
178
+ choose to offer, and charge a fee for, acceptance of support, warranty,
179
+ indemnity, or other liability obligations and/or rights consistent with
180
+ this License. However, in accepting such obligations, You may act only
181
+ on Your own behalf and on Your sole responsibility, not on behalf of any
182
+ other Contributor, and only if You agree to indemnify, defend, and hold
183
+ each Contributor harmless for any liability incurred by, or claims
184
+ asserted against, such Contributor by reason of your accepting any
185
+ such warranty or additional liability.
186
+
187
+ ##### END OF TERMS AND CONDITIONS
188
+
189
+ ## APPENDIX: How to apply the Apache License to your work.
190
+
191
+ To apply the Apache License to your work, attach the following
192
+ boilerplate notice, with the fields enclosed by brackets "[]"
193
+ replaced with your own identifying information. (Don't include the
194
+ brackets!) The text should be enclosed in the appropriate comment
195
+ syntax for the file format. We also recommend that a file or class name
196
+ and description of purpose be included on the same "printed page" as the
197
+ copyright notice for easier identification within third-party archives.
198
+
199
+ > #### Copyright [yyyy] [name of copyright owner]
200
+ >
201
+ > Licensed under the Apache License, Version 2.0 (the "License");
202
+ > you may not use this file except in compliance with the License.
203
+ > You may obtain a copy of the License at
204
+ >
205
+ > [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
206
+ >
207
+ > Unless required by applicable law or agreed to in writing, software
208
+ > distributed under the License is distributed on an "AS IS" BASIS,
209
+ > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
+ > See the License for the specific language governing permissions and
211
+ > limitations under the License.
package/NOTICE.md ADDED
@@ -0,0 +1,13 @@
1
+ # Copyright 2022 Juit GmbH
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,299 @@
1
+ SIRINGA
2
+ =======
3
+
4
+ > _"**siringa**"_ (italian): _"syringe"_, a tool for administering injections.
5
+
6
+ SIRINGA is an extremely simple dependency injection framework focusing on type
7
+ correctness and asynchronous injections, without relying on decorators and/or
8
+ decorator metadata.
9
+
10
+ * [Quick Start](#quick-start)
11
+ * [One-Time Injection](#one-time-injection)
12
+ * [Name-based Injection](#name-based-injection)
13
+ * [Using Factories](#using-factories)
14
+ * [Using Instances](#using-instances)
15
+ * [Child Injectors](#child-injectors)
16
+ * [API Reference](#api-reference)
17
+ * [`class Injector`](#class-injector)
18
+ * [`interface Injections`](#interface-injections)
19
+ * [Copyright Notice](NOTICE.md)
20
+ * [License](LICENSE.md)
21
+
22
+ Quick Start
23
+ -----------
24
+
25
+ At its core, SIRINGA tries to make dependency injection as easy as possible.
26
+
27
+ Classes can be _injected_ their dependencies by specifying a static `$inject`
28
+ property (a _tuple_ of injection keys):
29
+
30
+ ```ts
31
+ // A class with no dependencies, and an implicit zero-args constructor
32
+ class Foo {
33
+ foo() { /* ... your code... */ }
34
+ }
35
+
36
+ // Here "Bar" needs an instance of "Foo" to be injected
37
+ class Bar {
38
+ // The _tuple_ of required injections, this must be declared `as const`
39
+ // and the resolved types must match the constructor's arguments
40
+ static $inject = [ Foo ] as const
41
+
42
+ // Called by the injector with the correct dependencies
43
+ constructor(private _foo: Foo) {}
44
+
45
+ // Your code
46
+ bar() {
47
+ this._foo.bar()
48
+ }
49
+ }
50
+
51
+ // Create a new injector
52
+ const injector = new Injector()
53
+ .bind(Foo) // Bind "Foo" (no dependencies required)
54
+ .bind(Bar) // Bind "Bar" (requires "Foo")
55
+
56
+ // Get the singleton instance of "Bar"
57
+ const bar = await injector.get(Bar)
58
+ // Get the singleton instance of "Foo" (injection magically happens!)
59
+ const foo = await injector.get(Foo)
60
+ ```
61
+
62
+ One-Time Injection
63
+ ------------------
64
+
65
+ We can use an `Injector` also to perform one-time injections (the instance
66
+ injected won't be managed by the `Injector` itself).
67
+
68
+ Using the same `Foo` and `Bar` classes from above:
69
+
70
+ ```ts
71
+ // Create a new injector and bind Foo
72
+ const injector = new Injector().bind(Foo)
73
+
74
+ // Create a new "Bar" instance injected with its required "Foo"
75
+ const bar = await injector.inject(Bar)
76
+
77
+ // Will return the same instance given to "Bar"'s constructor
78
+ const foo = await injector.get(Foo)
79
+
80
+ // The code below will miserably fail, as "Bar" is not managed by the injector
81
+ // const bar2 = await injector.get(Bar)
82
+ ```
83
+
84
+
85
+ Name-based Injection
86
+ --------------------
87
+
88
+ Injection keys must not _necessarily_ be classes, they can also be `string`s:
89
+
90
+ ```ts
91
+ class Foo {
92
+ foo() { /* ... your code... */ }
93
+ }
94
+
95
+ class Bar {
96
+ // The string `foo` is used to identify the binding
97
+ static $inject = [ 'foo' ] as const
98
+
99
+ // Called by the injector with the correct dependencies
100
+ constructor(private _foo: Foo) {}
101
+
102
+ // Your code
103
+ bar() {
104
+ this._foo.bar()
105
+ }
106
+ }
107
+
108
+ // Create a new injector
109
+ const injector = new Injector()
110
+ .bind('foo', Foo) // Bind "Foo" to the string 'foo'
111
+ .bind('bar', Bar) // Bind "Bar" to the string 'bar'
112
+
113
+ // Get the singleton instance of "Bar"
114
+ const bar = await injector.get('bar')
115
+ // Get the singleton instance of "Foo"
116
+ const foo = await injector.get('foo')
117
+ ```
118
+
119
+ Using Factories
120
+ ---------------
121
+
122
+ The injector's `create(...)` method allows to use a _factory pattern_ to
123
+ create instances to be injected:
124
+
125
+ ```ts
126
+ class Foo {
127
+ constructor(public _value: number)
128
+ }
129
+
130
+ class Bar {
131
+ // The string `foo` is used to identify the binding
132
+ static $inject = [ Foo ] as const
133
+
134
+ // Called by the injector with the correct dependencies
135
+ constructor(private _foo: Foo) {}
136
+
137
+ // Your code
138
+ bar() {
139
+ console.log(this._foo._value)
140
+ }
141
+ }
142
+
143
+ // Create a new injector
144
+ const injector = new Injector()
145
+ .bind(Foo, (injections) => {
146
+ // The "injections" object can be used to resolve dependencies
147
+ // in the injector itself using "get(...)" or "inject(...)"
148
+
149
+ return new Foo(12345)
150
+ })
151
+
152
+ // Inject "Bar" with "Foo"
153
+ const bar = await injector.inject(Bar)
154
+
155
+ // This will print "12345"
156
+ bar.bar()
157
+ ```
158
+
159
+ As in the example above, factory methods will be given an `Injections` instance
160
+ which can be used to get instances, inject new objects, or create sub-injectors.
161
+
162
+ See the reference for [`Injections`](#interface-injections) below.
163
+
164
+ Using Instances
165
+ ---------------
166
+
167
+ Similar to factories (above) the injector's `use(...)` method allows to use
168
+ pre-baked instances as dependencies for other objects:
169
+
170
+ ```ts
171
+ class Foo {
172
+ constructor(public _value: number)
173
+ }
174
+
175
+ class Bar {
176
+ // The string `foo` is used to identify the binding
177
+ static $inject = [ Foo ] as const
178
+
179
+ // Called by the injector with the correct dependencies
180
+ constructor(private _foo: Foo) {}
181
+
182
+ // Your code
183
+ bar() {
184
+ console.log(this._foo._value)
185
+ }
186
+ }
187
+
188
+ // Create a new injector
189
+ const injector = new Injector()
190
+ .use(Foo, new Foo(12345))
191
+
192
+ // Inject "Bar" with "Foo"
193
+ const bar = await injector.inject(Bar)
194
+
195
+ // This will print "12345"
196
+ bar.bar()
197
+ ```
198
+
199
+ Child Injectors
200
+ ---------------
201
+
202
+ In some cases it is useful to create _child injectors_.
203
+
204
+ A _child injector_ inherits all the bindings from its parent, but any extra
205
+ binding declared in it won't affect its parent.
206
+
207
+ Also, a _child injector_ can _redeclare_ a binding without affecting its parent.
208
+
209
+ For example (using silly strings to simplify the inner workings!)
210
+
211
+ ```ts
212
+ const parent = new Injector()
213
+ .use('foo', 'parent foo')
214
+
215
+ const child = parent.injector()
216
+ .create('parentFoo', async (injections) => {
217
+ const s = await injections.get('foo') // this is the parent's value!!!
218
+ return `${s} from a child`
219
+ }
220
+ .use('foo', 'child foo')
221
+
222
+ await parent.get('foo') // this will return "parent foo"
223
+ await child.get('foo') // this will return "child foo" (overrides parent)
224
+
225
+ await child.get('parentFoo') // this will return "parent foo from a child"
226
+ // await parent.get('parentFoo') // fails, as parent doesn't define "parentFoo"
227
+ ```
228
+
229
+ API Reference
230
+ -------------
231
+
232
+ Quick-and-dirty reference for our types (for details, everything should be
233
+ annotated with _JSDoc_).
234
+
235
+ ### `class Injector`
236
+
237
+ #### Binding
238
+
239
+ * `injector.bind(component: Constructor): Injector` \
240
+ Bind the specified constructor (a _class_) to the injector
241
+
242
+ * `injector.bind(component: Constructor, implementation: Constructor): Injector` \
243
+ Bind the specified component (a _class_) to the injector, and use the
244
+ specified implementation (another _class_ extending the component) to
245
+ create instances
246
+
247
+ * `injector.bind(name: string, implementation: Constructor): Injector` \
248
+ Bind the specified name (a _string) to the injector, and use the
249
+ specified implementation (a _class_ ) to create instances
250
+
251
+ #### Factories
252
+
253
+ * `injector.create(component: Constructor, factory: Factory): Injector` \
254
+ Use the specified factory (a _function_) to create instances for the
255
+ specified _component_ (a _class_)
256
+
257
+ * `injector.create(name: string, factory: Factory): Injector` \
258
+ Use the specified factory (a _function_) to create instances for the
259
+ specified name (a _string_)
260
+
261
+ #### Instances
262
+
263
+ * `injector.use(component: Constructor, instance: any): Injector` \
264
+ Bind the specified instance to a component (a _class_).
265
+
266
+ * `injector.create(name: string, instance: any): Injector` \
267
+ Bind the specified instance to a name (a _string_).
268
+
269
+ #### Injections
270
+
271
+ * `injections.get(component: Constructor): Instance` \
272
+ Returns the instance bound to the specified constructor (a _class_)
273
+
274
+ * `injections.get(name: string): Instance` \
275
+ Returns the instance bound to the specified name (a _string_)
276
+
277
+ * `injections.inject(injectable: Constructor): Instance` \
278
+ Create a new instance of the given injectable (a _class_) injecting all its
279
+ required dependencies
280
+
281
+ #### Sub Injectors
282
+
283
+ * `injections.injector(): Injector` \
284
+ Create a sub-injector (child) of the current one
285
+
286
+ ### `class Injections`
287
+
288
+ * `injections.get(component: Constructor): Instance` \
289
+ Returns the instance bound to the specified constructor (a _class_)
290
+
291
+ * `injections.get(name: string): Instance` \
292
+ Returns the instance bound to the specified name (a _string_)
293
+
294
+ * `injections.inject(injectable: Constructor): Instance` \
295
+ Create a new instance of the given injectable (a _class_) injecting all its
296
+ required dependencies
297
+
298
+ * `injections.injector(): Injector` \
299
+ Create a sub-injector (child) of the current one
package/dist/index.js ADDED
@@ -0,0 +1,97 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __reExport = (target, module2, copyDefault, desc) => {
11
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
12
+ for (let key of __getOwnPropNames(module2))
13
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
14
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
15
+ }
16
+ return target;
17
+ };
18
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
19
+ return (module2, temp) => {
20
+ return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
21
+ };
22
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
23
+
24
+ // src/index.ts
25
+ var src_exports = {};
26
+ __export(src_exports, {
27
+ Injector: () => Injector
28
+ });
29
+ function bindingName(binding) {
30
+ return typeof binding === "function" ? `[class ${binding.name}]` : `"${binding}"`;
31
+ }
32
+ var Injector = class {
33
+ #factories = /* @__PURE__ */ new Map();
34
+ #promises = /* @__PURE__ */ new Map();
35
+ #parent;
36
+ async #get(binding, stack) {
37
+ if (stack.includes(binding)) {
38
+ if (this.#parent)
39
+ return this.#parent.#get(binding, []);
40
+ const message2 = `Recursion detected injecting ${bindingName(binding)}`;
41
+ return Promise.reject(new Error(message2));
42
+ }
43
+ const promise = this.#promises.get(binding);
44
+ if (promise)
45
+ return promise;
46
+ const factory = this.#factories.get(binding);
47
+ if (factory) {
48
+ const promise2 = Promise.resolve().then(() => factory([...stack, binding]));
49
+ this.#promises.set(binding, promise2);
50
+ return promise2;
51
+ }
52
+ if (this.#parent)
53
+ return this.#parent.#get(binding, []);
54
+ const message = `Unable to resolve binding ${bindingName(binding)}`;
55
+ return Promise.reject(new Error(message));
56
+ }
57
+ async #inject(injectable, stack) {
58
+ var _a;
59
+ const promises = (_a = injectable.$inject) == null ? void 0 : _a.map((binding) => this.#get(binding, stack));
60
+ const injections = promises ? await Promise.all(promises) : [];
61
+ return new injectable(...injections);
62
+ }
63
+ bind(binding, maybeInjectable) {
64
+ const injectable = maybeInjectable ? maybeInjectable : binding;
65
+ this.#factories.set(binding, async (stack) => this.#inject(injectable, stack));
66
+ return this;
67
+ }
68
+ create(binding, factory) {
69
+ this.#factories.set(binding, async (stack) => factory({
70
+ get: (component) => this.#get(component, stack),
71
+ inject: async (injectable) => this.#inject(injectable, stack),
72
+ injector: () => this.injector()
73
+ }));
74
+ return this;
75
+ }
76
+ use(binding, instance) {
77
+ this.#promises.set(binding, Promise.resolve(instance));
78
+ return this;
79
+ }
80
+ async get(binding) {
81
+ return this.#get(binding, []);
82
+ }
83
+ async inject(injectable) {
84
+ return this.#inject(injectable, []);
85
+ }
86
+ injector() {
87
+ const injector = new Injector();
88
+ injector.#parent = this;
89
+ return injector;
90
+ }
91
+ };
92
+ module.exports = __toCommonJS(src_exports);
93
+ // Annotate the CommonJS export names for ESM import in node:
94
+ 0 && (module.exports = {
95
+ Injector
96
+ });
97
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AA4HA,qBAAqB,SAA0B;AAC7C,SAAO,OAAO,YAAY,aAAa,UAAU,QAAQ,UAAU,IAAI;AAAA;AA0DlE,qBAGyC;AAAA,EACrC,aAA+D,oBAAI;AAAA,EACnE,YAAwC,oBAAI;AAAA,EACrD;AAAA,QAIM,KAAK,SAAkB,OAAgC;AAC3D,QAAI,MAAM,SAAS,UAAU;AAC3B,UAAI;AAAc,eAAO,kBAAkB,SAAS;AACpD,YAAM,WAAU,gCAAgC,YAAY;AAC5D,aAAO,QAAQ,OAAO,IAAI,MAAM;AAAA;AAGlC,UAAM,UAAU,eAAe,IAAI;AACnC,QAAI;AAAS,aAAO;AAEpB,UAAM,UAAU,gBAAgB,IAAI;AACpC,QAAI,SAAS;AACX,YAAM,WAAU,QAAQ,UAAU,KAAK,MAAM,QAAQ,CAAE,GAAG,OAAO;AACjE,qBAAe,IAAI,SAAS;AAC5B,aAAO;AAAA;AAGT,QAAI;AAAc,aAAO,kBAAkB,SAAS;AAEpD,UAAM,UAAU,6BAA6B,YAAY;AACzD,WAAO,QAAQ,OAAO,IAAI,MAAM;AAAA;AAAA,QAG5B,QAAQ,YAAgD,OAAgC;AAxNhG;AAyNI,UAAM,WAAW,iBAAW,YAAX,mBAAoB,IAAI,CAAC,YAAiB,UAAU,SAAS;AAC9E,UAAM,aAAa,WAAW,MAAM,QAAQ,IAAI,YAAY;AAG5D,WAAO,IAAI,WAAW,GAAG;AAAA;AAAA,EAuB3B,KACE,SACA,iBACM;AACN,UAAM,aAAa,kBAAkB,kBACjC;AAEJ,oBAAgB,IAAI,SAAS,OAAO,UAAU,aAAa,YAAY;AACvE,WAAO;AAAA;AAAA,EAkBT,OACE,SACA,SACM;AACN,oBAAgB,IAAI,SAAS,OAAO,UAAU,QAAQ;AAAA,MACpD,KAAK,CAAC,cAAmB,UAAU,WAAW;AAAA,MAC9C,QAAQ,OAAO,eAAoB,aAAa,YAAY;AAAA,MAC5D,UAAU,MAAM,KAAK;AAAA;AAGvB,WAAO;AAAA;AAAA,EAkBT,IACE,SACA,UACM;AACN,mBAAe,IAAI,SAAS,QAAQ,QAAQ;AAC5C,WAAO;AAAA;AAAA,QAYH,IACJ,SACc;AACd,WAAO,UAAU,SAAS;AAAA;AAAA,QAStB,OACJ,YAC0B;AAC1B,WAAO,aAAa,YAAY;AAAA;AAAA,EAMlC,WAA6C;AAC3C,UAAM,WAAW,IAAI;AACrB,uBAAmB;AACnB,WAAO;AAAA;AAAA;",
5
+ "names": []
6
+ }
package/dist/index.mjs ADDED
@@ -0,0 +1,68 @@
1
+ // src/index.ts
2
+ function bindingName(binding) {
3
+ return typeof binding === "function" ? `[class ${binding.name}]` : `"${binding}"`;
4
+ }
5
+ var Injector = class {
6
+ #factories = /* @__PURE__ */ new Map();
7
+ #promises = /* @__PURE__ */ new Map();
8
+ #parent;
9
+ async #get(binding, stack) {
10
+ if (stack.includes(binding)) {
11
+ if (this.#parent)
12
+ return this.#parent.#get(binding, []);
13
+ const message2 = `Recursion detected injecting ${bindingName(binding)}`;
14
+ return Promise.reject(new Error(message2));
15
+ }
16
+ const promise = this.#promises.get(binding);
17
+ if (promise)
18
+ return promise;
19
+ const factory = this.#factories.get(binding);
20
+ if (factory) {
21
+ const promise2 = Promise.resolve().then(() => factory([...stack, binding]));
22
+ this.#promises.set(binding, promise2);
23
+ return promise2;
24
+ }
25
+ if (this.#parent)
26
+ return this.#parent.#get(binding, []);
27
+ const message = `Unable to resolve binding ${bindingName(binding)}`;
28
+ return Promise.reject(new Error(message));
29
+ }
30
+ async #inject(injectable, stack) {
31
+ var _a;
32
+ const promises = (_a = injectable.$inject) == null ? void 0 : _a.map((binding) => this.#get(binding, stack));
33
+ const injections = promises ? await Promise.all(promises) : [];
34
+ return new injectable(...injections);
35
+ }
36
+ bind(binding, maybeInjectable) {
37
+ const injectable = maybeInjectable ? maybeInjectable : binding;
38
+ this.#factories.set(binding, async (stack) => this.#inject(injectable, stack));
39
+ return this;
40
+ }
41
+ create(binding, factory) {
42
+ this.#factories.set(binding, async (stack) => factory({
43
+ get: (component) => this.#get(component, stack),
44
+ inject: async (injectable) => this.#inject(injectable, stack),
45
+ injector: () => this.injector()
46
+ }));
47
+ return this;
48
+ }
49
+ use(binding, instance) {
50
+ this.#promises.set(binding, Promise.resolve(instance));
51
+ return this;
52
+ }
53
+ async get(binding) {
54
+ return this.#get(binding, []);
55
+ }
56
+ async inject(injectable) {
57
+ return this.#inject(injectable, []);
58
+ }
59
+ injector() {
60
+ const injector = new Injector();
61
+ injector.#parent = this;
62
+ return injector;
63
+ }
64
+ };
65
+ export {
66
+ Injector
67
+ };
68
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "mappings": ";AA4HA,qBAAqB,SAA0B;AAC7C,SAAO,OAAO,YAAY,aAAa,UAAU,QAAQ,UAAU,IAAI;AAAA;AA0DlE,qBAGyC;AAAA,EACrC,aAA+D,oBAAI;AAAA,EACnE,YAAwC,oBAAI;AAAA,EACrD;AAAA,QAIM,KAAK,SAAkB,OAAgC;AAC3D,QAAI,MAAM,SAAS,UAAU;AAC3B,UAAI;AAAc,eAAO,kBAAkB,SAAS;AACpD,YAAM,WAAU,gCAAgC,YAAY;AAC5D,aAAO,QAAQ,OAAO,IAAI,MAAM;AAAA;AAGlC,UAAM,UAAU,eAAe,IAAI;AACnC,QAAI;AAAS,aAAO;AAEpB,UAAM,UAAU,gBAAgB,IAAI;AACpC,QAAI,SAAS;AACX,YAAM,WAAU,QAAQ,UAAU,KAAK,MAAM,QAAQ,CAAE,GAAG,OAAO;AACjE,qBAAe,IAAI,SAAS;AAC5B,aAAO;AAAA;AAGT,QAAI;AAAc,aAAO,kBAAkB,SAAS;AAEpD,UAAM,UAAU,6BAA6B,YAAY;AACzD,WAAO,QAAQ,OAAO,IAAI,MAAM;AAAA;AAAA,QAG5B,QAAQ,YAAgD,OAAgC;AAxNhG;AAyNI,UAAM,WAAW,iBAAW,YAAX,mBAAoB,IAAI,CAAC,YAAiB,UAAU,SAAS;AAC9E,UAAM,aAAa,WAAW,MAAM,QAAQ,IAAI,YAAY;AAG5D,WAAO,IAAI,WAAW,GAAG;AAAA;AAAA,EAuB3B,KACE,SACA,iBACM;AACN,UAAM,aAAa,kBAAkB,kBACjC;AAEJ,oBAAgB,IAAI,SAAS,OAAO,UAAU,aAAa,YAAY;AACvE,WAAO;AAAA;AAAA,EAkBT,OACE,SACA,SACM;AACN,oBAAgB,IAAI,SAAS,OAAO,UAAU,QAAQ;AAAA,MACpD,KAAK,CAAC,cAAmB,UAAU,WAAW;AAAA,MAC9C,QAAQ,OAAO,eAAoB,aAAa,YAAY;AAAA,MAC5D,UAAU,MAAM,KAAK;AAAA;AAGvB,WAAO;AAAA;AAAA,EAkBT,IACE,SACA,UACM;AACN,mBAAe,IAAI,SAAS,QAAQ,QAAQ;AAC5C,WAAO;AAAA;AAAA,QAYH,IACJ,SACc;AACd,WAAO,UAAU,SAAS;AAAA;AAAA,QAStB,OACJ,YAC0B;AAC1B,WAAO,aAAa,YAAY;AAAA;AAAA,EAMlC,WAA6C;AAC3C,UAAM,WAAW,IAAI;AACrB,uBAAmB;AACnB,WAAO;AAAA;AAAA;",
5
+ "names": []
6
+ }
package/index.d.ts ADDED
@@ -0,0 +1,109 @@
1
+ /** A generic constructor */
2
+ declare type Constructor<T = any> = abstract new (...args: any) => T;
3
+ /**
4
+ * Check that an `Injector`'s static `$inject` member matches the `Injector`'s
5
+ * own components and provisions
6
+ */
7
+ declare type CheckInject<Inject, // the tuple from "$inject"
8
+ Components extends Constructor, // the `Injector`'s components
9
+ Provisions extends Record<string, any>> = Inject extends readonly [] ? readonly [] : Inject extends readonly [infer I1] ? I1 extends keyof Provisions ? readonly [I1] : I1 extends Extract<Components, I1> ? readonly [I1] : readonly [never] : Inject extends readonly [infer I1, ...infer I2] ? readonly [
10
+ ...CheckInject<[I1], Components, Provisions>,
11
+ ...CheckInject<I2, Components, Provisions>
12
+ ] : readonly [Components | keyof Provisions, ...(Components | keyof Provisions)[]];
13
+ /**
14
+ * Map the contents of the static `$inject` member to their types, resolving
15
+ * named provisions.
16
+ */
17
+ declare type MapInject<Inject, // the tuple from "$inject"
18
+ Provisions extends Record<string, any>> = Inject extends readonly [] ? readonly [] : Inject extends readonly [infer I1] ? I1 extends keyof Provisions ? readonly [Provisions[I1]] : I1 extends Constructor ? readonly [InstanceType<I1>] : readonly [never] : Inject extends readonly [infer I1, ...infer I2] ? readonly [
19
+ ...MapInject<[I1], Provisions>,
20
+ ...MapInject<I2, Provisions>
21
+ ] : readonly [never];
22
+ /**
23
+ * Check that an `Injectable` is valid for a given `Injector`.
24
+ */
25
+ declare type CheckInjectable<I extends Injectable<Components, Provisions>, // the `Injectable` to check
26
+ Components extends Constructor, // the `Injector`'s components
27
+ Provisions extends Record<string, any>> = I extends {
28
+ $inject: infer Inject;
29
+ } ? {
30
+ $inject: CheckInject<Inject, Components, Provisions>;
31
+ new (...args: MapInject<Inject, Provisions>): any;
32
+ } : I extends new () => any ? I : {
33
+ $inject: readonly [Components | keyof Provisions, ...(Components | keyof Provisions)[]];
34
+ };
35
+ /**
36
+ * Return the unrolled type of a `Promise`
37
+ */
38
+ declare type UnrollPromise<T> = T extends Promise<infer T> ? UnrollPromise<T> : T;
39
+ /**
40
+ * Override the type for an `Injector`'s existing provision, or add a new one
41
+ */
42
+ declare type ExtendProvisions<Provisions extends Record<string, any>, // the `Injector`'s provisions
43
+ P extends string, // the new (string) key of the provision
44
+ T> = {
45
+ [key in P | keyof Provisions]: key extends P ? UnrollPromise<T> : Provisions[key];
46
+ };
47
+ /** An `Injectable` defines a constructor for an injectable class */
48
+ export interface Injectable<Components extends Constructor, Provisions extends Record<string, any>, T = any> {
49
+ prototype: T;
50
+ new (...args: any): T;
51
+ $inject?: readonly (Components | keyof Provisions)[];
52
+ }
53
+ /**
54
+ * The `Injections` interface abstracts the idea of getting bound and
55
+ * provisioned instances from an `Injector`, injecting new `Injectable`
56
+ * instances, and creating sub-`Injector`s.
57
+ */
58
+ export interface Injections<Components extends Constructor, Provisions extends Record<string, any>> {
59
+ /** Get a _bound_ instance from an `Injector`. */
60
+ get<C extends Components>(component: C): Promise<InstanceType<C>>;
61
+ /** Get a _provisioned_ instance from an `Injector`. */
62
+ get<P extends keyof Provisions>(provision: P): Promise<Provisions[P]>;
63
+ /**
64
+ * Create a new instance of the specified `Injectable`, providing it with all
65
+ * necessary injections.
66
+ *
67
+ * @param injectable The constructor of the instance to create.
68
+ */
69
+ inject<I extends Injectable<Components, Provisions>>(injectable: I & CheckInjectable<I, Components, Provisions>): Promise<InstanceType<I>>;
70
+ /** Create a sub-`Injector` child of the current one. */
71
+ injector(): Injector<Components, Provisions>;
72
+ }
73
+ /** A `Factory` is a _function_ creating instances of a given type. */
74
+ export declare type Factory<Components extends Constructor = Constructor, Provisions extends Record<string, any> = Record<string, any>, T = any> = (injections: Injections<Components, Provisions>) => T | Promise<T>;
75
+ /**
76
+ * The `Injector` class acts as a registry of components and provisions,
77
+ * creating instances and injecting dependencies.
78
+ */
79
+ export declare class Injector<Components extends Constructor = never, Provisions extends Record<string, any> = {}> implements Injections<Components, Provisions> {
80
+ #private;
81
+ /** Bind an `Injectable` to this `Injector`. */
82
+ bind<I extends Injectable<Components, Provisions>>(injectable: I & CheckInjectable<I, Components, Provisions>): Injector<Components | I, Provisions>;
83
+ /** Bind an `Injectable` to a `Constructor` in this `Injector`. */
84
+ bind<C extends Constructor, I extends Injectable<Components, Provisions, InstanceType<C>>>(component: C, injectable: I & CheckInjectable<I, Components, Provisions>): Injector<Components | C, Provisions>;
85
+ /** Bind an `Injectable` to a name in this `Injector`. */
86
+ bind<P extends string, I extends Injectable<Components, Provisions>>(provision: P, injectable: I & CheckInjectable<I, Components, Provisions>): Injector<Components, ExtendProvisions<Provisions, P, InstanceType<I>>>;
87
+ /** Use a `Factory` to create instances bound to the given `Constructor`. */
88
+ create<C extends Constructor>(component: C, factory: Factory<Components, Provisions, InstanceType<C>>): Injector<Components | C, Provisions>;
89
+ /** Use a `Factory` to create instances bound to the given name. */
90
+ create<P extends string, F extends Factory<Components, Provisions>>(provision: P, factory: F): Injector<Components, ExtendProvisions<Provisions, P, ReturnType<F>>>;
91
+ /** Use the given instance binding it to to the given `Constructor`. */
92
+ use<C extends Constructor>(component: C, instance: InstanceType<C>): Injector<Components | C, Provisions>;
93
+ /** Use the given instance binding it to to the given name. */
94
+ use<P extends string, T>(provision: P, instance: T): Injector<Components, ExtendProvisions<Provisions, P, T>>;
95
+ /** Get a _bound_ instance from an `Injector` */
96
+ get<C extends Components>(component: C): Promise<InstanceType<C>>;
97
+ /** Get a _provisioned_ instance from an `Injector` */
98
+ get<P extends keyof Provisions>(provision: P): Promise<Provisions[P]>;
99
+ /**
100
+ * Create a new instance of the specified `Injectable`, providing all
101
+ * necessary injections.
102
+ *
103
+ * @param injectable The constructor of the instance to create.
104
+ */
105
+ inject<I extends Injectable<Components, Provisions>>(injectable: I & CheckInjectable<I, Components, Provisions>): Promise<InstanceType<I>>;
106
+ /** Create a sub-`Injector` child of this one. */
107
+ injector(): Injector<Components, Provisions>;
108
+ }
109
+ export {};
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "siringa",
3
+ "version": "0.0.1",
4
+ "description": "Simple type-checking injection library for Typescript",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.mjs",
10
+ "require": "./dist/index.js"
11
+ }
12
+ },
13
+ "types": "./index.d.ts",
14
+ "scripts": {
15
+ "build": "./build.sh",
16
+ "dev": "nodemon -e ts -x ./build.sh -w src -w test -w test-d",
17
+ "lint": "eslint src test test-d",
18
+ "prepare": "patch -N -p0 -i .nyc.patch || true"
19
+ },
20
+ "author": "Juit Developers <developers@juit.com>",
21
+ "license": "Apache-2.0",
22
+ "devDependencies": {
23
+ "@types/chai": "^4.3.0",
24
+ "@types/chai-as-promised": "^7.1.5",
25
+ "@types/mocha": "^9.1.0",
26
+ "@types/node": "~16.11.26",
27
+ "@typescript-eslint/eslint-plugin": "^5.12.1",
28
+ "@typescript-eslint/parser": "^5.12.1",
29
+ "chai": "^4.3.6",
30
+ "chai-as-promised": "^7.1.1",
31
+ "esbuild": "^0.14.23",
32
+ "eslint": "^8.9.0",
33
+ "eslint-config-google": "^0.14.0",
34
+ "mocha": "^9.2.1",
35
+ "nodemon": "^2.0.15",
36
+ "nyc": "^15.1.0",
37
+ "source-map-support": "^0.5.21",
38
+ "tsd": "^0.19.1",
39
+ "typescript": "^4.5.5"
40
+ },
41
+ "directories": {
42
+ "test": "test"
43
+ }
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,342 @@
1
+ /** A generic constructor */
2
+ type Constructor<T = any> = abstract new (...args: any) => T
3
+
4
+ /* ========================================================================== */
5
+
6
+ /**
7
+ * Check that an `Injector`'s static `$inject` member matches the `Injector`'s
8
+ * own components and provisions
9
+ */
10
+ type CheckInject<
11
+ Inject, // the tuple from "$inject"
12
+ Components extends Constructor, // the `Injector`'s components
13
+ Provisions extends Record<string, any>, // the `Injector`'s provisions
14
+ > =
15
+ // if "$inject" is an empty array, then we're fine
16
+ Inject extends readonly [] ?
17
+ readonly [] :
18
+
19
+ // if "$inject" is a single-element tuple, check that that this element is
20
+ // actually included in the list of components
21
+ Inject extends readonly [ infer I1 ] ?
22
+ I1 extends keyof Provisions ?
23
+ readonly [ I1 ] :
24
+ I1 extends Extract<Components, I1> ?
25
+ readonly [ I1 ] :
26
+ readonly [ never ] :
27
+
28
+ // if "$inject" is a multi-element tuple, recurse (twice) by cheking the first
29
+ // element as a single-element tuple (see above), and the remaining members.
30
+ Inject extends readonly [ infer I1, ...infer I2 ] ?
31
+ readonly [
32
+ ...CheckInject<[ I1 ], Components, Provisions>,
33
+ ...CheckInject<I2, Components, Provisions>,
34
+ ] :
35
+
36
+ // "$inject" here is something else (likely, an array but not "as const")
37
+ // so we want to fail by re-declaring it as a tuple
38
+ readonly [ Components | keyof Provisions, ...(Components | keyof Provisions)[] ]
39
+
40
+ /* ========================================================================== */
41
+
42
+ /**
43
+ * Map the contents of the static `$inject` member to their types, resolving
44
+ * named provisions.
45
+ */
46
+ type MapInject<
47
+ Inject, // the tuple from "$inject"
48
+ Provisions extends Record<string, any>, // the `Injector`'s provisions
49
+ > =
50
+ // if "$inject" is an empty array, then we're fine
51
+ Inject extends readonly [] ?
52
+ readonly [] :
53
+
54
+ // "$inject" is a single-element tuple
55
+ Inject extends readonly [ infer I1 ] ?
56
+ I1 extends keyof Provisions ?
57
+ readonly [ Provisions[I1] ] :
58
+ I1 extends Constructor ?
59
+ readonly [ InstanceType<I1> ] :
60
+ readonly [ never ] :
61
+
62
+ // "$inject" is a multi-element tuple (recurse)
63
+ Inject extends readonly [ infer I1, ...infer I2 ] ?
64
+ readonly [
65
+ ...MapInject<[ I1 ], Provisions>,
66
+ ...MapInject<I2, Provisions>,
67
+ ] :
68
+
69
+ // "$inject" is something else
70
+ readonly [ never ]
71
+
72
+ /* ========================================================================== */
73
+
74
+ /**
75
+ * Check that an `Injectable` is valid for a given `Injector`.
76
+ */
77
+ type CheckInjectable<
78
+ I extends Injectable<Components, Provisions>, // the `Injectable` to check
79
+ Components extends Constructor, // the `Injector`'s components
80
+ Provisions extends Record<string, any>, // the `Injector`'s provisions
81
+ > =
82
+ // If the static "$inject" member is specified, check it and map its
83
+ // types as constructor arguments for the `Injectable`
84
+ I extends { $inject: infer Inject } ?
85
+ {
86
+ $inject: CheckInject<Inject, Components, Provisions>,
87
+ new (...args: MapInject<Inject, Provisions>): any,
88
+ } :
89
+
90
+ // If "$inject" is not specified, the only valid injector is one with
91
+ // an empty (zero arguments) constructor
92
+ I extends new () => any ?
93
+ I :
94
+
95
+ // Anything else requires "$inject" to be present
96
+ { $inject: readonly [ Components | keyof Provisions, ...(Components | keyof Provisions)[] ] }
97
+
98
+ /* ========================================================================== */
99
+
100
+ /**
101
+ * Return the unrolled type of a `Promise`
102
+ */
103
+ type UnrollPromise<T> = T extends Promise<infer T> ? UnrollPromise<T> : T
104
+
105
+ /* ========================================================================== */
106
+
107
+ /**
108
+ * Override the type for an `Injector`'s existing provision, or add a new one
109
+ */
110
+ type ExtendProvisions<
111
+ Provisions extends Record<string, any>, // the `Injector`'s provisions
112
+ P extends string, // the new (string) key of the provision
113
+ T, // the new type associated with the provision key
114
+ > = {
115
+ [ key in P | keyof Provisions ]:
116
+ key extends P ?
117
+ UnrollPromise<T> :
118
+ Provisions[key]
119
+ }
120
+
121
+ /* ========================================================================== */
122
+
123
+ type Binding = Constructor | string
124
+
125
+ function bindingName(binding: Binding): string {
126
+ return typeof binding === 'function' ? `[class ${binding.name}]` : `"${binding}"`
127
+ }
128
+
129
+ /* ========================================================================== *
130
+ * EXPORTED TYPES *
131
+ * ========================================================================== */
132
+
133
+ /** An `Injectable` defines a constructor for an injectable class */
134
+ export interface Injectable<
135
+ Components extends Constructor,
136
+ Provisions extends Record<string, any>,
137
+ T = any,
138
+ > {
139
+ prototype: T
140
+ new (...args: any): T
141
+ $inject?: readonly (Components | keyof Provisions)[]
142
+ }
143
+
144
+ /**
145
+ * The `Injections` interface abstracts the idea of getting bound and
146
+ * provisioned instances from an `Injector`, injecting new `Injectable`
147
+ * instances, and creating sub-`Injector`s.
148
+ */
149
+ export interface Injections<
150
+ Components extends Constructor,
151
+ Provisions extends Record<string, any>,
152
+ > {
153
+ /** Get a _bound_ instance from an `Injector`. */
154
+ get<C extends Components>(component: C): Promise<InstanceType<C>>
155
+
156
+ /** Get a _provisioned_ instance from an `Injector`. */
157
+ get<P extends keyof Provisions>(provision: P): Promise<Provisions[P]>
158
+
159
+ /**
160
+ * Create a new instance of the specified `Injectable`, providing it with all
161
+ * necessary injections.
162
+ *
163
+ * @param injectable The constructor of the instance to create.
164
+ */
165
+ inject<I extends Injectable<Components, Provisions>>(
166
+ injectable: I & CheckInjectable<I, Components, Provisions>,
167
+ ): Promise<InstanceType<I>>
168
+
169
+ /** Create a sub-`Injector` child of the current one. */
170
+ injector(): Injector<Components, Provisions>
171
+ }
172
+
173
+ /** A `Factory` is a _function_ creating instances of a given type. */
174
+ export type Factory<
175
+ Components extends Constructor = Constructor,
176
+ Provisions extends Record<string, any> = Record<string, any>,
177
+ T = any,
178
+ > = (injections: Injections<Components, Provisions>) => T | Promise<T>
179
+
180
+ /**
181
+ * The `Injector` class acts as a registry of components and provisions,
182
+ * creating instances and injecting dependencies.
183
+ */
184
+ export class Injector<
185
+ Components extends Constructor = never,
186
+ Provisions extends Record<string, any> = {},
187
+ > implements Injections<Components, Provisions> {
188
+ readonly #factories: Map<Binding, (stack: Binding[]) => Promise<any>> = new Map()
189
+ readonly #promises: Map<Binding, Promise<any>> = new Map()
190
+ #parent?: Injector<Constructor, Record<string, any>>
191
+
192
+ /* INTERNALS ============================================================== */
193
+
194
+ async #get(binding: Binding, stack: Binding[]): Promise<any> {
195
+ if (stack.includes(binding)) {
196
+ if (this.#parent) return this.#parent.#get(binding, [])
197
+ const message = `Recursion detected injecting ${bindingName(binding)}`
198
+ return Promise.reject(new Error(message))
199
+ }
200
+
201
+ const promise = this.#promises.get(binding)
202
+ if (promise) return promise
203
+
204
+ const factory = this.#factories.get(binding)
205
+ if (factory) {
206
+ const promise = Promise.resolve().then(() => factory([ ...stack, binding ]))
207
+ this.#promises.set(binding, promise)
208
+ return promise
209
+ }
210
+
211
+ if (this.#parent) return this.#parent.#get(binding, [])
212
+
213
+ const message = `Unable to resolve binding ${bindingName(binding)}`
214
+ return Promise.reject(new Error(message))
215
+ }
216
+
217
+ async #inject(injectable: Injectable<Components, Provisions>, stack: Binding[]): Promise<any> {
218
+ const promises = injectable.$inject?.map((binding: any) => this.#get(binding, stack))
219
+ const injections = promises ? await Promise.all(promises) : []
220
+
221
+ // eslint-disable-next-line new-cap
222
+ return new injectable(...injections)
223
+ }
224
+
225
+ /* BINDING ================================================================ */
226
+
227
+ /** Bind an `Injectable` to this `Injector`. */
228
+ bind<I extends Injectable<Components, Provisions>>(
229
+ injectable: I & CheckInjectable<I, Components, Provisions>,
230
+ ): Injector<Components | I, Provisions>
231
+
232
+ /** Bind an `Injectable` to a `Constructor` in this `Injector`. */
233
+ bind<C extends Constructor, I extends Injectable<Components, Provisions, InstanceType<C>>>(
234
+ component: C,
235
+ injectable: I & CheckInjectable<I, Components, Provisions>,
236
+ ): Injector<Components | C, Provisions>
237
+
238
+ /** Bind an `Injectable` to a name in this `Injector`. */
239
+ bind<P extends string, I extends Injectable<Components, Provisions>>(
240
+ provision: P,
241
+ injectable: I & CheckInjectable<I, Components, Provisions>,
242
+ ): Injector<Components, ExtendProvisions<Provisions, P, InstanceType<I>>>
243
+
244
+ // Overloaded implementation
245
+ bind(
246
+ binding: Binding,
247
+ maybeInjectable?: Injectable<Components, Provisions>,
248
+ ): this {
249
+ const injectable = maybeInjectable ? maybeInjectable :
250
+ binding as Injectable<Components, Provisions>
251
+
252
+ this.#factories.set(binding, async (stack) => this.#inject(injectable, stack))
253
+ return this
254
+ }
255
+
256
+ /* FACTORIES ============================================================== */
257
+
258
+ /** Use a `Factory` to create instances bound to the given `Constructor`. */
259
+ create<C extends Constructor>(
260
+ component: C,
261
+ factory: Factory<Components, Provisions, InstanceType<C>>,
262
+ ): Injector<Components | C, Provisions>
263
+
264
+ /** Use a `Factory` to create instances bound to the given name. */
265
+ create<P extends string, F extends Factory<Components, Provisions>>(
266
+ provision: P,
267
+ factory: F,
268
+ ): Injector<Components, ExtendProvisions<Provisions, P, ReturnType<F>>>
269
+
270
+ // Overloaded implementation
271
+ create(
272
+ binding: Binding,
273
+ factory: Factory<Components, Provisions>,
274
+ ): this {
275
+ this.#factories.set(binding, async (stack) => factory({
276
+ get: (component: any) => this.#get(component, stack),
277
+ inject: async (injectable: any) => this.#inject(injectable, stack),
278
+ injector: () => this.injector(),
279
+ }))
280
+
281
+ return this
282
+ }
283
+
284
+ /* INSTANCES ============================================================== */
285
+
286
+ /** Use the given instance binding it to to the given `Constructor`. */
287
+ use<C extends Constructor>(
288
+ component: C,
289
+ instance: InstanceType<C>,
290
+ ): Injector<Components | C, Provisions>
291
+
292
+ /** Use the given instance binding it to to the given name. */
293
+ use<P extends string, T>(
294
+ provision: P,
295
+ instance: T,
296
+ ): Injector<Components, ExtendProvisions<Provisions, P, T>>
297
+
298
+ // Overloaded implementation
299
+ use(
300
+ binding: Binding,
301
+ instance: any,
302
+ ): this {
303
+ this.#promises.set(binding, Promise.resolve(instance))
304
+ return this
305
+ }
306
+
307
+ /* INSTANCES ============================================================== */
308
+
309
+ /** Get a _bound_ instance from an `Injector` */
310
+ get<C extends Components>(component: C): Promise<InstanceType<C>>
311
+
312
+ /** Get a _provisioned_ instance from an `Injector` */
313
+ get<P extends keyof Provisions>(provision: P): Promise<Provisions[P]>
314
+
315
+ // Overloaded implementation
316
+ async get<B extends Binding>(
317
+ binding: B,
318
+ ): Promise<any> {
319
+ return this.#get(binding, [])
320
+ }
321
+
322
+ /**
323
+ * Create a new instance of the specified `Injectable`, providing all
324
+ * necessary injections.
325
+ *
326
+ * @param injectable The constructor of the instance to create.
327
+ */
328
+ async inject<I extends Injectable<Components, Provisions>>(
329
+ injectable: I & CheckInjectable<I, Components, Provisions>,
330
+ ): Promise<InstanceType<I>> {
331
+ return this.#inject(injectable, [])
332
+ }
333
+
334
+ /* CHILD INJECTORS ======================================================== */
335
+
336
+ /** Create a sub-`Injector` child of this one. */
337
+ injector(): Injector<Components, Provisions> {
338
+ const injector = new Injector<Components, Provisions>()
339
+ injector.#parent = this
340
+ return injector
341
+ }
342
+ }