@warlock.js/core 4.12.0 → 4.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +214 -0
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/add.command.mjs +1 -1
- package/esm/cli/commands/add.command.mjs.map +1 -1
- package/esm/cli/commands/build.command.mjs +1 -1
- package/esm/cli/commands/build.command.mjs.map +1 -1
- package/esm/cli/commands/create-database.command.mjs +1 -1
- package/esm/cli/commands/create-database.command.mjs.map +1 -1
- package/esm/cli/commands/dev-server.command.mjs +1 -1
- package/esm/cli/commands/dev-server.command.mjs.map +1 -1
- package/esm/cli/commands/doctor/doctor-command.action.mjs.map +1 -1
- package/esm/cli/commands/doctor.command.mjs +1 -1
- package/esm/cli/commands/doctor.command.mjs.map +1 -1
- package/esm/cli/commands/drop-tables.command.mjs +1 -1
- package/esm/cli/commands/drop-tables.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generate.command.mjs +1 -1
- package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/module.generator.mjs +1 -1
- package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/path-resolver.mjs +1 -1
- package/esm/cli/commands/generate/utils/writer.mjs +1 -1
- package/esm/cli/commands/migrate.command.mjs +1 -1
- package/esm/cli/commands/migrate.command.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
- package/esm/cli/commands/routes.command.mjs +1 -1
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/commands/seed.command.mjs +1 -1
- package/esm/cli/commands/seed.command.mjs.map +1 -1
- package/esm/cli/commands/start-production.command.mjs +1 -1
- package/esm/cli/commands/start-production.command.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/storage-put.command.mjs +1 -1
- package/esm/cli/commands/storage-put.command.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs +2 -2
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/cli/commands/update.command.mjs +1 -1
- package/esm/cli/commands/update.command.mjs.map +1 -1
- package/esm/cli/commands-loader.mjs +1 -1
- package/esm/cli/commands-loader.mjs.map +1 -1
- package/esm/{cli → commands}/cli-command.d.mts +1 -1
- package/esm/commands/cli-command.d.mts.map +1 -0
- package/esm/{cli → commands}/cli-command.mjs +1 -1
- package/esm/commands/cli-command.mjs.map +1 -0
- package/esm/{cli → commands}/types.d.mts +1 -1
- package/esm/commands/types.d.mts.map +1 -0
- package/esm/config/load-config-files.mjs +1 -1
- package/esm/config/load-config-files.mjs.map +1 -1
- package/esm/connectors/base-connector.mjs +1 -1
- package/esm/connectors/base-connector.mjs.map +1 -1
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs +5 -3
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +0 -2
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/database/create-database-action.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs +1 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs +1 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs +1 -1
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +2 -2
- package/esm/dev-server/file-event-handler.mjs +1 -1
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/file-manager.mjs +1 -1
- package/esm/dev-server/file-manager.mjs.map +1 -1
- package/esm/dev-server/file-operations.mjs +1 -1
- package/esm/dev-server/file-operations.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +3 -18
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/files-watcher.mjs +1 -1
- package/esm/dev-server/files-watcher.mjs.map +1 -1
- package/esm/dev-server/health-checker/file-health-checker.contract.d.mts +1 -1
- package/esm/dev-server/layer-executor.mjs +1 -1
- package/esm/dev-server/loader/register-loader.mjs +1 -1
- package/esm/dev-server/package-json-manager.mjs +1 -1
- package/esm/dev-server/package-json-manager.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs +2 -2
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/tsconfig-manager.mjs +1 -1
- package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs +1 -1
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/dev-server/utils.mjs +1 -1
- package/esm/dev-server/utils.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +20 -8
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/http/build-cors-options.mjs +32 -0
- package/esm/http/build-cors-options.mjs.map +1 -0
- package/esm/http/middleware/max-body-size.middleware.d.mts +13 -5
- package/esm/http/middleware/max-body-size.middleware.d.mts.map +1 -1
- package/esm/http/middleware/max-body-size.middleware.mjs +13 -5
- package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
- package/esm/http/plugins.d.mts.map +1 -1
- package/esm/http/plugins.mjs +2 -9
- package/esm/http/plugins.mjs.map +1 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs +3 -8
- package/esm/http/server.mjs.map +1 -1
- package/esm/index.d.mts +9 -17
- package/esm/index.mjs +4 -15
- package/esm/production/production-builder.mjs +51 -3
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/resolve-build-config.mjs +1 -1
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/router/router.d.mts +9 -0
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +58 -5
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts +24 -1
- package/esm/router/types.d.mts.map +1 -1
- package/esm/tests/index.d.mts +3 -2
- package/esm/tests/index.mjs +2 -3
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/start-http-development-server.mjs +38 -15
- package/esm/tests/start-http-development-server.mjs.map +1 -1
- package/esm/tests/test-connectors-selection.d.mts +14 -0
- package/esm/tests/test-connectors-selection.d.mts.map +1 -0
- package/esm/tests/test-connectors-selection.mjs +72 -0
- package/esm/tests/test-connectors-selection.mjs.map +1 -0
- package/esm/tests/test-helpers.d.mts.map +1 -1
- package/esm/tests/test-helpers.mjs +34 -13
- package/esm/tests/test-helpers.mjs.map +1 -1
- package/esm/tests/test-lifecycle-state.mjs +27 -0
- package/esm/tests/test-lifecycle-state.mjs.map +1 -0
- package/esm/tests/test-setup-timeout.mjs +53 -0
- package/esm/tests/test-setup-timeout.mjs.map +1 -0
- package/esm/tests/vitest-setup.d.mts +64 -8
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs +317 -11
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/utils/framework-vesion.mjs +1 -1
- package/esm/utils/index.d.mts +1 -0
- package/esm/utils/index.mjs +1 -0
- package/esm/utils/normalized-path.d.mts +55 -0
- package/esm/utils/normalized-path.d.mts.map +1 -0
- package/esm/{dev-server/path.mjs → utils/normalized-path.mjs} +15 -2
- package/esm/utils/normalized-path.mjs.map +1 -0
- package/esm/vite/index.d.mts +2 -0
- package/esm/vite/index.mjs +1 -1
- package/esm/vite/lower-stage3-decorators.d.mts +1 -1
- package/esm/vite/lower-stage3-decorators.mjs +1 -1
- package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
- package/esm/warlock-config/index.mjs +1 -1
- package/esm/warlock-config/types.d.mts +34 -1
- package/esm/warlock-config/types.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs +1 -2
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +78 -23
- package/llms.txt +3 -3
- package/package.json +24 -12
- package/skills/lower-stage3-decorators/SKILL.md +4 -2
- package/skills/run-app/SKILL.md +6 -0
- package/skills/test-http/SKILL.md +37 -12
- package/skills/test-service/SKILL.md +167 -24
- package/skills/use-middleware/SKILL.md +5 -1
- package/esm/cli/cli-command.d.mts.map +0 -1
- package/esm/cli/cli-command.mjs.map +0 -1
- package/esm/cli/types.d.mts.map +0 -1
- package/esm/dev-server/files-orchestrator.d.mts +0 -89
- package/esm/dev-server/files-orchestrator.d.mts.map +0 -1
- package/esm/dev-server/files-watcher.d.mts +0 -69
- package/esm/dev-server/files-watcher.d.mts.map +0 -1
- package/esm/dev-server/health-checker/checkers/base-health-checker.d.mts +0 -55
- package/esm/dev-server/health-checker/checkers/base-health-checker.d.mts.map +0 -1
- package/esm/dev-server/health-checker/checkers/eslint-health-checker.d.mts +0 -44
- package/esm/dev-server/health-checker/checkers/eslint-health-checker.d.mts.map +0 -1
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.d.mts +0 -60
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.d.mts.map +0 -1
- package/esm/dev-server/health-checker/files-healthcare.manager.d.mts +0 -119
- package/esm/dev-server/health-checker/files-healthcare.manager.d.mts.map +0 -1
- package/esm/dev-server/health-checker/index.mjs +0 -7
- package/esm/dev-server/module-loader.d.mts +0 -63
- package/esm/dev-server/module-loader.d.mts.map +0 -1
- package/esm/dev-server/path.mjs.map +0 -1
- package/esm/tests/test-server-port-channel.d.mts +0 -27
- package/esm/tests/test-server-port-channel.d.mts.map +0 -1
- /package/esm/{cli → commands}/index.d.mts +0 -0
package/esm/router/router.mjs
CHANGED
|
@@ -11,6 +11,35 @@ import fastifyStatic from "@fastify/static";
|
|
|
11
11
|
import concatRoute from "@mongez/concat-route";
|
|
12
12
|
|
|
13
13
|
//#region ../core/src/router/router.ts
|
|
14
|
+
/**
|
|
15
|
+
* The pre-handler phases the dev server forwards from a route's `serverOptions`.
|
|
16
|
+
*
|
|
17
|
+
* These are the admission-control phases and they share the `(request, reply)`
|
|
18
|
+
* signature. `preParsing` is deliberately absent — it must return the payload
|
|
19
|
+
* stream, so forwarding it generically would corrupt the body rather than
|
|
20
|
+
* guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at
|
|
21
|
+
* registration time and no hook can bound a body already being parsed.
|
|
22
|
+
*/
|
|
23
|
+
const FORWARDED_ROUTE_PHASES = [
|
|
24
|
+
"onRequest",
|
|
25
|
+
"preValidation",
|
|
26
|
+
"preHandler"
|
|
27
|
+
];
|
|
28
|
+
function toHookList(hook) {
|
|
29
|
+
if (!hook) return [];
|
|
30
|
+
return Array.isArray(hook) ? hook : [hook];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Run a matched route's hooks for one phase.
|
|
34
|
+
*
|
|
35
|
+
* Returning the reply is how an async Fastify hook signals that it has answered
|
|
36
|
+
* the request; the chain must stop there, so the value is propagated rather
|
|
37
|
+
* than discarded.
|
|
38
|
+
*/
|
|
39
|
+
async function runRouteHooks(route, phase, request, reply) {
|
|
40
|
+
const hooks = toHookList(route.serverOptions?.[phase]);
|
|
41
|
+
for (const hook of hooks) if (await hook(request, reply) === reply) return reply;
|
|
42
|
+
}
|
|
14
43
|
var Router = class Router {
|
|
15
44
|
/**
|
|
16
45
|
* Get router instance
|
|
@@ -21,6 +50,7 @@ var Router = class Router {
|
|
|
21
50
|
}
|
|
22
51
|
constructor() {
|
|
23
52
|
this.routes = [];
|
|
53
|
+
this.routesVersion = 0;
|
|
24
54
|
this.staticDirectories = [];
|
|
25
55
|
this.eventListeners = {};
|
|
26
56
|
this.stacks = {
|
|
@@ -145,6 +175,7 @@ var Router = class Router {
|
|
|
145
175
|
else routeData.name += `.${routeData.method.toLowerCase()}`;
|
|
146
176
|
}
|
|
147
177
|
this.routes.push(routeData);
|
|
178
|
+
this.routesVersion++;
|
|
148
179
|
return this;
|
|
149
180
|
}
|
|
150
181
|
/**
|
|
@@ -351,6 +382,7 @@ var Router = class Router {
|
|
|
351
382
|
*/
|
|
352
383
|
removeRoutesBySourceFile(sourceFile) {
|
|
353
384
|
this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);
|
|
385
|
+
this.routesVersion++;
|
|
354
386
|
}
|
|
355
387
|
/**
|
|
356
388
|
* Manage validation system for the given resource
|
|
@@ -438,21 +470,42 @@ var Router = class Router {
|
|
|
438
470
|
*/
|
|
439
471
|
scanDevServer(server) {
|
|
440
472
|
this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));
|
|
441
|
-
|
|
442
|
-
|
|
473
|
+
let routeRegistry;
|
|
474
|
+
let registryVersion = -1;
|
|
475
|
+
const resolveRouteRegistry = () => {
|
|
476
|
+
if (routeRegistry && registryVersion === this.routesVersion) return routeRegistry;
|
|
477
|
+
routeRegistry = new RouteRegistry();
|
|
443
478
|
routeRegistry.register(this.routes);
|
|
444
|
-
|
|
479
|
+
registryVersion = this.routesVersion;
|
|
480
|
+
return routeRegistry;
|
|
481
|
+
};
|
|
482
|
+
server.addHook("onRequest", async (fastifyRequest, fastifyReply) => {
|
|
483
|
+
const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);
|
|
484
|
+
if (!match) return;
|
|
485
|
+
fastifyRequest.matchedDevRoute = match;
|
|
486
|
+
fastifyRequest.params = match.params;
|
|
487
|
+
return runRouteHooks(match.route, "onRequest", fastifyRequest, fastifyReply);
|
|
488
|
+
});
|
|
489
|
+
for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== "onRequest")) server.addHook(phase, async (fastifyRequest, fastifyReply) => {
|
|
490
|
+
const match = fastifyRequest.matchedDevRoute;
|
|
491
|
+
if (!match) return;
|
|
492
|
+
return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);
|
|
493
|
+
});
|
|
494
|
+
const wildcardHandler = async (fastifyRequest, fastifyReply) => {
|
|
495
|
+
const match = fastifyRequest.matchedDevRoute;
|
|
445
496
|
if (!match) return fastifyReply.code(404).send({
|
|
446
497
|
error: "Route not found",
|
|
447
498
|
path: fastifyRequest.url,
|
|
448
499
|
method: fastifyRequest.method
|
|
449
500
|
});
|
|
450
|
-
fastifyRequest.params = match.params;
|
|
451
501
|
try {
|
|
452
502
|
const { output, response } = await this.handleRoute(match.route)(fastifyRequest, fastifyReply);
|
|
453
503
|
return output || response.baseResponse;
|
|
454
504
|
} catch (error) {
|
|
455
|
-
|
|
505
|
+
log.error("router", "dev-dispatch", error, {
|
|
506
|
+
method: fastifyRequest.method,
|
|
507
|
+
url: fastifyRequest.url
|
|
508
|
+
});
|
|
456
509
|
throw error;
|
|
457
510
|
}
|
|
458
511
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../core/src/router/router.ts"],"sourcesContent":["import proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport fastifyStatic, { type FastifyStaticOptions } from \"@fastify/static\";\nimport concatRoute from \"@mongez/concat-route\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { Request } from \"../http/request\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { RouteRegistry } from \"./route-registry\";\nimport type {\n GroupedRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n} from \"./types\";\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: FastifyStaticOptions[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, (_request, response) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Server static folder\n */\n public directory(options: FastifyStaticOptions) {\n this.staticDirectories.push(options);\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n\n /**\n * Serve list of files\n */\n public files(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return concatRoute(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n path = concatRoute(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new Error(\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n if (routeData.name) {\n // check if the name exists\n const route = this.routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new Error(`Route name \"${routeData.name}\" already exists`);\n } else {\n routeData.name += `.${routeData.method.toLowerCase()}`;\n }\n }\n }\n\n this.routes.push(routeData);\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n return this.prefix(path, () => {\n path = \"\";\n // get base resource name\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n const resourceName = baseResourceName + \".list\";\n this.get(path, options.replace?.list || routeResource.list.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n const resourceName = baseResourceName + \".single\";\n\n this.get(path + \"/:id\", options.replace?.get || routeResource.get.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const resourceName = baseResourceName + \".create\";\n\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const resourceName = baseResourceName + \".update\";\n\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const resourceName = baseResourceName + \".patch\";\n\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".delete\";\n\n this.delete(\n path + \"/:id\",\n options.replace?.delete || routeResource.delete.bind(routeResource),\n {\n ...options,\n name: resourceName,\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".bulkDelete\";\n\n this.delete(\n path,\n options.replace?.bulkDelete || routeResource.bulkDelete.bind(routeResource),\n {\n ...options,\n name: resourceName,\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n } = options;\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = resource[method]?.bind(resource) as RequestHandler;\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async (request: Request, response: Response) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, request, response);\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, request, response);\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n config: {\n ...route.serverOptions?.config,\n ...(route.rateLimit && { rateLimit: route.rateLimit }),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Initialize route registry once (will be rebuilt on HMR via rebuildRouteRegistry)\n const routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n // Find matching route using find-my-way\n const match = routeRegistry.find(fastifyRequest.method, fastifyRequest.url);\n\n // No match found - return 404\n if (!match) {\n return fastifyReply.code(404).send({\n error: \"Route not found\",\n path: fastifyRequest.url,\n method: fastifyRequest.method,\n });\n }\n\n // Inject extracted params into the request\n fastifyRequest.params = match.params;\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n console.log(error);\n throw error;\n }\n };\n\n // Register wildcard route for all methods EXCEPT OPTIONS (to avoid conflict with CORS)\n // OPTIONS is handled by @fastify/cors plugin for preflight requests\n const methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"] as const;\n for (const method of methods) {\n server.route({\n method,\n url: \"*\",\n handler: wildcardHandler,\n });\n }\n\n // Register static directories\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: any = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new Error(`Route name \"${name}\" not found`);\n }\n\n let path = route.path;\n\n if (route.path.includes(\":\")) {\n Object.keys(params).forEach((key) => {\n path = path.replace(\":\" + key, params[key]);\n });\n }\n\n return path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n log.info({\n module: \"route\",\n action: route.method + \" \" + route.path.replace(\"/*\", \"\"),\n message: `Starting Request: ${request.id}`,\n context: {\n request,\n response,\n },\n });\n\n const result = await request.execute();\n\n return {\n output: result,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;AA0BA,IAAa,SAAb,MAAa,OAAO;;;;CAmClB,OAAc,cAAc;EAC1B,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,OAAO,OAAO;CAChB;CAEA,AAAQ,cAAc;gBAvCI,CAAC;2BAU2B,CAAC;wBAMrD,CAAC;gBAM8B;GAC/B,QAAQ,CAAC;GACT,MAAM,CAAC;GACP,YAAY,CAAC;EACf;CAeA;;;;CAKA,AAAO,eAAe,UAA6D;EACjF,KAAK,eAAe,aAAa,CAAC,GAAI,KAAK,eAAe,cAAc,CAAC,GAAI,QAAQ;EAErF,OAAO;CACT;;;;CAKA,AAAO,cAAc,UAA6D;EAChF,KAAK,eAAe,gBAAgB,CAAC,GAAI,KAAK,eAAe,iBAAiB,CAAC,GAAI,QAAQ;EAE3F,OAAO;CACT;;;;CAKA,AAAO,SAAS,MAAc,IAAY,eAA0C,aAAa;EAC/F,OAAO,KAAK,IAAI,OAAO,UAAU,aAAa;GAC5C,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AKA,AAAQ,YAAY,OAAc;EAChC,OAAO,OAAO,gBAAgC,oBAAkC;GAC9E,MAAM,UAAU,IAAI,QAAQ;GAC5B,MAAM,WAAW,IAAI,SAAS;GAC9B,SAAS,YAAY,eAAe;GACpC,QAAQ,WAAW;GAEnB,SAAS,UAAU;GAEnB,QAAQ,WAAW,cAAc,CAAC,CAAC,SAAS,KAAK;GAEjD,IAAI,KAAK;IACP,QAAQ;IACR,QAAQ,MAAM,SAAS,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE;IACxD,SAAS,qBAAqB,QAAQ;IACtC,SAAS;KACP;KACA;IACF;GACF,CAAC;GAID,OAAO;IACL,QAAQ,MAHW,QAAQ,QAAQ;IAInC;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
|
|
1
|
+
{"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../core/src/router/router.ts"],"sourcesContent":["import proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport fastifyStatic, { type FastifyStaticOptions } from \"@fastify/static\";\nimport concatRoute from \"@mongez/concat-route\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { Request } from \"../http/request\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { RouteRegistry } from \"./route-registry\";\nimport type {\n GroupedRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: FastifyStaticOptions[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, (_request, response) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Server static folder\n */\n public directory(options: FastifyStaticOptions) {\n this.staticDirectories.push(options);\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n\n /**\n * Serve list of files\n */\n public files(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return concatRoute(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n path = concatRoute(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new Error(\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n if (routeData.name) {\n // check if the name exists\n const route = this.routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new Error(`Route name \"${routeData.name}\" already exists`);\n } else {\n routeData.name += `.${routeData.method.toLowerCase()}`;\n }\n }\n }\n\n this.routes.push(routeData);\n\n this.routesVersion++;\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n return this.prefix(path, () => {\n path = \"\";\n // get base resource name\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n const resourceName = baseResourceName + \".list\";\n this.get(path, options.replace?.list || routeResource.list.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n const resourceName = baseResourceName + \".single\";\n\n this.get(path + \"/:id\", options.replace?.get || routeResource.get.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const resourceName = baseResourceName + \".create\";\n\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const resourceName = baseResourceName + \".update\";\n\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const resourceName = baseResourceName + \".patch\";\n\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".delete\";\n\n this.delete(\n path + \"/:id\",\n options.replace?.delete || routeResource.delete.bind(routeResource),\n {\n ...options,\n name: resourceName,\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".bulkDelete\";\n\n this.delete(\n path,\n options.replace?.bulkDelete || routeResource.bulkDelete.bind(routeResource),\n {\n ...options,\n name: resourceName,\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n } = options;\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = resource[method]?.bind(resource) as RequestHandler;\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async (request: Request, response: Response) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, request, response);\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, request, response);\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n config: {\n ...route.serverOptions?.config,\n ...(route.rateLimit && { rateLimit: route.rateLimit }),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply.code(404).send({\n error: \"Route not found\",\n path: fastifyRequest.url,\n method: fastifyRequest.method,\n });\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n });\n\n throw error;\n }\n };\n\n // Register wildcard route for all methods EXCEPT OPTIONS (to avoid conflict with CORS)\n // OPTIONS is handled by @fastify/cors plugin for preflight requests\n const methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"] as const;\n for (const method of methods) {\n server.route({\n method,\n url: \"*\",\n handler: wildcardHandler,\n });\n }\n\n // Register static directories\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: any = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new Error(`Route name \"${name}\" not found`);\n }\n\n let path = route.path;\n\n if (route.path.includes(\":\")) {\n Object.keys(params).forEach((key) => {\n path = path.replace(\":\" + key, params[key]);\n });\n }\n\n return path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n log.info({\n module: \"route\",\n action: route.method + \" \" + route.path.replace(\"/*\", \"\"),\n message: `Starting Request: ${request.id}`,\n context: {\n request,\n response,\n },\n });\n\n const result = await request.execute();\n\n return {\n output: result,\n response,\n request,\n };\n };\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;GACH,eAAe;EACjB,CAAC;EAGH,KAAK,eAAe,eAAe,SAAS,aAAa,SAAS,MAAM,MAAM,CAAC;CACjF;;;;CAKA,AAAO,SAAS,MAAc,SAAc,CAAC,GAAG;EAC9C,MAAM,QAAQ,KAAK,OAAO,MAAM,UAAU,MAAM,SAAS,IAAI;EAE7D,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,eAAe,KAAK,YAAY;EAGlD,IAAI,OAAO,MAAM;EAEjB,IAAI,MAAM,KAAK,SAAS,GAAG,GACzB,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,QAAQ;GACnC,OAAO,KAAK,QAAQ,MAAM,KAAK,OAAO,IAAI;EAC5C,CAAC;EAGH,OAAO;CACT;;;;CAKA,AAAQ,YAAY,OAAc;EAChC,OAAO,OAAO,gBAAgC,oBAAkC;GAC9E,MAAM,UAAU,IAAI,QAAQ;GAC5B,MAAM,WAAW,IAAI,SAAS;GAC9B,SAAS,YAAY,eAAe;GACpC,QAAQ,WAAW;GAEnB,SAAS,UAAU;GAEnB,QAAQ,WAAW,cAAc,CAAC,CAAC,SAAS,KAAK;GAEjD,IAAI,KAAK;IACP,QAAQ;IACR,QAAQ,MAAM,SAAS,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE;IACxD,SAAS,qBAAqB,QAAQ;IACtC,SAAS;KACP;KACA;IACF;GACF,CAAC;GAID,OAAO;IACL,QAAQ,MAHW,QAAQ,QAAQ;IAInC;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
|
package/esm/router/types.d.mts
CHANGED
|
@@ -101,7 +101,30 @@ interface RouteOptions {
|
|
|
101
101
|
*/
|
|
102
102
|
description?: string;
|
|
103
103
|
/**
|
|
104
|
-
*
|
|
104
|
+
* Fastify route options, forwarded to the route's registration.
|
|
105
|
+
*
|
|
106
|
+
* **Dev server caveat.** The dev server registers wildcard routes and
|
|
107
|
+
* dispatches per request, so it has no per-route registration slot. It
|
|
108
|
+
* forwards the pre-handler hook phases — `onRequest`, `preValidation` and
|
|
109
|
+
* `preHandler` — by matching in Fastify's own `onRequest` phase and running
|
|
110
|
+
* the matched route's hooks there, which keeps `onRequest` running before the
|
|
111
|
+
* body is parsed, as it does in production.
|
|
112
|
+
*
|
|
113
|
+
* **Two things are NOT forwarded in dev, and cannot be:**
|
|
114
|
+
* - `bodyLimit` — Fastify reads it at registration time; no hook can bound a
|
|
115
|
+
* body that is already being parsed.
|
|
116
|
+
* - `preParsing` — it must return the payload stream, so forwarding it
|
|
117
|
+
* generically would corrupt the body rather than guard it.
|
|
118
|
+
*
|
|
119
|
+
* A route that relies on either of those behaves differently in dev than in
|
|
120
|
+
* production. For a pre-parse guarantee that holds in both modes, register a
|
|
121
|
+
* server-level hook through `router.beforeScanning((_router, server) =>
|
|
122
|
+
* server.addHook("onRequest", ...))` — it lands on the Fastify instance
|
|
123
|
+
* rather than in per-route options. That hook fires for **every** request, so
|
|
124
|
+
* it must discriminate on `request.method` and `request.url` itself, and it
|
|
125
|
+
* must be **idempotent per request**: `beforeScanning` runs once per scan and
|
|
126
|
+
* restarting the HTTP connector builds a new server, so the callback can run
|
|
127
|
+
* more than once against different instances.
|
|
105
128
|
*/
|
|
106
129
|
serverOptions?: RouteShorthandOptions;
|
|
107
130
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/router/types.ts"],"mappings":";;;;;;;;;;;;KASY,kBAAA,GAAqB,gBAAgB;;AAAjD;;;;KAOY,UAAA,2BAAqC,OAAA,GAAU,OAAA;EAAA,CACxD,OAAA,EAAS,iBAAA,EAAmB,QAAA,EAAU,QAAA,GAAW,kBAAA;AAAA;AAAA,KAGxC,mBAAA;AAAA,KAEA,kBAAA,GAAqB,cAAA,SAAuB,aAAa;;;;KAKzD,cAAA;AAAA,KAEA,iBAAA,GAAoB,MAAM,UAAU,UAAA;AAAA,KAEpC,w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AA,GAAY,YAAA;AAAA;AAAA,KAGF,WAAA,oBAA+B,CAAA,IAAK,IAAA,CAAK,CAAA,EAAG,CAAA,IAAK,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,CAAA;;;;KAKjE,oBAAA;EALkE;AAAA;AAK9E;EAIE,UAAA,GAAa,UAAU;;;;EAIvB,MAAA;EAAA;;;AAKI;EAAJ,IAAA;AAAA;;KAIU,aAAA;EAQJ;;;EAJN,IAAA,GAAO,cAAA;EAoBE;;;EAhBT,GAAA,GAAM,cAAA;EAoCK;;;EAhCX,MAAA,GAAS,cAAA;EART;;;EAYA,MAAA,GAAS,cAAA;EAJT;;;EAQA,KAAA,GAAQ,cAAA;EAAR;;;EAIA,MAAA,GAAS,cAAA;EAIT;;;EAAA,UAAA,GAAa,cAAA;EAQL;;;EAJR,UAAA;IAYW;;;IART,GAAA,GAAM,wBAAA;IAY0B;AAIpC;;IAZI,MAAA,GAAS,wBAAA;IAeW;;;IAXpB,MAAA,GAAS,wBAAA;IAWC;;;IAPV,KAAA,GAAQ,wBAAA;EAAA;AAAA;AAAA,KAIA,YAAA;EACV,MAAA;EACA,IAAA;EACA,UAAA,EAAY,UAAU;;;;EAItB,UAAA;AAAA"}
|
package/esm/tests/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { StartHttpTestServerOptions, isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
|
|
2
2
|
import { expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import { setupTest } from "./vitest-setup.mjs";
|
|
3
|
+
import { TestConnectorsSelection } from "./test-connectors-selection.mjs";
|
|
4
|
+
import { TestLifecycleError, TestSetupOptions, setupTest, teardownTest } from "./vitest-setup.mjs";
|
|
5
|
+
export { StartHttpTestServerOptions, type TestConnectorsSelection, TestLifecycleError, TestSetupOptions, expectJson, getTestServerUrl, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest };
|
package/esm/tests/index.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { TEST_SERVER_PORT_ENV_KEY, publishTestServerPort, withdrawTestServerPort } from "./test-server-port-channel.mjs";
|
|
2
1
|
import { isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
|
|
3
2
|
import { expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
|
|
4
|
-
import { setupTest } from "./vitest-setup.mjs";
|
|
3
|
+
import { TestLifecycleError, setupTest, teardownTest } from "./vitest-setup.mjs";
|
|
5
4
|
|
|
6
|
-
export {
|
|
5
|
+
export { TestLifecycleError, expectJson, getTestServerUrl, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-http-development-server.d.mts","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"mappings":";KAwBY,0BAAA;EAAA;;;;AAON;
|
|
1
|
+
{"version":3,"file":"start-http-development-server.d.mts","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"mappings":";KAwBY,0BAAA;EAAA;;;;AAON;AA0EN;EA1EE,IAAI;AAAA;;;;;;AA4EI;AA+EV;;iBAjFsB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;;AA+EyC;AA6BnD;;iBA7BsB,kBAAA,IAAsB,OAAO;;AA6BhB;;iBAAnB,mBAAA"}
|
|
@@ -41,7 +41,8 @@ async function applyTestServerPort(port) {
|
|
|
41
41
|
}
|
|
42
42
|
if (port !== void 0) config.set("http.port", port);
|
|
43
43
|
const resolvedPort = config.get("http.port");
|
|
44
|
-
if (typeof resolvedPort !== "number"
|
|
44
|
+
if (typeof resolvedPort !== "number") return;
|
|
45
|
+
if (resolvedPort <= 0) throw new Error(`startHttpTestServer() cannot run on port ${resolvedPort}. Pass an explicit port — e.g. startHttpTestServer({ port: 3999 }) — or set \`http.port\` in your config. Test workers are separate processes that resolve the server's URL from the port published at startup, and an OS-assigned port is not knowable to them.`);
|
|
45
46
|
await assertPortIsAvailable(resolvedPort, config.get("http.host") || "localhost");
|
|
46
47
|
publishTestServerPort(resolvedPort);
|
|
47
48
|
}
|
|
@@ -59,18 +60,39 @@ async function startHttpTestServer(options = {}) {
|
|
|
59
60
|
return;
|
|
60
61
|
}
|
|
61
62
|
console.log("[test-server] Starting HTTP test server...");
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
63
|
+
try {
|
|
64
|
+
Application.setRuntimeStrategy("development");
|
|
65
|
+
Application.setEnvironment("test");
|
|
66
|
+
await warlockConfigManager.load();
|
|
67
|
+
await bootstrap();
|
|
68
|
+
await filesOrchestrator.init();
|
|
69
|
+
await filesOrchestrator.initializeAll();
|
|
70
|
+
await loadConfigFiles(true);
|
|
71
|
+
await connectorsManager.startPhase("early");
|
|
72
|
+
await filesOrchestrator.moduleLoader.loadAll();
|
|
73
|
+
await applyTestServerPort(options.port);
|
|
74
|
+
await connectorsManager.startPhase("late");
|
|
75
|
+
isServerRunning = true;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
await unwindPartialStartup();
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Best-effort teardown of whatever a failed {@link startHttpTestServer} managed
|
|
83
|
+
* to start.
|
|
84
|
+
*
|
|
85
|
+
* Every step is independent and none may throw: this runs while an error is
|
|
86
|
+
* already in flight, and the caller is about to rethrow it.
|
|
87
|
+
*/
|
|
88
|
+
async function unwindPartialStartup() {
|
|
89
|
+
try {
|
|
90
|
+
await connectorsManager.shutdown();
|
|
91
|
+
} catch (shutdownError) {
|
|
92
|
+
console.error("[test-server] Cleanup after a failed start did not complete:", shutdownError);
|
|
93
|
+
}
|
|
94
|
+
withdrawTestServerPort();
|
|
95
|
+
isServerRunning = false;
|
|
74
96
|
}
|
|
75
97
|
/**
|
|
76
98
|
* Stop the HTTP test server
|
|
@@ -83,12 +105,13 @@ async function stopHttpTestServer() {
|
|
|
83
105
|
}
|
|
84
106
|
try {
|
|
85
107
|
await connectorsManager.shutdown();
|
|
86
|
-
withdrawTestServerPort();
|
|
87
|
-
isServerRunning = false;
|
|
88
108
|
console.log("[test-server] HTTP test server stopped");
|
|
89
109
|
} catch (error) {
|
|
90
110
|
console.error("[test-server] Error stopping HTTP server:", error);
|
|
91
111
|
throw error;
|
|
112
|
+
} finally {
|
|
113
|
+
withdrawTestServerPort();
|
|
114
|
+
isServerRunning = false;
|
|
92
115
|
}
|
|
93
116
|
}
|
|
94
117
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-http-development-server.mjs","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"sourcesContent":["/**\r\n * HTTP Test Server\r\n *\r\n * Starts a minimal HTTP server for testing.\r\n * Unlike the full DevelopmentServer, this:\r\n * - Does NOT watch files\r\n * - Does NOT do HMR\r\n * - Only starts connectors needed for HTTP requests\r\n *\r\n * Used in Vitest's globalSetup to start server once for all test workers.\r\n */\r\nimport config from \"@mongez/config\";\r\nimport { Application } from \"../application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { assertPortIsAvailable } from \"../http/port-preflight\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { publishTestServerPort, withdrawTestServerPort } from \"./test-server-port-channel\";\r\n\r\nlet isServerRunning = false;\r\n\r\nexport type StartHttpTestServerOptions = {\r\n /**\r\n * Port the test server binds to, overriding `http.port`.\r\n *\r\n * Needed because the server cannot be moved from outside: this function\r\n * bootstraps the app itself, and that bootstrap re-reads `.env`.\r\n */\r\n port?: number;\r\n};\r\n\r\n/**\r\n * Apply the caller's port and preflight the bind.\r\n *\r\n * Called at the last moment before the HTTP connector binds, and that timing is\r\n * the fix: `bootstrap()` re-reads `.env` through `loadEnv()` (dotenv overrides\r\n * by default), and `src/config/http.ts` then resolves its port from that store,\r\n * so anything the caller set earlier is gone by the time the port is read.\r\n * Writing into `config` here is also the only channel that works — assigning\r\n * `process.env.HTTP_PORT` has no effect, since `env()` reads dotenv's own store\r\n * and never falls back to `process.env`.\r\n */\r\nasync function applyTestServerPort(port?: number): Promise<void> {\r\n const httpConfig = config.get(\"http\");\r\n\r\n if (!httpConfig) {\r\n if (port !== undefined) {\r\n throw new Error(\r\n `startHttpTestServer({ port: ${port} }) was given a port, but this app has no \\`http\\` config, so no HTTP server is started. Add \\`src/config/http.ts\\` first.`,\r\n );\r\n }\r\n\r\n return;\r\n }\r\n\r\n if (port !== undefined) {\r\n config.set(\"http.port\", port);\r\n }\r\n\r\n const resolvedPort = config.get(\"http.port\");\r\n\r\n // No configured port — or an explicit `0`, which is the OS's \"pick a free one\r\n // for me\" idiom — means Fastify chooses the port, so there is nothing to\r\n // preflight and nothing to publish: preflighting 0 would bind some unrelated\r\n // ephemeral port and pass without proving anything, and publishing 0 would\r\n // point every worker request at `http://host:0`.\r\n if (typeof resolvedPort !== \"number\" || resolvedPort <= 0) {\r\n return;\r\n }\r\n\r\n await assertPortIsAvailable(resolvedPort, config.get(\"http.host\") || \"localhost\");\r\n\r\n publishTestServerPort(resolvedPort);\r\n}\r\n\r\n/**\r\n * Start the HTTP test server (minimal - no file watching)\r\n * Call this in Vitest's globalSetup\r\n *\r\n * @example\r\n * // run this suite on its own port, whatever `.env` says\r\n * await startHttpTestServer({ port: 3999 });\r\n */\r\nexport async function startHttpTestServer(\r\n options: StartHttpTestServerOptions = {},\r\n): Promise<void> {\r\n if (isServerRunning) {\r\n console.log(\"[test-server] Server already running, skipping start\");\r\n return;\r\n }\r\n\r\n console.log(\"[test-server] Starting HTTP test server...\");\r\n\r\n // Set environment\r\n Application.setRuntimeStrategy(\"development\");\r\n Application.setEnvironment(\"test\");\r\n\r\n // Bootstrap (env, etc.)\r\n await warlockConfigManager.load();\r\n await bootstrap();\r\n\r\n // Initialize file orchestrator (but don't watch)\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n\r\n // Load config files\r\n await loadConfigFiles(true);\r\n\r\n // Early-phase connectors (database, cache, logger, storage, mailer,\r\n // herald) must start BEFORE app modules load: a module's `main.ts` boot\r\n // side-effect can query the DB at import time, so the data source has to\r\n // be registered first. This mirrors the dev/prod boot order (see\r\n // `cli-commands.manager`, `production-builder`, and `DevelopmentServer`).\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\r\n\r\n // Load application modules (their boot side-effects now see a live DB).\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n await applyTestServerPort(options.port);\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered its routes and listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n isServerRunning = true;\r\n}\r\n\r\n/**\r\n * Stop the HTTP test server\r\n * Call this in Vitest's globalTeardown\r\n */\r\nexport async function stopHttpTestServer(): Promise<void> {\r\n if (!isServerRunning) {\r\n console.log(\"[test-server] No server to stop\");\r\n return;\r\n }\r\n\r\n try {\r\n await connectorsManager.shutdown();\r\n withdrawTestServerPort();\r\n isServerRunning = false;\r\n console.log(\"[test-server] HTTP test server stopped\");\r\n } catch (error) {\r\n console.error(\"[test-server] Error stopping HTTP server:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Check if test server is running\r\n */\r\nexport function isTestServerRunning(): boolean {\r\n return isServerRunning;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAI,kBAAkB;;;;;;;;;;;;AAuBtB,eAAe,oBAAoB,MAA8B;CAG/D,IAAI,CAFe,OAAO,IAAI,MAEhB,GAAG;EACf,IAAI,SAAS,QACX,MAAM,IAAI,MACR,+BAA+B,KAAK,2HACtC;EAGF;CACF;CAEA,IAAI,SAAS,QACX,OAAO,IAAI,aAAa,IAAI;CAG9B,MAAM,eAAe,OAAO,IAAI,WAAW;CAO3C,IAAI,OAAO,iBAAiB,YAAY,gBAAgB,GACtD;CAGF,MAAM,sBAAsB,cAAc,OAAO,IAAI,WAAW,KAAK,WAAW;CAEhF,sBAAsB,YAAY;AACpC;;;;;;;;;AAUA,eAAsB,oBACpB,UAAsC,CAAC,GACxB;CACf,IAAI,iBAAiB;EACnB,QAAQ,IAAI,sDAAsD;EAClE;CACF;CAEA,QAAQ,IAAI,4CAA4C;CAGxD,YAAY,mBAAmB,aAAa;CAC5C,YAAY,eAAe,MAAM;CAGjC,MAAM,qBAAqB,KAAK;CAChC,MAAM,UAAU;CAGhB,MAAM,kBAAkB,KAAK;CAC7B,MAAM,kBAAkB,cAAc;CAGtC,MAAM,gBAAgB,IAAI;CAO1B,MAAM,kBAAkB,kBAAwC;CAGhE,MAAM,kBAAkB,aAAa,QAAQ;CAE7C,MAAM,oBAAoB,QAAQ,IAAI;CAItC,MAAM,kBAAkB,iBAAuC;CAE/D,kBAAkB;AACpB;;;;;AAMA,eAAsB,qBAAoC;CACxD,IAAI,CAAC,iBAAiB;EACpB,QAAQ,IAAI,iCAAiC;EAC7C;CACF;CAEA,IAAI;EACF,MAAM,kBAAkB,SAAS;EACjC,uBAAuB;EACvB,kBAAkB;EAClB,QAAQ,IAAI,wCAAwC;CACtD,SAAS,OAAO;EACd,QAAQ,MAAM,6CAA6C,KAAK;EAChE,MAAM;CACR;AACF;;;;AAKA,SAAgB,sBAA+B;CAC7C,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"start-http-development-server.mjs","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"sourcesContent":["/**\r\n * HTTP Test Server\r\n *\r\n * Starts a minimal HTTP server for testing.\r\n * Unlike the full DevelopmentServer, this:\r\n * - Does NOT watch files\r\n * - Does NOT do HMR\r\n * - Only starts connectors needed for HTTP requests\r\n *\r\n * Used in Vitest's globalSetup to start server once for all test workers.\r\n */\r\nimport config from \"@mongez/config\";\r\nimport { Application } from \"../application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { assertPortIsAvailable } from \"../http/port-preflight\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { publishTestServerPort, withdrawTestServerPort } from \"./test-server-port-channel\";\r\n\r\nlet isServerRunning = false;\r\n\r\nexport type StartHttpTestServerOptions = {\r\n /**\r\n * Port the test server binds to, overriding `http.port`.\r\n *\r\n * Needed because the server cannot be moved from outside: this function\r\n * bootstraps the app itself, and that bootstrap re-reads `.env`.\r\n */\r\n port?: number;\r\n};\r\n\r\n/**\r\n * Apply the caller's port and preflight the bind.\r\n *\r\n * Called at the last moment before the HTTP connector binds, and that timing is\r\n * the fix: `bootstrap()` re-reads `.env` through `loadEnv()` (dotenv overrides\r\n * by default), and `src/config/http.ts` then resolves its port from that store,\r\n * so anything the caller set earlier is gone by the time the port is read.\r\n * Writing into `config` here is also the only channel that works — assigning\r\n * `process.env.HTTP_PORT` has no effect, since `env()` reads dotenv's own store\r\n * and never falls back to `process.env`.\r\n */\r\nasync function applyTestServerPort(port?: number): Promise<void> {\r\n const httpConfig = config.get(\"http\");\r\n\r\n if (!httpConfig) {\r\n if (port !== undefined) {\r\n throw new Error(\r\n `startHttpTestServer({ port: ${port} }) was given a port, but this app has no \\`http\\` config, so no HTTP server is started. Add \\`src/config/http.ts\\` first.`,\r\n );\r\n }\r\n\r\n return;\r\n }\r\n\r\n if (port !== undefined) {\r\n config.set(\"http.port\", port);\r\n }\r\n\r\n const resolvedPort = config.get(\"http.port\");\r\n\r\n // No configured port at all is fine: Fastify falls back to its own default and\r\n // the workers resolve the same one from their own config, so both ends agree\r\n // without the channel.\r\n //\r\n // ⚠ A non-numeric port also lands here, and that is NOT fine — it is just not\r\n // this function's bug to fix. `env()` coerces a value only when it round-trips\r\n // exactly (`String(Number(v)) === v`), so `HTTP_PORT=3999` and `HTTP_PORT=0`\r\n // arrive as numbers, but `03999`, `+3999`, `1e3` and anything with stray\r\n // whitespace stay strings. Those skip the preflight and the publish here, and\r\n // reach `HttpConnector.start()`'s `listen({ port })` unchanged — a production\r\n // path, not a test one. Tracked separately rather than widened into this fix.\r\n if (typeof resolvedPort !== \"number\") {\r\n return;\r\n }\r\n\r\n // `0` is the OS's \"pick a free one for me\" idiom, and the test server cannot\r\n // support it. Preflighting 0 would bind some unrelated ephemeral port and pass\r\n // without proving anything, and there is nothing meaningful to publish: the\r\n // port Fastify ends up binding is never recorded — `HttpConnector.start()`\r\n // stores the port it ASKED for, not the one it got. Accepting 0 silently is\r\n // what left `getTestServerUrl()` resolving to `http://host:0` through its own\r\n // config fallback, so every worker request went to a port nothing listens on.\r\n if (resolvedPort <= 0) {\r\n throw new Error(\r\n `startHttpTestServer() cannot run on port ${resolvedPort}. Pass an explicit port — e.g. startHttpTestServer({ port: 3999 }) — or set \\`http.port\\` in your config. Test workers are separate processes that resolve the server's URL from the port published at startup, and an OS-assigned port is not knowable to them.`,\r\n );\r\n }\r\n\r\n await assertPortIsAvailable(resolvedPort, config.get(\"http.host\") || \"localhost\");\r\n\r\n publishTestServerPort(resolvedPort);\r\n}\r\n\r\n/**\r\n * Start the HTTP test server (minimal - no file watching)\r\n * Call this in Vitest's globalSetup\r\n *\r\n * @example\r\n * // run this suite on its own port, whatever `.env` says\r\n * await startHttpTestServer({ port: 3999 });\r\n */\r\nexport async function startHttpTestServer(\r\n options: StartHttpTestServerOptions = {},\r\n): Promise<void> {\r\n if (isServerRunning) {\r\n console.log(\"[test-server] Server already running, skipping start\");\r\n return;\r\n }\r\n\r\n console.log(\"[test-server] Starting HTTP test server...\");\r\n\r\n try {\r\n // Set environment\r\n Application.setRuntimeStrategy(\"development\");\r\n Application.setEnvironment(\"test\");\r\n\r\n // Bootstrap (env, etc.)\r\n await warlockConfigManager.load();\r\n await bootstrap();\r\n\r\n // Initialize file orchestrator (but don't watch)\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n\r\n // Load config files\r\n await loadConfigFiles(true);\r\n\r\n // Early-phase connectors (database, cache, logger, storage, mailer,\r\n // herald) must start BEFORE app modules load: a module's `main.ts` boot\r\n // side-effect can query the DB at import time, so the data source has to\r\n // be registered first. This mirrors the dev/prod boot order (see\r\n // `cli-commands.manager`, `production-builder`, and `DevelopmentServer`).\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\r\n\r\n // Load application modules (their boot side-effects now see a live DB).\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n await applyTestServerPort(options.port);\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered its routes and listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n isServerRunning = true;\r\n } catch (error) {\r\n // This function owns the connectors it starts, so a failure part-way\r\n // through has to leave nothing behind. Without this, `isServerRunning` was\r\n // still `false` — it is only set on the last line — so `globalTeardown`'s\r\n // `stopHttpTestServer()` reported \"No server to stop\" and walked away from\r\n // live early-phase connectors and a published port that outlived them.\r\n await unwindPartialStartup();\r\n\r\n // Rethrown unchanged: the startup failure is the one the caller needs to\r\n // read. A cleanup failure that replaced it would hide the actual cause.\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Best-effort teardown of whatever a failed {@link startHttpTestServer} managed\r\n * to start.\r\n *\r\n * Every step is independent and none may throw: this runs while an error is\r\n * already in flight, and the caller is about to rethrow it.\r\n */\r\nasync function unwindPartialStartup(): Promise<void> {\r\n try {\r\n await connectorsManager.shutdown();\r\n } catch (shutdownError) {\r\n // Reported, not thrown — it is secondary to the startup error being\r\n // rethrown, and losing that one to this would be the worse outcome.\r\n console.error(\"[test-server] Cleanup after a failed start did not complete:\", shutdownError);\r\n }\r\n\r\n withdrawTestServerPort();\r\n isServerRunning = false;\r\n}\r\n\r\n/**\r\n * Stop the HTTP test server\r\n * Call this in Vitest's globalTeardown\r\n */\r\nexport async function stopHttpTestServer(): Promise<void> {\r\n if (!isServerRunning) {\r\n console.log(\"[test-server] No server to stop\");\r\n return;\r\n }\r\n\r\n try {\r\n await connectorsManager.shutdown();\r\n\r\n console.log(\"[test-server] HTTP test server stopped\");\r\n } catch (error) {\r\n // Surfaced, never swallowed — cleaning up is not the same as the shutdown\r\n // having succeeded, and a suite whose teardown failed should say so.\r\n console.error(\"[test-server] Error stopping HTTP server:\", error);\r\n\r\n throw error;\r\n } finally {\r\n // In a `finally` rather than after the `await`: when `shutdown()` threw,\r\n // the published port survived the server it pointed at, so the next run in\r\n // the same process inherited a stale one and sent every request to it.\r\n withdrawTestServerPort();\r\n\r\n isServerRunning = false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if test server is running\r\n */\r\nexport function isTestServerRunning(): boolean {\r\n return isServerRunning;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAI,kBAAkB;;;;;;;;;;;;AAuBtB,eAAe,oBAAoB,MAA8B;CAG/D,IAAI,CAFe,OAAO,IAAI,MAEhB,GAAG;EACf,IAAI,SAAS,QACX,MAAM,IAAI,MACR,+BAA+B,KAAK,2HACtC;EAGF;CACF;CAEA,IAAI,SAAS,QACX,OAAO,IAAI,aAAa,IAAI;CAG9B,MAAM,eAAe,OAAO,I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@
|
|
|
1
|
+
import { ConnectorName } from "../connectors/types.mjs";
|
|
2
|
+
//#region ../core/src/tests/test-connectors-selection.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* What a test runtime was asked to start.
|
|
5
|
+
*
|
|
6
|
+
* - `false` — bootstrap the runtime, start no connectors.
|
|
7
|
+
* - `true` — start the framework's default connector set.
|
|
8
|
+
* - an array — start exactly those. Order is not promised; lifecycle priority
|
|
9
|
+
* decides the real boot/shutdown order.
|
|
10
|
+
*/
|
|
11
|
+
type TestConnectorsSelection = boolean | ConnectorName[];
|
|
12
|
+
//#endregion
|
|
13
|
+
export { TestConnectorsSelection };
|
|
14
|
+
//# sourceMappingURL=test-connectors-selection.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"test-connectors-selection.d.mts","names":[],"sources":["../../../../../../../core/src/tests/test-connectors-selection.ts"],"mappings":";;;;;AAqBA;;;;AAA6D;KAAjD,uBAAA,aAAoC,aAAa"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { config } from "../config/config-getter.mjs";
|
|
2
|
+
import "../config/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../core/src/tests/test-connectors-selection.ts
|
|
5
|
+
/**
|
|
6
|
+
* Classify the caller's `connectors` option as explicit or deferred.
|
|
7
|
+
*/
|
|
8
|
+
function readRequestedConnectors(selection) {
|
|
9
|
+
if (selection === void 0) return { isExplicit: false };
|
|
10
|
+
return {
|
|
11
|
+
isExplicit: true,
|
|
12
|
+
selection
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Read the `tests.connectors` config layer, or `undefined` when the project has
|
|
17
|
+
* not configured one.
|
|
18
|
+
*
|
|
19
|
+
* Only meaningful once config files are loaded — before that, every project
|
|
20
|
+
* looks like a project without a `tests` config.
|
|
21
|
+
*/
|
|
22
|
+
function readConfiguredConnectors() {
|
|
23
|
+
return config.get("tests", {})?.connectors;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Apply the ratified precedence:
|
|
27
|
+
*
|
|
28
|
+
* explicit non-`undefined` setupTest option > tests.connectors config > true
|
|
29
|
+
*
|
|
30
|
+
* ⚠ This is the reverse of 4.13, where config won over the parameter. Explicit
|
|
31
|
+
* call-site intent beats a project default; a call that supplied nothing is not
|
|
32
|
+
* intent, which is why "omitted" and "explicitly `undefined`" both defer.
|
|
33
|
+
*/
|
|
34
|
+
function resolveEffectiveConnectors(requested) {
|
|
35
|
+
if (requested.isExplicit) return requested.selection;
|
|
36
|
+
const configured = readConfiguredConnectors();
|
|
37
|
+
if (configured !== void 0) return configured;
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Deduplicate a connector list and put it in a stable order.
|
|
42
|
+
*
|
|
43
|
+
* Two callers naming the same connectors in a different order asked for the same
|
|
44
|
+
* thing, so the lifecycle must not treat them as a conflict.
|
|
45
|
+
*/
|
|
46
|
+
function normalizeConnectorNames(names) {
|
|
47
|
+
return [...new Set(names)].sort();
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Compare two selections by normalized semantics — arrays as deduplicated sets,
|
|
51
|
+
* never by caller order.
|
|
52
|
+
*/
|
|
53
|
+
function isSameConnectorsSelection(left, right) {
|
|
54
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
55
|
+
const normalizedLeft = normalizeConnectorNames(left);
|
|
56
|
+
const normalizedRight = normalizeConnectorNames(right);
|
|
57
|
+
return normalizedLeft.length === normalizedRight.length && normalizedLeft.every((name, index) => name === normalizedRight[index]);
|
|
58
|
+
}
|
|
59
|
+
return left === right;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Render a selection for an error message a caller can act on.
|
|
63
|
+
*/
|
|
64
|
+
function describeConnectorsSelection(selection) {
|
|
65
|
+
if (selection === true) return "the default connector set (`connectors: true`)";
|
|
66
|
+
if (selection === false) return "no connectors (`connectors: false`)";
|
|
67
|
+
return `\`connectors: [${normalizeConnectorNames(selection).map((name) => `"${name}"`).join(", ")}]\``;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
//#endregion
|
|
71
|
+
export { describeConnectorsSelection, isSameConnectorsSelection, normalizeConnectorNames, readRequestedConnectors, resolveEffectiveConnectors };
|
|
72
|
+
//# sourceMappingURL=test-connectors-selection.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"test-connectors-selection.mjs","names":[],"sources":["../../../../../../../core/src/tests/test-connectors-selection.ts"],"sourcesContent":["/**\n * Effective connector selection for the worker test lifecycle.\n *\n * Owns one decision: given what the caller passed and what the project\n * configured, which connectors does `setupTest` actually start? The precedence\n * is ratified in `contracts/2026-08-12-test-worker-lifecycle.md`:\n *\n * explicit non-`undefined` setupTest option > tests.connectors config > true\n */\nimport type { GenericObject } from \"@mongez/reinforcements\";\nimport { config } from \"../config\";\nimport type { ConnectorName } from \"../connectors\";\n\n/**\n * What a test runtime was asked to start.\n *\n * - `false` — bootstrap the runtime, start no connectors.\n * - `true` — start the framework's default connector set.\n * - an array — start exactly those. Order is not promised; lifecycle priority\n * decides the real boot/shutdown order.\n */\nexport type TestConnectorsSelection = boolean | ConnectorName[];\n\n/**\n * A caller's request, before the lower precedence layers are consulted.\n *\n * The distinction that matters is \"did the caller supply a value at all\", not\n * \"what value\" — `setupTest({ connectors: undefined })` must fall through to\n * project config exactly like `setupTest()` does, so an optional variable\n * holding `undefined` can never silently erase a project's configuration.\n */\nexport type RequestedTestConnectors =\n | { readonly isExplicit: true; readonly selection: TestConnectorsSelection }\n | { readonly isExplicit: false };\n\n/**\n * Classify the caller's `connectors` option as explicit or deferred.\n */\nexport function readRequestedConnectors(\n selection: TestConnectorsSelection | undefined,\n): RequestedTestConnectors {\n if (selection === undefined) {\n return { isExplicit: false };\n }\n\n return { isExplicit: true, selection };\n}\n\n/**\n * Read the `tests.connectors` config layer, or `undefined` when the project has\n * not configured one.\n *\n * Only meaningful once config files are loaded — before that, every project\n * looks like a project without a `tests` config.\n */\nexport function readConfiguredConnectors(): TestConnectorsSelection | undefined {\n // The default matters: `config.get` resolves an absent key to its default, and\n // ITS default is `null` — not `{}`. `warlock add test` does not generate\n // `src/config/tests.ts`, so reading `.connectors` off the result threw\n // \"Cannot read properties of null\" on the generated default path.\n const testsConfig = config.get<GenericObject>(\"tests\", {});\n\n // Cast at the config boundary: `GenericObject` values are untyped, and this is\n // the one place the untyped value becomes a typed selection.\n return testsConfig?.connectors as TestConnectorsSelection | undefined;\n}\n\n/**\n * Apply the ratified precedence:\n *\n * explicit non-`undefined` setupTest option > tests.connectors config > true\n *\n * ⚠ This is the reverse of 4.13, where config won over the parameter. Explicit\n * call-site intent beats a project default; a call that supplied nothing is not\n * intent, which is why \"omitted\" and \"explicitly `undefined`\" both defer.\n */\nexport function resolveEffectiveConnectors(\n requested: RequestedTestConnectors,\n): TestConnectorsSelection {\n if (requested.isExplicit) {\n return requested.selection;\n }\n\n const configured = readConfiguredConnectors();\n\n if (configured !== undefined) {\n return configured;\n }\n\n return true;\n}\n\n/**\n * Deduplicate a connector list and put it in a stable order.\n *\n * Two callers naming the same connectors in a different order asked for the same\n * thing, so the lifecycle must not treat them as a conflict.\n */\nexport function normalizeConnectorNames(names: ConnectorName[]): ConnectorName[] {\n return [...new Set(names)].sort();\n}\n\n/**\n * Compare two selections by normalized semantics — arrays as deduplicated sets,\n * never by caller order.\n */\nexport function isSameConnectorsSelection(\n left: TestConnectorsSelection,\n right: TestConnectorsSelection,\n): boolean {\n if (Array.isArray(left) && Array.isArray(right)) {\n const normalizedLeft = normalizeConnectorNames(left);\n const normalizedRight = normalizeConnectorNames(right);\n\n return (\n normalizedLeft.length === normalizedRight.length &&\n normalizedLeft.every((name, index) => name === normalizedRight[index])\n );\n }\n\n return left === right;\n}\n\n/**\n * Render a selection for an error message a caller can act on.\n */\nexport function describeConnectorsSelection(selection: TestConnectorsSelection): string {\n if (selection === true) {\n return \"the default connector set (`connectors: true`)\";\n }\n\n if (selection === false) {\n return \"no connectors (`connectors: false`)\";\n }\n\n const names = normalizeConnectorNames(selection)\n .map((name) => `\"${name}\"`)\n .join(\", \");\n\n return `\\`connectors: [${names}]\\``;\n}\n"],"mappings":";;;;;;;AAsCA,SAAgB,wBACd,WACyB;CACzB,IAAI,cAAc,QAChB,OAAO,EAAE,YAAY,MAAM;CAG7B,OAAO;EAAE,YAAY;EAAM;CAAU;AACvC;;;;;;;;AASA,SAAgB,2BAAgE;CAS9E,OAJoB,OAAO,IAAmB,SAAS,CAAC,CAIvC,CAAC,EAAE;AACtB;;;;;;;;;;AAWA,SAAgB,2BACd,WACyB;CACzB,IAAI,UAAU,YACZ,OAAO,UAAU;CAGnB,MAAM,aAAa,yBAAyB;CAE5C,IAAI,eAAe,QACjB,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAgB,wBAAwB,OAAyC;CAC/E,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK;AAClC;;;;;AAMA,SAAgB,0BACd,MACA,OACS;CACT,IAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,KAAK,GAAG;EAC/C,MAAM,iBAAiB,wBAAwB,IAAI;EACnD,MAAM,kBAAkB,wBAAwB,KAAK;EAErD,OACE,eAAe,WAAW,gBAAgB,UAC1C,eAAe,OAAO,MAAM,UAAU,SAAS,gBAAgB,MAAM;CAEzE;CAEA,OAAO,SAAS;AAClB;;;;AAKA,SAAgB,4BAA4B,WAA4C;CACtF,IAAI,cAAc,MAChB,OAAO;CAGT,IAAI,cAAc,OAChB,OAAO;CAOT,OAAO,kBAJO,wBAAwB,SAAS,CAAC,CAC7C,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAC1B,KAAK,IAEqB,EAAE;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-helpers.d.mts","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"mappings":";;AAYA;;;;AAAgC;AAehC;;AAfgC,iBAAhB,gBAAA;;;;;iBAeM,WAAA,CAAY,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;
|
|
1
|
+
{"version":3,"file":"test-helpers.d.mts","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"mappings":";;AAYA;;;;AAAgC;AAehC;;AAfgC,iBAAhB,gBAAA;;;;;iBAeM,WAAA,CAAY,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;iBAgD9D,OAAA,CAAQ,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;AAhDY;iBAuDtE,QAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;;;iBAOW,OAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;;;iBAOW,UAAA,CAAW,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;iBAO7D,SAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;AAxC6E;AAOxF;iBAwCsB,iBAAA,IAAqB,QAAA,EAAU,QAAA,GAAW,OAAA,CAAQ,CAAA;;;;iBAOlD,UAAA,IAAc,QAAA,EAAU,QAAA,EAAU,cAAA,YAAuB,OAAA,CAAQ,CAAA"}
|