@forinda/kickjs-testing 8.0.0 → 8.1.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/README.md +12 -34
- package/dist/index-DUe-yAd5.d.mts +320 -0
- package/dist/index-DUe-yAd5.d.mts.map +1 -0
- package/dist/index.d.mts +2 -257
- package/dist/index.mjs +2 -3
- package/dist/src-Ba8LA_fH.mjs +12 -0
- package/dist/src-Ba8LA_fH.mjs.map +1 -0
- package/dist/vitest.d.mts +33 -0
- package/dist/vitest.d.mts.map +1 -0
- package/dist/vitest.mjs +12 -0
- package/dist/vitest.mjs.map +1 -0
- package/package.json +23 -9
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,60 +1,38 @@
|
|
|
1
1
|
# @forinda/kickjs-testing
|
|
2
2
|
|
|
3
|
-
Test
|
|
3
|
+
Test helpers for KickJS: `createTestApp` boots your real modules with a request client, no port needed. Also `createTestModule`, `runContributor` and `createTestPlugin` for testing pieces in isolation.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
pnpm add -D @forinda/kickjs-testing
|
|
8
|
+
pnpm add -D @forinda/kickjs-testing supertest
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
## Quick
|
|
11
|
+
## Quick example
|
|
12
12
|
|
|
13
13
|
```ts
|
|
14
|
-
import { describe,
|
|
15
|
-
import supertest from 'supertest'
|
|
14
|
+
import { describe, expect, it } from 'vitest'
|
|
16
15
|
import { createTestApp } from '@forinda/kickjs-testing'
|
|
17
|
-
import { UserModule, USER_REPO } from '
|
|
18
|
-
import { MockUserRepository } from './mocks'
|
|
16
|
+
import { UserModule, USER_REPO } from '../src/modules/users'
|
|
19
17
|
|
|
20
|
-
describe('
|
|
18
|
+
describe('users', () => {
|
|
21
19
|
it('lists users', async () => {
|
|
22
|
-
const {
|
|
20
|
+
const { client } = await createTestApp({
|
|
23
21
|
modules: [UserModule()],
|
|
24
|
-
overrides: [[USER_REPO, new
|
|
22
|
+
overrides: [[USER_REPO, new InMemoryUserRepository()]],
|
|
25
23
|
})
|
|
26
24
|
|
|
27
|
-
const res = await
|
|
28
|
-
expect(res.
|
|
25
|
+
const res = await client().get('/api/v1/users').expect(200)
|
|
26
|
+
expect(res.body.data).toHaveLength(1)
|
|
29
27
|
})
|
|
30
28
|
})
|
|
31
29
|
```
|
|
32
30
|
|
|
33
|
-
|
|
34
|
-
whichever runtime is configured. (`expressApp` is deprecated and throws under
|
|
35
|
-
Fastify or h3.)
|
|
36
|
-
|
|
37
|
-
## Test the engine you deploy
|
|
38
|
-
|
|
39
|
-
Pass `runtime`, the same value you give `bootstrap()`. Routing, body parsing,
|
|
40
|
-
status handling and error mapping all live in the runtime seam, so a green
|
|
41
|
-
Express suite says nothing about them if you ship Fastify:
|
|
42
|
-
|
|
43
|
-
```ts
|
|
44
|
-
import { fastifyRuntime } from '@forinda/kickjs/fastify'
|
|
45
|
-
|
|
46
|
-
const { app } = await createTestApp({
|
|
47
|
-
modules: [UserModule()],
|
|
48
|
-
runtime: fastifyRuntime(),
|
|
49
|
-
})
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
`overrides` takes entries or a `Map` as well as an object — a `createToken()`
|
|
53
|
-
token is a frozen object, which TypeScript rejects as a computed key.
|
|
31
|
+
Pass `runtime` (as you do to `bootstrap()`) to test on the engine you deploy.
|
|
54
32
|
|
|
55
33
|
## Documentation
|
|
56
34
|
|
|
57
|
-
[kickjs.app/guide/testing](https://kickjs.app/guide/testing)
|
|
35
|
+
[kickjs.app/guide/testing](https://kickjs.app/guide/testing): HTTP tests, auth, jobs and sockets, contributors, environment, large suites.
|
|
58
36
|
|
|
59
37
|
## License
|
|
60
38
|
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
|
|
2
|
+
import { AppAdapter, AppModuleClass, AppModuleEntry, Application, ApplicationOptions, Container, ContextDecorator, ContextMetaKey, ContributorRegistration, ExecutionContext, KickPlugin, MetaValue, ModuleRoutes } from "@forinda/kickjs";
|
|
3
|
+
import express from "express";
|
|
4
|
+
//#region src/client.d.ts
|
|
5
|
+
/** A request in flight — supertest's `Test`, chainable and awaitable. */
|
|
6
|
+
type TestRequest = any;
|
|
7
|
+
/** Options for {@link TestClient} and `createTestApp(...).client()`. */
|
|
8
|
+
interface TestClientOptions {
|
|
9
|
+
/** Headers sent with every request: `{ host: 'localhost' }`, a tenant header. */
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
/** Sent as `Authorization: Bearer <token>`. */
|
|
12
|
+
bearer?: string;
|
|
13
|
+
/** Prefixed to every path: `basePath: '/api/v1'`, then `.get('/users')`. */
|
|
14
|
+
basePath?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Keep cookies between requests, like a browser — for session and CSRF
|
|
17
|
+
* flows. Default `false`: every request starts without cookies.
|
|
18
|
+
*/
|
|
19
|
+
cookies?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Requests against a test app, through whichever runtime it runs on, with
|
|
23
|
+
* the headers every call needs set once:
|
|
24
|
+
*
|
|
25
|
+
* const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })
|
|
26
|
+
* await api.as(token).post('/invoices').send(body).expect(201)
|
|
27
|
+
*/
|
|
28
|
+
interface TestClient {
|
|
29
|
+
get(path: string): TestRequest;
|
|
30
|
+
post(path: string): TestRequest;
|
|
31
|
+
put(path: string): TestRequest;
|
|
32
|
+
patch(path: string): TestRequest;
|
|
33
|
+
delete(path: string): TestRequest;
|
|
34
|
+
head(path: string): TestRequest;
|
|
35
|
+
options(path: string): TestRequest;
|
|
36
|
+
/** The same client, sending `Authorization: Bearer <token>`. */
|
|
37
|
+
as(token: string): TestClient;
|
|
38
|
+
/** The same client, with these headers added (or replaced). */
|
|
39
|
+
withHeaders(headers: Record<string, string>): TestClient;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/reset.d.ts
|
|
43
|
+
/** Register a reset; returns a function that unregisters it. */
|
|
44
|
+
declare function onTestReset(reset: () => unknown): () => void;
|
|
45
|
+
/** Run every registered reset, in registration order. All run even if one throws. */
|
|
46
|
+
declare function resetTestState(): Promise<void>;
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/index.d.ts
|
|
49
|
+
/**
|
|
50
|
+
* Bootstrap options forwarded verbatim to the underlying Application so
|
|
51
|
+
* test apps exercise the same HTTP pipeline shape as production.
|
|
52
|
+
*/
|
|
53
|
+
type BootstrapPassthroughOptions = Pick<ApplicationOptions, 'port' | 'apiPrefix' | 'defaultVersion' | 'middlewares' | 'onError' | 'onNotFound' | 'plugins' | 'trustProxy' | 'jsonLimit' | 'security' | 'contributors' | 'contextStore' | 'runtime' | 'health'>;
|
|
54
|
+
/**
|
|
55
|
+
* Options for creating a test application.
|
|
56
|
+
* Disables helmet, cors, compression, and morgan by default.
|
|
57
|
+
*/
|
|
58
|
+
interface CreateTestAppOptions extends BootstrapPassthroughOptions {
|
|
59
|
+
/**
|
|
60
|
+
* Modules registered for the test run. Accepts both legacy class form
|
|
61
|
+
* (`UserModule extends AppModule`) and `defineModule` factory output
|
|
62
|
+
* (call the factory: `UserModule()`) — `Application` discriminates
|
|
63
|
+
* at boot.
|
|
64
|
+
*/
|
|
65
|
+
modules: AppModuleEntry[];
|
|
66
|
+
/** Adapters to attach (auth, queue, devtools, etc.) */
|
|
67
|
+
adapters?: AppAdapter[];
|
|
68
|
+
/**
|
|
69
|
+
* DI overrides applied after module registration.
|
|
70
|
+
*
|
|
71
|
+
* An object literal covers string and symbol keys. It cannot cover
|
|
72
|
+
* `createToken()`, though — a token is a frozen OBJECT identified by
|
|
73
|
+
* reference, and TypeScript rejects an object as a computed key
|
|
74
|
+
* (`TS2464: A computed property name must be of type 'string', 'number',
|
|
75
|
+
* 'symbol', or 'any'`). Since tokens are the documented way to bind an
|
|
76
|
+
* interface to an implementation, that excluded exactly the key type most
|
|
77
|
+
* worth overriding in a test.
|
|
78
|
+
*
|
|
79
|
+
* Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is
|
|
80
|
+
* a string, and the container keys tokens by reference, so the override is
|
|
81
|
+
* accepted and never applied.
|
|
82
|
+
*
|
|
83
|
+
* Pass entries to override a token:
|
|
84
|
+
*
|
|
85
|
+
* ```ts
|
|
86
|
+
* const DATABASE = createToken<Database>('app/Db/connection')
|
|
87
|
+
*
|
|
88
|
+
* await createTestApp({
|
|
89
|
+
* modules: [UserModule()],
|
|
90
|
+
* overrides: [[DATABASE, fakeDb()]],
|
|
91
|
+
* })
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* A `Map` works too. The object form is unchanged.
|
|
95
|
+
*/
|
|
96
|
+
overrides?: Record<symbol | string, any> | ReadonlyArray<readonly [token: unknown, value: unknown]> | ReadonlyMap<unknown, unknown>;
|
|
97
|
+
/**
|
|
98
|
+
* Use an isolated container instead of the global singleton.
|
|
99
|
+
* Prevents concurrent tests from interfering with each other's DI state.
|
|
100
|
+
* When true, Container.create() is used instead of Container.reset() + getInstance().
|
|
101
|
+
*/
|
|
102
|
+
isolated?: boolean;
|
|
103
|
+
}
|
|
104
|
+
declare function createTestApp(options: CreateTestAppOptions): Promise<{
|
|
105
|
+
app: Application;
|
|
106
|
+
/**
|
|
107
|
+
* Requests against the app through whichever runtime it runs on, with the
|
|
108
|
+
* headers every call needs set once (needs supertest installed):
|
|
109
|
+
*
|
|
110
|
+
* const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })
|
|
111
|
+
* await api.as(token).get('/me').expect(200)
|
|
112
|
+
*/
|
|
113
|
+
client: (options?: TestClientOptions) => TestClient;
|
|
114
|
+
/**
|
|
115
|
+
* @deprecated Use `app.handle.bind(app)`. Only valid under the Express
|
|
116
|
+
* runtime — under
|
|
117
|
+
* any other engine this throws rather than handing back that engine's
|
|
118
|
+
* instance mistyped as `express.Express`, which is how a suite ends up
|
|
119
|
+
* silently exercising the wrong runtime.
|
|
120
|
+
*/
|
|
121
|
+
expressApp: express.Express;
|
|
122
|
+
container: Container;
|
|
123
|
+
}>;
|
|
124
|
+
/**
|
|
125
|
+
* Build a quick TestModule that explicitly registers dependencies.
|
|
126
|
+
* Useful for integration tests that need to control the DI graph.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* const TestModule = createTestModule({
|
|
131
|
+
* register: (c) => {
|
|
132
|
+
* c.registerFactory(USER_REPO, () => new InMemoryUserRepo())
|
|
133
|
+
* c.register(UserController)
|
|
134
|
+
* },
|
|
135
|
+
* routes: () => buildRoutes(UserController, '/users'),
|
|
136
|
+
* })
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
declare function createTestModule(config: {
|
|
140
|
+
register: (container: Container) => void;
|
|
141
|
+
routes: () => ModuleRoutes | ModuleRoutes[] | null;
|
|
142
|
+
}): AppModuleClass;
|
|
143
|
+
/**
|
|
144
|
+
* Options for {@link runContributor}.
|
|
145
|
+
*/
|
|
146
|
+
interface RunContributorOptions {
|
|
147
|
+
/**
|
|
148
|
+
* Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container
|
|
149
|
+
* entirely — bypass for unit tests that want to assert pure resolve()
|
|
150
|
+
* behaviour without standing up a container.
|
|
151
|
+
*
|
|
152
|
+
* Property names must match the spec's `deps` keys; values can be real
|
|
153
|
+
* service instances, mocks, or test doubles.
|
|
154
|
+
*/
|
|
155
|
+
deps?: Record<string, unknown>;
|
|
156
|
+
/**
|
|
157
|
+
* Pre-populate the fake context's metadata Map. Useful for testing
|
|
158
|
+
* contributors with `dependsOn` without running the full pipeline:
|
|
159
|
+
* pre-populate the dependency keys, then assert that `resolve()` reads
|
|
160
|
+
* them and produces the expected output.
|
|
161
|
+
*/
|
|
162
|
+
initial?: Record<string, unknown>;
|
|
163
|
+
/** Override the fake context's `requestId` (default: `'test-req'`). */
|
|
164
|
+
requestId?: string;
|
|
165
|
+
/**
|
|
166
|
+
* More fields on the fake context — what an HTTP contributor reads off it:
|
|
167
|
+
* `{ req: { headers: { host: 'acme.example.com' } } }`.
|
|
168
|
+
*/
|
|
169
|
+
ctx?: Record<string, unknown>;
|
|
170
|
+
/**
|
|
171
|
+
* Env values `getEnv` / `ConfigService` return while `resolve()` runs —
|
|
172
|
+
* parsed values, like `{ TRUST_PROXY: true }`. Restored afterwards.
|
|
173
|
+
*/
|
|
174
|
+
env?: Record<string, unknown>;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Result of {@link runContributor}.
|
|
178
|
+
*/
|
|
179
|
+
interface RunContributorResult<K extends string> {
|
|
180
|
+
/** Value returned by the contributor's `resolve()` call. */
|
|
181
|
+
value: MetaValue<K>;
|
|
182
|
+
/** The fake `ExecutionContext` used during the run. */
|
|
183
|
+
ctx: ExecutionContext;
|
|
184
|
+
/**
|
|
185
|
+
* Final state of the fake context's metadata Map after `resolve()`.
|
|
186
|
+
* Includes any `ctx.set(...)` calls the resolver made plus the final
|
|
187
|
+
* resolved value under the contributor's own key.
|
|
188
|
+
*/
|
|
189
|
+
meta: Map<string, unknown>;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Run a single context contributor in isolation against a fake
|
|
193
|
+
* {@link ExecutionContext}. Skips the container, the topo-sort, and the
|
|
194
|
+
* §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`
|
|
195
|
+
* directly so unit tests can assert pure resolve behaviour.
|
|
196
|
+
*
|
|
197
|
+
* Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`
|
|
198
|
+
* or `await expect(...).rejects.toThrow()` against them. To exercise the
|
|
199
|
+
* full error matrix (optional skip, onError replacement, etc.), build a
|
|
200
|
+
* one-element pipeline with `buildPipeline()` and use `runContributors()`
|
|
201
|
+
* directly.
|
|
202
|
+
*
|
|
203
|
+
* @example
|
|
204
|
+
* ```ts
|
|
205
|
+
* const LoadProject = defineContextDecorator({
|
|
206
|
+
* key: 'project',
|
|
207
|
+
* dependsOn: ['tenant'],
|
|
208
|
+
* deps: { repo: ProjectRepo },
|
|
209
|
+
* resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),
|
|
210
|
+
* })
|
|
211
|
+
*
|
|
212
|
+
* const { value } = await runContributor(LoadProject, {
|
|
213
|
+
* initial: { tenant: { id: 't-1' } },
|
|
214
|
+
* deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },
|
|
215
|
+
* })
|
|
216
|
+
* expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })
|
|
217
|
+
* ```
|
|
218
|
+
*/
|
|
219
|
+
declare function runContributor<K extends ContextMetaKey, D extends Record<string, any> = Record<string, never>>(decorator: ContextDecorator<K, D>, options?: RunContributorOptions): Promise<RunContributorResult<K>>;
|
|
220
|
+
/**
|
|
221
|
+
* Options for {@link createTestPlugin}.
|
|
222
|
+
*/
|
|
223
|
+
interface CreateTestPluginOptions {
|
|
224
|
+
/**
|
|
225
|
+
* Use an isolated container (default: `true`). Isolated harnesses never
|
|
226
|
+
* touch the global `Container.getInstance()` singleton, so concurrent
|
|
227
|
+
* tests can run without stomping each other's DI state.
|
|
228
|
+
*/
|
|
229
|
+
isolated?: boolean;
|
|
230
|
+
/**
|
|
231
|
+
* Skip auto-invoking `plugin.register(container)` — useful when a test
|
|
232
|
+
* wants to assert container state *before* the plugin touches it.
|
|
233
|
+
* Defaults to `false` (register is called eagerly).
|
|
234
|
+
*/
|
|
235
|
+
skipRegister?: boolean;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Result of {@link createTestPlugin}. Mirrors the spec sketch in
|
|
239
|
+
* `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a
|
|
240
|
+
* `runContributors()` helper that builds a one-plugin pipeline against a
|
|
241
|
+
* fake `ExecutionContext`.
|
|
242
|
+
*/
|
|
243
|
+
interface PluginTestHarness {
|
|
244
|
+
/** The plugin under test — exposed for direct introspection. */
|
|
245
|
+
readonly plugin: KickPlugin;
|
|
246
|
+
/** Isolated (or shared) DI container the plugin registered into. */
|
|
247
|
+
readonly container: Container;
|
|
248
|
+
/**
|
|
249
|
+
* Invoke `plugin.onReady(container)`. No-op if the plugin does not
|
|
250
|
+
* define the hook.
|
|
251
|
+
*/
|
|
252
|
+
callOnReady(): Promise<void>;
|
|
253
|
+
/**
|
|
254
|
+
* Invoke `plugin.shutdown()`. No-op if the plugin does not define the
|
|
255
|
+
* hook.
|
|
256
|
+
*/
|
|
257
|
+
shutdown(): Promise<void>;
|
|
258
|
+
/**
|
|
259
|
+
* Returns the module classes the plugin ships via `plugin.modules?()`.
|
|
260
|
+
* The harness does **not** auto-instantiate them — use `createTestApp`
|
|
261
|
+
* for that. Useful for assertions like "the plugin exposes the module I
|
|
262
|
+
* expect".
|
|
263
|
+
*/
|
|
264
|
+
modules(): AppModuleEntry[];
|
|
265
|
+
/**
|
|
266
|
+
* Returns adapter instances the plugin ships via `plugin.adapters?()`.
|
|
267
|
+
* Useful for testing the adapters alongside the plugin's DI bindings.
|
|
268
|
+
*/
|
|
269
|
+
adapters(): AppAdapter[];
|
|
270
|
+
/**
|
|
271
|
+
* Returns middleware entries the plugin ships via `plugin.middleware?()`.
|
|
272
|
+
*/
|
|
273
|
+
middleware(): any[];
|
|
274
|
+
/**
|
|
275
|
+
* Returns contributor registrations the plugin ships via
|
|
276
|
+
* `plugin.contributors?()`.
|
|
277
|
+
*/
|
|
278
|
+
contributors(): ContributorRegistration[];
|
|
279
|
+
/**
|
|
280
|
+
* Build a fake {@link ExecutionContext} pre-populated with the given
|
|
281
|
+
* metadata. Symmetric with {@link runContributor}'s fake context.
|
|
282
|
+
*/
|
|
283
|
+
makeContext(initial?: Record<string, unknown>): ExecutionContext;
|
|
284
|
+
/**
|
|
285
|
+
* Run every contributor the plugin ships through a built pipeline
|
|
286
|
+
* against the given context. Dependencies resolve through the harness's
|
|
287
|
+
* container (same path production uses). Throws if the plugin's
|
|
288
|
+
* contributors reference `dependsOn` keys no one in the plugin provides.
|
|
289
|
+
*/
|
|
290
|
+
runContributors(ctx: ExecutionContext): Promise<void>;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Build an isolated test harness around a single {@link KickPlugin}.
|
|
294
|
+
* Skips the full HTTP layer — symmetric with {@link runContributor} for
|
|
295
|
+
* contributors and {@link createTestApp} for integration runs.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```ts
|
|
299
|
+
* const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))
|
|
300
|
+
*
|
|
301
|
+
* // The plugin's register() already ran — resolve any bindings.
|
|
302
|
+
* const flags = harness.container.resolve(FLAGS_SERVICE)
|
|
303
|
+
*
|
|
304
|
+
* // Drive the post-bootstrap lifecycle.
|
|
305
|
+
* await harness.callOnReady()
|
|
306
|
+
*
|
|
307
|
+
* // Exercise contributors shipped by the plugin.
|
|
308
|
+
* const ctx = harness.makeContext({ requestId: 'req-1' })
|
|
309
|
+
* await harness.runContributors(ctx)
|
|
310
|
+
* expect(ctx.get('flags')).toEqual({ beta: true })
|
|
311
|
+
*
|
|
312
|
+
* await harness.shutdown()
|
|
313
|
+
* ```
|
|
314
|
+
*/
|
|
315
|
+
declare function createTestPlugin(plugin: KickPlugin, options?: CreateTestPluginOptions): Promise<PluginTestHarness>;
|
|
316
|
+
/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */
|
|
317
|
+
declare const testPlugin: typeof createTestPlugin;
|
|
318
|
+
//#endregion
|
|
319
|
+
export { RunContributorResult as a, createTestPlugin as c, onTestReset as d, resetTestState as f, TestRequest as h, RunContributorOptions as i, runContributor as l, TestClientOptions as m, CreateTestPluginOptions as n, createTestApp as o, TestClient as p, PluginTestHarness as r, createTestModule as s, CreateTestAppOptions as t, testPlugin as u };
|
|
320
|
+
//# sourceMappingURL=index-DUe-yAd5.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-DU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B;;;;;;;EAQhD,gBAAgB,KAAK,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BpB,iBACpB,QAAQ,YACR,UAAS,0BACR,QAAQ;;cAoEE,mBAAU"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,258 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
//#region src/index.d.ts
|
|
5
|
-
/**
|
|
6
|
-
* Bootstrap options forwarded verbatim to the underlying Application so
|
|
7
|
-
* test apps exercise the same HTTP pipeline shape as production.
|
|
8
|
-
*/
|
|
9
|
-
type BootstrapPassthroughOptions = Pick<ApplicationOptions, 'port' | 'apiPrefix' | 'defaultVersion' | 'middlewares' | 'onError' | 'onNotFound' | 'plugins' | 'trustProxy' | 'jsonLimit' | 'security' | 'contributors' | 'contextStore' | 'runtime' | 'health'>;
|
|
10
|
-
/**
|
|
11
|
-
* Options for creating a test application.
|
|
12
|
-
* Disables helmet, cors, compression, and morgan by default.
|
|
13
|
-
*/
|
|
14
|
-
interface CreateTestAppOptions extends BootstrapPassthroughOptions {
|
|
15
|
-
/**
|
|
16
|
-
* Modules registered for the test run. Accepts both legacy class form
|
|
17
|
-
* (`UserModule extends AppModule`) and `defineModule` factory output
|
|
18
|
-
* (call the factory: `UserModule()`) — `Application` discriminates
|
|
19
|
-
* at boot.
|
|
20
|
-
*/
|
|
21
|
-
modules: AppModuleEntry[];
|
|
22
|
-
/** Adapters to attach (auth, queue, devtools, etc.) */
|
|
23
|
-
adapters?: AppAdapter[];
|
|
24
|
-
/**
|
|
25
|
-
* DI overrides applied after module registration.
|
|
26
|
-
*
|
|
27
|
-
* An object literal covers string and symbol keys. It cannot cover
|
|
28
|
-
* `createToken()`, though — a token is a frozen OBJECT identified by
|
|
29
|
-
* reference, and TypeScript rejects an object as a computed key
|
|
30
|
-
* (`TS2464: A computed property name must be of type 'string', 'number',
|
|
31
|
-
* 'symbol', or 'any'`). Since tokens are the documented way to bind an
|
|
32
|
-
* interface to an implementation, that excluded exactly the key type most
|
|
33
|
-
* worth overriding in a test.
|
|
34
|
-
*
|
|
35
|
-
* Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is
|
|
36
|
-
* a string, and the container keys tokens by reference, so the override is
|
|
37
|
-
* accepted and never applied.
|
|
38
|
-
*
|
|
39
|
-
* Pass entries to override a token:
|
|
40
|
-
*
|
|
41
|
-
* ```ts
|
|
42
|
-
* const DATABASE = createToken<Database>('app/Db/connection')
|
|
43
|
-
*
|
|
44
|
-
* await createTestApp({
|
|
45
|
-
* modules: [UserModule()],
|
|
46
|
-
* overrides: [[DATABASE, fakeDb()]],
|
|
47
|
-
* })
|
|
48
|
-
* ```
|
|
49
|
-
*
|
|
50
|
-
* A `Map` works too. The object form is unchanged.
|
|
51
|
-
*/
|
|
52
|
-
overrides?: Record<symbol | string, any> | ReadonlyArray<readonly [token: unknown, value: unknown]> | ReadonlyMap<unknown, unknown>;
|
|
53
|
-
/**
|
|
54
|
-
* Use an isolated container instead of the global singleton.
|
|
55
|
-
* Prevents concurrent tests from interfering with each other's DI state.
|
|
56
|
-
* When true, Container.create() is used instead of Container.reset() + getInstance().
|
|
57
|
-
*/
|
|
58
|
-
isolated?: boolean;
|
|
59
|
-
}
|
|
60
|
-
declare function createTestApp(options: CreateTestAppOptions): Promise<{
|
|
61
|
-
app: Application;
|
|
62
|
-
/**
|
|
63
|
-
* @deprecated Use `app.handle.bind(app)`. Only valid under the Express
|
|
64
|
-
* runtime — under
|
|
65
|
-
* any other engine this throws rather than handing back that engine's
|
|
66
|
-
* instance mistyped as `express.Express`, which is how a suite ends up
|
|
67
|
-
* silently exercising the wrong runtime.
|
|
68
|
-
*/
|
|
69
|
-
expressApp: express.Express;
|
|
70
|
-
container: Container;
|
|
71
|
-
}>;
|
|
72
|
-
/**
|
|
73
|
-
* Build a quick TestModule that explicitly registers dependencies.
|
|
74
|
-
* Useful for integration tests that need to control the DI graph.
|
|
75
|
-
*
|
|
76
|
-
* @example
|
|
77
|
-
* ```ts
|
|
78
|
-
* const TestModule = createTestModule({
|
|
79
|
-
* register: (c) => {
|
|
80
|
-
* c.registerFactory(USER_REPO, () => new InMemoryUserRepo())
|
|
81
|
-
* c.register(UserController)
|
|
82
|
-
* },
|
|
83
|
-
* routes: () => buildRoutes(UserController, '/users'),
|
|
84
|
-
* })
|
|
85
|
-
* ```
|
|
86
|
-
*/
|
|
87
|
-
declare function createTestModule(config: {
|
|
88
|
-
register: (container: Container) => void;
|
|
89
|
-
routes: () => ModuleRoutes | ModuleRoutes[] | null;
|
|
90
|
-
}): AppModuleClass;
|
|
91
|
-
/**
|
|
92
|
-
* Options for {@link runContributor}.
|
|
93
|
-
*/
|
|
94
|
-
interface RunContributorOptions {
|
|
95
|
-
/**
|
|
96
|
-
* Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container
|
|
97
|
-
* entirely — bypass for unit tests that want to assert pure resolve()
|
|
98
|
-
* behaviour without standing up a container.
|
|
99
|
-
*
|
|
100
|
-
* Property names must match the spec's `deps` keys; values can be real
|
|
101
|
-
* service instances, mocks, or test doubles.
|
|
102
|
-
*/
|
|
103
|
-
deps?: Record<string, unknown>;
|
|
104
|
-
/**
|
|
105
|
-
* Pre-populate the fake context's metadata Map. Useful for testing
|
|
106
|
-
* contributors with `dependsOn` without running the full pipeline:
|
|
107
|
-
* pre-populate the dependency keys, then assert that `resolve()` reads
|
|
108
|
-
* them and produces the expected output.
|
|
109
|
-
*/
|
|
110
|
-
initial?: Record<string, unknown>;
|
|
111
|
-
/** Override the fake context's `requestId` (default: `'test-req'`). */
|
|
112
|
-
requestId?: string;
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* Result of {@link runContributor}.
|
|
116
|
-
*/
|
|
117
|
-
interface RunContributorResult<K extends string> {
|
|
118
|
-
/** Value returned by the contributor's `resolve()` call. */
|
|
119
|
-
value: MetaValue<K>;
|
|
120
|
-
/** The fake `ExecutionContext` used during the run. */
|
|
121
|
-
ctx: ExecutionContext;
|
|
122
|
-
/**
|
|
123
|
-
* Final state of the fake context's metadata Map after `resolve()`.
|
|
124
|
-
* Includes any `ctx.set(...)` calls the resolver made plus the final
|
|
125
|
-
* resolved value under the contributor's own key.
|
|
126
|
-
*/
|
|
127
|
-
meta: Map<string, unknown>;
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Run a single context contributor in isolation against a fake
|
|
131
|
-
* {@link ExecutionContext}. Skips the container, the topo-sort, and the
|
|
132
|
-
* §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`
|
|
133
|
-
* directly so unit tests can assert pure resolve behaviour.
|
|
134
|
-
*
|
|
135
|
-
* Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`
|
|
136
|
-
* or `await expect(...).rejects.toThrow()` against them. To exercise the
|
|
137
|
-
* full error matrix (optional skip, onError replacement, etc.), build a
|
|
138
|
-
* one-element pipeline with `buildPipeline()` and use `runContributors()`
|
|
139
|
-
* directly.
|
|
140
|
-
*
|
|
141
|
-
* @example
|
|
142
|
-
* ```ts
|
|
143
|
-
* const LoadProject = defineContextDecorator({
|
|
144
|
-
* key: 'project',
|
|
145
|
-
* dependsOn: ['tenant'],
|
|
146
|
-
* deps: { repo: ProjectRepo },
|
|
147
|
-
* resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),
|
|
148
|
-
* })
|
|
149
|
-
*
|
|
150
|
-
* const { value } = await runContributor(LoadProject, {
|
|
151
|
-
* initial: { tenant: { id: 't-1' } },
|
|
152
|
-
* deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },
|
|
153
|
-
* })
|
|
154
|
-
* expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })
|
|
155
|
-
* ```
|
|
156
|
-
*/
|
|
157
|
-
declare function runContributor<K extends ContextMetaKey, D extends Record<string, any> = Record<string, never>>(decorator: ContextDecorator<K, D>, options?: RunContributorOptions): Promise<RunContributorResult<K>>;
|
|
158
|
-
/**
|
|
159
|
-
* Options for {@link createTestPlugin}.
|
|
160
|
-
*/
|
|
161
|
-
interface CreateTestPluginOptions {
|
|
162
|
-
/**
|
|
163
|
-
* Use an isolated container (default: `true`). Isolated harnesses never
|
|
164
|
-
* touch the global `Container.getInstance()` singleton, so concurrent
|
|
165
|
-
* tests can run without stomping each other's DI state.
|
|
166
|
-
*/
|
|
167
|
-
isolated?: boolean;
|
|
168
|
-
/**
|
|
169
|
-
* Skip auto-invoking `plugin.register(container)` — useful when a test
|
|
170
|
-
* wants to assert container state *before* the plugin touches it.
|
|
171
|
-
* Defaults to `false` (register is called eagerly).
|
|
172
|
-
*/
|
|
173
|
-
skipRegister?: boolean;
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Result of {@link createTestPlugin}. Mirrors the spec sketch in
|
|
177
|
-
* `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a
|
|
178
|
-
* `runContributors()` helper that builds a one-plugin pipeline against a
|
|
179
|
-
* fake `ExecutionContext`.
|
|
180
|
-
*/
|
|
181
|
-
interface PluginTestHarness {
|
|
182
|
-
/** The plugin under test — exposed for direct introspection. */
|
|
183
|
-
readonly plugin: KickPlugin;
|
|
184
|
-
/** Isolated (or shared) DI container the plugin registered into. */
|
|
185
|
-
readonly container: Container;
|
|
186
|
-
/**
|
|
187
|
-
* Invoke `plugin.onReady(container)`. No-op if the plugin does not
|
|
188
|
-
* define the hook.
|
|
189
|
-
*/
|
|
190
|
-
callOnReady(): Promise<void>;
|
|
191
|
-
/**
|
|
192
|
-
* Invoke `plugin.shutdown()`. No-op if the plugin does not define the
|
|
193
|
-
* hook.
|
|
194
|
-
*/
|
|
195
|
-
shutdown(): Promise<void>;
|
|
196
|
-
/**
|
|
197
|
-
* Returns the module classes the plugin ships via `plugin.modules?()`.
|
|
198
|
-
* The harness does **not** auto-instantiate them — use `createTestApp`
|
|
199
|
-
* for that. Useful for assertions like "the plugin exposes the module I
|
|
200
|
-
* expect".
|
|
201
|
-
*/
|
|
202
|
-
modules(): AppModuleEntry[];
|
|
203
|
-
/**
|
|
204
|
-
* Returns adapter instances the plugin ships via `plugin.adapters?()`.
|
|
205
|
-
* Useful for testing the adapters alongside the plugin's DI bindings.
|
|
206
|
-
*/
|
|
207
|
-
adapters(): AppAdapter[];
|
|
208
|
-
/**
|
|
209
|
-
* Returns middleware entries the plugin ships via `plugin.middleware?()`.
|
|
210
|
-
*/
|
|
211
|
-
middleware(): any[];
|
|
212
|
-
/**
|
|
213
|
-
* Returns contributor registrations the plugin ships via
|
|
214
|
-
* `plugin.contributors?()`.
|
|
215
|
-
*/
|
|
216
|
-
contributors(): ContributorRegistration[];
|
|
217
|
-
/**
|
|
218
|
-
* Build a fake {@link ExecutionContext} pre-populated with the given
|
|
219
|
-
* metadata. Symmetric with {@link runContributor}'s fake context.
|
|
220
|
-
*/
|
|
221
|
-
makeContext(initial?: Record<string, unknown>): ExecutionContext;
|
|
222
|
-
/**
|
|
223
|
-
* Run every contributor the plugin ships through a built pipeline
|
|
224
|
-
* against the given context. Dependencies resolve through the harness's
|
|
225
|
-
* container (same path production uses). Throws if the plugin's
|
|
226
|
-
* contributors reference `dependsOn` keys no one in the plugin provides.
|
|
227
|
-
*/
|
|
228
|
-
runContributors(ctx: ExecutionContext): Promise<void>;
|
|
229
|
-
}
|
|
230
|
-
/**
|
|
231
|
-
* Build an isolated test harness around a single {@link KickPlugin}.
|
|
232
|
-
* Skips the full HTTP layer — symmetric with {@link runContributor} for
|
|
233
|
-
* contributors and {@link createTestApp} for integration runs.
|
|
234
|
-
*
|
|
235
|
-
* @example
|
|
236
|
-
* ```ts
|
|
237
|
-
* const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))
|
|
238
|
-
*
|
|
239
|
-
* // The plugin's register() already ran — resolve any bindings.
|
|
240
|
-
* const flags = harness.container.resolve(FLAGS_SERVICE)
|
|
241
|
-
*
|
|
242
|
-
* // Drive the post-bootstrap lifecycle.
|
|
243
|
-
* await harness.callOnReady()
|
|
244
|
-
*
|
|
245
|
-
* // Exercise contributors shipped by the plugin.
|
|
246
|
-
* const ctx = harness.makeContext({ requestId: 'req-1' })
|
|
247
|
-
* await harness.runContributors(ctx)
|
|
248
|
-
* expect(ctx.get('flags')).toEqual({ beta: true })
|
|
249
|
-
*
|
|
250
|
-
* await harness.shutdown()
|
|
251
|
-
* ```
|
|
252
|
-
*/
|
|
253
|
-
declare function createTestPlugin(plugin: KickPlugin, options?: CreateTestPluginOptions): Promise<PluginTestHarness>;
|
|
254
|
-
/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */
|
|
255
|
-
declare const testPlugin: typeof createTestPlugin;
|
|
256
|
-
//#endregion
|
|
257
|
-
export { CreateTestAppOptions, CreateTestPluginOptions, PluginTestHarness, RunContributorOptions, RunContributorResult, createTestApp, createTestModule, createTestPlugin, runContributor, testPlugin };
|
|
258
|
-
//# sourceMappingURL=index.d.mts.map
|
|
2
|
+
import { a as RunContributorResult, c as createTestPlugin, d as onTestReset, f as resetTestState, h as TestRequest, i as RunContributorOptions, l as runContributor, m as TestClientOptions, n as CreateTestPluginOptions, o as createTestApp, p as TestClient, r as PluginTestHarness, s as createTestModule, t as CreateTestAppOptions, u as testPlugin } from "./index-DUe-yAd5.mjs";
|
|
3
|
+
export { CreateTestAppOptions, CreateTestPluginOptions, PluginTestHarness, RunContributorOptions, RunContributorResult, type TestClient, type TestClientOptions, type TestRequest, createTestApp, createTestModule, createTestPlugin, onTestReset, resetTestState, runContributor, testPlugin };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-testing v8.
|
|
2
|
+
* @forinda/kickjs-testing v8.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{
|
|
12
|
-
//# sourceMappingURL=index.mjs.map
|
|
11
|
+
import{a as testPlugin,i as runContributor,n as createTestModule,o as onTestReset,r as createTestPlugin,s as resetTestState,t as createTestApp}from"./src-Ba8LA_fH.mjs";export{createTestApp,createTestModule,createTestPlugin,onTestReset,resetTestState,runContributor,testPlugin};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-testing v8.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import*as kick from"@forinda/kickjs";import{Application,Container,MissingContextValueError,buildPipeline,runContributors}from"@forinda/kickjs";let supertest;async function loadSupertest(){if(supertest!==void 0)return supertest;try{supertest=(await import(`supertest`)).default}catch{supertest=null}return supertest}const METHODS=[`get`,`post`,`put`,`patch`,`delete`,`head`,`options`];function createClient(app,request,options={},sharedAgent){if(!request)throw Error(`createTestApp: client() sends requests with supertest, which isn't installed — add it as a dev dependency`);let handler=app.handle.bind(app),agent=options.cookies?sharedAgent??request.agent(handler):void 0,headers=lowerCaseKeys(options.headers);options.bearer&&(headers.authorization=`Bearer ${options.bearer}`);let base=options.basePath?.replace(/\/$/,``)??``,client={};for(let method of METHODS)client[method]=path=>{let test=(agent??request(handler))[method](`${base}${path}`);for(let[name,value]of Object.entries(headers))test=test.set(name,value);return test};return client.as=token=>createClient(app,request,{...options,headers,bearer:token},agent),client.withHeaders=extra=>{let added=lowerCaseKeys(extra),bearer=`authorization`in added?void 0:options.bearer;return createClient(app,request,{...options,bearer,headers:{...headers,...added}},agent)},client}function lowerCaseKeys(headers={}){return Object.fromEntries(Object.entries(headers).map(([k,v])=>[k.toLowerCase(),v]))}const resets=new Set;function onTestReset(reset){return resets.add(reset),()=>resets.delete(reset)}async function resetTestState(){let errors=[];for(let reset of resets)try{await reset()}catch(err){errors.push(err)}if(errors.length===1)throw errors[0];if(errors.length>1)throw AggregateError(errors,`${errors.length} test resets failed`)}function overrideEntries(overrides){if(Array.isArray(overrides))return overrides.map(([token,value])=>[token,value]);if(overrides instanceof Map)return[...overrides.entries()];let record=overrides;return Reflect.ownKeys(record).map(key=>[key,record[key]])}async function createTestApp(options){let container;options.isolated?container=Container.create():(Container.reset(),container=Container.getInstance());let app=new Application({modules:options.modules,adapters:options.adapters,port:options.port,apiPrefix:options.apiPrefix,defaultVersion:options.defaultVersion,middlewares:options.middlewares,onError:options.onError,onNotFound:options.onNotFound,plugins:options.plugins,trustProxy:options.trustProxy,jsonLimit:options.jsonLimit,security:options.security,contributors:options.contributors,contextStore:options.contextStore,runtime:options.runtime,health:options.health});if(await Promise.resolve(app.setup()),options.isolated){for(let entry of options.modules)(typeof entry==`function`?new entry:entry).register?.(container);container.bootstrap()}if(options.overrides)for(let[token,value]of overrideEntries(options.overrides))container.registerInstance(token,value);let runtimeName=app.getActiveRuntime().name,request=await loadSupertest();return{app,client:clientOptions=>createClient(app,request,clientOptions),get expressApp(){if(runtimeName!==`express`)throw Error(`createTestApp: 'expressApp' is only available under the Express runtime — this app is running '${runtimeName}'. Drive the app instead, which follows whichever engine is configured: request(app.handle.bind(app)).get('/...').`);return app.getExpressApp()},container}}function createTestModule(config){class TestModule{register(container){config.register(container)}routes(){return config.routes()}}return TestModule}async function runContributor(decorator,options={}){let meta=new Map(Object.entries(options.initial??{})),ctx={get(key){return meta.get(key)},require(key){let value=meta.get(key);if(value===void 0)throw new MissingContextValueError(key);return value},set(key,value){meta.set(key,value)},requestId:options.requestId??`test-req`};Object.assign(ctx,options.ctx);let run=()=>decorator.registration.resolve(ctx,options.deps??{}),withEnv=kick.withEnv;if(options.env&&!withEnv)throw Error(`runContributor: the env option needs a newer @forinda/kickjs (withEnv)`);let value=await(options.env?withEnv(options.env,run):run());return meta.set(decorator.registration.key,value),{value,ctx,meta}}async function createTestPlugin(plugin,options={}){let container=options.isolated??!0?Container.create():(Container.reset(),Container.getInstance());return options.skipRegister||plugin.register?.(container),{plugin,container,async callOnReady(){await plugin.onReady?.(container)},async shutdown(){await plugin.shutdown?.()},modules(){return plugin.modules?.()??[]},adapters(){return plugin.adapters?.()??[]},middleware(){return plugin.middleware?.()??[]},contributors(){return[...plugin.contributors?.()??[]]},makeContext(initial={}){let meta=new Map(Object.entries(initial));return{get(key){return meta.get(key)},require(key){let value=meta.get(key);if(value===void 0)throw new MissingContextValueError(key);return value},set(key,value){meta.set(key,value)},requestId:`test-req`}},async runContributors(ctx){let sources=[...plugin.contributors?.()??[]].map(registration=>({registration,source:`adapter`,label:plugin.name})),pipeline=buildPipeline(sources);await runContributors({pipeline,ctx,container})}}}const testPlugin=createTestPlugin;export{testPlugin as a,runContributor as i,createTestModule as n,onTestReset as o,createTestPlugin as r,resetTestState as s,createTestApp as t};
|
|
12
|
+
//# sourceMappingURL=src-Ba8LA_fH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Ba8LA_fH.mjs","names":[],"sources":["../src/client.ts","../src/reset.ts","../src/index.ts"],"sourcesContent":["import type { Application } from '@forinda/kickjs'\n\n/** A request in flight — supertest's `Test`, chainable and awaitable. */\n// supertest stays an optional peer, so its type is described, not imported.\nexport type TestRequest = any\n\n/** Options for {@link TestClient} and `createTestApp(...).client()`. */\nexport interface TestClientOptions {\n /** Headers sent with every request: `{ host: 'localhost' }`, a tenant header. */\n headers?: Record<string, string>\n /** Sent as `Authorization: Bearer <token>`. */\n bearer?: string\n /** Prefixed to every path: `basePath: '/api/v1'`, then `.get('/users')`. */\n basePath?: string\n /**\n * Keep cookies between requests, like a browser — for session and CSRF\n * flows. Default `false`: every request starts without cookies.\n */\n cookies?: boolean\n}\n\n/**\n * Requests against a test app, through whichever runtime it runs on, with\n * the headers every call needs set once:\n *\n * const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })\n * await api.as(token).post('/invoices').send(body).expect(201)\n */\nexport interface TestClient {\n get(path: string): TestRequest\n post(path: string): TestRequest\n put(path: string): TestRequest\n patch(path: string): TestRequest\n delete(path: string): TestRequest\n head(path: string): TestRequest\n options(path: string): TestRequest\n /** The same client, sending `Authorization: Bearer <token>`. */\n as(token: string): TestClient\n /** The same client, with these headers added (or replaced). */\n withHeaders(headers: Record<string, string>): TestClient\n}\n\ntype Supertest = ((app: unknown) => Record<string, (path: string) => TestRequest>) & {\n agent(app: unknown): Record<string, (path: string) => TestRequest>\n}\n\nlet supertest: Supertest | null | undefined\n\n/** supertest, if installed. Loaded once, on the first test app. */\nexport async function loadSupertest(): Promise<Supertest | null> {\n if (supertest !== undefined) return supertest\n try {\n supertest = ((await import('supertest')) as unknown as { default: Supertest }).default\n } catch {\n supertest = null\n }\n return supertest\n}\n\nconst METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'] as const\n\nexport function createClient(\n app: Application,\n request: Supertest | null,\n options: TestClientOptions = {},\n sharedAgent?: Record<string, (path: string) => TestRequest>,\n): TestClient {\n if (!request) {\n throw new Error(\n \"createTestApp: client() sends requests with supertest, which isn't installed — add it as a dev dependency\",\n )\n }\n const handler = app.handle.bind(app)\n // One agent per client keeps cookies — shared with the clients scoped from\n // it, so `.as()` / `.withHeaders()` keep the same cookie jar. Otherwise a\n // fresh request each call.\n const agent = options.cookies ? (sharedAgent ?? request.agent(handler)) : undefined\n // Header names are case-insensitive: kept lower-case so a later one replaces an earlier one.\n const headers = lowerCaseKeys(options.headers)\n if (options.bearer) headers.authorization = `Bearer ${options.bearer}`\n const base = options.basePath?.replace(/\\/$/, '') ?? ''\n\n const client = {} as TestClient\n for (const method of METHODS) {\n client[method] = (path: string) => {\n let test = (agent ?? request(handler))[method](`${base}${path}`)\n for (const [name, value] of Object.entries(headers)) test = test.set(name, value)\n return test\n }\n }\n client.as = (token) => createClient(app, request, { ...options, headers, bearer: token }, agent)\n client.withHeaders = (extra) => {\n const added = lowerCaseKeys(extra)\n // An explicit Authorization replaces the inherited bearer token.\n const bearer = 'authorization' in added ? undefined : options.bearer\n return createClient(\n app,\n request,\n { ...options, bearer, headers: { ...headers, ...added } },\n agent,\n )\n }\n return client\n}\n\nfunction lowerCaseKeys(headers: Record<string, string> = {}): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]))\n}\n","/**\n * Test state that outlives a test: in-memory fakes, caches, module-level\n * maps. Register a reset once, next to the thing it resets; `useTestApp`\n * runs them between test files (or tests), and `resetTestState()` runs them\n * anywhere else.\n *\n * export const sentEmails: Email[] = []\n * onTestReset(() => { sentEmails.length = 0 })\n */\nconst resets = new Set<() => unknown>()\n\n/** Register a reset; returns a function that unregisters it. */\nexport function onTestReset(reset: () => unknown): () => void {\n resets.add(reset)\n return () => resets.delete(reset)\n}\n\n/** Run every registered reset, in registration order. All run even if one throws. */\nexport async function resetTestState(): Promise<void> {\n const errors: unknown[] = []\n for (const reset of resets) {\n try {\n await reset()\n } catch (err) {\n errors.push(err)\n }\n }\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) throw new AggregateError(errors, `${errors.length} test resets failed`)\n}\n","import express from 'express'\nimport {\n Application,\n Container,\n buildPipeline,\n runContributors,\n type AppAdapter,\n type AppModule,\n type AppModuleClass,\n type AppModuleEntry,\n type ApplicationOptions,\n type ContextDecorator,\n type ContextMetaKey,\n type ContributorRegistration,\n type ExecutionContext,\n MissingContextValueError,\n type KickPlugin,\n type MetaValue,\n type ModuleRoutes,\n} from '@forinda/kickjs'\nimport * as kick from '@forinda/kickjs'\nimport { createClient, loadSupertest, type TestClient, type TestClientOptions } from './client'\n\nexport type { TestClient, TestClientOptions, TestRequest } from './client'\nexport { onTestReset, resetTestState } from './reset'\n\n/**\n * Bootstrap options forwarded verbatim to the underlying Application so\n * test apps exercise the same HTTP pipeline shape as production.\n */\ntype BootstrapPassthroughOptions = Pick<\n ApplicationOptions,\n | 'port'\n | 'apiPrefix'\n | 'defaultVersion'\n | 'middlewares'\n | 'onError'\n | 'onNotFound'\n | 'plugins'\n | 'trustProxy'\n | 'jsonLimit'\n | 'security'\n | 'contributors'\n | 'contextStore'\n // The engine under test. Without this every test ran Express while\n // production ran Fastify or h3 — the one thing an integration test exists\n // to rule out.\n | 'runtime'\n // Without this the option is accepted by the type and dropped on the way\n // through, so `health: false` silently kept the endpoints mounted.\n | 'health'\n>\n\n/**\n * Options for creating a test application.\n * Disables helmet, cors, compression, and morgan by default.\n */\nexport interface CreateTestAppOptions extends BootstrapPassthroughOptions {\n /**\n * Modules registered for the test run. Accepts both legacy class form\n * (`UserModule extends AppModule`) and `defineModule` factory output\n * (call the factory: `UserModule()`) — `Application` discriminates\n * at boot.\n */\n modules: AppModuleEntry[]\n /** Adapters to attach (auth, queue, devtools, etc.) */\n adapters?: AppAdapter[]\n /**\n * DI overrides applied after module registration.\n *\n * An object literal covers string and symbol keys. It cannot cover\n * `createToken()`, though — a token is a frozen OBJECT identified by\n * reference, and TypeScript rejects an object as a computed key\n * (`TS2464: A computed property name must be of type 'string', 'number',\n * 'symbol', or 'any'`). Since tokens are the documented way to bind an\n * interface to an implementation, that excluded exactly the key type most\n * worth overriding in a test.\n *\n * Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is\n * a string, and the container keys tokens by reference, so the override is\n * accepted and never applied.\n *\n * Pass entries to override a token:\n *\n * ```ts\n * const DATABASE = createToken<Database>('app/Db/connection')\n *\n * await createTestApp({\n * modules: [UserModule()],\n * overrides: [[DATABASE, fakeDb()]],\n * })\n * ```\n *\n * A `Map` works too. The object form is unchanged.\n */\n overrides?:\n | Record<symbol | string, any>\n | ReadonlyArray<readonly [token: unknown, value: unknown]>\n | ReadonlyMap<unknown, unknown>\n /**\n * Use an isolated container instead of the global singleton.\n * Prevents concurrent tests from interfering with each other's DI state.\n * When true, Container.create() is used instead of Container.reset() + getInstance().\n */\n isolated?: boolean\n}\n\n/**\n * Create an Application instance configured for testing.\n * Resets the DI container, registers modules, applies overrides,\n * and returns the Application, which drives whichever runtime is configured.\n *\n * Drive it through `app` — `app.handle` is the Application's own Node request\n * listener and follows whichever runtime is configured, so the same test runs\n * against the engine you actually deploy.\n *\n * @example\n * ```ts\n * const { app, container } = await createTestApp({\n * modules: [UserModule],\n * overrides: { [USER_REPO]: new InMemoryUserRepo() },\n * })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n *\n * @example Test the engine you actually deploy\n * ```ts\n * import { fastifyRuntime } from '@forinda/kickjs/fastify'\n *\n * const { app } = await createTestApp({ modules: [UserModule], runtime: fastifyRuntime() })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n */\n/**\n * Normalize every accepted `overrides` shape to `[token, value]` pairs.\n *\n * An array or Map keeps the token's identity, which is what the container\n * matches on; an object literal is limited to string and symbol keys by the\n * language itself.\n */\nfunction overrideEntries(\n overrides: NonNullable<CreateTestAppOptions['overrides']>,\n): Array<[unknown, unknown]> {\n if (Array.isArray(overrides)) return overrides.map(([token, value]) => [token, value])\n if (overrides instanceof Map) return [...overrides.entries()]\n const record = overrides as Record<symbol | string, unknown>\n return Reflect.ownKeys(record).map((key) => [key, record[key as never]])\n}\n\nexport async function createTestApp(options: CreateTestAppOptions): Promise<{\n app: Application\n /**\n * Requests against the app through whichever runtime it runs on, with the\n * headers every call needs set once (needs supertest installed):\n *\n * const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })\n * await api.as(token).get('/me').expect(200)\n */\n client: (options?: TestClientOptions) => TestClient\n /**\n * @deprecated Use `app.handle.bind(app)`. Only valid under the Express\n * runtime — under\n * any other engine this throws rather than handing back that engine's\n * instance mistyped as `express.Express`, which is how a suite ends up\n * silently exercising the wrong runtime.\n */\n expressApp: express.Express\n container: Container\n}> {\n let container: Container\n if (options.isolated) {\n // Isolated container — safe for concurrent tests\n container = Container.create()\n } else {\n // Global singleton — reset for serial test isolation (default)\n Container.reset()\n container = Container.getInstance()\n }\n\n const app = new Application({\n modules: options.modules,\n adapters: options.adapters,\n port: options.port,\n apiPrefix: options.apiPrefix,\n defaultVersion: options.defaultVersion,\n // Left undefined so the Application applies its OWN defaults, including\n // the shared body-parsing policy (#590). Naming a middleware list here\n // put the Application on its user-declared branch, so a test app parsed\n // only `application/json` while the same app in production also parsed\n // `+json`, forms and text — the harness quietly tested a different\n // pipeline. The Application already guards on\n // `RuntimeCapabilities.nativeBodyParsing`, which is what kept a connect\n // parser off Fastify and h3.\n middlewares: options.middlewares,\n onError: options.onError,\n onNotFound: options.onNotFound,\n plugins: options.plugins,\n trustProxy: options.trustProxy,\n jsonLimit: options.jsonLimit,\n security: options.security,\n contributors: options.contributors,\n contextStore: options.contextStore,\n // Without this the option is accepted and ignored, which is worse than\n // not offering it: the suite reports Express while claiming Fastify.\n runtime: options.runtime,\n health: options.health,\n })\n\n // Run setup — mounts routes, registers modules, initializes adapters.\n // Awaited to support future async adapter hooks.\n await Promise.resolve(app.setup())\n\n // When using an isolated container, Application.setup() registers modules\n // on the global singleton (Container.getInstance()). Re-register them on\n // the isolated container so that bindings are available there too.\n if (options.isolated) {\n for (const entry of options.modules) {\n // Discriminate class vs instance — `defineModule` factories return\n // AppModule instances, legacy classes need `new`. Same dispatch\n // Application.setup() runs at boot.\n const mod: AppModule = typeof entry === 'function' ? new (entry as AppModuleClass)() : entry\n // register() is optional — see AppModule docs\n mod.register?.(container)\n }\n container.bootstrap()\n }\n\n // Apply DI overrides AFTER setup so they take precedence over\n // bindings registered by modules during register().\n if (options.overrides) {\n for (const [token, value] of overrideEntries(options.overrides)) {\n container.registerInstance(token, value)\n }\n }\n\n const runtimeName = app.getActiveRuntime().name\n const request = await loadSupertest()\n\n return {\n app,\n client: (clientOptions) => createClient(app, request, clientOptions),\n get expressApp(): express.Express {\n if (runtimeName !== 'express') {\n throw new Error(\n `createTestApp: 'expressApp' is only available under the Express runtime — ` +\n `this app is running '${runtimeName}'. Drive the app instead, which follows ` +\n `whichever engine is configured: request(app.handle.bind(app)).get('/...').`,\n )\n }\n return app.getExpressApp()\n },\n container,\n }\n}\n\n/**\n * Build a quick TestModule that explicitly registers dependencies.\n * Useful for integration tests that need to control the DI graph.\n *\n * @example\n * ```ts\n * const TestModule = createTestModule({\n * register: (c) => {\n * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())\n * c.register(UserController)\n * },\n * routes: () => buildRoutes(UserController, '/users'),\n * })\n * ```\n */\nexport function createTestModule(config: {\n register: (container: Container) => void\n routes: () => ModuleRoutes | ModuleRoutes[] | null\n}): AppModuleClass {\n class TestModule implements AppModule {\n register(container: Container) {\n config.register(container)\n }\n routes() {\n return config.routes()\n }\n }\n return TestModule\n}\n\n// ── Context Contributor unit-test helper (#107) ─────────────────────────\n\n/**\n * Options for {@link runContributor}.\n */\nexport interface RunContributorOptions {\n /**\n * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container\n * entirely — bypass for unit tests that want to assert pure resolve()\n * behaviour without standing up a container.\n *\n * Property names must match the spec's `deps` keys; values can be real\n * service instances, mocks, or test doubles.\n */\n deps?: Record<string, unknown>\n\n /**\n * Pre-populate the fake context's metadata Map. Useful for testing\n * contributors with `dependsOn` without running the full pipeline:\n * pre-populate the dependency keys, then assert that `resolve()` reads\n * them and produces the expected output.\n */\n initial?: Record<string, unknown>\n\n /** Override the fake context's `requestId` (default: `'test-req'`). */\n requestId?: string\n\n /**\n * More fields on the fake context — what an HTTP contributor reads off it:\n * `{ req: { headers: { host: 'acme.example.com' } } }`.\n */\n ctx?: Record<string, unknown>\n\n /**\n * Env values `getEnv` / `ConfigService` return while `resolve()` runs —\n * parsed values, like `{ TRUST_PROXY: true }`. Restored afterwards.\n */\n env?: Record<string, unknown>\n}\n\n/**\n * Result of {@link runContributor}.\n */\nexport interface RunContributorResult<K extends string> {\n /** Value returned by the contributor's `resolve()` call. */\n value: MetaValue<K>\n /** The fake `ExecutionContext` used during the run. */\n ctx: ExecutionContext\n /**\n * Final state of the fake context's metadata Map after `resolve()`.\n * Includes any `ctx.set(...)` calls the resolver made plus the final\n * resolved value under the contributor's own key.\n */\n meta: Map<string, unknown>\n}\n\n/**\n * Run a single context contributor in isolation against a fake\n * {@link ExecutionContext}. Skips the container, the topo-sort, and the\n * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`\n * directly so unit tests can assert pure resolve behaviour.\n *\n * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`\n * or `await expect(...).rejects.toThrow()` against them. To exercise the\n * full error matrix (optional skip, onError replacement, etc.), build a\n * one-element pipeline with `buildPipeline()` and use `runContributors()`\n * directly.\n *\n * @example\n * ```ts\n * const LoadProject = defineContextDecorator({\n * key: 'project',\n * dependsOn: ['tenant'],\n * deps: { repo: ProjectRepo },\n * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),\n * })\n *\n * const { value } = await runContributor(LoadProject, {\n * initial: { tenant: { id: 't-1' } },\n * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },\n * })\n * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })\n * ```\n */\nexport async function runContributor<\n K extends ContextMetaKey,\n D extends Record<string, any> = Record<string, never>,\n>(\n decorator: ContextDecorator<K, D>,\n options: RunContributorOptions = {},\n): Promise<RunContributorResult<K>> {\n const meta = new Map<string, unknown>(Object.entries(options.initial ?? {}))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n // Same contract as RequestContext.require — a resolver under test\n // that depends on an upstream key should fail here exactly the way\n // it would in production, not read `undefined`.\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: options.requestId ?? 'test-req',\n }\n Object.assign(ctx, options.ctx)\n\n const run = () => decorator.registration.resolve(ctx, (options.deps ?? {}) as never)\n // Looked up, not imported by name: the peer range reaches back before\n // withEnv existed, and a missing named import fails the whole module.\n const withEnv = (\n kick as { withEnv?: (env: Record<string, unknown>, fn: () => unknown) => Promise<unknown> }\n ).withEnv\n if (options.env && !withEnv) {\n throw new Error('runContributor: the env option needs a newer @forinda/kickjs (withEnv)')\n }\n const value = await (options.env ? withEnv!(options.env, run) : run())\n meta.set(decorator.registration.key, value)\n\n return { value: value as MetaValue<K>, ctx, meta }\n}\n\n// ── Plugin unit-test harness (architecture.md §21.3.2) ──────────────────\n\n/**\n * Options for {@link createTestPlugin}.\n */\nexport interface CreateTestPluginOptions {\n /**\n * Use an isolated container (default: `true`). Isolated harnesses never\n * touch the global `Container.getInstance()` singleton, so concurrent\n * tests can run without stomping each other's DI state.\n */\n isolated?: boolean\n\n /**\n * Skip auto-invoking `plugin.register(container)` — useful when a test\n * wants to assert container state *before* the plugin touches it.\n * Defaults to `false` (register is called eagerly).\n */\n skipRegister?: boolean\n}\n\n/**\n * Result of {@link createTestPlugin}. Mirrors the spec sketch in\n * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a\n * `runContributors()` helper that builds a one-plugin pipeline against a\n * fake `ExecutionContext`.\n */\nexport interface PluginTestHarness {\n /** The plugin under test — exposed for direct introspection. */\n readonly plugin: KickPlugin\n /** Isolated (or shared) DI container the plugin registered into. */\n readonly container: Container\n\n /**\n * Invoke `plugin.onReady(container)`. No-op if the plugin does not\n * define the hook.\n */\n callOnReady(): Promise<void>\n\n /**\n * Invoke `plugin.shutdown()`. No-op if the plugin does not define the\n * hook.\n */\n shutdown(): Promise<void>\n\n /**\n * Returns the module classes the plugin ships via `plugin.modules?()`.\n * The harness does **not** auto-instantiate them — use `createTestApp`\n * for that. Useful for assertions like \"the plugin exposes the module I\n * expect\".\n */\n modules(): AppModuleEntry[]\n\n /**\n * Returns adapter instances the plugin ships via `plugin.adapters?()`.\n * Useful for testing the adapters alongside the plugin's DI bindings.\n */\n adapters(): AppAdapter[]\n\n /**\n * Returns middleware entries the plugin ships via `plugin.middleware?()`.\n */\n middleware(): any[]\n\n /**\n * Returns contributor registrations the plugin ships via\n * `plugin.contributors?()`.\n */\n contributors(): ContributorRegistration[]\n\n /**\n * Build a fake {@link ExecutionContext} pre-populated with the given\n * metadata. Symmetric with {@link runContributor}'s fake context.\n */\n makeContext(initial?: Record<string, unknown>): ExecutionContext\n\n /**\n * Run every contributor the plugin ships through a built pipeline\n * against the given context. Dependencies resolve through the harness's\n * container (same path production uses). Throws if the plugin's\n * contributors reference `dependsOn` keys no one in the plugin provides.\n */\n runContributors(ctx: ExecutionContext): Promise<void>\n}\n\n/**\n * Build an isolated test harness around a single {@link KickPlugin}.\n * Skips the full HTTP layer — symmetric with {@link runContributor} for\n * contributors and {@link createTestApp} for integration runs.\n *\n * @example\n * ```ts\n * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))\n *\n * // The plugin's register() already ran — resolve any bindings.\n * const flags = harness.container.resolve(FLAGS_SERVICE)\n *\n * // Drive the post-bootstrap lifecycle.\n * await harness.callOnReady()\n *\n * // Exercise contributors shipped by the plugin.\n * const ctx = harness.makeContext({ requestId: 'req-1' })\n * await harness.runContributors(ctx)\n * expect(ctx.get('flags')).toEqual({ beta: true })\n *\n * await harness.shutdown()\n * ```\n */\nexport async function createTestPlugin(\n plugin: KickPlugin,\n options: CreateTestPluginOptions = {},\n): Promise<PluginTestHarness> {\n const isolated = options.isolated ?? true\n\n const container = isolated ? Container.create() : (Container.reset(), Container.getInstance())\n\n if (!options.skipRegister) plugin.register?.(container)\n\n return {\n plugin,\n container,\n\n async callOnReady() {\n await plugin.onReady?.(container)\n },\n\n async shutdown() {\n await plugin.shutdown?.()\n },\n\n modules() {\n return plugin.modules?.() ?? []\n },\n\n adapters() {\n return plugin.adapters?.() ?? []\n },\n\n middleware() {\n return plugin.middleware?.() ?? []\n },\n\n contributors() {\n return [...(plugin.contributors?.() ?? [])]\n },\n\n makeContext(initial: Record<string, unknown> = {}) {\n const meta = new Map<string, unknown>(Object.entries(initial))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: 'test-req',\n }\n return ctx\n },\n\n async runContributors(ctx: ExecutionContext) {\n const regs = plugin.contributors?.() ?? []\n const sources = [...regs].map((registration) => ({\n registration,\n source: 'adapter' as const,\n label: plugin.name,\n }))\n const pipeline = buildPipeline(sources)\n await runContributors({ pipeline, ctx, container })\n },\n }\n}\n\n/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */\nexport const testPlugin = createTestPlugin\n"],"mappings":";;;;;;;;;;+IA8CA,IAAI,UAGJ,eAAsB,eAA2C,CAC/D,GAAI,YAAc,IAAA,GAAW,OAAO,UACpC,GAAI,CACF,WAAc,MAAM,OAAO,aAAA,CAAoD,OACjF,MAAQ,CACN,UAAY,IACd,CACA,OAAO,SACT,CAEA,MAAM,QAAU,CAAC,MAAO,OAAQ,MAAO,QAAS,SAAU,OAAQ,SAAS,EAE3E,SAAgB,aACd,IACA,QACA,QAA6B,CAAC,EAC9B,YACY,CACZ,GAAI,CAAC,QACH,MAAU,MACR,2GACF,EAEF,IAAM,QAAU,IAAI,OAAO,KAAK,GAAG,EAI7B,MAAQ,QAAQ,QAAW,aAAe,QAAQ,MAAM,OAAO,EAAK,IAAA,GAEpE,QAAU,cAAc,QAAQ,OAAO,EACzC,QAAQ,SAAQ,QAAQ,cAAgB,UAAU,QAAQ,UAC9D,IAAM,KAAO,QAAQ,UAAU,QAAQ,MAAO,EAAE,GAAK,GAE/C,OAAS,CAAC,EAChB,IAAK,IAAM,UAAU,QACnB,OAAO,QAAW,MAAiB,CACjC,IAAI,MAAQ,OAAS,QAAQ,OAAO,EAAA,CAAG,OAAO,CAAC,GAAG,OAAO,MAAM,EAC/D,IAAK,GAAM,CAAC,KAAM,SAAU,OAAO,QAAQ,OAAO,EAAG,KAAO,KAAK,IAAI,KAAM,KAAK,EAChF,OAAO,IACT,EAcF,MAZA,QAAO,GAAM,OAAU,aAAa,IAAK,QAAS,CAAE,GAAG,QAAS,QAA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AAK,IAAI,GAAG,CACrB,EACA,QAAQ,IAAK,CACX,IAAM,MAAQ,KAAK,IAAI,GAAG,EAC1B,GAAI,QAAU,IAAA,GAAW,MAAM,IAAI,yBAAyB,GAAG,EAC/D,OAAO,KACT,EACA,IAAI,IAAK,MAAO,CACd,KAAK,IAAI,IAAK,KAAK,CACrB,EACA,UAAW,UAEJ,CACX,EAEA,MAAM,gBAAgB,IAAuB,CAE3C,IAAM,QAAU,CAAC,GADJ,OAAO,eAAe,GAAK,CAAC,CACjB,CAAC,CAAC,IAAK,eAAkB,CAC/C,aACA,OAAQ,UACR,MAAO,OAAO,IAChB,EAAE,EACI,SAAW,cAAc,OAAO,EACtC,MAAM,gBAAgB,CAAE,SAAU,IAAK,SAAU,CAAC,CACpD,CACF,CACF,CAGA,MAAa,WAAa"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
|
|
2
|
+
import { m as TestClientOptions, p as TestClient, t as CreateTestAppOptions } from "./index-DUe-yAd5.mjs";
|
|
3
|
+
import { Application, Container } from "@forinda/kickjs";
|
|
4
|
+
//#region src/vitest.d.ts
|
|
5
|
+
export interface UseTestAppOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Keep one app for every file this worker runs (with `isolate: false`)
|
|
8
|
+
* instead of one per file — far faster for a large suite. It is shut down
|
|
9
|
+
* when the worker exits. Default `false`.
|
|
10
|
+
*
|
|
11
|
+
* The app is built from the options of the FIRST file that asks for it;
|
|
12
|
+
* later files reuse it without calling their own. Files that need a
|
|
13
|
+
* differently configured app name their own: `shared: 'admin-api'` keeps
|
|
14
|
+
* one app per name. `true` is the name `'default'`.
|
|
15
|
+
*/
|
|
16
|
+
shared?: boolean | string;
|
|
17
|
+
/**
|
|
18
|
+
* When `onTestReset` resets run: before each test file (`'file'`, the
|
|
19
|
+
* default), before each test (`'test'`), or never (`false`).
|
|
20
|
+
*/
|
|
21
|
+
reset?: 'file' | 'test' | false;
|
|
22
|
+
/** Client options for `t.client()` with no arguments — the usual host or base path. */
|
|
23
|
+
client?: TestClientOptions;
|
|
24
|
+
}
|
|
25
|
+
export interface TestAppHandle {
|
|
26
|
+
readonly app: Application;
|
|
27
|
+
readonly container: Container;
|
|
28
|
+
/** A request client; with no options, the defaults from `useTestApp`. */
|
|
29
|
+
client(options?: TestClientOptions): TestClient;
|
|
30
|
+
}
|
|
31
|
+
export declare function useTestApp(options: () => CreateTestAppOptions | Promise<CreateTestAppOptions>, settings?: UseTestAppOptions): TestAppHandle;
|
|
32
|
+
//#endregion
|
|
33
|
+
//# sourceMappingURL=vitest.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vitest.d.mts","names":[],"sources":["../src/vitest.ts"],"mappings":";;;;iBAgBiB;;;;;;;;;;;EAWf;;;;;EAKA;;EAEA,SAAS;;iBAGM;WACN,KAAK;WACL,WAAW;;EAEpB,OAAO,UAAU,oBAAoB;;wBASvB,WACd,eAAe,uBAAuB,QAAQ,uBAC9C,WAAU,oBACT"}
|
package/dist/vitest.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-testing v8.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{s as resetTestState,t as createTestApp}from"./src-Ba8LA_fH.mjs";import{afterAll,beforeAll,beforeEach}from"vitest";const sharedApps=new Map;let shutdownRegistered=!1;function useTestApp(options,settings={}){let created,build=async()=>createTestApp(await options());beforeAll(async()=>{if(settings.reset!==!1&&await resetTestState(),settings.shared){let name=settings.shared===!0?`default`:settings.shared,app=sharedApps.get(name);app||(app=build(),sharedApps.set(name,app)),shutdownRegistered||(shutdownRegistered=!0,process.once(`beforeExit`,()=>{for(let shared of sharedApps.values())shared.then(({app})=>app.shutdown())})),created=await app}else created=await build()}),afterAll(async()=>{settings.shared||await created?.app.shutdown(),created=void 0}),settings.reset===`test`&&beforeEach(()=>resetTestState());let ready=()=>{if(!created)throw Error(`useTestApp: the app is only available inside tests and hooks`);return created};return{get app(){return ready().app},get container(){return ready().container},client(clientOptions){return ready().client(clientOptions??settings.client)}}}export{useTestApp};
|
|
12
|
+
//# sourceMappingURL=vitest.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vitest.mjs","names":[],"sources":["../src/vitest.ts"],"sourcesContent":["/**\n * Vitest wiring for a test app: one call per file instead of the\n * `let app` / `beforeAll` / `afterAll` boilerplate.\n *\n * const t = useTestApp(() => ({ ...appOptions, overrides: [[MAILER, fakeMailer]] }))\n *\n * it('lists invoices', async () => {\n * await t.client().as(token).get('/api/v1/invoices').expect(200)\n * })\n */\nimport { afterAll, beforeAll, beforeEach } from 'vitest'\nimport type { Application, Container } from '@forinda/kickjs'\nimport { createTestApp, type CreateTestAppOptions } from './index'\nimport type { TestClient, TestClientOptions } from './client'\nimport { resetTestState } from './reset'\n\nexport interface UseTestAppOptions {\n /**\n * Keep one app for every file this worker runs (with `isolate: false`)\n * instead of one per file — far faster for a large suite. It is shut down\n * when the worker exits. Default `false`.\n *\n * The app is built from the options of the FIRST file that asks for it;\n * later files reuse it without calling their own. Files that need a\n * differently configured app name their own: `shared: 'admin-api'` keeps\n * one app per name. `true` is the name `'default'`.\n */\n shared?: boolean | string\n /**\n * When `onTestReset` resets run: before each test file (`'file'`, the\n * default), before each test (`'test'`), or never (`false`).\n */\n reset?: 'file' | 'test' | false\n /** Client options for `t.client()` with no arguments — the usual host or base path. */\n client?: TestClientOptions\n}\n\nexport interface TestAppHandle {\n readonly app: Application\n readonly container: Container\n /** A request client; with no options, the defaults from `useTestApp`. */\n client(options?: TestClientOptions): TestClient\n}\n\ntype Created = Awaited<ReturnType<typeof createTestApp>>\n\n/** Shared apps by name, for the life of the worker. */\nconst sharedApps = new Map<string, Promise<Created>>()\nlet shutdownRegistered = false\n\nexport function useTestApp(\n options: () => CreateTestAppOptions | Promise<CreateTestAppOptions>,\n settings: UseTestAppOptions = {},\n): TestAppHandle {\n let created: Created | undefined\n const build = async () => createTestApp(await options())\n\n beforeAll(async () => {\n if (settings.reset !== false) await resetTestState()\n if (settings.shared) {\n const name = settings.shared === true ? 'default' : settings.shared\n let app = sharedApps.get(name)\n if (!app) {\n app = build()\n sharedApps.set(name, app)\n }\n if (!shutdownRegistered) {\n shutdownRegistered = true\n // Shared apps live as long as the worker. Vitest ends its workers when\n // the run is over, so a handle an app leaves open can't hold the run\n // up; this closes them cleanly when the worker drains.\n process.once('beforeExit', () => {\n for (const shared of sharedApps.values()) void shared.then(({ app }) => app.shutdown())\n })\n }\n created = await app\n } else {\n created = await build()\n }\n })\n\n afterAll(async () => {\n if (!settings.shared) await created?.app.shutdown()\n created = undefined\n })\n\n if (settings.reset === 'test') beforeEach(() => resetTestState())\n\n const ready = (): Created => {\n if (!created) throw new Error('useTestApp: the app is only available inside tests and hooks')\n return created\n }\n return {\n get app() {\n return ready().app\n },\n get container() {\n return ready().container\n },\n client(clientOptions) {\n return ready().client(clientOptions ?? settings.client)\n },\n }\n}\n"],"mappings":";;;;;;;;;;yHA+CA,MAAM,WAAa,IAAI,IACvB,IAAI,mBAAqB,GAEzB,SAAgB,WACd,QACA,SAA8B,CAAC,EAChB,CACf,IAAI,QACE,MAAQ,SAAY,cAAc,MAAM,QAAQ,CAAC,EAEvD,UAAU,SAAY,CAEpB,GADI,SAAS,QAAU,IAAO,MAAM,eAAe,EAC/C,SAAS,OAAQ,CACnB,IAAM,KAAO,SAAS,SAAW,GAAO,UAAY,SAAS,OACzD,IAAM,WAAW,IAAI,IAAI,EACxB,MACH,IAAM,MAAM,EACZ,WAAW,IAAI,KAAM,GAAG,GAErB,qBACH,mBAAqB,GAIrB,QAAQ,KAAK,iBAAoB,CAC/B,IAAK,IAAM,UAAU,WAAW,OAAO,EAAG,OAAY,MAAM,CAAE,OAAU,IAAI,SAAS,CAAC,CACxF,CAAC,GAEH,QAAU,MAAM,GAClB,KACE,SAAU,MAAM,MAAM,CAE1B,CAAC,EAED,SAAS,SAAY,CACd,SAAS,QAAQ,MAAM,SAAS,IAAI,SAAS,EAClD,QAAU,IAAA,EACZ,CAAC,EAEG,SAAS,QAAU,QAAQ,eAAiB,eAAe,CAAC,EAEhE,IAAM,UAAuB,CAC3B,GAAI,CAAC,QAAS,MAAU,MAAM,8DAA8D,EAC5F,OAAO,OACT,EACA,MAAO,CACL,IAAI,KAAM,CACR,OAAO,MAAM,CAAC,CAAC,GACjB,EACA,IAAI,WAAY,CACd,OAAO,MAAM,CAAC,CAAC,SACjB,EACA,OAAO,cAAe,CACpB,OAAO,MAAM,CAAC,CAAC,OAAO,eAAiB,SAAS,MAAM,CACxD,CACF,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forinda/kickjs-testing",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.1.0",
|
|
4
4
|
"description": "Test utilities, TestModule builder, and helpers for KickJS applications",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kickjs",
|
|
@@ -22,27 +22,34 @@
|
|
|
22
22
|
".": {
|
|
23
23
|
"import": "./dist/index.mjs",
|
|
24
24
|
"types": "./dist/index.d.mts"
|
|
25
|
+
},
|
|
26
|
+
"./vitest": {
|
|
27
|
+
"import": "./dist/vitest.mjs",
|
|
28
|
+
"types": "./dist/vitest.d.mts"
|
|
25
29
|
}
|
|
26
30
|
},
|
|
27
31
|
"files": [
|
|
28
32
|
"dist"
|
|
29
33
|
],
|
|
30
|
-
"dependencies": {},
|
|
31
34
|
"peerDependencies": {
|
|
35
|
+
"@forinda/kickjs": ">=5.18.0",
|
|
32
36
|
"express": "^5.1.0",
|
|
33
|
-
"
|
|
37
|
+
"supertest": ">=7.0.0",
|
|
38
|
+
"vitest": ">=3.0.0"
|
|
34
39
|
},
|
|
35
40
|
"devDependencies": {
|
|
36
|
-
"@swc/core": "^1.16.
|
|
41
|
+
"@swc/core": "^1.16.2",
|
|
37
42
|
"@types/express": "^5.0.6",
|
|
38
|
-
"@types/
|
|
43
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
44
|
+
"@types/node": "^26.6.2",
|
|
39
45
|
"@types/supertest": "^7.2.1",
|
|
40
46
|
"express": "^5.1.0",
|
|
47
|
+
"jsonwebtoken": "^9.0.3",
|
|
41
48
|
"reflect-metadata": "^0.2.2",
|
|
42
|
-
"supertest": "^7.
|
|
49
|
+
"supertest": "^7.3.0",
|
|
43
50
|
"typescript": "^7.0.2",
|
|
44
|
-
"vitest": "^
|
|
45
|
-
"@forinda/kickjs": "
|
|
51
|
+
"vitest": "^5.0.1",
|
|
52
|
+
"@forinda/kickjs": "9.0.0"
|
|
46
53
|
},
|
|
47
54
|
"publishConfig": {
|
|
48
55
|
"access": "public"
|
|
@@ -61,7 +68,14 @@
|
|
|
61
68
|
"bugs": {
|
|
62
69
|
"url": "https://github.com/forinda/kick-js/issues"
|
|
63
70
|
},
|
|
64
|
-
"peerDependenciesMeta": {
|
|
71
|
+
"peerDependenciesMeta": {
|
|
72
|
+
"supertest": {
|
|
73
|
+
"optional": true
|
|
74
|
+
},
|
|
75
|
+
"vitest": {
|
|
76
|
+
"optional": true
|
|
77
|
+
}
|
|
78
|
+
},
|
|
65
79
|
"scripts": {
|
|
66
80
|
"build": "tsdown",
|
|
67
81
|
"dev": "tsdown --watch",
|
package/dist/index.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;KAyBK,8BAA8B,KACjC;;;;;UA0Be,6BAA6B;;;;;;;EAO5C,SAAS;;EAET,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6BX,YACI,+BACA,wBAAwB,gBAAgB,mBACxC;;;;;;EAMJ;;iBA6CoB,cAAc,SAAS,uBAAuB;EAClE,KAAK;;;;;;;;EAQL,YAAY,QAAQ;EACpB,WAAW;;;;;;;;;;;;;;;;;iBAqGG,iBAAiB;EAC/B,WAAW,WAAW;EACtB,cAAc,eAAe;IAC3B;;;;UAiBa;;;;;;;;;EASf,OAAO;;;;;;;EAQP,UAAU;;EAGV;;;;;UAMe,qBAAqB;;EAEpC,OAAO,UAAU;;EAEjB,KAAK;;;;;;EAML,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Bc,eACpB,UAAU,gBACV,UAAU,sBAAsB,uBAEhC,WAAW,iBAAiB,GAAG,IAC/B,UAAS,wBACR,QAAQ,qBAAqB;;;;UA+Bf;;;;;;EAMf;;;;;;EAOA;;;;;;;;UASe;;WAEN,QAAQ;;WAER,WAAW;;;;;EAMpB,eAAe;;;;;EAMf,YAAY;;;;;;;EAQZ,WAAW;;;;;EAMX,YAAY;;;;EAKZ;;;;;EAMA,gBAAgB;;;;;EAMhB,YAAY,UAAU,0BAA0B;;;;;;;EAQhD,gBAAgB,KAAK,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BpB,iBACpB,QAAQ,YACR,UAAS,0BACR,QAAQ;;cAoEE,mBAAU"}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import express from 'express'\nimport {\n Application,\n Container,\n buildPipeline,\n runContributors,\n type AppAdapter,\n type AppModule,\n type AppModuleClass,\n type AppModuleEntry,\n type ApplicationOptions,\n type ContextDecorator,\n type ContextMetaKey,\n type ContributorRegistration,\n type ExecutionContext,\n MissingContextValueError,\n type KickPlugin,\n type MetaValue,\n type ModuleRoutes,\n} from '@forinda/kickjs'\n\n/**\n * Bootstrap options forwarded verbatim to the underlying Application so\n * test apps exercise the same HTTP pipeline shape as production.\n */\ntype BootstrapPassthroughOptions = Pick<\n ApplicationOptions,\n | 'port'\n | 'apiPrefix'\n | 'defaultVersion'\n | 'middlewares'\n | 'onError'\n | 'onNotFound'\n | 'plugins'\n | 'trustProxy'\n | 'jsonLimit'\n | 'security'\n | 'contributors'\n | 'contextStore'\n // The engine under test. Without this every test ran Express while\n // production ran Fastify or h3 — the one thing an integration test exists\n // to rule out.\n | 'runtime'\n // Without this the option is accepted by the type and dropped on the way\n // through, so `health: false` silently kept the endpoints mounted.\n | 'health'\n>\n\n/**\n * Options for creating a test application.\n * Disables helmet, cors, compression, and morgan by default.\n */\nexport interface CreateTestAppOptions extends BootstrapPassthroughOptions {\n /**\n * Modules registered for the test run. Accepts both legacy class form\n * (`UserModule extends AppModule`) and `defineModule` factory output\n * (call the factory: `UserModule()`) — `Application` discriminates\n * at boot.\n */\n modules: AppModuleEntry[]\n /** Adapters to attach (auth, queue, devtools, etc.) */\n adapters?: AppAdapter[]\n /**\n * DI overrides applied after module registration.\n *\n * An object literal covers string and symbol keys. It cannot cover\n * `createToken()`, though — a token is a frozen OBJECT identified by\n * reference, and TypeScript rejects an object as a computed key\n * (`TS2464: A computed property name must be of type 'string', 'number',\n * 'symbol', or 'any'`). Since tokens are the documented way to bind an\n * interface to an implementation, that excluded exactly the key type most\n * worth overriding in a test.\n *\n * Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is\n * a string, and the container keys tokens by reference, so the override is\n * accepted and never applied.\n *\n * Pass entries to override a token:\n *\n * ```ts\n * const DATABASE = createToken<Database>('app/Db/connection')\n *\n * await createTestApp({\n * modules: [UserModule()],\n * overrides: [[DATABASE, fakeDb()]],\n * })\n * ```\n *\n * A `Map` works too. The object form is unchanged.\n */\n overrides?:\n | Record<symbol | string, any>\n | ReadonlyArray<readonly [token: unknown, value: unknown]>\n | ReadonlyMap<unknown, unknown>\n /**\n * Use an isolated container instead of the global singleton.\n * Prevents concurrent tests from interfering with each other's DI state.\n * When true, Container.create() is used instead of Container.reset() + getInstance().\n */\n isolated?: boolean\n}\n\n/**\n * Create an Application instance configured for testing.\n * Resets the DI container, registers modules, applies overrides,\n * and returns the Application, which drives whichever runtime is configured.\n *\n * Drive it through `app` — `app.handle` is the Application's own Node request\n * listener and follows whichever runtime is configured, so the same test runs\n * against the engine you actually deploy.\n *\n * @example\n * ```ts\n * const { app, container } = await createTestApp({\n * modules: [UserModule],\n * overrides: { [USER_REPO]: new InMemoryUserRepo() },\n * })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n *\n * @example Test the engine you actually deploy\n * ```ts\n * import { fastifyRuntime } from '@forinda/kickjs/fastify'\n *\n * const { app } = await createTestApp({ modules: [UserModule], runtime: fastifyRuntime() })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n */\n/**\n * Normalize every accepted `overrides` shape to `[token, value]` pairs.\n *\n * An array or Map keeps the token's identity, which is what the container\n * matches on; an object literal is limited to string and symbol keys by the\n * language itself.\n */\nfunction overrideEntries(\n overrides: NonNullable<CreateTestAppOptions['overrides']>,\n): Array<[unknown, unknown]> {\n if (Array.isArray(overrides)) return overrides.map(([token, value]) => [token, value])\n if (overrides instanceof Map) return [...overrides.entries()]\n const record = overrides as Record<symbol | string, unknown>\n return Reflect.ownKeys(record).map((key) => [key, record[key as never]])\n}\n\nexport async function createTestApp(options: CreateTestAppOptions): Promise<{\n app: Application\n /**\n * @deprecated Use `app.handle.bind(app)`. Only valid under the Express\n * runtime — under\n * any other engine this throws rather than handing back that engine's\n * instance mistyped as `express.Express`, which is how a suite ends up\n * silently exercising the wrong runtime.\n */\n expressApp: express.Express\n container: Container\n}> {\n let container: Container\n if (options.isolated) {\n // Isolated container — safe for concurrent tests\n container = Container.create()\n } else {\n // Global singleton — reset for serial test isolation (default)\n Container.reset()\n container = Container.getInstance()\n }\n\n const app = new Application({\n modules: options.modules,\n adapters: options.adapters,\n port: options.port,\n apiPrefix: options.apiPrefix,\n defaultVersion: options.defaultVersion,\n // Left undefined so the Application applies its OWN defaults, including\n // the shared body-parsing policy (#590). Naming a middleware list here\n // put the Application on its user-declared branch, so a test app parsed\n // only `application/json` while the same app in production also parsed\n // `+json`, forms and text — the harness quietly tested a different\n // pipeline. The Application already guards on\n // `RuntimeCapabilities.nativeBodyParsing`, which is what kept a connect\n // parser off Fastify and h3.\n middlewares: options.middlewares,\n onError: options.onError,\n onNotFound: options.onNotFound,\n plugins: options.plugins,\n trustProxy: options.trustProxy,\n jsonLimit: options.jsonLimit,\n security: options.security,\n contributors: options.contributors,\n contextStore: options.contextStore,\n // Without this the option is accepted and ignored, which is worse than\n // not offering it: the suite reports Express while claiming Fastify.\n runtime: options.runtime,\n health: options.health,\n })\n\n // Run setup — mounts routes, registers modules, initializes adapters.\n // Awaited to support future async adapter hooks.\n await Promise.resolve(app.setup())\n\n // When using an isolated container, Application.setup() registers modules\n // on the global singleton (Container.getInstance()). Re-register them on\n // the isolated container so that bindings are available there too.\n if (options.isolated) {\n for (const entry of options.modules) {\n // Discriminate class vs instance — `defineModule` factories return\n // AppModule instances, legacy classes need `new`. Same dispatch\n // Application.setup() runs at boot.\n const mod: AppModule = typeof entry === 'function' ? new (entry as AppModuleClass)() : entry\n // register() is optional — see AppModule docs\n mod.register?.(container)\n }\n container.bootstrap()\n }\n\n // Apply DI overrides AFTER setup so they take precedence over\n // bindings registered by modules during register().\n if (options.overrides) {\n for (const [token, value] of overrideEntries(options.overrides)) {\n container.registerInstance(token, value)\n }\n }\n\n const runtimeName = app.getActiveRuntime().name\n\n return {\n app,\n get expressApp(): express.Express {\n if (runtimeName !== 'express') {\n throw new Error(\n `createTestApp: 'expressApp' is only available under the Express runtime — ` +\n `this app is running '${runtimeName}'. Drive the app instead, which follows ` +\n `whichever engine is configured: request(app.handle.bind(app)).get('/...').`,\n )\n }\n return app.getExpressApp()\n },\n container,\n }\n}\n\n/**\n * Build a quick TestModule that explicitly registers dependencies.\n * Useful for integration tests that need to control the DI graph.\n *\n * @example\n * ```ts\n * const TestModule = createTestModule({\n * register: (c) => {\n * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())\n * c.register(UserController)\n * },\n * routes: () => buildRoutes(UserController, '/users'),\n * })\n * ```\n */\nexport function createTestModule(config: {\n register: (container: Container) => void\n routes: () => ModuleRoutes | ModuleRoutes[] | null\n}): AppModuleClass {\n class TestModule implements AppModule {\n register(container: Container) {\n config.register(container)\n }\n routes() {\n return config.routes()\n }\n }\n return TestModule\n}\n\n// ── Context Contributor unit-test helper (#107) ─────────────────────────\n\n/**\n * Options for {@link runContributor}.\n */\nexport interface RunContributorOptions {\n /**\n * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container\n * entirely — bypass for unit tests that want to assert pure resolve()\n * behaviour without standing up a container.\n *\n * Property names must match the spec's `deps` keys; values can be real\n * service instances, mocks, or test doubles.\n */\n deps?: Record<string, unknown>\n\n /**\n * Pre-populate the fake context's metadata Map. Useful for testing\n * contributors with `dependsOn` without running the full pipeline:\n * pre-populate the dependency keys, then assert that `resolve()` reads\n * them and produces the expected output.\n */\n initial?: Record<string, unknown>\n\n /** Override the fake context's `requestId` (default: `'test-req'`). */\n requestId?: string\n}\n\n/**\n * Result of {@link runContributor}.\n */\nexport interface RunContributorResult<K extends string> {\n /** Value returned by the contributor's `resolve()` call. */\n value: MetaValue<K>\n /** The fake `ExecutionContext` used during the run. */\n ctx: ExecutionContext\n /**\n * Final state of the fake context's metadata Map after `resolve()`.\n * Includes any `ctx.set(...)` calls the resolver made plus the final\n * resolved value under the contributor's own key.\n */\n meta: Map<string, unknown>\n}\n\n/**\n * Run a single context contributor in isolation against a fake\n * {@link ExecutionContext}. Skips the container, the topo-sort, and the\n * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`\n * directly so unit tests can assert pure resolve behaviour.\n *\n * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`\n * or `await expect(...).rejects.toThrow()` against them. To exercise the\n * full error matrix (optional skip, onError replacement, etc.), build a\n * one-element pipeline with `buildPipeline()` and use `runContributors()`\n * directly.\n *\n * @example\n * ```ts\n * const LoadProject = defineContextDecorator({\n * key: 'project',\n * dependsOn: ['tenant'],\n * deps: { repo: ProjectRepo },\n * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),\n * })\n *\n * const { value } = await runContributor(LoadProject, {\n * initial: { tenant: { id: 't-1' } },\n * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },\n * })\n * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })\n * ```\n */\nexport async function runContributor<\n K extends ContextMetaKey,\n D extends Record<string, any> = Record<string, never>,\n>(\n decorator: ContextDecorator<K, D>,\n options: RunContributorOptions = {},\n): Promise<RunContributorResult<K>> {\n const meta = new Map<string, unknown>(Object.entries(options.initial ?? {}))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n // Same contract as RequestContext.require — a resolver under test\n // that depends on an upstream key should fail here exactly the way\n // it would in production, not read `undefined`.\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: options.requestId ?? 'test-req',\n }\n\n const value = await decorator.registration.resolve(ctx, (options.deps ?? {}) as never)\n meta.set(decorator.registration.key, value)\n\n return { value: value as MetaValue<K>, ctx, meta }\n}\n\n// ── Plugin unit-test harness (architecture.md §21.3.2) ──────────────────\n\n/**\n * Options for {@link createTestPlugin}.\n */\nexport interface CreateTestPluginOptions {\n /**\n * Use an isolated container (default: `true`). Isolated harnesses never\n * touch the global `Container.getInstance()` singleton, so concurrent\n * tests can run without stomping each other's DI state.\n */\n isolated?: boolean\n\n /**\n * Skip auto-invoking `plugin.register(container)` — useful when a test\n * wants to assert container state *before* the plugin touches it.\n * Defaults to `false` (register is called eagerly).\n */\n skipRegister?: boolean\n}\n\n/**\n * Result of {@link createTestPlugin}. Mirrors the spec sketch in\n * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a\n * `runContributors()` helper that builds a one-plugin pipeline against a\n * fake `ExecutionContext`.\n */\nexport interface PluginTestHarness {\n /** The plugin under test — exposed for direct introspection. */\n readonly plugin: KickPlugin\n /** Isolated (or shared) DI container the plugin registered into. */\n readonly container: Container\n\n /**\n * Invoke `plugin.onReady(container)`. No-op if the plugin does not\n * define the hook.\n */\n callOnReady(): Promise<void>\n\n /**\n * Invoke `plugin.shutdown()`. No-op if the plugin does not define the\n * hook.\n */\n shutdown(): Promise<void>\n\n /**\n * Returns the module classes the plugin ships via `plugin.modules?()`.\n * The harness does **not** auto-instantiate them — use `createTestApp`\n * for that. Useful for assertions like \"the plugin exposes the module I\n * expect\".\n */\n modules(): AppModuleEntry[]\n\n /**\n * Returns adapter instances the plugin ships via `plugin.adapters?()`.\n * Useful for testing the adapters alongside the plugin's DI bindings.\n */\n adapters(): AppAdapter[]\n\n /**\n * Returns middleware entries the plugin ships via `plugin.middleware?()`.\n */\n middleware(): any[]\n\n /**\n * Returns contributor registrations the plugin ships via\n * `plugin.contributors?()`.\n */\n contributors(): ContributorRegistration[]\n\n /**\n * Build a fake {@link ExecutionContext} pre-populated with the given\n * metadata. Symmetric with {@link runContributor}'s fake context.\n */\n makeContext(initial?: Record<string, unknown>): ExecutionContext\n\n /**\n * Run every contributor the plugin ships through a built pipeline\n * against the given context. Dependencies resolve through the harness's\n * container (same path production uses). Throws if the plugin's\n * contributors reference `dependsOn` keys no one in the plugin provides.\n */\n runContributors(ctx: ExecutionContext): Promise<void>\n}\n\n/**\n * Build an isolated test harness around a single {@link KickPlugin}.\n * Skips the full HTTP layer — symmetric with {@link runContributor} for\n * contributors and {@link createTestApp} for integration runs.\n *\n * @example\n * ```ts\n * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))\n *\n * // The plugin's register() already ran — resolve any bindings.\n * const flags = harness.container.resolve(FLAGS_SERVICE)\n *\n * // Drive the post-bootstrap lifecycle.\n * await harness.callOnReady()\n *\n * // Exercise contributors shipped by the plugin.\n * const ctx = harness.makeContext({ requestId: 'req-1' })\n * await harness.runContributors(ctx)\n * expect(ctx.get('flags')).toEqual({ beta: true })\n *\n * await harness.shutdown()\n * ```\n */\nexport async function createTestPlugin(\n plugin: KickPlugin,\n options: CreateTestPluginOptions = {},\n): Promise<PluginTestHarness> {\n const isolated = options.isolated ?? true\n\n const container = isolated ? Container.create() : (Container.reset(), Container.getInstance())\n\n if (!options.skipRegister) plugin.register?.(container)\n\n return {\n plugin,\n container,\n\n async callOnReady() {\n await plugin.onReady?.(container)\n },\n\n async shutdown() {\n await plugin.shutdown?.()\n },\n\n modules() {\n return plugin.modules?.() ?? []\n },\n\n adapters() {\n return plugin.adapters?.() ?? []\n },\n\n middleware() {\n return plugin.middleware?.() ?? []\n },\n\n contributors() {\n return [...(plugin.contributors?.() ?? [])]\n },\n\n makeContext(initial: Record<string, unknown> = {}) {\n const meta = new Map<string, unknown>(Object.entries(initial))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: 'test-req',\n }\n return ctx\n },\n\n async runContributors(ctx: ExecutionContext) {\n const regs = plugin.contributors?.() ?? []\n const sources = [...regs].map((registration) => ({\n registration,\n source: 'adapter' as const,\n label: plugin.name,\n }))\n const pipeline = buildPipeline(sources)\n await runContributors({ pipeline, ctx, container })\n },\n }\n}\n\n/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */\nexport const testPlugin = createTestPlugin\n"],"mappings":";;;;;;;;;;0GAuIA,SAAS,gBACP,UAC2B,CAC3B,GAAI,MAAM,QAAQ,SAAS,EAAG,OAAO,UAAU,KAAK,CAAC,MAAO,SAAW,CAAC,MAAO,KAAK,CAAC,EACrF,GAAI,qBAAqB,IAAK,MAAO,CAAC,GAAG,UAAU,QAAQ,CAAC,EAC5D,IAAM,OAAS,UACf,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,IAAK,KAAQ,CAAC,IAAK,OAAO,I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