@guren/server 2.9.0 → 2.10.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.
Files changed (92) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/discovery/AutoDiscovery.d.ts +8 -0
  21. package/dist/encryption/index.js +5 -96
  22. package/dist/encryption-fOWQaKqX.js +250 -0
  23. package/dist/endpoint-D-20PiHY.js +46 -0
  24. package/dist/endpoint-D6GIqOpe.js +31 -0
  25. package/dist/errors-quJOkkCn.js +81 -0
  26. package/dist/events/index.js +2 -28
  27. package/dist/events-aIH_bWRx.js +410 -0
  28. package/dist/health/index.js +2 -24
  29. package/dist/health-VWdWXRwh.js +345 -0
  30. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  31. package/dist/hot-reload/testing.d.ts +1 -1
  32. package/dist/http/Application.d.ts +0 -1
  33. package/dist/i18n/index.js +2 -30
  34. package/dist/i18n-mcWi7LCd.js +617 -0
  35. package/dist/index.js +7496 -7281
  36. package/dist/lambda/index.js +114 -71
  37. package/dist/logging/index.js +2 -24
  38. package/dist/logging-CPaRMuPP.js +518 -0
  39. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  40. package/dist/mail/index.js +2 -27
  41. package/dist/mail-DfEfSQEr.js +699 -0
  42. package/dist/mcp/index.js +2 -10
  43. package/dist/notifications/index.js +2 -33
  44. package/dist/notifications-BGqmUNZ8.js +759 -0
  45. package/dist/queue/index.js +3 -42
  46. package/dist/queue-CXrRK85G.js +948 -0
  47. package/dist/redis/index.js +672 -642
  48. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  49. package/dist/runtime/index.js +474 -604
  50. package/dist/scheduling/index.js +2 -29
  51. package/dist/scheduling-CPiEdtQd.js +839 -0
  52. package/dist/storage/index.js +2 -15
  53. package/dist/storage-tWHMv2H_.js +841 -0
  54. package/dist/support/expiry.js +69 -12
  55. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  56. package/dist/vite/index.js +118 -181
  57. package/dist/vite/plugin.d.ts +1 -1
  58. package/dist/vite-dev-server-CpCUqmiC.js +131 -0
  59. package/package.json +6 -5
  60. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  61. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  62. package/dist/chunk-2SC566CD.js +0 -376
  63. package/dist/chunk-2V3YID4H.js +0 -20
  64. package/dist/chunk-3KV5X2FL.js +0 -31
  65. package/dist/chunk-63SKW5PS.js +0 -457
  66. package/dist/chunk-6J6B5KOB.js +0 -425
  67. package/dist/chunk-A5JJ7XTH.js +0 -24
  68. package/dist/chunk-AZOYI43J.js +0 -18
  69. package/dist/chunk-B5E5VBDI.js +0 -115
  70. package/dist/chunk-DAQKYKLH.js +0 -182
  71. package/dist/chunk-DRNPVBAA.js +0 -1002
  72. package/dist/chunk-EI5GYMAT.js +0 -853
  73. package/dist/chunk-H3B23O6T.js +0 -271
  74. package/dist/chunk-HPET6XY5.js +0 -853
  75. package/dist/chunk-HR2KZ3WL.js +0 -616
  76. package/dist/chunk-IOTWFHZU.js +0 -558
  77. package/dist/chunk-K6CUBJX6.js +0 -642
  78. package/dist/chunk-KTNJG7R7.js +0 -911
  79. package/dist/chunk-LAJQCSSF.js +0 -355
  80. package/dist/chunk-LHR6OHI7.js +0 -189
  81. package/dist/chunk-N7PLD7MB.js +0 -729
  82. package/dist/chunk-O5XIXGYM.js +0 -274
  83. package/dist/chunk-Q2P6YLRR.js +0 -24
  84. package/dist/chunk-QQKTH5KX.js +0 -114
  85. package/dist/chunk-SFQP6O52.js +0 -126
  86. package/dist/chunk-SQR7277M.js +0 -911
  87. package/dist/chunk-T2FFUU6J.js +0 -484
  88. package/dist/chunk-TVV5YNEC.js +0 -1842
  89. package/dist/chunk-UY3AZSYL.js +0 -14
  90. package/dist/chunk-V4DNC2ER.js +0 -114
  91. package/dist/chunk-YSOJKAAU.js +0 -427
  92. package/dist/errors-PUNHAFL2.js +0 -34
@@ -1,1002 +0,0 @@
1
- import {
2
- claimHotDisposable,
3
- isHotReloadRuntime
4
- } from "./chunk-B5E5VBDI.js";
5
- import {
6
- randomHex
7
- } from "./chunk-V4DNC2ER.js";
8
-
9
- // src/broadcasting/channels/Channel.ts
10
- var Channel = class {
11
- constructor(name, driver) {
12
- this.name = name;
13
- this.driver = driver;
14
- }
15
- name;
16
- driver;
17
- /**
18
- * Broadcast an event to this channel.
19
- */
20
- async broadcast(event, data) {
21
- await this.driver.publish(this.name, event, data);
22
- }
23
- /**
24
- * Subscribe to events on this channel.
25
- * Returns an unsubscribe function.
26
- */
27
- subscribe(callback) {
28
- return this.driver.subscribe(this.name, (e) => {
29
- callback(e.event, e.data);
30
- });
31
- }
32
- /**
33
- * Get the full channel name for broadcasting.
34
- */
35
- getChannelName() {
36
- return this.name;
37
- }
38
- };
39
-
40
- // src/broadcasting/channels/PrivateChannel.ts
41
- var PrivateChannel = class _PrivateChannel extends Channel {
42
- /**
43
- * Channel name prefix.
44
- */
45
- static PREFIX = "private-";
46
- constructor(name, driver) {
47
- const channelName = name.startsWith(_PrivateChannel.PREFIX) ? name : `${_PrivateChannel.PREFIX}${name}`;
48
- super(channelName, driver);
49
- }
50
- /**
51
- * Get the channel name without the private prefix.
52
- */
53
- getBaseName() {
54
- return this.name.startsWith(_PrivateChannel.PREFIX) ? this.name.slice(_PrivateChannel.PREFIX.length) : this.name;
55
- }
56
- /**
57
- * Check if a channel name is a private channel.
58
- */
59
- static isPrivateChannel(name) {
60
- return name.startsWith(_PrivateChannel.PREFIX);
61
- }
62
- /**
63
- * Normalize a channel name to include the private prefix.
64
- */
65
- static normalize(name) {
66
- return name.startsWith(_PrivateChannel.PREFIX) ? name : `${_PrivateChannel.PREFIX}${name}`;
67
- }
68
- };
69
-
70
- // src/broadcasting/channels/PresenceChannel.ts
71
- var PresenceChannel = class _PresenceChannel extends Channel {
72
- /**
73
- * Channel name prefix.
74
- */
75
- static PREFIX = "presence-";
76
- presenceDriver;
77
- constructor(name, driver) {
78
- const channelName = name.startsWith(_PresenceChannel.PREFIX) ? name : `${_PresenceChannel.PREFIX}${name}`;
79
- super(channelName, driver);
80
- if (this.isPresenceDriver(driver)) {
81
- this.presenceDriver = driver;
82
- } else {
83
- throw new Error(
84
- `Driver does not support presence channels. Ensure the driver implements PresenceBroadcastDriver interface.`
85
- );
86
- }
87
- }
88
- /**
89
- * Check if a driver supports presence.
90
- */
91
- isPresenceDriver(driver) {
92
- return "getMembers" in driver && "addMember" in driver && "removeMember" in driver;
93
- }
94
- /**
95
- * Get members in this channel.
96
- */
97
- members() {
98
- return this.presenceDriver.getMembers(this.name);
99
- }
100
- /**
101
- * Join the channel.
102
- */
103
- async join(member) {
104
- this.presenceDriver.addMember(this.name, member);
105
- await this.broadcast("presence:joining", {
106
- member
107
- });
108
- }
109
- /**
110
- * Leave the channel.
111
- */
112
- async leave(memberId) {
113
- const members = this.members();
114
- const member = members.find((m) => m.id === memberId);
115
- this.presenceDriver.removeMember(this.name, memberId);
116
- if (member) {
117
- await this.broadcast("presence:leaving", {
118
- member
119
- });
120
- }
121
- }
122
- /**
123
- * Check if a member is in the channel.
124
- */
125
- hasMember(memberId) {
126
- return this.members().some((m) => m.id === memberId);
127
- }
128
- /**
129
- * Get member by ID.
130
- */
131
- getMember(memberId) {
132
- return this.members().find((m) => m.id === memberId);
133
- }
134
- /**
135
- * Get member count.
136
- */
137
- count() {
138
- return this.members().length;
139
- }
140
- /**
141
- * Get the channel name without the presence prefix.
142
- */
143
- getBaseName() {
144
- return this.name.startsWith(_PresenceChannel.PREFIX) ? this.name.slice(_PresenceChannel.PREFIX.length) : this.name;
145
- }
146
- /**
147
- * Check if a channel name is a presence channel.
148
- */
149
- static isPresenceChannel(name) {
150
- return name.startsWith(_PresenceChannel.PREFIX);
151
- }
152
- /**
153
- * Normalize a channel name to include the presence prefix.
154
- */
155
- static normalize(name) {
156
- return name.startsWith(_PresenceChannel.PREFIX) ? name : `${_PresenceChannel.PREFIX}${name}`;
157
- }
158
- };
159
-
160
- // src/broadcasting/drivers/MemoryDriver.ts
161
- var MemoryDriver = class {
162
- /**
163
- * Channel subscribers.
164
- */
165
- subscribers = /* @__PURE__ */ new Map();
166
- /**
167
- * Presence channel members.
168
- */
169
- presenceMembers = /* @__PURE__ */ new Map();
170
- /**
171
- * Published events (for testing).
172
- */
173
- publishedEvents = [];
174
- /**
175
- * Publish an event to a channel.
176
- */
177
- async publish(channel, event, data) {
178
- const broadcastEvent = {
179
- channel,
180
- event,
181
- data,
182
- timestamp: /* @__PURE__ */ new Date()
183
- };
184
- this.publishedEvents.push(broadcastEvent);
185
- const callbacks = this.subscribers.get(channel);
186
- if (callbacks) {
187
- for (const callback of callbacks) {
188
- try {
189
- callback(broadcastEvent);
190
- } catch (error) {
191
- console.error(`Error in broadcast subscriber:`, error);
192
- }
193
- }
194
- }
195
- }
196
- /**
197
- * Subscribe to a channel.
198
- */
199
- subscribe(channel, callback) {
200
- let callbacks = this.subscribers.get(channel);
201
- if (!callbacks) {
202
- callbacks = /* @__PURE__ */ new Set();
203
- this.subscribers.set(channel, callbacks);
204
- }
205
- callbacks.add(callback);
206
- return () => {
207
- this.unsubscribe(channel, callback);
208
- };
209
- }
210
- /**
211
- * Unsubscribe from a channel.
212
- */
213
- unsubscribe(channel, callback) {
214
- const callbacks = this.subscribers.get(channel);
215
- if (callbacks) {
216
- callbacks.delete(callback);
217
- if (callbacks.size === 0) {
218
- this.subscribers.delete(channel);
219
- }
220
- }
221
- }
222
- /**
223
- * Get members of a presence channel.
224
- */
225
- getMembers(channel) {
226
- const members = this.presenceMembers.get(channel);
227
- return members ? Array.from(members.values()) : [];
228
- }
229
- /**
230
- * Add a member to a presence channel.
231
- */
232
- addMember(channel, member) {
233
- let members = this.presenceMembers.get(channel);
234
- if (!members) {
235
- members = /* @__PURE__ */ new Map();
236
- this.presenceMembers.set(channel, members);
237
- }
238
- members.set(member.id, member);
239
- }
240
- /**
241
- * Remove a member from a presence channel.
242
- */
243
- removeMember(channel, memberId) {
244
- const members = this.presenceMembers.get(channel);
245
- if (members) {
246
- members.delete(memberId);
247
- if (members.size === 0) {
248
- this.presenceMembers.delete(channel);
249
- }
250
- }
251
- }
252
- /**
253
- * Check if a channel has subscribers.
254
- */
255
- hasSubscribers(channel) {
256
- const callbacks = this.subscribers.get(channel);
257
- return callbacks !== void 0 && callbacks.size > 0;
258
- }
259
- /**
260
- * Get subscriber count for a channel.
261
- */
262
- getSubscriberCount(channel) {
263
- const callbacks = this.subscribers.get(channel);
264
- return callbacks ? callbacks.size : 0;
265
- }
266
- /**
267
- * Get all channels with subscribers.
268
- */
269
- getChannels() {
270
- return Array.from(this.subscribers.keys());
271
- }
272
- /**
273
- * Get all presence channels.
274
- */
275
- getPresenceChannels() {
276
- return Array.from(this.presenceMembers.keys());
277
- }
278
- /**
279
- * Get all published events (for testing).
280
- */
281
- getPublishedEvents() {
282
- return [...this.publishedEvents];
283
- }
284
- /**
285
- * Get published events for a specific channel.
286
- */
287
- getPublishedEventsFor(channel) {
288
- return this.publishedEvents.filter((e) => e.channel === channel);
289
- }
290
- /**
291
- * Clear all data (for testing).
292
- */
293
- clear() {
294
- this.subscribers.clear();
295
- this.presenceMembers.clear();
296
- this.publishedEvents = [];
297
- }
298
- /**
299
- * Clear published events only.
300
- */
301
- clearPublishedEvents() {
302
- this.publishedEvents = [];
303
- }
304
- };
305
-
306
- // src/broadcasting/drivers/RedisDriver.ts
307
- var RedisDriver = class {
308
- /**
309
- * Publisher Redis client.
310
- */
311
- publisher;
312
- /**
313
- * Subscriber Redis client.
314
- */
315
- subscriber;
316
- /**
317
- * Local subscribers.
318
- */
319
- subscribers = /* @__PURE__ */ new Map();
320
- /**
321
- * Local presence members cache.
322
- */
323
- localPresence = /* @__PURE__ */ new Map();
324
- /**
325
- * Presence key prefix.
326
- */
327
- presencePrefix = "broadcasting:presence:";
328
- /**
329
- * Whether the driver is initialized.
330
- */
331
- initialized = false;
332
- constructor(redis, options = {}) {
333
- this.publisher = redis;
334
- this.subscriber = redis.duplicate();
335
- if (options.presencePrefix) {
336
- this.presencePrefix = options.presencePrefix;
337
- }
338
- this.setupSubscriber();
339
- }
340
- /**
341
- * Setup the subscriber client.
342
- */
343
- setupSubscriber() {
344
- this.subscriber.on("message", (channel, message) => {
345
- try {
346
- const event = JSON.parse(message);
347
- event.timestamp = new Date(event.timestamp);
348
- const callbacks = this.subscribers.get(channel);
349
- if (callbacks) {
350
- for (const callback of callbacks) {
351
- try {
352
- callback(event);
353
- } catch (error) {
354
- console.error(`Error in broadcast subscriber:`, error);
355
- }
356
- }
357
- }
358
- } catch (error) {
359
- console.error(`Error parsing broadcast message:`, error);
360
- }
361
- });
362
- this.initialized = true;
363
- }
364
- /**
365
- * Publish an event to a channel.
366
- */
367
- async publish(channel, event, data) {
368
- const broadcastEvent = {
369
- channel,
370
- event,
371
- data,
372
- timestamp: /* @__PURE__ */ new Date()
373
- };
374
- await this.publisher.publish(channel, JSON.stringify(broadcastEvent));
375
- }
376
- /**
377
- * Subscribe to a channel.
378
- */
379
- subscribe(channel, callback) {
380
- let callbacks = this.subscribers.get(channel);
381
- const isNew = !callbacks;
382
- if (!callbacks) {
383
- callbacks = /* @__PURE__ */ new Set();
384
- this.subscribers.set(channel, callbacks);
385
- }
386
- callbacks.add(callback);
387
- if (isNew) {
388
- this.subscriber.subscribe(channel).catch((error) => {
389
- console.error(`Error subscribing to Redis channel:`, error);
390
- });
391
- }
392
- return () => {
393
- this.unsubscribe(channel, callback);
394
- };
395
- }
396
- /**
397
- * Unsubscribe from a channel.
398
- */
399
- unsubscribe(channel, callback) {
400
- const callbacks = this.subscribers.get(channel);
401
- if (callbacks) {
402
- callbacks.delete(callback);
403
- if (callbacks.size === 0) {
404
- this.subscribers.delete(channel);
405
- this.subscriber.unsubscribe(channel).catch((error) => {
406
- console.error(`Error unsubscribing from Redis channel:`, error);
407
- });
408
- }
409
- }
410
- }
411
- /**
412
- * Get members of a presence channel.
413
- */
414
- getMembers(channel) {
415
- const members = this.localPresence.get(channel);
416
- return members ? Array.from(members.values()) : [];
417
- }
418
- /**
419
- * Get members asynchronously from Redis.
420
- */
421
- async getMembersAsync(channel) {
422
- const key = `${this.presencePrefix}${channel}`;
423
- const data = await this.publisher.hgetall(key);
424
- const members = [];
425
- for (const [_, value] of Object.entries(data)) {
426
- try {
427
- members.push(JSON.parse(value));
428
- } catch {
429
- }
430
- }
431
- const localMembers = /* @__PURE__ */ new Map();
432
- for (const member of members) {
433
- localMembers.set(member.id, member);
434
- }
435
- this.localPresence.set(channel, localMembers);
436
- return members;
437
- }
438
- /**
439
- * Add a member to a presence channel.
440
- */
441
- addMember(channel, member) {
442
- let members = this.localPresence.get(channel);
443
- if (!members) {
444
- members = /* @__PURE__ */ new Map();
445
- this.localPresence.set(channel, members);
446
- }
447
- members.set(member.id, member);
448
- const key = `${this.presencePrefix}${channel}`;
449
- this.publisher.hset(key, String(member.id), JSON.stringify(member)).catch((error) => {
450
- console.error(`Error adding presence member to Redis:`, error);
451
- });
452
- }
453
- /**
454
- * Remove a member from a presence channel.
455
- */
456
- removeMember(channel, memberId) {
457
- const members = this.localPresence.get(channel);
458
- if (members) {
459
- members.delete(memberId);
460
- if (members.size === 0) {
461
- this.localPresence.delete(channel);
462
- }
463
- }
464
- const key = `${this.presencePrefix}${channel}`;
465
- this.publisher.hdel(key, String(memberId)).catch((error) => {
466
- console.error(`Error removing presence member from Redis:`, error);
467
- });
468
- }
469
- /**
470
- * Check if a channel has subscribers.
471
- */
472
- hasSubscribers(channel) {
473
- const callbacks = this.subscribers.get(channel);
474
- return callbacks !== void 0 && callbacks.size > 0;
475
- }
476
- /**
477
- * Get subscriber count for a channel.
478
- */
479
- getSubscriberCount(channel) {
480
- const callbacks = this.subscribers.get(channel);
481
- return callbacks ? callbacks.size : 0;
482
- }
483
- };
484
-
485
- // src/http/request.ts
486
- function isPlainObject(value) {
487
- return typeof value === "object" && value !== null && !Array.isArray(value);
488
- }
489
- async function parseRequestPayload(ctx) {
490
- const contentType = ctx.req.header("content-type") ?? "";
491
- if (contentType.includes("application/json")) {
492
- const body = await ctx.req.json().catch(() => ({}));
493
- return isPlainObject(body) ? body : {};
494
- }
495
- if (typeof ctx.req.parseBody === "function") {
496
- const form = await ctx.req.parseBody();
497
- return Object.fromEntries(
498
- Object.entries(form).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value])
499
- );
500
- }
501
- return {};
502
- }
503
- function flattenRequestQueries(ctx) {
504
- const queries = ctx.req.queries();
505
- const flat = {};
506
- for (const [key, values] of Object.entries(queries)) {
507
- flat[key] = values.length === 1 ? values[0] : values;
508
- }
509
- return flat;
510
- }
511
- function formatValidationErrors(error, fallbackMessage = "The provided data is invalid.") {
512
- const errors = {};
513
- for (const issue of error.issues ?? []) {
514
- const field = issue.path?.[0];
515
- if (typeof field === "string" && !errors[field]) {
516
- errors[field] = issue.message;
517
- }
518
- }
519
- if (Object.keys(errors).length === 0) {
520
- errors.message = fallbackMessage;
521
- }
522
- return errors;
523
- }
524
-
525
- // src/broadcasting/BroadcastManager.ts
526
- function resolveClientUserId(user) {
527
- if (typeof user !== "object" || user === null) return void 0;
528
- const candidate = user;
529
- for (const value of [candidate.id, candidate.sub, candidate.userId]) {
530
- if (typeof value === "string" || typeof value === "number") return value;
531
- }
532
- return void 0;
533
- }
534
- var BroadcastManager = class {
535
- /**
536
- * Default driver name.
537
- */
538
- defaultDriver = "memory";
539
- /**
540
- * Driver factories.
541
- */
542
- driverFactories = /* @__PURE__ */ new Map();
543
- /**
544
- * Resolved drivers.
545
- */
546
- resolvedDrivers = /* @__PURE__ */ new Map();
547
- /**
548
- * Channel registrations.
549
- */
550
- channelRegistrations = [];
551
- /**
552
- * SSE clients.
553
- */
554
- sseClients = /* @__PURE__ */ new Map();
555
- /**
556
- * WebSocket clients.
557
- */
558
- wsClients = /* @__PURE__ */ new Map();
559
- constructor(options = {}) {
560
- if (options.default) {
561
- this.defaultDriver = options.default;
562
- }
563
- if (options.drivers) {
564
- for (const [name, factory] of Object.entries(options.drivers)) {
565
- this.registerDriver(name, factory);
566
- }
567
- }
568
- if (!this.driverFactories.has("memory")) {
569
- this.registerDriver("memory", () => new MemoryDriver());
570
- }
571
- }
572
- /**
573
- * Register a driver factory.
574
- */
575
- registerDriver(name, factory) {
576
- this.driverFactories.set(name, factory);
577
- return this;
578
- }
579
- /**
580
- * Get a driver by name.
581
- */
582
- driver(name) {
583
- const driverName = name ?? this.defaultDriver;
584
- const resolved = this.resolvedDrivers.get(driverName);
585
- if (resolved) {
586
- return resolved;
587
- }
588
- const factory = this.driverFactories.get(driverName);
589
- if (!factory) {
590
- throw new Error(`Broadcast driver "${driverName}" not found`);
591
- }
592
- const driver = factory();
593
- this.resolvedDrivers.set(driverName, driver);
594
- return driver;
595
- }
596
- /**
597
- * Register a public channel authorizer.
598
- */
599
- channel(pattern, authorizer) {
600
- this.channelRegistrations.push({
601
- pattern,
602
- type: "public",
603
- authorizer
604
- });
605
- return this;
606
- }
607
- /**
608
- * Register a private channel authorizer.
609
- */
610
- privateChannel(pattern, authorizer) {
611
- this.channelRegistrations.push({
612
- pattern: PrivateChannel.normalize(pattern),
613
- type: "private",
614
- authorizer
615
- });
616
- return this;
617
- }
618
- /**
619
- * Register a presence channel authorizer.
620
- */
621
- presenceChannel(pattern, authorizer) {
622
- this.channelRegistrations.push({
623
- pattern: PresenceChannel.normalize(pattern),
624
- type: "presence",
625
- authorizer
626
- });
627
- return this;
628
- }
629
- /**
630
- * Broadcast an event to a channel.
631
- */
632
- async broadcast(channelName, event, data) {
633
- await this.driver().publish(channelName, event, data);
634
- }
635
- /**
636
- * Get a public channel.
637
- */
638
- toChannel(name) {
639
- return new Channel(name, this.driver());
640
- }
641
- /**
642
- * Get a private channel.
643
- */
644
- toPrivate(name) {
645
- return new PrivateChannel(name, this.driver());
646
- }
647
- /**
648
- * Get a presence channel.
649
- */
650
- toPresence(name) {
651
- return new PresenceChannel(name, this.driver());
652
- }
653
- /**
654
- * Authorize a channel for a user.
655
- */
656
- async authorize(channelName, user) {
657
- const registration = this.findChannelRegistration(channelName);
658
- if (!registration) {
659
- return !(channelName.startsWith("private-") || channelName.startsWith("presence-"));
660
- }
661
- if (registration.type === "presence") {
662
- const presenceAuth = registration.authorizer;
663
- const member = await presenceAuth(channelName, user);
664
- return typeof member === "object" && member !== null ? member : false;
665
- }
666
- return await registration.authorizer(channelName, user) === true;
667
- }
668
- /**
669
- * Find channel registration for a channel name.
670
- */
671
- findChannelRegistration(channelName) {
672
- return this.channelRegistrations.find(
673
- (reg) => this.matchPattern(reg.pattern, channelName)
674
- );
675
- }
676
- /**
677
- * Match a channel name against a pattern.
678
- */
679
- matchPattern(pattern, channelName) {
680
- const regexPattern = pattern.replace(/\{[^}]+\}/g, "[^.]+").replace(/\*\*/g, ".+").replace(/\*/g, "[^.]+");
681
- const regex = new RegExp(`^${regexPattern}$`);
682
- return regex.test(channelName);
683
- }
684
- /**
685
- * Create SSE middleware.
686
- */
687
- sseMiddleware(options = {}) {
688
- const pingInterval = options.pingInterval ?? 3e4;
689
- const retry = options.retry ?? 3e3;
690
- return async (ctx) => {
691
- const clientId = this.generateClientId();
692
- const encoder = new TextEncoder();
693
- const manager = this;
694
- const requestedChannels = (ctx.req.query("channels") ?? "").split(",").map((value) => value.trim()).filter(Boolean);
695
- const user = options.getUser ? await options.getUser(ctx) : void 0;
696
- const authorizedChannels = [];
697
- for (const channelName of requestedChannels) {
698
- const authResult = await this.authorize(channelName, user);
699
- if (authResult !== false && authResult !== null) {
700
- authorizedChannels.push(channelName);
701
- }
702
- }
703
- const clientUserId = resolveClientUserId(user);
704
- let controller = null;
705
- let client = null;
706
- let pingTimer = null;
707
- const sendRaw = (message) => {
708
- if (!controller) return;
709
- controller.enqueue(encoder.encode(message));
710
- };
711
- const cleanup = () => {
712
- if (pingTimer) {
713
- clearInterval(pingTimer);
714
- pingTimer = null;
715
- }
716
- if (client) {
717
- manager.sseClients.delete(client.id);
718
- client = null;
719
- }
720
- if (controller) {
721
- try {
722
- controller.close();
723
- } catch {
724
- }
725
- controller = null;
726
- }
727
- };
728
- const stream = new ReadableStream({
729
- start(streamController) {
730
- controller = streamController;
731
- client = {
732
- id: clientId,
733
- // Recorded so `POST /broadcasting/auth` can refuse to attach
734
- // channels to a stream belonging to someone else.
735
- userId: clientUserId,
736
- channels: /* @__PURE__ */ new Set(),
737
- send: (event, data) => {
738
- const message = `event: ${event}
739
- data: ${JSON.stringify(data)}
740
-
741
- `;
742
- sendRaw(message);
743
- },
744
- close: cleanup
745
- };
746
- manager.sseClients.set(clientId, client);
747
- sendRaw(`retry: ${retry}
748
-
749
- `);
750
- client.send("connected", { clientId, channels: authorizedChannels });
751
- for (const channelName of authorizedChannels) {
752
- manager.subscribeClient(clientId, channelName);
753
- }
754
- pingTimer = setInterval(() => {
755
- try {
756
- client?.send("ping", { time: Date.now() });
757
- } catch {
758
- cleanup();
759
- }
760
- }, pingInterval);
761
- },
762
- cancel() {
763
- cleanup();
764
- }
765
- });
766
- ctx.req.raw.signal.addEventListener("abort", cleanup, { once: true });
767
- return new Response(stream, {
768
- headers: {
769
- "Content-Type": "text/event-stream",
770
- "Cache-Control": "no-cache",
771
- Connection: "keep-alive"
772
- }
773
- });
774
- };
775
- }
776
- /**
777
- * Create auth middleware for channel authorization.
778
- */
779
- authMiddleware(options = {}) {
780
- return async (ctx) => {
781
- const getUser = options.getUser ?? ((c) => c.auth?.user);
782
- const user = await getUser(ctx);
783
- const payload = await parseRequestPayload(ctx);
784
- const channel = typeof payload.channel === "string" ? payload.channel : void 0;
785
- const channels = Array.isArray(payload.channels) ? payload.channels.filter((value) => typeof value === "string") : typeof payload.channels === "string" ? [payload.channels] : channel ? [channel] : [];
786
- if (channels.length === 0) {
787
- return ctx.json({ error: "No channel specified" }, 400);
788
- }
789
- const clientId = typeof payload.clientId === "string" ? payload.clientId : void 0;
790
- const results = {};
791
- const requesterId = resolveClientUserId(user);
792
- const target = clientId ? this.sseClients.get(clientId) : void 0;
793
- const attachTo = target && (target.userId === void 0 || target.userId === requesterId) ? target : void 0;
794
- for (const ch of channels) {
795
- const authResult = await this.authorize(ch, user);
796
- if (authResult === false || authResult === null) {
797
- results[ch] = { authorized: false };
798
- continue;
799
- }
800
- const subscribed = attachTo ? this.subscribeClient(attachTo.id, ch) : false;
801
- if (authResult === true) {
802
- results[ch] = { authorized: true, subscribed };
803
- } else {
804
- results[ch] = {
805
- authorized: true,
806
- subscribed,
807
- member: authResult
808
- };
809
- }
810
- }
811
- return ctx.json(results);
812
- };
813
- }
814
- /**
815
- * Subscribe a client to a channel.
816
- */
817
- subscribeClient(clientId, channel) {
818
- const client = this.sseClients.get(clientId);
819
- if (!client) return false;
820
- client.channels.add(channel);
821
- this.driver().subscribe(channel, (event) => {
822
- if (client.channels.has(channel)) {
823
- client.send(event.event, event.data);
824
- }
825
- });
826
- return true;
827
- }
828
- /**
829
- * Register a WebSocket client and return its generated client ID.
830
- */
831
- registerWebSocketClient(client) {
832
- const clientId = this.generateClientId("ws");
833
- this.wsClients.set(clientId, {
834
- ...client,
835
- id: clientId,
836
- channels: /* @__PURE__ */ new Set()
837
- });
838
- return clientId;
839
- }
840
- /**
841
- * Remove a WebSocket client and close the underlying connection.
842
- */
843
- removeWebSocketClient(clientId) {
844
- const client = this.wsClients.get(clientId);
845
- if (!client) return false;
846
- this.wsClients.delete(clientId);
847
- client.close();
848
- return true;
849
- }
850
- /**
851
- * Subscribe a WebSocket client to a channel.
852
- */
853
- subscribeWebSocketClient(clientId, channel) {
854
- const client = this.wsClients.get(clientId);
855
- if (!client) return false;
856
- client.channels.add(channel);
857
- this.driver().subscribe(channel, async (event) => {
858
- if (client.channels.has(channel)) {
859
- await client.send(event.event, event.data);
860
- }
861
- });
862
- return true;
863
- }
864
- /**
865
- * Unsubscribe a WebSocket client from a channel.
866
- */
867
- unsubscribeWebSocketClient(clientId, channel) {
868
- const client = this.wsClients.get(clientId);
869
- if (!client) return false;
870
- client.channels.delete(channel);
871
- return true;
872
- }
873
- /**
874
- * Get a WebSocket client by ID.
875
- */
876
- getWebSocketClient(clientId) {
877
- return this.wsClients.get(clientId);
878
- }
879
- /**
880
- * Get all WebSocket clients.
881
- */
882
- getWebSocketClients() {
883
- return Array.from(this.wsClients.values());
884
- }
885
- /**
886
- * Unsubscribe a client from a channel.
887
- */
888
- unsubscribeClient(clientId, channel) {
889
- const client = this.sseClients.get(clientId);
890
- if (!client) return false;
891
- client.channels.delete(channel);
892
- return true;
893
- }
894
- /**
895
- * Get SSE client by ID.
896
- */
897
- getClient(clientId) {
898
- return this.sseClients.get(clientId);
899
- }
900
- /**
901
- * Get all SSE clients.
902
- */
903
- getClients() {
904
- return Array.from(this.sseClients.values());
905
- }
906
- /**
907
- * Get clients subscribed to a channel.
908
- */
909
- getChannelClients(channel) {
910
- return this.getClients().filter((client) => client.channels.has(channel));
911
- }
912
- /**
913
- * Close every SSE connection this manager is holding.
914
- *
915
- * Each connection owns a ping timer that is only cleared when the stream is
916
- * cancelled or the request aborts. `Bun.serve().stop()` without forcing waits
917
- * for in-flight requests instead of cutting them, and an SSE response never
918
- * finishes — so on a hot reload those connections outlive the manager, and
919
- * their timers go on pinging a stream nobody reads.
920
- *
921
- * `getClients()` returns a snapshot. A `Map` iterator does tolerate an entry
922
- * deleting itself, which is all `cleanup()` does today — but not a `close()`
923
- * that reaches another client, which would drop that one from the iteration
924
- * unvisited and leave its timer running.
925
- */
926
- disconnectAll() {
927
- for (const client of this.getClients()) {
928
- try {
929
- client.close();
930
- } catch {
931
- }
932
- }
933
- }
934
- /**
935
- * Generate a unique client ID.
936
- */
937
- generateClientId(prefix = "sse") {
938
- return `${prefix}_${randomHex(16)}`;
939
- }
940
- };
941
- var globalBroadcastManager = null;
942
- function setBroadcastManager(manager) {
943
- globalBroadcastManager = manager;
944
- }
945
- function getBroadcastManager() {
946
- if (!globalBroadcastManager) {
947
- throw new Error("BroadcastManager not initialized. Call setBroadcastManager() first.");
948
- }
949
- return globalBroadcastManager;
950
- }
951
- function createBroadcastManager(options) {
952
- const manager = new BroadcastManager(options);
953
- claimHotDisposable(
954
- "broadcast-manager",
955
- isHotReloadRuntime() ? new Error().stack : void 0,
956
- options?.default ?? "memory",
957
- () => manager.disconnectAll()
958
- );
959
- return manager;
960
- }
961
-
962
- // src/broadcasting/typed.ts
963
- function createTypedBroadcaster(manager) {
964
- return {
965
- broadcast(channel, event, payload) {
966
- return manager.broadcast(channel, event, payload);
967
- },
968
- toChannel(channel) {
969
- return wrapChannel(channel, manager.toChannel(channel));
970
- },
971
- toPrivate(channel) {
972
- return wrapChannel(channel, manager.toPrivate(channel));
973
- },
974
- toPresence(channel) {
975
- return wrapChannel(channel, manager.toPresence(channel));
976
- }
977
- };
978
- }
979
- function wrapChannel(name, channel) {
980
- return {
981
- name,
982
- broadcast(event, payload) {
983
- return channel.broadcast(event, payload);
984
- }
985
- };
986
- }
987
-
988
- export {
989
- parseRequestPayload,
990
- flattenRequestQueries,
991
- formatValidationErrors,
992
- Channel,
993
- PrivateChannel,
994
- PresenceChannel,
995
- MemoryDriver,
996
- RedisDriver,
997
- BroadcastManager,
998
- setBroadcastManager,
999
- getBroadcastManager,
1000
- createBroadcastManager,
1001
- createTypedBroadcaster
1002
- };