@extantape/payload-plugin-shipping 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -8
- package/dist/api.d.ts +4 -0
- package/dist/api.js +83 -8
- package/dist/easypost.d.ts +14 -2
- package/dist/easypost.js +26 -13
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/plugin.d.ts +2 -0
- package/dist/plugin.js +20 -0
- package/dist/testing.d.ts +4 -1
- package/dist/testing.js +7 -2
- package/dist/types.d.ts +10 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,20 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
Shipping for Payload: addresses, carrier rates, labels, refunds of unused labels and tracking webhooks, with EasyPost as the first carrier provider.
|
|
4
4
|
|
|
5
|
-
**Status:** 0.
|
|
5
|
+
**Status:** 0.2.0 is the latest release (see [CHANGELOG.md](CHANGELOG.md)). 43 tests pass: 27 against Payload 3.92 with an in-memory MongoDB and a fake carrier, and 16 with no database, on the go-ahead, money, secrets and the webhook's refusals. The 27 cover addresses, parcels, buying, buying each quote once (in a row and at the same moment), returns, the side-effects hook and each answer it can give, production refused without it, a timed-out purchase, errors without addresses, and the webhook's 503, 401 (a custom provider's async check included), unknown, too-old, too-new, retry and refund cases, and purchases whose outcome is unclear. It has never called EasyPost: the request shapes follow EasyPost's documentation and are checked in test mode once a test key is saved. No site uses it yet.
|
|
6
6
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
9
9
|
- **Addresses** of three kinds (street, PO Box, General Delivery), with `addressProblems` in plain codes, `labelAddress` (refuses a guessed or placeholder address), `addressKey` and `carriersFor`: PO Box and General Delivery take USPS only. Both addresses on a label always come from your records, never a carrier account's defaults.
|
|
10
10
|
- **Carrier calls**, through a provider (EasyPost first):
|
|
11
11
|
- `quote`: Ground Advantage first, else the cheapest allowed. A PO Box or General Delivery address on either side gets USPS only, whatever the caller asked;
|
|
12
|
-
- `buy`, and `buyLabel` (a quote then a purchase);
|
|
12
|
+
- `buy`, and `buyLabel` (a quote then a purchase). **Each quote is bought once**: see below;
|
|
13
13
|
- `buyReturn`: from the customer to your hub's address, USPS only;
|
|
14
14
|
- `quoteReturn`;
|
|
15
15
|
- `refund`, for an unused label, within 30 days for USPS;
|
|
16
16
|
- `verifyAddress`.
|
|
17
|
-
- **Your go-ahead before every outside call.** `beforeExternalCall({ action, mode })` runs before every verify, quote, buy and refund, and a throw
|
|
18
|
-
- **Errors in plain words**, with a stable code. They never include a name, an address or your key. A purchase whose outcome is
|
|
17
|
+
- **Your go-ahead before every outside call.** `beforeExternalCall({ action, mode })` runs before every verify, quote, buy and refund, and **the external-call hook allows only `true`**. The call goes ahead when the hook answers exactly `true`, or a promise of it. Every other answer refuses it and nothing is sent: `false`, nothing at all, `1`, `'yes'`, an object, a throw or a rejected promise. A hook that only throws to refuse must now end with `return true`. Without the hook, test mode (an `EZTK…` key) is allowed and production mode is refused, so a copied live key can't buy postage from a test site by accident.
|
|
18
|
+
- **Errors in plain words**, with a stable code. They never include a name, an address or your key. A purchase whose outcome is unknown (a timeout, a dropped connection, a 408, a 429, a 5xx, an unreadable reply, or a label with no tracking number) fails with `MAYBE_BOUGHT`. The error says the label may have been bought, carries the shipment's id as `shipmentId`, and says how to settle it. Address checks return EasyPost's codes, never its text.
|
|
19
19
|
- **Parcels:** `parcelFor` (a box's outside size, longest side first, and weight), `billableLb` and `dimWeightLb` (USPS dimensional weight past one cubic foot), and `mailability` (too big, too heavy, the nonstandard fees, in words).
|
|
20
20
|
- **Tracking:** `trackingLink` for USPS and UPS, and `noticeFor`, which maps a carrier status to out for delivery, delivered or an exception. Sending the emails is yours, through Notifications or your own code.
|
|
21
21
|
- **The webhook** at `/api/easypost/webhook` (a root endpoint, `webhookPath`). It fails closed:
|
|
@@ -26,17 +26,29 @@ Shipping for Payload: addresses, carrier rates, labels, refunds of unused labels
|
|
|
26
26
|
- a handler that throws, or answers anything but `'handled'` or `'unknown'`: 500, so the carrier retries.
|
|
27
27
|
|
|
28
28
|
Handlers are yours, or another plugin's, registered at `config.custom.shippingHandlers` with no import. They must be idempotent, because carriers retry.
|
|
29
|
-
- **
|
|
29
|
+
- **Buy each quote once.** `buy` and `buyLabel` claim the quote in a record with a unique key before the carrier is called, so one quote ends in one purchase, across repeated calls, calls made at the same moment and several server instances.
|
|
30
|
+
- a second `buy` of a bought quote answers the first label, with no carrier call;
|
|
31
|
+
- a `buy` that arrives while the first is still running is refused with `BUY_IN_PROGRESS`, with no carrier call. So is every later one if the server stopped mid-purchase;
|
|
32
|
+
- after `MAYBE_BOUGHT` the quote stays locked, and every later `buy` of it answers `MAYBE_BOUGHT` with no carrier call. To settle it, look up the shipment (`shipmentId` on the error) with the carrier. If it has a label, use it or `refund` it. If it has none, get a new quote and buy that one;
|
|
33
|
+
- after a clear refusal from the carrier nothing was bought, and the same quote can be tried again;
|
|
34
|
+
- if the claim can't be stored, the answer is `NOT_CLAIMED` and nothing is sent.
|
|
35
|
+
|
|
36
|
+
The purchase request also carries an `Idempotency-Key` header made from the quote's shipment and rate. EasyPost's documentation, as read on 2026-11-26, doesn't describe that header, so the plugin doesn't count on it: the record is what holds.
|
|
37
|
+
- **One collection, `shipping-purchases`**, for those claims: the quote's key, a status, the shipment's id and the label that came back (tracking number, label link, price). It holds no name or address, it's hidden from the admin, and every access rule answers no, so only the plugin's server code reads or writes it. The claim is written outside any transaction of yours. Your own code still records each label against its order or kit.
|
|
30
38
|
- **A fake carrier for tests and dry runs**, only from `@extantape/payload-plugin-shipping/testing`, so a production bundle can't pick it by accident. Its prices are made up, and every rate and label says `fake: true`.
|
|
31
39
|
|
|
32
40
|
## On its own, and with others
|
|
33
41
|
|
|
34
|
-
**On its own:** Shipping needs only Payload and an EasyPost key, which your site passes in, or the fake carrier for tests. It adds
|
|
42
|
+
**On its own:** Shipping needs only Payload and an EasyPost key, which your site passes in, or the fake carrier for tests. It adds one small collection, `shipping-purchases`, which keeps each quote to one purchase. Your own code records each label it buys against its order, and your own handlers answer the webhook.
|
|
43
|
+
|
|
44
|
+
**Needs:** Payload `^3.80.0` as a peer dependency. No other EXTANT APE plugin is required.
|
|
35
45
|
|
|
36
46
|
**Works with:**
|
|
37
47
|
- **Sample Kits:** your site passes Shipping's functions into Sample Kits' `adapters.shipping`, and Sample Kits registers its tracking and refund handler at `config.custom.shippingHandlers`. The two never import each other.
|
|
38
48
|
- **Notifications:** Shipping sends nothing itself. `noticeFor` turns a carrier status into out for delivery, delivered or a problem, and the plugin that owns the parcel can send that through Notifications.
|
|
39
|
-
- **Kitting:** Kitting's box suggestions can use Shipping's rates. From Kitting 0.3
|
|
49
|
+
- **Kitting:** Kitting's box suggestions can use Shipping's rates. From Kitting 0.3, pass Shipping's `quote` to Kitting's adapter as it is: `shipping: { provider: ratesFromShipping({ quote, from }) }`. Neither plugin imports the other, and every quote still goes through your `beforeExternalCall` hook. If a quote fails, Kitting packs by its own postage rates and marks the suggestion.
|
|
50
|
+
|
|
51
|
+
**Color Theory:** none needed. It has no screens of its own, and its collections use Payload's standard admin, which takes Color Theory's admin colors when its `applyToAdmin` option is on.
|
|
40
52
|
|
|
41
53
|
**Family:** Shipping sits in the Fulfillment family, with Kitting, Restock, Sample Kits, Scan, Labels, Wizards, Custody and Sequences, though the families are a working draft and Fulfillment is due to be split into different groups.
|
|
42
54
|
|
|
@@ -51,7 +63,7 @@ import { easyPost, shippingPlugin } from '@extantape/payload-plugin-shipping'
|
|
|
51
63
|
|
|
52
64
|
shippingPlugin({
|
|
53
65
|
provider: easyPost({ apiKey: process.env.EASYPOST_API_KEY, webhookSecret: process.env.EASYPOST_WEBHOOK_SECRET }),
|
|
54
|
-
beforeExternalCall: ({ action, mode }) => mySideEffectsCheck('easypost', action, mode), //
|
|
66
|
+
beforeExternalCall: ({ action, mode }) => mySideEffectsCheck('easypost', action, mode) === true, // only an exact true allows the call
|
|
55
67
|
handlers: [{ owner: 'orders', onTracker: async ({ event }) => (await markTracking(event)) ? 'handled' : 'unknown' }],
|
|
56
68
|
})
|
|
57
69
|
```
|
|
@@ -65,6 +77,9 @@ The go-ahead hook guards the plugin's functions (`quote`, `buy`, `buyLabel`, `re
|
|
|
65
77
|
- US addresses only for now.
|
|
66
78
|
- EasyPost is the only provider. The contract allows others.
|
|
67
79
|
- A label ledger across owners is planned, not in 0.1.
|
|
80
|
+
- Buying once is per quote. `buyLabel` and `buyReturn` make a new quote on every call, so calling one of them twice for the same order buys two labels. To make a retry safe, call `quote`, keep the quote with the order, and `buy` that.
|
|
81
|
+
- A locked quote is settled by hand, with the steps above. The plugin doesn't look the shipment up at the carrier for you yet.
|
|
82
|
+
- Buying once is enforced in the plugin's functions. The provider object on its own keeps no record.
|
|
68
83
|
|
|
69
84
|
## Commands
|
|
70
85
|
|
package/dist/api.d.ts
CHANGED
|
@@ -9,6 +9,10 @@ export declare function quote(payload: Payload, input: {
|
|
|
9
9
|
carrier?: 'any' | 'USPS';
|
|
10
10
|
reference: string;
|
|
11
11
|
}, req?: Req): Promise<Quote>;
|
|
12
|
+
/**
|
|
13
|
+
* Buys a quote's label, once. A second call with the same quote answers the first label without calling the carrier,
|
|
14
|
+
* and calls made at the same moment end in one purchase. See `buyOnce` for each answer.
|
|
15
|
+
*/
|
|
12
16
|
export declare function buy(payload: Payload, q: Quote, req?: Req): Promise<Label>;
|
|
13
17
|
/** A quote and a purchase. Both addresses always come from the caller: never the carrier account's defaults. */
|
|
14
18
|
export declare function buyLabel(payload: Payload, input: {
|
package/dist/api.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { labelAddress } from './address.js';
|
|
2
|
-
import { CarrierError } from './easypost.js';
|
|
2
|
+
import { CarrierError, maybeBought, reconcileSteps } from './easypost.js';
|
|
3
|
+
import { PURCHASES_SLUG } from './plugin.js';
|
|
3
4
|
const configOf = (payload) => {
|
|
4
5
|
const o = payload.config.custom?.shipping;
|
|
5
6
|
if (!o)
|
|
@@ -7,16 +8,22 @@ const configOf = (payload) => {
|
|
|
7
8
|
return o;
|
|
8
9
|
};
|
|
9
10
|
/**
|
|
10
|
-
* Every call that costs money or reaches the carrier passes the site's `beforeExternalCall` first
|
|
11
|
-
*
|
|
11
|
+
* Every call that costs money or reaches the carrier passes the site's `beforeExternalCall` first, and goes ahead only
|
|
12
|
+
* when the hook answers exactly `true` (or a promise of it). Any other answer refuses the call: `false`, nothing at
|
|
13
|
+
* all, `1`, `'yes'`, an object, a throw or a rejected promise. With no hook, test mode is allowed and production mode
|
|
14
|
+
* is refused: the plugin fails closed.
|
|
12
15
|
*/
|
|
13
16
|
async function guard(payload, action, req) {
|
|
14
17
|
const o = configOf(payload);
|
|
15
18
|
const mode = o.provider.mode;
|
|
16
19
|
if (!mode)
|
|
17
20
|
throw new CarrierError(0, 'NO_KEY', 'Shipping isn’t set up here.');
|
|
18
|
-
if (o.beforeExternalCall)
|
|
19
|
-
|
|
21
|
+
if (o.beforeExternalCall != null) {
|
|
22
|
+
// A throw or a rejection carries the site's own reason out to the caller, and nothing is sent.
|
|
23
|
+
const answer = await o.beforeExternalCall({ action, mode, req });
|
|
24
|
+
if (answer !== true)
|
|
25
|
+
throw new CarrierError(0, 'REFUSED', 'The site’s go-ahead (beforeExternalCall) didn’t answer exactly true, so nothing was sent to the carrier.');
|
|
26
|
+
}
|
|
20
27
|
else if (mode === 'production')
|
|
21
28
|
throw new CarrierError(0, 'REFUSED', 'Live postage needs the site’s go-ahead (beforeExternalCall), which isn’t set.');
|
|
22
29
|
}
|
|
@@ -31,17 +38,85 @@ export async function quote(payload, input, req) {
|
|
|
31
38
|
await guard(payload, 'quote', req);
|
|
32
39
|
return configOf(payload).provider.quote({ ...input, carrier: carrierFor(input) });
|
|
33
40
|
}
|
|
41
|
+
const PURCHASES = PURCHASES_SLUG;
|
|
42
|
+
/**
|
|
43
|
+
* Buy each quote once. The quote is claimed first, as a record with a unique key, and the carrier is called only by
|
|
44
|
+
* the caller whose claim went in. Everyone else gets the first label when there is one, and is refused otherwise,
|
|
45
|
+
* with nothing sent. The claim is written outside any transaction of the caller's, so rolling that back can't free a
|
|
46
|
+
* quote whose label was bought.
|
|
47
|
+
*
|
|
48
|
+
* - bought: the first label again;
|
|
49
|
+
* - being bought right now, or interrupted before the answer was recorded: `BUY_IN_PROGRESS`;
|
|
50
|
+
* - outcome unknown (a timeout, a dropped connection, a 408, 429 or 5xx): `MAYBE_BOUGHT`, and the quote stays locked;
|
|
51
|
+
* - a clear refusal from the carrier: nothing was bought, so the claim is removed and the quote can be tried again;
|
|
52
|
+
* - the claim can't be stored: `NOT_CLAIMED`, and nothing is sent.
|
|
53
|
+
*/
|
|
54
|
+
async function buyOnce(payload, q) {
|
|
55
|
+
const provider = configOf(payload).provider;
|
|
56
|
+
const shipmentId = typeof q?.shipmentId === 'string' ? q.shipmentId.trim() : '';
|
|
57
|
+
if (!shipmentId || !q.rate?.id)
|
|
58
|
+
throw new CarrierError(0, 'BAD_QUOTE', 'This quote has no shipment or rate, so it can’t be bought. Get a new quote.');
|
|
59
|
+
// One label per shipment: the rate isn't in the key, so a second rate on the same shipment can't buy a second label.
|
|
60
|
+
const quoteKey = `${provider.name}:${provider.mode}:${shipmentId}`;
|
|
61
|
+
const held = async (limit) => (await payload.find({ collection: PURCHASES, where: { quoteKey: { equals: quoteKey } }, limit, depth: 0, pagination: false })).docs;
|
|
62
|
+
const inProgress = () => new CarrierError(0, 'BUY_IN_PROGRESS', `This quote is already being bought, or a purchase of it was interrupted, so nothing was sent to the carrier. If this doesn’t clear in a minute, the label may have been bought. ${reconcileSteps(shipmentId)}`, shipmentId);
|
|
63
|
+
const notClaimed = () => new CarrierError(0, 'NOT_CLAIMED', 'The purchase couldn’t be recorded, so nothing was sent to the carrier. Nothing was bought; try again.', shipmentId);
|
|
64
|
+
let claim;
|
|
65
|
+
try {
|
|
66
|
+
claim = (await payload.create({ collection: PURCHASES, data: { quoteKey, status: 'buying', shipmentId }, depth: 0, disableTransaction: true }));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// Either the quote is already claimed (the unique key refused this one) or the record couldn't be written.
|
|
70
|
+
const first = (await held(1).catch(() => []))[0];
|
|
71
|
+
if (!first)
|
|
72
|
+
throw notClaimed();
|
|
73
|
+
if (first.status === 'bought' && first.label)
|
|
74
|
+
return first.label;
|
|
75
|
+
if (first.status === 'unknown')
|
|
76
|
+
throw maybeBought('an earlier purchase of this quote got no clear answer', shipmentId, 'The carrier');
|
|
77
|
+
throw inProgress();
|
|
78
|
+
}
|
|
79
|
+
// Belt and braces, for a database whose unique index isn't built yet: anyone who sees a second claim steps back.
|
|
80
|
+
const claims = await held(2).catch(() => null);
|
|
81
|
+
if (!claims || claims.length !== 1) {
|
|
82
|
+
await payload.delete({ collection: PURCHASES, id: claim.id, depth: 0, disableTransaction: true }).catch(() => undefined);
|
|
83
|
+
throw claims ? inProgress() : notClaimed();
|
|
84
|
+
}
|
|
85
|
+
const record = (data) => payload.update({ collection: PURCHASES, id: claim.id, data: data, depth: 0, disableTransaction: true }).catch((error) => {
|
|
86
|
+
// The claim stays as it was, which still locks the quote.
|
|
87
|
+
payload.logger.error({ err: { name: error?.name }, msg: 'shipping: a purchase’s outcome couldn’t be recorded; its quote stays locked' });
|
|
88
|
+
});
|
|
89
|
+
let label;
|
|
90
|
+
try {
|
|
91
|
+
label = await provider.buy(q);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (error instanceof CarrierError && error.code !== 'MAYBE_BOUGHT') {
|
|
95
|
+
// A clear refusal: nothing was bought. If the claim can't be removed it stays, and the quote stays locked.
|
|
96
|
+
await payload.delete({ collection: PURCHASES, id: claim.id, depth: 0, disableTransaction: true }).catch(() => undefined);
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
await record({ status: 'unknown' });
|
|
100
|
+
// An error that isn't the provider's own says nothing about the purchase, so it's unknown too.
|
|
101
|
+
throw error instanceof CarrierError && error.shipmentId ? error : maybeBought('UNKNOWN', shipmentId, 'The carrier');
|
|
102
|
+
}
|
|
103
|
+
await record({ status: 'bought', label });
|
|
104
|
+
return label;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Buys a quote's label, once. A second call with the same quote answers the first label without calling the carrier,
|
|
108
|
+
* and calls made at the same moment end in one purchase. See `buyOnce` for each answer.
|
|
109
|
+
*/
|
|
34
110
|
export async function buy(payload, q, req) {
|
|
35
111
|
await guard(payload, 'buy', req);
|
|
36
|
-
return
|
|
112
|
+
return buyOnce(payload, q);
|
|
37
113
|
}
|
|
38
114
|
/** A quote and a purchase. Both addresses always come from the caller: never the carrier account's defaults. */
|
|
39
115
|
export async function buyLabel(payload, input, req) {
|
|
40
116
|
// Both checks before anything leaves: a refused purchase costs no quote. The hook sees each action once.
|
|
41
117
|
await guard(payload, 'buy', req);
|
|
42
118
|
await guard(payload, 'quote', req);
|
|
43
|
-
|
|
44
|
-
return provider.buy(await provider.quote({ ...input, carrier: carrierFor(input) }));
|
|
119
|
+
return buyOnce(payload, await configOf(payload).provider.quote({ ...input, carrier: carrierFor(input) }));
|
|
45
120
|
}
|
|
46
121
|
/**
|
|
47
122
|
* A return label from the customer to a hub, written out from the hub's record, USPS only (PO Box and General
|
package/dist/easypost.d.ts
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
|
-
import type { CarrierProvider, Mode, Rate } from './types.js';
|
|
1
|
+
import type { CarrierProvider, Mode, Quote, Rate } from './types.js';
|
|
2
2
|
/** Every EasyPost call gives up after this long. */
|
|
3
3
|
export declare const CALL_TIMEOUT_MS = 60000;
|
|
4
4
|
/** An error from EasyPost or the client, in plain words, with a stable code. Never carries an address or a key. */
|
|
5
5
|
export declare class CarrierError extends Error {
|
|
6
6
|
readonly status: number;
|
|
7
7
|
readonly code: string;
|
|
8
|
-
|
|
8
|
+
/** The carrier's shipment, when the error is about one purchase: what to look up when the outcome is unknown. */
|
|
9
|
+
readonly shipmentId?: string | undefined;
|
|
10
|
+
constructor(status: number, code: string, message: string,
|
|
11
|
+
/** The carrier's shipment, when the error is about one purchase: what to look up when the outcome is unknown. */
|
|
12
|
+
shipmentId?: string | undefined);
|
|
9
13
|
}
|
|
14
|
+
/** How to find out what happened to a purchase with no clear answer. */
|
|
15
|
+
export declare const reconcileSteps: (shipmentId: string) => string;
|
|
16
|
+
/** A purchase whose outcome isn't known: it may have been bought, so nobody should simply buy again. */
|
|
17
|
+
export declare const maybeBought: (why: string, shipmentId: string, carrier?: string) => CarrierError;
|
|
18
|
+
/** The same quote always gives the same key, and a different shipment or rate gives a different one. */
|
|
19
|
+
export declare const idempotencyKey: (quote: Pick<Quote, "shipmentId"> & {
|
|
20
|
+
rate: Pick<Rate, "id">;
|
|
21
|
+
}) => string;
|
|
10
22
|
export declare const modeOf: (key?: string | null) => Mode | null;
|
|
11
23
|
/** Ground Advantage first, else the cheapest allowed rate. PO Box and General Delivery take USPS only. */
|
|
12
24
|
export declare function pickRate(rates: Rate[], carrier: 'any' | 'USPS'): Rate | null;
|
package/dist/easypost.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
const API = 'https://api.easypost.com/v2';
|
|
3
3
|
/** Every EasyPost call gives up after this long. */
|
|
4
4
|
export const CALL_TIMEOUT_MS = 60_000;
|
|
@@ -6,15 +6,23 @@ export const CALL_TIMEOUT_MS = 60_000;
|
|
|
6
6
|
export class CarrierError extends Error {
|
|
7
7
|
status;
|
|
8
8
|
code;
|
|
9
|
-
|
|
9
|
+
shipmentId;
|
|
10
|
+
constructor(status, code, message,
|
|
11
|
+
/** The carrier's shipment, when the error is about one purchase: what to look up when the outcome is unknown. */
|
|
12
|
+
shipmentId) {
|
|
10
13
|
super(message);
|
|
11
14
|
this.status = status;
|
|
12
15
|
this.code = code;
|
|
16
|
+
this.shipmentId = shipmentId;
|
|
13
17
|
this.name = 'CarrierError';
|
|
14
18
|
}
|
|
15
19
|
}
|
|
20
|
+
/** How to find out what happened to a purchase with no clear answer. */
|
|
21
|
+
export const reconcileSteps = (shipmentId) => `Look up shipment ${shipmentId} with the carrier. If it has a label, use that label or refund it. If it has none, get a new quote and buy that one.`;
|
|
16
22
|
/** A purchase whose outcome isn't known: it may have been bought, so nobody should simply buy again. */
|
|
17
|
-
const maybeBought = (why) => new CarrierError(0, 'MAYBE_BOUGHT',
|
|
23
|
+
export const maybeBought = (why, shipmentId, carrier = 'EasyPost') => new CarrierError(0, 'MAYBE_BOUGHT', `${carrier}’s answer was unclear (${why}). The label may have been bought anyway. ${reconcileSteps(shipmentId)}`, shipmentId);
|
|
24
|
+
/** The same quote always gives the same key, and a different shipment or rate gives a different one. */
|
|
25
|
+
export const idempotencyKey = (quote) => createHash('sha256').update(`buy\n${quote.shipmentId}\n${quote.rate.id}`, 'utf8').digest('hex');
|
|
18
26
|
export const modeOf = (key) => (!key ? null : key.startsWith('EZTK') ? 'test' : 'production');
|
|
19
27
|
const toEasyPost = (a) => ({ name: a.name, company: a.company, street1: a.street1, street2: a.street2, city: a.city, state: a.state, zip: a.zip, country: a.country, phone: a.phone });
|
|
20
28
|
const parcelBody = (p) => ({ weight: p.weightOz, ...(p.lengthIn ? { length: p.lengthIn, width: p.widthIn, height: p.heightIn } : {}) });
|
|
@@ -30,16 +38,20 @@ export function pickRate(rates, carrier) {
|
|
|
30
38
|
export function easyPost(opts) {
|
|
31
39
|
const key = opts.apiKey ?? null;
|
|
32
40
|
const mode = modeOf(key);
|
|
33
|
-
|
|
41
|
+
/** `purchase` marks the one call that spends money: it carries the quote's key, and an unclear answer is unknown. */
|
|
42
|
+
const call = async (method, path, body, purchase) => {
|
|
34
43
|
if (!key)
|
|
35
44
|
throw new CarrierError(0, 'NO_KEY', 'EasyPost isn’t set up here.');
|
|
36
|
-
const buying =
|
|
45
|
+
const buying = Boolean(purchase);
|
|
46
|
+
const unknown = (why) => maybeBought(why, purchase.shipmentId);
|
|
37
47
|
let res;
|
|
38
48
|
try {
|
|
39
49
|
res = await (opts.fetchImpl ?? fetch)(`${API}${path}`, {
|
|
40
50
|
signal: AbortSignal.timeout(opts.timeoutMs ?? CALL_TIMEOUT_MS),
|
|
41
51
|
method,
|
|
42
|
-
|
|
52
|
+
// EasyPost's documentation (read 2026-11-26) doesn't describe an Idempotency-Key header, so nothing here relies
|
|
53
|
+
// on it being honored: the plugin's own purchase record is what keeps a quote to one purchase.
|
|
54
|
+
headers: { Authorization: `Basic ${Buffer.from(`${key}:`).toString('base64')}`, 'Content-Type': 'application/json', ...(purchase ? { 'Idempotency-Key': purchase.key } : {}) },
|
|
43
55
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
44
56
|
});
|
|
45
57
|
}
|
|
@@ -47,25 +59,26 @@ export function easyPost(opts) {
|
|
|
47
59
|
const name = error?.name;
|
|
48
60
|
// A purchase whose request may have left this machine may still have gone through: say so, never "nothing was bought".
|
|
49
61
|
if (buying)
|
|
50
|
-
throw
|
|
62
|
+
throw unknown(name === 'TimeoutError' || name === 'AbortError' ? 'TIMEOUT' : 'NETWORK');
|
|
51
63
|
if (name !== 'TimeoutError' && name !== 'AbortError')
|
|
52
64
|
throw new CarrierError(0, 'NETWORK', 'EasyPost couldn’t be reached. Nothing was bought; try again.');
|
|
53
65
|
throw new CarrierError(0, 'TIMEOUT', 'EasyPost didn’t answer in time. Nothing was bought; try again.');
|
|
54
66
|
}
|
|
55
67
|
const json = (await res.json().catch(() => null));
|
|
56
|
-
// Only a clear 4xx is a clear refusal. A 5xx or 502 from a gateway,
|
|
57
|
-
|
|
58
|
-
|
|
68
|
+
// Only a clear 4xx is a clear refusal. A 5xx or 502 from a gateway, a 408 or 429 (the request may have been taken
|
|
69
|
+
// before the answer was cut short or throttled), or a reply that can't be read, leaves a purchase unknown.
|
|
70
|
+
if (buying && (res.status >= 500 || res.status === 408 || res.status === 429 || (res.ok && !json) || (!res.ok && res.status < 400)))
|
|
71
|
+
throw unknown(`HTTP_${res.status}`);
|
|
59
72
|
if (!res.ok)
|
|
60
73
|
throw new CarrierError(res.status, json?.error?.code ?? 'HTTP_ERROR', `EasyPost refused (${json?.error?.code ?? res.status}).`);
|
|
61
74
|
if (!json)
|
|
62
75
|
throw new CarrierError(res.status, 'BAD_REPLY', 'EasyPost’s reply couldn’t be read. Nothing was bought; try again.');
|
|
63
76
|
return json;
|
|
64
77
|
};
|
|
65
|
-
const asLabel = (b, fallback) => {
|
|
78
|
+
const asLabel = (b, fallback, shipmentId) => {
|
|
66
79
|
// A label with no shipment id or tracking number can't be refunded or followed: treat the purchase as unknown.
|
|
67
80
|
if (!b.id || !b.tracking_code)
|
|
68
|
-
throw maybeBought('INCOMPLETE');
|
|
81
|
+
throw maybeBought('INCOMPLETE', b.id || shipmentId);
|
|
69
82
|
const chosen = b.selected_rate ?? fallback;
|
|
70
83
|
return { shipmentId: b.id, tracking: b.tracking_code, carrier: chosen.carrier, service: chosen.service, rateCents: Math.round(Number(chosen.rate) * 100), labelUrl: b.postage_label?.label_url ?? '', trackerUrl: b.tracker?.public_url ?? null, mode: mode, ...(chosen.fake ? { fake: true } : {}) };
|
|
71
84
|
};
|
|
@@ -86,7 +99,7 @@ export function easyPost(opts) {
|
|
|
86
99
|
throw new CarrierError(0, 'NO_RATE', input.carrier === 'USPS' ? 'EasyPost offered no USPS rate for this parcel.' : 'EasyPost offered no rate for this parcel.');
|
|
87
100
|
return { shipmentId: shipment.id, rate, rateCents: Math.round(Number(rate.rate) * 100), mode: mode, ...(rate.fake ? { fake: true } : {}) };
|
|
88
101
|
},
|
|
89
|
-
buy: async (quote) => asLabel(await call('POST', `/shipments/${encodeURIComponent(quote.shipmentId)}/buy`, { rate: { id: quote.rate.id } }), quote.rate),
|
|
102
|
+
buy: async (quote) => asLabel(await call('POST', `/shipments/${encodeURIComponent(quote.shipmentId)}/buy`, { rate: { id: quote.rate.id } }, { shipmentId: quote.shipmentId, key: idempotencyKey(quote) }), quote.rate, quote.shipmentId),
|
|
90
103
|
refund: async (shipmentId) => (await call('POST', `/shipments/${encodeURIComponent(shipmentId)}/refund`, {})).refund_status ?? 'submitted',
|
|
91
104
|
webhook: {
|
|
92
105
|
configured: Boolean(opts.webhookSecret),
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { shippingPlugin, handlersOf } from './plugin.js';
|
|
1
|
+
export { shippingPlugin, handlersOf, PURCHASES_SLUG } from './plugin.js';
|
|
2
2
|
export { buy, buyLabel, buyReturn, quote, quoteReturn, refund, verifyAddress } from './api.js';
|
|
3
|
-
export { CALL_TIMEOUT_MS, CarrierError, easyPost, modeOf, pickRate } from './easypost.js';
|
|
3
|
+
export { CALL_TIMEOUT_MS, CarrierError, easyPost, idempotencyKey, modeOf, pickRate } from './easypost.js';
|
|
4
4
|
export { ADDRESS_KINDS, AddressError, addressKey, addressProblems, carriersFor, labelAddress, type AddressKind, type AddressProblem, type LabelAddress, type StoredAddress } from './address.js';
|
|
5
5
|
export { billableLb, dimWeightLb, mailability, parcelFor, type ParcelSize } from './parcel.js';
|
|
6
6
|
export { noticeFor, trackingLink, USPS_REFUND_DAYS, type ShipmentEvent } from './tracking.js';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { shippingPlugin, handlersOf } from './plugin.js';
|
|
1
|
+
export { shippingPlugin, handlersOf, PURCHASES_SLUG } from './plugin.js';
|
|
2
2
|
export { buy, buyLabel, buyReturn, quote, quoteReturn, refund, verifyAddress } from './api.js';
|
|
3
|
-
export { CALL_TIMEOUT_MS, CarrierError, easyPost, modeOf, pickRate } from './easypost.js';
|
|
3
|
+
export { CALL_TIMEOUT_MS, CarrierError, easyPost, idempotencyKey, modeOf, pickRate } from './easypost.js';
|
|
4
4
|
export { ADDRESS_KINDS, AddressError, addressKey, addressProblems, carriersFor, labelAddress } from './address.js';
|
|
5
5
|
export { billableLb, dimWeightLb, mailability, parcelFor } from './parcel.js';
|
|
6
6
|
export { noticeFor, trackingLink, USPS_REFUND_DAYS } from './tracking.js';
|
package/dist/plugin.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { Payload, Plugin } from 'payload';
|
|
2
2
|
import type { ShippingHandler, ShippingOptions } from './types.js';
|
|
3
|
+
/** Where each purchase is claimed before the carrier is called, one record per quote. */
|
|
4
|
+
export declare const PURCHASES_SLUG = "shipping-purchases";
|
|
3
5
|
/** Every handler: the plugin's own options and those other plugins registered at `config.custom.shippingHandlers`. */
|
|
4
6
|
export declare const handlersOf: (payload: Payload) => ShippingHandler[];
|
|
5
7
|
/** Shipping: addresses, carrier quotes and labels, refunds of unused labels, and the carrier's webhook. */
|
package/dist/plugin.js
CHANGED
|
@@ -1,4 +1,23 @@
|
|
|
1
1
|
const DAY = 86_400_000;
|
|
2
|
+
/** Where each purchase is claimed before the carrier is called, one record per quote. */
|
|
3
|
+
export const PURCHASES_SLUG = 'shipping-purchases';
|
|
4
|
+
const nobody = () => false;
|
|
5
|
+
/**
|
|
6
|
+
* One record per quote, with a unique key: the claim that keeps a quote to one purchase, across calls and across
|
|
7
|
+
* server instances. It holds the shipment's id and the label that came back (tracking number, label link, price),
|
|
8
|
+
* and no name or address. Only the plugin's own server code reads or writes it: every access rule answers no.
|
|
9
|
+
*/
|
|
10
|
+
const purchases = {
|
|
11
|
+
slug: PURCHASES_SLUG,
|
|
12
|
+
admin: { hidden: true },
|
|
13
|
+
access: { read: nobody, create: nobody, update: nobody, delete: nobody },
|
|
14
|
+
fields: [
|
|
15
|
+
{ name: 'quoteKey', type: 'text', required: true, unique: true, index: true },
|
|
16
|
+
{ name: 'status', type: 'select', required: true, defaultValue: 'buying', options: ['buying', 'bought', 'unknown'] },
|
|
17
|
+
{ name: 'shipmentId', type: 'text', required: true },
|
|
18
|
+
{ name: 'label', type: 'json' },
|
|
19
|
+
],
|
|
20
|
+
};
|
|
2
21
|
/** Clocks differ a little; an event dated further ahead than this is refused. */
|
|
3
22
|
const FUTURE_SKEW_MS = 10 * 60_000;
|
|
4
23
|
const json = (body, status = 200) => Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
|
|
@@ -84,6 +103,7 @@ export const shippingPlugin = (options) => (config) => {
|
|
|
84
103
|
return {
|
|
85
104
|
...config,
|
|
86
105
|
custom: { ...config.custom, shipping: o },
|
|
106
|
+
collections: [...(config.collections ?? []), purchases],
|
|
87
107
|
// A root endpoint, so the URL is exactly /api<webhookPath>.
|
|
88
108
|
endpoints: [...(config.endpoints ?? []), webhook(o.webhookPath)],
|
|
89
109
|
};
|
package/dist/testing.d.ts
CHANGED
|
@@ -11,7 +11,8 @@ export declare function fakePrices(p: ParcelSize, zone: number): {
|
|
|
11
11
|
};
|
|
12
12
|
/**
|
|
13
13
|
* A fake carrier: EasyPost's shapes answered in memory. `calls` records what was asked, for tests. `fail` makes a
|
|
14
|
-
* path answer with an error, `hang` makes it time out, and `offer` leaves services out
|
|
14
|
+
* path answer with an error, `hang` makes it time out, `drop` cuts the connection, and `offer` leaves services out
|
|
15
|
+
* of the rates. Each call's headers are recorded too, without the key.
|
|
15
16
|
*/
|
|
16
17
|
export declare function fakeCarrier(over?: {
|
|
17
18
|
mode?: 'test' | 'production';
|
|
@@ -22,6 +23,7 @@ export declare function fakeCarrier(over?: {
|
|
|
22
23
|
code: string;
|
|
23
24
|
} | null;
|
|
24
25
|
hang?: (path: string) => boolean;
|
|
26
|
+
drop?: (path: string) => boolean;
|
|
25
27
|
timeoutMs?: number;
|
|
26
28
|
offer?: (rate: {
|
|
27
29
|
carrier: string;
|
|
@@ -53,6 +55,7 @@ export declare function fakeCarrier(over?: {
|
|
|
53
55
|
calls: {
|
|
54
56
|
path: string;
|
|
55
57
|
body: Record<string, unknown>;
|
|
58
|
+
headers: Record<string, string>;
|
|
56
59
|
}[];
|
|
57
60
|
shipments: Map<string, {
|
|
58
61
|
id: string;
|
package/dist/testing.js
CHANGED
|
@@ -29,7 +29,8 @@ const API = 'https://api.easypost.com/v2';
|
|
|
29
29
|
const digits = (n) => Array.from({ length: n }, () => randomInt(10)).join('');
|
|
30
30
|
/**
|
|
31
31
|
* A fake carrier: EasyPost's shapes answered in memory. `calls` records what was asked, for tests. `fail` makes a
|
|
32
|
-
* path answer with an error, `hang` makes it time out, and `offer` leaves services out
|
|
32
|
+
* path answer with an error, `hang` makes it time out, `drop` cuts the connection, and `offer` leaves services out
|
|
33
|
+
* of the rates. Each call's headers are recorded too, without the key.
|
|
33
34
|
*/
|
|
34
35
|
export function fakeCarrier(over = {}) {
|
|
35
36
|
const shipments = new Map();
|
|
@@ -37,7 +38,11 @@ export function fakeCarrier(over = {}) {
|
|
|
37
38
|
const fetchImpl = (async (url, init) => {
|
|
38
39
|
const path = String(url).replace(API, '');
|
|
39
40
|
const body = (init?.body ? JSON.parse(String(init.body)) : {});
|
|
40
|
-
|
|
41
|
+
const headers = Object.fromEntries(new Headers(init?.headers));
|
|
42
|
+
delete headers.authorization;
|
|
43
|
+
calls.push({ path, body, headers });
|
|
44
|
+
if (over.drop?.(path))
|
|
45
|
+
throw new TypeError('fetch failed');
|
|
41
46
|
if (over.hang?.(path)) {
|
|
42
47
|
await new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(Object.assign(new Error('timed out'), { name: 'TimeoutError' }))));
|
|
43
48
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -70,6 +70,10 @@ export type CarrierProvider = {
|
|
|
70
70
|
carrier?: 'any' | 'USPS';
|
|
71
71
|
reference: string;
|
|
72
72
|
}) => Promise<Quote>;
|
|
73
|
+
/**
|
|
74
|
+
* Buys the quote's label. An unclear outcome (a timeout, a dropped connection, a 408, 429 or 5xx) is a
|
|
75
|
+
* `CarrierError` with code `MAYBE_BOUGHT`; any other `CarrierError` means nothing was bought.
|
|
76
|
+
*/
|
|
73
77
|
buy: (quote: Quote) => Promise<Label>;
|
|
74
78
|
refund: (shipmentId: string) => Promise<RefundStatus>;
|
|
75
79
|
/** Webhooks: is this raw body signed by the carrier, and what does it say? */
|
|
@@ -102,12 +106,16 @@ export type ShippingOptions = {
|
|
|
102
106
|
provider: CarrierProvider;
|
|
103
107
|
/** A root endpoint path. Default '/easypost/webhook', so it serves /api/easypost/webhook. */
|
|
104
108
|
webhookPath?: string;
|
|
105
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Runs before every call that costs money or reaches the carrier. Answer exactly `true` (or a promise of it) to
|
|
111
|
+
* allow the call. Any other answer refuses it: `false`, nothing at all, `1`, `'yes'`, an object, a throw or a
|
|
112
|
+
* rejected promise. Without the hook, production mode is refused.
|
|
113
|
+
*/
|
|
106
114
|
beforeExternalCall?: (args: {
|
|
107
115
|
action: ExternalAction;
|
|
108
116
|
mode: Mode;
|
|
109
117
|
req?: Req;
|
|
110
|
-
}) =>
|
|
118
|
+
}) => boolean | Promise<boolean>;
|
|
111
119
|
handlers?: ShippingHandler[];
|
|
112
120
|
/** Events older than this are ignored, so a captured body can't be replayed later. Default 7. */
|
|
113
121
|
maxEventAgeDays?: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-shipping",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Shipping for Payload: addresses, carrier rates, labels, refunds of unused labels and tracking webhooks, with EasyPost as the first carrier provider.",
|
|
5
5
|
"homepage": "https://github.com/ExtantApe/payload-plugin-shipping#readme",
|
|
6
6
|
"bugs": {
|