@nhost/nhost-js 0.3.5 → 0.3.9

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -5
  3. package/dist/{cjs/clients → clients}/functions.d.ts +3 -3
  4. package/dist/{esm/clients → clients}/graphql.d.ts +3 -3
  5. package/dist/{cjs/core → core}/index.d.ts +0 -0
  6. package/dist/{esm/core → core}/nhost-client.d.ts +3 -12
  7. package/dist/index.cjs.js +1 -0
  8. package/dist/{cjs/index.d.ts → index.d.ts} +1 -2
  9. package/dist/index.es.js +1293 -0
  10. package/dist/{cjs/types.d.ts → types.d.ts} +6 -6
  11. package/package.json +39 -33
  12. package/src/index.ts +6 -0
  13. package/dist/cjs/clients/functions.js +0 -113
  14. package/dist/cjs/clients/functions.js.map +0 -1
  15. package/dist/cjs/clients/graphql.d.ts +0 -15
  16. package/dist/cjs/clients/graphql.js +0 -133
  17. package/dist/cjs/clients/graphql.js.map +0 -1
  18. package/dist/cjs/core/index.js +0 -14
  19. package/dist/cjs/core/index.js.map +0 -1
  20. package/dist/cjs/core/nhost-client.d.ts +0 -28
  21. package/dist/cjs/core/nhost-client.js +0 -59
  22. package/dist/cjs/core/nhost-client.js.map +0 -1
  23. package/dist/cjs/index.js +0 -20
  24. package/dist/cjs/index.js.map +0 -1
  25. package/dist/cjs/types.js +0 -3
  26. package/dist/cjs/types.js.map +0 -1
  27. package/dist/esm/clients/functions.d.ts +0 -13
  28. package/dist/esm/clients/functions.js +0 -107
  29. package/dist/esm/clients/functions.js.map +0 -1
  30. package/dist/esm/clients/graphql.js +0 -127
  31. package/dist/esm/clients/graphql.js.map +0 -1
  32. package/dist/esm/core/index.d.ts +0 -1
  33. package/dist/esm/core/index.js +0 -2
  34. package/dist/esm/core/index.js.map +0 -1
  35. package/dist/esm/core/nhost-client.js +0 -56
  36. package/dist/esm/core/nhost-client.js.map +0 -1
  37. package/dist/esm/index.d.ts +0 -5
  38. package/dist/esm/index.js +0 -7
  39. package/dist/esm/index.js.map +0 -1
  40. package/dist/esm/types.d.ts +0 -19
  41. package/dist/esm/types.js +0 -2
  42. package/dist/esm/types.js.map +0 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Nhost
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -25,11 +25,11 @@ yarn add @nhost/nhost-js
25
25
  ### Initialize
26
26
 
27
27
  ```js
28
- import { NhostClient } from '@nhost/nhost-js';
28
+ import { NhostClient } from '@nhost/nhost-js'
29
29
 
30
30
  const nhost = new NhostClient({
31
- backendUrl: 'https://xxx.nhost.run',
32
- });
31
+ backendUrl: 'https://xxx.nhost.run'
32
+ })
33
33
  ```
34
34
 
35
35
  ## Features
@@ -52,5 +52,4 @@ Access Nhost Functions methods via `nhost.functions`.
52
52
 
53
53
  ## Documentation
54
54
 
55
- [Coming soon](https://docs.nhost.io)
56
-
55
+ [https://docs.nhost.io/reference/sdk](https://docs.nhost.io/reference/sdk)
@@ -1,8 +1,8 @@
1
- import { AxiosRequestConfig } from 'axios';
1
+ import type { AxiosRequestConfig } from 'axios';
2
2
  import { FunctionCallResponse } from '../types';
3
- export declare type NhostFunctionsConstructorParams = {
3
+ export interface NhostFunctionsConstructorParams {
4
4
  url: string;
5
- };
5
+ }
6
6
  export declare class NhostFunctionsClient {
7
7
  private instance;
8
8
  private accessToken;
@@ -1,8 +1,8 @@
1
- import { AxiosRequestConfig } from 'axios';
1
+ import type { AxiosRequestConfig } from 'axios';
2
2
  import { GraphqlRequestResponse } from '../types';
3
- export declare type NhostGraphqlConstructorParams = {
3
+ export interface NhostGraphqlConstructorParams {
4
4
  url: string;
5
- };
5
+ }
6
6
  export declare class NhostGraphqlClient {
7
7
  private url;
8
8
  private instance;
File without changes
@@ -1,28 +1,19 @@
1
- import { HasuraAuthClient } from '@nhost/hasura-auth-js';
1
+ import { ClientStorage, ClientStorageType, HasuraAuthClient } from '@nhost/hasura-auth-js';
2
2
  import { HasuraStorageClient } from '@nhost/hasura-storage-js';
3
- import { ClientStorage, ClientStorageType } from '@nhost/hasura-auth-js';
4
3
  import { NhostFunctionsClient } from '../clients/functions';
5
4
  import { NhostGraphqlClient } from '../clients/graphql';
6
- export declare type NhostClientConstructorParams = {
5
+ export interface NhostClientConstructorParams {
7
6
  backendUrl: string;
8
7
  refreshIntervalTime?: number;
9
8
  clientStorage?: ClientStorage;
10
9
  clientStorageType?: ClientStorageType;
11
10
  autoRefreshToken?: boolean;
12
11
  autoLogin?: boolean;
13
- };
12
+ }
14
13
  export declare class NhostClient {
15
14
  auth: HasuraAuthClient;
16
15
  storage: HasuraStorageClient;
17
16
  functions: NhostFunctionsClient;
18
17
  graphql: NhostGraphqlClient;
19
- /**
20
- * Nhost Client
21
- *
22
- * @example
23
- * const nhost = new NhostClient({ url });
24
- *
25
- * @docs https://docs.nhost.io/TODO
26
- */
27
18
  constructor(params: NhostClientConstructorParams);
28
19
  }
@@ -0,0 +1 @@
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,5 +1,4 @@
1
- import { NhostClient } from '.';
2
- import { NhostClientConstructorParams } from '.';
1
+ import { NhostClient, NhostClientConstructorParams } from './core';
3
2
  declare const createClient: (config: NhostClientConstructorParams) => NhostClient;
4
3
  export * from './core';
5
4
  export { createClient };