UNPKG

@directus/sdk-js

Version:

The official Directus SDK for use in JavaScript!

3 lines (2 loc) 20.2 kB
var e=function(e,t){return function(){for(var s=new Array(arguments.length),r=0;r<s.length;r++)s[r]=arguments[r];return e.apply(t,s)}},t=Object.prototype.toString;function s(e){return"[object Array]"===t.call(e)}function r(e){return void 0===e}function n(e){return null!==e&&"object"==typeof e}function o(e){if("[object Object]"!==t.call(e))return!1;var s=Object.getPrototypeOf(e);return null===s||s===Object.prototype}function i(e){return"[object Function]"===t.call(e)}function a(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),s(e))for(var r=0,n=e.length;r<n;r++)t.call(null,e[r],r,e);else for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.call(null,e[o],o,e)}var u={isArray:s,isArrayBuffer:function(e){return"[object ArrayBuffer]"===t.call(e)},isBuffer:function(e){return null!==e&&!r(e)&&null!==e.constructor&&!r(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:n,isPlainObject:o,isUndefined:r,isDate:function(e){return"[object Date]"===t.call(e)},isFile:function(e){return"[object File]"===t.call(e)},isBlob:function(e){return"[object Blob]"===t.call(e)},isFunction:i,isStream:function(e){return n(e)&&i(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:a,merge:function e(){var t={};function r(r,n){o(t[n])&&o(r)?t[n]=e(t[n],r):o(r)?t[n]=e({},r):s(r)?t[n]=r.slice():t[n]=r}for(var n=0,i=arguments.length;n<i;n++)a(arguments[n],r);return t},extend:function(t,s,r){return a(s,(function(s,n){t[n]=r&&"function"==typeof s?e(s,r):s})),t},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}};function c(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var h=function(e,t,s){if(!t)return e;var r;if(s)r=s(t);else if(u.isURLSearchParams(t))r=t.toString();else{var n=[];u.forEach(t,(function(e,t){null!=e&&(u.isArray(e)?t+="[]":e=[e],u.forEach(e,(function(e){u.isDate(e)?e=e.toISOString():u.isObject(e)&&(e=JSON.stringify(e)),n.push(c(t)+"="+c(e))})))})),r=n.join("&")}if(r){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e};function d(){this.handlers=[]}d.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},d.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},d.prototype.forEach=function(e){u.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var f=d,l=function(e,t,s){return u.forEach(s,(function(s){e=s(e,t)})),e},p=function(e){return!(!e||!e.__CANCEL__)},m=function(e,t){u.forEach(e,(function(s,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=s,delete e[r])}))},g=function(e,t,s,r,n){return function(e,t,s,r,n){return e.config=t,s&&(e.code=s),e.request=r,e.response=n,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e}(new Error(e),t,s,r,n)},w=u.isStandardBrowserEnv()?{write:function(e,t,s,r,n,o){var i=[];i.push(e+"="+encodeURIComponent(t)),u.isNumber(s)&&i.push("expires="+new Date(s).toGMTString()),u.isString(r)&&i.push("path="+r),u.isString(n)&&i.push("domain="+n),!0===o&&i.push("secure"),document.cookie=i.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},y=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],v=u.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),s=document.createElement("a");function r(e){var r=e;return t&&(s.setAttribute("href",r),r=s.href),s.setAttribute("href",r),{href:s.href,protocol:s.protocol?s.protocol.replace(/:$/,""):"",host:s.host,search:s.search?s.search.replace(/^\?/,""):"",hash:s.hash?s.hash.replace(/^#/,""):"",hostname:s.hostname,port:s.port,pathname:"/"===s.pathname.charAt(0)?s.pathname:"/"+s.pathname}}return e=r(window.location.href),function(t){var s=u.isString(t)?r(t):t;return s.protocol===e.protocol&&s.host===e.host}}():function(){return!0},x=function(e){return new Promise((function(t,s){var r=e.data,n=e.headers;u.isFormData(r)&&delete n["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var i=e.auth.username||"",a=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";n.Authorization="Basic "+btoa(i+":"+a)}var c,d,f=(c=e.baseURL,d=e.url,c&&!/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(d)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(c,d):d);if(o.open(e.method.toUpperCase(),h(f,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,o.onreadystatechange=function(){if(o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))){var r,n,i,a,c,h="getAllResponseHeaders"in o?(r=o.getAllResponseHeaders(),c={},r?(u.forEach(r.split("\n"),(function(e){if(a=e.indexOf(":"),n=u.trim(e.substr(0,a)).toLowerCase(),i=u.trim(e.substr(a+1)),n){if(c[n]&&y.indexOf(n)>=0)return;c[n]="set-cookie"===n?(c[n]?c[n]:[]).concat([i]):c[n]?c[n]+", "+i:i}})),c):c):null,d={data:e.responseType&&"text"!==e.responseType?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:h,config:e,request:o};!function(e,t,s){var r=s.config.validateStatus;s.status&&r&&!r(s.status)?t(g("Request failed with status code "+s.status,s.config,null,s.request,s)):e(s)}(t,s,d),o=null}},o.onabort=function(){o&&(s(g("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){s(g("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),s(g(t,e,"ECONNABORTED",o)),o=null},u.isStandardBrowserEnv()){var l=(e.withCredentials||v(f))&&e.xsrfCookieName?w.read(e.xsrfCookieName):void 0;l&&(n[e.xsrfHeaderName]=l)}if("setRequestHeader"in o&&u.forEach(n,(function(e,t){void 0===r&&"content-type"===t.toLowerCase()?delete n[t]:o.setRequestHeader(t,e)})),u.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),e.responseType)try{o.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),s(e),o=null)})),r||(r=null),o.send(r)}))},_={"Content-Type":"application/x-www-form-urlencoded"};function b(e,t){!u.isUndefined(e)&&u.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var k,A={adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(k=x),k),transformRequest:[function(e,t){return m(t,"Accept"),m(t,"Content-Type"),u.isFormData(e)||u.isArrayBuffer(e)||u.isBuffer(e)||u.isStream(e)||u.isFile(e)||u.isBlob(e)?e:u.isArrayBufferView(e)?e.buffer:u.isURLSearchParams(e)?(b(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):u.isObject(e)?(b(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};A.headers={common:{Accept:"application/json, text/plain, */*"}},u.forEach(["delete","get","head"],(function(e){A.headers[e]={}})),u.forEach(["post","put","patch"],(function(e){A.headers[e]=u.merge(_)}));var R=A;function E(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var T=function(e){return E(e),e.headers=e.headers||{},e.data=l(e.data,e.headers,e.transformRequest),e.headers=u.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),u.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||R.adapter)(e).then((function(t){return E(e),t.data=l(t.data,t.headers,e.transformResponse),t}),(function(t){return p(t)||(E(e),t&&t.response&&(t.response.data=l(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},j=function(e,t){t=t||{};var s={},r=["url","method","data"],n=["headers","auth","proxy","params"],o=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],i=["validateStatus"];function a(e,t){return u.isPlainObject(e)&&u.isPlainObject(t)?u.merge(e,t):u.isPlainObject(t)?u.merge({},t):u.isArray(t)?t.slice():t}function c(r){u.isUndefined(t[r])?u.isUndefined(e[r])||(s[r]=a(void 0,e[r])):s[r]=a(e[r],t[r])}u.forEach(r,(function(e){u.isUndefined(t[e])||(s[e]=a(void 0,t[e]))})),u.forEach(n,c),u.forEach(o,(function(r){u.isUndefined(t[r])?u.isUndefined(e[r])||(s[r]=a(void 0,e[r])):s[r]=a(void 0,t[r])})),u.forEach(i,(function(r){r in t?s[r]=a(e[r],t[r]):r in e&&(s[r]=a(void 0,e[r]))}));var h=r.concat(n).concat(o).concat(i),d=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===h.indexOf(e)}));return u.forEach(d,c),s};function I(e){this.defaults=e,this.interceptors={request:new f,response:new f}}I.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=j(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=[T,void 0],s=Promise.resolve(e);for(this.interceptors.request.forEach((function(e){t.unshift(e.fulfilled,e.rejected)})),this.interceptors.response.forEach((function(e){t.push(e.fulfilled,e.rejected)}));t.length;)s=s.then(t.shift(),t.shift());return s},I.prototype.getUri=function(e){return e=j(this.defaults,e),h(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},u.forEach(["delete","get","head","options"],(function(e){I.prototype[e]=function(t,s){return this.request(j(s||{},{method:e,url:t,data:(s||{}).data}))}})),u.forEach(["post","put","patch"],(function(e){I.prototype[e]=function(t,s,r){return this.request(j(r||{},{method:e,url:t,data:s}))}}));var S=I;function C(e){this.message=e}C.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},C.prototype.__CANCEL__=!0;var O=C;function U(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var s=this;e((function(e){s.reason||(s.reason=new O(e),t(s.reason))}))}U.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},U.source=function(){var e;return{token:new U((function(t){e=t})),cancel:e}};var N=U;function B(t){var s=new S(t),r=e(S.prototype.request,s);return u.extend(r,S.prototype,s),u.extend(r,s),r}var L=B(R);L.Axios=S,L.create=function(e){return B(j(L.defaults,e))},L.Cancel=O,L.CancelToken=N,L.isCancel=p,L.all=function(e){return Promise.all(e)},L.spread=function(e){return function(t){return e.apply(null,t)}},L.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError};var q=L,P=L;q.default=P;var D=q;class ${constructor(e,t){this.axios=t,this.endpoint=e.startsWith("directus_")?`/${e.substring(9)}/`:`/items/${e}/`}async create(e,t){return(await this.axios.post(this.endpoint,e,{params:t})).data}async read(e,t){let s=null;e&&(Array.isArray(e)||"string"==typeof e||"number"==typeof e)&&(s=e);let r={};t?r=t:t||"object"!=typeof e||!1!==Array.isArray(e)||(r=e);let n=this.endpoint;s&&(n+=s);return(await this.axios.get(n,{params:r})).data}async update(e,t,s){if("string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every((e=>["string","number"].includes(typeof e)))){const r=e,n=t;return(await this.axios.patch(`${this.endpoint}${r}`,n,{params:s})).data}return(await this.axios.patch(`${this.endpoint}`,e,{params:t})).data}async delete(e){await this.axios.delete(`${this.endpoint}${e}`)}}class z{constructor(e){this.specs={oas:async()=>(await this.axios.get("/server/specs/oas")).data},this.axios=e}async ping(){return await this.axios.get("/server/ping"),"pong"}async info(){return(await this.axios.get("/server/info")).data}}class F{constructor(e){this.random={string:async(e=32)=>(await this.axios.get("/utils/random/string",{params:{length:e}})).data},this.hash={generate:async e=>(await this.axios.post("/utils/hash/generate",{string:e})).data,verify:async(e,t)=>(await this.axios.post("/utils/hash/verify",{string:e,hash:t})).data},this.axios=e}async sort(e,t,s){await this.axios.post(`/utils/sort/${e}`,{item:t,to:s})}async revert(e){await this.axios.post(`/utils/revert/${e}`)}}class H{constructor(e){this.comments={create:async e=>(await this.axios.post("/activity/comments",e)).data,update:async(e,t)=>(await this.axios.patch(`/activity/comments/${e}`,t)).data,delete:async e=>{await this.axios.delete(`/activity/comments/${e}`)}},this.axios=e,this.itemsHandler=new $("directus_activity",e)}async read(e,t){return await this.itemsHandler.read(e,t)}}class M extends ${constructor(e){super("directus_folders",e)}}class X extends ${constructor(e){super("directus_permissions",e)}}class J extends ${constructor(e){super("directus_presets",e)}}class V extends ${constructor(e){super("directus_relations",e)}}class K extends ${constructor(e){super("directus_revisions",e)}}class W extends ${constructor(e){super("directus_roles",e)}}class G extends ${constructor(e){super("directus_users",e),this.tfa={enable:async e=>{await this.axios.post("/users/tfa/enable",{password:e})},disable:async e=>{await this.axios.post("/users/tfa/disable",{otp:e})}},this.me={read:async e=>(await this.axios.get("/users/me",{params:e})).data,update:async(e,t)=>(await this.axios.patch("/users/me",e,{params:t})).data}}async invite(e,t){await this.axios.post("/users/invite",{email:e,role:t})}async acceptInvite(e,t){await this.axios.post("/users/invite/accept",{token:e,password:t})}}class Y extends ${constructor(e){super("directus_settings",e)}}class Q extends ${constructor(e){super("directus_files",e)}}class Z extends ${constructor(e){super("directus_collections",e)}}class ee extends ${constructor(e){super("directus_fields",e)}}class te{constructor(e,t){this.autoRefreshTimeout=null,this.accessTokenInitId=null,this.password={request:async e=>{await this.axios.post("/auth/password/request",{email:e})},reset:async(e,t)=>{await this.axios.post("/auth/password/reset",{token:e,password:t})}},this.axios=e,this.storage=t.storage,this.mode=t.mode,this.autoRefresh=t.autoRefresh,this.accessTokenInitId=this.axios.interceptors.request.use((e=>this.initializeAccessToken(e))),this.autoRefresh&&this.refresh(!0)}get token(){var e,t;return(null===(t=null===(e=this.axios.defaults.headers)||void 0===e?void 0:e.Authorization)||void 0===t?void 0:t.split(" ")[1])||null}set token(e){var t;null===e?null===(t=this.axios.defaults.headers)||void 0===t||delete t.Authorization:this.axios.defaults.headers={...this.axios.defaults.headers||{},Authorization:`Bearer ${e}`}}async login(e){this.removeTimeout();const t=await this.axios.post("/auth/login",{...e,mode:this.mode}),s=t.data.data;return this.token=s.access_token,this.expiresAt=Date.now()+s.expires,await this.storage.setItem("directus_access_token",this.token),await this.storage.setItem("directus_access_token_expires",this.expiresAt),"json"===this.mode&&await this.storage.setItem("directus_refresh_token",s.refresh_token),this.autoRefresh&&this.refresh(!0),t.data}async refresh(e){if(this.removeTimeout(),this.expiresAt=await this.storage.getItem("directus_access_token_expires"),!this.expiresAt)return;if(Date.now()+1e4<this.expiresAt&&this.autoRefresh&&(this.autoRefreshTimeout=setTimeout((()=>this.refresh(!1)),this.expiresAt-Date.now()-1e4),!e))return;const t={mode:this.mode};if("json"===this.mode){const e=await this.storage.getItem("directus_refresh_token");t.refresh_token=e}this.expiresAt<Date.now()+1e3&&(this.token=null);const s=await this.axios.post("/auth/refresh",t).catch((async e=>{var t;throw 401===(null===(t=e.response)||void 0===t?void 0:t.status)&&(await this.storage.removeItem("directus_access_token"),await this.storage.removeItem("directus_access_token_expires"),"json"===this.mode&&await this.storage.removeItem("directus_refresh_token"),this.token=null),Promise.reject(e)})),r=s.data.data;return this.token=r.access_token,this.expiresAt=Date.now()+r.expires,await this.storage.setItem("directus_access_token",this.token),await this.storage.setItem("directus_access_token_expires",this.expiresAt),"json"===this.mode&&await this.storage.setItem("directus_refresh_token",s.data.data.refresh_token),this.autoRefresh&&(this.autoRefreshTimeout=setTimeout((()=>this.refresh(!1)),r.expires-1e4)),s.data}async logout(){this.removeTimeout();const e={};"json"===this.mode&&(e.refresh_token=await this.storage.getItem("directus_refresh_token")),await this.axios.post("/auth/logout",e),await this.storage.removeItem("directus_access_token"),await this.storage.removeItem("directus_access_token_expires"),"json"===this.mode&&await this.storage.removeItem("directus_refresh_token"),this.token=null}async initializeAccessToken(e){if(null!==this.accessTokenInitId){const t=await this.storage.getItem("directus_access_token");t&&(this.token=t,e.headers.Authorization=`Bearer ${t}`),this.axios.interceptors.request.eject(this.accessTokenInitId),this.accessTokenInitId=null}return e}removeTimeout(){null!==this.autoRefreshTimeout&&(clearTimeout(this.autoRefreshTimeout),this.autoRefreshTimeout=null)}}class se{async getItem(e){return window.localStorage.getItem(e)}async setItem(e,t){window.localStorage.setItem(e,t)}async removeItem(e){window.localStorage.removeItem(e)}}class re{constructor(){this.values={}}async getItem(e){return this.values[e]}async setItem(e,t){this.values[e]=t}async removeItem(e){delete this.values[e]}}export default class{constructor(e,t){var s,r,n,o,i,a;this.axios=D.create({baseURL:e,withCredentials:!0}),this.authOptions={storage:null!==(r=null===(s=null==t?void 0:t.auth)||void 0===s?void 0:s.storage)&&void 0!==r?r:"undefined"==typeof window?new re:new se,mode:null!==(o=null===(n=null==t?void 0:t.auth)||void 0===n?void 0:n.mode)&&void 0!==o?o:"cookie",autoRefresh:null!==(a=null===(i=null==t?void 0:t.auth)||void 0===i?void 0:i.autoRefresh)&&void 0!==a&&a},this.auth=new te(this.axios,this.authOptions)}get url(){return this.axios.defaults.baseURL}set url(e){this.axios.defaults.baseURL=e}items(e){if(e.startsWith("directus_"))throw new Error(`You can't read the "${e}" collection directly.`);return new $(e,this.axios)}get activity(){return new H(this.axios)}get collections(){return new Z(this.axios)}get fields(){return new ee(this.axios)}get files(){return new Q(this.axios)}get folders(){return new M(this.axios)}get permissions(){return new X(this.axios)}get presets(){return new J(this.axios)}get relations(){return new V(this.axios)}get revisions(){return new K(this.axios)}get roles(){return new W(this.axios)}get server(){return new z(this.axios)}get settings(){return new Y(this.axios)}get users(){return new G(this.axios)}get utils(){return new F(this.axios)}} //# sourceMappingURL=sdk-js.esm.min.js.map