@astratra/shipping 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.fr.md ADDED
@@ -0,0 +1,184 @@
1
+ # @astratra/shipping
2
+
3
+ Les étiquettes d'expédition sans les pièges : un contrat de transporteur, un
4
+ adaptateur Sendcloud (étiquettes, points relais, suivi), le webhook de suivi
5
+ signé et protégé contre les rejeux, et un mode test sans frais.
6
+
7
+ Né du code de Boutique Roro, pour toutes les boutiques : le paquet ne connaît
8
+ ni commandes, ni tables, ni prix. Il parle au transporteur ; la boutique décide.
9
+
10
+ ```bash
11
+ npm install @astratra/shipping
12
+ ```
13
+
14
+ ## Ce qu'il fait, et les pièges qu'il évite
15
+
16
+ - **Créer deux fois, c'est payer deux fois.** Seules les lectures sont relancées
17
+ après une panne. `createLabel` n'est jamais relancé : une seconde tentative
18
+ achèterait une seconde étiquette.
19
+ - **Un refus n'est pas une panne.** Un 4xx du transporteur (adresse invalide,
20
+ poids hors limite) est une réponse : il ne compte pas pour le disjoncteur et
21
+ n'est pas relancé. Seules les coupures et les 5xx le sont.
22
+ - **Les clés ne fuient pas.** Elles viennent des options (une valeur, ou une
23
+ fonction relue à chaque appel : rotation sans redémarrage), jamais d'un
24
+ fichier ni de l'environnement, jamais dans une erreur.
25
+ - **Le corps brut signé.** La signature du webhook se vérifie sur les octets
26
+ reçus, en temps constant. Monte le webhook **avant** tout analyseur JSON.
27
+ - **Un renvoi n'agit qu'une fois.** Le webhook passe par le tuyau de
28
+ `@astratra/payments` : l'événement (empreinte SHA-256 du corps brut) est
29
+ réservé avant d'être traité, libéré en cas d'échec pour que le renvoi passe.
30
+ - **« Étiquette créée » n'est pas « colis pris en charge ».** Seul un scan du
31
+ transporteur fait passer un colis à `picked_up`.
32
+
33
+ ## Le transporteur Sendcloud (API v3)
34
+
35
+ ```js
36
+ const { createSendcloudCarrier, messageFor } = require('@astratra/shipping');
37
+
38
+ const carrier = createSendcloudCarrier({
39
+ publicKey: () => coffre.lire('SENDCLOUD_PUBLIC_KEY'),
40
+ secretKey: () => coffre.lire('SENDCLOUD_SECRET_KEY'),
41
+ webhookSecret: () => coffre.lire('SENDCLOUD_WEBHOOK_KEY'), // si l'intégration a une « Webhook Signature Key »
42
+ sender: { addressId: 12345, country: 'FR' }, // adresse d'expédition enregistrée chez Sendcloud
43
+ testMode: process.env.NODE_ENV !== 'production'
44
+ });
45
+
46
+ await carrier.status(); // { configured, missing: ['secretKey', 'sender'], testMode } — jamais une valeur
47
+
48
+ const options = await carrier.shippingMethods({ country: 'FR', postalCode: '69003', weightGrams: 1250 });
49
+ // [{ id: 'colissimo:home/signature', name, carrier, servicePointRequired, priceCents }]
50
+
51
+ const points = await carrier.servicePoints({
52
+ country: 'FR', postalCode: '13002', carriers: ['mondial_relay', 'colissimo'], limit: 10
53
+ });
54
+ const optionsRelais = await carrier.shippingMethods({ country: 'FR', weightGrams: 1250, servicePointId: points[0].id });
55
+
56
+ const envoi = await carrier.createLabel({
57
+ orderNumber: 'R-1042',
58
+ reference: 'commande-R-1042', // unique : la renvoyer rend le premier envoi, sans racheter d'étiquette
59
+ recipient: { name: 'Awa Diallo', line1: '12 rue des Lilas', city: 'Lyon', postalCode: '69003', country: 'FR', email: 'awa@example.com' },
60
+ weightGrams: 1250,
61
+ method: options[0]
62
+ });
63
+ // { shipmentId, parcelId, trackingNumber, trackingUrl, carrier, service, label, alreadyExisted, testMode }
64
+ // envoi.label : le PDF de l'étiquette, revenu avec l'envoi (un seul colis) — pas de seconde demande
65
+
66
+ const { content } = await carrier.downloadLabel({ parcelId: envoi.parcelId, format: 'a4' }); // A4, A5 ou A6 (par défaut)
67
+ await carrier.cancelLabel({ shipmentId: envoi.shipmentId }); // { status: 'cancelled' | 'requested' }
68
+ ```
69
+
70
+ - **L'expéditeur** (`sender`) : l'identifiant d'une adresse enregistrée chez
71
+ Sendcloud avec son pays, ou l'adresse complète (`name`, `line1`, `city`,
72
+ `postalCode`, `country`…). Sans lui, `status()` signale `sender` manquant.
73
+ - **Les options d'expédition** sont des codes stables (`colissimo:home/signature`,
74
+ `mondial_relay:point`…), jamais des numéros qui changent. `priceCents` est le
75
+ devis de Sendcloud : tes prix restent les tiens.
76
+ - **La référence** (`reference`, unique par compte) protège contre le double
77
+ achat : la même référence annoncée deux fois rend le premier envoi
78
+ (`alreadyExisted: true`).
79
+ - **Un refus du transporteur** (code postal invalide…) revient de Sendcloud avec
80
+ un statut 201 et une erreur : le paquet en fait une erreur `rejected`.
81
+ - **L'annulation** porte sur l'envoi (`shipmentId`). `requested` : Sendcloud
82
+ surveille l'envoi et l'annule s'il ne bouge pas. Refusée si le colis est livré
83
+ ou annoncé depuis plus de 42 jours ; « déjà en cours d'annulation » compte
84
+ comme annulé.
85
+ - `servicePoints` : par code postal et/ou ville, ou par coordonnées ; les
86
+ transporteurs choisis (codes Sendcloud), sinon ceux activés sur ton
87
+ intégration ; rayon (`radiusMeters`, 10 km, de 100 m à 50 km) et nombre
88
+ (`limit`, 15) ; du plus proche au plus loin ; gardés 2 minutes
89
+ (`servicePointsCacheSeconds`, `false` pour couper).
90
+
91
+ ### Mode test
92
+
93
+ `testMode: true` crée chaque étiquette avec l'option `sendcloud:letter` (lettre
94
+ non affranchie) : rien n'est posté et aucun port n'est facturé (Sendcloud peut
95
+ compter des frais de traitement : voir sa documentation). L'option et le point
96
+ relais demandés sont ignorés, et `testMode` vaut `true` dans la réponse.
97
+
98
+ ## Les erreurs
99
+
100
+ Toute erreur est une `ShippingError` avec un **code stable**, un `status` HTTP à
101
+ répondre, et le `providerStatus` du transporteur — jamais son corps ni une clé :
102
+
103
+ | Code | Statut | Quand |
104
+ |---|---|---|
105
+ | `not_configured` | 503 | une clé manque |
106
+ | `credentials_refused` | 502 | 401 ou 403 du transporteur |
107
+ | `unavailable` | 503 | coupure, 5xx, disjoncteur ouvert |
108
+ | `rejected` | 422 | étiquette refusée (adresse, poids, méthode) |
109
+ | `no_method` | 422 | aucune méthode pour ce pays et ce poids |
110
+ | `not_found` | 404 | étiquette introuvable |
111
+ | `cancel_refused` | 409 | colis sans doute déjà pris en charge |
112
+ | `service_points_unavailable` | 503 | recherche de points relais refusée |
113
+ | `invalid_input` | 422 | informations incomplètes ou invalides |
114
+ | `unexpected_response` | 502 | réponse illisible |
115
+
116
+ `messageFor(codeOuErreur, 'fr' | 'en')` donne la phrase à montrer (catalogue de
117
+ `@astratra/i18n-server`) ; une langue inconnue donne le français.
118
+
119
+ ## Le webhook de suivi
120
+
121
+ ```js
122
+ const express = require('express');
123
+ const { Pool } = require('pg');
124
+ const { createPostgresEventLog, postgresEventLogSchema } = require('@astratra/payments');
125
+ const { createCarrierWebhook } = require('@astratra/shipping');
126
+
127
+ const pool = new Pool();
128
+ await pool.query(postgresEventLogSchema({ table: 'sendcloud_events' }));
129
+
130
+ const webhook = createCarrierWebhook({
131
+ carrier,
132
+ eventLog: createPostgresEventLog(pool, { table: 'sendcloud_events' }),
133
+ onEvent: async (colis) => { /* chaque statut : noter colis.message, la date du dernier scan… */ },
134
+ onPickedUp: async (colis, { sideEffect }) => {
135
+ await marquerPrisEnCharge(colis.parcelId);
136
+ await sideEffect('e-mail', () => envoyerEmailExpedition(colis)); // ne fait jamais échouer le webhook
137
+ },
138
+ onDelivered: async (colis) => marquerLivre(colis.parcelId),
139
+ onIncident: async (colis) => signalerIncident(colis.parcelId, colis.message)
140
+ });
141
+
142
+ // AVANT express.json : la signature porte sur les octets reçus.
143
+ app.post('/api/transporteurs/sendcloud/webhook', express.raw({ type: 'application/json', limit: '1mb' }), webhook.middleware);
144
+ ```
145
+
146
+ - En-tête `sendcloud-signature` : HMAC-SHA256 du corps brut, en hexadécimal.
147
+ - Signature fausse, corps déjà analysé ou illisible : **400**, pour que Sendcloud
148
+ ne renvoie pas indéfiniment. Sans clé secrète, tout est refusé.
149
+ - Un autre type d'événement que `parcel_status_changed` : **200**, ignoré.
150
+ - Un renvoi du même corps : **200** `duplicate`, sans rien refaire.
151
+ - Une erreur dans tes fonctions : **500** et l'événement est libéré, le renvoi
152
+ de Sendcloud sera traité.
153
+ - `stage` de l'événement : `picked_up`, `delivered`, `incident` ou `null`
154
+ (`classifySendcloudStatus`). Une tentative de livraison ratée ou un retard
155
+ reste `picked_up` : ce n'est pas un incident définitif.
156
+ - 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.
158
+ - La signature utilise la « Webhook Signature Key » de l'intégration
159
+ (`webhookSecret`) quand elle existe, sinon la clé secrète.
160
+
161
+ ## Écrire un autre transporteur
162
+
163
+ Étends `Carrier` et implémente : `name`, `status()`, `shippingMethods()`,
164
+ `createLabel()`, `downloadLabel()`, `cancelLabel()`, `servicePoints()`,
165
+ `verifySignature()`, `readEvent()`. `createCarrierWebhook` fonctionne avec
166
+ n'importe quel transporteur (`signatureHeader` en option).
167
+
168
+ ## Ce que ce paquet ne fait pas
169
+
170
+ - Pas de prix de livraison, de zones ni de pays livrés : c'est la boutique.
171
+ - Pas de commandes, pas de tables (sauf le journal des événements, fourni par
172
+ `@astratra/payments`), pas d'e-mails.
173
+ - Pas de limite de débit sur la recherche publique de points relais : mets-la
174
+ devant ta route.
175
+
176
+ ## Tests
177
+
178
+ ```bash
179
+ npm test --workspace @astratra/shipping
180
+ ```
181
+
182
+ Aucun appel réseau : un faux Sendcloud répond aux requêtes et les enregistre
183
+ (relances des lectures seulement, disjoncteur, clés jamais dans les erreurs,
184
+ mode test, points relais, signature, rejeux concurrents, échec puis renvoi).
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ # @astratra/shipping
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shipping labels without the traps: a carrier contract, a Sendcloud adapter
4
+ (labels, service points, tracking), the signed tracking webhook with replay
5
+ protection, and a free test mode.
6
+
7
+ Extracted from Boutique Roro, for every shop: the package knows no orders, no
8
+ tables and no prices. It talks to the carrier; the shop decides.
9
+
10
+ [Version française](README.fr.md)
11
+
12
+ ```bash
13
+ npm install @astratra/shipping
14
+ ```
15
+
16
+ ## What it does, and the traps it avoids
17
+
18
+ - **Creating twice is paying twice.** Only reads are retried after an outage.
19
+ `createLabel` is never retried: a second attempt would buy a second label.
20
+ - **A refusal is not an outage.** A carrier 4xx (invalid address, weight out of
21
+ range) is an answer: it does not count against the circuit breaker and is not
22
+ retried. Only network failures and 5xx are.
23
+ - **Keys do not leak.** They come from options (a value, or a function read on
24
+ every call: rotation without restart), never from a file or the environment,
25
+ never inside an error.
26
+ - **The signed raw body.** The webhook signature is checked on the bytes
27
+ received, in constant time. Mount the webhook **before** any JSON parser.
28
+ - **A resend acts once.** The webhook runs on `@astratra/payments`' pipeline:
29
+ the event (SHA-256 of the raw body) is reserved before it is handled, and
30
+ released on failure so the resend goes through.
31
+ - **"Label created" is not "parcel picked up".** Only a carrier scan moves a
32
+ parcel to `picked_up`.
33
+
34
+ ## The Sendcloud carrier (API v3)
35
+
36
+ ```js
37
+ const { createSendcloudCarrier, messageFor } = require('@astratra/shipping');
38
+
39
+ const carrier = createSendcloudCarrier({
40
+ publicKey: () => vault.read('SENDCLOUD_PUBLIC_KEY'),
41
+ secretKey: () => vault.read('SENDCLOUD_SECRET_KEY'),
42
+ webhookSecret: () => vault.read('SENDCLOUD_WEBHOOK_KEY'), // when the integration has a "Webhook Signature Key"
43
+ sender: { addressId: 12345, country: 'FR' }, // a sender address saved in Sendcloud
44
+ testMode: process.env.NODE_ENV !== 'production'
45
+ });
46
+
47
+ await carrier.status(); // { configured, missing, testMode } — never a value
48
+
49
+ const options = await carrier.shippingMethods({ country: 'FR', postalCode: '69003', weightGrams: 1250 });
50
+ const points = await carrier.servicePoints({ country: 'FR', postalCode: '13002', carriers: ['mondial_relay', 'colissimo'], limit: 10 });
51
+ const shipment = await carrier.createLabel({
52
+ orderNumber: 'R-1042',
53
+ reference: 'order-R-1042', // unique: announcing it again returns the first shipment, no second label
54
+ recipient: { name: 'Awa Diallo', line1: '12 rue des Lilas', city: 'Lyon', postalCode: '69003', country: 'FR' },
55
+ weightGrams: 1250,
56
+ method: options[0]
57
+ });
58
+ // shipment.label: the label PDF, returned with the shipment (one parcel) — no second request
59
+ const { content } = await carrier.downloadLabel({ parcelId: shipment.parcelId, format: 'a4' }); // A4, A5 or A6 (default)
60
+ await carrier.cancelLabel({ shipmentId: shipment.shipmentId }); // { status: 'cancelled' | 'requested' }
61
+ ```
62
+
63
+ - Shipping options are stable codes (`colissimo:home/signature`), never ids that
64
+ change. `priceCents` is Sendcloud's quote: your prices stay yours.
65
+ - `reference` (unique per account) guards against buying twice: the same
66
+ reference announced again returns the first shipment (`alreadyExisted`).
67
+ - A carrier refusal comes back as 201 with an error: it becomes `rejected`.
68
+ - Cancelling works on the shipment. `requested`: Sendcloud watches it and
69
+ cancels it if nothing moves. Refused once delivered or 42 days after
70
+ announcement; "already being cancelled" counts as cancelled.
71
+ - `servicePoints`: by postal code and/or city, or coordinates; the chosen
72
+ carriers, otherwise those enabled on the integration; `radiusMeters`
73
+ (10 km, 100 m to 50 km) and `limit` (15); nearest first; cached 2 minutes.
74
+ - **Test mode** (`testMode: true`) ships with the option `sendcloud:letter`
75
+ (unstamped letter): nothing is posted and no postage is charged (Sendcloud
76
+ may charge a processing fee).
77
+
78
+ ## Errors
79
+
80
+ Every error is a `ShippingError` with a **stable code** (`not_configured`,
81
+ `credentials_refused`, `unavailable`, `rejected`, `no_method`, `not_found`,
82
+ `cancel_refused`, `service_points_unavailable`, `invalid_input`,
83
+ `unexpected_response`), an HTTP `status` to answer with and the carrier's
84
+ `providerStatus` — never its body nor a key. `messageFor(codeOrError, 'fr' | 'en')`
85
+ gives the sentence to show (an `@astratra/i18n-server` catalog).
86
+
87
+ ## The tracking webhook
88
+
89
+ ```js
90
+ const { createPostgresEventLog } = require('@astratra/payments');
91
+ const { createCarrierWebhook } = require('@astratra/shipping');
92
+
93
+ const webhook = createCarrierWebhook({
94
+ carrier,
95
+ eventLog: createPostgresEventLog(pool, { table: 'sendcloud_events' }),
96
+ onEvent: async (parcel) => { /* every status */ },
97
+ onPickedUp: async (parcel, { sideEffect }) => {
98
+ await markPickedUp(parcel.parcelId);
99
+ await sideEffect('email', () => sendShippingEmail(parcel)); // never fails the webhook
100
+ },
101
+ onDelivered: async (parcel) => markDelivered(parcel.parcelId),
102
+ onIncident: async (parcel) => reportIncident(parcel.parcelId, parcel.message)
103
+ });
104
+
105
+ // BEFORE express.json: the signature covers the received bytes.
106
+ app.post('/webhooks/sendcloud', express.raw({ type: 'application/json', limit: '1mb' }), webhook.middleware);
107
+ ```
108
+
109
+ The signature is the HMAC-SHA256 of the raw body (hex), with the integration's
110
+ "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.
112
+ Wrong signature, parsed or unreadable body: 400 (no endless retries). Another
113
+ event type: 200, ignored. The same body again: 200 `duplicate`. An error in your
114
+ handlers: 500 and the event is released, so Sendcloud's resend is handled.
115
+
116
+ ## Another carrier
117
+
118
+ Extend `Carrier` and implement `name`, `status()`, `shippingMethods()`,
119
+ `createLabel()`, `downloadLabel()`, `cancelLabel()`, `servicePoints()`,
120
+ `verifySignature()` and `readEvent()`. `createCarrierWebhook` works with any
121
+ carrier (`signatureHeader` option).
122
+
123
+ ## Not in this package
124
+
125
+ Delivery prices, zones and countries served, orders, tables (except the event
126
+ log from `@astratra/payments`), emails, and rate limiting of a public service
127
+ point search: those belong to the shop.
128
+
129
+ ## Tests
130
+
131
+ ```bash
132
+ npm test --workspace @astratra/shipping
133
+ ```
134
+
135
+ No network: a fake Sendcloud answers and records every request.
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@astratra/shipping",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
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
+ "engines": {
6
+ "node": ">=20"
7
+ },
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "type": "commonjs",
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "test": "jest"
16
+ },
17
+ "jest": {
18
+ "testMatch": [
19
+ "**/__tests__/**/*.test.js"
20
+ ]
21
+ },
22
+ "keywords": [
23
+ "astratra",
24
+ "shipping",
25
+ "sendcloud",
26
+ "labels",
27
+ "service-points",
28
+ "tracking",
29
+ "webhook"
30
+ ],
31
+ "license": "MIT",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@astratra/i18n-server": "^1.0.0",
37
+ "@astratra/payments": "^1.1.0",
38
+ "@astratra/resilience": "^1.1.0"
39
+ },
40
+ "devDependencies": {
41
+ "jest": "30.4.2"
42
+ }
43
+ }
package/src/carrier.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The contract every carrier (or aggregator) honours. Routes and screens only
3
+ * ever speak to this contract: changing aggregator means writing another
4
+ * implementation, nothing else.
5
+ *
6
+ * Vocabulary: "label created" is NOT "parcel picked up". Only a carrier event
7
+ * (first scan) moves a parcel to picked_up.
8
+ */
9
+ class Carrier {
10
+ /** Short name stored next to a parcel (for example "sendcloud"). */
11
+ get name() { throw new Error('Carrier.name is not implemented.'); }
12
+
13
+ /** { configured, missing: string[] } — never a key value. */
14
+ status() { throw new Error('Carrier.status() is not implemented.'); }
15
+
16
+ /** Methods for a destination country (ISO 3166-1 alpha-2) and a weight in grams. */
17
+ async shippingMethods(_query) { throw new Error('Carrier.shippingMethods() is not implemented.'); }
18
+
19
+ /** Creates the parcel and its label: { parcelId, trackingNumber, trackingUrl, carrier, service, testMode }. */
20
+ async createLabel(_input) { throw new Error('Carrier.createLabel() is not implemented.'); }
21
+
22
+ /** The label PDF: { content: Buffer, type: 'application/pdf' } (format 'a4' or 'a6'). */
23
+ async downloadLabel(_input) { throw new Error('Carrier.downloadLabel() is not implemented.'); }
24
+
25
+ /** { status: 'cancelled' | 'requested' }. */
26
+ async cancelLabel(_input) { throw new Error('Carrier.cancelLabel() is not implemented.'); }
27
+
28
+ /** Service points near an address or coordinates, nearest first. */
29
+ async servicePoints(_query) { throw new Error('Carrier.servicePoints() is not implemented.'); }
30
+
31
+ /** Checks a webhook signature on the RAW body, in constant time. */
32
+ verifySignature(_rawBody, _signature) { throw new Error('Carrier.verifySignature() is not implemented.'); }
33
+
34
+ /**
35
+ * Reads a tracking event: { parcelId, trackingNumber, trackingUrl, message, stage } or null for an
36
+ * event that is not a parcel status change. stage: 'picked_up' | 'delivered' | 'incident' | null.
37
+ */
38
+ readEvent(_json) { throw new Error('Carrier.readEvent() is not implemented.'); }
39
+ }
40
+
41
+ module.exports = { Carrier };
package/src/errors.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Shipping errors carry a stable CODE the application can act on, never the
3
+ * provider's raw body and never a key. The sentence shown to a person comes
4
+ * from messageFor(code, language), in French or English.
5
+ */
6
+ const { createMessageCatalog } = require('@astratra/i18n-server');
7
+
8
+ const CODES = Object.freeze({
9
+ NOT_CONFIGURED: 'not_configured',
10
+ CREDENTIALS_REFUSED: 'credentials_refused',
11
+ UNAVAILABLE: 'unavailable',
12
+ REJECTED: 'rejected',
13
+ NOT_FOUND: 'not_found',
14
+ CANCEL_REFUSED: 'cancel_refused',
15
+ NO_METHOD: 'no_method',
16
+ SERVICE_POINTS_UNAVAILABLE: 'service_points_unavailable',
17
+ INVALID_INPUT: 'invalid_input',
18
+ UNEXPECTED_RESPONSE: 'unexpected_response'
19
+ });
20
+
21
+ /* French is the source sentence; English its translation (i18n-server catalog). */
22
+ const SOURCES = {
23
+ not_configured: "Le transporteur n'est pas encore configuré. Saisissez le colis à la main pour l'instant.",
24
+ credentials_refused: 'Le transporteur a refusé les clés enregistrées. Vérifiez-les dans votre compte.',
25
+ unavailable: 'Le transporteur est momentanément indisponible. Réessayez dans un instant, ou saisissez le colis à la main.',
26
+ rejected: "Le transporteur a refusé cette demande. Vérifiez l'adresse de livraison, le poids et la méthode d'expédition.",
27
+ not_found: "Le transporteur ne trouve pas l'étiquette de ce colis. Elle a peut-être été annulée.",
28
+ cancel_refused: 'Le transporteur ne peut plus annuler cette étiquette : le colis est peut-être déjà pris en charge.',
29
+ no_method: "Aucune méthode d'expédition n'est proposée pour cette destination et ce poids.",
30
+ service_points_unavailable: 'Le choix du point relais est indisponible pour le moment.',
31
+ invalid_input: 'Les informations du colis sont incomplètes ou invalides.',
32
+ unexpected_response: 'Le transporteur a envoyé une réponse inattendue. Réessayez dans un instant.'
33
+ };
34
+ const ENGLISH = {
35
+ not_configured: 'The carrier is not configured yet. Enter the parcel by hand for now.',
36
+ credentials_refused: 'The carrier refused the saved keys. Check them in your account.',
37
+ unavailable: 'The carrier is temporarily unavailable. Try again in a moment, or enter the parcel by hand.',
38
+ rejected: 'The carrier refused this request. Check the delivery address, the weight and the shipping method.',
39
+ not_found: 'The carrier cannot find the label of this parcel. It may have been cancelled.',
40
+ cancel_refused: 'The carrier can no longer cancel this label: the parcel may already have been picked up.',
41
+ no_method: 'No shipping method is offered for this destination and weight.',
42
+ service_points_unavailable: 'Choosing a service point is unavailable for now.',
43
+ invalid_input: 'The parcel details are incomplete or invalid.',
44
+ unexpected_response: 'The carrier sent an unexpected answer. Try again in a moment.'
45
+ };
46
+
47
+ const catalog = createMessageCatalog({
48
+ languages: ['fr', 'en'],
49
+ defaultLanguage: 'fr',
50
+ messages: Object.fromEntries(Object.keys(SOURCES).map((code) => [SOURCES[code], { en: ENGLISH[code] }]))
51
+ });
52
+
53
+ /** The sentence for a code (or a ShippingError) in 'fr' or 'en'; French when the language is unknown. */
54
+ function messageFor(codeOrError, language = 'fr') {
55
+ const code = typeof codeOrError === 'string' ? codeOrError : codeOrError && codeOrError.code;
56
+ const source = SOURCES[code] || SOURCES.unexpected_response;
57
+ return catalog.translate(source, catalog.supports(language) ? language : 'fr');
58
+ }
59
+
60
+ /** HTTP status an application can answer with, per code. */
61
+ const STATUS = {
62
+ not_configured: 503, credentials_refused: 502, unavailable: 503, rejected: 422, not_found: 404,
63
+ cancel_refused: 409, no_method: 422, service_points_unavailable: 503, invalid_input: 422, unexpected_response: 502
64
+ };
65
+
66
+ class ShippingError extends Error {
67
+ /**
68
+ * @param {string} code one of CODES
69
+ * @param {{ providerStatus?: number, cause?: unknown }} [details] the provider's HTTP status, never its body
70
+ */
71
+ constructor(code, details = {}) {
72
+ super(ENGLISH[code] || ENGLISH.unexpected_response);
73
+ this.name = 'ShippingError';
74
+ this.code = code;
75
+ this.status = STATUS[code] || 502;
76
+ if (details.providerStatus !== undefined) this.providerStatus = details.providerStatus;
77
+ }
78
+ }
79
+
80
+ module.exports = { CODES, ShippingError, messageFor };
package/src/index.d.ts ADDED
@@ -0,0 +1,191 @@
1
+ import type { EventLog, WebhookHandler, WebhookLogger, Outcome } from '@astratra/payments';
2
+
3
+ /* ─────────────────── Errors ─────────────────── */
4
+
5
+ export const CODES: Readonly<{
6
+ NOT_CONFIGURED: 'not_configured';
7
+ CREDENTIALS_REFUSED: 'credentials_refused';
8
+ UNAVAILABLE: 'unavailable';
9
+ REJECTED: 'rejected';
10
+ NOT_FOUND: 'not_found';
11
+ CANCEL_REFUSED: 'cancel_refused';
12
+ NO_METHOD: 'no_method';
13
+ SERVICE_POINTS_UNAVAILABLE: 'service_points_unavailable';
14
+ INVALID_INPUT: 'invalid_input';
15
+ UNEXPECTED_RESPONSE: 'unexpected_response';
16
+ }>;
17
+ export type ShippingErrorCode = (typeof CODES)[keyof typeof CODES];
18
+
19
+ /** A stable code, an HTTP status to answer with, the provider's status — never its body nor a key. */
20
+ export class ShippingError extends Error {
21
+ constructor(code: ShippingErrorCode, details?: { providerStatus?: number });
22
+ code: ShippingErrorCode;
23
+ status: number;
24
+ providerStatus?: number;
25
+ }
26
+
27
+ /** The sentence for a code (or a ShippingError) in 'fr' or 'en'; French when the language is unknown. */
28
+ export function messageFor(codeOrError: ShippingErrorCode | string | ShippingError, language?: string): string;
29
+
30
+ /* ─────────────────── The carrier contract ─────────────────── */
31
+
32
+ export type ParcelStage = 'picked_up' | 'delivered' | 'incident';
33
+
34
+ export interface ShippingMethod {
35
+ /** Sendcloud: the shipping option code (for example 'colissimo:home/signature'). */
36
+ id: string;
37
+ name: string;
38
+ carrier: string;
39
+ servicePointRequired: boolean;
40
+ /** The provider's indicative price, in cents; null when unknown. */
41
+ priceCents: number | null;
42
+ }
43
+
44
+ export interface Recipient {
45
+ name: string;
46
+ line1: string;
47
+ line2?: string;
48
+ city: string;
49
+ postalCode: string;
50
+ /** ISO 3166-1 alpha-2. */
51
+ country: string;
52
+ phone?: string;
53
+ email?: string;
54
+ }
55
+
56
+ export interface Label {
57
+ /** The shipment, needed to cancel it. */
58
+ shipmentId: string;
59
+ /** The parcel, needed to download its label. */
60
+ parcelId: number;
61
+ trackingNumber: string;
62
+ trackingUrl: string;
63
+ carrier: string;
64
+ service: string;
65
+ /** The label PDF when the provider returns it with the shipment (one parcel); otherwise downloadLabel. */
66
+ label: Buffer | null;
67
+ /** The same `reference` was announced before: this is the first shipment, no new label was bought. */
68
+ alreadyExisted: boolean;
69
+ testMode: boolean;
70
+ }
71
+
72
+ export interface ServicePoint {
73
+ id: number;
74
+ carrier: string;
75
+ name: string;
76
+ address: string;
77
+ postalCode: string;
78
+ city: string;
79
+ country: string;
80
+ openingTimes: Record<string, unknown>;
81
+ distanceMeters: number | null;
82
+ }
83
+
84
+ export interface ParcelEvent {
85
+ parcelId: number;
86
+ trackingNumber: string;
87
+ trackingUrl: string;
88
+ /** The provider's status label. */
89
+ message: string;
90
+ stage: ParcelStage | null;
91
+ /** When the status changed (seconds); webhooks can arrive out of order. */
92
+ timestamp: number | null;
93
+ }
94
+
95
+ export class Carrier {
96
+ get name(): string;
97
+ status(): Promise<{ configured: boolean; missing: string[]; testMode?: boolean }> | { configured: boolean; missing: string[] };
98
+ shippingMethods(query: { country: string; postalCode?: string; weightGrams: number; servicePointId?: number | string | null }): Promise<ShippingMethod[]>;
99
+ createLabel(input: {
100
+ orderNumber: string;
101
+ /** Unique per account: announcing it again returns the first shipment instead of a second label. */
102
+ reference?: string;
103
+ recipient: Recipient;
104
+ weightGrams: number;
105
+ method: { id?: string; code?: string };
106
+ servicePointId?: number | string | null;
107
+ }): Promise<Label>;
108
+ /** Paper size; default 'a6'. */
109
+ downloadLabel(input: { parcelId: number; format?: 'a4' | 'a5' | 'a6' }): Promise<{ content: Buffer; type: 'application/pdf' }>;
110
+ cancelLabel(input: { shipmentId: string }): Promise<{ status: 'cancelled' | 'requested' }>;
111
+ servicePoints(query: {
112
+ country: string;
113
+ postalCode?: string;
114
+ city?: string;
115
+ latitude?: number;
116
+ longitude?: number;
117
+ /** Provider carrier codes, for example ['mondial_relay', 'colissimo']; the integration's carriers when omitted. */
118
+ carriers?: string[];
119
+ radiusMeters?: number;
120
+ limit?: number;
121
+ }): Promise<ServicePoint[]>;
122
+ verifySignature(rawBody: Buffer, signature: string | undefined): Promise<boolean> | boolean;
123
+ readEvent(json: unknown): ParcelEvent | null;
124
+ }
125
+
126
+ /* ─────────────────── Sendcloud ─────────────────── */
127
+
128
+ /** https://panel.sendcloud.sc/api/v3 */
129
+ export const SENDCLOUD_API_URL: string;
130
+ /** The free test shipping option: an unstamped letter, nothing is posted. */
131
+ export const TEST_SHIPPING_OPTION: 'sendcloud:letter';
132
+
133
+ type Secret = string | (() => string | Promise<string>);
134
+
135
+ export interface SendcloudOptions {
136
+ publicKey: Secret;
137
+ secretKey: Secret;
138
+ /** The integration's "Webhook Signature Key" when it has one; otherwise webhooks are signed with secretKey. */
139
+ 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
+ };
145
+ fetch?: typeof fetch;
146
+ baseUrl?: string;
147
+ /** Default 20 000. */
148
+ timeoutMs?: number;
149
+ /** Options of @astratra/resilience retry (reads only). */
150
+ retry?: { attempts?: number; baseDelayMs?: number; maxDelayMs?: number; sleep?: (ms: number) => Promise<void> };
151
+ /** Options of @astratra/resilience createCircuitBreaker. */
152
+ breaker?: { failureThreshold?: number; recoveryMs?: number; now?: () => number };
153
+ /** Labels on 'sendcloud:letter' (unstamped letter): nothing is posted. */
154
+ testMode?: boolean;
155
+ /** Default 120; false disables the service point cache. */
156
+ servicePointsCacheSeconds?: number | false;
157
+ }
158
+
159
+ export class SendcloudCarrier extends Carrier {
160
+ constructor(options: SendcloudOptions);
161
+ readonly testMode: boolean;
162
+ status(): Promise<{ configured: boolean; missing: string[]; testMode: boolean }>;
163
+ verifySignature(rawBody: Buffer, signature: string | undefined): Promise<boolean>;
164
+ }
165
+
166
+ export function createSendcloudCarrier(options: SendcloudOptions): SendcloudCarrier;
167
+
168
+ /** 'picked_up' | 'delivered' | 'incident' | null for a Sendcloud status label. */
169
+ export function classifySendcloudStatus(message: unknown): ParcelStage | null;
170
+
171
+ /* ─────────────────── Tracking webhook ─────────────────── */
172
+
173
+ export const SIGNATURE_HEADER: 'sendcloud-signature';
174
+
175
+ type ParcelHandler = (
176
+ event: ParcelEvent,
177
+ tools: { sideEffect<T>(label: string, fn: () => Promise<T> | T): Promise<T | null>; handled(reason?: string): Outcome; unrelated(reason?: string): Outcome; duplicate(reason?: string): Outcome }
178
+ ) => Promise<Outcome | void> | Outcome | void;
179
+
180
+ /** The carrier's tracking webhook on @astratra/payments: mount it before any JSON body parser. */
181
+ export function createCarrierWebhook(options: {
182
+ carrier: Pick<Carrier, 'verifySignature' | 'readEvent'>;
183
+ /** Replay protection, for example createPostgresEventLog from @astratra/payments. */
184
+ eventLog?: EventLog;
185
+ onEvent?: ParcelHandler;
186
+ onPickedUp?: ParcelHandler;
187
+ onDelivered?: ParcelHandler;
188
+ onIncident?: ParcelHandler;
189
+ signatureHeader?: string;
190
+ logger?: WebhookLogger;
191
+ }): WebhookHandler;
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ ...require('./carrier'),
3
+ ...require('./errors'),
4
+ ...require('./statuses'),
5
+ ...require('./sendcloud'),
6
+ ...require('./webhook')
7
+ };
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Sendcloud (carrier aggregator), REST API v3: shipping options, shipments,
3
+ * parcel documents, service points, tracking webhooks.
4
+ *
5
+ * - Keys come from options (a value, or a function read on every call so they
6
+ * can be rotated or arrive after start-up). Never read from a file or the
7
+ * environment here, never put in an error.
8
+ * - Calls go through a circuit breaker; only READS are retried: announcing a
9
+ * shipment twice would buy two labels. With a `reference`, Sendcloud itself
10
+ * refuses a second shipment (409) and returns the first one.
11
+ * - A 4xx is Sendcloud refusing the request, not an outage: only network
12
+ * failures and 5xx count against the breaker and deserve a retry.
13
+ * - Test mode ships with the option code "sendcloud:letter" (unstamped letter):
14
+ * nothing is posted.
15
+ *
16
+ * References: https://sendcloud.dev (API v3: shipping-options, shipments/announce,
17
+ * shipments/{id}/cancel, parcels/{id}/documents/label, service-points).
18
+ */
19
+ const { createHmac, timingSafeEqual } = require('node:crypto');
20
+ const { URLSearchParams } = require('node:url');
21
+ const { createCircuitBreaker, retry, createCache } = require('@astratra/resilience');
22
+ const { Carrier } = require('./carrier');
23
+ const { CODES, ShippingError } = require('./errors');
24
+ const { classifySendcloudStatus } = require('./statuses');
25
+
26
+ const SENDCLOUD_API_URL = 'https://panel.sendcloud.sc/api/v3';
27
+ const TEST_SHIPPING_OPTION = 'sendcloud:letter';
28
+ const DEFAULT_TIMEOUT_MS = 20_000;
29
+ const SERVICE_POINT_DELIVERY = new Set(['service_point', 'locker', 'locker_or_service_point']);
30
+
31
+ const read = async (value) => String((typeof value === 'function' ? await value() : value) ?? '').trim();
32
+ const isOutage = (error) => !error || error.providerStatus === undefined || error.providerStatus >= 500;
33
+ const kilograms = (grams) => (grams / 1000).toFixed(3);
34
+ const country = (value) => String(value ?? '').trim().toUpperCase();
35
+ const cents = (value) => {
36
+ const n = Number.parseFloat(value);
37
+ return Number.isFinite(n) ? Math.round(n * 100) : null;
38
+ };
39
+
40
+ /** Any failure turned into a ShippingError; `whenRefused` says what a 4xx means for this call. */
41
+ function toShippingError(error, whenRefused) {
42
+ if (error instanceof ShippingError && error.code !== CODES.REJECTED) return error;
43
+ const status = error && error.providerStatus;
44
+ if (status === 401 || status === 403) return new ShippingError(CODES.CREDENTIALS_REFUSED, { providerStatus: status });
45
+ if (status !== undefined && status < 500) return new ShippingError(whenRefused, { providerStatus: status });
46
+ return new ShippingError(CODES.UNAVAILABLE, status === undefined ? {} : { providerStatus: status });
47
+ }
48
+
49
+ /** The sender, as Sendcloud's from_address: a saved sender address id, or the full address. */
50
+ function fromAddress(sender) {
51
+ if (!sender) return null;
52
+ if (sender.addressId !== undefined && sender.addressId !== null) return { sender_address_id: Number(sender.addressId) };
53
+ if (!sender.name || !sender.line1 || !sender.city || !sender.postalCode || !/^[A-Z]{2}$/.test(country(sender.country))) return null;
54
+ return {
55
+ name: sender.name,
56
+ company_name: sender.companyName || undefined,
57
+ address_line_1: sender.line1,
58
+ address_line_2: sender.line2 || undefined,
59
+ house_number: sender.houseNumber || undefined,
60
+ postal_code: sender.postalCode,
61
+ city: sender.city,
62
+ country_code: country(sender.country),
63
+ phone_number: sender.phone || undefined,
64
+ email: sender.email || undefined
65
+ };
66
+ }
67
+
68
+ class SendcloudCarrier extends Carrier {
69
+ /**
70
+ * @param {object} options
71
+ * @param {string|Function} options.publicKey
72
+ * @param {string|Function} options.secretKey
73
+ * @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, … }
75
+ * @param {Function} [options.fetch] injectable (tests)
76
+ * @param {string} [options.baseUrl]
77
+ * @param {number} [options.timeoutMs] default 20 000
78
+ * @param {object} [options.retry] options of @astratra/resilience retry (tests: { baseDelayMs: 0 })
79
+ * @param {object} [options.breaker] options of createCircuitBreaker
80
+ * @param {boolean} [options.testMode] labels on "sendcloud:letter": nothing is posted
81
+ * @param {number|false} [options.servicePointsCacheSeconds] default 120; false disables the cache
82
+ */
83
+ constructor(options = {}) {
84
+ super();
85
+ this.publicKey = options.publicKey;
86
+ this.secretKey = options.secretKey;
87
+ 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);
91
+ this.fetchImpl = options.fetch || globalThis.fetch;
92
+ this.baseUrl = options.baseUrl || SENDCLOUD_API_URL;
93
+ this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
94
+ this.retryOptions = options.retry || {};
95
+ this.testMode = Boolean(options.testMode);
96
+ this.breaker = createCircuitBreaker({
97
+ name: 'sendcloud', failureThreshold: 5, recoveryMs: 30_000, ...options.breaker, isFailure: isOutage
98
+ });
99
+ const seconds = options.servicePointsCacheSeconds === undefined ? 120 : options.servicePointsCacheSeconds;
100
+ this.cache = seconds ? createCache({ ttlSeconds: seconds, prefix: 'sendcloud:service-points:', maxEntries: 1000 }) : null;
101
+ }
102
+
103
+ get name() { return 'sendcloud'; }
104
+
105
+ /** { configured, missing, testMode } — names of what is missing, never a value. */
106
+ async status() {
107
+ const missing = [];
108
+ if (!(await read(this.publicKey))) missing.push('publicKey');
109
+ 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 };
112
+ }
113
+
114
+ async #keys() {
115
+ const publicKey = await read(this.publicKey);
116
+ const secretKey = await read(this.secretKey);
117
+ if (!publicKey || !secretKey) throw new ShippingError(CODES.NOT_CONFIGURED);
118
+ return { publicKey, secretKey };
119
+ }
120
+
121
+ /**
122
+ * One HTTP call; retried only when `retryable` (reads). Returns the response when ok, or when its
123
+ * status is listed in `accept` (for example 409 on a shipment announced again with its reference).
124
+ */
125
+ async #call(path, { method = 'GET', body, retryable = false, accept = [], headers: extra = {} } = {}) {
126
+ const { publicKey, secretKey } = await this.#keys();
127
+ const headers = {
128
+ Authorization: `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString('base64')}`,
129
+ Accept: 'application/json',
130
+ ...extra
131
+ };
132
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
133
+ const once = async () => {
134
+ let response;
135
+ try {
136
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
137
+ method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: globalThis.AbortSignal.timeout(this.timeoutMs)
138
+ });
139
+ } catch {
140
+ /* Network failure or timeout: no HTTP status, an outage. */
141
+ throw new ShippingError(CODES.UNAVAILABLE);
142
+ }
143
+ if (!response.ok && !accept.includes(response.status)) {
144
+ throw new ShippingError(CODES.REJECTED, { providerStatus: response.status });
145
+ }
146
+ return response;
147
+ };
148
+ try {
149
+ return await this.breaker.call(() => (retryable
150
+ ? retry(once, { attempts: 3, ...this.retryOptions, shouldRetry: (error) => isOutage(error) })
151
+ : once()));
152
+ } catch (error) {
153
+ if (error && error.code === 'CIRCUIT_OPEN') throw new ShippingError(CODES.UNAVAILABLE);
154
+ throw error;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Shipping options for a destination and a weight (POST /shipping-options, with quotes). With
160
+ * `servicePointId`, only service point or locker delivery; without, only the other deliveries.
161
+ * `id` is the shipping option code; `priceCents` is Sendcloud's quote, never recomputed here.
162
+ */
163
+ async shippingMethods({ country: to, postalCode, weightGrams, servicePointId = null } = {}) {
164
+ const destination = country(to);
165
+ if (!/^[A-Z]{2}$/.test(destination) || !(Number.isFinite(weightGrams) && weightGrams > 0)) {
166
+ throw new ShippingError(CODES.INVALID_INPUT);
167
+ }
168
+ if (!this.senderCountry || !/^[A-Z]{2}$/.test(this.senderCountry)) throw new ShippingError(CODES.NOT_CONFIGURED);
169
+ const body = {
170
+ from_address: { country_code: this.senderCountry },
171
+ to_address: { country_code: destination, ...(postalCode ? { postal_code: String(postalCode) } : {}) },
172
+ parcels: [{ weight: { value: kilograms(weightGrams), unit: 'kg' } }],
173
+ calculate_quotes: true,
174
+ ...(servicePointId ? { to_service_point: { id: String(servicePointId) } } : {})
175
+ };
176
+ let response;
177
+ try {
178
+ response = await this.#call('/shipping-options', { method: 'POST', body, retryable: true });
179
+ } catch (error) {
180
+ throw toShippingError(error, CODES.NO_METHOD);
181
+ }
182
+ const data = (await response.json().catch(() => ({}))).data;
183
+ return (Array.isArray(data) ? data : [])
184
+ .filter((option) => {
185
+ const toPoint = SERVICE_POINT_DELIVERY.has(option.functionalities?.last_mile);
186
+ return servicePointId ? toPoint : !toPoint;
187
+ })
188
+ .map((option) => ({
189
+ id: String(option.code),
190
+ name: String(option.name ?? ''),
191
+ carrier: String(option.carrier?.code ?? ''),
192
+ servicePointRequired: SERVICE_POINT_DELIVERY.has(option.functionalities?.last_mile),
193
+ priceCents: cents(option.quotes?.[0]?.price?.total?.value)
194
+ }));
195
+ }
196
+
197
+ /**
198
+ * Announces the shipment and gets its label in the same answer (POST /shipments/announce).
199
+ * NEVER retried. `reference` (optional, unique per account) makes a second announcement of the same
200
+ * shipment return the first one instead of buying a second label.
201
+ * recipient: { name, line1, line2?, houseNumber?, city, postalCode, country, phone?, email? }
202
+ * method: { id } — a shipping option code from shippingMethods
203
+ */
204
+ async createLabel({ orderNumber, reference, recipient = {}, weightGrams, method, servicePointId = null } = {}) {
205
+ const destination = country(recipient.country);
206
+ const code = method && (method.code ?? method.id);
207
+ if (!recipient.name || !recipient.line1 || !recipient.city || !recipient.postalCode || !/^[A-Z]{2}$/.test(destination)
208
+ || !(Number.isFinite(weightGrams) && weightGrams > 0) || (!code && !this.testMode) || !orderNumber) {
209
+ throw new ShippingError(CODES.INVALID_INPUT);
210
+ }
211
+ if (!this.sender) throw new ShippingError(CODES.NOT_CONFIGURED);
212
+ const optionCode = this.testMode ? TEST_SHIPPING_OPTION : String(code);
213
+ const body = {
214
+ from_address: this.sender,
215
+ to_address: {
216
+ name: recipient.name,
217
+ address_line_1: recipient.line1,
218
+ address_line_2: recipient.line2 || undefined,
219
+ house_number: recipient.houseNumber || undefined,
220
+ postal_code: recipient.postalCode,
221
+ city: recipient.city,
222
+ country_code: destination,
223
+ phone_number: recipient.phone || undefined,
224
+ email: recipient.email || undefined
225
+ },
226
+ ship_with: { type: 'shipping_option_code', properties: { shipping_option_code: optionCode } },
227
+ parcels: [{ weight: { value: kilograms(weightGrams), unit: 'kg' } }],
228
+ order_number: String(orderNumber),
229
+ ...(reference ? { external_reference_id: String(reference) } : {}),
230
+ ...(servicePointId && !this.testMode ? { to_service_point: { id: String(servicePointId) } } : {})
231
+ };
232
+ let response;
233
+ try {
234
+ response = await this.#call('/shipments/announce', { method: 'POST', body, accept: reference ? [409] : [] });
235
+ } catch (error) {
236
+ throw toShippingError(error, CODES.REJECTED);
237
+ }
238
+ const shipment = (await response.json().catch(() => ({}))).data;
239
+ const parcel = shipment && Array.isArray(shipment.parcels) ? shipment.parcels[0] : null;
240
+ /* A carrier refusal arrives as 201 with errors and an ANNOUNCEMENT_FAILED parcel. */
241
+ if (shipment && Array.isArray(shipment.errors) && shipment.errors.length) throw new ShippingError(CODES.REJECTED, { providerStatus: response.status });
242
+ if (parcel && String(parcel.status?.code ?? '').toUpperCase() === 'ANNOUNCEMENT_FAILED') throw new ShippingError(CODES.REJECTED, { providerStatus: response.status });
243
+ if (!shipment || !shipment.id || !parcel || !parcel.id) throw new ShippingError(CODES.UNEXPECTED_RESPONSE);
244
+ return {
245
+ shipmentId: String(shipment.id),
246
+ parcelId: Number(parcel.id),
247
+ trackingNumber: String(parcel.tracking_number ?? ''),
248
+ trackingUrl: String(parcel.tracking_url ?? ''),
249
+ carrier: String(shipment.carrier?.code ?? ''),
250
+ service: String(shipment.ship_with?.properties?.shipping_option_code ?? optionCode),
251
+ /* The label itself, when Sendcloud returns it inline (one parcel): no second request needed. */
252
+ label: typeof parcel.label_file === 'string' && parcel.label_file ? Buffer.from(parcel.label_file, 'base64') : null,
253
+ alreadyExisted: response.status === 409,
254
+ testMode: this.testMode
255
+ };
256
+ }
257
+
258
+ /** The label PDF (GET /parcels/{id}/documents/label), paper A4 or A6. */
259
+ async downloadLabel({ parcelId, format = 'a6' } = {}) {
260
+ const id = Number(parcelId);
261
+ if (!Number.isSafeInteger(id) || id <= 0 || !['a4', 'a5', 'a6'].includes(format)) throw new ShippingError(CODES.INVALID_INPUT);
262
+ let response;
263
+ try {
264
+ response = await this.#call(`/parcels/${id}/documents/label?paper_size=${format.toUpperCase()}`, {
265
+ retryable: true, headers: { Accept: 'application/pdf' }
266
+ });
267
+ } catch (error) {
268
+ throw toShippingError(error, CODES.NOT_FOUND);
269
+ }
270
+ const type = response.headers.get('content-type') || '';
271
+ const content = Buffer.from(await response.arrayBuffer());
272
+ if (!type.includes('pdf') || content.length === 0) throw new ShippingError(CODES.UNEXPECTED_RESPONSE);
273
+ return { content, type: 'application/pdf' };
274
+ }
275
+
276
+ /**
277
+ * Cancels a shipment (POST /shipments/{id}/cancel). 202 "queued": Sendcloud watches it and cancels
278
+ * it if nothing moves ({ status: 'requested' }). A 409 is refused (delivered, older than 42 days),
279
+ * except "already being cancelled", which is the wanted state.
280
+ */
281
+ async cancelLabel({ shipmentId } = {}) {
282
+ const id = String(shipmentId ?? '').trim();
283
+ if (!id || !/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new ShippingError(CODES.INVALID_INPUT);
284
+ let response;
285
+ try {
286
+ response = await this.#call(`/shipments/${encodeURIComponent(id)}/cancel`, { method: 'POST', accept: [409] });
287
+ } catch (error) {
288
+ throw toShippingError(error, error && error.providerStatus === 404 ? CODES.NOT_FOUND : CODES.CANCEL_REFUSED);
289
+ }
290
+ const body = await response.json().catch(() => ({}));
291
+ if (response.status === 409) {
292
+ const detail = Array.isArray(body.errors) ? body.errors.map((e) => String(e.detail ?? '')).join(' ') : '';
293
+ if (/already/i.test(detail)) return { status: 'cancelled' };
294
+ throw new ShippingError(CODES.CANCEL_REFUSED, { providerStatus: 409 });
295
+ }
296
+ return { status: response.status === 202 || body.data?.status === 'queued' ? 'requested' : 'cancelled' };
297
+ }
298
+
299
+ /**
300
+ * Service points near an address or coordinates, nearest first (GET /service-points).
301
+ * carriers: Sendcloud carrier codes (for example ['mondial_relay', 'colissimo']); without, the
302
+ * carriers enabled on the integration.
303
+ */
304
+ async servicePoints({ country: of, postalCode, city, latitude, longitude, carriers, radiusMeters = 10_000, limit = 15 } = {}) {
305
+ const pays = country(of);
306
+ const byCoordinates = latitude !== undefined || longitude !== undefined;
307
+ if (!/^[A-Z]{2}$/.test(pays)
308
+ || (byCoordinates && !(Number.isFinite(latitude) && Number.isFinite(longitude) && Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180))
309
+ || (!byCoordinates && !postalCode && !city)) {
310
+ throw new ShippingError(CODES.INVALID_INPUT);
311
+ }
312
+ const wanted = Array.isArray(carriers) && carriers.length ? carriers.map((c) => String(c).toLowerCase()) : null;
313
+ const params = new URLSearchParams({ country_code: pays });
314
+ if (wanted) for (const code of wanted) params.append('carrier_code', code);
315
+ else params.set('use_integration_carriers', 'true');
316
+ if (byCoordinates) {
317
+ params.set('latitude', String(latitude));
318
+ params.set('longitude', String(longitude));
319
+ } else {
320
+ if (postalCode) params.set('address_postal_code', String(postalCode));
321
+ if (city) params.set('address_city', String(city));
322
+ }
323
+ params.set('radius', String(Math.min(50_000, Math.max(100, Math.round(radiusMeters)))));
324
+ params.set('limit', String(Math.min(200, Math.max(1, limit))));
325
+ const fetchPoints = async () => {
326
+ let response;
327
+ try {
328
+ response = await this.#call(`/service-points?${params}`, { retryable: true });
329
+ } catch (error) {
330
+ throw toShippingError(error, CODES.SERVICE_POINTS_UNAVAILABLE);
331
+ }
332
+ const body = await response.json().catch(() => ({}));
333
+ return Array.isArray(body.data?.results) ? body.data.results : [];
334
+ };
335
+ const raw = this.cache ? await this.cache.remember(params.toString(), fetchPoints) : await fetchPoints();
336
+ return raw
337
+ .map((p) => ({
338
+ id: Number(p.id),
339
+ carrier: String(p.carrier?.code ?? '').toLowerCase(),
340
+ name: String(p.name ?? ''),
341
+ address: [p.address?.street, p.address?.house_number].filter(Boolean).join(' '),
342
+ postalCode: String(p.address?.postal_code ?? ''),
343
+ city: String(p.address?.city ?? ''),
344
+ country: country(p.address?.country_code),
345
+ openingTimes: p.opening_times ?? {},
346
+ distanceMeters: Number.isFinite(Number(p.distance)) && p.distance !== null ? Number(p.distance) : null
347
+ }))
348
+ .filter((p) => p.country === pays && (!wanted || wanted.includes(p.carrier))
349
+ && Number.isSafeInteger(p.id) && p.id > 0 && p.name && p.address && p.postalCode && p.city)
350
+ .sort((a, b) => (a.distanceMeters ?? Infinity) - (b.distanceMeters ?? Infinity))
351
+ .slice(0, Math.max(1, limit));
352
+ }
353
+
354
+ /** HMAC-SHA256 of the raw body (Sendcloud-Signature header, hex), compared in constant time. */
355
+ async verifySignature(rawBody, signature) {
356
+ const secret = (await read(this.webhookSecret)) || (await read(this.secretKey));
357
+ if (!secret || typeof signature !== 'string' || !Buffer.isBuffer(rawBody)) return false;
358
+ const expected = createHmac('sha256', secret).update(rawBody).digest();
359
+ const received = Buffer.from(signature.trim().toLowerCase(), 'hex');
360
+ return received.length === expected.length && timingSafeEqual(received, expected);
361
+ }
362
+
363
+ /**
364
+ * 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.
366
+ */
367
+ readEvent(json) {
368
+ if (!json || json.action !== 'parcel_status_changed' || !json.parcel || !json.parcel.id) return null;
369
+ const message = String(json.parcel.status?.message ?? '');
370
+ const timestamp = Number(json.timestamp);
371
+ return {
372
+ parcelId: Number(json.parcel.id),
373
+ trackingNumber: String(json.parcel.tracking_number ?? ''),
374
+ trackingUrl: String(json.parcel.tracking_url ?? ''),
375
+ message,
376
+ stage: classifySendcloudStatus(message),
377
+ timestamp: Number.isFinite(timestamp) ? timestamp : null
378
+ };
379
+ }
380
+ }
381
+
382
+ function createSendcloudCarrier(options) {
383
+ return new SendcloudCarrier(options);
384
+ }
385
+
386
+ module.exports = { SendcloudCarrier, createSendcloudCarrier, SENDCLOUD_API_URL, TEST_SHIPPING_OPTION };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Sendcloud tracking statuses ("Tracking statuses" list; the webhooks are the same in API v2 and v3) mapped to the
3
+ * three moments a shop acts on. Pure function.
4
+ *
5
+ * - picked_up: first scan by the carrier ("label created" is NOT a scan:
6
+ * "Ready to send", "Announced", "Being announced" map to null);
7
+ * - delivered: delivered or collected by the customer;
8
+ * - incident: the parcel will not be delivered normally;
9
+ * - null: no action. A failed delivery attempt or a delay is not a final
10
+ * incident: it still counts as "on its way".
11
+ */
12
+ const PICKED_UP = new Set([
13
+ 'shipment picked up by driver',
14
+ 'en route to sorting center',
15
+ 'at sorting centre',
16
+ 'being sorted',
17
+ 'sorted',
18
+ 'parcel en route',
19
+ 'driver en route',
20
+ 'awaiting customer pickup',
21
+ 'at customs',
22
+ 'delivery delayed',
23
+ 'delivery attempt failed',
24
+ 'delivery date changed',
25
+ 'delivery method changed',
26
+ 'delivery address changed'
27
+ ]);
28
+ const DELIVERED = new Set(['delivered', 'shipment collected by customer']);
29
+ const INCIDENT = new Set(['unable to deliver', 'refused by recipient', 'returned to sender', 'address invalid', 'error collecting']);
30
+
31
+ const normalize = (message) => String(message ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
32
+
33
+ /** 'picked_up' | 'delivered' | 'incident' | null for a Sendcloud status label. */
34
+ function classifySendcloudStatus(message) {
35
+ const m = normalize(message);
36
+ if (DELIVERED.has(m)) return 'delivered';
37
+ if (INCIDENT.has(m)) return 'incident';
38
+ if (PICKED_UP.has(m)) return 'picked_up';
39
+ return null;
40
+ }
41
+
42
+ module.exports = { classifySendcloudStatus };
package/src/webhook.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The tracking webhook of a carrier, on @astratra/payments' webhook pipeline:
3
+ * raw-body signature check, atomic replay protection (claim → handle → record,
4
+ * release on failure), side effects that cannot fail the webhook.
5
+ *
6
+ * The event id is the SHA-256 of the raw body: Sendcloud resends the same body,
7
+ * so a resend is recognised whatever it contains. The package knows no orders
8
+ * and no tables: the application says what a pickup, a delivery or an
9
+ * incident means for it.
10
+ *
11
+ * Mount BEFORE any JSON body parser: the signature is computed on the exact
12
+ * bytes received (express.raw({ type: 'application/json' })).
13
+ */
14
+ const { createHash } = require('node:crypto');
15
+ const { createWebhookHandler } = require('@astratra/payments');
16
+
17
+ const SIGNATURE_HEADER = 'sendcloud-signature';
18
+
19
+ /**
20
+ * @param {object} options
21
+ * @param {object} options.carrier a Carrier (verifySignature, readEvent)
22
+ * @param {object} [options.eventLog] { claim, release, record } — for example createPostgresEventLog
23
+ * @param {Function} [options.onEvent] (event, tools) called for every parcel status change
24
+ * @param {Function} [options.onPickedUp] (event, tools) first scan
25
+ * @param {Function} [options.onDelivered] (event, tools)
26
+ * @param {Function} [options.onIncident] (event, tools)
27
+ * @param {string} [options.signatureHeader] default 'sendcloud-signature'
28
+ * @param {object} [options.logger]
29
+ */
30
+ function createCarrierWebhook(options = {}) {
31
+ const carrier = options.carrier;
32
+ if (!carrier || typeof carrier.verifySignature !== 'function' || typeof carrier.readEvent !== 'function') {
33
+ throw new TypeError('createCarrierWebhook needs a carrier with verifySignature() and readEvent().');
34
+ }
35
+ const header = String(options.signatureHeader || SIGNATURE_HEADER).toLowerCase();
36
+ const byStage = { picked_up: options.onPickedUp, delivered: options.onDelivered, incident: options.onIncident };
37
+
38
+ const handler = createWebhookHandler({
39
+ eventLog: options.eventLog,
40
+ logger: options.logger,
41
+ eventId: (event) => event.id,
42
+ async verify({ payload, headers }) {
43
+ if (!Buffer.isBuffer(payload)) {
44
+ throw new Error('the body is not raw bytes: mount the webhook before any JSON body parser');
45
+ }
46
+ const signature = headers[header] ?? headers[header.toLowerCase()];
47
+ if (!(await carrier.verifySignature(payload, Array.isArray(signature) ? signature[0] : signature))) {
48
+ throw new Error('invalid signature');
49
+ }
50
+ let json;
51
+ try {
52
+ json = JSON.parse(payload.toString('utf8'));
53
+ } catch {
54
+ throw new Error('unreadable body');
55
+ }
56
+ const parcel = carrier.readEvent(json);
57
+ return {
58
+ id: createHash('sha256').update(payload).digest('hex'),
59
+ type: parcel ? 'parcel_status_changed' : String(json && json.action || 'unknown'),
60
+ parcel
61
+ };
62
+ },
63
+ events: {
64
+ async parcel_status_changed(event, tools) {
65
+ if (typeof options.onEvent === 'function') await options.onEvent(event.parcel, tools);
66
+ const act = byStage[event.parcel.stage];
67
+ if (typeof act === 'function') {
68
+ const outcome = await act(event.parcel, tools);
69
+ if (outcome) return outcome;
70
+ }
71
+ return tools.handled(event.parcel.stage || 'status');
72
+ }
73
+ }
74
+ });
75
+ return handler;
76
+ }
77
+
78
+ module.exports = { createCarrierWebhook, SIGNATURE_HEADER };