@myparcel/sdk
Version:
JavaScript SDK to connect to the MyParcel API via Node.js or browser
659 lines (658 loc) • 16.7 kB
JavaScript
var T = Object.defineProperty;
var O = (s, t, r) => t in s ? T(s, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : s[t] = r;
var e = (s, t, r) => O(s, typeof t != "symbol" ? t + "" : t, r);
import { isOfType as u } from "@myparcel/ts-utils";
class P {
constructor() {
e(this, "fns");
this.fns = [];
}
delete(t) {
const r = this.fns.indexOf(t);
r !== -1 && (this.fns = [...this.fns.slice(0, r), ...this.fns.slice(r + 1)]);
}
use(t) {
this.fns = [...this.fns, t];
}
}
class h extends Error {
constructor(r) {
super(r);
e(this, "name", "user");
Object.setPrototypeOf(this, h.prototype), this.name = "UserException";
}
}
class y extends Error {
constructor(r) {
super(r.message);
e(this, "data");
Object.setPrototypeOf(this, y.prototype), this.name = "ApiException", this.data = r;
}
}
const _ = (s, t) => {
if (t) {
const r = Object.entries(t).map(([a, i]) => `${a}=${i}`);
r.length && (s += `?${r.join("&")}`);
}
return s;
}, C = "https://api.myparcel.nl", A = ["POST", "PUT"];
class k {
constructor(t) {
/**
* Interceptors for request and response.
*
* @protected
*/
e(this, "interceptors");
/**
* Base URL to make requests to.
*
* @protected
*/
e(this, "baseUrl");
/**
* Headers to use with requests.
*
* @protected
*/
e(this, "headers");
/**
* @protected
*/
e(this, "parameters");
/**
* Additional client specific options.
*
* @protected
*/
e(this, "options");
/**
* Array of headers that are required. Client will throw an error if any are missing.
*
* @private
*/
e(this, "_requiredHeaders", []);
this.baseUrl = ((t == null ? void 0 : t.baseUrl) ?? C).replace(/\/+$/, ""), this.headers = (t == null ? void 0 : t.headers) ?? {}, this.parameters = (t == null ? void 0 : t.parameters) ?? {}, this.options = (t == null ? void 0 : t.options) ?? {}, this.interceptors = {
request: new P(),
response: new P()
};
}
get requiredHeaders() {
return this._requiredHeaders;
}
set requiredHeaders(t) {
this._requiredHeaders = t;
}
/**
* Prepare and execute the final request and handle the response.
*/
async doRequest(t, r) {
const a = this.normalizeOptions(t, { ...r, ...this.options });
this.validateHeaders(t, a);
let i = await this.request(t, a);
for (const n of this.interceptors.response.fns)
i = await n(i);
if (u(i, "errors"))
throw new y(i);
return this.getResponseBody(t, i);
}
getResponseBody(t, r) {
if (!u(r, "data"))
return r;
const a = t.getResponseProperty();
if (!a)
return r.data;
const { page: i, size: n, results: p } = r.data;
return i === void 0 && n === void 0 && p === void 0 ? r.data[a] : {
[a]: r.data[a],
...i !== void 0 && { page: i },
...n !== void 0 && { size: n },
...p !== void 0 && { results: p }
};
}
/**
* Gets default and custom headers.
*
* @protected
*/
getHeaders() {
return {
Accept: "application/json",
...this.headers
};
}
/**
* Uses the base url, endpoint and options to create the final request url.
*
* @protected
*/
createUrl(t, r) {
let a = t.getPath();
if (a.length && !a.startsWith("/") && (a = `/${a}`), r != null && r.path && (a = this.substitutePath(a, r.path)), a.includes("/:"))
throw new h(`One or more path variables are missing in ${a}`);
return r != null && r.parameters && (a = _(a, r.parameters)), this.baseUrl + a;
}
/**
* Replace path variables in an url path. Deletes optional parameters if
* they're not passed.
*
* @protected
*/
substitutePath(t, r) {
if (r && Object.entries(r).forEach(([a, i]) => {
t = t.replace(`:${a}`, String(i));
}), t.includes(":")) {
const a = t.match(/:\w+?\?/g);
a == null || a.forEach((i) => {
t = t.replace(`/${i}`, "");
});
}
return t;
}
/**
* Validates headers passed in options.
*
* @protected
*/
validateHeaders(t, r) {
const a = Object.entries(r.headers).reduce(
(n, [p, d]) => ({
...n,
[p.toLowerCase()]: d
}),
{}
), i = this.requiredHeaders.filter((n) => !(n.toLowerCase() in a));
if (i.length)
throw new h(`Required headers are missing: ${i.join(", ")}`);
}
/**
* Executes transformations on options before request.
*
* @protected
*/
normalizeOptions(t, r) {
const a = {
...r,
parameters: {
...this.parameters,
...r.parameters,
...t.getParameters()
},
headers: {
...A.includes(t.method) ? { "Content-Type": "application/json" } : {},
...this.getHeaders(),
...r.headers,
...t.getHeaders()
}
};
if (u(r, "body")) {
const i = t.getProperty();
if (r.body instanceof FormData)
return a.body = r.body, delete a.headers["Content-Type"], a;
i === void 0 ? a.body = {
data: r.body
} : a.body = {
data: { [i]: r.body }
};
}
return a;
}
}
const w = (s) => {
try {
return JSON.parse(s), !0;
} catch {
return !1;
}
};
class G extends k {
constructor(r) {
super(r);
e(this, "request", async (r, a) => {
var b, g, S;
for (const c of this.interceptors.request.fns)
a = await c(a);
const i = r.getTimeout() ?? a.timeout, n = new AbortController(), p = {
method: r.method,
headers: a.headers,
signal: n.signal
};
let d;
i && (d = setTimeout(() => {
n.abort();
}, i)), u(a, "body") && (a.body instanceof FormData ? p.body = a.body : p.body = JSON.stringify(a.body));
try {
const c = await fetch(this.createUrl(r, a), p);
if (c.body) {
if ((b = c.headers.get("Content-Disposition")) != null && b.includes("attachment") || (g = c.headers.get("Content-Type")) != null && g.includes("application/pdf"))
return c.blob();
const l = await c.text();
return (S = c.headers.get("Content-Type")) != null && S.includes("application/json") && w(l) ? JSON.parse(l) : l;
}
} finally {
d && clearTimeout(d);
}
});
}
}
class x {
constructor(t) {
/**
* HTTP method.
*/
e(this, "method", "GET");
/**
* The property in the request body and response body. If the response body
* property differs, set responseProperty alongside property.
* If the property is undefined, the endpoint will be called without a namespace.
*/
e(this, "property");
/**
* Property used in the response. Falls back to `this.property` if it's not
* set.
*/
e(this, "responseProperty");
/**
* Timeout in milliseconds.
* This is used to override the default timeout of the client.
*/
e(this, "timeout");
/**
* Headers to include when calling this endpoint.
*/
e(this, "headers");
/**
* Parameters to include in the endpoint url.
*/
e(this, "parameters");
this.headers = (t == null ? void 0 : t.headers) ?? {}, this.parameters = (t == null ? void 0 : t.parameters) ?? {};
}
getHeaders() {
return this.headers;
}
getParameters() {
return this.parameters;
}
getPath() {
return this.path;
}
getProperty() {
return this.property;
}
getResponseProperty() {
return this.responseProperty ?? this.property;
}
getTimeout() {
return this.timeout;
}
}
class o extends x {
}
class m extends x {
}
function f(s, t) {
if (!t.length)
throw new h("At least one endpoint must be passed.");
return {
...t.reduce(
(r, a) => ({
...r,
[a.name]: async (i) => s.doRequest(a, i ?? {})
}),
{}
),
client: s
};
}
const v = (s, t) => (s.requiredHeaders = ["Authorization"], f(s, t)), D = (s, t) => f(s, t);
class q extends o {
constructor() {
super(...arguments);
e(this, "method", "DELETE");
e(this, "name", "deleteAccountMessage");
e(this, "path", "account_messages/:id");
e(this, "property", "messages");
}
}
class j extends o {
constructor() {
super(...arguments);
e(this, "name", "getAccountMessages");
e(this, "path", "account_messages");
e(this, "property", "messages");
}
}
class U extends o {
constructor() {
super(...arguments);
e(this, "name", "getAccount");
e(this, "path", "accounts/:id");
e(this, "property", "accounts");
}
}
class L extends o {
constructor() {
super(...arguments);
e(this, "name", "getAccounts");
e(this, "path", "accounts");
e(this, "property", "accounts");
}
}
class $ extends o {
constructor() {
super(...arguments);
e(this, "method", "PUT");
e(this, "name", "putAccount");
e(this, "path", "accounts");
e(this, "property", "accounts");
}
}
class M extends o {
constructor() {
super(...arguments);
e(this, "name", "getApiKeys");
e(this, "path", "keys");
e(this, "property", "api_keys");
}
}
class R extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postApiKeys");
e(this, "path", "keys");
e(this, "property", "api_keys");
}
}
class W extends o {
constructor() {
super(...arguments);
e(this, "method", "DELETE");
e(this, "name", "deleteCarrierOption");
e(this, "path", "accounts/:account_id/carrier_options/:contract_id");
e(this, "property", "carrier_options");
}
}
class N extends o {
constructor() {
super(...arguments);
e(this, "name", "getCarrierOptions");
e(this, "path", "carrier_management/accounts/:account_id/carrier_options");
e(this, "property", "carrier_options");
}
}
class z extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postCarrierOptions");
e(this, "path", "accounts/:account_id/carrier_options");
e(this, "property", "carrier_options");
e(this, "responseProperty", "ids");
}
}
class J extends o {
constructor() {
super(...arguments);
e(this, "name", "putCarrierOptions");
e(this, "path", "carrier_management/accounts/:account_id/carrier_options");
e(this, "property", "carrier_options");
e(this, "method", "PUT");
}
}
class K extends o {
constructor() {
super(...arguments);
e(this, "name", "getLocations");
e(this, "path", "locations");
e(this, "property", "locations");
}
}
class B extends o {
constructor() {
super(...arguments);
e(this, "name", "getShipment");
e(this, "path", "shipments/:id");
e(this, "property", "shipments");
}
}
class F extends o {
constructor() {
super(...arguments);
e(this, "name", "getShipments");
e(this, "path", "shipments");
e(this, "property", "shipments");
}
}
class I extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postShipments");
e(this, "path", "shipments");
e(this, "property", "shipments");
e(this, "responseProperty", "ids");
}
getHeaders() {
return {
...super.getHeaders(),
"Content-Type": "application/vnd.shipment+json;charset=utf-8;version=1.1"
};
}
}
class Q extends o {
constructor() {
super(...arguments);
e(this, "name", "getShop");
e(this, "path", "shops/:id");
e(this, "property", "shops");
}
}
class X extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postShop");
e(this, "path", "shops/duplicate");
e(this, "property", "shops");
e(this, "responseProperty", "ids");
}
}
class Y extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postShopDuplicate");
e(this, "path", "shops/duplicate");
e(this, "property", "ids");
}
}
class Z extends o {
constructor() {
super(...arguments);
e(this, "method", "PUT");
e(this, "name", "putShop");
e(this, "path", "shops");
e(this, "property", "shops");
}
}
class V extends o {
constructor() {
super(...arguments);
e(this, "name", "getSubscriptionsCapabilities");
e(this, "path", "subscriptions/capabilities");
e(this, "property", "capabilities");
}
}
class ee extends o {
constructor() {
super(...arguments);
e(this, "method", "DELETE");
e(this, "name", "deleteSubscription");
e(this, "path", "subscriptions/:id");
e(this, "property", "subscriptions");
}
}
class te extends o {
constructor() {
super(...arguments);
e(this, "name", "getSubscriptions");
e(this, "path", "subscriptions");
e(this, "property", "subscriptions");
}
}
class se extends o {
constructor() {
super(...arguments);
e(this, "method", "PATCH");
e(this, "name", "patchSubscriptions");
e(this, "path", "subscriptions");
e(this, "property", "subscriptions");
e(this, "responseProperty", "ids");
}
}
class re extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postSubscriptions");
e(this, "path", "subscriptions");
e(this, "property", "subscriptions");
e(this, "responseProperty", "ids");
}
}
class ae extends o {
constructor() {
super(...arguments);
e(this, "name", "getSystemCountryCodes");
e(this, "path", "system_country_codes");
e(this, "property", "countries");
}
}
class oe extends o {
constructor() {
super(...arguments);
e(this, "name", "getSystemMessages");
e(this, "path", "system_messages");
e(this, "property", "messages");
}
}
class ie extends o {
constructor() {
super(...arguments);
e(this, "name", "getTrackAndTrace");
e(this, "path", "tracktraces/:shipment_id");
e(this, "property", "tracktraces");
}
}
class ne extends o {
constructor() {
super(...arguments);
e(this, "method", "DELETE");
e(this, "name", "deleteWebhookSubscriptions");
e(this, "path", "webhook_subscriptions/:ids");
e(this, "property", "webhook_subscriptions");
}
}
class pe extends o {
constructor() {
super(...arguments);
e(this, "name", "getWebhookSubscriptions");
e(this, "path", "webhook_subscriptions");
e(this, "property", "webhook_subscriptions");
}
}
class ce extends o {
constructor() {
super(...arguments);
e(this, "method", "POST");
e(this, "name", "postWebhookSubscriptions");
e(this, "path", "webhook_subscriptions");
e(this, "property", "webhook_subscriptions");
e(this, "responseProperty", "ids");
}
}
class de extends m {
constructor() {
super(...arguments);
e(this, "name", "getCarrier");
e(this, "path", "carriers/:carrier");
e(this, "property", "carriers");
}
}
class he extends m {
constructor() {
super(...arguments);
e(this, "name", "getCarriers");
e(this, "path", "carriers");
e(this, "property", "carriers");
}
}
class ue extends m {
constructor() {
super(...arguments);
e(this, "name", "getDeliveryOptions");
e(this, "path", "delivery_options");
e(this, "property", "deliveries");
}
getHeaders() {
return { ...super.getHeaders(), Accept: "application/json;version=2.0" };
}
}
class me extends m {
constructor() {
super(...arguments);
e(this, "name", "getPickupLocations");
e(this, "path", "pickup_locations");
e(this, "property", "pickup_locations");
}
}
export {
k as AbstractClient,
x as AbstractEndpoint,
o as AbstractPrivateEndpoint,
m as AbstractPublicEndpoint,
y as ApiException,
C as BASE_URL,
q as DeleteAccountMessage,
W as DeleteCarrierOptions,
ee as DeleteSubscription,
ne as DeleteWebhookSubscriptions,
G as FetchClient,
U as GetAccount,
j as GetAccountMessages,
L as GetAccounts,
M as GetApiKeys,
de as GetCarrier,
N as GetCarrierOptions,
he as GetCarriers,
ue as GetDeliveryOptions,
K as GetLocations,
me as GetPickupLocations,
B as GetShipment,
F as GetShipments,
Q as GetShop,
te as GetSubscriptions,
V as GetSubscriptionsCapabilities,
ae as GetSystemCountryCodes,
oe as GetSystemMessages,
ie as GetTrackAndTrace,
pe as GetWebhookSubscriptions,
se as PatchSubscriptions,
R as PostApiKeys,
z as PostCarrierOptions,
I as PostShipments,
X as PostShop,
Y as PostShopDuplicate,
re as PostSubscriptions,
ce as PostWebhookSubscriptions,
$ as PutAccount,
J as PutCarrierOptions,
Z as PutShop,
h as UserException,
_ as addParameters,
f as createMyParcelSdk,
v as createPrivateSdk,
D as createPublicSdk,
w as isJson
};