/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@easypost/api@8.8.0/dist/easypost.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";const g=require("os"),k=require("superagent"),P=require("util"),I=require("uuid"),x=require("crypto"),at="8.8.0",ct={version:at};class f extends Error{constructor({message:n}={}){super(n)}}class O extends f{}class N extends f{}class S extends f{}class ${getLowestSmartRate(n,t,e){const s=new Set(["percentile_50","percentile_75","percentile_85","percentile_90","percentile_95","percentile_97","percentile_99"]);let a=null;const c=e.toLowerCase();if(!s.has(c))throw new N({message:`Invalid deliveryAccuracy value, must be one of: ${new Array(...s).join(", ")}`});for(let i=0;i<n.length;i+=1){const o=n[i];o.time_in_transit[c]>parseInt(t,10)||(a===null||parseFloat(o.rate)<parseFloat(a.rate))&&(a=o)}if(a===null)throw new O({message:P.format(h.NO_OBJECT_FOUND,"rates")});return a}getLowestRate(n,t=null,e=null){if(t){const s=t.map(a=>a.toLowerCase());n=n.filter(a=>s.includes(a.carrier.toLowerCase()))}if(e){const s=e.map(a=>a.toLowerCase());n=n.filter(a=>s.includes(a.service.toLowerCase()))}if(n.length===0)throw new O({message:P.format(h.NO_OBJECT_FOUND,"rates")});return n.reduce((s,a)=>parseFloat(a.rate)<parseFloat(s.rate)?a:s,n[0])}validateWebhook(n,t,e){var c,i;let s={};const a=(i=(c=t["X-Hmac-Signature"])!=null?c:t["x-hmac-signature"])!=null?i:null;if(a!=null){const o=e.normalize("NFKD"),l=Buffer.from(o,"utf8"),p=Buffer.from(n).toString("utf8").replace(/("weight":\s*)(\d+)(\s*)(?=,|\})/g,"$1$2.0"),v=`hmac-sha256-hex=${x.createHmac("sha256",l).update(p,"utf-8").digest("hex")}`;try{if(x.timingSafeEqual(Buffer.from(a,"utf8"),Buffer.from(v,"utf8")))s=JSON.parse(p);else throw new S({message:h.WEBHOOK_DOES_NOT_MATCH})}catch{throw new S({message:h.WEBHOOK_DOES_NOT_MATCH})}}else throw new S({message:h.INVALID_WEBHOOK_SIGNATURE});return s}}class h{static get CARRIER_ACCOUNTS_WITH_CUSTOM_CREATE_WORKFLOWS(){return["FedexAccount","FedexSmartpostAccount"]}static get CARRIER_ACCOUNT_TYPES_WITH_CUSTOM_OAUTH(){return["AmazonShippingAccount","UpsAccount","UpsMailInnovationsAccount","UpsSurepostAccount","UspsShipAccount"]}static EXTERNAL_API_CALL_FAILED="Communication with %s failed, please try again later";static INVALID_API_KEY_TYPE="Invalid API key type.";static INVALID_PARAMETER="Invalid parameter: %s.";static INVALID_PAYMENT="The chosen payment method is not a credit card. Please try again.";static INVALID_WEBHOOK_SIGNATURE="Webhook does not contain a valid HMAC signature.";static MISSING_REQUIRED_PARAMETER="Missing required parameter: %s.";static NO_OBJECT_FOUND="No %s found.";static NO_PAYMENT_METHODS="No payment methods are set up. Please add a payment method and try again.";static API_DID_NOT_RETURN_ERROR_DETAILS="API did not return error details.";static WEBHOOK_DOES_NOT_MATCH="Webhook received did not originate from EasyPost or had a webhook secret mismatch.";static END_OF_PAGINATION="There are no more pages to retrieve.";static ERROR_DESERIALIZATION="Error deserializing JSON response";static Utils=new $}class y extends f{constructor({message:n,code:t,statusCode:e,errors:s}={}){super({message:n}),this.code=t,this.errors=s,this.message=n,this.statusCode=e}}class nt extends y{}class it extends y{}class ot extends y{}class ut extends y{}class dt extends y{}class lt extends y{}class _t extends y{}class pt extends y{}class ht extends y{}class yt extends y{}class mt extends y{}class vt extends y{}class ft extends y{}class bt extends y{}class Pt{static traverseJsonElement(n,t){if(n instanceof Object)for(const e of Object.values(n))this.traverseJsonElement(e,t);else if(n instanceof Array)for(const e of n)this.traverseJsonElement(e,t);else t.push(n.toString())}static handleApiError(n){const{statusCode:t}=n,{code:e,message:s,errors:a}=n.body.error,c={message:s,code:e,statusCode:t,errors:a};try{const i=[];this.traverseJsonElement(c.message,i),c.message=i.join(", ")}catch{const o={message:h.ERROR_DESERIALIZATION,code:"ERROR_DESERIALIZATION_ERROR"};return new f(o)}if(t>=300&&t<400)return new yt(c);switch(t){case 400:return new nt(c);case 401:return new ft(c);case 402:return new pt(c);case 403:return new it(c);case 404:return new _t(c);case 405:return new lt(c);case 408:return new vt(c);case 422:return new dt(c);case 429:return new ht(c);case 500:return new ut(c);case 503:return new mt(c);case 504:return new ot(c);default:return new bt(c)}}}class wt extends f{}class d{static id;static object;static mode;static created_at;static updated_at;static _params}class D extends d{static street1;static street2;static city;static state;static zip;static country;static residential;static carrier_facility;static name;static company;static phone;static email;static federal_tax_id;static state_tax_id;static verifications}class H extends d{static active;static key}class M extends d{static label_url;static num_shipments;static pickup;static reference;static scan_form;static shipments;static state;static status}class U extends d{static ad_href;static ad;static background_color;static color;static logo_href;static logo;static name;static theme;static user_id}class L extends d{static billing_type;static clone;static credentials;static description;static fields;static readable;static reference;static test_credentials}class Et extends d{static fields;static type}class gt extends d{static id;static object;static mode;static attachments;static contact_email;static created_at;static description;static history;static insurance_amount;static insurance_id;static payment_method;static recipient_name;static reference;static requested_amount;static shipment_id;static status_detail;static status_timestamp;static status;static tracking_code;static type;static updated_at}class F extends d{static content_explanation;static contents_type;static customs_certify;static customs_items;static customs_signer;static declaration;static eel_pfc;static non_delivery_option;static restriction_comments;static restriction_type}class B extends d{static code;static currency;static description;static hs_tariff_number;static origin_country;static quantity;static value;static weight}class q extends d{static street1;static street2;static city;static state;static zip;static country;static name;static company;static phone;static email}class C extends d{static completed_urls;static description;static pending_urls;static previous_attributes;static result;static status}class St extends d{static form_type;static form_url;static submitted_electronically}class V extends d{static amount;static fee;static from_address;static messages;static provider_id;static provider;static reference;static shipment_id;static status;static to_address;static tracking_code;static tracker}class W extends d{static buyer_address;static from_address;static is_return;static messages;static rates;static reference;static return_address;static shipments;static to_address;lowestRate(n,t){const e=this.rates||[];return h.Utils.getLowestRate(e,n,t)}}class K extends d{static height;static length;static predefined_package;static weight;static width}class z extends d{static response_body}class G extends d{static address;static carrier_accounts;static confirmation;static instructions;static is_account_address;static max_datetime;static messages;static min_datetime;static pickup_rates;static reference;static shipment;static status;lowestRate(n,t){const e=this.pickup_rates||[];return h.Utils.getLowestRate(e,n,t)}}class J extends d{static carrier;static currency;static pickup_id;static rate;static service}class Y extends d{static label_date;static label_epl2_url;static label_file_type;static label_pdf_url;static label_resolution;static label_size;static label_type;static label_url;static label_zpl_url}class X extends d{static billing_type;static carrier_account_id;static carrier;static currency;static delivery_date_guaranteed;static delivery_date;static delivery_days;static est_delivery_days;static list_currency;static list_rate;static rate;static retail_currency;static retail_rate;static service;static shipment_id}class Q extends d{static carrier;static confirmation_number;static shipment_id;static status;static tracking_code}class b extends d{static end_date;static include_children;static send_email;static start_date;static status;static url_expires_at;static url}class Z extends d{static address;static batch_id;static form_file_type;static form_url;static message;static status;static tracking_codes}class tt extends d{static batch_id;static batch_message;static batch_status;static buyer_address;static customs_info;static fees;static forms;static from_address;static insurance;static is_return;static messages;static options;static parcel;static postage_label;static rates;static reference;static refund_status;static return_address;static scan_form;static selected_rate;static status;static to_address;static tracker;static tracking_code;static usps_zone;lowestRate(n,t){const e=this.rates||[];return h.Utils.getLowestRate(e,n,t)}}class et extends d{static carrier_detail;static carrier;static est_delivery_date;static fees;static finalized;static is_return;static public_url;static shipment_id;static signed_by;static status_detail;static status;static tracking_code;static tracking_details;static weight}class st extends d{static api_keys;static balance;static cc_fee_rate;static children;static email;static insurance_fee_minimum;static insurance_fee_rate;static name;static parent_id;static phone_number;static price_per_shipment;static recharge_amount;static secondary_recharge_amount}class rt extends d{static disabled_at;static url}class w extends f{constructor(){super({message:h.END_OF_PAGINATION})}}const A={adr:D,ak:H,batch:M,brd:U,ca:L,cfrep:b,clm:gt,cstinfo:F,cstitem:B,es:q,evt:C,hook:rt,ins:V,order:W,payload:z,pickup:G,pickuprate:J,pl:Y,plrep:b,prcl:K,rate:X,refrep:b,rfnd:Q,sf:Z,shp:tt,shpinvrep:b,shprep:b,trk:et,trkrep:b,user:st},R={Address:D,ApiKey:H,Batch:M,Brand:U,CarrierAccount:L,CarrierType:Et,CustomsInfo:F,CustomsItem:B,EasyPostObject:d,EndShipper:q,Event:C,Form:St,Insurance:V,Order:W,Parcel:K,Payload:z,Pickup:G,PickupRate:J,PostageLabel:Y,Rate:X,Refund:Q,Report:b,ScanForm:Z,Shipment:tt,Tracker:et,User:st,Webhook:rt},u=r=>class{static _convertToEasyPostObject(t,e){if(Array.isArray(t))return t.map(s=>typeof s=="object"?this._convertToEasyPostObject(s,e):s);if(typeof t=="object"&&t!==null){let s;if(R[t.object]!==void 0)s=new R[t.object];else if(t.id!==void 0&&A[t.id.substr(0,t.id.indexOf("_"))]!==void 0){const a=t.id.substr(0,t.id.indexOf("_"));s=new A[a]}else s=new d;return Object.keys(t).forEach(a=>{s[a]=this._convertToEasyPostObject(t[a],e)}),s._params=e,s}return t}static async _create(t,e){try{const s=await r._post(t,e);return this._convertToEasyPostObject(s.body,e)}catch(s){return Promise.reject(s)}}static async _all(t,e={}){try{const s=await r._get(t,e);return this._convertToEasyPostObject(s.body,e)}catch(s){return Promise.reject(s)}}static async _retrieve(t){try{const e=await r._get(t);return this._convertToEasyPostObject(e.body)}catch(e){return Promise.reject(e)}}static async _getNextPage(t,e,s,a=null,c={}){var m,v,E;const i=s[e];if(i==null||i.length==0||!s.has_more)throw new w;const o=(v=(m=s._params)!=null?m:i[0]._params)!=null?v:{},l={...o,page_size:(E=o.page_size)!=null?E:a,before_id:i[i.length-1].id,...c},p=await this._all(t,l);if(p==null||p[e].length==0)throw new w;return p}},Tt=r=>class extends u(r){static async create(t){const e="addresses",s={};return t.verify&&(s.verify=t.verify,delete t.verify),t.verify_strict&&(s.verify_strict=t.verify_strict,delete t.verify_strict),t.verify_carrier&&(s.verify_carrier=t.verify_carrier,delete t.verify_carrier),s.address=t,this._create(e,s)}static async createAndVerify(t){const e="addresses/create_and_verify",s={};t.verify_carrier&&(s.verify_carrier=t.verify_carrier,delete t.verify_carrier),s.address=t;try{const a=await r._post(e,s);return this._convertToEasyPostObject(a.body.address,s)}catch(a){return Promise.reject(a)}}static async all(t={}){return this._all("addresses",t)}static async getNextPage(t,e=null){return this._getNextPage("addresses","addresses",t,e)}static async retrieve(t){const e=`addresses/${t}`;return this._retrieve(e)}static async verifyAddress(t){try{const e=`addresses/${t}/verify`,s=await r._get(e);return this._convertToEasyPostObject(s.body.address)}catch(e){return Promise.reject(e)}}},Ot=r=>class extends u(r){static async retrieveApiKeysForUser(t){const e="api_keys";try{const s=await r._get(e),a=this._convertToEasyPostObject(s.body);if(a.id==t)return a.keys;a.children.forEach(c=>{if(c.id==t)return c.keys})}catch(s){return Promise.reject(s)}throw new O({message:P.format(h.NO_OBJECT_FOUND,"child")})}static async all(t={}){return this._all("api_keys",t)}static async create(t){const e="api_keys",s={mode:t};return this._create(e,s)}static async delete(t){const e=`api_keys/${t}`;try{return await r._delete(e),Promise.resolve()}catch(s){return Promise.reject(s)}}static async enable(t){const e=`api_keys/${t}/enable`;try{const s=await r._post(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async disable(t){const e=`api_keys/${t}/disable`;try{const s=await r._post(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}},jt="pdf",xt=r=>class extends u(r){static async create(t){const e="batches",s={batch:t};return this._create(e,s)}static async addShipments(t,e){const s=`batches/${t}/add_shipments`,a={shipments:e.map(c=>({id:c}))};try{const c=await r._post(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async removeShipments(t,e){const s=`batches/${t}/remove_shipments`,a={shipments:e.map(c=>({id:c}))};try{const c=await r._post(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async generateLabel(t,e=jt){const s=`batches/${t}/label`,a={file_format:e};try{const c=await r._post(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async createScanForm(t){const e=`batches/${t}/scan_form`;try{const s=await r._post(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async buy(t){const e=`batches/${t}/buy`;try{const s=await r._post(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async all(t={}){return this._all("batches",t)}static async retrieve(t){const e=`batches/${t}`;return this._retrieve(e)}},At=r=>class extends u(r){static async retrieveStatelessRates(t){const e="beta/rates",s={shipment:t};try{const a=await r._post(e,s);return this._convertToEasyPostObject(a.body.rates,s)}catch(a){return Promise.reject(a)}}},Rt=r=>class extends u(r){static async addPaymentMethod(t,e,s="primary"){const a={payment_method:{stripe_customer_id:t,payment_method_reference:e,priority:s}};return(await r._post("beta/referral_customers/payment_method",a)).body}static async refundByAmount(t){const e={refund_amount:t};return(await r._post("beta/referral_customers/refunds",e)).body}static async refundByPaymentLog(t){const e={payment_log_id:t};return(await r._post("beta/referral_customers/refunds",e)).body}static async createCreditCardClientSecret(){return(await r._post("beta/setup_intents",null)).body}static async createBankAccountClientSecret(t){const e=t?{return_url:t}:null;return(await r._post("beta/financial_connections_sessions",e)).body}};class T extends f{}const kt=r=>class extends u(r){static async fundWallet(t,e="primary"){const s=await this._getPaymentInfo(e.toLowerCase()),a=s[0],c=s[1],i=`${a}/${c}/charges`,o={amount:t};await r._post(i,o)}static async deletePaymentMethod(t){const e=await this._getPaymentInfo(t.toLowerCase()),s=e[0],a=e[1],c=`${s}/${a}`;await r._delete(c)}static async retrievePaymentMethods(){const e=await r._get("payment_methods");if(e.body.id===null)throw new T({message:h.NO_PAYMENT_METHODS});return e.body}static async _getPaymentInfo(t){const e=await this.retrievePaymentMethods(),a={primary:"primary_payment_method",secondary:"secondary_payment_method"}[t];let c,i,o;const l="The chosen payment method is not valid. Please try again.";if(a!==void 0&&e[a]!==null)if(c=e[a].id,i=e[a].object,i==="CreditCard")o="credit_cards";else if(i==="BankAccount")o="bank_accounts";else throw new T({message:l});else throw new T({message:l});return[o,c]}},It=r=>class extends u(r){static async create(t){const e=t.type;if(!e)throw new N({message:P.format(h.MISSING_REQUIRED_PARAMETER,"CarrierAccount type")});const s=this._selectCarrierAccountCreationEndpoint(e),a=this._wrapCarrierAccountParams(e,t);return this._create(s,a)}static async update(t,e){const s={carrier_account:e};try{const a=await r._patch(`carrier_accounts/${t}`,s);return this._convertToEasyPostObject(a.body,s)}catch(a){return Promise.reject(a)}}static async delete(t){const e=`carrier_accounts/${t}`;try{return await r._delete(e),Promise.resolve()}catch(s){return Promise.reject(s)}}static _selectCarrierAccountCreationEndpoint(t){return h.CARRIER_ACCOUNTS_WITH_CUSTOM_CREATE_WORKFLOWS.includes(t)?"carrier_accounts/register":h.CARRIER_ACCOUNT_TYPES_WITH_CUSTOM_OAUTH.includes(t)?"carrier_accounts/register_oauth":"carrier_accounts"}static _wrapCarrierAccountParams(t,e){return h.CARRIER_ACCOUNT_TYPES_WITH_CUSTOM_OAUTH.includes(t)?{carrier_account_oauth_registrations:e}:{carrier_account:e}}static async all(t={}){return this._all("carrier_accounts",t)}static async retrieve(t){const e=`carrier_accounts/${t}`;return this._retrieve(e)}},Nt=r=>class extends u(r){static async retrieve(t=null,e=null){const s="metadata/carriers",a={...t&&t.length>0&&{carriers:t.join(",")},...e&&e.length>0&&{types:e.join(",")}};try{const c=await r._get(s,a);return this._convertToEasyPostObject(c.body.carriers||[],a)}catch(c){return Promise.reject(c)}}},$t=r=>class extends u(r){static async all(t={}){const e="carrier_types";try{const s=await r._get(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}},Dt=r=>class extends u(r){static async create(t){return this._create("claims",t)}static async all(t={}){return this._all("claims",t)}static async getNextPage(t,e=null){return this._getNextPage("claims","claims",t,e)}static async retrieve(t){const e=`claims/${t}`;return this._retrieve(e)}static async cancel(t){const e=`claims/${t}/cancel`;return this._create(e)}},Ht=r=>class extends u(r){static async createAccountLink(t={}){const e="customer_portal/account_link";try{const s=await r._post(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}},Mt=r=>class extends u(r){static async create(t){const e="customs_infos",s={customs_info:t};return this._create(e,s)}static async retrieve(t){const e=`customs_infos/${t}`;return this._retrieve(e)}},Ut=r=>class extends u(r){static async create(t){const e="customs_items",s={customs_item:t};return this._create(e,s)}static async retrieve(t){const e=`customs_items/${t}`;return this._retrieve(e)}},Lt=r=>class extends u(r){static async createSession(t={}){const e="embeddables/session";try{const s=await r._post(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}},Ft=r=>class extends u(r){static async create(t){const e="end_shippers",s={address:t};return this._create(e,s)}static async update(t,e){const s=`end_shippers/${t}`,a={address:e};try{const c=await r._put(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async retrieve(t){const e=`end_shippers/${t}`;return this._retrieve(e)}static async all(t={}){return this._all("end_shippers",t)}},Bt=r=>class extends u(r){static async retrieveAllPayloads(t){const e=`events/${t}/payloads`;try{const s=await r._get(e);return this._convertToEasyPostObject(s.body.payloads)}catch(s){return Promise.reject(s)}}static async retrievePayload(t,e){const s=`events/${t}/payloads/${e}`;try{const a=await r._get(s);return this._convertToEasyPostObject(a.body)}catch(a){return Promise.reject(a)}}static async all(t={}){return this._all("events",t)}static async getNextPage(t,e=null){return this._getNextPage("events","events",t,e)}static async retrieve(t){const e=`events/${t}`;return this._retrieve(e)}},qt=r=>class extends u(r){static async registerAddress(t,e){const s=this._wrapAddressValidation(e),a=`fedex_registrations/${t}/address`;try{const c=await r._post(a,s);return this._convertToEasyPostObject(c.body,e)}catch(c){return Promise.reject(c)}}static async requestPin(t,e){const s={pin_method:{option:e}},a=`fedex_registrations/${t}/pin`;try{const c=await r._post(a,s);return this._convertToEasyPostObject(c.body,s)}catch(c){return Promise.reject(c)}}static async validatePin(t,e){const s=this._wrapPinValidation(e),a=`fedex_registrations/${t}/pin/validate`;try{const c=await r._post(a,s);return this._convertToEasyPostObject(c.body,e)}catch(c){return Promise.reject(c)}}static async submitInvoice(t,e){const s=this._wrapInvoiceValidation(e),a=`fedex_registrations/${t}/invoice`;try{const c=await r._post(a,s);return this._convertToEasyPostObject(c.body,e)}catch(c){return Promise.reject(c)}}static _wrapAddressValidation(t){const e={};if(t.address_validation){const s={...t.address_validation};this._ensureNameField(s),e.address_validation=s}return t.easypost_details&&(e.easypost_details=t.easypost_details),e}static _wrapPinValidation(t){const e={};if(t.pin_validation){const s={...t.pin_validation};this._ensureNameField(s),e.pin_validation=s}return t.easypost_details&&(e.easypost_details=t.easypost_details),e}static _wrapInvoiceValidation(t){const e={};if(t.invoice_validation){const s={...t.invoice_validation};this._ensureNameField(s),e.invoice_validation=s}return t.easypost_details&&(e.easypost_details=t.easypost_details),e}static _ensureNameField(t){if(!t.name||t.name===null){const e=I.v4().replace(/-/g,"");t.name=e}}},Ct=r=>class extends u(r){static async create(t){const e="insurances",s={insurance:t};return this._create(e,s)}static async all(t={}){return this._all("insurances",t)}static async getNextPage(t,e=null){return this._getNextPage("insurances","insurances",t,e)}static async retrieve(t){const e=`insurances/${t}`;return this._retrieve(e)}static async refund(t){const e=`insurances/${t}/refund`,s=await r._post(e);return this._convertToEasyPostObject(s.body)}},Vt=r=>class extends u(r){static async getPromise(t){const e="luma/promise",s={shipment:t};try{const a=await r._post(e,s);return this._convertToEasyPostObject(a.body.luma_info,s)}catch(a){return Promise.reject(a)}}},Wt=r=>class extends u(r){static async create(t){const e="orders",s={order:t};return this._create(e,s)}static async buy(t,e,s){const a=`orders/${t}/buy`,c={carrier:e,service:s};try{const i=await r._post(a,c);return this._convertToEasyPostObject(i.body,c)}catch(i){return Promise.reject(i)}}static async getRates(t){const e=`orders/${t}/rates`;try{const s=await r._get(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async retrieve(t){const e=`orders/${t}`;return this._retrieve(e)}},Kt=r=>class extends u(r){static async create(t){const e="parcels",s={parcel:t};return this._create(e,s)}static async retrieve(t){const e=`parcels/${t}`;return this._retrieve(e)}},zt=r=>class extends u(r){static async create(t){const e="pickups",s={pickup:t};return this._create(e,s)}static async buy(t,e,s){const a=`pickups/${t}/buy`,c={carrier:e,service:s};try{const i=await r._post(a,c);return this._convertToEasyPostObject(i.body,c)}catch(i){return Promise.reject(i)}}static async cancel(t){const e=`pickups/${t}/cancel`;try{const s=await r._post(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async all(t={}){return this._all("pickups",t)}static async getNextPage(t,e=null){return this._getNextPage("pickups","pickups",t,e)}static async retrieve(t){const e=`pickups/${t}`;return this._retrieve(e)}},Gt=r=>class extends u(r){static async retrieve(t){const e=`rates/${t}`;return this._retrieve(e)}};class Jt extends y{}function j(r,n){return _.copyClient(r,{apiKey:n})}async function Yt(r){return(await r._get("partners/stripe_public_key")).body.public_key}async function Xt(r,n,t,e,s){const a=`https://api.stripe.com/v1/tokens?card[number]=${n}&card[exp_month]=${t}&card[exp_year]=${e}&card[cvc]=${s}`,c=k.post(a).set({Authorization:`Bearer ${r}`,"Content-Type":"application/x-www-form-urlencoded"});try{return(await c).body.id}catch{throw new Jt({message:P.format(h.EXTERNAL_API_CALL_FAILED,"Stripe")})}}async function Qt(r,n,t,e){const s=j(r,n),a="credit_cards",c={credit_card:{stripe_object_id:t,priority:e}};return(await s._post(a,c)).body}const Zt=r=>class extends u(r){static async create(t){const e="referral_customers",s={user:t};return this._create(e,s)}static async updateEmail(t,e){const s=`referral_customers/${t}`,a={user:{email:e}};return await r._put(s,a),!0}static async addCreditCard(t,e,s,a,c,i="primary"){const o=await Yt(r),l=await Xt(o,e,s,a,c);return await Qt(r,t,l,i)}static async addCreditCardFromStripe(t,e,s="primary"){const a=j(r,t),c={credit_card:{payment_method_id:e,priority:s}},o=await a._post("credit_cards",c);return this._convertToEasyPostObject(o.body,c)}static async addBankAccountFromStripe(t,e,s,a="primary"){const c=j(r,t),i={financial_connections_id:e,mandate_data:s,priority:a},l=await c._post("bank_accounts",i);return this._convertToEasyPostObject(l.body,i)}static async all(t={}){return this._all("referral_customers",t)}static async getNextPage(t,e=null){return this._getNextPage("referral_customers","referral_customers",t,e)}},te=r=>class extends u(r){static async create(t){const e="refunds",s={refund:t};return this._create(e,s)}static async all(t={}){return this._all("refunds",t)}static async getNextPage(t,e=null){return this._getNextPage("refunds","refunds",t,e)}static async retrieve(t){const e=`refunds/${t}`;return this._retrieve(e)}},ee=r=>class extends u(r){static async create(t){const e=`reports/${t.type}`;return this._create(e,t)}static async all(t={}){const e=t.type,s=`reports/${e}`;delete t.type;try{const a=await r._get(s,t);return this._convertToEasyPostObject(a.body,{...t,type:e})}catch(a){return Promise.reject(a)}}static async getNextPage(t,e=null){const s=`reports/${t.reports[0]._params.type}`;return this._getNextPage(s,"reports",t,e)}static async retrieve(t){const e=`reports/${t}`;return this._retrieve(e)}},se=r=>class extends u(r){static async create(t){const e="scan_forms";t.shipments&&(t.shipments=t.shipments.map(a=>typeof a=="string"?{id:a}:{id:a.id}));const s={scan_form:t};return this._create(e,s)}static async all(t={}){return this._all("scan_forms",t)}static async getNextPage(t,e=null){return this._getNextPage("scan_forms","scan_forms",t,e)}static async retrieve(t){const e=`scan_forms/${t}`;return this._retrieve(e)}},re=r=>class extends u(r){static async create(t){const e="shipments",s={shipment:t};return this._create(e,s)}static async buy(t,e,s=null,a=null){let c=e;typeof e=="object"&&(c=e.id);const i=`shipments/${t}/buy`,o={rate:{id:c}};s&&(o.insurance=s),a&&(o.end_shipper_id=a);try{const l=await r._post(i,o);return this._convertToEasyPostObject(l.body,o)}catch(l){return Promise.reject(l)}}static async convertLabelFormat(t,e){const s=`shipments/${t}/label`,a={file_format:e};try{const c=await r._get(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async regenerateRates(t){const e=`shipments/${t}/rerate`,s={};try{const a=await r._post(e,s);return this._convertToEasyPostObject(a.body,s)}catch(a){return Promise.reject(a)}}static async getSmartRates(t){const e=`shipments/${t}/smartrate`;try{const s=await r._get(e);return this._convertToEasyPostObject(s.body.result)}catch(s){return Promise.reject(s)}}static async insure(t,e){const s=`shipments/${t}/insure`,a={amount:e};try{const c=await r._post(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async generateForm(t,e,s={}){const a=`shipments/${t}/forms`,c={form:{...s,type:e}};try{const i=await r._post(a,c);return this._convertToEasyPostObject(i.body,c)}catch(i){return Promise.reject(i)}}static async refund(t){const e=`shipments/${t}/refund`;try{const s=await r._post(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async lowestSmartRate(t,e,s){const a=await this.getSmartRates(t);return h.Utils.getLowestSmartRate(a,e,s.toLowerCase())}static async all(t={}){return this._all("shipments",t)}static async getNextPage(t,e=null){return this._getNextPage("shipments","shipments",t,e)}static async retrieve(t){const e=`shipments/${t}`;return this._retrieve(e)}static async retrieveEstimatedDeliveryDate(t,e){var c;const s=`shipments/${t}/smartrate/delivery_date`,a={planned_ship_date:e};try{const i=await r._get(s,a);return this._convertToEasyPostObject((c=i.body.rates)!=null?c:[],a)}catch(i){return Promise.reject(i)}}static async recommendShipDate(t,e){var c;const s=`shipments/${t}/smartrate/precision_shipping`,a={desired_delivery_date:e};try{const i=await r._get(s,a);return this._convertToEasyPostObject((c=i.body.rates)!=null?c:[],a)}catch(i){return Promise.reject(i)}}static async createAndBuyLuma(t){const e="shipments/luma",s={shipment:t};try{const a=await r._post(e,s);return this._convertToEasyPostObject(a.body,s)}catch(a){return Promise.reject(a)}}static async buyLuma(t,e){const s=`shipments/${t}/luma`;try{const a=await r._post(s,e);return this._convertToEasyPostObject(a.body,e)}catch(a){return Promise.reject(a)}}},ae=r=>class extends u(r){static async estimateDeliveryDate(t){const e="smartrate/deliver_by";try{const s=await r._post(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}static async recommendShipDate(t){const e="smartrate/deliver_on";try{const s=await r._post(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}},ce=r=>class extends u(r){static async create(t){const e="trackers",s={tracker:t};return this._create(e,s)}static async all(t={}){return this._all("trackers",t)}static async getNextPage(t,e=null){return this._getNextPage("trackers","trackers",t,e)}static async retrieve(t){const e=`trackers/${t}`;return this._retrieve(e)}static async retrieveBatch(t={}){const e="trackers/batch";try{const s=await r._post(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}static async delete(t){const e=`trackers/${t}`;try{return await r._delete(e),Promise.resolve()}catch(s){return Promise.reject(s)}}},ne=r=>class extends u(r){static async create(t){const e="users",s={user:t};return this._create(e,s)}static async update(t,e){const s=`users/${t}`,a={user:e};try{const c=await r._patch(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async retrieve(t){const e=`users/${t}`;try{const s=await r._get(e);return this._convertToEasyPostObject(s.body)}catch(s){return Promise.reject(s)}}static async retrieveMe(){const t="users";try{const e=await r._get(t);return this._convertToEasyPostObject(e.body)}catch(e){return Promise.reject(e)}}static async delete(t){const e=`users/${t}`;try{return await r._delete(e),Promise.resolve()}catch(s){return Promise.reject(s)}}static async updateBrand(t,e){const s=`users/${t}/brand`,a={brand:e};try{const c=await r._patch(s,a);return this._convertToEasyPostObject(c.body,a)}catch(c){return Promise.reject(c)}}static async allChildren(t){const e="users/children";try{const s=await r._get(e,t);return this._convertToEasyPostObject(s.body,t)}catch(s){return Promise.reject(s)}}static async getNextPage(t,e=null){return this._getNextPage("users/children","children",t,e)}static async _getNextPage(t,e,s,a=null){var p,m,v;const c=s[e];if(c==null||c.length==0||!s.has_more)throw new w;const i=(m=(p=s._params)!=null?p:c[0]._params)!=null?m:{},o={...i,page_size:(v=i.page_size)!=null?v:a,after_id:c[c.length-1].id},l=await this._all(t,o);if(l==null||l[e].length==0)throw new w;return l}},ie=r=>class extends u(r){static async create(t){const e="webhooks",s={webhook:t};return this._create(e,s)}static async update(t,e){const s=`webhooks/${t}`;try{const a=await r._patch(s,e);return this._convertToEasyPostObject(a.body,e)}catch(a){return Promise.reject(a)}}static async delete(t){const e=`webhooks/${t}`;try{return await r._delete(e),Promise.resolve()}catch(s){return Promise.reject(s)}}static async all(t={}){return this._all("webhooks",t)}static async retrieve(t){const e=`webhooks/${t}`;return this._retrieve(e)}};class _{constructor(n,t={}){const{useProxy:e,timeout:s,baseUrl:a,superagentMiddleware:c,requestMiddleware:i}=t;if(!n&&!e)throw new wt({message:P.format(h.MISSING_REQUIRED_PARAMETER,"API Key")});this.key=n,this.timeout=s||_.DEFAULT_TIMEOUT,this.baseUrl=a||_.DEFAULT_BASE_URL,this.agent=k,this.requestMiddleware=i,this.requestHooks=[],this.responseHooks=[],this.Utils=new $,c&&(this.agent=c(this.agent)),this._attachServices(_.SERVICES)}addRequestHook(n){this.requestHooks=[...this.requestHooks,n]}removeRequestHook(n){this.requestHooks=this.requestHooks.filter(t=>t!==n)}clearRequestHooks(){this.requestHooks=[]}addResponseHook(n){this.responseHooks=[...this.responseHooks,n]}removeResponseHook(n){this.responseHooks=this.responseHooks.filter(t=>t!==n)}clearResponseHooks(){this.responseHooks=[]}async makeApiCall(n,t,e={}){return(await this._request(t,n,e)).body}static copyClient(n,t={}){const{apiKey:e,useProxy:s,timeout:a,baseUrl:c,superagentMiddleware:i,requestMiddleware:o}=t,l=i?i(n.agent):n.agent;return new _(e||n.key,{useProxy:s||n.useProxy,timeout:a||n.timeout,baseUrl:c||n.baseUrl,agent:l,requestMiddleware:o||n.requestMiddleware})}static _buildHeaders(n={}){return{..._.DEFAULT_HEADERS,...n}}_attachServices(n){Object.keys(n).forEach(t=>{this[t]=n[t](this)})}_buildPath(n=""){if(n.indexOf("http")===0)return n;let t=this.baseUrl+n;return t=n.includes("beta")?t.replace("/v2",""):t,t}_createResponseHooksValue(n,t){return{...n,httpStatus:t.status,responseBody:t.body,headers:t.headers,responseTimestamp:Date.now()}}async _request(n="",t=_.METHODS.GET,e={},s={}){const a=this._buildPath(n),c=_._buildHeaders(s);let i=this.agent[t](a).set(c);this.requestMiddleware&&(i=this.requestMiddleware(i)),this.key&&i.auth(this.key);const o=new URL(a);e!==void 0&&(t===_.METHODS.GET||t===_.METHODS.DELETE?(i.query(e),Object.entries(e).forEach(([p,m])=>{o.searchParams.append(p,m)})):i.send(e));const l={method:t,path:o.toString(),requestBody:i._data,headers:c,requestTimestamp:Date.now(),requestUUID:I.v4()};this.requestHooks.forEach(p=>p(l));try{const p=await i;if(this.responseHooks.length>0){const m=this._createResponseHooksValue(l,p);this.responseHooks.forEach(v=>v(m))}return p}catch(p){if(p.response&&p.response.body){const m=this._createResponseHooksValue(l,p.response);throw this.responseHooks.forEach(v=>v(m)),Pt.handleApiError(p.response)}else throw p}}_get(n,t={},e={}){return this._request(n,_.METHODS.GET,t,e)}_post(n,t={},e={}){return this._request(n,_.METHODS.POST,t,e)}_put(n,t={},e={}){return this._request(n,_.METHODS.PUT,t,e)}_patch(n,t={},e={}){return this._request(n,_.METHODS.PATCH,t,e)}_delete(n,t={},e={}){return this._request(n,_.METHODS.DELETE,t,e)}}_.MS_SECOND=1e3;_.DEFAULT_TIMEOUT=60*_.MS_SECOND;_.DEFAULT_BASE_URL="https://api.easypost.com/v2/";_.DEFAULT_HEADERS={Accept:"application/json","Content-Type":"application/json","User-Agent":`EasyPost/v2 NodejsClient/${ct.version} Nodejs/${process.versions.node} OS/${g.platform()} OSVersion/${g.release()} OSArch/${g.arch()}`};_.METHODS={GET:"get",POST:"post",PUT:"put",PATCH:"patch",DELETE:"del"};_.SERVICES={Address:Tt,ApiKey:Ot,Batch:xt,BetaRate:At,BetaReferralCustomer:Rt,Billing:kt,CarrierAccount:It,CarrierMetadata:Nt,CarrierType:$t,Claim:Dt,CustomerPortal:Ht,CustomsInfo:Mt,CustomsItem:Ut,Embeddable:Lt,EndShipper:Ft,Event:Bt,FedExRegistration:qt,Insurance:Ct,Luma:Vt,Order:Wt,Parcel:Kt,Pickup:zt,Rate:Gt,ReferralCustomer:Zt,Refund:te,Report:ee,ScanForm:se,Shipment:re,SmartRate:ae,Tracker:ce,User:ne,Webhook:ie};module.exports=_;
