@guren/server 2.21.0 → 2.23.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.
Files changed (115) hide show
  1. package/dist/Job-BxioDEcS.js +165 -0
  2. package/dist/{Logger-DFifRAtc.js → Logger-DWXdtLSJ.js} +62 -2
  3. package/dist/agent/approval-status.d.ts +1 -1
  4. package/dist/agent/approval.d.ts +2 -2
  5. package/dist/agent/audit-emitter.d.ts +11 -1
  6. package/dist/agent/gate.d.ts +10 -8
  7. package/dist/agent/meta-tools.d.ts +13 -5
  8. package/dist/agent/pipeline.d.ts +10 -9
  9. package/dist/auth/AuthManager.d.ts +29 -0
  10. package/dist/auth/AuthenticatableModel.d.ts +15 -0
  11. package/dist/auth/RequestAuthContext.d.ts +10 -1
  12. package/dist/auth/SessionGuard.d.ts +2 -0
  13. package/dist/auth/api-token.d.ts +6 -0
  14. package/dist/auth/context.d.ts +32 -0
  15. package/dist/auth/index.d.ts +7 -0
  16. package/dist/auth/index.js +2 -2
  17. package/dist/auth/model-capability.d.ts +8 -0
  18. package/dist/auth/oauth/index.d.ts +5 -0
  19. package/dist/auth/password/DefaultHasher.d.ts +17 -6
  20. package/dist/auth/password/configured-hasher.d.ts +23 -0
  21. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  22. package/dist/auth/providers/unconfigured-user-provider.d.ts +12 -0
  23. package/dist/auth/types.d.ts +9 -0
  24. package/dist/{auth-CjE2oO50.js → auth-D_W1cJp3.js} +279 -84
  25. package/dist/authorization/Gate.d.ts +12 -0
  26. package/dist/authorization/index.js +1 -1
  27. package/dist/{authorization-CdEWZZw3.js → authorization-0mCGUFoI.js} +58 -12
  28. package/dist/broadcasting/BroadcastManager.d.ts +10 -0
  29. package/dist/broadcasting/index.js +1 -1
  30. package/dist/{broadcasting-B5RzB0A2.js → broadcasting-BdJnaq1O.js} +17 -3
  31. package/dist/cache/index.js +1 -1
  32. package/dist/{cache-thXRnaju.js → cache-DikxP7Bk.js} +1 -1
  33. package/dist/container/Container.d.ts +18 -1
  34. package/dist/container/bindings.d.ts +9 -4
  35. package/dist/container/index.d.ts +4 -2
  36. package/dist/container/resolve-optional.d.ts +10 -0
  37. package/dist/context-af2n5abO.js +91 -0
  38. package/dist/{Job-CvDwk2Gj.js → default-application-Chbrul_m.js} +126 -82
  39. package/dist/encryption/Encrypter.d.ts +10 -0
  40. package/dist/encryption/index.js +1 -1
  41. package/dist/{encryption-uwP3Di4D.js → encryption-BRjZnshr.js} +23 -5
  42. package/dist/errors/ExceptionHandler.d.ts +10 -0
  43. package/dist/events/Event.d.ts +18 -0
  44. package/dist/events/EventManager.d.ts +56 -4
  45. package/dist/events/index.d.ts +2 -1
  46. package/dist/events/index.js +2 -2
  47. package/dist/events/queued.d.ts +8 -0
  48. package/dist/events/serialize.d.ts +8 -0
  49. package/dist/events/types.d.ts +19 -2
  50. package/dist/events-C86rS63h.js +428 -0
  51. package/dist/health/checks/CacheCheck.d.ts +3 -5
  52. package/dist/health/checks/StorageCheck.d.ts +3 -5
  53. package/dist/health/index.js +1 -1
  54. package/dist/{health-DQSvUplL.js → health-CB0oS_UE.js} +2 -2
  55. package/dist/http/Application.d.ts +28 -0
  56. package/dist/http/default-application.d.ts +33 -0
  57. package/dist/http/middleware/detect-locale.d.ts +2 -1
  58. package/dist/http/request-container.d.ts +25 -0
  59. package/dist/i18n/I18nManager.d.ts +16 -3
  60. package/dist/i18n/index.d.ts +1 -1
  61. package/dist/i18n/index.js +2 -2
  62. package/dist/{i18n-BZ2VrSud.js → i18n-DRo1g0AN.js} +34 -10
  63. package/dist/index.d.ts +16 -11
  64. package/dist/index.js +248 -129
  65. package/dist/lambda/index.js +1 -1
  66. package/dist/logging/LogManager.d.ts +9 -0
  67. package/dist/logging/index.js +2 -2
  68. package/dist/{logging-DXmqqUl4.js → logging-CXotojgW.js} +17 -4
  69. package/dist/mail/Mail.d.ts +14 -1
  70. package/dist/mail/MailManager.d.ts +10 -2
  71. package/dist/mail/index.js +1 -1
  72. package/dist/{mail-9CrvJyBZ.js → mail-CmxO2Ttx.js} +42 -11
  73. package/dist/mvc/Controller.d.ts +1 -1
  74. package/dist/mvc/Router.d.ts +16 -5
  75. package/dist/mvc/inertia/InertiaEngine.d.ts +24 -3
  76. package/dist/mvc/inertia/shared.d.ts +7 -0
  77. package/dist/notifications/NotificationManager.d.ts +15 -0
  78. package/dist/notifications/index.js +1 -1
  79. package/dist/{notifications-D0VXkFLF.js → notifications-CE3U7uyg.js} +24 -5
  80. package/dist/providers/AuthServiceProvider.d.ts +5 -4
  81. package/dist/providers/AuthorizationServiceProvider.d.ts +2 -2
  82. package/dist/providers/BroadcastServiceProvider.d.ts +4 -1
  83. package/dist/providers/EncryptionServiceProvider.d.ts +7 -1
  84. package/dist/providers/EventServiceProvider.d.ts +1 -0
  85. package/dist/providers/LogServiceProvider.d.ts +6 -1
  86. package/dist/providers/MailServiceProvider.d.ts +7 -1
  87. package/dist/providers/NotificationServiceProvider.d.ts +4 -1
  88. package/dist/queue/Job.d.ts +39 -0
  89. package/dist/queue/QueueManager.d.ts +14 -5
  90. package/dist/queue/Worker.d.ts +2 -1
  91. package/dist/queue/index.d.ts +1 -1
  92. package/dist/queue/index.js +3 -3
  93. package/dist/queue/types.d.ts +7 -0
  94. package/dist/{queue-zPPYZdif.js → queue-B3x_RKnB.js} +24 -10
  95. package/dist/redis/RedisSchedulerLock.d.ts +17 -0
  96. package/dist/redis/index.d.ts +2 -0
  97. package/dist/redis/index.js +21 -1
  98. package/dist/runtime/index.js +1 -1
  99. package/dist/scheduling/MemorySchedulerLock.d.ts +16 -0
  100. package/dist/scheduling/ScheduledTask.d.ts +19 -2
  101. package/dist/scheduling/Scheduler.d.ts +25 -0
  102. package/dist/scheduling/index.d.ts +2 -1
  103. package/dist/scheduling/index.js +2 -2
  104. package/dist/scheduling/types.d.ts +26 -2
  105. package/dist/{scheduling-C6tcOtUl.js → scheduling-DudNXGnh.js} +178 -20
  106. package/dist/storage/index.js +1 -1
  107. package/dist/{storage-D_yNe54O.js → storage-6HLaUf9j.js} +2 -13
  108. package/dist/support/deprecate.d.ts +16 -0
  109. package/dist/support/keep-alive.d.ts +26 -0
  110. package/dist/support/request-deferrer.d.ts +10 -0
  111. package/dist/{vite-manifest-CdfPfQdj.js → vite-manifest-B8720V7w.js} +1 -1
  112. package/dist/warn-once-p-IlMjra.js +13 -0
  113. package/package.json +3 -2
  114. package/dist/context-CXk_umpT.js +0 -21
  115. package/dist/events-DOmAHDeP.js +0 -230
@@ -1,4 +1,5 @@
1
1
  import { a as generateAppKey, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
2
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
2
3
  import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "crypto";
3
4
  //#region src/encryption/Encrypter.ts
4
5
  /**
@@ -128,20 +129,37 @@ let globalEncrypter = null;
128
129
  function createEncrypter(config) {
129
130
  return new Encrypter(config);
130
131
  }
132
+ /**
133
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the encrypter on
134
+ * the app's container instead — `EncryptionServiceProvider` already does, and a
135
+ * provider of your own reaches it as `this.container.instance('encrypter', e)`.
136
+ */
131
137
  function setEncrypter(encrypter) {
132
- globalEncrypter = encrypter;
138
+ warnDeprecatedSetter("setEncrypter");
139
+ globalEncrypter = bindAmbient("encrypter", encrypter) ? null : encrypter;
133
140
  }
141
+ /**
142
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use
143
+ * `this.make('encrypter')` in a controller, job or command, or
144
+ * `defaultContainer().make('encrypter')`. `encrypt()` / `decrypt()` are unaffected.
145
+ */
134
146
  function getEncrypter() {
135
- if (!globalEncrypter) throw new Error("Encrypter not initialized. Call setEncrypter() first.");
136
- return globalEncrypter;
147
+ warnDeprecatedGetter("getEncrypter");
148
+ return resolveEncrypter();
149
+ }
150
+ /** @internal The default application's `encrypter`, else the one `setEncrypter()` installed. */
151
+ function resolveEncrypter() {
152
+ const encrypter = ambientBinding("encrypter") ?? globalEncrypter;
153
+ if (!encrypter) throw new Error("Encrypter not initialized. Register EncryptionServiceProvider, or call setEncrypter() first.");
154
+ return encrypter;
137
155
  }
138
156
  /** Encrypt with the global encrypter. */
139
157
  function encrypt(value, options) {
140
- return getEncrypter().encrypt(value, options);
158
+ return resolveEncrypter().encrypt(value, options);
141
159
  }
142
160
  /** Decrypt with the global encrypter. */
143
161
  function decrypt(payload, options) {
144
- return getEncrypter().decrypt(payload, options);
162
+ return resolveEncrypter().decrypt(payload, options);
145
163
  }
146
164
  //#endregion
147
165
  //#region src/encryption/signed-url.ts
@@ -24,7 +24,17 @@ export declare class ExceptionHandler {
24
24
  middleware(): Middleware;
25
25
  }
26
26
  export declare function createExceptionHandler(options?: ExceptionHandlerOptions): ExceptionHandler;
27
+ /**
28
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the handler on the
29
+ * app's container instead — `ErrorServiceProvider` already does, and a provider
30
+ * of your own reaches it as `this.container.instance('exception.handler', h)`.
31
+ */
27
32
  export declare function setExceptionHandler(handler: ExceptionHandler): void;
33
+ /**
34
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use
35
+ * `this.make('exception.handler')` in a controller, job or command, or
36
+ * `defaultContainer().make('exception.handler')`.
37
+ */
28
38
  export declare function getExceptionHandler(): ExceptionHandler;
29
39
  export declare function abort(statusCode: number, message?: string, errors?: Record<string, string[]>): never;
30
40
  export declare function abortIf(condition: boolean, statusCode: number, message?: string): void;
@@ -1,6 +1,24 @@
1
1
  /** Base class for all application events. */
2
2
  export declare abstract class Event {
3
3
  readonly timestamp: Date;
4
+ /**
5
+ * Stable wire name: queued emits record it and the worker resolves the class
6
+ * back from it. Declare it as a static field to pin the name against a
7
+ * rename or identifier mangling.
8
+ * @default the class name
9
+ */
4
10
  static get eventName(): string;
5
11
  get eventName(): string;
6
12
  }
13
+ interface EventNameCarrier {
14
+ name: string;
15
+ eventName?: string;
16
+ }
17
+ /**
18
+ * Only an *own* `eventName` counts: statics are inherited, so reading the
19
+ * prototype chain would make every subclass of a pinned event claim its
20
+ * parent's name and take over its listeners. The base class's own entry is the
21
+ * accessor, which answers with the class name.
22
+ */
23
+ export declare function resolveEventName(eventClass: EventNameCarrier): string;
24
+ export {};
@@ -1,23 +1,75 @@
1
- import type { Event } from './Event.js';
2
- import type { EventClass, EventListener, ListenerOptions, EventSubscription } from './types.js';
1
+ import { type Event } from './Event.js';
2
+ import type { ListenerClass } from './Listener.js';
3
+ import type { EventClass, EventListener, ListenerOptions, QueueEventDispatcher, EventSubscription } from './types.js';
3
4
  /** Registers listeners and emits events. */
4
5
  export declare class EventManager {
5
6
  private readonly listeners;
7
+ /** Classes seen by `on()` or `registerEvent()`, so a queued event can be rebuilt as an instance on the worker. */
8
+ private readonly eventClasses;
9
+ /** Next `listenerSeq` per "<event>\u0000<queue>", never reset; see {@link RegisteredListener.listenerSeq}. */
10
+ private readonly listenerSeqCounters;
6
11
  private queueDispatcher?;
7
12
  on<T extends Event>(event: EventClass<T> | string, listener: EventListener<T>, options?: ListenerOptions): EventSubscription;
13
+ private register;
8
14
  once<T extends Event>(event: EventClass<T> | string, listener: EventListener<T>, options?: Omit<ListenerOptions, 'once'>): EventSubscription;
15
+ /**
16
+ * Makes the class resolvable by name when a queued emit reaches a worker.
17
+ * `on()` registers it too; a worker that only drains the queue registers the
18
+ * listeners anyway, so this is for a process that emits and never listens.
19
+ */
20
+ registerEvent(eventClass: EventClass): void;
21
+ /**
22
+ * Registers a `Listener` subclass under its own statics: `event`, `priority`,
23
+ * and `queue` when `shouldQueue`. The instance is built per invocation, so
24
+ * two events cannot share one listener's state. `failed()` is terminal either
25
+ * way: inline on the throw that then propagates, queued once the carrier
26
+ * job's retries are exhausted, where `Job.failed` runs.
27
+ */
28
+ listen<T extends Event>(listenerClass: ListenerClass<T>): EventSubscription;
9
29
  /** Omitting `listener` removes every listener for the event. */
10
30
  off<T extends Event>(event: EventClass<T> | string, listener?: EventListener<T>): void;
11
31
  /** Highest priority first, awaited one at a time. */
12
32
  emit<T extends Event>(event: T): Promise<void>;
13
33
  /** {@link emit} without the ordering guarantee. */
14
34
  emitParallel<T extends Event>(event: T): Promise<void>;
35
+ private dispatch;
36
+ /** Resolves whether the listener was sent to a queue rather than run here. */
37
+ private invoke;
38
+ /**
39
+ * Counted per event and queue, so an inline listener registered beside them
40
+ * does not move the numbers. The worker counts its own the same way, which is
41
+ * why both processes must register the queued listeners in the same order.
42
+ */
43
+ private nextListenerSeq;
44
+ private onQueue;
45
+ private forget;
46
+ /**
47
+ * The worker side of a queued emit: runs the listener the message names,
48
+ * with the event rebuilt as an instance of the registered class. An absent
49
+ * `listenerSeq` — a dispatcher of your own that does not send one — runs
50
+ * every listener for that event on that queue.
51
+ */
52
+ handleQueued(queueName: string, eventName: string, data: Record<string, unknown>, listenerSeq?: number): Promise<void>;
53
+ /**
54
+ * The worker side of a queued listener's failure, once the carrier job has
55
+ * run out of retries. Total by contract: an unknown listener, a class with no
56
+ * `failed()`, and an event it cannot rebuild are no-ops, since a throw here
57
+ * only buries the error that caused it.
58
+ */
59
+ failedQueued(queueName: string, eventName: string, data: Record<string, unknown>, listenerSeq: number | undefined, error: Error): Promise<void>;
60
+ private rehydrate;
15
61
  hasListeners(event: EventClass | string): boolean;
16
62
  getListeners<T extends Event>(event: EventClass<T> | string): EventListener<T>[];
17
63
  listenerCount(event: EventClass | string): number;
18
64
  eventNames(): string[];
19
65
  removeAllListeners(): void;
20
- /** Called by the Queue system when it is integrated. */
21
- setQueueDispatcher(dispatcher: (queueName: string, eventName: string, event: Event) => Promise<void>): void;
66
+ /**
67
+ * `EventServiceProvider` installs `createQueueEventDispatcher()` at boot,
68
+ * before the app's queue driver necessarily exists. A dispatcher that finds
69
+ * no queue at emit time resolves false, and the listener runs inline rather
70
+ * than failing the emit.
71
+ */
72
+ setQueueDispatcher(dispatcher: QueueEventDispatcher): void;
73
+ private nameOf;
22
74
  }
23
75
  export declare function createEventManager(): EventManager;
@@ -2,5 +2,6 @@ export { Event } from './Event.js';
2
2
  export { EventManager, createEventManager } from './EventManager.js';
3
3
  export { Listener } from './Listener.js';
4
4
  export type { ListenerClass } from './Listener.js';
5
- export type { EventClass, EventListener, ListenerOptions, RegisteredListener, EventSubscription, } from './types.js';
5
+ export { createQueueEventDispatcher } from './queued.js';
6
+ export type { EventClass, EventListener, ListenerOptions, QueueEventDispatcher, RegisteredListener, EventSubscription, } from './types.js';
6
7
  export { RequestReceived, RequestFinished, UserAuthenticated, UserLoggedOut, JobProcessed, JobFailed, ApplicationStarted, ApplicationShutdown, } from './builtin.js';
@@ -1,2 +1,2 @@
1
- import { a as RequestFinished, c as UserLoggedOut, d as createEventManager, f as Event, i as JobProcessed, l as Listener, n as ApplicationStarted, o as RequestReceived, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as EventManager } from "../events-DOmAHDeP.js";
2
- export { ApplicationShutdown, ApplicationStarted, Event, EventManager, JobFailed, JobProcessed, Listener, RequestFinished, RequestReceived, UserAuthenticated, UserLoggedOut, createEventManager };
1
+ import { a as RequestFinished, c as UserLoggedOut, d as EventManager, f as createEventManager, i as JobProcessed, l as createQueueEventDispatcher, n as ApplicationStarted, o as RequestReceived, p as Event, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as Listener } from "../events-C86rS63h.js";
2
+ export { ApplicationShutdown, ApplicationStarted, Event, EventManager, JobFailed, JobProcessed, Listener, RequestFinished, RequestReceived, UserAuthenticated, UserLoggedOut, createEventManager, createQueueEventDispatcher };
@@ -0,0 +1,8 @@
1
+ import type { QueueEventDispatcher } from './types.js';
2
+ /**
3
+ * The dispatcher `EventServiceProvider` installs at boot. Registers the carrier
4
+ * job too, which is what lets a worker booting the same app resolve the message.
5
+ * Resolves false rather than letting `Job.dispatch()` throw: it is installed
6
+ * before the app's queue is bound, and an emit it cannot queue runs inline.
7
+ */
8
+ export declare function createQueueEventDispatcher(): QueueEventDispatcher;
@@ -0,0 +1,8 @@
1
+ import type { Event } from './Event.js';
2
+ /**
3
+ * An event's own enumerable fields, one level deep: a Date nested inside an
4
+ * object or array field survives as whatever the driver's encoding makes of it.
5
+ */
6
+ export declare function encodeEventData(event: Event): Record<string, unknown>;
7
+ /** The inverse of {@link encodeEventData}; a value that carries no tag is passed through. */
8
+ export declare function decodeEventData(data: Record<string, unknown>): Record<string, unknown>;
@@ -16,14 +16,31 @@ export interface ListenerOptions {
16
16
  */
17
17
  priority?: number;
18
18
  /**
19
- * Dispatch to this queue instead of running inline. Requires the Queue
20
- * system to be configured.
19
+ * Dispatch to this queue instead of running inline. A manager that cannot
20
+ * reach a queue warns once and runs the listener inline.
21
21
  */
22
22
  queue?: string;
23
23
  }
24
+ /**
25
+ * Sends one queued listener's emit; `event` is the live instance, serialized by
26
+ * the dispatcher. `listenerSeq` identifies the listener among those on that
27
+ * queue — a dispatcher that drops it makes the worker run all of them.
28
+ * Only an explicit `false` means no queue was reachable, which runs the
29
+ * listener inline; a dispatcher resolving nothing reads as having queued.
30
+ */
31
+ export type QueueEventDispatcher = (queueName: string, eventName: string, event: Event, listenerSeq?: number) => Promise<boolean>;
24
32
  export interface RegisteredListener<T extends Event = Event> {
25
33
  listener: EventListener<T>;
26
34
  options: ListenerOptions;
35
+ /**
36
+ * Registration order among the listeners for this event on this queue, which
37
+ * a queued message addresses instead of an array position: a `once` listener
38
+ * removed after its own message renumbers every position behind it, and the
39
+ * message still in flight would then name the wrong listener or none.
40
+ */
41
+ listenerSeq?: number;
42
+ /** A queued listener class's `failed()`, run by the carrier job once its retries are exhausted. */
43
+ failed?: (event: T, error: Error) => void | Promise<void>;
27
44
  }
28
45
  export interface EventSubscription {
29
46
  unsubscribe(): void;
@@ -0,0 +1,428 @@
1
+ import { d as resolveQueueDriver, l as registerJob, t as Job } from "./Job-BxioDEcS.js";
2
+ import { t as warnOnce } from "./warn-once-p-IlMjra.js";
3
+ //#region src/events/Event.ts
4
+ /** Base class for all application events. */
5
+ var Event = class {
6
+ timestamp = /* @__PURE__ */ new Date();
7
+ /**
8
+ * Stable wire name: queued emits record it and the worker resolves the class
9
+ * back from it. Declare it as a static field to pin the name against a
10
+ * rename or identifier mangling.
11
+ * @default the class name
12
+ */
13
+ static get eventName() {
14
+ return this.name;
15
+ }
16
+ get eventName() {
17
+ return resolveEventName(this.constructor);
18
+ }
19
+ };
20
+ /**
21
+ * Only an *own* `eventName` counts: statics are inherited, so reading the
22
+ * prototype chain would make every subclass of a pinned event claim its
23
+ * parent's name and take over its listeners. The base class's own entry is the
24
+ * accessor, which answers with the class name.
25
+ */
26
+ function resolveEventName(eventClass) {
27
+ return (Object.prototype.hasOwnProperty.call(eventClass, "eventName") ? eventClass.eventName : void 0) ?? eventClass.name;
28
+ }
29
+ //#endregion
30
+ //#region src/events/serialize.ts
31
+ /**
32
+ * Marks a `Date` inside a queued event's fields. A driver that JSON-encodes the
33
+ * message turns every Date into a string indistinguishable from a string field,
34
+ * so the tag is what tells the worker which ones to revive.
35
+ */
36
+ const DATE_TAG = "__guren_date";
37
+ /**
38
+ * An event's own enumerable fields, one level deep: a Date nested inside an
39
+ * object or array field survives as whatever the driver's encoding makes of it.
40
+ */
41
+ function encodeEventData(event) {
42
+ const encoded = {};
43
+ for (const [key, value] of Object.entries(event)) encoded[key] = value instanceof Date ? { [DATE_TAG]: value.toISOString() } : value;
44
+ return encoded;
45
+ }
46
+ /** The inverse of {@link encodeEventData}; a value that carries no tag is passed through. */
47
+ function decodeEventData(data) {
48
+ const decoded = {};
49
+ for (const [key, value] of Object.entries(data)) {
50
+ const iso = readDateTag(value);
51
+ decoded[key] = iso === void 0 ? value : new Date(iso);
52
+ }
53
+ return decoded;
54
+ }
55
+ function readDateTag(value) {
56
+ if (typeof value !== "object" || value === null) return void 0;
57
+ const tagged = value[DATE_TAG];
58
+ return typeof tagged === "string" ? tagged : void 0;
59
+ }
60
+ //#endregion
61
+ //#region src/events/EventManager.ts
62
+ /** Registers listeners and emits events. */
63
+ var EventManager = class {
64
+ listeners = /* @__PURE__ */ new Map();
65
+ /** Classes seen by `on()` or `registerEvent()`, so a queued event can be rebuilt as an instance on the worker. */
66
+ eventClasses = /* @__PURE__ */ new Map();
67
+ /** Next `listenerSeq` per "<event>\u0000<queue>", never reset; see {@link RegisteredListener.listenerSeq}. */
68
+ listenerSeqCounters = /* @__PURE__ */ new Map();
69
+ queueDispatcher;
70
+ on(event, listener, options = {}) {
71
+ return this.register(event, listener, options);
72
+ }
73
+ register(event, listener, options, failed) {
74
+ const eventName = this.nameOf(event);
75
+ if (typeof event !== "string") this.eventClasses.set(eventName, event);
76
+ const registeredListeners = this.listeners.get(eventName) ?? [];
77
+ const registered = {
78
+ listener,
79
+ options: {
80
+ once: false,
81
+ priority: 0,
82
+ ...options
83
+ },
84
+ listenerSeq: options.queue === void 0 ? void 0 : this.nextListenerSeq(eventName, options.queue),
85
+ failed
86
+ };
87
+ registeredListeners.push(registered);
88
+ registeredListeners.sort((a, b) => (b.options.priority ?? 0) - (a.options.priority ?? 0));
89
+ this.listeners.set(eventName, registeredListeners);
90
+ return { unsubscribe: () => this.off(event, listener) };
91
+ }
92
+ once(event, listener, options = {}) {
93
+ return this.on(event, listener, {
94
+ ...options,
95
+ once: true
96
+ });
97
+ }
98
+ /**
99
+ * Makes the class resolvable by name when a queued emit reaches a worker.
100
+ * `on()` registers it too; a worker that only drains the queue registers the
101
+ * listeners anyway, so this is for a process that emits and never listens.
102
+ */
103
+ registerEvent(eventClass) {
104
+ this.eventClasses.set(resolveEventName(eventClass), eventClass);
105
+ }
106
+ /**
107
+ * Registers a `Listener` subclass under its own statics: `event`, `priority`,
108
+ * and `queue` when `shouldQueue`. The instance is built per invocation, so
109
+ * two events cannot share one listener's state. `failed()` is terminal either
110
+ * way: inline on the throw that then propagates, queued once the carrier
111
+ * job's retries are exhausted, where `Job.failed` runs.
112
+ */
113
+ listen(listenerClass) {
114
+ const queue = listenerClass.shouldQueue ? listenerClass.queue : void 0;
115
+ const listener = async (event) => {
116
+ const instance = new listenerClass();
117
+ if (instance.shouldHandle && !instance.shouldHandle(event)) return;
118
+ if (queue !== void 0) {
119
+ await instance.handle(event);
120
+ return;
121
+ }
122
+ try {
123
+ await instance.handle(event);
124
+ } catch (error) {
125
+ const failure = error instanceof Error ? error : new Error(String(error));
126
+ if (instance.failed) await instance.failed(event, failure);
127
+ throw failure;
128
+ }
129
+ };
130
+ const failed = queue === void 0 ? void 0 : async (event, error) => {
131
+ await new listenerClass().failed?.(event, error);
132
+ };
133
+ return this.register(listenerClass.event, listener, {
134
+ priority: listenerClass.priority,
135
+ queue
136
+ }, failed);
137
+ }
138
+ /** Omitting `listener` removes every listener for the event. */
139
+ off(event, listener) {
140
+ const eventName = this.nameOf(event);
141
+ const registeredListeners = this.listeners.get(eventName);
142
+ if (!registeredListeners) return;
143
+ if (!listener) {
144
+ this.listeners.delete(eventName);
145
+ return;
146
+ }
147
+ const index = registeredListeners.findIndex((r) => r.listener === listener);
148
+ if (index !== -1) {
149
+ registeredListeners.splice(index, 1);
150
+ if (registeredListeners.length === 0) this.listeners.delete(eventName);
151
+ }
152
+ }
153
+ /** Highest priority first, awaited one at a time. */
154
+ async emit(event) {
155
+ await this.dispatch(event, false);
156
+ }
157
+ /** {@link emit} without the ordering guarantee. */
158
+ async emitParallel(event) {
159
+ await this.dispatch(event, true);
160
+ }
161
+ async dispatch(event, parallel) {
162
+ const eventName = event.eventName;
163
+ const registeredListeners = this.listeners.get(eventName);
164
+ if (!registeredListeners || registeredListeners.length === 0) return;
165
+ const listenersToCall = [...registeredListeners];
166
+ const toRemove = [];
167
+ const call = async (registered) => {
168
+ const queued = await this.invoke(registered, event, eventName);
169
+ if (registered.options.once && !queued) toRemove.push(registered);
170
+ };
171
+ if (parallel) await Promise.all(listenersToCall.map(call));
172
+ else for (const registered of listenersToCall) await call(registered);
173
+ this.forget(eventName, registeredListeners, toRemove);
174
+ }
175
+ /** Resolves whether the listener was sent to a queue rather than run here. */
176
+ async invoke(registered, event, eventName) {
177
+ const queue = registered.options.queue;
178
+ if (!queue) {
179
+ await registered.listener(event);
180
+ return false;
181
+ }
182
+ const dispatcher = this.queueDispatcher;
183
+ if (!dispatcher || await dispatcher(queue, eventName, event, registered.listenerSeq) === false) {
184
+ warnOnce(`event-queue-unwired:${eventName}:${queue}`, `[guren] A listener for "${eventName}" is registered with queue "${queue}", but no queue is reachable from this EventManager, so it ran inline. Bind a QueueManager as "queue" (QueueServiceProvider) and register a driver, or call setQueueDispatcher(createQueueEventDispatcher()) on a manager you build yourself. A future major will throw here instead of running the listener inline.`);
185
+ await registered.listener(event);
186
+ return false;
187
+ }
188
+ return true;
189
+ }
190
+ /**
191
+ * Counted per event and queue, so an inline listener registered beside them
192
+ * does not move the numbers. The worker counts its own the same way, which is
193
+ * why both processes must register the queued listeners in the same order.
194
+ */
195
+ nextListenerSeq(eventName, queue) {
196
+ const key = `${eventName}\u0000${queue}`;
197
+ const next = this.listenerSeqCounters.get(key) ?? 0;
198
+ this.listenerSeqCounters.set(key, next + 1);
199
+ return next;
200
+ }
201
+ onQueue(eventName, queue) {
202
+ return (this.listeners.get(eventName) ?? []).filter((r) => r.options.queue === queue);
203
+ }
204
+ forget(eventName, registeredListeners, toRemove) {
205
+ for (const registered of toRemove) {
206
+ const index = registeredListeners.indexOf(registered);
207
+ if (index !== -1) registeredListeners.splice(index, 1);
208
+ }
209
+ if (registeredListeners.length === 0) this.listeners.delete(eventName);
210
+ }
211
+ /**
212
+ * The worker side of a queued emit: runs the listener the message names,
213
+ * with the event rebuilt as an instance of the registered class. An absent
214
+ * `listenerSeq` — a dispatcher of your own that does not send one — runs
215
+ * every listener for that event on that queue.
216
+ */
217
+ async handleQueued(queueName, eventName, data, listenerSeq) {
218
+ const onQueue = this.onQueue(eventName, queueName);
219
+ const named = listenerSeq === void 0 ? void 0 : onQueue.find((r) => r.listenerSeq === listenerSeq);
220
+ if (listenerSeq !== void 0 && named === void 0) throw new Error(`Queued event "${eventName}" names listener ${listenerSeq} on queue "${queueName}", but this process has no listener registered under that number (${onQueue.length} on that queue). The worker must register the same queued listeners, in the same order, as the process that emitted.`);
221
+ const event = this.rehydrate(eventName, data);
222
+ const toRun = named === void 0 ? onQueue : [named];
223
+ for (const registered of toRun) {
224
+ await registered.listener(event);
225
+ if (registered.options.once) this.off(eventName, registered.listener);
226
+ }
227
+ }
228
+ /**
229
+ * The worker side of a queued listener's failure, once the carrier job has
230
+ * run out of retries. Total by contract: an unknown listener, a class with no
231
+ * `failed()`, and an event it cannot rebuild are no-ops, since a throw here
232
+ * only buries the error that caused it.
233
+ */
234
+ async failedQueued(queueName, eventName, data, listenerSeq, error) {
235
+ if (listenerSeq === void 0 || !this.eventClasses.has(eventName)) return;
236
+ const registered = this.onQueue(eventName, queueName).find((r) => r.listenerSeq === listenerSeq);
237
+ if (!registered?.failed) return;
238
+ await registered.failed(this.rehydrate(eventName, data), error);
239
+ }
240
+ rehydrate(eventName, data) {
241
+ const eventClass = this.eventClasses.get(eventName);
242
+ if (!eventClass) throw new Error(`No event class is registered for "${eventName}", so the queued message cannot be rebuilt. Register it with events.registerEvent(EventClass) in the worker process, or listen for the class itself rather than the name. Pin the name with \`static eventName\` if the class may be renamed.`);
243
+ const event = Object.create(eventClass.prototype);
244
+ Object.assign(event, decodeEventData(data));
245
+ if (typeof event.timestamp === "string") event.timestamp = new Date(event.timestamp);
246
+ return event;
247
+ }
248
+ hasListeners(event) {
249
+ const listeners = this.listeners.get(this.nameOf(event));
250
+ return listeners !== void 0 && listeners.length > 0;
251
+ }
252
+ getListeners(event) {
253
+ const registeredListeners = this.listeners.get(this.nameOf(event));
254
+ if (!registeredListeners) return [];
255
+ return registeredListeners.map((r) => r.listener);
256
+ }
257
+ listenerCount(event) {
258
+ return this.listeners.get(this.nameOf(event))?.length ?? 0;
259
+ }
260
+ eventNames() {
261
+ return Array.from(this.listeners.keys());
262
+ }
263
+ removeAllListeners() {
264
+ this.listeners.clear();
265
+ this.eventClasses.clear();
266
+ }
267
+ /**
268
+ * `EventServiceProvider` installs `createQueueEventDispatcher()` at boot,
269
+ * before the app's queue driver necessarily exists. A dispatcher that finds
270
+ * no queue at emit time resolves false, and the listener runs inline rather
271
+ * than failing the emit.
272
+ */
273
+ setQueueDispatcher(dispatcher) {
274
+ this.queueDispatcher = dispatcher;
275
+ }
276
+ nameOf(event) {
277
+ return typeof event === "string" ? event : resolveEventName(event);
278
+ }
279
+ };
280
+ function createEventManager() {
281
+ return new EventManager();
282
+ }
283
+ //#endregion
284
+ //#region src/events/Listener.ts
285
+ /** Base class for reusable, class-based event listeners. */
286
+ var Listener = class {
287
+ /** Must be set by subclasses. */
288
+ static event;
289
+ /** @default false */
290
+ static shouldQueue = false;
291
+ /**
292
+ * Used when `shouldQueue`.
293
+ * @default 'default'
294
+ */
295
+ static queue = "default";
296
+ /**
297
+ * Higher runs first.
298
+ * @default 0
299
+ */
300
+ static priority = 0;
301
+ };
302
+ //#endregion
303
+ //#region src/events/queued.ts
304
+ /**
305
+ * Carries a queued emit to the worker, which runs the listener through the
306
+ * app's `events` binding. One message per queued listener, so a listener that
307
+ * throws is retried on its own rather than re-running the ones beside it.
308
+ */
309
+ var QueuedEventJob = class extends Job {
310
+ static jobName = "QueuedEventJob";
311
+ async handle(payload) {
312
+ await this.make("events").handleQueued(payload.queue, payload.eventName, payload.event, payload.listenerSeq);
313
+ }
314
+ async failed(payload, error) {
315
+ await this.make("events").failedQueued(payload.queue, payload.eventName, payload.event, payload.listenerSeq, error);
316
+ }
317
+ };
318
+ /**
319
+ * The dispatcher `EventServiceProvider` installs at boot. Registers the carrier
320
+ * job too, which is what lets a worker booting the same app resolve the message.
321
+ * Resolves false rather than letting `Job.dispatch()` throw: it is installed
322
+ * before the app's queue is bound, and an emit it cannot queue runs inline.
323
+ */
324
+ function createQueueEventDispatcher() {
325
+ registerJob(QueuedEventJob);
326
+ return async (queue, eventName, event, listenerSeq) => {
327
+ if (resolveQueueDriver() === null) return false;
328
+ await QueuedEventJob.dispatch({
329
+ queue,
330
+ eventName,
331
+ event: encodeEventData(event),
332
+ listenerSeq
333
+ }, { queue });
334
+ return true;
335
+ };
336
+ }
337
+ //#endregion
338
+ //#region src/events/builtin.ts
339
+ var RequestReceived = class extends Event {
340
+ method;
341
+ path;
342
+ requestId;
343
+ constructor(method, path, requestId) {
344
+ super();
345
+ this.method = method;
346
+ this.path = path;
347
+ this.requestId = requestId;
348
+ }
349
+ };
350
+ var RequestFinished = class extends Event {
351
+ method;
352
+ path;
353
+ status;
354
+ durationMs;
355
+ requestId;
356
+ constructor(method, path, status, durationMs, requestId) {
357
+ super();
358
+ this.method = method;
359
+ this.path = path;
360
+ this.status = status;
361
+ this.durationMs = durationMs;
362
+ this.requestId = requestId;
363
+ }
364
+ };
365
+ var UserAuthenticated = class extends Event {
366
+ userId;
367
+ guard;
368
+ constructor(userId, guard = "default") {
369
+ super();
370
+ this.userId = userId;
371
+ this.guard = guard;
372
+ }
373
+ };
374
+ var UserLoggedOut = class extends Event {
375
+ userId;
376
+ guard;
377
+ constructor(userId, guard = "default") {
378
+ super();
379
+ this.userId = userId;
380
+ this.guard = guard;
381
+ }
382
+ };
383
+ var JobProcessed = class extends Event {
384
+ jobId;
385
+ jobName;
386
+ queue;
387
+ durationMs;
388
+ constructor(jobId, jobName, queue, durationMs) {
389
+ super();
390
+ this.jobId = jobId;
391
+ this.jobName = jobName;
392
+ this.queue = queue;
393
+ this.durationMs = durationMs;
394
+ }
395
+ };
396
+ var JobFailed = class extends Event {
397
+ jobId;
398
+ jobName;
399
+ queue;
400
+ error;
401
+ attempts;
402
+ constructor(jobId, jobName, queue, error, attempts) {
403
+ super();
404
+ this.jobId = jobId;
405
+ this.jobName = jobName;
406
+ this.queue = queue;
407
+ this.error = error;
408
+ this.attempts = attempts;
409
+ }
410
+ };
411
+ var ApplicationStarted = class extends Event {
412
+ port;
413
+ host;
414
+ constructor(port, host) {
415
+ super();
416
+ this.port = port;
417
+ this.host = host;
418
+ }
419
+ };
420
+ var ApplicationShutdown = class extends Event {
421
+ reason;
422
+ constructor(reason) {
423
+ super();
424
+ this.reason = reason;
425
+ }
426
+ };
427
+ //#endregion
428
+ export { RequestFinished as a, UserLoggedOut as c, EventManager as d, createEventManager as f, JobProcessed as i, createQueueEventDispatcher as l, ApplicationStarted as n, RequestReceived as o, Event as p, JobFailed as r, UserAuthenticated as s, ApplicationShutdown as t, Listener as u };