@guren/server 1.4.0 → 1.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.
@@ -184,6 +184,13 @@ interface InertiaDocumentOptions {
184
184
  * `matchMedia` before React hydrates.
185
185
  */
186
186
  readonly prepaintScript?: InertiaDocumentValue;
187
+ /**
188
+ * Raw markup inlined into `<head>`, ahead of the critical CSS and stylesheet
189
+ * links. Unescaped — the app author owns this string. Use it for static,
190
+ * site-wide tags the framework has no way to infer on its own, such as
191
+ * `<link rel="icon">` favicons.
192
+ */
193
+ readonly head?: InertiaDocumentValue;
187
194
  }
188
195
  /**
189
196
  * Register app-wide document defaults for server-rendered Inertia responses.
@@ -198,8 +205,9 @@ interface InertiaDocumentOptions {
198
205
  * requests are in flight leaks the new policy into them. Use the matching
199
206
  * {@link InertiaOptions} fields for a single response instead.
200
207
  *
201
- * The values are emitted verbatim inside `<style>` / `<script>` elements —
202
- * they are developer-authored assets, never user input.
208
+ * The values are emitted verbatim — inside `<style>` / `<script>` elements,
209
+ * or as raw markup for `head` — they are developer-authored assets, never
210
+ * user input.
203
211
  *
204
212
  * ```typescript
205
213
  * setInertiaDocument({
@@ -631,6 +639,17 @@ declare function getQueueDriver(): QueueDriver | null;
631
639
  * ```
632
640
  */
633
641
  declare abstract class Job<T = unknown> {
642
+ /**
643
+ * Stable wire name for this job.
644
+ *
645
+ * Queued messages record this name, and the worker resolves the class back
646
+ * from it. When omitted the class name is used, which breaks if a bundler
647
+ * mangles identifiers or if the class is later renamed while messages are
648
+ * still in flight. Set it to pin the name across both.
649
+ *
650
+ * @default the class name
651
+ */
652
+ static jobName?: string;
634
653
  /**
635
654
  * The queue this job should be dispatched to.
636
655
  * @default 'default'
@@ -687,6 +706,7 @@ declare abstract class Job<T = unknown> {
687
706
  interface JobClass<T = unknown> {
688
707
  new (): Job<T>;
689
708
  name: string;
709
+ jobName?: string;
690
710
  queue: string;
691
711
  maxAttempts: number;
692
712
  backoff: 'exponential' | 'linear' | number;
@@ -694,6 +714,18 @@ interface JobClass<T = unknown> {
694
714
  dispatchAfter(delayMs: number, payload: T, options?: Omit<JobOptions, 'delay'>): Promise<string>;
695
715
  calculateRetryDelay(attempts: number): number;
696
716
  }
717
+ /**
718
+ * Resolve the wire name a job is queued and looked up under.
719
+ *
720
+ * Prefers an explicit `jobName` over the class name so that renaming the class
721
+ * or bundling with identifier mangling does not orphan queued messages.
722
+ *
723
+ * Only an *own* `jobName` counts. Static members are inherited, so reading it
724
+ * off the prototype chain would make every subclass of a pinned job claim its
725
+ * parent's identity and overwrite it in the registry. A subclass that wants a
726
+ * pinned name declares its own.
727
+ */
728
+ declare function resolveJobName(jobClass: Pick<JobClass, 'name' | 'jobName'>): string;
697
729
  /**
698
730
  * Register a job class for the worker to use.
699
731
  */
@@ -904,6 +936,14 @@ interface Notifiable {
904
936
  * Get the notification routing information for a given channel.
905
937
  */
906
938
  routeNotificationFor(channel: string): string | null;
939
+ /**
940
+ * Stable type name for this notifiable (optional).
941
+ *
942
+ * Defaults to the constructor name. Set this when the notifiable is rebuilt
943
+ * from a queue payload, or when the class name is not durable (bundlers that
944
+ * mangle identifiers).
945
+ */
946
+ notifiableType?: string;
907
947
  /**
908
948
  * Database notifications (optional).
909
949
  */
@@ -1113,16 +1153,28 @@ declare class NotificationManager {
1113
1153
  sendNowToMany(notifiables: Notifiable[], notification: Notification): Promise<void>;
1114
1154
  /**
1115
1155
  * Serialize notifiable for queue storage.
1156
+ *
1157
+ * Routing is resolved here rather than in the worker: `routeNotificationFor`
1158
+ * is arbitrary user code — often a closure on an object literal — and cannot
1159
+ * be reconstructed from a payload.
1160
+ *
1161
+ * @param channels - Channels to resolve routes for
1116
1162
  */
1117
- protected serializeNotifiable(notifiable: Notifiable): SerializedNotifiable;
1163
+ protected serializeNotifiable(notifiable: Notifiable, channels?: string[]): SerializedNotifiable;
1118
1164
  /**
1119
1165
  * Serialize notification for queue storage.
1166
+ *
1167
+ * Only own enumerable properties are captured. Behaviour is restored by
1168
+ * rebuilding the registered class in the job handler, not by serializing it.
1120
1169
  */
1121
1170
  protected serializeNotification(notification: Notification): SerializedNotification;
1122
1171
  /**
1123
- * Create the notification job class.
1172
+ * Bind this manager to the queued-notification job and register it.
1173
+ *
1174
+ * Call this during boot in a process that runs a worker but may never send
1175
+ * a notification itself: without it, the worker cannot resolve the job.
1124
1176
  */
1125
- protected createNotificationJob(): typeof SendNotificationJob;
1177
+ registerQueueJob(): typeof SendNotificationJob;
1126
1178
  }
1127
1179
  /**
1128
1180
  * Payload for queued notifications.
@@ -1134,11 +1186,13 @@ interface SendNotificationPayload {
1134
1186
  }
1135
1187
  interface SerializedNotifiable {
1136
1188
  type: string;
1189
+ /** Channel routes resolved at dispatch time. Absent on legacy payloads. */
1190
+ routes?: Record<string, string | null>;
1137
1191
  data: Record<string, unknown>;
1138
1192
  }
1139
1193
  interface SerializedNotification {
1140
- type: string;
1141
1194
  id: string;
1195
+ createdAt: string;
1142
1196
  data: Record<string, unknown>;
1143
1197
  }
1144
1198
  /**
@@ -1150,6 +1204,18 @@ declare class SendNotificationJob extends Job<SendNotificationPayload> {
1150
1204
  static maxAttempts: number;
1151
1205
  static notificationManager: NotificationManager | null;
1152
1206
  handle(payload: SendNotificationPayload): Promise<void>;
1207
+ /**
1208
+ * Rebuild the notifiable from its serialized data.
1209
+ */
1210
+ protected rebuildNotifiable(serialized: SerializedNotifiable): Notifiable;
1211
+ /**
1212
+ * Rebuild a real notification instance from its serialized data.
1213
+ *
1214
+ * The class is looked up in the notification registry and instantiated via
1215
+ * its prototype, so prototype methods (`via`, `toMail`, `toDatabase`,
1216
+ * `toSlack`, `shouldSend`) are restored without running the constructor.
1217
+ */
1218
+ protected rebuildNotification(type: string, serialized: SerializedNotification): Notification;
1153
1219
  }
1154
1220
  /**
1155
1221
  * Set the global notification manager.
@@ -2152,6 +2218,112 @@ declare class ProviderManager {
2152
2218
  getDeferredServices(): string[];
2153
2219
  }
2154
2220
 
2221
+ /**
2222
+ * Parsed argument definition.
2223
+ */
2224
+ interface ArgumentDefinition {
2225
+ name: string;
2226
+ description?: string;
2227
+ required: boolean;
2228
+ array: boolean;
2229
+ defaultValue?: string;
2230
+ }
2231
+ /**
2232
+ * Parsed option definition.
2233
+ */
2234
+ interface OptionDefinition {
2235
+ name: string;
2236
+ shortcut?: string;
2237
+ description?: string;
2238
+ requiresValue: boolean;
2239
+ defaultValue?: string | boolean;
2240
+ array: boolean;
2241
+ }
2242
+ /**
2243
+ * Parsed signature.
2244
+ */
2245
+ interface ParsedSignature {
2246
+ name: string;
2247
+ arguments: ArgumentDefinition[];
2248
+ options: OptionDefinition[];
2249
+ }
2250
+ /**
2251
+ * Command class type.
2252
+ */
2253
+ interface CommandClass {
2254
+ signature: string;
2255
+ description: string;
2256
+ new (container?: Container): CommandInstance;
2257
+ }
2258
+ /**
2259
+ * Command instance type.
2260
+ */
2261
+ interface CommandInstance {
2262
+ setInput(argv: string[]): void;
2263
+ setOutput(output: OutputInterface): void;
2264
+ setKernel(kernel: {
2265
+ handle(argv: string[]): Promise<number>;
2266
+ }): void;
2267
+ run(): Promise<number>;
2268
+ }
2269
+ /**
2270
+ * Output interface.
2271
+ */
2272
+ interface OutputInterface {
2273
+ info(message: string): void;
2274
+ error(message: string): void;
2275
+ warn(message: string): void;
2276
+ success(message: string): void;
2277
+ line(message: string): void;
2278
+ newLine(count?: number): void;
2279
+ table(headers: string[], rows: string[][]): void;
2280
+ write(message: string): void;
2281
+ }
2282
+ /**
2283
+ * Input interface.
2284
+ */
2285
+ interface InputInterface {
2286
+ argument<T = string>(name: string): T;
2287
+ arguments(): Record<string, string | string[]>;
2288
+ option<T = string | boolean>(name: string): T | undefined;
2289
+ options(): Record<string, string | boolean | string[]>;
2290
+ hasOption(name: string): boolean;
2291
+ }
2292
+ /**
2293
+ * Console kernel options.
2294
+ */
2295
+ interface ConsoleKernelOptions {
2296
+ container?: Container;
2297
+ }
2298
+ /**
2299
+ * Schedule definition for a command.
2300
+ */
2301
+ interface ScheduledCommand {
2302
+ command: string;
2303
+ args?: string[];
2304
+ expression: string;
2305
+ timezone?: string;
2306
+ description?: string;
2307
+ }
2308
+ /**
2309
+ * Interactive prompt types.
2310
+ */
2311
+ interface PromptInterface {
2312
+ ask(question: string, defaultValue?: string): Promise<string>;
2313
+ confirm(question: string, defaultValue?: boolean): Promise<boolean>;
2314
+ choice<T extends string>(question: string, choices: T[], defaultValue?: T): Promise<T>;
2315
+ secret(question: string): Promise<string>;
2316
+ }
2317
+ /**
2318
+ * Progress bar interface.
2319
+ */
2320
+ interface ProgressInterface {
2321
+ start(total: number): void;
2322
+ advance(step?: number): void;
2323
+ finish(): void;
2324
+ setProgress(current: number): void;
2325
+ }
2326
+
2155
2327
  /**
2156
2328
  * Declarative definition of an application module — a self-contained
2157
2329
  * `modules/<name>/` directory that can register routes and providers, per
@@ -2173,16 +2345,29 @@ interface ModuleDefinition {
2173
2345
  routes?: (router: Router) => void | Promise<void>;
2174
2346
  /** Providers appended to the application's provider list. */
2175
2347
  providers?: ServiceProviderConstructor[];
2348
+ /**
2349
+ * Console commands the module owns, exposed so the project's console
2350
+ * entrypoint can register them without importing module internals:
2351
+ * `kernel.registerMany(billingModule.commands)`. Nothing registers them
2352
+ * automatically — `Application` never builds a `ConsoleKernel`, and
2353
+ * command registration stays explicit so a bundled deployment resolves
2354
+ * the same commands as a local checkout.
2355
+ */
2356
+ commands?: CommandClass[];
2176
2357
  }
2177
2358
  /**
2178
- * A module as `Application` consumes it — `providers` normalized to always
2179
- * be an array so callers don't repeat the `?? []` fallback.
2359
+ * A module as `Application` consumes it — `providers` and `commands`
2360
+ * normalized to always be arrays so callers don't repeat the `?? []`
2361
+ * fallback. `commands` in particular is read by hand-written console
2362
+ * entrypoints (`kernel.registerMany(billingModule.commands)`), where an
2363
+ * `undefined` would be a runtime error rather than a no-op.
2180
2364
  */
2181
2365
  interface GurenModule {
2182
2366
  name: string;
2183
2367
  prefix?: string;
2184
2368
  routes?: (router: Router) => void | Promise<void>;
2185
2369
  providers: ServiceProviderConstructor[];
2370
+ commands: CommandClass[];
2186
2371
  }
2187
2372
  /**
2188
2373
  * Define a Guren application module without boilerplate.
@@ -2195,10 +2380,14 @@ interface GurenModule {
2195
2380
  * prefix: '/billing',
2196
2381
  * routes: registerBillingRoutes,
2197
2382
  * providers: [BillingServiceProvider],
2383
+ * commands: [InvoiceCommand],
2198
2384
  * })
2199
2385
  *
2200
2386
  * // src/app.ts
2201
2387
  * createApp({ routes, providers, modules: [billingModule] })
2388
+ *
2389
+ * // src/console.ts
2390
+ * kernel.registerMany(billingModule.commands)
2202
2391
  * ```
2203
2392
  */
2204
2393
  declare function defineModule(definition: ModuleDefinition): GurenModule;
@@ -2363,4 +2552,4 @@ declare class Application {
2363
2552
  }
2364
2553
  declare function createApp(options?: ApplicationOptions): Application;
2365
2554
 
2366
- export { type JobHandler as $, Application as A, type GurenModule as B, Container as C, type DevBannerOptions as D, type ErrorResponse as E, type FailedJob as F, GUREN_ASCII_ART as G, type HostAuthorizationOptions as H, type HstsOptions as I, type InertiaDocumentContext as J, type InertiaDocumentOptions as K, type InertiaOptions as L, type InertiaPagePayload as M, NotificationManager as N, type InertiaResponse as O, type Provider as P, QueueManager as Q, type InertiaSharedProps as R, ServiceProvider as S, type InertiaSsrContext as T, type InertiaSsrOptions as U, type InertiaSsrRenderer as V, type InertiaSsrResult as W, type InferInertiaProps as X, Job as Y, type JobClass as Z, type JobFailureHandler as _, type StartViteDevServerOptions as a, inertia as a$, type JobOptions as a0, type ModuleDefinition as a1, type Notifiable as a2, Notification as a3, type NotificationAttachment as a4, type NotificationChannel as a5, type NotificationChannelFactory as a6, type NotificationClass as a7, type NotificationMailMessage as a8, type NotificationManagerOptions as a9, type ValidateRequestOptions as aA, type ValidationSchema as aB, type WorkerOptions as aC, abort as aD, abortIf as aE, abortUnless as aF, clearJobRegistry as aG, createApp as aH, createContainer as aI, createCsrfMiddleware as aJ, createExceptionHandler as aK, createHostAuthorizationMiddleware as aL, createNotificationManager as aM, createQueueManager as aN, createSecurityHeaders as aO, csrfField as aP, defineModule as aQ, formatValidationErrors as aR, getContainer as aS, getCsrfToken as aT, getExceptionHandler as aU, getInertiaSharedPropsResolver as aV, getJob as aW, getNotificationManager as aX, getQueueDriver as aY, getRegisteredJobs as aZ, getValidatedData as a_, ProviderManager as aa, type QueueConfig as ab, type QueueDriver as ac, type QueueDriverFactory as ad, type QueuedJob as ae, type RendererRegistration as af, type ResolvedSharedInertiaProps as ag, type ResourceRouteOptions as ah, type RouteBuilder as ai, type RouteContractOptions as aj, type RouteDefinition as ak, type RouteOpenApiMetadata as al, type ResourceAction as am, Router as an, type SecurityHeadersOptions as ao, type SentNotification as ap, type ServiceBinding as aq, type ServiceClass as ar, type ServiceFactory as as, type ServiceProviderClass as at, type ServiceProviderOptions as au, type SharedInertiaPropsResolver as av, type SlackAttachment as aw, type SlackBlock as ax, type SlackMessage as ay, VALIDATED_DATA_KEY as az, type StartedViteDevServer as b, mountModuleRoutes as b0, parseRequestPayload as b1, registerJob as b2, resolve as b3, setContainer as b4, setExceptionHandler as b5, setInertiaDocument as b6, setInertiaSharedProps as b7, setInertiaSsrRenderer as b8, setNotificationManager as b9, setQueueDriver as ba, shareInertiaProps as bb, validate as bc, validateRequest as bd, validateRequestWith as be, validateSafe as bf, verifyCsrfToken as bg, type ServiceProviderConstructor as c, type ServiceBindings as d, type ApplicationListenOptions as e, type ApplicationOptions as f, type AuthPayload as g, type AuthPluginOptions as h, CSRF_FORM_FIELD as i, CSRF_HEADER_NAME as j, CSRF_TOKEN_KEY as k, logDevServerBanner as l, type ContextualBinding as m, type ContextualBindingBuilder as n, type ContextualNeedsBuilder as o, Controller as p, type ControllerInertiaProps as q, type CsrfOptions as r, startViteDevServer as s, type DatabaseChannelOptions as t, type DatabaseNotification as u, type ExceptionClass as v, ExceptionHandler as w, type ExceptionHandlerOptions as x, type ExceptionRenderer as y, type ExceptionReporter as z };
2555
+ export { type InertiaSsrContext as $, Application as A, type DatabaseNotification as B, type CommandClass as C, type DevBannerOptions as D, type ErrorResponse as E, type ExceptionClass as F, GUREN_ASCII_ART as G, ExceptionHandler as H, type InputInterface as I, type ExceptionHandlerOptions as J, type ExceptionRenderer as K, type ExceptionReporter as L, type FailedJob as M, NotificationManager as N, type OutputInterface as O, type ParsedSignature as P, QueueManager as Q, type GurenModule as R, ServiceProvider as S, type HostAuthorizationOptions as T, type HstsOptions as U, type InertiaDocumentContext as V, type InertiaDocumentOptions as W, type InertiaOptions as X, type InertiaPagePayload as Y, type InertiaResponse as Z, type InertiaSharedProps as _, Container as a, defineModule as a$, type InertiaSsrOptions as a0, type InertiaSsrRenderer as a1, type InertiaSsrResult as a2, type InferInertiaProps as a3, Job as a4, type JobClass as a5, type JobFailureHandler as a6, type JobHandler as a7, type JobOptions as a8, type ModuleDefinition as a9, type SentNotification as aA, type ServiceBinding as aB, type ServiceClass as aC, type ServiceFactory as aD, type ServiceProviderClass as aE, type ServiceProviderOptions as aF, type SharedInertiaPropsResolver as aG, type SlackAttachment as aH, type SlackBlock as aI, type SlackMessage as aJ, VALIDATED_DATA_KEY as aK, type ValidateRequestOptions as aL, type ValidationSchema as aM, type WorkerOptions as aN, abort as aO, abortIf as aP, abortUnless as aQ, clearJobRegistry as aR, createApp as aS, createContainer as aT, createCsrfMiddleware as aU, createExceptionHandler as aV, createHostAuthorizationMiddleware as aW, createNotificationManager as aX, createQueueManager as aY, createSecurityHeaders as aZ, csrfField as a_, type Notifiable as aa, Notification as ab, type NotificationAttachment as ac, type NotificationChannel as ad, type NotificationChannelFactory as ae, type NotificationClass as af, type NotificationMailMessage as ag, type NotificationManagerOptions as ah, type ProgressInterface as ai, type PromptInterface as aj, ProviderManager as ak, type QueueConfig as al, type QueueDriver as am, type QueueDriverFactory as an, type QueuedJob as ao, type RendererRegistration as ap, type ResolvedSharedInertiaProps as aq, type ResourceRouteOptions as ar, type RouteBuilder as as, type RouteContractOptions as at, type RouteDefinition as au, type RouteOpenApiMetadata as av, type ResourceAction as aw, Router as ax, type ScheduledCommand as ay, type SecurityHeadersOptions as az, type ConsoleKernelOptions as b, formatValidationErrors as b0, getContainer as b1, getCsrfToken as b2, getExceptionHandler as b3, getInertiaSharedPropsResolver as b4, getJob as b5, getNotificationManager as b6, getQueueDriver as b7, getRegisteredJobs as b8, getValidatedData as b9, inertia as ba, mountModuleRoutes as bb, parseRequestPayload as bc, registerJob as bd, resolve as be, resolveJobName as bf, setContainer as bg, setExceptionHandler as bh, setInertiaDocument as bi, setInertiaSharedProps as bj, setInertiaSsrRenderer as bk, setNotificationManager as bl, setQueueDriver as bm, shareInertiaProps as bn, validate as bo, validateRequest as bp, validateRequestWith as bq, validateSafe as br, verifyCsrfToken as bs, type StartViteDevServerOptions as c, type StartedViteDevServer as d, type ServiceProviderConstructor as e, type OptionDefinition as f, type CommandInstance as g, type ServiceBindings as h, type ApplicationListenOptions as i, type ApplicationOptions as j, type ArgumentDefinition as k, logDevServerBanner as l, type AuthPayload as m, type AuthPluginOptions as n, CSRF_FORM_FIELD as o, CSRF_HEADER_NAME as p, CSRF_TOKEN_KEY as q, type Provider as r, startViteDevServer as s, type ContextualBinding as t, type ContextualBindingBuilder as u, type ContextualNeedsBuilder as v, Controller as w, type ControllerInertiaProps as x, type CsrfOptions as y, type DatabaseChannelOptions as z };
@@ -0,0 +1,101 @@
1
+ import { C as CommandClass, a as Container, O as OutputInterface, b as ConsoleKernelOptions } from './Application-Bi-olFMF.js';
2
+
3
+ /**
4
+ * Console kernel for managing and executing commands.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const kernel = new ConsoleKernel()
9
+ *
10
+ * kernel.register(CreateUserCommand)
11
+ * kernel.register(SendNotificationsCommand)
12
+ *
13
+ * // Execute command
14
+ * const exitCode = await kernel.handle(['users:create', 'john@example.com', '--admin'])
15
+ * ```
16
+ */
17
+ declare class ConsoleKernel {
18
+ /**
19
+ * Registered commands.
20
+ */
21
+ protected commands: Map<string, CommandClass>;
22
+ /**
23
+ * Service container.
24
+ */
25
+ protected container?: Container;
26
+ /**
27
+ * Output instance.
28
+ */
29
+ protected output: OutputInterface;
30
+ constructor(options?: ConsoleKernelOptions);
31
+ /**
32
+ * Register a command.
33
+ */
34
+ register(command: CommandClass): this;
35
+ /**
36
+ * Register multiple commands.
37
+ */
38
+ registerMany(commands: CommandClass[]): this;
39
+ /**
40
+ * Get all registered commands.
41
+ */
42
+ getCommands(): Map<string, CommandClass>;
43
+ /**
44
+ * Get a command by name.
45
+ */
46
+ getCommand(name: string): CommandClass | undefined;
47
+ /**
48
+ * Check if a command is registered.
49
+ */
50
+ hasCommand(name: string): boolean;
51
+ /**
52
+ * Set the output instance.
53
+ */
54
+ setOutput(output: OutputInterface): this;
55
+ /**
56
+ * Get the output instance.
57
+ */
58
+ getOutput(): OutputInterface;
59
+ /**
60
+ * Handle command execution.
61
+ */
62
+ handle(argv?: string[]): Promise<number>;
63
+ /**
64
+ * Run a command.
65
+ */
66
+ protected runCommand(CommandClass: CommandClass, args: string[]): Promise<number>;
67
+ /**
68
+ * Show help.
69
+ */
70
+ protected showHelp(): void;
71
+ /**
72
+ * Show help for a specific command.
73
+ */
74
+ protected showCommandHelp(commandName: string): void;
75
+ /**
76
+ * List all commands.
77
+ */
78
+ protected listCommands(): void;
79
+ /**
80
+ * Group commands by namespace.
81
+ */
82
+ protected groupCommands(): Map<string, Map<string, CommandClass>>;
83
+ /**
84
+ * Suggest similar commands.
85
+ */
86
+ protected suggestCommands(input: string): void;
87
+ /**
88
+ * Calculate string similarity (simple Dice coefficient).
89
+ */
90
+ protected similarity(a: string, b: string): number;
91
+ /**
92
+ * Call a command programmatically.
93
+ */
94
+ call(commandName: string, args?: string[], silent?: boolean): Promise<number>;
95
+ }
96
+ /**
97
+ * Create a console kernel.
98
+ */
99
+ declare function createConsoleKernel(options?: ConsoleKernelOptions): ConsoleKernel;
100
+
101
+ export { ConsoleKernel as C, createConsoleKernel as c };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  Job,
3
3
  registerJob
4
- } from "./chunk-R2TCP7D7.js";
4
+ } from "./chunk-6J6B5KOB.js";
5
5
 
6
6
  // src/notifications/Notification.ts
7
7
  var Notification = class {
@@ -62,6 +62,36 @@ var Notification = class {
62
62
  }
63
63
  };
64
64
 
65
+ // src/notifications/registry.ts
66
+ var notificationRegistry = /* @__PURE__ */ new Map();
67
+ function resolveRegistryKey(notificationClass) {
68
+ try {
69
+ const { type } = Object.create(notificationClass.prototype);
70
+ if (typeof type === "string" && type.length > 0) {
71
+ return type;
72
+ }
73
+ } catch {
74
+ }
75
+ return notificationClass.name;
76
+ }
77
+ function registerNotification(notificationClass, type) {
78
+ notificationRegistry.set(
79
+ type ?? resolveRegistryKey(notificationClass),
80
+ notificationClass
81
+ );
82
+ }
83
+ function getNotification(type) {
84
+ return notificationRegistry.get(type);
85
+ }
86
+ function clearNotificationRegistry() {
87
+ notificationRegistry.clear();
88
+ }
89
+
90
+ // src/notifications/notifiable-type.ts
91
+ function resolveNotifiableType(notifiable) {
92
+ return notifiable.notifiableType ?? notifiable.constructor?.name ?? "Unknown";
93
+ }
94
+
65
95
  // src/notifications/NotificationManager.ts
66
96
  var NotificationManager = class {
67
97
  channels = /* @__PURE__ */ new Map();
@@ -173,10 +203,16 @@ var NotificationManager = class {
173
203
  * Queue a notification for later delivery.
174
204
  */
175
205
  async queue(notifiable, notification, queueConfig) {
176
- const job = this.createNotificationJob();
177
- registerJob(job);
206
+ const job = this.registerQueueJob();
207
+ registerNotification(
208
+ notification.constructor,
209
+ notification.type
210
+ );
178
211
  const payload = {
179
- notifiableData: this.serializeNotifiable(notifiable),
212
+ notifiableData: this.serializeNotifiable(
213
+ notifiable,
214
+ notification.via(notifiable)
215
+ ),
180
216
  notificationData: this.serializeNotification(notification),
181
217
  notificationType: notification.type
182
218
  };
@@ -206,32 +242,47 @@ var NotificationManager = class {
206
242
  }
207
243
  /**
208
244
  * Serialize notifiable for queue storage.
209
- */
210
- serializeNotifiable(notifiable) {
245
+ *
246
+ * Routing is resolved here rather than in the worker: `routeNotificationFor`
247
+ * is arbitrary user code — often a closure on an object literal — and cannot
248
+ * be reconstructed from a payload.
249
+ *
250
+ * @param channels - Channels to resolve routes for
251
+ */
252
+ serializeNotifiable(notifiable, channels = []) {
253
+ const routes = {};
254
+ for (const channel of channels) {
255
+ routes[channel] = notifiable.routeNotificationFor(channel);
256
+ }
211
257
  return {
212
- type: notifiable.constructor?.name ?? "Unknown",
258
+ type: resolveNotifiableType(notifiable),
259
+ routes,
213
260
  data: { ...notifiable }
214
261
  };
215
262
  }
216
263
  /**
217
264
  * Serialize notification for queue storage.
265
+ *
266
+ * Only own enumerable properties are captured. Behaviour is restored by
267
+ * rebuilding the registered class in the job handler, not by serializing it.
218
268
  */
219
269
  serializeNotification(notification) {
220
270
  return {
221
- type: notification.type,
222
271
  id: notification.id,
272
+ createdAt: notification.createdAt.toISOString(),
223
273
  data: { ...notification }
224
274
  };
225
275
  }
226
276
  /**
227
- * Create the notification job class.
277
+ * Bind this manager to the queued-notification job and register it.
278
+ *
279
+ * Call this during boot in a process that runs a worker but may never send
280
+ * a notification itself: without it, the worker cannot resolve the job.
228
281
  */
229
- createNotificationJob() {
230
- const manager = this;
231
- class BoundSendNotificationJob extends SendNotificationJob {
232
- static notificationManager = manager;
233
- }
234
- return BoundSendNotificationJob;
282
+ registerQueueJob() {
283
+ SendNotificationJob.notificationManager = this;
284
+ registerJob(SendNotificationJob);
285
+ return SendNotificationJob;
235
286
  }
236
287
  };
237
288
  var SendNotificationJob = class extends Job {
@@ -245,33 +296,54 @@ var SendNotificationJob = class extends Job {
245
296
  if (!manager) {
246
297
  throw new Error("NotificationManager not set on SendNotificationJob");
247
298
  }
248
- const notifiable = {
249
- ...payload.notifiableData.data,
299
+ const notifiable = this.rebuildNotifiable(payload.notifiableData);
300
+ const notification = this.rebuildNotification(
301
+ payload.notificationType,
302
+ payload.notificationData
303
+ );
304
+ await manager.sendNow(notifiable, notification);
305
+ }
306
+ /**
307
+ * Rebuild the notifiable from its serialized data.
308
+ */
309
+ rebuildNotifiable(serialized) {
310
+ const { data, routes } = serialized;
311
+ return {
312
+ ...data,
313
+ notifiableType: serialized.type,
250
314
  routeNotificationFor(channel) {
251
- const key = `${channel}Route`;
252
- const value = payload.notifiableData.data[key];
315
+ if (routes && channel in routes) {
316
+ return routes[channel] ?? null;
317
+ }
318
+ const value = data[`${channel}Route`];
253
319
  if (typeof value === "string") return value;
254
320
  if (channel === "mail") {
255
- const email = payload.notifiableData.data["email"];
321
+ const email = data["email"];
256
322
  return typeof email === "string" ? email : null;
257
323
  }
258
324
  return null;
259
325
  }
260
326
  };
261
- const notification = {
262
- ...payload.notificationData.data,
263
- id: payload.notificationData.id,
264
- type: payload.notificationType,
265
- via: () => {
266
- const viaChannels = payload.notificationData.data._viaChannels;
267
- return viaChannels ?? [];
268
- },
269
- shouldSend: () => true,
270
- toMail: payload.notificationData.data.toMail,
271
- toDatabase: payload.notificationData.data.toDatabase,
272
- toSlack: payload.notificationData.data.toSlack
273
- };
274
- await manager.sendNow(notifiable, notification);
327
+ }
328
+ /**
329
+ * Rebuild a real notification instance from its serialized data.
330
+ *
331
+ * The class is looked up in the notification registry and instantiated via
332
+ * its prototype, so prototype methods (`via`, `toMail`, `toDatabase`,
333
+ * `toSlack`, `shouldSend`) are restored without running the constructor.
334
+ */
335
+ rebuildNotification(type, serialized) {
336
+ const NotificationClass = getNotification(type);
337
+ if (!NotificationClass) {
338
+ throw new Error(
339
+ `Notification type "${type}" is not registered. Call registerNotification(${type}) before running the queue worker.`
340
+ );
341
+ }
342
+ return Object.assign(
343
+ Object.create(NotificationClass.prototype),
344
+ serialized.data,
345
+ { id: serialized.id, createdAt: new Date(serialized.createdAt) }
346
+ );
275
347
  }
276
348
  };
277
349
  var globalNotificationManager = null;
@@ -399,7 +471,7 @@ var DatabaseChannel = class {
399
471
  * Get the notifiable type.
400
472
  */
401
473
  getNotifiableType(notifiable) {
402
- return notifiable.constructor?.name ?? "Unknown";
474
+ return resolveNotifiableType(notifiable);
403
475
  }
404
476
  /**
405
477
  * Get all stored notifications (for testing).
@@ -641,6 +713,10 @@ var MemoryChannel = class {
641
713
 
642
714
  export {
643
715
  Notification,
716
+ registerNotification,
717
+ getNotification,
718
+ clearNotificationRegistry,
719
+ resolveNotifiableType,
644
720
  NotificationManager,
645
721
  setNotificationManager,
646
722
  getNotificationManager,