@astratra/shipping 1.0.0 → 1.1.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/README.fr.md CHANGED
@@ -64,12 +64,28 @@ const envoi = await carrier.createLabel({
64
64
  // envoi.label : le PDF de l'étiquette, revenu avec l'envoi (un seul colis) — pas de seconde demande
65
65
 
66
66
  const { content } = await carrier.downloadLabel({ parcelId: envoi.parcelId, format: 'a4' }); // A4, A5 ou A6 (par défaut)
67
+ // Pas de « commencer à la case N » sur une planche A4 : l'API v3 de Sendcloud ne le propose pas.
67
68
  await carrier.cancelLabel({ shipmentId: envoi.shipmentId }); // { status: 'cancelled' | 'requested' }
68
69
  ```
69
70
 
70
71
  - **L'expéditeur** (`sender`) : l'identifiant d'une adresse enregistrée chez
71
72
  Sendcloud avec son pays, ou l'adresse complète (`name`, `line1`, `city`,
72
73
  `postalCode`, `country`…). Sans lui, `status()` signale `sender` manquant.
74
+ - **Réglages relus à chaque appel** (1.1.0) : `sender` et `testMode` acceptent
75
+ une valeur ou une fonction (éventuellement asynchrone), comme les clés. La
76
+ boutique change son adresse d'expédition ou passe en mode test depuis son
77
+ administration, sans recréer le transporteur :
78
+
79
+ ```js
80
+ const carrier = createSendcloudCarrier({
81
+ publicKey, secretKey,
82
+ sender: async () => (await lireReglages()).adresseExpedition, // { addressId, country } ou l'adresse complète
83
+ testMode: async () => (await lireReglages()).modeTest
84
+ });
85
+ ```
86
+
87
+ `carrier.testMode` vaut le booléen donné, ou `null` quand c'est une fonction :
88
+ lis alors `(await carrier.status()).testMode`.
73
89
  - **Les options d'expédition** sont des codes stables (`colissimo:home/signature`,
74
90
  `mondial_relay:point`…), jamais des numéros qui changent. `priceCents` est le
75
91
  devis de Sendcloud : tes prix restent les tiens.
@@ -154,7 +170,25 @@ app.post('/api/transporteurs/sendcloud/webhook', express.raw({ type: 'applicatio
154
170
  (`classifySendcloudStatus`). Une tentative de livraison ratée ou un retard
155
171
  reste `picked_up` : ce n'est pas un incident définitif.
156
172
  - Les notifications peuvent arriver dans le désordre : `timestamp` dit quand le
157
- statut a changé, pour ne pas écraser un statut récent par un ancien.
173
+ statut a changé, **toujours en millisecondes** (1.1.0 : secondes, millisecondes
174
+ ou date ISO sont ramenées en millisecondes), pour ne pas écraser un statut
175
+ récent par un ancien :
176
+
177
+ ```js
178
+ onEvent: async (colis) => {
179
+ await pool.query(
180
+ `UPDATE colis SET statut = $2, statut_le = to_timestamp($3 / 1000.0)
181
+ WHERE id = $1 AND (statut_le IS NULL OR statut_le < to_timestamp($3 / 1000.0))`,
182
+ [colis.parcelId, colis.message, colis.timestamp]
183
+ );
184
+ }
185
+ ```
186
+ - **Purge de la trace des notifications** (1.1.0) : avec un journal qui sait
187
+ purger (`createPostgresEventLog` de `@astratra/payments`), les événements
188
+ traités de plus de 90 jours sont effacés, au plus une fois par jour, après la
189
+ réponse à Sendcloud (jamais sur son chemin ; un échec est seulement journalisé).
190
+ Réglable : `pruneOlderThanMs` (`false` pour le faire toi-même) et
191
+ `pruneEveryMs`. `webhook.settled()` attend une purge en cours (arrêt propre).
158
192
  - La signature utilise la « Webhook Signature Key » de l'intégration
159
193
  (`webhookSecret`) quand elle existe, sinon la clé secrète.
160
194
 
package/README.md CHANGED
@@ -56,10 +56,16 @@ const shipment = await carrier.createLabel({
56
56
  method: options[0]
57
57
  });
58
58
  // shipment.label: the label PDF, returned with the shipment (one parcel) — no second request
59
+ // No "start at box N" on an A4 sheet: Sendcloud API v3 does not offer it.
59
60
  const { content } = await carrier.downloadLabel({ parcelId: shipment.parcelId, format: 'a4' }); // A4, A5 or A6 (default)
60
61
  await carrier.cancelLabel({ shipmentId: shipment.shipmentId }); // { status: 'cancelled' | 'requested' }
61
62
  ```
62
63
 
64
+ - **Settings read on every call** (1.1.0): `sender` and `testMode` take a value
65
+ or a (possibly async) function, like the keys — change the sender address or
66
+ switch to test mode from the shop's admin without creating a new carrier.
67
+ `carrier.testMode` is the boolean given, or `null` for a function (read
68
+ `(await carrier.status()).testMode`).
63
69
  - Shipping options are stable codes (`colissimo:home/signature`), never ids that
64
70
  change. `priceCents` is Sendcloud's quote: your prices stay yours.
65
71
  - `reference` (unique per account) guards against buying twice: the same
@@ -108,7 +114,12 @@ app.post('/webhooks/sendcloud', express.raw({ type: 'application/json', limit: '
108
114
 
109
115
  The signature is the HMAC-SHA256 of the raw body (hex), with the integration's
110
116
  "Webhook Signature Key" (`webhookSecret`) when it has one, else the secret key.
111
- Webhooks can arrive out of order: `timestamp` says when the status changed.
117
+ Webhooks can arrive out of order: `timestamp` says when the status changed,
118
+ **always in milliseconds** (1.1.0: seconds, milliseconds or an ISO date are
119
+ converted), so an older status never overwrites a newer one.
120
+ With an event log that can prune (`createPostgresEventLog`), handled events
121
+ older than 90 days are deleted at most once a day, after the answer
122
+ (`pruneOlderThanMs`, `false` to do it yourself; `pruneEveryMs`; `settled()`).
112
123
  Wrong signature, parsed or unreadable body: 400 (no endless retries). Another
113
124
  event type: 200, ignored. The same body again: 200 `duplicate`. An error in your
114
125
  handlers: 500 and the event is released, so Sendcloud's resend is handled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/shipping",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Shipping labels without the traps: a carrier contract, a Sendcloud adapter (labels, service points, tracking), signed tracking webhooks with replay protection, and a free test mode.",
5
5
  "engines": {
6
6
  "node": ">=20"
package/src/index.d.ts CHANGED
@@ -88,7 +88,7 @@ export interface ParcelEvent {
88
88
  /** The provider's status label. */
89
89
  message: string;
90
90
  stage: ParcelStage | null;
91
- /** When the status changed (seconds); webhooks can arrive out of order. */
91
+ /** When the status changed, ALWAYS in milliseconds since 1970 (whatever unit arrived); webhooks can arrive out of order. */
92
92
  timestamp: number | null;
93
93
  }
94
94
 
@@ -105,7 +105,7 @@ export class Carrier {
105
105
  method: { id?: string; code?: string };
106
106
  servicePointId?: number | string | null;
107
107
  }): Promise<Label>;
108
- /** Paper size; default 'a6'. */
108
+ /** Paper size; default 'a6'. Sendcloud v3 has no "start from box N" for A4 sheets. */
109
109
  downloadLabel(input: { parcelId: number; format?: 'a4' | 'a5' | 'a6' }): Promise<{ content: Buffer; type: 'application/pdf' }>;
110
110
  cancelLabel(input: { shipmentId: string }): Promise<{ status: 'cancelled' | 'requested' }>;
111
111
  servicePoints(query: {
@@ -132,16 +132,24 @@ export const TEST_SHIPPING_OPTION: 'sendcloud:letter';
132
132
 
133
133
  type Secret = string | (() => string | Promise<string>);
134
134
 
135
+ export type Sender = { addressId: number; country: string } | {
136
+ name: string; companyName?: string; line1: string; line2?: string; houseNumber?: string;
137
+ city: string; postalCode: string; country: string; phone?: string; email?: string;
138
+ };
139
+
140
+ /** An event time in milliseconds since 1970 from seconds, milliseconds or an ISO date; null when unreadable. */
141
+ export function toMilliseconds(value: unknown): number | null;
142
+
135
143
  export interface SendcloudOptions {
136
144
  publicKey: Secret;
137
145
  secretKey: Secret;
138
146
  /** The integration's "Webhook Signature Key" when it has one; otherwise webhooks are signed with secretKey. */
139
147
  webhookSecret?: Secret;
140
- /** The sender: an address saved in Sendcloud, or the full address. `country` is required in both cases. */
141
- sender: { addressId: number; country: string } | {
142
- name: string; companyName?: string; line1: string; line2?: string; houseNumber?: string;
143
- city: string; postalCode: string; country: string; phone?: string; email?: string;
144
- };
148
+ /**
149
+ * The sender: an address saved in Sendcloud, or the full address. `country` is required in both cases.
150
+ * A value, or a function read on every call (change the address without creating a new carrier).
151
+ */
152
+ sender: Sender | null | (() => Sender | null | undefined | Promise<Sender | null | undefined>);
145
153
  fetch?: typeof fetch;
146
154
  baseUrl?: string;
147
155
  /** Default 20 000. */
@@ -150,15 +158,16 @@ export interface SendcloudOptions {
150
158
  retry?: { attempts?: number; baseDelayMs?: number; maxDelayMs?: number; sleep?: (ms: number) => Promise<void> };
151
159
  /** Options of @astratra/resilience createCircuitBreaker. */
152
160
  breaker?: { failureThreshold?: number; recoveryMs?: number; now?: () => number };
153
- /** Labels on 'sendcloud:letter' (unstamped letter): nothing is posted. */
154
- testMode?: boolean;
161
+ /** Labels on 'sendcloud:letter' (unstamped letter): nothing is posted. A value, or a function read on every call. */
162
+ testMode?: boolean | (() => boolean | Promise<boolean>);
155
163
  /** Default 120; false disables the service point cache. */
156
164
  servicePointsCacheSeconds?: number | false;
157
165
  }
158
166
 
159
167
  export class SendcloudCarrier extends Carrier {
160
168
  constructor(options: SendcloudOptions);
161
- readonly testMode: boolean;
169
+ /** The test mode as given: a boolean, or null when it is a function (read it with status()). */
170
+ readonly testMode: boolean | null;
162
171
  status(): Promise<{ configured: boolean; missing: string[]; testMode: boolean }>;
163
172
  verifySignature(rawBody: Buffer, signature: string | undefined): Promise<boolean>;
164
173
  }
@@ -188,4 +197,12 @@ export function createCarrierWebhook(options: {
188
197
  onIncident?: ParcelHandler;
189
198
  signatureHeader?: string;
190
199
  logger?: WebhookLogger;
191
- }): WebhookHandler;
200
+ /** With an event log that has prune(): handled events older than this are deleted, at most once per pruneEveryMs. Default 90 days; false disables it. */
201
+ pruneOlderThanMs?: number | false;
202
+ /** Default 24 h. */
203
+ pruneEveryMs?: number;
204
+ now?: () => number;
205
+ }): WebhookHandler & {
206
+ /** Waits for a prune in progress (tests, graceful shutdown). */
207
+ settled(): Promise<void>;
208
+ };
package/src/sendcloud.js CHANGED
@@ -37,6 +37,20 @@ const cents = (value) => {
37
37
  return Number.isFinite(n) ? Math.round(n * 100) : null;
38
38
  };
39
39
 
40
+ /**
41
+ * An event time in MILLISECONDS since 1970, whatever unit arrived (seconds or milliseconds, number or
42
+ * numeric string, ISO date): below 10^12 a number is read as seconds (10^12 ms is 2001; 10^12 s is
43
+ * year 33 658). null when unreadable.
44
+ */
45
+ function toMilliseconds(value) {
46
+ if (value === null || value === undefined || value === '') return null;
47
+ const n = Number(value);
48
+ if (Number.isFinite(n)) return n > 0 ? Math.round(n < 1e12 ? n * 1000 : n) : null;
49
+ if (typeof value !== 'string') return null;
50
+ const parsed = Date.parse(value);
51
+ return Number.isFinite(parsed) ? parsed : null;
52
+ }
53
+
40
54
  /** Any failure turned into a ShippingError; `whenRefused` says what a 4xx means for this call. */
41
55
  function toShippingError(error, whenRefused) {
42
56
  if (error instanceof ShippingError && error.code !== CODES.REJECTED) return error;
@@ -71,13 +85,14 @@ class SendcloudCarrier extends Carrier {
71
85
  * @param {string|Function} options.publicKey
72
86
  * @param {string|Function} options.secretKey
73
87
  * @param {string|Function} [options.webhookSecret] the "Webhook Signature Key" when the integration has one; else the secret key
74
- * @param {object} options.sender { addressId, country } (a sender address saved in Sendcloud) or { name, line1, city, postalCode, country, … }
88
+ * @param {object|Function} options.sender { addressId, country } (a sender address saved in Sendcloud) or { name, line1, city, postalCode, country, … };
89
+ * a value, or a function read on every call (the shop changes its address without a restart)
75
90
  * @param {Function} [options.fetch] injectable (tests)
76
91
  * @param {string} [options.baseUrl]
77
92
  * @param {number} [options.timeoutMs] default 20 000
78
93
  * @param {object} [options.retry] options of @astratra/resilience retry (tests: { baseDelayMs: 0 })
79
94
  * @param {object} [options.breaker] options of createCircuitBreaker
80
- * @param {boolean} [options.testMode] labels on "sendcloud:letter": nothing is posted
95
+ * @param {boolean|Function} [options.testMode] labels on "sendcloud:letter": nothing is posted (a value, or a function read on every call)
81
96
  * @param {number|false} [options.servicePointsCacheSeconds] default 120; false disables the cache
82
97
  */
83
98
  constructor(options = {}) {
@@ -85,14 +100,12 @@ class SendcloudCarrier extends Carrier {
85
100
  this.publicKey = options.publicKey;
86
101
  this.secretKey = options.secretKey;
87
102
  this.webhookSecret = options.webhookSecret;
88
- this.sender = fromAddress(options.sender);
89
- /* Shipping options need the departure country, also with a saved sender address. */
90
- this.senderCountry = country(options.sender && options.sender.country);
103
+ this.senderOption = options.sender;
91
104
  this.fetchImpl = options.fetch || globalThis.fetch;
92
105
  this.baseUrl = options.baseUrl || SENDCLOUD_API_URL;
93
106
  this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
94
107
  this.retryOptions = options.retry || {};
95
- this.testMode = Boolean(options.testMode);
108
+ this.testModeOption = options.testMode;
96
109
  this.breaker = createCircuitBreaker({
97
110
  name: 'sendcloud', failureThreshold: 5, recoveryMs: 30_000, ...options.breaker, isFailure: isOutage
98
111
  });
@@ -102,13 +115,28 @@ class SendcloudCarrier extends Carrier {
102
115
 
103
116
  get name() { return 'sendcloud'; }
104
117
 
118
+ /** The test mode as given: a boolean, or null when it is a function (read it with status()). */
119
+ get testMode() { return typeof this.testModeOption === 'function' ? null : Boolean(this.testModeOption); }
120
+
121
+ async #isTestMode() {
122
+ return Boolean(typeof this.testModeOption === 'function' ? await this.testModeOption() : this.testModeOption);
123
+ }
124
+
125
+ /** The sender, read on every call: { from: Sendcloud's from_address or null, country }. */
126
+ async #sender() {
127
+ const sender = typeof this.senderOption === 'function' ? await this.senderOption() : this.senderOption;
128
+ /* Shipping options need the departure country, also with a saved sender address. */
129
+ return { from: fromAddress(sender), country: country(sender && sender.country) };
130
+ }
131
+
105
132
  /** { configured, missing, testMode } — names of what is missing, never a value. */
106
133
  async status() {
107
134
  const missing = [];
108
135
  if (!(await read(this.publicKey))) missing.push('publicKey');
109
136
  if (!(await read(this.secretKey))) missing.push('secretKey');
110
- if (!this.sender || !/^[A-Z]{2}$/.test(this.senderCountry)) missing.push('sender');
111
- return { configured: missing.length === 0, missing, testMode: this.testMode };
137
+ const sender = await this.#sender();
138
+ if (!sender.from || !/^[A-Z]{2}$/.test(sender.country)) missing.push('sender');
139
+ return { configured: missing.length === 0, missing, testMode: await this.#isTestMode() };
112
140
  }
113
141
 
114
142
  async #keys() {
@@ -165,9 +193,10 @@ class SendcloudCarrier extends Carrier {
165
193
  if (!/^[A-Z]{2}$/.test(destination) || !(Number.isFinite(weightGrams) && weightGrams > 0)) {
166
194
  throw new ShippingError(CODES.INVALID_INPUT);
167
195
  }
168
- if (!this.senderCountry || !/^[A-Z]{2}$/.test(this.senderCountry)) throw new ShippingError(CODES.NOT_CONFIGURED);
196
+ const sender = await this.#sender();
197
+ if (!/^[A-Z]{2}$/.test(sender.country)) throw new ShippingError(CODES.NOT_CONFIGURED);
169
198
  const body = {
170
- from_address: { country_code: this.senderCountry },
199
+ from_address: { country_code: sender.country },
171
200
  to_address: { country_code: destination, ...(postalCode ? { postal_code: String(postalCode) } : {}) },
172
201
  parcels: [{ weight: { value: kilograms(weightGrams), unit: 'kg' } }],
173
202
  calculate_quotes: true,
@@ -204,14 +233,16 @@ class SendcloudCarrier extends Carrier {
204
233
  async createLabel({ orderNumber, reference, recipient = {}, weightGrams, method, servicePointId = null } = {}) {
205
234
  const destination = country(recipient.country);
206
235
  const code = method && (method.code ?? method.id);
236
+ const testMode = await this.#isTestMode();
207
237
  if (!recipient.name || !recipient.line1 || !recipient.city || !recipient.postalCode || !/^[A-Z]{2}$/.test(destination)
208
- || !(Number.isFinite(weightGrams) && weightGrams > 0) || (!code && !this.testMode) || !orderNumber) {
238
+ || !(Number.isFinite(weightGrams) && weightGrams > 0) || (!code && !testMode) || !orderNumber) {
209
239
  throw new ShippingError(CODES.INVALID_INPUT);
210
240
  }
211
- if (!this.sender) throw new ShippingError(CODES.NOT_CONFIGURED);
212
- const optionCode = this.testMode ? TEST_SHIPPING_OPTION : String(code);
241
+ const sender = await this.#sender();
242
+ if (!sender.from) throw new ShippingError(CODES.NOT_CONFIGURED);
243
+ const optionCode = testMode ? TEST_SHIPPING_OPTION : String(code);
213
244
  const body = {
214
- from_address: this.sender,
245
+ from_address: sender.from,
215
246
  to_address: {
216
247
  name: recipient.name,
217
248
  address_line_1: recipient.line1,
@@ -227,7 +258,7 @@ class SendcloudCarrier extends Carrier {
227
258
  parcels: [{ weight: { value: kilograms(weightGrams), unit: 'kg' } }],
228
259
  order_number: String(orderNumber),
229
260
  ...(reference ? { external_reference_id: String(reference) } : {}),
230
- ...(servicePointId && !this.testMode ? { to_service_point: { id: String(servicePointId) } } : {})
261
+ ...(servicePointId && !testMode ? { to_service_point: { id: String(servicePointId) } } : {})
231
262
  };
232
263
  let response;
233
264
  try {
@@ -251,7 +282,7 @@ class SendcloudCarrier extends Carrier {
251
282
  /* The label itself, when Sendcloud returns it inline (one parcel): no second request needed. */
252
283
  label: typeof parcel.label_file === 'string' && parcel.label_file ? Buffer.from(parcel.label_file, 'base64') : null,
253
284
  alreadyExisted: response.status === 409,
254
- testMode: this.testMode
285
+ testMode
255
286
  };
256
287
  }
257
288
 
@@ -362,19 +393,19 @@ class SendcloudCarrier extends Carrier {
362
393
 
363
394
  /**
364
395
  * parcel_status_changed only; anything else is null (acknowledged, nothing to do). Webhooks can
365
- * arrive out of order: `timestamp` says which status is the latest.
396
+ * arrive out of order: `timestamp` (always milliseconds) says which status is the latest.
366
397
  */
367
398
  readEvent(json) {
368
399
  if (!json || json.action !== 'parcel_status_changed' || !json.parcel || !json.parcel.id) return null;
369
400
  const message = String(json.parcel.status?.message ?? '');
370
- const timestamp = Number(json.timestamp);
401
+ const timestamp = toMilliseconds(json.timestamp);
371
402
  return {
372
403
  parcelId: Number(json.parcel.id),
373
404
  trackingNumber: String(json.parcel.tracking_number ?? ''),
374
405
  trackingUrl: String(json.parcel.tracking_url ?? ''),
375
406
  message,
376
407
  stage: classifySendcloudStatus(message),
377
- timestamp: Number.isFinite(timestamp) ? timestamp : null
408
+ timestamp
378
409
  };
379
410
  }
380
411
  }
@@ -383,4 +414,4 @@ function createSendcloudCarrier(options) {
383
414
  return new SendcloudCarrier(options);
384
415
  }
385
416
 
386
- module.exports = { SendcloudCarrier, createSendcloudCarrier, SENDCLOUD_API_URL, TEST_SHIPPING_OPTION };
417
+ module.exports = { SendcloudCarrier, createSendcloudCarrier, SENDCLOUD_API_URL, TEST_SHIPPING_OPTION, toMilliseconds };
package/src/webhook.js CHANGED
@@ -15,6 +15,8 @@ const { createHash } = require('node:crypto');
15
15
  const { createWebhookHandler } = require('@astratra/payments');
16
16
 
17
17
  const SIGNATURE_HEADER = 'sendcloud-signature';
18
+ const DEFAULT_PRUNE_OLDER_THAN_MS = 90 * 24 * 3600_000;
19
+ const DEFAULT_PRUNE_EVERY_MS = 24 * 3600_000;
18
20
 
19
21
  /**
20
22
  * @param {object} options
@@ -26,6 +28,11 @@ const SIGNATURE_HEADER = 'sendcloud-signature';
26
28
  * @param {Function} [options.onIncident] (event, tools)
27
29
  * @param {string} [options.signatureHeader] default 'sendcloud-signature'
28
30
  * @param {object} [options.logger]
31
+ * @param {number|false} [options.pruneOlderThanMs] when the event log has prune(): handled events older
32
+ * than this are deleted, at most once per `pruneEveryMs`, after a webhook is answered. Default 90 days;
33
+ * false disables it (prune it yourself).
34
+ * @param {number} [options.pruneEveryMs] default 24 h
35
+ * @param {Function} [options.now] for tests
29
36
  */
30
37
  function createCarrierWebhook(options = {}) {
31
38
  const carrier = options.carrier;
@@ -34,9 +41,28 @@ function createCarrierWebhook(options = {}) {
34
41
  }
35
42
  const header = String(options.signatureHeader || SIGNATURE_HEADER).toLowerCase();
36
43
  const byStage = { picked_up: options.onPickedUp, delivered: options.onDelivered, incident: options.onIncident };
44
+ const eventLog = options.eventLog;
45
+ const pruneOlderThanMs = options.pruneOlderThanMs === undefined ? DEFAULT_PRUNE_OLDER_THAN_MS : options.pruneOlderThanMs;
46
+ const pruneEveryMs = options.pruneEveryMs || DEFAULT_PRUNE_EVERY_MS;
47
+ const now = options.now || Date.now;
48
+ const logger = options.logger || {};
49
+ let lastPrune = null;
50
+ let pruning = null;
51
+
52
+ /* The event log only grows: old handled events are deleted now and then, never on the answer's path. */
53
+ function maybePrune() {
54
+ if (!pruneOlderThanMs || !eventLog || typeof eventLog.prune !== 'function' || pruning) return null;
55
+ if (lastPrune !== null && now() - lastPrune < pruneEveryMs) return null;
56
+ lastPrune = now();
57
+ pruning = Promise.resolve()
58
+ .then(() => eventLog.prune(pruneOlderThanMs))
59
+ .catch((error) => { if (logger.warn) logger.warn(`[shipping] event log prune failed: ${error.message}`); })
60
+ .finally(() => { pruning = null; });
61
+ return pruning;
62
+ }
37
63
 
38
64
  const handler = createWebhookHandler({
39
- eventLog: options.eventLog,
65
+ eventLog,
40
66
  logger: options.logger,
41
67
  eventId: (event) => event.id,
42
68
  async verify({ payload, headers }) {
@@ -72,7 +98,19 @@ function createCarrierWebhook(options = {}) {
72
98
  }
73
99
  }
74
100
  });
75
- return handler;
101
+ async function receive(request) {
102
+ const answer = await handler.receive(request);
103
+ maybePrune();
104
+ return answer;
105
+ }
106
+ function middleware(req, res) {
107
+ return receive({ payload: req.body, headers: req.headers }).then(({ status, body }) => {
108
+ res.status(status).json(body);
109
+ });
110
+ }
111
+ /** Waits for a prune in progress (tests, graceful shutdown). */
112
+ const settled = () => pruning || Promise.resolve();
113
+ return { receive, middleware, sideEffect: handler.sideEffect, settled };
76
114
  }
77
115
 
78
116
  module.exports = { createCarrierWebhook, SIGNATURE_HEADER };