@nimbusnexus/webhooks-sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,10 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
1
8
  // src/signature.ts
2
9
  import { createHmac, timingSafeEqual } from "crypto";
3
10
  var PREFIX = "sha256=";
@@ -30,6 +37,9 @@ function verify(secret, rawBody, signature, opts = {}) {
30
37
  return false;
31
38
  }
32
39
 
40
+ // src/client.ts
41
+ import { randomUUID } from "crypto";
42
+
33
43
  // src/errors.ts
34
44
  var WebhookdError = class extends Error {
35
45
  constructor(message) {
@@ -48,6 +58,437 @@ var WebhookdApiError = class extends WebhookdError {
48
58
  }
49
59
  };
50
60
 
61
+ // src/outbox.ts
62
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
63
+ import { join } from "path";
64
+ import { randomBytes } from "crypto";
65
+ import { createRequire } from "module";
66
+
67
+ // src/stores/redis.ts
68
+ function byCreatedAt(a, b) {
69
+ return a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
70
+ }
71
+ var RedisStore = class {
72
+ url;
73
+ keyPrefix;
74
+ client;
75
+ connecting;
76
+ constructor(opts = {}) {
77
+ this.url = opts.url;
78
+ this.client = opts.client;
79
+ this.keyPrefix = opts.keyPrefix ?? "webhookd:outbox";
80
+ }
81
+ get zsetKey() {
82
+ return `${this.keyPrefix}:due`;
83
+ }
84
+ get hashKey() {
85
+ return `${this.keyPrefix}:records`;
86
+ }
87
+ /** Lazily import the driver + connect exactly once. */
88
+ async ensure() {
89
+ if (this.client && this.client.isOpen) return this.client;
90
+ if (this.connecting) return this.connecting;
91
+ this.connecting = (async () => {
92
+ if (!this.client) {
93
+ const { createClient: create } = await import("redis");
94
+ this.client = create({ url: this.url });
95
+ }
96
+ if (!this.client.isOpen) await this.client.connect();
97
+ return this.client;
98
+ })();
99
+ try {
100
+ return await this.connecting;
101
+ } finally {
102
+ this.connecting = void 0;
103
+ }
104
+ }
105
+ async save(record) {
106
+ const client = await this.ensure();
107
+ await client.hSet(this.hashKey, record.id, JSON.stringify(record));
108
+ await client.zAdd(this.zsetKey, { score: record.nextAttemptAt, value: record.id });
109
+ }
110
+ async listPending(limit) {
111
+ const client = await this.ensure();
112
+ const ids = await client.zRangeByScore(this.zsetKey, "-inf", Date.now());
113
+ return this.loadSorted(client, ids, limit);
114
+ }
115
+ async markSent(id) {
116
+ const client = await this.ensure();
117
+ await client.hDel(this.hashKey, id);
118
+ await client.zRem(this.zsetKey, id);
119
+ }
120
+ async markFailed(id, error, attempts, nextAttemptAt) {
121
+ const client = await this.ensure();
122
+ const raw = await client.hGet(this.hashKey, id);
123
+ if (raw === void 0 || raw === null) return;
124
+ const record = JSON.parse(raw);
125
+ record.attempts = attempts;
126
+ record.lastError = error;
127
+ record.nextAttemptAt = nextAttemptAt;
128
+ await client.hSet(this.hashKey, id, JSON.stringify(record));
129
+ await client.zAdd(this.zsetKey, { score: nextAttemptAt, value: id });
130
+ }
131
+ async size() {
132
+ const client = await this.ensure();
133
+ return client.hLen(this.hashKey);
134
+ }
135
+ async listDead(limit) {
136
+ const client = await this.ensure();
137
+ const ids = await client.zRangeByScore(this.zsetKey, DEAD_NEXT_ATTEMPT_MS, "+inf");
138
+ const dead = (await this.loadSorted(client, ids, ids.length)).filter(isDead);
139
+ return limit === void 0 ? dead : dead.slice(0, limit);
140
+ }
141
+ async close() {
142
+ if (this.client && this.client.isOpen) await this.client.close();
143
+ }
144
+ /** Load records for `ids` from the hash, drop any missing, sort oldest-first, cap at `limit`. */
145
+ async loadSorted(client, ids, limit) {
146
+ const records = [];
147
+ for (const id of ids) {
148
+ const raw = await client.hGet(this.hashKey, id);
149
+ if (raw === void 0 || raw === null) continue;
150
+ records.push(cloneRecord(JSON.parse(raw)));
151
+ }
152
+ return records.sort(byCreatedAt).slice(0, limit);
153
+ }
154
+ };
155
+
156
+ // src/stores/postgres.ts
157
+ function rowToRecord(row) {
158
+ return {
159
+ id: row.id,
160
+ eventType: row.event_type,
161
+ payload: row.payload,
162
+ projectId: row.project_id,
163
+ source: row.source,
164
+ createdAt: Number(row.created_at),
165
+ attempts: row.attempts,
166
+ lastError: row.last_error,
167
+ nextAttemptAt: Number(row.next_attempt_at)
168
+ };
169
+ }
170
+ var PostgresStore = class {
171
+ connectionString;
172
+ table;
173
+ pool;
174
+ ready;
175
+ constructor(opts = {}) {
176
+ this.connectionString = opts.connectionString;
177
+ this.pool = opts.pool;
178
+ const table = opts.table ?? "webhookd_outbox";
179
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
180
+ throw new Error(`invalid table name: ${table}`);
181
+ }
182
+ this.table = table;
183
+ }
184
+ /** Lazily import the driver, open the pool, and create the table exactly once. */
185
+ async ensure() {
186
+ if (this.ready) return this.ready;
187
+ this.ready = (async () => {
188
+ if (!this.pool) {
189
+ const pg = await import("pg");
190
+ const Pool = pg.Pool ?? pg.default?.Pool;
191
+ if (!Pool) throw new Error("pg: could not resolve Pool export");
192
+ this.pool = new Pool({ connectionString: this.connectionString });
193
+ }
194
+ await this.pool.query(
195
+ `CREATE TABLE IF NOT EXISTS ${this.table} (
196
+ id TEXT PRIMARY KEY,
197
+ event_type TEXT NOT NULL,
198
+ payload JSONB NOT NULL,
199
+ project_id TEXT,
200
+ source TEXT,
201
+ sent BOOLEAN NOT NULL DEFAULT FALSE,
202
+ attempts INTEGER NOT NULL,
203
+ last_error TEXT,
204
+ next_attempt_at BIGINT NOT NULL,
205
+ created_at BIGINT NOT NULL
206
+ )`
207
+ );
208
+ return this.pool;
209
+ })();
210
+ return this.ready;
211
+ }
212
+ async save(record) {
213
+ const pool = await this.ensure();
214
+ await pool.query(
215
+ `INSERT INTO ${this.table}
216
+ (id, event_type, payload, project_id, source, sent, attempts, last_error, next_attempt_at, created_at)
217
+ VALUES ($1, $2, $3, $4, $5, FALSE, $6, $7, $8, $9)
218
+ ON CONFLICT (id) DO UPDATE SET
219
+ event_type = EXCLUDED.event_type,
220
+ payload = EXCLUDED.payload,
221
+ project_id = EXCLUDED.project_id,
222
+ source = EXCLUDED.source,
223
+ sent = EXCLUDED.sent,
224
+ attempts = EXCLUDED.attempts,
225
+ last_error = EXCLUDED.last_error,
226
+ next_attempt_at = EXCLUDED.next_attempt_at,
227
+ created_at = EXCLUDED.created_at`,
228
+ [
229
+ record.id,
230
+ record.eventType,
231
+ JSON.stringify(record.payload),
232
+ record.projectId,
233
+ record.source,
234
+ record.attempts,
235
+ record.lastError,
236
+ record.nextAttemptAt,
237
+ record.createdAt
238
+ ]
239
+ );
240
+ }
241
+ async listPending(limit) {
242
+ const pool = await this.ensure();
243
+ const res = await pool.query(
244
+ `SELECT * FROM ${this.table}
245
+ WHERE NOT sent AND next_attempt_at <= $1 AND next_attempt_at < $2
246
+ ORDER BY created_at ASC, id ASC
247
+ LIMIT $3`,
248
+ [Date.now(), DEAD_NEXT_ATTEMPT_MS, limit]
249
+ );
250
+ return res.rows.map(rowToRecord);
251
+ }
252
+ async markSent(id) {
253
+ const pool = await this.ensure();
254
+ await pool.query(`UPDATE ${this.table} SET sent = TRUE WHERE id = $1`, [id]);
255
+ }
256
+ async markFailed(id, error, attempts, nextAttemptAt) {
257
+ const pool = await this.ensure();
258
+ await pool.query(
259
+ `UPDATE ${this.table} SET attempts = $2, last_error = $3, next_attempt_at = $4 WHERE id = $1`,
260
+ [id, attempts, error, nextAttemptAt]
261
+ );
262
+ }
263
+ async size() {
264
+ const pool = await this.ensure();
265
+ const res = await pool.query(
266
+ `SELECT COUNT(*) AS n FROM ${this.table} WHERE NOT sent`
267
+ );
268
+ return Number(res.rows[0].n);
269
+ }
270
+ async listDead(limit) {
271
+ const pool = await this.ensure();
272
+ const res = await pool.query(
273
+ `SELECT * FROM ${this.table}
274
+ WHERE NOT sent AND next_attempt_at >= $1
275
+ ORDER BY created_at ASC, id ASC
276
+ ${limit === void 0 ? "" : "LIMIT $2"}`,
277
+ limit === void 0 ? [DEAD_NEXT_ATTEMPT_MS] : [DEAD_NEXT_ATTEMPT_MS, limit]
278
+ );
279
+ return res.rows.map(rowToRecord);
280
+ }
281
+ async close() {
282
+ if (this.pool) await this.pool.end();
283
+ }
284
+ };
285
+
286
+ // src/outbox.ts
287
+ var DEAD_NEXT_ATTEMPT_MS = 864e13;
288
+ function isDead(record) {
289
+ return record.nextAttemptAt >= DEAD_NEXT_ATTEMPT_MS;
290
+ }
291
+ function cloneRecord(record) {
292
+ return { ...record, payload: structuredClone(record.payload) };
293
+ }
294
+ function byCreatedAt2(a, b) {
295
+ return a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
296
+ }
297
+ var MemoryStore = class {
298
+ records = /* @__PURE__ */ new Map();
299
+ save(record) {
300
+ this.records.set(record.id, cloneRecord(record));
301
+ }
302
+ listPending(limit) {
303
+ const now = Date.now();
304
+ return [...this.records.values()].filter((r) => r.nextAttemptAt <= now).sort(byCreatedAt2).slice(0, limit).map(cloneRecord);
305
+ }
306
+ markSent(id) {
307
+ this.records.delete(id);
308
+ }
309
+ markFailed(id, error, attempts, nextAttemptAt) {
310
+ const record = this.records.get(id);
311
+ if (!record) return;
312
+ record.attempts = attempts;
313
+ record.lastError = error;
314
+ record.nextAttemptAt = nextAttemptAt;
315
+ }
316
+ size() {
317
+ return this.records.size;
318
+ }
319
+ listDead(limit) {
320
+ const dead = [...this.records.values()].filter(isDead).sort(byCreatedAt2).map(cloneRecord);
321
+ return limit === void 0 ? dead : dead.slice(0, limit);
322
+ }
323
+ close() {
324
+ this.records.clear();
325
+ }
326
+ };
327
+ var FileStore = class {
328
+ dir;
329
+ constructor(dir) {
330
+ this.dir = dir;
331
+ mkdirSync(dir, { recursive: true });
332
+ }
333
+ /** Map an arbitrary id to a safe filename (ids may be caller-supplied idempotency keys). */
334
+ pathFor(id) {
335
+ return join(this.dir, `${encodeURIComponent(id)}.json`);
336
+ }
337
+ readAll() {
338
+ const out = [];
339
+ for (const name of readdirSync(this.dir)) {
340
+ if (!name.endsWith(".json")) continue;
341
+ try {
342
+ out.push(JSON.parse(readFileSync(join(this.dir, name), "utf8")));
343
+ } catch {
344
+ }
345
+ }
346
+ return out;
347
+ }
348
+ save(record) {
349
+ const dest = this.pathFor(record.id);
350
+ const tmp = `${dest}.tmp-${randomBytes(6).toString("hex")}`;
351
+ writeFileSync(tmp, JSON.stringify(record), "utf8");
352
+ renameSync(tmp, dest);
353
+ }
354
+ listPending(limit) {
355
+ const now = Date.now();
356
+ return this.readAll().filter((r) => r.nextAttemptAt <= now).sort(byCreatedAt2).slice(0, limit);
357
+ }
358
+ markSent(id) {
359
+ rmSync(this.pathFor(id), { force: true });
360
+ }
361
+ markFailed(id, error, attempts, nextAttemptAt) {
362
+ let record;
363
+ try {
364
+ record = JSON.parse(readFileSync(this.pathFor(id), "utf8"));
365
+ } catch {
366
+ return;
367
+ }
368
+ record.attempts = attempts;
369
+ record.lastError = error;
370
+ record.nextAttemptAt = nextAttemptAt;
371
+ this.save(record);
372
+ }
373
+ size() {
374
+ return readdirSync(this.dir).filter((n) => n.endsWith(".json")).length;
375
+ }
376
+ listDead(limit) {
377
+ const dead = this.readAll().filter(isDead).sort(byCreatedAt2);
378
+ return limit === void 0 ? dead : dead.slice(0, limit);
379
+ }
380
+ close() {
381
+ }
382
+ };
383
+ function rowToRecord2(row) {
384
+ return {
385
+ id: row.id,
386
+ eventType: row.event_type,
387
+ payload: JSON.parse(row.payload),
388
+ projectId: row.project_id,
389
+ source: row.source,
390
+ createdAt: row.created_at,
391
+ attempts: row.attempts,
392
+ lastError: row.last_error,
393
+ nextAttemptAt: row.next_attempt_at
394
+ };
395
+ }
396
+ var SqliteStore = class {
397
+ db;
398
+ constructor(path = ":memory:") {
399
+ let DatabaseSync;
400
+ try {
401
+ let load;
402
+ try {
403
+ load = createRequire(import.meta.url);
404
+ } catch {
405
+ load = __require;
406
+ }
407
+ ({ DatabaseSync } = load("node:sqlite"));
408
+ } catch (err) {
409
+ throw new Error(
410
+ `SqliteStore requires the built-in node:sqlite (Node >= 22.5): ${String(err)}`
411
+ );
412
+ }
413
+ this.db = new DatabaseSync(path);
414
+ this.db.exec(
415
+ // `project_id` is NULLABLE: NULL = the workspace's default project (the publish body simply
416
+ // omits the field). Renamed from the legacy `project` slug column — this store has no
417
+ // schema-versioning mechanism, so a table created by an older SDK build is not upgraded.
418
+ `CREATE TABLE IF NOT EXISTS webhookd_outbox (
419
+ id TEXT PRIMARY KEY,
420
+ event_type TEXT NOT NULL,
421
+ payload TEXT NOT NULL,
422
+ project_id TEXT,
423
+ source TEXT,
424
+ created_at INTEGER NOT NULL,
425
+ attempts INTEGER NOT NULL,
426
+ last_error TEXT,
427
+ next_attempt_at INTEGER NOT NULL
428
+ )`
429
+ );
430
+ }
431
+ save(record) {
432
+ this.db.prepare(
433
+ `INSERT INTO webhookd_outbox
434
+ (id, event_type, payload, project_id, source, created_at, attempts, last_error, next_attempt_at)
435
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
436
+ ON CONFLICT(id) DO UPDATE SET
437
+ event_type = excluded.event_type,
438
+ payload = excluded.payload,
439
+ project_id = excluded.project_id,
440
+ source = excluded.source,
441
+ created_at = excluded.created_at,
442
+ attempts = excluded.attempts,
443
+ last_error = excluded.last_error,
444
+ next_attempt_at = excluded.next_attempt_at`
445
+ ).run(
446
+ record.id,
447
+ record.eventType,
448
+ JSON.stringify(record.payload),
449
+ record.projectId,
450
+ record.source,
451
+ record.createdAt,
452
+ record.attempts,
453
+ record.lastError,
454
+ record.nextAttemptAt
455
+ );
456
+ }
457
+ listPending(limit) {
458
+ const rows = this.db.prepare(
459
+ `SELECT * FROM webhookd_outbox
460
+ WHERE next_attempt_at <= ? AND next_attempt_at < ?
461
+ ORDER BY created_at ASC, id ASC
462
+ LIMIT ?`
463
+ ).all(Date.now(), DEAD_NEXT_ATTEMPT_MS, limit);
464
+ return rows.map(rowToRecord2);
465
+ }
466
+ markSent(id) {
467
+ this.db.prepare(`DELETE FROM webhookd_outbox WHERE id = ?`).run(id);
468
+ }
469
+ markFailed(id, error, attempts, nextAttemptAt) {
470
+ this.db.prepare(
471
+ `UPDATE webhookd_outbox SET attempts = ?, last_error = ?, next_attempt_at = ? WHERE id = ?`
472
+ ).run(attempts, error, nextAttemptAt, id);
473
+ }
474
+ size() {
475
+ const row = this.db.prepare(`SELECT COUNT(*) AS n FROM webhookd_outbox`).get();
476
+ return Number(row.n);
477
+ }
478
+ listDead(limit) {
479
+ const rows = this.db.prepare(
480
+ `SELECT * FROM webhookd_outbox
481
+ WHERE next_attempt_at >= ?
482
+ ORDER BY created_at ASC, id ASC
483
+ ${limit === void 0 ? "" : "LIMIT ?"}`
484
+ ).all(...limit === void 0 ? [DEAD_NEXT_ATTEMPT_MS] : [DEAD_NEXT_ATTEMPT_MS, limit]);
485
+ return rows.map(rowToRecord2);
486
+ }
487
+ close() {
488
+ this.db.close();
489
+ }
490
+ };
491
+
51
492
  // src/client.ts
52
493
  var RETRY_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
53
494
  var WebhookdClient = class {
@@ -56,20 +497,32 @@ var WebhookdClient = class {
56
497
  timeoutMs;
57
498
  maxRetries;
58
499
  fetchImpl;
500
+ store;
501
+ maxAttempts;
502
+ drainBatchLimit;
503
+ onDead;
504
+ onDrainError;
505
+ drainTimer;
506
+ draining = false;
59
507
  constructor(opts) {
60
508
  this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
61
509
  this.apiKey = opts.apiKey;
62
510
  this.timeoutMs = opts.timeoutMs ?? 1e4;
63
511
  this.maxRetries = opts.maxRetries ?? 2;
64
512
  this.fetchImpl = opts.fetchImpl ?? fetch;
513
+ this.store = opts.store;
514
+ this.maxAttempts = opts.maxAttempts ?? 10;
515
+ this.drainBatchLimit = opts.drainBatchLimit ?? 100;
516
+ this.onDead = opts.onDead;
517
+ this.onDrainError = opts.onDrainError;
65
518
  }
66
519
  async publish(eventType, payload, opts = {}) {
67
520
  const body = {
68
521
  event_type: eventType,
69
- payload,
70
- environment: opts.environment ?? "prod",
71
- application: opts.application ?? "default"
522
+ payload
72
523
  };
524
+ const projectId = normalizeProjectId(opts.projectId);
525
+ if (projectId !== null) body.project_id = projectId;
73
526
  if (opts.source !== void 0) body.source = opts.source;
74
527
  const headers = {};
75
528
  if (opts.idempotencyKey !== void 0) headers["Idempotency-Key"] = opts.idempotencyKey;
@@ -79,20 +532,124 @@ var WebhookdClient = class {
79
532
  id: String(data.id),
80
533
  eventUid: String(data.event_uid),
81
534
  eventType: String(data.event_type),
82
- application: String(data.application ?? "default"),
83
- environment: String(data.environment ?? "prod"),
535
+ projectId: String(data.project_id),
84
536
  deliveriesCreated: Number(data.deliveries_created ?? 0),
85
537
  source: data.source ?? null
86
538
  };
87
539
  }
540
+ // ── Outbox (write-first, durable) ────────────────────────────────────────────
541
+ /**
542
+ * Durably buffer an event and return IMMEDIATELY — NO network call. Builds an {@link OutboxRecord}
543
+ * (id = `opts.idempotencyKey` or a fresh UUID v4), saves it to the configured store, and returns the
544
+ * id. Ship it later with {@link drain} (or the background drainer). Requires a `store` in options.
545
+ */
546
+ async enqueue(eventType, payload, opts = {}) {
547
+ const store = this.requireStore();
548
+ const now = Date.now();
549
+ const record = {
550
+ id: opts.idempotencyKey ?? randomUUID(),
551
+ eventType,
552
+ payload,
553
+ // null = the workspace's default project (the field is omitted from the publish body on drain).
554
+ projectId: normalizeProjectId(opts.projectId),
555
+ source: opts.source ?? null,
556
+ createdAt: now,
557
+ attempts: 0,
558
+ lastError: null,
559
+ nextAttemptAt: now
560
+ };
561
+ await store.save(record);
562
+ return { id: record.id };
563
+ }
564
+ /**
565
+ * Send buffered records to webhookd. Pulls a due batch (oldest first), POSTs each to `/v1/events`
566
+ * with header `Idempotency-Key = record.id` (so a re-drain after a crash never double-publishes —
567
+ * webhookd dedupes). On 2xx the record is marked sent; on error `attempts` is bumped and the record
568
+ * is rescheduled with capped exponential backoff, or parked dead once it hits `maxAttempts` (the
569
+ * `onDead` hook fires, and it is retrievable via `store.listDead()`). Requires a `store`.
570
+ */
571
+ async drain(opts = {}) {
572
+ const store = this.requireStore();
573
+ const batchLimit = opts.batchLimit ?? this.drainBatchLimit;
574
+ const maxAttempts = opts.maxAttempts ?? this.maxAttempts;
575
+ const rows = await store.listPending(batchLimit);
576
+ let sent = 0;
577
+ let failed = 0;
578
+ for (const record of rows) {
579
+ const body = {
580
+ event_type: record.eventType,
581
+ payload: record.payload
582
+ };
583
+ if (record.projectId !== null) body.project_id = record.projectId;
584
+ if (record.source !== null) body.source = record.source;
585
+ try {
586
+ await this.request("POST", "/v1/events", {
587
+ body,
588
+ headers: { "Idempotency-Key": record.id }
589
+ });
590
+ await store.markSent(record.id);
591
+ sent += 1;
592
+ } catch (err) {
593
+ const attempts = record.attempts + 1;
594
+ const message = err instanceof Error ? err.message : String(err);
595
+ if (attempts >= maxAttempts) {
596
+ await store.markFailed(record.id, message, attempts, DEAD_NEXT_ATTEMPT_MS);
597
+ this.onDead?.({
598
+ ...record,
599
+ attempts,
600
+ lastError: message,
601
+ nextAttemptAt: DEAD_NEXT_ATTEMPT_MS
602
+ });
603
+ } else {
604
+ await store.markFailed(record.id, message, attempts, Date.now() + backoffMs(attempts - 1));
605
+ }
606
+ failed += 1;
607
+ }
608
+ }
609
+ return { sent, failed, remaining: await store.size() };
610
+ }
611
+ /**
612
+ * Start a background loop calling {@link drain} every `intervalSeconds`. Overlapping ticks are
613
+ * skipped while a drain is in flight, and a tick that throws is swallowed (routed to `onDrainError`)
614
+ * so the loop keeps running. The timer is `unref`'d so it never blocks process exit. Idempotent.
615
+ */
616
+ startDrainer(intervalSeconds) {
617
+ this.requireStore();
618
+ if (this.drainTimer) return;
619
+ const ms = Math.max(1, Math.floor(intervalSeconds * 1e3));
620
+ this.drainTimer = setInterval(() => void this.drainTick(), ms);
621
+ this.drainTimer.unref?.();
622
+ }
623
+ /** Stop the background drainer started by {@link startDrainer}. Safe to call when not running. */
624
+ stopDrainer() {
625
+ if (this.drainTimer) {
626
+ clearInterval(this.drainTimer);
627
+ this.drainTimer = void 0;
628
+ }
629
+ }
630
+ async drainTick() {
631
+ if (this.draining) return;
632
+ this.draining = true;
633
+ try {
634
+ await this.drain();
635
+ } catch (err) {
636
+ this.onDrainError?.(err);
637
+ } finally {
638
+ this.draining = false;
639
+ }
640
+ }
641
+ requireStore() {
642
+ if (!this.store) {
643
+ throw new WebhookdError("no outbox store configured \u2014 pass `store` in ClientOptions");
644
+ }
645
+ return this.store;
646
+ }
88
647
  // ── Endpoints ──────────────────────────────────────────────────────────────
89
648
  /** Create an endpoint. The response includes the signing `secret` exactly once — persist it. */
90
649
  async createEndpoint(url, opts = {}) {
91
- const body = {
92
- url,
93
- environment: opts.environment ?? "prod",
94
- application: opts.application ?? "default"
95
- };
650
+ const body = { url };
651
+ const projectId = normalizeProjectId(opts.projectId);
652
+ if (projectId !== null) body.project_id = projectId;
96
653
  if (opts.subscriptions !== void 0) body.subscriptions = opts.subscriptions;
97
654
  if (opts.secret !== void 0) body.secret = opts.secret;
98
655
  if (opts.maxAttempts !== void 0) body.max_attempts = opts.maxAttempts;
@@ -102,9 +659,11 @@ var WebhookdClient = class {
102
659
  if (opts.deliveryTimeoutMs !== void 0) body.delivery_timeout_ms = opts.deliveryTimeoutMs;
103
660
  return this.requestJson("POST", "/v1/endpoints", { body });
104
661
  }
105
- /** List endpoints for an environment (defaults to `prod`). */
662
+ /** List endpoints for a project. Omit `projectId` for the workspace's default project. */
106
663
  async listEndpoints(opts = {}) {
107
- const query = { environment: opts.environment ?? "prod" };
664
+ const query = {};
665
+ const projectId = normalizeProjectId(opts.projectId);
666
+ if (projectId !== null) query.project_id = projectId;
108
667
  if (opts.offset !== void 0) query.offset = opts.offset;
109
668
  if (opts.limit !== void 0) query.limit = opts.limit;
110
669
  return this.requestJson("GET", "/v1/endpoints", { query });
@@ -227,6 +786,9 @@ var WebhookdClient = class {
227
786
  throw new WebhookdError(`request failed after retries: ${String(lastErr)}`);
228
787
  }
229
788
  };
789
+ function normalizeProjectId(projectId) {
790
+ return projectId === void 0 || projectId === null || projectId === "" ? null : projectId;
791
+ }
230
792
  function backoffMs(attempt) {
231
793
  return Math.min(2e3, 200 * 2 ** attempt);
232
794
  }
@@ -252,13 +814,20 @@ function sleep(ms) {
252
814
  }
253
815
 
254
816
  // src/index.ts
255
- var VERSION = "0.2.0";
817
+ var VERSION = "0.4.0";
256
818
  export {
819
+ DEAD_NEXT_ATTEMPT_MS,
257
820
  DEFAULT_TOLERANCE_SECONDS,
821
+ FileStore,
822
+ MemoryStore,
823
+ PostgresStore,
824
+ RedisStore,
825
+ SqliteStore,
258
826
  VERSION,
259
827
  WebhookdApiError,
260
828
  WebhookdClient,
261
829
  WebhookdError,
830
+ isDead,
262
831
  sign,
263
832
  verify
264
833
  };