@astratra/shipping 0.0.0-stage → 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/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,218 @@
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
+ // Pas de « commencer à la case N » sur une planche A4 : l'API v3 de Sendcloud ne le propose pas.
68
+ await carrier.cancelLabel({ shipmentId: envoi.shipmentId }); // { status: 'cancelled' | 'requested' }
69
+ ```
70
+
71
+ - **L'expéditeur** (`sender`) : l'identifiant d'une adresse enregistrée chez
72
+ Sendcloud avec son pays, ou l'adresse complète (`name`, `line1`, `city`,
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`.
89
+ - **Les options d'expédition** sont des codes stables (`colissimo:home/signature`,
90
+ `mondial_relay:point`…), jamais des numéros qui changent. `priceCents` est le
91
+ devis de Sendcloud : tes prix restent les tiens.
92
+ - **La référence** (`reference`, unique par compte) protège contre le double
93
+ achat : la même référence annoncée deux fois rend le premier envoi
94
+ (`alreadyExisted: true`).
95
+ - **Un refus du transporteur** (code postal invalide…) revient de Sendcloud avec
96
+ un statut 201 et une erreur : le paquet en fait une erreur `rejected`.
97
+ - **L'annulation** porte sur l'envoi (`shipmentId`). `requested` : Sendcloud
98
+ surveille l'envoi et l'annule s'il ne bouge pas. Refusée si le colis est livré
99
+ ou annoncé depuis plus de 42 jours ; « déjà en cours d'annulation » compte
100
+ comme annulé.
101
+ - `servicePoints` : par code postal et/ou ville, ou par coordonnées ; les
102
+ transporteurs choisis (codes Sendcloud), sinon ceux activés sur ton
103
+ intégration ; rayon (`radiusMeters`, 10 km, de 100 m à 50 km) et nombre
104
+ (`limit`, 15) ; du plus proche au plus loin ; gardés 2 minutes
105
+ (`servicePointsCacheSeconds`, `false` pour couper).
106
+
107
+ ### Mode test
108
+
109
+ `testMode: true` crée chaque étiquette avec l'option `sendcloud:letter` (lettre
110
+ non affranchie) : rien n'est posté et aucun port n'est facturé (Sendcloud peut
111
+ compter des frais de traitement : voir sa documentation). L'option et le point
112
+ relais demandés sont ignorés, et `testMode` vaut `true` dans la réponse.
113
+
114
+ ## Les erreurs
115
+
116
+ Toute erreur est une `ShippingError` avec un **code stable**, un `status` HTTP à
117
+ répondre, et le `providerStatus` du transporteur — jamais son corps ni une clé :
118
+
119
+ | Code | Statut | Quand |
120
+ |---|---|---|
121
+ | `not_configured` | 503 | une clé manque |
122
+ | `credentials_refused` | 502 | 401 ou 403 du transporteur |
123
+ | `unavailable` | 503 | coupure, 5xx, disjoncteur ouvert |
124
+ | `rejected` | 422 | étiquette refusée (adresse, poids, méthode) |
125
+ | `no_method` | 422 | aucune méthode pour ce pays et ce poids |
126
+ | `not_found` | 404 | étiquette introuvable |
127
+ | `cancel_refused` | 409 | colis sans doute déjà pris en charge |
128
+ | `service_points_unavailable` | 503 | recherche de points relais refusée |
129
+ | `invalid_input` | 422 | informations incomplètes ou invalides |
130
+ | `unexpected_response` | 502 | réponse illisible |
131
+
132
+ `messageFor(codeOuErreur, 'fr' | 'en')` donne la phrase à montrer (catalogue de
133
+ `@astratra/i18n-server`) ; une langue inconnue donne le français.
134
+
135
+ ## Le webhook de suivi
136
+
137
+ ```js
138
+ const express = require('express');
139
+ const { Pool } = require('pg');
140
+ const { createPostgresEventLog, postgresEventLogSchema } = require('@astratra/payments');
141
+ const { createCarrierWebhook } = require('@astratra/shipping');
142
+
143
+ const pool = new Pool();
144
+ await pool.query(postgresEventLogSchema({ table: 'sendcloud_events' }));
145
+
146
+ const webhook = createCarrierWebhook({
147
+ carrier,
148
+ eventLog: createPostgresEventLog(pool, { table: 'sendcloud_events' }),
149
+ onEvent: async (colis) => { /* chaque statut : noter colis.message, la date du dernier scan… */ },
150
+ onPickedUp: async (colis, { sideEffect }) => {
151
+ await marquerPrisEnCharge(colis.parcelId);
152
+ await sideEffect('e-mail', () => envoyerEmailExpedition(colis)); // ne fait jamais échouer le webhook
153
+ },
154
+ onDelivered: async (colis) => marquerLivre(colis.parcelId),
155
+ onIncident: async (colis) => signalerIncident(colis.parcelId, colis.message)
156
+ });
157
+
158
+ // AVANT express.json : la signature porte sur les octets reçus.
159
+ app.post('/api/transporteurs/sendcloud/webhook', express.raw({ type: 'application/json', limit: '1mb' }), webhook.middleware);
160
+ ```
161
+
162
+ - En-tête `sendcloud-signature` : HMAC-SHA256 du corps brut, en hexadécimal.
163
+ - Signature fausse, corps déjà analysé ou illisible : **400**, pour que Sendcloud
164
+ ne renvoie pas indéfiniment. Sans clé secrète, tout est refusé.
165
+ - Un autre type d'événement que `parcel_status_changed` : **200**, ignoré.
166
+ - Un renvoi du même corps : **200** `duplicate`, sans rien refaire.
167
+ - Une erreur dans tes fonctions : **500** et l'événement est libéré, le renvoi
168
+ de Sendcloud sera traité.
169
+ - `stage` de l'événement : `picked_up`, `delivered`, `incident` ou `null`
170
+ (`classifySendcloudStatus`). Une tentative de livraison ratée ou un retard
171
+ reste `picked_up` : ce n'est pas un incident définitif.
172
+ - Les notifications peuvent arriver dans le désordre : `timestamp` dit quand le
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).
192
+ - La signature utilise la « Webhook Signature Key » de l'intégration
193
+ (`webhookSecret`) quand elle existe, sinon la clé secrète.
194
+
195
+ ## Écrire un autre transporteur
196
+
197
+ Étends `Carrier` et implémente : `name`, `status()`, `shippingMethods()`,
198
+ `createLabel()`, `downloadLabel()`, `cancelLabel()`, `servicePoints()`,
199
+ `verifySignature()`, `readEvent()`. `createCarrierWebhook` fonctionne avec
200
+ n'importe quel transporteur (`signatureHeader` en option).
201
+
202
+ ## Ce que ce paquet ne fait pas
203
+
204
+ - Pas de prix de livraison, de zones ni de pays livrés : c'est la boutique.
205
+ - Pas de commandes, pas de tables (sauf le journal des événements, fourni par
206
+ `@astratra/payments`), pas d'e-mails.
207
+ - Pas de limite de débit sur la recherche publique de points relais : mets-la
208
+ devant ta route.
209
+
210
+ ## Tests
211
+
212
+ ```bash
213
+ npm test --workspace @astratra/shipping
214
+ ```
215
+
216
+ Aucun appel réseau : un faux Sendcloud répond aux requêtes et les enregistre
217
+ (relances des lectures seulement, disjoncteur, clés jamais dans les erreurs,
218
+ mode test, points relais, signature, rejeux concurrents, échec puis renvoi).
package/README.md CHANGED
@@ -1,3 +1,146 @@
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
+ // No "start at box N" on an A4 sheet: Sendcloud API v3 does not offer it.
60
+ const { content } = await carrier.downloadLabel({ parcelId: shipment.parcelId, format: 'a4' }); // A4, A5 or A6 (default)
61
+ await carrier.cancelLabel({ shipmentId: shipment.shipmentId }); // { status: 'cancelled' | 'requested' }
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`).
69
+ - Shipping options are stable codes (`colissimo:home/signature`), never ids that
70
+ change. `priceCents` is Sendcloud's quote: your prices stay yours.
71
+ - `reference` (unique per account) guards against buying twice: the same
72
+ reference announced again returns the first shipment (`alreadyExisted`).
73
+ - A carrier refusal comes back as 201 with an error: it becomes `rejected`.
74
+ - Cancelling works on the shipment. `requested`: Sendcloud watches it and
75
+ cancels it if nothing moves. Refused once delivered or 42 days after
76
+ announcement; "already being cancelled" counts as cancelled.
77
+ - `servicePoints`: by postal code and/or city, or coordinates; the chosen
78
+ carriers, otherwise those enabled on the integration; `radiusMeters`
79
+ (10 km, 100 m to 50 km) and `limit` (15); nearest first; cached 2 minutes.
80
+ - **Test mode** (`testMode: true`) ships with the option `sendcloud:letter`
81
+ (unstamped letter): nothing is posted and no postage is charged (Sendcloud
82
+ may charge a processing fee).
83
+
84
+ ## Errors
85
+
86
+ Every error is a `ShippingError` with a **stable code** (`not_configured`,
87
+ `credentials_refused`, `unavailable`, `rejected`, `no_method`, `not_found`,
88
+ `cancel_refused`, `service_points_unavailable`, `invalid_input`,
89
+ `unexpected_response`), an HTTP `status` to answer with and the carrier's
90
+ `providerStatus` — never its body nor a key. `messageFor(codeOrError, 'fr' | 'en')`
91
+ gives the sentence to show (an `@astratra/i18n-server` catalog).
92
+
93
+ ## The tracking webhook
94
+
95
+ ```js
96
+ const { createPostgresEventLog } = require('@astratra/payments');
97
+ const { createCarrierWebhook } = require('@astratra/shipping');
98
+
99
+ const webhook = createCarrierWebhook({
100
+ carrier,
101
+ eventLog: createPostgresEventLog(pool, { table: 'sendcloud_events' }),
102
+ onEvent: async (parcel) => { /* every status */ },
103
+ onPickedUp: async (parcel, { sideEffect }) => {
104
+ await markPickedUp(parcel.parcelId);
105
+ await sideEffect('email', () => sendShippingEmail(parcel)); // never fails the webhook
106
+ },
107
+ onDelivered: async (parcel) => markDelivered(parcel.parcelId),
108
+ onIncident: async (parcel) => reportIncident(parcel.parcelId, parcel.message)
109
+ });
110
+
111
+ // BEFORE express.json: the signature covers the received bytes.
112
+ app.post('/webhooks/sendcloud', express.raw({ type: 'application/json', limit: '1mb' }), webhook.middleware);
113
+ ```
114
+
115
+ The signature is the HMAC-SHA256 of the raw body (hex), with the integration's
116
+ "Webhook Signature Key" (`webhookSecret`) when it has one, else the secret key.
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()`).
123
+ Wrong signature, parsed or unreadable body: 400 (no endless retries). Another
124
+ event type: 200, ignored. The same body again: 200 `duplicate`. An error in your
125
+ handlers: 500 and the event is released, so Sendcloud's resend is handled.
126
+
127
+ ## Another carrier
128
+
129
+ Extend `Carrier` and implement `name`, `status()`, `shippingMethods()`,
130
+ `createLabel()`, `downloadLabel()`, `cancelLabel()`, `servicePoints()`,
131
+ `verifySignature()` and `readEvent()`. `createCarrierWebhook` works with any
132
+ carrier (`signatureHeader` option).
133
+
134
+ ## Not in this package
135
+
136
+ Delivery prices, zones and countries served, orders, tables (except the event
137
+ log from `@astratra/payments`), emails, and rate limiting of a public service
138
+ point search: those belong to the shop.
139
+
140
+ ## Tests
141
+
142
+ ```bash
143
+ npm test --workspace @astratra/shipping
144
+ ```
145
+
146
+ 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.1.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 };