@nhost/nhost-js 0.3.9 → 0.3.12

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 CHANGED
@@ -36,7 +36,7 @@ const nhost = new NhostClient({
36
36
 
37
37
  ### GraphQL
38
38
 
39
- Access Nhost Auth methods using `nhost.graphql`.
39
+ Access Nhost GraphQL methods using `nhost.graphql`.
40
40
 
41
41
  ### Authentication
42
42
 
@@ -1,4 +1,4 @@
1
- import type { AxiosRequestConfig } from 'axios';
1
+ import { AxiosRequestConfig } from 'axios';
2
2
  import { FunctionCallResponse } from '../types';
3
3
  export interface NhostFunctionsConstructorParams {
4
4
  url: string;
@@ -1,4 +1,4 @@
1
- import type { AxiosRequestConfig } from 'axios';
1
+ import { AxiosRequestConfig } from 'axios';
2
2
  import { GraphqlRequestResponse } from '../types';
3
3
  export interface NhostGraphqlConstructorParams {
4
4
  url: string;
package/dist/index.cjs.js CHANGED
@@ -1 +1,2 @@
1
- "use strict";var H=Object.defineProperty,q=Object.defineProperties;var D=Object.getOwnPropertyDescriptors;var _=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var N=(i,e,t)=>e in i?H(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,w=(i,e)=>{for(var t in e||(e={}))M.call(e,t)&&N(i,t,e[t]);if(_)for(var t of _(e))z.call(e,t)&&N(i,t,e[t]);return i},k=(i,e)=>q(i,D(e));Object.defineProperty(exports,"__esModule",{value:!0});exports[Symbol.toStringTag]="Module";const B=require("axios"),V=500;class G{constructor({url:e=""}){this.url=e,this.httpClient=B.create({baseURL:this.url}),this.httpClient.interceptors.response.use(t=>t,t=>{var o,l,h,f,m,y;return Promise.reject({message:(f=(h=(l=(o=t.response)==null?void 0:o.data)==null?void 0:l.message)!=null?h:t.message)!=null?f:JSON.stringify(t),status:(y=(m=t.response)==null?void 0:m.status)!=null?y:V})})}async signUpEmailPassword(e){try{return{data:(await this.httpClient.post("/signup/email-password",e)).data,error:null}}catch(t){return{data:null,error:t}}}async signInEmailPassword(e){try{return{data:(await this.httpClient.post("/signin/email-password",e)).data,error:null}}catch(t){return{data:null,error:t}}}async signInPasswordlessEmail(e){try{return{data:(await this.httpClient.post("/signin/passwordless/email",e)).data,error:null}}catch(t){return{data:null,error:t}}}async signInPasswordlessSms(e){try{return{data:(await this.httpClient.post("/signin/passwordless/sms",e)).data,error:null}}catch(t){return{data:null,error:t}}}async signInPasswordlessSmsOtp(e){try{return{data:(await this.httpClient.post("/signin/passwordless/sms/otp",e)).data,error:null}}catch(t){return{data:null,error:t}}}async signOut(e){try{return await this.httpClient.post("/signout",e),{error:null}}catch(t){return{error:t}}}async refreshToken(e){try{const t=await this.httpClient.post("/token",e);return{error:null,session:t.data}}catch(t){return{error:t,session:null}}}async resetPassword(e){try{return await this.httpClient.post("/user/password/reset",e),{error:null}}catch(t){return{error:t}}}async changePassword(e){try{return await this.httpClient.post("/user/password",e,{headers:w({},this.generateAuthHeaders())}),{error:null}}catch(t){return{error:t}}}async sendVerificationEmail(e){try{return await this.httpClient.post("/user/email/send-verification-email",e),{error:null}}catch(t){return{error:t}}}async changeEmail(e){try{return await this.httpClient.post("/user/email/change",e,{headers:w({},this.generateAuthHeaders())}),{error:null}}catch(t){return{error:t}}}async deanonymize(e){try{return await this.httpClient.post("/user/deanonymize",e),{error:null}}catch(t){return{error:t}}}async verifyEmail(e){try{return{data:(await this.httpClient.post("/user/email/verify",e)).data,error:null}}catch(t){return{data:null,error:t}}}setAccessToken(e){this.accessToken=e}generateAuthHeaders(){return this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:null}}var $={},Q=i=>encodeURIComponent(i).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),x="%[a-f0-9]{2}",j=new RegExp(x,"gi"),v=new RegExp("("+x+")+","gi");function b(i,e){try{return decodeURIComponent(i.join(""))}catch{}if(i.length===1)return i;e=e||1;var t=i.slice(0,e),o=i.slice(e);return Array.prototype.concat.call([],b(t),b(o))}function J(i){try{return decodeURIComponent(i)}catch{for(var e=i.match(j),t=1;t<e.length;t++)i=b(e,t).join(""),e=i.match(j);return i}}function W(i){for(var e={"%FE%FF":"\uFFFD\uFFFD","%FF%FE":"\uFFFD\uFFFD"},t=v.exec(i);t;){try{e[t[0]]=decodeURIComponent(t[0])}catch{var o=J(t[0]);o!==t[0]&&(e[t[0]]=o)}t=v.exec(i)}e["%C2"]="\uFFFD";for(var l=Object.keys(e),h=0;h<l.length;h++){var f=l[h];i=i.replace(new RegExp(f,"g"),e[f])}return i}var K=function(i){if(typeof i!="string")throw new TypeError("Expected `encodedURI` to be of type `string`, got `"+typeof i+"`");try{return i=i.replace(/\+/g," "),decodeURIComponent(i)}catch{return W(i)}},X=(i,e)=>{if(!(typeof i=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[i];const t=i.indexOf(e);return t===-1?[i]:[i.slice(0,t),i.slice(t+e.length)]},Y=function(i,e){for(var t={},o=Object.keys(i),l=Array.isArray(e),h=0;h<o.length;h++){var f=o[h],m=i[f];(l?e.indexOf(f)!==-1:e(f,m,i))&&(t[f]=m)}return t};(function(i){const e=Q,t=K,o=X,l=Y,h=r=>r==null,f=Symbol("encodeFragmentIdentifier");function m(r){switch(r.arrayFormat){case"index":return n=>(a,s)=>{const c=a.length;return s===void 0||r.skipNull&&s===null||r.skipEmptyString&&s===""?a:s===null?[...a,[g(n,r),"[",c,"]"].join("")]:[...a,[g(n,r),"[",g(c,r),"]=",g(s,r)].join("")]};case"bracket":return n=>(a,s)=>s===void 0||r.skipNull&&s===null||r.skipEmptyString&&s===""?a:s===null?[...a,[g(n,r),"[]"].join("")]:[...a,[g(n,r),"[]=",g(s,r)].join("")];case"colon-list-separator":return n=>(a,s)=>s===void 0||r.skipNull&&s===null||r.skipEmptyString&&s===""?a:s===null?[...a,[g(n,r),":list="].join("")]:[...a,[g(n,r),":list=",g(s,r)].join("")];case"comma":case"separator":case"bracket-separator":{const n=r.arrayFormat==="bracket-separator"?"[]=":"=";return a=>(s,c)=>c===void 0||r.skipNull&&c===null||r.skipEmptyString&&c===""?s:(c=c===null?"":c,s.length===0?[[g(a,r),n,g(c,r)].join("")]:[[s,g(c,r)].join(r.arrayFormatSeparator)])}default:return n=>(a,s)=>s===void 0||r.skipNull&&s===null||r.skipEmptyString&&s===""?a:s===null?[...a,g(n,r)]:[...a,[g(n,r),"=",g(s,r)].join("")]}}function y(r){let n;switch(r.arrayFormat){case"index":return(a,s,c)=>{if(n=/\[(\d*)\]$/.exec(a),a=a.replace(/\[\d*\]$/,""),!n){c[a]=s;return}c[a]===void 0&&(c[a]={}),c[a][n[1]]=s};case"bracket":return(a,s,c)=>{if(n=/(\[\])$/.exec(a),a=a.replace(/\[\]$/,""),!n){c[a]=s;return}if(c[a]===void 0){c[a]=[s];return}c[a]=[].concat(c[a],s)};case"colon-list-separator":return(a,s,c)=>{if(n=/(:list)$/.exec(a),a=a.replace(/:list$/,""),!n){c[a]=s;return}if(c[a]===void 0){c[a]=[s];return}c[a]=[].concat(c[a],s)};case"comma":case"separator":return(a,s,c)=>{const d=typeof s=="string"&&s.includes(r.arrayFormatSeparator),u=typeof s=="string"&&!d&&I(s,r).includes(r.arrayFormatSeparator);s=u?I(s,r):s;const S=d||u?s.split(r.arrayFormatSeparator).map(R=>I(R,r)):s===null?s:I(s,r);c[a]=S};case"bracket-separator":return(a,s,c)=>{const d=/(\[\])$/.test(a);if(a=a.replace(/\[\]$/,""),!d){c[a]=s&&I(s,r);return}const u=s===null?[]:s.split(r.arrayFormatSeparator).map(S=>I(S,r));if(c[a]===void 0){c[a]=u;return}c[a]=[].concat(c[a],u)};default:return(a,s,c)=>{if(c[a]===void 0){c[a]=s;return}c[a]=[].concat(c[a],s)}}}function p(r){if(typeof r!="string"||r.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function g(r,n){return n.encode?n.strict?e(r):encodeURIComponent(r):r}function I(r,n){return n.decode?t(r):r}function C(r){return Array.isArray(r)?r.sort():typeof r=="object"?C(Object.keys(r)).sort((n,a)=>Number(n)-Number(a)).map(n=>r[n]):r}function F(r){const n=r.indexOf("#");return n!==-1&&(r=r.slice(0,n)),r}function P(r){let n="";const a=r.indexOf("#");return a!==-1&&(n=r.slice(a)),n}function E(r){r=F(r);const n=r.indexOf("?");return n===-1?"":r.slice(n+1)}function U(r,n){return n.parseNumbers&&!Number.isNaN(Number(r))&&typeof r=="string"&&r.trim()!==""?r=Number(r):n.parseBooleans&&r!==null&&(r.toLowerCase()==="true"||r.toLowerCase()==="false")&&(r=r.toLowerCase()==="true"),r}function O(r,n){n=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},n),p(n.arrayFormatSeparator);const a=y(n),s=Object.create(null);if(typeof r!="string"||(r=r.trim().replace(/^[?#&]/,""),!r))return s;for(const c of r.split("&")){if(c==="")continue;let[d,u]=o(n.decode?c.replace(/\+/g," "):c,"=");u=u===void 0?null:["comma","separator","bracket-separator"].includes(n.arrayFormat)?u:I(u,n),a(I(d,n),u,s)}for(const c of Object.keys(s)){const d=s[c];if(typeof d=="object"&&d!==null)for(const u of Object.keys(d))d[u]=U(d[u],n);else s[c]=U(d,n)}return n.sort===!1?s:(n.sort===!0?Object.keys(s).sort():Object.keys(s).sort(n.sort)).reduce((c,d)=>{const u=s[d];return Boolean(u)&&typeof u=="object"&&!Array.isArray(u)?c[d]=C(u):c[d]=u,c},Object.create(null))}i.extract=E,i.parse=O,i.stringify=(r,n)=>{if(!r)return"";n=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},n),p(n.arrayFormatSeparator);const a=u=>n.skipNull&&h(r[u])||n.skipEmptyString&&r[u]==="",s=m(n),c={};for(const u of Object.keys(r))a(u)||(c[u]=r[u]);const d=Object.keys(c);return n.sort!==!1&&d.sort(n.sort),d.map(u=>{const S=r[u];return S===void 0?"":S===null?g(u,n):Array.isArray(S)?S.length===0&&n.arrayFormat==="bracket-separator"?g(u,n)+"[]":S.reduce(s(u),[]).join("&"):g(u,n)+"="+g(S,n)}).filter(u=>u.length>0).join("&")},i.parseUrl=(r,n)=>{n=Object.assign({decode:!0},n);const[a,s]=o(r,"#");return Object.assign({url:a.split("?")[0]||"",query:O(E(r),n)},n&&n.parseFragmentIdentifier&&s?{fragmentIdentifier:I(s,n)}:{})},i.stringifyUrl=(r,n)=>{n=Object.assign({encode:!0,strict:!0,[f]:!0},n);const a=F(r.url).split("?")[0]||"",s=i.extract(r.url),c=i.parse(s,{sort:!1}),d=Object.assign(c,r.query);let u=i.stringify(d,n);u&&(u=`?${u}`);let S=P(r.url);return r.fragmentIdentifier&&(S=`#${n[f]?g(r.fragmentIdentifier,n):r.fragmentIdentifier}`),`${a}${u}${S}`},i.pick=(r,n,a)=>{a=Object.assign({parseFragmentIdentifier:!0,[f]:!1},a);const{url:s,query:c,fragmentIdentifier:d}=i.parseUrl(r,a);return i.stringifyUrl({url:s,query:l(c,n),fragmentIdentifier:d},a)},i.exclude=(r,n,a)=>{const s=Array.isArray(n)?c=>!n.includes(c):(c,d)=>!n(c,d);return i.pick(r,s,a)}})($);const T="nhostRefreshToken",A=()=>typeof window!="undefined";class Z{constructor(){this.memory={}}setItem(e,t){this.memory[e]=t}getItem(e){return this.memory[e]}removeItem(e){delete this.memory[e]}}class ee{constructor({url:e,autoRefreshToken:t=!0,autoLogin:o=!0,refreshIntervalTime:l,clientStorage:h,clientStorageType:f="web"}){this.refreshIntervalTime=l,h?this.clientStorage=h:this.clientStorage=A()?localStorage:new Z,this.clientStorageType=f,this.onTokenChangedFunctions=[],this.onAuthChangedFunctions=[],this.refreshInterval,this.refreshSleepCheckInterval=0,this.refreshIntervalSleepCheckLastSample=Date.now(),this.sampleRate=2e3,this.url=e,this.autoRefreshToken=t,this.initAuthLoading=!0,this.session=null,this.api=new G({url:this.url});let m=null,y=!1;if(o&&A()&&window.location){const p=$.parse(window.location.toString().split("#")[1]);if("refreshToken"in p&&(m=p.refreshToken),"otp"in p&&"email"in p){const{otp:g,email:I}=p;this.signIn({otp:g,email:I}),y=!0}}!y&&o?this._autoLogin(m):m&&this._setItem(T,m)}async signUp(e){const{email:t,password:o}=e;if(t&&o){const{data:l,error:h}=await this.api.signUpEmailPassword(e);if(h)return{session:null,error:h};if(!l)return{session:null,error:{message:"An error occurred on sign up.",status:500}};const{session:f}=l;return f&&await this._setSession(f),{session:f,error:null}}return{session:null,error:{message:"Incorrect parameters",status:500}}}async signIn(e){if("provider"in e){const{provider:t}=e,o=`${this.url}/signin/provider/${t}`;return A()&&(window.location.href=o),{providerUrl:o,provider:t,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const{data:t,error:o}=await this.api.signInEmailPassword(e);if(o)return{session:null,mfa:null,error:o};if(!t)return{session:null,mfa:null,error:{message:"Incorrect Data",status:500}};const{session:l,mfa:h}=t;return l&&await this._setSession(l),{session:l,mfa:h,error:null}}if("email"in e&&!("otp"in e)){const{error:t}=await this.api.signInPasswordlessEmail(e);return t?{session:null,mfa:null,error:t}:{session:null,mfa:null,error:null}}if("phoneNumber"in e&&!("otp"in e)){const{error:t}=await this.api.signInPasswordlessSms(e);return t?{session:null,mfa:null,error:t}:{session:null,mfa:null,error:null}}if("otp"in e){const{data:t,error:o}=await this.api.signInPasswordlessSmsOtp(e);if(o)return{session:null,mfa:null,error:o};if(!t)return{session:null,mfa:null,error:{message:"Incorrect data",status:500}};const{session:l,mfa:h}=t;return l&&await this._setSession(l),{session:l,mfa:h,error:null}}return{session:null,mfa:null,error:{message:"Incorrect parameters",status:500}}}async signOut(e){const t=await this._getItem(T);this._clearSession();const{error:o}=await this.api.signOut({refreshToken:t,all:e==null?void 0:e.all});return{error:o}}async verifyEmail(e){return await this.api.verifyEmail(e)}async resetPassword(e){const{error:t}=await this.api.resetPassword(e);return{error:t}}async changePassword(e){const{error:t}=await this.api.changePassword(e);return{error:t}}async sendVerificationEmail(e){const{error:t}=await this.api.sendVerificationEmail(e);return{error:t}}async changeEmail(e){const{error:t}=await this.api.changeEmail(e);return{error:t}}async deanonymize(e){const{error:t}=await this.api.deanonymize(e);return{error:t}}onTokenChanged(e){this.onTokenChangedFunctions.push(e);const t=this.onTokenChangedFunctions.length-1;return()=>{try{this.onTokenChangedFunctions[t]=()=>{}}catch{console.warn("Unable to unsubscribe onTokenChanged function. Maybe the functions is already unsubscribed?")}}}onAuthStateChanged(e){this.onAuthChangedFunctions.push(e);const t=this.onAuthChangedFunctions.length-1;return()=>{try{this.onAuthChangedFunctions[t]=()=>{}}catch{console.warn("Unable to unsubscribe onAuthStateChanged function. Maybe you already did?")}}}isAuthenticated(){return this.session!==null}async isAuthenticatedAsync(){return new Promise(e=>{if(!this.initAuthLoading)e(this.isAuthenticated());else{const t=this.onAuthStateChanged((o,l)=>{e(o==="SIGNED_IN"),t()})}})}getAuthenticationStatus(){return this.initAuthLoading?{isAuthenticated:!1,isLoading:!0}:{isAuthenticated:this.session!==null,isLoading:!1}}getJWTToken(){return this.getAccessToken()}getAccessToken(){if(!!this.session)return this.session.accessToken}async refreshSession(e){const t=e||await this._getItem(T);return t||console.warn("no refresh token found. No way of refreshing session"),this._refreshTokens(t)}getSession(){return this.session}getUser(){return this.session?this.session.user:null}async _setItem(e,t){if(typeof t!="string"){console.error('value is not of type "string"');return}switch(this.clientStorageType){case"web":if(typeof this.clientStorage.setItem!="function"){console.error("this.clientStorage.setItem is not a function");break}this.clientStorage.setItem(e,t);break;case"custom":case"react-native":if(typeof this.clientStorage.setItem!="function"){console.error("this.clientStorage.setItem is not a function");break}await this.clientStorage.setItem(e,t);break;case"capacitor":if(typeof this.clientStorage.set!="function"){console.error("this.clientStorage.set is not a function");break}await this.clientStorage.set({key:e,value:t});break;case"expo-secure-storage":if(typeof this.clientStorage.setItemAsync!="function"){console.error("this.clientStorage.setItemAsync is not a function");break}this.clientStorage.setItemAsync(e,t);break}}async _getItem(e){switch(this.clientStorageType){case"web":if(typeof this.clientStorage.getItem!="function"){console.error("this.clientStorage.getItem is not a function");break}return this.clientStorage.getItem(e);case"custom":case"react-native":if(typeof this.clientStorage.getItem!="function"){console.error("this.clientStorage.getItem is not a function");break}return await this.clientStorage.getItem(e);case"capacitor":if(typeof this.clientStorage.get!="function"){console.error("this.clientStorage.get is not a function");break}return(await this.clientStorage.get({key:e})).value;case"expo-secure-storage":if(typeof this.clientStorage.getItemAsync!="function"){console.error("this.clientStorage.getItemAsync is not a function");break}return this.clientStorage.getItemAsync(e);default:return""}return""}async _removeItem(e){switch(this.clientStorageType){case"web":if(typeof this.clientStorage.removeItem!="function"){console.error("this.clientStorage.removeItem is not a function");break}return void this.clientStorage.removeItem(e);case"custom":case"react-native":if(typeof this.clientStorage.removeItem!="function"){console.error("this.clientStorage.removeItem is not a function");break}return void this.clientStorage.removeItem(e);case"capacitor":if(typeof this.clientStorage.remove!="function"){console.error("this.clientStorage.remove is not a function");break}await this.clientStorage.remove({key:e});break;case"expo-secure-storage":if(typeof this.clientStorage.deleteItemAsync!="function"){console.error("this.clientStorage.deleteItemAsync is not a function");break}this.clientStorage.deleteItemAsync(e);break}}_autoLogin(e){!A()||this._refreshTokens(e)}async _refreshTokens(e){const t=e||await this._getItem(T);if(!t){setTimeout(async()=>{await this._clearSession()},0);return}try{const{session:o,error:l}=await this.api.refreshToken({refreshToken:t});if(l&&l.status===401){await this._clearSession();return}if(!o)throw new Error("Invalid session data");await this._setSession(o),this.tokenChanged()}catch{}}tokenChanged(){for(const e of this.onTokenChangedFunctions)e(this.session)}authStateChanged({event:e,session:t}){e==="SIGNED_IN"&&t?this.api.setAccessToken(t.accessToken):this.api.setAccessToken(void 0);for(const o of this.onAuthChangedFunctions)o(e,t)}async _clearSession(){const{isLoading:e,isAuthenticated:t}=this.getAuthenticationStatus();this.session=null,this.initAuthLoading=!1,await this._removeItem(T),(e||t)&&(clearInterval(this.refreshInterval),clearInterval(this.refreshSleepCheckInterval),this.authStateChanged({event:"SIGNED_OUT",session:null}))}async _setSession(e){const{isAuthenticated:t}=this.getAuthenticationStatus();if(this.session=e,await this._setItem(T,e.refreshToken),this.autoRefreshToken&&!t){const o=e.accessTokenExpiresIn,l=this.refreshIntervalTime?this.refreshIntervalTime:Math.max(1,o-1);this.refreshInterval=setInterval(async()=>{const h=await this._getItem(T);await this._refreshTokens(h)},l*1e3),this.refreshIntervalSleepCheckLastSample=Date.now(),this.refreshSleepCheckInterval=setInterval(async()=>{if(Date.now()-this.refreshIntervalSleepCheckLastSample>=this.sampleRate*2){const h=await this._getItem(T);await this._refreshTokens(h)}this.refreshIntervalSleepCheckLastSample=Date.now()},this.sampleRate),this.authStateChanged({event:"SIGNED_IN",session:this.session})}this.initAuthLoading=!1}}const te=require("axios");class re{constructor({url:e}){this.url=e,this.httpClient=te.create({baseURL:this.url})}async upload(e){try{return{fileMetadata:(await this.httpClient.post("/files",e.file,{headers:w(w({},this.generateUploadHeaders(e)),this.generateAuthHeaders())})).data,error:null}}catch(t){return{fileMetadata:null,error:t}}}async getPresignedUrl(e){try{const{fileId:t}=e;return{presignedUrl:(await this.httpClient.get(`/files/${t}/presignedurl`,{headers:w({},this.generateAuthHeaders())})).data,error:null}}catch(t){return{presignedUrl:null,error:t}}}async delete(e){try{const{fileId:t}=e;return await this.httpClient.delete(`/files/${t}`,{headers:w({},this.generateAuthHeaders())}),{error:null}}catch(t){return{error:t}}}setAccessToken(e){this.accessToken=e}generateUploadHeaders(e){const{bucketId:t,name:o,id:l}=e,h={};return t&&(h["x-nhost-bucket-id"]=t),l&&(h["x-nhost-file-id"]=l),o&&(h["x-nhost-file-name"]=o),h}generateAuthHeaders(){return this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:null}}class ne{constructor({url:e}){this.url=e,this.api=new re({url:e})}async upload(e){const t=new FormData;t.append("file",e.file);const{fileMetadata:o,error:l}=await this.api.upload(k(w({},e),{file:t}));return l?{fileMetadata:null,error:l}:o?{fileMetadata:o,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){const{fileId:t}=e;return`${this.url}/files/${t}`}async getPresignedUrl(e){const{presignedUrl:t,error:o}=await this.api.getPresignedUrl(e);return o?{presignedUrl:null,error:o}:t?{presignedUrl:t,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:t}=await this.api.delete(e);return t?{error:t}:{error:null}}setAccessToken(e){this.api.setAccessToken(e)}}const se=require("axios");class ae{constructor(e){const{url:t}=e;this.accessToken=null,this.instance=se.create({baseURL:t})}async call(e,t,o){const l=w(w({},this.generateAccessTokenHeaders()),o==null?void 0:o.headers);let h;try{h=await this.instance.post(e,t,k(w({},o),{headers:l}))}catch(f){if(f instanceof Error)return{res:null,error:f}}return h?{res:h,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}}const ie=require("axios");class oe{constructor(e){const{url:t}=e;this.url=t,this.accessToken=null,this.instance=ie.create({baseURL:t})}async request(e,t,o){const l=w(w({},o==null?void 0:o.headers),this.generateAccessTokenHeaders()),h="";let f;try{f=(await this.instance.post("",{operationName:h||void 0,query:e,variables:t},k(w({},o),{headers:l}))).data}catch(m){return m instanceof Error?{data:null,error:m}:(console.error(m),{data:null,error:new Error("Unable to get do GraphQL request")})}return typeof f!="object"||Array.isArray(f)||f===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:(f=f,f.errors?{data:null,error:f.errors}:{data:f.data,error:null})}getUrl(){return this.url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}}class L{constructor(e){if(!e.backendUrl)throw new Error("Please specify a `backendUrl`. Docs: [todo]!");const{backendUrl:t,refreshIntervalTime:o,clientStorage:l,clientStorageType:h,autoRefreshToken:f,autoLogin:m}=e;this.auth=new ee({url:`${t}/v1/auth`,refreshIntervalTime:o,clientStorage:l,clientStorageType:h,autoRefreshToken:f,autoLogin:m}),this.storage=new ne({url:`${t}/v1/storage`}),this.functions=new ae({url:`${t}/v1/functions`}),this.graphql=new oe({url:`${t}/v1/graphql`}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),this.auth.onAuthStateChanged((y,p)=>{this.storage.setAccessToken(p==null?void 0:p.accessToken),this.functions.setAccessToken(p==null?void 0:p.accessToken),this.graphql.setAccessToken(p==null?void 0:p.accessToken)}),this.auth.onTokenChanged(y=>{this.storage.setAccessToken(y==null?void 0:y.accessToken),this.functions.setAccessToken(y==null?void 0:y.accessToken),this.graphql.setAccessToken(y==null?void 0:y.accessToken)})}}const ce=i=>new L(i);exports.NhostClient=L;exports.createClient=ce;
1
+ var N=Object.create;var h=Object.defineProperty,b=Object.defineProperties,w=Object.getOwnPropertyDescriptor,P=Object.getOwnPropertyDescriptors,S=Object.getOwnPropertyNames,f=Object.getOwnPropertySymbols,G=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable;var m=(t,e,r)=>e in t?h(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i=(t,e)=>{for(var r in e||(e={}))A.call(e,r)&&m(t,r,e[r]);if(f)for(var r of f(e))U.call(e,r)&&m(t,r,e[r]);return t},p=(t,e)=>b(t,P(e)),C=t=>h(t,"__esModule",{value:!0});var H=(t,e)=>{for(var r in e)h(t,r,{get:e[r],enumerable:!0})},d=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of S(e))!A.call(t,a)&&(r||a!=="default")&&h(t,a,{get:()=>e[a],enumerable:!(n=w(e,a))||n.enumerable});return t},q=(t,e)=>d(C(h(t!=null?N(G(t)):{},"default",!e&&t&&t.__esModule?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t),E=(t=>(e,r)=>t&&t.get(e)||(r=d(C({}),e,1),t&&t.set(e,r),r))(typeof WeakMap!="undefined"?new WeakMap:0);var I={};H(I,{NhostClient:()=>T,createClient:()=>F});var v=require("@nhost/hasura-auth-js"),y=require("@nhost/hasura-storage-js");var x=q(require("axios")),k=class{constructor(e){let{url:r}=e;this.accessToken=null,this.instance=x.default.create({baseURL:r})}async call(e,r,n){let a=i(i({},this.generateAccessTokenHeaders()),n==null?void 0:n.headers),u;try{u=await this.instance.post(e,r,p(i({},n),{headers:a}))}catch(s){if(s instanceof Error)return{res:null,error:s}}return u?{res:u,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}};var R=q(require("axios")),g=class{constructor(e){let{url:r}=e;this.url=r,this.accessToken=null,this.instance=R.default.create({baseURL:r})}async request(e,r,n){let a=i(i({},n==null?void 0:n.headers),this.generateAccessTokenHeaders()),u="",s;try{s=(await this.instance.post("",{operationName:u||void 0,query:e,variables:r},p(i({},n),{headers:a}))).data}catch(l){return l instanceof Error?{data:null,error:l}:(console.error(l),{data:null,error:new Error("Unable to get do GraphQL request")})}return typeof s!="object"||Array.isArray(s)||s===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:(s=s,s.errors?{data:null,error:s.errors}:{data:s.data,error:null})}getUrl(){return this.url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}};var T=class{constructor(e){if(!e.backendUrl)throw new Error("Please specify a `backendUrl`. Docs: [todo]!");let{backendUrl:r,refreshIntervalTime:n,clientStorage:a,clientStorageType:u,autoRefreshToken:s,autoLogin:l}=e;this.auth=new v.HasuraAuthClient({url:`${r}/v1/auth`,refreshIntervalTime:n,clientStorage:a,clientStorageType:u,autoRefreshToken:s,autoLogin:l}),this.storage=new y.HasuraStorageClient({url:`${r}/v1/storage`}),this.functions=new k({url:`${r}/v1/functions`}),this.graphql=new g({url:`${r}/v1/graphql`}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),this.auth.onAuthStateChanged((o,c)=>{this.storage.setAccessToken(c==null?void 0:c.accessToken),this.functions.setAccessToken(c==null?void 0:c.accessToken),this.graphql.setAccessToken(c==null?void 0:c.accessToken)}),this.auth.onTokenChanged(o=>{this.storage.setAccessToken(o==null?void 0:o.accessToken),this.functions.setAccessToken(o==null?void 0:o.accessToken),this.graphql.setAccessToken(o==null?void 0:o.accessToken)})}};var F=t=>new T(t);module.exports=E(I);0&&(module.exports={NhostClient,createClient});
2
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/core/nhost-client.ts", "../src/clients/functions.ts", "../src/clients/graphql.ts"],
4
+ "sourcesContent": ["import { NhostClient, NhostClientConstructorParams } from './core'\n\nconst createClient = (config: NhostClientConstructorParams) => new NhostClient(config)\n\nexport * from './core'\nexport { createClient }\n", "import { ClientStorage, ClientStorageType, HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { NhostFunctionsClient } from '../clients/functions'\nimport { NhostGraphqlClient } from '../clients/graphql'\n\nexport interface NhostClientConstructorParams {\n backendUrl: string\n refreshIntervalTime?: number\n clientStorage?: ClientStorage\n clientStorageType?: ClientStorageType\n autoRefreshToken?: boolean\n autoLogin?: boolean\n}\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n\n /**\n * Nhost Client\n *\n * @example\n * const nhost = new NhostClient({ url });\n *\n * @docs https://docs.nhost.io/TODO\n */\n constructor(params: NhostClientConstructorParams) {\n if (!params.backendUrl) throw new Error('Please specify a `backendUrl`. Docs: [todo]!')\n\n const {\n backendUrl,\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoLogin\n } = params\n\n this.auth = new HasuraAuthClient({\n url: `${backendUrl}/v1/auth`,\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoLogin\n })\n\n this.storage = new HasuraStorageClient({\n url: `${backendUrl}/v1/storage`\n })\n\n this.functions = new NhostFunctionsClient({\n url: `${backendUrl}/v1/functions`\n })\n\n this.graphql = new NhostGraphqlClient({\n url: `${backendUrl}/v1/graphql`\n })\n\n // set current token if token is already accessable\n this.storage.setAccessToken(this.auth.getAccessToken())\n this.functions.setAccessToken(this.auth.getAccessToken())\n this.graphql.setAccessToken(this.auth.getAccessToken())\n\n // update access token for clients\n this.auth.onAuthStateChanged((_event, session) => {\n this.storage.setAccessToken(session?.accessToken)\n this.functions.setAccessToken(session?.accessToken)\n this.graphql.setAccessToken(session?.accessToken)\n })\n\n // update access token for clients\n this.auth.onTokenChanged((session) => {\n this.storage.setAccessToken(session?.accessToken)\n this.functions.setAccessToken(session?.accessToken)\n this.graphql.setAccessToken(session?.accessToken)\n })\n }\n}\n", "import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\n\nimport { FunctionCallResponse } from '../types'\nexport interface NhostFunctionsConstructorParams {\n url: string\n}\n\nexport class NhostFunctionsClient {\n private instance: AxiosInstance\n private accessToken: string | null\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url } = params\n\n this.accessToken = null\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n async call(url: string, data: any, config?: AxiosRequestConfig): Promise<FunctionCallResponse> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post(url, data, { ...config, headers })\n } catch (error) {\n if (error instanceof Error) {\n return { res: null, error }\n }\n }\n\n if (!res) {\n return {\n res: null,\n error: new Error('Unable to make post request to funtion')\n }\n }\n\n return { res, error: null }\n }\n\n setAccessToken(accessToken: string | undefined) {\n if (!accessToken) {\n this.accessToken = null\n return\n }\n\n this.accessToken = accessToken\n }\n\n private generateAccessTokenHeaders(): { Authorization: string } | undefined {\n if (!this.accessToken) {\n return\n }\n\n // eslint-disable-next-line consistent-return\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n}\n", "import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\n\nimport { GraphqlRequestResponse, GraphqlResponse } from '../types'\n\nexport interface NhostGraphqlConstructorParams {\n url: string\n}\n\nexport class NhostGraphqlClient {\n private url: string\n private instance: AxiosInstance\n private accessToken: string | null\n\n constructor(params: NhostGraphqlConstructorParams) {\n const { url } = params\n\n this.url = url\n this.accessToken = null\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n async request(\n document: string,\n variables?: any,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse> {\n // add auth headers if any\n const headers = {\n ...config?.headers,\n ...this.generateAccessTokenHeaders()\n }\n\n const operationName = ''\n\n let responseData\n try {\n const res = await this.instance.post(\n '',\n {\n operationName: operationName || undefined,\n query: document,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n variables\n },\n { ...config, headers }\n )\n\n responseData = res.data\n } catch (error) {\n if (error instanceof Error) {\n return { data: null, error }\n }\n console.error(error)\n return {\n data: null,\n error: new Error('Unable to get do GraphQL request')\n }\n }\n\n if (typeof responseData !== 'object' || Array.isArray(responseData) || responseData === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n responseData = responseData as GraphqlResponse\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n return { data: responseData.data, error: null }\n }\n\n getUrl(): string {\n return this.url\n }\n\n setAccessToken(accessToken: string | undefined) {\n if (!accessToken) {\n this.accessToken = null\n return\n }\n\n this.accessToken = accessToken\n }\n\n private generateAccessTokenHeaders() {\n if (!this.accessToken) {\n return\n }\n\n // eslint-disable-next-line consistent-return\n return {\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