@flexops/sdk 1.1.1 → 2.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 +28 -31
- package/dist/index.d.mts +32 -2
- package/dist/index.d.ts +32 -2
- package/dist/index.js +33 -3
- package/dist/index.mjs +33 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -71,37 +71,24 @@ 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
|
-
parcel: {
|
|
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
|
+
}, 10.00, crypto.randomUUID());
|
|
77
|
+
if (operation.preview) console.log({ quote: operation.preview.quotedPostageAmount,
|
|
78
|
+
maximum: operation.preview.maximumPostageAmount, currency: operation.preview.currency,
|
|
79
|
+
expiresAt: operation.preview.expiresAt }); // omit the signed token from display/logs
|
|
80
|
+
// Keep operation securely with the original Gateway and API-key identity.
|
|
81
|
+
|
|
82
|
+
// In a terminal example, ask explicitly before any live purchase:
|
|
83
|
+
const { createInterface } = await import('node:readline/promises');
|
|
84
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
85
|
+
try {
|
|
86
|
+
const approved = operation.sandboxLabel || await prompt.question('Type approve to buy at the displayed maximum (later adjustments/fees excluded): ') === 'approve';
|
|
87
|
+
if (approved) {
|
|
88
|
+
const label = await client.shipping.purchaseLabel(operation);
|
|
89
|
+
console.log(label.trackingNumber);
|
|
90
|
+
}
|
|
91
|
+
} finally { prompt.close(); }
|
|
105
92
|
```
|
|
106
93
|
|
|
107
94
|
### Tracking
|
|
@@ -440,3 +427,13 @@ npm run build
|
|
|
440
427
|
## License
|
|
441
428
|
|
|
442
429
|
MIT © FlexOps, LLC. See [LICENSE](LICENSE) for full text.
|
|
430
|
+
|
|
431
|
+
### Approval and retries
|
|
432
|
+
|
|
433
|
+
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.
|
|
434
|
+
|
|
435
|
+
## Guarded label release compatibility
|
|
436
|
+
|
|
437
|
+
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.
|
|
438
|
+
|
|
439
|
+
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.
|
package/dist/index.d.mts
CHANGED
|
@@ -149,6 +149,32 @@ interface CreateLabelRequest {
|
|
|
149
149
|
labelFormat?: 'PDF' | 'PNG' | 'ZPL';
|
|
150
150
|
idempotencyKey?: string;
|
|
151
151
|
}
|
|
152
|
+
/** Normalized Gateway label request. Additional shipment options are preserved in the approval snapshot. */
|
|
153
|
+
interface CanonicalLabelRequest {
|
|
154
|
+
origin: ShippingAddress;
|
|
155
|
+
destination: ShippingAddress;
|
|
156
|
+
package: ShippingPackage;
|
|
157
|
+
carrierCode: string;
|
|
158
|
+
serviceCode: string;
|
|
159
|
+
orderId?: number;
|
|
160
|
+
labelFormat?: 'PDF' | 'PNG' | 'ZPL';
|
|
161
|
+
[option: string]: unknown;
|
|
162
|
+
}
|
|
163
|
+
interface LabelPurchasePreview {
|
|
164
|
+
status: 'Preview';
|
|
165
|
+
quotedPostageAmount: number;
|
|
166
|
+
maximumPostageAmount: number;
|
|
167
|
+
currency: 'USD';
|
|
168
|
+
expiresAt: string;
|
|
169
|
+
confirmationToken: string;
|
|
170
|
+
}
|
|
171
|
+
/** Retain securely for retries; requestJson contains private shipment data and the approval token. */
|
|
172
|
+
interface LabelPurchaseApproval {
|
|
173
|
+
readonly idempotencyKey: string;
|
|
174
|
+
readonly requestJson: string;
|
|
175
|
+
readonly preview: LabelPurchasePreview | null;
|
|
176
|
+
readonly sandboxLabel?: Label;
|
|
177
|
+
}
|
|
152
178
|
interface Label {
|
|
153
179
|
labelId: string;
|
|
154
180
|
carrierCode: string;
|
|
@@ -630,7 +656,11 @@ declare class ShippingResource {
|
|
|
630
656
|
* existing order — the order's ownership, status, ship-method and addresses are validated
|
|
631
657
|
* server-side and postage is settled atomically. Returns the raw label (HTTP 201).
|
|
632
658
|
*/
|
|
633
|
-
createLabel(request: CreateLabelRequest): Promise<Label>;
|
|
659
|
+
createLabel(request: CreateLabelRequest | CanonicalLabelRequest): Promise<Label>;
|
|
660
|
+
/** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
|
|
661
|
+
prepareLabel(request: CanonicalLabelRequest, maximumPostageAmount: number, idempotencyKey: string): Promise<LabelPurchaseApproval>;
|
|
662
|
+
/** Call only after explicit approval. Same-key replay remains valid after token expiry. */
|
|
663
|
+
purchaseLabel(approval: LabelPurchaseApproval): Promise<Label>;
|
|
634
664
|
/** Cancel (void) a shipping label. `carrierCode` is required. */
|
|
635
665
|
cancelLabel(labelId: string, carrierCode: string): Promise<unknown>;
|
|
636
666
|
/** Track a shipment by tracking number. */
|
|
@@ -1266,4 +1296,4 @@ declare class FlexOps {
|
|
|
1266
1296
|
setApiKey(key: string): void;
|
|
1267
1297
|
}
|
|
1268
1298
|
|
|
1269
|
-
export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingAddress, type ShippingPackage, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
|
|
1299
|
+
export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CanonicalLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LabelPurchaseApproval, type LabelPurchasePreview, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingAddress, type ShippingPackage, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
|
package/dist/index.d.ts
CHANGED
|
@@ -149,6 +149,32 @@ interface CreateLabelRequest {
|
|
|
149
149
|
labelFormat?: 'PDF' | 'PNG' | 'ZPL';
|
|
150
150
|
idempotencyKey?: string;
|
|
151
151
|
}
|
|
152
|
+
/** Normalized Gateway label request. Additional shipment options are preserved in the approval snapshot. */
|
|
153
|
+
interface CanonicalLabelRequest {
|
|
154
|
+
origin: ShippingAddress;
|
|
155
|
+
destination: ShippingAddress;
|
|
156
|
+
package: ShippingPackage;
|
|
157
|
+
carrierCode: string;
|
|
158
|
+
serviceCode: string;
|
|
159
|
+
orderId?: number;
|
|
160
|
+
labelFormat?: 'PDF' | 'PNG' | 'ZPL';
|
|
161
|
+
[option: string]: unknown;
|
|
162
|
+
}
|
|
163
|
+
interface LabelPurchasePreview {
|
|
164
|
+
status: 'Preview';
|
|
165
|
+
quotedPostageAmount: number;
|
|
166
|
+
maximumPostageAmount: number;
|
|
167
|
+
currency: 'USD';
|
|
168
|
+
expiresAt: string;
|
|
169
|
+
confirmationToken: string;
|
|
170
|
+
}
|
|
171
|
+
/** Retain securely for retries; requestJson contains private shipment data and the approval token. */
|
|
172
|
+
interface LabelPurchaseApproval {
|
|
173
|
+
readonly idempotencyKey: string;
|
|
174
|
+
readonly requestJson: string;
|
|
175
|
+
readonly preview: LabelPurchasePreview | null;
|
|
176
|
+
readonly sandboxLabel?: Label;
|
|
177
|
+
}
|
|
152
178
|
interface Label {
|
|
153
179
|
labelId: string;
|
|
154
180
|
carrierCode: string;
|
|
@@ -630,7 +656,11 @@ declare class ShippingResource {
|
|
|
630
656
|
* existing order — the order's ownership, status, ship-method and addresses are validated
|
|
631
657
|
* server-side and postage is settled atomically. Returns the raw label (HTTP 201).
|
|
632
658
|
*/
|
|
633
|
-
createLabel(request: CreateLabelRequest): Promise<Label>;
|
|
659
|
+
createLabel(request: CreateLabelRequest | CanonicalLabelRequest): Promise<Label>;
|
|
660
|
+
/** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
|
|
661
|
+
prepareLabel(request: CanonicalLabelRequest, maximumPostageAmount: number, idempotencyKey: string): Promise<LabelPurchaseApproval>;
|
|
662
|
+
/** Call only after explicit approval. Same-key replay remains valid after token expiry. */
|
|
663
|
+
purchaseLabel(approval: LabelPurchaseApproval): Promise<Label>;
|
|
634
664
|
/** Cancel (void) a shipping label. `carrierCode` is required. */
|
|
635
665
|
cancelLabel(labelId: string, carrierCode: string): Promise<unknown>;
|
|
636
666
|
/** Track a shipment by tracking number. */
|
|
@@ -1266,4 +1296,4 @@ declare class FlexOps {
|
|
|
1266
1296
|
setApiKey(key: string): void;
|
|
1267
1297
|
}
|
|
1268
1298
|
|
|
1269
|
-
export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingAddress, type ShippingPackage, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
|
|
1299
|
+
export { type Address, type AddressValidationResult, AnalyticsResource, type ApiKeyInfo, ApiKeysResource, type ApiResponse, AuthResource, type BatchLabelJob, type BatchLabelRequest, type CanonicalLabelRequest, type CarrierRecommendation, type CarrierRecommendationRequest, type CarrierRecommendationResponse, type CarrierSummary, CarriersResource, type CostSavingsSummary, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateEmailTemplateRequest, type CreateLabelRequest, type CreateRecurringShipmentRequest, type CreateReportScheduleRequest, type CreateWebhookRequest, type CreateWorkspaceRequest, type CustomsItem, type DeliveryPredictionRequest, type DeliveryPredictionResponse, type EmailTemplate, EmailTemplatesResource, type EmissionsEstimate, FlexOps, FlexOpsAuthError, type FlexOpsConfig, FlexOpsError, FlexOpsRateLimitError, type HsCodeResult, HsCodesResource, type InsurancePolicy, type InsuranceQuote, InsuranceResource, InventoryResource, type Label, type LabelPurchaseApproval, type LabelPurchasePreview, type LandedCostEstimate, type LandedCostRequest, type LaneSavingsOpportunity, type LoginRequest, type LoginResponse, OffsetResource, type OffsetResult, type Order, type OrderItem, OrdersResource, type PaginatedResponse, type Parcel, type PickupConfirmation, type PickupRequest, PickupsResource, type RateRequest, type RecurringShipment, RecurringShipmentsResource, type RegisterRequest, type ReportSchedule, ReportsResource, type RetryConfig, type ReturnAuthorization, type ReturnItem, type ReturnRequest, ReturnsResource, type RuleAction, type RuleCondition, RulesResource, type ScanForm, type ScanFormRequest, ScanFormsResource, type ShipmentsTrend, type ShippingAddress, type ShippingPackage, type ShippingRate, ShippingResource, type ShippingRule, type TrackingEvent, type TrackingInfo, type UpdateEmailTemplateRequest, type UpdateRecurringShipmentRequest, type UpdateReportScheduleRequest, type WalletBalance, WalletResource, type WebhookSubscription, WebhooksResource, type Workspace, type WorkspaceMember, WorkspacesResource };
|
package/dist/index.js
CHANGED
|
@@ -153,7 +153,7 @@ var HttpClient = class {
|
|
|
153
153
|
const error = new FlexOpsError(
|
|
154
154
|
errorBody.message ?? `HTTP ${response.status}: ${response.statusText}`,
|
|
155
155
|
response.status,
|
|
156
|
-
|
|
156
|
+
errorBody.code ?? errorBody.errorCode,
|
|
157
157
|
errorBody.errors
|
|
158
158
|
);
|
|
159
159
|
if (this.retry.retryableStatusCodes.includes(response.status)) {
|
|
@@ -372,7 +372,37 @@ var ShippingResource = class {
|
|
|
372
372
|
* server-side and postage is settled atomically. Returns the raw label (HTTP 201).
|
|
373
373
|
*/
|
|
374
374
|
async createLabel(request) {
|
|
375
|
-
|
|
375
|
+
const result = await this.http.post("/api/shipping/labels", request);
|
|
376
|
+
if ("status" in result) throw new FlexOpsError("Approval required. Use prepareLabel, review its preview, then purchaseLabel.", 400, "ApprovalRequired");
|
|
377
|
+
return result;
|
|
378
|
+
}
|
|
379
|
+
/** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
|
|
380
|
+
async prepareLabel(request, maximumPostageAmount, idempotencyKey) {
|
|
381
|
+
if (!idempotencyKey.trim() || !Number.isFinite(maximumPostageAmount) || maximumPostageAmount <= 0 || maximumPostageAmount > 1e6 || Math.abs(maximumPostageAmount * 100 - Math.round(maximumPostageAmount * 100)) > 1e-7)
|
|
382
|
+
throw new FlexOpsError("Supply a stable key and positive USD maximum with at most two decimal places.", 400, "InvalidApproval");
|
|
383
|
+
const body = JSON.parse(JSON.stringify(request));
|
|
384
|
+
for (const key of Object.keys(body)) if (["confirmationtoken", "maximumpostageamount"].includes(key.toLowerCase())) delete body[key];
|
|
385
|
+
body.maximumPostageAmount = maximumPostageAmount;
|
|
386
|
+
const result = await this.http.request("POST", "/api/shipping/labels", {
|
|
387
|
+
body,
|
|
388
|
+
headers: { "Idempotency-Key": idempotencyKey }
|
|
389
|
+
});
|
|
390
|
+
if ("isSandbox" in result && result.isSandbox === true)
|
|
391
|
+
return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: null, sandboxLabel: result });
|
|
392
|
+
if (!("status" in result) || result.status !== "Preview" || !result.confirmationToken || result.currency !== "USD" || !Number.isFinite(result.quotedPostageAmount) || result.quotedPostageAmount <= 0 || result.quotedPostageAmount > maximumPostageAmount || result.maximumPostageAmount !== maximumPostageAmount || !Number.isFinite(Date.parse(result.expiresAt)))
|
|
393
|
+
throw new FlexOpsError("Gateway did not return a valid bounded preview.", 502, "InvalidPreview");
|
|
394
|
+
body.confirmationToken = result.confirmationToken;
|
|
395
|
+
return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: Object.freeze(result) });
|
|
396
|
+
}
|
|
397
|
+
/** Call only after explicit approval. Same-key replay remains valid after token expiry. */
|
|
398
|
+
async purchaseLabel(approval) {
|
|
399
|
+
if (approval.sandboxLabel) return approval.sandboxLabel;
|
|
400
|
+
const result = await this.http.request("POST", "/api/shipping/labels", {
|
|
401
|
+
body: JSON.parse(approval.requestJson),
|
|
402
|
+
headers: { "Idempotency-Key": approval.idempotencyKey }
|
|
403
|
+
});
|
|
404
|
+
if (!result.trackingNumber) throw new FlexOpsError("Unresolved purchase. Retain the operation and reconcile before creating another label.", 409, "OutcomeUnknown");
|
|
405
|
+
return result;
|
|
376
406
|
}
|
|
377
407
|
/** Cancel (void) a shipping label. `carrierCode` is required. */
|
|
378
408
|
async cancelLabel(labelId, carrierCode) {
|
|
@@ -469,7 +499,7 @@ var CarriersResource = class {
|
|
|
469
499
|
// Domestic USPS labels go through the reliable order-based Gateway path
|
|
470
500
|
// (POST /api/shipping/labels): pass a LabelRequest body with carrierCode:'USPS'
|
|
471
501
|
// and orderId set — server-side order validation + atomic postage settlement.
|
|
472
|
-
createDomesticLabel: (body) => this.http.
|
|
502
|
+
createDomesticLabel: (body) => new ShippingResource(this.http, () => void 0).createLabel(body),
|
|
473
503
|
/** Generate a domestic return label. */
|
|
474
504
|
createReturnLabel: (body) => this.http.post(this.proxy("api/v3/Shipping/postUspsGenerateDomesticReturnsShippingLabel"), body),
|
|
475
505
|
/** Generate an international shipping label. */
|
package/dist/index.mjs
CHANGED
|
@@ -111,7 +111,7 @@ var HttpClient = class {
|
|
|
111
111
|
const error = new FlexOpsError(
|
|
112
112
|
errorBody.message ?? `HTTP ${response.status}: ${response.statusText}`,
|
|
113
113
|
response.status,
|
|
114
|
-
|
|
114
|
+
errorBody.code ?? errorBody.errorCode,
|
|
115
115
|
errorBody.errors
|
|
116
116
|
);
|
|
117
117
|
if (this.retry.retryableStatusCodes.includes(response.status)) {
|
|
@@ -330,7 +330,37 @@ var ShippingResource = class {
|
|
|
330
330
|
* server-side and postage is settled atomically. Returns the raw label (HTTP 201).
|
|
331
331
|
*/
|
|
332
332
|
async createLabel(request) {
|
|
333
|
-
|
|
333
|
+
const result = await this.http.post("/api/shipping/labels", request);
|
|
334
|
+
if ("status" in result) throw new FlexOpsError("Approval required. Use prepareLabel, review its preview, then purchaseLabel.", 400, "ApprovalRequired");
|
|
335
|
+
return result;
|
|
336
|
+
}
|
|
337
|
+
/** Preview without approval. Keep the returned immutable operation for every purchase attempt. */
|
|
338
|
+
async prepareLabel(request, maximumPostageAmount, idempotencyKey) {
|
|
339
|
+
if (!idempotencyKey.trim() || !Number.isFinite(maximumPostageAmount) || maximumPostageAmount <= 0 || maximumPostageAmount > 1e6 || Math.abs(maximumPostageAmount * 100 - Math.round(maximumPostageAmount * 100)) > 1e-7)
|
|
340
|
+
throw new FlexOpsError("Supply a stable key and positive USD maximum with at most two decimal places.", 400, "InvalidApproval");
|
|
341
|
+
const body = JSON.parse(JSON.stringify(request));
|
|
342
|
+
for (const key of Object.keys(body)) if (["confirmationtoken", "maximumpostageamount"].includes(key.toLowerCase())) delete body[key];
|
|
343
|
+
body.maximumPostageAmount = maximumPostageAmount;
|
|
344
|
+
const result = await this.http.request("POST", "/api/shipping/labels", {
|
|
345
|
+
body,
|
|
346
|
+
headers: { "Idempotency-Key": idempotencyKey }
|
|
347
|
+
});
|
|
348
|
+
if ("isSandbox" in result && result.isSandbox === true)
|
|
349
|
+
return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: null, sandboxLabel: result });
|
|
350
|
+
if (!("status" in result) || result.status !== "Preview" || !result.confirmationToken || result.currency !== "USD" || !Number.isFinite(result.quotedPostageAmount) || result.quotedPostageAmount <= 0 || result.quotedPostageAmount > maximumPostageAmount || result.maximumPostageAmount !== maximumPostageAmount || !Number.isFinite(Date.parse(result.expiresAt)))
|
|
351
|
+
throw new FlexOpsError("Gateway did not return a valid bounded preview.", 502, "InvalidPreview");
|
|
352
|
+
body.confirmationToken = result.confirmationToken;
|
|
353
|
+
return Object.freeze({ idempotencyKey, requestJson: JSON.stringify(body), preview: Object.freeze(result) });
|
|
354
|
+
}
|
|
355
|
+
/** Call only after explicit approval. Same-key replay remains valid after token expiry. */
|
|
356
|
+
async purchaseLabel(approval) {
|
|
357
|
+
if (approval.sandboxLabel) return approval.sandboxLabel;
|
|
358
|
+
const result = await this.http.request("POST", "/api/shipping/labels", {
|
|
359
|
+
body: JSON.parse(approval.requestJson),
|
|
360
|
+
headers: { "Idempotency-Key": approval.idempotencyKey }
|
|
361
|
+
});
|
|
362
|
+
if (!result.trackingNumber) throw new FlexOpsError("Unresolved purchase. Retain the operation and reconcile before creating another label.", 409, "OutcomeUnknown");
|
|
363
|
+
return result;
|
|
334
364
|
}
|
|
335
365
|
/** Cancel (void) a shipping label. `carrierCode` is required. */
|
|
336
366
|
async cancelLabel(labelId, carrierCode) {
|
|
@@ -427,7 +457,7 @@ var CarriersResource = class {
|
|
|
427
457
|
// Domestic USPS labels go through the reliable order-based Gateway path
|
|
428
458
|
// (POST /api/shipping/labels): pass a LabelRequest body with carrierCode:'USPS'
|
|
429
459
|
// and orderId set — server-side order validation + atomic postage settlement.
|
|
430
|
-
createDomesticLabel: (body) => this.http.
|
|
460
|
+
createDomesticLabel: (body) => new ShippingResource(this.http, () => void 0).createLabel(body),
|
|
431
461
|
/** Generate a domestic return label. */
|
|
432
462
|
createReturnLabel: (body) => this.http.post(this.proxy("api/v3/Shipping/postUspsGenerateDomesticReturnsShippingLabel"), body),
|
|
433
463
|
/** Generate an international shipping label. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flexops/sdk",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Official FlexOps Platform Node.js/TypeScript SDK — multi-carrier shipping, order management, and logistics API",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -60,6 +60,6 @@
|
|
|
60
60
|
"tsup": "^8.4.0",
|
|
61
61
|
"typescript": "^5.8.0",
|
|
62
62
|
"typescript-eslint": "^8.65.0",
|
|
63
|
-
"vitest": "^
|
|
63
|
+
"vitest": "^5.0.0"
|
|
64
64
|
}
|
|
65
65
|
}
|