@flexops/sdk 2.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +210 -119
- package/dist/index.d.mts +1123 -420
- package/dist/index.d.ts +1123 -420
- package/dist/index.js +827 -405
- package/dist/index.mjs +818 -402
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -7,8 +7,8 @@ Official Node.js/TypeScript SDK for the [FlexOps](https://flexops.io) multi-carr
|
|
|
7
7
|
- Full TypeScript support with complete type definitions
|
|
8
8
|
- All 4 carriers: **USPS**, **UPS**, **FedEx**, **DHL**
|
|
9
9
|
- High-level shipping operations (rate shopping, labels, tracking)
|
|
10
|
-
-
|
|
11
|
-
-
|
|
10
|
+
- The documented FlexOps API only: every method is checked against the published OpenAPI in CI
|
|
11
|
+
- Retries that cannot buy twice: writes carry an `Idempotency-Key` (see [Retries](#retries))
|
|
12
12
|
- JWT and API key authentication
|
|
13
13
|
- Webhook signature verification (HMAC-SHA256)
|
|
14
14
|
- ESM and CommonJS support
|
|
@@ -25,7 +25,7 @@ npm install @flexops/sdk
|
|
|
25
25
|
### API Key Authentication (server-to-server)
|
|
26
26
|
|
|
27
27
|
```typescript
|
|
28
|
-
import { FlexOps } from '@flexops/sdk';
|
|
28
|
+
import { FlexOps, HazmatClassification } from '@flexops/sdk';
|
|
29
29
|
|
|
30
30
|
const client = new FlexOps({
|
|
31
31
|
apiKey: 'fxk_live_...',
|
|
@@ -73,6 +73,8 @@ const fastest = await client.shipping.getFastestRate(rateRequest);
|
|
|
73
73
|
```typescript
|
|
74
74
|
const operation = await client.shipping.prepareLabel({
|
|
75
75
|
...rateRequest, carrierCode: 'USPS', serviceCode: 'PRIORITY',
|
|
76
|
+
// Required without an orderId. The SDK never fills it in; None = not hazardous.
|
|
77
|
+
hazmatClassification: HazmatClassification.None,
|
|
76
78
|
}, 10.00, crypto.randomUUID());
|
|
77
79
|
if (operation.preview) console.log({ quote: operation.preview.quotedPostageAmount,
|
|
78
80
|
maximum: operation.preview.maximumPostageAmount, currency: operation.preview.currency,
|
|
@@ -96,7 +98,7 @@ try {
|
|
|
96
98
|
```typescript
|
|
97
99
|
const tracking = await client.shipping.track('9400111899223456789012');
|
|
98
100
|
|
|
99
|
-
for (const event of tracking.
|
|
101
|
+
for (const event of tracking.events) {
|
|
100
102
|
console.log(`${event.timestamp}: ${event.description}`);
|
|
101
103
|
}
|
|
102
104
|
```
|
|
@@ -113,128 +115,152 @@ const result = await client.shipping.validateAddress({
|
|
|
113
115
|
country: 'US',
|
|
114
116
|
});
|
|
115
117
|
|
|
116
|
-
if (
|
|
117
|
-
console.log('
|
|
118
|
+
if (result.validationUnavailable) {
|
|
119
|
+
console.log('Validation is unavailable right now; isValid is not a verdict.');
|
|
120
|
+
} else if (!result.isValid) {
|
|
121
|
+
console.log('Suggested:', result.suggestedAddress, result.warnings);
|
|
118
122
|
}
|
|
119
123
|
```
|
|
120
124
|
|
|
121
125
|
### Batch Labels
|
|
122
126
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const preview = await client.shipping.previewBatch({
|
|
126
|
-
items: [/* array of CreateLabelRequest */],
|
|
127
|
-
});
|
|
128
|
-
|
|
129
|
-
// Create the batch
|
|
130
|
-
const batch = await client.shipping.createBatch({
|
|
131
|
-
items: [/* array of CreateLabelRequest */],
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
// Check status
|
|
135
|
-
const status = await client.shipping.getBatchStatus(batch.data.jobId);
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
## Direct Carrier Access
|
|
139
|
-
|
|
140
|
-
For full control, use carrier-specific endpoints:
|
|
141
|
-
|
|
142
|
-
### USPS
|
|
127
|
+
Each item is an order you already have in FlexOps; the addresses come from the order. Leave out
|
|
128
|
+
`carrierCode` and `serviceCode` to let your shipping rules choose.
|
|
143
129
|
|
|
144
130
|
```typescript
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
131
|
+
import { HazmatClassification, type CreateBatchLabelRequest } from '@flexops/sdk';
|
|
132
|
+
|
|
133
|
+
const request: CreateBatchLabelRequest = {
|
|
134
|
+
items: [
|
|
135
|
+
{
|
|
136
|
+
orderId: 12345,
|
|
137
|
+
packageWeightInOunces: 12,
|
|
138
|
+
packageLengthInInches: 10,
|
|
139
|
+
packageWidthInInches: 8,
|
|
140
|
+
packageHeightInInches: 4,
|
|
141
|
+
carrierCode: 'USPS',
|
|
142
|
+
serviceCode: 'PRIORITY',
|
|
143
|
+
hazmatClassification: HazmatClassification.None,
|
|
144
|
+
},
|
|
145
|
+
],
|
|
146
|
+
};
|
|
152
147
|
|
|
153
|
-
//
|
|
154
|
-
const
|
|
155
|
-
originZIPCode: '10001',
|
|
156
|
-
destinationZIPCode: '90210',
|
|
157
|
-
weight: 1.0,
|
|
158
|
-
});
|
|
148
|
+
// Preview (dry-run): per-order rates and the total, nothing bought
|
|
149
|
+
const preview = await client.shipping.previewBatch(request);
|
|
159
150
|
|
|
160
|
-
//
|
|
161
|
-
const
|
|
162
|
-
zipCode: '10001',
|
|
163
|
-
});
|
|
164
|
-
```
|
|
151
|
+
// Create the batch; it runs in the background
|
|
152
|
+
const batch = await client.shipping.createBatch(request);
|
|
165
153
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
```typescript
|
|
169
|
-
const label = await client.carriers.ups.createLabel({ /* UPS payload */ });
|
|
170
|
-
const rates = await client.carriers.ups.getRates({ /* UPS payload */ });
|
|
171
|
-
const tracking = await client.carriers.ups.track({ trackingNumber: '1Z...' });
|
|
172
|
-
const transitTimes = await client.carriers.ups.getTransitTimes({ /* payload */ });
|
|
154
|
+
// Check status
|
|
155
|
+
const status = await client.shipping.getBatchStatus(batch.data!.jobId);
|
|
173
156
|
```
|
|
174
157
|
|
|
175
|
-
|
|
158
|
+
## Carrier-Specific Calls
|
|
176
159
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
// Multi-package (Open Ship)
|
|
183
|
-
await client.carriers.fedex.createOpenShipment({ /* payload */ });
|
|
184
|
-
await client.carriers.fedex.addPackagesToOpenShipment({ /* payload */ });
|
|
185
|
-
await client.carriers.fedex.confirmOpenShipment({ /* payload */ });
|
|
186
|
-
```
|
|
160
|
+
Rates, labels, voids, pickups and scan forms go through `client.shipping`, `client.pickups` and
|
|
161
|
+
`client.scanForms`, which work for every carrier and with API keys. `client.carriers` reaches
|
|
162
|
+
carrier-specific endpoints through the Gateway's legacy pass-through, which is deprecated and
|
|
163
|
+
retired on 2027-06-30:
|
|
187
164
|
|
|
188
|
-
|
|
165
|
+
- **Lookups (GET)** work with API keys.
|
|
166
|
+
- **Writes** (for example `carriers.usps.getDomesticRates`, `carriers.fedex.createPickup`) are marked
|
|
167
|
+
`@deprecated`. They need a user token (`auth.login`): the Gateway answers an API key with 403
|
|
168
|
+
`API_KEY_SCOPE_REQUIRED`. Move them to the native resources above.
|
|
169
|
+
- **Label purchases** through the pass-through are closed by the Gateway (410), so the SDK has no
|
|
170
|
+
carrier-specific label methods; buy labels with `client.shipping.createLabel`.
|
|
189
171
|
|
|
190
172
|
```typescript
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
const
|
|
194
|
-
const
|
|
173
|
+
const city = await client.carriers.usps.cityStateLookup('10001');
|
|
174
|
+
const locations = await client.carriers.usps.findDropOffLocations({ zipCode: '10001' });
|
|
175
|
+
const upsTracking = await client.carriers.ups.track({ trackingNumber: '1Z...' });
|
|
176
|
+
const dhlRates = await client.carriers.dhl.getRates({ countryCode: 'US', weight: '1' });
|
|
195
177
|
```
|
|
196
178
|
|
|
197
179
|
## Workspace Management
|
|
198
180
|
|
|
199
181
|
```typescript
|
|
182
|
+
import { WorkspaceRole } from '@flexops/sdk';
|
|
183
|
+
|
|
200
184
|
// List workspaces
|
|
201
185
|
const workspaces = await client.workspaces.list();
|
|
202
186
|
|
|
203
187
|
// Switch workspace
|
|
204
188
|
client.workspaceId = 'different-workspace-id';
|
|
205
189
|
|
|
206
|
-
//
|
|
207
|
-
await client.workspaces.
|
|
190
|
+
// Members and pending invites
|
|
191
|
+
const { data } = await client.workspaces.listMembers();
|
|
192
|
+
console.log(data.members.length, data.pendingInvites.length);
|
|
193
|
+
|
|
194
|
+
// Invite a member (roles are numbers on the wire; use WorkspaceRole)
|
|
195
|
+
await client.workspaces.inviteMember('newuser@company.com', WorkspaceRole.Member);
|
|
208
196
|
```
|
|
209
197
|
|
|
210
198
|
## Webhooks
|
|
211
199
|
|
|
212
200
|
```typescript
|
|
213
|
-
|
|
201
|
+
import { WebhookEventType } from '@flexops/sdk';
|
|
202
|
+
|
|
203
|
+
// Create a subscription. Omit `events` to receive every event.
|
|
214
204
|
const webhook = await client.webhooks.create({
|
|
215
205
|
url: 'https://your-app.com/webhooks/flexops',
|
|
216
|
-
events: [
|
|
206
|
+
events: [WebhookEventType.LabelCreated, WebhookEventType.LabelCanceled, WebhookEventType.BatchCompleted],
|
|
217
207
|
});
|
|
208
|
+
const signingSecret = webhook.data.secret; // returned only on create; store it
|
|
218
209
|
|
|
219
210
|
// Rotate the signing secret
|
|
220
211
|
await client.webhooks.rotateSecret(webhook.data.id);
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
FlexOps sends these events, named exactly as below. Names are PascalCase and matched exactly, so a
|
|
215
|
+
name like `label.created` would never match; the SDK refuses unknown names with an
|
|
216
|
+
`UnknownWebhookEvent` error.
|
|
217
|
+
|
|
218
|
+
| Event | Sent when |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `LabelCreated` | A live label is purchased (sandbox labels send nothing) |
|
|
221
|
+
| `LabelCanceled` | A live label is voided |
|
|
222
|
+
| `BatchCompleted` | A batch label job finishes |
|
|
223
|
+
| `TrackingUpdated` | A USPS tracking scan arrives (USPS push-tracking pilot workspaces only) |
|
|
224
|
+
| `TrackingDelivered` | A USPS package is delivered (USPS push-tracking pilot workspaces only) |
|
|
225
|
+
|
|
226
|
+
### Verifying deliveries
|
|
227
|
+
|
|
228
|
+
Each delivery is a `POST` whose body is the event data itself (there is no `{ type, data }`
|
|
229
|
+
envelope). The headers carry the rest:
|
|
230
|
+
|
|
231
|
+
| Header | Value |
|
|
232
|
+
|---|---|
|
|
233
|
+
| `X-FlexOps-Event` | Event name, e.g. `LabelCreated`; `test` for a test delivery |
|
|
234
|
+
| `X-FlexOps-Event-Id` | Event ID; use it to ignore retried duplicates |
|
|
235
|
+
| `X-FlexOps-Timestamp` | Unix seconds when the delivery was signed |
|
|
236
|
+
| `X-FlexOps-Signature` | `sha256=` + hex HMAC-SHA256 of `{timestamp}.{raw body}`, keyed with your `whsec_...` secret |
|
|
237
|
+
| `X-FlexOps-Delivery` | Delivery attempt ID |
|
|
238
|
+
|
|
239
|
+
Verify against the raw body bytes. Re-serializing parsed JSON (`JSON.stringify(req.body)`) does not
|
|
240
|
+
reproduce what was signed.
|
|
221
241
|
|
|
222
|
-
|
|
242
|
+
```typescript
|
|
243
|
+
import express from 'express';
|
|
223
244
|
import { WebhooksResource } from '@flexops/sdk';
|
|
224
245
|
|
|
225
|
-
app.post('/webhooks/flexops', (req, res) => {
|
|
226
|
-
const signature = req.headers['x-flexops-signature'];
|
|
246
|
+
app.post('/webhooks/flexops', express.raw({ type: 'application/json' }), (req, res) => {
|
|
227
247
|
const isValid = WebhooksResource.verifySignature(
|
|
228
|
-
|
|
229
|
-
signature,
|
|
230
|
-
process.env.FLEXOPS_WEBHOOK_SECRET
|
|
248
|
+
req.body, // raw Buffer from express.raw()
|
|
249
|
+
req.header('x-flexops-signature'),
|
|
250
|
+
process.env.FLEXOPS_WEBHOOK_SECRET!,
|
|
251
|
+
req.header('x-flexops-timestamp'), // rejected if more than 300 s from now
|
|
231
252
|
);
|
|
232
|
-
|
|
233
253
|
if (!isValid) return res.status(401).send('Invalid signature');
|
|
234
|
-
|
|
254
|
+
|
|
255
|
+
const eventType = req.header('x-flexops-event'); // 'LabelCreated', 'TrackingUpdated', 'test', ...
|
|
256
|
+
const data = JSON.parse(req.body.toString('utf8')); // the event data; no envelope
|
|
257
|
+
// Process the event...
|
|
258
|
+
res.sendStatus(200);
|
|
235
259
|
});
|
|
236
260
|
```
|
|
237
261
|
|
|
262
|
+
Pass `{ toleranceSeconds }` as a fifth argument to change the 300 second timestamp window.
|
|
263
|
+
|
|
238
264
|
## Curl Quickstart
|
|
239
265
|
|
|
240
266
|
Every SDK method is a thin wrapper around the FlexOps REST API. If you want to verify the API before committing to the SDK — or you're integrating from a language we don't ship a SDK for — these curl invocations hit the same endpoints:
|
|
@@ -250,44 +276,37 @@ curl -X POST https://gateway.flexops.io/api/shipping/rates \
|
|
|
250
276
|
"package": {"weight": 16, "weightUnit": "oz"}
|
|
251
277
|
}'
|
|
252
278
|
|
|
253
|
-
# Create a label
|
|
254
|
-
curl -X POST https://gateway.flexops.io/api/
|
|
279
|
+
# Create a label (hazmatClassification 0 = not hazardous; required when there is no orderId)
|
|
280
|
+
curl -X POST https://gateway.flexops.io/api/shipping/labels \
|
|
255
281
|
-H "X-API-Key: fxk_live_..." \
|
|
256
282
|
-H "Content-Type: application/json" \
|
|
257
283
|
-d '{
|
|
258
|
-
"
|
|
259
|
-
"
|
|
260
|
-
"
|
|
261
|
-
"
|
|
262
|
-
"
|
|
284
|
+
"carrierCode": "USPS",
|
|
285
|
+
"serviceCode": "PRIORITY",
|
|
286
|
+
"origin": {"name": "Warehouse", "addressLine1": "123 Main St", "city": "New York", "stateProvince": "NY", "postalCode": "10001", "countryCode": "US"},
|
|
287
|
+
"destination": {"name": "Customer", "addressLine1": "456 Oak Ave", "city": "Los Angeles", "stateProvince": "CA", "postalCode": "90210", "countryCode": "US"},
|
|
288
|
+
"package": {"weight": 16, "weightUnit": "oz"},
|
|
289
|
+
"hazmatClassification": 0
|
|
263
290
|
}'
|
|
264
291
|
|
|
265
292
|
# Track a shipment
|
|
266
|
-
curl https://gateway.flexops.io/api/
|
|
293
|
+
curl https://gateway.flexops.io/api/shipping/track/9400111899223456789012 \
|
|
267
294
|
-H "X-API-Key: fxk_live_..."
|
|
268
295
|
|
|
269
|
-
# Cancel a label
|
|
270
|
-
curl -X DELETE https://gateway.flexops.io/api/
|
|
296
|
+
# Cancel (void) a label
|
|
297
|
+
curl -X DELETE "https://gateway.flexops.io/api/shipping/labels/{labelId}?carrierCode=usps" \
|
|
271
298
|
-H "X-API-Key: fxk_live_..."
|
|
272
299
|
```
|
|
273
300
|
|
|
274
301
|
Use an `fxk_test_...` key instead of `fxk_live_...` to hit the sandbox environment; mock carriers respond, no real charges, no real labels.
|
|
275
302
|
|
|
276
|
-
## Wallet
|
|
303
|
+
## Wallet
|
|
277
304
|
|
|
278
|
-
|
|
279
|
-
const balance = await client.wallet.getBalance();
|
|
280
|
-
console.log(`Balance: $${balance.data.balance}`);
|
|
281
|
-
|
|
282
|
-
// Add funds
|
|
283
|
-
await client.wallet.addFunds(100.00);
|
|
305
|
+
The balance is read-only here; funding and auto-reload are managed in the FlexOps portal.
|
|
284
306
|
|
|
285
|
-
|
|
286
|
-
await client.wallet.
|
|
287
|
-
|
|
288
|
-
threshold: 25.00,
|
|
289
|
-
amount: 100.00,
|
|
290
|
-
});
|
|
307
|
+
```typescript
|
|
308
|
+
const balance = await client.wallet.getBalance(); // for client.workspaceId
|
|
309
|
+
console.log(`Balance: $${balance.balance}`);
|
|
291
310
|
```
|
|
292
311
|
|
|
293
312
|
## Insurance
|
|
@@ -298,38 +317,92 @@ const providers = await client.insurance.getProviders();
|
|
|
298
317
|
// Returns ["FlexOps"] or ["FlexOps", "U-PIC"]
|
|
299
318
|
|
|
300
319
|
// Get a quote
|
|
301
|
-
const quote = await client.insurance.getQuote({
|
|
302
|
-
carrier: 'USPS',
|
|
303
|
-
declaredValue: 500.00,
|
|
304
|
-
provider: 'FlexOps',
|
|
305
|
-
});
|
|
320
|
+
const quote = await client.insurance.getQuote({ carrierCode: 'usps', declaredValue: 500.00 });
|
|
306
321
|
|
|
307
|
-
// Purchase insurance
|
|
322
|
+
// Purchase insurance (premium charged to the wallet). A shipment already insured is refused
|
|
323
|
+
// with 409 ALREADY_EXISTS.
|
|
308
324
|
const policy = await client.insurance.purchase({
|
|
309
325
|
trackingNumber: '9400111899223456789012',
|
|
310
|
-
|
|
326
|
+
carrierCode: 'usps',
|
|
311
327
|
declaredValue: 500.00,
|
|
312
328
|
});
|
|
329
|
+
|
|
330
|
+
// File a claim
|
|
331
|
+
await client.insurance.fileClaim({ policyId: policy.data.policyId, claimReason: 'Lost in transit', claimAmount: 500.00 });
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## Carbon Offsets
|
|
335
|
+
|
|
336
|
+
```typescript
|
|
337
|
+
const quote = await client.carbonOffsets.quote({ weightLbs: 2, distanceMiles: 800 });
|
|
338
|
+
const offset = await client.carbonOffsets.purchase({ trackingNumber: '9400...', weightLbs: 2, distanceMiles: 800 });
|
|
339
|
+
const summary = await client.carbonOffsets.getSummary();
|
|
313
340
|
```
|
|
314
341
|
|
|
315
342
|
## Returns & RMA
|
|
316
343
|
|
|
317
344
|
```typescript
|
|
318
|
-
// Create a return authorization
|
|
345
|
+
// Create a return authorization for an order (numeric order id)
|
|
319
346
|
const rma = await client.returns.create({
|
|
320
|
-
orderId:
|
|
347
|
+
orderId: 12345,
|
|
321
348
|
reason: 'Defective product',
|
|
322
349
|
items: [{ sku: 'WIDGET-001', quantity: 1 }],
|
|
323
350
|
});
|
|
324
351
|
|
|
325
|
-
//
|
|
326
|
-
|
|
327
|
-
await client.returns.generateLabel(
|
|
352
|
+
// Generate the return label. Send the package weight and size. Anything left out comes from the
|
|
353
|
+
// workspace's default shipping preset; with no preset the API answers 400 PackageMeasurementsRequired.
|
|
354
|
+
await client.returns.generateLabel('RMA-12345', {
|
|
355
|
+
weightOz: 16,
|
|
356
|
+
lengthIn: 10,
|
|
357
|
+
widthIn: 8,
|
|
358
|
+
heightIn: 4,
|
|
359
|
+
});
|
|
328
360
|
|
|
329
|
-
//
|
|
330
|
-
await client.returns.markReceived(
|
|
331
|
-
|
|
332
|
-
|
|
361
|
+
// Record the inspected items at a warehouse (disposition 0 restock, 1 refurbish, 2 dispose)
|
|
362
|
+
await client.returns.markReceived(rmaId, {
|
|
363
|
+
rmaNumber: 'RMA-12345',
|
|
364
|
+
warehouseId: 1,
|
|
365
|
+
inspectedItems: [{ partNumber: 'WIDGET-001', quantity: 1, disposition: 2 }],
|
|
366
|
+
});
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
Approving, rejecting, cancelling and refunding returns are done in the FlexOps portal.
|
|
370
|
+
|
|
371
|
+
## Recurring Shipments, Report Schedules and Email Templates
|
|
372
|
+
|
|
373
|
+
Reads work with any API key. Writes need a user token (`auth.login`) or an API key granted the
|
|
374
|
+
resource's write permission: `recurring-shipments:write`, `report-schedules:write` or
|
|
375
|
+
`email-templates:write`. Other keys get 403 `API_KEY_SCOPE_REQUIRED`.
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
import { RecurrenceInterval, ReportFormat, ReportFrequency, TrackingEmailEvent } from '@flexops/sdk';
|
|
379
|
+
|
|
380
|
+
// Ship the same package to a saved address every week
|
|
381
|
+
const recurring = await client.recurringShipments.create({
|
|
382
|
+
name: 'Weekly refill',
|
|
383
|
+
addressId: 'address-guid',
|
|
384
|
+
presetId: 'preset-guid',
|
|
385
|
+
interval: RecurrenceInterval.Weekly,
|
|
386
|
+
firstRunUtc: '2026-11-02T15:00:00Z',
|
|
387
|
+
});
|
|
388
|
+
await client.recurringShipments.trigger(recurring.id); // run now (creates an order)
|
|
389
|
+
|
|
390
|
+
// Email a shipments report every Monday at 08:00 UTC
|
|
391
|
+
await client.reportSchedules.create({
|
|
392
|
+
reportType: 'shipments',
|
|
393
|
+
format: ReportFormat.Csv,
|
|
394
|
+
frequencyType: ReportFrequency.Weekly,
|
|
395
|
+
dayOfWeek: 1,
|
|
396
|
+
timeOfDayUtc: '08:00:00',
|
|
397
|
+
recipientEmails: 'ops@example.com',
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
// Customize the "delivered" tracking email
|
|
401
|
+
await client.emailTemplates.upsert({
|
|
402
|
+
eventType: TrackingEmailEvent.Delivered,
|
|
403
|
+
subjectTemplate: 'Your order has arrived',
|
|
404
|
+
htmlBodyTemplate: '<p>Delivered.</p>',
|
|
405
|
+
});
|
|
333
406
|
```
|
|
334
407
|
|
|
335
408
|
## Analytics
|
|
@@ -352,7 +425,7 @@ const performance = await client.analytics.deliveryPerformance();
|
|
|
352
425
|
// Create a shipping rule
|
|
353
426
|
await client.rules.create({
|
|
354
427
|
name: 'Route light packages via USPS',
|
|
355
|
-
|
|
428
|
+
isEnabled: true,
|
|
356
429
|
priority: 1,
|
|
357
430
|
conditions: [
|
|
358
431
|
{ field: 'Weight', operator: 'LessThan', value: '16' },
|
|
@@ -363,6 +436,9 @@ await client.rules.create({
|
|
|
363
436
|
{ type: 'SetService', value: 'GROUND_ADVANTAGE' },
|
|
364
437
|
],
|
|
365
438
|
});
|
|
439
|
+
|
|
440
|
+
// Dry-run the rules against a sample shipment
|
|
441
|
+
const result = await client.rules.test({ weightOz: 12, declaredValue: 25, destinationCountry: 'US', itemCount: 1 });
|
|
366
442
|
```
|
|
367
443
|
|
|
368
444
|
## Error Handling
|
|
@@ -403,6 +479,21 @@ const client = new FlexOps({
|
|
|
403
479
|
});
|
|
404
480
|
```
|
|
405
481
|
|
|
482
|
+
## Retries
|
|
483
|
+
|
|
484
|
+
Requests that fail with a network error, a timeout or a 429/502/503/504 are retried with
|
|
485
|
+
exponential backoff (`retry.maxRetries`, default 3). Retries are safe for purchases:
|
|
486
|
+
|
|
487
|
+
- Every `POST`, `PUT` and `PATCH` sends an `Idempotency-Key`: yours if you pass one, otherwise one
|
|
488
|
+
generated per call and reused on every retry of that call. The Gateway answers a repeated key with
|
|
489
|
+
the first result instead of running the request again. Pass your own key to purchases
|
|
490
|
+
(`insurance.purchase(request, key)`, `carbonOffsets.purchase(request, key)`) and store it, so a retry
|
|
491
|
+
your app makes after an error or a timeout reuses it and cannot buy twice.
|
|
492
|
+
- A write is never retried after a `500`, whose result the Gateway does not replay. A `409
|
|
493
|
+
IDEMPOTENCY_CONFLICT` (the first attempt is still running) is retried. A key reused with a different
|
|
494
|
+
request gets `422 IDEMPOTENCY_KEY_REUSED`, which is not retried: use a new key for a new request.
|
|
495
|
+
- `DELETE` is retried only on `429`. `GET` is retried on every status in `retryableStatusCodes`.
|
|
496
|
+
|
|
406
497
|
## OpenAPI Spec Generation
|
|
407
498
|
|
|
408
499
|
The SDK includes tooling to generate TypeScript types from the live API spec:
|