@znight/core 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -93,6 +93,36 @@ export class DatabaseFactory {
93
93
  }
94
94
  ```
95
95
 
96
+ ## Custom parameter decorators
97
+
98
+ `createParamDecorator<T, D>(resolvers)` defines a parameter decorator of your own (RFC 0010), usable
99
+ on HTTP routes, GraphQL fields and message handlers. Each key of `resolvers` is a transport
100
+ (`http`, `graphql`, `messaging`: the installed transport packages declare them in `ParamContexts`)
101
+ and its value computes the parameter: a function `(ctx, data) => T | PromiseLike<T>`, or the class
102
+ of a provider implementing `ParamResolver<C, T, D>` (constructor injection, any scope).
103
+
104
+ ```ts
105
+ import { createParamDecorator } from '@znight/core'
106
+ import type { User } from './user.ts'
107
+
108
+ /** The authenticated user, stored in the request state by the authentication guard. */
109
+ export const CurrentUser = createParamDecorator<User>({
110
+ http: ctx => ctx.state.get('user') as User,
111
+ })
112
+
113
+ // @Get('/me') me(@CurrentUser() user: User) { ... }
114
+ ```
115
+
116
+ - `T` (required) is the injected type; the compiler checks it against every decorated parameter.
117
+ - `D` is the type of the data argument (`@Claim('sub')`): none by default, required when it excludes
118
+ `undefined`. The argument is a `value` argument: statically evaluable or an exported binding.
119
+ - The definition is an exported top-level `const`: the generated module imports it and calls
120
+ `CurrentUser.resolvers.http(ctx, data)` (no lookup, no closure, no promise when the resolver
121
+ returns a value). `resolvers` is frozen.
122
+ - Using the decorator on a handler of a transport it has no resolver for, on a constructor parameter,
123
+ with a data argument that cannot be emitted or on a parameter whose type does not accept `T` is a
124
+ ZNIGHT005 at build time.
125
+
96
126
  ## Application
97
127
 
98
128
  `Application.create(options)` builds the container and runs the plugins:
package/dist/index.d.mts CHANGED
@@ -7,7 +7,7 @@
7
7
  * messaging, config, observability).
8
8
  * - From `ZNIGHT030`, each first-party package reserves a block of ten: `ZNIGHT030`–`039`
9
9
  * `@znight/openapi`, `ZNIGHT040`–`049` `@znight/schedule`, `ZNIGHT050`–`059` `@znight/websocket`
10
- * (reserved), `ZNIGHT060`–`069` `@znight/graphql`.
10
+ * (reserved), `ZNIGHT060`–`069` `@znight/graphql`, `ZNIGHT070`–`079` `@znight/events`.
11
11
  *
12
12
  * Within a range, codes are allocated in order without gaps. A package uses its block for its own
13
13
  * failure modes, with one catch-all code for invalid usage and options, and reuses a lower code
@@ -132,6 +132,12 @@ export declare const ErrorCode: {
132
132
  * type or argument the SDL does not declare, a signature that does not conform to the SDL types.
133
133
  */
134
134
  readonly GraphQLSchemaMismatch: "ZNIGHT068";
135
+ /**
136
+ * Invalid event listener: an `@OnEvent` method whose parameter is not a class (or a union of
137
+ * classes), a generic or optional event, an event class the generated module cannot import, invalid
138
+ * options, the NestJS string form, a detached listener depending on a request-scoped external.
139
+ */
140
+ readonly InvalidEventListener: "ZNIGHT070";
135
141
  };
136
142
  export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
137
143
  /** Short human readable description of every error code. */
@@ -652,6 +658,17 @@ interface ZnightHooks {
652
658
  * emitted when listeners exist.
653
659
  */
654
660
  "graphql:operation": GraphQLOperationEvent;
661
+ /**
662
+ * One publication of `@znight/events` (`EventPublisher.publish()` or `emit()`) that matched at least
663
+ * one listener (RFC 0011): wraps the inline phase with `hooks.run` when wrappers exist, then is
664
+ * emitted when listeners exist. A publication without listener produces nothing.
665
+ */
666
+ "events:publish": EventPublishEvent;
667
+ /**
668
+ * One listener invocation of `@znight/events` (RFC 0011), inline or detached: wrapped with
669
+ * `hooks.run` when wrappers exist, then emitted when listeners exist.
670
+ */
671
+ "events:listener": EventListenerEvent;
655
672
  }
656
673
  /**
657
674
  * Instrumentation event of the `http:request` hook. Defined in core so that producers
@@ -833,6 +850,49 @@ interface GraphQLOperationEvent {
833
850
  /** Errors of the response (field and request errors), set before `hooks.run` resolves. */
834
851
  errors?: readonly GraphQLOperationError[];
835
852
  }
853
+ /** How an application event was published (`EventPublishEvent.mode`). */
854
+ type EventPublishMode = "publish" | "emit";
855
+ /**
856
+ * Instrumentation event of the `events:publish` hook, produced by `@znight/events` (RFC 0011) for a
857
+ * publication that matched at least one listener. The wrappers surround the inline phase (the
858
+ * detached listeners are scheduled after it succeeded); `error` and `failedListener` are set before
859
+ * `next()` rejects.
860
+ */
861
+ interface EventPublishEvent {
862
+ /** Class name of the event (`UserCreated`). */
863
+ readonly event: string;
864
+ /** The published object. */
865
+ readonly payload: object;
866
+ readonly mode: EventPublishMode;
867
+ /** Number of inline listeners matched. */
868
+ readonly inline: number;
869
+ /** Number of detached listeners matched. */
870
+ readonly detached: number;
871
+ /** `performance.now()` when the publication started. */
872
+ readonly startTime: number;
873
+ /** First inline error, set before `next()` rejects in the wrappers. */
874
+ error?: unknown;
875
+ /** `Class.method` of the inline listener that failed. */
876
+ failedListener?: string;
877
+ }
878
+ /**
879
+ * Instrumentation event of the `events:listener` hook, produced by `@znight/events` (RFC 0011) for
880
+ * every listener invocation. Inline listeners run in the publisher's async context, detached ones in
881
+ * a fresh scope of their own; `error` is set before `next()` rejects.
882
+ */
883
+ interface EventListenerEvent {
884
+ /** Class name of the event. */
885
+ readonly event: string;
886
+ /** The published object. */
887
+ readonly payload: object;
888
+ /** `Class.method` of the listener (`WelcomeMail.send`). */
889
+ readonly listener: string;
890
+ readonly detached: boolean;
891
+ /** `performance.now()` when the invocation started. */
892
+ readonly startTime: number;
893
+ /** What the listener threw or rejected with. */
894
+ error?: unknown;
895
+ }
836
896
  /** Name of a declared hook. */
837
897
  type HookName = keyof ZnightHooks;
838
898
  /** Event type of hook `K`. */
@@ -1159,6 +1219,65 @@ export declare function isDisposable(instance: unknown, disposeMethod?: string):
1159
1219
  * @throws ZnightError (ZNIGHT021) when `disposeMethod` is not a method of `instance`.
1160
1220
  */
1161
1221
  export declare function disposeInstance(instance: unknown, disposeMethod?: string): unknown;
1222
+ /**
1223
+ * Resolver contexts by transport. Each transport package adds its own entry through declaration
1224
+ * merging (`http: HttpContext` in `@znight/http`, `graphql: ResolverContext`, `messaging:
1225
+ * InboundMessage`); a transport that is not installed has no entry.
1226
+ *
1227
+ * ```ts
1228
+ * declare module '@znight/core' {
1229
+ * interface ParamContexts {
1230
+ * http: HttpContext
1231
+ * }
1232
+ * }
1233
+ * ```
1234
+ */
1235
+ interface ParamContexts {}
1236
+ /** A provider computing the value of a parameter, in the scope of the call (RFC 0010 §4.6). */
1237
+ interface ParamResolver<C, T, D = undefined> {
1238
+ resolve(ctx: C, data: D): T | PromiseLike<T>;
1239
+ }
1240
+ /** A resolver function: receives the context of its transport and the data argument of the use. */
1241
+ type ParamResolverFunction<C, T, D> = (ctx: C, data: D) => T | PromiseLike<T>;
1242
+ /** The class of a provider implementing {@link ParamResolver} (bound at build time, resolved in the scope of the call). */
1243
+ type ParamResolverClass<C, T, D> = abstract new (...args: never[]) => ParamResolver<C, T, D>;
1244
+ /** Computes the value of a parameter: a function, or the class of a provider implementing {@link ParamResolver}. */
1245
+ type ParamResolverOf<C, T, D> = ParamResolverFunction<C, T, D> | ParamResolverClass<C, T, D>;
1246
+ /** The resolvers of a definition, by transport (keys of {@link ParamContexts}). */
1247
+ type ParamResolvers<T, D> = { readonly [K in keyof ParamContexts]?: ParamResolverOf<ParamContexts[K], T, D>; };
1248
+ /** Arguments of a use: none when `D` is `undefined`, optional when `D` includes `undefined`, required otherwise. */
1249
+ type ParamDataArgs<D> = undefined extends D ? [data?: D] : [data: D];
1250
+ /** What {@link createParamDecorator} returns: the decorator (a no-op marker) and its resolvers, for generated code. */
1251
+ interface ParamDecorator<T, D = undefined> {
1252
+ (...data: ParamDataArgs<D>): ParameterMarker;
1253
+ /** The resolvers of the definition, frozen. */
1254
+ readonly resolvers: ParamResolvers<T, D>;
1255
+ }
1256
+ /**
1257
+ * The resolver function of a definition for a transport, as generated code calls it:
1258
+ * `(CurrentUser.resolvers.http as ParamFunctionOf<typeof CurrentUser, 'http'>)(ctx, undefined)`.
1259
+ * The compiler emits it only for function resolvers.
1260
+ */
1261
+ type ParamFunctionOf<P extends {
1262
+ readonly resolvers: object;
1263
+ }, K extends keyof P["resolvers"]> = Extract<NonNullable<P["resolvers"][K]>, (...args: any[]) => unknown>;
1264
+ /**
1265
+ * Defines a parameter decorator whose value is computed per call by a resolver of the handler's
1266
+ * transport (RFC 0010). `T` (required) is the injected type, checked at build time against every
1267
+ * decorated parameter; `D` is the type of the data argument (none by default). The definition must
1268
+ * be an exported top-level `const`: the generated module imports it.
1269
+ *
1270
+ * ```ts
1271
+ * export const CurrentUser = createParamDecorator<User>({
1272
+ * http: ctx => userOf(ctx.state),
1273
+ * graphql: ctx => userOf(ctx.operation.state),
1274
+ * })
1275
+ *
1276
+ * @Get('/me')
1277
+ * me(@CurrentUser() user: User) { ... }
1278
+ * ```
1279
+ */
1280
+ export declare function createParamDecorator<T, D = undefined>(resolvers: ParamResolvers<T, D>): ParamDecorator<T, D>;
1162
1281
  /**
1163
1282
  * ZNIGHT015: a provider factory threw or rejected.
1164
1283
  *
@@ -1190,5 +1309,5 @@ export declare class ZnightAggregateError extends ZnightError {
1190
1309
  * that were attached to it instead of being thrown. Empty when there are none.
1191
1310
  */
1192
1311
  export declare function getSuppressedErrors(error: unknown): readonly unknown[];
1193
- export type { ApplicationOptions, ApplicationState, ClassKey, ClassMarker, ConsoleLike, ConsoleLoggerOptions, CoreLogger, GraphQLOperationError, GraphQLOperationEvent, GraphQLOperationOutcome, GraphQLOperationTransport, GraphQLOperationType, HookEvent, HookListener, HookName, HookWrapper, HooksOptions, HotContext, HttpRequestEvent, InitOptions, InjectableOptions, InterceptMethodOptions, InterceptOptionsArgs, InterceptorClass, InterceptorLink, LogContext, LogLevel, ManagedInstance, MessageDeliveryEvent, MessagePublishEvent, MethodInterceptor, MethodInvocation, MethodMarker, OnReady, OnStart, OnStop, OpenedScope, ParameterMarker, Plugin, PluginContext, PluginHook, PluginOptions, PluginRootsContext, ProcessLike, ProviderKey, ProviderValues, ProvidesOptions, ScheduledRunAbortReason, ScheduledRunEvent, ScheduledRunOutcome, ScheduledRunTrigger, ScopeContext, ScopeValues, ShutdownOptions, ShutdownSignal, TypedToken, ZnightHooks };
1312
+ export type { ApplicationOptions, ApplicationState, ClassKey, ClassMarker, ConsoleLike, ConsoleLoggerOptions, CoreLogger, EventListenerEvent, EventPublishEvent, EventPublishMode, GraphQLOperationError, GraphQLOperationEvent, GraphQLOperationOutcome, GraphQLOperationTransport, GraphQLOperationType, HookEvent, HookListener, HookName, HookWrapper, HooksOptions, HotContext, HttpRequestEvent, InitOptions, InjectableOptions, InterceptMethodOptions, InterceptOptionsArgs, InterceptorClass, InterceptorLink, LogContext, LogLevel, ManagedInstance, MessageDeliveryEvent, MessagePublishEvent, MethodInterceptor, MethodInvocation, MethodMarker, OnReady, OnStart, OnStop, OpenedScope, ParamContexts, ParamDataArgs, ParamDecorator, ParamFunctionOf, ParamResolver, ParamResolverClass, ParamResolverFunction, ParamResolverOf, ParamResolvers, ParameterMarker, Plugin, PluginContext, PluginHook, PluginOptions, PluginRootsContext, ProcessLike, ProviderKey, ProviderValues, ProvidesOptions, ScheduledRunAbortReason, ScheduledRunEvent, ScheduledRunOutcome, ScheduledRunTrigger, ScopeContext, ScopeValues, ShutdownOptions, ShutdownSignal, TypedToken, ZnightHooks };
1194
1313
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -9,7 +9,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
9
9
  * messaging, config, observability).
10
10
  * - From `ZNIGHT030`, each first-party package reserves a block of ten: `ZNIGHT030`–`039`
11
11
  * `@znight/openapi`, `ZNIGHT040`–`049` `@znight/schedule`, `ZNIGHT050`–`059` `@znight/websocket`
12
- * (reserved), `ZNIGHT060`–`069` `@znight/graphql`.
12
+ * (reserved), `ZNIGHT060`–`069` `@znight/graphql`, `ZNIGHT070`–`079` `@znight/events`.
13
13
  *
14
14
  * Within a range, codes are allocated in order without gaps. A package uses its block for its own
15
15
  * failure modes, with one catch-all code for invalid usage and options, and reuses a lower code
@@ -133,7 +133,13 @@ const ErrorCode = {
133
133
  * Schema-first resolvers do not match the SDL (RFC 0007): a field without resolver, a resolver,
134
134
  * type or argument the SDL does not declare, a signature that does not conform to the SDL types.
135
135
  */
136
- GraphQLSchemaMismatch: "ZNIGHT068"
136
+ GraphQLSchemaMismatch: "ZNIGHT068",
137
+ /**
138
+ * Invalid event listener: an `@OnEvent` method whose parameter is not a class (or a union of
139
+ * classes), a generic or optional event, an event class the generated module cannot import, invalid
140
+ * options, the NestJS string form, a detached listener depending on a request-scoped external.
141
+ */
142
+ InvalidEventListener: "ZNIGHT070"
137
143
  };
138
144
  /** Short human readable description of every error code. */
139
145
  const ERROR_DESCRIPTIONS = {
@@ -181,7 +187,8 @@ const ERROR_DESCRIPTIONS = {
181
187
  ZNIGHT065: "Invalid loader: not a Loader of a BatchLoad provider, or a batch returning the wrong number of values",
182
188
  ZNIGHT066: "Invalid GraphQL setup: metadata, schema, GraphQLPlugin options, driver or HttpPlugin missing",
183
189
  ZNIGHT067: "Invalid GraphQL SDL: the schema-first .graphql files cannot be read, parsed or validated",
184
- ZNIGHT068: "GraphQL schema mismatch: schema-first resolvers do not cover or conform to the SDL"
190
+ ZNIGHT068: "GraphQL schema mismatch: schema-first resolvers do not cover or conform to the SDL",
191
+ ZNIGHT070: "Invalid event listener: an @OnEvent method does not listen to a class, or its options are invalid"
185
192
  };
186
193
  /** Base class of every error thrown by Znight at runtime. */
187
194
  var ZnightError = class extends Error {
@@ -2236,11 +2243,11 @@ function positive(value, fallback, name) {
2236
2243
  return value;
2237
2244
  }
2238
2245
  // src/decorators.ts
2239
- function marker() {}
2240
- const classMarker = marker;
2241
- const methodMarker = marker;
2242
- const parameterMarker = marker;
2243
- const classOrMethodMarker = marker;
2246
+ function marker$1() {}
2247
+ const classMarker = marker$1;
2248
+ const methodMarker = marker$1;
2249
+ const parameterMarker$1 = marker$1;
2250
+ const classOrMethodMarker = marker$1;
2244
2251
  /**
2245
2252
  * Declares a provider class. Its constructor parameters are injected.
2246
2253
  *
@@ -2275,11 +2282,11 @@ function Provides(_options) {
2275
2282
  }
2276
2283
  /** Injects the provider qualified with `name` (see {@link Named}). `name` is static. */
2277
2284
  function Inject(_name) {
2278
- return parameterMarker;
2285
+ return parameterMarker$1;
2279
2286
  }
2280
2287
  /** Marks a dependency as optional: `undefined` is injected when no provider exists. */
2281
2288
  function Optional() {
2282
- return parameterMarker;
2289
+ return parameterMarker$1;
2283
2290
  }
2284
2291
  /** Sets the qualifier of a provider class or `@Provides` method. `name` is static. */
2285
2292
  function Named(_name) {
@@ -2301,11 +2308,38 @@ function Primary() {
2301
2308
  function Intercept(_interceptor, ..._options) {
2302
2309
  return methodMarker;
2303
2310
  }
2311
+ // src/params.ts
2312
+ function marker() {}
2313
+ const parameterMarker = marker;
2314
+ /**
2315
+ * Defines a parameter decorator whose value is computed per call by a resolver of the handler's
2316
+ * transport (RFC 0010). `T` (required) is the injected type, checked at build time against every
2317
+ * decorated parameter; `D` is the type of the data argument (none by default). The definition must
2318
+ * be an exported top-level `const`: the generated module imports it.
2319
+ *
2320
+ * ```ts
2321
+ * export const CurrentUser = createParamDecorator<User>({
2322
+ * http: ctx => userOf(ctx.state),
2323
+ * graphql: ctx => userOf(ctx.operation.state),
2324
+ * })
2325
+ *
2326
+ * @Get('/me')
2327
+ * me(@CurrentUser() user: User) { ... }
2328
+ * ```
2329
+ */
2330
+ function createParamDecorator(resolvers) {
2331
+ const decorator = ((..._data) => parameterMarker);
2332
+ Object.defineProperty(decorator, "resolvers", {
2333
+ value: Object.freeze({ ...resolvers }),
2334
+ enumerable: true
2335
+ });
2336
+ return decorator;
2337
+ }
2304
2338
  // src/plugin.ts
2305
2339
  /** Resolves {@link PluginOptions}: calls the function form with the container, returns the others as is. */
2306
2340
  function resolveOptions(options, container) {
2307
2341
  return typeof options === "function" ? options(container) : options;
2308
2342
  }
2309
- export { Application, Container, CoreTokens, DelegatingLogger, ERROR_DESCRIPTIONS, ErrorCode, Factory, Hooks, Inject, Injectable, InstantiationError, Intercept, METADATA_VERSION, Named, Optional, Primary, Provides, ZnightAggregateError, ZnightError, applyInterceptors, callLifecycleHook, createConsoleLogger, describeToken, displayName, disposeInstance, formatPath, getSuppressedErrors, hasLifecycleHook, interceptMethod, isDisposable, isProviderDefinition, resolveOptions, silentLogger, token };
2343
+ export { Application, Container, CoreTokens, DelegatingLogger, ERROR_DESCRIPTIONS, ErrorCode, Factory, Hooks, Inject, Injectable, InstantiationError, Intercept, METADATA_VERSION, Named, Optional, Primary, Provides, ZnightAggregateError, ZnightError, applyInterceptors, callLifecycleHook, createConsoleLogger, createParamDecorator, describeToken, displayName, disposeInstance, formatPath, getSuppressedErrors, hasLifecycleHook, interceptMethod, isDisposable, isProviderDefinition, resolveOptions, silentLogger, token };
2310
2344
 
2311
2345
  //# sourceMappingURL=index.mjs.map