@nhost/nhost-js 1.1.12 → 1.2.0

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
@@ -7,22 +7,22 @@
7
7
  <a href="LICENSE">
8
8
  <img src="https://img.shields.io/badge/license-MIT-yellow.svg" alt="license: MIT" />
9
9
  </a>
10
- <a href="https://prettier.io">
11
- <img src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg" alt="code style: prettier" />
12
- </a>
13
10
  </p>
14
11
 
15
- ## Get Started
12
+ ## Documentation
13
+
14
+ [Reference documentation](https://docs.nhost.io/reference/javascript)
16
15
 
17
- ### Install
16
+ ## Install
18
17
 
19
18
  ```
20
19
  npm install @nhost/nhost-js
20
+
21
21
  # or yarn
22
22
  yarn add @nhost/nhost-js
23
23
  ```
24
24
 
25
- ### Initialize
25
+ ### Initialise
26
26
 
27
27
  ```js
28
28
  import { NhostClient } from '@nhost/nhost-js'
@@ -50,6 +50,3 @@ Access Nhost Storage methods using `nhost.storage`.
50
50
 
51
51
  Access Nhost Functions methods via `nhost.functions`.
52
52
 
53
- ## Documentation
54
-
55
- [https://docs.nhost.io/reference/javascript](https://docs.nhost.io/reference/javascript)
@@ -1,7 +1,14 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
2
  import { FunctionCallResponse } from '../types';
3
3
  export interface NhostFunctionsConstructorParams {
4
+ /**
5
+ * Serverless Functions endpoint.
6
+ */
4
7
  url: string;
8
+ /**
9
+ * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.
10
+ */
11
+ adminSecret?: string;
5
12
  }
6
13
  /**
7
14
  * @alias Functions
@@ -9,6 +16,7 @@ export interface NhostFunctionsConstructorParams {
9
16
  export declare class NhostFunctionsClient {
10
17
  private instance;
11
18
  private accessToken;
19
+ private adminSecret?;
12
20
  constructor(params: NhostFunctionsConstructorParams);
13
21
  /**
14
22
  * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.
@@ -1 +1 @@
1
- {"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["functions.ts"],"names":[],"mappings":"AAAA,OAAc,EAAiB,kBAAkB,EAAiB,MAAM,OAAO,CAAA;AAE/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,MAAM,WAAW,+BAA+B;IAC9C,GAAG,EAAE,MAAM,CAAA;CACZ;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAe;IAC/B,OAAO,CAAC,WAAW,CAAe;gBAEtB,MAAM,EAAE,+BAA+B;IASnD;;;;;;;;;OASG;IACG,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,GAAG,EAC7B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,CAAC,EACP,MAAM,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAyBnC;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,OAAO,CAAC,0BAA0B;CAUnC"}
1
+ {"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["functions.ts"],"names":[],"mappings":"AAAA,OAAc,EAAiB,kBAAkB,EAAsC,MAAM,OAAO,CAAA;AAEpG,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,MAAM,WAAW,+BAA+B;IAC9C;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAe;IAC/B,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;gBAEhB,MAAM,EAAE,+BAA+B;IAUnD;;;;;;;;;OASG;IACG,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,GAAG,EAC7B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,CAAC,EACP,MAAM,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAyBnC;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,OAAO,CAAC,0BAA0B;CAanC"}
@@ -1,8 +1,15 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
- import type { DocumentNode } from 'graphql';
2
+ import { DocumentNode } from 'graphql';
3
3
  import { GraphqlRequestResponse } from '../types';
4
4
  export interface NhostGraphqlConstructorParams {
5
+ /**
6
+ * GraphQL endpoint.
7
+ */
5
8
  url: string;
9
+ /**
10
+ * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.
11
+ */
12
+ adminSecret?: string;
6
13
  }
7
14
  /**
8
15
  * @alias GraphQL
@@ -11,6 +18,7 @@ export declare class NhostGraphqlClient {
11
18
  private url;
12
19
  private instance;
13
20
  private accessToken;
21
+ private adminSecret?;
14
22
  constructor(params: NhostGraphqlConstructorParams);
15
23
  /**
16
24
  * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage in your app we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).
@@ -1 +1 @@
1
- {"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["graphql.ts"],"names":[],"mappings":"AAAA,OAAc,EAAiB,kBAAkB,EAAE,MAAM,OAAO,CAAA;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAG3C,OAAO,EAAE,sBAAsB,EAAmB,MAAM,UAAU,CAAA;AAElE,MAAM,WAAW,6BAA6B;IAC5C,GAAG,EAAE,MAAM,CAAA;CACZ;AAED;;GAEG;AACH,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,GAAG,CAAQ;IACnB,OAAO,CAAC,QAAQ,CAAe;IAC/B,OAAO,CAAC,WAAW,CAAe;gBAEtB,MAAM,EAAE,6BAA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hB;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,OAAO,CAAC,0BAA0B;CAanC"}
@@ -7,12 +7,18 @@ export interface NhostClientConstructorParams extends Omit<NhostAuthConstructorP
7
7
  * Nhost backend URL.
8
8
  */
9
9
  backendUrl: string;
10
+ /**
11
+ * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all
12
+ * GraphQL, Storage, and Serverless Functions requests.
13
+ */
14
+ adminSecret?: string;
10
15
  }
11
16
  export declare class NhostClient {
12
17
  auth: HasuraAuthClient;
13
18
  storage: HasuraStorageClient;
14
19
  functions: NhostFunctionsClient;
15
20
  graphql: NhostGraphqlClient;
21
+ readonly devTools?: boolean;
16
22
  /**
17
23
  * Nhost Client
18
24
  *
@@ -21,6 +27,6 @@ export declare class NhostClient {
21
27
  *
22
28
  * @docs https://docs.nhost.io/reference/javascript
23
29
  */
24
- constructor({ backendUrl, refreshIntervalTime, clientStorageGetter, clientStorageSetter, clientStorage, clientStorageType, autoRefreshToken, autoSignIn, start }: NhostClientConstructorParams);
30
+ constructor({ backendUrl, refreshIntervalTime, clientStorageGetter, clientStorageSetter, clientStorage, clientStorageType, autoRefreshToken, autoSignIn, adminSecret, devTools, start }: NhostClientConstructorParams);
25
31
  }
26
32
  //# sourceMappingURL=nhost-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"nhost-client.d.ts","sourceRoot":"","sources":["nhost-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAA;AACpF,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAE9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAEvD,MAAM,WAAW,4BAA6B,SAAQ,IAAI,CAAC,0BAA0B,EAAE,KAAK,CAAC;IAC3F;;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package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var v=Object.defineProperty,y=Object.defineProperties;var w=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable;var d=(r,e,t)=>e in r?v(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,o=(r,e)=>{for(var t in e||(e={}))C.call(e,t)&&d(r,t,e[t]);if(k)for(var t of k(e))N.call(e,t)&&d(r,t,e[t]);return r},l=(r,e)=>y(r,w(e));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var E=require("@nhost/hasura-auth-js"),S=require("@nhost/hasura-storage-js"),H=require("axios"),_=require("graphql/language/printer");function $(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}var p=$(H);class A{constructor(e){const{url:t}=e;this.accessToken=null,this.instance=p.default.create({baseURL:t})}async call(e,t,s){const u=o(o({},this.generateAccessTokenHeaders()),s==null?void 0:s.headers);let a;try{a=await this.instance.post(e,t,l(o({},s),{headers:u}))}catch(i){if(i instanceof Error)return{res:null,error:i}}return a?{res:a,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}`}}}class f{constructor(e){const{url:t}=e;this.url=t,this.accessToken=null,this.instance=p.default.create({baseURL:t})}async request(e,t,s){const u=o(o({},s==null?void 0:s.headers),this.generateAccessTokenHeaders());try{const a="",h=(await this.instance.post("",{operationName:a||void 0,query:typeof e=="string"?e:_.print(e),variables:t},l(o({},s),{headers:u}))).data,{data:c}=h;return h.errors?{data:null,error:h.errors}:typeof c!="object"||Array.isArray(c)||c===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:c,error:null}}catch(a){return a instanceof Error?{data:null,error:a}:(console.error(a),{data:null,error:new Error("Unable to get do GraphQL request")})}}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 g{constructor({backendUrl:e,refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:u,clientStorage:a,clientStorageType:i,autoRefreshToken:h,autoSignIn:c,start:q=!0}){var T;if(!e)throw new Error("Please specify a `backendUrl`. Docs: [todo]!");this.auth=new E.HasuraAuthClient({url:`${e}/v1/auth`,refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:u,clientStorage:a,clientStorageType:i,autoRefreshToken:h,autoSignIn:c,start:q}),this.storage=new S.HasuraStorageClient({url:`${e}/v1/storage`}),this.functions=new A({url:`${e}/v1/functions`}),this.graphql=new f({url:`${e}/v1/graphql`}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),(T=this.auth.client)==null||T.onStart(()=>{this.auth.onAuthStateChanged((n,j)=>{n==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(n=>{this.storage.setAccessToken(n==null?void 0:n.accessToken),this.functions.setAccessToken(n==null?void 0:n.accessToken),this.graphql.setAccessToken(n==null?void 0:n.accessToken)})})}}const b=r=>new g(r);exports.NhostClient=g;exports.NhostFunctionsClient=A;exports.NhostGraphqlClient=f;exports.createClient=b;
1
+ "use strict";var S=Object.defineProperty,w=Object.defineProperties;var C=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var m=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable;var p=(r,e,t)=>e in r?S(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,o=(r,e)=>{for(var t in e||(e={}))m.call(e,t)&&p(r,t,e[t]);if(k)for(var t of k(e))N.call(e,t)&&p(r,t,e[t]);return r},d=(r,e)=>w(r,C(e));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var E=require("@nhost/hasura-auth-js"),H=require("@nhost/hasura-storage-js"),_=require("axios"),$=require("graphql");function b(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}var A=b(_);class f{constructor(e){const{url:t,adminSecret:s}=e;this.accessToken=null,this.adminSecret=s,this.instance=A.default.create({baseURL:t})}async call(e,t,s){const i=o(o({},this.generateAccessTokenHeaders()),s==null?void 0:s.headers);let a;try{a=await this.instance.post(e,t,d(o({},s),{headers:i}))}catch(h){if(h instanceof Error)return{res:null,error:h}}return a?{res:a,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(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}class g{constructor(e){const{url:t,adminSecret:s}=e;this.url=t,this.accessToken=null,this.adminSecret=s,this.instance=A.default.create({baseURL:t})}async request(e,t,s){const i=o(o({},this.generateAccessTokenHeaders()),s==null?void 0:s.headers);try{const a="",u=(await this.instance.post("",{operationName:a||void 0,query:typeof e=="string"?e:$.print(e),variables:t},d(o({},s),{headers:i}))).data,{data:c}=u;return u.errors?{data:null,error:u.errors}:typeof c!="object"||Array.isArray(c)||c===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:c,error:null}}catch(a){return a instanceof Error?{data:null,error:a}:(console.error(a),{data:null,error:new Error("Unable to get do GraphQL request")})}}getUrl(){return this.url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}class q{constructor({backendUrl:e,refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:i,clientStorage:a,clientStorageType:h,autoRefreshToken:u,autoSignIn:c,adminSecret:l,devTools:v,start:y=!0}){var T;if(!e)throw new Error("Please specify a `backendUrl`. Docs: [todo]!");this.auth=new E.HasuraAuthClient({url:`${e}/v1/auth`,refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:i,clientStorage:a,clientStorageType:h,autoRefreshToken:u,autoSignIn:c,start:y}),this.storage=new H.HasuraStorageClient({url:`${e}/v1/storage`,adminSecret:l}),this.functions=new f({url:`${e}/v1/functions`,adminSecret:l}),this.graphql=new g({url:`${e}/v1/graphql`,adminSecret:l}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),(T=this.auth.client)==null||T.onStart(()=>{this.auth.onAuthStateChanged((n,x)=>{n==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(n=>{this.storage.setAccessToken(n==null?void 0:n.accessToken),this.functions.setAccessToken(n==null?void 0:n.accessToken),this.graphql.setAccessToken(n==null?void 0:n.accessToken)})}),this.devTools=v}}const j=r=>new q(r);exports.NhostClient=q;exports.NhostFunctionsClient=f;exports.NhostGraphqlClient=g;exports.createClient=j;
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/clients/functions.ts","../src/clients/graphql.ts","../src/core/nhost-client.ts","../src/index.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'\n\nimport { FunctionCallResponse } from '../types'\nexport interface NhostFunctionsConstructorParams {\n url: string\n}\n\n/**\n * @alias Functions\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 /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: AxiosRequestConfig\n ): Promise<FunctionCallResponse<T>> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(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 /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\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'\nimport type { DocumentNode } from 'graphql'\nimport { print } from 'graphql/language/printer'\n\nimport { GraphqlRequestResponse, GraphqlResponse } from '../types'\n\nexport interface NhostGraphqlConstructorParams {\n url: string\n}\n\n/**\n * @alias GraphQL\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 /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage in your app we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n ...config?.headers,\n ...this.generateAccessTokenHeaders()\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<GraphqlResponse<T>>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n return { data, error: null }\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\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/set-access-token\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 {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n}\n","import { HasuraAuthClient, NhostAuthConstructorParams } 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 extends Omit<NhostAuthConstructorParams, 'url'> {\n /**\n * Nhost backend URL.\n */\n backendUrl: string\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/reference/javascript\n */\n constructor({\n backendUrl,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start = true\n }: NhostClientConstructorParams) {\n if (!backendUrl) throw new Error('Please specify a `backendUrl`. Docs: [todo]!')\n this.auth = new HasuraAuthClient({\n url: `${backendUrl}/v1/auth`,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start\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 this.auth.client?.onStart(() => {\n // * Set access token when signing out\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\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}\n","import { NhostClient, NhostClientConstructorParams } from './core'\n\nconst createClient = (config: NhostClientConstructorParams) => new NhostClient(config)\n\nexport * from './clients'\nexport * from './core'\nexport { createClient }\n"],"names":["axios","print","HasuraAuthClient","HasuraStorageClient"],"mappings":"kvBAUO,MAAM,CAAqB,CAIhC,YAAY,EAAyC,CACnD,KAAM,CAAE,OAAQ,EAEhB,KAAK,YAAc,KACd,KAAA,SAAWA,UAAM,OAAO,CAC3B,QAAS,CAAA,CACV,CACH,MAYM,MACJ,EACA,EACA,EACkC,CAClC,KAAM,GAAU,OACX,KAAK,2BAA2B,GAChC,iBAAQ,SAGT,GAAA,GACA,GAAA,CACI,EAAA,KAAM,MAAK,SAAS,KAA6B,EAAK,EAAM,OAAK,GAAL,CAAa,SAAA,EAAS,QACjF,GACP,GAAI,YAAiB,OACZ,MAAA,CAAE,IAAK,KAAM,QAExB,CAEA,MAAK,GAOE,CAAE,MAAK,MAAO,MANZ,CACL,IAAK,KACL,MAAO,GAAI,OAAM,wCAAwC,CAAA,CAK/D,CAYA,eAAe,EAAiC,CAC9C,GAAI,CAAC,EAAa,CAChB,KAAK,YAAc,KACnB,MACF,CAEA,KAAK,YAAc,CACrB,CAEQ,4BAAoE,CACtE,GAAA,EAAC,KAAK,YAKH,MAAA,CACL,cAAe,UAAU,KAAK,aAAA,CAElC,CACF,CC9EO,MAAM,CAAmB,CAK9B,YAAY,EAAuC,CACjD,KAAM,CAAE,OAAQ,EAEhB,KAAK,IAAM,EACX,KAAK,YAAc,KACd,KAAA,SAAWA,UAAM,OAAO,CAC3B,QAAS,CAAA,CACV,CACH,MAoBM,SACJ,EACA,EACA,EACoC,CAEpC,KAAM,GAAU,OACX,iBAAQ,SACR,KAAK,2BAA2B,GAGjC,GAAA,CACF,KAAM,G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KAAK,KAAK,gBAAgB,EACtD,KAAK,UAAU,eAAe,KAAK,KAAK,gBAAgB,EACxD,KAAK,QAAQ,eAAe,KAAK,KAAK,gBAAgB,EAEjD,QAAA,KAAK,SAAL,QAAa,QAAQ,IAAM,CAE9B,KAAK,KAAK,mBAAmB,CAAC,EAAQ,IAAY,CAChD,AAAI,IAAW,cACR,MAAA,QAAQ,eAAe,MAAS,EAChC,KAAA,UAAU,eAAe,MAAS,EAClC,KAAA,QAAQ,eAAe,MAAS,EACvC,CACD,EAGI,KAAA,KAAK,eAAe,AAAC,GAAY,CAC/B,KAAA,QAAQ,eAAe,iBAAS,WAAW,EAC3C,KAAA,UAAU,eAAe,iBAAS,WAAW,EAC7C,KAAA,QAAQ,eAAe,iBAAS,WAAW,CAAA,CACjD,CAAA,EAEL,CACF,CCpFA,KAAM,GAAe,AAAC,GAAyC,GAAI,GAAY,CAAM"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/clients/functions.ts","../src/clients/graphql.ts","../src/core/nhost-client.ts","../src/index.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'\n\nimport { FunctionCallResponse } from '../types'\nexport interface NhostFunctionsConstructorParams {\n /**\n * Serverless Functions endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: AxiosRequestConfig\n ): Promise<FunctionCallResponse<T>> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(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 /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\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(): AxiosRequestHeaders {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders } from 'axios'\nimport { DocumentNode, print } from 'graphql'\n\nimport { GraphqlRequestResponse, GraphqlResponse } from '../types'\n\nexport interface NhostGraphqlConstructorParams {\n /**\n * GraphQL endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\n/**\n * @alias GraphQL\n */\nexport class NhostGraphqlClient {\n private url: string\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostGraphqlConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage in your app we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<GraphqlResponse<T>>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n return { data, error: null }\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\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/set-access-token\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(): AxiosRequestHeaders {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { HasuraAuthClient, NhostAuthConstructorParams } 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 extends Omit<NhostAuthConstructorParams, 'url'> {\n /**\n * Nhost backend URL.\n */\n backendUrl: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all\n * GraphQL, Storage, and Serverless Functions requests.\n */\n adminSecret?: string\n}\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * const nhost = new NhostClient({ url });\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n backendUrl,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true\n }: NhostClientConstructorParams) {\n if (!backendUrl) throw new Error('Please specify a `backendUrl`. Docs: [todo]!')\n this.auth = new HasuraAuthClient({\n url: `${backendUrl}/v1/auth`,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start\n })\n\n this.storage = new HasuraStorageClient({\n url: `${backendUrl}/v1/storage`,\n adminSecret\n })\n\n this.functions = new NhostFunctionsClient({\n url: `${backendUrl}/v1/functions`,\n adminSecret\n })\n\n this.graphql = new NhostGraphqlClient({\n url: `${backendUrl}/v1/graphql`,\n adminSecret\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 this.auth.client?.onStart(() => {\n // * Set access token when signing out\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\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 this.devTools = devTools\n }\n}\n","import { NhostClient, NhostClientConstructorParams } from './core'\n\nconst createClient = (config: NhostClientConstructorParams) => new NhostClient(config)\n\nexport * from './clients'\nexport * from './core'\nexport { createClient }\n"],"names":["axios","print","HasuraAuthClient","HasuraStorageClient"],"mappings":"iuBAiBO,MAAM,CAAqB,CAKhC,YAAY,EAAyC,CAC7C,KAAA,CAAE,MAAK,eAAgB,EAE7B,KAAK,YAAc,KACnB,KAAK,YAAc,EACd,KAAA,SAAWA,UAAM,OAAO,CAC3B,QAAS,CAAA,CACV,CACH,MAYM,MACJ,EACA,EACA,EACkC,CAClC,KAAM,GAAU,OACX,KAAK,2BAA2B,GAChC,iBAAQ,SAGT,GAAA,GACA,GAAA,CACI,EAAA,KAAM,MAAK,SAAS,KAA6B,EAAK,EAAM,OAAK,GAAL,CAAa,SAAA,EAAS,QACjF,GACP,GAAI,YAAiB,OACZ,MAAA,CAAE,IAAK,KAAM,QAExB,CAEA,MAAK,GAOE,CAAE,MAAK,MAAO,MANZ,CACL,IAAK,KACL,MAAO,GAAI,OAAM,wCAAwC,CAAA,CAK/D,CAYA,eAAe,EAAiC,CAC9C,GAAI,CAAC,EAAa,CAChB,KAAK,YAAc,KACnB,MACF,CAEA,KAAK,YAAc,CACrB,CAEQ,4BAAkD,CACxD,MAAI,MAAK,YACA,CACL,wBAAyB,KAAK,WAAA,E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A,cACA,WACA,QAAQ,IACuB,OAC/B,GAAI,CAAC,EAAkB,KAAA,IAAI,OAAM,8CAA8C,EAC1E,KAAA,KAAO,GAAIC,oBAAiB,CAC/B,IAAK,GAAG,YACR,sBACA,sBACA,sBACA,gBACA,oBACA,mBACA,aACA,OAAA,CACD,EAEI,KAAA,QAAU,GAAIC,uBAAoB,CACrC,IAAK,GAAG,eACR,aAAA,CACD,EAEI,KAAA,UAAY,GAAI,GAAqB,CACxC,IAAK,GAAG,iBACR,aAAA,CACD,EAEI,KAAA,QAAU,GAAI,GAAmB,CACpC,IAAK,GAAG,eACR,aAAA,CACD,EAGD,KAAK,QAAQ,eAAe,KAAK,KAAK,gBAAgB,EACtD,KAAK,UAAU,eAAe,KAAK,KAAK,gBAAgB,EACxD,KAAK,QAAQ,eAAe,KAAK,KAAK,gBAAgB,EAEjD,QAAA,KAAK,SAAL,QAAa,QAAQ,IAAM,CAE9B,KAAK,KAAK,mBAAmB,CAAC,EAAQ,IAAY,CAChD,AAAI,IAAW,cACR,MAAA,QAAQ,eAAe,MAAS,EAChC,KAAA,UAAU,eAAe,MAAS,EAClC,KAAA,QAAQ,eAAe,MAAS,EACvC,CACD,EAGI,KAAA,KAAK,eAAe,AAAC,GAAY,CAC/B,KAAA,QAAQ,eAAe,iBAAS,WAAW,EAC3C,KAAA,UAAU,eAAe,iBAAS,WAAW,EAC7C,KAAA,QAAQ,eAAe,iBAAS,WAAW,CAAA,CACjD,CAAA,GAEH,KAAK,SAAW,CAClB,CACF,CChGA,KAAM,GAAe,AAAC,GAAyC,GAAI,GAAY,CAAM"}
package/dist/index.es.js CHANGED
@@ -20,11 +20,12 @@ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
20
  import { HasuraAuthClient } from "@nhost/hasura-auth-js";
21
21
  import { HasuraStorageClient } from "@nhost/hasura-storage-js";
22
22
  import axios from "axios";
23
- import { print } from "graphql/language/printer";
23
+ import { print } from "graphql";
24
24
  class NhostFunctionsClient {
25
25
  constructor(params) {
26
- const { url } = params;
26
+ const { url, adminSecret } = params;
27
27
  this.accessToken = null;
28
+ this.adminSecret = adminSecret;
28
29
  this.instance = axios.create({
29
30
  baseURL: url
30
31
  });
@@ -55,25 +56,31 @@ class NhostFunctionsClient {
55
56
  this.accessToken = accessToken;
56
57
  }
57
58
  generateAccessTokenHeaders() {
58
- if (!this.accessToken) {
59
- return;
59
+ if (this.adminSecret) {
60
+ return {
61
+ "x-hasura-admin-secret": this.adminSecret
62
+ };
60
63
  }
61
- return {
62
- Authorization: `Bearer ${this.accessToken}`
63
- };
64
+ if (this.accessToken) {
65
+ return {
66
+ Authorization: `Bearer ${this.accessToken}`
67
+ };
68
+ }
69
+ return {};
64
70
  }
65
71
  }
66
72
  class NhostGraphqlClient {
67
73
  constructor(params) {
68
- const { url } = params;
74
+ const { url, adminSecret } = params;
69
75
  this.url = url;
70
76
  this.accessToken = null;
77
+ this.adminSecret = adminSecret;
71
78
  this.instance = axios.create({
72
79
  baseURL: url
73
80
  });
74
81
  }
75
82
  async request(document, variables, config) {
76
- const headers = __spreadValues(__spreadValues({}, config == null ? void 0 : config.headers), this.generateAccessTokenHeaders());
83
+ const headers = __spreadValues(__spreadValues({}, this.generateAccessTokenHeaders()), config == null ? void 0 : config.headers);
77
84
  try {
78
85
  const operationName = "";
79
86
  const res = await this.instance.post("", {
@@ -118,12 +125,17 @@ class NhostGraphqlClient {
118
125
  this.accessToken = accessToken;
119
126
  }
120
127
  generateAccessTokenHeaders() {
121
- if (!this.accessToken) {
122
- return;
128
+ if (this.adminSecret) {
129
+ return {
130
+ "x-hasura-admin-secret": this.adminSecret
131
+ };
132
+ }
133
+ if (this.accessToken) {
134
+ return {
135
+ Authorization: `Bearer ${this.accessToken}`
136
+ };
123
137
  }
124
- return {
125
- Authorization: `Bearer ${this.accessToken}`
126
- };
138
+ return {};
127
139
  }
128
140
  }
129
141
  class NhostClient {
@@ -136,6 +148,8 @@ class NhostClient {
136
148
  clientStorageType,
137
149
  autoRefreshToken,
138
150
  autoSignIn,
151
+ adminSecret,
152
+ devTools,
139
153
  start = true
140
154
  }) {
141
155
  var _a;
@@ -153,13 +167,16 @@ class NhostClient {
153
167
  start
154
168
  });
155
169
  this.storage = new HasuraStorageClient({
156
- url: `${backendUrl}/v1/storage`
170
+ url: `${backendUrl}/v1/storage`,
171
+ adminSecret
157
172
  });
158
173
  this.functions = new NhostFunctionsClient({
159
- url: `${backendUrl}/v1/functions`
174
+ url: `${backendUrl}/v1/functions`,
175
+ adminSecret
160
176
  });
161
177
  this.graphql = new NhostGraphqlClient({
162
- url: `${backendUrl}/v1/graphql`
178
+ url: `${backendUrl}/v1/graphql`,
179
+ adminSecret
163
180
  });
164
181
  this.storage.setAccessToken(this.auth.getAccessToken());
165
182
  this.functions.setAccessToken(this.auth.getAccessToken());
@@ -178,8 +195,9 @@ class NhostClient {
178
195
  this.graphql.setAccessToken(session == null ? void 0 : session.accessToken);
179
196
  });
180
197
  });
198
+ this.devTools = devTools;
181
199
  }
182
200
  }
183
201
  const createClient = (config) => new NhostClient(config);
184
202
  export { NhostClient, NhostFunctionsClient, NhostGraphqlClient, createClient };
185
- //# sourceMappingURL=index.es.js.map
203
+ //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/clients/functions.ts","../src/clients/graphql.ts","../src/core/nhost-client.ts","../src/index.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'\n\nimport { FunctionCallResponse } from '../types'\nexport interface NhostFunctionsConstructorParams {\n url: string\n}\n\n/**\n * @alias Functions\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 /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: AxiosRequestConfig\n ): Promise<FunctionCallResponse<T>> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(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 /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\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'\nimport type { DocumentNode } from 'graphql'\nimport { print } from 'graphql/language/printer'\n\nimport { GraphqlRequestResponse, GraphqlResponse } from '../types'\n\nexport interface NhostGraphqlConstructorParams {\n url: string\n}\n\n/**\n * @alias GraphQL\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 /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage in your app we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n ...config?.headers,\n ...this.generateAccessTokenHeaders()\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<GraphqlResponse<T>>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n return { data, error: null }\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\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/set-access-token\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 {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n}\n","import { HasuraAuthClient, NhostAuthConstructorParams } 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 extends Omit<NhostAuthConstructorParams, 'url'> {\n /**\n * Nhost backend URL.\n */\n backendUrl: string\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/reference/javascript\n */\n constructor({\n backendUrl,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start = true\n }: NhostClientConstructorParams) {\n if (!backendUrl) throw new Error('Please specify a `backendUrl`. Docs: [todo]!')\n this.auth = new HasuraAuthClient({\n url: `${backendUrl}/v1/auth`,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start\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 this.auth.client?.onStart(() => {\n // * Set access token when signing out\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\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}\n","import { NhostClient, NhostClientConstructorParams } from './core'\n\nconst createClient = (config: NhostClientConstructorParams) => new NhostClient(config)\n\nexport * from './clients'\nexport * from './core'\nexport { createClient }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAUO,MAAM,qBAAqB;AAAA,EAIhC,YAAY,QAAyC;AACnD,UAAM,EAAE,QAAQ;AAEhB,SAAK,cAAc;AACd,SAAA,WAAW,MAAM,OAAO;AAAA,MAC3B,SAAS;AAAA,IAAA,CACV;AAAA,EACH;AAAA,QAYM,KACJ,KACA,MACA,QACkC;AAClC,UAAM,UAAU,kCACX,KAAK,2BAA2B,IAChC,iCAAQ;AAGT,QAAA;AACA,QAAA;AACI,YAAA,MAAM,KAAK,SAAS,KAA6B,KAAK,MAAM,iCAAK,SAAL,EAAa,QAAA,EAAS;AAAA,aACjF;AACP,UAAI,iBAAiB,OAAO;AACnB,eAAA,EAAE,KAAK,MAAM;MACtB;AAAA,IACF;AAEA,QAAI,CAAC,KAAK;AACD,aAAA;AAAA,QACL,KAAK;AAAA,QACL,OAAO,IAAI,MAAM,wCAAwC;AAAA,MAAA;AAAA,IAE7D;AAEO,WAAA,EAAE,KAAK,OAAO;EACvB;AAAA,EAYA,eAAe,aAAiC;AAC9C,QAAI,CAAC,aAAa;AAChB,WAAK,cAAc;AACnB;AAAA,IACF;AAEA,SAAK,cAAc;AAAA,EACrB;AAAA,EAEQ,6BAAoE;AACtE,QAAA,CAAC,KAAK,aAAa;AACrB;AAAA,IACF;AAGO,WAAA;AAAA,MACL,eAAe,UAAU,KAAK;AAAA,IAAA;AAAA,EAElC;AACF;AC9EO,MAAM,mBAAmB;AAAA,EAK9B,YAAY,QAAuC;AACjD,UAAM,EAAE,QAAQ;AAEhB,SAAK,MAAM;AACX,SAAK,cAAc;AACd,SAAA,WAA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functions.ts","../src/clients/graphql.ts","../src/core/nhost-client.ts","../src/index.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'\n\nimport { FunctionCallResponse } from '../types'\nexport interface NhostFunctionsConstructorParams {\n /**\n * Serverless Functions endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: AxiosRequestConfig\n ): Promise<FunctionCallResponse<T>> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(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 /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\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(): AxiosRequestHeaders {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders } from 'axios'\nimport { DocumentNode, print } from 'graphql'\n\nimport { GraphqlRequestResponse, GraphqlResponse } from '../types'\n\nexport interface NhostGraphqlConstructorParams {\n /**\n * GraphQL endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\n/**\n * @alias GraphQL\n */\nexport class NhostGraphqlClient {\n private url: string\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostGraphqlConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage in your app we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<GraphqlResponse<T>>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n return { data, error: null }\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\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/set-access-token\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(): AxiosRequestHeaders {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { HasuraAuthClient, NhostAuthConstructorParams } 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 extends Omit<NhostAuthConstructorParams, 'url'> {\n /**\n * Nhost backend URL.\n */\n backendUrl: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all\n * GraphQL, Storage, and Serverless Functions requests.\n */\n adminSecret?: string\n}\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * const nhost = new NhostClient({ url });\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n backendUrl,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true\n }: NhostClientConstructorParams) {\n if (!backendUrl) throw new Error('Please specify a `backendUrl`. Docs: [todo]!')\n this.auth = new HasuraAuthClient({\n url: `${backendUrl}/v1/auth`,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start\n })\n\n this.storage = new HasuraStorageClient({\n url: `${backendUrl}/v1/storage`,\n adminSecret\n })\n\n this.functions = new NhostFunctionsClient({\n url: `${backendUrl}/v1/functions`,\n adminSecret\n })\n\n this.graphql = new NhostGraphqlClient({\n url: `${backendUrl}/v1/graphql`,\n adminSecret\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 this.auth.client?.onStart(() => {\n // * Set access token when signing out\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\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 this.devTools = devTools\n }\n}\n","import { NhostClient, NhostClientConstructorParams } from './core'\n\nconst createClient = (config: NhostClientConstructorParams) => new NhostClient(config)\n\nexport * from './clients'\nexport * from './core'\nexport { createClient }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBO,MAAM,qBAAqB;AAAA,EAKhC,YAAY,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defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ import { HasuraAuthClient } from "@nhost/hasura-auth-js";
21
+ import { HasuraStorageClient } from "@nhost/hasura-storage-js";
22
+ import axios from "axios";
23
+ import { print } from "graphql";
24
+ class NhostFunctionsClient {
25
+ constructor(params) {
26
+ const { url, adminSecret } = params;
27
+ this.accessToken = null;
28
+ this.adminSecret = adminSecret;
29
+ this.instance = axios.create({
30
+ baseURL: url
31
+ });
32
+ }
33
+ async call(url, data, config) {
34
+ const headers = __spreadValues(__spreadValues({}, this.generateAccessTokenHeaders()), config == null ? void 0 : config.headers);
35
+ let res;
36
+ try {
37
+ res = await this.instance.post(url, data, __spreadProps(__spreadValues({}, config), { headers }));
38
+ } catch (error) {
39
+ if (error instanceof Error) {
40
+ return { res: null, error };
41
+ }
42
+ }
43
+ if (!res) {
44
+ return {
45
+ res: null,
46
+ error: new Error("Unable to make post request to funtion")
47
+ };
48
+ }
49
+ return { res, error: null };
50
+ }
51
+ setAccessToken(accessToken) {
52
+ if (!accessToken) {
53
+ this.accessToken = null;
54
+ return;
55
+ }
56
+ this.accessToken = accessToken;
57
+ }
58
+ generateAccessTokenHeaders() {
59
+ if (this.adminSecret) {
60
+ return {
61
+ "x-hasura-admin-secret": this.adminSecret
62
+ };
63
+ }
64
+ if (this.accessToken) {
65
+ return {
66
+ Authorization: `Bearer ${this.accessToken}`
67
+ };
68
+ }
69
+ return {};
70
+ }
71
+ }
72
+ class NhostGraphqlClient {
73
+ constructor(params) {
74
+ const { url, adminSecret } = params;
75
+ this.url = url;
76
+ this.accessToken = null;
77
+ this.adminSecret = adminSecret;
78
+ this.instance = axios.create({
79
+ baseURL: url
80
+ });
81
+ }
82
+ async request(document, variables, config) {
83
+ const headers = __spreadValues(__spreadValues({}, this.generateAccessTokenHeaders()), config == null ? void 0 : config.headers);
84
+ try {
85
+ const operationName = "";
86
+ const res = await this.instance.post("", {
87
+ operationName: operationName || void 0,
88
+ query: typeof document === "string" ? document : print(document),
89
+ variables
90
+ }, __spreadProps(__spreadValues({}, config), { headers }));
91
+ const responseData = res.data;
92
+ const { data } = responseData;
93
+ if (responseData.errors) {
94
+ return {
95
+ data: null,
96
+ error: responseData.errors
97
+ };
98
+ }
99
+ if (typeof data !== "object" || Array.isArray(data) || data === null) {
100
+ return {
101
+ data: null,
102
+ error: new Error("incorrect response data from GraphQL server")
103
+ };
104
+ }
105
+ return { data, error: null };
106
+ } catch (error) {
107
+ if (error instanceof Error) {
108
+ return { data: null, error };
109
+ }
110
+ console.error(error);
111
+ return {
112
+ data: null,
113
+ error: new Error("Unable to get do GraphQL request")
114
+ };
115
+ }
116
+ }
117
+ getUrl() {
118
+ return this.url;
119
+ }
120
+ setAccessToken(accessToken) {
121
+ if (!accessToken) {
122
+ this.accessToken = null;
123
+ return;
124
+ }
125
+ this.accessToken = accessToken;
126
+ }
127
+ generateAccessTokenHeaders() {
128
+ if (this.adminSecret) {
129
+ return {
130
+ "x-hasura-admin-secret": this.adminSecret
131
+ };
132
+ }
133
+ if (this.accessToken) {
134
+ return {
135
+ Authorization: `Bearer ${this.accessToken}`
136
+ };
137
+ }
138
+ return {};
139
+ }
140
+ }
141
+ class NhostClient {
142
+ constructor({
143
+ backendUrl,
144
+ refreshIntervalTime,
145
+ clientStorageGetter,
146
+ clientStorageSetter,
147
+ clientStorage,
148
+ clientStorageType,
149
+ autoRefreshToken,
150
+ autoSignIn,
151
+ adminSecret,
152
+ devTools,
153
+ start = true
154
+ }) {
155
+ var _a;
156
+ if (!backendUrl)
157
+ throw new Error("Please specify a `backendUrl`. Docs: [todo]!");
158
+ this.auth = new HasuraAuthClient({
159
+ url: `${backendUrl}/v1/auth`,
160
+ refreshIntervalTime,
161
+ clientStorageGetter,
162
+ clientStorageSetter,
163
+ clientStorage,
164
+ clientStorageType,
165
+ autoRefreshToken,
166
+ autoSignIn,
167
+ start
168
+ });
169
+ this.storage = new HasuraStorageClient({
170
+ url: `${backendUrl}/v1/storage`,
171
+ adminSecret
172
+ });
173
+ this.functions = new NhostFunctionsClient({
174
+ url: `${backendUrl}/v1/functions`,
175
+ adminSecret
176
+ });
177
+ this.graphql = new NhostGraphqlClient({
178
+ url: `${backendUrl}/v1/graphql`,
179
+ adminSecret
180
+ });
181
+ this.storage.setAccessToken(this.auth.getAccessToken());
182
+ this.functions.setAccessToken(this.auth.getAccessToken());
183
+ this.graphql.setAccessToken(this.auth.getAccessToken());
184
+ (_a = this.auth.client) == null ? void 0 : _a.onStart(() => {
185
+ this.auth.onAuthStateChanged((_event, session) => {
186
+ if (_event === "SIGNED_OUT") {
187
+ this.storage.setAccessToken(void 0);
188
+ this.functions.setAccessToken(void 0);
189
+ this.graphql.setAccessToken(void 0);
190
+ }
191
+ });
192
+ this.auth.onTokenChanged((session) => {
193
+ this.storage.setAccessToken(session == null ? void 0 : session.accessToken);
194
+ this.functions.setAccessToken(session == null ? void 0 : session.accessToken);
195
+ this.graphql.setAccessToken(session == null ? void 0 : session.accessToken);
196
+ });
197
+ });
198
+ this.devTools = devTools;
199
+ }
200
+ }
201
+ const createClient = (config) => new NhostClient(config);
202
+ export { NhostClient, NhostFunctionsClient, NhostGraphqlClient, createClient };
203
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/clients/functions.ts","../src/clients/graphql.ts","../src/core/nhost-client.ts","../src/index.ts"],"sourcesContent":["import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'\n\nimport { FunctionCallResponse } from '../types'\nexport interface NhostFunctionsConstructorParams {\n /**\n * Serverless Functions endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: AxiosRequestConfig\n ): Promise<FunctionCallResponse<T>> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(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 /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\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(): AxiosRequestHeaders {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import axios, { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders } from 'axios'\nimport { DocumentNode, print } from 'graphql'\n\nimport { GraphqlRequestResponse, GraphqlResponse } from '../types'\n\nexport interface NhostGraphqlConstructorParams {\n /**\n * GraphQL endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\n/**\n * @alias GraphQL\n */\nexport class NhostGraphqlClient {\n private url: string\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostGraphqlConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage in your app we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<GraphqlResponse<T>>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n return { data, error: null }\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\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/set-access-token\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(): AxiosRequestHeaders {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { HasuraAuthClient, NhostAuthConstructorParams } 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 extends Omit<NhostAuthConstructorParams, 'url'> {\n /**\n * Nhost backend URL.\n */\n backendUrl: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all\n * GraphQL, Storage, and Serverless Functions requests.\n */\n adminSecret?: string\n}\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * const nhost = new NhostClient({ url });\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n backendUrl,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true\n }: NhostClientConstructorParams) {\n if (!backendUrl) throw new Error('Please specify a `backendUrl`. Docs: [todo]!')\n this.auth = new HasuraAuthClient({\n url: `${backendUrl}/v1/auth`,\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start\n })\n\n this.storage = new HasuraStorageClient({\n url: `${backendUrl}/v1/storage`,\n adminSecret\n })\n\n this.functions = new NhostFunctionsClient({\n url: `${backendUrl}/v1/functions`,\n adminSecret\n })\n\n this.graphql = new NhostGraphqlClient({\n url: `${backendUrl}/v1/graphql`,\n adminSecret\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 this.auth.client?.onStart(() => {\n // * Set access token when signing out\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\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 this.devTools = devTools\n }\n}\n","import { NhostClient, NhostClientConstructorParams } from './core'\n\nconst createClient = (config: NhostClientConstructorParams) => new NhostClient(config)\n\nexport * from './clients'\nexport * from './core'\nexport { createClient }\n"],"names":[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