@myparcel/sdk
Advanced tools
Comparing version 3.1.0 to 3.2.0
337
lib/index.js
@@ -1,1 +0,336 @@ | ||
"use strict";var g=Object.defineProperty;var v=(a,e,t)=>e in a?g(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var s=(a,e,t)=>(v(a,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@myparcel/ts-utils");class m extends Error{constructor(t){super(t.message);s(this,"data");Object.setPrototypeOf(this,m.prototype),this.name="ApiException",this.data=t}}class h extends Error{constructor(t){super(t);s(this,"name","user");Object.setPrototypeOf(this,h.prototype),this.name="UserException"}}const H=(a,e)=>{if(e){const t=Object.entries(e).map(([r,i])=>`${r}=${i}`);t.length&&(a+=`?${t.join("&")}`)}return a},O="https://api.myparcel.nl",T=["POST","PUT"];class S{constructor(e){s(this,"baseUrl");s(this,"headers");s(this,"parameters");s(this,"options");s(this,"_requiredHeaders",[]);this.baseUrl=((e==null?void 0:e.baseUrl)??O).replace(/\/+$/,""),this.headers=(e==null?void 0:e.headers)??{},this.parameters=(e==null?void 0:e.parameters)??{},this.options=(e==null?void 0:e.options)??{}}get requiredHeaders(){return this._requiredHeaders}set requiredHeaders(e){this._requiredHeaders=e}async doRequest(e,t){const r=this.normalizeOptions(e,{...t,...this.options});this.validateHeaders(e,r);const i=await this.request(e,r);if(l.isOfType(i,"errors"))throw new m(i);if(l.isOfType(i,"data")){const p=e.getResponseProperty();let n=i.data[p];const{page:d,size:o,results:c}=i.data;return(d!==void 0||o!==void 0||c!==void 0)&&(n={[p]:i.data[p]},d!==void 0&&(n.page=d),o!==void 0&&(n.size=o),c!==void 0&&(n.results=c)),n}return i}getHeaders(){return{Accept:"application/json",...this.headers}}createUrl(e,t){let r=e.getPath();if(r.length&&!r.startsWith("/")&&(r=`/${r}`),t!=null&&t.path&&(r=this.substitutePath(r,t.path)),r.includes("/:"))throw new h(`One or more path variables are missing in ${r}`);return t!=null&&t.parameters&&(r=H(r,t.parameters)),this.baseUrl+r}substitutePath(e,t){if(t&&Object.entries(t).forEach(([r,i])=>{e=e.replace(`:${r}`,String(i))}),e.includes(":")){const r=e.match(/:\w+?\?/g);r==null||r.forEach(i=>{e=e.replace(`/${i}`,"")})}return e}validateHeaders(e,t){const r=Object.entries(t.headers).reduce((p,[n,d])=>({...p,[n.toLowerCase()]:d}),{}),i=this.requiredHeaders.filter(p=>!(p.toLowerCase()in r));if(i.length)throw new h(`Required headers are missing: ${i.join(", ")}`)}normalizeOptions(e,t){const r={...t,parameters:{...this.parameters,...t.parameters,...e.getParameters()},headers:{...T.includes(e.method)?{"Content-Type":"application/json"}:{},...this.getHeaders(),...t.headers,...e.getHeaders()}};if(l.isOfType(t,"body")){const i=e.getProperty();i===void 0?r.body={data:t.body}:r.body={data:{[i]:t.body}}}return r}}const E=a=>{try{return JSON.parse(a),!0}catch{return!1}};class f extends S{constructor(t){super(t);s(this,"request",async(t,r)=>{var o;const i=new AbortController,p=setTimeout(()=>i.abort(),r.timeout),n={method:t.method,headers:r.headers,...r.timeout&&{signal:i.signal}};l.isOfType(r,"body")&&(n.body=JSON.stringify(r.body));const d=await fetch(this.createUrl(t,r),n);if(clearTimeout(p),d.body){const c=await d.text();return(o=d.headers.get("Content-Type"))!=null&&o.includes("application/json")&&E(c)?JSON.parse(c):c}})}}class b{constructor(e){s(this,"method","GET");s(this,"responseProperty");s(this,"headers");s(this,"parameters");this.headers=(e==null?void 0:e.headers)??{},this.parameters=(e==null?void 0:e.parameters)??{}}getHeaders(){return this.headers}getParameters(){return this.parameters}getPath(){return this.path}getProperty(){return this.property}getResponseProperty(){return this.responseProperty??this.property}}class u extends b{}class y extends b{}function P(a,e){if(!e.length)throw new h("At least one endpoint must be passed.");return e.reduce((t,r)=>({...t,[r.name]:async i=>a.doRequest(r,i??{})}),{})}const w=(a,e)=>(a.requiredHeaders=["Authorization"],P(a,e)),x=(a,e)=>P(a,e);class C extends y{constructor(){super(...arguments);s(this,"name","getShipment");s(this,"path","shipments/:id");s(this,"property","shipments")}}class A extends y{constructor(){super(...arguments);s(this,"name","getShipments");s(this,"path","shipments");s(this,"property","shipments")}}class j extends y{constructor(){super(...arguments);s(this,"method","POST");s(this,"name","postShipments");s(this,"path","shipments");s(this,"property","shipments");s(this,"responseProperty","ids")}getHeaders(){return{...super.getHeaders(),"Content-Type":"application/vnd.shipment+json;charset=utf-8;version=1.1"}}}class q extends u{constructor(){super(...arguments);s(this,"name","getCarrier");s(this,"path","carriers/:carrier");s(this,"property","carriers")}}class G extends u{constructor(){super(...arguments);s(this,"name","getCarriers");s(this,"path","carriers");s(this,"property","carriers")}}class U extends u{constructor(){super(...arguments);s(this,"name","getDeliveryOptions");s(this,"path","delivery_options");s(this,"property","deliveries")}getHeaders(){return{...super.getHeaders(),Accept:"application/json;version=2.0"}}}class k extends u{constructor(){super(...arguments);s(this,"name","getPickupLocations");s(this,"path","pickup_locations");s(this,"property","pickup_locations")}}exports.AbstractClient=S;exports.AbstractEndpoint=b;exports.AbstractPrivateEndpoint=y;exports.AbstractPublicEndpoint=u;exports.ApiException=m;exports.BASE_URL=O;exports.FetchClient=f;exports.GetCarrier=q;exports.GetCarriers=G;exports.GetDeliveryOptions=U;exports.GetPickupLocations=k;exports.GetShipment=C;exports.GetShipments=A;exports.PostShipments=j;exports.UserException=h;exports.createMyParcelSdk=P;exports.createPrivateSdk=w;exports.createPublicSdk=x; | ||
var O = Object.defineProperty; | ||
var H = (a, e, t) => e in a ? O(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t; | ||
var s = (a, e, t) => (H(a, typeof e != "symbol" ? e + "" : e, t), t); | ||
import { isOfType as u } from "@myparcel/ts-utils"; | ||
class y extends Error { | ||
constructor(t) { | ||
super(t.message); | ||
s(this, "data"); | ||
Object.setPrototypeOf(this, y.prototype), this.name = "ApiException", this.data = t; | ||
} | ||
} | ||
class o extends Error { | ||
constructor(t) { | ||
super(t); | ||
s(this, "name", "user"); | ||
Object.setPrototypeOf(this, o.prototype), this.name = "UserException"; | ||
} | ||
} | ||
const v = (a, e) => { | ||
if (e) { | ||
const t = Object.entries(e).map(([r, i]) => `${r}=${i}`); | ||
t.length && (a += `?${t.join("&")}`); | ||
} | ||
return a; | ||
}, w = "https://api.myparcel.nl", S = ["POST", "PUT"]; | ||
class x { | ||
constructor(e) { | ||
/** | ||
* Base URL to make requests to. | ||
* | ||
* @protected | ||
*/ | ||
s(this, "baseUrl"); | ||
/** | ||
* Headers to use with requests. | ||
* | ||
* @protected | ||
*/ | ||
s(this, "headers"); | ||
/** | ||
* @protected | ||
*/ | ||
s(this, "parameters"); | ||
/** | ||
* Additional client specific options. | ||
* | ||
* @protected | ||
*/ | ||
s(this, "options"); | ||
/** | ||
* Array of headers that are required. Client will throw an error if any are missing. | ||
* | ||
* @private | ||
*/ | ||
s(this, "_requiredHeaders", []); | ||
this.baseUrl = ((e == null ? void 0 : e.baseUrl) ?? w).replace(/\/+$/, ""), this.headers = (e == null ? void 0 : e.headers) ?? {}, this.parameters = (e == null ? void 0 : e.parameters) ?? {}, this.options = (e == null ? void 0 : e.options) ?? {}; | ||
} | ||
get requiredHeaders() { | ||
return this._requiredHeaders; | ||
} | ||
set requiredHeaders(e) { | ||
this._requiredHeaders = e; | ||
} | ||
/** | ||
* Prepare and execute the final request and handle the response. | ||
*/ | ||
async doRequest(e, t) { | ||
const r = this.normalizeOptions(e, { ...t, ...this.options }); | ||
this.validateHeaders(e, r); | ||
const i = await this.request(e, r); | ||
if (u(i, "errors")) | ||
throw new y(i); | ||
if (u(i, "data")) { | ||
const p = e.getResponseProperty(); | ||
let d = i.data[p]; | ||
const { page: n, size: c, results: h } = i.data; | ||
return (n !== void 0 || c !== void 0 || h !== void 0) && (d = { | ||
[p]: i.data[p] | ||
}, n !== void 0 && (d.page = n), c !== void 0 && (d.size = c), h !== void 0 && (d.results = h)), d; | ||
} | ||
return i; | ||
} | ||
/** | ||
* 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(e, t) { | ||
let r = e.getPath(); | ||
if (r.length && !r.startsWith("/") && (r = `/${r}`), t != null && t.path && (r = this.substitutePath(r, t.path)), r.includes("/:")) | ||
throw new o(`One or more path variables are missing in ${r}`); | ||
return t != null && t.parameters && (r = v(r, t.parameters)), this.baseUrl + r; | ||
} | ||
/** | ||
* Replace path variables in an url path. Deletes optional parameters if | ||
* they're not passed. | ||
* | ||
* @protected | ||
*/ | ||
substitutePath(e, t) { | ||
if (t && Object.entries(t).forEach(([r, i]) => { | ||
e = e.replace(`:${r}`, String(i)); | ||
}), e.includes(":")) { | ||
const r = e.match(/:\w+?\?/g); | ||
r == null || r.forEach((i) => { | ||
e = e.replace(`/${i}`, ""); | ||
}); | ||
} | ||
return e; | ||
} | ||
/** | ||
* Validates headers passed in options. | ||
* | ||
* @protected | ||
*/ | ||
validateHeaders(e, t) { | ||
const r = Object.entries(t.headers).reduce( | ||
(p, [d, n]) => ({ | ||
...p, | ||
[d.toLowerCase()]: n | ||
}), | ||
{} | ||
), i = this.requiredHeaders.filter((p) => !(p.toLowerCase() in r)); | ||
if (i.length) | ||
throw new o(`Required headers are missing: ${i.join(", ")}`); | ||
} | ||
/** | ||
* Executes transformations on options before request. | ||
* | ||
* @protected | ||
*/ | ||
normalizeOptions(e, t) { | ||
const r = { | ||
...t, | ||
parameters: { | ||
...this.parameters, | ||
...t.parameters, | ||
...e.getParameters() | ||
}, | ||
headers: { | ||
...S.includes(e.method) ? { "Content-Type": "application/json" } : {}, | ||
...this.getHeaders(), | ||
...t.headers, | ||
...e.getHeaders() | ||
} | ||
}; | ||
if (u(t, "body")) { | ||
const i = e.getProperty(); | ||
i === void 0 ? r.body = { | ||
data: t.body | ||
} : r.body = { | ||
data: { [i]: t.body } | ||
}; | ||
} | ||
return r; | ||
} | ||
} | ||
const f = (a) => { | ||
try { | ||
return JSON.parse(a), !0; | ||
} catch { | ||
return !1; | ||
} | ||
}; | ||
class E extends x { | ||
constructor(t) { | ||
super(t); | ||
s(this, "request", async (t, r) => { | ||
var c, h; | ||
const i = new AbortController(), p = setTimeout(() => i.abort(), r.timeout), d = { | ||
method: t.method, | ||
headers: r.headers, | ||
...r.timeout && { signal: i.signal } | ||
}; | ||
u(r, "body") && (d.body = JSON.stringify(r.body)); | ||
const n = await fetch(this.createUrl(t, r), d); | ||
if (clearTimeout(p), n.body) { | ||
if ((c = n.headers.get("Content-Disposition")) != null && c.includes("attachment")) | ||
return n.blob(); | ||
const m = await n.text(); | ||
return (h = n.headers.get("Content-Type")) != null && h.includes("application/json") && f(m) ? JSON.parse(m) : m; | ||
} | ||
}); | ||
} | ||
} | ||
class P { | ||
constructor(e) { | ||
/** | ||
* HTTP method. | ||
*/ | ||
s(this, "method", "GET"); | ||
/** | ||
* Property used in the response. Falls back to `this.property` if it's not | ||
* set. | ||
*/ | ||
s(this, "responseProperty"); | ||
/** | ||
* Headers to include when calling this endpoint. | ||
*/ | ||
s(this, "headers"); | ||
/** | ||
* Parameters to include in the endpoint url. | ||
*/ | ||
s(this, "parameters"); | ||
this.headers = (e == null ? void 0 : e.headers) ?? {}, this.parameters = (e == null ? void 0 : e.parameters) ?? {}; | ||
} | ||
getHeaders() { | ||
return this.headers; | ||
} | ||
getParameters() { | ||
return this.parameters; | ||
} | ||
getPath() { | ||
return this.path; | ||
} | ||
getProperty() { | ||
return this.property; | ||
} | ||
getResponseProperty() { | ||
return this.responseProperty ?? this.property; | ||
} | ||
} | ||
class l extends P { | ||
} | ||
class b extends P { | ||
} | ||
function g(a, e) { | ||
if (!e.length) | ||
throw new o("At least one endpoint must be passed."); | ||
return e.reduce( | ||
(t, r) => ({ | ||
...t, | ||
[r.name]: async (i) => a.doRequest(r, i ?? {}) | ||
}), | ||
{} | ||
); | ||
} | ||
const j = (a, e) => (a.requiredHeaders = ["Authorization"], g(a, e)), q = (a, e) => g(a, e); | ||
class A extends b { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "name", "getShipment"); | ||
s(this, "path", "shipments/:id"); | ||
s(this, "property", "shipments"); | ||
} | ||
} | ||
class U extends b { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "name", "getShipments"); | ||
s(this, "path", "shipments"); | ||
s(this, "property", "shipments"); | ||
} | ||
} | ||
class $ extends b { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "method", "POST"); | ||
s(this, "name", "postShipments"); | ||
s(this, "path", "shipments"); | ||
s(this, "property", "shipments"); | ||
s(this, "responseProperty", "ids"); | ||
} | ||
getHeaders() { | ||
return { | ||
...super.getHeaders(), | ||
"Content-Type": "application/vnd.shipment+json;charset=utf-8;version=1.1" | ||
}; | ||
} | ||
} | ||
class _ extends l { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "name", "getCarrier"); | ||
s(this, "path", "carriers/:carrier"); | ||
s(this, "property", "carriers"); | ||
} | ||
} | ||
class k extends l { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "name", "getCarriers"); | ||
s(this, "path", "carriers"); | ||
s(this, "property", "carriers"); | ||
} | ||
} | ||
class G extends l { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "name", "getDeliveryOptions"); | ||
s(this, "path", "delivery_options"); | ||
s(this, "property", "deliveries"); | ||
} | ||
getHeaders() { | ||
return { ...super.getHeaders(), Accept: "application/json;version=2.0" }; | ||
} | ||
} | ||
class R extends l { | ||
constructor() { | ||
super(...arguments); | ||
s(this, "name", "getPickupLocations"); | ||
s(this, "path", "pickup_locations"); | ||
s(this, "property", "pickup_locations"); | ||
} | ||
} | ||
export { | ||
x as AbstractClient, | ||
P as AbstractEndpoint, | ||
b as AbstractPrivateEndpoint, | ||
l as AbstractPublicEndpoint, | ||
y as ApiException, | ||
w as BASE_URL, | ||
E as FetchClient, | ||
_ as GetCarrier, | ||
k as GetCarriers, | ||
G as GetDeliveryOptions, | ||
R as GetPickupLocations, | ||
A as GetShipment, | ||
U as GetShipments, | ||
$ as PostShipments, | ||
o as UserException, | ||
g as createMyParcelSdk, | ||
j as createPrivateSdk, | ||
q as createPublicSdk | ||
}; |
{ | ||
"name": "@myparcel/sdk", | ||
"version": "3.1.0", | ||
"version": "3.2.0", | ||
"description": "JavaScript SDK to connect to the MyParcel API via Node.js or browser", | ||
@@ -14,11 +14,12 @@ "keywords": [ | ||
"author": "Edie Lemoine <edie@myparcel.nl>", | ||
"type": "module", | ||
"exports": { | ||
".": { | ||
"types": "./lib/index.d.ts", | ||
"import": "./lib/index.mjs", | ||
"require": "./lib/index.js" | ||
"import": "./lib/index.js", | ||
"require": "./lib/index.cjs" | ||
} | ||
}, | ||
"main": "./lib/index.js", | ||
"module": "./lib/index.mjs", | ||
"main": "./lib/index.cjs", | ||
"module": "./lib/index.js", | ||
"types": "./lib/index.d.ts", | ||
@@ -52,3 +53,3 @@ "files": [ | ||
"@myparcel-eslint/eslint-config-prettier-typescript": "^1.2.0", | ||
"@myparcel/semantic-release-config": "^4.2.3", | ||
"@myparcel/semantic-release-config": "^5.0.0", | ||
"@tsconfig/recommended": "^1.0.2", | ||
@@ -61,5 +62,5 @@ "@vitest/coverage-v8": "^0.34.4", | ||
"sort-package-json": "^2.4.1", | ||
"typescript": "^4.9.5", | ||
"typescript": "^5.2.0", | ||
"vite": "^4.1.1", | ||
"vite-plugin-dts": "^1.7.3", | ||
"vite-plugin-dts": "^3.6.0", | ||
"vitest": "^0.34.0", | ||
@@ -66,0 +67,0 @@ "vitest-fetch-mock": "^0.2.1" |
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
45299
52
1126
Yes