@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,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { d as classGuards, f as classInterceptors, h as requireMetadata, n as MembersKey, p as prepend, t as applyAttributes, u as classAttributes } from "./attribute-value-BNiJjxl1.mjs";
|
|
2
|
+
import { a as needsScope, c as runInContext, t as ExecutionContextToken } from "./execution-context-token-Cb3M3Ao0.mjs";
|
|
3
3
|
// src/transports/transport.mts
|
|
4
4
|
/**
|
|
5
5
|
* Defines a transport.
|
|
@@ -58,9 +58,11 @@ function assertUndisputed({ node, owner, member }) {
|
|
|
58
58
|
}
|
|
59
59
|
/**
|
|
60
60
|
* The guards and interceptors that apply to one handler, in the order they
|
|
61
|
-
* run
|
|
62
|
-
*
|
|
63
|
-
*
|
|
61
|
+
* run, and what its contexts tell about it: the interceptors of the
|
|
62
|
+
* application, then the guards from the module chain, the owning class and
|
|
63
|
+
* the handler, then the interceptors of the same three. A class that appears
|
|
64
|
+
* twice is kept where it first appears. `info.guards` are the guards and
|
|
65
|
+
* `info.interceptors` the interceptors, `outer` and then `inner`.
|
|
64
66
|
*
|
|
65
67
|
* An interceptor of the application sees every execution, denied ones
|
|
66
68
|
* included, as tracing and logging need. One that is attached to handlers runs
|
|
@@ -69,28 +71,39 @@ function assertUndisputed({ node, owner, member }) {
|
|
|
69
71
|
* Throws when the handler would inherit an attribute that the importers of its
|
|
70
72
|
* module do not agree about.
|
|
71
73
|
*
|
|
72
|
-
* Every transport uses this, so the rule is the same everywhere.
|
|
73
|
-
*
|
|
74
|
+
* Every transport uses this, so the rule is the same everywhere.
|
|
75
|
+
* `resolveChain` resolves the chain and `runChain` runs it.
|
|
74
76
|
*/
|
|
75
77
|
function handlerChain(input) {
|
|
76
78
|
assertUndisputed(input);
|
|
77
|
-
const { application, node, owner, member } = input;
|
|
78
|
-
const
|
|
79
|
+
const { application, node, controller, owner, handlerName, member } = input;
|
|
80
|
+
const everywhere = new Set(application);
|
|
79
81
|
const attached = [
|
|
80
82
|
...node.interceptors,
|
|
81
83
|
...owner.interceptors,
|
|
82
84
|
...member.interceptors
|
|
83
85
|
];
|
|
84
|
-
const
|
|
86
|
+
const outer = Array.from(everywhere);
|
|
87
|
+
const inner = Array.from(new Set(attached.filter((interceptor) => !everywhere.has(interceptor))));
|
|
85
88
|
return {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
89
|
+
info: {
|
|
90
|
+
module: node.module,
|
|
91
|
+
controller,
|
|
92
|
+
handlerName,
|
|
93
|
+
guards: Array.from(/* @__PURE__ */ new Set([
|
|
94
|
+
...node.guards,
|
|
95
|
+
...owner.guards,
|
|
96
|
+
...member.guards
|
|
97
|
+
])),
|
|
98
|
+
interceptors: [...outer, ...inner],
|
|
99
|
+
attributes: {
|
|
100
|
+
handler: member.attributes,
|
|
101
|
+
controller: owner.attributes,
|
|
102
|
+
module: node.attributes
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
outer,
|
|
106
|
+
inner
|
|
94
107
|
};
|
|
95
108
|
}
|
|
96
109
|
// src/metadata/run-chain.mts
|
|
@@ -100,15 +113,15 @@ async function resolve(container, type, kind, method) {
|
|
|
100
113
|
return instance;
|
|
101
114
|
}
|
|
102
115
|
/**
|
|
103
|
-
* Resolves the classes of a chain. A transport
|
|
104
|
-
* while it is set up.
|
|
116
|
+
* Resolves the classes of a chain that `handlerChain` returned. A transport
|
|
117
|
+
* does this once per handler, while it is set up.
|
|
105
118
|
*/
|
|
106
119
|
async function resolveChain(container, chain) {
|
|
107
120
|
const outer = [];
|
|
108
121
|
const guards = [];
|
|
109
122
|
const inner = [];
|
|
110
123
|
for (const type of chain.outer) outer.push(await resolve(container, type, "Interceptor", "intercept"));
|
|
111
|
-
for (const type of chain.guards) guards.push({
|
|
124
|
+
for (const type of chain.info.guards) guards.push({
|
|
112
125
|
type,
|
|
113
126
|
guard: await resolve(container, type, "Guard", "canActivate")
|
|
114
127
|
});
|
|
@@ -141,6 +154,22 @@ function runChain(ctx, chain, handler, onDenied) {
|
|
|
141
154
|
};
|
|
142
155
|
return intercepted(ctx, chain.outer, guarded)();
|
|
143
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Runs a handler with what applies to it, as `runChain`, in the async context
|
|
159
|
+
* when the application keeps one, and then finishes its context, whatever the
|
|
160
|
+
* outcome. The context is finished inside the async context, so that
|
|
161
|
+
* `currentContext()` still answers in `onFinish` callbacks.
|
|
162
|
+
*/
|
|
163
|
+
function executeChain(host, ctx, chain, handler, onDenied) {
|
|
164
|
+
const execute = async () => {
|
|
165
|
+
try {
|
|
166
|
+
return await runChain(ctx, chain, handler, onDenied);
|
|
167
|
+
} finally {
|
|
168
|
+
await ctx.finish();
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
return host.asyncContext ? runInContext(ctx, execute) : execute();
|
|
172
|
+
}
|
|
144
173
|
// src/execution/basic-execution-context.mts
|
|
145
174
|
/**
|
|
146
175
|
* An `ExecutionContext` for transports that need nothing beyond the neutral
|
|
@@ -152,7 +181,6 @@ var BasicExecutionContext = class {
|
|
|
152
181
|
id;
|
|
153
182
|
handler;
|
|
154
183
|
host;
|
|
155
|
-
givenSignal;
|
|
156
184
|
ownSignal = null;
|
|
157
185
|
slots = null;
|
|
158
186
|
scope = null;
|
|
@@ -164,11 +192,13 @@ var BasicExecutionContext = class {
|
|
|
164
192
|
this.id = init.id;
|
|
165
193
|
this.handler = init.handler;
|
|
166
194
|
this.host = init.host;
|
|
167
|
-
this.givenSignal = init.signal;
|
|
168
195
|
}
|
|
169
|
-
/**
|
|
196
|
+
/**
|
|
197
|
+
* A signal that never aborts. Not shared between contexts: listeners would
|
|
198
|
+
* outlive their execution.
|
|
199
|
+
*/
|
|
170
200
|
get signal() {
|
|
171
|
-
return this.
|
|
201
|
+
return this.ownSignal ??= new AbortController().signal;
|
|
172
202
|
}
|
|
173
203
|
get(key) {
|
|
174
204
|
const slots = this.slots;
|
|
@@ -190,9 +220,10 @@ var BasicExecutionContext = class {
|
|
|
190
220
|
* @internal
|
|
191
221
|
*/
|
|
192
222
|
resolverFor(token) {
|
|
193
|
-
const { container } = this.host;
|
|
194
|
-
if (this.scope
|
|
195
|
-
|
|
223
|
+
const { container, onScopedUse } = this.host;
|
|
224
|
+
if (this.scope !== null && onScopedUse === null) return this.scope;
|
|
225
|
+
if (!needsScope(container, token)) return this.scope ?? container;
|
|
226
|
+
onScopedUse?.(token);
|
|
196
227
|
if (this.scope === null) {
|
|
197
228
|
if (this.finished) throw new Error("[Navios] Request-scoped services cannot be used: the execution has finished, so nothing would dispose them.");
|
|
198
229
|
this.scope = container.createScope();
|
|
@@ -241,6 +272,6 @@ BasicExecutionContext.prototype.use = function use(token, args) {
|
|
|
241
272
|
BasicExecutionContext.prototype.resolve = function resolve(token, args) {
|
|
242
273
|
return this.resolverFor(token).get(token, args);
|
|
243
274
|
};
|
|
244
|
-
export {
|
|
275
|
+
export { handlerChain as a, runChain as i, executeChain as n, describeHandlerClass as o, resolveChain as r, defineTransport as s, BasicExecutionContext as t };
|
|
245
276
|
|
|
246
|
-
//# sourceMappingURL=basic-execution-context-
|
|
277
|
+
//# sourceMappingURL=basic-execution-context-u1VktGoM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"basic-execution-context-u1VktGoM.mjs","names":[],"sources":["../src/transports/transport.mts","../src/metadata/handler-class.mts","../src/metadata/handler-chain.mts","../src/metadata/run-chain.mts","../src/execution/basic-execution-context.mts"],"sourcesContent":["import type { ClassType, Container } from '@navios/di'\n\nimport type { ContextHost } from '../execution/context-host.mjs'\nimport type { OptionsArgument } from '../internal/options-argument.mjs'\nimport type { LoggerService } from '../logger/logger-output.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * What the application gives a transport when it creates it.\n */\nexport interface TransportHost {\n readonly container: Container\n readonly logger: LoggerService\n /** For the transport's execution contexts. */\n readonly contextHost: ContextHost\n /** Whether the application keeps the current context in an async store. */\n readonly asyncContext: boolean\n /**\n * Interceptors around every handler of the application, outermost first.\n * Complete once `setup()` is called.\n */\n readonly interceptors: readonly ClassType[]\n}\n\n/**\n * One way work reaches the application: an HTTP server, a queue consumer, a\n * command line. The application creates it, hands it the module graph, and\n * starts and stops it together with the others.\n */\nexport interface Transport {\n /**\n * Reads the module graph and prepares the transport's handlers. Must not\n * start accepting work.\n */\n setup(graph: readonly ModuleNode[]): void | Promise<void>\n /** Starts accepting work. Called at most once. */\n start?(): void | Promise<void>\n /**\n * Stops accepting work and waits, up to `timeoutMs`, for what is in flight.\n * One that takes much longer is left behind. When the application fails to\n * initialise or to start it is called for every transport that was created,\n * with no time to wait and possibly before `setup` or `start` ran; it must\n * release what `create` acquired. Called once, and again when `start` settles\n * only after that.\n */\n stop(timeoutMs: number): void | Promise<void>\n}\n\nexport interface TransportDefinition<Options, T extends Transport> {\n /** The kind of transport, and the default name of an instance. */\n name: string\n create(host: TransportHost, options: Options): T | Promise<T>\n}\n\n/**\n * A transport as it is listed in an application's options.\n */\nexport interface TransportInstance<T extends Transport = Transport> {\n readonly definition: TransportDefinition<any, T>\n /** `{}` when the transport was given none. */\n readonly options: unknown\n /** Unique within the application. Defaults to the definition's name. */\n readonly instanceName: string\n}\n\n/**\n * What `defineTransport` returns: called with options it gives the instance\n * to list in an application, and it is the key to look the transport up with.\n */\nexport interface TransportFactory<Options, T extends Transport> {\n (...args: OptionsArgument<Options, [instanceName?: string]>): TransportInstance<T>\n readonly definition: TransportDefinition<Options, T>\n}\n\n/**\n * Defines a transport.\n *\n * ```ts\n * export const queueTransport = defineTransport({\n * name: 'queue',\n * create(host, options: { url: string }) {\n * return new QueueTransport(host, options)\n * },\n * })\n *\n * const app = createApplication(AppModule, {\n * transports: [queueTransport({ url })],\n * })\n * await app.start()\n * app.transport(queueTransport) // the QueueTransport\n * ```\n *\n * An application can hold several transports of one definition when each has\n * its own name: `queueTransport({ url }, 'orders')`.\n */\nexport function defineTransport<Options = void, T extends Transport = Transport>(\n definition: TransportDefinition<Options, T>,\n): TransportFactory<Options, T> {\n const factory = (options?: Options, instanceName?: string): TransportInstance<T> => ({\n definition,\n options: options ?? {},\n instanceName: instanceName ?? definition.name,\n })\n return Object.assign(factory, { definition })\n}\n","import type { ClassType } from '@navios/di'\n\nimport { applyAttributes } from '../attributes/attribute-value.mjs'\n\nimport type { AttributeValue } from '../attributes/attribute-value.mjs'\n\nimport { classAttributes, classGuards, classInterceptors, prepend } from './class-metadata.mjs'\nimport { requireMetadata } from './decorator-metadata.mjs'\nimport { MembersKey } from './member-metadata.mjs'\n\nimport type { DecoratorMetadata } from './decorator-metadata.mjs'\nimport type { HandlerExtras, MethodHandlerMetadata } from './member-metadata.mjs'\n\n/** What a transport's decorator for handler classes may take. */\nexport interface HandlerClassOptions {\n guards?: Iterable<ClassType>\n interceptors?: Iterable<ClassType>\n attributes?: AttributeValue[]\n}\n\n/** A class that owns handlers: what applies to all of them, and its members. */\nexport interface HandlerClassMetadata extends HandlerExtras {\n /** The members decorators were applied to, by name. */\n members: Map<string, MethodHandlerMetadata>\n}\n\n/**\n * What decorators attached to a class of handlers and to its members, together\n * with the options of the class decorator that asks. The lists are live:\n * `@UseGuards` and the like placed above that decorator run after it and are\n * still seen.\n */\nexport function describeHandlerClass(\n context: { metadata?: DecoratorMetadata },\n options: HandlerClassOptions = {},\n): HandlerClassMetadata {\n const metadata = requireMetadata(context)\n const attributes = classAttributes(context)\n applyAttributes(attributes, options.attributes)\n return {\n guards: prepend(classGuards(context), options.guards),\n interceptors: prepend(classInterceptors(context), options.interceptors),\n attributes,\n members: (metadata[MembersKey] as Map<string, MethodHandlerMetadata> | undefined) ?? new Map(),\n }\n}\n","import type { ClassType } from '@navios/di'\n\nimport type { HandlerInfo } from '../execution/execution-context.mjs'\nimport type { ModuleNode } from '../modules/module-graph.mjs'\n\ninterface Extras {\n readonly guards: readonly ClassType[]\n readonly interceptors: readonly ClassType[]\n}\n\ninterface OwnExtras extends Extras {\n readonly attributes: ReadonlyMap<symbol, unknown>\n}\n\nexport interface HandlerChainInput {\n /**\n * Interceptors around every handler of the application or of the transport,\n * outermost first.\n */\n application: readonly ClassType[]\n /** The module the handler belongs to, with what it inherits. */\n node: Extras & Pick<ModuleNode, 'module' | 'attributes' | 'disputed'>\n /** The class that owns the handler. */\n controller: ClassType\n /** What applies to every handler of `controller`. */\n owner: OwnExtras\n /** The name of the handler in its class. */\n handlerName: string\n /** The handler itself. */\n member: OwnExtras\n}\n\nexport interface HandlerChain {\n /** What the contexts of the handler tell about it. */\n info: HandlerInfo\n /** Interceptors around the guards: those of the application. */\n outer: ClassType[]\n /** Interceptors inside the guards: those of the module, the class and the handler. */\n inner: ClassType[]\n}\n\n/**\n * An attribute may open the handler to everyone or restrict it, so it is not\n * guessed which of the import paths is meant.\n */\nfunction assertUndisputed({ node, owner, member }: HandlerChainInput): void {\n for (const [key, paths] of node.disputed) {\n if (!owner.attributes.has(key) && !member.attributes.has(key)) {\n throw new Error(\n `[Navios] Module ${node.module.name} inherits different values of the attribute ` +\n `${String(key)}: ${paths}. Set it on the controllers or handlers it is meant for, or ` +\n `on ${node.module.name} itself.`,\n )\n }\n }\n}\n\n/**\n * The guards and interceptors that apply to one handler, in the order they\n * run, and what its contexts tell about it: the interceptors of the\n * application, then the guards from the module chain, the owning class and\n * the handler, then the interceptors of the same three. A class that appears\n * twice is kept where it first appears. `info.guards` are the guards and\n * `info.interceptors` the interceptors, `outer` and then `inner`.\n *\n * An interceptor of the application sees every execution, denied ones\n * included, as tracing and logging need. One that is attached to handlers runs\n * only for what their guards let through.\n *\n * Throws when the handler would inherit an attribute that the importers of its\n * module do not agree about.\n *\n * Every transport uses this, so the rule is the same everywhere.\n * `resolveChain` resolves the chain and `runChain` runs it.\n */\nexport function handlerChain(input: HandlerChainInput): HandlerChain {\n assertUndisputed(input)\n const { application, node, controller, owner, handlerName, member } = input\n const everywhere = new Set(application)\n const attached = [...node.interceptors, ...owner.interceptors, ...member.interceptors]\n const outer = Array.from(everywhere)\n const inner = Array.from(new Set(attached.filter((interceptor) => !everywhere.has(interceptor))))\n return {\n info: {\n module: node.module,\n controller,\n handlerName,\n guards: Array.from(new Set([...node.guards, ...owner.guards, ...member.guards])),\n interceptors: [...outer, ...inner],\n attributes: {\n handler: member.attributes,\n controller: owner.attributes,\n module: node.attributes,\n },\n },\n outer,\n inner,\n }\n}\n","import type { ClassType, Container } from '@navios/di'\n\nimport { runInContext } from '../execution/async-context.mjs'\n\nimport type { ExecutionContext, HandlerInfo } from '../execution/execution-context.mjs'\nimport type { Guard } from '../guards/guard.mjs'\nimport type { Interceptor } from '../interceptors/interceptor.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A handler's chain with its instances, ready to run. */\nexport interface ResolvedChain<Ctx extends ExecutionContext = ExecutionContext, Result = unknown> {\n readonly outer: ReadonlyArray<Interceptor<Ctx, Result>>\n readonly guards: ReadonlyArray<{ readonly type: ClassType; readonly guard: Guard<Ctx> }>\n readonly inner: ReadonlyArray<Interceptor<Ctx, Result>>\n}\n\nasync function resolve(\n container: Pick<Container, 'get'>,\n type: ClassType,\n kind: string,\n method: string,\n): Promise<any> {\n const instance = (await container.get(type)) as any\n if (typeof instance?.[method] !== 'function') {\n throw new Error(`[Navios] ${kind} ${type.name} does not implement ${method}()`)\n }\n return instance\n}\n\n/**\n * Resolves the classes of a chain that `handlerChain` returned. A transport\n * does this once per handler, while it is set up.\n */\nexport async function resolveChain<\n Ctx extends ExecutionContext = ExecutionContext,\n Result = unknown,\n>(\n container: Pick<Container, 'get'>,\n chain: {\n readonly info: Pick<HandlerInfo, 'guards'>\n readonly outer: readonly ClassType[]\n readonly inner: readonly ClassType[]\n },\n): Promise<ResolvedChain<Ctx, Result>> {\n const outer: Interceptor<Ctx, Result>[] = []\n const guards: Array<{ type: ClassType; guard: Guard<Ctx> }> = []\n const inner: Interceptor<Ctx, Result>[] = []\n for (const type of chain.outer) {\n outer.push(await resolve(container, type, 'Interceptor', 'intercept'))\n }\n for (const type of chain.info.guards) {\n guards.push({ type, guard: await resolve(container, type, 'Guard', 'canActivate') })\n }\n for (const type of chain.inner) {\n inner.push(await resolve(container, type, 'Interceptor', 'intercept'))\n }\n return { outer, guards, inner }\n}\n\nfunction intercepted<Ctx extends ExecutionContext, Result>(\n ctx: Ctx,\n interceptors: ReadonlyArray<Interceptor<Ctx, Result>>,\n innermost: () => Result | Promise<Result>,\n): () => Promise<Result> {\n let next = async () => innermost()\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i]\n const inner = next\n next = async () => interceptor.intercept(ctx, inner)\n }\n return next\n}\n\n/**\n * Runs a handler with what applies to it: the outer interceptors, the guards\n * one after another, the inner interceptors, the handler. When a guard refuses,\n * nothing further runs and `onDenied` says what becomes of the execution: what\n * it returns is the result, and what it throws is the failure.\n */\nexport function runChain<Ctx extends ExecutionContext, Result>(\n ctx: Ctx,\n chain: ResolvedChain<Ctx, Result>,\n handler: () => Result | Promise<Result>,\n onDenied: (guard: ClassType) => Result | Promise<Result>,\n): Promise<Result> {\n const guarded = async (): Promise<Result> => {\n for (const { type, guard } of chain.guards) {\n if ((await guard.canActivate(ctx)) !== true) {\n return onDenied(type)\n }\n }\n return intercepted(ctx, chain.inner, handler)()\n }\n return intercepted(ctx, chain.outer, guarded)()\n}\n\n/**\n * Runs a handler with what applies to it, as `runChain`, in the async context\n * when the application keeps one, and then finishes its context, whatever the\n * outcome. The context is finished inside the async context, so that\n * `currentContext()` still answers in `onFinish` callbacks.\n */\nexport function executeChain<Ctx extends ExecutionContext & { finish(): Promise<void> }, Result>(\n host: { readonly asyncContext: boolean },\n ctx: Ctx,\n chain: ResolvedChain<Ctx, Result>,\n handler: () => Result | Promise<Result>,\n onDenied: (guard: ClassType) => Result | Promise<Result>,\n): Promise<Result> {\n const execute = async (): Promise<Result> => {\n try {\n return await runChain(ctx, chain, handler, onDenied)\n } finally {\n await ctx.finish()\n }\n }\n return host.asyncContext ? runInContext(ctx, execute) : execute()\n}\n","import type { AnyInjectableType, Container, ScopedContainer } from '@navios/di'\n\nimport { needsScope } from './context-host.mjs'\nimport { ExecutionContextToken } from './execution-context-token.mjs'\n\nimport type { ContextHost } from './context-host.mjs'\nimport type { ContextKey, ContextValue } from './context-key.mjs'\nimport type { ExecutionContext, HandlerInfo } from './execution-context.mjs'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface BasicExecutionContextInit {\n /** The transport kind, for example `'cli'`. */\n kind: string\n id: string\n handler: HandlerInfo\n host: ContextHost\n}\n\n/**\n * An `ExecutionContext` for transports that need nothing beyond the neutral\n * contract. The transport creates one per execution and calls `finish()` when\n * the handler is done.\n */\nexport class BasicExecutionContext implements ExecutionContext {\n readonly kind: string\n readonly id: string\n readonly handler: HandlerInfo\n private readonly host: ContextHost\n private ownSignal: AbortSignal | null = null\n private slots: Map<ContextKey, unknown> | null = null\n private scope: ScopedContainer | null = null\n private finishers: Array<() => void | Promise<void>> | null = null\n private finished = false\n private finishing: Promise<void> | null = null\n\n constructor(init: BasicExecutionContextInit) {\n this.kind = init.kind\n this.id = init.id\n this.handler = init.handler\n this.host = init.host\n }\n\n /**\n * A signal that never aborts. Not shared between contexts: listeners would\n * outlive their execution.\n */\n get signal(): AbortSignal {\n return (this.ownSignal ??= new AbortController().signal)\n }\n\n get<K extends ContextKey>(key: K): ContextValue<K> {\n const slots = this.slots\n if (slots === null || !slots.has(key)) {\n throw new Error(\n `[Navios] Context key ${key.name} is not set. ` +\n `Set it with ctx.set() (usually in a guard), or read it with ctx.find().`,\n )\n }\n return slots.get(key) as ContextValue<K>\n }\n\n find<K extends ContextKey>(key: K): ContextValue<K> | undefined {\n return this.slots?.get(key) as ContextValue<K> | undefined\n }\n\n set<K extends ContextKey>(key: K, value: ContextValue<K>): void {\n ;(this.slots ??= new Map()).set(key, value)\n }\n\n has(key: ContextKey): boolean {\n return this.slots?.has(key) ?? false\n }\n\n /**\n * What resolves a token for this execution: its DI scope, which is created\n * when something needs it.\n * @internal\n */\n resolverFor(token: AnyInjectableType): Container | ScopedContainer {\n const { container, onScopedUse } = this.host\n if (this.scope !== null && onScopedUse === null) {\n return this.scope\n }\n if (!needsScope(container, token)) {\n return this.scope ?? container\n }\n onScopedUse?.(token)\n if (this.scope === null) {\n if (this.finished) {\n throw new Error(\n '[Navios] Request-scoped services cannot be used: the execution has finished, so ' +\n 'nothing would dispose them.',\n )\n }\n this.scope = container.createScope()\n this.scope.addInstance(ExecutionContextToken, this)\n }\n return this.scope\n }\n\n declare use: ScopedContainer['getSync']\n\n declare resolve: ScopedContainer['get']\n\n onFinish(callback: () => void | Promise<void>): void {\n if (this.finished) {\n void this.runFinisher(callback)\n return\n }\n ;(this.finishers ??= []).push(callback)\n }\n\n /**\n * Runs the `onFinish` callbacks in reverse order, those they register\n * included, then disposes the DI scope. Runs once, however often it is\n * called; every caller waits for that run.\n */\n finish(): Promise<void> {\n return (this.finishing ??= this.runFinishers())\n }\n\n private async runFinishers(): Promise<void> {\n let finisher: (() => void | Promise<void>) | undefined\n while ((finisher = this.finishers?.pop()) !== undefined) {\n await this.runFinisher(finisher)\n }\n this.finished = true\n this.ownSignal = null\n const scope = this.scope\n this.scope = null\n if (scope !== null) {\n await scope.dispose()\n }\n }\n\n /** Runs a callback whose failure must not stop what follows. */\n private async runFinisher(callback: () => void | Promise<void>): Promise<void> {\n try {\n await callback()\n } catch (error) {\n // A failing callback must not stop the others, so it is only reported.\n try {\n this.host.logger?.error(`Error in an onFinish callback of ${this.kind} ${this.id}`, error)\n } catch {\n // Nor may a failing logger.\n }\n }\n }\n}\n\nBasicExecutionContext.prototype.use = function use(\n this: BasicExecutionContext,\n token: AnyInjectableType,\n args?: unknown,\n) {\n return (this.resolverFor(token).getSync as any)(token, args)\n} as ScopedContainer['getSync']\n\nBasicExecutionContext.prototype.resolve = function resolve(\n this: BasicExecutionContext,\n token: AnyInjectableType,\n args?: unknown,\n) {\n return (this.resolverFor(token).get as any)(token, args)\n} as ScopedContainer['get']\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiGA,SAAgB,gBACd,YAC8B;CAC9B,MAAM,WAAW,SAAmB,kBAAiD;EACnF;EACA,SAAS,WAAW,CAAC;EACrB,cAAc,gBAAgB,WAAW;CAC3C;CACA,OAAO,OAAO,OAAO,SAAS,EAAE,WAAW,CAAC;AAC9C;;;;;;;;AC1EA,SAAg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EACnB,IAAI,KAAK,UAAU,MAAM;GACvB,IAAI,KAAK,UACP,MAAM,IAAI,MACR,6GAEF;GAEF,KAAK,QAAQ,UAAU,YAAY;GACnC,KAAK,MAAM,YAAY,uBAAuB,IAAI;EACpD;EACA,OAAO,KAAK;CACd;CAMA,SAAS,UAA4C;EACnD,IAAI,KAAK,UAAU;GACZ,KAAK,YAAY,QAAQ;GAC9B;EACF;EACC,CAAC,KAAK,cAAc,CAAC,EAAA,CAAG,KAAK,QAAQ;CACxC;;;;;;CAOA,SAAwB;EACtB,OAAQ,KAAK,cAAc,KAAK,aAAa;CAC/C;CAEA,MAAc,eAA8B;EAC1C,IAAI;EACJ,QAAQ,WAAW,KAAK,WAAW,IAAI,OAAO,KAAA,GAC5C,MAAM,KAAK,YAAY,QAAQ;EAEjC,KAAK,WAAW;EAChB,KAAK,YAAY;EACjB,MAAM,QAAQ,KAAK;EACnB,KAAK,QAAQ;EACb,IAAI,UAAU,MACZ,MAAM,MAAM,QAAQ;CAExB;;CAGA,MAAc,YAAY,UAAqD;EAC7E,IAAI;GACF,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"}
|
|
@@ -32,7 +32,7 @@ type AttributeMap = ReadonlyMap<symbol, unknown>;
|
|
|
32
32
|
* is declared and what applies to it.
|
|
33
33
|
*/
|
|
34
34
|
interface HandlerInfo {
|
|
35
|
-
readonly module: ClassType
|
|
35
|
+
readonly module: ClassType;
|
|
36
36
|
/** The class that owns the handler. */
|
|
37
37
|
readonly controller: ClassType;
|
|
38
38
|
readonly handlerName: string;
|
|
@@ -68,4 +68,4 @@ interface ExecutionContext {
|
|
|
68
68
|
onFinish(callback: () => void | Promise<void>): void;
|
|
69
69
|
}
|
|
70
70
|
export { ContextValue as a, ContextKey as i, ExecutionContext as n, PlainContextKey as o, HandlerInfo as r, createContextKey as s, AttributeMap as t };
|
|
71
|
-
//# sourceMappingURL=execution-context-
|
|
71
|
+
//# sourceMappingURL=execution-context-BVSmLkYp.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution-context-
|
|
1
|
+
{"version":3,"file":"execution-context-BVSmLkYp.d.cts","names":[],"sources":["../src/execution/context-key.mts","../src/execution/execution-context.mts"],"mappings":";;;;;;;;;cAUa,gBAAgB;WAGC;WAFX,QAAQ;EAEzB,YAA4B;EAE5B;;iBAKc,iBAAiB,GAAG,eAAe,gBAAgB;;KAKvD,WAAW,WAAW,gBAAgB;;;;;;;KAQtC,aAAa,KACvB,UAAU,sBAAsB,KAC5B,IACA;EAAsB,QAAQ,iBAAiB;KAC7C,cAAc;KAGjB,cAAc,KAAK,UAAU,eAAe,IAAI,UAAU,kBAAkB,KAAK,QAAQ,KAAK;KCpCvF,eAAe;;;;;UAMV;WACN,QAAQ;;WAER,YAAY;WACZ;WACA,iBAAiB;WACjB,uBAAuB;WACvB;aACE,SAAS;aACT,YAAY;aACZ,QAAQ;;;;;;;UAQJ;;WAEN;WACA;WACA,QAAQ;WACR,SAAS;;EAElB,IAAI,UAAU,YAAY,KAAK,IAAI,aAAa;;EAEhD,KAAK,UAAU,YAAY,KAAK,IAAI,aAAa;EACjD,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,aAAa;EACtD,IAAI,KAAK;;EAET,KAAK;;EAEL,SAAS;;EAET,SAAS,uBAAuB"}
|
|
@@ -32,7 +32,7 @@ type AttributeMap = ReadonlyMap<symbol, unknown>;
|
|
|
32
32
|
* is declared and what applies to it.
|
|
33
33
|
*/
|
|
34
34
|
interface HandlerInfo {
|
|
35
|
-
readonly module: ClassType
|
|
35
|
+
readonly module: ClassType;
|
|
36
36
|
/** The class that owns the handler. */
|
|
37
37
|
readonly controller: ClassType;
|
|
38
38
|
readonly handlerName: string;
|
|
@@ -68,4 +68,4 @@ interface ExecutionContext {
|
|
|
68
68
|
onFinish(callback: () => void | Promise<void>): void;
|
|
69
69
|
}
|
|
70
70
|
export { ContextValue as a, ContextKey as i, ExecutionContext as n, PlainContextKey as o, HandlerInfo as r, createContextKey as s, AttributeMap as t };
|
|
71
|
-
//# sourceMappingURL=execution-context-
|
|
71
|
+
//# sourceMappingURL=execution-context-C5F9rojO.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution-context-
|
|
1
|
+
{"version":3,"file":"execution-context-C5F9rojO.d.mts","names":[],"sources":["../src/execution/context-key.mts","../src/execution/execution-context.mts"],"mappings":";;;;;;;;;cAUa,gBAAgB;WAGC;WAFX,QAAQ;EAEzB,YAA4B;EAE5B;;iBAKc,iBAAiB,GAAG,eAAe,gBAAgB;;KAKvD,WAAW,WAAW,gBAAgB;;;;;;;KAQtC,aAAa,KACvB,UAAU,sBAAsB,KAC5B,IACA;EAAsB,QAAQ,iBAAiB;KAC7C,cAAc;KAGjB,cAAc,KAAK,UAAU,eAAe,IAAI,UAAU,kBAAkB,KAAK,QAAQ,KAAK;KCpCvF,eAAe;;;;;UAMV;WACN,QAAQ;;WAER,YAAY;WACZ;WACA,iBAAiB;WACjB,uBAAuB;WACvB;aACE,SAAS;aACT,YAAY;aACZ,QAAQ;;;;;;;UAQJ;;WAEN;WACA;WACA,QAAQ;WACR,SAAS;;EAElB,IAAI,UAAU,YAAY,KAAK,IAAI,aAAa;;EAEhD,KAAK,UAAU,YAAY,KAAK,IAAI,aAAa;EACjD,IAAI,UAAU,YAAY,KAAK,GAAG,OAAO,aAAa;EACtD,IAAI,KAAK;;EAET,KAAK;;EAEL,SAAS;;EAET,SAAS,uBAAuB"}
|
|
@@ -1,8 +1,85 @@
|
|
|
1
|
+
const require_attribute_value = require("./attribute-value-Cux5HhOL.cjs");
|
|
2
|
+
let _navios_di = require("@navios/di");
|
|
1
3
|
let node_util = require("node:util");
|
|
2
|
-
|
|
4
|
+
// src/execution/async-context.mts
|
|
5
|
+
let storage = null;
|
|
6
|
+
/**
|
|
7
|
+
* Turns on the async context: one `AsyncLocalStorage` holding the current
|
|
8
|
+
* `ExecutionContext`. The `asyncContext: true` option of an application does it.
|
|
9
|
+
*/
|
|
10
|
+
async function enableAsyncContext() {
|
|
11
|
+
if (storage === null) {
|
|
12
|
+
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
13
|
+
storage = new AsyncLocalStorage();
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Runs `fn` with `ctx` as the current context. A transport does this when its
|
|
18
|
+
* host says that the application has an async context.
|
|
19
|
+
*/
|
|
20
|
+
function runInContext(ctx, fn) {
|
|
21
|
+
return storage === null ? fn() : storage.run(ctx, fn);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The context of the handler being run, for code that cannot receive it as an
|
|
25
|
+
* argument. Returns `undefined` outside a handler, and always when the
|
|
26
|
+
* application was not created with `asyncContext: true`.
|
|
27
|
+
*/
|
|
28
|
+
function currentContext() {
|
|
29
|
+
return storage?.getStore();
|
|
30
|
+
}
|
|
31
|
+
// src/execution/context-host.mts
|
|
32
|
+
function tokenName(token) {
|
|
33
|
+
return typeof token === "function" ? token.name : String(token);
|
|
34
|
+
}
|
|
35
|
+
/** The token itself, without the args that are bound to it. */
|
|
36
|
+
function plainToken(token) {
|
|
37
|
+
return token instanceof _navios_di.BoundInjectionToken || token instanceof _navios_di.FactoryInjectionToken ? token.token : token;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Whether a context resolves `token` from a DI scope of its execution. A
|
|
41
|
+
* singleton is the same in all of them.
|
|
42
|
+
*/
|
|
43
|
+
function needsScope(container, token) {
|
|
44
|
+
return container.getProvider(token)?.scope !== _navios_di.InjectableScope.Singleton;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Builds the host for an application's contexts, applying its policy for
|
|
48
|
+
* request-scoped services.
|
|
49
|
+
*/
|
|
50
|
+
function createContextHost(container, mode, logger) {
|
|
51
|
+
if (mode === "allow") return {
|
|
52
|
+
container,
|
|
53
|
+
onScopedUse: null,
|
|
54
|
+
logger
|
|
55
|
+
};
|
|
56
|
+
const seen = /* @__PURE__ */ new Set();
|
|
57
|
+
return {
|
|
58
|
+
container,
|
|
59
|
+
logger,
|
|
60
|
+
onScopedUse: (used) => {
|
|
61
|
+
const token = plainToken(used);
|
|
62
|
+
if (mode === "forbid") throw new Error(`[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this application forbids request-scoped services (requestScopedServices: 'forbid'). Keep per-execution data in a context key instead.`);
|
|
63
|
+
if (!seen.has(token)) {
|
|
64
|
+
seen.add(token);
|
|
65
|
+
logger.warn(`${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). If it only carries data derived from the context, a context key is cheaper and needs no DI scope. Set requestScopedServices: 'allow' to silence this.`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
3
70
|
// src/modules/module-graph.mts
|
|
4
|
-
|
|
5
|
-
|
|
71
|
+
/**
|
|
72
|
+
* The classes a module lists under one of the options of a transport, once
|
|
73
|
+
* each. Throws for an entry that is not a class: what an import cycle between
|
|
74
|
+
* the files of two classes leaves behind.
|
|
75
|
+
*/
|
|
76
|
+
function moduleClasses(node, entry) {
|
|
77
|
+
const listed = node.entries.get(entry);
|
|
78
|
+
if (!listed) return [];
|
|
79
|
+
const classes = Array.from(new Set(listed));
|
|
80
|
+
const index = classes.findIndex((listedClass) => typeof listedClass !== "function");
|
|
81
|
+
if (index !== -1) throw new Error(`[Navios] Module ${node.module.name} lists ${String(classes[index])} in ${entry}. When it should be a class, the files of the two usually import each other.`);
|
|
82
|
+
return classes;
|
|
6
83
|
}
|
|
7
84
|
function names(path) {
|
|
8
85
|
return path.map((module) => module.name).join(" -> ");
|
|
@@ -81,9 +158,7 @@ function buildModuleGraph(roots) {
|
|
|
81
158
|
if (importer && !known.node.importers.includes(importer)) known.node.importers.push(importer);
|
|
82
159
|
return;
|
|
83
160
|
}
|
|
84
|
-
const metadata =
|
|
85
|
-
const imports = metadata.imports;
|
|
86
|
-
require_module_metadata.assertImportsDefined(module, imports);
|
|
161
|
+
const metadata = require_attribute_value.getModuleMetadata(module);
|
|
87
162
|
const node = {
|
|
88
163
|
module,
|
|
89
164
|
providers: metadata.providers,
|
|
@@ -104,7 +179,7 @@ function buildModuleGraph(roots) {
|
|
|
104
179
|
};
|
|
105
180
|
drafts.set(module, draft);
|
|
106
181
|
path.push(module);
|
|
107
|
-
for (const imported of imports) visit(imported, node);
|
|
182
|
+
for (const imported of metadata.imports) visit(imported, node);
|
|
108
183
|
path.pop();
|
|
109
184
|
draft.open = false;
|
|
110
185
|
order.push(node);
|
|
@@ -125,23 +200,71 @@ function buildModuleGraph(roots) {
|
|
|
125
200
|
outermostFirst.reverse();
|
|
126
201
|
for (const draft of outermostFirst) {
|
|
127
202
|
const { node, metadata } = draft;
|
|
128
|
-
|
|
129
|
-
|
|
203
|
+
require_attribute_value.addMissing(node.guards, metadata.guards);
|
|
204
|
+
require_attribute_value.addMissing(node.interceptors, metadata.interceptors);
|
|
130
205
|
inheritAttributes(draft, node.importers.map((importer) => drafts.get(importer.module)));
|
|
131
206
|
for (const [key, value] of metadata.attributes) node.attributes.set(key, value);
|
|
132
207
|
for (const imported of metadata.imports) {
|
|
133
208
|
const child = drafts.get(imported);
|
|
134
|
-
|
|
135
|
-
|
|
209
|
+
require_attribute_value.addMissing(child.node.guards, node.guards);
|
|
210
|
+
require_attribute_value.addMissing(child.node.interceptors, node.interceptors);
|
|
136
211
|
}
|
|
137
212
|
}
|
|
138
213
|
return order;
|
|
139
214
|
}
|
|
215
|
+
// src/execution/execution-context-token.mts
|
|
216
|
+
/**
|
|
217
|
+
* The context of the current execution, on any transport. Injectable in
|
|
218
|
+
* request-scoped services.
|
|
219
|
+
*/
|
|
220
|
+
const ExecutionContextToken = _navios_di.InjectionToken.create("ExecutionContext", { scope: _navios_di.InjectableScope.Request });
|
|
221
|
+
Object.defineProperty(exports, "ExecutionContextToken", {
|
|
222
|
+
enumerable: true,
|
|
223
|
+
get: function() {
|
|
224
|
+
return ExecutionContextToken;
|
|
225
|
+
}
|
|
226
|
+
});
|
|
140
227
|
Object.defineProperty(exports, "buildModuleGraph", {
|
|
141
228
|
enumerable: true,
|
|
142
229
|
get: function() {
|
|
143
230
|
return buildModuleGraph;
|
|
144
231
|
}
|
|
145
232
|
});
|
|
233
|
+
Object.defineProperty(exports, "createContextHost", {
|
|
234
|
+
enumerable: true,
|
|
235
|
+
get: function() {
|
|
236
|
+
return createContextHost;
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
Object.defineProperty(exports, "currentContext", {
|
|
240
|
+
enumerable: true,
|
|
241
|
+
get: function() {
|
|
242
|
+
return currentContext;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
Object.defineProperty(exports, "enableAsyncContext", {
|
|
246
|
+
enumerable: true,
|
|
247
|
+
get: function() {
|
|
248
|
+
return enableAsyncContext;
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
Object.defineProperty(exports, "moduleClasses", {
|
|
252
|
+
enumerable: true,
|
|
253
|
+
get: function() {
|
|
254
|
+
return moduleClasses;
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
Object.defineProperty(exports, "needsScope", {
|
|
258
|
+
enumerable: true,
|
|
259
|
+
get: function() {
|
|
260
|
+
return needsScope;
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
Object.defineProperty(exports, "runInContext", {
|
|
264
|
+
enumerable: true,
|
|
265
|
+
get: function() {
|
|
266
|
+
return runInContext;
|
|
267
|
+
}
|
|
268
|
+
});
|
|
146
269
|
|
|
147
|
-
//# sourceMappingURL=
|
|
270
|
+
//# sourceMappingURL=execution-context-token--cKS4cJv.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execution-context-token--cKS4cJv.cjs","names":["BoundInjectionToken","FactoryInjectionToken","InjectableScope","isDeepStrictEqual","getModuleMetadata","addMissing","InjectionToken","InjectableScope"],"sources":["../src/execution/async-context.mts","../src/execution/context-host.mts","../src/modules/module-graph.mts","../src/execution/execution-context-token.mts"],"sourcesContent":["import type { ExecutionContext } from './execution-context.mjs'\n\ninterface Storage {\n run<R>(store: ExecutionContext, fn: () => R): R\n getStore(): ExecutionContext | undefined\n}\n\nlet storage: Storage | null = null\n\n/**\n * Turns on the async context: one `AsyncLocalStorage` holding the current\n * `ExecutionContext`. The `asyncContext: true` option of an application does it.\n */\nexport async function enableAsyncContext(): Promise<void> {\n if (storage === null) {\n const { AsyncLocalStorage } = await import('node:async_hooks')\n storage = new AsyncLocalStorage<ExecutionContext>()\n }\n}\n\n/**\n * Runs `fn` with `ctx` as the current context. A transport does this when its\n * host says that the application has an async context.\n */\nexport function runInContext<R>(ctx: ExecutionContext, fn: () => R): R {\n return storage === null ? fn() : storage.run(ctx, fn)\n}\n\n/**\n * The context of the handler being run, for code that cannot receive it as an\n * argument. Returns `undefined` outside a handler, and always when the\n * application was not created with `asyncContext: true`.\n */\nexport function currentContext(): ExecutionContext | undefined {\n return storage?.getStore()\n}\n","import { BoundInjectionToken, FactoryInjectionToken, InjectableScope } from '@navios/di'\n\nimport type { AnyInjectableType, ClassType, Container, InjectionToken } from '@navios/di'\n\nimport type { LoggerService } from '../logger/logger-output.mjs'\n\n/**\n * Dependencies shared by every execution context of an application.\n */\nexport interface ContextHost {\n readonly container: Container\n /**\n * Called when a context resolves a token that `needsScope` is true for; may\n * throw.\n */\n onScopedUse: ((token: AnyInjectableType) => void) | null\n /** Receives what an `onFinish` callback throws; without it that is dropped. */\n readonly logger?: Pick<LoggerService, 'error'>\n}\n\nfunction tokenName(token: unknown): string {\n return typeof token === 'function' ? token.name : String(token)\n}\n\ntype PlainToken = ClassType | InjectionToken<unknown, unknown>\n\n/** The token itself, without the args that are bound to it. */\nfunction plainToken(token: AnyInjectableType): PlainToken {\n return (\n token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken\n ? token.token\n : token\n ) as PlainToken\n}\n\n/**\n * Whether a context resolves `token` from a DI scope of its execution. A\n * singleton is the same in all of them.\n */\nexport function needsScope(container: Container, token: AnyInjectableType): boolean {\n return container.getProvider(token)?.scope !== InjectableScope.Singleton\n}\n\n/**\n * Builds the host for an application's contexts, applying its policy for\n * request-scoped services.\n */\nexport function createContextHost(\n container: Container,\n mode: 'allow' | 'warn' | 'forbid',\n logger: LoggerService,\n): ContextHost {\n if (mode === 'allow') {\n return { container, onScopedUse: null, logger }\n }\n const seen = new Set<PlainToken>()\n return {\n container,\n logger,\n onScopedUse: (used) => {\n const token = plainToken(used)\n if (mode === 'forbid') {\n throw new Error(\n `[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this ` +\n `application forbids request-scoped services (requestScopedServices: 'forbid'). ` +\n `Keep per-execution data in a context key instead.`,\n )\n }\n if (!seen.has(token)) {\n seen.add(token)\n logger.warn(\n `${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). ` +\n `If it only carries data derived from the context, a context key is cheaper and ` +\n `needs no DI scope. Set requestScopedServices: 'allow' to silence this.`,\n )\n }\n },\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\n\nimport type { ClassType, Provider } from '@navios/di'\n\nimport { addMissing } from '../metadata/class-metadata.mjs'\n\nimport { getModuleMetadata } from './module-metadata.mjs'\n\nimport type { ModuleMetadata } from './module-metadata.mjs'\n\n/**\n * A module as it applies to one application: its guards, interceptors and\n * attributes together with those it inherits, and the modules that import it.\n */\nexport interface ModuleNode {\n module: ClassType\n providers: Provider[]\n /** The module's transport-specific options, by option name. */\n entries: ReadonlyMap<string, unknown>\n guards: ClassType[]\n interceptors: ClassType[]\n attributes: Map<symbol, unknown>\n /**\n * The attributes that the importers of the module do not agree about, and what\n * each of two import paths gives it. They are not among `attributes`;\n * `handlerChain` refuses a handler that would inherit one.\n */\n disputed: ReadonlyMap<symbol, string>\n /** The modules that import this one, in the order they were reached. */\n importers: ModuleNode[]\n /** Whether the module was given to the application directly. */\n isRoot: boolean\n}\n\n/**\n * The classes a module lists under one of the options of a transport, once\n * each. Throws for an entry that is not a class: what an import cycle between\n * the files of two classes leaves behind.\n */\nexport function moduleClasses(\n node: Pick<ModuleNode, 'module' | 'entries'>,\n entry: string,\n): ClassType[] {\n const listed = node.entries.get(entry) as Iterable<unknown> | null | undefined\n if (!listed) {\n return []\n }\n const classes = Array.from(new Set(listed))\n const index = classes.findIndex((listedClass) => typeof listedClass !== 'function')\n if (index !== -1) {\n throw new Error(\n `[Navios] Module ${node.module.name} lists ${String(classes[index])} in ${entry}. When it ` +\n `should be a class, the files of the two usually import each other.`,\n )\n }\n return classes as ClassType[]\n}\n\n/** Two import paths that give a module different values of one attribute. */\ninterface Disagreement {\n one: ClassType[]\n other: ClassType[]\n /** Whether the other path gives a value at all. */\n otherHasValue: boolean\n}\n\n/** What a module has while the graph is being computed. */\ninterface Draft {\n node: ModuleNode\n metadata: ModuleMetadata\n /** The attributes the importers do not agree about. */\n disagreements: Map<symbol, Disagreement>\n /** Whether the walk is at what it imports. */\n open: boolean\n ranked: boolean\n}\n\nfunction names(path: readonly ClassType[]): string {\n return path.map((module) => module.name).join(' -> ')\n}\n\n/** One way to a module from a root, the module included. */\nfunction pathTo(node: ModuleNode): ClassType[] {\n const path = [node.module]\n for (let at = node; !at.isRoot && at.importers.length > 0;) {\n at = at.importers[0]\n path.unshift(at.module)\n }\n return path\n}\n\n/**\n * Gives a module the attributes it inherits. Guards add up over several import\n * paths, which is safe; attributes cannot. One that opens a handler and one that\n * restricts it would each be wrong if it applied because of one path alone, so\n * the paths have to agree where a handler inherits it.\n */\nfunction inheritAttributes(draft: Draft, importers: readonly Draft[]): void {\n const { node, metadata, disagreements } = draft\n const keys = new Set(\n importers.flatMap((importer) => [\n ...importer.node.attributes.keys(),\n ...importer.disagreements.keys(),\n ]),\n )\n for (const key of keys) {\n if (metadata.attributes.has(key)) {\n continue\n }\n const inherited = importers.find((importer) => importer.disagreements.has(key))\n if (inherited) {\n const { one, other, otherHasValue } = inherited.disagreements.get(key)!\n disagreements.set(key, {\n one: [...one, node.module],\n other: [...other, node.module],\n otherHasValue,\n })\n continue\n }\n const source = importers.find((importer) => importer.node.attributes.has(key))!\n const value = source.node.attributes.get(key)\n const disagrees = (importer: Draft) =>\n !importer.node.attributes.has(key) ||\n !isDeepStrictEqual(importer.node.attributes.get(key), value)\n const other = importers.find(disagrees)\n if (other === undefined && !node.isRoot) {\n node.attributes.set(key, value)\n } else {\n disagreements.set(key, {\n one: [...pathTo(source.node), node.module],\n other: other === undefined ? [node.module] : [...pathTo(other.node), node.module],\n otherHasValue: other !== undefined && other.node.attributes.has(key),\n })\n }\n }\n node.disputed = new Map(Array.from(disagreements, ([key, value]) => [key, described(value)]))\n}\n\nfunction described({ one, other, otherHasValue }: Disagreement): string {\n return `one over ${names(one)}, ${otherHasValue ? 'another' : 'none'} over ${names(other)}`\n}\n\n/**\n * Walks the import graph from the given roots and computes, for this\n * application only, what applies to each module.\n *\n * - Guards and interceptors are the union over every path that reaches a\n * module, outermost first: what the importers contribute, importers in\n * import order, then the module's own. Nothing is written back to the\n * classes, so two applications importing one module under different parents\n * do not affect each other.\n * - An attribute comes from the module itself or else from what imports it.\n * One that the importers do not agree about is in `disputed` instead.\n *\n * Neither depends on the order in which a module happens to be reached.\n * Modules are returned in dependency order: a module comes after everything\n * it imports. That cannot be done for modules that import each other, which is\n * an error as well.\n */\nexport function buildModuleGraph(roots: ClassType[]): ModuleNode[] {\n const drafts = new Map<ClassType, Draft>()\n const order: ModuleNode[] = []\n\n // First walk: every module once, in dependency order, with its importers.\n const path: ClassType[] = []\n const visit = (module: ClassType, importer: ModuleNode | null): void => {\n const known = drafts.get(module)\n if (known) {\n if (known.open) {\n throw new Error(\n `[Navios] Modules import each other in a cycle: ` +\n names([...path.slice(path.indexOf(module)), module]),\n )\n }\n if (importer && !known.node.importers.includes(importer)) {\n known.node.importers.push(importer)\n }\n return\n }\n const metadata = getModuleMetadata(module)\n const node: ModuleNode = {\n module,\n providers: metadata.providers,\n entries: metadata.entries,\n guards: [],\n interceptors: [],\n attributes: new Map(),\n disputed: new Map(),\n importers: importer ? [importer] : [],\n isRoot: false,\n }\n const draft: Draft = {\n node,\n metadata,\n disagreements: new Map(),\n open: true,\n ranked: false,\n }\n drafts.set(module, draft)\n path.push(module)\n for (const imported of metadata.imports) {\n visit(imported, node)\n }\n path.pop()\n draft.open = false\n order.push(node)\n }\n for (const root of roots) {\n visit(root, null)\n drafts.get(root)!.node.isRoot = true\n }\n\n // Second walk: importers before what they import, siblings in import\n // order. That is the reverse of a post-order that takes the imports last\n // to first.\n const outermostFirst: Draft[] = []\n const rank = (draft: Draft): void => {\n if (draft.ranked) {\n return\n }\n draft.ranked = true\n const imports = draft.metadata.imports\n for (let i = imports.length - 1; i >= 0; i--) {\n rank(drafts.get(imports[i])!)\n }\n outermostFirst.push(draft)\n }\n for (let i = roots.length - 1; i >= 0; i--) {\n rank(drafts.get(roots[i])!)\n }\n outermostFirst.reverse()\n\n // Each module is complete when its turn comes, because everything that\n // imports it came before; it then hands what it has to its imports.\n for (const draft of outermostFirst) {\n const { node, metadata } = draft\n addMissing(node.guards, metadata.guards)\n addMissing(node.interceptors, metadata.interceptors)\n inheritAttributes(\n draft,\n node.importers.map((importer) => drafts.get(importer.module)!),\n )\n for (const [key, value] of metadata.attributes) {\n node.attributes.set(key, value)\n }\n for (const imported of metadata.imports) {\n const child = drafts.get(imported)!\n addMissing(child.node.guards, node.guards)\n addMissing(child.node.interceptors, node.interceptors)\n }\n }\n return order\n}\n","import { InjectableScope, InjectionToken } from '@navios/di'\n\nimport type { ExecutionContext } from './execution-context.mjs'\n\n/**\n * The context of the current execution, on any transport. Injectable in\n * request-scoped services.\n */\nexport const ExecutionContextToken = InjectionToken.create<ExecutionContext>('ExecutionContext', {\n scope: InjectableScope.Request,\n})\n"],"mappings":";;;;AAOA,IAAI,UAA0B;;;;;AAM9B,eAAsB,qBAAoC;CACxD,IAAI,YAAY,MAAM;EACpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,UAAU,IAAI,kBAAoC;CACpD;AACF;;;;;AAMA,SAAgB,aAAgB,KAAuB,IAAgB;CACrE,OAAO,YAAY,OAAO,GAAG,IAAI,QAAQ,IAAI,KAAK,EAAE;AACtD;;;;;;AAOA,SAAgB,iBAA+C;CAC7D,OAAO,SAAS,SAAS;AAC3B;;ACfA,SAAS,UAAU,OAAwB;CACzC,OAAO,OAAO,UAAU,aAAa,MAAM,OAAO,OAAO,KAAK;AAChE;;AAKA,SAAS,WAAW,OAAsC;CACxD,OACE,iBAAiBA,WAAAA,uBAAuB,iBAAiBC,WAAAA,wBACrD,MAAM,QACN;AAER;;;;;AAMA,SAAgB,WAAW,WAAsB,OAAmC;CAClF,OAAO,UAAU,YAAY,KAAK,CAAC,EAAE,UAAUC,WAAAA,gBAAgB;AACjE;;;;;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,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;;;;;;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AAAA,WAAW,KAAK,cAAc,SAAS,YAAY;EACnD,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;GACjCA,wBAAAA,WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM;GACzCA,wBAAAA,WAAW,MAAM,KAAK,cAAc,KAAK,YAAY;EACvD;CACF;CACA,OAAO;AACT;;;;;;ACpPA,MAAa,wBAAwBC,WAAAA,eAAe,OAAyB,oBAAoB,EAC/F,OAAOC,WAAAA,gBAAgB,QACzB,CAAC"}
|
|
@@ -1,8 +1,85 @@
|
|
|
1
|
+
import { l as addMissing, s as getModuleMetadata } from "./attribute-value-BNiJjxl1.mjs";
|
|
2
|
+
import { BoundInjectionToken, FactoryInjectionToken, InjectableScope, InjectionToken } from "@navios/di";
|
|
1
3
|
import { isDeepStrictEqual } from "node:util";
|
|
2
|
-
|
|
4
|
+
// src/execution/async-context.mts
|
|
5
|
+
let storage = null;
|
|
6
|
+
/**
|
|
7
|
+
* Turns on the async context: one `AsyncLocalStorage` holding the current
|
|
8
|
+
* `ExecutionContext`. The `asyncContext: true` option of an application does it.
|
|
9
|
+
*/
|
|
10
|
+
async function enableAsyncContext() {
|
|
11
|
+
if (storage === null) {
|
|
12
|
+
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
13
|
+
storage = new AsyncLocalStorage();
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Runs `fn` with `ctx` as the current context. A transport does this when its
|
|
18
|
+
* host says that the application has an async context.
|
|
19
|
+
*/
|
|
20
|
+
function runInContext(ctx, fn) {
|
|
21
|
+
return storage === null ? fn() : storage.run(ctx, fn);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The context of the handler being run, for code that cannot receive it as an
|
|
25
|
+
* argument. Returns `undefined` outside a handler, and always when the
|
|
26
|
+
* application was not created with `asyncContext: true`.
|
|
27
|
+
*/
|
|
28
|
+
function currentContext() {
|
|
29
|
+
return storage?.getStore();
|
|
30
|
+
}
|
|
31
|
+
// src/execution/context-host.mts
|
|
32
|
+
function tokenName(token) {
|
|
33
|
+
return typeof token === "function" ? token.name : String(token);
|
|
34
|
+
}
|
|
35
|
+
/** The token itself, without the args that are bound to it. */
|
|
36
|
+
function plainToken(token) {
|
|
37
|
+
return token instanceof BoundInjectionToken || token instanceof FactoryInjectionToken ? token.token : token;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Whether a context resolves `token` from a DI scope of its execution. A
|
|
41
|
+
* singleton is the same in all of them.
|
|
42
|
+
*/
|
|
43
|
+
function needsScope(container, token) {
|
|
44
|
+
return container.getProvider(token)?.scope !== InjectableScope.Singleton;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Builds the host for an application's contexts, applying its policy for
|
|
48
|
+
* request-scoped services.
|
|
49
|
+
*/
|
|
50
|
+
function createContextHost(container, mode, logger) {
|
|
51
|
+
if (mode === "allow") return {
|
|
52
|
+
container,
|
|
53
|
+
onScopedUse: null,
|
|
54
|
+
logger
|
|
55
|
+
};
|
|
56
|
+
const seen = /* @__PURE__ */ new Set();
|
|
57
|
+
return {
|
|
58
|
+
container,
|
|
59
|
+
logger,
|
|
60
|
+
onScopedUse: (used) => {
|
|
61
|
+
const token = plainToken(used);
|
|
62
|
+
if (mode === "forbid") throw new Error(`[Navios] ${tokenName(token)} was requested with ctx.use()/ctx.resolve(), but this application forbids request-scoped services (requestScopedServices: 'forbid'). Keep per-execution data in a context key instead.`);
|
|
63
|
+
if (!seen.has(token)) {
|
|
64
|
+
seen.add(token);
|
|
65
|
+
logger.warn(`${tokenName(token)} is resolved for every execution with ctx.use()/ctx.resolve(). If it only carries data derived from the context, a context key is cheaper and needs no DI scope. Set requestScopedServices: 'allow' to silence this.`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
3
70
|
// src/modules/module-graph.mts
|
|
4
|
-
|
|
5
|
-
|
|
71
|
+
/**
|
|
72
|
+
* The classes a module lists under one of the options of a transport, once
|
|
73
|
+
* each. Throws for an entry that is not a class: what an import cycle between
|
|
74
|
+
* the files of two classes leaves behind.
|
|
75
|
+
*/
|
|
76
|
+
function moduleClasses(node, entry) {
|
|
77
|
+
const listed = node.entries.get(entry);
|
|
78
|
+
if (!listed) return [];
|
|
79
|
+
const classes = Array.from(new Set(listed));
|
|
80
|
+
const index = classes.findIndex((listedClass) => typeof listedClass !== "function");
|
|
81
|
+
if (index !== -1) throw new Error(`[Navios] Module ${node.module.name} lists ${String(classes[index])} in ${entry}. When it should be a class, the files of the two usually import each other.`);
|
|
82
|
+
return classes;
|
|
6
83
|
}
|
|
7
84
|
function names(path) {
|
|
8
85
|
return path.map((module) => module.name).join(" -> ");
|
|
@@ -82,8 +159,6 @@ function buildModuleGraph(roots) {
|
|
|
82
159
|
return;
|
|
83
160
|
}
|
|
84
161
|
const metadata = getModuleMetadata(module);
|
|
85
|
-
const imports = metadata.imports;
|
|
86
|
-
assertImportsDefined(module, imports);
|
|
87
162
|
const node = {
|
|
88
163
|
module,
|
|
89
164
|
providers: metadata.providers,
|
|
@@ -104,7 +179,7 @@ function buildModuleGraph(roots) {
|
|
|
104
179
|
};
|
|
105
180
|
drafts.set(module, draft);
|
|
106
181
|
path.push(module);
|
|
107
|
-
for (const imported of imports) visit(imported, node);
|
|
182
|
+
for (const imported of metadata.imports) visit(imported, node);
|
|
108
183
|
path.pop();
|
|
109
184
|
draft.open = false;
|
|
110
185
|
order.push(node);
|
|
@@ -125,18 +200,24 @@ function buildModuleGraph(roots) {
|
|
|
125
200
|
outermostFirst.reverse();
|
|
126
201
|
for (const draft of outermostFirst) {
|
|
127
202
|
const { node, metadata } = draft;
|
|
128
|
-
|
|
129
|
-
|
|
203
|
+
addMissing(node.guards, metadata.guards);
|
|
204
|
+
addMissing(node.interceptors, metadata.interceptors);
|
|
130
205
|
inheritAttributes(draft, node.importers.map((importer) => drafts.get(importer.module)));
|
|
131
206
|
for (const [key, value] of metadata.attributes) node.attributes.set(key, value);
|
|
132
207
|
for (const imported of metadata.imports) {
|
|
133
208
|
const child = drafts.get(imported);
|
|
134
|
-
|
|
135
|
-
|
|
209
|
+
addMissing(child.node.guards, node.guards);
|
|
210
|
+
addMissing(child.node.interceptors, node.interceptors);
|
|
136
211
|
}
|
|
137
212
|
}
|
|
138
213
|
return order;
|
|
139
214
|
}
|
|
140
|
-
|
|
215
|
+
// src/execution/execution-context-token.mts
|
|
216
|
+
/**
|
|
217
|
+
* The context of the current execution, on any transport. Injectable in
|
|
218
|
+
* request-scoped services.
|
|
219
|
+
*/
|
|
220
|
+
const ExecutionContextToken = InjectionToken.create("ExecutionContext", { scope: InjectableScope.Request });
|
|
221
|
+
export { needsScope as a, runInContext as c, createContextHost as i, buildModuleGraph as n, currentContext as o, moduleClasses as r, enableAsyncContext as s, ExecutionContextToken as t };
|
|
141
222
|
|
|
142
|
-
//# sourceMappingURL=
|
|
223
|
+
//# sourceMappingURL=execution-context-token-Cb3M3Ao0.mjs.map
|