@navios/core 2.0.0-alpha.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 +33 -3
- package/README.md +8 -6
- package/lib/{async-context-6pdlnNLA.d.mts → async-context-BAdt7bno.d.mts} +11 -9
- package/lib/async-context-BAdt7bno.d.mts.map +1 -0
- package/lib/{async-context-Dqk7pE-D.d.cts → async-context-RsWmy2Hi.d.cts} +11 -9
- package/lib/async-context-RsWmy2Hi.d.cts.map +1 -0
- package/lib/{attribute-factory-B3VuYnp7.d.cts → attribute-factory-BW1kgBqf.d.mts} +2 -2
- package/lib/{attribute-factory-B3VuYnp7.d.cts.map → attribute-factory-BW1kgBqf.d.mts.map} +1 -1
- package/lib/{attribute-factory-mKOXoVnV.d.mts → attribute-factory-DqN4x5XM.d.cts} +2 -2
- package/lib/{attribute-factory-mKOXoVnV.d.mts.map → attribute-factory-DqN4x5XM.d.cts.map} +1 -1
- 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-DSk5MNtc.cjs → basic-execution-context-5uq2DvEA.cjs} +66 -29
- package/lib/basic-execution-context-5uq2DvEA.cjs.map +1 -0
- package/lib/{basic-execution-context-CeGuhMOz.mjs → basic-execution-context-u1VktGoM.mjs} +61 -30
- package/lib/basic-execution-context-u1VktGoM.mjs.map +1 -0
- package/lib/{execution-context-BPD3FeFb.d.mts → execution-context-BVSmLkYp.d.cts} +2 -2
- package/lib/{execution-context-BPD3FeFb.d.mts.map → execution-context-BVSmLkYp.d.cts.map} +1 -1
- package/lib/{execution-context-BTJdHhbf.d.cts → execution-context-C5F9rojO.d.mts} +2 -2
- package/lib/{execution-context-BTJdHhbf.d.cts.map → execution-context-C5F9rojO.d.mts.map} +1 -1
- package/lib/{module-graph-DCP9MHG0.cjs → execution-context-token--cKS4cJv.cjs} +135 -12
- package/lib/execution-context-token--cKS4cJv.cjs.map +1 -0
- package/lib/{module-graph-xvVEykFM.mjs → execution-context-token-Cb3M3Ao0.mjs} +93 -12
- package/lib/execution-context-token-Cb3M3Ao0.mjs.map +1 -0
- package/lib/index.cjs +84 -101
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +14 -10
- package/lib/index.d.cts.map +1 -1
- package/lib/index.d.mts +14 -10
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +76 -92
- package/lib/index.mjs.map +1 -1
- package/lib/legacy-compat/index.cjs +2 -2
- package/lib/legacy-compat/index.d.cts +3 -3
- package/lib/legacy-compat/index.d.mts +2 -2
- package/lib/legacy-compat/index.mjs +2 -2
- package/lib/{module-DZewk_2r.cjs → module-Bz83ZnJ5.cjs} +43 -34
- package/lib/module-Bz83ZnJ5.cjs.map +1 -0
- package/lib/{module-options-Dmse0gii.d.mts → module-options-CSqQUSTm.d.mts} +2 -2
- package/lib/{module-options-Dmse0gii.d.mts.map → module-options-CSqQUSTm.d.mts.map} +1 -1
- package/lib/{module-options-IuDO-p8u.d.cts → module-options-DSRBri4J.d.cts} +2 -2
- package/lib/{module-options-IuDO-p8u.d.cts.map → module-options-DSRBri4J.d.cts.map} +1 -1
- package/lib/{module-Bha7GER_.mjs → module-zPXwR2qp.mjs} +38 -35
- 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 +12 -34
- package/lib/testing/index.cjs.map +1 -1
- package/lib/testing/index.d.cts +2 -2
- package/lib/testing/index.d.cts.map +1 -1
- package/lib/testing/index.d.mts +1 -1
- package/lib/testing/index.d.mts.map +1 -1
- package/lib/testing/index.mjs +12 -34
- package/lib/testing/index.mjs.map +1 -1
- package/lib/transport.cjs +19 -8
- package/lib/transport.d.cts +102 -38
- package/lib/transport.d.cts.map +1 -1
- package/lib/transport.d.mts +102 -38
- package/lib/transport.d.mts.map +1 -1
- package/lib/transport.mjs +6 -7
- package/package.json +2 -2
- package/lib/async-context-6pdlnNLA.d.mts.map +0 -1
- package/lib/async-context-Dqk7pE-D.d.cts.map +0 -1
- package/lib/attribute-value-CjX9ZkLq.cjs +0 -172
- package/lib/attribute-value-CjX9ZkLq.cjs.map +0 -1
- package/lib/attribute-value-DMEA255r.mjs +0 -119
- package/lib/attribute-value-DMEA255r.mjs.map +0 -1
- package/lib/basic-execution-context-CeGuhMOz.mjs.map +0 -1
- package/lib/basic-execution-context-DSk5MNtc.cjs.map +0 -1
- package/lib/execution-context-token-BXUKB2hf.cjs +0 -112
- package/lib/execution-context-token-BXUKB2hf.cjs.map +0 -1
- package/lib/execution-context-token-CrXmTvk2.mjs +0 -77
- package/lib/execution-context-token-CrXmTvk2.mjs.map +0 -1
- package/lib/module-Bha7GER_.mjs.map +0 -1
- package/lib/module-DZewk_2r.cjs.map +0 -1
- package/lib/module-graph-DCP9MHG0.cjs.map +0 -1
- package/lib/module-graph-xvVEykFM.mjs.map +0 -1
- package/lib/module-metadata-C8S92seK.cjs +0 -95
- package/lib/module-metadata-C8S92seK.cjs.map +0 -1
- package/lib/module-metadata-k3RTt20x.mjs +0 -66
- package/lib/module-metadata-k3RTt20x.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"basic-execution-context-CeGuhMOz.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 { 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' | 'disputed'>\n /** The class that owns the handler. */\n owner: OwnExtras\n /** The handler itself. */\n member: OwnExtras\n}\n\nexport interface HandlerChain {\n guards: ClassType[]\n /** `outer` and `inner`, one after the other. */\n interceptors: ClassType[]\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: the interceptors of the application, then the guards from the module\n * chain, the owning class and the handler, then the interceptors of the same\n * three. A class that appears twice is kept where it first appears.\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. `runChain`\n * runs the chain.\n */\nexport function handlerChain(input: HandlerChainInput): HandlerChain {\n assertUndisputed(input)\n const { application, node, owner, member } = input\n const outer = new Set(application)\n const attached = [...node.interceptors, ...owner.interceptors, ...member.interceptors]\n const inner = new Set(attached.filter((interceptor) => !outer.has(interceptor)))\n return {\n guards: Array.from(new Set([...node.guards, ...owner.guards, ...member.guards])),\n interceptors: [...outer, ...inner],\n outer: Array.from(outer),\n inner: Array.from(inner),\n }\n}\n","import type { ClassType, Container } from '@navios/di'\n\nimport type { ExecutionContext } from '../execution/execution-context.mjs'\nimport type { Guard } from '../guards/guard.mjs'\nimport type { Interceptor } from '../interceptors/interceptor.mjs'\n\nimport type { HandlerChain } from './handler-chain.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. A transport does this once per handler,\n * 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: Pick<HandlerChain, 'outer' | 'guards' | 'inner'>,\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.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","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 /** Defaults to a signal of the context's own that never aborts. */\n signal?: AbortSignal\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 readonly givenSignal: AbortSignal | undefined\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 this.givenSignal = init.signal\n }\n\n /** Not shared between contexts: listeners would outlive their execution. */\n get signal(): AbortSignal {\n return this.givenSignal ?? (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 } = this.host\n if (this.scope === null && !needsScope(container, token)) {\n return container\n }\n this.host.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,+B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ACF,MAAM,SAAS;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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"basic-execution-context-DSk5MNtc.cjs","names":["requireMetadata","classAttributes","applyAttributes","prepend","classGuards","classInterceptors","MembersKey","needsScope","ExecutionContextToken"],"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 { 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' | 'disputed'>\n /** The class that owns the handler. */\n owner: OwnExtras\n /** The handler itself. */\n member: OwnExtras\n}\n\nexport interface HandlerChain {\n guards: ClassType[]\n /** `outer` and `inner`, one after the other. */\n interceptors: ClassType[]\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: the interceptors of the application, then the guards from the module\n * chain, the owning class and the handler, then the interceptors of the same\n * three. A class that appears twice is kept where it first appears.\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. `runChain`\n * runs the chain.\n */\nexport function handlerChain(input: HandlerChainInput): HandlerChain {\n assertUndisputed(input)\n const { application, node, owner, member } = input\n const outer = new Set(application)\n const attached = [...node.interceptors, ...owner.interceptors, ...member.interceptors]\n const inner = new Set(attached.filter((interceptor) => !outer.has(interceptor)))\n return {\n guards: Array.from(new Set([...node.guards, ...owner.guards, ...member.guards])),\n interceptors: [...outer, ...inner],\n outer: Array.from(outer),\n inner: Array.from(inner),\n }\n}\n","import type { ClassType, Container } from '@navios/di'\n\nimport type { ExecutionContext } from '../execution/execution-context.mjs'\nimport type { Guard } from '../guards/guard.mjs'\nimport type { Interceptor } from '../interceptors/interceptor.mjs'\n\nimport type { HandlerChain } from './handler-chain.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. A transport does this once per handler,\n * 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: Pick<HandlerChain, 'outer' | 'guards' | 'inner'>,\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.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","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 /** Defaults to a signal of the context's own that never aborts. */\n signal?: AbortSignal\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 readonly givenSignal: AbortSignal | undefined\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 this.givenSignal = init.signal\n }\n\n /** Not shared between contexts: listeners would outlive their execution. */\n get signal(): AbortSignal {\n return this.givenSignal ?? (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 } = this.host\n if (this.scope === null && !needsScope(container, token)) {\n return container\n }\n this.host.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,WAAWA,wBAAAA,gBAAgB,OAAO;CACxC,MAAM,aAAaC,wBAAAA,gBAAgB,OAAO;CAC1CC,wBAAAA,gBAAgB,YAAY,QAAQ,UAAU;CAC9C,OAAO;EACL,QAAQC,wBAAAA,QAAQC,wBAAAA,YAAY,OAAO,GAAG,QAAQ,MAAM;EACpD,cAAcD,wBAAAA,QAAQE,wBAAAA,kBAAkB,OAAO,GAAG,QAAQ,YAAY;EACtE;EACA,SAAU,SAASC,wBAAAA,+BAAkE,IAAI,IAAI;CAC/F;AACF;;;;;;ACJA,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;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAa,OAAwC;CACnE,iBAAiB,KAAK;CAC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zD"}
|
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
let _navios_di = require("@navios/di");
|
|
2
|
-
// src/execution/async-context.mts
|
|
3
|
-
let storage = null;
|
|
4
|
-
/**
|
|
5
|
-
* Turns on the async context: one `AsyncLocalStorage` holding the current
|
|
6
|
-
* `ExecutionContext`. The `asyncContext: true` option of an application does it.
|
|
7
|
-
*/
|
|
8
|
-
async function enableAsyncContext() {
|
|
9
|
-
if (storage === null) {
|
|
10
|
-
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
11
|
-
storage = new AsyncLocalStorage();
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Runs `fn` with `ctx` as the current context. A transport does this when its
|
|
16
|
-
* host says that the application has an async context.
|
|
17
|
-
*/
|
|
18
|
-
function runInContext(ctx, fn) {
|
|
19
|
-
return storage === null ? fn() : storage.run(ctx, fn);
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* The context of the handler being run, for code that cannot receive it as an
|
|
23
|
-
* argument. Returns `undefined` outside a handler, and always when the
|
|
24
|
-
* application was not created with `asyncContext: true`.
|
|
25
|
-
*/
|
|
26
|
-
function currentContext() {
|
|
27
|
-
return storage?.getStore();
|
|
28
|
-
}
|
|
29
|
-
// src/execution/context-host.mts
|
|
30
|
-
function tokenName(token) {
|
|
31
|
-
return typeof token === "function" ? token.name : String(token);
|
|
32
|
-
}
|
|
33
|
-
/** The token itself, without the args that are bound to it. */
|
|
34
|
-
function plainToken(token) {
|
|
35
|
-
return token instanceof _navios_di.BoundInjectionToken || token instanceof _navios_di.FactoryInjectionToken ? token.token : token;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Whether a context resolves `token` from a DI scope of its execution. A
|
|
39
|
-
* singleton is the same in all of them.
|
|
40
|
-
*/
|
|
41
|
-
function needsScope(container, token) {
|
|
42
|
-
return container.getProvider(plainToken(token))?.scope !== _navios_di.InjectableScope.Singleton;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Builds the host for an application's contexts, applying its policy for
|
|
46
|
-
* request-scoped services.
|
|
47
|
-
*/
|
|
48
|
-
function createContextHost(container, mode, logger) {
|
|
49
|
-
if (mode === "allow") return {
|
|
50
|
-
container,
|
|
51
|
-
onScopedUse: null,
|
|
52
|
-
logger
|
|
53
|
-
};
|
|
54
|
-
const seen = /* @__PURE__ */ new Set();
|
|
55
|
-
return {
|
|
56
|
-
container,
|
|
57
|
-
logger,
|
|
58
|
-
onScopedUse: (used) => {
|
|
59
|
-
if (!needsScope(container, used)) return;
|
|
60
|
-
const token = plainToken(used);
|
|
61
|
-
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.`);
|
|
62
|
-
if (!seen.has(token)) {
|
|
63
|
-
seen.add(token);
|
|
64
|
-
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.`);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
// src/execution/execution-context-token.mts
|
|
70
|
-
/**
|
|
71
|
-
* The context of the current execution, on any transport. Injectable in
|
|
72
|
-
* request-scoped services.
|
|
73
|
-
*/
|
|
74
|
-
const ExecutionContextToken = _navios_di.InjectionToken.create("ExecutionContext", { scope: _navios_di.InjectableScope.Request });
|
|
75
|
-
Object.defineProperty(exports, "ExecutionContextToken", {
|
|
76
|
-
enumerable: true,
|
|
77
|
-
get: function() {
|
|
78
|
-
return ExecutionContextToken;
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
Object.defineProperty(exports, "createContextHost", {
|
|
82
|
-
enumerable: true,
|
|
83
|
-
get: function() {
|
|
84
|
-
return createContextHost;
|
|
85
|
-
}
|
|
86
|
-
});
|
|
87
|
-
Object.defineProperty(exports, "currentContext", {
|
|
88
|
-
enumerable: true,
|
|
89
|
-
get: function() {
|
|
90
|
-
return currentContext;
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
Object.defineProperty(exports, "enableAsyncContext", {
|
|
94
|
-
enumerable: true,
|
|
95
|
-
get: function() {
|
|
96
|
-
return enableAsyncContext;
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
Object.defineProperty(exports, "needsScope", {
|
|
100
|
-
enumerable: true,
|
|
101
|
-
get: function() {
|
|
102
|
-
return needsScope;
|
|
103
|
-
}
|
|
104
|
-
});
|
|
105
|
-
Object.defineProperty(exports, "runInContext", {
|
|
106
|
-
enumerable: true,
|
|
107
|
-
get: function() {
|
|
108
|
-
return runInContext;
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
//# sourceMappingURL=execution-context-token-BXUKB2hf.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execution-context-token-BXUKB2hf.cjs","names":["BoundInjectionToken","FactoryInjectionToken","InjectableScope","InjectionToken","InjectableScope"],"sources":["../src/execution/async-context.mts","../src/execution/context-host.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 token is used through a context; may throw. Does nothing for\n * a token that `needsScope` is false for.\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(plainToken(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 if (!needsScope(container, used)) {\n return\n }\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 { 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,WAAW,KAAK,CAAC,CAAC,EAAE,UAAUC,WAAAA,gBAAgB;AAC7E;;;;;AAMA,SAAgB,kBACd,WACA,MACA,QACa;CACb,IAAI,SAAS,SACX,OAAO;EAAE;EAAW,aAAa;EAAM;CAAO;CAEhD,MAAM,uBAAO,IAAI,IAAgB;CACjC,OAAO;EACL;EACA;EACA,cAAc,SAAS;GACrB,IAAI,CAAC,WAAW,WAAW,IAAI,GAC7B;GAEF,MAAM,QAAQ,WAAW,IAAI;GAC7B,IAAI,SAAS,UACX,MAAM,IAAI,MACR,YAAY,UAAU,KAAK,EAAE,uLAG/B;GAEF,IAAI,CAAC,KAAK,IAAI,KAAK,GAAG;IACpB,KAAK,IAAI,KAAK;IACd,OAAO,KACL,GAAG,UAAU,KAAK,EAAE,qNAGtB;GACF;EACF;CACF;AACF;;;;;;ACzEA,MAAa,wBAAwBC,WAAAA,eAAe,OAAyB,oBAAoB,EAC/F,OAAOC,WAAAA,gBAAgB,QACzB,CAAC"}
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { BoundInjectionToken, FactoryInjectionToken, InjectableScope, InjectionToken } from "@navios/di";
|
|
2
|
-
// src/execution/async-context.mts
|
|
3
|
-
let storage = null;
|
|
4
|
-
/**
|
|
5
|
-
* Turns on the async context: one `AsyncLocalStorage` holding the current
|
|
6
|
-
* `ExecutionContext`. The `asyncContext: true` option of an application does it.
|
|
7
|
-
*/
|
|
8
|
-
async function enableAsyncContext() {
|
|
9
|
-
if (storage === null) {
|
|
10
|
-
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
11
|
-
storage = new AsyncLocalStorage();
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Runs `fn` with `ctx` as the current context. A transport does this when its
|
|
16
|
-
* host says that the application has an async context.
|
|
17
|
-
*/
|
|
18
|
-
function runInContext(ctx, fn) {
|
|
19
|
-
return storage === null ? fn() : storage.run(ctx, fn);
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* The context of the handler being run, for code that cannot receive it as an
|
|
23
|
-
* argument. Returns `undefined` outside a handler, and always when the
|
|
24
|
-
* application was not created with `asyncContext: true`.
|
|
25
|
-
*/
|
|
26
|
-
function currentContext() {
|
|
27
|
-
return storage?.getStore();
|
|
28
|
-
}
|
|
29
|
-
// src/execution/context-host.mts
|
|
30
|
-
function tokenName(token) {
|
|
31
|
-
return typeof token === "function" ? token.name : String(token);
|
|
32
|
-
}
|
|
33
|
-
/** The token itself, without the args that are bound to it. */
|
|
34
|
-
function plainToken(token) {
|
|
35
|
-
return token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken ? token.token : token;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Whether a context resolves `token` from a DI scope of its execution. A
|
|
39
|
-
* singleton is the same in all of them.
|
|
40
|
-
*/
|
|
41
|
-
function needsScope(container, token) {
|
|
42
|
-
return container.getProvider(plainToken(token))?.scope !== InjectableScope.Singleton;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Builds the host for an application's contexts, applying its policy for
|
|
46
|
-
* request-scoped services.
|
|
47
|
-
*/
|
|
48
|
-
function createContextHost(container, mode, logger) {
|
|
49
|
-
if (mode === "allow") return {
|
|
50
|
-
container,
|
|
51
|
-
onScopedUse: null,
|
|
52
|
-
logger
|
|
53
|
-
};
|
|
54
|
-
const seen = /* @__PURE__ */ new Set();
|
|
55
|
-
return {
|
|
56
|
-
container,
|
|
57
|
-
logger,
|
|
58
|
-
onScopedUse: (used) => {
|
|
59
|
-
if (!needsScope(container, used)) return;
|
|
60
|
-
const token = plainToken(used);
|
|
61
|
-
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.`);
|
|
62
|
-
if (!seen.has(token)) {
|
|
63
|
-
seen.add(token);
|
|
64
|
-
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.`);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
// src/execution/execution-context-token.mts
|
|
70
|
-
/**
|
|
71
|
-
* The context of the current execution, on any transport. Injectable in
|
|
72
|
-
* request-scoped services.
|
|
73
|
-
*/
|
|
74
|
-
const ExecutionContextToken = InjectionToken.create("ExecutionContext", { scope: InjectableScope.Request });
|
|
75
|
-
export { enableAsyncContext as a, currentContext as i, createContextHost as n, runInContext as o, needsScope as r, ExecutionContextToken as t };
|
|
76
|
-
|
|
77
|
-
//# sourceMappingURL=execution-context-token-CrXmTvk2.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execution-context-token-CrXmTvk2.mjs","names":[],"sources":["../src/execution/async-context.mts","../src/execution/context-host.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 token is used through a context; may throw. Does nothing for\n * a token that `needsScope` is false for.\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(plainToken(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 if (!needsScope(container, used)) {\n return\n }\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 { 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,iBAAiB,uBAAuB,iBAAiB,wBACrD,MAAM,QACN;AAER;;;;;AAMA,SAAgB,WAAW,WAAsB,OAAmC;CAClF,OAAO,UAAU,YAAY,WAAW,KAAK,CAAC,CAAC,EAAE,UAAU,gBAAgB;AAC7E;;;;;AAMA,SAAgB,kBACd,WACA,MACA,QACa;CACb,IAAI,SAAS,SACX,OAAO;EAAE;EAAW,aAAa;EAAM;CAAO;CAEhD,MAAM,uBAAO,IAAI,IAAgB;CACjC,OAAO;EACL;EACA;EACA,cAAc,SAAS;GACrB,IAAI,CAAC,WAAW,WAAW,IAAI,GAC7B;GAEF,MAAM,QAAQ,WAAW,IAAI;GAC7B,IAAI,SAAS,UACX,MAAM,IAAI,MACR,YAAY,UAAU,KAAK,EAAE,uLAG/B;GAEF,IAAI,CAAC,KAAK,IAAI,KAAK,GAAG;IACpB,KAAK,IAAI,KAAK;IACd,OAAO,KACL,GAAG,UAAU,KAAK,EAAE,qNAGtB;GACF;EACF;CACF;AACF;;;;;;ACzEA,MAAa,wBAAwB,eAAe,OAAyB,oBAAoB,EAC/F,OAAO,gBAAgB,QACzB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"module-Bha7GER_.mjs","names":[],"sources":["../src/attributes/attribute-factory.mts","../src/metadata/attach-classes.mts","../src/guards/use-guards.mts","../src/interceptors/use-interceptors.mts","../src/modules/module.mts"],"sourcesContent":["import type { InferInput, InferOutput, StandardSchemaV1 } from '@navios/di'\n\nimport { classAttributes } from '../metadata/class-metadata.mjs'\nimport { memberMetadata } from '../metadata/member-metadata.mjs'\n\nimport type { HandlerInfo } from '../execution/execution-context.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype AttributeContext =\n | ClassDecoratorContext\n | ClassMethodDecoratorContext\n | ClassFieldDecoratorContext\n\n/**\n * The result of calling an attribute. It is a decorator for a module, a\n * controller, a handler method or a handler field, and it can also be passed\n * in `handler(endpoint, { attributes: [...] }, fn)`.\n */\nexport interface AttributeApplication {\n (target: any, context: AttributeContext): any\n readonly token: symbol\n readonly value: unknown\n}\n\nexport interface ClassAttribute {\n (): AttributeApplication\n readonly token: symbol\n}\n\nexport interface ClassSchemaAttribute<Schema extends StandardSchemaV1> {\n (value: InferInput<Schema>): AttributeApplication\n readonly token: symbol\n readonly schema: Schema\n}\n\nfunction apply(token: symbol, value: unknown): AttributeApplication {\n const decorator = (target: any, context: AttributeContext) => {\n if (context.kind === 'class') {\n classAttributes(context).set(token, value)\n } else if (context.kind === 'method' || context.kind === 'field') {\n if (typeof context.name !== 'string') {\n throw new Error('[Navios] Attributes cannot be applied to symbol-named members')\n }\n memberMetadata(context, context.name).attributes.set(token, value)\n } else {\n throw new Error('[Navios] Attributes can only be applied to classes, methods and fields')\n }\n return context.kind === 'field' ? undefined : target\n }\n return Object.assign(decorator, { token, value })\n}\n\n/**\n * What reading an attribute needs of it. An attribute of either factory, the\n * standard one or the one from `@navios/core/legacy-compat`, has this shape;\n * what calling it returns differs between the two and does not matter here.\n */\ninterface ReadableAttribute {\n readonly token: symbol\n readonly schema?: undefined\n}\n\ninterface ReadableSchemaAttribute<Schema extends StandardSchemaV1> {\n readonly token: symbol\n readonly schema: Schema\n}\n\ntype AttributeSource = HandlerInfo | { attributes: ReadonlyMap<symbol, unknown> }\n\nfunction layers(source: AttributeSource): ReadonlyMap<symbol, unknown>[] {\n const attributes = source.attributes\n if (attributes instanceof Map) {\n return [attributes]\n }\n const route = attributes as HandlerInfo['attributes']\n // Most specific first.\n return [route.handler, route.controller, route.module]\n}\n\n/**\n * Creates and reads attributes: typed metadata attached to modules,\n * controllers and handlers.\n *\n * ```ts\n * export const Public = AttributeFactory.createAttribute(Symbol.for('Public'))\n * export const Roles = AttributeFactory.createAttribute(Symbol.for('Roles'), z.array(z.string()))\n *\n * if (AttributeFactory.has(Public, ctx.handler)) return true\n * const roles = AttributeFactory.get(Roles, ctx.handler) // string[] | null\n * ```\n */\nexport class AttributeFactory {\n static createAttribute(token: symbol): ClassAttribute\n static createAttribute<Schema extends StandardSchemaV1>(\n token: symbol,\n schema: Schema,\n ): ClassSchemaAttribute<Schema>\n static createAttribute(token: symbol, schema?: StandardSchemaV1): any {\n const attribute = (value?: unknown) => {\n if (!schema) {\n return apply(token, true)\n }\n const result = schema['~standard'].validate(value)\n if (result instanceof Promise) {\n result.catch(() => {})\n throw new Error(\n `[Navios] Attribute ${token.toString()} must use a schema that validates synchronously`,\n )\n }\n if (result.issues) {\n throw new Error(\n `[Navios] Invalid value for attribute ${token.toString()}: ${result.issues\n .map((issue) => issue.message)\n .join('; ')}`,\n )\n }\n return apply(token, result.value)\n }\n return Object.assign(attribute, schema ? { token, schema } : { token })\n }\n\n /**\n * The attribute's value for a handler: the handler's own, else the controller's,\n * else the module's. `null` when none has it.\n */\n static get(attribute: ReadableAttribute, source: AttributeSource): true | null\n static get<Schema extends StandardSchemaV1>(\n attribute: ReadableSchemaAttribute<Schema>,\n source: AttributeSource,\n ): InferOutput<Schema> | null\n static get(attribute: { token: symbol }, source: AttributeSource): unknown {\n for (const layer of layers(source)) {\n if (layer.has(attribute.token)) {\n return layer.get(attribute.token)\n }\n }\n return null\n }\n\n /**\n * Every value of the attribute for a handler, most specific first.\n */\n static getAll(attribute: ReadableAttribute, source: AttributeSource): true[]\n static getAll<Schema extends StandardSchemaV1>(\n attribute: ReadableSchemaAttribute<Schema>,\n source: AttributeSource,\n ): InferOutput<Schema>[]\n static getAll(attribute: { token: symbol }, source: AttributeSource): unknown[] {\n const values: unknown[] = []\n for (const layer of layers(source)) {\n if (layer.has(attribute.token)) {\n values.push(layer.get(attribute.token))\n }\n }\n return values\n }\n\n static has(attribute: { token: symbol }, source: AttributeSource): boolean {\n return layers(source).some((layer) => layer.has(attribute.token))\n }\n}\n","import type { ClassType } from '@navios/di'\n\nimport { classGuards, classInterceptors } from './class-metadata.mjs'\nimport { memberMetadata } from './member-metadata.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype AnyMemberContext =\n | ClassDecoratorContext\n | ClassMethodDecoratorContext\n | ClassFieldDecoratorContext\n\n/**\n * The decorator behind `@UseGuards` and `@UseInterceptors`: adds classes to\n * the list of a class or of one of its members.\n * @internal\n */\nexport function attachClasses(\n kind: 'guards' | 'interceptors',\n classes: ClassType[],\n name: string,\n): (target: any, context: AnyMemberContext) => any {\n return (target, context) => {\n if (context.kind === 'class') {\n const list = kind === 'guards' ? classGuards(context) : classInterceptors(context)\n for (const cls of classes) {\n if (!list.includes(cls)) {\n list.push(cls)\n }\n }\n return target\n }\n if (context.kind !== 'method' && context.kind !== 'field') {\n throw new Error(`[Navios] @${name} can only be used on classes, methods and fields.`)\n }\n if (typeof context.name !== 'string') {\n throw new Error(`[Navios] @${name} cannot be used on symbol-named members.`)\n }\n const list = memberMetadata(context, context.name)[kind]\n for (const cls of classes) {\n if (!list.includes(cls)) {\n list.push(cls)\n }\n }\n return context.kind === 'field' ? undefined : target\n }\n}\n","import { attachClasses } from '../metadata/attach-classes.mjs'\n\nimport type { GuardClass } from './guard.mjs'\n\n/**\n * Adds guards to a module, a controller or a handler. Guards run in the\n * order module, controller, handler, and within one level in the order given.\n *\n * On a class, place it above `@Controller` / `@Module`.\n */\nexport function UseGuards(...guards: GuardClass[]) {\n return attachClasses('guards', guards, 'UseGuards')\n}\n","import { attachClasses } from '../metadata/attach-classes.mjs'\n\nimport type { InterceptorClass } from './interceptor.mjs'\n\n/**\n * Adds interceptors to a module, a controller or a handler. The first one\n * given is the outermost. They run for what the guards let through, unlike the\n * interceptors of the application.\n *\n * On a class, place it above `@Controller` / `@Module`.\n */\nexport function UseInterceptors(...interceptors: InterceptorClass[]) {\n return attachClasses('interceptors', interceptors, 'UseInterceptors')\n}\n","import { InjectableScope, registerInjectable } from '@navios/di'\n\nimport type { ClassType } from '@navios/di'\n\nimport { applyAttributes } from '../attributes/attribute-value.mjs'\n\nimport { defineModuleMetadata } from './module-metadata.mjs'\n\nimport type { ModuleOptions } from './module-options.mjs'\n\n/**\n * Marks a class as a module: a group of handlers with shared guards,\n * interceptors and attributes.\n */\nexport function Module(options: ModuleOptions = {}) {\n return <T extends ClassType>(target: T, context: ClassDecoratorContext): T => {\n if (context.kind !== 'class') {\n throw new Error('[Navios] @Module can only be used on classes.')\n }\n applyAttributes(defineModuleMetadata(target, context, options).attributes, options.attributes)\n registerInjectable(target, { scope: InjectableScope.Singleton })\n return target\n }\n}\n\n/**\n * Registers a class as a module without decorator syntax.\n */\nexport function registerModule<T extends ClassType>(target: T, options: ModuleOptions = {}): T {\n applyAttributes(\n defineModuleMetadata(target, { metadata: {} }, options).attributes,\n options.attributes,\n )\n registerInjectable(target, { scope: InjectableScope.Singleton })\n return target\n}\n"],"mappings":";;;;AAoCA,SAAS,MAAM,OAAe,OAAsC;CAClE,MAAM,aAAa,QAAa,YAA8B;EAC5D,IAAI,QAAQ,SAAS,SACnB,gBAAgB,OAAO,CAAC,CAAC,IAAI,OAAO,KAAK;OACpC,IAAI,QAAQ,SAAS,YAAY,QAAQ,SAAS,SAAS;GAChE,IAAI,OAAO,QAAQ,SAAS,UAC1B,MAAM,IAAI,MAAM,+DAA+D;GAEjF,eAAe,SAAS,QAAQ,IAAI,CAAC,CAAC,WAAW,IAAI,OAAO,KAAK;EACnE,OACE,MAAM,IAAI,MAAM,wEAAwE;EAE1F,OAAO,QAAQ,SAAS,UAAU,KAAA,IAAY;CAChD;CACA,OAAO,OAAO,OAAO,WAAW;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,OAAO,CAAC,CAAC,YACxD,QAAQ,UACV;CACA,mBAAmB,QAAQ,EAAE,OAAO,gBAAgB,UAAU,CAAC;CAC/D,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"module-DZewk_2r.cjs","names":["classAttributes","memberMetadata","classGuards","classInterceptors","memberMetadata","applyAttributes","defineModuleMetadata","registerInjectable","InjectableScope"],"sources":["../src/attributes/attribute-factory.mts","../src/metadata/attach-classes.mts","../src/guards/use-guards.mts","../src/interceptors/use-interceptors.mts","../src/modules/module.mts"],"sourcesContent":["import type { InferInput, InferOutput, StandardSchemaV1 } from '@navios/di'\n\nimport { classAttributes } from '../metadata/class-metadata.mjs'\nimport { memberMetadata } from '../metadata/member-metadata.mjs'\n\nimport type { HandlerInfo } from '../execution/execution-context.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype AttributeContext =\n | ClassDecoratorContext\n | ClassMethodDecoratorContext\n | ClassFieldDecoratorContext\n\n/**\n * The result of calling an attribute. It is a decorator for a module, a\n * controller, a handler method or a handler field, and it can also be passed\n * in `handler(endpoint, { attributes: [...] }, fn)`.\n */\nexport interface AttributeApplication {\n (target: any, context: AttributeContext): any\n readonly token: symbol\n readonly value: unknown\n}\n\nexport interface ClassAttribute {\n (): AttributeApplication\n readonly token: symbol\n}\n\nexport interface ClassSchemaAttribute<Schema extends StandardSchemaV1> {\n (value: InferInput<Schema>): AttributeApplication\n readonly token: symbol\n readonly schema: Schema\n}\n\nfunction apply(token: symbol, value: unknown): AttributeApplication {\n const decorator = (target: any, context: AttributeContext) => {\n if (context.kind === 'class') {\n classAttributes(context).set(token, value)\n } else if (context.kind === 'method' || context.kind === 'field') {\n if (typeof context.name !== 'string') {\n throw new Error('[Navios] Attributes cannot be applied to symbol-named members')\n }\n memberMetadata(context, context.name).attributes.set(token, value)\n } else {\n throw new Error('[Navios] Attributes can only be applied to classes, methods and fields')\n }\n return context.kind === 'field' ? undefined : target\n }\n return Object.assign(decorator, { token, value })\n}\n\n/**\n * What reading an attribute needs of it. An attribute of either factory, the\n * standard one or the one from `@navios/core/legacy-compat`, has this shape;\n * what calling it returns differs between the two and does not matter here.\n */\ninterface ReadableAttribute {\n readonly token: symbol\n readonly schema?: undefined\n}\n\ninterface ReadableSchemaAttribute<Schema extends StandardSchemaV1> {\n readonly token: symbol\n readonly schema: Schema\n}\n\ntype AttributeSource = HandlerInfo | { attributes: ReadonlyMap<symbol, unknown> }\n\nfunction layers(source: AttributeSource): ReadonlyMap<symbol, unknown>[] {\n const attributes = source.attributes\n if (attributes instanceof Map) {\n return [attributes]\n }\n const route = attributes as HandlerInfo['attributes']\n // Most specific first.\n return [route.handler, route.controller, route.module]\n}\n\n/**\n * Creates and reads attributes: typed metadata attached to modules,\n * controllers and handlers.\n *\n * ```ts\n * export const Public = AttributeFactory.createAttribute(Symbol.for('Public'))\n * export const Roles = AttributeFactory.createAttribute(Symbol.for('Roles'), z.array(z.string()))\n *\n * if (AttributeFactory.has(Public, ctx.handler)) return true\n * const roles = AttributeFactory.get(Roles, ctx.handler) // string[] | null\n * ```\n */\nexport class AttributeFactory {\n static createAttribute(token: symbol): ClassAttribute\n static createAttribute<Schema extends StandardSchemaV1>(\n token: symbol,\n schema: Schema,\n ): ClassSchemaAttribute<Schema>\n static createAttribute(token: symbol, schema?: StandardSchemaV1): any {\n const attribute = (value?: unknown) => {\n if (!schema) {\n return apply(token, true)\n }\n const result = schema['~standard'].validate(value)\n if (result instanceof Promise) {\n result.catch(() => {})\n throw new Error(\n `[Navios] Attribute ${token.toString()} must use a schema that validates synchronously`,\n )\n }\n if (result.issues) {\n throw new Error(\n `[Navios] Invalid value for attribute ${token.toString()}: ${result.issues\n .map((issue) => issue.message)\n .join('; ')}`,\n )\n }\n return apply(token, result.value)\n }\n return Object.assign(attribute, schema ? { token, schema } : { token })\n }\n\n /**\n * The attribute's value for a handler: the handler's own, else the controller's,\n * else the module's. `null` when none has it.\n */\n static get(attribute: ReadableAttribute, source: AttributeSource): true | null\n static get<Schema extends StandardSchemaV1>(\n attribute: ReadableSchemaAttribute<Schema>,\n source: AttributeSource,\n ): InferOutput<Schema> | null\n static get(attribute: { token: symbol }, source: AttributeSource): unknown {\n for (const layer of layers(source)) {\n if (layer.has(attribute.token)) {\n return layer.get(attribute.token)\n }\n }\n return null\n }\n\n /**\n * Every value of the attribute for a handler, most specific first.\n */\n static getAll(attribute: ReadableAttribute, source: AttributeSource): true[]\n static getAll<Schema extends StandardSchemaV1>(\n attribute: ReadableSchemaAttribute<Schema>,\n source: AttributeSource,\n ): InferOutput<Schema>[]\n static getAll(attribute: { token: symbol }, source: AttributeSource): unknown[] {\n const values: unknown[] = []\n for (const layer of layers(source)) {\n if (layer.has(attribute.token)) {\n values.push(layer.get(attribute.token))\n }\n }\n return values\n }\n\n static has(attribute: { token: symbol }, source: AttributeSource): boolean {\n return layers(source).some((layer) => layer.has(attribute.token))\n }\n}\n","import type { ClassType } from '@navios/di'\n\nimport { classGuards, classInterceptors } from './class-metadata.mjs'\nimport { memberMetadata } from './member-metadata.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype AnyMemberContext =\n | ClassDecoratorContext\n | ClassMethodDecoratorContext\n | ClassFieldDecoratorContext\n\n/**\n * The decorator behind `@UseGuards` and `@UseInterceptors`: adds classes to\n * the list of a class or of one of its members.\n * @internal\n */\nexport function attachClasses(\n kind: 'guards' | 'interceptors',\n classes: ClassType[],\n name: string,\n): (target: any, context: AnyMemberContext) => any {\n return (target, context) => {\n if (context.kind === 'class') {\n const list = kind === 'guards' ? classGuards(context) : classInterceptors(context)\n for (const cls of classes) {\n if (!list.includes(cls)) {\n list.push(cls)\n }\n }\n return target\n }\n if (context.kind !== 'method' && context.kind !== 'field') {\n throw new Error(`[Navios] @${name} can only be used on classes, methods and fields.`)\n }\n if (typeof context.name !== 'string') {\n throw new Error(`[Navios] @${name} cannot be used on symbol-named members.`)\n }\n const list = memberMetadata(context, context.name)[kind]\n for (const cls of classes) {\n if (!list.includes(cls)) {\n list.push(cls)\n }\n }\n return context.kind === 'field' ? undefined : target\n }\n}\n","import { attachClasses } from '../metadata/attach-classes.mjs'\n\nimport type { GuardClass } from './guard.mjs'\n\n/**\n * Adds guards to a module, a controller or a handler. Guards run in the\n * order module, controller, handler, and within one level in the order given.\n *\n * On a class, place it above `@Controller` / `@Module`.\n */\nexport function UseGuards(...guards: GuardClass[]) {\n return attachClasses('guards', guards, 'UseGuards')\n}\n","import { attachClasses } from '../metadata/attach-classes.mjs'\n\nimport type { InterceptorClass } from './interceptor.mjs'\n\n/**\n * Adds interceptors to a module, a controller or a handler. The first one\n * given is the outermost. They run for what the guards let through, unlike the\n * interceptors of the application.\n *\n * On a class, place it above `@Controller` / `@Module`.\n */\nexport function UseInterceptors(...interceptors: InterceptorClass[]) {\n return attachClasses('interceptors', interceptors, 'UseInterceptors')\n}\n","import { InjectableScope, registerInjectable } from '@navios/di'\n\nimport type { ClassType } from '@navios/di'\n\nimport { applyAttributes } from '../attributes/attribute-value.mjs'\n\nimport { defineModuleMetadata } from './module-metadata.mjs'\n\nimport type { ModuleOptions } from './module-options.mjs'\n\n/**\n * Marks a class as a module: a group of handlers with shared guards,\n * interceptors and attributes.\n */\nexport function Module(options: ModuleOptions = {}) {\n return <T extends ClassType>(target: T, context: ClassDecoratorContext): T => {\n if (context.kind !== 'class') {\n throw new Error('[Navios] @Module can only be used on classes.')\n }\n applyAttributes(defineModuleMetadata(target, context, options).attributes, options.attributes)\n registerInjectable(target, { scope: InjectableScope.Singleton })\n return target\n }\n}\n\n/**\n * Registers a class as a module without decorator syntax.\n */\nexport function registerModule<T extends ClassType>(target: T, options: ModuleOptions = {}): T {\n applyAttributes(\n defineModuleMetadata(target, { metadata: {} }, options).attributes,\n options.attributes,\n )\n registerInjectable(target, { scope: InjectableScope.Singleton })\n return target\n}\n"],"mappings":";;;;AAoCA,SAAS,MAAM,OAAe,OAAsC;CAClE,MAAM,aAAa,QAAa,YAA8B;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,cAAc,gBAAgB,cAAc,iBAAiB;AACtE;;;;;;ACCA,SAAgB,OAAO,UAAyB,CAAC,GAAG;CAClD,QAA6B,QAAW,YAAsC;EAC5E,IAAI,QAAQ,SAAS,SACnB,MAAM,IAAI,MAAM,+CAA+C;EAEjEC,wBAAAA,gBAAgBC,wBAAAA,qBAAqB,QAAQ,SAAS,OAAO,CAAC,CAAC,YAAY,QAAQ,UAAU;EAC7FC,CAAAA,GAAAA,WAAAA,mBAAAA,CAAmB,QAAQ,EAAE,OAAOC,WAAAA,gBAAgB,UAAU,CAAC;EAC/D,OAAO;CACT;AACF;;;;AAKA,SAAgB,eAAoC,QAAW,UAAyB,CAAC,GAAM;CAC7FH,wBAAAA,gBACEC,wBAAAA,qBAAqB,QAAQ,EAAE,UAAU,CAAC,EAAE,GAAG,OAAO,CAAC,CAAC,YACxD,QAAQ,UACV;CACAC,CAAAA,GAAAA,WAAAA,mBAAAA,CAAmB,QAAQ,EAAE,OAAOC,WAAAA,gBAAgB,UAAU,CAAC;CAC/D,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"module-graph-DCP9MHG0.cjs","names":["isDeepStrictEqual","getModuleMetadata","assertImportsDefined"],"sources":["../src/modules/module-graph.mts"],"sourcesContent":["import { isDeepStrictEqual } from 'node:util'\n\nimport type { ClassType, Provider } from '@navios/di'\n\nimport { assertImportsDefined, 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/** 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 addAll<T>(target: T[], source: Iterable<T>): void {\n for (const item of source) {\n if (!target.includes(item)) {\n target.push(item)\n }\n }\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 imports = metadata.imports\n assertImportsDefined(module, imports)\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 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 addAll(node.guards, metadata.guards)\n addAll(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 addAll(child.node.guards, node.guards)\n addAll(child.node.interceptors, node.interceptors)\n }\n }\n return order\n}\n"],"mappings":";;;AAmDA,SAAS,OAAU,QAAa,QAA2B;CACzD,KAAK,MAAM,QAAQ,QACjB,IAAI,CAAC,OAAO,SAAS,IAAI,GACvB,OAAO,KAAK,IAAI;AAGtB;AAEA,SAAS,MAAM,MAAoC;CACjD,OAAO,KAAK,KAAK,WAAW,OAAO,IAAI,CAAC,CAAC,KAAK,MAAM;AACtD;;AAGA,SAAS,OAAO,MAA+B;CAC7C,MAAM,OAAO,CAAC,KAAK,MAAM;CACzB,KAAK,IAAI,KAAK,MAAM,CAAC,GAAG,UAAU,GAAG,UAAU,SAAS,IAAI;EAC1D,KAAK,GAAG,UAAU;EAClB,KAAK,QAAQ,GAAG,MAAM;CACxB;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,kBAAkB,OAAc,W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Q,OAAO;EACxB,MAAM,MAAM,IAAI;EAChB,OAAO,IAAI,IAAI,CAAC,CAAE,KAAK,SAAS;CAClC;CAKA,MAAM,iBAA0B,CAAC;CACjC,MAAM,QAAQ,UAAuB;EACnC,IAAI,MAAM,QACR;EAEF,MAAM,SAAS;EACf,MAAM,UAAU,MAAM,SAAS;EAC/B,KAAK,IAAI,IAAI,QAAQ,SAAS,GAAG,KAAK,GAAG,KACvC,KAAK,OAAO,IAAI,QAAQ,EAAE,CAAE;EAE9B,eAAe,KAAK,KAAK;CAC3B;CACA,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KACrC,KAAK,OAAO,IAAI,MAAM,EAAE,CAAE;CAE5B,eAAe,QAAQ;CAIvB,KAAK,MAAM,SAAS,gBAAgB;EAClC,MAAM,EAAE,MAAM,aAAa;EAC3B,OAAO,KAAK,QAAQ,SAAS,MAAM;EACnC,OAAO,KAAK,cAAc,SAAS,YAAY;EAC/C,kBACE,OACA,KAAK,UAAU,KAAK,aAAa,OAAO,IAAI,SAAS,MAAM,CAAE,CAC/D;EACA,KAAK,MAAM,CAAC,KAAK,UAAU,SAAS,YAClC,KAAK,WAAW,IAAI,KAAK,KAAK;EAEhC,KAAK,MAAM,YAAY,SAAS,SAAS;GACvC,MAAM,QAAQ,OAAO,IAAI,QAAQ;GACjC,OAAO,MAAM,KAAK,QAAQ,KAAK,MAAM;GACrC,OAAO,MAAM,KAAK,cAAc,KAAK,YAAY;EACnD;CACF;CACA,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"module-graph-xvVEykFM.mjs","names":[],"sources":["../src/modules/module-graph.mts"],"sourcesContent":["import { isDeepStrictEqual } from 'node:util'\n\nimport type { ClassType, Provider } from '@navios/di'\n\nimport { assertImportsDefined, 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/** 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 addAll<T>(target: T[], source: Iterable<T>): void {\n for (const item of source) {\n if (!target.includes(item)) {\n target.push(item)\n }\n }\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 imports = metadata.imports\n assertImportsDefined(module, imports)\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 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 addAll(node.guards, metadata.guards)\n addAll(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 addAll(child.node.guards, node.guards)\n addAll(child.node.interceptors, node.interceptors)\n }\n }\n return order\n}\n"],"mappings":";;;AAmDA,SAAS,OAAU,QAAa,QAA2B;CACzD,KAAK,MAAM,QAAQ,QACjB,IAAI,CAAC,OAAO,SAAS,IAAI,GACvB,OAAO,KAAK,IAAI;AAGtB;AAEA,SAAS,MAAM,MAAoC;CACjD,OAAO,KAAK,KAAK,WAAW,OAAO,IAAI,CAAC,CAAC,KAAK,MAAM;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js");
|
|
2
|
-
// src/modules/module-metadata.mts
|
|
3
|
-
const ModuleMetadataKey = Symbol.for("navios.core.module");
|
|
4
|
-
const ownOptions = /* @__PURE__ */ new Set([
|
|
5
|
-
"imports",
|
|
6
|
-
"guards",
|
|
7
|
-
"interceptors",
|
|
8
|
-
"providers",
|
|
9
|
-
"attributes"
|
|
10
|
-
]);
|
|
11
|
-
function defineModuleMetadata(target, context, options) {
|
|
12
|
-
if (hasModuleMetadata(target)) throw new Error(`[Navios] ${target.name} is already a module. One @Module takes all of its options.`);
|
|
13
|
-
const entries = /* @__PURE__ */ new Map();
|
|
14
|
-
for (const [name, value] of Object.entries(options)) if (!ownOptions.has(name) && value !== void 0) entries.set(name, value);
|
|
15
|
-
const imports = require_attribute_value.unique([...options.imports ?? []]);
|
|
16
|
-
assertImportsDefined(target, imports);
|
|
17
|
-
const providers = [...options.providers ?? []];
|
|
18
|
-
assertProviders(target.name, providers);
|
|
19
|
-
const base = Object.getPrototypeOf(target)[ModuleMetadataKey];
|
|
20
|
-
const module = {
|
|
21
|
-
imports,
|
|
22
|
-
guards: require_attribute_value.prepend(require_attribute_value.prepend(require_attribute_value.classGuards(context), base?.guards), options.guards),
|
|
23
|
-
interceptors: require_attribute_value.prepend(require_attribute_value.prepend(require_attribute_value.classInterceptors(context), base?.interceptors), options.interceptors),
|
|
24
|
-
providers,
|
|
25
|
-
attributes: require_attribute_value.classAttributes(context),
|
|
26
|
-
entries
|
|
27
|
-
};
|
|
28
|
-
for (const [key, value] of base?.attributes ?? []) if (!module.attributes.has(key)) module.attributes.set(key, value);
|
|
29
|
-
Object.defineProperty(target, ModuleMetadataKey, {
|
|
30
|
-
value: module,
|
|
31
|
-
configurable: true,
|
|
32
|
-
enumerable: false
|
|
33
|
-
});
|
|
34
|
-
return module;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* An import that is `undefined` is what an import cycle between files leaves
|
|
38
|
-
* behind: the importing file ran before the imported one defined its class.
|
|
39
|
-
* @internal
|
|
40
|
-
*/
|
|
41
|
-
function assertImportsDefined(target, imports) {
|
|
42
|
-
const index = imports.findIndex((imported) => imported === void 0 || imported === null);
|
|
43
|
-
if (index !== -1) throw new Error(`[Navios] Module ${target.name} imports ${String(imports[index])} at index ${index} of its imports. This usually means the files of the two modules import each other, so the imported module was not defined yet when ${target.name} was. Break the import cycle.`);
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Where there are no types, a class is easily listed for itself.
|
|
47
|
-
* @internal
|
|
48
|
-
*/
|
|
49
|
-
function assertProviders(owner, providers) {
|
|
50
|
-
for (const provider of providers) {
|
|
51
|
-
if (typeof provider === "object" && provider !== null && "token" in provider) continue;
|
|
52
|
-
const listed = typeof provider === "function" ? provider.name : typeof provider === "object" && provider !== null ? "an object" : String(provider);
|
|
53
|
-
throw new Error(`[Navios] ${owner} lists ${listed} in providers, which is not a provider. Use provide(token, ...); an @Injectable class needs no entry.`);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function getModuleMetadata(target) {
|
|
57
|
-
const metadata = Object.hasOwn(target, ModuleMetadataKey) ? target[ModuleMetadataKey] : void 0;
|
|
58
|
-
if (!metadata) throw new Error(`[Navios] ${target.name} is not a module. Make sure it is decorated with @Module.`);
|
|
59
|
-
return metadata;
|
|
60
|
-
}
|
|
61
|
-
function hasModuleMetadata(target) {
|
|
62
|
-
return Object.hasOwn(target, ModuleMetadataKey);
|
|
63
|
-
}
|
|
64
|
-
Object.defineProperty(exports, "assertImportsDefined", {
|
|
65
|
-
enumerable: true,
|
|
66
|
-
get: function() {
|
|
67
|
-
return assertImportsDefined;
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
Object.defineProperty(exports, "assertProviders", {
|
|
71
|
-
enumerable: true,
|
|
72
|
-
get: function() {
|
|
73
|
-
return assertProviders;
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
Object.defineProperty(exports, "defineModuleMetadata", {
|
|
77
|
-
enumerable: true,
|
|
78
|
-
get: function() {
|
|
79
|
-
return defineModuleMetadata;
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
Object.defineProperty(exports, "getModuleMetadata", {
|
|
83
|
-
enumerable: true,
|
|
84
|
-
get: function() {
|
|
85
|
-
return getModuleMetadata;
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
Object.defineProperty(exports, "hasModuleMetadata", {
|
|
89
|
-
enumerable: true,
|
|
90
|
-
get: function() {
|
|
91
|
-
return hasModuleMetadata;
|
|
92
|
-
}
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
//# sourceMappingURL=module-metadata-C8S92seK.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"module-metadata-C8S92seK.cjs","names":["unique","prepend","classGuards","classInterceptors","classAttributes"],"sources":["../src/modules/module-metadata.mts"],"sourcesContent":["import type { ClassType, Provider } from '@navios/di'\n\nimport {\n classAttributes,\n classGuards,\n classInterceptors,\n prepend,\n unique,\n} from '../metadata/class-metadata.mjs'\n\nimport type { DecoratorMetadata } from '../metadata/decorator-metadata.mjs'\n\nimport type { ModuleOptions } from './module-options.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ModuleMetadata {\n imports: ClassType[]\n guards: ClassType[]\n interceptors: ClassType[]\n providers: Provider[]\n attributes: Map<symbol, unknown>\n /**\n * Every option the module system itself does not use, by option name, as\n * written. A transport reads its own from here.\n */\n entries: Map<string, unknown>\n}\n\nconst ModuleMetadataKey = Symbol.for('navios.core.module')\n\nconst ownOptions = new Set(['imports', 'guards', 'interceptors', 'providers', 'attributes'])\n\nexport function defineModuleMetadata(\n target: ClassType,\n context: { metadata?: DecoratorMetadata },\n options: ModuleOptions,\n): ModuleMetadata {\n if (hasModuleMetadata(target)) {\n throw new Error(\n `[Navios] ${target.name} is already a module. One @Module takes all of its options.`,\n )\n }\n const entries = new Map<string, unknown>()\n for (const [name, value] of Object.entries(options)) {\n if (!ownOptions.has(name) && value !== undefined) {\n entries.set(name, value)\n }\n }\n const imports = unique([...(options.imports ?? [])])\n assertImportsDefined(target, imports)\n const providers = [...(options.providers ?? [])]\n assertProviders(target.name, providers)\n // Decorator metadata inherits by itself between two decorated classes. This\n // covers a class or a base class that was registered without decorators.\n const base = Object.getPrototypeOf(target)[ModuleMetadataKey] as ModuleMetadata | undefined\n const module: ModuleMetadata = {\n imports,\n guards: prepend(prepend(classGuards(context), base?.guards), options.guards),\n interceptors: prepend(\n prepend(classInterceptors(context), base?.interceptors),\n options.interceptors,\n ),\n providers,\n attributes: classAttributes(context),\n entries,\n }\n for (const [key, value] of base?.attributes ?? []) {\n if (!module.attributes.has(key)) {\n module.attributes.set(key, value)\n }\n }\n Object.defineProperty(target, ModuleMetadataKey, {\n value: module,\n configurable: true,\n enumerable: false,\n })\n return module\n}\n\n/**\n * An import that is `undefined` is what an import cycle between files leaves\n * behind: the importing file ran before the imported one defined its class.\n * @internal\n */\nexport function assertImportsDefined(target: ClassType, imports: readonly unknown[]): void {\n const index = imports.findIndex((imported) => imported === undefined || imported === null)\n if (index !== -1) {\n throw new Error(\n `[Navios] Module ${target.name} imports ${String(imports[index])} at index ${index} of ` +\n `its imports. This usually means the files of the two modules import each other, so the ` +\n `imported module was not defined yet when ${target.name} was. Break the import cycle.`,\n )\n }\n}\n\n/**\n * Where there are no types, a class is easily listed for itself.\n * @internal\n */\nexport function assertProviders(owner: string, providers: readonly unknown[]): void {\n for (const provider of providers) {\n if (typeof provider === 'object' && provider !== null && 'token' in provider) {\n continue\n }\n const listed =\n typeof provider === 'function'\n ? provider.name\n : typeof provider === 'object' && provider !== null\n ? 'an object'\n : String(provider)\n throw new Error(\n `[Navios] ${owner} lists ${listed} in providers, which is not a provider. Use ` +\n `provide(token, ...); an @Injectable class needs no entry.`,\n )\n }\n}\n\nexport function getModuleMetadata(target: ClassType): ModuleMetadata {\n const metadata = Object.hasOwn(target, ModuleMetadataKey)\n ? ((target as any)[ModuleMetadataKey] as ModuleMetadata)\n : undefined\n if (!metadata) {\n throw new Error(\n `[Navios] ${target.name} is not a module. Make sure it is decorated with @Module.`,\n )\n }\n return metadata\n}\n\nexport function hasModuleMetadata(target: ClassType): boolean {\n return Object.hasOwn(target, ModuleMetadataKey)\n}\n"],"mappings":";;AA6BA,MAAM,oBAAoB,OAAO,IAAI,oBAAoB;AAEzD,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAW;CAAU;CAAgB;CAAa;AAAY,CAAC;AAE3F,SAAgB,qBACd,QACA,SACA,SACgB;CAChB,IAAI,kBAAkB,MAAM,GAC1B,MAAM,IAAI,MACR,YAAY,OAAO,KAAK,4DAC1B;CAEF,MAAM,0BAAU,IAAI,IAAqB;CACzC,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,GAChD,IAAI,CAAC,WAAW,IAAI,IAAI,KAAK,UAAU,KAAA,GACrC,QAAQ,IAAI,MAAM,KAAK;CAG3B,MAAM,UAAUA,wBAAAA,OAAO,CAAC,GAAI,QAAQ,WAAW,CAAC,CAAE,CAAC;CACnD,qBAAqB,QAAQ,OAAO;CACpC,MAAM,YAAY,CAAC,GAAI,QAAQ,aAAa,CAAC,CAAE;CAC/C,gBAAgB,OAAO,MAAM,SAAS;CAGtC,MAAM,OAAO,OAAO,eAAe,MAAM,CAAC,CAAC;CAC3C,MAAM,SAAyB;EAC7B;EACA,QAAQC,wBAAAA,QAAQA,wBAAAA,QAAQC,wBAAAA,YAAY,OAAO,GAAG,MAAM,MAAM,GAAG,QAAQ,MAAM;EAC3E,cAAcD,wBAAAA,QACZA,wBAAAA,QAAQE,wBAAAA,kBAAkB,OAAO,GAAG,MAAM,YAAY,GACtD,QAAQ,YACV;EACA;EACA,YAAYC,wBAAAA,gBAAgB,OAAO;EACnC;CACF;CACA,KAAK,MAAM,CAAC,KAAK,UAAU,MAAM,cAAc,CAAC,GAC9C,IAAI,CAAC,OAAO,WAAW,IAAI,GAAG,GAC5B,OAAO,WAAW,IAAI,KA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