@nhost/nhost-js 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +9 -10
  2. package/dist/middlewareWithAdminSession-BtFo6WUj.js +2 -0
  3. package/dist/middlewareWithAdminSession-BtFo6WUj.js.map +1 -0
  4. package/dist/middlewareWithAdminSession-w7fkl0J9.mjs +106 -0
  5. package/dist/middlewareWithAdminSession-w7fkl0J9.mjs.map +1 -0
  6. package/dist/nhost-js/auth.cjs.js +1 -1
  7. package/dist/nhost-js/auth.cjs.js.map +1 -1
  8. package/dist/nhost-js/auth.es.js +48 -0
  9. package/dist/nhost-js/auth.es.js.map +1 -1
  10. package/dist/nhost-js/fetch.cjs.js +1 -1
  11. package/dist/nhost-js/fetch.cjs.js.map +1 -1
  12. package/dist/nhost-js/fetch.es.js +19 -79
  13. package/dist/nhost-js/fetch.es.js.map +1 -1
  14. package/dist/nhost-js/functions.cjs.js +1 -1
  15. package/dist/nhost-js/functions.cjs.js.map +1 -1
  16. package/dist/nhost-js/functions.es.js +7 -2
  17. package/dist/nhost-js/functions.es.js.map +1 -1
  18. package/dist/nhost-js/graphql.cjs.js +1 -1
  19. package/dist/nhost-js/graphql.cjs.js.map +1 -1
  20. package/dist/nhost-js/graphql.es.js +7 -2
  21. package/dist/nhost-js/graphql.es.js.map +1 -1
  22. package/dist/nhost-js/session.es.js +1 -1
  23. package/dist/nhost-js/storage.cjs.js.map +1 -1
  24. package/dist/nhost-js/storage.es.js.map +1 -1
  25. package/dist/nhost-js.cjs.js +1 -1
  26. package/dist/nhost-js.cjs.js.map +1 -1
  27. package/dist/nhost-js.es.js +78 -65
  28. package/dist/nhost-js.es.js.map +1 -1
  29. package/dist/nhost-js.umd.js +1 -1
  30. package/dist/nhost-js.umd.js.map +1 -1
  31. package/dist/refreshSession-Bw715ZmX.js.map +1 -1
  32. package/dist/{refreshSession-WwGlzgtM.mjs → refreshSession-CG8GIEun.mjs} +5 -2
  33. package/dist/refreshSession-CG8GIEun.mjs.map +1 -0
  34. package/dist/src/auth/client.d.ts +72 -1
  35. package/dist/src/auth/client.d.ts.map +1 -1
  36. package/dist/src/auth/client.js +56 -0
  37. package/dist/src/auth/client.js.map +1 -1
  38. package/dist/src/fetch/index.d.ts +15 -0
  39. package/dist/src/fetch/index.d.ts.map +1 -1
  40. package/dist/src/fetch/index.js +15 -0
  41. package/dist/src/fetch/index.js.map +1 -1
  42. package/dist/src/fetch/middlewareUpdateSessionFromResponse.js +1 -1
  43. package/dist/src/fetch/middlewareUpdateSessionFromResponse.js.map +1 -1
  44. package/dist/src/fetch/middlewareWithAdminSession.d.ts +87 -0
  45. package/dist/src/fetch/middlewareWithAdminSession.d.ts.map +1 -0
  46. package/dist/src/fetch/middlewareWithAdminSession.js +79 -0
  47. package/dist/src/fetch/middlewareWithAdminSession.js.map +1 -0
  48. package/dist/src/fetch/middlewareWithHeaders.d.ts +23 -0
  49. package/dist/src/fetch/middlewareWithHeaders.d.ts.map +1 -0
  50. package/dist/src/fetch/middlewareWithHeaders.js +31 -0
  51. package/dist/src/fetch/middlewareWithHeaders.js.map +1 -0
  52. package/dist/src/fetch/middlewareWithRole.d.ts +44 -0
  53. package/dist/src/fetch/middlewareWithRole.d.ts.map +1 -0
  54. package/dist/src/fetch/middlewareWithRole.js +50 -0
  55. package/dist/src/fetch/middlewareWithRole.js.map +1 -0
  56. package/dist/src/functions/client.d.ts +6 -1
  57. package/dist/src/functions/client.d.ts.map +1 -1
  58. package/dist/src/functions/client.js +6 -1
  59. package/dist/src/functions/client.js.map +1 -1
  60. package/dist/src/graphql/client.d.ts +4 -0
  61. package/dist/src/graphql/client.d.ts.map +1 -1
  62. package/dist/src/graphql/client.js +6 -1
  63. package/dist/src/graphql/client.js.map +1 -1
  64. package/dist/src/index.d.ts +12 -2
  65. package/dist/src/index.d.ts.map +1 -1
  66. package/dist/src/index.js +12 -2
  67. package/dist/src/index.js.map +1 -1
  68. package/dist/src/nhost.d.ts +109 -0
  69. package/dist/src/nhost.d.ts.map +1 -1
  70. package/dist/src/nhost.js +167 -49
  71. package/dist/src/nhost.js.map +1 -1
  72. package/dist/src/session/refreshSession.d.ts.map +1 -1
  73. package/dist/src/session/refreshSession.js +3 -1
  74. package/dist/src/session/refreshSession.js.map +1 -1
  75. package/dist/src/storage/client.d.ts +3 -0
  76. package/dist/src/storage/client.d.ts.map +1 -1
  77. package/dist/src/storage/client.js.map +1 -1
  78. package/dist/tsconfig.tsbuildinfo +1 -1
  79. package/package.json +2 -2
  80. package/dist/refreshSession-WwGlzgtM.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../fetch-DWXwEnoe.js"),n=require("../refreshSession-Bw715ZmX.js");function s(e,n){return n.accessToken&&e.set("Authorization",`Bearer ${n.accessToken}`),e}exports.FetchError=e.FetchError,exports.createEnhancedFetch=e.createEnhancedFetch,exports.attachAccessTokenMiddleware=e=>n=>async(r,t={})=>{const o=new Headers(t.headers||{});if(o.has("Authorization"))return n(r,t);const i=e.get();if(i?.accessToken){const e={...t,headers:s(o,i)};return n(r,e)}return n(r,t)},exports.sessionRefreshMiddleware=(e,s,r)=>{const{marginSeconds:t=60}=r||{};return r=>async(o,i={})=>{if(function(e,n){const s=new Headers(n.headers||{});if(s.has("Authorization"))return!0;if(e.endsWith("/v1/token"))return!0;return!1}(o,i))return r(o,i);try{await n.refreshSession(e,s,t)}catch{}return r(o,i)}},exports.updateSessionFromResponseMiddleware=e=>n=>async(s,r)=>{const t=await n(s,r);try{if(s.endsWith("/signout"))return e.remove(),t;if(s.endsWith("/token")||s.includes("/signin/")||s.includes("/signup/")){const n=t.clone(),s=await n.json().catch((()=>null));if(s){const n=(e=>"string"==typeof e?null:"session"in e?e.session||null:"accessToken"in e&&"refreshToken"in e?e:null)(s);n?.accessToken&&n.refreshToken&&e.set(n)}}}catch(o){console.warn("Error in session response middleware:",o)}return t};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../fetch-DWXwEnoe.js"),s=require("../middlewareWithAdminSession-BtFo6WUj.js");exports.FetchError=e.FetchError,exports.createEnhancedFetch=e.createEnhancedFetch,exports.attachAccessTokenMiddleware=s.attachAccessTokenMiddleware,exports.sessionRefreshMiddleware=s.sessionRefreshMiddleware,exports.updateSessionFromResponseMiddleware=s.updateSessionFromResponseMiddleware,exports.withAdminSessionMiddleware=s.withAdminSessionMiddleware,exports.withHeadersMiddleware=e=>s=>async(r,a={})=>{const t=new Headers(a.headers||{});return new Headers(e).forEach(((e,s)=>{t.has(s)||t.set(s,e)})),s(r,{...a,headers:t})},exports.withRoleMiddleware=e=>s=>async(r,a={})=>{const t=new Headers(a.headers||{});return t.has("x-hasura-role")||t.set("x-hasura-role",e),s(r,{...a,headers:t})};
2
2
  //# sourceMappingURL=fetch.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.cjs.js","sources":["../../src/fetch/middlewareAttachAccessToken.ts","../../src/fetch/middlewareSessionRefresh.ts","../../src/fetch/middlewareUpdateSessionFromResponse.ts"],"sourcesContent":["/**\n * Authorization token attachment middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * authorization tokens to outgoing API requests, ensuring the client\n * is properly authenticated.\n */\n\nimport type { Session } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that adds the Authorization header with the current access token.\n *\n * This middleware:\n * 1. Gets the current session from storage\n * 2. Adds the authorization header with the access token to outgoing requests\n *\n * This middleware should be used after the refresh middleware in the chain to\n * ensure the most recent token is used.\n *\n * @param storage - Storage implementation for retrieving session data\n * @returns A middleware function that adds Authorization headers\n */\nexport const attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n\n // Skip if Authorization header is already set\n if (headers.has(\"Authorization\")) {\n return next(url, options);\n }\n\n // Get current session from storage\n const session = storage.get();\n\n if (session?.accessToken) {\n // Add authorization header\n const newOptions = {\n ...options,\n headers: addAuthorizationHeader(headers, session),\n };\n\n // Continue with the fetch chain\n return next(url, newOptions);\n }\n\n // No session or no access token, continue without authorization\n return next(url, options);\n };\n\n/**\n * Adds the Authorization header with the access token to the request headers\n *\n * @param headers - Original request headers\n * @param session - Current session containing the access token\n * @returns Modified headers with Authorization header\n */\nfunction addAuthorizationHeader(headers: Headers, session: Session): Headers {\n if (session.accessToken) {\n headers.set(\"Authorization\", `Bearer ${session.accessToken}`);\n }\n return headers;\n}\n","/**\n * Auth token refresh middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically refresh\n * authentication tokens before they expire, ensuring seamless API access\n * without requiring manual token refresh by the application.\n */\n\nimport type { Client } from \"../auth\";\nimport { refreshSession } from \"../session/refreshSession\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that automatically refreshes authentication tokens.\n *\n * This middleware:\n * 1. Checks if the current token is about to expire\n * 2. If so, uses the refresh token to obtain a new access token\n *\n * The middleware handles token refresh transparently, so the application\n * doesn't need to manually refresh tokens.\n *\n * @param auth - Auth API client for token refresh operations\n * @param storage - Storage implementation for persisting session data\n * @param options - Configuration options for token refresh behavior\n * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\n };\n};\n\n/**\n * Determines if token handling should be skipped for this request\n *\n * @param url - Request URL\n * @param options - Request options\n * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): boolean {\n const headers = new Headers(options.headers || {});\n\n // If Authorization header is explicitly set, skip token handling\n if (headers.has(\"Authorization\")) {\n return true;\n }\n\n // If calling the token endpoint, skip to avoid infinite loops\n if (url.endsWith(\"/v1/token\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * Session response middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically extract\n * and persist session information from authentication responses, ensuring\n * that new sessions are properly stored after sign-in operations.\n */\n\nimport type { Session, SessionPayload } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that automatically extracts and stores session data from API responses.\n *\n * This middleware:\n * 1. Monitors responses from authentication-related endpoints\n * 2. Extracts session information when present\n * 3. Stores the session in the provided storage implementation\n * 4. Handles session removal on sign-out\n *\n * This ensures that session data is always up-to-date in storage after operations\n * that create or invalidate sessions.\n *\n * @param storage - Storage implementation for persisting session data\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === \"string\") {\n return null;\n }\n\n if (\"session\" in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if (\"accessToken\" in body && \"refreshToken\" in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n async (url: string, options?: RequestInit) => {\n // Call the next middleware in the chain\n const response = await next(url, options);\n\n try {\n // Check if this is a logout request\n if (url.endsWith(\"/signout\")) {\n // Remove session on sign-out\n storage.remove();\n return response;\n }\n\n // Check if this is an auth-related endpoint that might return session data\n if (\n url.endsWith(\"/token\") ||\n url.includes(\"/signin/\") ||\n url.includes(\"/signup/\")\n ) {\n // Clone the response to avoid consuming it\n const clonedResponse = response.clone();\n\n // Parse the JSON data\n const body = (await clonedResponse.json().catch(() => null)) as\n | Session\n | SessionPayload;\n\n if (body) {\n // Extract session data from response using provided extractor\n const session = sessionExtractor(body);\n\n // If session data is found, store it\n if (session?.accessToken && session.refreshToken) {\n storage.set(session);\n }\n }\n }\n } catch (error) {\n console.warn(\"Error in session response middleware:\", error);\n }\n\n // Return the original response\n return response;\n };\n};\n"],"names":["addAuthorizationHeader","headers","session","accessToken","set","storage","next","async","url","options","Headers","has","get","newOptions","auth","marginSeconds","endsWith","shouldSkipTokenHandling","refreshSession","response","remove","includes","clonedResponse","clone","body","json","catch","sessionExtractor","refreshToken","error","console","warn"],"mappings":"mKA6DA,SAASA,EAAuBC,EAAkBC,GAIhD,OAHIA,EAAQC,aACVF,EAAQG,IAAI,gBAAiB,UAAUF,EAAQC,eAE1CF,CACT,uHAxCGI,GACAC,GACDC,MAAOC,EAAaC,EAAuB,MACzC,MAAMR,EAAU,IAAIS,QAAQD,EAAQR,SAAW,CAAA,GAG/C,GAAIA,EAAQU,IAAI,iBACd,OAAOL,EAAKE,EAAKC,GAInB,MAAMP,EAAUG,EAAQO,MAExB,GAAIV,GAASC,YAAa,CAExB,MAAMU,EAAa,IACdJ,EACHR,QAASD,EAAuBC,EAASC,IAI3C,OAAOI,EAAKE,EAAKK,EACnB,CAGA,OAAOP,EAAKE,EAAKC,EAAO,mCCtBY,CACtCK,EACAT,EACAI,KAIA,MAAMM,cAAEA,EAAgB,IAAON,GAAW,CAAA,EAG1C,OAAQH,GACNC,MAAOC,EAAaC,EAAuB,CAAA,KAEzC,GAoBN,SAAiCD,EAAaC,GAC5C,MAAMR,EAAU,IAAIS,QAAQD,EAAQR,SAAW,CAAA,GAG/C,GAAIA,EAAQU,IAAI,iBACd,OAAO,EAIT,GAAIH,EAAIQ,SAAS,aACf,OAAO,EAGT,OAAO,CACT,CAlCUC,CAAwBT,EAAKC,GAC/B,OAAOH,EAAKE,EAAKC,GAGnB,UACQS,iBAAeJ,EAAMT,EAASU,EACtC,CAAA,MAEA,CACA,OAAOT,EAAKE,EAAKC,EAAO,CAC1B,8CCxBFJ,GA4BQC,GACNC,MAAOC,EAAaC,KAElB,MAAMU,QAAiBb,EAAKE,EAAKC,GAEjC,IAEE,GAAID,EAAIQ,SAAS,YAGf,OADAX,EAAQe,SACDD,EAIT,GACEX,EAAIQ,SAAS,WACbR,EAAIa,SAAS,aACbb,EAAIa,SAAS,YACb,CAEA,MAAMC,EAAiBH,EAASI,QAG1BC,QAAcF,EAAeG,OAAOC,OAAM,IAAM,OAItD,GAAIF,EAAM,CAER,MAAMtB,EAjDS,CACvBsB,GAEoB,iBAATA,EACF,KAGL,YAAaA,EAERA,EAAKtB,SAAW,KAGrB,gBAAiBsB,GAAQ,iBAAkBA,EAEtCA,EAGF,KAgCiBG,CAAiBH,GAG7BtB,GAASC,aAAeD,EAAQ0B,cAClCvB,EAAQD,IAAIF,EAEhB,CACF,CACF,OAAS2B,GACPC,QAAQC,KAAK,wCAAyCF,EACxD,CAGA,OAAOV,CAAA"}
1
+ {"version":3,"file":"fetch.cjs.js","sources":["../../src/fetch/middlewareWithHeaders.ts","../../src/fetch/middlewareWithRole.ts"],"sourcesContent":["/**\n * Headers middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * default headers to all outgoing requests, while allowing request-specific\n * headers to take precedence.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that attaches default headers to requests.\n *\n * This middleware:\n * 1. Merges default headers with request-specific headers\n * 2. Preserves request-specific headers when they conflict with defaults\n *\n * The middleware ensures consistent headers across requests while allowing\n * individual requests to override defaults as needed.\n *\n * @param defaultHeaders - Default headers to attach to all requests\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const withHeadersMiddleware =\n (defaultHeaders: HeadersInit): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n const defaults = new Headers(defaultHeaders);\n\n defaults.forEach((value, key) => {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n });\n\n return next(url, { ...options, headers });\n };\n","/**\n * Role middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically set\n * the Hasura role for all requests. This is useful when you want to\n * make requests as a specific role without using the admin secret.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that sets the Hasura role header.\n *\n * This middleware sets the x-hasura-role header for all requests, allowing\n * you to specify which role's permissions should be used. This works with\n * authenticated sessions where the user has access to the specified role.\n *\n * Unlike `withAdminSessionMiddleware`, this does not bypass permission rules\n * but instead uses the permission rules defined for the specified role.\n *\n * The middleware preserves request-specific headers when they conflict with\n * the role configuration.\n *\n * @param role - The Hasura role to use for requests\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Use with createClient to default all requests to a specific role\n * const nhost = createClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n *\n * // Use with createServerClient for server-side requests\n * const serverNhost = createServerClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * storage: myServerStorage,\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n * ```\n */\nexport const withRoleMiddleware =\n (role: string): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-role if not already present\n if (!headers.has(\"x-hasura-role\")) {\n headers.set(\"x-hasura-role\", role);\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["defaultHeaders","next","async","url","options","headers","Headers","forEach","value","key","has","set","role","requestOptions"],"mappings":"+iBAwBGA,GACAC,GACDC,MAAOC,EAAaC,EAAuB,MACzC,MAAMC,EAAU,IAAIC,QAAQF,EAAQC,SAAW,CAAA,GAS/C,OARiB,IAAIC,QAAQN,GAEpBO,SAAQ,CAACC,EAAOC,KAClBJ,EAAQK,IAAID,IACfJ,EAAQM,IAAIF,EAAKD,EACnB,IAGKP,EAAKE,EAAK,IAAKC,EAASC,WAAS,6BCSzCO,GACAX,GACDC,MAAOC,EAAaU,EAA8B,MAChD,MAAMR,EAAU,IAAIC,QAAQO,EAAeR,SAAW,CAAA,GAOtD,OAJKA,EAAQK,IAAI,kBACfL,EAAQM,IAAI,gBAAiBC,GAGxBX,EAAKE,EAAK,IAAKU,EAAgBR,WAAS"}
@@ -1,90 +1,30 @@
1
1
  import { F, c } from "../fetch-2PHmQBIJ.mjs";
2
- import { r as refreshSession } from "../refreshSession-WwGlzgtM.mjs";
3
- const attachAccessTokenMiddleware = (storage) => (next) => async (url, options = {}) => {
2
+ import { a, s, u, w } from "../middlewareWithAdminSession-w7fkl0J9.mjs";
3
+ const withHeadersMiddleware = (defaultHeaders) => (next) => async (url, options = {}) => {
4
4
  const headers = new Headers(options.headers || {});
5
- if (headers.has("Authorization")) {
6
- return next(url, options);
7
- }
8
- const session = storage.get();
9
- if (session?.accessToken) {
10
- const newOptions = {
11
- ...options,
12
- headers: addAuthorizationHeader(headers, session)
13
- };
14
- return next(url, newOptions);
15
- }
16
- return next(url, options);
17
- };
18
- function addAuthorizationHeader(headers, session) {
19
- if (session.accessToken) {
20
- headers.set("Authorization", `Bearer ${session.accessToken}`);
21
- }
22
- return headers;
23
- }
24
- const sessionRefreshMiddleware = (auth, storage, options) => {
25
- const { marginSeconds = 60 } = options || {};
26
- return (next) => async (url, options2 = {}) => {
27
- if (shouldSkipTokenHandling(url, options2)) {
28
- return next(url, options2);
29
- }
30
- try {
31
- await refreshSession(auth, storage, marginSeconds);
32
- } catch {
5
+ const defaults = new Headers(defaultHeaders);
6
+ defaults.forEach((value, key) => {
7
+ if (!headers.has(key)) {
8
+ headers.set(key, value);
33
9
  }
34
- return next(url, options2);
35
- };
10
+ });
11
+ return next(url, { ...options, headers });
36
12
  };
37
- function shouldSkipTokenHandling(url, options) {
38
- const headers = new Headers(options.headers || {});
39
- if (headers.has("Authorization")) {
40
- return true;
13
+ const withRoleMiddleware = (role) => (next) => async (url, requestOptions = {}) => {
14
+ const headers = new Headers(requestOptions.headers || {});
15
+ if (!headers.has("x-hasura-role")) {
16
+ headers.set("x-hasura-role", role);
41
17
  }
42
- if (url.endsWith("/v1/token")) {
43
- return true;
44
- }
45
- return false;
46
- }
47
- const updateSessionFromResponseMiddleware = (storage) => {
48
- const sessionExtractor = (body) => {
49
- if (typeof body === "string") {
50
- return null;
51
- }
52
- if ("session" in body) {
53
- return body.session || null;
54
- }
55
- if ("accessToken" in body && "refreshToken" in body) {
56
- return body;
57
- }
58
- return null;
59
- };
60
- return (next) => async (url, options) => {
61
- const response = await next(url, options);
62
- try {
63
- if (url.endsWith("/signout")) {
64
- storage.remove();
65
- return response;
66
- }
67
- if (url.endsWith("/token") || url.includes("/signin/") || url.includes("/signup/")) {
68
- const clonedResponse = response.clone();
69
- const body = await clonedResponse.json().catch(() => null);
70
- if (body) {
71
- const session = sessionExtractor(body);
72
- if (session?.accessToken && session.refreshToken) {
73
- storage.set(session);
74
- }
75
- }
76
- }
77
- } catch (error) {
78
- console.warn("Error in session response middleware:", error);
79
- }
80
- return response;
81
- };
18
+ return next(url, { ...requestOptions, headers });
82
19
  };
83
20
  export {
84
21
  F as FetchError,
85
- attachAccessTokenMiddleware,
22
+ a as attachAccessTokenMiddleware,
86
23
  c as createEnhancedFetch,
87
- sessionRefreshMiddleware,
88
- updateSessionFromResponseMiddleware
24
+ s as sessionRefreshMiddleware,
25
+ u as updateSessionFromResponseMiddleware,
26
+ w as withAdminSessionMiddleware,
27
+ withHeadersMiddleware,
28
+ withRoleMiddleware
89
29
  };
90
30
  //# sourceMappingURL=fetch.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.es.js","sources":["../../src/fetch/middlewareAttachAccessToken.ts","../../src/fetch/middlewareSessionRefresh.ts","../../src/fetch/middlewareUpdateSessionFromResponse.ts"],"sourcesContent":["/**\n * Authorization token attachment middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * authorization tokens to outgoing API requests, ensuring the client\n * is properly authenticated.\n */\n\nimport type { Session } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that adds the Authorization header with the current access token.\n *\n * This middleware:\n * 1. Gets the current session from storage\n * 2. Adds the authorization header with the access token to outgoing requests\n *\n * This middleware should be used after the refresh middleware in the chain to\n * ensure the most recent token is used.\n *\n * @param storage - Storage implementation for retrieving session data\n * @returns A middleware function that adds Authorization headers\n */\nexport const attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n\n // Skip if Authorization header is already set\n if (headers.has(\"Authorization\")) {\n return next(url, options);\n }\n\n // Get current session from storage\n const session = storage.get();\n\n if (session?.accessToken) {\n // Add authorization header\n const newOptions = {\n ...options,\n headers: addAuthorizationHeader(headers, session),\n };\n\n // Continue with the fetch chain\n return next(url, newOptions);\n }\n\n // No session or no access token, continue without authorization\n return next(url, options);\n };\n\n/**\n * Adds the Authorization header with the access token to the request headers\n *\n * @param headers - Original request headers\n * @param session - Current session containing the access token\n * @returns Modified headers with Authorization header\n */\nfunction addAuthorizationHeader(headers: Headers, session: Session): Headers {\n if (session.accessToken) {\n headers.set(\"Authorization\", `Bearer ${session.accessToken}`);\n }\n return headers;\n}\n","/**\n * Auth token refresh middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically refresh\n * authentication tokens before they expire, ensuring seamless API access\n * without requiring manual token refresh by the application.\n */\n\nimport type { Client } from \"../auth\";\nimport { refreshSession } from \"../session/refreshSession\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that automatically refreshes authentication tokens.\n *\n * This middleware:\n * 1. Checks if the current token is about to expire\n * 2. If so, uses the refresh token to obtain a new access token\n *\n * The middleware handles token refresh transparently, so the application\n * doesn't need to manually refresh tokens.\n *\n * @param auth - Auth API client for token refresh operations\n * @param storage - Storage implementation for persisting session data\n * @param options - Configuration options for token refresh behavior\n * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\n };\n};\n\n/**\n * Determines if token handling should be skipped for this request\n *\n * @param url - Request URL\n * @param options - Request options\n * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): boolean {\n const headers = new Headers(options.headers || {});\n\n // If Authorization header is explicitly set, skip token handling\n if (headers.has(\"Authorization\")) {\n return true;\n }\n\n // If calling the token endpoint, skip to avoid infinite loops\n if (url.endsWith(\"/v1/token\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * Session response middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically extract\n * and persist session information from authentication responses, ensuring\n * that new sessions are properly stored after sign-in operations.\n */\n\nimport type { Session, SessionPayload } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that automatically extracts and stores session data from API responses.\n *\n * This middleware:\n * 1. Monitors responses from authentication-related endpoints\n * 2. Extracts session information when present\n * 3. Stores the session in the provided storage implementation\n * 4. Handles session removal on sign-out\n *\n * This ensures that session data is always up-to-date in storage after operations\n * that create or invalidate sessions.\n *\n * @param storage - Storage implementation for persisting session data\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === \"string\") {\n return null;\n }\n\n if (\"session\" in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if (\"accessToken\" in body && \"refreshToken\" in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n async (url: string, options?: RequestInit) => {\n // Call the next middleware in the chain\n const response = await next(url, options);\n\n try {\n // Check if this is a logout request\n if (url.endsWith(\"/signout\")) {\n // Remove session on sign-out\n storage.remove();\n return response;\n }\n\n // Check if this is an auth-related endpoint that might return session data\n if (\n url.endsWith(\"/token\") ||\n url.includes(\"/signin/\") ||\n url.includes(\"/signup/\")\n ) {\n // Clone the response to avoid consuming it\n const clonedResponse = response.clone();\n\n // Parse the JSON data\n const body = (await clonedResponse.json().catch(() => null)) as\n | Session\n | SessionPayload;\n\n if (body) {\n // Extract session data from response using provided extractor\n const session = sessionExtractor(body);\n\n // If session data is found, store it\n if (session?.accessToken && session.refreshToken) {\n storage.set(session);\n }\n }\n }\n } catch (error) {\n console.warn(\"Error in session response middleware:\", error);\n }\n\n // Return the original response\n return response;\n };\n};\n"],"names":["options"],"mappings":";;AAyBO,MAAM,8BACX,CAAC,YACD,CAAC,SACD,OAAO,KAAa,UAAuB,OAA0B;AACnE,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AAGjD,MAAI,QAAQ,IAAI,eAAe,GAAG;AAChC,WAAO,KAAK,KAAK,OAAO;AAAA,EAC1B;AAGA,QAAM,UAAU,QAAQ,IAAA;AAExB,MAAI,SAAS,aAAa;AAExB,UAAM,aAAa;AAAA,MACjB,GAAG;AAAA,MACH,SAAS,uBAAuB,SAAS,OAAO;AAAA,IAAA;AAIlD,WAAO,KAAK,KAAK,UAAU;AAAA,EAC7B;AAGA,SAAO,KAAK,KAAK,OAAO;AAC1B;AASF,SAAS,uBAAuB,SAAkB,SAA2B;AAC3E,MAAI,QAAQ,aAAa;AACvB,YAAQ,IAAI,iBAAiB,UAAU,QAAQ,WAAW,EAAE;AAAA,EAC9D;AACA,SAAO;AACT;ACrCO,MAAM,2BAA2B,CACtC,MACA,SACA,YAGkB;AAClB,QAAM,EAAE,gBAAgB,GAAA,IAAO,WAAW,CAAA;AAG1C,SAAO,CAAC,SACN,OAAO,KAAaA,WAAuB,CAAA,MAA0B;AAEnE,QAAI,wBAAwB,KAAKA,QAAO,GAAG;AACzC,aAAO,KAAK,KAAKA,QAAO;AAAA,IAC1B;AAEA,QAAI;AACF,YAAM,eAAe,MAAM,SAAS,aAAa;AAAA,IACnD,QAAQ;AAAA,IAER;AACA,WAAO,KAAK,KAAKA,QAAO;AAAA,EAC1B;AACJ;AASA,SAAS,wBAAwB,KAAa,SAA+B;AAC3E,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AAGjD,MAAI,QAAQ,IAAI,eAAe,GAAG;AAChC,WAAO;AAAA,EACT;AAGA,MAAI,IAAI,SAAS,WAAW,GAAG;AAC7B,WAAO;AAAA,EACT;AAEA,SAAO;AACT;ACjDO,MAAM,sCAAsC,CACjD,YACkB;AAOlB,QAAM,mBAAmB,CACvB,SACmB;AACnB,QAAI,OAAO,SAAS,UAAU;AAC5B,aAAO;AAAA,IACT;AAEA,QAAI,aAAa,MAAM;AAErB,aAAO,KAAK,WAAW;AAAA,IACzB;AAEA,QAAI,iBAAiB,QAAQ,kBAAkB,MAAM;AAEnD,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,CAAC,SACN,OAAO,KAAa,YAA0B;AAE5C,UAAM,WAAW,MAAM,KAAK,KAAK,OAAO;AAExC,QAAI;AAEF,UAAI,IAAI,SAAS,UAAU,GAAG;AAE5B,gBAAQ,OAAA;AACR,eAAO;AAAA,MACT;AAGA,UACE,IAAI,SAAS,QAAQ,KACrB,IAAI,SAAS,UAAU,KACvB,IAAI,SAAS,UAAU,GACvB;AAEA,cAAM,iBAAiB,SAAS,MAAA;AAGhC,cAAM,OAAQ,MAAM,eAAe,OAAO,MAAM,MAAM,IAAI;AAI1D,YAAI,MAAM;AAER,gBAAM,UAAU,iBAAiB,IAAI;AAGrC,cAAI,SAAS,eAAe,QAAQ,cAAc;AAChD,oBAAQ,IAAI,OAAO;AAAA,UACrB;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,KAAK,yCAAyC,KAAK;AAAA,IAC7D;AAGA,WAAO;AAAA,EACT;AACJ;"}
1
+ {"version":3,"file":"fetch.es.js","sources":["../../src/fetch/middlewareWithHeaders.ts","../../src/fetch/middlewareWithRole.ts"],"sourcesContent":["/**\n * Headers middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * default headers to all outgoing requests, while allowing request-specific\n * headers to take precedence.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that attaches default headers to requests.\n *\n * This middleware:\n * 1. Merges default headers with request-specific headers\n * 2. Preserves request-specific headers when they conflict with defaults\n *\n * The middleware ensures consistent headers across requests while allowing\n * individual requests to override defaults as needed.\n *\n * @param defaultHeaders - Default headers to attach to all requests\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const withHeadersMiddleware =\n (defaultHeaders: HeadersInit): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n const defaults = new Headers(defaultHeaders);\n\n defaults.forEach((value, key) => {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n });\n\n return next(url, { ...options, headers });\n };\n","/**\n * Role middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically set\n * the Hasura role for all requests. This is useful when you want to\n * make requests as a specific role without using the admin secret.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that sets the Hasura role header.\n *\n * This middleware sets the x-hasura-role header for all requests, allowing\n * you to specify which role's permissions should be used. This works with\n * authenticated sessions where the user has access to the specified role.\n *\n * Unlike `withAdminSessionMiddleware`, this does not bypass permission rules\n * but instead uses the permission rules defined for the specified role.\n *\n * The middleware preserves request-specific headers when they conflict with\n * the role configuration.\n *\n * @param role - The Hasura role to use for requests\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Use with createClient to default all requests to a specific role\n * const nhost = createClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n *\n * // Use with createServerClient for server-side requests\n * const serverNhost = createServerClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * storage: myServerStorage,\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n * ```\n */\nexport const withRoleMiddleware =\n (role: string): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-role if not already present\n if (!headers.has(\"x-hasura-role\")) {\n headers.set(\"x-hasura-role\", role);\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":[],"mappings":";;AAuBO,MAAM,wBACX,CAAC,mBACD,CAAC,SACD,OAAO,KAAa,UAAuB,OAA0B;AACnE,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AACjD,QAAM,WAAW,IAAI,QAAQ,cAAc;AAE3C,WAAS,QAAQ,CAAC,OAAO,QAAQ;AAC/B,QAAI,CAAC,QAAQ,IAAI,GAAG,GAAG;AACrB,cAAQ,IAAI,KAAK,KAAK;AAAA,IACxB;AAAA,EACF,CAAC;AAED,SAAO,KAAK,KAAK,EAAE,GAAG,SAAS,SAAS;AAC1C;ACOK,MAAM,qBACX,CAAC,SACD,CAAC,SACD,OAAO,KAAa,iBAA8B,OAA0B;AAC1E,QAAM,UAAU,IAAI,QAAQ,eAAe,WAAW,CAAA,CAAE;AAGxD,MAAI,CAAC,QAAQ,IAAI,eAAe,GAAG;AACjC,YAAQ,IAAI,iBAAiB,IAAI;AAAA,EACnC;AAEA,SAAO,KAAK,KAAK,EAAE,GAAG,gBAAgB,SAAS;AACjD;"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../fetch-DWXwEnoe.js");exports.createAPIClient=(e,s=[])=>{const a=t.createEnhancedFetch(s),n=async(s,n)=>{const o=await a(`${e}${s}`,n);let r;if(r=o.headers.get("content-type")?.includes("application/json")?await o.json():o.headers.get("content-type")?.startsWith("text/")?await o.text():await o.blob(),!o.ok)throw new t.FetchError(r,o.status,o.headers);return{status:o.status,body:r,headers:o.headers}};return{baseURL:e,fetch:n,post:async(t,e,s={})=>{const a={...s,method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...s.headers},body:e?JSON.stringify(e):void 0};return n(t,a)}}};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../fetch-DWXwEnoe.js");exports.createAPIClient=(e,a=[])=>{let s=t.createEnhancedFetch(a);const n=async(a,n)=>{const o=await s(`${e}${a}`,n);let r;if(r=o.headers.get("content-type")?.includes("application/json")?await o.json():o.headers.get("content-type")?.startsWith("text/")?await o.text():await o.blob(),!o.ok)throw new t.FetchError(r,o.status,o.headers);return{status:o.status,body:r,headers:o.headers}};return{baseURL:e,fetch:n,post:async(t,e,a={})=>{const s={...a,method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a.headers},body:e?JSON.stringify(e):void 0};return n(t,s)},pushChainFunction:e=>{a.push(e),s=t.createEnhancedFetch(a)}}};
2
2
  //# sourceMappingURL=functions.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"functions.cjs.js","sources":["../../src/functions/client.ts"],"sourcesContent":["/**\n * Functions client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing serverless function calls\n * against Nhost serverless functions.\n */\n\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Functions client interface providing methods for executing serverless function calls\n */\nexport interface Client {\n baseURL: string;\n\n /**\n * Execute a request to a serverless function\n * The response body will be automatically parsed based on the content type into the following types:\n * - Object if the response is application/json\n * - string text string if the response is text/*\n * - Blob if the response is any other type\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata. */\n fetch<T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n post<T = unknown>(\n path: string,\n body?: unknown,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n}\n\n/**\n * Creates a Functions API client for interacting with serverless functions.\n *\n * This client provides methods for executing requests against serverless functions,\n * with support for middleware functions to handle authentication, error handling,\n * and other cross-cutting concerns.\n *\n * @param baseURL - Base URL for the functions endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns Functions client with fetch method\n */\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n const enhancedFetch = createEnhancedFetch(chainFunctions);\n\n /**\n * Executes a request to a serverless function and processes the response\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata. Body will be either\n * - JSON object if the response is application/json\n - text string if the response is text/*\n - Blob if the response is any other type\n */\n const fetch = async <T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T | string | Blob>> => {\n const resp = await enhancedFetch(`${baseURL}${path}`, options);\n\n let body: T | string | Blob;\n // Process response based on content type\n if (resp.headers.get(\"content-type\")?.includes(\"application/json\")) {\n body = (await resp.json()) as T;\n } else if (resp.headers.get(\"content-type\")?.startsWith(\"text/\")) {\n body = await resp.text();\n } else {\n body = await resp.blob();\n }\n\n // Throw error for non-OK responses\n if (!resp.ok) {\n throw new FetchError(body, resp.status, resp.headers);\n }\n\n return {\n status: resp.status,\n body,\n headers: resp.headers,\n };\n };\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n const post = async <T = unknown>(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n ): Promise<FetchResponse<T | string | Blob>> => {\n // Ensure the method is POST and set the body\n const requestOptions: RequestInit = {\n ...options,\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n };\n\n return fetch<T>(path, requestOptions);\n };\n\n // Return client object with the fetch method\n return {\n baseURL,\n fetch,\n post,\n } as Client;\n};\n"],"names":["baseURL","chainFunctions","enhancedFetch","createEnhancedFetch","fetch","async","path","options","resp","body","headers","get","includes","json","startsWith","text","blob","ok","FetchError","status","post","requestOptions","method","Accept","JSON","stringify"],"mappings":"gJAmE+B,CAC7BA,EACAC,EAAkC,MAElC,MAAMC,EAAgBC,EAAAA,oBAAoBF,GAYpCG,EAAQC,MACZC,EACAC,KAEA,MAAMC,QAAaN,EAAc,GAAGF,IAAUM,IAAQC,GAEtD,IAAIE,EAWJ,GAREA,EADED,EAAKE,QAAQC,IAAI,iBAAiBC,SAAS,0BAC/BJ,EAAKK,OACVL,EAAKE,QAAQC,IAAI,iBAAiBG,WAAW,eACzCN,EAAKO,aAELP,EAAKQ,QAIfR,EAAKS,GACR,MAAM,IAAIC,EAAAA,WAAWT,EAAMD,EAAKW,OAAQX,EAAKE,SAG/C,MAAO,CACLS,OAAQX,EAAKW,OACbV,OACAC,QAASF,EAAKE,QAAA,EAuClB,MAAO,CACLV,UAAAI,MACAA,EACAgB,KAxBWf,MACXC,EACAG,EACAF,EAAuB,CAAA,KAGvB,MAAMc,EAA8B,IAC/Bd,EACHe,OAAQ,OACRZ,QAAS,CACPa,OAAQ,mBACR,eAAgB,sBACbhB,EAAQG,SAEbD,KAAMA,EAAOe,KAAKC,UAAUhB,QAAQ,GAGtC,OAAOL,EAASE,EAAMe,EAAc,EAOpC"}
1
+ {"version":3,"file":"functions.cjs.js","sources":["../../src/functions/client.ts"],"sourcesContent":["/**\n * Functions client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing serverless function calls\n * against Nhost serverless functions.\n */\n\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Functions client interface providing methods for executing serverless function calls\n */\nexport interface Client {\n baseURL: string;\n\n /** Add a middleware function to the fetch chain\n * @param chainFunction - The middleware function to add\n */\n pushChainFunction(chainFunction: ChainFunction): void;\n\n /**\n * Execute a request to a serverless function\n * The response body will be automatically parsed based on the content type into the following types:\n * - Object if the response is application/json\n * - string text string if the response is text/*\n * - Blob if the response is any other type\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata.\n */\n fetch<T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n post<T = unknown>(\n path: string,\n body?: unknown,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n}\n\n/**\n * Creates a Functions API client for interacting with serverless functions.\n *\n * This client provides methods for executing requests against serverless functions,\n * with support for middleware functions to handle authentication, error handling,\n * and other cross-cutting concerns.\n *\n * @param baseURL - Base URL for the functions endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns Functions client with fetch method\n */\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n enhancedFetch = createEnhancedFetch(chainFunctions);\n };\n\n /**\n * Executes a request to a serverless function and processes the response\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata. Body will be either\n * - JSON object if the response is application/json\n - text string if the response is text/*\n - Blob if the response is any other type\n */\n const fetch = async <T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T | string | Blob>> => {\n const resp = await enhancedFetch(`${baseURL}${path}`, options);\n\n let body: T | string | Blob;\n // Process response based on content type\n if (resp.headers.get(\"content-type\")?.includes(\"application/json\")) {\n body = (await resp.json()) as T;\n } else if (resp.headers.get(\"content-type\")?.startsWith(\"text/\")) {\n body = await resp.text();\n } else {\n body = await resp.blob();\n }\n\n // Throw error for non-OK responses\n if (!resp.ok) {\n throw new FetchError(body, resp.status, resp.headers);\n }\n\n return {\n status: resp.status,\n body,\n headers: resp.headers,\n };\n };\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n const post = async <T = unknown>(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n ): Promise<FetchResponse<T | string | Blob>> => {\n // Ensure the method is POST and set the body\n const requestOptions: RequestInit = {\n ...options,\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n };\n\n return fetch<T>(path, requestOptions);\n };\n\n // Return client object with the fetch method\n return {\n baseURL,\n fetch,\n post,\n pushChainFunction,\n } as Client;\n};\n"],"names":["baseURL","chainFunctions","enhancedFetch","createEnhancedFetch","fetch","async","path","options","resp","body","headers","get","includes","json","startsWith","text","blob","ok","FetchError","status","post","requestOptions","method","Accept","JSON","stringify","pushChainFunction","chainFunction","push"],"mappings":"gJAyE+B,CAC7BA,EACAC,EAAkC,MAElC,IAAIC,EAAgBC,EAAAA,oBAAoBF,GAExC,MAeMG,EAAQC,MACZC,EACAC,KAEA,MAAMC,QAAaN,EAAc,GAAGF,IAAUM,IAAQC,GAEtD,IAAIE,EAWJ,GAREA,EADED,EAAKE,QAAQC,IAAI,iBAAiBC,SAAS,0BAC/BJ,EAAKK,OACVL,EAAKE,QAAQC,IAAI,iBAAiBG,WAAW,eACzCN,EAAKO,aAELP,EAAKQ,QAIfR,EAAKS,GACR,MAAM,IAAIC,EAAAA,WAAWT,EAAMD,EAAKW,OAAQX,EAAKE,SAG/C,MAAO,CACLS,OAAQX,EAAKW,OACbV,OACAC,QAASF,EAAKE,QAAA,EAuClB,MAAO,CACLV,UAAAI,MACAA,EACAgB,KAxBWf,MACXC,EACAG,EACAF,EAAuB,CAAA,KAGvB,MAAMc,EAA8B,IAC/Bd,EACHe,OAAQ,OACRZ,QAAS,CACPa,OAAQ,mBACR,eAAgB,sBACbhB,EAAQG,SAEbD,KAAMA,EAAOe,KAAKC,UAAUhB,QAAQ,GAGtC,OAAOL,EAASE,EAAMe,EAAc,EAQpCK,kBAlFyBC,IACzB1B,EAAe2B,KAAKD,GACpBzB,EAAgBC,EAAAA,oBAAoBF,EAAc,EAgFlD"}
@@ -1,6 +1,10 @@
1
1
  import { c as createEnhancedFetch, F as FetchError } from "../fetch-2PHmQBIJ.mjs";
2
2
  const createAPIClient = (baseURL, chainFunctions = []) => {
3
- const enhancedFetch = createEnhancedFetch(chainFunctions);
3
+ let enhancedFetch = createEnhancedFetch(chainFunctions);
4
+ const pushChainFunction = (chainFunction) => {
5
+ chainFunctions.push(chainFunction);
6
+ enhancedFetch = createEnhancedFetch(chainFunctions);
7
+ };
4
8
  const fetch = async (path, options) => {
5
9
  const resp = await enhancedFetch(`${baseURL}${path}`, options);
6
10
  let body;
@@ -36,7 +40,8 @@ const createAPIClient = (baseURL, chainFunctions = []) => {
36
40
  return {
37
41
  baseURL,
38
42
  fetch,
39
- post
43
+ post,
44
+ pushChainFunction
40
45
  };
41
46
  };
42
47
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"functions.es.js","sources":["../../src/functions/client.ts"],"sourcesContent":["/**\n * Functions client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing serverless function calls\n * against Nhost serverless functions.\n */\n\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Functions client interface providing methods for executing serverless function calls\n */\nexport interface Client {\n baseURL: string;\n\n /**\n * Execute a request to a serverless function\n * The response body will be automatically parsed based on the content type into the following types:\n * - Object if the response is application/json\n * - string text string if the response is text/*\n * - Blob if the response is any other type\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata. */\n fetch<T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n post<T = unknown>(\n path: string,\n body?: unknown,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n}\n\n/**\n * Creates a Functions API client for interacting with serverless functions.\n *\n * This client provides methods for executing requests against serverless functions,\n * with support for middleware functions to handle authentication, error handling,\n * and other cross-cutting concerns.\n *\n * @param baseURL - Base URL for the functions endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns Functions client with fetch method\n */\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n const enhancedFetch = createEnhancedFetch(chainFunctions);\n\n /**\n * Executes a request to a serverless function and processes the response\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata. Body will be either\n * - JSON object if the response is application/json\n - text string if the response is text/*\n - Blob if the response is any other type\n */\n const fetch = async <T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T | string | Blob>> => {\n const resp = await enhancedFetch(`${baseURL}${path}`, options);\n\n let body: T | string | Blob;\n // Process response based on content type\n if (resp.headers.get(\"content-type\")?.includes(\"application/json\")) {\n body = (await resp.json()) as T;\n } else if (resp.headers.get(\"content-type\")?.startsWith(\"text/\")) {\n body = await resp.text();\n } else {\n body = await resp.blob();\n }\n\n // Throw error for non-OK responses\n if (!resp.ok) {\n throw new FetchError(body, resp.status, resp.headers);\n }\n\n return {\n status: resp.status,\n body,\n headers: resp.headers,\n };\n };\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n const post = async <T = unknown>(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n ): Promise<FetchResponse<T | string | Blob>> => {\n // Ensure the method is POST and set the body\n const requestOptions: RequestInit = {\n ...options,\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n };\n\n return fetch<T>(path, requestOptions);\n };\n\n // Return client object with the fetch method\n return {\n baseURL,\n fetch,\n post,\n } as Client;\n};\n"],"names":[],"mappings":";AAmEO,MAAM,kBAAkB,CAC7B,SACA,iBAAkC,OACvB;AACX,QAAM,gBAAgB,oBAAoB,cAAc;AAYxD,QAAM,QAAQ,OACZ,MACA,YAC8C;AAC9C,UAAM,OAAO,MAAM,cAAc,GAAG,OAAO,GAAG,IAAI,IAAI,OAAO;AAE7D,QAAI;AAEJ,QAAI,KAAK,QAAQ,IAAI,cAAc,GAAG,SAAS,kBAAkB,GAAG;AAClE,aAAQ,MAAM,KAAK,KAAA;AAAA,IACrB,WAAW,KAAK,QAAQ,IAAI,cAAc,GAAG,WAAW,OAAO,GAAG;AAChE,aAAO,MAAM,KAAK,KAAA;AAAA,IACpB,OAAO;AACL,aAAO,MAAM,KAAK,KAAA;AAAA,IACpB;AAGA,QAAI,CAAC,KAAK,IAAI;AACZ,YAAM,IAAI,WAAW,MAAM,KAAK,QAAQ,KAAK,OAAO;AAAA,IACtD;AAEA,WAAO;AAAA,MACL,QAAQ,KAAK;AAAA,MACb;AAAA,MACA,SAAS,KAAK;AAAA,IAAA;AAAA,EAElB;AAgBA,QAAM,OAAO,OACX,MACA,MACA,UAAuB,CAAA,MACuB;AAE9C,UAAM,iBAA8B;AAAA,MAClC,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,GAAG,QAAQ;AAAA,MAAA;AAAA,MAEb,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,IAAA;AAGtC,WAAO,MAAS,MAAM,cAAc;AAAA,EACtC;AAGA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"functions.es.js","sources":["../../src/functions/client.ts"],"sourcesContent":["/**\n * Functions client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing serverless function calls\n * against Nhost serverless functions.\n */\n\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Functions client interface providing methods for executing serverless function calls\n */\nexport interface Client {\n baseURL: string;\n\n /** Add a middleware function to the fetch chain\n * @param chainFunction - The middleware function to add\n */\n pushChainFunction(chainFunction: ChainFunction): void;\n\n /**\n * Execute a request to a serverless function\n * The response body will be automatically parsed based on the content type into the following types:\n * - Object if the response is application/json\n * - string text string if the response is text/*\n * - Blob if the response is any other type\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata.\n */\n fetch<T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n post<T = unknown>(\n path: string,\n body?: unknown,\n options?: RequestInit,\n ): Promise<FetchResponse<T>>;\n}\n\n/**\n * Creates a Functions API client for interacting with serverless functions.\n *\n * This client provides methods for executing requests against serverless functions,\n * with support for middleware functions to handle authentication, error handling,\n * and other cross-cutting concerns.\n *\n * @param baseURL - Base URL for the functions endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns Functions client with fetch method\n */\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n enhancedFetch = createEnhancedFetch(chainFunctions);\n };\n\n /**\n * Executes a request to a serverless function and processes the response\n *\n * @param path - The path to the serverless function\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata. Body will be either\n * - JSON object if the response is application/json\n - text string if the response is text/*\n - Blob if the response is any other type\n */\n const fetch = async <T = unknown>(\n path: string,\n options?: RequestInit,\n ): Promise<FetchResponse<T | string | Blob>> => {\n const resp = await enhancedFetch(`${baseURL}${path}`, options);\n\n let body: T | string | Blob;\n // Process response based on content type\n if (resp.headers.get(\"content-type\")?.includes(\"application/json\")) {\n body = (await resp.json()) as T;\n } else if (resp.headers.get(\"content-type\")?.startsWith(\"text/\")) {\n body = await resp.text();\n } else {\n body = await resp.blob();\n }\n\n // Throw error for non-OK responses\n if (!resp.ok) {\n throw new FetchError(body, resp.status, resp.headers);\n }\n\n return {\n status: resp.status,\n body,\n headers: resp.headers,\n };\n };\n\n /**\n * Executes a POST request to a serverless function with a JSON body\n *\n * This is a convenience method assuming the request is a POST with JSON body\n * setting the `Content-Type` and 'Accept' headers to `application/json` and\n * automatically stringifying the body.\n *\n * For a more generic request, use the `fetch` method instead.\n *\n * @param path - The path to the serverless function\n * @param body - The JSON body to send in the request\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the function response and metadata\n */\n const post = async <T = unknown>(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n ): Promise<FetchResponse<T | string | Blob>> => {\n // Ensure the method is POST and set the body\n const requestOptions: RequestInit = {\n ...options,\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n };\n\n return fetch<T>(path, requestOptions);\n };\n\n // Return client object with the fetch method\n return {\n baseURL,\n fetch,\n post,\n pushChainFunction,\n } as Client;\n};\n"],"names":[],"mappings":";AAyEO,MAAM,kBAAkB,CAC7B,SACA,iBAAkC,OACvB;AACX,MAAI,gBAAgB,oBAAoB,cAAc;AAEtD,QAAM,oBAAoB,CAAC,kBAAiC;AAC1D,mBAAe,KAAK,aAAa;AACjC,oBAAgB,oBAAoB,cAAc;AAAA,EACpD;AAYA,QAAM,QAAQ,OACZ,MACA,YAC8C;AAC9C,UAAM,OAAO,MAAM,cAAc,GAAG,OAAO,GAAG,IAAI,IAAI,OAAO;AAE7D,QAAI;AAEJ,QAAI,KAAK,QAAQ,IAAI,cAAc,GAAG,SAAS,kBAAkB,GAAG;AAClE,aAAQ,MAAM,KAAK,KAAA;AAAA,IACrB,WAAW,KAAK,QAAQ,IAAI,cAAc,GAAG,WAAW,OAAO,GAAG;AAChE,aAAO,MAAM,KAAK,KAAA;AAAA,IACpB,OAAO;AACL,aAAO,MAAM,KAAK,KAAA;AAAA,IACpB;AAGA,QAAI,CAAC,KAAK,IAAI;AACZ,YAAM,IAAI,WAAW,MAAM,KAAK,QAAQ,KAAK,OAAO;AAAA,IACtD;AAEA,WAAO;AAAA,MACL,QAAQ,KAAK;AAAA,MACb;AAAA,MACA,SAAS,KAAK;AAAA,IAAA;AAAA,EAElB;AAgBA,QAAM,OAAO,OACX,MACA,MACA,UAAuB,CAAA,MACuB;AAE9C,UAAM,iBAA8B;AAAA,MAClC,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,QAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,GAAG,QAAQ;AAAA,MAAA;AAAA,MAEb,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;AAAA,IAAA;AAGtC,WAAO,MAAS,MAAM,cAAc;AAAA,EACtC;AAGA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../fetch-DWXwEnoe.js");exports.createAPIClient=(t,r=[])=>{const n=e.createEnhancedFetch(r),o=async(r,o)=>{const s=await n(`${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),...o}),a=await s.text(),i=a?JSON.parse(a):{},c={body:i,status:s.status,headers:s.headers};if(i.errors)throw new e.FetchError(i,s.status,s.headers);return c};return{request:function(e,t,r){if("object"==typeof e&&"kind"in e){const n=e.definitions[0],s={query:e.loc?.source.body||"",variables:t,operationName:n&&"name"in n?n.name?.value:void 0};return o(s,r)}return o(e,t)},url:t}};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../fetch-DWXwEnoe.js");exports.createAPIClient=(t,r=[])=>{let n=e.createEnhancedFetch(r);const a=async(r,a)=>{const o=await n(`${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),...a}),s=await o.text(),i=s?JSON.parse(s):{},c={body:i,status:o.status,headers:o.headers};if(i.errors)throw new e.FetchError(i,o.status,o.headers);return c};return{request:function(e,t,r){if("object"==typeof e&&"kind"in e){const n=e.definitions[0],o={query:e.loc?.source.body||"",variables:t,operationName:n&&"name"in n?n.name?.value:void 0};return a(o,r)}return a(e,t)},url:t,pushChainFunction:t=>{r.push(t),n=e.createEnhancedFetch(r)}}};
2
2
  //# sourceMappingURL=graphql.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"graphql.cjs.js","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API.\n */\n\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport type GraphQLVariables = Record<string, unknown>;\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest<TVariables = GraphQLVariables> {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: TVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: { path: string; code: string };\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\nexport interface GraphQLResponse<TResponseData = unknown> {\n /** The data returned from successful execution */\n data?: TResponseData;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * Execute a GraphQL query operation using a typed document node\n *\n * @param document - TypedDocumentNode containing the query and type information\n * @param variables - Variables for the GraphQL operation\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * URL for the GraphQL endpoint.\n */\n url: string;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param url - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n url: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n const enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const executeOperation = async <\n TResponseData = unknown,\n TVariables = GraphQLVariables,\n >(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> => {\n const response = await enhancedFetch(`${url}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse<TResponseData> = (\n body ? JSON.parse(body) : {}\n ) as GraphQLResponse<TResponseData>;\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw new FetchError(data, response.status, response.headers);\n }\n\n return resp;\n };\n\n function request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n requestOrDocument:\n | GraphQLRequest<TVariables>\n | TypedDocumentNode<TResponseData, TVariables>,\n variablesOrOptions?: TVariables | RequestInit,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> {\n if (typeof requestOrDocument === \"object\" && \"kind\" in requestOrDocument) {\n const definition = requestOrDocument.definitions[0];\n\n const request: GraphQLRequest<TVariables> = {\n query: requestOrDocument.loc?.source.body || \"\",\n variables: variablesOrOptions as TVariables,\n operationName:\n definition && \"name\" in definition\n ? definition.name?.value\n : undefined,\n };\n return executeOperation(request, options);\n } else {\n // Handle GraphQLRequest\n const request = requestOrDocument;\n const requestOptions = variablesOrOptions as RequestInit;\n return executeOperation(request, requestOptions);\n }\n }\n\n return {\n request,\n url,\n } as Client;\n};\n"],"names":["url","chainFunctions","enhancedFetch","createEnhancedFetch","executeOperation","async","request","options","response","method","headers","body","JSON","stringify","text","data","parse","resp","status","errors","FetchError","requestOrDocument","variablesOrOptions","definition","definitions","query","loc","source","variables","operationName","name","value"],"mappings":"gJA0G+B,CAC7BA,EACAC,EAAkC,MAElC,MAAMC,EAAgBC,EAAAA,oBAAoBF,GAEpCG,EAAmBC,MAIvBC,EACAC,KAEA,MAAMC,QAAiBN,EAAc,GAAGF,IAAO,CAC7CS,OAAQ,OACRC,QAAS,CACP,eAAgB,oBAElBC,KAAMC,KAAKC,UAAUP,MAClBC,IAGCI,QAAaH,EAASM,OACtBC,EACJJ,EAAOC,KAAKI,MAAML,GAAQ,CAAA,EAGtBM,EAAO,CACXN,KAAMI,EACNG,OAAQV,EAASU,OACjBR,QAASF,EAASE,SAGpB,GAAIK,EAAKI,OACP,MAAM,IAAIC,EAAAA,WAAWL,EAAMP,EAASU,OAAQV,EAASE,SAGvD,OAAOO,CAAA,EAuCT,MAAO,CACLX,QA5BF,SACEe,EAGAC,EACAf,GAEA,GAAiC,iBAAtBc,GAAkC,SAAUA,EAAmB,CACxE,MAAME,EAAaF,EAAkBG,YAAY,GAE3ClB,EAAsC,CAC1CmB,MAAOJ,EAAkBK,KAAKC,OAAOhB,MAAQ,GAC7CiB,UAAWN,EACXO,cACEN,GAAc,SAAUA,EACpBA,EAAWO,MAAMC,WACjB,GAER,OAAO3B,EAAiBE,EAASC,EACnC,CAIE,OAAOH,EAFSiB,EACOC,EAG3B,EAIEtB,MAAA"}
1
+ {"version":3,"file":"graphql.cjs.js","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API.\n */\n\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport type GraphQLVariables = Record<string, unknown>;\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest<TVariables = GraphQLVariables> {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: TVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: { path: string; code: string };\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\nexport interface GraphQLResponse<TResponseData = unknown> {\n /** The data returned from successful execution */\n data?: TResponseData;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * Execute a GraphQL query operation using a typed document node\n *\n * @param document - TypedDocumentNode containing the query and type information\n * @param variables - Variables for the GraphQL operation\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * URL for the GraphQL endpoint.\n */\n url: string;\n\n /** Add a middleware function to the fetch chain\n * @param chainFunction - The middleware function to add\n */\n pushChainFunction(chainFunction: ChainFunction): void;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param url - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n url: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n enhancedFetch = createEnhancedFetch(chainFunctions);\n };\n\n const executeOperation = async <\n TResponseData = unknown,\n TVariables = GraphQLVariables,\n >(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> => {\n const response = await enhancedFetch(`${url}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse<TResponseData> = (\n body ? JSON.parse(body) : {}\n ) as GraphQLResponse<TResponseData>;\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw new FetchError(data, response.status, response.headers);\n }\n\n return resp;\n };\n\n function request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n requestOrDocument:\n | GraphQLRequest<TVariables>\n | TypedDocumentNode<TResponseData, TVariables>,\n variablesOrOptions?: TVariables | RequestInit,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> {\n if (typeof requestOrDocument === \"object\" && \"kind\" in requestOrDocument) {\n const definition = requestOrDocument.definitions[0];\n\n const request: GraphQLRequest<TVariables> = {\n query: requestOrDocument.loc?.source.body || \"\",\n variables: variablesOrOptions as TVariables,\n operationName:\n definition && \"name\" in definition\n ? definition.name?.value\n : undefined,\n };\n return executeOperation(request, options);\n } else {\n // Handle GraphQLRequest\n const request = requestOrDocument;\n const requestOptions = variablesOrOptions as RequestInit;\n return executeOperation(request, requestOptions);\n }\n }\n\n return {\n request,\n url,\n pushChainFunction,\n } as Client;\n};\n"],"names":["url","chainFunctions","enhancedFetch","createEnhancedFetch","executeOperation","async","request","options","response","method","headers","body","JSON","stringify","text","data","parse","resp","status","errors","FetchError","requestOrDocument","variablesOrOptions","definition","definitions","query","loc","source","variables","operationName","name","value","pushChainFunction","chainFunction","push"],"mappings":"gJA+G+B,CAC7BA,EACAC,EAAkC,MAElC,IAAIC,EAAgBC,EAAAA,oBAAoBF,GAExC,MAKMG,EAAmBC,MAIvBC,EACAC,KAEA,MAAMC,QAAiBN,EAAc,GAAGF,IAAO,CAC7CS,OAAQ,OACRC,QAAS,CACP,eAAgB,oBAElBC,KAAMC,KAAKC,UAAUP,MAClBC,IAGCI,QAAaH,EAASM,OACtBC,EACJJ,EAAOC,KAAKI,MAAML,GAAQ,CAAA,EAGtBM,EAAO,CACXN,KAAMI,EACNG,OAAQV,EAASU,OACjBR,QAASF,EAASE,SAGpB,GAAIK,EAAKI,OACP,MAAM,IAAIC,EAAAA,WAAWL,EAAMP,EAASU,OAAQV,EAASE,SAGvD,OAAOO,CAAA,EAuCT,MAAO,CACLX,QA5BF,SACEe,EAGAC,EACAf,GAEA,GAAiC,iBAAtBc,GAAkC,SAAUA,EAAmB,CACxE,MAAME,EAAaF,EAAkBG,YAAY,GAE3ClB,EAAsC,CAC1CmB,MAAOJ,EAAkBK,KAAKC,OAAOhB,MAAQ,GAC7CiB,UAAWN,EACXO,cACEN,GAAc,SAAUA,EACpBA,EAAWO,MAAMC,WACjB,GAER,OAAO3B,EAAiBE,EAASC,EACnC,CAIE,OAAOH,EAFSiB,EACOC,EAG3B,EAIEtB,MACAgC,kBA9EyBC,IACzBhC,EAAeiC,KAAKD,GACpB/B,EAAgBC,EAAAA,oBAAoBF,EAAc,EA4ElD"}
@@ -1,6 +1,10 @@
1
1
  import { c as createEnhancedFetch, F as FetchError } from "../fetch-2PHmQBIJ.mjs";
2
2
  const createAPIClient = (url, chainFunctions = []) => {
3
- const enhancedFetch = createEnhancedFetch(chainFunctions);
3
+ let enhancedFetch = createEnhancedFetch(chainFunctions);
4
+ const pushChainFunction = (chainFunction) => {
5
+ chainFunctions.push(chainFunction);
6
+ enhancedFetch = createEnhancedFetch(chainFunctions);
7
+ };
4
8
  const executeOperation = async (request2, options) => {
5
9
  const response = await enhancedFetch(`${url}`, {
6
10
  method: "POST",
@@ -39,7 +43,8 @@ const createAPIClient = (url, chainFunctions = []) => {
39
43
  }
40
44
  return {
41
45
  request,
42
- url
46
+ url,
47
+ pushChainFunction
43
48
  };
44
49
  };
45
50
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"graphql.es.js","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API.\n */\n\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport type GraphQLVariables = Record<string, unknown>;\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest<TVariables = GraphQLVariables> {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: TVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: { path: string; code: string };\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\nexport interface GraphQLResponse<TResponseData = unknown> {\n /** The data returned from successful execution */\n data?: TResponseData;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * Execute a GraphQL query operation using a typed document node\n *\n * @param document - TypedDocumentNode containing the query and type information\n * @param variables - Variables for the GraphQL operation\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * URL for the GraphQL endpoint.\n */\n url: string;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param url - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n url: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n const enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const executeOperation = async <\n TResponseData = unknown,\n TVariables = GraphQLVariables,\n >(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> => {\n const response = await enhancedFetch(`${url}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse<TResponseData> = (\n body ? JSON.parse(body) : {}\n ) as GraphQLResponse<TResponseData>;\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw new FetchError(data, response.status, response.headers);\n }\n\n return resp;\n };\n\n function request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n requestOrDocument:\n | GraphQLRequest<TVariables>\n | TypedDocumentNode<TResponseData, TVariables>,\n variablesOrOptions?: TVariables | RequestInit,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> {\n if (typeof requestOrDocument === \"object\" && \"kind\" in requestOrDocument) {\n const definition = requestOrDocument.definitions[0];\n\n const request: GraphQLRequest<TVariables> = {\n query: requestOrDocument.loc?.source.body || \"\",\n variables: variablesOrOptions as TVariables,\n operationName:\n definition && \"name\" in definition\n ? definition.name?.value\n : undefined,\n };\n return executeOperation(request, options);\n } else {\n // Handle GraphQLRequest\n const request = requestOrDocument;\n const requestOptions = variablesOrOptions as RequestInit;\n return executeOperation(request, requestOptions);\n }\n }\n\n return {\n request,\n url,\n } as Client;\n};\n"],"names":["request"],"mappings":";AA0GO,MAAM,kBAAkB,CAC7B,KACA,iBAAkC,OACvB;AACX,QAAM,gBAAgB,oBAAoB,cAAc;AAExD,QAAM,mBAAmB,OAIvBA,UACA,YAC2D;AAC3D,UAAM,WAAW,MAAM,cAAc,GAAG,GAAG,IAAI;AAAA,MAC7C,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,MAAA;AAAA,MAElB,MAAM,KAAK,UAAUA,QAAO;AAAA,MAC5B,GAAG;AAAA,IAAA,CACJ;AAED,UAAM,OAAO,MAAM,SAAS,KAAA;AAC5B,UAAM,OACJ,OAAO,KAAK,MAAM,IAAI,IAAI,CAAA;AAG5B,UAAM,OAAO;AAAA,MACX,MAAM;AAAA,MACN,QAAQ,SAAS;AAAA,MACjB,SAAS,SAAS;AAAA,IAAA;AAGpB,QAAI,KAAK,QAAQ;AACf,YAAM,IAAI,WAAW,MAAM,SAAS,QAAQ,SAAS,OAAO;AAAA,IAC9D;AAEA,WAAO;AAAA,EACT;AAWA,WAAS,QACP,mBAGA,oBACA,SACwD;AACxD,QAAI,OAAO,sBAAsB,YAAY,UAAU,mBAAmB;AACxE,YAAM,aAAa,kBAAkB,YAAY,CAAC;AAElD,YAAMA,WAAsC;AAAA,QAC1C,OAAO,kBAAkB,KAAK,OAAO,QAAQ;AAAA,QAC7C,WAAW;AAAA,QACX,eACE,cAAc,UAAU,aACpB,WAAW,MAAM,QACjB;AAAA,MAAA;AAER,aAAO,iBAAiBA,UAAS,OAAO;AAAA,IAC1C,OAAO;AAEL,YAAMA,WAAU;AAChB,YAAM,iBAAiB;AACvB,aAAO,iBAAiBA,UAAS,cAAc;AAAA,IACjD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"graphql.es.js","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API.\n */\n\nimport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from \"../fetch\";\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport type GraphQLVariables = Record<string, unknown>;\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest<TVariables = GraphQLVariables> {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: TVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: { path: string; code: string };\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\nexport interface GraphQLResponse<TResponseData = unknown> {\n /** The data returned from successful execution */\n data?: TResponseData;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * Execute a GraphQL query operation using a typed document node\n *\n * @param document - TypedDocumentNode containing the query and type information\n * @param variables - Variables for the GraphQL operation\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * URL for the GraphQL endpoint.\n */\n url: string;\n\n /** Add a middleware function to the fetch chain\n * @param chainFunction - The middleware function to add\n */\n pushChainFunction(chainFunction: ChainFunction): void;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param url - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n url: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n enhancedFetch = createEnhancedFetch(chainFunctions);\n };\n\n const executeOperation = async <\n TResponseData = unknown,\n TVariables = GraphQLVariables,\n >(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> => {\n const response = await enhancedFetch(`${url}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse<TResponseData> = (\n body ? JSON.parse(body) : {}\n ) as GraphQLResponse<TResponseData>;\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw new FetchError(data, response.status, response.headers);\n }\n\n return resp;\n };\n\n function request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n requestOrDocument:\n | GraphQLRequest<TVariables>\n | TypedDocumentNode<TResponseData, TVariables>,\n variablesOrOptions?: TVariables | RequestInit,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> {\n if (typeof requestOrDocument === \"object\" && \"kind\" in requestOrDocument) {\n const definition = requestOrDocument.definitions[0];\n\n const request: GraphQLRequest<TVariables> = {\n query: requestOrDocument.loc?.source.body || \"\",\n variables: variablesOrOptions as TVariables,\n operationName:\n definition && \"name\" in definition\n ? definition.name?.value\n : undefined,\n };\n return executeOperation(request, options);\n } else {\n // Handle GraphQLRequest\n const request = requestOrDocument;\n const requestOptions = variablesOrOptions as RequestInit;\n return executeOperation(request, requestOptions);\n }\n }\n\n return {\n request,\n url,\n pushChainFunction,\n } as Client;\n};\n"],"names":["request"],"mappings":";AA+GO,MAAM,kBAAkB,CAC7B,KACA,iBAAkC,OACvB;AACX,MAAI,gBAAgB,oBAAoB,cAAc;AAEtD,QAAM,oBAAoB,CAAC,kBAAiC;AAC1D,mBAAe,KAAK,aAAa;AACjC,oBAAgB,oBAAoB,cAAc;AAAA,EACpD;AAEA,QAAM,mBAAmB,OAIvBA,UACA,YAC2D;AAC3D,UAAM,WAAW,MAAM,cAAc,GAAG,GAAG,IAAI;AAAA,MAC7C,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,MAAA;AAAA,MAElB,MAAM,KAAK,UAAUA,QAAO;AAAA,MAC5B,GAAG;AAAA,IAAA,CACJ;AAED,UAAM,OAAO,MAAM,SAAS,KAAA;AAC5B,UAAM,OACJ,OAAO,KAAK,MAAM,IAAI,IAAI,CAAA;AAG5B,UAAM,OAAO;AAAA,MACX,MAAM;AAAA,MACN,QAAQ,SAAS;AAAA,MACjB,SAAS,SAAS;AAAA,IAAA;AAGpB,QAAI,KAAK,QAAQ;AACf,YAAM,IAAI,WAAW,MAAM,SAAS,QAAQ,SAAS,OAAO;AAAA,IAC9D;AAEA,WAAO;AAAA,EACT;AAWA,WAAS,QACP,mBAGA,oBACA,SACwD;AACxD,QAAI,OAAO,sBAAsB,YAAY,UAAU,mBAAmB;AACxE,YAAM,aAAa,kBAAkB,YAAY,CAAC;AAElD,YAAMA,WAAsC;AAAA,QAC1C,OAAO,kBAAkB,KAAK,OAAO,QAAQ;AAAA,QAC7C,WAAW;AAAA,QACX,eACE,cAAc,UAAU,aACpB,WAAW,MAAM,QACjB;AAAA,MAAA;AAER,aAAO,iBAAiBA,UAAS,OAAO;AAAA,IAC1C,OAAO;AAEL,YAAMA,WAAU;AAChB,YAAM,iBAAiB;AACvB,aAAO,iBAAiBA,UAAS,cAAc;AAAA,IACjD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
@@ -1,4 +1,4 @@
1
- import { r } from "../refreshSession-WwGlzgtM.mjs";
1
+ import { r } from "../refreshSession-CG8GIEun.mjs";
2
2
  const decodeUserSession = (accessToken) => {
3
3
  const s = accessToken.split(".");
4
4
  if (s.length !== 3 || !s[1]) {