awilixify 3.1.1 → 3.1.3

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.
Files changed (38) hide show
  1. package/README.md +3 -3
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +1 -0
  4. package/dist/lib/codegen/cli.d.ts +2 -0
  5. package/dist/lib/codegen/cli.js +57 -0
  6. package/dist/lib/codegen/config.d.ts +8 -0
  7. package/dist/lib/codegen/config.js +3 -0
  8. package/dist/lib/codegen/generate-asyncapi-client.d.ts +55 -0
  9. package/dist/lib/codegen/generate-asyncapi-client.js +359 -0
  10. package/dist/lib/codegen/generate-orval-api-client.d.ts +36 -0
  11. package/dist/lib/codegen/generate-orval-api-client.js +211 -0
  12. package/dist/lib/codegen/index.d.ts +3 -0
  13. package/dist/lib/codegen/index.js +3 -0
  14. package/dist/lib/decorators/decorator-state.d.ts +1 -1
  15. package/dist/lib/decorators/decorator-state.js +7 -1
  16. package/dist/lib/decorators/decorator-state.types.d.ts +1 -0
  17. package/dist/lib/devtools/devtools.types.d.ts +14 -9
  18. package/dist/lib/devtools/index.d.ts +2 -1
  19. package/dist/lib/devtools/index.js +2 -1
  20. package/dist/lib/devtools/trace-context.d.ts +12 -0
  21. package/dist/lib/devtools/trace-context.js +46 -0
  22. package/dist/lib/di/contexts/di-context-base.js +1 -1
  23. package/dist/lib/di/processors/controller-processor.d.ts +6 -1
  24. package/dist/lib/di/processors/controller-processor.js +87 -5
  25. package/dist/lib/di/processors/handler-processor.js +6 -17
  26. package/dist/lib/di/processors/initializer-processor.js +1 -16
  27. package/dist/lib/di/processors/interceptor-processor.js +133 -17
  28. package/dist/lib/di/processors/keyed-feature-registrar.d.ts +5 -1
  29. package/dist/lib/di/processors/keyed-feature-registrar.js +48 -7
  30. package/dist/lib/di/providers/provider-resolver.js +27 -22
  31. package/dist/lib/http/openapi-builder.d.ts +2 -2
  32. package/dist/lib/http/openapi-builder.js +10 -5
  33. package/dist/lib/mediator/mediator.d.ts +2 -1
  34. package/dist/lib/mediator/mediator.js +24 -4
  35. package/dist/lib/operations/operation.decorator.d.ts +23 -0
  36. package/dist/lib/operations/operation.decorator.js +30 -0
  37. package/dist/tsconfig.tsbuildinfo +1 -1
  38. package/package.json +15 -3
@@ -0,0 +1,211 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, extname, resolve } from "node:path";
4
+ const httpMethods = new Set([
5
+ "delete",
6
+ "get",
7
+ "head",
8
+ "options",
9
+ "patch",
10
+ "post",
11
+ "put",
12
+ "trace",
13
+ ]);
14
+ export async function generateOrvalApiClient(options) {
15
+ const document = await resolveOpenApiDocument(options.openApi);
16
+ const operationIds = collectOperationIds(document, options.tags);
17
+ const getOperationFunctionName = options.getOperationFunctionName ?? ((operationId) => operationId);
18
+ assertIdentifier(options.apiClientClassName, "API client class name");
19
+ assertIdentifier(options.operationsConstName, "operations constant name");
20
+ const operations = operationIds.map((operationId) => {
21
+ assertIdentifier(operationId, "operation ID");
22
+ const functionName = getOperationFunctionName(operationId);
23
+ assertIdentifier(functionName, `function name for operation "${operationId}"`);
24
+ return { functionName, operationId };
25
+ });
26
+ const apiClientFileName = options.apiClientFileName ?? "generated-api-client.ts";
27
+ const operationsFileName = options.operationsFileName ?? "generated.operations.ts";
28
+ const outputDirectory = resolve(options.outputDirectory);
29
+ const apiClientPath = resolve(outputDirectory, apiClientFileName);
30
+ const operationsPath = resolve(outputDirectory, operationsFileName);
31
+ const moduleOptions = options.module;
32
+ const modulePath = moduleOptions
33
+ ? resolve(moduleOptions.outputPath)
34
+ : undefined;
35
+ await mkdir(outputDirectory, { recursive: true });
36
+ await Promise.all([
37
+ replaceFile(apiClientPath, renderApiClient({
38
+ ...options,
39
+ operations,
40
+ operationsImport: toJavaScriptImport(operationsFileName),
41
+ })),
42
+ replaceFile(operationsPath, renderOperations(options.serviceName, options.operationsConstName, operationIds)),
43
+ ]);
44
+ const moduleCreated = moduleOptions && modulePath
45
+ ? await createModuleIfMissing(modulePath, renderModule(options.apiClientClassName, moduleOptions))
46
+ : undefined;
47
+ return {
48
+ operationIds,
49
+ apiClientPath,
50
+ operationsPath,
51
+ modulePath,
52
+ moduleCreated,
53
+ };
54
+ }
55
+ async function replaceFile(filePath, source) {
56
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
57
+ try {
58
+ await writeFile(temporaryPath, source);
59
+ await rename(temporaryPath, filePath);
60
+ }
61
+ finally {
62
+ await rm(temporaryPath, { force: true });
63
+ }
64
+ }
65
+ async function createModuleIfMissing(modulePath, source) {
66
+ await mkdir(dirname(modulePath), { recursive: true });
67
+ try {
68
+ await writeFile(modulePath, source, { flag: "wx" });
69
+ return true;
70
+ }
71
+ catch (error) {
72
+ if (typeof error === "object" &&
73
+ error !== null &&
74
+ "code" in error &&
75
+ error.code === "EEXIST") {
76
+ return false;
77
+ }
78
+ throw error;
79
+ }
80
+ }
81
+ async function resolveOpenApiDocument(input) {
82
+ if (typeof input !== "string")
83
+ return input;
84
+ const response = await fetch(input);
85
+ if (!response.ok) {
86
+ throw new Error(`Failed to fetch OpenAPI document from ${input}: ${response.status} ${response.statusText}`);
87
+ }
88
+ return (await response.json());
89
+ }
90
+ function collectOperationIds(document, tags) {
91
+ const operationIds = new Set();
92
+ for (const pathItem of Object.values(document.paths ?? {})) {
93
+ for (const [method, operation] of Object.entries(pathItem)) {
94
+ if (!httpMethods.has(method.toLowerCase()))
95
+ continue;
96
+ if (typeof operation.operationId !== "string")
97
+ continue;
98
+ const operationTags = Array.isArray(operation.tags)
99
+ ? operation.tags.filter((tag) => typeof tag === "string")
100
+ : [];
101
+ if (tags?.length && !tags.some((tag) => operationTags.includes(tag))) {
102
+ continue;
103
+ }
104
+ operationIds.add(operation.operationId);
105
+ }
106
+ }
107
+ return [...operationIds];
108
+ }
109
+ function renderApiClient({ apiClientClassName, generatedClientImport, operations, operationsConstName, operationsImport, }) {
110
+ const imports = operations
111
+ .map(({ functionName, operationId }) => `\t${functionName} as ${operationId}Request,`)
112
+ .join("\n");
113
+ const methods = operations
114
+ .map(({ operationId, }) => `\t@callsOperation(${operationsConstName}.${operationId})
115
+ \t${operationId}(
116
+ \t\t...args: Parameters<typeof ${operationId}Request>
117
+ \t): ReturnType<typeof ${operationId}Request> {
118
+ \t\treturn ${operationId}Request(
119
+ \t\t\t...(withTracePropagation(args, ${operationId}Request.length - 1) as Parameters<
120
+ \t\t\t\ttypeof ${operationId}Request
121
+ \t\t\t>),
122
+ \t\t);
123
+ \t}`)
124
+ .join("\n\n");
125
+ return `// Generated from OpenAPI. Do not edit.
126
+ import { callsOperation } from "awilixify";
127
+ import { getTracePropagationHeaders } from "awilixify/devtools";
128
+
129
+ import {
130
+ ${imports}
131
+ } from ${JSON.stringify(generatedClientImport)};
132
+ import { ${operationsConstName} } from ${JSON.stringify(operationsImport)};
133
+
134
+ function withTracePropagation(args: unknown[], optionsIndex: number): unknown[] {
135
+ \tconst tracedArgs = [...args];
136
+ \tconst options = (tracedArgs[optionsIndex] ?? {}) as {
137
+ \t\theaders?: Record<string, string>;
138
+ \t};
139
+
140
+ \ttracedArgs[optionsIndex] = {
141
+ \t\t...options,
142
+ \t\theaders: {
143
+ \t\t\t...options.headers,
144
+ \t\t\t...getTracePropagationHeaders(),
145
+ \t\t},
146
+ \t};
147
+
148
+ \treturn tracedArgs;
149
+ }
150
+
151
+ export class ${apiClientClassName} {
152
+ ${methods}
153
+ }
154
+ `;
155
+ }
156
+ function renderOperations(serviceName, operationsConstName, operationIds) {
157
+ const operations = Object.fromEntries(operationIds.map((operationId) => [
158
+ operationId,
159
+ {
160
+ serviceName,
161
+ operationId,
162
+ transport: "http",
163
+ },
164
+ ]));
165
+ return `// Generated from OpenAPI. Do not edit.
166
+ export const ${operationsConstName} = ${JSON.stringify(operations, null, 2)} as const;
167
+ `;
168
+ }
169
+ function renderModule(apiClientClassName, options) {
170
+ assertIdentifier(options.moduleName, "module name");
171
+ assertIdentifier(options.apiClientProviderName, "API client provider name");
172
+ const exportNames = options.exports ?? [options.apiClientProviderName];
173
+ for (const providerName of exportNames) {
174
+ if (providerName !== options.apiClientProviderName) {
175
+ throw new Error(`Initial module export "${providerName}" is not the generated API client provider`);
176
+ }
177
+ }
178
+ const imports = `import { createModule, type ModuleDef } from "awilixify";
179
+
180
+ import { ${apiClientClassName} } from ${JSON.stringify(options.apiClientImport)};`;
181
+ const exportKeys = exportNames.map((name) => JSON.stringify(name)).join(", ");
182
+ const moduleDefName = `${options.moduleName}Def`;
183
+ return `// Generated once by Awilixify codegen. Safe to customize.
184
+ ${imports}
185
+
186
+ export type ${moduleDefName} = ModuleDef<{
187
+ \tproviders: {
188
+ \t\t${options.apiClientProviderName}: ${apiClientClassName};
189
+ \t};
190
+ \texportKeys: [${exportKeys}];
191
+ }>;
192
+
193
+ export type Deps = ${moduleDefName}["deps"];
194
+
195
+ export const ${options.moduleName} = createModule<${moduleDefName}>({
196
+ \tname: "${options.moduleName}",
197
+ \tproviders: {
198
+ \t\t${options.apiClientProviderName}: ${apiClientClassName},
199
+ \t},
200
+ \texports: [${exportKeys}],
201
+ });
202
+ `;
203
+ }
204
+ function assertIdentifier(value, label) {
205
+ if (!/^[$A-Z_a-z][$\w]*$/.test(value)) {
206
+ throw new Error(`${label} "${value}" is not a valid TypeScript identifier`);
207
+ }
208
+ }
209
+ function toJavaScriptImport(fileName) {
210
+ return `./${basename(fileName, extname(fileName))}.js`;
211
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./config.js";
2
+ export * from "./generate-asyncapi-client.js";
3
+ export * from "./generate-orval-api-client.js";
@@ -0,0 +1,3 @@
1
+ export * from "./config.js";
2
+ export * from "./generate-asyncapi-client.js";
3
+ export * from "./generate-orval-api-client.js";
@@ -9,7 +9,7 @@ export declare function createDecoratorStateUpdater<TInitializers extends {
9
9
  token: DecoratorToken<DecoratorState<MethodStateFrom<TInitializers>, RootStateFrom<TInitializers>>>;
10
10
  update: {
11
11
  (context: ClassDecoratorContext<any>, updater: RootUpdate<DecoratorState<MethodStateFrom<TInitializers>, RootStateFrom<TInitializers>>>): void;
12
- (context: ClassMethodDecoratorContext<any, any>, updater: MethodUpdate<DecoratorState<MethodStateFrom<TInitializers>, RootStateFrom<TInitializers>>>): void;
12
+ (context: ClassMethodDecoratorContext<any, any>, updater: MethodUpdate<DecoratorState<MethodStateFrom<TInitializers>, RootStateFrom<TInitializers>>>, decoratorName?: string): void;
13
13
  };
14
14
  };
15
15
  export declare function resolveDecoratorState<TState extends DecoratorState<any, any>>(target: unknown, token: DecoratorToken<TState>): TState | null;
@@ -44,8 +44,9 @@ function createUpdater(token, initializers) {
44
44
  const initializeState = () => ({
45
45
  root: initializers.root(),
46
46
  methods: new Map(),
47
+ decoratorNames: new Map(),
47
48
  });
48
- function update(context, updater) {
49
+ function update(context, updater, decoratorName) {
49
50
  if (!context.metadata)
50
51
  return;
51
52
  const state = context.metadata[token.stateSymbol] || initializeState();
@@ -62,9 +63,14 @@ function createUpdater(token, initializers) {
62
63
  return;
63
64
  const nextMethods = new Map(state.methods);
64
65
  nextMethods.set(context.name, updater.method(nextMethods.get(context.name) ?? initializers.method()));
66
+ const nextDecoratorNames = new Map(state.decoratorNames);
67
+ if (decoratorName) {
68
+ nextDecoratorNames.set(context.name, decoratorName);
69
+ }
65
70
  context.metadata[token.stateSymbol] = {
66
71
  ...state,
67
72
  methods: nextMethods,
73
+ decoratorNames: nextDecoratorNames,
68
74
  };
69
75
  }
70
76
  return update;
@@ -2,6 +2,7 @@ export type MethodName = string | symbol;
2
2
  export type DecoratorState<TMethod, TRoot = null> = {
3
3
  root: TRoot;
4
4
  methods: Map<MethodName, TMethod>;
5
+ decoratorNames: Map<MethodName, string>;
5
6
  };
6
7
  export type DecoratorMethodState<TState> = TState extends DecoratorState<infer TMethod, any> ? TMethod : never;
7
8
  export type DecoratorRootState<TState> = TState extends DecoratorState<any, infer TRoot> ? TRoot : never;
@@ -2,36 +2,41 @@ import type * as Awilix from "awilix";
2
2
  import type { InternalModuleLike } from "../di/modules/runtime-module.types.js";
3
3
  import type { ConstructorController, Initializer } from "../di/providers/provider.types.js";
4
4
  export declare const AWILIXIFY_DEVTOOLS_PROCESSOR = "__awilixifyDevtoolsProcessor";
5
- export type TraceSpanKind = "http" | "provider" | "handler" | "prehandler" | "interceptor" | "initializer";
5
+ export type TraceSpanKind = "controller" | "provider" | "mediator" | "handler" | "prehandler" | "interceptor";
6
6
  export type RecordSpanInput<T> = {
7
7
  kind: TraceSpanKind;
8
8
  moduleName: string;
9
- providerKey: string;
9
+ className: string;
10
+ registrationKey: string;
10
11
  methodName: string;
11
12
  args: unknown[];
13
+ parameterNames?: string[];
12
14
  callback: () => T | Promise<T>;
13
15
  moduleId?: string;
16
+ getProceedDurationMs?: () => number;
14
17
  };
15
18
  export type WrapResolverInput = {
16
19
  kind: TraceSpanKind;
17
20
  module: InternalModuleLike;
18
21
  options: Awilix.BuildResolverOptions<any>;
19
- providerKey: string;
22
+ className: string;
23
+ registrationKey: string;
20
24
  resolver: Awilix.Resolver<any>;
21
25
  moduleId?: string;
22
26
  isFactory?: boolean;
23
27
  };
24
- export type TraceInitializerInput<T = unknown> = {
28
+ export type RunInControllerTraceInput<T> = {
29
+ moduleName: string;
30
+ className: string;
31
+ registrationKey: string;
32
+ methodName: string;
25
33
  args: unknown[];
26
34
  callback: () => T | Promise<T>;
27
- controllerName: string;
28
- getStatusCode: () => number | undefined;
29
- methodName: string;
30
- moduleName: string;
31
35
  };
32
36
  export interface Tracer {
33
37
  recordSpan<T>(input: RecordSpanInput<T>): T | Promise<T>;
34
- traceInitializer<T>(input: TraceInitializerInput<T>): T | Promise<T>;
38
+ runInCurrentSpan<T>(callback: () => T | Promise<T>): T | Promise<T>;
39
+ runInControllerTrace<T>(input: RunInControllerTraceInput<T>): T | Promise<T>;
35
40
  wrapResolver(input: WrapResolverInput): Awilix.Resolver<any>;
36
41
  }
37
42
  export type ModuleDecoratorMetadata = {
@@ -1,4 +1,5 @@
1
1
  export type { InternalModuleLike } from "../di/modules/runtime-module.types.js";
2
- export { hasInitAfter, hasUseClass, isCostructorProvider, isCostructorProvider as isConstructorProvider, isEagerProvider, isPromiseLike, isResultLike, } from "../di/type-guards.js";
2
+ export { hasInitAfter, hasUseClass, isCostructorProvider, isCostructorProvider as isConstructorProvider, isEagerProvider, isFactoryProvider, isPromiseLike, isResultLike, } from "../di/type-guards.js";
3
3
  export * from "./devtools.types.js";
4
4
  export { getControllerMethodNames } from "./helpers.js";
5
+ export * from "./trace-context.js";
@@ -1,3 +1,4 @@
1
- export { hasInitAfter, hasUseClass, isCostructorProvider, isCostructorProvider as isConstructorProvider, isEagerProvider, isPromiseLike, isResultLike, } from "../di/type-guards.js";
1
+ export { hasInitAfter, hasUseClass, isCostructorProvider, isCostructorProvider as isConstructorProvider, isEagerProvider, isFactoryProvider, isPromiseLike, isResultLike, } from "../di/type-guards.js";
2
2
  export * from "./devtools.types.js";
3
3
  export { getControllerMethodNames } from "./helpers.js";
4
+ export * from "./trace-context.js";
@@ -0,0 +1,12 @@
1
+ export declare const TRACEPARENT_HEADER = "traceparent";
2
+ export type TracePropagationContext = {
3
+ traceId: string;
4
+ spanId: string;
5
+ traceFlags: string;
6
+ };
7
+ export declare function getTracePropagationContext(): TracePropagationContext | undefined;
8
+ export declare function runWithTracePropagationContext<T>(context: TracePropagationContext, callback: () => T | Promise<T>): T | Promise<T>;
9
+ export declare function parseTraceparent(value: string | string[] | undefined): TracePropagationContext | undefined;
10
+ export declare function formatTraceparent(context: TracePropagationContext): string;
11
+ export declare function getTracePropagationHeaders(): Record<string, string>;
12
+ export declare function runWithTraceparent<T>(value: string | string[] | undefined, callback: () => T | Promise<T>): T | Promise<T>;
@@ -0,0 +1,46 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export const TRACEPARENT_HEADER = "traceparent";
3
+ const TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
4
+ const propagationStorage = new AsyncLocalStorage();
5
+ export function getTracePropagationContext() {
6
+ return propagationStorage.getStore();
7
+ }
8
+ export function runWithTracePropagationContext(context, callback) {
9
+ return propagationStorage.run(context, callback);
10
+ }
11
+ export function parseTraceparent(value) {
12
+ const candidate = Array.isArray(value) ? value[0] : value;
13
+ if (!candidate)
14
+ return undefined;
15
+ const match = TRACEPARENT_PATTERN.exec(candidate.trim());
16
+ if (!match)
17
+ return undefined;
18
+ const traceId = match[1];
19
+ const spanId = match[2];
20
+ const traceFlags = match[3];
21
+ if (!traceId || !spanId || !traceFlags)
22
+ return undefined;
23
+ if (isAllZeros(traceId) || isAllZeros(spanId))
24
+ return undefined;
25
+ return {
26
+ traceId: traceId.toLowerCase(),
27
+ spanId: spanId.toLowerCase(),
28
+ traceFlags: traceFlags.toLowerCase(),
29
+ };
30
+ }
31
+ export function formatTraceparent(context) {
32
+ return `00-${context.traceId}-${context.spanId}-${context.traceFlags}`;
33
+ }
34
+ export function getTracePropagationHeaders() {
35
+ const context = getTracePropagationContext();
36
+ return context ? { [TRACEPARENT_HEADER]: formatTraceparent(context) } : {};
37
+ }
38
+ export function runWithTraceparent(value, callback) {
39
+ const context = parseTraceparent(value);
40
+ return context
41
+ ? runWithTracePropagationContext(context, callback)
42
+ : callback();
43
+ }
44
+ function isAllZeros(value) {
45
+ return /^0+$/.test(value);
46
+ }
@@ -18,7 +18,7 @@ export class DIContextBase extends ContainerContextBase {
18
18
  this.handlerProcessor = new HandlerProcessor(this.options.providerOptions || {}, this.devtoolsProcessorRef);
19
19
  this.interceptorProcessor = new InterceptorProcessor(this.options.providerOptions || {}, this.devtoolsProcessorRef);
20
20
  this.initializerProcessor = new InitializerProcessor(this.devtoolsProcessorRef);
21
- this.controllerProcessor = new ControllerProcessor(this.interceptorProcessor, this.options.providerOptions || {}, this.options.skipRegisterRoutes === true);
21
+ this.controllerProcessor = new ControllerProcessor(this.interceptorProcessor, this.options.providerOptions || {}, this.options.skipRegisterRoutes === true, this.devtoolsProcessorRef);
22
22
  this.providerResolver = new ProviderResolver(this.interceptorProcessor, this.options.providerOptions || {}, this.devtoolsProcessorRef, getOrCreateRequestScope);
23
23
  }
24
24
  beforeRegisterProviders(m, scope, importedModulesWithScope) {
@@ -1,4 +1,5 @@
1
1
  import * as Awilix from "awilix";
2
+ import type { DevtoolsProcessorRef } from "../../devtools/devtools.types.js";
2
3
  import type { InternalModuleLike as M } from "../modules/runtime-module.types.js";
3
4
  import type { ControllerRuntimeEntry } from "./initializer-processor.js";
4
5
  import type { InterceptorProcessor } from "./interceptor-processor.js";
@@ -6,8 +7,12 @@ export declare class ControllerProcessor {
6
7
  private readonly interceptorProcessor;
7
8
  private readonly providerOptions;
8
9
  private readonly skipRegisterRoutes;
10
+ private readonly devtoolsProcessorRef;
9
11
  private readonly registeredControllers;
10
- constructor(interceptorProcessor: InterceptorProcessor, providerOptions: Partial<Awilix.BuildResolverOptions<any>>, skipRegisterRoutes: boolean);
12
+ constructor(interceptorProcessor: InterceptorProcessor, providerOptions: Partial<Awilix.BuildResolverOptions<any>>, skipRegisterRoutes: boolean, devtoolsProcessorRef: DevtoolsProcessorRef);
11
13
  processControllers(m: M, diScope: Awilix.AwilixContainer): ControllerRuntimeEntry[];
12
14
  private resolveBySymbol;
15
+ private get devtoolsTracer();
16
+ private createTracedControllerResolver;
17
+ private createTraceStarterResolver;
13
18
  }
@@ -6,11 +6,13 @@ export class ControllerProcessor {
6
6
  interceptorProcessor;
7
7
  providerOptions;
8
8
  skipRegisterRoutes;
9
+ devtoolsProcessorRef;
9
10
  registeredControllers = new WeakMap();
10
- constructor(interceptorProcessor, providerOptions, skipRegisterRoutes) {
11
+ constructor(interceptorProcessor, providerOptions, skipRegisterRoutes, devtoolsProcessorRef) {
11
12
  this.interceptorProcessor = interceptorProcessor;
12
13
  this.providerOptions = providerOptions;
13
14
  this.skipRegisterRoutes = skipRegisterRoutes;
15
+ this.devtoolsProcessorRef = devtoolsProcessorRef;
14
16
  }
15
17
  processControllers(m, diScope) {
16
18
  if (!m.controllers?.length)
@@ -43,13 +45,32 @@ export class ControllerProcessor {
43
45
  }),
44
46
  }),
45
47
  });
46
- diScope.register({
47
- [controllerSymbol]: this.interceptorProcessor.createInterceptedProviderResolver({
48
+ const tracedResolver = this.devtoolsTracer
49
+ ? this.createTracedControllerResolver({
48
50
  module: m,
49
- useClass,
50
51
  options,
52
+ className: useClass.name,
53
+ registrationKey: useClass.name,
51
54
  resolver: baseResolver,
52
- }),
55
+ })
56
+ : baseResolver;
57
+ const interceptedResolver = this.interceptorProcessor.createInterceptedProviderResolver({
58
+ module: m,
59
+ useClass,
60
+ options,
61
+ resolver: tracedResolver,
62
+ });
63
+ const traceStarterResolver = this.devtoolsTracer
64
+ ? this.createTraceStarterResolver({
65
+ module: m,
66
+ options,
67
+ className: useClass.name,
68
+ registrationKey: useClass.name,
69
+ resolver: interceptedResolver,
70
+ })
71
+ : interceptedResolver;
72
+ diScope.register({
73
+ [controllerSymbol]: traceStarterResolver,
53
74
  });
54
75
  if (!this.skipRegisterRoutes &&
55
76
  typeof useClass.prototype.registerRoutes === "function") {
@@ -73,4 +94,65 @@ export class ControllerProcessor {
73
94
  return resolveFromRequestScope(scope, symbol);
74
95
  return scope.resolve(symbol);
75
96
  }
97
+ get devtoolsTracer() {
98
+ return this.devtoolsProcessorRef.current?.tracer;
99
+ }
100
+ createTracedControllerResolver({ className, module, options, registrationKey, resolver, }) {
101
+ return Awilix.createBuildResolver({
102
+ ...options,
103
+ resolve: (container) => {
104
+ const instance = resolver.resolve(container);
105
+ const tracer = this.devtoolsProcessorRef.current?.tracer;
106
+ if (!tracer || module.name === "DevtoolsModule") {
107
+ return instance;
108
+ }
109
+ return tracer
110
+ .wrapResolver({
111
+ kind: "controller",
112
+ module,
113
+ options,
114
+ className,
115
+ registrationKey,
116
+ resolver: Awilix.asValue(instance),
117
+ })
118
+ .resolve(container);
119
+ },
120
+ });
121
+ }
122
+ createTraceStarterResolver({ className, module, options, registrationKey, resolver, }) {
123
+ return Awilix.createBuildResolver({
124
+ ...options,
125
+ resolve: (container) => {
126
+ const instance = resolver.resolve(container);
127
+ const tracer = this.devtoolsProcessorRef.current?.tracer;
128
+ if (!tracer || module.name === "DevtoolsModule") {
129
+ return instance;
130
+ }
131
+ const wrappers = new Map();
132
+ return new Proxy(instance, {
133
+ get: (target, propertyKey, proxyReceiver) => {
134
+ const value = Reflect.get(target, propertyKey, proxyReceiver);
135
+ if (typeof value !== "function")
136
+ return value;
137
+ if (propertyKey === "constructor")
138
+ return value;
139
+ const existing = wrappers.get(propertyKey);
140
+ if (existing)
141
+ return existing;
142
+ const methodName = String(propertyKey);
143
+ const wrapped = (...args) => tracer.runInControllerTrace({
144
+ moduleName: module.name,
145
+ className,
146
+ registrationKey,
147
+ methodName,
148
+ args,
149
+ callback: () => value.apply(proxyReceiver, args),
150
+ });
151
+ wrappers.set(propertyKey, wrapped);
152
+ return wrapped;
153
+ },
154
+ });
155
+ },
156
+ });
157
+ }
76
158
  }
@@ -28,7 +28,7 @@ export class HandlerProcessor {
28
28
  constructor(providerOptions, devtoolsProcessorRef) {
29
29
  this.providerOptions = providerOptions;
30
30
  this.devtoolsProcessorRef = devtoolsProcessorRef;
31
- this.keyedFeatureRegistrar = new KeyedFeatureRegistrar(providerOptions);
31
+ this.keyedFeatureRegistrar = new KeyedFeatureRegistrar(providerOptions, devtoolsProcessorRef);
32
32
  }
33
33
  processHandlers(m, scope, importedModulesWithScope, handlerType) {
34
34
  const { handlersKey, mediatorKey, preHandlersKey } = HandlerProcessor.handlerConfig[handlerType];
@@ -65,21 +65,9 @@ export class HandlerProcessor {
65
65
  const requestScope = options.lifetime === Awilix.Lifetime.SINGLETON
66
66
  ? scope
67
67
  : getOrCreateRequestScope(scope);
68
- if (!this.devtoolsTracer) {
69
- return requestScope
70
- .resolve(handlerSymbol)
71
- .executor(payload, context);
72
- }
73
- return this.devtoolsTracer.recordSpan({
74
- kind: "handler",
75
- moduleName: m.name,
76
- providerKey: `${handlerType}:${handlerKey}`,
77
- methodName: "executor",
78
- args: [payload, context],
79
- callback: () => requestScope
80
- .resolve(handlerSymbol)
81
- .executor(payload, context),
82
- });
68
+ return requestScope
69
+ .resolve(handlerSymbol)
70
+ .executor(payload, context);
83
71
  });
84
72
  }
85
73
  scope.register({
@@ -93,7 +81,8 @@ export class HandlerProcessor {
93
81
  kind: "handler",
94
82
  module,
95
83
  options,
96
- providerKey: handlerClassName,
84
+ className: handlerClassName,
85
+ registrationKey: handlerClassName,
97
86
  resolver,
98
87
  });
99
88
  }
@@ -34,15 +34,7 @@ export class InitializerProcessor {
34
34
  return;
35
35
  for (const controller of controllers) {
36
36
  for (const methodName of getControllerMethodNames(controller.controllerClass)) {
37
- const invoke = (...args) => this.devtoolsProcessorRef.current?.tracer.traceInitializer({
38
- args,
39
- callback: () => runInRequestScopeContext(() => controller.resolve()[methodName](...args)),
40
- controllerName: controller.controllerClass.name,
41
- getStatusCode: () => getStatusCode(args),
42
- methodName: String(methodName),
43
- moduleName: m.name,
44
- }) ??
45
- runInRequestScopeContext(() => controller.resolve()[methodName](...args));
37
+ const invoke = (...args) => runInRequestScopeContext(() => controller.resolve()[methodName](...args));
46
38
  this.ensureNoMultiInvokableInitializersPerMethod(m.name, methodName, controller, activeInitializers);
47
39
  for (const [, resolveInitializer] of activeInitializers) {
48
40
  const initializer = resolveInitializer();
@@ -86,10 +78,3 @@ export class InitializerProcessor {
86
78
  return initializers.filter(([key]) => !excludedKeys.has(key));
87
79
  }
88
80
  }
89
- function getStatusCode(args) {
90
- const reply = args[1];
91
- if (!reply || typeof reply !== "object")
92
- return undefined;
93
- const statusCode = reply.statusCode;
94
- return typeof statusCode === "number" ? statusCode : undefined;
95
- }