@nhost/nhost-js 3.1.10 → 3.2.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/auth.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 +43 -39
- package/dist/index.esm.js.map +1 -1
- package/dist/utils/types.d.ts +1 -1
- package/dist/utils/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/umd/nhost-js.umd.js +9 -9
- package/umd/nhost-js.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/clients/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,4BAA4B,
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/clients/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAGxD,OAAO,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAE7D;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,4BAA4B,oBAcpE"}
|
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"),q=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{subdomain:
|
|
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:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const u=r.match(q);if(u!=null&&u.groups){const{protocol:h,host:a,port:c}=u.groups,s=U(e);return s||(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://${r}.${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 $(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function b(t){const e="subdomain"in t?d(t,"auth"):t.authUrl,{subdomain:r,region:n}=t;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new g.HasuraAuthClient({url:e,broadcastKey:`${r}${n!=null?n:"local"}`,...t})}function T(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:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var a,c;const u={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers,...this.headers},h=$(this.url,e);try{const s=await C(h,{body:r?JSON.stringify(r):null,headers:u,method:"POST"});if(!s.ok){let i;return(a=s.headers.get("content-type"))!=null&&a.includes("application/json")?i=await s.json():i=await s.text(),{res:null,error:{message:i,error:s.statusText,status:s.status}}}let o;return(c=s.headers.get("content-type"))!=null&&c.includes("application/json")?o=await s.json():o=await s.text(),{res:{data:o,status:s.status,statusText:s.statusText},error:null}}catch(s){const o=s;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 v=t=>new S(t);class S{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:u,autoSignIn:h,adminSecret:a,devTools:c,start:s=!0,...o}){this.auth=b({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:u,autoSignIn:h,start:s,...o}),this.storage=A({adminSecret:a,...o}),this.functions=T({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,...r})=>r)(this.graphql.getHeaders())),this.storage.setHeaders((({"x-hasura-role":e,...r})=>r)(this.storage.getHeaders())),this.functions.setHeaders((({"x-hasura-role":e,...r})=>r)(this.functions.getHeaders()))}}exports.NhostClient=S;exports.NhostFunctionsClient=w;exports.createAuthClient=b;exports.createFunctionsClient=T;exports.createGraphqlClient=m;exports.createNhostClient=v;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 ? 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 *\n * @example\n * ```ts\n * // Create a new Nhost client from subdomain and region.\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client from individual service URLs (custom domains, self-hosting, etc).\n * const nhost = new NhostClient({ \n * authUrl: \"my-auth-service-url\",\n * storageUrl: \"my-storage-service-url\",\n * graphqlUrl: \"my-graphql-service-url\",\n * functionsUrl: \"my-functions-service-url\",\n * });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client for local development.\n * const nhost = new NhostClient({ subdomain: \"local\" });\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/nhost-js/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()\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/unset-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","autoRefreshToken","autoSignIn","devTools","start","urlParams","event","session","newValue","role","_","rest"],"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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/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 const { subdomain, region } = params\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({\n url: authUrl,\n broadcastKey: `${subdomain}${region ?? 'local'}`,\n ...params\n })\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 *\n * @example\n * ```ts\n * // Create a new Nhost client from subdomain and region.\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client from individual service URLs (custom domains, self-hosting, etc).\n * const nhost = new NhostClient({\n * authUrl: \"my-auth-service-url\",\n * storageUrl: \"my-storage-service-url\",\n * graphqlUrl: \"my-graphql-service-url\",\n * functionsUrl: \"my-functions-service-url\",\n * });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client for local development.\n * const nhost = new NhostClient({ subdomain: \"local\" });\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/nhost-js/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()\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/unset-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","autoRefreshToken","autoSignIn","devTools","start","urlParams","event","session","newValue","role","_","rest"],"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,WAAWD,CAAS,IAAID,CAAO,IAAIE,CAAM,eAClD,CAMA,SAASO,GAAqB,CAC5B,OAAO,OAAO,QAAW,WAC3B,CAMA,SAASC,GAAyB,CACzB,OAAA,OAAO,SAAY,aAAe,QAAQ,GACnD,CAQA,SAASF,EAAgBR,EAAiB,CACxC,OAAIS,EAAU,GAAK,CAACC,IACX,KAGF,QAAQ,IAAI,SAASV,EAAQ,YAAa,CAAA,MAAM,CACzD,CASgB,SAAAW,EAASC,EAAiBC,EAAc,CAEtD,MAAMC,EADkBD,EAAK,WAAW,GAAG,EACTA,EAAO,IAAIA,CAAI,GACjD,OAAOD,EAAUE,CACnB,CCtFO,SAASC,EAAiBC,EAAsC,CACrE,MAAMC,EAAU,cAAeD,EAASlB,EAAiBkB,EAA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EA,IAAI,aAAkC,CACpC,OAAO,KAAK,YACd,CAEA,IAAI,YAAYK,EAA8B,CAC5C,KAAK,aAAeA,EACf,KAAA,QAAQ,eAAeA,CAAQ,CAItC,CAuBA,QAAQC,EAAc,CACpB,KAAK,QAAQ,WAAW,CAAE,gBAAiBA,CAAM,CAAA,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
|
@@ -6,38 +6,42 @@ 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: s, region: n } = e;
|
|
10
|
+
if (!s)
|
|
11
11
|
throw new Error("A `subdomain` must be set.");
|
|
12
|
-
const h =
|
|
12
|
+
const h = s.match(w);
|
|
13
13
|
if (h != null && h.groups) {
|
|
14
|
-
const { protocol: c, host: a, port: u } = h.groups,
|
|
15
|
-
return
|
|
14
|
+
const { protocol: c, host: a, port: u } = h.groups, r = A(t);
|
|
15
|
+
return r || (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://${s}.${t}.${n}.nhost.run/v1`;
|
|
22
22
|
}
|
|
23
23
|
function k() {
|
|
24
24
|
return typeof window != "undefined";
|
|
25
25
|
}
|
|
26
|
-
function
|
|
26
|
+
function b() {
|
|
27
27
|
return typeof process != "undefined" && process.env;
|
|
28
28
|
}
|
|
29
|
-
function
|
|
30
|
-
return k() || !
|
|
29
|
+
function A(e) {
|
|
30
|
+
return k() || !b() ? null : process.env[`NHOST_${e.toUpperCase()}_URL`];
|
|
31
31
|
}
|
|
32
32
|
function S(e, t) {
|
|
33
33
|
const n = t.startsWith("/") ? t : `/${t}`;
|
|
34
34
|
return e + n;
|
|
35
35
|
}
|
|
36
36
|
function H(e) {
|
|
37
|
-
const t = "subdomain" in e ? d(e, "auth") : e.authUrl;
|
|
37
|
+
const t = "subdomain" in e ? d(e, "auth") : e.authUrl, { subdomain: s, region: n } = e;
|
|
38
38
|
if (!t)
|
|
39
39
|
throw new Error("Please provide `subdomain` or `authUrl`.");
|
|
40
|
-
return new g({
|
|
40
|
+
return new g({
|
|
41
|
+
url: t,
|
|
42
|
+
broadcastKey: `${s}${n != null ? n : "local"}`,
|
|
43
|
+
...e
|
|
44
|
+
});
|
|
41
45
|
}
|
|
42
46
|
function x(e) {
|
|
43
47
|
const t = "subdomain" in e ? d(e, "functions") : e.functionsUrl;
|
|
@@ -48,8 +52,8 @@ function x(e) {
|
|
|
48
52
|
class U {
|
|
49
53
|
constructor(t) {
|
|
50
54
|
this.headers = {};
|
|
51
|
-
const { url:
|
|
52
|
-
this.url =
|
|
55
|
+
const { url: s, adminSecret: n } = t;
|
|
56
|
+
this.url = s, this.accessToken = null, this.adminSecret = n;
|
|
53
57
|
}
|
|
54
58
|
/**
|
|
55
59
|
* Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic
|
|
@@ -92,7 +96,7 @@ class U {
|
|
|
92
96
|
*
|
|
93
97
|
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call
|
|
94
98
|
*/
|
|
95
|
-
async call(t,
|
|
99
|
+
async call(t, s, n) {
|
|
96
100
|
var a, u;
|
|
97
101
|
const h = {
|
|
98
102
|
"Content-Type": "application/json",
|
|
@@ -102,29 +106,29 @@ class U {
|
|
|
102
106
|
// nhost functions client headers to be sent with all calls
|
|
103
107
|
}, c = S(this.url, t);
|
|
104
108
|
try {
|
|
105
|
-
const
|
|
106
|
-
body:
|
|
109
|
+
const r = await T(c, {
|
|
110
|
+
body: s ? JSON.stringify(s) : null,
|
|
107
111
|
headers: h,
|
|
108
112
|
method: "POST"
|
|
109
113
|
});
|
|
110
|
-
if (!
|
|
114
|
+
if (!r.ok) {
|
|
111
115
|
let i;
|
|
112
|
-
return (a =
|
|
116
|
+
return (a = r.headers.get("content-type")) != null && a.includes("application/json") ? i = await r.json() : i = await r.text(), {
|
|
113
117
|
res: null,
|
|
114
118
|
error: {
|
|
115
119
|
message: i,
|
|
116
|
-
error:
|
|
117
|
-
status:
|
|
120
|
+
error: r.statusText,
|
|
121
|
+
status: r.status
|
|
118
122
|
}
|
|
119
123
|
};
|
|
120
124
|
}
|
|
121
125
|
let o;
|
|
122
|
-
return (u =
|
|
123
|
-
res: { data: o, status:
|
|
126
|
+
return (u = r.headers.get("content-type")) != null && u.includes("application/json") ? o = await r.json() : o = await r.text(), {
|
|
127
|
+
res: { data: o, status: r.status, statusText: r.statusText },
|
|
124
128
|
error: null
|
|
125
129
|
};
|
|
126
|
-
} catch (
|
|
127
|
-
const o =
|
|
130
|
+
} catch (r) {
|
|
131
|
+
const o = r;
|
|
128
132
|
return {
|
|
129
133
|
res: null,
|
|
130
134
|
error: {
|
|
@@ -205,20 +209,20 @@ class U {
|
|
|
205
209
|
} : {};
|
|
206
210
|
}
|
|
207
211
|
}
|
|
208
|
-
function
|
|
212
|
+
function $(e) {
|
|
209
213
|
const t = "subdomain" in e ? d(e, "graphql") : e.graphqlUrl;
|
|
210
214
|
if (!t)
|
|
211
215
|
throw new Error("Please provide `subdomain` or `graphqlUrl`.");
|
|
212
216
|
return new m({ url: t, ...e });
|
|
213
217
|
}
|
|
214
|
-
function
|
|
218
|
+
function v(e) {
|
|
215
219
|
const t = "subdomain" in e ? d(e, "storage") : e.storageUrl;
|
|
216
220
|
if (!t)
|
|
217
221
|
throw new Error("Please provide `subdomain` or `storageUrl`.");
|
|
218
222
|
return new p({ url: t, ...e });
|
|
219
223
|
}
|
|
220
|
-
const N = (e) => new
|
|
221
|
-
class
|
|
224
|
+
const N = (e) => new C(e);
|
|
225
|
+
class C {
|
|
222
226
|
/**
|
|
223
227
|
*
|
|
224
228
|
* @example
|
|
@@ -230,7 +234,7 @@ class $ {
|
|
|
230
234
|
*
|
|
231
235
|
* ```ts
|
|
232
236
|
* // Create a new Nhost client from individual service URLs (custom domains, self-hosting, etc).
|
|
233
|
-
* const nhost = new NhostClient({
|
|
237
|
+
* const nhost = new NhostClient({
|
|
234
238
|
* authUrl: "my-auth-service-url",
|
|
235
239
|
* storageUrl: "my-storage-service-url",
|
|
236
240
|
* graphqlUrl: "my-graphql-service-url",
|
|
@@ -248,24 +252,24 @@ class $ {
|
|
|
248
252
|
*/
|
|
249
253
|
constructor({
|
|
250
254
|
refreshIntervalTime: t,
|
|
251
|
-
clientStorage:
|
|
255
|
+
clientStorage: s,
|
|
252
256
|
clientStorageType: n,
|
|
253
257
|
autoRefreshToken: h,
|
|
254
258
|
autoSignIn: c,
|
|
255
259
|
adminSecret: a,
|
|
256
260
|
devTools: u,
|
|
257
|
-
start:
|
|
261
|
+
start: r = !0,
|
|
258
262
|
...o
|
|
259
263
|
}) {
|
|
260
264
|
this.auth = H({
|
|
261
265
|
refreshIntervalTime: t,
|
|
262
|
-
clientStorage:
|
|
266
|
+
clientStorage: s,
|
|
263
267
|
clientStorageType: n,
|
|
264
268
|
autoRefreshToken: h,
|
|
265
269
|
autoSignIn: c,
|
|
266
|
-
start:
|
|
270
|
+
start: r,
|
|
267
271
|
...o
|
|
268
|
-
}), this.storage =
|
|
272
|
+
}), this.storage = v({ adminSecret: a, ...o }), this.functions = x({ adminSecret: a, ...o }), this.graphql = $({ adminSecret: a, ...o }), this.auth.onAuthStateChanged((i, l) => {
|
|
269
273
|
if (i === "SIGNED_OUT") {
|
|
270
274
|
this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0);
|
|
271
275
|
return;
|
|
@@ -322,19 +326,19 @@ class $ {
|
|
|
322
326
|
* @docs https://docs.nhost.io/reference/javascript/nhost-js/unset-role
|
|
323
327
|
*/
|
|
324
328
|
unsetRole() {
|
|
325
|
-
this.graphql.setHeaders((({ "x-hasura-role": t, ...
|
|
326
|
-
(({ "x-hasura-role": t, ...
|
|
329
|
+
this.graphql.setHeaders((({ "x-hasura-role": t, ...s }) => s)(this.graphql.getHeaders())), this.storage.setHeaders((({ "x-hasura-role": t, ...s }) => s)(this.storage.getHeaders())), this.functions.setHeaders(
|
|
330
|
+
(({ "x-hasura-role": t, ...s }) => s)(this.functions.getHeaders())
|
|
327
331
|
);
|
|
328
332
|
}
|
|
329
333
|
}
|
|
330
334
|
export {
|
|
331
|
-
|
|
335
|
+
C as NhostClient,
|
|
332
336
|
U as NhostFunctionsClient,
|
|
333
337
|
H as createAuthClient,
|
|
334
338
|
x as createFunctionsClient,
|
|
335
|
-
|
|
339
|
+
$ as createGraphqlClient,
|
|
336
340
|
N as createNhostClient,
|
|
337
|
-
|
|
341
|
+
v as createStorageClient,
|
|
338
342
|
d as urlFromSubdomain
|
|
339
343
|
};
|
|
340
344
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.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 *\n * @example\n * ```ts\n * // Create a new Nhost client from subdomain and region.\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client from individual service URLs (custom domains, self-hosting, etc).\n * const nhost = new NhostClient({ \n * authUrl: \"my-auth-service-url\",\n * storageUrl: \"my-storage-service-url\",\n * graphqlUrl: \"my-graphql-service-url\",\n * functionsUrl: \"my-functions-service-url\",\n * });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client for local development.\n * const nhost = new NhostClient({ subdomain: \"local\" });\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/nhost-js/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()\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/unset-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","autoRefreshToken","autoSignIn","devTools","start","urlParams","event","session","newValue","role","_","rest"],"mappings":";;;;;;AAGO,MAAMA,IACX;AASc,SAAAC,EACdC,GACAC,GACQ;AACF,QAAA,EAAE,WAAAC,GAAW,QAAAC,EAAW,IAAAH;AAE9B,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,4BAA4B;AAIxC,QAAAE,IAA0BF,EAAU,MAAMJ,CAAe;AAC/D,MAAIM,KAAA,QAAAA,EAAyB,QAAQ;AACnC,UAAM,EAAE,UAAAC,GAAU,MAAAC,GAAM,MAAAC,EAAA,IAASH,EAAwB,QAEnDI,IAAaC,EAAgBR,CAAO;AAC1C,WAAIO,MAIAF,MAAS,eACH,QAAA;AAAA,MACN;AAAA,IAAA,GAGK,GAAGD,KAAY,MAAM,gBAAgBE,KAAQ,IAAI,OAAON,CAAO,MAGjEM,IACH,GAAGF,KAAY,OAAO,YAAYJ,CAAO,cAAcM,CAAI,QAC3D,GAAGF,KAAY,OAAO,YAAYJ,CAAO;AAAA,EAC/C;AAEA,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,mEAAmE;AAGrF,SAAO,WAAWD,CAAS,IAAID,CAAO,IAAIE,CAAM;AAClD;AAMA,SAASO,IAAqB;AAC5B,SAAO,OAAO,UAAW;AAC3B;AAMA,SAASC,IAAyB;AACzB,SAAA,OAAO,WAAY,eAAe,QAAQ;AACnD;AAQA,SAASF,EAAgBR,GAAiB;AACxC,SAAIS,EAAU,KAAK,CAACC,MACX,OAGF,QAAQ,IAAI,SAASV,EAAQ,YAAa,CAAA,MAAM;AACzD;AASgB,SAAAW,EAASC,GAAiBC,GAAc;AAEtD,QAAMC,IADkBD,EAAK,WAAW,GAAG,IACTA,IAAO,IAAIA,CAAI;AACjD,SAAOD,IAAUE;AACnB;ACtFO,SAASC,EAAiBC,GAAsC;AACrE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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBA,QAAQC,GAAc;AACpB,SAAK,QAAQ,WAAW,EAAE,iBAAiBA,EAAM,CAAA,GACjD,KAAK,QAAQ,WAAW,EAAE,iBAAiBA,EAAM,CAAA,GACjD,KAAK,UAAU,WAAW,EAAE,iBAAiBA,EAAM,CAAA;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,YAAY;AACV,SAAK,QAAQ,YAAY,CAAC,EAAE,iBAAiBC,GAAG,GAAGC,EAAK,MAAMA,GAAM,KAAK,QAAQ,WAAA,CAAY,CAAC,GAC9F,KAAK,QAAQ,YAAY,CAAC,EAAE,iBAAiBD,GAAG,GAAGC,EAAK,MAAMA,GAAM,KAAK,QAAQ,WAAA,CAAY,CAAC,GAC9F,KAAK,UAAU;AAAA,OACZ,CAAC,EAAE,iBAAiBD,GAAG,GAAGC,QAAWA,GAAM,KAAK,UAAU,YAAY;AAAA,IAAA;AAAA,EAE3E;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.esm.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 const { subdomain, region } = params\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({\n url: authUrl,\n broadcastKey: `${subdomain}${region ?? 'local'}`,\n ...params\n })\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 *\n * @example\n * ```ts\n * // Create a new Nhost client from subdomain and region.\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client from individual service URLs (custom domains, self-hosting, etc).\n * const nhost = new NhostClient({\n * authUrl: \"my-auth-service-url\",\n * storageUrl: \"my-storage-service-url\",\n * graphqlUrl: \"my-graphql-service-url\",\n * functionsUrl: \"my-functions-service-url\",\n * });\n * ```\n *\n *\n * ```ts\n * // Create a new Nhost client for local development.\n * const nhost = new NhostClient({ subdomain: \"local\" });\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/nhost-js/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()\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/unset-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","autoRefreshToken","autoSignIn","devTools","start","urlParams","event","session","newValue","role","_","rest"],"mappings":";;;;;;AAGO,MAAMA,IACX;AASc,SAAAC,EACdC,GACAC,GACQ;AACF,QAAA,EAAE,WAAAC,GAAW,QAAAC,EAAW,IAAAH;AAE9B,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,4BAA4B;AAIxC,QAAAE,IAA0BF,EAAU,MAAMJ,CAAe;AAC/D,MAAIM,KAAA,QAAAA,EAAyB,QAAQ;AACnC,UAAM,EAAE,UAAAC,GAAU,MAAAC,GAAM,MAAAC,EAAA,IAASH,EAAwB,QAEnDI,IAA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A;AAAA;AAAA;AAAA,EAgBA,YAAY;AACV,SAAK,QAAQ,YAAY,CAAC,EAAE,iBAAiBC,GAAG,GAAGC,EAAK,MAAMA,GAAM,KAAK,QAAQ,WAAA,CAAY,CAAC,GAC9F,KAAK,QAAQ,YAAY,CAAC,EAAE,iBAAiBD,GAAG,GAAGC,EAAK,MAAMA,GAAM,KAAK,QAAQ,WAAA,CAAY,CAAC,GAC9F,KAAK,UAAU;AAAA,OACZ,CAAC,EAAE,iBAAiBD,GAAG,GAAGC,QAAWA,GAAM,KAAK,UAAU,YAAY;AAAA,IAAA;AAAA,EAE3E;AACF;"}
|
package/dist/utils/types.d.ts
CHANGED
|
@@ -47,7 +47,7 @@ export type ServiceUrls = {
|
|
|
47
47
|
storageUrl?: string;
|
|
48
48
|
functionsUrl?: string;
|
|
49
49
|
};
|
|
50
|
-
export interface NhostClientConstructorParams extends Partial<Subdomain>, Partial<ServiceUrls>, Omit<NhostAuthConstructorParams, 'url'> {
|
|
50
|
+
export interface NhostClientConstructorParams extends Partial<Subdomain>, Partial<ServiceUrls>, Omit<NhostAuthConstructorParams, 'url' | 'broadcastKey'> {
|
|
51
51
|
/**
|
|
52
52
|
* When set, the admin secret is sent as a header, `x-hasura-admin-secret`,
|
|
53
53
|
* for all requests to GraphQL, Storage, and Serverless Functions.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/utils/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAA;AAGlE,MAAM,WAAW,YAAY,CAAC,QAAQ,GAAG,GAAG;IAC1C,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,QAAQ,CAAA;CAClB;AAGD,MAAM,WAAW,gBAAgB;IAC/B;;;SAGK;IACL,OAAO,EAAE,OAAO,CAAA;IAChB,uCAAuC;IACvC,KAAK,EAAE,YAAY,GAAG,IAA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,MAAM,MAAM,SAAS,GAAG;IACtB;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,MAAM,WAAW,4BACf,SAAQ,OAAO,CAAC,SAAS,CAAC,EACxB,OAAO,CAAC,WAAW,CAAC,EACpB,IAAI,CAAC,0BAA0B,EAAE,KAAK,GAAG,cAAc,CAAC;IAC1D;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nhost/nhost-js",
|
|
3
|
-
"version": "3.1
|
|
3
|
+
"version": "3.2.1",
|
|
4
4
|
"description": "Nhost JavaScript SDK",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"dependencies": {
|
|
47
47
|
"isomorphic-unfetch": "^3.1.0",
|
|
48
48
|
"@nhost/graphql-js": "0.3.0",
|
|
49
|
-
"@nhost/hasura-auth-js": "2.
|
|
49
|
+
"@nhost/hasura-auth-js": "2.8.0",
|
|
50
50
|
"@nhost/hasura-storage-js": "2.5.1"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|