@mmstack/di 19.3.0
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 +21 -0
- package/README.md +386 -0
- package/fesm2022/mmstack-di.mjs +93 -0
- package/fesm2022/mmstack-di.mjs.map +1 -0
- package/index.d.ts +2 -0
- package/lib/injectable.d.ts +61 -0
- package/lib/root-injectable.d.ts +19 -0
- package/package.json +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026-present Miha J. Mulec
|
|
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,386 @@
|
|
|
1
|
+
# @mmstack/di
|
|
2
|
+
|
|
3
|
+
A collection of dependency injection utilities for Angular that simplify working with InjectionTokens and provide type-safe patterns for creating injectable services.
|
|
4
|
+
|
|
5
|
+
[](https://badge.fury.io/js/%40mmstack%2Fdi)
|
|
6
|
+
[](https://github.com/mihajm/mmstack/blob/master/packages/di/LICENSE)
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @mmstack/di
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Utilities
|
|
15
|
+
|
|
16
|
+
This library provides the following utilities:
|
|
17
|
+
|
|
18
|
+
- `injectable` - Creates a typed InjectionToken with inject and provide helper functions for type-safe dependency injection.
|
|
19
|
+
- `rootInjectable` - Creates a lazily-initialized root-level injectable that maintains a singleton instance.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## injectable
|
|
24
|
+
|
|
25
|
+
Creates a typed InjectionToken with convenient, type-safe inject and provider functions, eliminating boilerplate and ensuring type safety throughout your dependency injection flow. It returns a tuple of `[injectFn, provideFn]` that work together seamlessly.
|
|
26
|
+
|
|
27
|
+
The `injectable` function supports three patterns:
|
|
28
|
+
|
|
29
|
+
1. **Basic** - Returns `T | null` when not provided
|
|
30
|
+
2. **With Fallback** - Returns a default value when not provided, can be either
|
|
31
|
+
3. **With Lazy Fallback** - Same as with fallback, but the fallback iz lazily evaluated, useful for expensive fallbacks or ones that require injection
|
|
32
|
+
4. **With Error** - Throws a custom error message when not provided
|
|
33
|
+
|
|
34
|
+
### Basic Usage
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { Component, Injectable } from '@angular/core';
|
|
38
|
+
import { injectable } from '@mmstack/di';
|
|
39
|
+
|
|
40
|
+
// Create a typed injectable
|
|
41
|
+
const [injectLogger, provideLogger] = injectable<Logger>('Logger');
|
|
42
|
+
|
|
43
|
+
// Provide the value in a component or module
|
|
44
|
+
@Component({
|
|
45
|
+
selector: 'app-root',
|
|
46
|
+
providers: [
|
|
47
|
+
provideLogger({
|
|
48
|
+
log: (msg) => console.log(`[LOG]: ${msg}`),
|
|
49
|
+
error: (msg) => console.error(`[ERROR]: ${msg}`),
|
|
50
|
+
}),
|
|
51
|
+
],
|
|
52
|
+
})
|
|
53
|
+
export class AppComponent {}
|
|
54
|
+
|
|
55
|
+
// Inject it anywhere in the component tree
|
|
56
|
+
@Injectable()
|
|
57
|
+
export class DataService {
|
|
58
|
+
private logger = injectLogger(); // Logger | null
|
|
59
|
+
|
|
60
|
+
fetchData() {
|
|
61
|
+
this.logger?.log('Fetching data...');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### With Factory Dependencies
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { HttpClient } from '@angular/common/http';
|
|
70
|
+
import { injectable } from '@mmstack/di';
|
|
71
|
+
|
|
72
|
+
interface ApiConfig {
|
|
73
|
+
baseUrl: string;
|
|
74
|
+
timeout: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const [injectApiConfig, provideApiConfig] = injectable<ApiConfig>('ApiConfig');
|
|
78
|
+
|
|
79
|
+
// Provide using a factory with dependencies
|
|
80
|
+
@Component({
|
|
81
|
+
providers: [
|
|
82
|
+
provideApiConfig(
|
|
83
|
+
(http: HttpClient) => ({
|
|
84
|
+
baseUrl: 'https://api.example.com',
|
|
85
|
+
timeout: 5000,
|
|
86
|
+
}),
|
|
87
|
+
[HttpClient], // Dependencies array
|
|
88
|
+
),
|
|
89
|
+
],
|
|
90
|
+
})
|
|
91
|
+
export class AppComponent {}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### With Fallback Value
|
|
95
|
+
|
|
96
|
+
When you want to provide a default value instead of returning `null`:
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { injectable } from '@mmstack/di';
|
|
100
|
+
|
|
101
|
+
interface Theme {
|
|
102
|
+
primary: string;
|
|
103
|
+
secondary: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const [injectTheme, provideTheme] = injectable<Theme>('Theme', {
|
|
107
|
+
fallback: {
|
|
108
|
+
primary: '#007bff',
|
|
109
|
+
secondary: '#6c757d',
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// or if you need inject/lazy evaluation
|
|
114
|
+
const [injectTheme, provideTheme] = injectable<Theme>('Theme', {
|
|
115
|
+
lazyFallback: () => {
|
|
116
|
+
return {
|
|
117
|
+
primary: inject(APP_PRIMARY),
|
|
118
|
+
secondary: '#6c757d',
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
@Injectable()
|
|
124
|
+
export class ThemeService {
|
|
125
|
+
// Always returns a Theme, never null
|
|
126
|
+
private theme = injectTheme();
|
|
127
|
+
|
|
128
|
+
getPrimaryColor() {
|
|
129
|
+
return this.theme.primary; // Safe to access
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### With Error Message
|
|
135
|
+
|
|
136
|
+
When you want to enforce that the value must be provided:
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
import { injectable } from '@mmstack/di';
|
|
140
|
+
|
|
141
|
+
const [injectApiKey, provideApiKey] = injectable<string>('ApiKey', {
|
|
142
|
+
errorMessage: 'API Key is required! Please provide it using provideApiKey().',
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
@Injectable()
|
|
146
|
+
export class ApiService {
|
|
147
|
+
// Throws error if not provided
|
|
148
|
+
private apiKey = injectApiKey();
|
|
149
|
+
|
|
150
|
+
makeRequest() {
|
|
151
|
+
// apiKey is guaranteed to exist here
|
|
152
|
+
return fetch(`https://api.example.com?key=${this.apiKey}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Providing Functions as Values
|
|
158
|
+
|
|
159
|
+
The `provideFn` correctly handles functions as values (not factories):
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
import { injectable } from '@mmstack/di';
|
|
163
|
+
|
|
164
|
+
type Validator = (value: string) => boolean;
|
|
165
|
+
|
|
166
|
+
const [injectValidator, provideValidator] = injectable<Validator>('Validator');
|
|
167
|
+
|
|
168
|
+
@Component({
|
|
169
|
+
providers: [
|
|
170
|
+
// Providing a function as a value (not a factory)
|
|
171
|
+
provideValidator((value: string) => value.length > 5),
|
|
172
|
+
],
|
|
173
|
+
})
|
|
174
|
+
export class FormComponent {
|
|
175
|
+
private validator = injectValidator();
|
|
176
|
+
|
|
177
|
+
validate(input: string) {
|
|
178
|
+
return this.validator?.(input) ?? false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Advanced: Scoped Context Pattern
|
|
184
|
+
|
|
185
|
+
Create context-like dependency injection patterns:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
import { Component, Injectable } from '@angular/core';
|
|
189
|
+
import { injectable } from '@mmstack/di';
|
|
190
|
+
|
|
191
|
+
interface FormContext {
|
|
192
|
+
formId: string;
|
|
193
|
+
isDirty: boolean;
|
|
194
|
+
submit: () => void;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const [injectFormContext, provideFormContext] = injectable<FormContext>('FormContext', {
|
|
198
|
+
errorMessage: 'FormContext must be provided by a parent form component',
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
@Component({
|
|
202
|
+
selector: 'app-form',
|
|
203
|
+
providers: [
|
|
204
|
+
provideFormContext({
|
|
205
|
+
formId: 'user-form',
|
|
206
|
+
isDirty: false,
|
|
207
|
+
submit: () => console.log('Submitting form...'),
|
|
208
|
+
}),
|
|
209
|
+
],
|
|
210
|
+
template: `
|
|
211
|
+
<form>
|
|
212
|
+
<app-form-field></app-form-field>
|
|
213
|
+
<app-form-actions></app-form-actions>
|
|
214
|
+
</form>
|
|
215
|
+
`,
|
|
216
|
+
})
|
|
217
|
+
export class FormComponent {}
|
|
218
|
+
|
|
219
|
+
@Component({
|
|
220
|
+
selector: 'app-form-field',
|
|
221
|
+
template: `<input [id]="formContext.formId + '-input'" />`,
|
|
222
|
+
})
|
|
223
|
+
export class FormFieldComponent {
|
|
224
|
+
// Automatically gets the context from parent
|
|
225
|
+
formContext = injectFormContext();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
@Component({
|
|
229
|
+
selector: 'app-form-actions',
|
|
230
|
+
template: `<button (click)="formContext.submit()">Submit</button>`,
|
|
231
|
+
})
|
|
232
|
+
export class FormActionsComponent {
|
|
233
|
+
formContext = injectFormContext();
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## rootInjectable
|
|
240
|
+
|
|
241
|
+
Creates a lazily-initialized root-level injectable that maintains a singleton instance across your entire application. The factory function runs in the root injection context on first access, allowing you to inject other dependencies.
|
|
242
|
+
|
|
243
|
+
**Important:** This should only be used for pure singletons. If you need scoped instances, use regular `@Injectable` services with `providedIn` or component-level providers.
|
|
244
|
+
|
|
245
|
+
### Basic Usage
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
import { Injectable } from '@angular/core';
|
|
249
|
+
import { rootInjectable } from '@mmstack/di';
|
|
250
|
+
|
|
251
|
+
interface Logger {
|
|
252
|
+
log: (message: string) => void;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Create a root-level injectable
|
|
256
|
+
const injectLogger = rootInjectable<Logger>(() => ({
|
|
257
|
+
log: (message) => console.log(`[${new Date().toISOString()}] ${message}`),
|
|
258
|
+
}));
|
|
259
|
+
|
|
260
|
+
@Injectable()
|
|
261
|
+
export class DataService {
|
|
262
|
+
private logger = injectLogger();
|
|
263
|
+
|
|
264
|
+
fetchData() {
|
|
265
|
+
this.logger.log('Fetching data...');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
@Injectable()
|
|
270
|
+
export class UserService {
|
|
271
|
+
private logger = injectLogger(); // Same instance as above
|
|
272
|
+
|
|
273
|
+
saveUser() {
|
|
274
|
+
this.logger.log('Saving user...');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### With Dependencies
|
|
280
|
+
|
|
281
|
+
The factory function receives the root injector, allowing you to inject other services:
|
|
282
|
+
|
|
283
|
+
```typescript
|
|
284
|
+
import { HttpClient } from '@angular/common/http';
|
|
285
|
+
import { rootInjectable } from '@mmstack/di';
|
|
286
|
+
|
|
287
|
+
interface ApiClient {
|
|
288
|
+
get: (url: string) => Promise<any>;
|
|
289
|
+
post: (url: string, data: any) => Promise<any>;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const injectApiClient = rootInjectable<ApiClient>((injector) => {
|
|
293
|
+
const http = injector.get(HttpClient); // or just inject(HttpClient)
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
get: (url) => fetch(url).then((r) => r.json()),
|
|
297
|
+
post: (url, data) =>
|
|
298
|
+
fetch(url, {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
body: JSON.stringify(data),
|
|
301
|
+
}).then((r) => r.json()),
|
|
302
|
+
};
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
@Injectable()
|
|
306
|
+
export class ProductService {
|
|
307
|
+
private api = injectApiClient(); // Singleton instance
|
|
308
|
+
|
|
309
|
+
loadProducts() {
|
|
310
|
+
return this.api.get('/api/products');
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
### State Management Example
|
|
316
|
+
|
|
317
|
+
Create a simple global state manager:
|
|
318
|
+
|
|
319
|
+
```typescript
|
|
320
|
+
import { signal, computed } from '@angular/core';
|
|
321
|
+
import { rootInjectable } from '@mmstack/di';
|
|
322
|
+
|
|
323
|
+
interface User {
|
|
324
|
+
id: string;
|
|
325
|
+
name: string;
|
|
326
|
+
email: string;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
interface AuthState {
|
|
330
|
+
user: User | null;
|
|
331
|
+
isAuthenticated: boolean;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const injectAuthStore = rootInjectable(() => {
|
|
335
|
+
const user = signal<User | null>(null);
|
|
336
|
+
const isAuthenticated = computed(() => user() !== null);
|
|
337
|
+
|
|
338
|
+
return {
|
|
339
|
+
user: user.asReadonly(),
|
|
340
|
+
isAuthenticated,
|
|
341
|
+
login: (userData: User) => user.set(userData),
|
|
342
|
+
logout: () => user.set(null),
|
|
343
|
+
};
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
@Injectable()
|
|
347
|
+
export class AuthService {
|
|
348
|
+
private store = injectAuthStore(); // Singleton across app
|
|
349
|
+
|
|
350
|
+
login(email: string, password: string) {
|
|
351
|
+
// Perform authentication...
|
|
352
|
+
this.store.login({
|
|
353
|
+
id: '123',
|
|
354
|
+
name: 'John Doe',
|
|
355
|
+
email,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
logout() {
|
|
360
|
+
this.store.logout();
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
@Component({
|
|
365
|
+
selector: 'app-navbar',
|
|
366
|
+
template: `
|
|
367
|
+
@if (authStore.isAuthenticated()) {
|
|
368
|
+
<span>{{ authStore.user()?.name }}</span>
|
|
369
|
+
<button (click)="logout()">Logout</button>
|
|
370
|
+
}
|
|
371
|
+
`,
|
|
372
|
+
})
|
|
373
|
+
export class NavbarComponent {
|
|
374
|
+
authStore = injectAuthStore(); // Same instance
|
|
375
|
+
|
|
376
|
+
logout() {
|
|
377
|
+
this.authStore.logout();
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
---
|
|
383
|
+
|
|
384
|
+
## License
|
|
385
|
+
|
|
386
|
+
MIT © [Miha Mulec](https://github.com/mihajm)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, Injector, runInInjectionContext, Injectable } from '@angular/core';
|
|
3
|
+
|
|
4
|
+
function injectable(token, opt) {
|
|
5
|
+
const injectionToken = new InjectionToken(token);
|
|
6
|
+
const options = opt;
|
|
7
|
+
let fallback = options?.fallback;
|
|
8
|
+
const initFallback = options?.lazyFallback ?? (() => options?.fallback ?? null);
|
|
9
|
+
const fallbackFn = () => {
|
|
10
|
+
if (fallback === undefined)
|
|
11
|
+
fallback = initFallback();
|
|
12
|
+
return fallback;
|
|
13
|
+
};
|
|
14
|
+
const injectFn = (iOpt) => {
|
|
15
|
+
const injected = inject(injectionToken, {
|
|
16
|
+
...iOpt,
|
|
17
|
+
optional: true,
|
|
18
|
+
}) ?? fallbackFn();
|
|
19
|
+
if (injected === null && options?.errorMessage)
|
|
20
|
+
throw new Error(options.errorMessage);
|
|
21
|
+
return injected;
|
|
22
|
+
};
|
|
23
|
+
const provideFn = (fnOrValue, deps) => {
|
|
24
|
+
if (deps !== undefined)
|
|
25
|
+
return {
|
|
26
|
+
provide: injectionToken,
|
|
27
|
+
useFactory: fnOrValue,
|
|
28
|
+
deps,
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
provide: injectionToken,
|
|
32
|
+
useValue: fnOrValue,
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
return [injectFn, provideFn];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function generateID() {
|
|
39
|
+
if (globalThis.crypto?.randomUUID) {
|
|
40
|
+
return globalThis.crypto.randomUUID();
|
|
41
|
+
}
|
|
42
|
+
return Math.random().toString(36).substring(2);
|
|
43
|
+
}
|
|
44
|
+
class RootInjectables {
|
|
45
|
+
injector = inject(Injector);
|
|
46
|
+
registry = {};
|
|
47
|
+
register(register) {
|
|
48
|
+
let key = generateID();
|
|
49
|
+
while (this.registry[key]) {
|
|
50
|
+
key = generateID();
|
|
51
|
+
}
|
|
52
|
+
const injector = this.injector;
|
|
53
|
+
const value = runInInjectionContext(this.injector, () => register(injector));
|
|
54
|
+
this.registry[key] = value;
|
|
55
|
+
return key;
|
|
56
|
+
}
|
|
57
|
+
get(key) {
|
|
58
|
+
return this.registry[key];
|
|
59
|
+
}
|
|
60
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.19", ngImport: i0, type: RootInjectables, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
61
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.19", ngImport: i0, type: RootInjectables, providedIn: 'root' });
|
|
62
|
+
}
|
|
63
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.19", ngImport: i0, type: RootInjectables, decorators: [{
|
|
64
|
+
type: Injectable,
|
|
65
|
+
args: [{
|
|
66
|
+
providedIn: 'root',
|
|
67
|
+
}]
|
|
68
|
+
}] });
|
|
69
|
+
/**
|
|
70
|
+
* Creates a lazily-initialized root-level injectable that maintains a singleton instance.
|
|
71
|
+
* The factory function runs in the root injection context on first access.
|
|
72
|
+
* This should only be used for pure singletons, if you need scoped instances use regular @Injectable services.
|
|
73
|
+
*
|
|
74
|
+
* @param register - Factory function that creates the injectable instance using the root injector
|
|
75
|
+
* @returns An inject function that returns the singleton instance
|
|
76
|
+
*/
|
|
77
|
+
function rootInjectable(register) {
|
|
78
|
+
let key = null;
|
|
79
|
+
return () => {
|
|
80
|
+
const registry = inject(RootInjectables);
|
|
81
|
+
if (!key) {
|
|
82
|
+
key = registry.register(register);
|
|
83
|
+
}
|
|
84
|
+
return registry.get(key);
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Generated bundle index. Do not edit.
|
|
90
|
+
*/
|
|
91
|
+
|
|
92
|
+
export { injectable, rootInjectable };
|
|
93
|
+
//# sourceMappingURL=mmstack-di.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mmstack-di.mjs","sources":["../../../../packages/di/src/lib/injectable.ts","../../../../packages/di/src/lib/root-injectable.ts","../../../../packages/di/src/mmstack-di.ts"],"sourcesContent":["import {\n inject,\n InjectionToken,\n type AbstractType,\n type InjectOptions,\n type Provider,\n type Type,\n} from '@angular/core';\n\ntype ServiceType<T> =\n T extends Type<infer U>\n ? U\n : T extends AbstractType<infer U>\n ? U\n : T extends InjectionToken<infer U>\n ? U\n : never;\n\ntype MapDeps<T extends readonly any[]> = {\n [K in keyof T]: ServiceType<T[K]>;\n};\n\ntype ProviderFn<T> = {\n (value: T): Provider;\n <const TDeps extends any[]>(\n fn: (...deps: MapDeps<TDeps>) => T,\n deps: TDeps,\n ): Provider;\n};\n\ntype InjectFns<T> = [\n (opt?: Omit<InjectOptions, 'optional'>) => T,\n ProviderFn<T>,\n];\n\ntype FallbackInjectableOptions<T> = {\n /** Default value returned when the injectable is not provided */\n fallback: T;\n};\n\ntype LazyFallbackInjectableOptions<T> = {\n /** Function that returns a default value when the injectable is not provided. Useful for expensive defaults. */\n lazyFallback: () => T;\n};\n\ntype ErrorMessageInjectableOptions = {\n /** Error message thrown when the injectable is not provided */\n errorMessage: string;\n};\n\ntype InjectableOptions<T> =\n | FallbackInjectableOptions<T>\n | LazyFallbackInjectableOptions<T>\n | ErrorMessageInjectableOptions;\n\n/**\n * Creates a typed InjectionToken with inject and provide helper functions.\n *\n * @param token - Unique token identifier\n * @param opt - Optional configuration for fallback value or error message\n * @returns A tuple of [injectFn, provideFn] for type-safe dependency injection\n */\nexport function injectable<T>(token: string): InjectFns<T | null>;\n\n/**\n * Creates a typed InjectionToken with inject and provide helper functions.\n * Returns a fallback value when the injectable is not provided.\n *\n * @param token - Unique token identifier\n * @param opt - Configuration with fallback value\n * @returns A tuple of [injectFn, provideFn] for type-safe dependency injection\n */\nexport function injectable<T>(\n token: string,\n opt: FallbackInjectableOptions<T>,\n): InjectFns<T>;\n\n/**\n *\n * Creates a typed InjectionToken with inject and provide helper functions.\n * Returns a lazily evaluated fallback value when the injectable is not provided.\n *\n * @param token\n * @param opt\n */\nexport function injectable<T>(\n token: string,\n opt: LazyFallbackInjectableOptions<T>,\n): InjectFns<T>;\n\n/**\n * Creates a typed InjectionToken with inject and provide helper functions.\n * Throws an error with a custom message when the injectable is not provided.\n *\n * @param token - Unique token identifier\n * @param opt - Configuration with error message\n * @returns A tuple of [injectFn, provideFn] for type-safe dependency injection\n */\nexport function injectable<T>(\n token: string,\n opt: ErrorMessageInjectableOptions,\n): InjectFns<T>;\n\nexport function injectable<T>(\n token: string,\n opt?: InjectableOptions<T>,\n): InjectFns<T> {\n const injectionToken = new InjectionToken<T>(token);\n\n const options = opt as\n | Partial<\n FallbackInjectableOptions<T> &\n LazyFallbackInjectableOptions<T> &\n ErrorMessageInjectableOptions\n >\n | undefined;\n\n let fallback: T | undefined | null = options?.fallback;\n\n const initFallback =\n options?.lazyFallback ?? (() => options?.fallback ?? null);\n\n const fallbackFn = () => {\n if (fallback === undefined) fallback = initFallback();\n return fallback;\n };\n\n const injectFn = (iOpt?: Omit<InjectOptions, 'optional'>) => {\n const injected =\n inject(injectionToken, {\n ...iOpt,\n optional: true,\n }) ?? fallbackFn();\n\n if (injected === null && options?.errorMessage)\n throw new Error(options.errorMessage);\n\n return injected as T;\n };\n\n const provideFn = (\n fnOrValue: T | ((...deps: any[]) => T),\n deps?: any[],\n ): Provider => {\n if (deps !== undefined)\n return {\n provide: injectionToken,\n useFactory: fnOrValue as (...args: any[]) => T,\n deps,\n };\n\n return {\n provide: injectionToken,\n useValue: fnOrValue,\n };\n };\n\n return [injectFn, provideFn];\n}\n","import {\n inject,\n Injectable,\n Injector,\n runInInjectionContext,\n} from '@angular/core';\n\nfunction generateID() {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n return Math.random().toString(36).substring(2);\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class RootInjectables {\n private readonly injector = inject(Injector);\n private readonly registry: Record<string, any> = {};\n\n register<T>(register: (injector: Injector) => T): string {\n let key = generateID();\n\n while (this.registry[key]) {\n key = generateID();\n }\n\n const injector = this.injector;\n\n const value = runInInjectionContext(this.injector, () =>\n register(injector),\n );\n this.registry[key] = value;\n\n return key;\n }\n\n get<T>(key: string): T {\n return this.registry[key];\n }\n}\n\n/**\n * Creates a lazily-initialized root-level injectable that maintains a singleton instance.\n * The factory function runs in the root injection context on first access.\n * This should only be used for pure singletons, if you need scoped instances use regular @Injectable services.\n *\n * @param register - Factory function that creates the injectable instance using the root injector\n * @returns An inject function that returns the singleton instance\n */\nexport function rootInjectable<T>(\n register: (injector: Injector) => T,\n): () => T {\n let key: string | null = null;\n return () => {\n const registry = inject(RootInjectables);\n if (!key) {\n key = registry.register(register);\n }\n return registry.get<T>(key);\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":"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"}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { InjectionToken, type AbstractType, type InjectOptions, type Provider, type Type } from '@angular/core';
|
|
2
|
+
type ServiceType<T> = T extends Type<infer U> ? U : T extends AbstractType<infer U> ? U : T extends InjectionToken<infer U> ? U : never;
|
|
3
|
+
type MapDeps<T extends readonly any[]> = {
|
|
4
|
+
[K in keyof T]: ServiceType<T[K]>;
|
|
5
|
+
};
|
|
6
|
+
type ProviderFn<T> = {
|
|
7
|
+
(value: T): Provider;
|
|
8
|
+
<const TDeps extends any[]>(fn: (...deps: MapDeps<TDeps>) => T, deps: TDeps): Provider;
|
|
9
|
+
};
|
|
10
|
+
type InjectFns<T> = [
|
|
11
|
+
(opt?: Omit<InjectOptions, 'optional'>) => T,
|
|
12
|
+
ProviderFn<T>
|
|
13
|
+
];
|
|
14
|
+
type FallbackInjectableOptions<T> = {
|
|
15
|
+
/** Default value returned when the injectable is not provided */
|
|
16
|
+
fallback: T;
|
|
17
|
+
};
|
|
18
|
+
type LazyFallbackInjectableOptions<T> = {
|
|
19
|
+
/** Function that returns a default value when the injectable is not provided. Useful for expensive defaults. */
|
|
20
|
+
lazyFallback: () => T;
|
|
21
|
+
};
|
|
22
|
+
type ErrorMessageInjectableOptions = {
|
|
23
|
+
/** Error message thrown when the injectable is not provided */
|
|
24
|
+
errorMessage: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Creates a typed InjectionToken with inject and provide helper functions.
|
|
28
|
+
*
|
|
29
|
+
* @param token - Unique token identifier
|
|
30
|
+
* @param opt - Optional configuration for fallback value or error message
|
|
31
|
+
* @returns A tuple of [injectFn, provideFn] for type-safe dependency injection
|
|
32
|
+
*/
|
|
33
|
+
export declare function injectable<T>(token: string): InjectFns<T | null>;
|
|
34
|
+
/**
|
|
35
|
+
* Creates a typed InjectionToken with inject and provide helper functions.
|
|
36
|
+
* Returns a fallback value when the injectable is not provided.
|
|
37
|
+
*
|
|
38
|
+
* @param token - Unique token identifier
|
|
39
|
+
* @param opt - Configuration with fallback value
|
|
40
|
+
* @returns A tuple of [injectFn, provideFn] for type-safe dependency injection
|
|
41
|
+
*/
|
|
42
|
+
export declare function injectable<T>(token: string, opt: FallbackInjectableOptions<T>): InjectFns<T>;
|
|
43
|
+
/**
|
|
44
|
+
*
|
|
45
|
+
* Creates a typed InjectionToken with inject and provide helper functions.
|
|
46
|
+
* Returns a lazily evaluated fallback value when the injectable is not provided.
|
|
47
|
+
*
|
|
48
|
+
* @param token
|
|
49
|
+
* @param opt
|
|
50
|
+
*/
|
|
51
|
+
export declare function injectable<T>(token: string, opt: LazyFallbackInjectableOptions<T>): InjectFns<T>;
|
|
52
|
+
/**
|
|
53
|
+
* Creates a typed InjectionToken with inject and provide helper functions.
|
|
54
|
+
* Throws an error with a custom message when the injectable is not provided.
|
|
55
|
+
*
|
|
56
|
+
* @param token - Unique token identifier
|
|
57
|
+
* @param opt - Configuration with error message
|
|
58
|
+
* @returns A tuple of [injectFn, provideFn] for type-safe dependency injection
|
|
59
|
+
*/
|
|
60
|
+
export declare function injectable<T>(token: string, opt: ErrorMessageInjectableOptions): InjectFns<T>;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Injector } from '@angular/core';
|
|
2
|
+
import * as i0 from "@angular/core";
|
|
3
|
+
export declare class RootInjectables {
|
|
4
|
+
private readonly injector;
|
|
5
|
+
private readonly registry;
|
|
6
|
+
register<T>(register: (injector: Injector) => T): string;
|
|
7
|
+
get<T>(key: string): T;
|
|
8
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<RootInjectables, never>;
|
|
9
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<RootInjectables>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Creates a lazily-initialized root-level injectable that maintains a singleton instance.
|
|
13
|
+
* The factory function runs in the root injection context on first access.
|
|
14
|
+
* This should only be used for pure singletons, if you need scoped instances use regular @Injectable services.
|
|
15
|
+
*
|
|
16
|
+
* @param register - Factory function that creates the injectable instance using the root injector
|
|
17
|
+
* @returns An inject function that returns the singleton instance
|
|
18
|
+
*/
|
|
19
|
+
export declare function rootInjectable<T>(register: (injector: Injector) => T): () => T;
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mmstack/di",
|
|
3
|
+
"version": "19.3.0",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"angular",
|
|
6
|
+
"dependency injection",
|
|
7
|
+
"di",
|
|
8
|
+
"singleton",
|
|
9
|
+
"provider",
|
|
10
|
+
"inject"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "https://github.com/mihajm/mmstack"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/mihajm/mmstack/blob/master/packages/di",
|
|
18
|
+
"peerDependencies": {
|
|
19
|
+
"@angular/core": ">=19 <20"
|
|
20
|
+
},
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"module": "fesm2022/mmstack-di.mjs",
|
|
23
|
+
"typings": "index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
"./package.json": {
|
|
26
|
+
"default": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./index.d.ts",
|
|
30
|
+
"default": "./fesm2022/mmstack-di.mjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"tslib": "^2.3.0"
|
|
35
|
+
}
|
|
36
|
+
}
|