alepha 0.8.1 → 0.9.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/core.d.ts CHANGED
@@ -2,308 +2,132 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { TypeCheck } from "@sinclair/typebox/compiler";
3
3
  import * as TypeBoxValue from "@sinclair/typebox/value";
4
4
  import * as TypeBox from "@sinclair/typebox";
5
- import { ArrayOptions, FormatRegistry, IntegerOptions, NumberOptions, ObjectOptions, SchemaOptions, Static, Static as Static$1, StaticDecode, StaticEncode, StringOptions, TAny, TAny as TAny$1, TArray, TArray as TArray$1, TBoolean, TBoolean as TBoolean$1, TComposite, TInteger, TIntersect, TMappedResult, TNull, TNumber, TNumber as TNumber$1, TObject, TObject as TObject$1, TOmit, TOptional, TOptionalWithFlag, TPartial, TPartialFromMappedResult, TPick, TProperties, TProperties as TProperties$1, TRecord, TRecord as TRecord$1, TRecordOrObject, TSchema, TSchema as TSchema$1, TString, TString as TString$1, TUndefined, TUnion, TUnsafe, TVoid, Type, TypeGuard, Union, UnsafeOptions } from "@sinclair/typebox";
5
+ import { ArrayOptions, FormatRegistry, IntegerOptions, NumberOptions, ObjectOptions, SchemaOptions, Static, Static as Static$1, StaticDecode, StaticEncode, StringOptions, TAny, TAny as TAny$1, TArray, TArray as TArray$1, TBoolean, TBoolean as TBoolean$1, TComposite, TInteger, TIntersect, TNull, TNumber, TNumber as TNumber$1, TObject, TObject as TObject$1, TOmit, TOptional, TOptionalWithFlag, TPartial, TPick, TProperties, TProperties as TProperties$1, TRecord, TRecord as TRecord$1, TSchema, TSchema as TSchema$1, TString, TString as TString$1, TUnion, TUnsafe, TypeGuard, UnsafeOptions } from "@sinclair/typebox";
6
6
  import { ValueError } from "@sinclair/typebox/errors";
7
7
  import { Readable } from "node:stream";
8
8
  import { ReadableStream as ReadableStream$1 } from "node:stream/web";
9
9
 
10
10
  //#region src/constants/KIND.d.ts
11
11
  /**
12
- * Used for identifying descriptors.
13
- *
14
- * @internal
15
- */
12
+ * Used for identifying descriptors.
13
+ *
14
+ * @internal
15
+ */
16
16
  declare const KIND: unique symbol;
17
- //#endregion
18
- //#region src/constants/OPTIONS.d.ts
19
- /**
20
- * Used for descriptors options.
21
- *
22
- * @internal
23
- */
24
- declare const OPTIONS: unique symbol;
25
- //#endregion
26
- //#region src/interfaces/Async.d.ts
27
- // ---------------------------------------------------------------------------------------------------------------------
28
- /**
29
- * Represents a value that can be either a value or a promise.
30
- */
31
- type Async<T> = T | Promise<T>;
32
- // ---------------------------------------------------------------------------------------------------------------------
33
- /**
34
- * Represents a function that returns a promise.
35
- */
36
- type PromiseFn = (...args: any[]) => Promise<any>;
37
- // ---------------------------------------------------------------------------------------------------------------------
38
- /**
39
- * Represents a function that returns an async value.
40
- */
41
- type AsyncFn = (...args: any[]) => Async<any>;
42
- // ---------------------------------------------------------------------------------------------------------------------
43
- type MaybePromise<T> = T extends Promise<any> ? T : Promise<T>;
17
+ //# sourceMappingURL=KIND.d.ts.map
44
18
  //#endregion
45
19
  //#region src/interfaces/Service.d.ts
46
- // ---------------------------------------------------------------------------------------------------------------------
47
20
  /**
48
- * In Alepha, a service is a class that can be instantiated. Nothing more, nothing less.
49
- */
50
- type Service<T extends object = any> = InstantiableService<T> | AbstractService<T>;
51
- type InstantiableService<T extends object = any> = new (...args: any[]) => T;
52
- type AbstractService<T extends object = any> = abstract new (...args: any[]) => T;
53
- // ---------------------------------------------------------------------------------------------------------------------
21
+ * In Alepha, a service is a class that can be instantiated or an abstract class. Nothing more, nothing less...
22
+ */
23
+ type Service<T extends object = any> = InstantiableClass<T> | AbstractClass<T>;
24
+ type InstantiableClass<T extends object = any> = new (...args: any[]) => T;
25
+ /**
26
+ * Abstract class is a class that cannot be instantiated directly!
27
+ * It widely used for defining interfaces.
28
+ */
29
+ type AbstractClass<T extends object = any> = abstract new (...args: any[]) => T;
54
30
  /**
55
- * Service substitution allows you to register a class as a different class.
56
- */
31
+ * Service substitution allows you to register a class as a different class.
32
+ * Providing class A, but using class B instead.
33
+ * This is useful for testing, mocking, or providing a different implementation of a service.
34
+ *
35
+ * class A is mostly an AbstractClass, while class B is an InstantiableClass.
36
+ */
57
37
  interface ServiceSubstitution<T extends object = any> {
58
38
  /**
59
- * Every time someone asks for this service, it will be provided with the 'use' service.
60
- */
39
+ * Every time someone asks for this class, it will be provided with the 'use' class.
40
+ */
61
41
  provide: Service<T>;
62
42
  /**
63
- * Service to use instead of the 'provide' service.
64
- *
65
- * Note: Syntax is based on Angular's DI system.
66
- */
43
+ * Service to use instead of the 'provide' service.
44
+ *
45
+ * Syntax is inspired by Angular's DI system.
46
+ */
67
47
  use: Service<T>;
68
48
  /**
69
- * If true and the service already exists, just ignore the substitution and do not throw an error.
70
- * Mostly used for plugins to enforce a substitution without throwing an error.
71
- */
49
+ * If true, if the service already exists -> just ignore the substitution and do not throw an error.
50
+ * Mostly used for plugins to enforce a substitution without throwing an error.
51
+ */
72
52
  optional?: boolean;
73
53
  }
74
- // ---------------------------------------------------------------------------------------------------------------------
75
54
  /**
76
- * Every time you register a service, you can use this type to define it.
77
- *
78
- * alepha.with( ServiceEntry )
79
- * or
80
- * alepha.with( provide: ServiceEntry, use: MyOwnServiceEntry )
81
- *
82
- * And yes, you declare the *type* of the service, not the *instance*.
83
- */
55
+ * Every time you register a service, you can use this type to define it.
56
+ *
57
+ * alepha.with( ServiceEntry )
58
+ * or
59
+ * alepha.with( provide: ServiceEntry, use: MyOwnServiceEntry )
60
+ *
61
+ * And yes, you declare the *type* of the service, not the *instance*.
62
+ */
84
63
  type ServiceEntry<T extends object = any> = Service<T> | ServiceSubstitution<T>;
64
+ //# sourceMappingURL=Service.d.ts.map
85
65
  //#endregion
86
- //#region src/descriptors/$hook.d.ts
87
- declare const KEY = "HOOK";
88
- /**
89
- * Registers a new hook.
90
- *
91
- * ```ts
92
- * import { $hook } from "alepha";
93
- *
94
- * class MyProvider {
95
- * onStart = $hook({
96
- * name: "start", // or "configure", "ready", "stop", ...
97
- * handler: async (app) => {
98
- * // await db.connect(); ...
99
- * }
100
- * });
101
- * }
102
- * ```
103
- *
104
- * Hooks are used to run async functions from all registered providers/services.
105
- *
106
- * You can't register a hook after the App has started.
107
- *
108
- * It's used under the hood by the `configure`, `start`, and `stop` methods.
109
- * Some modules also use hooks to run their own logic. (e.g. `@alepha/server`).
110
- *
111
- * You can create your own hooks by using module augmentation:
112
- *
113
- * ```ts
114
- * declare module "alepha" {
115
- *
116
- * interface Hooks {
117
- * "my:custom:hook": {
118
- * arg1: string;
119
- * }
120
- * }
121
- * }
122
- *
123
- * await alepha.emit("my:custom:hook", { arg1: "value" });
124
- * ```
125
- *
126
- */
127
- declare const $hook: {
128
- <T extends keyof Hooks>(options: HookOptions<T>): HookDescriptor<T>;
129
- [KIND]: string;
66
+ //#region src/helpers/descriptor.d.ts
67
+ declare const descriptorEvents: {
68
+ events: Map<Service, ((alepha: Alepha) => void)[]>;
69
+ on(descriptor: Service, callback: (alepha: Alepha) => void): void;
70
+ emit(descriptor: Service, alepha: Alepha): void;
71
+ bind(when: Service, register: Service): void;
130
72
  };
131
- interface HookOptions<T extends keyof Hooks> {
132
- /**
133
- * The name of the hook. "configure", "start", "ready", "stop", ...
134
- */
135
- on: T;
136
- /**
137
- * The handler to run when the hook is triggered.
138
- */
139
- handler: (app: Hooks[T]) => Async<any>;
140
- /**
141
- * Force the hook to run first or last on the list of hooks.
142
- */
143
- priority?: "first" | "last";
144
- /**
145
- * Empty placeholder, not working yet. :-)
146
- */
147
- before?: object | Array<object>;
148
- /**
149
- * Empty placeholder, not working yet. :-)
150
- */
151
- after?: object | Array<object>;
73
+ interface DescriptorArgs<T extends object = {}> {
74
+ options: T;
75
+ alepha: Alepha;
76
+ service: InstantiableClass<Service>;
77
+ module?: Service;
152
78
  }
153
- interface Hook<T extends keyof Hooks = any> {
154
- caller?: Service;
155
- priority?: "first" | "last";
156
- callback: (payload: Hooks[T]) => Async<void>;
79
+ interface DescriptorConfig {
80
+ propertyKey: string;
81
+ service: InstantiableClass<Service>;
82
+ module?: Service;
157
83
  }
158
- interface HookDescriptor<T extends keyof Hooks> {
159
- [KIND]: typeof KEY;
160
- [OPTIONS]: HookOptions<T>;
161
- (app: Hooks[T]): Async<any>;
84
+ declare abstract class Descriptor<T extends object = {}> {
85
+ protected readonly alepha: Alepha;
86
+ readonly options: T;
87
+ readonly config: DescriptorConfig;
88
+ constructor(args: DescriptorArgs<T>);
89
+ /**
90
+ * Called automatically by Alepha after the descriptor is created.
91
+ */
92
+ protected onInit(): void;
162
93
  }
94
+ type DescriptorFactory<TDescriptor extends Descriptor = Descriptor> = {
95
+ (options: TDescriptor["options"]): TDescriptor;
96
+ [KIND]: InstantiableClass<TDescriptor>;
97
+ };
98
+ type DescriptorFactoryLike<T extends object = any> = {
99
+ (options: T): any;
100
+ [KIND]: any;
101
+ };
102
+ declare const createDescriptor: <TDescriptor extends Descriptor>(descriptor: InstantiableClass<TDescriptor>, options: TDescriptor["options"]) => TDescriptor;
103
+ //# sourceMappingURL=descriptor.d.ts.map
163
104
  //#endregion
164
105
  //#region src/helpers/Module.d.ts
165
106
  interface Module {
166
- name?: string;
107
+ $name?: string;
167
108
  $services: (alepha: Alepha) => void | Alepha;
168
109
  }
169
110
  interface ModuleDefinition extends Module {
170
111
  services: Array<Service>;
171
112
  }
172
- // ---------------------------------------------------------------------------------------------------------------------
173
113
  declare const isModule: (value: unknown) => value is Module;
174
114
  declare const toModuleName: (name: string) => string;
115
+ //# sourceMappingURL=Module.d.ts.map
175
116
  //#endregion
176
- //#region src/descriptors/$cursor.d.ts
177
- /**
178
- * Get Alepha instance and Class definition from the current context.
179
- * This should be used inside a descriptor only.
180
- *
181
- * ```ts
182
- * import { $cursor } from "alepha";
183
- *
184
- * const $ = () => {
185
- *
186
- * const { context, definition } = $cursor();
187
- *
188
- * // context - alepha instance
189
- * // definition - class which is creating this descriptor
190
- *
191
- * return {};
192
- * }
193
- *
194
- * ```
195
- *
196
- * @internal
197
- */
198
- declare const $cursor: () => CursorDescriptor;
199
- // ---------------------------------------------------------------------------------------------------------------------
200
- /**
201
- * /!\ Global variable /!\
202
- *
203
- * Store the current context and definition during injection phase.
204
- *
205
- * @internal
206
- */
207
- declare const __alephaRef: {
208
- context?: Alepha;
209
- definition?: Service;
210
- module?: ModuleDefinition;
211
- $services?: {
212
- module: ModuleDefinition;
213
- parent: Service;
214
- };
215
- };
216
- // ---------------------------------------------------------------------------------------------------------------------
217
- /**
218
- * Cursor descriptor.
219
- */
220
- interface CursorDescriptor {
221
- context: Alepha;
222
- definition?: Service;
223
- module?: ModuleDefinition;
224
- }
225
- //#endregion
226
- //#region src/helpers/EventEmitterLike.d.ts
227
- // ---------------------------------------------------------------------------------------------------------------------
228
- /**
229
- * Low-cost event emitter like for internal use.
230
- * Used only for descriptor implicit registration.
231
- */
232
- declare class EventEmitterLike<TEvents extends {
233
- [key: string]: any;
234
- }> {
235
- private hooks;
236
- on<T extends keyof TEvents>(event: T, callback: (data: TEvents[T]) => void): void;
237
- emit<T extends keyof TEvents>(event: T, data: TEvents[T]): void;
238
- }
239
- //#endregion
240
- //#region src/helpers/descriptor.d.ts
241
- // ---------------------------------------------------------------------------------------------------------------------
242
- /**
243
- * Descriptor events.
244
- *
245
- * - `create` - Emitted when a descriptor is created.
246
- */
247
- declare const descriptorEvents: EventEmitterLike<{
248
- create: CursorDescriptor & {
249
- [KIND]: string;
250
- };
251
- }>;
252
- // ---------------------------------------------------------------------------------------------------------------------
253
- /**
254
- * Register a descriptor.
255
- *
256
- * This is used to run the event "create" and allow auto-registration of descriptors.
257
- *
258
- * @internal
259
- * @param kind
260
- */
261
- declare const __descriptor: (kind: string) => void;
262
- // ---------------------------------------------------------------------------------------------------------------------
263
- /**
264
- * Auto-inject a class/module when a descriptor is created.
265
- *
266
- * Like, you auto-inject the ServerModule when a `$route` descriptor is used.
267
- *
268
- * @param descriptor
269
- * @param to
270
- */
271
- declare const __bind: (descriptor: {
272
- [KIND]: string;
273
- }, ...to: Service[]) => void;
274
- // ---------------------------------------------------------------------------------------------------------------------
275
- /**
276
- * Check if the value is a descriptor value.
277
- *
278
- * @param value - Value to check.
279
- * @returns Is the value a descriptor value.
280
- */
281
- declare const isDescriptorValue: (value: any) => value is DescriptorIdentifier;
282
- // ---------------------------------------------------------------------------------------------------------------------
117
+ //#region src/interfaces/Async.d.ts
283
118
  /**
284
- * The "$descriptor" function.
285
- */
286
- interface Descriptor<T extends object = any> {
287
- [KIND]: string;
288
- (options: T): DescriptorIdentifier<T>;
289
- }
290
- // ---------------------------------------------------------------------------------------------------------------------
119
+ * Represents a value that can be either a value or a promise of value.
120
+ */
121
+ type Async<T> = T | Promise<T>;
291
122
  /**
292
- * Class member descriptor.
293
- */
294
- interface DescriptorIdentifier<T = object> {
295
- [KIND]: string;
296
- [OPTIONS]: T;
297
- }
298
- // ---------------------------------------------------------------------------------------------------------------------
123
+ * Represents a function that returns an async value.
124
+ */
125
+ type AsyncFn = (...args: any[]) => Async<any>;
299
126
  /**
300
- * Descriptor identifier + his instance + his key.
301
- */
302
- interface DescriptorItem<T extends Descriptor> {
303
- value: ReturnType<T>;
304
- key: string;
305
- instance: Record<string, any>;
306
- }
127
+ * Transforms a type T into a promise if it is not already a promise.
128
+ */
129
+ type MaybePromise<T> = T extends Promise<any> ? T : Promise<T>;
130
+ //# sourceMappingURL=Async.d.ts.map
307
131
  //#endregion
308
132
  //#region src/providers/AlsProvider.d.ts
309
133
  type AsyncLocalStorageData = any;
@@ -316,70 +140,70 @@ declare class AlsProvider {
316
140
  get<T>(key: string): T | undefined;
317
141
  set<T>(key: string, value: T): void;
318
142
  }
143
+ //# sourceMappingURL=AlsProvider.d.ts.map
319
144
  //#endregion
320
145
  //#region src/services/Logger.d.ts
321
- // ---------------------------------------------------------------------------------------------------------------------
322
146
  type LogLevel = "error" | "warn" | "info" | "debug" | "trace" | "silent";
323
- // ---------------------------------------------------------------------------------------------------------------------
324
147
  interface LoggerEnv {
325
148
  /**
326
- * Default log level for the application.
327
- * Default by environment:
328
- * - dev = "debug"
329
- * - test = "error"
330
- * - prod = "info"
331
- *
332
- * "trace" | "debug" | "info" | "warn" | "error" | "silent"
333
- */
149
+ * Default log level for the application.
150
+ * Default by environment:
151
+ * - dev = "debug"
152
+ * - test = "error"
153
+ * - prod = "info"
154
+ *
155
+ * "trace" | "debug" | "info" | "warn" | "error" | "silent"
156
+ */
334
157
  LOG_LEVEL?: string;
335
158
  /**
336
- * Disable colors in the console output.
337
- */
159
+ * Disable colors in the console output.
160
+ */
338
161
  NO_COLOR?: string;
339
162
  /**
340
- * Force color output for the application.
341
- */
163
+ * Force color output for the application.
164
+ */
342
165
  FORCE_COLOR?: string;
343
166
  /**
344
- * Log format.
345
- *
346
- * @default "text"
347
- */
167
+ * Log format.
168
+ *
169
+ * @default "text"
170
+ */
348
171
  LOG_FORMAT?: "json" | "text" | "cli" | "raw";
349
172
  }
350
- // ---------------------------------------------------------------------------------------------------------------------
351
173
  interface LoggerOptions {
352
174
  /**
353
- * The logging level. Can be one of "error", "warn", "info", "debug", or "trace".
354
- */
175
+ * The logging level. Can be one of "error", "warn", "info", "debug", or "trace".
176
+ */
355
177
  level?: string;
178
+ /**
179
+ * The name of the application. Used to identify the source of the log messages.
180
+ */
356
181
  app?: string;
357
182
  /**
358
- * The name of the logger. Like a module name or a service name.
359
- */
183
+ * The name of the logger. Like a module name or a service name.
184
+ */
360
185
  name?: string;
361
186
  /**
362
- * An optional context to include in the log output. Like a request ID or a correlation ID.
363
- */
187
+ * An optional context to include in the log output. Like a request ID or a correlation ID.
188
+ */
364
189
  context?: string;
365
190
  /**
366
- * An optional tag to include in the log output. Like a class name or a module name.
367
- */
191
+ * An optional tag to include in the log output. Like a class name or a module name.
192
+ */
368
193
  caller?: string;
369
194
  /**
370
- * Whether to use colors in the log output. Defaults to true.
371
- */
195
+ * Whether to use colors in the log output. Defaults to true.
196
+ */
372
197
  color?: boolean;
373
198
  /**
374
- * Log output format. Can be "json", "text", or "cli".
375
- */
199
+ * Log output format. Can be "json", "text", or "cli".
200
+ */
376
201
  format?: string;
377
202
  /**
378
- * An optional async local storage provider to use for storing context information.
379
- */
203
+ * An optional async local storage provider to use for storing context information.
204
+ */
380
205
  als?: AlsProvider;
381
206
  }
382
- // ---------------------------------------------------------------------------------------------------------------------
383
207
  declare const COLORS: {
384
208
  reset: string;
385
209
  grey: string;
@@ -392,7 +216,6 @@ declare const COLORS: {
392
216
  darkGrey: string;
393
217
  };
394
218
  declare const LEVEL_COLORS: Record<string, string>;
395
- // ---------------------------------------------------------------------------------------------------------------------
396
219
  declare class Logger {
397
220
  protected levelOrder: Record<string, number>;
398
221
  readonly level: string;
@@ -414,32 +237,34 @@ declare class Logger {
414
237
  debug(message: unknown, data?: object | Error | string): void;
415
238
  trace(message: unknown, data?: object | Error | string): void;
416
239
  /**
417
- * Log a message to the console.
418
- */
240
+ * Log a message to the console.
241
+ */
419
242
  protected log(level: LogLevel, message: unknown, data?: object | Error | string): void;
420
243
  /**
421
- * Print a log message to the console.
422
- */
244
+ * Print a log message to the console.
245
+ */
423
246
  protected print(formatted: string): void;
424
247
  /**
425
- * Format a log message to JSON.
426
- */
248
+ * Format a log message to JSON.
249
+ */
427
250
  protected formatJson(level: LogLevel, message: unknown, data?: object | Error | string): string;
428
251
  protected formatJsonError(error: Error): object;
429
252
  /**
430
- * Format a log message to a string.
431
- */
253
+ * Format a log message to a string.
254
+ */
432
255
  protected formatLog(level: LogLevel, message: string, data?: object | Error): string;
256
+ protected nowTimeFormatted(): string;
257
+ protected pad2: (n: number) => string;
258
+ protected pad3: (n: number) => string;
433
259
  protected colorize(color: string, text: string, reset?: string): string;
434
260
  /**
435
- * Format an error to a string.
436
- *
437
- * @param error
438
- * @protected
439
- */
261
+ * Format an error to a string.
262
+ *
263
+ * @param error
264
+ * @protected
265
+ */
440
266
  protected formatError(error: Error): string;
441
267
  }
442
- // ---------------------------------------------------------------------------------------------------------------------
443
268
  declare class MockLogger extends Logger {
444
269
  store: MockLoggerStore;
445
270
  constructor(options?: LoggerOptions & {
@@ -449,7 +274,6 @@ declare class MockLogger extends Logger {
449
274
  child(options: LoggerOptions): MockLogger;
450
275
  reset(): void;
451
276
  }
452
- // ---------------------------------------------------------------------------------------------------------------------
453
277
  interface MockLoggerStore {
454
278
  stack: Array<{
455
279
  date: string;
@@ -459,515 +283,594 @@ interface MockLoggerStore {
459
283
  app?: string;
460
284
  } & Record<string, any>>;
461
285
  }
286
+ //# sourceMappingURL=Logger.d.ts.map
462
287
  //#endregion
463
288
  //#region src/Alepha.d.ts
464
289
  /**
465
- * Core container of the Alepha framework.
466
- *
467
- * It is responsible for managing the lifecycle of services,
468
- * handling dependency injection,
469
- * and providing a unified interface for the application.
470
- *
471
- * @example
472
- * ```ts
473
- * import { Alepha, run } from "alepha";
474
- *
475
- * class MyService {
476
- * // business logic here
477
- * }
478
- *
479
- * const alepha = Alepha.create({
480
- * // state, env, and other properties
481
- * })
482
- *
483
- * alepha.with(MyService);
484
- *
485
- * run(alepha); // trigger .start (and .stop) automatically
486
- * ```
487
- *
488
- * > Some alepha methods are not intended to be used directly, use descriptors instead.
489
- * >
490
- * > - $hook -> alepha.on()
491
- * > - $inject -> alepha.get(), alepha.parseEnv()
492
- */
290
+ * Core container of the Alepha framework.
291
+ *
292
+ * It is responsible for managing the lifecycle of services,
293
+ * handling dependency injection,
294
+ * and providing a unified interface for the application.
295
+ *
296
+ * @example
297
+ * ```ts
298
+ * import { Alepha, run } from "alepha";
299
+ *
300
+ * class MyService {
301
+ * // business logic here
302
+ * }
303
+ *
304
+ * const alepha = Alepha.create({
305
+ * // state, env, and other properties
306
+ * })
307
+ *
308
+ * alepha.with(MyService);
309
+ *
310
+ * run(alepha); // trigger .start (and .stop) automatically
311
+ * ```
312
+ *
313
+ * ### Alepha Factory
314
+ *
315
+ * Alepha.create() is an enhanced version of new Alepha().
316
+ * - It merges `process.env` with the provided state.env when available.
317
+ * - It populates the test hooks for Vitest or Jest environments when available.
318
+ *
319
+ * new Alepha() is fine if you don't need these helpers.
320
+ *
321
+ * ### Platforms & Environments
322
+ *
323
+ * Alepha is designed to work in various environments:
324
+ * - **Browser**: Runs in the browser, using the global `window` object.
325
+ * - **Serverless**: Runs in serverless environments like Vercel or Vite.
326
+ * - **Test**: Runs in test environments like Jest or Vitest.
327
+ * - **Production**: Runs in production environments, typically with NODE_ENV set to "production".
328
+ * * You can check the current environment using the following methods:
329
+ *
330
+ * - `isBrowser()`: Returns true if the App is running in a browser environment.
331
+ * - `isServerless()`: Returns true if the App is running in a serverless environment.
332
+ * - `isTest()`: Returns true if the App is running in a test environment.
333
+ * - `isProduction()`: Returns true if the App is running in a production environment.
334
+ *
335
+ * ### State & Environment
336
+ *
337
+ * The state of the Alepha container is stored in the `store` property.
338
+ * Most important property is `store.env`, which contains the environment variables.
339
+ *
340
+ * ```ts
341
+ * const alepha = Alepha.create({ env: { MY_VAR: "value" } });
342
+ *
343
+ * // You can access the environment variables using alepha.env
344
+ * console.log(alepha.env.MY_VAR); // "value"
345
+ *
346
+ * // But you should use $env() descriptor to get typed values from the environment.
347
+ * class App {
348
+ * env = $env(
349
+ * t.object({
350
+ * MY_VAR: t.string(),
351
+ * })
352
+ * );
353
+ * }
354
+ * ```
355
+ *
356
+ * ### Modules
357
+ *
358
+ * Modules are a way to group services together.
359
+ * You can register a module using the `$module` descriptor.
360
+ *
361
+ * ```ts
362
+ * import { $module } from "alepha";
363
+ *
364
+ * class MyLib {}
365
+ *
366
+ * const myModule = $module({
367
+ * name: "my.project.module",
368
+ * services: [MyLib],
369
+ * });
370
+ * ```
371
+ *
372
+ * Do not use modules for small applications.
373
+ *
374
+ * ### Hooks
375
+ *
376
+ * Hooks are a way to run async functions from all registered providers/services.
377
+ * You can register a hook using the `$hook` descriptor.
378
+ *
379
+ * ```ts
380
+ * import { $hook } from "alepha";
381
+ *
382
+ * class App {
383
+ * log = $logger();
384
+ * onCustomerHook = $hook({
385
+ * on: "my:custom:hook",
386
+ * handler: () => {
387
+ * this.log.info("App is being configured");
388
+ * },
389
+ * });
390
+ * }
391
+ *
392
+ * Alepha.create()
393
+ * .with(App)
394
+ * .start()
395
+ * .then(alepha => alepha.emit("my:custom:hook"));
396
+ * ```
397
+ *
398
+ * Hooks are fully typed. You can create your own hooks by using module augmentation:
399
+ *
400
+ * ```ts
401
+ * declare module "alepha" {
402
+ * interface Hooks {
403
+ * "my:custom:hook": {
404
+ * arg1: string;
405
+ * }
406
+ * }
407
+ * }
408
+ * ```
409
+ */
493
410
  declare class Alepha {
494
411
  /**
495
- * Creates a new instance of the Alepha container with some helpers:
496
- *
497
- * - merges `process.env` with the provided state.env when available.
498
- * - populates the test hooks for Vitest or Jest environments when available.
499
- *
500
- * If you are not interested about these helpers, you can use the constructor directly.
501
- */
412
+ * Creates a new instance of the Alepha container with some helpers:
413
+ *
414
+ * - merges `process.env` with the provided state.env when available.
415
+ * - populates the test hooks for Vitest or Jest environments when available.
416
+ *
417
+ * If you are not interested about these helpers, you can use the constructor directly.
418
+ */
502
419
  static create(state?: Partial<State>): Alepha;
503
420
  /**
504
- * List of all services + how they are provided.
505
- */
421
+ * List of all services + how they are provided.
422
+ */
506
423
  protected registry: Map<Service, ServiceDefinition>;
507
424
  /**
508
- * Flag indicating whether the App won't accept any further changes.
509
- * Pass to true when #start() is called.
510
- */
425
+ * Flag indicating whether the App won't accept any further changes.
426
+ * Pass to true when #start() is called.
427
+ */
511
428
  protected locked: boolean;
512
429
  /**
513
- * True if the App has been configured.
514
- */
430
+ * True if the App has been configured.
431
+ */
515
432
  protected configured: boolean;
516
433
  /**
517
- * True if the App has started.
518
- */
434
+ * True if the App has started.
435
+ */
519
436
  protected started: boolean;
520
437
  /**
521
- * True if the App is ready.
522
- */
438
+ * True if the App is ready.
439
+ */
523
440
  protected ready: boolean;
524
441
  /**
525
- * A promise that resolves when the App has started.
526
- */
442
+ * A promise that resolves when the App has started.
443
+ */
527
444
  protected starting?: PromiseWithResolvers<this>;
528
445
  /**
529
- * The current state of the App.
530
- *
531
- * It contains the environment variables, logger, and other state-related properties.
532
- *
533
- * You can declare your own state properties by extending the `State` interface.
534
- *
535
- * ```ts
536
- * declare module "alepha" {
537
- * interface State {
538
- * myCustomValue: string;
539
- * }
540
- * }
541
- * ```
542
- *
543
- * Same story for the `Env` interface.
544
- * ```ts
545
- * declare module "alepha" {
546
- * interface Env {
547
- * readonly myCustomValue: string;
548
- * }
549
- * }
550
- * ```
551
- *
552
- * State values can be function or primitive values.
553
- * However, all .env variables must serializable to JSON.
554
- */
446
+ * The current state of the App.
447
+ *
448
+ * It contains the environment variables, logger, and other state-related properties.
449
+ *
450
+ * You can declare your own state properties by extending the `State` interface.
451
+ *
452
+ * ```ts
453
+ * declare module "alepha" {
454
+ * interface State {
455
+ * myCustomValue: string;
456
+ * }
457
+ * }
458
+ * ```
459
+ *
460
+ * Same story for the `Env` interface.
461
+ * ```ts
462
+ * declare module "alepha" {
463
+ * interface Env {
464
+ * readonly myCustomValue: string;
465
+ * }
466
+ * }
467
+ * ```
468
+ *
469
+ * State values can be function or primitive values.
470
+ * However, all .env variables must serializable to JSON.
471
+ */
555
472
  protected store: State;
556
473
  /**
557
- * During the instantiation process, we keep a list of pending instantiations.
558
- * > It allows us to detect circular dependencies.
559
- */
474
+ * During the instantiation process, we keep a list of pending instantiations.
475
+ * > It allows us to detect circular dependencies.
476
+ */
560
477
  protected pendingInstantiations: Service[];
561
478
  /**
562
- * Cache for environment variables.
563
- * > It allows us to avoid parsing the same schema multiple times.
564
- */
479
+ * Cache for environment variables.
480
+ * > It allows us to avoid parsing the same schema multiple times.
481
+ */
565
482
  protected cacheEnv: Map<TSchema$1, any>;
566
483
  /**
567
- * Cache for TypeBox type checks.
568
- * > It allows us to avoid compiling the same schema multiple times.
569
- */
484
+ * Cache for TypeBox type checks.
485
+ * > It allows us to avoid compiling the same schema multiple times.
486
+ */
570
487
  protected cacheTypeCheck: Map<TSchema$1, TypeCheck<TSchema$1>>;
571
488
  /**
572
- * List of events that can be triggered. Powered by $hook().
573
- */
489
+ * List of events that can be triggered. Powered by $hook().
490
+ */
574
491
  protected events: Record<string, Array<Hook>>;
575
492
  /**
576
- * List of modules that are registered in the container.
577
- *
578
- * Modules are used to group services and provide a way to register them in the container.
579
- */
493
+ * List of modules that are registered in the container.
494
+ *
495
+ * Modules are used to group services and provide a way to register them in the container.
496
+ */
580
497
  protected modules: Array<ModuleDefinition>;
581
- /**
582
- * Node.js feature that allows to store context across asynchronous calls.
583
- *
584
- * This is used for logging, tracing, and other context-related features.
585
- *
586
- * Mocked for browser environments.
587
- */
498
+ protected substitutions: Map<Service, Service>;
499
+ protected configurations: Map<Service, object>;
500
+ protected descriptorRegistry: Map<Service<Descriptor<{}>>, Descriptor<{}>[]>;
501
+ /**
502
+ * Node.js feature that allows to store context across asynchronous calls.
503
+ *
504
+ * This is used for logging, tracing, and other context-related features.
505
+ *
506
+ * Mocked for browser environments.
507
+ */
588
508
  readonly context: AlsProvider;
589
509
  /**
590
- * Get logger instance.
591
- */
510
+ * Get logger instance.
511
+ */
592
512
  get log(): Logger;
593
513
  /**
594
- * The environment variables for the App.
595
- */
514
+ * The environment variables for the App.
515
+ */
596
516
  get env(): Readonly<Env>;
597
517
  constructor(state?: Partial<State>);
598
518
  /**
599
- * State accessor and mutator.
600
- */
519
+ * State accessor and mutator.
520
+ */
601
521
  state<Key extends keyof State>(key: Key, value?: State[Key]): State[Key];
602
- // -------------------------------------------------------------------------------------------------------------------
603
522
  /**
604
- * True when start() is called.
605
- *
606
- * -> No more services can be added, it's over, bye!
607
- */
523
+ * True when start() is called.
524
+ *
525
+ * -> No more services can be added, it's over, bye!
526
+ */
608
527
  isLocked(): boolean;
609
528
  /**
610
- * Returns whether the App is configured.
611
- *
612
- * It means that Alepha#configure() has been called.
613
- *
614
- * > By default, configure() is called automatically when start() is called, but you can also call it manually.
615
- */
529
+ * Returns whether the App is configured.
530
+ *
531
+ * It means that Alepha#configure() has been called.
532
+ *
533
+ * > By default, configure() is called automatically when start() is called, but you can also call it manually.
534
+ */
616
535
  isConfigured(): boolean;
617
536
  /**
618
- * Returns whether the App has started.
619
- *
620
- * It means that #start() has been called but maybe not all services are ready.
621
- */
537
+ * Returns whether the App has started.
538
+ *
539
+ * It means that #start() has been called but maybe not all services are ready.
540
+ */
622
541
  isStarted(): boolean;
623
542
  /**
624
- * True if the App is ready. It means that Alepha is started AND ready() hook has beed called.
625
- */
543
+ * True if the App is ready. It means that Alepha is started AND ready() hook has beed called.
544
+ */
626
545
  isReady(): boolean;
627
546
  /**
628
- * True if the App is running in a browser environment.
629
- */
547
+ * True if the App is running in a browser environment.
548
+ */
630
549
  isBrowser(): boolean;
631
550
  /**
632
- * Returns whether the App is running in a serverless environment.
633
- *
634
- * > Vite developer mode is also considered serverless.
635
- */
551
+ * Returns whether the App is running in a serverless environment.
552
+ *
553
+ * > Vite developer mode is also considered serverless.
554
+ */
636
555
  isServerless(): boolean | "vite" | "vercel";
637
556
  /**
638
- * Returns whether the App is in test mode. (Running in a test environment)
639
- *
640
- * > This is automatically set when running tests with Jest or Vitest.
641
- */
557
+ * Returns whether the App is in test mode. (Running in a test environment)
558
+ *
559
+ * > This is automatically set when running tests with Jest or Vitest.
560
+ */
642
561
  isTest(): boolean;
643
562
  /**
644
- * Returns whether the App is in production mode. (Running in a production environment)
645
- *
646
- * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps.
647
- */
563
+ * Returns whether the App is in production mode. (Running in a production environment)
564
+ *
565
+ * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps.
566
+ */
648
567
  isProduction(): boolean;
649
- // -------------------------------------------------------------------------------------------------------------------
650
- /**
651
- * Starts the App.
652
- *
653
- * - Lock any further changes to the container.
654
- * - Run "configure" hook for all services. Descriptors will be processed.
655
- * - Run "start" hook for all services. Providers will connect/listen/...
656
- * - Run "ready" hook for all services. This is the point where the App is ready to serve requests.
657
- *
658
- * @return A promise that resolves when the App has started.
659
- */
568
+ /**
569
+ * Starts the App.
570
+ *
571
+ * - Lock any further changes to the container.
572
+ * - Run "configure" hook for all services. Descriptors will be processed.
573
+ * - Run "start" hook for all services. Providers will connect/listen/...
574
+ * - Run "ready" hook for all services. This is the point where the App is ready to serve requests.
575
+ *
576
+ * @return A promise that resolves when the App has started.
577
+ */
660
578
  start(): Promise<this>;
661
579
  /**
662
- * Stops the App.
663
- *
664
- * - Run "stop" hook for all services.
665
- *
666
- * Stop will NOT reset the container.
667
- * Stop will NOT unlock the container.
668
- *
669
- * > Stop is used to gracefully shut down the application, nothing more. There is no "restart".
670
- *
671
- * @return A promise that resolves when the App has stopped.
672
- */
580
+ * Stops the App.
581
+ *
582
+ * - Run "stop" hook for all services.
583
+ *
584
+ * Stop will NOT reset the container.
585
+ * Stop will NOT unlock the container.
586
+ *
587
+ * > Stop is used to gracefully shut down the application, nothing more. There is no "restart".
588
+ *
589
+ * @return A promise that resolves when the App has stopped.
590
+ */
673
591
  stop(): Promise<void>;
674
- // -------------------------------------------------------------------------------------------------------------------
675
592
  /**
676
- * Check if entry is registered in the container.
677
- */
593
+ * Check if entry is registered in the container.
594
+ */
678
595
  has(entry: ServiceEntry, opts?: {
679
596
  /**
680
- * Check if the entry is registered in the pending instantiation stack.
681
- *
682
- * Default: true
683
- */
597
+ * Check if the entry is registered in the pending instantiation stack.
598
+ *
599
+ * Default: true
600
+ */
684
601
  inStack?: boolean;
685
602
  /**
686
- * Check if the entry is registered in the container registry.
687
- *
688
- * Default: true
689
- */
603
+ * Check if the entry is registered in the container registry.
604
+ *
605
+ * Default: true
606
+ */
690
607
  inRegistry?: boolean;
691
608
  }): boolean;
692
609
  /**
693
- * Registers the specified service in the container.
694
- *
695
- * - If the service is ALREADY registered, the method does nothing.
696
- * - If the service is NOT registered, a new instance is created and registered.
697
- *
698
- * Method is chainable, so you can register multiple services in a single call.
699
- *
700
- * > ServiceEntry allows to provide a service **substitution** feature.
701
- *
702
- * @example
703
- * ```ts
704
- * class A { value = "a"; }
705
- * class B { value = "b"; }
706
- * class M { a = $inject(A); }
707
- *
708
- * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // "b"
709
- * ```
710
- *
711
- * > **Substitution** is an advanced feature that allows you to replace a service with another service.
712
- * > It's useful for testing or for providing different implementations of a service.
713
- * > If you are interested in configuring a service, use Alepha#configure() instead.
714
- *
715
- * @param entry - The service to register in the container.
716
- * @return Current instance of Alepha.
717
- */
610
+ * Registers the specified service in the container.
611
+ *
612
+ * - If the service is ALREADY registered, the method does nothing.
613
+ * - If the service is NOT registered, a new instance is created and registered.
614
+ *
615
+ * Method is chainable, so you can register multiple services in a single call.
616
+ *
617
+ * > ServiceEntry allows to provide a service **substitution** feature.
618
+ *
619
+ * @example
620
+ * ```ts
621
+ * class A { value = "a"; }
622
+ * class B { value = "b"; }
623
+ * class M { a = $inject(A); }
624
+ *
625
+ * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // "b"
626
+ * ```
627
+ *
628
+ * > **Substitution** is an advanced feature that allows you to replace a service with another service.
629
+ * > It's useful for testing or for providing different implementations of a service.
630
+ * > If you are interested in configuring a service, use Alepha#configure() instead.
631
+ *
632
+ * @param entry - The service to register in the container.
633
+ * @return Current instance of Alepha.
634
+ */
718
635
  with<T extends object>(entry: ServiceEntry<T>): this;
719
636
  /**
720
- * Get the instance of the specified service and apply some changes, depending on the options.
721
- * - If the service is already registered, it will return the existing instance. (except if `skipCache` is true)
722
- * - If the service is not registered, it will create a new instance and register it. (except if `skipRegistration` is true)
723
- * - New instance can be created with custom constructor arguments. (`args` option)
724
- *
725
- * > This method is used by $inject() under the hood.
726
- *
727
- * @return The instance of the specified class or type.
728
- */
729
- get<T extends object>(serviceEntry: ServiceEntry<T>, opts?: {
637
+ * Get the instance of the specified service and apply some changes, depending on the options.
638
+ * - If the service is already registered, it will return the existing instance. (except if `skipCache` is true)
639
+ * - If the service is not registered, it will create a new instance and register it. (except if `skipRegistration` is true)
640
+ * - New instance can be created with custom constructor arguments. (`args` option)
641
+ *
642
+ * > This method is used by $inject() under the hood.
643
+ *
644
+ * @return The instance of the specified class or type.
645
+ */
646
+ inject<T extends object>(service: Service<T>, opts?: {
730
647
  /**
731
- * Ignore current existing instance.
732
- */
648
+ * Ignore current existing instance.
649
+ */
733
650
  skipCache?: boolean;
734
651
  /**
735
- * Don't store the instance in the registry.
736
- */
652
+ * Don't store the instance in the registry.
653
+ */
737
654
  skipRegistration?: boolean;
738
655
  /**
739
- * Constructor arguments to pass when creating a new instance.
740
- */
741
- args?: ConstructorParameters<InstantiableService<T>>;
656
+ * Constructor arguments to pass when creating a new instance.
657
+ */
658
+ args?: ConstructorParameters<InstantiableClass<T>>;
742
659
  /**
743
- * Parent service that requested the instance.
744
- * @internal
745
- */
660
+ * Parent service that requested the instance.
661
+ * @internal
662
+ */
746
663
  parent?: Service | null;
747
664
  /**
748
- * If the service is provided by a module, the module definition.
749
- * @internal
750
- */
665
+ * If the service is provided by a module, the module definition.
666
+ * @internal
667
+ */
751
668
  module?: ModuleDefinition;
752
669
  }): T;
753
- /**
754
- * Configures the specified service with the provided state.
755
- * If service is not registered, it will do nothing.
756
- *
757
- * It's recommended to use this method on the `configure` hook.
758
- * @example
759
- * ```ts
760
- * class AppConfig {
761
- * configure = $hook({
762
- * name: "configure",
763
- * handler: (a) => {
764
- * a.configure(MyProvider, { some: "data" });
765
- * }
766
- * })
767
- * }
768
- * ```
769
- */
670
+ protected pushModule(instance: Module): void;
671
+ /**
672
+ * Configures the specified service with the provided state.
673
+ * If service is not registered, it will do nothing.
674
+ *
675
+ * It's recommended to use this method on the `configure` hook.
676
+ * @example
677
+ * ```ts
678
+ * class AppConfig {
679
+ * configure = $hook({
680
+ * name: "configure",
681
+ * handler: (a) => {
682
+ * a.configure(MyProvider, { some: "data" });
683
+ * }
684
+ * })
685
+ * }
686
+ * ```
687
+ */
770
688
  configure<T extends {
771
689
  options: object;
772
690
  }>(service: Service<T>, state: Partial<T["options"]>): this;
773
- // -------------------------------------------------------------------------------------------------------------------
774
- protected useCounter: number;
775
- use<T extends Descriptor>(descriptor: T, options: Parameters<T>[0]): ReturnType<T>;
776
- // -------------------------------------------------------------------------------------------------------------------
777
691
  /**
778
- * Registers a hook for the specified event.
779
- */
692
+ * Registers a hook for the specified event.
693
+ */
780
694
  on<T extends keyof Hooks>(event: T, hookOrFunc: Hook<T> | ((payload: Hooks[T]) => Async<void>)): () => void;
781
695
  /**
782
- * Emits the specified event with the given payload.
783
- */
696
+ * Emits the specified event with the given payload.
697
+ */
784
698
  emit<T extends keyof Hooks>(func: keyof Hooks, payload: Hooks[T], options?: {
785
699
  /**
786
- * If true, the hooks will be executed in reverse order.
787
- * This is useful for "stop" hooks that should be executed in reverse order.
788
- *
789
- * @default false
790
- */
700
+ * If true, the hooks will be executed in reverse order.
701
+ * This is useful for "stop" hooks that should be executed in reverse order.
702
+ *
703
+ * @default false
704
+ */
791
705
  reverse?: boolean;
792
706
  /**
793
- * If true, the hooks will be logged with their execution time.
794
- *
795
- * @default false
796
- */
707
+ * If true, the hooks will be logged with their execution time.
708
+ *
709
+ * @default false
710
+ */
797
711
  log?: boolean;
798
712
  /**
799
- * If true, errors will be caught and logged instead of throwing.
800
- *
801
- * @default false
802
- */
713
+ * If true, errors will be caught and logged instead of throwing.
714
+ *
715
+ * @default false
716
+ */
803
717
  catch?: boolean;
804
718
  }): Promise<void>;
805
- // -------------------------------------------------------------------------------------------------------------------
806
719
  /**
807
- * Casts the given value to the specified schema.
808
- *
809
- * It uses the TypeBox library to validate the value against the schema.
810
- */
720
+ * Casts the given value to the specified schema.
721
+ *
722
+ * It uses the TypeBox library to validate the value against the schema.
723
+ */
811
724
  parse<T extends TSchema$1>(schema: T, value?: any, opts?: {
812
725
  /**
813
- * Clone the value before parsing.
814
- * @default true
815
- */
726
+ * Clone the value before parsing.
727
+ * @default true
728
+ */
816
729
  clone?: boolean;
817
730
  /**
818
- * Apply default values defined in the schema.
819
- * @default true
820
- */
731
+ * Apply default values defined in the schema.
732
+ * @default true
733
+ */
821
734
  default?: boolean;
822
735
  /**
823
- * Remove all values not defined in the schema.
824
- * @default true
825
- */
736
+ * Remove all values not defined in the schema.
737
+ * @default true
738
+ */
826
739
  clean?: boolean;
827
740
  /**
828
- * Try to cast/convert some data based on the schema.
829
- * @default true
830
- */
741
+ * Try to cast/convert some data based on the schema.
742
+ * @default true
743
+ */
831
744
  convert?: boolean;
832
745
  /**
833
- * Prepare value after being deserialized.
834
- * @default true
835
- */
746
+ * Prepare value after being deserialized.
747
+ * @default true
748
+ */
836
749
  check?: boolean;
837
750
  }): Static$1<T>;
838
751
  /**
839
- * Applies environment variables to the provided schema and state object.
840
- *
841
- * It replaces also all templated $ENV inside string values.
842
- *
843
- * @param schema - The schema object to apply environment variables to.
844
- * @return The schema object with environment variables applied.
845
- */
752
+ * Applies environment variables to the provided schema and state object.
753
+ *
754
+ * It replaces also all templated $ENV inside string values.
755
+ *
756
+ * @param schema - The schema object to apply environment variables to.
757
+ * @return The schema object with environment variables applied.
758
+ */
846
759
  parseEnv<T extends TObject$1>(schema: T): Static$1<T>;
847
- // -------------------------------------------------------------------------------------------------------------------
848
760
  /**
849
- * Dump the current dependency graph of the App.
850
- *
851
- * This method returns a record where the keys are the names of the services.
852
- */
761
+ * Dump the current dependency graph of the App.
762
+ *
763
+ * This method returns a record where the keys are the names of the services.
764
+ */
853
765
  graph(): Record<string, {
854
766
  from: string[];
855
- as?: string;
767
+ as?: string[];
856
768
  module?: string;
857
769
  }>;
858
- // -------------------------------------------------------------------------------------------------------------------
859
- /**
860
- * @internal
861
- */
862
- getDescriptorValues<T extends Descriptor>(descriptor: T): Array<DescriptorItem<T>>;
863
- /**
864
- * @internal
865
- */
866
- protected new<T extends object>(definition: Service<T>, args?: any[], module?: ModuleDefinition): T;
867
- /**
868
- * @internal
869
- */
770
+ descriptors<TDescriptor extends Descriptor>(factory: {
771
+ [KIND]: InstantiableClass<TDescriptor> | string;
772
+ }): Array<TDescriptor>;
773
+ protected new<T extends object>(service: Service<T>, args?: any[], module?: ModuleDefinition): T;
774
+ protected processDescriptor(value: Descriptor, propertyKey?: string): void;
775
+ /**
776
+ * @internal
777
+ */
870
778
  protected createLogger(env: Env): Logger;
871
- getModuleOf(service: Service): Module | undefined;
872
779
  }
873
- // ---------------------------------------------------------------------------------------------------------------------
780
+ interface Hook<T extends keyof Hooks = any> {
781
+ caller?: Service;
782
+ priority?: "first" | "last";
783
+ callback: (payload: Hooks[T]) => Async<void>;
784
+ }
874
785
  /**
875
- * This is how we store services in the Alepha container.
876
- */
786
+ * This is how we store services in the Alepha container.
787
+ */
877
788
  interface ServiceDefinition<T extends object = any> {
878
789
  /**
879
- * The class or type definition to provide.
880
- */
881
- provide: Service<T>;
882
- /**
883
- * The class or type definition to use. This will override the 'provide' property.
884
- */
885
- use?: Service<T>;
886
- /**
887
- * The instance of the class or type definition.
888
- * Mostly used for caching / singleton but can be used for other purposes like forcing the instance.
889
- */
790
+ * The instance of the class or type definition.
791
+ * Mostly used for caching / singleton but can be used for other purposes like forcing the instance.
792
+ */
890
793
  instance: T;
891
794
  /**
892
- * List of classes which use this class.
893
- */
795
+ * List of classes which use this class.
796
+ */
894
797
  parents: Array<Service | null>;
895
798
  /**
896
- * If the service is provided by a module, the module definition.
897
- */
799
+ * If the service is provided by a module, the module definition.
800
+ */
898
801
  module?: ModuleDefinition;
899
802
  }
900
- // ---------------------------------------------------------------------------------------------------------------------
901
803
  interface Env extends LoggerEnv {
902
804
  [key: string]: string | boolean | number | undefined;
903
805
  /**
904
- * Optional environment variable that indicates the current environment.
905
- */
806
+ * Optional environment variable that indicates the current environment.
807
+ */
906
808
  NODE_ENV?: "dev" | "test" | "production";
907
809
  /**
908
- * Optional name of the application.
909
- */
810
+ * Optional name of the application.
811
+ */
910
812
  APP_NAME?: string;
911
813
  /**
912
- * Optional root module name.
913
- */
814
+ * Optional root module name.
815
+ */
914
816
  MODULE_NAME?: string;
915
817
  /**
916
- * If true, the container will not automatically register the default providers based on the descriptors.
917
- *
918
- * It means that you have to alepha.with(ServiceModule) manually. No magic.
919
- *
920
- * @default false
921
- */
818
+ * If true, the container will not automatically register the default providers based on the descriptors.
819
+ *
820
+ * It means that you have to alepha.with(ServiceModule) manually. No magic.
821
+ *
822
+ * @default false
823
+ */
922
824
  EXPLICIT_PROVIDERS?: boolean;
923
825
  }
924
- // ---------------------------------------------------------------------------------------------------------------------
925
826
  interface State {
926
827
  log: Logger;
927
828
  env?: Readonly<Env>;
928
- // test hooks
829
+ /**
830
+ * If defined, the Alepha container will only register this service and its dependencies.
831
+ */
832
+ target?: Service;
929
833
  beforeAll?: (run: any) => any;
930
834
  afterAll?: (run: any) => any;
931
835
  afterEach?: (run: any) => any;
932
836
  onTestFinished?: (run: any) => any;
933
837
  }
934
- // ---------------------------------------------------------------------------------------------------------------------
935
838
  interface Hooks {
936
839
  echo: any;
937
840
  /**
938
- * Triggered during the configuration phase. Before the start phase.
939
- */
841
+ * Triggered during the configuration phase. Before the start phase.
842
+ */
940
843
  configure: Alepha;
941
844
  /**
942
- * Triggered during the start phase. When `Alepha#start()` is called.
943
- */
845
+ * Triggered during the start phase. When `Alepha#start()` is called.
846
+ */
944
847
  start: Alepha;
945
848
  /**
946
- * Triggered during the ready phase. After the start phase.
947
- */
849
+ * Triggered during the ready phase. After the start phase.
850
+ */
948
851
  ready: Alepha;
949
852
  /**
950
- * Triggered during the stop phase.
951
- *
952
- * - Stop should be called after a SIGINT or SIGTERM signal in order to gracefully shutdown the application. (@see `run()` method)
953
- *
954
- */
853
+ * Triggered during the stop phase.
854
+ *
855
+ * - Stop should be called after a SIGINT or SIGTERM signal in order to gracefully shutdown the application. (@see `run()` method)
856
+ *
857
+ */
955
858
  stop: Alepha;
956
859
  /**
957
- * Triggered when a state value is mutated.
958
- */
860
+ * Triggered when a state value is mutated.
861
+ */
959
862
  "state:mutate": {
960
863
  /**
961
- * The key of the state that was mutated.
962
- */
864
+ * The key of the state that was mutated.
865
+ */
963
866
  key: keyof State;
964
867
  /**
965
- * The new value of the state.
966
- */
868
+ * The new value of the state.
869
+ */
967
870
  value: any;
968
871
  /**
969
- * The previous value of the state.
970
- */
872
+ * The previous value of the state.
873
+ */
971
874
  prevValue: any;
972
875
  };
973
876
  }
@@ -975,321 +878,570 @@ interface Hooks {
975
878
  //#region src/interfaces/Run.d.ts
976
879
  interface RunOptions {
977
880
  /**
978
- * Environment variables to be used by the application.
979
- * If not provided, it will use the current process environment.
980
- */
881
+ * Environment variables to be used by the application.
882
+ * It will be merged with the current process environment.
883
+ */
981
884
  env?: Env;
982
885
  /**
983
- * A callback that will be executed before the application starts.
984
- */
886
+ * A callback that will be executed before the application starts.
887
+ */
985
888
  configure?: (alepha: Alepha) => Async<void>;
986
889
  /**
987
- * A callback that will be executed once the application is ready.
988
- * This is useful for initializing resources or starting background tasks.
989
- */
890
+ * A callback that will be executed once the application is ready.
891
+ * This is useful for initializing resources or starting background tasks.
892
+ */
990
893
  ready?: (alepha: Alepha) => Async<void>;
991
894
  /**
992
- * If true, the application will stop after the ready callback is executed.
993
- */
895
+ * If true, the application will .stop() after the ready callback is executed.
896
+ * Useful for one-time tasks!
897
+ */
994
898
  once?: boolean;
899
+ /**
900
+ * If true, the application will run in cluster mode.
901
+ */
902
+ cluster?: boolean;
995
903
  }
904
+ //# sourceMappingURL=Run.d.ts.map
996
905
  //#endregion
997
- //#region src/descriptors/$inject.d.ts
906
+ //#region src/constants/OPTIONS.d.ts
907
+ /**
908
+ * Used for descriptors options.
909
+ *
910
+ * @internal
911
+ */
912
+ declare const OPTIONS: unique symbol;
913
+ //# sourceMappingURL=OPTIONS.d.ts.map
914
+
915
+ //#endregion
916
+ //#region src/descriptors/$cursor.d.ts
917
+ /**
918
+ * Get Alepha instance and Class definition from the current context.
919
+ * This should be used inside a descriptor only.
920
+ *
921
+ * ```ts
922
+ * import { $cursor } from "alepha";
923
+ *
924
+ * const $ = () => {
925
+ *
926
+ * const { context, definition } = $cursor();
927
+ *
928
+ * // context - alepha instance
929
+ * // definition - class which is creating this descriptor
930
+ *
931
+ * return {};
932
+ * }
933
+ *
934
+ * ```
935
+ *
936
+ * @internal
937
+ */
938
+ declare const $cursor: () => CursorDescriptor;
939
+ /**
940
+ * /!\ Global variable /!\
941
+ *
942
+ * Store the current context and definition during injection phase.
943
+ *
944
+ * @internal
945
+ */
946
+ declare const __alephaRef: {
947
+ context?: Alepha;
948
+ definition?: Service;
949
+ module?: ModuleDefinition;
950
+ $services?: {
951
+ module: ModuleDefinition;
952
+ parent: Service;
953
+ };
954
+ };
998
955
  /**
999
- * Get the instance of the specified type from the context.
1000
- *
1001
- * - If the type is a class, it will be resolved from the context.
1002
- * - If the type is a schema, it will be parsed from the environment.
1003
- *
1004
- * ```ts
1005
- * class A { }
1006
- * class B {
1007
- * a = $inject(A);
1008
- * }
1009
- * ```
1010
- *
1011
- * @param type - Type (or TypeBox schema) to resolve
1012
- * @returns Instance of the specified type
1013
- */
1014
- declare function $inject<T extends TObject$1>(type: T): Static$1<T>;
1015
- declare function $inject<T extends object>(type: Service<T>): T;
1016
- declare class InjectResolverRegistry {
1017
- resolvers: Array<(it: any) => any>;
1018
- register(fn: (it: any) => any): void;
1019
- resolve(it: any): any;
956
+ * Cursor descriptor.
957
+ */
958
+ interface CursorDescriptor {
959
+ context: Alepha;
960
+ definition?: Service;
961
+ module?: ModuleDefinition;
1020
962
  }
1021
- declare const $injectResolverRegistry: InjectResolverRegistry;
963
+ //# sourceMappingURL=$cursor.d.ts.map
964
+ //#endregion
965
+ //#region src/descriptors/$env.d.ts
966
+ /**
967
+ * Get typed values from environment variables.
968
+ *
969
+ * @example
970
+ * ```ts
971
+ * const alepha = Alepha.create({
972
+ * env: {
973
+ * // Alepha.create() will also use process.env when running on Node.js
974
+ * HELLO: "world",
975
+ * }
976
+ * });
977
+ *
978
+ * class App {
979
+ * log = $logger();
980
+ *
981
+ * // program expect a var env "HELLO" as string to works
982
+ * env = $env(t.object({
983
+ * HELLO: t.string()
984
+ * }));
985
+ *
986
+ * sayHello = () => this.log.info("Hello ${this.env.HELLO}")
987
+ * }
988
+ *
989
+ * run(alepha.with(App));
990
+ * ```
991
+ */
992
+ declare const $env: <T extends TObject$1>(type: T) => Static$1<T>;
993
+ //# sourceMappingURL=$env.d.ts.map
994
+
995
+ //#endregion
996
+ //#region src/descriptors/$hook.d.ts
997
+ /**
998
+ * Registers a new hook.
999
+ *
1000
+ * ```ts
1001
+ * import { $hook } from "alepha";
1002
+ *
1003
+ * class MyProvider {
1004
+ * onStart = $hook({
1005
+ * name: "start", // or "configure", "ready", "stop", ...
1006
+ * handler: async (app) => {
1007
+ * // await db.connect(); ...
1008
+ * }
1009
+ * });
1010
+ * }
1011
+ * ```
1012
+ *
1013
+ * Hooks are used to run async functions from all registered providers/services.
1014
+ *
1015
+ * You can't register a hook after the App has started.
1016
+ *
1017
+ * It's used under the hood by the `configure`, `start`, and `stop` methods.
1018
+ * Some modules also use hooks to run their own logic. (e.g. `@alepha/server`).
1019
+ *
1020
+ * You can create your own hooks by using module augmentation:
1021
+ *
1022
+ * ```ts
1023
+ * declare module "alepha" {
1024
+ *
1025
+ * interface Hooks {
1026
+ * "my:custom:hook": {
1027
+ * arg1: string;
1028
+ * }
1029
+ * }
1030
+ * }
1031
+ *
1032
+ * await alepha.emit("my:custom:hook", { arg1: "value" });
1033
+ * ```
1034
+ *
1035
+ */
1036
+ declare const $hook: {
1037
+ <T extends keyof Hooks>(options: HookOptions<T>): HookDescriptor<T>;
1038
+ [KIND]: typeof HookDescriptor;
1039
+ };
1040
+ interface HookOptions<T extends keyof Hooks> {
1041
+ /**
1042
+ * The name of the hook. "configure", "start", "ready", "stop", ...
1043
+ */
1044
+ on: T;
1045
+ /**
1046
+ * The handler to run when the hook is triggered.
1047
+ */
1048
+ handler: (app: Hooks[T]) => Async<any>;
1049
+ /**
1050
+ * Force the hook to run first or last on the list of hooks.
1051
+ */
1052
+ priority?: "first" | "last";
1053
+ /**
1054
+ * Empty placeholder, not implemented yet. :-)
1055
+ */
1056
+ before?: object | Array<object>;
1057
+ /**
1058
+ * Empty placeholder, not implemented yet. :-)
1059
+ */
1060
+ after?: object | Array<object>;
1061
+ }
1062
+ declare class HookDescriptor<T extends keyof Hooks> extends Descriptor<HookOptions<T>> {
1063
+ called: number;
1064
+ protected onInit(): void;
1065
+ }
1066
+ //# sourceMappingURL=$hook.d.ts.map
1067
+ //#endregion
1068
+ //#region src/descriptors/$inject.d.ts
1069
+ /**
1070
+ * Get the instance of the specified type from the context.
1071
+ *
1072
+ * ```ts
1073
+ * class A { }
1074
+ * class B {
1075
+ * a = $inject(A);
1076
+ * }
1077
+ * ```
1078
+ */
1079
+ declare const $inject: <T extends object>(type: Service<T>) => T;
1080
+ declare class InjectDescriptor extends Descriptor {}
1081
+ //# sourceMappingURL=$inject.d.ts.map
1082
+
1022
1083
  //#endregion
1023
1084
  //#region src/descriptors/$logger.d.ts
1024
1085
  /**
1025
- * Create a logger.
1026
- *
1027
- * `name` is optional, by default it will use the name of the service.
1028
- *
1029
- * @example
1030
- * ```ts
1031
- * import { $logger } from "alepha";
1032
- *
1033
- * class MyService {
1034
- * log = $logger();
1035
- *
1036
- * constructor() {
1037
- * // print something like 'date - [MyService] Service initialized'
1038
- * this.log.info("Service initialized");
1039
- * }
1040
- * }
1041
- * ```
1042
- */
1043
- declare const $logger: (name?: string) => Logger;
1086
+ * Create a logger.
1087
+ *
1088
+ * `name` is optional, by default it will use the name of the service.
1089
+ *
1090
+ * @example
1091
+ * ```ts
1092
+ * import { $logger } from "alepha";
1093
+ *
1094
+ * class MyService {
1095
+ * log = $logger();
1096
+ *
1097
+ * constructor() {
1098
+ * // print something like 'date - [MyService] Service initialized'
1099
+ * this.log.info("Service initialized");
1100
+ * }
1101
+ * }
1102
+ * ```
1103
+ */
1104
+ declare const $logger: {
1105
+ (options?: LoggerDescriptorOptions): Logger;
1106
+ [KIND]: typeof Logger;
1107
+ };
1108
+ interface LoggerDescriptorOptions {
1109
+ name?: string;
1110
+ }
1111
+ //# sourceMappingURL=$logger.d.ts.map
1112
+
1113
+ //#endregion
1114
+ //#region src/descriptors/$module.d.ts
1115
+ /**
1116
+ * Wrap services and descriptors into a module.
1117
+ *
1118
+ * Module is just a class.
1119
+ * You must attach a `name` to it.
1120
+ *
1121
+ * It's recommended to use `project.module.submodule` format.
1122
+ *
1123
+ * @example
1124
+ * ```ts
1125
+ * import { $module } from "alepha";
1126
+ * import { MyService } from "./MyService.ts";
1127
+ *
1128
+ * // export MyService so it can be used everywhere
1129
+ * export * from "./MyService.ts";
1130
+ *
1131
+ * export default $module({
1132
+ * name: "my.project.module",
1133
+ * // MyService will have a module context "my.project.module"
1134
+ * services: [MyService],
1135
+ * });
1136
+ * ```
1137
+ *
1138
+ * - Module is used for logging and other purposes.
1139
+ * - It's useful for large applications or libraries to group services and descriptors together.
1140
+ * - It's probably overkill for small applications.
1141
+ */
1142
+ declare const $module: (args: ModuleDescriptorOptions) => ModuleDescriptor;
1143
+ type ModuleDescriptor = Service<Module>;
1144
+ interface ModuleDescriptorOptions {
1145
+ /**
1146
+ * Name of the module.
1147
+ *
1148
+ * It should be in the format of `project.module.submodule`.
1149
+ */
1150
+ name: string;
1151
+ /**
1152
+ * List of services to register in the module.
1153
+ */
1154
+ services?: Array<ServiceEntry>;
1155
+ /**
1156
+ * List of $descriptors to register in the module.
1157
+ */
1158
+ descriptors?: Array<DescriptorFactoryLike>;
1159
+ /**
1160
+ * By default, module will register all services.
1161
+ * You can override this behavior by providing a register function.
1162
+ * It's useful when you want to register services conditionally or in a specific order.
1163
+ */
1164
+ register?: (alepha: Alepha) => void;
1165
+ }
1166
+ //# sourceMappingURL=$module.d.ts.map
1044
1167
  //#endregion
1045
1168
  //#region src/errors/AlephaError.d.ts
1046
- // ---------------------------------------------------------------------------------------------------------------------
1047
1169
  /**
1048
- * Default error class for Alepha.
1049
- */
1170
+ * Default error class for Alepha.
1171
+ */
1050
1172
  declare class AlephaError extends Error {}
1173
+ //# sourceMappingURL=AlephaError.d.ts.map
1051
1174
  //#endregion
1052
1175
  //#region src/errors/AppNotStartedError.d.ts
1053
1176
  declare class AppNotStartedError extends Error {
1054
1177
  constructor();
1055
1178
  }
1179
+ //# sourceMappingURL=AppNotStartedError.d.ts.map
1056
1180
  //#endregion
1057
1181
  //#region src/errors/CircularDependencyError.d.ts
1058
1182
  declare class CircularDependencyError extends Error {
1059
1183
  constructor(provider: string, parents?: string[]);
1060
1184
  }
1185
+ //# sourceMappingURL=CircularDependencyError.d.ts.map
1061
1186
  //#endregion
1062
1187
  //#region src/errors/ContainerLockedError.d.ts
1063
1188
  declare class ContainerLockedError extends Error {
1064
1189
  constructor(message?: string);
1065
1190
  }
1191
+ //# sourceMappingURL=ContainerLockedError.d.ts.map
1066
1192
  //#endregion
1067
1193
  //#region src/errors/NotImplementedError.d.ts
1068
1194
  declare class NotImplementedError extends Error {
1069
1195
  constructor(provider: string);
1070
1196
  }
1197
+ //# sourceMappingURL=NotImplementedError.d.ts.map
1071
1198
  //#endregion
1072
1199
  //#region src/errors/TypeBoxError.d.ts
1073
1200
  declare class TypeBoxError extends Error {
1074
1201
  readonly value: ValueError;
1075
1202
  constructor(value: ValueError);
1076
1203
  }
1204
+ //# sourceMappingURL=TypeBoxError.d.ts.map
1205
+
1077
1206
  //#endregion
1078
1207
  //#region src/providers/TypeProvider.d.ts
1079
- // ---------------------------------------------------------------------------------------------------------------------
1080
1208
  declare class TypeProvider {
1081
1209
  static DEFAULT_STRING_MAX_LENGTH: number;
1082
1210
  static DEFAULT_LONG_STRING_MAX_LENGTH: number;
1083
1211
  static DEFAULT_RICH_STRING_MAX_LENGTH: number;
1084
1212
  static DEFAULT_ARRAY_MAX_ITEMS: number;
1085
1213
  static FormatRegistry: typeof FormatRegistry;
1086
- raw: typeof Type;
1087
- any(options?: SchemaOptions): TAny$1;
1088
- void(options?: SchemaOptions): TVoid;
1089
- undefined(options?: SchemaOptions): TUndefined;
1090
- record<Key extends TSchema$1, Value extends TSchema$1>(key: Key, value: Value, options?: ObjectOptions): TRecordOrObject<Key, Value>;
1091
- omit<Type extends TSchema$1, Key extends TSchema$1>(type: Type, key: Key, options?: SchemaOptions): TOmit<Type, Key>;
1092
- partial<MappedResult extends TMappedResult>(type: MappedResult, options?: SchemaOptions): TPartialFromMappedResult<MappedResult>;
1093
- union<Types extends TSchema$1[]>(types: [...Types], options?: SchemaOptions): Union<Types>;
1094
- composite<T extends TSchema$1[]>(schemas: [...T], options?: ObjectOptions): TComposite<T>;
1095
- pick<Type extends TSchema$1, Key extends PropertyKey[]>(type: Type, key: readonly [...Key], options?: SchemaOptions): TPick<Type, Key>;
1096
- /**
1097
- * Create a schema for an object.
1098
- *
1099
- * @param properties The properties of the object.
1100
- * @param options The options for the object.
1101
- */
1214
+ raw: TypeBox.JavaScriptTypeBuilder;
1215
+ any: (options?: SchemaOptions) => TAny$1;
1216
+ void: (options?: SchemaOptions) => TypeBox.TVoid;
1217
+ undefined: (options?: SchemaOptions) => TypeBox.TUndefined;
1218
+ record: <Key extends TSchema$1, Value extends TSchema$1>(key: Key, value: Value, options?: ObjectOptions) => TypeBox.TRecordOrObject<Key, Value>;
1219
+ omit: {
1220
+ <Type extends TSchema$1, Key extends PropertyKey[]>(type: Type, key: readonly [...Key], options?: SchemaOptions): TOmit<Type, Key>;
1221
+ <Type extends TSchema$1, Key extends TSchema$1>(type: Type, key: Key, options?: SchemaOptions): TOmit<Type, Key>;
1222
+ };
1223
+ partial: {
1224
+ <MappedResult extends TypeBox.TMappedResult>(type: MappedResult, options?: SchemaOptions): TypeBox.TPartialFromMappedResult<MappedResult>;
1225
+ <Type extends TSchema$1>(type: Type, options?: SchemaOptions): TPartial<Type>;
1226
+ };
1227
+ union: <Types extends TSchema$1[]>(types: [...Types], options?: SchemaOptions) => TypeBox.Union<Types>;
1228
+ composite: <T extends TSchema$1[]>(schemas: [...T], options?: ObjectOptions) => TComposite<T>;
1229
+ pick: {
1230
+ <Type extends TSchema$1, Key extends PropertyKey[]>(type: Type, key: readonly [...Key], options?: SchemaOptions): TPick<Type, Key>;
1231
+ <Type extends TSchema$1, Key extends TSchema$1>(type: Type, key: Key, options?: SchemaOptions): TPick<Type, Key>;
1232
+ };
1233
+ /**
1234
+ * Create a schema for an object.
1235
+ *
1236
+ * @param properties The properties of the object.
1237
+ * @param options The options for the object.
1238
+ */
1102
1239
  object<T extends TProperties$1>(properties: T, options?: ObjectOptions): TObject$1<T>;
1103
1240
  /**
1104
- * Create a schema for an array.
1105
- *
1106
- * @param schema
1107
- * @param options
1108
- */
1241
+ * Create a schema for an array.
1242
+ *
1243
+ * @param schema
1244
+ * @param options
1245
+ */
1109
1246
  array<T extends TSchema$1>(schema: T, options?: ArrayOptions): TArray$1<T>;
1110
1247
  /**
1111
- * Create a schema for a string.
1112
- *
1113
- * @param options
1114
- */
1248
+ * Create a schema for a string.
1249
+ *
1250
+ * @param options
1251
+ */
1115
1252
  string(options?: AlephaStringOptions): TString$1;
1116
1253
  /**
1117
- * Create a schema for a JSON object.
1118
- *
1119
- * @param options
1120
- */
1254
+ * Create a schema for a JSON object.
1255
+ *
1256
+ * @param options
1257
+ */
1121
1258
  json(options?: SchemaOptions): TRecord$1<TString$1, TAny$1>;
1122
1259
  /**
1123
- * Create a schema for a boolean.
1124
- *
1125
- * @param options
1126
- */
1260
+ * Create a schema for a boolean.
1261
+ *
1262
+ * @param options
1263
+ */
1127
1264
  boolean(options?: SchemaOptions): TBoolean$1;
1128
1265
  /**
1129
- * Create a schema for a number.
1130
- *
1131
- * @param options
1132
- */
1266
+ * Create a schema for a number.
1267
+ *
1268
+ * @param options
1269
+ */
1133
1270
  number(options?: NumberOptions): TNumber$1;
1134
1271
  /**
1135
- * Create a schema for an unsigned 8-bit integer.
1136
- *
1137
- * @param options
1138
- */
1272
+ * Create a schema for an unsigned 8-bit integer.
1273
+ *
1274
+ * @param options
1275
+ */
1139
1276
  uchar(options?: IntegerOptions): TInteger;
1140
1277
  /**
1141
- * Create a schema for an unsigned 32-bit integer.
1142
- */
1278
+ * Create a schema for an unsigned 32-bit integer.
1279
+ */
1143
1280
  uint(options?: IntegerOptions): TNumber$1;
1144
1281
  /**
1145
- * Create a schema for a signed 32-bit integer.
1146
- */
1282
+ * Create a schema for a signed 32-bit integer.
1283
+ */
1147
1284
  int(options?: IntegerOptions): TInteger;
1148
1285
  /**
1149
- * Create a schema for a signed 32-bit integer.
1150
- */
1286
+ * Create a schema for a signed 32-bit integer.
1287
+ */
1151
1288
  integer(options?: IntegerOptions): TInteger;
1152
1289
  /**
1153
- * Create a schema for a bigint. Bigint is a 64-bit integer.
1154
- * This is a workaround for TypeBox, which does not support bigint natively.
1155
- */
1290
+ * Create a schema for a bigint. Bigint is a 64-bit integer.
1291
+ * This is a workaround for TypeBox, which does not support bigint natively.
1292
+ */
1156
1293
  bigint(options?: IntegerOptions): TNumber$1;
1157
1294
  /**
1158
- * Make a schema optional.
1159
- *
1160
- * @param schema The schema to make optional.
1161
- */
1295
+ * Make a schema optional.
1296
+ *
1297
+ * @param schema The schema to make optional.
1298
+ */
1162
1299
  optional<T extends TSchema$1>(schema: T): TOptionalWithFlag<T, true>;
1163
1300
  /**
1164
- * Make a schema nullable.
1165
- *
1166
- * @param schema The schema to make nullable.
1167
- * @param options The options for the schema.
1168
- */
1301
+ * Make a schema nullable.
1302
+ *
1303
+ * @param schema The schema to make nullable.
1304
+ * @param options The options for the schema.
1305
+ */
1169
1306
  nullable<T extends TSchema$1>(schema: T, options?: ObjectOptions): TUnion<[TNull, T]>;
1170
- /**
1171
- * Map a schema to another schema.
1172
- *
1173
- * @param schema The schema to map.
1174
- * @param operations The operations to perform on the schema.
1175
- * @param options The options for the schema.
1176
- * @returns The mapped schema.
1177
- */
1307
+ nullify: <T extends TSchema$1>(schema: T, options?: ObjectOptions) => TObject$1<TypeBox.Evaluate<TypeBox.TMappedFunctionReturnType<TypeBox.TIndexPropertyKeys<TypeBox.TKeyOf<T>>, TUnion<[TNull, TypeBox.TMappedResult<TypeBox.Evaluate<TypeBox.TIndexPropertyKeys<TypeBox.TKeyOf<T>> extends infer T_1 ? T_1 extends TypeBox.TIndexPropertyKeys<TypeBox.TKeyOf<T>> ? T_1 extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? Right extends [infer Left extends PropertyKey, ...infer Right extends PropertyKey[]] ? /*elided*/any : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : { [_ in Left]: TypeBox.Assert<TypeBox.TIndexFromPropertyKey<T, Left>, TSchema$1> } : {} : never : never>>]>, {}>>>;
1308
+ /**
1309
+ * Map a schema to another schema.
1310
+ *
1311
+ * @param schema The schema to map.
1312
+ * @param operations The operations to perform on the schema.
1313
+ * @param options The options for the schema.
1314
+ * @returns The mapped schema.
1315
+ */
1178
1316
  map<T extends TObject$1 | TIntersect, Omit extends (keyof T["properties"])[], Optional extends (keyof T["properties"])[]>(schema: T, operations: {
1179
1317
  omit: readonly [...Omit];
1180
1318
  optional: [...Optional];
1181
1319
  }, options?: ObjectOptions): TComposite<[TOmit<T, [...Omit, ...Optional]>, TPartial<TPick<T, Optional>>]>;
1182
1320
  /**
1183
- * Create a schema for a string enum.
1184
- *
1185
- * @param values
1186
- * @param options
1187
- */
1321
+ * Create a schema for a string enum.
1322
+ *
1323
+ * @param values
1324
+ * @param options
1325
+ */
1188
1326
  enum<T extends string[]>(values: [...T], options?: StringOptions): TUnsafe<T[number]>;
1189
1327
  /**
1190
- * Create a schema for a datetime.
1191
- *
1192
- * @param options The options for the date.
1193
- */
1328
+ * Create a schema for a datetime.
1329
+ *
1330
+ * @param options The options for the date.
1331
+ */
1194
1332
  datetime(options?: StringOptions): TString$1;
1195
1333
  /**
1196
- * Create a schema for a date.
1197
- *
1198
- * @param options
1199
- */
1334
+ * Create a schema for a date.
1335
+ *
1336
+ * @param options
1337
+ */
1200
1338
  date(options?: StringOptions): TString$1;
1201
1339
  /**
1202
- * Create a schema for uuid.
1203
- *
1204
- * @param options The options for the duration.
1205
- */
1340
+ * Create a schema for uuid.
1341
+ *
1342
+ * @param options The options for the duration.
1343
+ */
1206
1344
  uuid(options?: StringOptions): TString$1;
1207
1345
  unsafe<T>(kind: string, options?: UnsafeOptions): TUnsafe<T>;
1208
1346
  file(options?: {
1209
1347
  max?: number;
1210
1348
  }): TFile;
1211
1349
  stream(): TStream;
1350
+ /**
1351
+ * Create a schema for a string enum e.g. LIKE_THIS.
1352
+ *
1353
+ * @param options
1354
+ */
1355
+ snakeCase: (options?: StringOptions) => TString$1;
1356
+ /**
1357
+ * Create a schema for an object with a value and label.
1358
+ */
1359
+ valueLabel: (options?: ObjectOptions) => TObject$1<{
1360
+ value: TString$1;
1361
+ label: TString$1;
1362
+ description: TypeBox.TOptional<TString$1>;
1363
+ }>;
1212
1364
  }
1213
- // ---------------------------------------------------------------------------------------------------------------------
1214
1365
  interface FileLike {
1215
1366
  /**
1216
- * Filename.
1217
- * @default "file"
1218
- */
1367
+ * Filename.
1368
+ * @default "file"
1369
+ */
1219
1370
  name: string;
1220
1371
  /**
1221
- * Mandatory MIME type of the file.
1222
- * @default "application/octet-stream"
1223
- */
1372
+ * Mandatory MIME type of the file.
1373
+ * @default "application/octet-stream"
1374
+ */
1224
1375
  type: string;
1225
1376
  /**
1226
- * Size of the file in bytes.
1227
- *
1228
- * Always 0 for streams, as the size is not known until the stream is fully read.
1229
- *
1230
- * @default 0
1231
- */
1377
+ * Size of the file in bytes.
1378
+ *
1379
+ * Always 0 for streams, as the size is not known until the stream is fully read.
1380
+ *
1381
+ * @default 0
1382
+ */
1232
1383
  size: number;
1233
1384
  /**
1234
- * Last modified timestamp in milliseconds since epoch.
1235
- *
1236
- * Always the current timestamp for streams, as the last modified time is not known.
1237
- * We use this field to ensure compatibility with File API.
1238
- *
1239
- * @default Date.now()
1240
- */
1385
+ * Last modified timestamp in milliseconds since epoch.
1386
+ *
1387
+ * Always the current timestamp for streams, as the last modified time is not known.
1388
+ * We use this field to ensure compatibility with File API.
1389
+ *
1390
+ * @default Date.now()
1391
+ */
1241
1392
  lastModified: number;
1242
1393
  /**
1243
- * Returns a ReadableStream or Node.js Readable stream of the file content.
1244
- *
1245
- * For streams, this is the original stream.
1246
- */
1394
+ * Returns a ReadableStream or Node.js Readable stream of the file content.
1395
+ *
1396
+ * For streams, this is the original stream.
1397
+ */
1247
1398
  stream(): StreamLike;
1248
1399
  /**
1249
- * Returns the file content as an ArrayBuffer.
1250
- *
1251
- * For streams, this reads the entire stream into memory.
1252
- */
1400
+ * Returns the file content as an ArrayBuffer.
1401
+ *
1402
+ * For streams, this reads the entire stream into memory.
1403
+ */
1253
1404
  arrayBuffer(): Promise<ArrayBuffer>;
1254
1405
  /**
1255
- * Returns the file content as a string.
1256
- *
1257
- * For streams, this reads the entire stream into memory and converts it to a string.
1258
- */
1406
+ * Returns the file content as a string.
1407
+ *
1408
+ * For streams, this reads the entire stream into memory and converts it to a string.
1409
+ */
1259
1410
  text(): Promise<string>;
1260
- // -- node specific fields --
1261
1411
  /**
1262
- * Optional file path, if the file is stored on disk.
1263
- *
1264
- * This is not from the File API, but rather a custom field to indicate where the file is stored.
1265
- */
1412
+ * Optional file path, if the file is stored on disk.
1413
+ *
1414
+ * This is not from the File API, but rather a custom field to indicate where the file is stored.
1415
+ */
1266
1416
  filepath?: string;
1267
1417
  }
1268
1418
  /**
1269
- * TypeBox view of FileLike.
1270
- */
1419
+ * TypeBox view of FileLike.
1420
+ */
1271
1421
  type TFile = TUnsafe<FileLike>;
1272
1422
  declare const isTypeFile: (value: TSchema$1) => value is TFile;
1273
1423
  declare const isFileLike: (value: any) => value is FileLike;
1274
- // ---------------------------------------------------------------------------------------------------------------------
1275
1424
  type StreamLike = ReadableStream | ReadableStream$1 | Readable | NodeJS.ReadableStream;
1276
1425
  type TStream = TUnsafe<StreamLike>;
1277
1426
  declare const isTypeStream: (value: TSchema$1) => value is TStream;
1278
- // ---------------------------------------------------------------------------------------------------------------------
1279
1427
  type TextLength = "short" | "long" | "rich";
1280
1428
  interface AlephaStringOptions extends StringOptions {
1281
1429
  size?: TextLength;
1282
1430
  }
1283
- // ---------------------------------------------------------------------------------------------------------------------
1284
1431
  declare const t: TypeProvider;
1285
- // ---------------------------------------------------------------------------------------------------------------------
1286
- declare const isUUID: (value: string) => boolean;
1432
+ declare function isISODate(str: string): boolean;
1433
+ declare function isISODateTime(value: string): boolean;
1434
+ declare function isUUID(value: string): boolean;
1435
+ declare function isEmail(value: string): boolean;
1436
+ //# sourceMappingURL=TypeProvider.d.ts.map
1287
1437
  //#endregion
1288
1438
  //#region src/index.d.ts
1289
1439
  /**
1290
- *
1291
- */
1292
- declare const run: (entry: Alepha | Service | Array<Service>, opts?: RunOptions) => Alepha;
1440
+ *
1441
+ */
1442
+ declare const run: (entry: Alepha | Service | Array<Service>, opts?: RunOptions) => void;
1443
+ //# sourceMappingURL=index.d.ts.map
1444
+
1293
1445
  //#endregion
1294
- export { $cursor, $hook, $inject, $injectResolverRegistry, $logger, AbstractService, Alepha, AlephaError, AlephaStringOptions, AlsProvider, AppNotStartedError, Async, AsyncFn, AsyncLocalStorageData, COLORS, CircularDependencyError, ContainerLockedError, CursorDescriptor, Descriptor, DescriptorIdentifier, DescriptorItem, Env, FileLike, Hook, HookDescriptor, HookOptions, Hooks, InstantiableService, KIND, LEVEL_COLORS, LogLevel, Logger, LoggerEnv, LoggerOptions, MaybePromise, MockLogger, MockLoggerStore, Module, ModuleDefinition, NotImplementedError, OPTIONS, PromiseFn, Service, ServiceEntry, ServiceSubstitution, State, Static, StaticDecode, StaticEncode, StreamLike, TAny, TArray, TBoolean, TFile, TNumber, TObject, TOptional, TProperties, TRecord, TSchema, TStream, TString, TextLength, TypeBox, TypeBoxError, TypeBoxValue, TypeGuard, TypeProvider, __alephaRef, __bind, __descriptor, descriptorEvents, isDescriptorValue, isFileLike, isModule, isTypeFile, isTypeStream, isUUID, run, t, toModuleName };
1446
+ export { $cursor, $env, $hook, $inject, $logger, $module, AbstractClass, Alepha, AlephaError, AlephaStringOptions, AlsProvider, AppNotStartedError, Async, AsyncFn, AsyncLocalStorageData, COLORS, CircularDependencyError, ContainerLockedError, CursorDescriptor, Descriptor, DescriptorArgs, DescriptorConfig, DescriptorFactory, DescriptorFactoryLike, Env, FileLike, Hook, HookDescriptor, HookOptions, Hooks, InjectDescriptor, InstantiableClass, KIND, LEVEL_COLORS, LogLevel, Logger, LoggerDescriptorOptions, LoggerEnv, LoggerOptions, MaybePromise, MockLogger, MockLoggerStore, Module, ModuleDefinition, ModuleDescriptor, ModuleDescriptorOptions, NotImplementedError, OPTIONS, Service, ServiceEntry, ServiceSubstitution, State, type Static, type StaticDecode, type StaticEncode, StreamLike, type TAny, type TArray, type TBoolean, TFile, type TNumber, type TObject, type TOptional, type TProperties, type TRecord, type TSchema, TStream, type TString, TextLength, TypeBox, TypeBoxError, TypeBoxValue, TypeGuard, TypeProvider, __alephaRef, createDescriptor, descriptorEvents, isEmail, isFileLike, isISODate, isISODateTime, isModule, isTypeFile, isTypeStream, isUUID, run, t, toModuleName };
1295
1447
  //# sourceMappingURL=index.d.ts.map