@extantape/payload-plugin-shipping 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +93 -2
- package/dist/address.d.ts +58 -0
- package/dist/address.js +75 -0
- package/dist/api.d.ts +49 -0
- package/dist/api.js +139 -0
- package/dist/easypost.d.ts +34 -0
- package/dist/easypost.js +134 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/parcel.d.ts +27 -0
- package/dist/parcel.js +50 -0
- package/dist/plugin.d.ts +8 -0
- package/dist/plugin.js +110 -0
- package/dist/testing.d.ts +68 -0
- package/dist/testing.js +88 -0
- package/dist/tracking.d.ts +8 -0
- package/dist/tracking.js +19 -0
- package/dist/types.d.ts +126 -0
- package/dist/types.js +1 -0
- package/package.json +67 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EXTANT APE
|
|
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.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# payload-plugin-shipping
|
|
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
|
+
|
|
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
|
+
|
|
7
|
+
## What it does
|
|
8
|
+
|
|
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
|
+
- **Carrier calls**, through a provider (EasyPost first):
|
|
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). **Each quote is bought once**: see below;
|
|
13
|
+
- `buyReturn`: from the customer to your hub's address, USPS only;
|
|
14
|
+
- `quoteReturn`;
|
|
15
|
+
- `refund`, for an unused label, within 30 days for USPS;
|
|
16
|
+
- `verifyAddress`.
|
|
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
|
+
- **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
|
+
- **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
|
+
- **The webhook** at `/api/easypost/webhook` (a root endpoint, `webhookPath`). It fails closed:
|
|
22
|
+
- no secret configured: 503;
|
|
23
|
+
- unsigned or wrongly signed: 401, with the HMAC checked over the raw bytes before anything is parsed. A custom provider's `webhook.verify` may be sync or async, and only an answer of exactly `true` counts: `false`, `1`, an object such as `{ valid: false }`, or an error thrown or rejected is a 401;
|
|
24
|
+
- a tracker or refund event older than 7 days, or dated more than 10 minutes ahead, is ignored, so a captured body can't be replayed later;
|
|
25
|
+
- an event no handler claims: 200 "unknown", nothing written;
|
|
26
|
+
- a handler that throws, or answers anything but `'handled'` or `'unknown'`: 500, so the carrier retries.
|
|
27
|
+
|
|
28
|
+
Handlers are yours, or another plugin's, registered at `config.custom.shippingHandlers` with no import. They must be idempotent, because carriers retry.
|
|
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.
|
|
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`.
|
|
39
|
+
|
|
40
|
+
## On its own, and with others
|
|
41
|
+
|
|
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.
|
|
45
|
+
|
|
46
|
+
**Works with:**
|
|
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.
|
|
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.
|
|
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.
|
|
52
|
+
|
|
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.
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
npm install @extantape/payload-plugin-shipping
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { easyPost, shippingPlugin } from '@extantape/payload-plugin-shipping'
|
|
63
|
+
|
|
64
|
+
shippingPlugin({
|
|
65
|
+
provider: easyPost({ apiKey: process.env.EASYPOST_API_KEY, webhookSecret: process.env.EASYPOST_WEBHOOK_SECRET }),
|
|
66
|
+
beforeExternalCall: ({ action, mode }) => mySideEffectsCheck('easypost', action, mode) === true, // only an exact true allows the call
|
|
67
|
+
handlers: [{ owner: 'orders', onTracker: async ({ event }) => (await markTracking(event)) ? 'handled' : 'unknown' }],
|
|
68
|
+
})
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The plugin reads no environment: your site passes the key and the secret in.
|
|
72
|
+
|
|
73
|
+
The go-ahead hook guards the plugin's functions (`quote`, `buy`, `buyLabel`, `refund` and the rest). The provider object itself, from `easyPost()` or `config.custom.shipping.provider`, calls the carrier directly: it's server code, so treat it like your key and go through the functions.
|
|
74
|
+
|
|
75
|
+
## Limits
|
|
76
|
+
|
|
77
|
+
- US addresses only for now.
|
|
78
|
+
- EasyPost is the only provider. The contract allows others.
|
|
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.
|
|
83
|
+
|
|
84
|
+
## Commands
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
npm test # integration tests, in-memory MongoDB, fake carrier
|
|
88
|
+
npm run typecheck
|
|
89
|
+
npm run build
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mailing addresses for labels (kits plan §6, owner 2026-11-09). A hub's address is one of three
|
|
3
|
+
* kinds, switchable in the admin without a code change:
|
|
4
|
+
* - street: a street address (also a private mailbox at a mail store, which is street-style);
|
|
5
|
+
* - po-box: a USPS PO Box, with no street;
|
|
6
|
+
* - general-delivery: USPS General Delivery at a post office: "GENERAL DELIVERY" as the street line and
|
|
7
|
+
* the office's ZIP+4 ending in -9999. Mail waits there about 30 days, so returns need prompt pickup.
|
|
8
|
+
* PO Box and General Delivery take USPS only. Labels always carry the address from the record, never
|
|
9
|
+
* a carrier account's default. Names and addresses live in the database only.
|
|
10
|
+
*/
|
|
11
|
+
export declare const ADDRESS_KINDS: readonly ["street", "po-box", "general-delivery"];
|
|
12
|
+
export type AddressKind = (typeof ADDRESS_KINDS)[number];
|
|
13
|
+
export type StoredAddress = {
|
|
14
|
+
kind?: AddressKind | null;
|
|
15
|
+
/** The recipient line, e.g. a person's name. */
|
|
16
|
+
name?: string | null;
|
|
17
|
+
/** The "C/O" line: the company the mail is in care of. */
|
|
18
|
+
company?: string | null;
|
|
19
|
+
line1?: string | null;
|
|
20
|
+
line2?: string | null;
|
|
21
|
+
poBox?: string | null;
|
|
22
|
+
city?: string | null;
|
|
23
|
+
state?: string | null;
|
|
24
|
+
postalCode?: string | null;
|
|
25
|
+
phone?: string | null;
|
|
26
|
+
};
|
|
27
|
+
/** What a label needs (EasyPost's address shape). */
|
|
28
|
+
export type LabelAddress = {
|
|
29
|
+
name: string;
|
|
30
|
+
company: string | null;
|
|
31
|
+
street1: string;
|
|
32
|
+
street2: string | null;
|
|
33
|
+
city: string;
|
|
34
|
+
state: string;
|
|
35
|
+
zip: string;
|
|
36
|
+
country: 'US';
|
|
37
|
+
phone: string | null;
|
|
38
|
+
};
|
|
39
|
+
export type AddressProblem = 'placeholder' | 'name' | 'street' | 'poBox' | 'city' | 'state' | 'zip' | 'gdZip';
|
|
40
|
+
/** Why this address can't go on a label, or an empty list. */
|
|
41
|
+
export declare function addressProblems(a: StoredAddress | null | undefined, opts?: {
|
|
42
|
+
placeholder?: boolean | null;
|
|
43
|
+
}): AddressProblem[];
|
|
44
|
+
/** The address as it goes on a label. Refuses an address with problems: no label to a guessed address. */
|
|
45
|
+
export declare function labelAddress(a: StoredAddress | null | undefined, opts?: {
|
|
46
|
+
placeholder?: boolean | null;
|
|
47
|
+
}): LabelAddress;
|
|
48
|
+
/**
|
|
49
|
+
* A short fingerprint of where a label sends mail, so a label made for an older hub address can be
|
|
50
|
+
* found after the address changes. Only the delivery fields count, not the phone.
|
|
51
|
+
*/
|
|
52
|
+
export declare function addressKey(a: LabelAddress): string;
|
|
53
|
+
/** Carriers allowed to deliver to this kind of address. */
|
|
54
|
+
export declare const carriersFor: (kind: AddressKind | null | undefined) => "any" | "USPS";
|
|
55
|
+
export declare class AddressError extends Error {
|
|
56
|
+
readonly problems: AddressProblem[];
|
|
57
|
+
constructor(problems: AddressProblem[]);
|
|
58
|
+
}
|
package/dist/address.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Mailing addresses for labels (kits plan §6, owner 2026-11-09). A hub's address is one of three
|
|
4
|
+
* kinds, switchable in the admin without a code change:
|
|
5
|
+
* - street: a street address (also a private mailbox at a mail store, which is street-style);
|
|
6
|
+
* - po-box: a USPS PO Box, with no street;
|
|
7
|
+
* - general-delivery: USPS General Delivery at a post office: "GENERAL DELIVERY" as the street line and
|
|
8
|
+
* the office's ZIP+4 ending in -9999. Mail waits there about 30 days, so returns need prompt pickup.
|
|
9
|
+
* PO Box and General Delivery take USPS only. Labels always carry the address from the record, never
|
|
10
|
+
* a carrier account's default. Names and addresses live in the database only.
|
|
11
|
+
*/
|
|
12
|
+
export const ADDRESS_KINDS = ['street', 'po-box', 'general-delivery'];
|
|
13
|
+
const clean = (v) => (v ?? '').trim();
|
|
14
|
+
const ZIP = /^\d{5}(-\d{4})?$/;
|
|
15
|
+
/** Why this address can't go on a label, or an empty list. */
|
|
16
|
+
export function addressProblems(a, opts = {}) {
|
|
17
|
+
const out = [];
|
|
18
|
+
if (opts.placeholder)
|
|
19
|
+
out.push('placeholder');
|
|
20
|
+
const kind = a?.kind ?? 'street';
|
|
21
|
+
// A PO Box or General Delivery item is only handed to the named person.
|
|
22
|
+
if (kind !== 'street' && !clean(a?.name))
|
|
23
|
+
out.push('name');
|
|
24
|
+
if (kind === 'street' && !clean(a?.line1))
|
|
25
|
+
out.push('street');
|
|
26
|
+
if (kind === 'po-box' && !/^\d{1,10}$/.test(clean(a?.poBox).replace(/^(PO\s*BOX\s*)/i, '')))
|
|
27
|
+
out.push('poBox');
|
|
28
|
+
if (!clean(a?.city))
|
|
29
|
+
out.push('city');
|
|
30
|
+
if (!/^[A-Z]{2}$/i.test(clean(a?.state)))
|
|
31
|
+
out.push('state');
|
|
32
|
+
const zip = clean(a?.postalCode);
|
|
33
|
+
if (!ZIP.test(zip))
|
|
34
|
+
out.push('zip');
|
|
35
|
+
else if (kind === 'general-delivery' && !/^\d{5}-9999$/.test(zip))
|
|
36
|
+
out.push('gdZip');
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** The address as it goes on a label. Refuses an address with problems: no label to a guessed address. */
|
|
40
|
+
export function labelAddress(a, opts = {}) {
|
|
41
|
+
const problems = addressProblems(a, opts);
|
|
42
|
+
if (problems.length)
|
|
43
|
+
throw new AddressError(problems);
|
|
44
|
+
const kind = a.kind ?? 'street';
|
|
45
|
+
const street1 = kind === 'po-box' ? `PO BOX ${clean(a.poBox).replace(/^(PO\s*BOX\s*)/i, '')}` : kind === 'general-delivery' ? 'GENERAL DELIVERY' : clean(a.line1);
|
|
46
|
+
return {
|
|
47
|
+
name: clean(a.name) || clean(a.company),
|
|
48
|
+
company: clean(a.company) ? `C/O ${clean(a.company).replace(/^C\/O\s*/i, '')}` : null,
|
|
49
|
+
street1,
|
|
50
|
+
// PO Box and General Delivery have no street; a second line would confuse the carrier.
|
|
51
|
+
street2: kind === 'street' ? clean(a.line2) || null : null,
|
|
52
|
+
city: clean(a.city),
|
|
53
|
+
state: clean(a.state).toUpperCase(),
|
|
54
|
+
zip: clean(a.postalCode),
|
|
55
|
+
country: 'US',
|
|
56
|
+
phone: clean(a.phone) || null,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A short fingerprint of where a label sends mail, so a label made for an older hub address can be
|
|
61
|
+
* found after the address changes. Only the delivery fields count, not the phone.
|
|
62
|
+
*/
|
|
63
|
+
export function addressKey(a) {
|
|
64
|
+
const fields = [a.name, a.company ?? '', a.street1, a.street2 ?? '', a.city, a.state, a.zip].map((f) => f.trim().toUpperCase().replace(/\s+/g, ' '));
|
|
65
|
+
return createHash('sha256').update(fields.join('|')).digest('hex').slice(0, 16);
|
|
66
|
+
}
|
|
67
|
+
/** Carriers allowed to deliver to this kind of address. */
|
|
68
|
+
export const carriersFor = (kind) => (kind && kind !== 'street' ? 'USPS' : 'any');
|
|
69
|
+
export class AddressError extends Error {
|
|
70
|
+
problems;
|
|
71
|
+
constructor(problems) {
|
|
72
|
+
super(`The address can't go on a label: ${problems.join(', ')}.`);
|
|
73
|
+
this.problems = problems;
|
|
74
|
+
}
|
|
75
|
+
}
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
import { type LabelAddress, type StoredAddress } from './address.js';
|
|
3
|
+
import type { Label, Parcel, Quote, RefundStatus, Req, Verification } from './types.js';
|
|
4
|
+
export declare function verifyAddress(payload: Payload, a: LabelAddress, req?: Req): Promise<Verification>;
|
|
5
|
+
export declare function quote(payload: Payload, input: {
|
|
6
|
+
from: LabelAddress;
|
|
7
|
+
to: LabelAddress;
|
|
8
|
+
parcel: Parcel;
|
|
9
|
+
carrier?: 'any' | 'USPS';
|
|
10
|
+
reference: string;
|
|
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
|
+
*/
|
|
16
|
+
export declare function buy(payload: Payload, q: Quote, req?: Req): Promise<Label>;
|
|
17
|
+
/** A quote and a purchase. Both addresses always come from the caller: never the carrier account's defaults. */
|
|
18
|
+
export declare function buyLabel(payload: Payload, input: {
|
|
19
|
+
from: LabelAddress;
|
|
20
|
+
to: LabelAddress;
|
|
21
|
+
parcel: Parcel;
|
|
22
|
+
carrier?: 'any' | 'USPS';
|
|
23
|
+
reference: string;
|
|
24
|
+
}, req?: Req): Promise<Label>;
|
|
25
|
+
/**
|
|
26
|
+
* A return label from the customer to a hub, written out from the hub's record, USPS only (PO Box and General
|
|
27
|
+
* Delivery take nothing else). Refuses a placeholder or incomplete hub address, and any other carrier.
|
|
28
|
+
*/
|
|
29
|
+
export declare function buyReturn(payload: Payload, input: {
|
|
30
|
+
customer: LabelAddress;
|
|
31
|
+
hub: {
|
|
32
|
+
address?: StoredAddress | null;
|
|
33
|
+
placeholder?: boolean | null;
|
|
34
|
+
};
|
|
35
|
+
parcel: Parcel;
|
|
36
|
+
carrier?: string;
|
|
37
|
+
reference: string;
|
|
38
|
+
}, req?: Req): Promise<Label>;
|
|
39
|
+
export declare function quoteReturn(payload: Payload, input: {
|
|
40
|
+
customer: LabelAddress;
|
|
41
|
+
hub: {
|
|
42
|
+
address?: StoredAddress | null;
|
|
43
|
+
placeholder?: boolean | null;
|
|
44
|
+
};
|
|
45
|
+
parcel: Parcel;
|
|
46
|
+
reference: string;
|
|
47
|
+
}, req?: Req): Promise<Quote>;
|
|
48
|
+
/** Ask for an unused label's money back (USPS: within 30 days, never scanned). */
|
|
49
|
+
export declare function refund(payload: Payload, shipmentId: string, req?: Req): Promise<RefundStatus>;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { labelAddress } from './address.js';
|
|
2
|
+
import { CarrierError, maybeBought, reconcileSteps } from './easypost.js';
|
|
3
|
+
import { PURCHASES_SLUG } from './plugin.js';
|
|
4
|
+
const configOf = (payload) => {
|
|
5
|
+
const o = payload.config.custom?.shipping;
|
|
6
|
+
if (!o)
|
|
7
|
+
throw new Error('Shipping: the plugin is not configured on this site.');
|
|
8
|
+
return o;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
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.
|
|
15
|
+
*/
|
|
16
|
+
async function guard(payload, action, req) {
|
|
17
|
+
const o = configOf(payload);
|
|
18
|
+
const mode = o.provider.mode;
|
|
19
|
+
if (!mode)
|
|
20
|
+
throw new CarrierError(0, 'NO_KEY', 'Shipping isn’t set up here.');
|
|
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
|
+
}
|
|
27
|
+
else if (mode === 'production')
|
|
28
|
+
throw new CarrierError(0, 'REFUSED', 'Live postage needs the site’s go-ahead (beforeExternalCall), which isn’t set.');
|
|
29
|
+
}
|
|
30
|
+
export async function verifyAddress(payload, a, req) {
|
|
31
|
+
await guard(payload, 'verify', req);
|
|
32
|
+
return configOf(payload).provider.verify(a);
|
|
33
|
+
}
|
|
34
|
+
/** PO Box and General Delivery take USPS only, whatever the caller asked: the label addresses say which they are. */
|
|
35
|
+
const USPS_ONLY = /^(PO BOX\b|GENERAL DELIVERY$)/i;
|
|
36
|
+
const carrierFor = (input) => input.carrier === 'USPS' || [input.from, input.to].some((a) => USPS_ONLY.test(a.street1.trim())) ? 'USPS' : 'any';
|
|
37
|
+
export async function quote(payload, input, req) {
|
|
38
|
+
await guard(payload, 'quote', req);
|
|
39
|
+
return configOf(payload).provider.quote({ ...input, carrier: carrierFor(input) });
|
|
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
|
+
*/
|
|
110
|
+
export async function buy(payload, q, req) {
|
|
111
|
+
await guard(payload, 'buy', req);
|
|
112
|
+
return buyOnce(payload, q);
|
|
113
|
+
}
|
|
114
|
+
/** A quote and a purchase. Both addresses always come from the caller: never the carrier account's defaults. */
|
|
115
|
+
export async function buyLabel(payload, input, req) {
|
|
116
|
+
// Both checks before anything leaves: a refused purchase costs no quote. The hook sees each action once.
|
|
117
|
+
await guard(payload, 'buy', req);
|
|
118
|
+
await guard(payload, 'quote', req);
|
|
119
|
+
return buyOnce(payload, await configOf(payload).provider.quote({ ...input, carrier: carrierFor(input) }));
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* A return label from the customer to a hub, written out from the hub's record, USPS only (PO Box and General
|
|
123
|
+
* Delivery take nothing else). Refuses a placeholder or incomplete hub address, and any other carrier.
|
|
124
|
+
*/
|
|
125
|
+
export async function buyReturn(payload, input, req) {
|
|
126
|
+
if (input.carrier && input.carrier.toUpperCase() !== 'USPS')
|
|
127
|
+
throw new CarrierError(0, 'USPS_ONLY', 'Return labels are USPS only.');
|
|
128
|
+
const to = labelAddress(input.hub.address, { placeholder: input.hub.placeholder });
|
|
129
|
+
return buyLabel(payload, { from: input.customer, to, parcel: input.parcel, carrier: 'USPS', reference: input.reference }, req);
|
|
130
|
+
}
|
|
131
|
+
export async function quoteReturn(payload, input, req) {
|
|
132
|
+
const to = labelAddress(input.hub.address, { placeholder: input.hub.placeholder });
|
|
133
|
+
return quote(payload, { from: input.customer, to, parcel: input.parcel, carrier: 'USPS', reference: input.reference }, req);
|
|
134
|
+
}
|
|
135
|
+
/** Ask for an unused label's money back (USPS: within 30 days, never scanned). */
|
|
136
|
+
export async function refund(payload, shipmentId, req) {
|
|
137
|
+
await guard(payload, 'refund', req);
|
|
138
|
+
return configOf(payload).provider.refund(shipmentId);
|
|
139
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { CarrierProvider, Mode, Quote, Rate } from './types.js';
|
|
2
|
+
/** Every EasyPost call gives up after this long. */
|
|
3
|
+
export declare const CALL_TIMEOUT_MS = 60000;
|
|
4
|
+
/** An error from EasyPost or the client, in plain words, with a stable code. Never carries an address or a key. */
|
|
5
|
+
export declare class CarrierError extends Error {
|
|
6
|
+
readonly status: number;
|
|
7
|
+
readonly code: string;
|
|
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);
|
|
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;
|
|
22
|
+
export declare const modeOf: (key?: string | null) => Mode | null;
|
|
23
|
+
/** Ground Advantage first, else the cheapest allowed rate. PO Box and General Delivery take USPS only. */
|
|
24
|
+
export declare function pickRate(rates: Rate[], carrier: 'any' | 'USPS'): Rate | null;
|
|
25
|
+
/**
|
|
26
|
+
* EasyPost, by plain REST (no SDK). The site reads its environment and passes the key and the webhook secret in:
|
|
27
|
+
* the plugin reads no environment. A test key (EZTK…) makes free test labels; any other key is production.
|
|
28
|
+
*/
|
|
29
|
+
export declare function easyPost(opts: {
|
|
30
|
+
apiKey?: string | null;
|
|
31
|
+
webhookSecret?: string | null;
|
|
32
|
+
fetchImpl?: typeof fetch;
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
}): CarrierProvider;
|
package/dist/easypost.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
const API = 'https://api.easypost.com/v2';
|
|
3
|
+
/** Every EasyPost call gives up after this long. */
|
|
4
|
+
export const CALL_TIMEOUT_MS = 60_000;
|
|
5
|
+
/** An error from EasyPost or the client, in plain words, with a stable code. Never carries an address or a key. */
|
|
6
|
+
export class CarrierError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
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) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.shipmentId = shipmentId;
|
|
17
|
+
this.name = 'CarrierError';
|
|
18
|
+
}
|
|
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.`;
|
|
22
|
+
/** A purchase whose outcome isn't known: it may have been bought, so nobody should simply buy again. */
|
|
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');
|
|
26
|
+
export const modeOf = (key) => (!key ? null : key.startsWith('EZTK') ? 'test' : 'production');
|
|
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 });
|
|
28
|
+
const parcelBody = (p) => ({ weight: p.weightOz, ...(p.lengthIn ? { length: p.lengthIn, width: p.widthIn, height: p.heightIn } : {}) });
|
|
29
|
+
/** Ground Advantage first, else the cheapest allowed rate. PO Box and General Delivery take USPS only. */
|
|
30
|
+
export function pickRate(rates, carrier) {
|
|
31
|
+
const allowed = rates.filter((r) => carrier === 'any' || r.carrier.toUpperCase() === 'USPS');
|
|
32
|
+
return allowed.find((r) => r.carrier.toUpperCase() === 'USPS' && r.service === 'GroundAdvantage') ?? [...allowed].sort((a, b) => Number(a.rate) - Number(b.rate))[0] ?? null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* EasyPost, by plain REST (no SDK). The site reads its environment and passes the key and the webhook secret in:
|
|
36
|
+
* the plugin reads no environment. A test key (EZTK…) makes free test labels; any other key is production.
|
|
37
|
+
*/
|
|
38
|
+
export function easyPost(opts) {
|
|
39
|
+
const key = opts.apiKey ?? null;
|
|
40
|
+
const mode = modeOf(key);
|
|
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) => {
|
|
43
|
+
if (!key)
|
|
44
|
+
throw new CarrierError(0, 'NO_KEY', 'EasyPost isn’t set up here.');
|
|
45
|
+
const buying = Boolean(purchase);
|
|
46
|
+
const unknown = (why) => maybeBought(why, purchase.shipmentId);
|
|
47
|
+
let res;
|
|
48
|
+
try {
|
|
49
|
+
res = await (opts.fetchImpl ?? fetch)(`${API}${path}`, {
|
|
50
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? CALL_TIMEOUT_MS),
|
|
51
|
+
method,
|
|
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 } : {}) },
|
|
55
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const name = error?.name;
|
|
60
|
+
// A purchase whose request may have left this machine may still have gone through: say so, never "nothing was bought".
|
|
61
|
+
if (buying)
|
|
62
|
+
throw unknown(name === 'TimeoutError' || name === 'AbortError' ? 'TIMEOUT' : 'NETWORK');
|
|
63
|
+
if (name !== 'TimeoutError' && name !== 'AbortError')
|
|
64
|
+
throw new CarrierError(0, 'NETWORK', 'EasyPost couldn’t be reached. Nothing was bought; try again.');
|
|
65
|
+
throw new CarrierError(0, 'TIMEOUT', 'EasyPost didn’t answer in time. Nothing was bought; try again.');
|
|
66
|
+
}
|
|
67
|
+
const json = (await res.json().catch(() => null));
|
|
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}`);
|
|
72
|
+
if (!res.ok)
|
|
73
|
+
throw new CarrierError(res.status, json?.error?.code ?? 'HTTP_ERROR', `EasyPost refused (${json?.error?.code ?? res.status}).`);
|
|
74
|
+
if (!json)
|
|
75
|
+
throw new CarrierError(res.status, 'BAD_REPLY', 'EasyPost’s reply couldn’t be read. Nothing was bought; try again.');
|
|
76
|
+
return json;
|
|
77
|
+
};
|
|
78
|
+
const asLabel = (b, fallback, shipmentId) => {
|
|
79
|
+
// A label with no shipment id or tracking number can't be refunded or followed: treat the purchase as unknown.
|
|
80
|
+
if (!b.id || !b.tracking_code)
|
|
81
|
+
throw maybeBought('INCOMPLETE', b.id || shipmentId);
|
|
82
|
+
const chosen = b.selected_rate ?? fallback;
|
|
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 } : {}) };
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
name: 'easypost',
|
|
87
|
+
mode,
|
|
88
|
+
verify: async (a) => {
|
|
89
|
+
const r = await call('POST', '/addresses', { address: { ...toEasyPost(a), verify: true } });
|
|
90
|
+
const v = r.verifications?.delivery;
|
|
91
|
+
return { ok: Boolean(v?.success), errors: (v?.errors ?? []).map((e) => e.code ?? 'UNKNOWN'), corrected: v?.success && (r.street1 !== a.street1 || r.zip !== a.zip) ? { street1: r.street1, zip: r.zip } : null };
|
|
92
|
+
},
|
|
93
|
+
quote: async (input) => {
|
|
94
|
+
if (!(input.parcel.weightOz > 0))
|
|
95
|
+
throw new CarrierError(0, 'NO_WEIGHT', 'The parcel needs a weight.');
|
|
96
|
+
const shipment = await call('POST', '/shipments', { shipment: { from_address: toEasyPost(input.from), to_address: toEasyPost(input.to), parcel: parcelBody(input.parcel), reference: input.reference, options: { label_format: 'PDF' } } });
|
|
97
|
+
const rate = pickRate(shipment.rates ?? [], input.carrier ?? 'any');
|
|
98
|
+
if (!rate)
|
|
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.');
|
|
100
|
+
return { shipmentId: shipment.id, rate, rateCents: Math.round(Number(rate.rate) * 100), mode: mode, ...(rate.fake ? { fake: true } : {}) };
|
|
101
|
+
},
|
|
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),
|
|
103
|
+
refund: async (shipmentId) => (await call('POST', `/shipments/${encodeURIComponent(shipmentId)}/refund`, {})).refund_status ?? 'submitted',
|
|
104
|
+
webhook: {
|
|
105
|
+
configured: Boolean(opts.webhookSecret),
|
|
106
|
+
// EasyPost signs the raw body: `X-Hmac-Signature: hmac-sha256-hex=<HMAC>`, the secret NFKD-normalized.
|
|
107
|
+
verify: (raw, headers) => {
|
|
108
|
+
const secret = opts.webhookSecret;
|
|
109
|
+
const header = headers.get('x-hmac-signature');
|
|
110
|
+
if (!secret || !header)
|
|
111
|
+
return false;
|
|
112
|
+
const expected = `hmac-sha256-hex=${createHmac('sha256', secret.normalize('NFKD')).update(raw, 'utf8').digest('hex')}`;
|
|
113
|
+
const a = Buffer.from(header.trim());
|
|
114
|
+
const b = Buffer.from(expected);
|
|
115
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
116
|
+
},
|
|
117
|
+
parse: (raw) => {
|
|
118
|
+
let body;
|
|
119
|
+
try {
|
|
120
|
+
body = JSON.parse(raw);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
const r = body.result;
|
|
126
|
+
if (body.id && body.created_at && /^refund\./.test(body.description ?? '') && r?.object === 'Refund' && r.tracking_code && ['submitted', 'refunded', 'rejected', 'not_applicable'].includes(r.status ?? ''))
|
|
127
|
+
return { refund: { id: body.id, createdAt: body.created_at, tracking: r.tracking_code.toUpperCase(), status: r.status } };
|
|
128
|
+
if (body.id && body.created_at && /^tracker\./.test(body.description ?? '') && r?.object === 'Tracker' && r.tracking_code && r.status)
|
|
129
|
+
return { tracker: { id: body.id, createdAt: body.created_at, tracking: r.tracking_code.toUpperCase(), status: r.status, carrier: r.carrier ?? null, publicUrl: r.public_url ?? null } };
|
|
130
|
+
return null;
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { shippingPlugin, handlersOf, PURCHASES_SLUG } from './plugin.js';
|
|
2
|
+
export { buy, buyLabel, buyReturn, quote, quoteReturn, refund, verifyAddress } from './api.js';
|
|
3
|
+
export { CALL_TIMEOUT_MS, CarrierError, easyPost, idempotencyKey, modeOf, pickRate } from './easypost.js';
|
|
4
|
+
export { ADDRESS_KINDS, AddressError, addressKey, addressProblems, carriersFor, labelAddress, type AddressKind, type AddressProblem, type LabelAddress, type StoredAddress } from './address.js';
|
|
5
|
+
export { billableLb, dimWeightLb, mailability, parcelFor, type ParcelSize } from './parcel.js';
|
|
6
|
+
export { noticeFor, trackingLink, USPS_REFUND_DAYS, type ShipmentEvent } from './tracking.js';
|
|
7
|
+
export type { CarrierProvider, ExternalAction, Label, Mode, Parcel, Quote, Rate, RefundEvent, RefundStatus, ShippingHandler, ShippingOptions, TrackerEvent, TrackerStatus, Verification } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { shippingPlugin, handlersOf, PURCHASES_SLUG } from './plugin.js';
|
|
2
|
+
export { buy, buyLabel, buyReturn, quote, quoteReturn, refund, verifyAddress } from './api.js';
|
|
3
|
+
export { CALL_TIMEOUT_MS, CarrierError, easyPost, idempotencyKey, modeOf, pickRate } from './easypost.js';
|
|
4
|
+
export { ADDRESS_KINDS, AddressError, addressKey, addressProblems, carriersFor, labelAddress } from './address.js';
|
|
5
|
+
export { billableLb, dimWeightLb, mailability, parcelFor } from './parcel.js';
|
|
6
|
+
export { noticeFor, trackingLink, USPS_REFUND_DAYS } from './tracking.js';
|
package/dist/parcel.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** A parcel's outside size, in inches, and its weight, in ounces. */
|
|
2
|
+
export type ParcelSize = {
|
|
3
|
+
lengthIn: number;
|
|
4
|
+
widthIn: number;
|
|
5
|
+
heightIn: number;
|
|
6
|
+
weightOz: number;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A box holding some contents: its outside size, longest side first, and its weight. The box's own weight and the
|
|
10
|
+
* contents' weight come from the caller, who knows what's in it.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parcelFor(box: {
|
|
13
|
+
outside: [number, number, number] | null;
|
|
14
|
+
emptyWeightOz?: number | null;
|
|
15
|
+
}, contentsWeightOz: number): ParcelSize | null;
|
|
16
|
+
/** USPS dimensional weight in pounds (volume ÷ 139), which counts only past one cubic foot. */
|
|
17
|
+
export declare function dimWeightLb(p: ParcelSize): number;
|
|
18
|
+
/** The weight USPS charges for, in whole pounds: the actual weight, or the dimensional weight past 1 cu ft. */
|
|
19
|
+
export declare function billableLb(p: ParcelSize): number;
|
|
20
|
+
/**
|
|
21
|
+
* What USPS's rules say about a parcel (DMM 101, 223 and 283): too big or too heavy to mail, the nonstandard fees,
|
|
22
|
+
* dimensional weight past one cubic foot. Plain words; the fee amounts come from the rates.
|
|
23
|
+
*/
|
|
24
|
+
export declare function mailability(p: ParcelSize): {
|
|
25
|
+
mailable: boolean;
|
|
26
|
+
notes: string[];
|
|
27
|
+
};
|
package/dist/parcel.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A box holding some contents: its outside size, longest side first, and its weight. The box's own weight and the
|
|
3
|
+
* contents' weight come from the caller, who knows what's in it.
|
|
4
|
+
*/
|
|
5
|
+
export function parcelFor(box, contentsWeightOz) {
|
|
6
|
+
if (!box.outside)
|
|
7
|
+
return null;
|
|
8
|
+
const [lengthIn, widthIn, heightIn] = [...box.outside].sort((a, b) => b - a);
|
|
9
|
+
return { lengthIn, widthIn, heightIn, weightOz: Math.round(((box.emptyWeightOz ?? 0) + contentsWeightOz) * 10) / 10 };
|
|
10
|
+
}
|
|
11
|
+
/** USPS dimensional weight in pounds (volume ÷ 139), which counts only past one cubic foot. */
|
|
12
|
+
export function dimWeightLb(p) {
|
|
13
|
+
return (Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn)) / 139;
|
|
14
|
+
}
|
|
15
|
+
/** The weight USPS charges for, in whole pounds: the actual weight, or the dimensional weight past 1 cu ft. */
|
|
16
|
+
export function billableLb(p) {
|
|
17
|
+
const actual = p.weightOz / 16;
|
|
18
|
+
const cubic = Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn);
|
|
19
|
+
return Math.max(1, Math.ceil(cubic > 1728 ? Math.max(actual, dimWeightLb(p)) : actual));
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What USPS's rules say about a parcel (DMM 101, 223 and 283): too big or too heavy to mail, the nonstandard fees,
|
|
23
|
+
* dimensional weight past one cubic foot. Plain words; the fee amounts come from the rates.
|
|
24
|
+
*/
|
|
25
|
+
export function mailability(p) {
|
|
26
|
+
const [l, w, h] = [p.lengthIn, p.widthIn, p.heightIn].sort((a, b) => b - a);
|
|
27
|
+
const girth = 2 * (w + h);
|
|
28
|
+
const cubicIn = Math.round(l) * Math.round(w) * Math.round(h);
|
|
29
|
+
const notes = [];
|
|
30
|
+
let mailable = true;
|
|
31
|
+
if (p.weightOz > 70 * 16) {
|
|
32
|
+
mailable = false;
|
|
33
|
+
notes.push('over 70 lb: too heavy to mail');
|
|
34
|
+
}
|
|
35
|
+
if (l + girth > 130) {
|
|
36
|
+
mailable = false;
|
|
37
|
+
notes.push('over 130 in length plus girth: too big to mail');
|
|
38
|
+
}
|
|
39
|
+
else if (l + girth > 108)
|
|
40
|
+
notes.push('over 108 in length plus girth: oversized');
|
|
41
|
+
if (l > 30)
|
|
42
|
+
notes.push('over 30 in long: nonstandard fee');
|
|
43
|
+
else if (l > 22)
|
|
44
|
+
notes.push('over 22 in long: nonstandard fee');
|
|
45
|
+
if (cubicIn > 3456)
|
|
46
|
+
notes.push('over 2 cubic feet: nonstandard fee');
|
|
47
|
+
if (cubicIn > 1728)
|
|
48
|
+
notes.push(`over 1 cubic foot: dimensional weight (${Math.ceil(dimWeightLb(p))} lb)`);
|
|
49
|
+
return { mailable, notes };
|
|
50
|
+
}
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Payload, Plugin } from 'payload';
|
|
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";
|
|
5
|
+
/** Every handler: the plugin's own options and those other plugins registered at `config.custom.shippingHandlers`. */
|
|
6
|
+
export declare const handlersOf: (payload: Payload) => ShippingHandler[];
|
|
7
|
+
/** Shipping: addresses, carrier quotes and labels, refunds of unused labels, and the carrier's webhook. */
|
|
8
|
+
export declare const shippingPlugin: (options: ShippingOptions) => Plugin;
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
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
|
+
};
|
|
21
|
+
/** Clocks differ a little; an event dated further ahead than this is refused. */
|
|
22
|
+
const FUTURE_SKEW_MS = 10 * 60_000;
|
|
23
|
+
const json = (body, status = 200) => Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
|
|
24
|
+
/** Every handler: the plugin's own options and those other plugins registered at `config.custom.shippingHandlers`. */
|
|
25
|
+
export const handlersOf = (payload) => {
|
|
26
|
+
const o = payload.config.custom.shipping;
|
|
27
|
+
const extra = payload.config.custom?.shippingHandlers;
|
|
28
|
+
return [...o.handlers, ...(Array.isArray(extra) ? extra : [])];
|
|
29
|
+
};
|
|
30
|
+
/** Only an answer of exactly `true` (or a promise of it) passes; anything else, a thrown or rejected error included, is no. */
|
|
31
|
+
async function signedExactly(check) {
|
|
32
|
+
try {
|
|
33
|
+
return (await check()) === true;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The carrier's webhook. It fails closed:
|
|
41
|
+
* - no secret configured: 503;
|
|
42
|
+
* - an unsigned or wrongly signed body: 401, checked over the raw bytes before anything is parsed. Only `verify`
|
|
43
|
+
* answering exactly `true` (sync or async) counts; anything else, a throw included, is 401;
|
|
44
|
+
* - too old (a captured body replayed later), dated in the future, or not ours: 200, nothing written;
|
|
45
|
+
* - no handler claims it: 200 "unknown", nothing written;
|
|
46
|
+
* - a handler throws, or answers anything but "handled" or "unknown": 500, so the carrier retries (handlers must be idempotent).
|
|
47
|
+
*/
|
|
48
|
+
const webhook = (path) => ({
|
|
49
|
+
path,
|
|
50
|
+
method: 'post',
|
|
51
|
+
handler: async (req) => {
|
|
52
|
+
const o = req.payload.config.custom.shipping;
|
|
53
|
+
const hook = o.provider.webhook;
|
|
54
|
+
if (!hook?.configured)
|
|
55
|
+
return json({ error: 'Not configured' }, 503);
|
|
56
|
+
const raw = (await req.text?.()) ?? '';
|
|
57
|
+
// Only an exact `true`, awaited: a promise (a custom provider's async verify), any other truthy answer, or a
|
|
58
|
+
// throw is unsigned. EasyPost's own verify is sync and answers a boolean.
|
|
59
|
+
if (!(await signedExactly(() => hook.verify(raw, req.headers))))
|
|
60
|
+
return json({ error: 'Unauthorized' }, 401);
|
|
61
|
+
const ev = hook.parse(raw);
|
|
62
|
+
if (!ev)
|
|
63
|
+
return json({ result: 'ignored' });
|
|
64
|
+
// Both kinds of event: a captured body can't be replayed after the window, nor dated ahead to outlive it.
|
|
65
|
+
const at = new Date((ev.tracker ?? ev.refund).createdAt).getTime();
|
|
66
|
+
if (!(at > Date.now() - o.maxEventAgeDays * DAY))
|
|
67
|
+
return json({ result: 'too-old' });
|
|
68
|
+
if (!(at < Date.now() + FUTURE_SKEW_MS))
|
|
69
|
+
return json({ result: 'too-new' });
|
|
70
|
+
try {
|
|
71
|
+
for (const h of handlersOf(req.payload)) {
|
|
72
|
+
const fn = ev.tracker ? h.onTracker : h.onRefund;
|
|
73
|
+
if (!fn)
|
|
74
|
+
continue;
|
|
75
|
+
const result = ev.tracker ? await h.onTracker({ event: ev.tracker, req, payload: req.payload }) : await h.onRefund({ event: ev.refund, req, payload: req.payload });
|
|
76
|
+
if (result === 'handled')
|
|
77
|
+
return json({ result: 'handled' });
|
|
78
|
+
// A handler that forgot to answer may have half-done its work: fail closed, so the carrier retries.
|
|
79
|
+
if (result !== 'unknown')
|
|
80
|
+
throw new Error('shipping: a handler answered neither "handled" nor "unknown"');
|
|
81
|
+
}
|
|
82
|
+
return json({ result: 'unknown' });
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
req.payload.logger.error({ err: { name: error?.name }, msg: 'shipping: a webhook handler failed; the carrier will retry' });
|
|
86
|
+
return json({ error: 'Handler failed' }, 500);
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
/** Shipping: addresses, carrier quotes and labels, refunds of unused labels, and the carrier's webhook. */
|
|
91
|
+
export const shippingPlugin = (options) => (config) => {
|
|
92
|
+
if (!options?.provider || typeof options.provider.quote !== 'function')
|
|
93
|
+
throw new Error('Shipping: give a `provider`, for example easyPost({ apiKey, webhookSecret }).');
|
|
94
|
+
const o = {
|
|
95
|
+
provider: options.provider,
|
|
96
|
+
webhookPath: options.webhookPath ?? '/easypost/webhook',
|
|
97
|
+
maxEventAgeDays: options.maxEventAgeDays ?? 7,
|
|
98
|
+
beforeExternalCall: options.beforeExternalCall,
|
|
99
|
+
handlers: options.handlers ?? [],
|
|
100
|
+
};
|
|
101
|
+
if (!o.webhookPath.startsWith('/'))
|
|
102
|
+
throw new Error('Shipping: webhookPath starts with "/".');
|
|
103
|
+
return {
|
|
104
|
+
...config,
|
|
105
|
+
custom: { ...config.custom, shipping: o },
|
|
106
|
+
collections: [...(config.collections ?? []), purchases],
|
|
107
|
+
// A root endpoint, so the URL is exactly /api<webhookPath>.
|
|
108
|
+
endpoints: [...(config.endpoints ?? []), webhook(o.webhookPath)],
|
|
109
|
+
};
|
|
110
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { type ParcelSize } from './parcel.js';
|
|
2
|
+
/**
|
|
3
|
+
* For tests and dry runs only, from `@extantape/payload-plugin-shipping/testing`, so a production bundle can't
|
|
4
|
+
* pick it by accident. A stand-in for EasyPost: nothing leaves the process. **Its prices are made up** (USPS-shaped,
|
|
5
|
+
* so the logic can be tested); every rate and label says `fake: true`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function fakeZone(fromZip?: string, toZip?: string): number;
|
|
8
|
+
export declare function fakePrices(p: ParcelSize, zone: number): {
|
|
9
|
+
ground: number;
|
|
10
|
+
priority: number;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
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, `drop` cuts the connection, and `offer` leaves services out
|
|
15
|
+
* of the rates. Each call's headers are recorded too, without the key.
|
|
16
|
+
*/
|
|
17
|
+
export declare function fakeCarrier(over?: {
|
|
18
|
+
mode?: 'test' | 'production';
|
|
19
|
+
refund?: 'submitted' | 'rejected';
|
|
20
|
+
webhookSecret?: string | null;
|
|
21
|
+
fail?: (path: string) => {
|
|
22
|
+
status: number;
|
|
23
|
+
code: string;
|
|
24
|
+
} | null;
|
|
25
|
+
hang?: (path: string) => boolean;
|
|
26
|
+
drop?: (path: string) => boolean;
|
|
27
|
+
timeoutMs?: number;
|
|
28
|
+
offer?: (rate: {
|
|
29
|
+
carrier: string;
|
|
30
|
+
service: string;
|
|
31
|
+
}) => boolean;
|
|
32
|
+
}): {
|
|
33
|
+
provider: {
|
|
34
|
+
name: string;
|
|
35
|
+
mode: import("./types.js").Mode | null;
|
|
36
|
+
verify: (a: import("./address.js").LabelAddress) => Promise<import("./types.js").Verification>;
|
|
37
|
+
quote: (input: {
|
|
38
|
+
from: import("./address.js").LabelAddress;
|
|
39
|
+
to: import("./address.js").LabelAddress;
|
|
40
|
+
parcel: import("./types.js").Parcel;
|
|
41
|
+
carrier?: "any" | "USPS";
|
|
42
|
+
reference: string;
|
|
43
|
+
}) => Promise<import("./types.js").Quote>;
|
|
44
|
+
buy: (quote: import("./types.js").Quote) => Promise<import("./types.js").Label>;
|
|
45
|
+
refund: (shipmentId: string) => Promise<import("./types.js").RefundStatus>;
|
|
46
|
+
webhook?: {
|
|
47
|
+
configured: boolean;
|
|
48
|
+
verify: (raw: string, headers: Headers) => boolean | Promise<boolean>;
|
|
49
|
+
parse: (raw: string) => {
|
|
50
|
+
tracker?: import("./types.js").TrackerEvent;
|
|
51
|
+
refund?: import("./types.js").RefundEvent;
|
|
52
|
+
} | null;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
calls: {
|
|
56
|
+
path: string;
|
|
57
|
+
body: Record<string, unknown>;
|
|
58
|
+
headers: Record<string, string>;
|
|
59
|
+
}[];
|
|
60
|
+
shipments: Map<string, {
|
|
61
|
+
id: string;
|
|
62
|
+
carrier: string;
|
|
63
|
+
service: string;
|
|
64
|
+
rate: string;
|
|
65
|
+
fake: true;
|
|
66
|
+
}[]>;
|
|
67
|
+
sign: (raw: string) => string;
|
|
68
|
+
};
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createHmac, randomInt } from 'node:crypto';
|
|
2
|
+
import { easyPost } from './easypost.js';
|
|
3
|
+
import { billableLb } from './parcel.js';
|
|
4
|
+
/**
|
|
5
|
+
* For tests and dry runs only, from `@extantape/payload-plugin-shipping/testing`, so a production bundle can't
|
|
6
|
+
* pick it by accident. A stand-in for EasyPost: nothing leaves the process. **Its prices are made up** (USPS-shaped,
|
|
7
|
+
* so the logic can be tested); every rate and label says `fake: true`.
|
|
8
|
+
*/
|
|
9
|
+
export function fakeZone(fromZip = '', toZip = '') {
|
|
10
|
+
const a = Number(String(fromZip).slice(0, 3));
|
|
11
|
+
const b = Number(String(toZip).slice(0, 3));
|
|
12
|
+
if (!Number.isFinite(a) || !Number.isFinite(b))
|
|
13
|
+
return 5;
|
|
14
|
+
const remote = (z) => (z >= 995 && z <= 999) || z === 967 || z === 968;
|
|
15
|
+
if (remote(a) !== remote(b))
|
|
16
|
+
return 8;
|
|
17
|
+
return Math.min(8, 1 + Math.floor(Math.abs(a - b) / 120));
|
|
18
|
+
}
|
|
19
|
+
export function fakePrices(p, zone) {
|
|
20
|
+
const lb = billableLb(p);
|
|
21
|
+
const light = p.weightOz <= 15.99 && Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn) <= 1728;
|
|
22
|
+
let ground = light ? 450 + zone * 25 + Math.ceil(p.weightOz / 4) * 20 : 700 + zone * 60 + (lb - 1) * (35 + zone * 12);
|
|
23
|
+
const long = Math.max(p.lengthIn, p.widthIn, p.heightIn);
|
|
24
|
+
const cubic = Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn);
|
|
25
|
+
ground += Math.max(long > 30 ? 1500 : long > 22 ? 400 : 0, cubic > 3456 ? 1500 : 0);
|
|
26
|
+
return { ground, priority: Math.round(ground * 1.4) };
|
|
27
|
+
}
|
|
28
|
+
const API = 'https://api.easypost.com/v2';
|
|
29
|
+
const digits = (n) => Array.from({ length: n }, () => randomInt(10)).join('');
|
|
30
|
+
/**
|
|
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, `drop` cuts the connection, and `offer` leaves services out
|
|
33
|
+
* of the rates. Each call's headers are recorded too, without the key.
|
|
34
|
+
*/
|
|
35
|
+
export function fakeCarrier(over = {}) {
|
|
36
|
+
const shipments = new Map();
|
|
37
|
+
const calls = [];
|
|
38
|
+
const fetchImpl = (async (url, init) => {
|
|
39
|
+
const path = String(url).replace(API, '');
|
|
40
|
+
const body = (init?.body ? JSON.parse(String(init.body)) : {});
|
|
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');
|
|
46
|
+
if (over.hang?.(path)) {
|
|
47
|
+
await new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(Object.assign(new Error('timed out'), { name: 'TimeoutError' }))));
|
|
48
|
+
}
|
|
49
|
+
const json = (status, reply) => new Response(JSON.stringify(reply), { status, headers: { 'Content-Type': 'application/json' } });
|
|
50
|
+
const failure = over.fail?.(path);
|
|
51
|
+
if (failure)
|
|
52
|
+
return json(failure.status, { error: { code: failure.code, message: 'made-up failure' } });
|
|
53
|
+
if (path === '/shipments') {
|
|
54
|
+
const s = (body.shipment ?? {});
|
|
55
|
+
const p = s.parcel ?? {};
|
|
56
|
+
const size = { lengthIn: p.length ?? 6, widthIn: p.width ?? 6, heightIn: p.height ?? 2, weightOz: p.weight ?? 1 };
|
|
57
|
+
const { ground, priority } = fakePrices(size, fakeZone(s.from_address?.zip, s.to_address?.zip));
|
|
58
|
+
const id = `shp_fake${digits(10)}`;
|
|
59
|
+
const rates = [
|
|
60
|
+
{ id: `rate_g${digits(8)}`, carrier: 'USPS', service: 'GroundAdvantage', rate: (ground / 100).toFixed(2), fake: true },
|
|
61
|
+
{ id: `rate_p${digits(8)}`, carrier: 'USPS', service: 'Priority', rate: (priority / 100).toFixed(2), fake: true },
|
|
62
|
+
{ id: `rate_u${digits(8)}`, carrier: 'UPS', service: 'Ground', rate: ((ground - 50) / 100).toFixed(2), fake: true },
|
|
63
|
+
].filter((r) => over.offer?.(r) ?? true);
|
|
64
|
+
shipments.set(id, rates);
|
|
65
|
+
return json(201, { id, rates });
|
|
66
|
+
}
|
|
67
|
+
const buy = path.match(/^\/shipments\/([^/]+)\/buy$/);
|
|
68
|
+
if (buy) {
|
|
69
|
+
const chosen = shipments.get(buy[1])?.find((r) => r.id === body.rate?.id);
|
|
70
|
+
if (!chosen)
|
|
71
|
+
return json(422, { error: { code: 'SHIPMENT.RATE.INVALID', message: 'That rate isn’t on this shipment.' } });
|
|
72
|
+
return json(200, { id: buy[1], tracking_code: `9400${digits(18)}`, postage_label: { label_url: `https://example.invalid/labels/${buy[1]}.pdf` }, tracker: { public_url: `https://example.invalid/track/${buy[1]}` }, selected_rate: chosen });
|
|
73
|
+
}
|
|
74
|
+
const refund = path.match(/^\/shipments\/([^/]+)\/refund$/);
|
|
75
|
+
if (refund)
|
|
76
|
+
return json(200, { id: refund[1], refund_status: over.refund ?? 'submitted' });
|
|
77
|
+
if (path === '/addresses') {
|
|
78
|
+
const a = (body.address ?? {});
|
|
79
|
+
return json(201, { ...a, verifications: { delivery: { success: true, errors: [] } } });
|
|
80
|
+
}
|
|
81
|
+
return json(404, { error: { code: 'NOT_FOUND', message: 'not answered' } });
|
|
82
|
+
});
|
|
83
|
+
const secret = over.webhookSecret === undefined ? 'a-made-up-webhook-secret' : over.webhookSecret;
|
|
84
|
+
const provider = easyPost({ apiKey: over.mode === 'production' ? 'EZAK_made_up' : 'EZTK_made_up', webhookSecret: secret, fetchImpl, timeoutMs: over.timeoutMs });
|
|
85
|
+
/** Signs a body the way EasyPost does, for webhook tests. */
|
|
86
|
+
const sign = (raw) => `hmac-sha256-hex=${createHmac('sha256', String(secret).normalize('NFKD')).update(raw, 'utf8').digest('hex')}`;
|
|
87
|
+
return { provider: { ...provider, name: 'fake' }, calls, shipments, sign };
|
|
88
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { TrackerStatus } from './types.js';
|
|
2
|
+
/** The carrier's public tracking page for a number. UPS numbers start with 1Z; everything else is taken as USPS. */
|
|
3
|
+
export declare function trackingLink(number: string, carrier?: string | null): string;
|
|
4
|
+
export type ShipmentEvent = 'out-for-delivery' | 'delivered' | 'exception';
|
|
5
|
+
/** Which customer notice a carrier status means, if any. "Available for pickup" is delivered to a PO Box or General Delivery. */
|
|
6
|
+
export declare function noticeFor(status: TrackerStatus): ShipmentEvent | null;
|
|
7
|
+
/** USPS refund window for an unused label, in days. */
|
|
8
|
+
export declare const USPS_REFUND_DAYS = 30;
|
package/dist/tracking.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The carrier's public tracking page for a number. UPS numbers start with 1Z; everything else is taken as USPS. */
|
|
2
|
+
export function trackingLink(number, carrier) {
|
|
3
|
+
const n = number.replace(/\s/g, '').toUpperCase();
|
|
4
|
+
if (carrier?.toUpperCase() === 'UPS' || (!carrier && /^1Z[0-9A-Z]{16}$/.test(n)))
|
|
5
|
+
return `https://www.ups.com/track?tracknum=${encodeURIComponent(n)}`;
|
|
6
|
+
return `https://tools.usps.com/go/TrackConfirmAction?tLabels=${encodeURIComponent(n)}`;
|
|
7
|
+
}
|
|
8
|
+
/** Which customer notice a carrier status means, if any. "Available for pickup" is delivered to a PO Box or General Delivery. */
|
|
9
|
+
export function noticeFor(status) {
|
|
10
|
+
if (status === 'out_for_delivery')
|
|
11
|
+
return 'out-for-delivery';
|
|
12
|
+
if (status === 'delivered' || status === 'available_for_pickup')
|
|
13
|
+
return 'delivered';
|
|
14
|
+
if (status === 'return_to_sender' || status === 'failure' || status === 'error')
|
|
15
|
+
return 'exception';
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
/** USPS refund window for an unused label, in days. */
|
|
19
|
+
export const USPS_REFUND_DAYS = 30;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest } from 'payload';
|
|
2
|
+
import type { LabelAddress } from './address.js';
|
|
3
|
+
export type Req = Partial<PayloadRequest>;
|
|
4
|
+
export type Mode = 'test' | 'production';
|
|
5
|
+
export type Parcel = {
|
|
6
|
+
weightOz: number;
|
|
7
|
+
lengthIn?: number | null;
|
|
8
|
+
widthIn?: number | null;
|
|
9
|
+
heightIn?: number | null;
|
|
10
|
+
};
|
|
11
|
+
export type Rate = {
|
|
12
|
+
id: string;
|
|
13
|
+
carrier: string;
|
|
14
|
+
service: string;
|
|
15
|
+
rate: string;
|
|
16
|
+
fake?: boolean;
|
|
17
|
+
};
|
|
18
|
+
export type Quote = {
|
|
19
|
+
shipmentId: string;
|
|
20
|
+
rate: Rate;
|
|
21
|
+
rateCents: number;
|
|
22
|
+
mode: Mode;
|
|
23
|
+
fake?: boolean;
|
|
24
|
+
};
|
|
25
|
+
export type Label = {
|
|
26
|
+
shipmentId: string;
|
|
27
|
+
tracking: string;
|
|
28
|
+
carrier: string;
|
|
29
|
+
service: string;
|
|
30
|
+
rateCents: number;
|
|
31
|
+
labelUrl: string;
|
|
32
|
+
trackerUrl: string | null;
|
|
33
|
+
mode: Mode;
|
|
34
|
+
fake?: boolean;
|
|
35
|
+
};
|
|
36
|
+
export type RefundStatus = 'submitted' | 'refunded' | 'rejected' | 'not_applicable';
|
|
37
|
+
export type Verification = {
|
|
38
|
+
ok: boolean;
|
|
39
|
+
errors: string[];
|
|
40
|
+
corrected: {
|
|
41
|
+
street1?: string;
|
|
42
|
+
zip?: string;
|
|
43
|
+
} | null;
|
|
44
|
+
};
|
|
45
|
+
export type TrackerStatus = 'unknown' | 'pre_transit' | 'in_transit' | 'out_for_delivery' | 'delivered' | 'available_for_pickup' | 'return_to_sender' | 'failure' | 'cancelled' | 'error';
|
|
46
|
+
export type TrackerEvent = {
|
|
47
|
+
id: string;
|
|
48
|
+
createdAt: string;
|
|
49
|
+
tracking: string;
|
|
50
|
+
status: TrackerStatus;
|
|
51
|
+
carrier: string | null;
|
|
52
|
+
publicUrl: string | null;
|
|
53
|
+
};
|
|
54
|
+
export type RefundEvent = {
|
|
55
|
+
id: string;
|
|
56
|
+
createdAt: string;
|
|
57
|
+
tracking: string;
|
|
58
|
+
status: RefundStatus;
|
|
59
|
+
};
|
|
60
|
+
/** What a carrier provider does. EasyPost is the first; the fake one is for tests. */
|
|
61
|
+
export type CarrierProvider = {
|
|
62
|
+
name: string;
|
|
63
|
+
/** test or production, from the key. Null when not set up. */
|
|
64
|
+
mode: Mode | null;
|
|
65
|
+
verify: (a: LabelAddress) => Promise<Verification>;
|
|
66
|
+
quote: (input: {
|
|
67
|
+
from: LabelAddress;
|
|
68
|
+
to: LabelAddress;
|
|
69
|
+
parcel: Parcel;
|
|
70
|
+
carrier?: 'any' | 'USPS';
|
|
71
|
+
reference: string;
|
|
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
|
+
*/
|
|
77
|
+
buy: (quote: Quote) => Promise<Label>;
|
|
78
|
+
refund: (shipmentId: string) => Promise<RefundStatus>;
|
|
79
|
+
/** Webhooks: is this raw body signed by the carrier, and what does it say? */
|
|
80
|
+
webhook?: {
|
|
81
|
+
configured: boolean;
|
|
82
|
+
/** Is the raw body signed by the carrier? Answer exactly `true` (or a promise of it) for yes; anything else, a throw included, is a 401. */
|
|
83
|
+
verify: (raw: string, headers: Headers) => boolean | Promise<boolean>;
|
|
84
|
+
parse: (raw: string) => {
|
|
85
|
+
tracker?: TrackerEvent;
|
|
86
|
+
refund?: RefundEvent;
|
|
87
|
+
} | null;
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
export type ExternalAction = 'verify' | 'quote' | 'buy' | 'refund';
|
|
91
|
+
/** An owner's handler for webhook events. Must be idempotent: carriers retry. 'unknown' when it isn't theirs. */
|
|
92
|
+
export type ShippingHandler = {
|
|
93
|
+
owner: string;
|
|
94
|
+
onTracker?: (args: {
|
|
95
|
+
event: TrackerEvent;
|
|
96
|
+
req: PayloadRequest;
|
|
97
|
+
payload: Payload;
|
|
98
|
+
}) => Promise<'handled' | 'unknown'>;
|
|
99
|
+
onRefund?: (args: {
|
|
100
|
+
event: RefundEvent;
|
|
101
|
+
req: PayloadRequest;
|
|
102
|
+
payload: Payload;
|
|
103
|
+
}) => Promise<'handled' | 'unknown'>;
|
|
104
|
+
};
|
|
105
|
+
export type ShippingOptions = {
|
|
106
|
+
provider: CarrierProvider;
|
|
107
|
+
/** A root endpoint path. Default '/easypost/webhook', so it serves /api/easypost/webhook. */
|
|
108
|
+
webhookPath?: string;
|
|
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
|
+
*/
|
|
114
|
+
beforeExternalCall?: (args: {
|
|
115
|
+
action: ExternalAction;
|
|
116
|
+
mode: Mode;
|
|
117
|
+
req?: Req;
|
|
118
|
+
}) => boolean | Promise<boolean>;
|
|
119
|
+
handlers?: ShippingHandler[];
|
|
120
|
+
/** Events older than this are ignored, so a captured body can't be replayed later. Default 7. */
|
|
121
|
+
maxEventAgeDays?: number;
|
|
122
|
+
};
|
|
123
|
+
export type Resolved = Required<Pick<ShippingOptions, 'provider' | 'webhookPath' | 'maxEventAgeDays'>> & {
|
|
124
|
+
beforeExternalCall?: ShippingOptions['beforeExternalCall'];
|
|
125
|
+
handlers: ShippingHandler[];
|
|
126
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-shipping",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Shipping for Payload: addresses, carrier rates, labels, refunds of unused labels and tracking webhooks, with EasyPost as the first carrier provider.",
|
|
5
|
+
"homepage": "https://github.com/ExtantApe/payload-plugin-shipping#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/ExtantApe/payload-plugin-shipping/issues"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [
|
|
10
|
+
"payload",
|
|
11
|
+
"payload-plugin",
|
|
12
|
+
"payloadcms",
|
|
13
|
+
"ecommerce",
|
|
14
|
+
"integrations",
|
|
15
|
+
"shipping",
|
|
16
|
+
"easypost",
|
|
17
|
+
"usps",
|
|
18
|
+
"postage",
|
|
19
|
+
"shipping-labels",
|
|
20
|
+
"tracking",
|
|
21
|
+
"webhooks"
|
|
22
|
+
],
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/ExtantApe/payload-plugin-shipping.git"
|
|
27
|
+
},
|
|
28
|
+
"type": "module",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./testing": {
|
|
35
|
+
"types": "./dist/testing.d.ts",
|
|
36
|
+
"import": "./dist/testing.js"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"main": "./dist/index.js",
|
|
40
|
+
"types": "./dist/index.d.ts",
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE"
|
|
45
|
+
],
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=22"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"test": "vitest run",
|
|
53
|
+
"leak-check": "bash scripts/leak-check.sh",
|
|
54
|
+
"prepack": "npm run build",
|
|
55
|
+
"prepublishOnly": "npm run typecheck && npm test"
|
|
56
|
+
},
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"payload": "^3.80.0"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@payloadcms/db-mongodb": "3.92.1",
|
|
62
|
+
"@types/node": "^24.0.0",
|
|
63
|
+
"graphql": "^16.14.2",
|
|
64
|
+
"mongodb-memory-server": "^11.3.0",
|
|
65
|
+
"payload": "3.92.1",
|
|
66
|
+
"typescript": "^5.9.0",
|
|
67
|
+
"vitest": "^3.2.0"
|
|
68
|
+
}
|
|
69
|
+
}
|