@flexops/sdk 1.1.1 → 3.0.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 +214 -142
- package/dist/index.d.mts +1065 -414
- package/dist/index.d.ts +1065 -414
- package/dist/index.js +818 -397
- package/dist/index.mjs +809 -394
- 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_...',
|
|
@@ -71,37 +71,26 @@ const fastest = await client.shipping.getFastestRate(rateRequest);
|
|
|
71
71
|
### Create a Shipping Label
|
|
72
72
|
|
|
73
73
|
```typescript
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
weight: 16,
|
|
95
|
-
weightUnit: 'oz',
|
|
96
|
-
length: 10,
|
|
97
|
-
width: 8,
|
|
98
|
-
height: 4,
|
|
99
|
-
dimensionUnit: 'in',
|
|
100
|
-
},
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
console.log(label.data.trackingNumber);
|
|
104
|
-
console.log(label.data.labelData); // Base64 PDF
|
|
74
|
+
const operation = await client.shipping.prepareLabel({
|
|
75
|
+
...rateRequest, carrierCode: 'USPS', serviceCode: 'PRIORITY',
|
|
76
|
+
// Required without an orderId. The SDK never fills it in; None = not hazardous.
|
|
77
|
+
hazmatClassification: HazmatClassification.None,
|
|
78
|
+
}, 10.00, crypto.randomUUID());
|
|
79
|
+
if (operation.preview) console.log({ quote: operation.preview.quotedPostageAmount,
|
|
80
|
+
maximum: operation.preview.maximumPostageAmount, currency: operation.preview.currency,
|
|
81
|
+
expiresAt: operation.preview.expiresAt }); // omit the signed token from display/logs
|
|
82
|
+
// Keep operation securely with the original Gateway and API-key identity.
|
|
83
|
+
|
|
84
|
+
// In a terminal example, ask explicitly before any live purchase:
|
|
85
|
+
const { createInterface } = await import('node:readline/promises');
|
|
86
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
87
|
+
try {
|
|
88
|
+
const approved = operation.sandboxLabel || await prompt.question('Type approve to buy at the displayed maximum (later adjustments/fees excluded): ') === 'approve';
|
|
89
|
+
if (approved) {
|
|
90
|
+
const label = await client.shipping.purchaseLabel(operation);
|
|
91
|
+
console.log(label.trackingNumber);
|
|
92
|
+
}
|
|
93
|
+
} finally { prompt.close(); }
|
|
105
94
|
```
|
|
106
95
|
|
|
107
96
|
### Tracking
|
|
@@ -109,7 +98,7 @@ console.log(label.data.labelData); // Base64 PDF
|
|
|
109
98
|
```typescript
|
|
110
99
|
const tracking = await client.shipping.track('9400111899223456789012');
|
|
111
100
|
|
|
112
|
-
for (const event of tracking.
|
|
101
|
+
for (const event of tracking.events) {
|
|
113
102
|
console.log(`${event.timestamp}: ${event.description}`);
|
|
114
103
|
}
|
|
115
104
|
```
|
|
@@ -126,8 +115,10 @@ const result = await client.shipping.validateAddress({
|
|
|
126
115
|
country: 'US',
|
|
127
116
|
});
|
|
128
117
|
|
|
129
|
-
if (
|
|
130
|
-
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);
|
|
131
122
|
}
|
|
132
123
|
```
|
|
133
124
|
|
|
@@ -148,106 +139,112 @@ const batch = await client.shipping.createBatch({
|
|
|
148
139
|
const status = await client.shipping.getBatchStatus(batch.data.jobId);
|
|
149
140
|
```
|
|
150
141
|
|
|
151
|
-
##
|
|
152
|
-
|
|
153
|
-
For full control, use carrier-specific endpoints:
|
|
154
|
-
|
|
155
|
-
### USPS
|
|
142
|
+
## Carrier-Specific Calls
|
|
156
143
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
mailClass: 'PRIORITY_MAIL',
|
|
162
|
-
weightInOunces: 16,
|
|
163
|
-
// ... full USPS API payload
|
|
164
|
-
});
|
|
144
|
+
Rates, labels, voids, pickups and scan forms go through `client.shipping`, `client.pickups` and
|
|
145
|
+
`client.scanForms`, which work for every carrier and with API keys. `client.carriers` reaches
|
|
146
|
+
carrier-specific endpoints through the Gateway's legacy pass-through, which is deprecated and
|
|
147
|
+
retired on 2027-06-30:
|
|
165
148
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
// Find drop-off locations
|
|
174
|
-
const locations = await client.carriers.usps.findDropOffLocations({
|
|
175
|
-
zipCode: '10001',
|
|
176
|
-
});
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
### UPS
|
|
149
|
+
- **Lookups (GET)** work with API keys.
|
|
150
|
+
- **Writes** (for example `carriers.usps.getDomesticRates`, `carriers.fedex.createPickup`) are marked
|
|
151
|
+
`@deprecated`. They need a user token (`auth.login`): the Gateway answers an API key with 403
|
|
152
|
+
`API_KEY_SCOPE_REQUIRED`. Move them to the native resources above.
|
|
153
|
+
- **Label purchases** through the pass-through are closed by the Gateway (410), so the SDK has no
|
|
154
|
+
carrier-specific label methods; buy labels with `client.shipping.createLabel`.
|
|
180
155
|
|
|
181
156
|
```typescript
|
|
182
|
-
const
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
const
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
### FedEx
|
|
189
|
-
|
|
190
|
-
```typescript
|
|
191
|
-
const shipment = await client.carriers.fedex.createShipment({ /* FedEx payload */ });
|
|
192
|
-
const rates = await client.carriers.fedex.getRates({ /* FedEx payload */ });
|
|
193
|
-
const tracking = await client.carriers.fedex.track({ /* payload */ });
|
|
194
|
-
|
|
195
|
-
// Multi-package (Open Ship)
|
|
196
|
-
await client.carriers.fedex.createOpenShipment({ /* payload */ });
|
|
197
|
-
await client.carriers.fedex.addPackagesToOpenShipment({ /* payload */ });
|
|
198
|
-
await client.carriers.fedex.confirmOpenShipment({ /* payload */ });
|
|
199
|
-
```
|
|
200
|
-
|
|
201
|
-
### DHL
|
|
202
|
-
|
|
203
|
-
```typescript
|
|
204
|
-
const shipment = await client.carriers.dhl.createShipment({ /* DHL payload */ });
|
|
205
|
-
const rates = await client.carriers.dhl.getRates({ countryCode: 'US', weight: '1' });
|
|
206
|
-
const tracking = await client.carriers.dhl.track({ shipmentTrackingNumber: '123456' });
|
|
207
|
-
const landedCost = await client.carriers.dhl.calculateLandedCost({ /* payload */ });
|
|
157
|
+
const city = await client.carriers.usps.cityStateLookup('10001');
|
|
158
|
+
const locations = await client.carriers.usps.findDropOffLocations({ zipCode: '10001' });
|
|
159
|
+
const upsTracking = await client.carriers.ups.track({ trackingNumber: '1Z...' });
|
|
160
|
+
const dhlRates = await client.carriers.dhl.getRates({ countryCode: 'US', weight: '1' });
|
|
208
161
|
```
|
|
209
162
|
|
|
210
163
|
## Workspace Management
|
|
211
164
|
|
|
212
165
|
```typescript
|
|
166
|
+
import { WorkspaceRole } from '@flexops/sdk';
|
|
167
|
+
|
|
213
168
|
// List workspaces
|
|
214
169
|
const workspaces = await client.workspaces.list();
|
|
215
170
|
|
|
216
171
|
// Switch workspace
|
|
217
172
|
client.workspaceId = 'different-workspace-id';
|
|
218
173
|
|
|
219
|
-
//
|
|
220
|
-
await client.workspaces.
|
|
174
|
+
// Members and pending invites
|
|
175
|
+
const { data } = await client.workspaces.listMembers();
|
|
176
|
+
console.log(data.members.length, data.pendingInvites.length);
|
|
177
|
+
|
|
178
|
+
// Invite a member (roles are numbers on the wire; use WorkspaceRole)
|
|
179
|
+
await client.workspaces.inviteMember('newuser@company.com', WorkspaceRole.Member);
|
|
221
180
|
```
|
|
222
181
|
|
|
223
182
|
## Webhooks
|
|
224
183
|
|
|
225
184
|
```typescript
|
|
226
|
-
|
|
185
|
+
import { WebhookEventType } from '@flexops/sdk';
|
|
186
|
+
|
|
187
|
+
// Create a subscription. Omit `events` to receive every event.
|
|
227
188
|
const webhook = await client.webhooks.create({
|
|
228
189
|
url: 'https://your-app.com/webhooks/flexops',
|
|
229
|
-
events: [
|
|
190
|
+
events: [WebhookEventType.LabelCreated, WebhookEventType.LabelCanceled, WebhookEventType.BatchCompleted],
|
|
230
191
|
});
|
|
192
|
+
const signingSecret = webhook.data.secret; // returned only on create; store it
|
|
231
193
|
|
|
232
194
|
// Rotate the signing secret
|
|
233
195
|
await client.webhooks.rotateSecret(webhook.data.id);
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
FlexOps sends these events, named exactly as below. Names are PascalCase and matched exactly, so a
|
|
199
|
+
name like `label.created` would never match; the SDK refuses unknown names with an
|
|
200
|
+
`UnknownWebhookEvent` error.
|
|
201
|
+
|
|
202
|
+
| Event | Sent when |
|
|
203
|
+
|---|---|
|
|
204
|
+
| `LabelCreated` | A live label is purchased (sandbox labels send nothing) |
|
|
205
|
+
| `LabelCanceled` | A live label is voided |
|
|
206
|
+
| `BatchCompleted` | A batch label job finishes |
|
|
207
|
+
| `TrackingUpdated` | A USPS tracking scan arrives (USPS push-tracking pilot workspaces only) |
|
|
208
|
+
| `TrackingDelivered` | A USPS package is delivered (USPS push-tracking pilot workspaces only) |
|
|
209
|
+
|
|
210
|
+
### Verifying deliveries
|
|
234
211
|
|
|
235
|
-
|
|
212
|
+
Each delivery is a `POST` whose body is the event data itself (there is no `{ type, data }`
|
|
213
|
+
envelope). The headers carry the rest:
|
|
214
|
+
|
|
215
|
+
| Header | Value |
|
|
216
|
+
|---|---|
|
|
217
|
+
| `X-FlexOps-Event` | Event name, e.g. `LabelCreated`; `test` for a test delivery |
|
|
218
|
+
| `X-FlexOps-Event-Id` | Event ID; use it to ignore retried duplicates |
|
|
219
|
+
| `X-FlexOps-Timestamp` | Unix seconds when the delivery was signed |
|
|
220
|
+
| `X-FlexOps-Signature` | `sha256=` + hex HMAC-SHA256 of `{timestamp}.{raw body}`, keyed with your `whsec_...` secret |
|
|
221
|
+
| `X-FlexOps-Delivery` | Delivery attempt ID |
|
|
222
|
+
|
|
223
|
+
Verify against the raw body bytes. Re-serializing parsed JSON (`JSON.stringify(req.body)`) does not
|
|
224
|
+
reproduce what was signed.
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
import express from 'express';
|
|
236
228
|
import { WebhooksResource } from '@flexops/sdk';
|
|
237
229
|
|
|
238
|
-
app.post('/webhooks/flexops', (req, res) => {
|
|
239
|
-
const signature = req.headers['x-flexops-signature'];
|
|
230
|
+
app.post('/webhooks/flexops', express.raw({ type: 'application/json' }), (req, res) => {
|
|
240
231
|
const isValid = WebhooksResource.verifySignature(
|
|
241
|
-
|
|
242
|
-
signature,
|
|
243
|
-
process.env.FLEXOPS_WEBHOOK_SECRET
|
|
232
|
+
req.body, // raw Buffer from express.raw()
|
|
233
|
+
req.header('x-flexops-signature'),
|
|
234
|
+
process.env.FLEXOPS_WEBHOOK_SECRET!,
|
|
235
|
+
req.header('x-flexops-timestamp'), // rejected if more than 300 s from now
|
|
244
236
|
);
|
|
245
|
-
|
|
246
237
|
if (!isValid) return res.status(401).send('Invalid signature');
|
|
247
|
-
|
|
238
|
+
|
|
239
|
+
const eventType = req.header('x-flexops-event'); // 'LabelCreated', 'TrackingUpdated', 'test', ...
|
|
240
|
+
const data = JSON.parse(req.body.toString('utf8')); // the event data; no envelope
|
|
241
|
+
// Process the event...
|
|
242
|
+
res.sendStatus(200);
|
|
248
243
|
});
|
|
249
244
|
```
|
|
250
245
|
|
|
246
|
+
Pass `{ toleranceSeconds }` as a fifth argument to change the 300 second timestamp window.
|
|
247
|
+
|
|
251
248
|
## Curl Quickstart
|
|
252
249
|
|
|
253
250
|
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:
|
|
@@ -263,44 +260,37 @@ curl -X POST https://gateway.flexops.io/api/shipping/rates \
|
|
|
263
260
|
"package": {"weight": 16, "weightUnit": "oz"}
|
|
264
261
|
}'
|
|
265
262
|
|
|
266
|
-
# Create a label
|
|
267
|
-
curl -X POST https://gateway.flexops.io/api/
|
|
263
|
+
# Create a label (hazmatClassification 0 = not hazardous; required when there is no orderId)
|
|
264
|
+
curl -X POST https://gateway.flexops.io/api/shipping/labels \
|
|
268
265
|
-H "X-API-Key: fxk_live_..." \
|
|
269
266
|
-H "Content-Type: application/json" \
|
|
270
267
|
-d '{
|
|
271
|
-
"
|
|
272
|
-
"
|
|
273
|
-
"
|
|
274
|
-
"
|
|
275
|
-
"
|
|
268
|
+
"carrierCode": "USPS",
|
|
269
|
+
"serviceCode": "PRIORITY",
|
|
270
|
+
"origin": {"name": "Warehouse", "addressLine1": "123 Main St", "city": "New York", "stateProvince": "NY", "postalCode": "10001", "countryCode": "US"},
|
|
271
|
+
"destination": {"name": "Customer", "addressLine1": "456 Oak Ave", "city": "Los Angeles", "stateProvince": "CA", "postalCode": "90210", "countryCode": "US"},
|
|
272
|
+
"package": {"weight": 16, "weightUnit": "oz"},
|
|
273
|
+
"hazmatClassification": 0
|
|
276
274
|
}'
|
|
277
275
|
|
|
278
276
|
# Track a shipment
|
|
279
|
-
curl https://gateway.flexops.io/api/
|
|
277
|
+
curl https://gateway.flexops.io/api/shipping/track/9400111899223456789012 \
|
|
280
278
|
-H "X-API-Key: fxk_live_..."
|
|
281
279
|
|
|
282
|
-
# Cancel a label
|
|
283
|
-
curl -X DELETE https://gateway.flexops.io/api/
|
|
280
|
+
# Cancel (void) a label
|
|
281
|
+
curl -X DELETE "https://gateway.flexops.io/api/shipping/labels/{labelId}?carrierCode=usps" \
|
|
284
282
|
-H "X-API-Key: fxk_live_..."
|
|
285
283
|
```
|
|
286
284
|
|
|
287
285
|
Use an `fxk_test_...` key instead of `fxk_live_...` to hit the sandbox environment; mock carriers respond, no real charges, no real labels.
|
|
288
286
|
|
|
289
|
-
## Wallet
|
|
290
|
-
|
|
291
|
-
```typescript
|
|
292
|
-
const balance = await client.wallet.getBalance();
|
|
293
|
-
console.log(`Balance: $${balance.data.balance}`);
|
|
287
|
+
## Wallet
|
|
294
288
|
|
|
295
|
-
|
|
296
|
-
await client.wallet.addFunds(100.00);
|
|
289
|
+
The balance is read-only here; funding and auto-reload are managed in the FlexOps portal.
|
|
297
290
|
|
|
298
|
-
|
|
299
|
-
await client.wallet.
|
|
300
|
-
|
|
301
|
-
threshold: 25.00,
|
|
302
|
-
amount: 100.00,
|
|
303
|
-
});
|
|
291
|
+
```typescript
|
|
292
|
+
const balance = await client.wallet.getBalance(); // for client.workspaceId
|
|
293
|
+
console.log(`Balance: $${balance.balance}`);
|
|
304
294
|
```
|
|
305
295
|
|
|
306
296
|
## Insurance
|
|
@@ -311,38 +301,92 @@ const providers = await client.insurance.getProviders();
|
|
|
311
301
|
// Returns ["FlexOps"] or ["FlexOps", "U-PIC"]
|
|
312
302
|
|
|
313
303
|
// Get a quote
|
|
314
|
-
const quote = await client.insurance.getQuote({
|
|
315
|
-
carrier: 'USPS',
|
|
316
|
-
declaredValue: 500.00,
|
|
317
|
-
provider: 'FlexOps',
|
|
318
|
-
});
|
|
304
|
+
const quote = await client.insurance.getQuote({ carrierCode: 'usps', declaredValue: 500.00 });
|
|
319
305
|
|
|
320
|
-
// Purchase insurance
|
|
306
|
+
// Purchase insurance (premium charged to the wallet). A shipment already insured is refused
|
|
307
|
+
// with 409 ALREADY_EXISTS.
|
|
321
308
|
const policy = await client.insurance.purchase({
|
|
322
309
|
trackingNumber: '9400111899223456789012',
|
|
323
|
-
|
|
310
|
+
carrierCode: 'usps',
|
|
324
311
|
declaredValue: 500.00,
|
|
325
312
|
});
|
|
313
|
+
|
|
314
|
+
// File a claim
|
|
315
|
+
await client.insurance.fileClaim({ policyId: policy.data.policyId, claimReason: 'Lost in transit', claimAmount: 500.00 });
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
## Carbon Offsets
|
|
319
|
+
|
|
320
|
+
```typescript
|
|
321
|
+
const quote = await client.carbonOffsets.quote({ weightLbs: 2, distanceMiles: 800 });
|
|
322
|
+
const offset = await client.carbonOffsets.purchase({ trackingNumber: '9400...', weightLbs: 2, distanceMiles: 800 });
|
|
323
|
+
const summary = await client.carbonOffsets.getSummary();
|
|
326
324
|
```
|
|
327
325
|
|
|
328
326
|
## Returns & RMA
|
|
329
327
|
|
|
330
328
|
```typescript
|
|
331
|
-
// Create a return authorization
|
|
329
|
+
// Create a return authorization for an order (numeric order id)
|
|
332
330
|
const rma = await client.returns.create({
|
|
333
|
-
orderId:
|
|
331
|
+
orderId: 12345,
|
|
334
332
|
reason: 'Defective product',
|
|
335
333
|
items: [{ sku: 'WIDGET-001', quantity: 1 }],
|
|
336
334
|
});
|
|
337
335
|
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
await client.returns.generateLabel(
|
|
336
|
+
// Generate the return label. Send the package weight and size. Anything left out comes from the
|
|
337
|
+
// workspace's default shipping preset; with no preset the API answers 400 PackageMeasurementsRequired.
|
|
338
|
+
await client.returns.generateLabel('RMA-12345', {
|
|
339
|
+
weightOz: 16,
|
|
340
|
+
lengthIn: 10,
|
|
341
|
+
widthIn: 8,
|
|
342
|
+
heightIn: 4,
|
|
343
|
+
});
|
|
341
344
|
|
|
342
|
-
//
|
|
343
|
-
await client.returns.markReceived(
|
|
344
|
-
|
|
345
|
-
|
|
345
|
+
// Record the inspected items at a warehouse (disposition 0 restock, 1 refurbish, 2 dispose)
|
|
346
|
+
await client.returns.markReceived(rmaId, {
|
|
347
|
+
rmaNumber: 'RMA-12345',
|
|
348
|
+
warehouseId: 1,
|
|
349
|
+
inspectedItems: [{ partNumber: 'WIDGET-001', quantity: 1, disposition: 2 }],
|
|
350
|
+
});
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
Approving, rejecting, cancelling and refunding returns are done in the FlexOps portal.
|
|
354
|
+
|
|
355
|
+
## Recurring Shipments, Report Schedules and Email Templates
|
|
356
|
+
|
|
357
|
+
Reads work with any API key. Writes need a user token (`auth.login`) or an API key granted the
|
|
358
|
+
resource's write permission: `recurring-shipments:write`, `report-schedules:write` or
|
|
359
|
+
`email-templates:write`. Other keys get 403 `API_KEY_SCOPE_REQUIRED`.
|
|
360
|
+
|
|
361
|
+
```typescript
|
|
362
|
+
import { RecurrenceInterval, ReportFormat, ReportFrequency, TrackingEmailEvent } from '@flexops/sdk';
|
|
363
|
+
|
|
364
|
+
// Ship the same package to a saved address every week
|
|
365
|
+
const recurring = await client.recurringShipments.create({
|
|
366
|
+
name: 'Weekly refill',
|
|
367
|
+
addressId: 'address-guid',
|
|
368
|
+
presetId: 'preset-guid',
|
|
369
|
+
interval: RecurrenceInterval.Weekly,
|
|
370
|
+
firstRunUtc: '2026-11-02T15:00:00Z',
|
|
371
|
+
});
|
|
372
|
+
await client.recurringShipments.trigger(recurring.id); // run now (creates an order)
|
|
373
|
+
|
|
374
|
+
// Email a shipments report every Monday at 08:00 UTC
|
|
375
|
+
await client.reportSchedules.create({
|
|
376
|
+
reportType: 'shipments',
|
|
377
|
+
format: ReportFormat.Csv,
|
|
378
|
+
frequencyType: ReportFrequency.Weekly,
|
|
379
|
+
dayOfWeek: 1,
|
|
380
|
+
timeOfDayUtc: '08:00:00',
|
|
381
|
+
recipientEmails: 'ops@example.com',
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
// Customize the "delivered" tracking email
|
|
385
|
+
await client.emailTemplates.upsert({
|
|
386
|
+
eventType: TrackingEmailEvent.Delivered,
|
|
387
|
+
subjectTemplate: 'Your order has arrived',
|
|
388
|
+
htmlBodyTemplate: '<p>Delivered.</p>',
|
|
389
|
+
});
|
|
346
390
|
```
|
|
347
391
|
|
|
348
392
|
## Analytics
|
|
@@ -365,7 +409,7 @@ const performance = await client.analytics.deliveryPerformance();
|
|
|
365
409
|
// Create a shipping rule
|
|
366
410
|
await client.rules.create({
|
|
367
411
|
name: 'Route light packages via USPS',
|
|
368
|
-
|
|
412
|
+
isEnabled: true,
|
|
369
413
|
priority: 1,
|
|
370
414
|
conditions: [
|
|
371
415
|
{ field: 'Weight', operator: 'LessThan', value: '16' },
|
|
@@ -376,6 +420,9 @@ await client.rules.create({
|
|
|
376
420
|
{ type: 'SetService', value: 'GROUND_ADVANTAGE' },
|
|
377
421
|
],
|
|
378
422
|
});
|
|
423
|
+
|
|
424
|
+
// Dry-run the rules against a sample shipment
|
|
425
|
+
const result = await client.rules.test({ weightOz: 12, declaredValue: 25, destinationCountry: 'US', itemCount: 1 });
|
|
379
426
|
```
|
|
380
427
|
|
|
381
428
|
## Error Handling
|
|
@@ -416,6 +463,21 @@ const client = new FlexOps({
|
|
|
416
463
|
});
|
|
417
464
|
```
|
|
418
465
|
|
|
466
|
+
## Retries
|
|
467
|
+
|
|
468
|
+
Requests that fail with a network error, a timeout or a 429/502/503/504 are retried with
|
|
469
|
+
exponential backoff (`retry.maxRetries`, default 3). Retries are safe for purchases:
|
|
470
|
+
|
|
471
|
+
- Every `POST`, `PUT` and `PATCH` sends an `Idempotency-Key`: yours if you pass one, otherwise one
|
|
472
|
+
generated per call and reused on every retry of that call. The Gateway answers a repeated key with
|
|
473
|
+
the first result instead of running the request again. Pass your own key to purchases
|
|
474
|
+
(`insurance.purchase(request, key)`, `carbonOffsets.purchase(request, key)`) and store it, so a retry
|
|
475
|
+
your app makes after an error or a timeout reuses it and cannot buy twice.
|
|
476
|
+
- A write is never retried after a `500`, whose result the Gateway does not replay. A `409
|
|
477
|
+
IDEMPOTENCY_CONFLICT` (the first attempt is still running) is retried. A key reused with a different
|
|
478
|
+
request gets `422 IDEMPOTENCY_KEY_REUSED`, which is not retried: use a new key for a new request.
|
|
479
|
+
- `DELETE` is retried only on `429`. `GET` is retried on every status in `retryableStatusCodes`.
|
|
480
|
+
|
|
419
481
|
## OpenAPI Spec Generation
|
|
420
482
|
|
|
421
483
|
The SDK includes tooling to generate TypeScript types from the live API spec:
|
|
@@ -440,3 +502,13 @@ npm run build
|
|
|
440
502
|
## License
|
|
441
503
|
|
|
442
504
|
MIT © FlexOps, LLC. See [LICENSE](LICENSE) for full text.
|
|
505
|
+
|
|
506
|
+
### Approval and retries
|
|
507
|
+
|
|
508
|
+
Use these methods only with Gateway's bounded approval contract; coordinate client/Gateway activation. Preparation does not automatically approve. The ceiling covers pre-dispatch postage, excluding later carrier adjustments and separate fees. Persist the operation securely if it must survive process restart. Retry the same request/key after response loss; OutcomeUnknown requires reconciliation, never a new purchase key. Completed replay remains possible after token expiry. Sandbox operations return a synthetic label without real postage. The legacy createLabel and USPS domestic wrapper reject preview responses; use shipping.prepareLabel/purchaseLabel for live purchases.
|
|
509
|
+
|
|
510
|
+
## Guarded label release compatibility
|
|
511
|
+
|
|
512
|
+
This release requires a Gateway deployment with the bounded label preview/approval contract (Gateway PR #509 or later). Do not use its live label preparation against an older Gateway: older servers may purchase immediately. Upgrade the Gateway and affected callers together during a purchase maintenance window.
|
|
513
|
+
|
|
514
|
+
Live label creation now requires a USD maximum, preview, explicit approval, and replay of the saved request with its original idempotency key. Never retry an uncertain purchase with a new key. Sandbox results do not certify production postage.
|