@geekmidas/services 10.0.0-alpha.98 → 10.0.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/CHANGELOG.md +117 -0
- package/README.md +5 -5
- package/dist/{ServiceDiscovery-I7GKGDgi.d.mts → ServiceDiscovery-BO8W-RY8.d.cts} +8 -5
- package/dist/ServiceDiscovery-BO8W-RY8.d.cts.map +1 -0
- package/dist/{ServiceDiscovery-C1bAv6vY.cjs → ServiceDiscovery-BrCUabG_.cjs} +9 -9
- package/dist/ServiceDiscovery-BrCUabG_.cjs.map +1 -0
- package/dist/{ServiceDiscovery-YbZxbSHi.d.cts → ServiceDiscovery-CRq_bGbi.d.mts} +8 -5
- package/dist/ServiceDiscovery-CRq_bGbi.d.mts.map +1 -0
- package/dist/{ServiceDiscovery-5LlW7BgD.mjs → ServiceDiscovery-WHikQSQv.mjs} +5 -5
- package/dist/ServiceDiscovery-WHikQSQv.mjs.map +1 -0
- package/dist/context-1ROj3zvL.cjs +197 -0
- package/dist/context-1ROj3zvL.cjs.map +1 -0
- package/dist/context-CH2c0ftq.mjs +145 -0
- package/dist/context-CH2c0ftq.mjs.map +1 -0
- package/dist/context-CU-87vsM.d.mts +64 -0
- package/dist/context-CU-87vsM.d.mts.map +1 -0
- package/dist/context-D2owD3ac.d.cts +64 -0
- package/dist/context-D2owD3ac.d.cts.map +1 -0
- package/dist/context.cjs +5 -156
- package/dist/context.d.cts +3 -74
- package/dist/context.d.mts +3 -74
- package/dist/context.mjs +2 -152
- package/dist/index.cjs +4 -5
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +4 -3
- package/dist/middy.cjs +4 -4
- package/dist/middy.cjs.map +1 -1
- package/dist/middy.d.cts +13 -9
- package/dist/middy.d.cts.map +1 -1
- package/dist/middy.d.mts +13 -9
- package/dist/middy.d.mts.map +1 -1
- package/dist/middy.mjs +4 -3
- package/dist/middy.mjs.map +1 -1
- package/dist/trpc.cjs +7 -7
- package/dist/trpc.cjs.map +1 -1
- package/dist/trpc.d.cts +11 -8
- package/dist/trpc.d.cts.map +1 -1
- package/dist/trpc.d.mts +11 -8
- package/dist/trpc.d.mts.map +1 -1
- package/dist/trpc.mjs +6 -5
- package/dist/trpc.mjs.map +1 -1
- package/dist/{types-DDxt5Kcu.d.mts → types-Bgk-0NOO.d.cts} +5 -2
- package/dist/types-Bgk-0NOO.d.cts.map +1 -0
- package/dist/{types-DDxt5Kcu.d.cts → types-BoyOCa57.d.mts} +5 -2
- package/dist/types-BoyOCa57.d.mts.map +1 -0
- package/docs/request-scoped-logging.md +167 -0
- package/package.json +12 -16
- package/src/ServiceDiscovery.ts +252 -0
- package/src/__tests__/context.spec.ts +485 -0
- package/src/__tests__/index.spec.ts +564 -0
- package/src/__tests__/middy.spec.ts +218 -0
- package/src/__tests__/trpc.spec.ts +218 -0
- package/src/context.ts +222 -0
- package/src/index.ts +17 -0
- package/src/middy.ts +226 -0
- package/src/trpc.ts +190 -0
- package/src/types.ts +92 -0
- package/tsconfig.json +9 -0
- package/tsdown.config.ts +13 -0
- package/dist/ServiceDiscovery-5LlW7BgD.mjs.map +0 -1
- package/dist/ServiceDiscovery-C1bAv6vY.cjs.map +0 -1
- package/dist/ServiceDiscovery-I7GKGDgi.d.mts.map +0 -1
- package/dist/ServiceDiscovery-YbZxbSHi.d.cts.map +0 -1
- package/dist/context.cjs.map +0 -1
- package/dist/context.d.cts.map +0 -1
- package/dist/context.d.mts.map +0 -1
- package/dist/context.mjs.map +0 -1
- package/dist/types-DDxt5Kcu.d.cts.map +0 -1
- package/dist/types-DDxt5Kcu.d.mts.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# @geekmidas/services
|
|
2
|
+
|
|
3
|
+
## 10.0.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies []:
|
|
8
|
+
- @geekmidas/envkit@10.0.0
|
|
9
|
+
- @geekmidas/logger@10.0.0
|
|
10
|
+
|
|
11
|
+
## 9.0.2
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- [#12](https://github.com/geekmidas/toolbox/pull/12) [`d53863a`](https://github.com/geekmidas/toolbox/commit/d53863a84db2e4ab5420e08f79128b637043fc42) Thanks [@geekmidas](https://github.com/geekmidas)! - Align every published package on a single version and keep them in step.
|
|
16
|
+
|
|
17
|
+
All packages now share one version, enforced by a changesets `fixed` group. The
|
|
18
|
+
baseline is 9.0.1 — @geekmidas/client's published version — so nothing moves
|
|
19
|
+
backwards; this release takes the whole set to 9.0.2 together.
|
|
20
|
+
|
|
21
|
+
Independent versions made "which version of the docs applies to me"
|
|
22
|
+
unanswerable: a reader on constructs@7 and cli@2 was on no version at all. One
|
|
23
|
+
number per release makes versioned documentation possible, and lets 9 freeze as
|
|
24
|
+
the current paradigm while the constructs rework is developed against it.
|
|
25
|
+
|
|
26
|
+
Every release now publishes every package, and a major anywhere is a major
|
|
27
|
+
everywhere. Peer ranges get simpler in return.
|
|
28
|
+
|
|
29
|
+
- Updated dependencies [[`d53863a`](https://github.com/geekmidas/toolbox/commit/d53863a84db2e4ab5420e08f79128b637043fc42)]:
|
|
30
|
+
- @geekmidas/envkit@9.0.2
|
|
31
|
+
- @geekmidas/logger@9.0.2
|
|
32
|
+
|
|
33
|
+
## 2.0.1
|
|
34
|
+
|
|
35
|
+
### Patch Changes
|
|
36
|
+
|
|
37
|
+
- 🐛 [#11](https://github.com/geekmidas/toolbox/pull/11) [`40f4dc0`](https://github.com/geekmidas/toolbox/commit/40f4dc095911b2223a255029d8f776caf7781309) Thanks [@geekmidas](https://github.com/geekmidas)! - Patch release across all packages to realign published versions with the
|
|
38
|
+
registry. The previous release only published the four packages that had
|
|
39
|
+
version bumps; the remaining packages failed with "cannot publish over the
|
|
40
|
+
previously published versions" because their versions were unchanged.
|
|
41
|
+
- Updated dependencies [[`40f4dc0`](https://github.com/geekmidas/toolbox/commit/40f4dc095911b2223a255029d8f776caf7781309)]:
|
|
42
|
+
- @geekmidas/envkit@1.1.1
|
|
43
|
+
- @geekmidas/logger@1.0.3
|
|
44
|
+
|
|
45
|
+
## 2.0.0
|
|
46
|
+
|
|
47
|
+
### Patch Changes
|
|
48
|
+
|
|
49
|
+
- Updated dependencies [[`7323f34`](https://github.com/geekmidas/toolbox/commit/7323f34176d63170dd53450889ac0b5959420c3c), [`79e2929`](https://github.com/geekmidas/toolbox/commit/79e292978d3dbc8927e25814bdb051d1c380600a)]:
|
|
50
|
+
- @geekmidas/envkit@1.1.0
|
|
51
|
+
|
|
52
|
+
## 1.1.1
|
|
53
|
+
|
|
54
|
+
### Patch Changes
|
|
55
|
+
|
|
56
|
+
- 🐛 [`9f02e9c`](https://github.com/geekmidas/toolbox/commit/9f02e9c8419db1e41692e996e177f2473237ca76) Thanks [@geekmidas](https://github.com/geekmidas)! - fix(services): bind `this` when invoking request-scoped logger methods
|
|
57
|
+
|
|
58
|
+
The request-scoped logger proxy re-resolved log methods at call time but
|
|
59
|
+
invoked them unbound. Pino's log methods read internal state off the
|
|
60
|
+
receiver (`this[Symbol(pino.msgPrefix)]`), so calling them without `this`
|
|
61
|
+
threw "Cannot read properties of undefined (reading 'Symbol(pino.msgPrefix)')"
|
|
62
|
+
in production (pino), while dev/test console & spy loggers were unaffected.
|
|
63
|
+
The proxy now invokes the resolved method with the current request's logger
|
|
64
|
+
as `this`.
|
|
65
|
+
|
|
66
|
+
## 1.1.0
|
|
67
|
+
|
|
68
|
+
### Minor Changes
|
|
69
|
+
|
|
70
|
+
- [#5](https://github.com/geekmidas/toolbox/pull/5) [`811d740`](https://github.com/geekmidas/toolbox/commit/811d740ae3875d59ad1b0dc50261266963c8cb76) Thanks [@geekmidas](https://github.com/geekmidas)! - Move the tRPC and Middy service integrations from `@geekmidas/constructs` to `@geekmidas/services`, where they belong — they depend only on `@geekmidas/services`, not on any construct.
|
|
71
|
+
- ✨ **`@geekmidas/constructs`:** the `@geekmidas/constructs/trpc` and `@geekmidas/constructs/middy` entry points are removed (they were only just added). Import from `@geekmidas/services/trpc` and `@geekmidas/services/middy` instead. (`@trpc/server` is no longer a peer dependency of `@geekmidas/constructs`.)
|
|
72
|
+
- ✨ **`@geekmidas/services`:** adds `/trpc` (`createServicesMiddleware`, `createRequestContextMiddleware`) and `/middy` (`requestContext`, `addServices`, `withServices`, `EventServices`) exports.
|
|
73
|
+
|
|
74
|
+
The Middy middlewares were also tightened:
|
|
75
|
+
- `requestContext` / `withServices` now require an explicit `logger` (no `ConsoleLogger` default) and are generic over `TLogger extends Logger`, so a custom logger type is preserved.
|
|
76
|
+
- `addServices` / `withServices` now require an `envParser` (no implicit `process.env` default).
|
|
77
|
+
- 🐛 Resolved services are attached to `event.services` (matching the `Function`/`Cron` constructs).
|
|
78
|
+
|
|
79
|
+
## 1.0.4
|
|
80
|
+
|
|
81
|
+
### Patch Changes
|
|
82
|
+
|
|
83
|
+
- 🐛 [#3](https://github.com/geekmidas/toolbox/pull/3) [`42fda53`](https://github.com/geekmidas/toolbox/commit/42fda532bdf4489a3352f6a684f5f30beafccedd) Thanks [@geekmidas](https://github.com/geekmidas)! - Fix stale logger from service initialization
|
|
84
|
+
|
|
85
|
+
## 1.0.3
|
|
86
|
+
|
|
87
|
+
### Patch Changes
|
|
88
|
+
|
|
89
|
+
- ✨ [`351f73b`](https://github.com/geekmidas/toolbox/commit/351f73b032bc0742b7f611a9fbcdfc85bbfd69a8) Thanks [@geekmidas](https://github.com/geekmidas)! - Update request context and add support for trpc
|
|
90
|
+
|
|
91
|
+
## 1.0.2
|
|
92
|
+
|
|
93
|
+
### Patch Changes
|
|
94
|
+
|
|
95
|
+
- 🐛 [`d70c6c0`](https://github.com/geekmidas/toolbox/commit/d70c6c0aeb8a79da2473ac77dbd8255a4a2f5651) Thanks [@geekmidas](https://github.com/geekmidas)! - Fix `package.json` exports so TypeScript declarations resolve correctly under NodeNext/Bundler module resolution. Each subpath export now nests `types` inside its `import`/`require` condition, pointing at the `.d.mts` and `.d.cts` files that `tsdown` actually emits (previously the exports referenced non-existent `.d.ts` files, causing type-resolution failures for consumers). Both ESM (`.mjs`) and CJS (`.cjs`) runtime entry points are preserved. Additionally, `@geekmidas/ui` had `import` paths pointing at `.js` files that were never emitted — those are corrected to `.mjs`.
|
|
96
|
+
|
|
97
|
+
- Updated dependencies [[`d70c6c0`](https://github.com/geekmidas/toolbox/commit/d70c6c0aeb8a79da2473ac77dbd8255a4a2f5651)]:
|
|
98
|
+
- @geekmidas/envkit@1.0.7
|
|
99
|
+
- @geekmidas/logger@1.0.2
|
|
100
|
+
|
|
101
|
+
## 1.0.1
|
|
102
|
+
|
|
103
|
+
### Patch Changes
|
|
104
|
+
|
|
105
|
+
- 🔥 [`4bed570`](https://github.com/geekmidas/toolbox/commit/4bed57049db24417ef81279bc88fa0e1255f7b9a) Thanks [@geekmidas](https://github.com/geekmidas)! - Remove singleton enforcement so people can use it how they see fit
|
|
106
|
+
|
|
107
|
+
## 1.0.0
|
|
108
|
+
|
|
109
|
+
### Major Changes
|
|
110
|
+
|
|
111
|
+
- [`ff7b115`](https://github.com/geekmidas/toolbox/commit/ff7b11599f60f84ac6cdc73714c853ecf786b2e8) Thanks [@geekmidas](https://github.com/geekmidas)! - Version 1 Stable release
|
|
112
|
+
|
|
113
|
+
### Patch Changes
|
|
114
|
+
|
|
115
|
+
- Updated dependencies [[`ff7b115`](https://github.com/geekmidas/toolbox/commit/ff7b11599f60f84ac6cdc73714c853ecf786b2e8)]:
|
|
116
|
+
- @geekmidas/envkit@1.0.0
|
|
117
|
+
- @geekmidas/logger@1.0.0
|
package/README.md
CHANGED
|
@@ -49,11 +49,11 @@ export { databaseService };
|
|
|
49
49
|
### Use Services in Constructs
|
|
50
50
|
|
|
51
51
|
```typescript
|
|
52
|
-
import {
|
|
52
|
+
import { e } from '@geekmidas/constructs/endpoints';
|
|
53
53
|
import { databaseService } from './services/database';
|
|
54
54
|
import { z } from 'zod';
|
|
55
55
|
|
|
56
|
-
export const getUser =
|
|
56
|
+
export const getUser = e
|
|
57
57
|
.get('/users/:id')
|
|
58
58
|
.params(z.object({ id: z.string() }))
|
|
59
59
|
.services([databaseService])
|
|
@@ -210,17 +210,17 @@ const userEventPublisher = {
|
|
|
210
210
|
Inject multiple services into a construct:
|
|
211
211
|
|
|
212
212
|
```typescript
|
|
213
|
-
import {
|
|
213
|
+
import { e } from '@geekmidas/constructs/endpoints';
|
|
214
214
|
import { databaseService } from './services/database';
|
|
215
215
|
import { cacheService } from './services/cache';
|
|
216
216
|
import { emailService } from './services/email';
|
|
217
217
|
import { z } from 'zod';
|
|
218
218
|
|
|
219
|
-
export const createUser =
|
|
219
|
+
export const createUser = e
|
|
220
220
|
.post('/users')
|
|
221
221
|
.body(z.object({
|
|
222
222
|
name: z.string(),
|
|
223
|
-
email: z.email()
|
|
223
|
+
email: z.string().email()
|
|
224
224
|
}))
|
|
225
225
|
.services([databaseService, cacheService, emailService])
|
|
226
226
|
.handle(async ({ body, services }) => {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Service } from "./types-Bgk-0NOO.cjs";
|
|
2
2
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
3
|
+
|
|
3
4
|
//#region src/ServiceDiscovery.d.ts
|
|
5
|
+
|
|
4
6
|
/**
|
|
5
7
|
* Service discovery container that manages service registration and retrieval.
|
|
6
8
|
* Implements a singleton pattern with lazy initialization of services.
|
|
@@ -129,7 +131,7 @@ declare class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {
|
|
|
129
131
|
* ]);
|
|
130
132
|
* ```
|
|
131
133
|
*/
|
|
132
|
-
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P]
|
|
134
|
+
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P] }>;
|
|
133
135
|
/**
|
|
134
136
|
* Check if a service exists in the service discovery.
|
|
135
137
|
* Can check by service name or service instance.
|
|
@@ -178,7 +180,8 @@ type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];
|
|
|
178
180
|
* // }
|
|
179
181
|
* ```
|
|
180
182
|
*/
|
|
181
|
-
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never
|
|
183
|
+
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never };
|
|
184
|
+
//# sourceMappingURL=ServiceDiscovery.d.ts.map
|
|
182
185
|
//#endregion
|
|
183
|
-
export { ServiceDiscovery
|
|
184
|
-
//# sourceMappingURL=ServiceDiscovery-
|
|
186
|
+
export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
|
|
187
|
+
//# sourceMappingURL=ServiceDiscovery-BO8W-RY8.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-BO8W-RY8.d.cts","names":[],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;AAgL8B;AAoB9B;AAA+B,cApMlB,gBAoMkB,CAAA,kBApMiB,MAoMjB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAA,SAAW,SAAA,EAlJT,iBAkJS,CAAA,CAAA,CAAA,CAAA;EAAO;EAAO,eAAA,SAAA;EAiB5C;EAAa,QAAA,QAAA;EAAA;EAAkB,QACpC,SAAA;EAAC;;;;;;AACG;;;;;;;+BAlMmB,uCACjB,wBACT,iBAAiB;;;;;;;;;;;;;;;;;;yBA2BY;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BP,qBAAqB,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;sBAwCpD,0BAA0B,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;2BA6BrC,kCACnB,KACT,gBAAgB,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;wBA6BnB;;;;;;;;;;;;;KAoBX,8BAA8B,aAAa;;;;;;;;;;;;;;;;KAiB3C,wBAAwB,qBAC7B,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
const require_context = require(
|
|
1
|
+
const require_context = require('./context-1ROj3zvL.cjs');
|
|
2
|
+
|
|
2
3
|
//#region src/ServiceDiscovery.ts
|
|
3
4
|
/**
|
|
4
5
|
* Service discovery container that manages service registration and retrieval.
|
|
@@ -31,7 +32,6 @@ const require_context = require("./context.cjs");
|
|
|
31
32
|
* ```
|
|
32
33
|
*/
|
|
33
34
|
var ServiceDiscovery = class ServiceDiscovery {
|
|
34
|
-
envParser;
|
|
35
35
|
/** Singleton instance of ServiceDiscovery */
|
|
36
36
|
static _instance;
|
|
37
37
|
/** Map of registered service definitions */
|
|
@@ -187,12 +187,12 @@ var ServiceDiscovery = class ServiceDiscovery {
|
|
|
187
187
|
return this.services.has(service.serviceName);
|
|
188
188
|
}
|
|
189
189
|
};
|
|
190
|
+
|
|
190
191
|
//#endregion
|
|
191
|
-
Object.defineProperty(exports,
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
192
|
+
Object.defineProperty(exports, 'ServiceDiscovery', {
|
|
193
|
+
enumerable: true,
|
|
194
|
+
get: function () {
|
|
195
|
+
return ServiceDiscovery;
|
|
196
|
+
}
|
|
196
197
|
});
|
|
197
|
-
|
|
198
|
-
//# sourceMappingURL=ServiceDiscovery-C1bAv6vY.cjs.map
|
|
198
|
+
//# sourceMappingURL=ServiceDiscovery-BrCUabG_.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-BrCUabG_.cjs","names":["envParser: EnvironmentParser<{}>","services: T","serviceContext","name: K","names: [...K]","service: string | Service"],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { serviceContext } from './context';\nimport type { Service } from './types';\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);\n *\n * // Register services\n * await discovery.register([\n * databaseService,\n * cacheService,\n * authService\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {\n\t/** Singleton instance of ServiceDiscovery */\n\tprivate static _instance: ServiceDiscovery<any>;\n\t/** Map of registered service definitions */\n\tprivate services = new Map<string, Service>();\n\t/** Map of instantiated service instances */\n\tprivate instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n\t/**\n\t * Gets the singleton instance of ServiceDiscovery.\n\t * Creates a new instance if one doesn't exist.\n\t *\n\t * @template T - Record type mapping service names to their instance types\n\t * @param envParser - Environment parser for service configuration\n\t * @returns The ServiceDiscovery singleton instance\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = ServiceDiscovery.getInstance<MyServices>(envParser);\n\t * ```\n\t */\n\tstatic getInstance<T extends Record<any, unknown> = any>(\n\t\tenvParser: EnvironmentParser<{}>,\n\t): ServiceDiscovery<T> {\n\t\tif (!ServiceDiscovery._instance) {\n\t\t\tServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);\n\t\t}\n\t\treturn ServiceDiscovery._instance as ServiceDiscovery<T>;\n\t}\n\n\t/**\n\t * Resets the singleton instance. Use only for testing purposes.\n\t * This clears all cached services and allows a fresh instance to be created.\n\t *\n\t * @example\n\t * ```typescript\n\t * // In test teardown\n\t * afterEach(() => {\n\t * ServiceDiscovery.reset();\n\t * });\n\t * ```\n\t */\n\tstatic reset(): void {\n\t\tServiceDiscovery._instance = undefined as any;\n\t}\n\n\t/**\n\t *\n\t * @param envParser - Environment parser for service configuration\n\t */\n\tconstructor(readonly envParser: EnvironmentParser<{}>) {}\n\n\t/**\n\t * Register multiple services with the service discovery.\n\t * Services are instantiated lazily on first access.\n\t * Already instantiated services are returned from cache.\n\t *\n\t * @template T - Array type of services to register\n\t * @param services - Array of services to register\n\t * @returns Promise resolving to a record of service names to instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = await discovery.register([\n\t * databaseService,\n\t * cacheService,\n\t * authService\n\t * ]);\n\t *\n\t * // services = {\n\t * // database: Database instance,\n\t * // cache: CacheService instance,\n\t * // auth: AuthService instance\n\t * // }\n\t * ```\n\t */\n\tasync register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n\t\tconst registeredServices = {} as ServiceRecord<T>;\n\t\tfor (const service of services) {\n\t\t\tconst name = service.serviceName as T[number]['serviceName'];\n\t\t\tif (this.instances.has(name)) {\n\t\t\t\t(registeredServices as any)[name] = this.instances.get(\n\t\t\t\t\tname,\n\t\t\t\t) as TServices[keyof TServices];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Pass both envParser and context to service\n\t\t\tconst instance = await service.register({\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\tcontext: serviceContext,\n\t\t\t});\n\n\t\t\tthis.instances.set(name, instance as TServices[keyof TServices]);\n\t\t\t(registeredServices as any)[name] =\n\t\t\t\tinstance as TServices[keyof TServices];\n\t\t}\n\n\t\treturn registeredServices;\n\t}\n\n\t/**\n\t * Get a service from the service discovery.\n\t * Services are instantiated on first access if not already cached.\n\t *\n\t * @template K - The service name key\n\t * @param name - The name of the service to get\n\t * @returns Promise resolving to the service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * const database = await discovery.get('database');\n\t * const users = await database.query('SELECT * FROM users');\n\t * ```\n\t */\n\tget<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n\t\tconst service = this.services.get(name);\n\n\t\tif (!service) {\n\t\t\tthrow new Error(`Service '${name}' not found in service discovery`);\n\t\t}\n\n\t\treturn service.register({\n\t\t\tenvParser: this.envParser,\n\t\t\tcontext: serviceContext,\n\t\t}) as Promise<TServices[K]>;\n\t}\n\t/**\n\t * Get multiple services from the service discovery.\n\t * Useful for retrieving multiple dependencies at once.\n\t *\n\t * @template K - Array of service name keys\n\t * @param names - Array of service names to retrieve\n\t * @returns Promise resolving to an object containing the service instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const { database, cache, auth } = await discovery.getMany([\n\t * 'database',\n\t * 'cache',\n\t * 'auth'\n\t * ]);\n\t * ```\n\t */\n\tasync getMany<K extends (keyof TServices & string)[]>(\n\t\tnames: [...K],\n\t): Promise<{ [P in K[number]]: TServices[P] }> {\n\t\tconst result = {} as { [P in K[number]]: TServices[P] };\n\n\t\tfor (const name of names) {\n\t\t\tresult[name] = await this.get(name);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check if a service exists in the service discovery.\n\t * Can check by service name or service instance.\n\t *\n\t * @param service - The service name or service instance to check\n\t * @returns True if the service exists, false otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (discovery.has('database')) {\n\t * const db = await discovery.get('database');\n\t * }\n\t *\n\t * // Or check with service instance\n\t * if (!discovery.has(databaseService)) {\n\t * await discovery.register([databaseService]);\n\t * }\n\t * ```\n\t */\n\thas(service: string | Service): boolean {\n\t\tif (typeof service === 'string') {\n\t\t\treturn this.services.has(service);\n\t\t}\n\n\t\treturn this.services.has(service.serviceName);\n\t}\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;\n * // type MyServiceRecord = {\n * // database: DatabaseInstance;\n * // cache: CacheInstance;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n\t[K in T[number] as K['serviceName']]: K extends Service\n\t\t? Awaited<ReturnType<K['register']>>\n\t\t: never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,mBAAb,MAAa,iBAAiE;;CAE7E,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;CAexB,OAAO,YACNA,WACsB;AACtB,OAAK,iBAAiB,UACrB,kBAAiB,YAAY,IAAI,iBAAoB;AAEtD,SAAO,iBAAiB;CACxB;;;;;;;;;;;;;CAcD,OAAO,QAAc;AACpB,mBAAiB;CACjB;;;;;CAMD,YAAqBA,WAAkC;EAAlC;CAAoC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BzD,MAAM,SAA8BC,UAAwC;EAC3E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC7B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IAClD,KACA;AACD;GACA;GAGD,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAASC;GACT,EAAC;AAEF,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC3B;EACD;AAED,SAAO;CACP;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACJ,OAAM,IAAI,OAAO,WAAW,KAAK;AAGlC,SAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAASD;EACT,EAAC;CACF;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACLE,OAC8C;EAC9C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MAClB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGpC,SAAO;CACP;;;;;;;;;;;;;;;;;;;;CAqBD,IAAIC,SAAoC;AACvC,aAAW,YAAY,SACtB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGlC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC7C;AACD"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Service } from "./types-BoyOCa57.mjs";
|
|
2
2
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
3
|
+
|
|
3
4
|
//#region src/ServiceDiscovery.d.ts
|
|
5
|
+
|
|
4
6
|
/**
|
|
5
7
|
* Service discovery container that manages service registration and retrieval.
|
|
6
8
|
* Implements a singleton pattern with lazy initialization of services.
|
|
@@ -129,7 +131,7 @@ declare class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {
|
|
|
129
131
|
* ]);
|
|
130
132
|
* ```
|
|
131
133
|
*/
|
|
132
|
-
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P]
|
|
134
|
+
getMany<K extends (keyof TServices & string)[]>(names: [...K]): Promise<{ [P in K[number]]: TServices[P] }>;
|
|
133
135
|
/**
|
|
134
136
|
* Check if a service exists in the service discovery.
|
|
135
137
|
* Can check by service name or service instance.
|
|
@@ -178,7 +180,8 @@ type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];
|
|
|
178
180
|
* // }
|
|
179
181
|
* ```
|
|
180
182
|
*/
|
|
181
|
-
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never
|
|
183
|
+
type ServiceRecord<T extends Service[]> = { [K in T[number] as K['serviceName']]: K extends Service ? Awaited<ReturnType<K['register']>> : never };
|
|
184
|
+
//# sourceMappingURL=ServiceDiscovery.d.ts.map
|
|
182
185
|
//#endregion
|
|
183
|
-
export { ServiceDiscovery
|
|
184
|
-
//# sourceMappingURL=ServiceDiscovery-
|
|
186
|
+
export { ExtractServiceNames, ServiceDiscovery, ServiceRecord };
|
|
187
|
+
//# sourceMappingURL=ServiceDiscovery-CRq_bGbi.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-CRq_bGbi.d.mts","names":[],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;AAgL8B;AAoB9B;AAA+B,cApMlB,gBAoMkB,CAAA,kBApMiB,MAoMjB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAA,SAAW,SAAA,EAlJT,iBAkJS,CAAA,CAAA,CAAA,CAAA;EAAO;EAAO,eAAA,SAAA;EAiB5C;EAAa,QAAA,QAAA;EAAA;EAAkB,QACpC,SAAA;EAAC;;;;;;AACG;;;;;;;+BAlMmB,uCACjB,wBACT,iBAAiB;;;;;;;;;;;;;;;;;;yBA2BY;;;;;;;;;;;;;;;;;;;;;;;;;qBA0BP,qBAAqB,IAAI,QAAQ,cAAc;;;;;;;;;;;;;;;;sBAwCpD,0BAA0B,IAAI,QAAQ,UAAU;;;;;;;;;;;;;;;;;;2BA6BrC,kCACnB,KACT,gBAAgB,YAAY,UAAU;;;;;;;;;;;;;;;;;;;;wBA6BnB;;;;;;;;;;;;;KAoBX,8BAA8B,aAAa;;;;;;;;;;;;;;;;KAiB3C,wBAAwB,qBAC7B,aAAa,mBAAmB,UAAU,UAC7C,QAAQ,WAAW"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { serviceContext } from "./context.mjs";
|
|
1
|
+
import { serviceContext } from "./context-CH2c0ftq.mjs";
|
|
2
|
+
|
|
2
3
|
//#region src/ServiceDiscovery.ts
|
|
3
4
|
/**
|
|
4
5
|
* Service discovery container that manages service registration and retrieval.
|
|
@@ -31,7 +32,6 @@ import { serviceContext } from "./context.mjs";
|
|
|
31
32
|
* ```
|
|
32
33
|
*/
|
|
33
34
|
var ServiceDiscovery = class ServiceDiscovery {
|
|
34
|
-
envParser;
|
|
35
35
|
/** Singleton instance of ServiceDiscovery */
|
|
36
36
|
static _instance;
|
|
37
37
|
/** Map of registered service definitions */
|
|
@@ -187,7 +187,7 @@ var ServiceDiscovery = class ServiceDiscovery {
|
|
|
187
187
|
return this.services.has(service.serviceName);
|
|
188
188
|
}
|
|
189
189
|
};
|
|
190
|
-
//#endregion
|
|
191
|
-
export { ServiceDiscovery as t };
|
|
192
190
|
|
|
193
|
-
//#
|
|
191
|
+
//#endregion
|
|
192
|
+
export { ServiceDiscovery };
|
|
193
|
+
//# sourceMappingURL=ServiceDiscovery-WHikQSQv.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceDiscovery-WHikQSQv.mjs","names":["envParser: EnvironmentParser<{}>","services: T","name: K","names: [...K]","service: string | Service"],"sources":["../src/ServiceDiscovery.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { serviceContext } from './context';\nimport type { Service } from './types';\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);\n *\n * // Register services\n * await discovery.register([\n * databaseService,\n * cacheService,\n * authService\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {\n\t/** Singleton instance of ServiceDiscovery */\n\tprivate static _instance: ServiceDiscovery<any>;\n\t/** Map of registered service definitions */\n\tprivate services = new Map<string, Service>();\n\t/** Map of instantiated service instances */\n\tprivate instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n\t/**\n\t * Gets the singleton instance of ServiceDiscovery.\n\t * Creates a new instance if one doesn't exist.\n\t *\n\t * @template T - Record type mapping service names to their instance types\n\t * @param envParser - Environment parser for service configuration\n\t * @returns The ServiceDiscovery singleton instance\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = ServiceDiscovery.getInstance<MyServices>(envParser);\n\t * ```\n\t */\n\tstatic getInstance<T extends Record<any, unknown> = any>(\n\t\tenvParser: EnvironmentParser<{}>,\n\t): ServiceDiscovery<T> {\n\t\tif (!ServiceDiscovery._instance) {\n\t\t\tServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);\n\t\t}\n\t\treturn ServiceDiscovery._instance as ServiceDiscovery<T>;\n\t}\n\n\t/**\n\t * Resets the singleton instance. Use only for testing purposes.\n\t * This clears all cached services and allows a fresh instance to be created.\n\t *\n\t * @example\n\t * ```typescript\n\t * // In test teardown\n\t * afterEach(() => {\n\t * ServiceDiscovery.reset();\n\t * });\n\t * ```\n\t */\n\tstatic reset(): void {\n\t\tServiceDiscovery._instance = undefined as any;\n\t}\n\n\t/**\n\t *\n\t * @param envParser - Environment parser for service configuration\n\t */\n\tconstructor(readonly envParser: EnvironmentParser<{}>) {}\n\n\t/**\n\t * Register multiple services with the service discovery.\n\t * Services are instantiated lazily on first access.\n\t * Already instantiated services are returned from cache.\n\t *\n\t * @template T - Array type of services to register\n\t * @param services - Array of services to register\n\t * @returns Promise resolving to a record of service names to instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const services = await discovery.register([\n\t * databaseService,\n\t * cacheService,\n\t * authService\n\t * ]);\n\t *\n\t * // services = {\n\t * // database: Database instance,\n\t * // cache: CacheService instance,\n\t * // auth: AuthService instance\n\t * // }\n\t * ```\n\t */\n\tasync register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n\t\tconst registeredServices = {} as ServiceRecord<T>;\n\t\tfor (const service of services) {\n\t\t\tconst name = service.serviceName as T[number]['serviceName'];\n\t\t\tif (this.instances.has(name)) {\n\t\t\t\t(registeredServices as any)[name] = this.instances.get(\n\t\t\t\t\tname,\n\t\t\t\t) as TServices[keyof TServices];\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Pass both envParser and context to service\n\t\t\tconst instance = await service.register({\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\tcontext: serviceContext,\n\t\t\t});\n\n\t\t\tthis.instances.set(name, instance as TServices[keyof TServices]);\n\t\t\t(registeredServices as any)[name] =\n\t\t\t\tinstance as TServices[keyof TServices];\n\t\t}\n\n\t\treturn registeredServices;\n\t}\n\n\t/**\n\t * Get a service from the service discovery.\n\t * Services are instantiated on first access if not already cached.\n\t *\n\t * @template K - The service name key\n\t * @param name - The name of the service to get\n\t * @returns Promise resolving to the service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * const database = await discovery.get('database');\n\t * const users = await database.query('SELECT * FROM users');\n\t * ```\n\t */\n\tget<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n\t\tconst service = this.services.get(name);\n\n\t\tif (!service) {\n\t\t\tthrow new Error(`Service '${name}' not found in service discovery`);\n\t\t}\n\n\t\treturn service.register({\n\t\t\tenvParser: this.envParser,\n\t\t\tcontext: serviceContext,\n\t\t}) as Promise<TServices[K]>;\n\t}\n\t/**\n\t * Get multiple services from the service discovery.\n\t * Useful for retrieving multiple dependencies at once.\n\t *\n\t * @template K - Array of service name keys\n\t * @param names - Array of service names to retrieve\n\t * @returns Promise resolving to an object containing the service instances\n\t *\n\t * @example\n\t * ```typescript\n\t * const { database, cache, auth } = await discovery.getMany([\n\t * 'database',\n\t * 'cache',\n\t * 'auth'\n\t * ]);\n\t * ```\n\t */\n\tasync getMany<K extends (keyof TServices & string)[]>(\n\t\tnames: [...K],\n\t): Promise<{ [P in K[number]]: TServices[P] }> {\n\t\tconst result = {} as { [P in K[number]]: TServices[P] };\n\n\t\tfor (const name of names) {\n\t\t\tresult[name] = await this.get(name);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check if a service exists in the service discovery.\n\t * Can check by service name or service instance.\n\t *\n\t * @param service - The service name or service instance to check\n\t * @returns True if the service exists, false otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (discovery.has('database')) {\n\t * const db = await discovery.get('database');\n\t * }\n\t *\n\t * // Or check with service instance\n\t * if (!discovery.has(databaseService)) {\n\t * await discovery.register([databaseService]);\n\t * }\n\t * ```\n\t */\n\thas(service: string | Service): boolean {\n\t\tif (typeof service === 'string') {\n\t\t\treturn this.services.has(service);\n\t\t}\n\n\t\treturn this.services.has(service.serviceName);\n\t}\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;\n * // type MyServiceRecord = {\n * // database: DatabaseInstance;\n * // cache: CacheInstance;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n\t[K in T[number] as K['serviceName']]: K extends Service\n\t\t? Awaited<ReturnType<K['register']>>\n\t\t: never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,mBAAb,MAAa,iBAAiE;;CAE7E,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;CAexB,OAAO,YACNA,WACsB;AACtB,OAAK,iBAAiB,UACrB,kBAAiB,YAAY,IAAI,iBAAoB;AAEtD,SAAO,iBAAiB;CACxB;;;;;;;;;;;;;CAcD,OAAO,QAAc;AACpB,mBAAiB;CACjB;;;;;CAMD,YAAqBA,WAAkC;EAAlC;CAAoC;;;;;;;;;;;;;;;;;;;;;;;;;CA0BzD,MAAM,SAA8BC,UAAwC;EAC3E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC/B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC7B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IAClD,KACA;AACD;GACA;GAGD,MAAM,WAAW,MAAM,QAAQ,SAAS;IACvC,WAAW,KAAK;IAChB,SAAS;GACT,EAAC;AAEF,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC3B;EACD;AAED,SAAO;CACP;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACvE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACJ,OAAM,IAAI,OAAO,WAAW,KAAK;AAGlC,SAAO,QAAQ,SAAS;GACvB,WAAW,KAAK;GAChB,SAAS;EACT,EAAC;CACF;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACLC,OAC8C;EAC9C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MAClB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGpC,SAAO;CACP;;;;;;;;;;;;;;;;;;;;CAqBD,IAAIC,SAAoC;AACvC,aAAW,YAAY,SACtB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGlC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC7C;AACD"}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
//#region rolldown:runtime
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
const node_async_hooks = __toESM(require("node:async_hooks"));
|
|
25
|
+
|
|
26
|
+
//#region src/context.ts
|
|
27
|
+
/**
|
|
28
|
+
* Internal AsyncLocalStorage instance for request context.
|
|
29
|
+
* Not exported - use runWithRequestContext() to establish context
|
|
30
|
+
* and serviceContext to access it.
|
|
31
|
+
*/
|
|
32
|
+
const requestContextStorage = new node_async_hooks.AsyncLocalStorage();
|
|
33
|
+
/**
|
|
34
|
+
* Resolve the logger for the current request, or throw if there is none.
|
|
35
|
+
*/
|
|
36
|
+
function resolveRequestLogger() {
|
|
37
|
+
const store = requestContextStorage.getStore();
|
|
38
|
+
if (!store) throw new Error("ServiceContext.getLogger() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
39
|
+
return store.logger;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a Logger that re-resolves its underlying logger on every call instead
|
|
43
|
+
* of capturing it once.
|
|
44
|
+
*
|
|
45
|
+
* This is what makes it safe for a **singleton** service to grab the logger a
|
|
46
|
+
* single time (e.g. during `register()`, which `ServiceDiscovery` only runs
|
|
47
|
+
* once and then caches) and reuse that reference for every request: each log
|
|
48
|
+
* call resolves the *current* request's logger from `AsyncLocalStorage`, so
|
|
49
|
+
* requests no longer inherit the first request's logger (and its `requestId`,
|
|
50
|
+
* user bindings, etc.).
|
|
51
|
+
*
|
|
52
|
+
* Implemented as a `Proxy` rather than a fixed list of methods so it forwards
|
|
53
|
+
* the *entire* surface of whatever logger is supplied — including members
|
|
54
|
+
* beyond the base `Logger` interface (e.g. a richer pino-backed logger's
|
|
55
|
+
* `flush()` or `level`) and any methods added to `Logger` in the future.
|
|
56
|
+
*
|
|
57
|
+
* @param bindings - `child()` bindings applied, in order, on top of the
|
|
58
|
+
* resolved logger before each call.
|
|
59
|
+
*/
|
|
60
|
+
function createRequestScopedLogger(bindings = []) {
|
|
61
|
+
let cachedBase;
|
|
62
|
+
let cachedResolved;
|
|
63
|
+
const resolve = () => {
|
|
64
|
+
const base = resolveRequestLogger();
|
|
65
|
+
if (base !== cachedBase) {
|
|
66
|
+
cachedBase = base;
|
|
67
|
+
cachedResolved = bindings.reduce((log, obj) => log.child(obj), base);
|
|
68
|
+
}
|
|
69
|
+
return cachedResolved;
|
|
70
|
+
};
|
|
71
|
+
return new Proxy({}, {
|
|
72
|
+
get(_target, prop) {
|
|
73
|
+
if (prop === "child") return (obj) => createRequestScopedLogger([...bindings, obj]);
|
|
74
|
+
if (prop === "then" || typeof prop === "symbol") return void 0;
|
|
75
|
+
const value = resolve()[prop];
|
|
76
|
+
return typeof value === "function" ? (...args) => {
|
|
77
|
+
const resolved = resolve();
|
|
78
|
+
const fn = resolved[prop];
|
|
79
|
+
return fn.apply(resolved, args);
|
|
80
|
+
} : value;
|
|
81
|
+
},
|
|
82
|
+
has(_target, prop) {
|
|
83
|
+
if (prop === "child") return true;
|
|
84
|
+
if (prop === "then" || typeof prop === "symbol") return false;
|
|
85
|
+
return prop in resolve();
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Stable, process-wide request-scoped logger proxy. Shared across requests on
|
|
91
|
+
* purpose — it carries no request state itself, delegating to the current
|
|
92
|
+
* `AsyncLocalStorage` store on each call.
|
|
93
|
+
*/
|
|
94
|
+
const requestScopedLogger = createRequestScopedLogger();
|
|
95
|
+
/**
|
|
96
|
+
* ServiceContext implementation.
|
|
97
|
+
* Singleton that reads from AsyncLocalStorage.
|
|
98
|
+
* Methods throw if called outside a request context (catches bugs early).
|
|
99
|
+
*/
|
|
100
|
+
const serviceContext = {
|
|
101
|
+
getLogger() {
|
|
102
|
+
resolveRequestLogger();
|
|
103
|
+
return requestScopedLogger;
|
|
104
|
+
},
|
|
105
|
+
getRequestId() {
|
|
106
|
+
const store = requestContextStorage.getStore();
|
|
107
|
+
if (!store) throw new Error("ServiceContext.getRequestId() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
108
|
+
return store.requestId;
|
|
109
|
+
},
|
|
110
|
+
getRequestStartTime() {
|
|
111
|
+
const store = requestContextStorage.getStore();
|
|
112
|
+
if (!store) throw new Error("ServiceContext.getRequestStartTime() called outside request context. Ensure code runs within runWithRequestContext().");
|
|
113
|
+
return store.startTime;
|
|
114
|
+
},
|
|
115
|
+
hasContext() {
|
|
116
|
+
return requestContextStorage.getStore() !== void 0;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Run a function with request context.
|
|
121
|
+
* Used by endpoint/function/subscriber adaptors.
|
|
122
|
+
*
|
|
123
|
+
* @param data - Request context data (logger, requestId, startTime)
|
|
124
|
+
* @param fn - Function to run with context
|
|
125
|
+
* @returns Result of the function
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```typescript
|
|
129
|
+
* const result = await runWithRequestContext(
|
|
130
|
+
* { logger, requestId, startTime: Date.now() },
|
|
131
|
+
* async () => {
|
|
132
|
+
* // Inside here, serviceContext.getLogger() returns `logger`
|
|
133
|
+
* // serviceContext.getRequestId() returns `requestId`
|
|
134
|
+
* return await handleRequest();
|
|
135
|
+
* }
|
|
136
|
+
* );
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
function runWithRequestContext(data, fn) {
|
|
140
|
+
return requestContextStorage.run(data, fn);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Mutate the current async task's store so that subsequent code in this task
|
|
144
|
+
* (and any descendants) sees the supplied request context.
|
|
145
|
+
*
|
|
146
|
+
* Unlike `runWithRequestContext`, this does not scope the context to a
|
|
147
|
+
* callback — useful when the caller can't wrap a function, for example in a
|
|
148
|
+
* Vitest fixture that suspends on `use()` and yields control to the test
|
|
149
|
+
* runner before the test body executes.
|
|
150
|
+
*
|
|
151
|
+
* **Test setup only.** In production handlers, prefer `runWithRequestContext`
|
|
152
|
+
* so the frame is automatically cleaned up.
|
|
153
|
+
*/
|
|
154
|
+
function enterRequestContext(data) {
|
|
155
|
+
requestContextStorage.enterWith(data);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Clear the request context for the current async task. Pairs with
|
|
159
|
+
* `enterRequestContext`. After calling, `serviceContext.hasContext()` returns
|
|
160
|
+
* false for the remainder of the current async resource.
|
|
161
|
+
*/
|
|
162
|
+
function exitRequestContext() {
|
|
163
|
+
requestContextStorage.enterWith(void 0);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
//#endregion
|
|
167
|
+
Object.defineProperty(exports, '__toESM', {
|
|
168
|
+
enumerable: true,
|
|
169
|
+
get: function () {
|
|
170
|
+
return __toESM;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
Object.defineProperty(exports, 'enterRequestContext', {
|
|
174
|
+
enumerable: true,
|
|
175
|
+
get: function () {
|
|
176
|
+
return enterRequestContext;
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
Object.defineProperty(exports, 'exitRequestContext', {
|
|
180
|
+
enumerable: true,
|
|
181
|
+
get: function () {
|
|
182
|
+
return exitRequestContext;
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
Object.defineProperty(exports, 'runWithRequestContext', {
|
|
186
|
+
enumerable: true,
|
|
187
|
+
get: function () {
|
|
188
|
+
return runWithRequestContext;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
Object.defineProperty(exports, 'serviceContext', {
|
|
192
|
+
enumerable: true,
|
|
193
|
+
get: function () {
|
|
194
|
+
return serviceContext;
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
//# sourceMappingURL=context-1ROj3zvL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-1ROj3zvL.cjs","names":["AsyncLocalStorage","bindings: object[]","cachedBase: Logger | undefined","cachedResolved: Logger | undefined","obj: object","serviceContext: ServiceContext","data: RequestContextData","fn: () => T | Promise<T>"],"sources":["../src/context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceContext } from './types';\n\n/**\n * Internal storage for request context data.\n * Not exported - services use ServiceContext interface.\n */\nexport interface RequestContextData {\n\tlogger: Logger;\n\trequestId: string;\n\tstartTime: number;\n}\n\n/**\n * Internal AsyncLocalStorage instance for request context.\n * Not exported - use runWithRequestContext() to establish context\n * and serviceContext to access it.\n */\nconst requestContextStorage = new AsyncLocalStorage<RequestContextData>();\n\n/**\n * Resolve the logger for the current request, or throw if there is none.\n */\nfunction resolveRequestLogger(): Logger {\n\tconst store = requestContextStorage.getStore();\n\tif (!store) {\n\t\tthrow new Error(\n\t\t\t'ServiceContext.getLogger() called outside request context. ' +\n\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t);\n\t}\n\treturn store.logger;\n}\n\n/**\n * Create a Logger that re-resolves its underlying logger on every call instead\n * of capturing it once.\n *\n * This is what makes it safe for a **singleton** service to grab the logger a\n * single time (e.g. during `register()`, which `ServiceDiscovery` only runs\n * once and then caches) and reuse that reference for every request: each log\n * call resolves the *current* request's logger from `AsyncLocalStorage`, so\n * requests no longer inherit the first request's logger (and its `requestId`,\n * user bindings, etc.).\n *\n * Implemented as a `Proxy` rather than a fixed list of methods so it forwards\n * the *entire* surface of whatever logger is supplied — including members\n * beyond the base `Logger` interface (e.g. a richer pino-backed logger's\n * `flush()` or `level`) and any methods added to `Logger` in the future.\n *\n * @param bindings - `child()` bindings applied, in order, on top of the\n * resolved logger before each call.\n */\nfunction createRequestScopedLogger(bindings: object[] = []): Logger {\n\t// Memoise the resolved (optionally child) logger per underlying base logger\n\t// so we don't rebuild the child chain on every access within a request.\n\t// Recomputed whenever the current request's logger changes — there is no\n\t// await between the check and use, so this is safe under concurrency.\n\tlet cachedBase: Logger | undefined;\n\tlet cachedResolved: Logger | undefined;\n\n\tconst resolve = (): Logger => {\n\t\tconst base = resolveRequestLogger();\n\t\tif (base !== cachedBase) {\n\t\t\tcachedBase = base;\n\t\t\tcachedResolved = bindings.reduce<Logger>(\n\t\t\t\t(log, obj) => log.child(obj),\n\t\t\t\tbase,\n\t\t\t);\n\t\t}\n\t\treturn cachedResolved as Logger;\n\t};\n\n\treturn new Proxy({} as Logger, {\n\t\tget(_target, prop) {\n\t\t\t// `child()` must stay request-scoped: return a new proxy carrying the\n\t\t\t// extra binding, NOT the underlying logger's child (which would freeze\n\t\t\t// to the current request).\n\t\t\tif (prop === 'child') {\n\t\t\t\treturn (obj: object) => createRequestScopedLogger([...bindings, obj]);\n\t\t\t}\n\t\t\t// Never look like a thenable, and don't answer symbol/inspection probes\n\t\t\t// (util.inspect, Symbol.toPrimitive, etc.) with bound functions.\n\t\t\tif (prop === 'then' || typeof prop === 'symbol') {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst value = (resolve() as unknown as Record<string, unknown>)[prop];\n\t\t\t// Functions are re-resolved at *call* time so detached references\n\t\t\t// (`const info = logger.info`) still target the current request's\n\t\t\t// logger. Non-function members (e.g. `level`) forward as their live\n\t\t\t// value on the current request's logger.\n\t\t\treturn typeof value === 'function'\n\t\t\t\t? (...args: unknown[]) => {\n\t\t\t\t\t\t// Re-resolve at call time so detached references target the\n\t\t\t\t\t\t// current request's logger, and invoke with that logger as\n\t\t\t\t\t\t// `this`: pino's log methods read internal state off the\n\t\t\t\t\t\t// receiver (`this[Symbol(pino.msgPrefix)]`), so calling them\n\t\t\t\t\t\t// unbound throws \"Cannot read properties of undefined\".\n\t\t\t\t\t\tconst resolved = resolve();\n\t\t\t\t\t\tconst fn = (resolved as unknown as Record<string, unknown>)[\n\t\t\t\t\t\t\tprop\n\t\t\t\t\t\t] as (...a: unknown[]) => unknown;\n\t\t\t\t\t\treturn fn.apply(resolved, args);\n\t\t\t\t\t}\n\t\t\t\t: value;\n\t\t},\n\t\t// Keep `'prop' in logger` / hasOwnProperty truthful against the underlying\n\t\t// logger so feature-detection works.\n\t\thas(_target, prop) {\n\t\t\tif (prop === 'child') return true;\n\t\t\tif (prop === 'then' || typeof prop === 'symbol') return false;\n\t\t\treturn prop in (resolve() as object);\n\t\t},\n\t});\n}\n\n/**\n * Stable, process-wide request-scoped logger proxy. Shared across requests on\n * purpose — it carries no request state itself, delegating to the current\n * `AsyncLocalStorage` store on each call.\n */\nconst requestScopedLogger = createRequestScopedLogger();\n\n/**\n * ServiceContext implementation.\n * Singleton that reads from AsyncLocalStorage.\n * Methods throw if called outside a request context (catches bugs early).\n */\nexport const serviceContext: ServiceContext = {\n\tgetLogger() {\n\t\t// Throw eagerly if there is no context, preserving the \"catch bugs early\"\n\t\t// contract for callers that read the logger at an unexpected time.\n\t\tresolveRequestLogger();\n\t\t// Return the shared proxy rather than the raw `store.logger`. A service\n\t\t// that captures this once still logs against the correct per-request\n\t\t// logger because the proxy re-resolves on every call.\n\t\treturn requestScopedLogger;\n\t},\n\n\tgetRequestId() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestId() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.requestId;\n\t},\n\n\tgetRequestStartTime() {\n\t\tconst store = requestContextStorage.getStore();\n\t\tif (!store) {\n\t\t\tthrow new Error(\n\t\t\t\t'ServiceContext.getRequestStartTime() called outside request context. ' +\n\t\t\t\t\t'Ensure code runs within runWithRequestContext().',\n\t\t\t);\n\t\t}\n\t\treturn store.startTime;\n\t},\n\n\thasContext() {\n\t\treturn requestContextStorage.getStore() !== undefined;\n\t},\n};\n\n/**\n * Run a function with request context.\n * Used by endpoint/function/subscriber adaptors.\n *\n * @param data - Request context data (logger, requestId, startTime)\n * @param fn - Function to run with context\n * @returns Result of the function\n *\n * @example\n * ```typescript\n * const result = await runWithRequestContext(\n * { logger, requestId, startTime: Date.now() },\n * async () => {\n * // Inside here, serviceContext.getLogger() returns `logger`\n * // serviceContext.getRequestId() returns `requestId`\n * return await handleRequest();\n * }\n * );\n * ```\n */\nexport function runWithRequestContext<T>(\n\tdata: RequestContextData,\n\tfn: () => T | Promise<T>,\n): T | Promise<T> {\n\treturn requestContextStorage.run(data, fn);\n}\n\n/**\n * Mutate the current async task's store so that subsequent code in this task\n * (and any descendants) sees the supplied request context.\n *\n * Unlike `runWithRequestContext`, this does not scope the context to a\n * callback — useful when the caller can't wrap a function, for example in a\n * Vitest fixture that suspends on `use()` and yields control to the test\n * runner before the test body executes.\n *\n * **Test setup only.** In production handlers, prefer `runWithRequestContext`\n * so the frame is automatically cleaned up.\n */\nexport function enterRequestContext(data: RequestContextData): void {\n\trequestContextStorage.enterWith(data);\n}\n\n/**\n * Clear the request context for the current async task. Pairs with\n * `enterRequestContext`. After calling, `serviceContext.hasContext()` returns\n * false for the remainder of the current async resource.\n */\nexport function exitRequestContext(): void {\n\t// AsyncLocalStorage<T>.enterWith requires T, but Node accepts undefined at\n\t// runtime — passing it resets getStore() back to undefined.\n\t(requestContextStorage as unknown as AsyncLocalStorage<unknown>).enterWith(\n\t\tundefined,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,wBAAwB,IAAIA;;;;AAKlC,SAAS,uBAA+B;CACvC,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,MAAK,MACJ,OAAM,IAAI,MACT;AAIF,QAAO,MAAM;AACb;;;;;;;;;;;;;;;;;;;;AAqBD,SAAS,0BAA0BC,WAAqB,CAAE,GAAU;CAKnE,IAAIC;CACJ,IAAIC;CAEJ,MAAM,UAAU,MAAc;EAC7B,MAAM,OAAO,sBAAsB;AACnC,MAAI,SAAS,YAAY;AACxB,gBAAa;AACb,oBAAiB,SAAS,OACzB,CAAC,KAAK,QAAQ,IAAI,MAAM,IAAI,EAC5B,KACA;EACD;AACD,SAAO;CACP;AAED,QAAO,IAAI,MAAM,CAAE,GAAY;EAC9B,IAAI,SAAS,MAAM;AAIlB,OAAI,SAAS,QACZ,QAAO,CAACC,QAAgB,0BAA0B,CAAC,GAAG,UAAU,GAAI,EAAC;AAItE,OAAI,SAAS,iBAAiB,SAAS,SACtC;GAED,MAAM,QAAS,SAAS,CAAwC;AAKhE,iBAAc,UAAU,aACrB,CAAC,GAAG,SAAoB;IAMxB,MAAM,WAAW,SAAS;IAC1B,MAAM,KAAM,SACX;AAED,WAAO,GAAG,MAAM,UAAU,KAAK;GAC/B,IACA;EACH;EAGD,IAAI,SAAS,MAAM;AAClB,OAAI,SAAS,QAAS,QAAO;AAC7B,OAAI,SAAS,iBAAiB,SAAS,SAAU,QAAO;AACxD,UAAO,QAAS,SAAS;EACzB;CACD;AACD;;;;;;AAOD,MAAM,sBAAsB,2BAA2B;;;;;;AAOvD,MAAaC,iBAAiC;CAC7C,YAAY;AAGX,wBAAsB;AAItB,SAAO;CACP;CAED,eAAe;EACd,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,sBAAsB;EACrB,MAAM,QAAQ,sBAAsB,UAAU;AAC9C,OAAK,MACJ,OAAM,IAAI,MACT;AAIF,SAAO,MAAM;CACb;CAED,aAAa;AACZ,SAAO,sBAAsB,UAAU;CACvC;AACD;;;;;;;;;;;;;;;;;;;;;AAsBD,SAAgB,sBACfC,MACAC,IACiB;AACjB,QAAO,sBAAsB,IAAI,MAAM,GAAG;AAC1C;;;;;;;;;;;;;AAcD,SAAgB,oBAAoBD,MAAgC;AACnE,uBAAsB,UAAU,KAAK;AACrC;;;;;;AAOD,SAAgB,qBAA2B;AAG1C,CAAC,sBAAgE,iBAEhE;AACD"}
|