@nhost/nhost-js 1.13.4 → 2.0.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.
@@ -1,7 +1,5 @@
1
- import { AxiosRequestConfig } from 'axios';
2
1
  import { NhostClientConstructorParams } from '../../utils/types';
3
- import { DeprecatedNhostFunctionCallResponse, NhostFunctionCallConfig, NhostFunctionCallResponse, NhostFunctionsConstructorParams } from './types';
4
- export * from './types';
2
+ import { NhostFunctionCallConfig, NhostFunctionCallResponse, NhostFunctionsConstructorParams } from './types';
5
3
  /**
6
4
  * Creates a client for Functions from either a subdomain or a URL
7
5
  */
@@ -11,17 +9,10 @@ export declare function createFunctionsClient(params: NhostClientConstructorPara
11
9
  */
12
10
  export declare class NhostFunctionsClient {
13
11
  readonly url: string;
14
- private instance;
15
12
  private accessToken;
16
13
  private adminSecret?;
17
14
  constructor(params: NhostFunctionsConstructorParams);
18
- /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */
19
- call<T = unknown, D = any>(url: string, data?: D, config?: (NhostFunctionCallConfig | AxiosRequestConfig) & {
20
- useAxios?: true;
21
- }): Promise<DeprecatedNhostFunctionCallResponse<T>>;
22
- call<T = unknown, D = any>(url: string, data: D, config?: NhostFunctionCallConfig & {
23
- useAxios: false;
24
- }): Promise<NhostFunctionCallResponse<T>>;
15
+ call<T = unknown, D = any>(url: string, data: D, config?: NhostFunctionCallConfig): Promise<NhostFunctionCallResponse<T>>;
25
16
  /**
26
17
  * 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.
27
18
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAc,EAGZ,kBAAkB,EAGnB,MAAM,OAAO,CAAA;AAEd,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EAC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qB,CAAC,MAAM,EAAE,4BAA4B,wBAWzE;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC/B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;gBAEhB,MAAM,EAAE,+BAA+B;IAQ7C,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,GAAG,EAC7B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,CAAC,EACP,MAAM,CAAC,EAAE,uBAAuB,GAC/B,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC;IAuDxC;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,OAAO,CAAC,0BAA0B;CAanC"}
@@ -1,4 +1,3 @@
1
- import type { AxiosResponse } from 'axios';
2
1
  import { ErrorPayload } from '../../utils/types';
3
2
  export interface NhostFunctionsConstructorParams {
4
3
  /**
@@ -21,16 +20,10 @@ export declare type NhostFunctionCallResponse<T = unknown> = {
21
20
  res: null;
22
21
  error: ErrorPayload;
23
22
  };
24
- /**@deprecated */
25
- export declare type DeprecatedNhostFunctionCallResponse<T = unknown> = {
26
- res: AxiosResponse<T>;
27
- error: null;
28
- } | {
29
- res: null;
30
- error: Error;
31
- };
32
23
  /** Subset of RequestInit parameters that are supported by the functions client */
33
24
  export interface NhostFunctionCallConfig {
34
25
  headers?: Record<string, string>;
26
+ /** @deprecated Axios has been replaced by cross-fetch. You should now remove this option. */
27
+ useAxios?: false;
35
28
  }
36
29
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,MAAM,WAAW,+BAA+B;IAC9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;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,KAAK,CAAA;CACjB"}
@@ -0,0 +1,7 @@
1
+ import { GenericSchema, NhostGraphqlClient } from '@nhost/graphql-js';
2
+ import { NhostClientConstructorParams } from '../utils/types';
3
+ /**
4
+ * Creates a client for GraphQL from either a subdomain or a URL
5
+ */
6
+ export declare function createGraphqlClient<Schema extends GenericSchema | undefined>(params: NhostClientConstructorParams<Schema>): NhostGraphqlClient<Schema>;
7
+ //# sourceMappingURL=graphql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAErE,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,SAAS,aAAa,GAAG,SAAS,EAC1E,MAAM,EAAE,4BAA4B,CAAC,MAAM,CAAC,8BAY7C"}
@@ -1,14 +1,14 @@
1
+ import { GenericSchema, NhostGraphqlClient } from '@nhost/graphql-js';
1
2
  import { HasuraAuthClient } from '@nhost/hasura-auth-js';
2
3
  import { HasuraStorageClient } from '@nhost/hasura-storage-js';
3
4
  import { NhostClientConstructorParams } from '../utils/types';
4
5
  import { NhostFunctionsClient } from './functions';
5
- import { NhostGraphqlClient } from './graphql';
6
- export declare const createNhostClient: (params: NhostClientConstructorParams) => NhostClient;
7
- export declare class NhostClient {
6
+ export declare const createNhostClient: <Schema extends GenericSchema | undefined = undefined>(params: NhostClientConstructorParams<Schema>) => NhostClient<Schema>;
7
+ export declare class NhostClient<Schema extends GenericSchema | undefined = undefined> {
8
8
  auth: HasuraAuthClient;
9
9
  storage: HasuraStorageClient;
10
10
  functions: NhostFunctionsClient;
11
- graphql: NhostGraphqlClient;
11
+ graphql: NhostGraphqlClient<Schema>;
12
12
  private _adminSecret?;
13
13
  readonly devTools?: boolean;
14
14
  /**
@@ -21,7 +21,7 @@ export declare class NhostClient {
21
21
  *
22
22
  * @docs https://docs.nhost.io/reference/javascript
23
23
  */
24
- constructor({ refreshIntervalTime, clientStorageGetter, clientStorageSetter, clientStorage, clientStorageType, autoRefreshToken, autoSignIn, adminSecret, devTools, start, ...urlParams }: NhostClientConstructorParams);
24
+ constructor({ refreshIntervalTime, clientStorage, clientStorageType, autoRefreshToken, autoSignIn, adminSecret, devTools, start, schema, ...urlParams }: NhostClientConstructorParams<Schema>);
25
25
  get adminSecret(): string | undefined;
26
26
  set adminSecret(newValue: string | undefined);
27
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"nhost.d.ts","sourceRoot":"","sources":["nhost.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAE7D,OAAO,EAAyB,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACzE,OAAO,EAAuB,kBAAkB,EAAE,MAAM,WAAW,CAAA;AAGnE,eAAO,MAAM,iBAAiB,WAAY,4BAA4B,gBAA4B,CAAA;AAClG,qBAAa,WAAW;IACtB,IAAI,EAAE,gBAAgB,CAAA;IACtB,OAAO,EAAE,mBAAmB,CAAA;IAC5B,SAAS,EAAE,oBAAoB,CAAA;IAC/B,OAAO,EAAE,kBAAkB,CAAA;IAC3B,OAAO,CAAC,YAAY,CAAC,CAAQ;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;IAE3B;;;;;;;;;OASG;gBACS,EACV,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,E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hostClientConstructorParams } from '../utils/types';
3
3
  /**
4
4
  * Creates a client for Storage from either a subdomain or a URL
5
5
  */
6
- export declare function createStorageClient(params: NhostClientConstructorParams): HasuraStorageClient;
6
+ export declare function createStorageClient(params: NhostClientConstructorParams<undefined>): HasuraStorageClient;
7
7
  //# sourceMappingURL=storage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAG9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,4BAA4B,uBAWvE"}
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAG9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,4BAA4B,CAAC,SAAS,CAAC,uBAWlF"}
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@nhost/hasura-auth-js"),g=require("@nhost/hasura-storage-js"),k=require("axios"),q=require("graphql"),v=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function f(e,t){const{backendUrl:s,subdomain:r,region:o}=e;if(s)return`${s}/v1/${t}`;if(!r)throw new Error("Either `backendUrl` or `subdomain` must be set.");const c=r.match(v);if(c!=null&&c.groups){const{protocol:n="http",host:a,port:i=1337}=c.groups,u=$(t);return u||`${n}://${a}:${i}/v1/${t}`}if(!o)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${r}.${t}.${o}.nhost.run/v1`}function E(){return typeof window<"u"}function y(){return typeof process<"u"&&process.env}function $(e){return E()||!y()?null:process.env[`NHOST_${e.toUpperCase()}_URL`]}function b(e){const t="subdomain"in e||"backendUrl"in e?f(e,"auth"):e.authUrl;if(!t)throw new Error("Please provide `subdomain` or `authUrl`.");return new p.HasuraAuthClient({url:t,...e})}function w(e){const t="subdomain"in e||"backendUrl"in e?f(e,"functions"):e.functionsUrl;if(!t)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new T({url:t,...e})}class T{constructor(t){const{url:s,adminSecret:r}=t;this.url=s,this.accessToken=null,this.adminSecret=r,this.instance=k.create({baseURL:s})}async call(t,s,{useAxios:r=!0,...o}={}){r&&console.warn("nhost.functions.call() will no longer use Axios in the near future. Please add `useAxios: false` in the config argument to use the new implementation.");const c={...this.generateAccessTokenHeaders(),...o==null?void 0:o.headers};let n;try{n=await this.instance.post(t,s,{...o,headers:c})}catch(a){if(a instanceof Error){if(r)return{res:null,error:a};const i=a;return{res:null,error:{error:i.code||"unknown",status:i.status||0,message:i.message}}}}return n?r?{res:n,error:null}:{res:{status:n.status,statusText:n.statusText,data:n.data},error:null}:r?{res:null,error:new Error("Unable to make post request to function")}:{res:null,error:{error:"invalid-response",status:0,message:"Unable to make post request to function"}}}setAccessToken(t){if(!t){this.accessToken=null;return}this.accessToken=t}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function m(e){const t="subdomain"in e||"backendUrl"in e?f(e,"graphql"):e.graphqlUrl;if(!t)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new U({url:t,...e})}class U{constructor(t){const{url:s,adminSecret:r}=t;this.url=s,this.accessToken=null,this.adminSecret=r,this.instance=k.create({baseURL:s})}async request(t,s,{useAxios:r=!0,...o}={}){const c={"Accept-Encoding":"*",...this.generateAccessTokenHeaders(),...o==null?void 0:o.headers};try{const n="",i=(await this.instance.post("",{operationName:n||void 0,query:typeof t=="string"?t:q.print(t),variables:s},{...o,headers:c})).data,{data:u}=i;return i.errors?{data:null,error:i.errors}:typeof u!="object"||Array.isArray(u)||u===null?r?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:null,error:{error:"invalid-response",status:0,message:"incorrect response data from GraphQL server"}}:{data:u,error:null}}catch(n){if(console.error(n),r)return n instanceof Error?{data:null,error:n}:{data:null,error:new Error("Unable to get do GraphQL request")};const a=n;return{data:null,error:{error:a.code||"unknown",status:a.status||0,message:a.message}}}}getUrl(){return this.url}setAccessToken(t){if(!t){this.accessToken=null;return}this.accessToken=t}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function A(e){const t="subdomain"in e||"backendUrl"in e?f(e,"storage"):e.storageUrl;if(!t)throw new Error("Please provide `subdomain` or `storageUrl`.");return new g.HasuraStorageClient({url:t,...e})}const N=e=>new C(e);class C{constructor({refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:r,clientStorage:o,clientStorageType:c,autoRefreshToken:n,autoSignIn:a,adminSecret:i,devTools:u,start:S=!0,...h}){this.auth=b({refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:r,clientStorage:o,clientStorageType:c,autoRefreshToken:n,autoSignIn:a,start:S,...h}),this.storage=A({adminSecret:i,...h}),this.functions=w({adminSecret:i,...h}),this.graphql=m({adminSecret:i,...h}),this.auth.onAuthStateChanged((l,d)=>{l==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(l=>{const d=l==null?void 0:l.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),this._adminSecret=i,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(t){this._adminSecret=t,this.storage.setAdminSecret(t)}}exports.NhostClient=C;exports.NhostFunctionsClient=T;exports.NhostGraphqlClient=U;exports.createAuthClient=b;exports.createFunctionsClient=w;exports.createGraphqlClient=m;exports.createNhostClient=N;exports.createStorageClient=A;for(const e in p)e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>p[e]});for(const e in g)e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>g[e]});
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@nhost/hasura-auth-js"),b=require("@nhost/hasura-storage-js"),A=require("cross-fetch"),S=require("@nhost/graphql-js"),y=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function h(t,e){const{backendUrl:s,subdomain:o,region:i}=t;if(s)return`${s}/v1/${e}`;if(!o)throw new Error("Either `backendUrl` or `subdomain` must be set.");const r=o.match(y);if(r!=null&&r.groups){const{protocol:n="http",host:d,port:f=1337}=r.groups,u=v(e);return u||`${n}://${d}:${f}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${o}.${e}.${i}.nhost.run/v1`}function m(){return typeof window<"u"}function q(){return typeof process<"u"&&process.env}function v(t){return m()||!q()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function w(t){const e="subdomain"in t||"backendUrl"in t?h(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new g.HasuraAuthClient({url:e,...t})}function p(t){const e="subdomain"in t||"backendUrl"in t?h(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new k({url:e,...t})}class k{constructor(e){const{url:s,adminSecret:o}=e;this.url=s,this.accessToken=null,this.adminSecret=o}async call(e,s,o){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...o==null?void 0:o.headers};try{const r=await A(e,{body:JSON.stringify(s),headers:i,method:"POST"});if(!r.ok)throw new Error(r.statusText);let n;try{n=await r.json()}catch{n=await r.text()}return{res:{data:n,status:r.status,statusText:r.statusText},error:null}}catch(r){const n=r;return{res:null,error:{message:n.message,status:n.name==="AbortError"?0:500,error:n.name==="AbortError"?"abort-error":"unknown"}}}}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}`}:{}}}function T(t){const e="subdomain"in t||"backendUrl"in t?h(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new S.NhostGraphqlClient({url:e,...t})}function C(t){const e="subdomain"in t||"backendUrl"in t?h(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new b.HasuraStorageClient({url:e,...t})}const E=t=>new U(t);class U{constructor({refreshIntervalTime:e,clientStorage:s,clientStorageType:o,autoRefreshToken:i,autoSignIn:r,adminSecret:n,devTools:d,start:f=!0,schema:u,...a}){this.auth=w({refreshIntervalTime:e,clientStorage:s,clientStorageType:o,autoRefreshToken:i,autoSignIn:r,start:f,...a}),this.storage=C({adminSecret:n,...a}),this.functions=p({adminSecret:n,...a}),this.graphql=T({adminSecret:n,schema:u,...a}),this.auth.onAuthStateChanged((c,l)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const l=c==null?void 0:c.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=n,this.devTools=d}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}exports.NhostClient=U;exports.NhostFunctionsClient=k;exports.createAuthClient=w;exports.createFunctionsClient=p;exports.createGraphqlClient=T;exports.createNhostClient=E;exports.createStorageClient=C;for(const t in g)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>g[t]});for(const t in b)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>b[t]});
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions/index.ts","../src/clients/graphql/index.ts","../src/clients/storage.ts","../src/clients/nhost.ts"],"sourcesContent":["import { NhostClientConstructorParams } from './types'\n\n// a port can be a number or a placeholder string with leading and trailing double underscores, f.e. \"8080\" or \"__PLACEHOLDER_NAME__\"\nconst LOCALHOST_REGEX = /^((?<protocol>http[s]?):\\/\\/)?(?<host>localhost)(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol = 'http', host, port = 1337 } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n return `${protocol}://${host}:${port}/v1/${service}`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"localhost\".')\n }\n\n return `https://${subdomain}.${service}.${region}.nhost.run/v1`\n}\n\n/**\n *\n * @returns whether the code is running in a browser\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\n/**\n *\n * @returns whether the code is running in a Node.js environment\n */\nfunction environmentIsAvailable() {\n return typeof process !== 'undefined' && process.env\n}\n\n/**\n *\n * @param service auth | storage | graphql | functions\n * @returns the service's url if the corresponding env var is set\n * NHOST_${service}_URL\n */\nfunction getValueFromEnv(service: string) {\n if (isBrowser() || !environmentIsAvailable()) {\n return null\n }\n\n return process.env[`NHOST_${service.toUpperCase()}_URL`]\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Auth from either a subdomain or a URL\n */\nexport function createAuthClient(params: NhostClientConstructorParams) {\n const authUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import axios, {\n AxiosError,\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n RawAxiosRequestHeaders\n} from 'axios'\nimport { urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n DeprecatedNhostFunctionCallResponse,\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n\nexport * from './types'\n/**\n * Creates a client for Functions from either a subdomain or a URL\n */\nexport function createFunctionsClient(params: NhostClientConstructorParams) {\n const functionsUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\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.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */\n async call<T = unknown, D = any>(\n url: string,\n data?: D,\n config?: (NhostFunctionCallConfig | AxiosRequestConfig) & { useAxios?: true }\n ): Promise<DeprecatedNhostFunctionCallResponse<T>>\n\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: NhostFunctionCallConfig & { useAxios: false }\n ): Promise<NhostFunctionCallResponse<T>>\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 {\n useAxios = true,\n ...config\n }: (AxiosRequestConfig | NhostFunctionCallConfig) & { useAxios?: boolean } = {}\n ): Promise<DeprecatedNhostFunctionCallResponse<T> | NhostFunctionCallResponse> {\n if (useAxios) {\n console.warn(\n 'nhost.functions.call() will no longer use Axios in the near future. Please add `useAxios: false` in the config argument to use the new implementation.'\n )\n }\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 if (useAxios) {\n return { res: null, error }\n }\n const axiosError = error as AxiosError\n return {\n res: null,\n error: {\n error: axiosError.code || 'unknown',\n status: axiosError.status || 0,\n message: axiosError.message\n }\n }\n }\n }\n\n if (!res) {\n if (useAxios) {\n return {\n res: null,\n error: new Error('Unable to make post request to function')\n }\n }\n return {\n res: null,\n error: {\n error: 'invalid-response',\n status: 0,\n message: 'Unable to make post request to function'\n }\n }\n }\n\n if (useAxios) {\n return { res, error: null }\n }\n return {\n res: {\n status: res.status,\n statusText: res.statusText,\n data: res.data\n },\n error: null\n }\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(): RawAxiosRequestHeaders {\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, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'\nimport { DocumentNode, GraphQLError, print } from 'graphql'\nimport { urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n DeprecatedNhostGraphqlRequestResponse,\n NhostGraphqlConstructorParams,\n NhostGraphqlRequestConfig,\n NhostGraphqlRequestResponse\n} from './types'\n\n/**\n * Creates a client for GraphQL from either a subdomain or a URL\n */\nexport function createGraphqlClient(params: NhostClientConstructorParams) {\n const graphqlUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n\n/**\n * @alias GraphQL\n */\nexport class NhostGraphqlClient {\n readonly 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 /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: (AxiosRequestConfig | NhostGraphqlRequestConfig) & { useAxios?: true }\n ): Promise<DeprecatedNhostGraphqlRequestResponse<T>>\n\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: NhostGraphqlRequestConfig & { useAxios: false }\n ): Promise<NhostGraphqlRequestResponse<T>>\n\n /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage 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 {\n useAxios = true,\n ...config\n }: (AxiosRequestConfig | NhostGraphqlRequestConfig) & { useAxios?: boolean } = {}\n ): Promise<DeprecatedNhostGraphqlRequestResponse<T> | NhostGraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n 'Accept-Encoding': '*',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<{\n errors?: GraphQLError[]\n data?: T\n }>(\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 if (useAxios) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n return {\n data: null,\n error: {\n error: 'invalid-response',\n status: 0,\n message: 'incorrect response data from GraphQL server'\n }\n }\n }\n\n return { data, error: null }\n } catch (error) {\n console.error(error)\n if (useAxios) {\n if (error instanceof Error) {\n return { data: null, error }\n }\n return {\n data: null,\n error: new Error('Unable to get do GraphQL request')\n }\n }\n\n const axiosError = error as AxiosError\n return {\n data: null,\n error: {\n error: axiosError.code || 'unknown',\n status: axiosError.status || 0,\n message: axiosError.message\n }\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(): Record<string, string> {\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 { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\nimport { NhostClientConstructorParams } from '../utils/types'\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient, NhostGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n private _adminSecret?: string\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * ```ts\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true,\n ...urlParams\n }: NhostClientConstructorParams) {\n // * Set clients for all services\n this.auth = createAuthClient({\n refreshIntervalTime,\n clientStorageGetter,\n clientStorageSetter,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start,\n ...urlParams\n })\n this.storage = createStorageClient({ adminSecret, ...urlParams })\n this.functions = createFunctionsClient({ adminSecret, ...urlParams })\n this.graphql = createGraphqlClient({ adminSecret, ...urlParams })\n\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 const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","axios","data","useAxios","config","headers","res","error","axiosError","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","document","variables","operationName","responseData","print","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorageGetter","clientStorageSetter","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":"uMAGMA,EAAkB,8EAUR,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,iDAAiD,EAI7D,MAAAE,EAA0BF,EAAU,MAAML,CAAe,EAC/D,GAAIO,GAAA,MAAAA,EAAyB,OAAQ,CACnC,KAAM,CAAE,SAAAC,EAAW,OAAQ,KAAAC,EAAM,KAAAC,EAAO,MAASH,EAAwB,OAEnEI,EAAaC,EAAgBT,CAAO,EAC1C,OAAIQ,GAGG,GAAGH,OAAcC,KAAQC,QAAWP,GAC7C,CAEA,GAAI,CAACG,EACG,MAAA,IAAI,MAAM,uEAAuE,EAGlF,MAAA,WAAWD,KAAaF,KAAWG,gBAC5C,CAMA,SAASO,GAAqB,CAC5B,OAAO,OAAO,OAAW,GAC3B,CAMA,SAASC,GAAyB,CACzB,OAAA,OAAO,QAAY,KAAe,QAAQ,GACnD,CAQA,SAASF,EAAgBT,EAAiB,CACxC,OAAIU,EAAU,GAAK,CAACC,IACX,KAGF,QAAQ,IAAI,SAASX,EAAQ,YAAY,QAClD,CClEO,SAASY,EAAiBC,EAAsC,CAC/D,MAAAC,EACJ,cAAeD,GAAU,e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M,EAC1F,MAAM6B,CAAY,CAkBvB,YAAY,CACV,oBAAAC,EACA,oBAAAC,EACA,oBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,YAAA7B,EACA,SAAA8B,EACA,MAAAC,EAAQ,MACLC,CAAA,EAC4B,CAE/B,KAAK,KAAOxC,EAAiB,CAC3B,oBAAA+B,EACA,oBAAAC,EACA,oBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,MAAAE,EACA,GAAGC,CAAA,CACJ,EACD,KAAK,QAAUd,EAAoB,CAAE,YAAAlB,EAAa,GAAGgC,EAAW,EAChE,KAAK,UAAYpC,EAAsB,CAAE,YAAAI,EAAa,GAAGgC,EAAW,EACpE,KAAK,QAAUtB,EAAoB,CAAE,YAAAV,EAAa,GAAGgC,EAAW,EAEhE,KAAK,KAAK,mBAAmB,CAACC,EAAQC,IAAY,CAC5CD,IAAW,eACR,KAAA,QAAQ,eAAe,MAAS,EAChC,KAAA,UAAU,eAAe,MAAS,EAClC,KAAA,QAAQ,eAAe,MAAS,EACvC,CACD,EAGI,KAAA,KAAK,eAAgBC,GAAY,CACpC,MAAMzB,EAAcyB,GAAA,YAAAA,EAAS,YACxB,KAAA,QAAQ,eAAezB,CAAW,EAClC,KAAA,UAAU,eAAeA,CAAW,EACpC,KAAA,QAAQ,eAAeA,CAAW,CAAA,CACxC,EAED,KAAK,aAAeT,EACpB,KAAK,SAAW8B,CAClB,CAEA,IAAI,aAAkC,CACpC,OAAO,KAAK,YACd,CAEA,IAAI,YAAYK,EAA8B,CAC5C,KAAK,aAAeA,EACf,KAAA,QAAQ,eAAeA,CAAQ,CAItC,CACF"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions/index.ts","../src/clients/graphql.ts","../src/clients/storage.ts","../src/clients/nhost.ts"],"sourcesContent":["import { NhostClientConstructorParams } from './types'\n\n// a port can be a number or a placeholder string with leading and trailing double underscores, f.e. \"8080\" or \"__PLACEHOLDER_NAME__\"\nconst LOCALHOST_REGEX = /^((?<protocol>http[s]?):\\/\\/)?(?<host>localhost)(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol = 'http', host, port = 1337 } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n return `${protocol}://${host}:${port}/v1/${service}`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"localhost\".')\n }\n\n return `https://${subdomain}.${service}.${region}.nhost.run/v1`\n}\n\n/**\n *\n * @returns whether the code is running in a browser\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\n/**\n *\n * @returns whether the code is running in a Node.js environment\n */\nfunction environmentIsAvailable() {\n return typeof process !== 'undefined' && process.env\n}\n\n/**\n *\n * @param service auth | storage | graphql | functions\n * @returns the service's url if the corresponding env var is set\n * NHOST_${service}_URL\n */\nfunction getValueFromEnv(service: string) {\n if (isBrowser() || !environmentIsAvailable()) {\n return null\n }\n\n return process.env[`NHOST_${service.toUpperCase()}_URL`]\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Auth from either a subdomain or a URL\n */\nexport function createAuthClient(params: NhostClientConstructorParams) {\n const authUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from 'cross-fetch'\nimport { urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n/**\n * Creates a client for Functions from either a subdomain or a URL\n */\nexport function createFunctionsClient(params: NhostClientConstructorParams) {\n const functionsUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<T>>\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 body: D,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<T>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n try {\n const result = await fetch(url, {\n body: JSON.stringify(body),\n headers,\n method: 'POST'\n })\n if (!result.ok) {\n throw new Error(result.statusText)\n }\n let data: T\n try {\n data = await result.json()\n } catch {\n data = (await result.text()) as unknown as T\n }\n return {\n res: { data, status: result.status, statusText: result.statusText },\n error: null\n }\n } catch (e) {\n const error = e as Error\n return {\n res: null,\n error: {\n message: error.message,\n status: error.name === 'AbortError' ? 0 : 500,\n error: error.name === 'AbortError' ? 'abort-error' : 'unknown'\n }\n }\n }\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(): NhostFunctionCallConfig['headers'] {\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 { GenericSchema, NhostGraphqlClient } from '@nhost/graphql-js'\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for GraphQL from either a subdomain or a URL\n */\nexport function createGraphqlClient<Schema extends GenericSchema | undefined>(\n params: NhostClientConstructorParams<Schema>\n) {\n const graphqlUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams<undefined>) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { GenericSchema, NhostGraphqlClient } from '@nhost/graphql-js'\nimport { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\nimport { NhostClientConstructorParams } from '../utils/types'\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = <Schema extends GenericSchema | undefined = undefined>(\n params: NhostClientConstructorParams<Schema>\n) => new NhostClient(params)\n\nexport class NhostClient<Schema extends GenericSchema | undefined = undefined> {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient<Schema>\n private _adminSecret?: string\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * ```ts\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true,\n schema,\n ...urlParams\n }: NhostClientConstructorParams<Schema>) {\n // * Set clients for all services\n this.auth = createAuthClient({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start,\n ...urlParams\n })\n this.storage = createStorageClient({ adminSecret, ...urlParams })\n this.functions = createFunctionsClient({ adminSecret, ...urlParams })\n this.graphql = createGraphqlClient({ adminSecret, schema, ...urlParams })\n\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 const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","result","fetch","data","e","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","schema","urlParams","_event","session","newValue"],"mappings":"uNAGMA,EAAkB,8EAUR,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,iDAAiD,EAI7D,MAAAE,EAA0BF,EAAU,MAAML,CAAe,EAC/D,GAAIO,GAAA,MAAAA,EAAyB,OAAQ,CACnC,KAAM,CAAE,SAAAC,EAAW,OAAQ,KAAAC,EAAM,KAAAC,EAAO,MAASH,EAAwB,OAEnEI,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AEpB,MAAMwB,CAAkE,CAkB7E,YAAY,CACV,oBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,YAAAtB,EACA,SAAAuB,EACA,MAAAC,EAAQ,GACR,OAAAC,KACGC,CAAA,EACoC,CAEvC,KAAK,KAAOlC,EAAiB,CAC3B,oBAAA0B,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,MAAAE,EACA,GAAGE,CAAA,CACJ,EACD,KAAK,QAAUb,EAAoB,CAAE,YAAAb,EAAa,GAAG0B,EAAW,EAChE,KAAK,UAAY9B,EAAsB,CAAE,YAAAI,EAAa,GAAG0B,EAAW,EACpE,KAAK,QAAUhB,EAAoB,CAAE,YAAAV,EAAa,OAAAyB,EAAQ,GAAGC,EAAW,EAExE,KAAK,KAAK,mBAAmB,CAACC,EAAQC,IAAY,CAC5CD,IAAW,eACR,KAAA,QAAQ,eAAe,MAAS,EAChC,KAAA,UAAU,eAAe,MAAS,EAClC,KAAA,QAAQ,eAAe,MAAS,EACvC,CACD,EAGI,KAAA,KAAK,eAAgBC,GAAY,CACpC,MAAMnB,EAAcmB,GAAA,YAAAA,EAAS,YACxB,KAAA,QAAQ,eAAenB,CAAW,EAClC,KAAA,UAAU,eAAeA,CAAW,EACpC,KAAA,QAAQ,eAAeA,CAAW,CAAA,CACxC,EAED,KAAK,aAAeT,EACpB,KAAK,SAAWuB,CAClB,CAEA,IAAI,aAAkC,CACpC,OAAO,KAAK,YACd,CAEA,IAAI,YAAYM,EAA8B,CAC5C,KAAK,aAAeA,EACf,KAAA,QAAQ,eAAeA,CAAQ,CAItC,CACF"}
package/dist/index.esm.js CHANGED
@@ -1,182 +1,87 @@
1
1
  import { HasuraAuthClient as g } from "@nhost/hasura-auth-js";
2
2
  export * from "@nhost/hasura-auth-js";
3
- import { HasuraStorageClient as k } from "@nhost/hasura-storage-js";
3
+ import { HasuraStorageClient as w } from "@nhost/hasura-storage-js";
4
4
  export * from "@nhost/hasura-storage-js";
5
- import p from "axios";
6
- import { print as w } from "graphql";
7
- const T = /^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;
8
- function f(r, e) {
9
- const { backendUrl: s, subdomain: t, region: o } = r;
5
+ import T from "cross-fetch";
6
+ import { NhostGraphqlClient as b } from "@nhost/graphql-js";
7
+ const k = /^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;
8
+ function l(t, e) {
9
+ const { backendUrl: s, subdomain: o, region: i } = t;
10
10
  if (s)
11
11
  return `${s}/v1/${e}`;
12
- if (!t)
12
+ if (!o)
13
13
  throw new Error("Either `backendUrl` or `subdomain` must be set.");
14
- const c = t.match(T);
15
- if (c != null && c.groups) {
16
- const { protocol: n = "http", host: a, port: i = 1337 } = c.groups, u = A(e);
17
- return u || `${n}://${a}:${i}/v1/${e}`;
14
+ const r = o.match(k);
15
+ if (r != null && r.groups) {
16
+ const { protocol: n = "http", host: d, port: f = 1337 } = r.groups, u = U(e);
17
+ return u || `${n}://${d}:${f}/v1/${e}`;
18
18
  }
19
- if (!o)
19
+ if (!i)
20
20
  throw new Error('`region` must be set when using a `subdomain` other than "localhost".');
21
- return `https://${t}.${e}.${o}.nhost.run/v1`;
21
+ return `https://${o}.${e}.${i}.nhost.run/v1`;
22
22
  }
23
- function U() {
23
+ function p() {
24
24
  return typeof window < "u";
25
25
  }
26
- function b() {
26
+ function m() {
27
27
  return typeof process < "u" && process.env;
28
28
  }
29
- function A(r) {
30
- return U() || !b() ? null : process.env[`NHOST_${r.toUpperCase()}_URL`];
29
+ function U(t) {
30
+ return p() || !m() ? null : process.env[`NHOST_${t.toUpperCase()}_URL`];
31
31
  }
32
- function E(r) {
33
- const e = "subdomain" in r || "backendUrl" in r ? f(r, "auth") : r.authUrl;
32
+ function A(t) {
33
+ const e = "subdomain" in t || "backendUrl" in t ? l(t, "auth") : t.authUrl;
34
34
  if (!e)
35
35
  throw new Error("Please provide `subdomain` or `authUrl`.");
36
- return new g({ url: e, ...r });
36
+ return new g({ url: e, ...t });
37
37
  }
38
- function v(r) {
39
- const e = "subdomain" in r || "backendUrl" in r ? f(r, "functions") : r.functionsUrl;
38
+ function S(t) {
39
+ const e = "subdomain" in t || "backendUrl" in t ? l(t, "functions") : t.functionsUrl;
40
40
  if (!e)
41
41
  throw new Error("Please provide `subdomain` or `functionsUrl`.");
42
- return new S({ url: e, ...r });
43
- }
44
- class S {
45
- constructor(e) {
46
- const { url: s, adminSecret: t } = e;
47
- this.url = s, this.accessToken = null, this.adminSecret = t, this.instance = p.create({
48
- baseURL: s
49
- });
50
- }
51
- async call(e, s, {
52
- useAxios: t = !0,
53
- ...o
54
- } = {}) {
55
- t && console.warn(
56
- "nhost.functions.call() will no longer use Axios in the near future. Please add `useAxios: false` in the config argument to use the new implementation."
57
- );
58
- const c = {
59
- ...this.generateAccessTokenHeaders(),
60
- ...o == null ? void 0 : o.headers
61
- };
62
- let n;
63
- try {
64
- n = await this.instance.post(e, s, { ...o, headers: c });
65
- } catch (a) {
66
- if (a instanceof Error) {
67
- if (t)
68
- return { res: null, error: a };
69
- const i = a;
70
- return {
71
- res: null,
72
- error: {
73
- error: i.code || "unknown",
74
- status: i.status || 0,
75
- message: i.message
76
- }
77
- };
78
- }
79
- }
80
- return n ? t ? { res: n, error: null } : {
81
- res: {
82
- status: n.status,
83
- statusText: n.statusText,
84
- data: n.data
85
- },
86
- error: null
87
- } : t ? {
88
- res: null,
89
- error: new Error("Unable to make post request to function")
90
- } : {
91
- res: null,
92
- error: {
93
- error: "invalid-response",
94
- status: 0,
95
- message: "Unable to make post request to function"
96
- }
97
- };
98
- }
99
- setAccessToken(e) {
100
- if (!e) {
101
- this.accessToken = null;
102
- return;
103
- }
104
- this.accessToken = e;
105
- }
106
- generateAccessTokenHeaders() {
107
- return this.adminSecret ? {
108
- "x-hasura-admin-secret": this.adminSecret
109
- } : this.accessToken ? {
110
- Authorization: `Bearer ${this.accessToken}`
111
- } : {};
112
- }
113
- }
114
- function q(r) {
115
- const e = "subdomain" in r || "backendUrl" in r ? f(r, "graphql") : r.graphqlUrl;
116
- if (!e)
117
- throw new Error("Please provide `subdomain` or `graphqlUrl`.");
118
- return new C({ url: e, ...r });
42
+ return new C({ url: e, ...t });
119
43
  }
120
44
  class C {
121
45
  constructor(e) {
122
- const { url: s, adminSecret: t } = e;
123
- this.url = s, this.accessToken = null, this.adminSecret = t, this.instance = p.create({
124
- baseURL: s
125
- });
46
+ const { url: s, adminSecret: o } = e;
47
+ this.url = s, this.accessToken = null, this.adminSecret = o;
126
48
  }
127
- async request(e, s, {
128
- useAxios: t = !0,
129
- ...o
130
- } = {}) {
131
- const c = {
132
- "Accept-Encoding": "*",
49
+ async call(e, s, o) {
50
+ const i = {
51
+ "Content-Type": "application/json",
133
52
  ...this.generateAccessTokenHeaders(),
134
53
  ...o == null ? void 0 : o.headers
135
54
  };
136
55
  try {
137
- const n = "", i = (await this.instance.post(
138
- "",
139
- {
140
- operationName: n || void 0,
141
- query: typeof e == "string" ? e : w(e),
142
- variables: s
143
- },
144
- { ...o, headers: c }
145
- )).data, { data: u } = i;
146
- return i.errors ? {
147
- data: null,
148
- error: i.errors
149
- } : typeof u != "object" || Array.isArray(u) || u === null ? t ? {
150
- data: null,
151
- error: new Error("incorrect response data from GraphQL server")
152
- } : {
153
- data: null,
154
- error: {
155
- error: "invalid-response",
156
- status: 0,
157
- message: "incorrect response data from GraphQL server"
158
- }
159
- } : { data: u, error: null };
160
- } catch (n) {
161
- if (console.error(n), t)
162
- return n instanceof Error ? { data: null, error: n } : {
163
- data: null,
164
- error: new Error("Unable to get do GraphQL request")
165
- };
166
- const a = n;
56
+ const r = await T(e, {
57
+ body: JSON.stringify(s),
58
+ headers: i,
59
+ method: "POST"
60
+ });
61
+ if (!r.ok)
62
+ throw new Error(r.statusText);
63
+ let n;
64
+ try {
65
+ n = await r.json();
66
+ } catch {
67
+ n = await r.text();
68
+ }
69
+ return {
70
+ res: { data: n, status: r.status, statusText: r.statusText },
71
+ error: null
72
+ };
73
+ } catch (r) {
74
+ const n = r;
167
75
  return {
168
- data: null,
76
+ res: null,
169
77
  error: {
170
- error: a.code || "unknown",
171
- status: a.status || 0,
172
- message: a.message
78
+ message: n.message,
79
+ status: n.name === "AbortError" ? 0 : 500,
80
+ error: n.name === "AbortError" ? "abort-error" : "unknown"
173
81
  }
174
82
  };
175
83
  }
176
84
  }
177
- getUrl() {
178
- return this.url;
179
- }
180
85
  setAccessToken(e) {
181
86
  if (!e) {
182
87
  this.accessToken = null;
@@ -192,43 +97,46 @@ class C {
192
97
  } : {};
193
98
  }
194
99
  }
195
- function $(r) {
196
- const e = "subdomain" in r || "backendUrl" in r ? f(r, "storage") : r.storageUrl;
100
+ function E(t) {
101
+ const e = "subdomain" in t || "backendUrl" in t ? l(t, "graphql") : t.graphqlUrl;
102
+ if (!e)
103
+ throw new Error("Please provide `subdomain` or `graphqlUrl`.");
104
+ return new b({ url: e, ...t });
105
+ }
106
+ function v(t) {
107
+ const e = "subdomain" in t || "backendUrl" in t ? l(t, "storage") : t.storageUrl;
197
108
  if (!e)
198
109
  throw new Error("Please provide `subdomain` or `storageUrl`.");
199
- return new k({ url: e, ...r });
110
+ return new w({ url: e, ...t });
200
111
  }
201
- const G = (r) => new y(r);
202
- class y {
112
+ const N = (t) => new $(t);
113
+ class $ {
203
114
  constructor({
204
115
  refreshIntervalTime: e,
205
- clientStorageGetter: s,
206
- clientStorageSetter: t,
207
- clientStorage: o,
208
- clientStorageType: c,
209
- autoRefreshToken: n,
210
- autoSignIn: a,
211
- adminSecret: i,
212
- devTools: u,
213
- start: m = !0,
116
+ clientStorage: s,
117
+ clientStorageType: o,
118
+ autoRefreshToken: i,
119
+ autoSignIn: r,
120
+ adminSecret: n,
121
+ devTools: d,
122
+ start: f = !0,
123
+ schema: u,
214
124
  ...h
215
125
  }) {
216
- this.auth = E({
126
+ this.auth = A({
217
127
  refreshIntervalTime: e,
218
- clientStorageGetter: s,
219
- clientStorageSetter: t,
220
- clientStorage: o,
221
- clientStorageType: c,
222
- autoRefreshToken: n,
223
- autoSignIn: a,
224
- start: m,
128
+ clientStorage: s,
129
+ clientStorageType: o,
130
+ autoRefreshToken: i,
131
+ autoSignIn: r,
132
+ start: f,
225
133
  ...h
226
- }), this.storage = $({ adminSecret: i, ...h }), this.functions = v({ adminSecret: i, ...h }), this.graphql = q({ adminSecret: i, ...h }), this.auth.onAuthStateChanged((l, d) => {
227
- l === "SIGNED_OUT" && (this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0));
228
- }), this.auth.onTokenChanged((l) => {
229
- const d = l == null ? void 0 : l.accessToken;
230
- this.storage.setAccessToken(d), this.functions.setAccessToken(d), this.graphql.setAccessToken(d);
231
- }), this._adminSecret = i, this.devTools = u;
134
+ }), this.storage = v({ adminSecret: n, ...h }), this.functions = S({ adminSecret: n, ...h }), this.graphql = E({ adminSecret: n, schema: u, ...h }), this.auth.onAuthStateChanged((c, a) => {
135
+ c === "SIGNED_OUT" && (this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0));
136
+ }), this.auth.onTokenChanged((c) => {
137
+ const a = c == null ? void 0 : c.accessToken;
138
+ this.storage.setAccessToken(a), this.functions.setAccessToken(a), this.graphql.setAccessToken(a);
139
+ }), this._adminSecret = n, this.devTools = d;
232
140
  }
233
141
  get adminSecret() {
234
142
  return this._adminSecret;
@@ -238,13 +146,12 @@ class y {
238
146
  }
239
147
  }
240
148
  export {
241
- y as NhostClient,
242
- S as NhostFunctionsClient,
243
- C as NhostGraphqlClient,
244
- E as createAuthClient,
245
- v as createFunctionsClient,
246
- q as createGraphqlClient,
247
- G as createNhostClient,
248
- $ as createStorageClient
149
+ $ as NhostClient,
150
+ C as NhostFunctionsClient,
151
+ A as createAuthClient,
152
+ S as createFunctionsClient,
153
+ E as createGraphqlClient,
154
+ N as createNhostClient,
155
+ v as createStorageClient
249
156
  };
250
157
  //# sourceMappingURL=index.esm.js.map