npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@astratra/shipping

v1.2.0

Published

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.

Readme

@astratra/shipping

Shipping labels without the traps: a carrier contract, a Sendcloud adapter (labels, service points, tracking), the signed tracking webhook with replay protection, and a free test mode.

For every shop: the package knows no orders, no tables and no prices. It talks to the carrier; the shop decides.

Version française

npm install @astratra/shipping

What it does, and the traps it avoids

  • Creating twice is paying twice. Only reads are retried after an outage. createLabel is never retried: a second attempt would buy a second label.
  • A refusal is not an outage. A carrier 4xx (invalid address, weight out of range) is an answer: it does not count against the circuit breaker and is not retried. Only network failures and 5xx are.
  • Keys do not leak. They come from options (a value, or a function read on every call: rotation without restart), never from a file or the environment, never inside an error.
  • The signed raw body. The webhook signature is checked on the bytes received, in constant time. Mount the webhook before any JSON parser.
  • A resend acts once. The webhook runs on @astratra/payments' pipeline: the event (SHA-256 of the raw body) is reserved before it is handled, and released on failure so the resend goes through.
  • "Label created" is not "parcel picked up". Only a carrier scan moves a parcel to picked_up.

The Sendcloud carrier (API v3)

const { createSendcloudCarrier, messageFor } = require('@astratra/shipping');

const carrier = createSendcloudCarrier({
  publicKey: () => vault.read('SENDCLOUD_PUBLIC_KEY'),
  secretKey: () => vault.read('SENDCLOUD_SECRET_KEY'),
  webhookSecret: () => vault.read('SENDCLOUD_WEBHOOK_KEY'), // when the integration has a "Webhook Signature Key"
  sender: { addressId: 12345, country: 'FR' },             // a sender address saved in Sendcloud
  testMode: process.env.NODE_ENV !== 'production'
});

await carrier.status(); // { configured, missing, testMode } — never a value

const options = await carrier.shippingMethods({ country: 'FR', postalCode: '69003', weightGrams: 1250 });
const points = await carrier.servicePoints({ country: 'FR', postalCode: '13002', carriers: ['mondial_relay', 'colissimo'], limit: 10 });
const shipment = await carrier.createLabel({
  orderNumber: 'R-1042',
  reference: 'order-R-1042', // unique: announcing it again returns the first shipment, no second label
  recipient: { name: 'Awa Diallo', line1: '12 rue des Lilas', city: 'Lyon', postalCode: '69003', country: 'FR' },
  weightGrams: 1250,
  method: options[0]
});
// shipment.label: the label PDF, returned with the shipment (one parcel) — no second request
// No "start at box N" on an A4 sheet: Sendcloud API v3 does not offer it.
const { content } = await carrier.downloadLabel({ parcelId: shipment.parcelId, format: 'a4' }); // A4, A5 or A6 (default)
await carrier.cancelLabel({ shipmentId: shipment.shipmentId }); // { status: 'cancelled' | 'requested' }
  • Settings read on every call (1.1.0): sender and testMode take a value or a (possibly async) function, like the keys — change the sender address or switch to test mode from the shop's admin without creating a new carrier. carrier.testMode is the boolean given, or null for a function (read (await carrier.status()).testMode).
  • Shipping options are stable codes (colissimo:home/signature), never ids that change. priceCents is Sendcloud's quote: your prices stay yours.
  • reference (unique per account) guards against buying twice: the same reference announced again returns the first shipment (alreadyExisted).
  • A carrier refusal comes back as 201 with an error: it becomes rejected.
  • Cancelling works on the shipment. requested: Sendcloud watches it and cancels it if nothing moves. Refused once delivered or 42 days after announcement; "already being cancelled" counts as cancelled.
  • servicePoints: by postal code and/or city, or coordinates; the chosen carriers, otherwise those enabled on the integration; radiusMeters (10 km, 100 m to 50 km) and limit (15); nearest first; cached 2 minutes.
  • Test mode (testMode: true) ships with the option sendcloud:letter (unstamped letter): nothing is posted and no postage is charged (Sendcloud may charge a processing fee).

Errors

Every error is a ShippingError with a stable code (not_configured, credentials_refused, unavailable, rejected, no_method, not_found, cancel_refused, service_points_unavailable, invalid_input, unexpected_response), an HTTP status to answer with and the carrier's providerStatus — never its body nor a key. messageFor(codeOrError, 'fr' | 'en') gives the sentence to show (an @astratra/i18n-server catalog).

The tracking webhook

const { createPostgresEventLog } = require('@astratra/payments');
const { createCarrierWebhook } = require('@astratra/shipping');

const webhook = createCarrierWebhook({
  carrier,
  eventLog: createPostgresEventLog(pool, { table: 'sendcloud_events' }),
  onEvent: async (parcel) => { /* every status */ },
  onPickedUp: async (parcel, { sideEffect }) => {
    await markPickedUp(parcel.parcelId);
    await sideEffect('email', () => sendShippingEmail(parcel)); // never fails the webhook
  },
  onDelivered: async (parcel) => markDelivered(parcel.parcelId),
  onIncident: async (parcel) => reportIncident(parcel.parcelId, parcel.message)
});

// BEFORE express.json: the signature covers the received bytes.
app.post('/webhooks/sendcloud', express.raw({ type: 'application/json', limit: '1mb' }), webhook.middleware);

The signature is the HMAC-SHA256 of the raw body (hex), with the integration's "Webhook Signature Key" (webhookSecret) when it has one, else the secret key. Webhooks can arrive out of order: timestamp says when the status changed, always in milliseconds (1.1.0: seconds, milliseconds or an ISO date are converted), so an older status never overwrites a newer one. With an event log that can prune (createPostgresEventLog), handled events older than 90 days are deleted at most once a day, after the answer (pruneOlderThanMs, false to do it yourself; pruneEveryMs; settled()). Wrong signature, parsed or unreadable body: 400 (no endless retries). Another event type: 200, ignored. The same body again: 200 duplicate. An error in your handlers: 500 and the event is released, so Sendcloud's resend is handled.

Another carrier

Extend Carrier and implement name, status(), shippingMethods(), createLabel(), downloadLabel(), cancelLabel(), servicePoints(), verifySignature() and readEvent(). createCarrierWebhook works with any carrier (signatureHeader option).

Not in this package

Delivery prices, zones and countries served, orders, tables (except the event log from @astratra/payments), emails, and rate limiting of a public service point search: those belong to the shop.

Tests

npm test --workspace @astratra/shipping

No network: a fake Sendcloud answers and records every request.