@nhost/nhost-js 3.0.11 → 3.1.1
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/dist/clients/functions/index.d.ts +36 -0
- package/dist/clients/functions/index.d.ts.map +1 -1
- package/dist/clients/nhost.d.ts +37 -0
- package/dist/clients/nhost.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +161 -70
- package/dist/index.esm.js.map +1 -1
- package/package.json +4 -4
- package/umd/nhost-js.umd.js +8 -8
- package/umd/nhost-js.umd.js.map +1 -1
|
@@ -12,6 +12,7 @@ export declare class NhostFunctionsClient {
|
|
|
12
12
|
readonly url: string;
|
|
13
13
|
private accessToken;
|
|
14
14
|
private adminSecret?;
|
|
15
|
+
private headers;
|
|
15
16
|
constructor(params: NhostFunctionsConstructorParams);
|
|
16
17
|
/**
|
|
17
18
|
* Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic
|
|
@@ -66,6 +67,41 @@ export declare class NhostFunctionsClient {
|
|
|
66
67
|
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token
|
|
67
68
|
*/
|
|
68
69
|
setAccessToken(accessToken: string | undefined): void;
|
|
70
|
+
/**
|
|
71
|
+
* Use `nhost.functions.getHeaders` to get the global headers sent with all functions requests.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* nhost.functions.getHeaders()
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/get-headers
|
|
79
|
+
*/
|
|
80
|
+
getHeaders(): Record<string, string>;
|
|
81
|
+
/**
|
|
82
|
+
* Use `nhost.functions.setHeaders` to a set global headers to be sent in all subsequent functions requests.
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```ts
|
|
86
|
+
* nhost.functions.setHeaders({
|
|
87
|
+
* 'x-hasura-role': 'admin'
|
|
88
|
+
* })
|
|
89
|
+
* ```
|
|
90
|
+
*
|
|
91
|
+
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-headers
|
|
92
|
+
*/
|
|
93
|
+
setHeaders(headers?: Record<string, string>): void;
|
|
94
|
+
/**
|
|
95
|
+
* Use `nhost.functions.unsetHeaders` to a unset global headers sent with all functions requests.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* nhost.functions.unsetHeaders()
|
|
100
|
+
* ```
|
|
101
|
+
*
|
|
102
|
+
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/unset-headers
|
|
103
|
+
*/
|
|
104
|
+
unsetHeaders(): void;
|
|
69
105
|
generateAccessTokenHeaders(): NhostFunctionCallConfig['headers'];
|
|
70
106
|
}
|
|
71
107
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/clients/functions/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,+BAA+B,EAChC,MAAM,SAAS,CAAA;AAChB;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,4BAA4B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/clients/functions/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,+BAA+B,EAChC,MAAM,SAAS,CAAA;AAChB;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,4BAA4B,wBASzE;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC/B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;IAC5B,OAAO,CAAC,OAAO,CAA6B;gBAEhC,MAAM,EAAE,+BAA+B;IAQnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAwCG;IACG,IAAI,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,GAAG,EAAE,aAAa,GAAG,GAAG,EAC1D,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,KAAK,GAAG,IAAI,EACnB,MAAM,CAAC,EAAE,uBAAuB,GAC/B,OAAO,CAAC,yBAAyB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IA6D3D;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C;;;;;;;;;OASG;IACH,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAIpC;;;;;;;;;;;OAWG;IACH,UAAU,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAW3C;;;;;;;;;OASG;IACH,YAAY;IAOZ,0BAA0B,IAAI,uBAAuB,CAAC,SAAS,CAAC;CAajE"}
|
package/dist/clients/nhost.d.ts
CHANGED
|
@@ -25,5 +25,42 @@ export declare class NhostClient {
|
|
|
25
25
|
constructor({ refreshIntervalTime, clientStorage, clientStorageType, autoRefreshToken, autoSignIn, adminSecret, devTools, start, ...urlParams }: NhostClientConstructorParams);
|
|
26
26
|
get adminSecret(): string | undefined;
|
|
27
27
|
set adminSecret(newValue: string | undefined);
|
|
28
|
+
/**
|
|
29
|
+
* Use `nhost.setRole` to set the user role for all subsequent GraphQL, storage, and functions calls.
|
|
30
|
+
* Underneath, this method sets the `x-hasura-role` header on the graphql, storage,
|
|
31
|
+
* and functions clients.
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* nhost.graphql.setHeaders({ 'x-hasura-role': role })
|
|
35
|
+
* nhost.storage.setHeaders({ 'x-hasura-role': role })
|
|
36
|
+
* nhost.functions.setHeaders({ 'x-hasura-role': role })
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* Note: Exercise caution when mixing the use of `setRole` along with `setHeaders` when setting the
|
|
40
|
+
* `x-hasura-role` header, as the last call will override any previous ones.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* nhost.setRole('admin')
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @docs https://docs.nhost.io/reference/javascript/set-role
|
|
48
|
+
*/
|
|
49
|
+
setRole(role: string): void;
|
|
50
|
+
/**
|
|
51
|
+
* Use `nhost.unsetRole` to unset the user role for all subsequent graphql, storage and functions calls.
|
|
52
|
+
* Underneath, this method removes the `x-hasura-role` header from the graphql, storage and functions clients.
|
|
53
|
+
*
|
|
54
|
+
* Note: Exercise caution when mixing the use of `unsetRole` along with `setHeaders` when setting the
|
|
55
|
+
* `x-hasura-role` header, as the last call will override any previous ones.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* nhost.unsetRole('admin')
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* @docs https://docs.nhost.io/reference/javascript/set-role
|
|
63
|
+
*/
|
|
64
|
+
unsetRole(): void;
|
|
28
65
|
}
|
|
29
66
|
//# sourceMappingURL=nhost.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nhost.d.ts","sourceRoot":"","sources":["../../src/clients/nhost.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACtD,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,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E,OAAO,CAAA;IAE3B;;;;;;;;;OASG;gBACS,EACV,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,QAAQ,EACR,KAAY,EACZ,GAAG,SAAS,EACb,EAAE,4BAA4B;IA0C/B,IAAI,WAAW,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED,IAAI,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAM3C;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM;IAMpB;;;;;;;;;;;;;OAaG;IACH,SAAS;CAOV"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@nhost/hasura-auth-js"),p=require("@nhost/hasura-storage-js"),C=require("isomorphic-unfetch"),k=require("@nhost/graphql-js"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@nhost/hasura-auth-js"),p=require("@nhost/hasura-storage-js"),C=require("isomorphic-unfetch"),k=require("@nhost/graphql-js"),q=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{subdomain:s,region:n}=t;if(!s)throw new Error("A `subdomain` must be set.");const u=s.match(q);if(u!=null&&u.groups){const{protocol:h,host:a,port:c}=u.groups,r=U(e);return r||(a==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${h||"http"}://localhost:${c||1337}/v1/${e}`):c?`${h||"https"}://local.${e}.nhost.run:${c}/v1`:`${h||"https"}://local.${e}.nhost.run/v1`)}if(!n)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${s}.${e}.${n}.nhost.run/v1`}function y(){return typeof window!="undefined"}function H(){return typeof process!="undefined"&&process.env}function U(t){return y()||!H()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function v(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function T(t){const e="subdomain"in t?d(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new g.HasuraAuthClient({url:e,...t})}function b(t){const e="subdomain"in t?d(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new w({url:e,...t})}class w{constructor(e){this.headers={};const{url:s,adminSecret:n}=e;this.url=s,this.accessToken=null,this.adminSecret=n}async call(e,s,n){var a,c;const u={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers,...this.headers},h=v(this.url,e);try{const r=await C(h,{body:s?JSON.stringify(s):null,headers:u,method:"POST"});if(!r.ok){let i;return(a=r.headers.get("content-type"))!=null&&a.includes("application/json")?i=await r.json():i=await r.text(),{res:null,error:{message:i,error:r.statusText,status:r.status}}}let o;return(c=r.headers.get("content-type"))!=null&&c.includes("application/json")?o=await r.json():o=await r.text(),{res:{data:o,status:r.status,statusText:r.statusText},error:null}}catch(r){const o=r;return{res:null,error:{message:o.message,status:o.name==="AbortError"?0:500,error:o.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function m(t){const e="subdomain"in t?d(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new k.NhostGraphqlClient({url:e,...t})}function A(t){const e="subdomain"in t?d(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new p.HasuraStorageClient({url:e,...t})}const E=t=>new S(t);class S{constructor({refreshIntervalTime:e,clientStorage:s,clientStorageType:n,autoRefreshToken:u,autoSignIn:h,adminSecret:a,devTools:c,start:r=!0,...o}){this.auth=T({refreshIntervalTime:e,clientStorage:s,clientStorageType:n,autoRefreshToken:u,autoSignIn:h,start:r,...o}),this.storage=A({adminSecret:a,...o}),this.functions=b({adminSecret:a,...o}),this.graphql=m({adminSecret:a,...o}),this.auth.onAuthStateChanged((i,l)=>{if(i==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const f=l==null?void 0:l.accessToken;this.storage.setAccessToken(f),this.functions.setAccessToken(f),this.graphql.setAccessToken(f)}),this.auth.onTokenChanged(i=>{const l=i==null?void 0:i.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=a,this.devTools=c}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}setRole(e){this.graphql.setHeaders({"x-hasura-role":e}),this.storage.setHeaders({"x-hasura-role":e}),this.functions.setHeaders({"x-hasura-role":e})}unsetRole(){this.graphql.setHeaders((({"x-hasura-role":e,...s})=>s)(this.graphql.getHeaders())),this.storage.setHeaders((({"x-hasura-role":e,...s})=>s)(this.storage.getHeaders())),this.functions.setHeaders((({"x-hasura-role":e,...s})=>s)(this.functions.getHeaders()))}}exports.NhostClient=S;exports.NhostFunctionsClient=w;exports.createAuthClient=T;exports.createFunctionsClient=b;exports.createGraphqlClient=m;exports.createNhostClient=E;exports.createStorageClient=A;exports.urlFromSubdomain=d;Object.keys(g).forEach(t=>{t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>g[t]})});Object.keys(p).forEach(t=>{t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>p[t]})});
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -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.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__\"\nexport const LOCALHOST_REGEX =\n /^((?<protocol>http[s]?):\\/\\/)?(?<host>(localhost|local))(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * \\`subdomain\\` and `region` should be used when running the Nhost platform\n *\n * @param subdomainAndRegion\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n subdomainAndRegion: Pick<NhostClientConstructorParams, 'region' | 'subdomain'>,\n service: string\n): string {\n const { subdomain, region } = subdomainAndRegion\n\n if (!subdomain) {\n throw new Error('A `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] or [http[s]://]local[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol, host, port } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n\n if (host === 'localhost') {\n console.warn(\n 'The `subdomain` is set to \"localhost\". Support for this will be removed in a future release. Please use \"local\" instead.'\n )\n\n return `${protocol || 'http'}://localhost:${port || 1337}/v1/${service}`\n }\n\n return port\n ? `${protocol || 'https'}://local.${service}.nhost.run:${port}/v1`\n : `${protocol || 'https'}://local.${service}.nhost.run/v1`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"local\".')\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\n/**\n * Combines a base URL and a path into a single URL string.\n *\n * @param baseUrl - The base URL to use.\n * @param path - The path to append to the base URL.\n * @returns The combined URL string.\n */\nexport function buildUrl(baseUrl: string, path: string) {\n const hasLeadingSlash = path.startsWith('/')\n const urlPath = hasLeadingSlash ? path : `/${path}`\n return baseUrl + urlPath\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 = 'subdomain' in params ? urlFromSubdomain(params, 'auth') : 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 'isomorphic-unfetch'\nimport { buildUrl, 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\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 /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic\n * types to specify the expected response data, request body and error message.\n *\n * @example\n * ### Without generic types\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @example\n * ### Using generic types\n * ```ts\n * type Data = {\n * message: string\n * }\n *\n * type Body = {\n * email: string\n * name: string\n * }\n *\n * type ErrorMessage = {\n * details: string\n * }\n *\n * // The function will only accept a body of type `Body`\n * const { res, error } = await nhost.functions.call<Data, Body, ErrorMessage>(\n * 'send-welcome-email',\n * { email: 'joe@example.com', name: 'Joe Doe' }\n * )\n *\n * // Now the response data is typed as `Data`\n * console.log(res?.data.message)\n *\n * // Now the error message is typed as `ErrorMessage`\n * console.log(error?.message.details)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<TData = unknown, TBody = any, TErrorMessage = any>(\n url: string,\n body?: TBody | null,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<TData, TErrorMessage>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n const fullUrl = buildUrl(this.url, url)\n\n try {\n const result = await fetch(fullUrl, {\n body: body ? JSON.stringify(body) : null,\n headers,\n method: 'POST'\n })\n\n if (!result.ok) {\n let message: TErrorMessage\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n message = await result.json()\n } else {\n message = (await result.text()) as unknown as TErrorMessage\n }\n\n return {\n res: null,\n error: {\n message,\n error: result.statusText,\n status: result.status\n }\n }\n }\n\n let data: TData\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n data = await result.json()\n } else {\n data = (await result.text()) as unknown as TData\n }\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 as unknown as TErrorMessage,\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 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 { 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(params: NhostClientConstructorParams) {\n const graphqlUrl = 'subdomain' in params ? urlFromSubdomain(params, 'graphql') : 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) {\n const storageUrl = 'subdomain' in params ? urlFromSubdomain(params, 'storage') : 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 { 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 = (params: NhostClientConstructorParams) => new NhostClient(params)\n\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 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 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 return\n }\n\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\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","subdomainAndRegion","service","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","buildUrl","baseUrl","path","urlPath","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","fullUrl","result","fetch","message","_a","data","_b","e","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","event","session","newValue"],"mappings":"8NAGaA,EACX,sFASc,SAAAC,EACdC,EACAC,EACQ,CACF,KAAA,CAAE,UAAAC,EAAW,OAAAC,CAAW,EAAAH,EAE9B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,4BAA4B,EAIxC,MAAAE,EAA0BF,EAAU,MAAMJ,CAAe,EAC/D,GAAIM,GAAA,MAAAA,EAAyB,OAAQ,CACnC,KAAM,CAAE,SAAAC,EAAU,KAAAC,EAAM,KAAAC,CAAA,EAASH,EAAwB,OAEnDI,EAAaC,EAAgBR,CAAO,EAC1C,OAAIO,IAIAF,IAAS,aACH,QAAA,KACN,0HAAA,EAGK,GAAGD,GAAY,MAAM,gBAAgBE,GAAQ,IAAI,OAAON,CAAO,IAGjEM,EACH,GAAGF,GAAY,OAAO,YAAYJ,CAAO,cAAcM,CAAI,MAC3D,GAAGF,GAAY,OAAO,YAAYJ,CAAO,gBAC/C,CAEA,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,mEAAmE,EAGrF,MAAO,WAAW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EACpC,KAAA,QAAQ,eAAeA,CAAW,CAAA,CACxC,EAED,KAAK,aAAeb,EACpB,KAAK,SAAW2B,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__\"\nexport const LOCALHOST_REGEX =\n /^((?<protocol>http[s]?):\\/\\/)?(?<host>(localhost|local))(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * \\`subdomain\\` and `region` should be used when running the Nhost platform\n *\n * @param subdomainAndRegion\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n subdomainAndRegion: Pick<NhostClientConstructorParams, 'region' | 'subdomain'>,\n service: string\n): string {\n const { subdomain, region } = subdomainAndRegion\n\n if (!subdomain) {\n throw new Error('A `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] or [http[s]://]local[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol, host, port } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n\n if (host === 'localhost') {\n console.warn(\n 'The `subdomain` is set to \"localhost\". Support for this will be removed in a future release. Please use \"local\" instead.'\n )\n\n return `${protocol || 'http'}://localhost:${port || 1337}/v1/${service}`\n }\n\n return port\n ? `${protocol || 'https'}://local.${service}.nhost.run:${port}/v1`\n : `${protocol || 'https'}://local.${service}.nhost.run/v1`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"local\".')\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\n/**\n * Combines a base URL and a path into a single URL string.\n *\n * @param baseUrl - The base URL to use.\n * @param path - The path to append to the base URL.\n * @returns The combined URL string.\n */\nexport function buildUrl(baseUrl: string, path: string) {\n const hasLeadingSlash = path.startsWith('/')\n const urlPath = hasLeadingSlash ? path : `/${path}`\n return baseUrl + urlPath\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 = 'subdomain' in params ? urlFromSubdomain(params, 'auth') : 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 'isomorphic-unfetch'\nimport { buildUrl, 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 ? urlFromSubdomain(params, 'functions') : 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 private headers: Record<string, 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 /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic\n * types to specify the expected response data, request body and error message.\n *\n * @example\n * ### Without generic types\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @example\n * ### Using generic types\n * ```ts\n * type Data = {\n * message: string\n * }\n *\n * type Body = {\n * email: string\n * name: string\n * }\n *\n * type ErrorMessage = {\n * details: string\n * }\n *\n * // The function will only accept a body of type `Body`\n * const { res, error } = await nhost.functions.call<Data, Body, ErrorMessage>(\n * 'send-welcome-email',\n * { email: 'joe@example.com', name: 'Joe Doe' }\n * )\n *\n * // Now the response data is typed as `Data`\n * console.log(res?.data.message)\n *\n * // Now the error message is typed as `ErrorMessage`\n * console.log(error?.message.details)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<TData = unknown, TBody = any, TErrorMessage = any>(\n url: string,\n body?: TBody | null,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<TData, TErrorMessage>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers,\n ...this.headers // nhost functions client headers to be sent with all calls\n }\n\n const fullUrl = buildUrl(this.url, url)\n\n try {\n const result = await fetch(fullUrl, {\n body: body ? JSON.stringify(body) : null,\n headers,\n method: 'POST'\n })\n\n if (!result.ok) {\n let message: TErrorMessage\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n message = await result.json()\n } else {\n message = (await result.text()) as unknown as TErrorMessage\n }\n\n return {\n res: null,\n error: {\n message,\n error: result.statusText,\n status: result.status\n }\n }\n }\n\n let data: TData\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n data = await result.json()\n } else {\n data = (await result.text()) as unknown as TData\n }\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 as unknown as TErrorMessage,\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 /**\n * Use `nhost.functions.getHeaders` to get the global headers sent with all functions requests.\n *\n * @example\n * ```ts\n * nhost.functions.getHeaders()\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/get-headers\n */\n getHeaders(): Record<string, string> {\n return this.headers\n }\n\n /**\n * Use `nhost.functions.setHeaders` to a set global headers to be sent in all subsequent functions requests.\n *\n * @example\n * ```ts\n * nhost.functions.setHeaders({\n * 'x-hasura-role': 'admin'\n * })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-headers\n */\n setHeaders(headers?: Record<string, string>) {\n if (!headers) {\n return\n }\n\n this.headers = {\n ...this.headers,\n ...headers\n }\n }\n\n /**\n * Use `nhost.functions.unsetHeaders` to a unset global headers sent with all functions requests.\n *\n * @example\n * ```ts\n * nhost.functions.unsetHeaders()\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/unset-headers\n */\n unsetHeaders() {\n const userRole = this.headers['x-hasura-role']\n\n // preserve the user role header to avoid invalidating preceding 'setRole' call.\n this.headers = userRole ? { 'x-hasura-role': userRole } : {}\n }\n\n 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 { 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(params: NhostClientConstructorParams) {\n const graphqlUrl = 'subdomain' in params ? urlFromSubdomain(params, 'graphql') : 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) {\n const storageUrl = 'subdomain' in params ? urlFromSubdomain(params, 'storage') : 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 { 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 = (params: NhostClientConstructorParams) => new NhostClient(params)\n\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 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 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 return\n }\n\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\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 /**\n * Use `nhost.setRole` to set the user role for all subsequent GraphQL, storage, and functions calls.\n * Underneath, this method sets the `x-hasura-role` header on the graphql, storage,\n * and functions clients.\n *\n * ```ts\n * nhost.graphql.setHeaders({ 'x-hasura-role': role })\n * nhost.storage.setHeaders({ 'x-hasura-role': role })\n * nhost.functions.setHeaders({ 'x-hasura-role': role })\n * ```\n *\n * Note: Exercise caution when mixing the use of `setRole` along with `setHeaders` when setting the\n * `x-hasura-role` header, as the last call will override any previous ones.\n *\n * @example\n * ```ts\n * nhost.setRole('admin')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/set-role\n */\n setRole(role: string) {\n this.graphql.setHeaders({ 'x-hasura-role': role })\n this.storage.setHeaders({ 'x-hasura-role': role })\n this.functions.setHeaders({ 'x-hasura-role': role })\n }\n\n /**\n * Use `nhost.unsetRole` to unset the user role for all subsequent graphql, storage and functions calls.\n * Underneath, this method removes the `x-hasura-role` header from the graphql, storage and functions clients.\n *\n * Note: Exercise caution when mixing the use of `unsetRole` along with `setHeaders` when setting the\n * `x-hasura-role` header, as the last call will override any previous ones.\n *\n * @example\n * ```ts\n * nhost.unsetRole('admin')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/set-role\n */\n unsetRole() {\n this.graphql.setHeaders((({ 'x-hasura-role': _, ...rest }) => rest)(this.graphql.getHeaders()))\n this.storage.setHeaders((({ 'x-hasura-role': _, ...rest }) => rest)(this.storage.getHeaders()))\n this.functions.setHeaders(\n (({ 'x-hasura-role': _, ...rest }) => rest)(this.functions.getHeaders())\n )\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","subdomainAndRegion","service","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","buildUrl","baseUrl","path","urlPath","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","fullUrl","result","fetch","message","_a","data","_b","e","error","accessToken","userRole","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoR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AA,EACjD,KAAK,QAAQ,WAAW,CAAE,gBAAiBA,CAAM,CAAA,EACjD,KAAK,UAAU,WAAW,CAAE,gBAAiBA,CAAM,CAAA,CACrD,CAgBA,WAAY,CACV,KAAK,QAAQ,YAAY,CAAC,CAAE,gBAAiBC,EAAG,GAAGC,CAAK,IAAMA,GAAM,KAAK,QAAQ,WAAA,CAAY,CAAC,EAC9F,KAAK,QAAQ,YAAY,CAAC,CAAE,gBAAiBD,EAAG,GAAGC,CAAK,IAAMA,GAAM,KAAK,QAAQ,WAAA,CAAY,CAAC,EAC9F,KAAK,UAAU,YACZ,CAAC,CAAE,gBAAiBD,EAAG,GAAGC,KAAWA,GAAM,KAAK,UAAU,YAAY,CAAA,CAE3E,CACF"}
|
package/dist/index.esm.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import { HasuraAuthClient as
|
|
1
|
+
import { HasuraAuthClient as g } from "@nhost/hasura-auth-js";
|
|
2
2
|
export * from "@nhost/hasura-auth-js";
|
|
3
|
-
import { HasuraStorageClient as
|
|
3
|
+
import { HasuraStorageClient as p } from "@nhost/hasura-storage-js";
|
|
4
4
|
export * from "@nhost/hasura-storage-js";
|
|
5
5
|
import T from "isomorphic-unfetch";
|
|
6
6
|
import { NhostGraphqlClient as m } from "@nhost/graphql-js";
|
|
7
7
|
const w = /^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;
|
|
8
8
|
function d(e, t) {
|
|
9
|
-
const { subdomain:
|
|
10
|
-
if (!
|
|
9
|
+
const { subdomain: r, region: n } = e;
|
|
10
|
+
if (!r)
|
|
11
11
|
throw new Error("A `subdomain` must be set.");
|
|
12
|
-
const
|
|
13
|
-
if (
|
|
14
|
-
const { protocol:
|
|
15
|
-
return
|
|
12
|
+
const h = r.match(w);
|
|
13
|
+
if (h != null && h.groups) {
|
|
14
|
+
const { protocol: c, host: a, port: u } = h.groups, s = b(t);
|
|
15
|
+
return s || (a === "localhost" ? (console.warn(
|
|
16
16
|
'The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'
|
|
17
|
-
), `${
|
|
17
|
+
), `${c || "http"}://localhost:${u || 1337}/v1/${t}`) : u ? `${c || "https"}://local.${t}.nhost.run:${u}/v1` : `${c || "https"}://local.${t}.nhost.run/v1`);
|
|
18
18
|
}
|
|
19
19
|
if (!n)
|
|
20
20
|
throw new Error('`region` must be set when using a `subdomain` other than "local".');
|
|
21
|
-
return `https://${
|
|
21
|
+
return `https://${r}.${t}.${n}.nhost.run/v1`;
|
|
22
22
|
}
|
|
23
23
|
function k() {
|
|
24
24
|
return typeof window != "undefined";
|
|
@@ -33,22 +33,23 @@ function S(e, t) {
|
|
|
33
33
|
const n = t.startsWith("/") ? t : `/${t}`;
|
|
34
34
|
return e + n;
|
|
35
35
|
}
|
|
36
|
-
function
|
|
36
|
+
function H(e) {
|
|
37
37
|
const t = "subdomain" in e ? d(e, "auth") : e.authUrl;
|
|
38
38
|
if (!t)
|
|
39
39
|
throw new Error("Please provide `subdomain` or `authUrl`.");
|
|
40
|
-
return new
|
|
40
|
+
return new g({ url: t, ...e });
|
|
41
41
|
}
|
|
42
|
-
function
|
|
42
|
+
function x(e) {
|
|
43
43
|
const t = "subdomain" in e ? d(e, "functions") : e.functionsUrl;
|
|
44
44
|
if (!t)
|
|
45
45
|
throw new Error("Please provide `subdomain` or `functionsUrl`.");
|
|
46
|
-
return new
|
|
46
|
+
return new U({ url: t, ...e });
|
|
47
47
|
}
|
|
48
|
-
class
|
|
48
|
+
class U {
|
|
49
49
|
constructor(t) {
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
this.headers = {};
|
|
51
|
+
const { url: r, adminSecret: n } = t;
|
|
52
|
+
this.url = r, this.accessToken = null, this.adminSecret = n;
|
|
52
53
|
}
|
|
53
54
|
/**
|
|
54
55
|
* Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic
|
|
@@ -91,43 +92,45 @@ class C {
|
|
|
91
92
|
*
|
|
92
93
|
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call
|
|
93
94
|
*/
|
|
94
|
-
async call(t,
|
|
95
|
-
var
|
|
96
|
-
const
|
|
95
|
+
async call(t, r, n) {
|
|
96
|
+
var a, u;
|
|
97
|
+
const h = {
|
|
97
98
|
"Content-Type": "application/json",
|
|
98
99
|
...this.generateAccessTokenHeaders(),
|
|
99
|
-
...n == null ? void 0 : n.headers
|
|
100
|
-
|
|
100
|
+
...n == null ? void 0 : n.headers,
|
|
101
|
+
...this.headers
|
|
102
|
+
// nhost functions client headers to be sent with all calls
|
|
103
|
+
}, c = S(this.url, t);
|
|
101
104
|
try {
|
|
102
|
-
const
|
|
103
|
-
body:
|
|
104
|
-
headers:
|
|
105
|
+
const s = await T(c, {
|
|
106
|
+
body: r ? JSON.stringify(r) : null,
|
|
107
|
+
headers: h,
|
|
105
108
|
method: "POST"
|
|
106
109
|
});
|
|
107
|
-
if (!
|
|
108
|
-
let
|
|
109
|
-
return (
|
|
110
|
+
if (!s.ok) {
|
|
111
|
+
let i;
|
|
112
|
+
return (a = s.headers.get("content-type")) != null && a.includes("application/json") ? i = await s.json() : i = await s.text(), {
|
|
110
113
|
res: null,
|
|
111
114
|
error: {
|
|
112
|
-
message:
|
|
113
|
-
error:
|
|
114
|
-
status:
|
|
115
|
+
message: i,
|
|
116
|
+
error: s.statusText,
|
|
117
|
+
status: s.status
|
|
115
118
|
}
|
|
116
119
|
};
|
|
117
120
|
}
|
|
118
|
-
let
|
|
119
|
-
return (u =
|
|
120
|
-
res: { data:
|
|
121
|
+
let o;
|
|
122
|
+
return (u = s.headers.get("content-type")) != null && u.includes("application/json") ? o = await s.json() : o = await s.text(), {
|
|
123
|
+
res: { data: o, status: s.status, statusText: s.statusText },
|
|
121
124
|
error: null
|
|
122
125
|
};
|
|
123
|
-
} catch (
|
|
124
|
-
const
|
|
126
|
+
} catch (s) {
|
|
127
|
+
const o = s;
|
|
125
128
|
return {
|
|
126
129
|
res: null,
|
|
127
130
|
error: {
|
|
128
|
-
message:
|
|
129
|
-
status:
|
|
130
|
-
error:
|
|
131
|
+
message: o.message,
|
|
132
|
+
status: o.name === "AbortError" ? 0 : 500,
|
|
133
|
+
error: o.name === "AbortError" ? "abort-error" : "unknown"
|
|
131
134
|
}
|
|
132
135
|
};
|
|
133
136
|
}
|
|
@@ -149,6 +152,51 @@ class C {
|
|
|
149
152
|
}
|
|
150
153
|
this.accessToken = t;
|
|
151
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Use `nhost.functions.getHeaders` to get the global headers sent with all functions requests.
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```ts
|
|
160
|
+
* nhost.functions.getHeaders()
|
|
161
|
+
* ```
|
|
162
|
+
*
|
|
163
|
+
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/get-headers
|
|
164
|
+
*/
|
|
165
|
+
getHeaders() {
|
|
166
|
+
return this.headers;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Use `nhost.functions.setHeaders` to a set global headers to be sent in all subsequent functions requests.
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```ts
|
|
173
|
+
* nhost.functions.setHeaders({
|
|
174
|
+
* 'x-hasura-role': 'admin'
|
|
175
|
+
* })
|
|
176
|
+
* ```
|
|
177
|
+
*
|
|
178
|
+
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-headers
|
|
179
|
+
*/
|
|
180
|
+
setHeaders(t) {
|
|
181
|
+
t && (this.headers = {
|
|
182
|
+
...this.headers,
|
|
183
|
+
...t
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Use `nhost.functions.unsetHeaders` to a unset global headers sent with all functions requests.
|
|
188
|
+
*
|
|
189
|
+
* @example
|
|
190
|
+
* ```ts
|
|
191
|
+
* nhost.functions.unsetHeaders()
|
|
192
|
+
* ```
|
|
193
|
+
*
|
|
194
|
+
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/unset-headers
|
|
195
|
+
*/
|
|
196
|
+
unsetHeaders() {
|
|
197
|
+
const t = this.headers["x-hasura-role"];
|
|
198
|
+
this.headers = t ? { "x-hasura-role": t } : {};
|
|
199
|
+
}
|
|
152
200
|
generateAccessTokenHeaders() {
|
|
153
201
|
return this.adminSecret ? {
|
|
154
202
|
"x-hasura-admin-secret": this.adminSecret
|
|
@@ -157,20 +205,20 @@ class C {
|
|
|
157
205
|
} : {};
|
|
158
206
|
}
|
|
159
207
|
}
|
|
160
|
-
function
|
|
208
|
+
function v(e) {
|
|
161
209
|
const t = "subdomain" in e ? d(e, "graphql") : e.graphqlUrl;
|
|
162
210
|
if (!t)
|
|
163
211
|
throw new Error("Please provide `subdomain` or `graphqlUrl`.");
|
|
164
212
|
return new m({ url: t, ...e });
|
|
165
213
|
}
|
|
166
|
-
function
|
|
214
|
+
function C(e) {
|
|
167
215
|
const t = "subdomain" in e ? d(e, "storage") : e.storageUrl;
|
|
168
216
|
if (!t)
|
|
169
217
|
throw new Error("Please provide `subdomain` or `storageUrl`.");
|
|
170
|
-
return new
|
|
218
|
+
return new p({ url: t, ...e });
|
|
171
219
|
}
|
|
172
|
-
const
|
|
173
|
-
class
|
|
220
|
+
const N = (e) => new $(e);
|
|
221
|
+
class $ {
|
|
174
222
|
/**
|
|
175
223
|
* Nhost Client
|
|
176
224
|
*
|
|
@@ -183,34 +231,34 @@ class _ {
|
|
|
183
231
|
*/
|
|
184
232
|
constructor({
|
|
185
233
|
refreshIntervalTime: t,
|
|
186
|
-
clientStorage:
|
|
234
|
+
clientStorage: r,
|
|
187
235
|
clientStorageType: n,
|
|
188
|
-
autoRefreshToken:
|
|
189
|
-
autoSignIn:
|
|
190
|
-
adminSecret:
|
|
236
|
+
autoRefreshToken: h,
|
|
237
|
+
autoSignIn: c,
|
|
238
|
+
adminSecret: a,
|
|
191
239
|
devTools: u,
|
|
192
|
-
start:
|
|
193
|
-
...
|
|
240
|
+
start: s = !0,
|
|
241
|
+
...o
|
|
194
242
|
}) {
|
|
195
|
-
this.auth =
|
|
243
|
+
this.auth = H({
|
|
196
244
|
refreshIntervalTime: t,
|
|
197
|
-
clientStorage:
|
|
245
|
+
clientStorage: r,
|
|
198
246
|
clientStorageType: n,
|
|
199
|
-
autoRefreshToken:
|
|
200
|
-
autoSignIn:
|
|
201
|
-
start:
|
|
202
|
-
...
|
|
203
|
-
}), this.storage =
|
|
204
|
-
if (
|
|
247
|
+
autoRefreshToken: h,
|
|
248
|
+
autoSignIn: c,
|
|
249
|
+
start: s,
|
|
250
|
+
...o
|
|
251
|
+
}), this.storage = C({ adminSecret: a, ...o }), this.functions = x({ adminSecret: a, ...o }), this.graphql = v({ adminSecret: a, ...o }), this.auth.onAuthStateChanged((i, l) => {
|
|
252
|
+
if (i === "SIGNED_OUT") {
|
|
205
253
|
this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0);
|
|
206
254
|
return;
|
|
207
255
|
}
|
|
208
|
-
const f =
|
|
256
|
+
const f = l == null ? void 0 : l.accessToken;
|
|
209
257
|
this.storage.setAccessToken(f), this.functions.setAccessToken(f), this.graphql.setAccessToken(f);
|
|
210
|
-
}), this.auth.onTokenChanged((
|
|
211
|
-
const
|
|
212
|
-
this.storage.setAccessToken(
|
|
213
|
-
}), this._adminSecret =
|
|
258
|
+
}), this.auth.onTokenChanged((i) => {
|
|
259
|
+
const l = i == null ? void 0 : i.accessToken;
|
|
260
|
+
this.storage.setAccessToken(l), this.functions.setAccessToken(l), this.graphql.setAccessToken(l);
|
|
261
|
+
}), this._adminSecret = a, this.devTools = u;
|
|
214
262
|
}
|
|
215
263
|
get adminSecret() {
|
|
216
264
|
return this._adminSecret;
|
|
@@ -218,15 +266,58 @@ class _ {
|
|
|
218
266
|
set adminSecret(t) {
|
|
219
267
|
this._adminSecret = t, this.storage.setAdminSecret(t);
|
|
220
268
|
}
|
|
269
|
+
/**
|
|
270
|
+
* Use `nhost.setRole` to set the user role for all subsequent GraphQL, storage, and functions calls.
|
|
271
|
+
* Underneath, this method sets the `x-hasura-role` header on the graphql, storage,
|
|
272
|
+
* and functions clients.
|
|
273
|
+
*
|
|
274
|
+
* ```ts
|
|
275
|
+
* nhost.graphql.setHeaders({ 'x-hasura-role': role })
|
|
276
|
+
* nhost.storage.setHeaders({ 'x-hasura-role': role })
|
|
277
|
+
* nhost.functions.setHeaders({ 'x-hasura-role': role })
|
|
278
|
+
* ```
|
|
279
|
+
*
|
|
280
|
+
* Note: Exercise caution when mixing the use of `setRole` along with `setHeaders` when setting the
|
|
281
|
+
* `x-hasura-role` header, as the last call will override any previous ones.
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* ```ts
|
|
285
|
+
* nhost.setRole('admin')
|
|
286
|
+
* ```
|
|
287
|
+
*
|
|
288
|
+
* @docs https://docs.nhost.io/reference/javascript/set-role
|
|
289
|
+
*/
|
|
290
|
+
setRole(t) {
|
|
291
|
+
this.graphql.setHeaders({ "x-hasura-role": t }), this.storage.setHeaders({ "x-hasura-role": t }), this.functions.setHeaders({ "x-hasura-role": t });
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Use `nhost.unsetRole` to unset the user role for all subsequent graphql, storage and functions calls.
|
|
295
|
+
* Underneath, this method removes the `x-hasura-role` header from the graphql, storage and functions clients.
|
|
296
|
+
*
|
|
297
|
+
* Note: Exercise caution when mixing the use of `unsetRole` along with `setHeaders` when setting the
|
|
298
|
+
* `x-hasura-role` header, as the last call will override any previous ones.
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
* ```ts
|
|
302
|
+
* nhost.unsetRole('admin')
|
|
303
|
+
* ```
|
|
304
|
+
*
|
|
305
|
+
* @docs https://docs.nhost.io/reference/javascript/set-role
|
|
306
|
+
*/
|
|
307
|
+
unsetRole() {
|
|
308
|
+
this.graphql.setHeaders((({ "x-hasura-role": t, ...r }) => r)(this.graphql.getHeaders())), this.storage.setHeaders((({ "x-hasura-role": t, ...r }) => r)(this.storage.getHeaders())), this.functions.setHeaders(
|
|
309
|
+
(({ "x-hasura-role": t, ...r }) => r)(this.functions.getHeaders())
|
|
310
|
+
);
|
|
311
|
+
}
|
|
221
312
|
}
|
|
222
313
|
export {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
314
|
+
$ as NhostClient,
|
|
315
|
+
U as NhostFunctionsClient,
|
|
316
|
+
H as createAuthClient,
|
|
317
|
+
x as createFunctionsClient,
|
|
318
|
+
v as createGraphqlClient,
|
|
319
|
+
N as createNhostClient,
|
|
320
|
+
C as createStorageClient,
|
|
230
321
|
d as urlFromSubdomain
|
|
231
322
|
};
|
|
232
323
|
//# sourceMappingURL=index.esm.js.map
|