@nhost/nhost-js 4.2.2 → 4.3.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.
- package/dist/fetch-2PHmQBIJ.js.map +1 -1
- package/dist/fetch-DWXwEnoe.cjs.map +1 -1
- package/dist/{middlewareWithAdminSession-DLqDQUbW.js → middlewareWithAdminSession-BeIk-9HO.js} +2 -2
- package/dist/middlewareWithAdminSession-BeIk-9HO.js.map +1 -0
- package/dist/middlewareWithAdminSession-DDApoLkL.cjs.map +1 -1
- package/dist/nhost-js/auth.cjs.map +1 -1
- package/dist/nhost-js/auth.js.map +1 -1
- package/dist/nhost-js/fetch.cjs.map +1 -1
- package/dist/nhost-js/fetch.js +1 -1
- package/dist/nhost-js/fetch.js.map +1 -1
- package/dist/nhost-js/functions.cjs.map +1 -1
- package/dist/nhost-js/functions.js.map +1 -1
- package/dist/nhost-js/graphql.cjs.map +1 -1
- package/dist/nhost-js/graphql.js.map +1 -1
- package/dist/nhost-js/session.cjs.map +1 -1
- package/dist/nhost-js/session.js +1 -1
- package/dist/nhost-js/session.js.map +1 -1
- package/dist/nhost-js/storage.cjs.map +1 -1
- package/dist/nhost-js/storage.js.map +1 -1
- package/dist/nhost-js.cjs.map +1 -1
- package/dist/nhost-js.js +2 -2
- package/dist/nhost-js.js.map +1 -1
- package/dist/nhost-js.umd.js.map +1 -1
- package/dist/refreshSession-Bw715ZmX.cjs.map +1 -1
- package/dist/{refreshSession-CG8GIEun.js → refreshSession-WwGlzgtM.js} +2 -5
- package/dist/refreshSession-WwGlzgtM.js.map +1 -0
- package/dist/src/auth/client.d.ts +28 -28
- package/dist/src/auth/client.js +76 -76
- package/dist/src/auth/index.d.ts +1 -1
- package/dist/src/auth/index.js +1 -1
- package/dist/src/fetch/fetch.js +20 -20
- package/dist/src/fetch/index.d.ts +7 -7
- package/dist/src/fetch/index.js +7 -7
- package/dist/src/fetch/middlewareAttachAccessToken.d.ts +2 -2
- package/dist/src/fetch/middlewareAttachAccessToken.js +2 -2
- package/dist/src/fetch/middlewareSessionRefresh.d.ts +3 -3
- package/dist/src/fetch/middlewareSessionRefresh.js +3 -3
- package/dist/src/fetch/middlewareUpdateSessionFromResponse.d.ts +2 -2
- package/dist/src/fetch/middlewareUpdateSessionFromResponse.js +8 -8
- package/dist/src/fetch/middlewareWithAdminSession.d.ts +1 -1
- package/dist/src/fetch/middlewareWithAdminSession.js +5 -5
- package/dist/src/fetch/middlewareWithHeaders.d.ts +1 -1
- package/dist/src/fetch/middlewareWithRole.d.ts +1 -1
- package/dist/src/fetch/middlewareWithRole.js +2 -2
- package/dist/src/functions/client.d.ts +1 -1
- package/dist/src/functions/client.js +6 -6
- package/dist/src/functions/index.d.ts +1 -1
- package/dist/src/functions/index.js +1 -1
- package/dist/src/graphql/client.d.ts +2 -2
- package/dist/src/graphql/client.js +6 -6
- package/dist/src/graphql/index.d.ts +1 -1
- package/dist/src/graphql/index.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/nhost.d.ts +6 -6
- package/dist/src/nhost.js +11 -11
- package/dist/src/session/index.d.ts +4 -4
- package/dist/src/session/index.js +3 -3
- package/dist/src/session/refreshSession.d.ts +3 -3
- package/dist/src/session/refreshSession.d.ts.map +1 -1
- package/dist/src/session/refreshSession.js +5 -7
- package/dist/src/session/refreshSession.js.map +1 -1
- package/dist/src/session/session.d.ts +2 -2
- package/dist/src/session/session.js +15 -15
- package/dist/src/session/storage.d.ts +3 -3
- package/dist/src/session/storage.js +4 -4
- package/dist/src/session/storageBackend.d.ts +2 -2
- package/dist/src/session/storageBackend.js +7 -7
- package/dist/src/storage/client.d.ts +5 -5
- package/dist/src/storage/client.js +44 -44
- package/dist/src/storage/index.d.ts +1 -1
- package/dist/src/storage/index.js +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -2
- package/dist/middlewareWithAdminSession-DLqDQUbW.js.map +0 -1
- package/dist/refreshSession-CG8GIEun.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","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
|
|
1
|
+
{"version":3,"file":"fetch.cjs","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":"ijBAwBGA,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"}
|
package/dist/nhost-js/fetch.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { F, c } from "../fetch-2PHmQBIJ.js";
|
|
2
|
-
import { a, s, u, w } from "../middlewareWithAdminSession-
|
|
2
|
+
import { a, s, u, w } from "../middlewareWithAdminSession-BeIk-9HO.js";
|
|
3
3
|
const withHeadersMiddleware = (defaultHeaders) => (next) => async (url, options = {}) => {
|
|
4
4
|
const headers = new Headers(options.headers || {});
|
|
5
5
|
const defaults = new Headers(defaultHeaders);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.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
|
|
1
|
+
{"version":3,"file":"fetch.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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functions.cjs","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
|
|
1
|
+
{"version":3,"file":"functions.cjs","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":"iJAyE+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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functions.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
|
|
1
|
+
{"version":3,"file":"functions.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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.cjs","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
|
|
1
|
+
{"version":3,"file":"graphql.cjs","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":"iJA+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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.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
|
|
1
|
+
{"version":3,"file":"graphql.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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.cjs","sources":["../../src/session/session.ts","../../src/session/storageBackend.ts","../../src/session/storage.ts"],"sourcesContent":["import type { Session as AuthSession } from \"../auth\";\n\n/**\n * Decoded JWT token payload with processed timestamps and Hasura claims\n */\nexport interface DecodedToken {\n /** Token expiration time as Date object */\n exp?: number;\n /** Token issued at time as Date object */\n iat?: number;\n /** Token issuer */\n iss?: string;\n /** Token subject (user ID) */\n sub?: string;\n /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */\n \"https://hasura.io/jwt/claims\"?: Record<string, unknown>;\n /** Any other JWT claims */\n [key: string]: unknown;\n}\n\nexport interface Session extends AuthSession {\n /** Decoded JWT token payload with processed timestamps and Hasura claims */\n decodedToken: DecodedToken;\n}\n\nexport const decodeUserSession = (accessToken: string): DecodedToken => {\n const s = accessToken.split(\".\");\n if (s.length !== 3 || !s[1]) {\n throw new Error(\"Invalid access token format\");\n }\n\n const decodedToken = JSON.parse(\n typeof atob !== \"undefined\"\n ? atob(s[1])\n : Buffer.from(s[1], \"base64\").toString(\"utf-8\"),\n ) as Record<string, unknown>;\n\n // Convert iat and exp to Date objects\n const iat =\n typeof decodedToken[\"iat\"] === \"number\"\n ? decodedToken[\"iat\"] * 1000 // Convert seconds to milliseconds\n : undefined;\n const exp =\n typeof decodedToken[\"exp\"] === \"number\"\n ? decodedToken[\"exp\"] * 1000 // Convert seconds to milliseconds\n : undefined;\n\n // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays\n const hasuraClaims = decodedToken[\"https://hasura.io/jwt/claims\"] as\n | Record<string, unknown>\n | undefined;\n const processedClaims = hasuraClaims\n ? Object.entries(hasuraClaims).reduce(\n (acc, [key, value]) => {\n if (typeof value === \"string\" && isPostgresArray(value)) {\n acc[key] = parsePostgresArray(value);\n } else {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : undefined;\n\n return {\n ...decodedToken,\n iat,\n exp,\n \"https://hasura.io/jwt/claims\": processedClaims,\n };\n};\n\nconst isPostgresArray = (value: string): boolean => {\n return value.startsWith(\"{\") && value.endsWith(\"}\");\n};\n\nconst parsePostgresArray = (value: string): string[] => {\n if (!value || value === \"{}\") return [];\n // Remove curly braces and split by comma, handling quoted values\n return value\n .slice(1, -1)\n .split(\",\")\n .map((item) => item.trim().replace(/^\"(.*)\"$/, \"$1\"));\n};\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session } from \"./session\";\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageBackend {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = \"nhostSession\";\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageBackend {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param options - Configuration options\n * @param options.storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(options?: { storageKey?: string }) {\n this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageBackend {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for synchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageBackend {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: \"strict\" | \"lax\" | \"none\";\n\n /**\n * Creates a new CookieStorage instance\n * @param options - Configuration options\n * @param options.cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param options.sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(options?: {\n cookieName?: string;\n expirationDays?: number;\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n }) {\n this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;\n this.expirationDays = options?.expirationDays ?? 30;\n this.secure = options?.secure ?? true;\n this.sameSite = options?.sameSite || \"lax\";\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(\";\");\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split(\"=\");\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || \"\")) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? \"secure; \" : \"\"}SameSite=${this.sameSite}`;\n\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? \"secure; \" : \"\"}SameSite=${this.sameSite}`;\n }\n}\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session as AuthSession } from \"../auth\";\nimport { decodeUserSession, type Session } from \"./session\";\nimport {\n LocalStorage,\n MemoryStorage,\n type SessionStorageBackend,\n} from \"./storageBackend\";\n\n/**\n * Callback function type for session change subscriptions\n */\nexport type SessionChangeCallback = (session: Session | null) => void;\n\n/**\n * A wrapper around any SessionStorageInterface implementation that adds\n * the ability to subscribe to session changes.\n */\nexport class SessionStorage {\n private readonly storage: SessionStorageBackend;\n private subscribers = new Set<SessionChangeCallback>();\n\n /**\n * Creates a new SessionStorage instance\n * @param storage - The underlying storage implementation to use\n */\n constructor(storage: SessionStorageBackend) {\n this.storage = storage;\n }\n\n /**\n * Gets the session from the underlying storage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n return this.storage.get();\n }\n\n /**\n * Sets the session in the underlying storage and notifies subscribers\n * @param value - The session to store\n */\n set(value: AuthSession): void {\n const decodedToken = decodeUserSession(value.accessToken);\n const decodedSession = {\n ...value,\n decodedToken: decodedToken,\n };\n\n this.storage.set(decodedSession);\n this.notifySubscribers(decodedSession);\n }\n\n /**\n * Removes the session from the underlying storage and notifies subscribers\n */\n remove(): void {\n this.storage.remove();\n this.notifySubscribers(null);\n }\n\n /**\n * Subscribe to session changes\n * @param callback - Function that will be called when the session changes\n * @returns An unsubscribe function to remove this subscription\n */\n onChange(callback: SessionChangeCallback) {\n this.subscribers.add(callback);\n\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Notify all subscribers of a session change\n * @param session - The new session value or null if removed\n */\n private notifySubscribers(session: Session | null): void {\n for (const subscriber of this.subscribers) {\n try {\n subscriber(session);\n } catch (error) {\n console.error(\"Error notifying subscriber:\", error);\n }\n }\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation as a SessionStorageBackend\n */\nexport const detectStorage = (): SessionStorageBackend => {\n if (typeof window !== \"undefined\") {\n return new LocalStorage();\n }\n return new MemoryStorage();\n};\n"],"names":["isPostgresArray","value","startsWith","endsWith","parsePostgresArray","slice","split","map","item","trim","replace","DEFAULT_SESSION_KEY","LocalStorage","storageKey","constructor","options","this","get","window","localStorage","getItem","JSON","parse","remove","set","setItem","stringify","removeItem","MemoryStorage","session","cookieName","expirationDays","secure","sameSite","cookies","document","cookie","name","decodeURIComponent","expires","Date","setTime","getTime","cookieValue","encodeURIComponent","cookieString","toUTCString","storage","subscribers","Set","decodedToken","accessToken","s","length","Error","atob","Buffer","from","toString","iat","exp","hasuraClaims","processedClaims","Object","entries","reduce","acc","key","decodeUserSession","decodedSession","notifySubscribers","onChange","callback","add","delete","subscriber","error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BpE,EACHiD,gBAGFlC,KAAK+B,QAAQvB,IAAI6C,GACjBrD,KAAKsD,kBAAkBD,EACzB,CAKA,MAAA9C,GACEP,KAAK+B,QAAQxB,SACbP,KAAKsD,kBAAkB,KACzB,CAOA,QAAAC,CAASC,GAGP,OAFAxD,KAAKgC,YAAYyB,IAAID,GAEd,KACLxD,KAAKgC,YAAY0B,OAAOF,EAAQ,CAEpC,CAMQ,iBAAAF,CAAkBzC,GACxB,IAAA,MAAW8C,KAAc3D,KAAKgC,YAC5B,IACE2B,EAAW9C,EACb,OAAS+C,GACPC,QAAQD,MAAM,8BAA+BA,EAC/C,CAEJ,yBAY2B,IACL,oBAAX1D,OACF,IAAIN,EAEN,IAAIgB"}
|
|
1
|
+
{"version":3,"file":"session.cjs","sources":["../../src/session/session.ts","../../src/session/storageBackend.ts","../../src/session/storage.ts"],"sourcesContent":["import type { Session as AuthSession } from '../auth';\n\n/**\n * Decoded JWT token payload with processed timestamps and Hasura claims\n */\nexport interface DecodedToken {\n /** Token expiration time as Date object */\n exp?: number;\n /** Token issued at time as Date object */\n iat?: number;\n /** Token issuer */\n iss?: string;\n /** Token subject (user ID) */\n sub?: string;\n /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */\n 'https://hasura.io/jwt/claims'?: Record<string, unknown>;\n /** Any other JWT claims */\n [key: string]: unknown;\n}\n\nexport interface Session extends AuthSession {\n /** Decoded JWT token payload with processed timestamps and Hasura claims */\n decodedToken: DecodedToken;\n}\n\nexport const decodeUserSession = (accessToken: string): DecodedToken => {\n const s = accessToken.split('.');\n if (s.length !== 3 || !s[1]) {\n throw new Error('Invalid access token format');\n }\n\n const decodedToken = JSON.parse(\n typeof atob !== 'undefined'\n ? atob(s[1])\n : Buffer.from(s[1], 'base64').toString('utf-8'),\n ) as Record<string, unknown>;\n\n // Convert iat and exp to Date objects\n const iat =\n typeof decodedToken['iat'] === 'number'\n ? decodedToken['iat'] * 1000 // Convert seconds to milliseconds\n : undefined;\n const exp =\n typeof decodedToken['exp'] === 'number'\n ? decodedToken['exp'] * 1000 // Convert seconds to milliseconds\n : undefined;\n\n // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays\n const hasuraClaims = decodedToken['https://hasura.io/jwt/claims'] as\n | Record<string, unknown>\n | undefined;\n const processedClaims = hasuraClaims\n ? Object.entries(hasuraClaims).reduce(\n (acc, [key, value]) => {\n if (typeof value === 'string' && isPostgresArray(value)) {\n acc[key] = parsePostgresArray(value);\n } else {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : undefined;\n\n return {\n ...decodedToken,\n iat,\n exp,\n 'https://hasura.io/jwt/claims': processedClaims,\n };\n};\n\nconst isPostgresArray = (value: string): boolean => {\n return value.startsWith('{') && value.endsWith('}');\n};\n\nconst parsePostgresArray = (value: string): string[] => {\n if (!value || value === '{}') return [];\n // Remove curly braces and split by comma, handling quoted values\n return value\n .slice(1, -1)\n .split(',')\n .map((item) => item.trim().replace(/^\"(.*)\"$/, '$1'));\n};\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session } from './session';\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageBackend {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = 'nhostSession';\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageBackend {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param options - Configuration options\n * @param options.storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(options?: { storageKey?: string }) {\n this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageBackend {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for synchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageBackend {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: 'strict' | 'lax' | 'none';\n\n /**\n * Creates a new CookieStorage instance\n * @param options - Configuration options\n * @param options.cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param options.sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(options?: {\n cookieName?: string;\n expirationDays?: number;\n secure?: boolean;\n sameSite?: 'strict' | 'lax' | 'none';\n }) {\n this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;\n this.expirationDays = options?.expirationDays ?? 30;\n this.secure = options?.secure ?? true;\n this.sameSite = options?.sameSite || 'lax';\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split('=');\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || '')) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n }\n}\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session as AuthSession } from '../auth';\nimport { decodeUserSession, type Session } from './session';\nimport {\n LocalStorage,\n MemoryStorage,\n type SessionStorageBackend,\n} from './storageBackend';\n\n/**\n * Callback function type for session change subscriptions\n */\nexport type SessionChangeCallback = (session: Session | null) => void;\n\n/**\n * A wrapper around any SessionStorageInterface implementation that adds\n * the ability to subscribe to session changes.\n */\nexport class SessionStorage {\n private readonly storage: SessionStorageBackend;\n private subscribers = new Set<SessionChangeCallback>();\n\n /**\n * Creates a new SessionStorage instance\n * @param storage - The underlying storage implementation to use\n */\n constructor(storage: SessionStorageBackend) {\n this.storage = storage;\n }\n\n /**\n * Gets the session from the underlying storage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n return this.storage.get();\n }\n\n /**\n * Sets the session in the underlying storage and notifies subscribers\n * @param value - The session to store\n */\n set(value: AuthSession): void {\n const decodedToken = decodeUserSession(value.accessToken);\n const decodedSession = {\n ...value,\n decodedToken: decodedToken,\n };\n\n this.storage.set(decodedSession);\n this.notifySubscribers(decodedSession);\n }\n\n /**\n * Removes the session from the underlying storage and notifies subscribers\n */\n remove(): void {\n this.storage.remove();\n this.notifySubscribers(null);\n }\n\n /**\n * Subscribe to session changes\n * @param callback - Function that will be called when the session changes\n * @returns An unsubscribe function to remove this subscription\n */\n onChange(callback: SessionChangeCallback) {\n this.subscribers.add(callback);\n\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Notify all subscribers of a session change\n * @param session - The new session value or null if removed\n */\n private notifySubscribers(session: Session | null): void {\n for (const subscriber of this.subscribers) {\n try {\n subscriber(session);\n } catch (error) {\n console.error('Error notifying subscriber:', error);\n }\n }\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation as a SessionStorageBackend\n */\nexport const detectStorage = (): SessionStorageBackend => {\n if (typeof window !== 'undefined') {\n return new LocalStorage();\n }\n return new MemoryStorage();\n};\n"],"names":["isPostgresArray","value","startsWith","endsWith","parsePostgresArray","slice","split","map","item","trim","replace","DEFAULT_SESSION_KEY","LocalStorage","storageKey","constructor","options","this","get","window","localStorage","getItem","JSON","parse","remove","set","setItem","stringify","removeItem","MemoryStorage","session","cookieName","expirationDays","secure","sameSite","cookies","document","cookie","name","decodeURIComponent","expires","Date","setTime","getTime","cookieValue","encodeURIComponent","cookieString","toUTCString","storage","subscribers","Set","decodedToken","accessToken","s","length","Error","atob","Buffer","from","toString","iat","exp","hasuraClaims","processedClaims","Object","entries","reduce","acc","key","decodeUserSession","decodedSession","notifySubscribers","onChange","callback","add","delete","subscriber","error","console"],"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ACHiD,gBAGFlC,KAAK+B,QAAQvB,IAAI6C,GACjBrD,KAAKsD,kBAAkBD,EACzB,CAKA,MAAA9C,GACEP,KAAK+B,QAAQxB,SACbP,KAAKsD,kBAAkB,KACzB,CAOA,QAAAC,CAASC,GAGP,OAFAxD,KAAKgC,YAAYyB,IAAID,GAEd,KACLxD,KAAKgC,YAAY0B,OAAOF,EAAQ,CAEpC,CAMQ,iBAAAF,CAAkBzC,GACxB,IAAA,MAAW8C,KAAc3D,KAAKgC,YAC5B,IACE2B,EAAW9C,EACb,OAAS+C,GACPC,QAAQD,MAAM,8BAA+BA,EAC/C,CAEJ,yBAY2B,IACL,oBAAX1D,OACF,IAAIN,EAEN,IAAIgB"}
|
package/dist/nhost-js/session.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sources":["../../src/session/session.ts","../../src/session/storageBackend.ts","../../src/session/storage.ts"],"sourcesContent":["import type { Session as AuthSession } from \"../auth\";\n\n/**\n * Decoded JWT token payload with processed timestamps and Hasura claims\n */\nexport interface DecodedToken {\n /** Token expiration time as Date object */\n exp?: number;\n /** Token issued at time as Date object */\n iat?: number;\n /** Token issuer */\n iss?: string;\n /** Token subject (user ID) */\n sub?: string;\n /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */\n \"https://hasura.io/jwt/claims\"?: Record<string, unknown>;\n /** Any other JWT claims */\n [key: string]: unknown;\n}\n\nexport interface Session extends AuthSession {\n /** Decoded JWT token payload with processed timestamps and Hasura claims */\n decodedToken: DecodedToken;\n}\n\nexport const decodeUserSession = (accessToken: string): DecodedToken => {\n const s = accessToken.split(\".\");\n if (s.length !== 3 || !s[1]) {\n throw new Error(\"Invalid access token format\");\n }\n\n const decodedToken = JSON.parse(\n typeof atob !== \"undefined\"\n ? atob(s[1])\n : Buffer.from(s[1], \"base64\").toString(\"utf-8\"),\n ) as Record<string, unknown>;\n\n // Convert iat and exp to Date objects\n const iat =\n typeof decodedToken[\"iat\"] === \"number\"\n ? decodedToken[\"iat\"] * 1000 // Convert seconds to milliseconds\n : undefined;\n const exp =\n typeof decodedToken[\"exp\"] === \"number\"\n ? decodedToken[\"exp\"] * 1000 // Convert seconds to milliseconds\n : undefined;\n\n // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays\n const hasuraClaims = decodedToken[\"https://hasura.io/jwt/claims\"] as\n | Record<string, unknown>\n | undefined;\n const processedClaims = hasuraClaims\n ? Object.entries(hasuraClaims).reduce(\n (acc, [key, value]) => {\n if (typeof value === \"string\" && isPostgresArray(value)) {\n acc[key] = parsePostgresArray(value);\n } else {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : undefined;\n\n return {\n ...decodedToken,\n iat,\n exp,\n \"https://hasura.io/jwt/claims\": processedClaims,\n };\n};\n\nconst isPostgresArray = (value: string): boolean => {\n return value.startsWith(\"{\") && value.endsWith(\"}\");\n};\n\nconst parsePostgresArray = (value: string): string[] => {\n if (!value || value === \"{}\") return [];\n // Remove curly braces and split by comma, handling quoted values\n return value\n .slice(1, -1)\n .split(\",\")\n .map((item) => item.trim().replace(/^\"(.*)\"$/, \"$1\"));\n};\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session } from \"./session\";\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageBackend {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = \"nhostSession\";\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageBackend {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param options - Configuration options\n * @param options.storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(options?: { storageKey?: string }) {\n this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageBackend {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for synchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageBackend {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: \"strict\" | \"lax\" | \"none\";\n\n /**\n * Creates a new CookieStorage instance\n * @param options - Configuration options\n * @param options.cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param options.sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(options?: {\n cookieName?: string;\n expirationDays?: number;\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n }) {\n this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;\n this.expirationDays = options?.expirationDays ?? 30;\n this.secure = options?.secure ?? true;\n this.sameSite = options?.sameSite || \"lax\";\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(\";\");\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split(\"=\");\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || \"\")) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? \"secure; \" : \"\"}SameSite=${this.sameSite}`;\n\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? \"secure; \" : \"\"}SameSite=${this.sameSite}`;\n }\n}\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session as AuthSession } from \"../auth\";\nimport { decodeUserSession, type Session } from \"./session\";\nimport {\n LocalStorage,\n MemoryStorage,\n type SessionStorageBackend,\n} from \"./storageBackend\";\n\n/**\n * Callback function type for session change subscriptions\n */\nexport type SessionChangeCallback = (session: Session | null) => void;\n\n/**\n * A wrapper around any SessionStorageInterface implementation that adds\n * the ability to subscribe to session changes.\n */\nexport class SessionStorage {\n private readonly storage: SessionStorageBackend;\n private subscribers = new Set<SessionChangeCallback>();\n\n /**\n * Creates a new SessionStorage instance\n * @param storage - The underlying storage implementation to use\n */\n constructor(storage: SessionStorageBackend) {\n this.storage = storage;\n }\n\n /**\n * Gets the session from the underlying storage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n return this.storage.get();\n }\n\n /**\n * Sets the session in the underlying storage and notifies subscribers\n * @param value - The session to store\n */\n set(value: AuthSession): void {\n const decodedToken = decodeUserSession(value.accessToken);\n const decodedSession = {\n ...value,\n decodedToken: decodedToken,\n };\n\n this.storage.set(decodedSession);\n this.notifySubscribers(decodedSession);\n }\n\n /**\n * Removes the session from the underlying storage and notifies subscribers\n */\n remove(): void {\n this.storage.remove();\n this.notifySubscribers(null);\n }\n\n /**\n * Subscribe to session changes\n * @param callback - Function that will be called when the session changes\n * @returns An unsubscribe function to remove this subscription\n */\n onChange(callback: SessionChangeCallback) {\n this.subscribers.add(callback);\n\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Notify all subscribers of a session change\n * @param session - The new session value or null if removed\n */\n private notifySubscribers(session: Session | null): void {\n for (const subscriber of this.subscribers) {\n try {\n subscriber(session);\n } catch (error) {\n console.error(\"Error notifying subscriber:\", error);\n }\n }\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation as a SessionStorageBackend\n */\nexport const detectStorage = (): SessionStorageBackend => {\n if (typeof window !== \"undefined\") {\n return new LocalStorage();\n }\n return new MemoryStorage();\n};\n"],"names":[],"mappings":";AAyBO,MAAM,oBAAoB,CAAC,gBAAsC;AACtE,QAAM,IAAI,YAAY,MAAM,GAAG;AAC/B,MAAI,EAAE,WAAW,KAAK,CAAC,EAAE,CAAC,GAAG;AAC3B,UAAM,IAAI,MAAM,6BAA6B;AAAA,EAC/C;AAEA,QAAM,eAAe,KAAK;AAAA,IACxB,OAAO,SAAS,cACZ,KAAK,EAAE,CAAC,CAAC,IACT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eAAW,cAAc,KAAK,aAAa;AACzC,UAAI;AACF,mBAAW,OAAO;AAAA,MACpB,SAAS,OAAO;AACd,gBAAQ,MAAM,+BAA+B,KAAK;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AACF;AAWO,MAAM,gBAAgB,MAA6B;AACxD,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,IAAI,aAAA;AAAA,EACb;AACA,SAAO,IAAI,cAAA;AACb;"}
|
|
1
|
+
{"version":3,"file":"session.js","sources":["../../src/session/session.ts","../../src/session/storageBackend.ts","../../src/session/storage.ts"],"sourcesContent":["import type { Session as AuthSession } from '../auth';\n\n/**\n * Decoded JWT token payload with processed timestamps and Hasura claims\n */\nexport interface DecodedToken {\n /** Token expiration time as Date object */\n exp?: number;\n /** Token issued at time as Date object */\n iat?: number;\n /** Token issuer */\n iss?: string;\n /** Token subject (user ID) */\n sub?: string;\n /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */\n 'https://hasura.io/jwt/claims'?: Record<string, unknown>;\n /** Any other JWT claims */\n [key: string]: unknown;\n}\n\nexport interface Session extends AuthSession {\n /** Decoded JWT token payload with processed timestamps and Hasura claims */\n decodedToken: DecodedToken;\n}\n\nexport const decodeUserSession = (accessToken: string): DecodedToken => {\n const s = accessToken.split('.');\n if (s.length !== 3 || !s[1]) {\n throw new Error('Invalid access token format');\n }\n\n const decodedToken = JSON.parse(\n typeof atob !== 'undefined'\n ? atob(s[1])\n : Buffer.from(s[1], 'base64').toString('utf-8'),\n ) as Record<string, unknown>;\n\n // Convert iat and exp to Date objects\n const iat =\n typeof decodedToken['iat'] === 'number'\n ? decodedToken['iat'] * 1000 // Convert seconds to milliseconds\n : undefined;\n const exp =\n typeof decodedToken['exp'] === 'number'\n ? decodedToken['exp'] * 1000 // Convert seconds to milliseconds\n : undefined;\n\n // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays\n const hasuraClaims = decodedToken['https://hasura.io/jwt/claims'] as\n | Record<string, unknown>\n | undefined;\n const processedClaims = hasuraClaims\n ? Object.entries(hasuraClaims).reduce(\n (acc, [key, value]) => {\n if (typeof value === 'string' && isPostgresArray(value)) {\n acc[key] = parsePostgresArray(value);\n } else {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : undefined;\n\n return {\n ...decodedToken,\n iat,\n exp,\n 'https://hasura.io/jwt/claims': processedClaims,\n };\n};\n\nconst isPostgresArray = (value: string): boolean => {\n return value.startsWith('{') && value.endsWith('}');\n};\n\nconst parsePostgresArray = (value: string): string[] => {\n if (!value || value === '{}') return [];\n // Remove curly braces and split by comma, handling quoted values\n return value\n .slice(1, -1)\n .split(',')\n .map((item) => item.trim().replace(/^\"(.*)\"$/, '$1'));\n};\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session } from './session';\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageBackend {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = 'nhostSession';\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageBackend {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param options - Configuration options\n * @param options.storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(options?: { storageKey?: string }) {\n this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageBackend {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for synchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageBackend {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: 'strict' | 'lax' | 'none';\n\n /**\n * Creates a new CookieStorage instance\n * @param options - Configuration options\n * @param options.cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param options.sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(options?: {\n cookieName?: string;\n expirationDays?: number;\n secure?: boolean;\n sameSite?: 'strict' | 'lax' | 'none';\n }) {\n this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;\n this.expirationDays = options?.expirationDays ?? 30;\n this.secure = options?.secure ?? true;\n this.sameSite = options?.sameSite || 'lax';\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split('=');\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || '')) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n }\n}\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session as AuthSession } from '../auth';\nimport { decodeUserSession, type Session } from './session';\nimport {\n LocalStorage,\n MemoryStorage,\n type SessionStorageBackend,\n} from './storageBackend';\n\n/**\n * Callback function type for session change subscriptions\n */\nexport type SessionChangeCallback = (session: Session | null) => void;\n\n/**\n * A wrapper around any SessionStorageInterface implementation that adds\n * the ability to subscribe to session changes.\n */\nexport class SessionStorage {\n private readonly storage: SessionStorageBackend;\n private subscribers = new Set<SessionChangeCallback>();\n\n /**\n * Creates a new SessionStorage instance\n * @param storage - The underlying storage implementation to use\n */\n constructor(storage: SessionStorageBackend) {\n this.storage = storage;\n }\n\n /**\n * Gets the session from the underlying storage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n return this.storage.get();\n }\n\n /**\n * Sets the session in the underlying storage and notifies subscribers\n * @param value - The session to store\n */\n set(value: AuthSession): void {\n const decodedToken = decodeUserSession(value.accessToken);\n const decodedSession = {\n ...value,\n decodedToken: decodedToken,\n };\n\n this.storage.set(decodedSession);\n this.notifySubscribers(decodedSession);\n }\n\n /**\n * Removes the session from the underlying storage and notifies subscribers\n */\n remove(): void {\n this.storage.remove();\n this.notifySubscribers(null);\n }\n\n /**\n * Subscribe to session changes\n * @param callback - Function that will be called when the session changes\n * @returns An unsubscribe function to remove this subscription\n */\n onChange(callback: SessionChangeCallback) {\n this.subscribers.add(callback);\n\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Notify all subscribers of a session change\n * @param session - The new session value or null if removed\n */\n private notifySubscribers(session: Session | null): void {\n for (const subscriber of this.subscribers) {\n try {\n subscriber(session);\n } catch (error) {\n console.error('Error notifying subscriber:', error);\n }\n }\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation as a SessionStorageBackend\n */\nexport const detectStorage = (): SessionStorageBackend => {\n if (typeof window !== 'undefined') {\n return new LocalStorage();\n }\n return new MemoryStorage();\n};\n"],"names":[],"mappings":";AAyBO,MAAM,oBAAoB,CAAC,gBAAsC;AACtE,QAAM,IAAI,YAAY,MAAM,GAAG;AAC/B,MAAI,EAAE,WAAW,KAAK,CAAC,EAAE,CAAC,GAAG;AAC3B,UAAM,IAAI,MAAM,6BAA6B;AAAA,EAC/C;AAEA,QAAM,eAAe,KAAK;AAAA,IACxB,OAAO,SAAS,cACZ,KAAK,EAAE,CAAC,CAAC,IACT,OAAO,KAAK,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,OAAO;AAAA,EAAA;AAIlD,QAAM,MACJ,OAAO,aAAa,KAAK,MAAM,WAC3B,aAAa,KAAK,IAAI,MACtB;AACN,QAAM,MACJ,OAAO,aAAa,KAAK,MAAM,WAC3B,aAAa,KAAK,IAAI,MACtB;AAGN,QAAM,eAAe,aAAa,8BAA8B;AAGhE,QAAM,kBAAkB,eACpB,OAAO,QAAQ,YAAY,EAAE;AAAA,I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