@navios/core 1.1.0 → 2.0.0-alpha.1
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 +85 -13
- package/README.md +69 -220
- package/lib/async-context-BAdt7bno.d.mts +239 -0
- package/lib/async-context-BAdt7bno.d.mts.map +1 -0
- package/lib/async-context-RsWmy2Hi.d.cts +239 -0
- package/lib/async-context-RsWmy2Hi.d.cts.map +1 -0
- package/lib/attribute-factory-BW1kgBqf.d.mts +70 -0
- package/lib/attribute-factory-BW1kgBqf.d.mts.map +1 -0
- package/lib/attribute-factory-DqN4x5XM.d.cts +70 -0
- package/lib/attribute-factory-DqN4x5XM.d.cts.map +1 -0
- package/lib/attribute-value-BNiJjxl1.mjs +225 -0
- package/lib/attribute-value-BNiJjxl1.mjs.map +1 -0
- package/lib/attribute-value-Cux5HhOL.cjs +314 -0
- package/lib/attribute-value-Cux5HhOL.cjs.map +1 -0
- package/lib/basic-execution-context-5uq2DvEA.cjs +318 -0
- package/lib/basic-execution-context-5uq2DvEA.cjs.map +1 -0
- package/lib/basic-execution-context-u1VktGoM.mjs +277 -0
- package/lib/basic-execution-context-u1VktGoM.mjs.map +1 -0
- package/lib/execution-context-BVSmLkYp.d.cts +71 -0
- package/lib/execution-context-BVSmLkYp.d.cts.map +1 -0
- package/lib/execution-context-C5F9rojO.d.mts +71 -0
- package/lib/execution-context-C5F9rojO.d.mts.map +1 -0
- package/lib/execution-context-token--cKS4cJv.cjs +270 -0
- package/lib/execution-context-token--cKS4cJv.cjs.map +1 -0
- package/lib/execution-context-token-Cb3M3Ao0.mjs +223 -0
- package/lib/execution-context-token-Cb3M3Ao0.mjs.map +1 -0
- package/lib/index.cjs +1672 -4426
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +842 -3
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +842 -3
- package/lib/index.d.mts.map +1 -0
- package/lib/index.mjs +1559 -4221
- package/lib/index.mjs.map +1 -1
- package/lib/legacy-compat/index.cjs +72 -371
- package/lib/legacy-compat/index.cjs.map +1 -1
- package/lib/legacy-compat/index.d.cts +42 -382
- package/lib/legacy-compat/index.d.cts.map +1 -1
- package/lib/legacy-compat/index.d.mts +41 -382
- package/lib/legacy-compat/index.d.mts.map +1 -1
- package/lib/legacy-compat/index.mjs +51 -345
- package/lib/legacy-compat/index.mjs.map +1 -1
- package/lib/module-Bz83ZnJ5.cjs +173 -0
- package/lib/module-Bz83ZnJ5.cjs.map +1 -0
- package/lib/module-options-CSqQUSTm.d.mts +51 -0
- package/lib/module-options-CSqQUSTm.d.mts.map +1 -0
- package/lib/module-options-DSRBri4J.d.cts +51 -0
- package/lib/module-options-DSRBri4J.d.cts.map +1 -0
- package/lib/module-zPXwR2qp.mjs +138 -0
- package/lib/module-zPXwR2qp.mjs.map +1 -0
- package/lib/settled-within-B6gpu2XW.cjs +32 -0
- package/lib/settled-within-B6gpu2XW.cjs.map +1 -0
- package/lib/settled-within-Bc2pj8WB.mjs +21 -0
- package/lib/settled-within-Bc2pj8WB.mjs.map +1 -0
- package/lib/testing/index.cjs +74 -414
- package/lib/testing/index.cjs.map +1 -1
- package/lib/testing/index.d.cts +25 -385
- package/lib/testing/index.d.cts.map +1 -1
- package/lib/testing/index.d.mts +24 -385
- package/lib/testing/index.d.mts.map +1 -1
- package/lib/testing/index.mjs +72 -408
- package/lib/testing/index.mjs.map +1 -1
- package/lib/transport.cjs +36 -0
- package/lib/transport.d.cts +254 -0
- package/lib/transport.d.cts.map +1 -0
- package/lib/transport.d.mts +254 -0
- package/lib/transport.d.mts.map +1 -0
- package/lib/transport.mjs +6 -0
- package/package.json +37 -17
- package/docs/README.md +0 -316
- package/docs/adapters.md +0 -308
- package/docs/application-setup.md +0 -524
- package/docs/attributes.md +0 -689
- package/docs/controllers.md +0 -373
- package/docs/endpoints.md +0 -444
- package/docs/exceptions.md +0 -352
- package/docs/guards.md +0 -550
- package/docs/legacy-compat.md +0 -356
- package/docs/modules.md +0 -377
- package/docs/quick-start.md +0 -290
- package/docs/services.md +0 -427
- package/docs/testing.md +0 -827
- package/lib/index-3LcTrbxz.d.mts +0 -3804
- package/lib/index-3LcTrbxz.d.mts.map +0 -1
- package/lib/index-B14SekVb.d.cts +0 -3804
- package/lib/index-B14SekVb.d.cts.map +0 -1
- package/lib/navios.factory-CUrO_p6K.cjs +0 -4538
- package/lib/navios.factory-CUrO_p6K.cjs.map +0 -1
- package/lib/navios.factory-DjUOOVVL.mjs +0 -4151
- package/lib/navios.factory-DjUOOVVL.mjs.map +0 -1
- package/lib/tokens-BEuBMGGX.cjs +0 -193
- package/lib/tokens-BEuBMGGX.cjs.map +0 -1
- package/lib/tokens-COyNGV1I.mjs +0 -97
- package/lib/tokens-COyNGV1I.mjs.map +0 -1
- package/lib/use-guards.decorator-DLmRl2CV.mjs +0 -336
- package/lib/use-guards.decorator-DLmRl2CV.mjs.map +0 -1
- package/lib/use-guards.decorator-DhumFTk3.cjs +0 -444
- package/lib/use-guards.decorator-DhumFTk3.cjs.map +0 -1
- package/project.json +0 -66
- package/src/__tests__/attribute.factory.spec.mts +0 -300
- package/src/__tests__/config.service.spec.mts +0 -43
- package/src/__tests__/console-logger.service.spec.mts +0 -312
- package/src/__tests__/controller-resolver.spec.mts +0 -229
- package/src/__tests__/controller.spec.mts +0 -58
- package/src/__tests__/guard-runner.service.spec.mts +0 -399
- package/src/__tests__/logger.service.spec.mts +0 -147
- package/src/__tests__/responders.spec.mts +0 -340
- package/src/__tests__/testing-module.spec.mts +0 -459
- package/src/__tests__/unit-testing-module.spec.mts +0 -424
- package/src/attribute.factory.mts +0 -325
- package/src/config/config-service.interface.mts +0 -47
- package/src/config/config.provider.mts +0 -69
- package/src/config/config.service.mts +0 -176
- package/src/config/index.mts +0 -5
- package/src/config/types.mts +0 -58
- package/src/config/utils/helpers.mts +0 -23
- package/src/config/utils/index.mts +0 -1
- package/src/decorators/controller.decorator.mts +0 -81
- package/src/decorators/endpoint.decorator.mts +0 -181
- package/src/decorators/header.decorator.mts +0 -38
- package/src/decorators/http-code.decorator.mts +0 -38
- package/src/decorators/index.mts +0 -8
- package/src/decorators/module.decorator.mts +0 -106
- package/src/decorators/multipart.decorator.mts +0 -169
- package/src/decorators/stream.decorator.mts +0 -155
- package/src/decorators/use-guards.decorator.mts +0 -73
- package/src/exceptions/bad-request.exception.mts +0 -28
- package/src/exceptions/conflict.exception.mts +0 -31
- package/src/exceptions/forbidden.exception.mts +0 -30
- package/src/exceptions/http.exception.mts +0 -33
- package/src/exceptions/index.mts +0 -7
- package/src/exceptions/internal-server-error.exception.mts +0 -33
- package/src/exceptions/not-found.exception.mts +0 -33
- package/src/exceptions/unauthorized.exception.mts +0 -30
- package/src/factories/adapter.factory.mts +0 -20
- package/src/factories/endpoint-adapter.factory.mts +0 -21
- package/src/factories/http-adapter.factory.mts +0 -20
- package/src/factories/index.mts +0 -8
- package/src/factories/multipart-adapter.factory.mts +0 -21
- package/src/factories/reply.factory.mts +0 -21
- package/src/factories/request.factory.mts +0 -21
- package/src/factories/stream-adapter.factory.mts +0 -20
- package/src/factories/xml-stream-adapter.factory.mts +0 -20
- package/src/index.mts +0 -16
- package/src/interfaces/abstract-adapter.interface.mts +0 -32
- package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
- package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
- package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
- package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
- package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
- package/src/interfaces/adapter-environment.interface.mts +0 -74
- package/src/interfaces/can-activate.mts +0 -38
- package/src/interfaces/http-header.mts +0 -18
- package/src/interfaces/index.mts +0 -14
- package/src/interfaces/navios-module.mts +0 -28
- package/src/interfaces/plugin-context.mts +0 -104
- package/src/interfaces/plugin-stage.mts +0 -62
- package/src/interfaces/plugin.interface.mts +0 -119
- package/src/interfaces/staged-plugin.interface.mts +0 -209
- package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
- package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
- package/src/legacy-compat/attribute.factory.mts +0 -351
- package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
- package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
- package/src/legacy-compat/decorators/header.decorator.mts +0 -43
- package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
- package/src/legacy-compat/decorators/index.mts +0 -11
- package/src/legacy-compat/decorators/module.decorator.mts +0 -37
- package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
- package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
- package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
- package/src/legacy-compat/index.mts +0 -57
- package/src/logger/README.md +0 -3
- package/src/logger/console-logger.service.mts +0 -714
- package/src/logger/index.mts +0 -6
- package/src/logger/log-levels.mts +0 -21
- package/src/logger/logger-service.interface.mts +0 -42
- package/src/logger/logger.service.mts +0 -113
- package/src/logger/logger.tokens.mts +0 -44
- package/src/logger/utils/cli-colors.util.mts +0 -17
- package/src/logger/utils/filter-log-levelts.util.mts +0 -29
- package/src/logger/utils/index.mts +0 -5
- package/src/logger/utils/is-log-level-enabled.mts +0 -33
- package/src/logger/utils/is-log-level.util.mts +0 -10
- package/src/logger/utils/shared.utils.mts +0 -51
- package/src/metadata/controller.metadata.mts +0 -79
- package/src/metadata/handler.metadata.mts +0 -80
- package/src/metadata/index.mts +0 -4
- package/src/metadata/module.metadata.mts +0 -116
- package/src/metadata/navios-managed.metadata.mts +0 -42
- package/src/navios.application.mts +0 -678
- package/src/navios.environment.mts +0 -42
- package/src/navios.factory.mts +0 -158
- package/src/responders/enums/framework-error.enum.mts +0 -38
- package/src/responders/enums/index.mts +0 -1
- package/src/responders/index.mts +0 -4
- package/src/responders/interfaces/error-responder.interface.mts +0 -42
- package/src/responders/interfaces/error-response.interface.mts +0 -22
- package/src/responders/interfaces/index.mts +0 -3
- package/src/responders/interfaces/problem-details.interface.mts +0 -34
- package/src/responders/services/error-response-producer.service.mts +0 -143
- package/src/responders/services/forbidden-responder.service.mts +0 -77
- package/src/responders/services/index.mts +0 -5
- package/src/responders/services/internal-server-error-responder.service.mts +0 -57
- package/src/responders/services/not-found-responder.service.mts +0 -76
- package/src/responders/services/validation-error-responder.service.mts +0 -78
- package/src/responders/tokens/index.mts +0 -1
- package/src/responders/tokens/responder.tokens.mts +0 -84
- package/src/services/abstract-handler-adapter.service.mts +0 -366
- package/src/services/guard-runner.service.mts +0 -152
- package/src/services/index.mts +0 -4
- package/src/services/instance-resolver.service.mts +0 -177
- package/src/services/module-loader.service.mts +0 -255
- package/src/stores/index.mts +0 -1
- package/src/stores/request-id.store.mts +0 -85
- package/src/testing/index.mts +0 -3
- package/src/testing/testing-module.mts +0 -393
- package/src/testing/unit-testing-module.mts +0 -298
- package/src/tokens/adapter.token.mts +0 -6
- package/src/tokens/endpoint-adapter.token.mts +0 -8
- package/src/tokens/execution-context.token.mts +0 -9
- package/src/tokens/http-adapter.token.mts +0 -8
- package/src/tokens/index.mts +0 -10
- package/src/tokens/multipart-adapter.token.mts +0 -8
- package/src/tokens/navios-options.token.mts +0 -6
- package/src/tokens/reply.token.mts +0 -3
- package/src/tokens/request.token.mts +0 -3
- package/src/tokens/stream-adapter.token.mts +0 -8
- package/src/tokens/xml-stream-adapter.token.mts +0 -8
- package/src/utils/adapter-supports.util.mts +0 -47
- package/src/utils/define-plugin.mts +0 -251
- package/src/utils/index.mts +0 -2
- package/tsconfig.json +0 -21
- package/tsconfig.lib.json +0 -8
- package/tsconfig.spec.json +0 -15
- package/tsdown.config.mts +0 -35
- package/vitest.config.mts +0 -15
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"basic-execution-context-u1VktGoM.mjs","names":[],"sources":["../src/transports/transport.mts","../src/metadata/handler-class.mts","../src/metadata/handler-chain.mts","../src/metadata/run-chain.mts","../src/execution/basic-execution-context.mts"],"sourcesContent":["import type { ClassType, Container } from '@navios/di'\n\nimport type { ContextHost } from '../execution/context-host.mjs'\nimport type { OptionsArgument } from '../internal/options-argument.mjs'\nimport type { LoggerService } from '../logger/logger-output.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * What the application gives a transport when it creates it.\n */\nexport interface TransportHost {\n readonly container: Container\n readonly logger: LoggerService\n /** For the transport's execution contexts. */\n readonly contextHost: ContextHost\n /** Whether the application keeps the current context in an async store. */\n readonly asyncContext: boolean\n /**\n * Interceptors around every handler of the application, outermost first.\n * Complete once `setup()` is called.\n */\n readonly interceptors: readonly ClassType[]\n}\n\n/**\n * One way work reaches the application: an HTTP server, a queue consumer, a\n * command line. The application creates it, hands it the module graph, and\n * starts and stops it together with the others.\n */\nexport interface Transport {\n /**\n * Reads the module graph and prepares the transport's handlers. Must not\n * start accepting work.\n */\n setup(graph: readonly ModuleNode[]): void | Promise<void>\n /** Starts accepting work. Called at most once. */\n start?(): void | Promise<void>\n /**\n * Stops accepting work and waits, up to `timeoutMs`, for what is in flight.\n * One that takes much longer is left behind. When the application fails to\n * initialise or to start it is called for every transport that was created,\n * with no time to wait and possibly before `setup` or `start` ran; it must\n * release what `create` acquired. Called once, and again when `start` settles\n * only after that.\n */\n stop(timeoutMs: number): void | Promise<void>\n}\n\nexport interface TransportDefinition<Options, T extends Transport> {\n /** The kind of transport, and the default name of an instance. */\n name: string\n create(host: TransportHost, options: Options): T | Promise<T>\n}\n\n/**\n * A transport as it is listed in an application's options.\n */\nexport interface TransportInstance<T extends Transport = Transport> {\n readonly definition: TransportDefinition<any, T>\n /** `{}` when the transport was given none. */\n readonly options: unknown\n /** Unique within the application. Defaults to the definition's name. */\n readonly instanceName: string\n}\n\n/**\n * What `defineTransport` returns: called with options it gives the instance\n * to list in an application, and it is the key to look the transport up with.\n */\nexport interface TransportFactory<Options, T extends Transport> {\n (...args: OptionsArgument<Options, [instanceName?: string]>): TransportInstance<T>\n readonly definition: TransportDefinition<Options, T>\n}\n\n/**\n * Defines a transport.\n *\n * ```ts\n * export const queueTransport = defineTransport({\n * name: 'queue',\n * create(host, options: { url: string }) {\n * return new QueueTransport(host, options)\n * },\n * })\n *\n * const app = createApplication(AppModule, {\n * transports: [queueTransport({ url })],\n * })\n * await app.start()\n * app.transport(queueTransport) // the QueueTransport\n * ```\n *\n * An application can hold several transports of one definition when each has\n * its own name: `queueTransport({ url }, 'orders')`.\n */\nexport function defineTransport<Options = void, T extends Transport = Transport>(\n definition: TransportDefinition<Options, T>,\n): TransportFactory<Options, T> {\n const factory = (options?: Options, instanceName?: string): TransportInstance<T> => ({\n definition,\n options: options ?? {},\n instanceName: instanceName ?? definition.name,\n })\n return Object.assign(factory, { definition })\n}\n","import type { ClassType } from '@navios/di'\n\nimport { applyAttributes } from '../attributes/attribute-value.mjs'\n\nimport type { AttributeValue } from '../attributes/attribute-value.mjs'\n\nimport { classAttributes, classGuards, classInterceptors, prepend } from './class-metadata.mjs'\nimport { requireMetadata } from './decorator-metadata.mjs'\nimport { MembersKey } from './member-metadata.mjs'\n\nimport type { DecoratorMetadata } from './decorator-metadata.mjs'\nimport type { HandlerExtras, MethodHandlerMetadata } from './member-metadata.mjs'\n\n/** What a transport's decorator for handler classes may take. */\nexport interface HandlerClassOptions {\n guards?: Iterable<ClassType>\n interceptors?: Iterable<ClassType>\n attributes?: AttributeValue[]\n}\n\n/** A class that owns handlers: what applies to all of them, and its members. */\nexport interface HandlerClassMetadata extends HandlerExtras {\n /** The members decorators were applied to, by name. */\n members: Map<string, MethodHandlerMetadata>\n}\n\n/**\n * What decorators attached to a class of handlers and to its members, together\n * with the options of the class decorator that asks. The lists are live:\n * `@UseGuards` and the like placed above that decorator run after it and are\n * still seen.\n */\nexport function describeHandlerClass(\n context: { metadata?: DecoratorMetadata },\n options: HandlerClassOptions = {},\n): HandlerClassMetadata {\n const metadata = requireMetadata(context)\n const attributes = classAttributes(context)\n applyAttributes(attributes, options.attributes)\n return {\n guards: prepend(classGuards(context), options.guards),\n interceptors: prepend(classInterceptors(context), options.interceptors),\n attributes,\n members: (metadata[MembersKey] as Map<string, MethodHandlerMetadata> | undefined) ?? new Map(),\n }\n}\n","import type { ClassType } from '@navios/di'\n\nimport type { HandlerInfo } from '../execution/execution-context.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\ninterface Extras {\n readonly guards: readonly ClassType[]\n readonly interceptors: readonly ClassType[]\n}\n\ninterface OwnExtras extends Extras {\n readonly attributes: ReadonlyMap<symbol, unknown>\n}\n\nexport interface HandlerChainInput {\n /**\n * Interceptors around every handler of the application or of the transport,\n * outermost first.\n */\n application: readonly ClassType[]\n /** The module the handler belongs to, with what it inherits. */\n node: Extras & Pick<ModuleNode, 'module' | 'attributes' | 'disputed'>\n /** The class that owns the handler. */\n controller: ClassType\n /** What applies to every handler of `controller`. */\n owner: OwnExtras\n /** The name of the handler in its class. */\n handlerName: string\n /** The handler itself. */\n member: OwnExtras\n}\n\nexport interface HandlerChain {\n /** What the contexts of the handler tell about it. */\n info: HandlerInfo\n /** Interceptors around the guards: those of the application. */\n outer: ClassType[]\n /** Interceptors inside the guards: those of the module, the class and the handler. */\n inner: ClassType[]\n}\n\n/**\n * An attribute may open the handler to everyone or restrict it, so it is not\n * guessed which of the import paths is meant.\n */\nfunction assertUndisputed({ node, owner, member }: HandlerChainInput): void {\n for (const [key, paths] of node.disputed) {\n if (!owner.attributes.has(key) && !member.attributes.has(key)) {\n throw new Error(\n `[Navios] Module ${node.module.name} inherits different values of the attribute ` +\n `${String(key)}: ${paths}. Set it on the controllers or handlers it is meant for, or ` +\n `on ${node.module.name} itself.`,\n )\n }\n }\n}\n\n/**\n * The guards and interceptors that apply to one handler, in the order they\n * run, and what its contexts tell about it: the interceptors of the\n * application, then the guards from the module chain, the owning class and\n * the handler, then the interceptors of the same three. A class that appears\n * twice is kept where it first appears. `info.guards` are the guards and\n * `info.interceptors` the interceptors, `outer` and then `inner`.\n *\n * An interceptor of the application sees every execution, denied ones\n * included, as tracing and logging need. One that is attached to handlers runs\n * only for what their guards let through.\n *\n * Throws when the handler would inherit an attribute that the importers of its\n * module do not agree about.\n *\n * Every transport uses this, so the rule is the same everywhere.\n * `resolveChain` resolves the chain and `runChain` runs it.\n */\nexport function handlerChain(input: HandlerChainInput): HandlerChain {\n assertUndisputed(input)\n const { application, node, controller, owner, handlerName, member } = input\n const everywhere = new Set(application)\n const attached = [...node.interceptors, ...owner.interceptors, ...member.interceptors]\n const outer = Array.from(everywhere)\n const inner = Array.from(new Set(attached.filter((interceptor) => !everywhere.has(interceptor))))\n return {\n info: {\n module: node.module,\n controller,\n handlerName,\n guards: Array.from(new Set([...node.guards, ...owner.guards, ...member.guards])),\n interceptors: [...outer, ...inner],\n attributes: {\n handler: member.attributes,\n controller: owner.attributes,\n module: node.attributes,\n },\n },\n outer,\n inner,\n }\n}\n","import type { ClassType, Container } from '@navios/di'\n\nimport { runInContext } from '../execution/async-context.mjs'\n\nimport type { ExecutionContext, HandlerInfo } from '../execution/execution-context.mjs'\nimport type { Guard } from '../guards/guard.mjs'\nimport type { Interceptor } from '../interceptors/interceptor.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A handler's chain with its instances, ready to run. */\nexport interface ResolvedChain<Ctx extends ExecutionContext = ExecutionContext, Result = unknown> {\n readonly outer: ReadonlyArray<Interceptor<Ctx, Result>>\n readonly guards: ReadonlyArray<{ readonly type: ClassType; readonly guard: Guard<Ctx> }>\n readonly inner: ReadonlyArray<Interceptor<Ctx, Result>>\n}\n\nasync function resolve(\n container: Pick<Container, 'get'>,\n type: ClassType,\n kind: string,\n method: string,\n): Promise<any> {\n const instance = (await container.get(type)) as any\n if (typeof instance?.[method] !== 'function') {\n throw new Error(`[Navios] ${kind} ${type.name} does not implement ${method}()`)\n }\n return instance\n}\n\n/**\n * Resolves the classes of a chain that `handlerChain` returned. A transport\n * does this once per handler, while it is set up.\n */\nexport async function resolveChain<\n Ctx extends ExecutionContext = ExecutionContext,\n Result = unknown,\n>(\n container: Pick<Container, 'get'>,\n chain: {\n readonly info: Pick<HandlerInfo, 'guards'>\n readonly outer: readonly ClassType[]\n readonly inner: readonly ClassType[]\n },\n): Promise<ResolvedChain<Ctx, Result>> {\n const outer: Interceptor<Ctx, Result>[] = []\n const guards: Array<{ type: ClassType; guard: Guard<Ctx> }> = []\n const inner: Interceptor<Ctx, Result>[] = []\n for (const type of chain.outer) {\n outer.push(await resolve(container, type, 'Interceptor', 'intercept'))\n }\n for (const type of chain.info.guards) {\n guards.push({ type, guard: await resolve(container, type, 'Guard', 'canActivate') })\n }\n for (const type of chain.inner) {\n inner.push(await resolve(container, type, 'Interceptor', 'intercept'))\n }\n return { outer, guards, inner }\n}\n\nfunction intercepted<Ctx extends ExecutionContext, Result>(\n ctx: Ctx,\n interceptors: ReadonlyArray<Interceptor<Ctx, Result>>,\n innermost: () => Result | Promise<Result>,\n): () => Promise<Result> {\n let next = async () => innermost()\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i]\n const inner = next\n next = async () => interceptor.intercept(ctx, inner)\n }\n return next\n}\n\n/**\n * Runs a handler with what applies to it: the outer interceptors, the guards\n * one after another, the inner interceptors, the handler. When a guard refuses,\n * nothing further runs and `onDenied` says what becomes of the execution: what\n * it returns is the result, and what it throws is the failure.\n */\nexport function runChain<Ctx extends ExecutionContext, Result>(\n ctx: Ctx,\n chain: ResolvedChain<Ctx, Result>,\n handler: () => Result | Promise<Result>,\n onDenied: (guard: ClassType) => Result | Promise<Result>,\n): Promise<Result> {\n const guarded = async (): Promise<Result> => {\n for (const { type, guard } of chain.guards) {\n if ((await guard.canActivate(ctx)) !== true) {\n return onDenied(type)\n }\n }\n return intercepted(ctx, chain.inner, handler)()\n }\n return intercepted(ctx, chain.outer, guarded)()\n}\n\n/**\n * Runs a handler with what applies to it, as `runChain`, in the async context\n * when the application keeps one, and then finishes its context, whatever the\n * outcome. The context is finished inside the async context, so that\n * `currentContext()` still answers in `onFinish` callbacks.\n */\nexport function executeChain<Ctx extends ExecutionContext & { finish(): Promise<void> }, Result>(\n host: { readonly asyncContext: boolean },\n ctx: Ctx,\n chain: ResolvedChain<Ctx, Result>,\n handler: () => Result | Promise<Result>,\n onDenied: (guard: ClassType) => Result | Promise<Result>,\n): Promise<Result> {\n const execute = async (): Promise<Result> => {\n try {\n return await runChain(ctx, chain, handler, onDenied)\n } finally {\n await ctx.finish()\n }\n }\n return host.asyncContext ? runInContext(ctx, execute) : execute()\n}\n","import type { AnyInjectableType, Container, ScopedContainer } from '@navios/di'\n\nimport { needsScope } from './context-host.mjs'\nimport { ExecutionContextToken } from './execution-context-token.mjs'\n\nimport type { ContextHost } from './context-host.mjs'\nimport type { ContextKey, ContextValue } from './context-key.mjs'\nimport type { ExecutionContext, HandlerInfo } from './execution-context.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface BasicExecutionContextInit {\n /** The transport kind, for example `'cli'`. */\n kind: string\n id: string\n handler: HandlerInfo\n host: ContextHost\n}\n\n/**\n * An `ExecutionContext` for transports that need nothing beyond the neutral\n * contract. The transport creates one per execution and calls `finish()` when\n * the handler is done.\n */\nexport class BasicExecutionContext implements ExecutionContext {\n readonly kind: string\n readonly id: string\n readonly handler: HandlerInfo\n private readonly host: ContextHost\n private ownSignal: AbortSignal | null = null\n private slots: Map<ContextKey, unknown> | null = null\n private scope: ScopedContainer | null = null\n private finishers: Array<() => void | Promise<void>> | null = null\n private finished = false\n private finishing: Promise<void> | null = null\n\n constructor(init: BasicExecutionContextInit) {\n this.kind = init.kind\n this.id = init.id\n this.handler = init.handler\n this.host = init.host\n }\n\n /**\n * A signal that never aborts. Not shared between contexts: listeners would\n * outlive their execution.\n */\n get signal(): AbortSignal {\n return (this.ownSignal ??= new AbortController().signal)\n }\n\n get<K extends ContextKey>(key: K): ContextValue<K> {\n const slots = this.slots\n if (slots === null || !slots.has(key)) {\n throw new Error(\n `[Navios] Context key ${key.name} is not set. ` +\n `Set it with ctx.set() (usually in a guard), or read it with ctx.find().`,\n )\n }\n return slots.get(key) as ContextValue<K>\n }\n\n find<K extends ContextKey>(key: K): ContextValue<K> | undefined {\n return this.slots?.get(key) as ContextValue<K> | undefined\n }\n\n set<K extends ContextKey>(key: K, value: ContextValue<K>): void {\n ;(this.slots ??= new Map()).set(key, value)\n }\n\n has(key: ContextKey): boolean {\n return this.slots?.has(key) ?? false\n }\n\n /**\n * What resolves a token for this execution: its DI scope, which is created\n * when something needs it.\n * @internal\n */\n resolverFor(token: AnyInjectableType): Container | ScopedContainer {\n const { container, onScopedUse } = this.host\n if (this.scope !== null && onScopedUse === null) {\n return this.scope\n }\n if (!needsScope(container, token)) {\n return this.scope ?? container\n }\n onScopedUse?.(token)\n if (this.scope === null) {\n if (this.finished) {\n throw new Error(\n '[Navios] Request-scoped services cannot be used: the execution has finished, so ' +\n 'nothing would dispose them.',\n )\n }\n this.scope = container.createScope()\n this.scope.addInstance(ExecutionContextToken, this)\n }\n return this.scope\n }\n\n declare use: ScopedContainer['getSync']\n\n declare resolve: ScopedContainer['get']\n\n onFinish(callback: () => void | Promise<void>): void {\n if (this.finished) {\n void this.runFinisher(callback)\n return\n }\n ;(this.finishers ??= []).push(callback)\n }\n\n /**\n * Runs the `onFinish` callbacks in reverse order, those they register\n * included, then disposes the DI scope. Runs once, however often it is\n * called; every caller waits for that run.\n */\n finish(): Promise<void> {\n return (this.finishing ??= this.runFinishers())\n }\n\n private async runFinishers(): Promise<void> {\n let finisher: (() => void | Promise<void>) | undefined\n while ((finisher = this.finishers?.pop()) !== undefined) {\n await this.runFinisher(finisher)\n }\n this.finished = true\n this.ownSignal = null\n const scope = this.scope\n this.scope = null\n if (scope !== null) {\n await scope.dispose()\n }\n }\n\n /** Runs a callback whose failure must not stop what follows. */\n private async runFinisher(callback: () => void | Promise<void>): Promise<void> {\n try {\n await callback()\n } catch (error) {\n // A failing callback must not stop the others, so it is only reported.\n try {\n this.host.logger?.error(`Error in an onFinish callback of ${this.kind} ${this.id}`, error)\n } catch {\n // Nor may a failing logger.\n }\n }\n }\n}\n\nBasicExecutionContext.prototype.use = function use(\n this: BasicExecutionContext,\n token: AnyInjectableType,\n args?: unknown,\n) {\n return (this.resolverFor(token).getSync as any)(token, args)\n} as ScopedContainer['getSync']\n\nBasicExecutionContext.prototype.resolve = function resolve(\n this: BasicExecutionContext,\n token: AnyInjectableType,\n args?: unknown,\n) {\n return (this.resolverFor(token).get as any)(token, args)\n} as ScopedContainer['get']\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiGA,SAAgB,gBACd,YAC8B;CAC9B,MAAM,WAAW,SAAmB,kBAAiD;EACnF;EACA,SAAS,WAAW,CAAC;EACrB,cAAc,gBAAgB,WAAW;CAC3C;CACA,OAAO,OAAO,OAAO,SAAS,EAAE,WAAW,CAAC;AAC9C;;;;;;;;AC1EA,SAAgB,qBACd,SACA,UAA+B,CAAC,GACV;CACtB,MAAM,WAAW,gBAAgB,OAAO;CACxC,MAAM,aAAa,gBAAgB,OAAO;CAC1C,gBAAgB,YAAY,QAAQ,UAAU;CAC9C,OAAO;EACL,QAAQ,QAAQ,YAAY,OAAO,GAAG,QAAQ,MAAM;EACpD,cAAc,QAAQ,kBAAkB,OAAO,GAAG,QAAQ,YAAY;EACtE;EACA,SAAU,SAAS,+BAAkE,IAAI,IAAI;CAC/F;AACF;;;;;;ACAA,SAAS,iBAAiB,EAAE,MAAM,OAAO,UAAmC;CAC1E,KAAK,MAAM,CAAC,KAAK,UAAU,KAAK,UAC9B,IAAI,CAAC,MAAM,WAAW,IAAI,GAAG,KAAK,CAAC,OAAO,WAAW,IAAI,GAAG,GAC1D,MAAM,IAAI,MACR,mBAAmB,KAAK,OAAO,KAAK,8CAC/B,OAAO,GAAG,EAAE,IAAI,MAAM,iEACnB,KAAK,OAAO,KAAK,SAC3B;AAGN;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,aAAa,OAAwC;CACnE,iBAAiB,KAAK;C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AS;EACjB,SAAS,OAAO;GAEd,IAAI;IACF,KAAK,KAAK,QAAQ,MAAM,oCAAoC,KAAK,KAAK,GAAG,KAAK,MAAM,KAAK;GAC3F,QAAQ,CAER;EACF;CACF;AACF;AAEA,sBAAsB,UAAU,MAAM,SAAS,IAE7C,OACA,MACA;CACA,OAAQ,KAAK,YAAY,KAAK,CAAC,CAAC,QAAgB,OAAO,IAAI;AAC7D;AAEA,sBAAsB,UAAU,UAAU,SAAS,QAEjD,OACA,MACA;CACA,OAAQ,KAAK,YAAY,KAAK,CAAC,CAAC,IAAY,OAAO,IAAI;AACzD"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { ClassType, ScopedContainer } from "@navios/di";
|
|
2
|
+
/**
|
|
3
|
+
* A typed slot in an execution context. Something sets it (usually a guard),
|
|
4
|
+
* and reading it before that throws.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* export const CurrentUser = createContextKey<User>('CurrentUser')
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
declare class PlainContextKey<T> {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly __type: T;
|
|
13
|
+
constructor(name: string);
|
|
14
|
+
toString(): string;
|
|
15
|
+
}
|
|
16
|
+
declare function createContextKey<T>(name: string): PlainContextKey<T>;
|
|
17
|
+
/** A key every transport's context accepts. */
|
|
18
|
+
type ContextKey<T = any> = PlainContextKey<T>;
|
|
19
|
+
/**
|
|
20
|
+
* The type `ctx.get(key)` returns: a plain key's type, or, for a key that is
|
|
21
|
+
* a class whose instances compute the value with `resolve`, what `resolve`
|
|
22
|
+
* returns (a promise when it returns a thenable). A transport decides whether
|
|
23
|
+
* it accepts such classes as keys.
|
|
24
|
+
*/
|
|
25
|
+
type ContextValue<K> = K extends PlainContextKey<infer T> ? T : K extends (new () => {
|
|
26
|
+
resolve(ctx: any): infer R;
|
|
27
|
+
}) ? ResolvedValue<R> : never;
|
|
28
|
+
type ResolvedValue<R> = R extends Promise<any> ? R : R extends PromiseLike<infer T> ? Promise<T> : R;
|
|
29
|
+
type AttributeMap = ReadonlyMap<symbol, unknown>;
|
|
30
|
+
/**
|
|
31
|
+
* The handler a context belongs to, the same for every transport: where it
|
|
32
|
+
* is declared and what applies to it.
|
|
33
|
+
*/
|
|
34
|
+
interface HandlerInfo {
|
|
35
|
+
readonly module: ClassType;
|
|
36
|
+
/** The class that owns the handler. */
|
|
37
|
+
readonly controller: ClassType;
|
|
38
|
+
readonly handlerName: string;
|
|
39
|
+
readonly guards: readonly ClassType[];
|
|
40
|
+
readonly interceptors: readonly ClassType[];
|
|
41
|
+
readonly attributes: {
|
|
42
|
+
readonly handler: AttributeMap;
|
|
43
|
+
readonly controller: AttributeMap;
|
|
44
|
+
readonly module: AttributeMap;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* What every transport's context offers. A guard, interceptor or service
|
|
49
|
+
* written against this works on any transport.
|
|
50
|
+
*/
|
|
51
|
+
interface ExecutionContext {
|
|
52
|
+
/** The transport kind, for example `'http'`. */
|
|
53
|
+
readonly kind: string;
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly signal: AbortSignal;
|
|
56
|
+
readonly handler: HandlerInfo;
|
|
57
|
+
/** Reads a slot; throws when a plain key is not set. */
|
|
58
|
+
get<K extends ContextKey>(key: K): ContextValue<K>;
|
|
59
|
+
/** Like `get`, but `undefined` for a plain key that is not set. */
|
|
60
|
+
find<K extends ContextKey>(key: K): ContextValue<K> | undefined;
|
|
61
|
+
set<K extends ContextKey>(key: K, value: ContextValue<K>): void;
|
|
62
|
+
has(key: ContextKey): boolean;
|
|
63
|
+
/** Resolves a service from this execution's DI scope, synchronously. */
|
|
64
|
+
use: ScopedContainer['getSync'];
|
|
65
|
+
/** Resolves a service from this execution's DI scope. */
|
|
66
|
+
resolve: ScopedContainer['get'];
|
|
67
|
+
/** Runs `callback` after the handler has finished, whatever the outcome. */
|
|
68
|
+
onFinish(callback: () => void | Promise<void>): void;
|
|
69
|
+
}
|
|
70
|
+
export { ContextValue as a, ContextKey as i, ExecutionContext as n, PlainContextKey as o, HandlerInfo as r, createContextKey as s, AttributeMap as t };
|
|
71
|
+
//# sourceMappingURL=execution-context-BVSmLkYp.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-BVSmLkYp.d.cts","names":[],"sources":["../src/execution/context-key.mts","../src/execution/execution-context.mts"],"mappings":";;;;;;;;;cAUa,gBAAgB;WAGC;WAFX,QAAQ;EAEzB,YAA4B;EAE5B;;iBAKc,iBAAiB,GAAG,eAAe,gBAAgB;;KAKvD,WAAW,WAAW,gBAAgB;;;;;;;KAQtC,aAAa,KACvB,UAAU,sBAAsB,KAC5B,IACA;EAAsB,QAAQ,iBAAiB;KAC7C,cAAc;KAGjB,cAAc,KAAK,UAAU,eAAe,IAAI,UAAU,kBAAkB,KAAK,QAAQ,KAAK;KCpCvF,eAAe;;;;;UAMV;WACN,QAAQ;;WAER,YAAY;WACZ;WACA,iBAAiB;WACjB,uBAAuB;WACvB;aACE,SAAS;aACT,YAAY;aACZ,QAAQ;;;;;;;UAQJ;;WAEN;WACA;WACA,QAAQ;WACR,SAAS;;EAElB,IAAI,UAAU,YAAY,KAAK,IAAI,aAAa;;EAEhD,KAAK,UAAU,YAAY,KAAK,IAAI,aAAa;EACjD,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,aAAa;EACtD,IAAI,KAAK;;EAET,KAAK;;EAEL,SAAS;;EAET,SAAS,uBAAuB"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { ClassType, ScopedContainer } from "@navios/di";
|
|
2
|
+
/**
|
|
3
|
+
* A typed slot in an execution context. Something sets it (usually a guard),
|
|
4
|
+
* and reading it before that throws.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* export const CurrentUser = createContextKey<User>('CurrentUser')
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
declare class PlainContextKey<T> {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly __type: T;
|
|
13
|
+
constructor(name: string);
|
|
14
|
+
toString(): string;
|
|
15
|
+
}
|
|
16
|
+
declare function createContextKey<T>(name: string): PlainContextKey<T>;
|
|
17
|
+
/** A key every transport's context accepts. */
|
|
18
|
+
type ContextKey<T = any> = PlainContextKey<T>;
|
|
19
|
+
/**
|
|
20
|
+
* The type `ctx.get(key)` returns: a plain key's type, or, for a key that is
|
|
21
|
+
* a class whose instances compute the value with `resolve`, what `resolve`
|
|
22
|
+
* returns (a promise when it returns a thenable). A transport decides whether
|
|
23
|
+
* it accepts such classes as keys.
|
|
24
|
+
*/
|
|
25
|
+
type ContextValue<K> = K extends PlainContextKey<infer T> ? T : K extends (new () => {
|
|
26
|
+
resolve(ctx: any): infer R;
|
|
27
|
+
}) ? ResolvedValue<R> : never;
|
|
28
|
+
type ResolvedValue<R> = R extends Promise<any> ? R : R extends PromiseLike<infer T> ? Promise<T> : R;
|
|
29
|
+
type AttributeMap = ReadonlyMap<symbol, unknown>;
|
|
30
|
+
/**
|
|
31
|
+
* The handler a context belongs to, the same for every transport: where it
|
|
32
|
+
* is declared and what applies to it.
|
|
33
|
+
*/
|
|
34
|
+
interface HandlerInfo {
|
|
35
|
+
readonly module: ClassType;
|
|
36
|
+
/** The class that owns the handler. */
|
|
37
|
+
readonly controller: ClassType;
|
|
38
|
+
readonly handlerName: string;
|
|
39
|
+
readonly guards: readonly ClassType[];
|
|
40
|
+
readonly interceptors: readonly ClassType[];
|
|
41
|
+
readonly attributes: {
|
|
42
|
+
readonly handler: AttributeMap;
|
|
43
|
+
readonly controller: AttributeMap;
|
|
44
|
+
readonly module: AttributeMap;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* What every transport's context offers. A guard, interceptor or service
|
|
49
|
+
* written against this works on any transport.
|
|
50
|
+
*/
|
|
51
|
+
interface ExecutionContext {
|
|
52
|
+
/** The transport kind, for example `'http'`. */
|
|
53
|
+
readonly kind: string;
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly signal: AbortSignal;
|
|
56
|
+
readonly handler: HandlerInfo;
|
|
57
|
+
/** Reads a slot; throws when a plain key is not set. */
|
|
58
|
+
get<K extends ContextKey>(key: K): ContextValue<K>;
|
|
59
|
+
/** Like `get`, but `undefined` for a plain key that is not set. */
|
|
60
|
+
find<K extends ContextKey>(key: K): ContextValue<K> | undefined;
|
|
61
|
+
set<K extends ContextKey>(key: K, value: ContextValue<K>): void;
|
|
62
|
+
has(key: ContextKey): boolean;
|
|
63
|
+
/** Resolves a service from this execution's DI scope, synchronously. */
|
|
64
|
+
use: ScopedContainer['getSync'];
|
|
65
|
+
/** Resolves a service from this execution's DI scope. */
|
|
66
|
+
resolve: ScopedContainer['get'];
|
|
67
|
+
/** Runs `callback` after the handler has finished, whatever the outcome. */
|
|
68
|
+
onFinish(callback: () => void | Promise<void>): void;
|
|
69
|
+
}
|
|
70
|
+
export { ContextValue as a, ContextKey as i, ExecutionContext as n, PlainContextKey as o, HandlerInfo as r, createContextKey as s, AttributeMap as t };
|
|
71
|
+
//# sourceMappingURL=execution-context-C5F9rojO.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-C5F9rojO.d.mts","names":[],"sources":["../src/execution/context-key.mts","../src/execution/execution-context.mts"],"mappings":";;;;;;;;;cAUa,gBAAgB;WAGC;WAFX,QAAQ;EAEzB,YAA4B;EAE5B;;iBAKc,iBAAiB,GAAG,eAAe,gBAAgB;;KAKvD,WAAW,WAAW,gBAAgB;;;;;;;KAQtC,aAAa,KACvB,UAAU,sBAAsB,KAC5B,IACA;EAAsB,QAAQ,iBAAiB;KAC7C,cAAc;KAGjB,cAAc,KAAK,UAAU,eAAe,IAAI,UAAU,kBAAkB,KAAK,QAAQ,KAAK;KCpCvF,eAAe;;;;;UAMV;WACN,QAAQ;;WAER,YAAY;WACZ;WACA,iBAAiB;WACjB,uBAAuB;WACvB;aACE,SAAS;aACT,YAAY;aACZ,QAAQ;;;;;;;UAQJ;;WAEN;WACA;WACA,QAAQ;WACR,SAAS;;EAElB,IAAI,UAAU,YAAY,KAAK,IAAI,aAAa;;EAEhD,KAAK,UAAU,YAAY,KAAK,IAAI,aAAa;EACjD,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,aAAa;EACtD,IAAI,KAAK;;EAET,KAAK;;EAEL,SAAS;;EAET,SAAS,uBAAuB"}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
const require_attribute_value = require("./attribute-value-Cux5HhOL.cjs");
|
|
2
|
+
let _navios_di = require("@navios/di");
|
|
3
|
+
let node_util = require("node:util");
|
|
4
|
+
// src/execution/async-context.mts
|
|
5
|
+
let storage = null;
|
|
6
|
+
/**
|
|
7
|
+
* Turns on the async context: one `AsyncLocalStorage` holding the current
|
|
8
|
+
* `ExecutionContext`. The `asyncContext: true` option of an application does it.
|
|
9
|
+
*/
|
|
10
|
+
async function enableAsyncContext() {
|
|
11
|
+
if (storage === null) {
|
|
12
|
+
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
13
|
+
storage = new AsyncLocalStorage();
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Runs `fn` with `ctx` as the current context. A transport does this when its
|
|
18
|
+
* host says that the application has an async context.
|
|
19
|
+
*/
|
|
20
|
+
function runInContext(ctx, fn) {
|
|
21
|
+
return storage === null ? fn() : storage.run(ctx, fn);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The context of the handler being run, for code that cannot receive it as an
|
|
25
|
+
* argument. Returns `undefined` outside a handler, and always when the
|
|
26
|
+
* application was not created with `asyncContext: true`.
|
|
27
|
+
*/
|
|
28
|
+
function currentContext() {
|
|
29
|
+
return storage?.getStore();
|
|
30
|
+
}
|
|
31
|
+
// src/execution/context-host.mts
|
|
32
|
+
function tokenName(token) {
|
|
33
|
+
return typeof token === "function" ? token.name : String(token);
|
|
34
|
+
}
|
|
35
|
+
/** The token itself, without the args that are bound to it. */
|
|
36
|
+
function plainToken(token) {
|
|
37
|
+
return token instanceof _navios_di.BoundInjectionToken || token instanceof _navios_di.FactoryInjectionToken ? token.token : token;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Whether a context resolves `token` from a DI scope of its execution. A
|
|
41
|
+
* singleton is the same in all of them.
|
|
42
|
+
*/
|
|
43
|
+
function needsScope(container, token) {
|
|
44
|
+
return container.getProvider(token)?.scope !== _navios_di.InjectableScope.Singleton;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Builds the host for an application's contexts, applying its policy for
|
|
48
|
+
* request-scoped services.
|
|
49
|
+
*/
|
|
50
|
+
function createContextHost(container, mode, logger) {
|
|
51
|
+
if (mode === "allow") return {
|
|
52
|
+
container,
|
|
53
|
+
onScopedUse: null,
|
|
54
|
+
logger
|
|
55
|
+
};
|
|
56
|
+
const seen = /* @__PURE__ */ new Set();
|
|
57
|
+
return {
|
|
58
|
+
container,
|
|
59
|
+
logger,
|
|
60
|
+
onScopedUse: (used) => {
|
|
61
|
+
const token = plainToken(used);
|
|
62
|
+
if (mode === "forbid") throw new Error(`[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this application forbids request-scoped services (requestScopedServices: 'forbid'). Keep per-execution data in a context key instead.`);
|
|
63
|
+
if (!seen.has(token)) {
|
|
64
|
+
seen.add(token);
|
|
65
|
+
logger.warn(`${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). If it only carries data derived from the context, a context key is cheaper and needs no DI scope. Set requestScopedServices: 'allow' to silence this.`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
// src/modules/module-graph.mts
|
|
71
|
+
/**
|
|
72
|
+
* The classes a module lists under one of the options of a transport, once
|
|
73
|
+
* each. Throws for an entry that is not a class: what an import cycle between
|
|
74
|
+
* the files of two classes leaves behind.
|
|
75
|
+
*/
|
|
76
|
+
function moduleClasses(node, entry) {
|
|
77
|
+
const listed = node.entries.get(entry);
|
|
78
|
+
if (!listed) return [];
|
|
79
|
+
const classes = Array.from(new Set(listed));
|
|
80
|
+
const index = classes.findIndex((listedClass) => typeof listedClass !== "function");
|
|
81
|
+
if (index !== -1) throw new Error(`[Navios] Module ${node.module.name} lists ${String(classes[index])} in ${entry}. When it should be a class, the files of the two usually import each other.`);
|
|
82
|
+
return classes;
|
|
83
|
+
}
|
|
84
|
+
function names(path) {
|
|
85
|
+
return path.map((module) => module.name).join(" -> ");
|
|
86
|
+
}
|
|
87
|
+
/** One way to a module from a root, the module included. */
|
|
88
|
+
function pathTo(node) {
|
|
89
|
+
const path = [node.module];
|
|
90
|
+
for (let at = node; !at.isRoot && at.importers.length > 0;) {
|
|
91
|
+
at = at.importers[0];
|
|
92
|
+
path.unshift(at.module);
|
|
93
|
+
}
|
|
94
|
+
return path;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Gives a module the attributes it inherits. Guards add up over several import
|
|
98
|
+
* paths, which is safe; attributes cannot. One that opens a handler and one that
|
|
99
|
+
* restricts it would each be wrong if it applied because of one path alone, so
|
|
100
|
+
* the paths have to agree where a handler inherits it.
|
|
101
|
+
*/
|
|
102
|
+
function inheritAttributes(draft, importers) {
|
|
103
|
+
const { node, metadata, disagreements } = draft;
|
|
104
|
+
const keys = new Set(importers.flatMap((importer) => [...importer.node.attributes.keys(), ...importer.disagreements.keys()]));
|
|
105
|
+
for (const key of keys) {
|
|
106
|
+
if (metadata.attributes.has(key)) continue;
|
|
107
|
+
const inherited = importers.find((importer) => importer.disagreements.has(key));
|
|
108
|
+
if (inherited) {
|
|
109
|
+
const { one, other, otherHasValue } = inherited.disagreements.get(key);
|
|
110
|
+
disagreements.set(key, {
|
|
111
|
+
one: [...one, node.module],
|
|
112
|
+
other: [...other, node.module],
|
|
113
|
+
otherHasValue
|
|
114
|
+
});
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const source = importers.find((importer) => importer.node.attributes.has(key));
|
|
118
|
+
const value = source.node.attributes.get(key);
|
|
119
|
+
const disagrees = (importer) => !importer.node.attributes.has(key) || !(0, node_util.isDeepStrictEqual)(importer.node.attributes.get(key), value);
|
|
120
|
+
const other = importers.find(disagrees);
|
|
121
|
+
if (other === void 0 && !node.isRoot) node.attributes.set(key, value);
|
|
122
|
+
else disagreements.set(key, {
|
|
123
|
+
one: [...pathTo(source.node), node.module],
|
|
124
|
+
other: other === void 0 ? [node.module] : [...pathTo(other.node), node.module],
|
|
125
|
+
otherHasValue: other !== void 0 && other.node.attributes.has(key)
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
node.disputed = new Map(Array.from(disagreements, ([key, value]) => [key, described(value)]));
|
|
129
|
+
}
|
|
130
|
+
function described({ one, other, otherHasValue }) {
|
|
131
|
+
return `one over ${names(one)}, ${otherHasValue ? "another" : "none"} over ${names(other)}`;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Walks the import graph from the given roots and computes, for this
|
|
135
|
+
* application only, what applies to each module.
|
|
136
|
+
*
|
|
137
|
+
* - Guards and interceptors are the union over every path that reaches a
|
|
138
|
+
* module, outermost first: what the importers contribute, importers in
|
|
139
|
+
* import order, then the module's own. Nothing is written back to the
|
|
140
|
+
* classes, so two applications importing one module under different parents
|
|
141
|
+
* do not affect each other.
|
|
142
|
+
* - An attribute comes from the module itself or else from what imports it.
|
|
143
|
+
* One that the importers do not agree about is in `disputed` instead.
|
|
144
|
+
*
|
|
145
|
+
* Neither depends on the order in which a module happens to be reached.
|
|
146
|
+
* Modules are returned in dependency order: a module comes after everything
|
|
147
|
+
* it imports. That cannot be done for modules that import each other, which is
|
|
148
|
+
* an error as well.
|
|
149
|
+
*/
|
|
150
|
+
function buildModuleGraph(roots) {
|
|
151
|
+
const drafts = /* @__PURE__ */ new Map();
|
|
152
|
+
const order = [];
|
|
153
|
+
const path = [];
|
|
154
|
+
const visit = (module, importer) => {
|
|
155
|
+
const known = drafts.get(module);
|
|
156
|
+
if (known) {
|
|
157
|
+
if (known.open) throw new Error(`[Navios] Modules import each other in a cycle: ` + names([...path.slice(path.indexOf(module)), module]));
|
|
158
|
+
if (importer && !known.node.importers.includes(importer)) known.node.importers.push(importer);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const metadata = require_attribute_value.getModuleMetadata(module);
|
|
162
|
+
const node = {
|
|
163
|
+
module,
|
|
164
|
+
providers: metadata.providers,
|
|
165
|
+
entries: metadata.entries,
|
|
166
|
+
guards: [],
|
|
167
|
+
interceptors: [],
|
|
168
|
+
attributes: /* @__PURE__ */ new Map(),
|
|
169
|
+
disputed: /* @__PURE__ */ new Map(),
|
|
170
|
+
importers: importer ? [importer] : [],
|
|
171
|
+
isRoot: false
|
|
172
|
+
};
|
|
173
|
+
const draft = {
|
|
174
|
+
node,
|
|
175
|
+
metadata,
|
|
176
|
+
disagreements: /* @__PURE__ */ new Map(),
|
|
177
|
+
open: true,
|
|
178
|
+
ranked: false
|
|
179
|
+
};
|
|
180
|
+
drafts.set(module, draft);
|
|
181
|
+
path.push(module);
|
|
182
|
+
for (const imported of metadata.imports) visit(imported, node);
|
|
183
|
+
path.pop();
|
|
184
|
+
draft.open = false;
|
|
185
|
+
order.push(node);
|
|
186
|
+
};
|
|
187
|
+
for (const root of roots) {
|
|
188
|
+
visit(root, null);
|
|
189
|
+
drafts.get(root).node.isRoot = true;
|
|
190
|
+
}
|
|
191
|
+
const outermostFirst = [];
|
|
192
|
+
const rank = (draft) => {
|
|
193
|
+
if (draft.ranked) return;
|
|
194
|
+
draft.ranked = true;
|
|
195
|
+
const imports = draft.metadata.imports;
|
|
196
|
+
for (let i = imports.length - 1; i >= 0; i--) rank(drafts.get(imports[i]));
|
|
197
|
+
outermostFirst.push(draft);
|
|
198
|
+
};
|
|
199
|
+
for (let i = roots.length - 1; i >= 0; i--) rank(drafts.get(roots[i]));
|
|
200
|
+
outermostFirst.reverse();
|
|
201
|
+
for (const draft of outermostFirst) {
|
|
202
|
+
const { node, metadata } = draft;
|
|
203
|
+
require_attribute_value.addMissing(node.guards, metadata.guards);
|
|
204
|
+
require_attribute_value.addMissing(node.interceptors, metadata.interceptors);
|
|
205
|
+
inheritAttributes(draft, node.importers.map((importer) => drafts.get(importer.module)));
|
|
206
|
+
for (const [key, value] of metadata.attributes) node.attributes.set(key, value);
|
|
207
|
+
for (const imported of metadata.imports) {
|
|
208
|
+
const child = drafts.get(imported);
|
|
209
|
+
require_attribute_value.addMissing(child.node.guards, node.guards);
|
|
210
|
+
require_attribute_value.addMissing(child.node.interceptors, node.interceptors);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return order;
|
|
214
|
+
}
|
|
215
|
+
// src/execution/execution-context-token.mts
|
|
216
|
+
/**
|
|
217
|
+
* The context of the current execution, on any transport. Injectable in
|
|
218
|
+
* request-scoped services.
|
|
219
|
+
*/
|
|
220
|
+
const ExecutionContextToken = _navios_di.InjectionToken.create("ExecutionContext", { scope: _navios_di.InjectableScope.Request });
|
|
221
|
+
Object.defineProperty(exports, "ExecutionContextToken", {
|
|
222
|
+
enumerable: true,
|
|
223
|
+
get: function() {
|
|
224
|
+
return ExecutionContextToken;
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
Object.defineProperty(exports, "buildModuleGraph", {
|
|
228
|
+
enumerable: true,
|
|
229
|
+
get: function() {
|
|
230
|
+
return buildModuleGraph;
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
Object.defineProperty(exports, "createContextHost", {
|
|
234
|
+
enumerable: true,
|
|
235
|
+
get: function() {
|
|
236
|
+
return createContextHost;
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
Object.defineProperty(exports, "currentContext", {
|
|
240
|
+
enumerable: true,
|
|
241
|
+
get: function() {
|
|
242
|
+
return currentContext;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
Object.defineProperty(exports, "enableAsyncContext", {
|
|
246
|
+
enumerable: true,
|
|
247
|
+
get: function() {
|
|
248
|
+
return enableAsyncContext;
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
Object.defineProperty(exports, "moduleClasses", {
|
|
252
|
+
enumerable: true,
|
|
253
|
+
get: function() {
|
|
254
|
+
return moduleClasses;
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
Object.defineProperty(exports, "needsScope", {
|
|
258
|
+
enumerable: true,
|
|
259
|
+
get: function() {
|
|
260
|
+
return needsScope;
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
Object.defineProperty(exports, "runInContext", {
|
|
264
|
+
enumerable: true,
|
|
265
|
+
get: function() {
|
|
266
|
+
return runInContext;
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
//# sourceMappingURL=execution-context-token--cKS4cJv.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-token--cKS4cJv.cjs","names":["BoundInjectionToken","FactoryInjectionToken","InjectableScope","isDeepStrictEqual","getModuleMetadata","addMissing","InjectionToken","InjectableScope"],"sources":["../src/execution/async-context.mts","../src/execution/context-host.mts","../src/modules/module-graph.mts","../src/execution/execution-context-token.mts"],"sourcesContent":["import type { ExecutionContext } from './execution-context.mjs'\n\ninterface Storage {\n run<R>(store: ExecutionContext, fn: () => R): R\n getStore(): ExecutionContext | undefined\n}\n\nlet storage: Storage | null = null\n\n/**\n * Turns on the async context: one `AsyncLocalStorage` holding the current\n * `ExecutionContext`. The `asyncContext: true` option of an application does it.\n */\nexport async function enableAsyncContext(): Promise<void> {\n if (storage === null) {\n const { AsyncLocalStorage } = await import('node:async_hooks')\n storage = new AsyncLocalStorage<ExecutionContext>()\n }\n}\n\n/**\n * Runs `fn` with `ctx` as the current context. A transport does this when its\n * host says that the application has an async context.\n */\nexport function runInContext<R>(ctx: ExecutionContext, fn: () => R): R {\n return storage === null ? fn() : storage.run(ctx, fn)\n}\n\n/**\n * The context of the handler being run, for code that cannot receive it as an\n * argument. Returns `undefined` outside a handler, and always when the\n * application was not created with `asyncContext: true`.\n */\nexport function currentContext(): ExecutionContext | undefined {\n return storage?.getStore()\n}\n","import { BoundInjectionToken, FactoryInjectionToken, InjectableScope } from '@navios/di'\n\nimport type { AnyInjectableType, ClassType, Container, InjectionToken } from '@navios/di'\n\nimport type { LoggerService } from '../logger/logger-output.mjs'\n\n/**\n * Dependencies shared by every execution context of an application.\n */\nexport interface ContextHost {\n readonly container: Container\n /**\n * Called when a context resolves a token that `needsScope` is true for; may\n * throw.\n */\n onScopedUse: ((token: AnyInjectableType) => void) | null\n /** Receives what an `onFinish` callback throws; without it that is dropped. */\n readonly logger?: Pick<LoggerService, 'error'>\n}\n\nfunction tokenName(token: unknown): string {\n return typeof token === 'function' ? token.name : String(token)\n}\n\ntype PlainToken = ClassType | InjectionToken<unknown, unknown>\n\n/** The token itself, without the args that are bound to it. */\nfunction plainToken(token: AnyInjectableType): PlainToken {\n return (\n token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken\n ? token.token\n : token\n ) as PlainToken\n}\n\n/**\n * Whether a context resolves `token` from a DI scope of its execution. A\n * singleton is the same in all of them.\n */\nexport function needsScope(container: Container, token: AnyInjectableType): boolean {\n return container.getProvider(token)?.scope !== InjectableScope.Singleton\n}\n\n/**\n * Builds the host for an application's contexts, applying its policy for\n * request-scoped services.\n */\nexport function createContextHost(\n container: Container,\n mode: 'allow' | 'warn' | 'forbid',\n logger: LoggerService,\n): ContextHost {\n if (mode === 'allow') {\n return { container, onScopedUse: null, logger }\n }\n const seen = new Set<PlainToken>()\n return {\n container,\n logger,\n onScopedUse: (used) => {\n const token = plainToken(used)\n if (mode === 'forbid') {\n throw new Error(\n `[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this ` +\n `application forbids request-scoped services (requestScopedServices: 'forbid'). ` +\n `Keep per-execution data in a context key instead.`,\n )\n }\n if (!seen.has(token)) {\n seen.add(token)\n logger.warn(\n `${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). ` +\n `If it only carries data derived from the context, a context key is cheaper and ` +\n `needs no DI scope. Set requestScopedServices: 'allow' to silence this.`,\n )\n }\n },\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\n\nimport type { ClassType, Provider } from '@navios/di'\n\nimport { addMissing } from '../metadata/class-metadata.mjs'\n\nimport { getModuleMetadata } from './module-metadata.mjs'\n\nimport type { ModuleMetadata } from './module-metadata.mjs'\n\n/**\n * A module as it applies to one application: its guards, interceptors and\n * attributes together with those it inherits, and the modules that import it.\n */\nexport interface ModuleNode {\n module: ClassType\n providers: Provider[]\n /** The module's transport-specific options, by option name. */\n entries: ReadonlyMap<string, unknown>\n guards: ClassType[]\n interceptors: ClassType[]\n attributes: Map<symbol, unknown>\n /**\n * The attributes that the importers of the module do not agree about, and what\n * each of two import paths gives it. They are not among `attributes`;\n * `handlerChain` refuses a handler that would inherit one.\n */\n disputed: ReadonlyMap<symbol, string>\n /** The modules that import this one, in the order they were reached. */\n importers: ModuleNode[]\n /** Whether the module was given to the application directly. */\n isRoot: boolean\n}\n\n/**\n * The classes a module lists under one of the options of a transport, once\n * each. Throws for an entry that is not a class: what an import cycle between\n * the files of two classes leaves behind.\n */\nexport function moduleClasses(\n node: Pick<ModuleNode, 'module' | 'entries'>,\n entry: string,\n): ClassType[] {\n const listed = node.entries.get(entry) as Iterable<unknown> | null | undefined\n if (!listed) {\n return []\n }\n const classes = Array.from(new Set(listed))\n const index = classes.findIndex((listedClass) => typeof listedClass !== 'function')\n if (index !== -1) {\n throw new Error(\n `[Navios] Module ${node.module.name} lists ${String(classes[index])} in ${entry}. When it ` +\n `should be a class, the files of the two usually import each other.`,\n )\n }\n return classes as ClassType[]\n}\n\n/** Two import paths that give a module different values of one attribute. */\ninterface Disagreement {\n one: ClassType[]\n other: ClassType[]\n /** Whether the other path gives a value at all. */\n otherHasValue: boolean\n}\n\n/** What a module has while the graph is being computed. */\ninterface Draft {\n node: ModuleNode\n metadata: ModuleMetadata\n /** The attributes the importers do not agree about. */\n disagreements: Map<symbol, Disagreement>\n /** Whether the walk is at what it imports. */\n open: boolean\n ranked: boolean\n}\n\nfunction names(path: readonly ClassType[]): string {\n return path.map((module) => module.name).join(' -> ')\n}\n\n/** One way to a module from a root, the module included. */\nfunction pathTo(node: ModuleNode): ClassType[] {\n const path = [node.module]\n for (let at = node; !at.isRoot && at.importers.length > 0;) {\n at = at.importers[0]\n path.unshift(at.module)\n }\n return path\n}\n\n/**\n * Gives a module the attributes it inherits. Guards add up over several import\n * paths, which is safe; attributes cannot. One that opens a handler and one that\n * restricts it would each be wrong if it applied because of one path alone, so\n * the paths have to agree where a handler inherits it.\n */\nfunction inheritAttributes(draft: Draft, importers: readonly Draft[]): void {\n const { node, metadata, disagreements } = draft\n const keys = new Set(\n importers.flatMap((importer) => [\n ...importer.node.attributes.keys(),\n ...importer.disagreements.keys(),\n ]),\n )\n for (const key of keys) {\n if (metadata.attributes.has(key)) {\n continue\n }\n const inherited = importers.find((importer) => importer.disagreements.has(key))\n if (inherited) {\n const { one, other, otherHasValue } = inherited.disagreements.get(key)!\n disagreements.set(key, {\n one: [...one, node.module],\n other: [...other, node.module],\n otherHasValue,\n })\n continue\n }\n const source = importers.find((importer) => importer.node.attributes.has(key))!\n const value = source.node.attributes.get(key)\n const disagrees = (importer: Draft) =>\n !importer.node.attributes.has(key) ||\n !isDeepStrictEqual(importer.node.attributes.get(key), value)\n const other = importers.find(disagrees)\n if (other === undefined && !node.isRoot) {\n node.attributes.set(key, value)\n } else {\n disagreements.set(key, {\n one: [...pathTo(source.node), node.module],\n other: other === undefined ? [node.module] : [...pathTo(other.node), node.module],\n otherHasValue: other !== undefined && other.node.attributes.has(key),\n })\n }\n }\n node.disputed = new Map(Array.from(disagreements, ([key, value]) => [key, described(value)]))\n}\n\nfunction described({ one, other, otherHasValue }: Disagreement): string {\n return `one over ${names(one)}, ${otherHasValue ? 'another' : 'none'} over ${names(other)}`\n}\n\n/**\n * Walks the import graph from the given roots and computes, for this\n * application only, what applies to each module.\n *\n * - Guards and interceptors are the union over every path that reaches a\n * module, outermost first: what the importers contribute, importers in\n * import order, then the module's own. Nothing is written back to the\n * classes, so two applications importing one module under different parents\n * do not affect each other.\n * - An attribute comes from the module itself or else from what imports it.\n * One that the importers do not agree about is in `disputed` instead.\n *\n * Neither depends on the order in which a module happens to be reached.\n * Modules are returned in dependency order: a module comes after everything\n * it imports. That cannot be done for modules that import each other, which is\n * an error as well.\n */\nexport function buildModuleGraph(roots: ClassType[]): ModuleNode[] {\n const drafts = new Map<ClassType, Draft>()\n const order: ModuleNode[] = []\n\n // First walk: every module once, in dependency order, with its importers.\n const path: ClassType[] = []\n const visit = (module: ClassType, importer: ModuleNode | null): void => {\n const known = drafts.get(module)\n if (known) {\n if (known.open) {\n throw new Error(\n `[Navios] Modules import each other in a cycle: ` +\n names([...path.slice(path.indexOf(module)), module]),\n )\n }\n if (importer && !known.node.importers.includes(importer)) {\n known.node.importers.push(importer)\n }\n return\n }\n const metadata = getModuleMetadata(module)\n const node: ModuleNode = {\n module,\n providers: metadata.providers,\n entries: metadata.entries,\n guards: [],\n interceptors: [],\n attributes: new Map(),\n disputed: new Map(),\n importers: importer ? [importer] : [],\n isRoot: false,\n }\n const draft: Draft = {\n node,\n metadata,\n disagreements: new Map(),\n open: true,\n ranked: false,\n }\n drafts.set(module, draft)\n path.push(module)\n for (const imported of metadata.imports) {\n visit(imported, node)\n }\n path.pop()\n draft.open = false\n order.push(node)\n }\n for (const root of roots) {\n visit(root, null)\n drafts.get(root)!.node.isRoot = true\n }\n\n // Second walk: importers before what they import, siblings in import\n // order. That is the reverse of a post-order that takes the imports last\n // to first.\n const outermostFirst: Draft[] = []\n const rank = (draft: Draft): void => {\n if (draft.ranked) {\n return\n }\n draft.ranked = true\n const imports = draft.metadata.imports\n for (let i = imports.length - 1; i >= 0; i--) {\n rank(drafts.get(imports[i])!)\n }\n outermostFirst.push(draft)\n }\n for (let i = roots.length - 1; i >= 0; i--) {\n rank(drafts.get(roots[i])!)\n }\n outermostFirst.reverse()\n\n // Each module is complete when its turn comes, because everything that\n // imports it came before; it then hands what it has to its imports.\n for (const draft of outermostFirst) {\n const { node, metadata } = draft\n addMissing(node.guards, metadata.guards)\n addMissing(node.interceptors, metadata.interceptors)\n inheritAttributes(\n draft,\n node.importers.map((importer) => drafts.get(importer.module)!),\n )\n for (const [key, value] of metadata.attributes) {\n node.attributes.set(key, value)\n }\n for (const imported of metadata.imports) {\n const child = drafts.get(imported)!\n addMissing(child.node.guards, node.guards)\n addMissing(child.node.interceptors, node.interceptors)\n }\n }\n return order\n}\n","import { InjectableScope, InjectionToken } from '@navios/di'\n\nimport type { ExecutionContext } from './execution-context.mjs'\n\n/**\n * The context of the current execution, on any transport. Injectable in\n * request-scoped services.\n */\nexport const ExecutionContextToken = InjectionToken.create<ExecutionContext>('ExecutionContext', {\n scope: InjectableScope.Request,\n})\n"],"mappings":";;;;AAOA,IAAI,UAA0B;;;;;AAM9B,eAAsB,qBAAoC;CACxD,IAAI,YAAY,MAAM;EACpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,UAAU,IAAI,kBAAoC;CACpD;AACF;;;;;AAMA,SAAgB,aAAgB,KAAuB,IAAgB;CACrE,OAAO,YAAY,OAAO,GAAG,IAAI,QAAQ,IAAI,KAAK,EAAE;AACtD;;;;;;AAOA,SAAgB,iBAA+C;CAC7D,OAAO,SAAS,SAAS;AAC3B;;ACfA,SAAS,UAAU,OAAwB;CACzC,OAAO,OAAO,UAAU,aAAa,MAAM,OAAO,OAAO,KAAK;AAChE;;AAKA,SAAS,WAAW,OAAsC;CACxD,OACE,iBAAiBA,WAAAA,uBAAuB,iBAAiBC,WAAAA,wBACrD,MAAM,QACN;AAER;;;;;AAMA,SAAgB,WAAW,WAAsB,OAAmC;CAClF,OAAO,UAAU,YAAY,KAAK,CAAC,EAAE,UAAUC,WAAAA,gBAAgB;AACjE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