@nhost/nhost-js 2.2.7 → 2.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +57 -52
- package/dist/index.esm.js.map +1 -1
- package/package.json +3 -3
- package/umd/nhost-js.umd.js +7 -7
- package/umd/nhost-js.umd.js.map +1 -1
|
@@ -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,EAAE,MAAM,aAAa,CAAA;AAIzE,eAAO,MAAM,iBAAiB,WAAY,4BAA4B,gBAA4B,CAAA;AAElG,qBAAa,WAAW;IACtB,IAAI,EAAE,gBAAgB,CAAA;IACtB,OAAO,EAAE,mBAAmB,CAAA;IAC5B,SAAS,EAAE,oBAAoB,CAAA;IAC/B,OAAO,EAAE,kBAAkB,CAAA;IAC3B,OAAO,CAAC,YAAY,CAAC,CAAQ;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;IAE3B;;;;;;;;;OASG;gBACS,EACV,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,QAAQ,EACR,KAAY,EACZ,GAAG,SAAS,EACb,EAAE,4BAA4B;
|
|
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,EAAE,MAAM,aAAa,CAAA;AAIzE,eAAO,MAAM,iBAAiB,WAAY,4BAA4B,gBAA4B,CAAA;AAElG,qBAAa,WAAW;IACtB,IAAI,EAAE,gBAAgB,CAAA;IACtB,OAAO,EAAE,mBAAmB,CAAA;IAC5B,SAAS,EAAE,oBAAoB,CAAA;IAC/B,OAAO,EAAE,kBAAkB,CAAA;IAC3B,OAAO,CAAC,YAAY,CAAC,CAAQ;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;IAE3B;;;;;;;;;OASG;gBACS,EACV,mBAAmB,EACnB,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;CACF"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@nhost/hasura-auth-js"),b=require("@nhost/hasura-storage-js"),U=require("isomorphic-unfetch"),C=require("@nhost/graphql-js"),m=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{backendUrl:i,subdomain:s,region:u}=t;if(i)return`${i}/v1/${e}`;if(!s)throw new Error("Either `backendUrl` or `subdomain` must be set.");const a=s.match(m);if(a!=null&&a.groups){const{protocol:o,host:h,port:r}=a.groups,n=q(e);return n||(h==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${o||"http"}://localhost:${r||1337}/v1/${e}`):r?`${o||"https"}://local.${e}.nhost.run:${r}/v1`:`${o||"https"}://local.${e}.nhost.run/v1`)}if(!u)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${s}.${e}.${u}.nhost.run/v1`}function y(){return typeof window!="undefined"}function $(){return typeof process!="undefined"&&process.env}function q(t){return y()||!$()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function v(t,e){const s=e.startsWith("/")?e:`/${e}`;return t+s}function p(t){const e="subdomain"in t||"backendUrl"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 T(t){const e="subdomain"in t||"backendUrl"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){const{url:i,adminSecret:s}=e;this.url=i,this.accessToken=null,this.adminSecret=s}async call(e,i,s){var o,h;const u={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s==null?void 0:s.headers},a=v(this.url,e);try{const r=await U(a,{body:i?JSON.stringify(i):null,headers:u,method:"POST"});if(!r.ok){let c;return(o=r.headers.get("content-type"))!=null&&o.includes("application/json")?c=await r.json():c=await r.text(),{res:null,error:{message:c,error:r.statusText,status:r.status}}}let n;return(h=r.headers.get("content-type"))!=null&&h.includes("application/json")?n=await r.json():n=await r.text(),{res:{data:n,status:r.status,statusText:r.statusText},error:null}}catch(r){const n=r;return{res:null,error:{message:n.message,status:n.name==="AbortError"?0:500,error:n.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function k(t){const e="subdomain"in t||"backendUrl"in t?d(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new C.NhostGraphqlClient({url:e,...t})}function A(t){const e="subdomain"in t||"backendUrl"in t?d(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new b.HasuraStorageClient({url:e,...t})}const E=t=>new S(t);class S{constructor({refreshIntervalTime:e,clientStorage:i,clientStorageType:s,autoRefreshToken:u,autoSignIn:a,adminSecret:o,devTools:h,start:r=!0,...n}){this.auth=p({refreshIntervalTime:e,clientStorage:i,clientStorageType:s,autoRefreshToken:u,autoSignIn:a,start:r,...n}),this.storage=A({adminSecret:o,...n}),this.functions=T({adminSecret:o,...n}),this.graphql=k({adminSecret:o,...n}),this.auth.onAuthStateChanged((c,l)=>{if(c==="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(c=>{const l=c==null?void 0:c.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=o,this.devTools=h}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}exports.NhostClient=S;exports.NhostFunctionsClient=w;exports.createAuthClient=p;exports.createFunctionsClient=T;exports.createGraphqlClient=k;exports.createNhostClient=E;exports.createStorageClient=A;Object.keys(g).forEach(t=>{t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>g[t]})});Object.keys(b).forEach(t=>{t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>b[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 * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] 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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from '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 || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { 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 })\n\n // * Update access token for clients, including when signin in\n this.auth.onTokenChanged((session) => {\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","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,sFAUc,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,iDAAiD,EAI7D,MAAAE,EAA0BF,EAAU,MAAML,CAAe,EAC/D,GAAIO,GAAA,MAAAA,EAAyB,OAAQ,CACnC,KAAM,CAAE,SAAAC,EAAU,KAAAC,EAAM,KAAAC,CAAA,EAASH,EAAwB,OAEnDI,EAAaC,EAAgBT,CAAO,EAC1C,OAAIQ,IAIAF,IAAS,aACH,QAAA,KACN,0HAAA,EAGK,GAAGD,GAAY,sBAAsBE,GAAQ,WAAWP,KAG1DO,EACH,GAA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AAeA,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 * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] 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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from '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 || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { 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","backendOrSubdomain","service","backendUrl","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,sFAUc,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,iDAAiD,EAI7D,MAAAE,EAA0BF,EAAU,MAAML,CAAe,EAC/D,GAAIO,GAAA,MAAAA,EAAyB,OAA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AChC,KAAA,UAAU,eAAe,MAAS,EAClC,KAAA,QAAQ,eAAe,MAAS,EAErC,OAGF,MAAMjB,EAAckB,GAAA,YAAAA,EAAS,YACxB,KAAA,QAAQ,eAAelB,CAAW,EAClC,KAAA,UAAU,eAAeA,CAAW,EACpC,KAAA,QAAQ,eAAeA,CAAW,CAAA,CACxC,EAGI,KAAA,KAAK,eAAgBkB,GAAY,CACpC,MAAMlB,EAAckB,GAAA,YAAAA,EAAS,YACxB,KAAA,QAAQ,eAAelB,CAAW,EAClC,KAAA,UAAU,eAAeA,CAAW,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"}
|
package/dist/index.esm.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
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
|
-
import
|
|
6
|
-
import { NhostGraphqlClient as
|
|
7
|
-
const
|
|
5
|
+
import T from "isomorphic-unfetch";
|
|
6
|
+
import { NhostGraphqlClient as k } from "@nhost/graphql-js";
|
|
7
|
+
const w = /^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;
|
|
8
8
|
function d(e, t) {
|
|
9
|
-
const { backendUrl: i, subdomain: o, region:
|
|
9
|
+
const { backendUrl: i, subdomain: o, region: l } = e;
|
|
10
10
|
if (i)
|
|
11
11
|
return `${i}/v1/${t}`;
|
|
12
12
|
if (!o)
|
|
13
13
|
throw new Error("Either `backendUrl` or `subdomain` must be set.");
|
|
14
|
-
const
|
|
15
|
-
if (
|
|
16
|
-
const { protocol: s, host:
|
|
17
|
-
return n || (
|
|
14
|
+
const a = o.match(w);
|
|
15
|
+
if (a != null && a.groups) {
|
|
16
|
+
const { protocol: s, host: h, port: r } = a.groups, n = U(t);
|
|
17
|
+
return n || (h === "localhost" ? (console.warn(
|
|
18
18
|
'The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'
|
|
19
19
|
), `${s || "http"}://localhost:${r || 1337}/v1/${t}`) : r ? `${s || "https"}://local.${t}.nhost.run:${r}/v1` : `${s || "https"}://local.${t}.nhost.run/v1`);
|
|
20
20
|
}
|
|
21
|
-
if (!
|
|
21
|
+
if (!l)
|
|
22
22
|
throw new Error('`region` must be set when using a `subdomain` other than "local".');
|
|
23
|
-
return `https://${o}.${t}.${
|
|
23
|
+
return `https://${o}.${t}.${l}.nhost.run/v1`;
|
|
24
24
|
}
|
|
25
|
-
function
|
|
25
|
+
function b() {
|
|
26
26
|
return typeof window != "undefined";
|
|
27
27
|
}
|
|
28
28
|
function m() {
|
|
29
29
|
return typeof process != "undefined" && process.env;
|
|
30
30
|
}
|
|
31
|
-
function
|
|
32
|
-
return
|
|
31
|
+
function U(e) {
|
|
32
|
+
return b() || !m() ? null : process.env[`NHOST_${e.toUpperCase()}_URL`];
|
|
33
33
|
}
|
|
34
|
-
function
|
|
34
|
+
function A(e, t) {
|
|
35
35
|
const o = t.startsWith("/") ? t : `/${t}`;
|
|
36
36
|
return e + o;
|
|
37
37
|
}
|
|
@@ -39,15 +39,15 @@ function S(e) {
|
|
|
39
39
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "auth") : e.authUrl;
|
|
40
40
|
if (!t)
|
|
41
41
|
throw new Error("Please provide `subdomain` or `authUrl`.");
|
|
42
|
-
return new
|
|
42
|
+
return new g({ url: t, ...e });
|
|
43
43
|
}
|
|
44
|
-
function
|
|
44
|
+
function $(e) {
|
|
45
45
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "functions") : e.functionsUrl;
|
|
46
46
|
if (!t)
|
|
47
47
|
throw new Error("Please provide `subdomain` or `functionsUrl`.");
|
|
48
|
-
return new
|
|
48
|
+
return new v({ url: t, ...e });
|
|
49
49
|
}
|
|
50
|
-
class
|
|
50
|
+
class v {
|
|
51
51
|
constructor(t) {
|
|
52
52
|
const { url: i, adminSecret: o } = t;
|
|
53
53
|
this.url = i, this.accessToken = null, this.adminSecret = o;
|
|
@@ -94,31 +94,31 @@ class $ {
|
|
|
94
94
|
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call
|
|
95
95
|
*/
|
|
96
96
|
async call(t, i, o) {
|
|
97
|
-
var s,
|
|
98
|
-
const
|
|
97
|
+
var s, h;
|
|
98
|
+
const l = {
|
|
99
99
|
"Content-Type": "application/json",
|
|
100
100
|
...this.generateAccessTokenHeaders(),
|
|
101
101
|
...o == null ? void 0 : o.headers
|
|
102
|
-
},
|
|
102
|
+
}, a = A(this.url, t);
|
|
103
103
|
try {
|
|
104
|
-
const r = await
|
|
104
|
+
const r = await T(a, {
|
|
105
105
|
body: i ? JSON.stringify(i) : null,
|
|
106
|
-
headers:
|
|
106
|
+
headers: l,
|
|
107
107
|
method: "POST"
|
|
108
108
|
});
|
|
109
109
|
if (!r.ok) {
|
|
110
|
-
let
|
|
111
|
-
return (s = r.headers.get("content-type")) != null && s.includes("application/json") ?
|
|
110
|
+
let c;
|
|
111
|
+
return (s = r.headers.get("content-type")) != null && s.includes("application/json") ? c = await r.json() : c = await r.text(), {
|
|
112
112
|
res: null,
|
|
113
113
|
error: {
|
|
114
|
-
message:
|
|
114
|
+
message: c,
|
|
115
115
|
error: r.statusText,
|
|
116
116
|
status: r.status
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
119
|
}
|
|
120
120
|
let n;
|
|
121
|
-
return (
|
|
121
|
+
return (h = r.headers.get("content-type")) != null && h.includes("application/json") ? n = await r.json() : n = await r.text(), {
|
|
122
122
|
res: { data: n, status: r.status, statusText: r.statusText },
|
|
123
123
|
error: null
|
|
124
124
|
};
|
|
@@ -159,20 +159,20 @@ class $ {
|
|
|
159
159
|
} : {};
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
|
-
function
|
|
162
|
+
function C(e) {
|
|
163
163
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "graphql") : e.graphqlUrl;
|
|
164
164
|
if (!t)
|
|
165
165
|
throw new Error("Please provide `subdomain` or `graphqlUrl`.");
|
|
166
|
-
return new
|
|
166
|
+
return new k({ url: t, ...e });
|
|
167
167
|
}
|
|
168
|
-
function
|
|
168
|
+
function E(e) {
|
|
169
169
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "storage") : e.storageUrl;
|
|
170
170
|
if (!t)
|
|
171
171
|
throw new Error("Please provide `subdomain` or `storageUrl`.");
|
|
172
|
-
return new
|
|
172
|
+
return new p({ url: t, ...e });
|
|
173
173
|
}
|
|
174
|
-
const
|
|
175
|
-
class
|
|
174
|
+
const H = (e) => new _(e);
|
|
175
|
+
class _ {
|
|
176
176
|
/**
|
|
177
177
|
* Nhost Client
|
|
178
178
|
*
|
|
@@ -187,10 +187,10 @@ class E {
|
|
|
187
187
|
refreshIntervalTime: t,
|
|
188
188
|
clientStorage: i,
|
|
189
189
|
clientStorageType: o,
|
|
190
|
-
autoRefreshToken:
|
|
191
|
-
autoSignIn:
|
|
190
|
+
autoRefreshToken: l,
|
|
191
|
+
autoSignIn: a,
|
|
192
192
|
adminSecret: s,
|
|
193
|
-
devTools:
|
|
193
|
+
devTools: h,
|
|
194
194
|
start: r = !0,
|
|
195
195
|
...n
|
|
196
196
|
}) {
|
|
@@ -198,16 +198,21 @@ class E {
|
|
|
198
198
|
refreshIntervalTime: t,
|
|
199
199
|
clientStorage: i,
|
|
200
200
|
clientStorageType: o,
|
|
201
|
-
autoRefreshToken:
|
|
202
|
-
autoSignIn:
|
|
201
|
+
autoRefreshToken: l,
|
|
202
|
+
autoSignIn: a,
|
|
203
203
|
start: r,
|
|
204
204
|
...n
|
|
205
|
-
}), this.storage =
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
205
|
+
}), this.storage = E({ adminSecret: s, ...n }), this.functions = $({ adminSecret: s, ...n }), this.graphql = C({ adminSecret: s, ...n }), this.auth.onAuthStateChanged((c, u) => {
|
|
206
|
+
if (c === "SIGNED_OUT") {
|
|
207
|
+
this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const f = u == null ? void 0 : u.accessToken;
|
|
211
|
+
this.storage.setAccessToken(f), this.functions.setAccessToken(f), this.graphql.setAccessToken(f);
|
|
212
|
+
}), this.auth.onTokenChanged((c) => {
|
|
213
|
+
const u = c == null ? void 0 : c.accessToken;
|
|
214
|
+
this.storage.setAccessToken(u), this.functions.setAccessToken(u), this.graphql.setAccessToken(u);
|
|
215
|
+
}), this._adminSecret = s, this.devTools = h;
|
|
211
216
|
}
|
|
212
217
|
get adminSecret() {
|
|
213
218
|
return this._adminSecret;
|
|
@@ -217,12 +222,12 @@ class E {
|
|
|
217
222
|
}
|
|
218
223
|
}
|
|
219
224
|
export {
|
|
220
|
-
|
|
221
|
-
|
|
225
|
+
_ as NhostClient,
|
|
226
|
+
v as NhostFunctionsClient,
|
|
222
227
|
S as createAuthClient,
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
228
|
+
$ as createFunctionsClient,
|
|
229
|
+
C as createGraphqlClient,
|
|
230
|
+
H as createNhostClient,
|
|
231
|
+
E as createStorageClient
|
|
227
232
|
};
|
|
228
233
|
//# 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 * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] 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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from '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 || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { 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 })\n\n // * Update access token for clients, including when signin in\n this.auth.onTokenChanged((session) => {\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","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":";;;;;;AAGO,MAAMA,IACX;AAUc,SAAAC,EACdC,GACAC,GACQ;AACR,QAAM,EAAE,YAAAC,GAAY,WAAAC,GAAW,QAAAC,EAAA,IAAWJ;AAE1C,MAAIE;AACF,WAAO,GAAGA,QAAiBD;AAG7B,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,iDAAiD;AAI7D,QAAAE,IAA0BF,EAAU,MAAML,CAAe;AAC/D,MAAIO,KAAA,QAAAA,EAAyB,QAAQ;AACnC,UAAM,EAAE,UAAAC,GAAU,MAAAC,GAAM,MAAAC,EAAA,IAASH,EAAwB,QAEnDI,IAAaC,EAAgBT,CAAO;AAC1C,WAAIQ,MAIAF,MAAS,eACH,QAAA;AAAA,MACN;AAAA,IAAA,GAGK,GAAGD,KAAY,sBAAsBE,KAAQ,WAAWP,OAG1DO,IACH,GAAGF,KAAY,mBAAmBL,eAAqBO,SACvD,GAAGF,KAAY,mBAAmBL;AAAA;AAGxC,MAAI,CAACG;AACG,UAAA,IAAI,MAAM,mEAAmE;AAG9E,SAAA,WAAW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ACA,kBAAAC;AAAA,MACA,YAAAC;AAAA,MACA,OAAAE;AAAA,MACA,GAAGC;AAAA,IAAA,CACJ,GACD,KAAK,UAAUZ,EAAoB,EAAE,aAAAjB,GAAa,GAAG6B,GAAW,GAChE,KAAK,YAAYjC,EAAsB,EAAE,aAAAI,GAAa,GAAG6B,GAAW,GACpE,KAAK,UAAUf,EAAoB,EAAE,aAAAd,GAAa,GAAG6B,GAAW,GAEhE,KAAK,KAAK,mBAAmB,CAACC,GAAQC,MAAY;AAChD,MAAID,MAAW,iBACR,KAAA,QAAQ,eAAe,MAAS,GAChC,KAAA,UAAU,eAAe,MAAS,GAClC,KAAA,QAAQ,eAAe,MAAS;AAAA,IACvC,CACD,GAGI,KAAA,KAAK,eAAe,CAACC,MAAY;AACpC,YAAMlB,IAAckB,KAAA,gBAAAA,EAAS;AACxB,WAAA,QAAQ,eAAelB,CAAW,GAClC,KAAA,UAAU,eAAeA,CAAW,GACpC,KAAA,QAAQ,eAAeA,CAAW;AAAA,IAAA,CACxC,GAED,KAAK,eAAeb,GACpB,KAAK,WAAW2B;AAAA,EAClB;AAAA,EAEA,IAAI,cAAkC;AACpC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,YAAYK,GAA8B;AAC5C,SAAK,eAAeA,GACf,KAAA,QAAQ,eAAeA,CAAQ;AAAA,EAItC;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 * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] 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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from '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 || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\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 =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { 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","backendOrSubdomain","service","backendUrl","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":";;;;;;AAGO,MAAMA,IACX;AAUc,SAAAC,EACdC,GACAC,GACQ;AACR,QAAM,EAAE,YAAAC,GAAY,WAAAC,GAAW,QAAAC,EAAA,IAAWJ;AAE1C,MAAIE;AACF,WAAO,GAAGA,QAAiBD;AAG7B,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,iDAAiD;AAI7D,QAAAE,IAA0BF,EAAU,MAAML,CAAe;AAC/D,MAAIO,KAAA,QAAAA,EAAyB,QAAQ;AACnC,UAAM,EAAE,UAAAC,GAAU,MAAAC,GAAM,MAAAC,EAAA,IAASH,EAAwB,QAEnDI,IAAaC,EAAgBT,CAAO;AAC1C,WAAIQ,MAIAF,MAAS,eACH,QAAA;AAAA,MACN;AAAA,IAAA,GAGK,GAAGD,KAAY,sBAAsBE,KAAQ,WAAWP,OAG1DO,IACH,GAAGF,KAAY,mBAAmBL,eAAqBO,SACvD,GAAGF,KAAY,mBAAmBL;AAAA;AAGxC,MAAI,CAACG;AACG,UAAA,IAAI,MAAM,mEAAmE;AAG9E,SAAA,WAAWD,KAAaF,KAAWG;AAC5C;AAMA,SAASO,IAAqB;AAC5B,SAAO,OAAO,UAAW;AAC3B;AAMA,SAASC,IAAyB;AACzB,SAAA,OAAO,WAAY,eAAe,QAAQ;AACnD;AAQA,SAASF,EAAgBT,GAAiB;AACxC,SAAIU,EAAU,KAAK,CAACC,MACX,OAGF,QAAQ,IAAI,SA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f,EAAoB,EAAE,aAAAd,GAAa,GAAG6B,GAAW,GAEhE,KAAK,KAAK,mBAAmB,CAACC,GAAOC,MAAY;AAC/C,UAAID,MAAU,cAAc;AACrB,aAAA,QAAQ,eAAe,MAAS,GAChC,KAAA,UAAU,eAAe,MAAS,GAClC,KAAA,QAAQ,eAAe,MAAS;AAErC;AAAA;AAGF,YAAMjB,IAAckB,KAAA,gBAAAA,EAAS;AACxB,WAAA,QAAQ,eAAelB,CAAW,GAClC,KAAA,UAAU,eAAeA,CAAW,GACpC,KAAA,QAAQ,eAAeA,CAAW;AAAA,IAAA,CACxC,GAGI,KAAA,KAAK,eAAe,CAACkB,MAAY;AACpC,YAAMlB,IAAckB,KAAA,gBAAAA,EAAS;AACxB,WAAA,QAAQ,eAAelB,CAAW,GAClC,KAAA,UAAU,eAAeA,CAAW,GACpC,KAAA,QAAQ,eAAeA,CAAW;AAAA,IAAA,CACxC,GAED,KAAK,eAAeb,GACpB,KAAK,WAAW2B;AAAA,EAClB;AAAA,EAEA,IAAI,cAAkC;AACpC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,YAAYK,GAA8B;AAC5C,SAAK,eAAeA,GACf,KAAA,QAAQ,eAAeA,CAAQ;AAAA,EAItC;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nhost/nhost-js",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.9",
|
|
4
4
|
"description": "Nhost JavaScript SDK",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"dependencies": {
|
|
47
47
|
"isomorphic-unfetch": "^3.1.0",
|
|
48
48
|
"@nhost/graphql-js": "0.1.3",
|
|
49
|
-
"@nhost/hasura-auth-js": "2.1.
|
|
50
|
-
"@nhost/hasura-storage-js": "2.1.
|
|
49
|
+
"@nhost/hasura-auth-js": "2.1.7",
|
|
50
|
+
"@nhost/hasura-storage-js": "2.1.6"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"graphql": "16.6.0",
|