@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,911 +0,0 @@
1
- import {
2
- getJob,
3
- setQueueDriver
4
- } from "./chunk-6J6B5KOB.js";
5
-
6
- // src/queue/drivers/MemoryDriver.ts
7
- var MemoryDriver = class {
8
- jobs = /* @__PURE__ */ new Map();
9
- failedJobs = /* @__PURE__ */ new Map();
10
- /**
11
- * Push a job onto the queue.
12
- */
13
- async push(job) {
14
- this.jobs.set(job.id, { ...job });
15
- }
16
- /**
17
- * Pop the next available job from the queue.
18
- */
19
- async pop(queue) {
20
- const now = /* @__PURE__ */ new Date();
21
- for (const [id, job] of this.jobs) {
22
- if (job.queue === queue && job.availableAt <= now && job.reservedAt === null) {
23
- job.reservedAt = now;
24
- return { ...job };
25
- }
26
- }
27
- return null;
28
- }
29
- /**
30
- * Release a job back onto the queue.
31
- */
32
- async release(job, delayMs = 0) {
33
- const existing = this.jobs.get(job.id);
34
- if (existing) {
35
- existing.reservedAt = null;
36
- existing.availableAt = new Date(Date.now() + delayMs);
37
- existing.attempts = job.attempts;
38
- if (job.lastError) {
39
- existing.lastError = job.lastError;
40
- }
41
- }
42
- }
43
- /**
44
- * Delete a job from the queue.
45
- */
46
- async delete(jobId) {
47
- this.jobs.delete(jobId);
48
- }
49
- /**
50
- * Mark a job as failed.
51
- */
52
- async fail(job, error) {
53
- const failedJob = {
54
- ...job,
55
- failedAt: /* @__PURE__ */ new Date(),
56
- error: error.message,
57
- stack: error.stack
58
- };
59
- this.failedJobs.set(job.id, failedJob);
60
- this.jobs.delete(job.id);
61
- }
62
- /**
63
- * Get the number of jobs in a queue.
64
- */
65
- async size(queue) {
66
- let count = 0;
67
- for (const job of this.jobs.values()) {
68
- if (job.queue === queue && job.reservedAt === null) {
69
- count++;
70
- }
71
- }
72
- return count;
73
- }
74
- /**
75
- * Get failed jobs.
76
- */
77
- async getFailedJobs(queue) {
78
- const jobs = [];
79
- for (const job of this.failedJobs.values()) {
80
- if (!queue || job.queue === queue) {
81
- jobs.push({ ...job });
82
- }
83
- }
84
- return jobs.sort((a, b) => b.failedAt.getTime() - a.failedAt.getTime());
85
- }
86
- /**
87
- * Retry a failed job.
88
- */
89
- async retryFailedJob(jobId) {
90
- const failedJob = this.failedJobs.get(jobId);
91
- if (!failedJob) {
92
- throw new Error(`Failed job not found: ${jobId}`);
93
- }
94
- const job = {
95
- id: failedJob.id,
96
- name: failedJob.name,
97
- payload: failedJob.payload,
98
- queue: failedJob.queue,
99
- attempts: 0,
100
- maxAttempts: failedJob.maxAttempts,
101
- availableAt: /* @__PURE__ */ new Date(),
102
- createdAt: /* @__PURE__ */ new Date(),
103
- reservedAt: null
104
- };
105
- this.jobs.set(job.id, job);
106
- this.failedJobs.delete(jobId);
107
- }
108
- /**
109
- * Delete a failed job.
110
- */
111
- async deleteFailedJob(jobId) {
112
- this.failedJobs.delete(jobId);
113
- }
114
- /**
115
- * Clear all jobs (for testing).
116
- */
117
- async clear() {
118
- this.jobs.clear();
119
- this.failedJobs.clear();
120
- }
121
- /**
122
- * Get all pending jobs (for testing/debugging).
123
- */
124
- getPendingJobs(queue) {
125
- const jobs = [];
126
- for (const job of this.jobs.values()) {
127
- if (!queue || job.queue === queue) {
128
- jobs.push({ ...job });
129
- }
130
- }
131
- return jobs;
132
- }
133
- };
134
-
135
- // src/queue/drivers/SyncDriver.ts
136
- var SyncDriver = class {
137
- failedJobs = /* @__PURE__ */ new Map();
138
- async push(job) {
139
- const JobClass = getJob(job.name);
140
- if (!JobClass) {
141
- throw new Error(
142
- `SyncDriver: job class "${job.name}" is not registered. Call registerJob() with the class whose jobName (or class name) is "${job.name}".`
143
- );
144
- }
145
- job.attempts += 1;
146
- try {
147
- const instance = new JobClass();
148
- await instance.handle(job.payload);
149
- } catch (error) {
150
- await this.fail(job, error instanceof Error ? error : new Error(String(error)));
151
- throw error;
152
- }
153
- }
154
- async pop() {
155
- return null;
156
- }
157
- async release(job) {
158
- await this.push(job);
159
- }
160
- async delete() {
161
- }
162
- async fail(job, error) {
163
- this.failedJobs.set(job.id, {
164
- ...job,
165
- failedAt: /* @__PURE__ */ new Date(),
166
- error: error.message,
167
- stack: error.stack
168
- });
169
- }
170
- async size() {
171
- return 0;
172
- }
173
- async getFailedJobs(queue) {
174
- const failed = [...this.failedJobs.values()];
175
- return queue ? failed.filter((job) => job.queue === queue) : failed;
176
- }
177
- async retryFailedJob(jobId) {
178
- const failed = this.failedJobs.get(jobId);
179
- if (!failed) {
180
- throw new Error(`SyncDriver: failed job "${jobId}" not found.`);
181
- }
182
- this.failedJobs.delete(jobId);
183
- const { failedAt: _failedAt, error: _error, stack: _stack, ...job } = failed;
184
- await this.push({ ...job, reservedAt: null });
185
- }
186
- async deleteFailedJob(jobId) {
187
- this.failedJobs.delete(jobId);
188
- }
189
- async clear() {
190
- this.failedJobs.clear();
191
- }
192
- };
193
-
194
- // src/queue/drivers/RedisDriver.ts
195
- var RedisDriver = class {
196
- constructor(redis, options = {}) {
197
- this.redis = redis;
198
- this.prefix = options.prefix ?? "queue:";
199
- this.visibilityTimeout = options.visibilityTimeout ?? 6e4;
200
- }
201
- redis;
202
- prefix;
203
- visibilityTimeout;
204
- pendingKey(queue) {
205
- return `${this.prefix}${queue}:pending`;
206
- }
207
- reservedKey(queue) {
208
- return `${this.prefix}${queue}:reserved`;
209
- }
210
- failedKey(queue) {
211
- return `${this.prefix}${queue}:failed`;
212
- }
213
- jobKey(id) {
214
- return `${this.prefix}job:${id}`;
215
- }
216
- /**
217
- * Push a job onto the queue.
218
- */
219
- async push(job) {
220
- const jobData = {
221
- id: job.id,
222
- name: job.name,
223
- payload: JSON.stringify(job.payload),
224
- queue: job.queue,
225
- attempts: String(job.attempts),
226
- maxAttempts: String(job.maxAttempts),
227
- availableAt: job.availableAt.toISOString(),
228
- createdAt: job.createdAt.toISOString()
229
- };
230
- const pipeline = this.redis.pipeline();
231
- pipeline.hset(this.jobKey(job.id), jobData);
232
- pipeline.zadd(this.pendingKey(job.queue), job.availableAt.getTime(), job.id);
233
- await pipeline.exec();
234
- }
235
- /**
236
- * Pop the next available job from the queue.
237
- */
238
- async pop(queue) {
239
- const now = Date.now();
240
- await this.releaseTimedOutJobs(queue);
241
- const jobIds = await this.redis.zrangebyscore(
242
- this.pendingKey(queue),
243
- "-inf",
244
- now,
245
- "LIMIT",
246
- 0,
247
- 1
248
- );
249
- if (jobIds.length === 0) {
250
- return null;
251
- }
252
- const jobId = jobIds[0];
253
- const removed = await this.redis.zrem(this.pendingKey(queue), jobId);
254
- if (removed === 0) {
255
- return null;
256
- }
257
- const timeout = now + this.visibilityTimeout;
258
- await this.redis.zadd(this.reservedKey(queue), timeout, jobId);
259
- await this.redis.hset(this.jobKey(jobId), "reservedAt", (/* @__PURE__ */ new Date()).toISOString());
260
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
261
- if (!jobData || !jobData.id) {
262
- await this.redis.zrem(this.reservedKey(queue), jobId);
263
- return null;
264
- }
265
- return this.parseJobData(jobData);
266
- }
267
- /**
268
- * Release jobs that have exceeded visibility timeout.
269
- */
270
- async releaseTimedOutJobs(queue) {
271
- const now = Date.now();
272
- const timedOutIds = await this.redis.zrangebyscore(
273
- this.reservedKey(queue),
274
- "-inf",
275
- now
276
- );
277
- for (const jobId of timedOutIds) {
278
- const removed = await this.redis.zrem(this.reservedKey(queue), jobId);
279
- if (removed > 0) {
280
- await this.redis.zadd(this.pendingKey(queue), now, jobId);
281
- await this.redis.hdel(this.jobKey(jobId), "reservedAt");
282
- }
283
- }
284
- }
285
- /**
286
- * Release a job back onto the queue.
287
- */
288
- async release(job, delayMs = 0) {
289
- const availableAt = Date.now() + delayMs;
290
- await this.redis.zrem(this.reservedKey(job.queue), job.id);
291
- const updates = {
292
- attempts: String(job.attempts),
293
- availableAt: new Date(availableAt).toISOString()
294
- };
295
- if (job.lastError) {
296
- updates.lastError = job.lastError;
297
- }
298
- await this.redis.hset(this.jobKey(job.id), updates);
299
- await this.redis.hdel(this.jobKey(job.id), "reservedAt");
300
- await this.redis.zadd(this.pendingKey(job.queue), availableAt, job.id);
301
- }
302
- /**
303
- * Delete a job from the queue.
304
- */
305
- async delete(jobId) {
306
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
307
- if (jobData && jobData.queue) {
308
- const pipeline = this.redis.pipeline();
309
- pipeline.zrem(this.pendingKey(jobData.queue), jobId);
310
- pipeline.zrem(this.reservedKey(jobData.queue), jobId);
311
- pipeline.del(this.jobKey(jobId));
312
- await pipeline.exec();
313
- } else {
314
- await this.redis.del(this.jobKey(jobId));
315
- }
316
- }
317
- /**
318
- * Mark a job as failed.
319
- */
320
- async fail(job, error) {
321
- const failedData = {
322
- failedAt: (/* @__PURE__ */ new Date()).toISOString(),
323
- error: error.message,
324
- stack: error.stack ?? ""
325
- };
326
- await this.redis.hset(this.jobKey(job.id), failedData);
327
- const pipeline = this.redis.pipeline();
328
- pipeline.zrem(this.reservedKey(job.queue), job.id);
329
- pipeline.lpush(this.failedKey(job.queue), job.id);
330
- await pipeline.exec();
331
- }
332
- /**
333
- * Get the number of jobs in a queue.
334
- */
335
- async size(queue) {
336
- return this.redis.zcard(this.pendingKey(queue));
337
- }
338
- /**
339
- * Get failed jobs.
340
- */
341
- async getFailedJobs(queue) {
342
- const jobs = [];
343
- if (queue) {
344
- jobs.push(...await this.getFailedJobsForQueue(queue));
345
- } else {
346
- const pattern = `${this.prefix}*:failed`;
347
- let cursor = "0";
348
- const queueKeys = [];
349
- do {
350
- const [newCursor, keys] = await this.redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
351
- cursor = newCursor;
352
- queueKeys.push(...keys);
353
- } while (cursor !== "0");
354
- for (const key of queueKeys) {
355
- const queueName = key.replace(this.prefix, "").replace(":failed", "");
356
- jobs.push(...await this.getFailedJobsForQueue(queueName));
357
- }
358
- }
359
- return jobs.sort((a, b) => b.failedAt.getTime() - a.failedAt.getTime());
360
- }
361
- async getFailedJobsForQueue(queue) {
362
- const jobIds = await this.redis.lrange(this.failedKey(queue), 0, -1);
363
- const jobs = [];
364
- for (const jobId of jobIds) {
365
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
366
- if (jobData && jobData.id) {
367
- const job = this.parseJobData(jobData);
368
- jobs.push({
369
- ...job,
370
- failedAt: new Date(jobData.failedAt || Date.now()),
371
- error: jobData.error || "Unknown error",
372
- stack: jobData.stack
373
- });
374
- }
375
- }
376
- return jobs;
377
- }
378
- /**
379
- * Retry a failed job.
380
- */
381
- async retryFailedJob(jobId) {
382
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
383
- if (!jobData || !jobData.queue) {
384
- throw new Error(`Failed job not found: ${jobId}`);
385
- }
386
- const queue = jobData.queue;
387
- await this.redis.lrem(this.failedKey(queue), 1, jobId);
388
- const now = /* @__PURE__ */ new Date();
389
- await this.redis.hset(this.jobKey(jobId), {
390
- attempts: "0",
391
- availableAt: now.toISOString(),
392
- createdAt: now.toISOString()
393
- });
394
- await this.redis.hdel(this.jobKey(jobId), "reservedAt", "failedAt", "error", "stack", "lastError");
395
- await this.redis.zadd(this.pendingKey(queue), now.getTime(), jobId);
396
- }
397
- /**
398
- * Delete a failed job.
399
- */
400
- async deleteFailedJob(jobId) {
401
- const jobData = await this.redis.hgetall(this.jobKey(jobId));
402
- if (jobData && jobData.queue) {
403
- await this.redis.lrem(this.failedKey(jobData.queue), 1, jobId);
404
- }
405
- await this.redis.del(this.jobKey(jobId));
406
- }
407
- /**
408
- * Clear all jobs (for testing).
409
- */
410
- async clear() {
411
- const pattern = this.prefix + "*";
412
- let cursor = "0";
413
- const keys = [];
414
- do {
415
- const [newCursor, foundKeys] = await this.redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
416
- cursor = newCursor;
417
- keys.push(...foundKeys);
418
- } while (cursor !== "0");
419
- if (keys.length > 0) {
420
- await this.redis.del(...keys);
421
- }
422
- }
423
- /**
424
- * Parse job data from Redis hash.
425
- */
426
- parseJobData(data) {
427
- return {
428
- id: data.id,
429
- name: data.name,
430
- payload: JSON.parse(data.payload || "{}"),
431
- queue: data.queue,
432
- attempts: parseInt(data.attempts || "0", 10),
433
- maxAttempts: parseInt(data.maxAttempts || "3", 10),
434
- availableAt: new Date(data.availableAt),
435
- createdAt: new Date(data.createdAt),
436
- reservedAt: data.reservedAt ? new Date(data.reservedAt) : null,
437
- lastError: data.lastError
438
- };
439
- }
440
- };
441
-
442
- // src/queue/drivers/SqsDriver.ts
443
- function createSqsAdapter(client) {
444
- return {
445
- async sendMessage(params) {
446
- const { SendMessageCommand } = await importSqs();
447
- const input = {
448
- QueueUrl: params.queueUrl,
449
- MessageBody: params.messageBody,
450
- DelaySeconds: params.delaySeconds
451
- };
452
- if (params.messageGroupId) {
453
- input.MessageGroupId = params.messageGroupId;
454
- input.MessageDeduplicationId = params.messageDeduplicationId;
455
- }
456
- await client.send(new SendMessageCommand(input));
457
- },
458
- async receiveMessage(params) {
459
- const { ReceiveMessageCommand } = await importSqs();
460
- const result = await client.send(
461
- new ReceiveMessageCommand({
462
- QueueUrl: params.queueUrl,
463
- MaxNumberOfMessages: 1,
464
- WaitTimeSeconds: params.waitTimeSeconds ?? 5
465
- })
466
- );
467
- const msg = result.Messages?.[0];
468
- if (!msg?.Body || !msg.ReceiptHandle) return null;
469
- return { body: msg.Body, receiptHandle: msg.ReceiptHandle };
470
- },
471
- async changeMessageVisibility(params) {
472
- const { ChangeMessageVisibilityCommand } = await importSqs();
473
- await client.send(
474
- new ChangeMessageVisibilityCommand({
475
- QueueUrl: params.queueUrl,
476
- ReceiptHandle: params.receiptHandle,
477
- VisibilityTimeout: params.visibilityTimeout
478
- })
479
- );
480
- },
481
- async getApproximateMessageCount(queueUrl) {
482
- const { GetQueueAttributesCommand } = await importSqs();
483
- const result = await client.send(
484
- new GetQueueAttributesCommand({
485
- QueueUrl: queueUrl,
486
- AttributeNames: ["ApproximateNumberOfMessages"]
487
- })
488
- );
489
- return parseInt(result.Attributes?.ApproximateNumberOfMessages ?? "0", 10);
490
- }
491
- };
492
- }
493
- var SQS_MODULE = "@aws-sdk/client-sqs";
494
- async function importSqs() {
495
- try {
496
- return await import(SQS_MODULE);
497
- } catch {
498
- throw new Error(
499
- `Missing optional dependency "${SQS_MODULE}". Install @aws-sdk/client-sqs to use the SQS driver or createSqsAdapter.`
500
- );
501
- }
502
- }
503
- var SqsDriver = class {
504
- adapter;
505
- options;
506
- failedJobs = /* @__PURE__ */ new Map();
507
- receiptHandles = /* @__PURE__ */ new Map();
508
- constructor(adapter, options) {
509
- this.adapter = adapter;
510
- this.options = options;
511
- }
512
- async push(job) {
513
- const delaySeconds = Math.min(
514
- 900,
515
- Math.max(0, Math.floor((job.availableAt.getTime() - Date.now()) / 1e3))
516
- );
517
- await this.adapter.sendMessage({
518
- queueUrl: this.resolveQueueUrl(job.queue),
519
- messageBody: JSON.stringify(job),
520
- delaySeconds,
521
- messageGroupId: this.options.messageGroupId,
522
- messageDeduplicationId: this.options.messageGroupId ? job.id : void 0
523
- });
524
- }
525
- async pop(queue) {
526
- const result = await this.adapter.receiveMessage({
527
- queueUrl: this.resolveQueueUrl(queue)
528
- });
529
- if (!result) return null;
530
- const job = deserializeJob(result.body);
531
- this.receiptHandles.set(job.id, result.receiptHandle);
532
- job.reservedAt = /* @__PURE__ */ new Date();
533
- return job;
534
- }
535
- async release(job, delayMs = 0) {
536
- const receiptHandle = this.receiptHandles.get(job.id);
537
- if (receiptHandle) {
538
- await this.adapter.changeMessageVisibility({
539
- queueUrl: this.resolveQueueUrl(job.queue),
540
- receiptHandle,
541
- visibilityTimeout: Math.ceil(delayMs / 1e3)
542
- });
543
- this.receiptHandles.delete(job.id);
544
- } else {
545
- job.reservedAt = null;
546
- job.availableAt = new Date(Date.now() + delayMs);
547
- await this.push(job);
548
- }
549
- }
550
- async delete(jobId) {
551
- this.receiptHandles.delete(jobId);
552
- }
553
- async fail(job, error) {
554
- const failedJob = {
555
- ...job,
556
- failedAt: /* @__PURE__ */ new Date(),
557
- error: error.message,
558
- stack: error.stack
559
- };
560
- this.failedJobs.set(job.id, failedJob);
561
- this.receiptHandles.delete(job.id);
562
- }
563
- async size(queue) {
564
- return this.adapter.getApproximateMessageCount(this.resolveQueueUrl(queue));
565
- }
566
- async getFailedJobs(queue) {
567
- const jobs = [];
568
- for (const job of this.failedJobs.values()) {
569
- if (!queue || job.queue === queue) {
570
- jobs.push({ ...job });
571
- }
572
- }
573
- return jobs.sort((a, b) => b.failedAt.getTime() - a.failedAt.getTime());
574
- }
575
- async retryFailedJob(jobId) {
576
- const failedJob = this.failedJobs.get(jobId);
577
- if (!failedJob) {
578
- throw new Error(`Failed job not found: ${jobId}`);
579
- }
580
- const job = {
581
- id: failedJob.id,
582
- name: failedJob.name,
583
- payload: failedJob.payload,
584
- queue: failedJob.queue,
585
- attempts: 0,
586
- maxAttempts: failedJob.maxAttempts,
587
- availableAt: /* @__PURE__ */ new Date(),
588
- createdAt: /* @__PURE__ */ new Date(),
589
- reservedAt: null
590
- };
591
- await this.push(job);
592
- this.failedJobs.delete(jobId);
593
- }
594
- async deleteFailedJob(jobId) {
595
- this.failedJobs.delete(jobId);
596
- }
597
- async clear() {
598
- this.failedJobs.clear();
599
- this.receiptHandles.clear();
600
- }
601
- resolveQueueUrl(queue) {
602
- return this.options.queueUrls?.[queue] ?? this.options.queueUrl;
603
- }
604
- };
605
- function deserializeJob(body) {
606
- const raw = JSON.parse(body);
607
- return {
608
- ...raw,
609
- availableAt: new Date(raw.availableAt),
610
- createdAt: new Date(raw.createdAt),
611
- reservedAt: raw.reservedAt ? new Date(raw.reservedAt) : null
612
- };
613
- }
614
-
615
- // src/queue/Worker.ts
616
- var Worker = class {
617
- constructor(driver, options = {}, events = {}) {
618
- this.driver = driver;
619
- this.options = options;
620
- this.events = events;
621
- this.queues = options.queues ?? ["default"];
622
- this.sleep = options.sleep ?? 1e3;
623
- this.maxJobs = options.maxJobs ?? 0;
624
- this.timeout = options.timeout ?? 6e4;
625
- this.stopWhenEmpty = options.stopWhenEmpty ?? false;
626
- }
627
- driver;
628
- options;
629
- events;
630
- running = false;
631
- shouldStop = false;
632
- processedJobs = 0;
633
- queues;
634
- sleep;
635
- maxJobs;
636
- timeout;
637
- stopWhenEmpty;
638
- currentJob = null;
639
- /**
640
- * Start the worker.
641
- */
642
- async start() {
643
- if (this.running) {
644
- return;
645
- }
646
- this.running = true;
647
- this.shouldStop = false;
648
- this.processedJobs = 0;
649
- this.events.workerStarted?.();
650
- while (!this.shouldStop) {
651
- if (this.maxJobs > 0 && this.processedJobs >= this.maxJobs) {
652
- break;
653
- }
654
- const job = await this.getNextJob();
655
- if (job) {
656
- await this.processJob(job);
657
- this.processedJobs++;
658
- } else {
659
- if (this.stopWhenEmpty) {
660
- break;
661
- }
662
- await this.sleepMs(this.sleep);
663
- }
664
- }
665
- this.running = false;
666
- this.events.workerStopped?.();
667
- }
668
- /**
669
- * Stop the worker gracefully.
670
- */
671
- async stop() {
672
- this.shouldStop = true;
673
- const startWait = Date.now();
674
- while (this.running && this.currentJob && Date.now() - startWait < this.timeout) {
675
- await this.sleepMs(100);
676
- }
677
- }
678
- /**
679
- * Check if the worker is running.
680
- */
681
- isRunning() {
682
- return this.running;
683
- }
684
- /**
685
- * Get the number of processed jobs.
686
- */
687
- getProcessedJobsCount() {
688
- return this.processedJobs;
689
- }
690
- /**
691
- * Get the next available job from the queues.
692
- */
693
- async getNextJob() {
694
- for (const queue of this.queues) {
695
- const job = await this.driver.pop(queue);
696
- if (job) {
697
- return job;
698
- }
699
- }
700
- return null;
701
- }
702
- /**
703
- * Process a single job.
704
- */
705
- async processJob(job) {
706
- this.currentJob = job;
707
- job.attempts++;
708
- const JobClass = getJob(job.name);
709
- if (!JobClass) {
710
- console.error(`Job class not found: ${job.name}`);
711
- await this.driver.fail(job, new Error(`Job class not found: ${job.name}`));
712
- this.currentJob = null;
713
- return;
714
- }
715
- try {
716
- const instance = new JobClass();
717
- await this.executeWithTimeout(
718
- async () => instance.handle(job.payload),
719
- this.timeout
720
- );
721
- await this.driver.delete(job.id);
722
- this.events.jobProcessed?.(job);
723
- } catch (error) {
724
- await this.handleFailedJob(job, error, JobClass);
725
- } finally {
726
- this.currentJob = null;
727
- }
728
- }
729
- /**
730
- * Handle a failed job.
731
- */
732
- async handleFailedJob(job, error, JobClass) {
733
- const willRetry = job.attempts < job.maxAttempts;
734
- if (willRetry) {
735
- const delay = JobClass.calculateRetryDelay(job.attempts);
736
- job.lastError = error.message;
737
- await this.driver.release(job, delay);
738
- } else {
739
- await this.driver.fail(job, error);
740
- try {
741
- const instance = new JobClass();
742
- if (instance.failed) {
743
- await instance.failed(job.payload, error);
744
- }
745
- } catch (failedError) {
746
- console.error(`Error in job.failed() handler:`, failedError);
747
- }
748
- }
749
- console.error(JSON.stringify({
750
- level: "error",
751
- msg: `Job failed: ${job.name}`,
752
- job: job.name,
753
- queue: job.queue ?? "default",
754
- attempt: job.attempts,
755
- maxAttempts: job.maxAttempts,
756
- willRetry,
757
- error: error.message
758
- }));
759
- this.events.jobFailed?.(job, error, willRetry);
760
- }
761
- /**
762
- * Execute a function with a timeout.
763
- */
764
- async executeWithTimeout(fn, timeoutMs) {
765
- return new Promise((resolve, reject) => {
766
- const timer = setTimeout(() => {
767
- reject(new Error(`Job timed out after ${timeoutMs}ms`));
768
- }, timeoutMs);
769
- fn().then((result) => {
770
- clearTimeout(timer);
771
- resolve(result);
772
- }).catch((error) => {
773
- clearTimeout(timer);
774
- reject(error);
775
- });
776
- });
777
- }
778
- /**
779
- * Sleep for a given number of milliseconds.
780
- */
781
- sleepMs(ms) {
782
- return new Promise((resolve) => setTimeout(resolve, ms));
783
- }
784
- };
785
- async function processJob(driver, queue = "default") {
786
- const worker = new Worker(driver, { queues: [queue], maxJobs: 1, stopWhenEmpty: true });
787
- await worker.start();
788
- return worker.getProcessedJobsCount() > 0;
789
- }
790
-
791
- // src/queue/FailedJobReporter.ts
792
- function defaultLogHandler(info) {
793
- console.error(JSON.stringify({
794
- level: "error",
795
- msg: `Job failed: ${info.jobName}`,
796
- job: info.jobName,
797
- queue: info.queue,
798
- attempt: info.attempt,
799
- maxAttempts: info.maxAttempts,
800
- willRetry: info.willRetry,
801
- error: info.error.message,
802
- failedAt: info.failedAt.toISOString()
803
- }));
804
- }
805
- var FailedJobReporter = class {
806
- handlers = [];
807
- constructor() {
808
- this.handlers.push(defaultLogHandler);
809
- }
810
- /** Add a custom handler for failed jobs. */
811
- onFailure(handler) {
812
- this.handlers.push(handler);
813
- return this;
814
- }
815
- /** Report a job failure to all registered handlers. */
816
- async report(info) {
817
- for (const handler of this.handlers) {
818
- try {
819
- await handler(info);
820
- } catch {
821
- }
822
- }
823
- }
824
- };
825
-
826
- // src/queue/QueueManager.ts
827
- var QueueManager = class {
828
- defaultDriver;
829
- driverFactories = /* @__PURE__ */ new Map();
830
- resolvedDrivers = /* @__PURE__ */ new Map();
831
- constructor(config = {}) {
832
- this.defaultDriver = config.default ?? "memory";
833
- if (config.drivers) {
834
- for (const [name, factory] of Object.entries(config.drivers)) {
835
- this.driverFactories.set(name, factory);
836
- }
837
- }
838
- }
839
- /**
840
- * Get a queue driver by name.
841
- * Returns the default driver if no name is specified.
842
- */
843
- driver(name) {
844
- const driverName = name ?? this.defaultDriver;
845
- const cached = this.resolvedDrivers.get(driverName);
846
- if (cached) {
847
- return cached;
848
- }
849
- const factory = this.driverFactories.get(driverName);
850
- if (!factory) {
851
- throw new Error(`Queue driver not found: ${driverName}`);
852
- }
853
- const driver = factory();
854
- this.resolvedDrivers.set(driverName, driver);
855
- if (driverName === this.defaultDriver) {
856
- setQueueDriver(driver);
857
- }
858
- return driver;
859
- }
860
- /**
861
- * Register a custom driver factory.
862
- */
863
- registerDriver(name, factory) {
864
- this.driverFactories.set(name, factory);
865
- this.resolvedDrivers.delete(name);
866
- }
867
- /**
868
- * Check if a driver is registered.
869
- */
870
- hasDriver(name) {
871
- return this.driverFactories.has(name);
872
- }
873
- /**
874
- * Get the default driver name.
875
- */
876
- getDefaultDriverName() {
877
- return this.defaultDriver;
878
- }
879
- /**
880
- * Get all registered driver names.
881
- */
882
- getDriverNames() {
883
- return Array.from(this.driverFactories.keys());
884
- }
885
- /**
886
- * Set the default driver and update global driver.
887
- */
888
- setDefaultDriver(name) {
889
- if (!this.driverFactories.has(name)) {
890
- throw new Error(`Queue driver not found: ${name}`);
891
- }
892
- const driver = this.driver(name);
893
- setQueueDriver(driver);
894
- }
895
- };
896
- function createQueueManager(config) {
897
- return new QueueManager(config);
898
- }
899
-
900
- export {
901
- MemoryDriver,
902
- SyncDriver,
903
- RedisDriver,
904
- createSqsAdapter,
905
- SqsDriver,
906
- Worker,
907
- processJob,
908
- FailedJobReporter,
909
- QueueManager,
910
- createQueueManager
911
- };