@nhost/nhost-js 3.3.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +67 -32
  2. package/dist/fetch-2PHmQBIJ.mjs +61 -0
  3. package/dist/fetch-2PHmQBIJ.mjs.map +1 -0
  4. package/dist/fetch-DWXwEnoe.js +2 -0
  5. package/dist/fetch-DWXwEnoe.js.map +1 -0
  6. package/dist/nhost-js/auth.cjs.js +2 -0
  7. package/dist/nhost-js/auth.cjs.js.map +1 -0
  8. package/dist/nhost-js/auth.es.js +917 -0
  9. package/dist/nhost-js/auth.es.js.map +1 -0
  10. package/dist/nhost-js/fetch.cjs.js +2 -0
  11. package/dist/nhost-js/fetch.cjs.js.map +1 -0
  12. package/dist/nhost-js/fetch.es.js +90 -0
  13. package/dist/nhost-js/fetch.es.js.map +1 -0
  14. package/dist/nhost-js/functions.cjs.js +2 -0
  15. package/dist/nhost-js/functions.cjs.js.map +1 -0
  16. package/dist/nhost-js/functions.es.js +45 -0
  17. package/dist/nhost-js/functions.es.js.map +1 -0
  18. package/dist/nhost-js/graphql.cjs.js +2 -0
  19. package/dist/nhost-js/graphql.cjs.js.map +1 -0
  20. package/dist/nhost-js/graphql.es.js +48 -0
  21. package/dist/nhost-js/graphql.es.js.map +1 -0
  22. package/dist/nhost-js/session.cjs.js +2 -0
  23. package/dist/nhost-js/session.cjs.js.map +1 -0
  24. package/dist/nhost-js/session.es.js +234 -0
  25. package/dist/nhost-js/session.es.js.map +1 -0
  26. package/dist/nhost-js/storage.cjs.js +2 -0
  27. package/dist/nhost-js/storage.cjs.js.map +1 -0
  28. package/dist/nhost-js/storage.es.js +324 -0
  29. package/dist/nhost-js/storage.es.js.map +1 -0
  30. package/dist/nhost-js.cjs.js +2 -0
  31. package/dist/nhost-js.cjs.js.map +1 -0
  32. package/dist/nhost-js.es.js +228 -0
  33. package/dist/nhost-js.es.js.map +1 -0
  34. package/dist/nhost-js.umd.js +2 -0
  35. package/dist/nhost-js.umd.js.map +1 -0
  36. package/dist/refreshSession-Bw715ZmX.js +2 -0
  37. package/dist/refreshSession-Bw715ZmX.js.map +1 -0
  38. package/dist/refreshSession-WwGlzgtM.mjs +95 -0
  39. package/dist/refreshSession-WwGlzgtM.mjs.map +1 -0
  40. package/dist/src/auth/client.d.ts +1763 -0
  41. package/dist/src/auth/client.d.ts.map +1 -0
  42. package/dist/src/auth/client.js +1043 -0
  43. package/dist/src/auth/client.js.map +1 -0
  44. package/dist/src/auth/index.d.ts +35 -0
  45. package/dist/src/auth/index.d.ts.map +1 -0
  46. package/dist/src/auth/index.js +35 -0
  47. package/dist/src/auth/index.js.map +1 -0
  48. package/dist/src/fetch/fetch.d.ts +88 -0
  49. package/dist/src/fetch/fetch.d.ts.map +1 -0
  50. package/dist/src/fetch/fetch.js +98 -0
  51. package/dist/src/fetch/fetch.js.map +1 -0
  52. package/dist/src/fetch/index.d.ts +38 -0
  53. package/dist/src/fetch/index.d.ts.map +1 -0
  54. package/dist/src/fetch/index.js +38 -0
  55. package/dist/src/fetch/index.js.map +1 -0
  56. package/dist/src/fetch/middlewareAttachAccessToken.d.ts +24 -0
  57. package/dist/src/fetch/middlewareAttachAccessToken.d.ts.map +1 -0
  58. package/dist/src/fetch/middlewareAttachAccessToken.js +54 -0
  59. package/dist/src/fetch/middlewareAttachAccessToken.js.map +1 -0
  60. package/dist/src/fetch/middlewareSessionRefresh.d.ts +30 -0
  61. package/dist/src/fetch/middlewareSessionRefresh.d.ts.map +1 -0
  62. package/dist/src/fetch/middlewareSessionRefresh.js +61 -0
  63. package/dist/src/fetch/middlewareSessionRefresh.js.map +1 -0
  64. package/dist/src/fetch/middlewareUpdateSessionFromResponse.d.ts +26 -0
  65. package/dist/src/fetch/middlewareUpdateSessionFromResponse.d.ts.map +1 -0
  66. package/dist/src/fetch/middlewareUpdateSessionFromResponse.js +79 -0
  67. package/dist/src/fetch/middlewareUpdateSessionFromResponse.js.map +1 -0
  68. package/dist/src/functions/client.d.ts +52 -0
  69. package/dist/src/functions/client.d.ts.map +1 -0
  70. package/dist/src/functions/client.js +89 -0
  71. package/dist/src/functions/client.js.map +1 -0
  72. package/dist/src/functions/index.d.ts +43 -0
  73. package/dist/src/functions/index.d.ts.map +1 -0
  74. package/dist/src/functions/index.js +43 -0
  75. package/dist/src/functions/index.js.map +1 -0
  76. package/dist/src/graphql/client.d.ts +93 -0
  77. package/dist/src/graphql/client.d.ts.map +1 -0
  78. package/dist/src/graphql/client.js +66 -0
  79. package/dist/src/graphql/client.js.map +1 -0
  80. package/dist/src/graphql/index.d.ts +65 -0
  81. package/dist/src/graphql/index.d.ts.map +1 -0
  82. package/dist/src/graphql/index.js +65 -0
  83. package/dist/src/graphql/index.js.map +1 -0
  84. package/dist/src/index.d.ts +35 -0
  85. package/dist/src/index.d.ts.map +1 -0
  86. package/dist/src/index.js +45 -0
  87. package/dist/src/index.js.map +1 -0
  88. package/dist/src/nhost.d.ts +301 -0
  89. package/dist/src/nhost.d.ts.map +1 -0
  90. package/dist/src/nhost.js +323 -0
  91. package/dist/src/nhost.js.map +1 -0
  92. package/dist/src/session/index.d.ts +20 -0
  93. package/dist/src/session/index.d.ts.map +1 -0
  94. package/dist/src/session/index.js +19 -0
  95. package/dist/src/session/index.js.map +1 -0
  96. package/dist/src/session/refreshSession.d.ts +17 -0
  97. package/dist/src/session/refreshSession.d.ts.map +1 -0
  98. package/dist/src/session/refreshSession.js +120 -0
  99. package/dist/src/session/refreshSession.js.map +1 -0
  100. package/dist/src/session/session.d.ts +24 -0
  101. package/dist/src/session/session.d.ts.map +1 -0
  102. package/dist/src/session/session.js +48 -0
  103. package/dist/src/session/session.js.map +1 -0
  104. package/dist/src/session/storage.d.ts +62 -0
  105. package/dist/src/session/storage.d.ts.map +1 -0
  106. package/dist/src/session/storage.js +91 -0
  107. package/dist/src/session/storage.js.map +1 -0
  108. package/dist/src/session/storageBackend.d.ts +122 -0
  109. package/dist/src/session/storageBackend.d.ts.map +1 -0
  110. package/dist/src/session/storageBackend.js +145 -0
  111. package/dist/src/session/storageBackend.js.map +1 -0
  112. package/dist/src/storage/client.d.ts +546 -0
  113. package/dist/src/storage/client.d.ts.map +1 -0
  114. package/dist/src/storage/client.js +368 -0
  115. package/dist/src/storage/client.js.map +1 -0
  116. package/dist/src/storage/index.d.ts +37 -0
  117. package/dist/src/storage/index.d.ts.map +1 -0
  118. package/dist/src/storage/index.js +37 -0
  119. package/dist/src/storage/index.js.map +1 -0
  120. package/dist/tsconfig.tsbuildinfo +1 -0
  121. package/package.json +103 -59
  122. package/dist/clients/auth.d.ts +0 -8
  123. package/dist/clients/auth.d.ts.map +0 -1
  124. package/dist/clients/functions/index.d.ts +0 -107
  125. package/dist/clients/functions/index.d.ts.map +0 -1
  126. package/dist/clients/functions/types.d.ts +0 -28
  127. package/dist/clients/functions/types.d.ts.map +0 -1
  128. package/dist/clients/graphql.d.ts +0 -8
  129. package/dist/clients/graphql.d.ts.map +0 -1
  130. package/dist/clients/index.d.ts +0 -6
  131. package/dist/clients/index.d.ts.map +0 -1
  132. package/dist/clients/nhost.d.ts +0 -83
  133. package/dist/clients/nhost.d.ts.map +0 -1
  134. package/dist/clients/storage.d.ts +0 -8
  135. package/dist/clients/storage.d.ts.map +0 -1
  136. package/dist/index.cjs.js +0 -2
  137. package/dist/index.cjs.js.map +0 -1
  138. package/dist/index.d.ts +0 -6
  139. package/dist/index.d.ts.map +0 -1
  140. package/dist/index.esm.js +0 -356
  141. package/dist/index.esm.js.map +0 -1
  142. package/dist/utils/helpers.d.ts +0 -20
  143. package/dist/utils/helpers.d.ts.map +0 -1
  144. package/dist/utils/types.d.ts +0 -57
  145. package/dist/utils/types.d.ts.map +0 -1
  146. package/umd/nhost-js.umd.js +0 -22
  147. package/umd/nhost-js.umd.js.map +0 -1
@@ -0,0 +1,48 @@
1
+ import { c as createEnhancedFetch, F as FetchError } from "../fetch-2PHmQBIJ.mjs";
2
+ const createAPIClient = (url, chainFunctions = []) => {
3
+ const enhancedFetch = createEnhancedFetch(chainFunctions);
4
+ const executeOperation = async (request2, options) => {
5
+ const response = await enhancedFetch(`${url}`, {
6
+ method: "POST",
7
+ headers: {
8
+ "Content-Type": "application/json"
9
+ },
10
+ body: JSON.stringify(request2),
11
+ ...options
12
+ });
13
+ const body = await response.text();
14
+ const data = body ? JSON.parse(body) : {};
15
+ const resp = {
16
+ body: data,
17
+ status: response.status,
18
+ headers: response.headers
19
+ };
20
+ if (data.errors) {
21
+ throw new FetchError(data, response.status, response.headers);
22
+ }
23
+ return resp;
24
+ };
25
+ function request(requestOrDocument, variablesOrOptions, options) {
26
+ if (typeof requestOrDocument === "object" && "kind" in requestOrDocument) {
27
+ const definition = requestOrDocument.definitions[0];
28
+ const request2 = {
29
+ query: requestOrDocument.loc?.source.body || "",
30
+ variables: variablesOrOptions,
31
+ operationName: definition && "name" in definition ? definition.name?.value : void 0
32
+ };
33
+ return executeOperation(request2, options);
34
+ } else {
35
+ const request2 = requestOrDocument;
36
+ const requestOptions = variablesOrOptions;
37
+ return executeOperation(request2, requestOptions);
38
+ }
39
+ }
40
+ return {
41
+ request,
42
+ url
43
+ };
44
+ };
45
+ export {
46
+ createAPIClient
47
+ };
48
+ //# sourceMappingURL=graphql.es.js.map
@@ -0,0 +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;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../refreshSession-Bw715ZmX.js"),t=e=>e.startsWith("{")&&e.endsWith("}"),s=e=>e&&"{}"!==e?e.slice(1,-1).split(",").map((e=>e.trim().replace(/^"(.*)"$/,"$1"))):[],o="nhostSession";class r{storageKey;constructor(e){this.storageKey=e?.storageKey||o}get(){try{const e=window.localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch{return this.remove(),null}}set(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e))}remove(){window.localStorage.removeItem(this.storageKey)}}class i{session=null;get(){return this.session}set(e){this.session=e}remove(){this.session=null}}exports.refreshSession=e.refreshSession,exports.CookieStorage=class{cookieName;expirationDays;secure;sameSite;constructor(e){this.cookieName=e?.cookieName||o,this.expirationDays=e?.expirationDays??30,this.secure=e?.secure??!0,this.sameSite=e?.sameSite||"lax"}get(){const e=document.cookie.split(";");for(const t of e){const[e,s]=t.trim().split("=");if(e===this.cookieName)try{return JSON.parse(decodeURIComponent(s||""))}catch{return this.remove(),null}}return null}set(e){const t=new Date;t.setTime(t.getTime()+24*this.expirationDays*60*60*1e3);const s=encodeURIComponent(JSON.stringify(e)),o=`${this.cookieName}=${s}; expires=${t.toUTCString()}; path=/; ${this.secure?"secure; ":""}SameSite=${this.sameSite}`;document.cookie=o}remove(){document.cookie=`${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure?"secure; ":""}SameSite=${this.sameSite}`}},exports.DEFAULT_SESSION_KEY=o,exports.LocalStorage=r,exports.MemoryStorage=i,exports.SessionStorage=class{storage;subscribers=new Set;constructor(e){this.storage=e}get(){return this.storage.get()}set(e){const o=(e=>{const o=e.split(".");if(3!==o.length||!o[1])throw new Error("Invalid access token format");const r=JSON.parse("undefined"!=typeof atob?atob(o[1]):Buffer.from(o[1],"base64").toString("utf-8")),i="number"==typeof r.iat?1e3*r.iat:void 0,n="number"==typeof r.exp?1e3*r.exp:void 0,a=r["https://hasura.io/jwt/claims"],c=a?Object.entries(a).reduce(((e,[o,r])=>("string"==typeof r&&t(r)?e[o]=s(r):e[o]=r,e)),{}):void 0;return{...r,iat:i,exp:n,"https://hasura.io/jwt/claims":c}})(e.accessToken),r={...e,decodedToken:o};this.storage.set(r),this.notifySubscribers(r)}remove(){this.storage.remove(),this.notifySubscribers(null)}onChange(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(e){for(const s of this.subscribers)try{s(e)}catch(t){console.error("Error notifying subscriber:",t)}}},exports.detectStorage=()=>"undefined"!=typeof window?new r:new i;
2
+ //# sourceMappingURL=session.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.cjs.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":["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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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"}
@@ -0,0 +1,234 @@
1
+ import { r } from "../refreshSession-WwGlzgtM.mjs";
2
+ const decodeUserSession = (accessToken) => {
3
+ const s = accessToken.split(".");
4
+ if (s.length !== 3 || !s[1]) {
5
+ throw new Error("Invalid access token format");
6
+ }
7
+ const decodedToken = JSON.parse(
8
+ typeof atob !== "undefined" ? atob(s[1]) : Buffer.from(s[1], "base64").toString("utf-8")
9
+ );
10
+ const iat = typeof decodedToken["iat"] === "number" ? decodedToken["iat"] * 1e3 : void 0;
11
+ const exp = typeof decodedToken["exp"] === "number" ? decodedToken["exp"] * 1e3 : void 0;
12
+ const hasuraClaims = decodedToken["https://hasura.io/jwt/claims"];
13
+ const processedClaims = hasuraClaims ? Object.entries(hasuraClaims).reduce(
14
+ (acc, [key, value]) => {
15
+ if (typeof value === "string" && isPostgresArray(value)) {
16
+ acc[key] = parsePostgresArray(value);
17
+ } else {
18
+ acc[key] = value;
19
+ }
20
+ return acc;
21
+ },
22
+ {}
23
+ ) : void 0;
24
+ return {
25
+ ...decodedToken,
26
+ iat,
27
+ exp,
28
+ "https://hasura.io/jwt/claims": processedClaims
29
+ };
30
+ };
31
+ const isPostgresArray = (value) => {
32
+ return value.startsWith("{") && value.endsWith("}");
33
+ };
34
+ const parsePostgresArray = (value) => {
35
+ if (!value || value === "{}") return [];
36
+ return value.slice(1, -1).split(",").map((item) => item.trim().replace(/^"(.*)"$/, "$1"));
37
+ };
38
+ const DEFAULT_SESSION_KEY = "nhostSession";
39
+ class LocalStorage {
40
+ storageKey;
41
+ /**
42
+ * Creates a new LocalStorage instance
43
+ * @param options - Configuration options
44
+ * @param options.storageKey - The key to use in localStorage (defaults to "nhostSession")
45
+ */
46
+ constructor(options) {
47
+ this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;
48
+ }
49
+ /**
50
+ * Gets the session from localStorage
51
+ * @returns The stored session or null if not found
52
+ */
53
+ get() {
54
+ try {
55
+ const value = window.localStorage.getItem(this.storageKey);
56
+ return value ? JSON.parse(value) : null;
57
+ } catch {
58
+ this.remove();
59
+ return null;
60
+ }
61
+ }
62
+ /**
63
+ * Sets the session in localStorage
64
+ * @param value - The session to store
65
+ */
66
+ set(value) {
67
+ window.localStorage.setItem(this.storageKey, JSON.stringify(value));
68
+ }
69
+ /**
70
+ * Removes the session from localStorage
71
+ */
72
+ remove() {
73
+ window.localStorage.removeItem(this.storageKey);
74
+ }
75
+ }
76
+ class MemoryStorage {
77
+ session = null;
78
+ /**
79
+ * Gets the session from memory
80
+ * @returns The stored session or null if not set
81
+ */
82
+ get() {
83
+ return this.session;
84
+ }
85
+ /**
86
+ * Sets the session in memory
87
+ * @param value - The session to store
88
+ */
89
+ set(value) {
90
+ this.session = value;
91
+ }
92
+ /**
93
+ * Clears the session from memory
94
+ */
95
+ remove() {
96
+ this.session = null;
97
+ }
98
+ }
99
+ class CookieStorage {
100
+ cookieName;
101
+ expirationDays;
102
+ secure;
103
+ sameSite;
104
+ /**
105
+ * Creates a new CookieStorage instance
106
+ * @param options - Configuration options
107
+ * @param options.cookieName - Name of the cookie to use (defaults to "nhostSession")
108
+ * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)
109
+ * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)
110
+ * @param options.sameSite - SameSite policy for the cookie (defaults to "lax")
111
+ */
112
+ constructor(options) {
113
+ this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;
114
+ this.expirationDays = options?.expirationDays ?? 30;
115
+ this.secure = options?.secure ?? true;
116
+ this.sameSite = options?.sameSite || "lax";
117
+ }
118
+ /**
119
+ * Gets the session from cookies
120
+ * @returns The stored session or null if not found
121
+ */
122
+ get() {
123
+ const cookies = document.cookie.split(";");
124
+ for (const cookie of cookies) {
125
+ const [name, value] = cookie.trim().split("=");
126
+ if (name === this.cookieName) {
127
+ try {
128
+ return JSON.parse(decodeURIComponent(value || ""));
129
+ } catch {
130
+ this.remove();
131
+ return null;
132
+ }
133
+ }
134
+ }
135
+ return null;
136
+ }
137
+ /**
138
+ * Sets the session in a cookie
139
+ * @param value - The session to store
140
+ */
141
+ set(value) {
142
+ const expires = /* @__PURE__ */ new Date();
143
+ expires.setTime(
144
+ expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1e3
145
+ );
146
+ const cookieValue = encodeURIComponent(JSON.stringify(value));
147
+ const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? "secure; " : ""}SameSite=${this.sameSite}`;
148
+ document.cookie = cookieString;
149
+ }
150
+ /**
151
+ * Removes the session cookie
152
+ */
153
+ remove() {
154
+ document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? "secure; " : ""}SameSite=${this.sameSite}`;
155
+ }
156
+ }
157
+ class SessionStorage {
158
+ storage;
159
+ subscribers = /* @__PURE__ */ new Set();
160
+ /**
161
+ * Creates a new SessionStorage instance
162
+ * @param storage - The underlying storage implementation to use
163
+ */
164
+ constructor(storage) {
165
+ this.storage = storage;
166
+ }
167
+ /**
168
+ * Gets the session from the underlying storage
169
+ * @returns The stored session or null if not found
170
+ */
171
+ get() {
172
+ return this.storage.get();
173
+ }
174
+ /**
175
+ * Sets the session in the underlying storage and notifies subscribers
176
+ * @param value - The session to store
177
+ */
178
+ set(value) {
179
+ const decodedToken = decodeUserSession(value.accessToken);
180
+ const decodedSession = {
181
+ ...value,
182
+ decodedToken
183
+ };
184
+ this.storage.set(decodedSession);
185
+ this.notifySubscribers(decodedSession);
186
+ }
187
+ /**
188
+ * Removes the session from the underlying storage and notifies subscribers
189
+ */
190
+ remove() {
191
+ this.storage.remove();
192
+ this.notifySubscribers(null);
193
+ }
194
+ /**
195
+ * Subscribe to session changes
196
+ * @param callback - Function that will be called when the session changes
197
+ * @returns An unsubscribe function to remove this subscription
198
+ */
199
+ onChange(callback) {
200
+ this.subscribers.add(callback);
201
+ return () => {
202
+ this.subscribers.delete(callback);
203
+ };
204
+ }
205
+ /**
206
+ * Notify all subscribers of a session change
207
+ * @param session - The new session value or null if removed
208
+ */
209
+ notifySubscribers(session) {
210
+ for (const subscriber of this.subscribers) {
211
+ try {
212
+ subscriber(session);
213
+ } catch (error) {
214
+ console.error("Error notifying subscriber:", error);
215
+ }
216
+ }
217
+ }
218
+ }
219
+ const detectStorage = () => {
220
+ if (typeof window !== "undefined") {
221
+ return new LocalStorage();
222
+ }
223
+ return new MemoryStorage();
224
+ };
225
+ export {
226
+ CookieStorage,
227
+ DEFAULT_SESSION_KEY,
228
+ LocalStorage,
229
+ MemoryStorage,
230
+ SessionStorage,
231
+ detectStorage,
232
+ r as refreshSession
233
+ };
234
+ //# sourceMappingURL=session.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.es.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,IAC3B,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,UAAI,OAAO,UAAU,YAAY,gBAAgB,KAAK,GAAG;AACvD,YAAI,GAAG,IAAI,mBAAmB,KAAK;AAAA,MACrC,OAAO;AACL,YAAI,GAAG,IAAI;AAAA,MACb;AACA,aAAO;AAAA,IACT;AAAA,IACA,CAAA;AAAA,EAAC,IAEH;AAEJ,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA,gCAAgC;AAAA,EAAA;AAEpC;AAEA,MAAM,kBAAkB,CAAC,UAA2B;AAClD,SAAO,MAAM,WAAW,GAAG,KAAK,MAAM,SAAS,GAAG;AACpD;AAEA,MAAM,qBAAqB,CAAC,UAA4B;AACtD,MAAI,CAAC,SAAS,UAAU,aAAa,CAAA;AAErC,SAAO,MACJ,MAAM,GAAG,EAAE,EACX,MAAM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AK,QAAQ,IAAI,cAAc;AAC/B,SAAK,kBAAkB,cAAc;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,SAAe;AACb,SAAK,QAAQ,OAAA;AACb,SAAK,kBAAkB,IAAI;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,SAAS,UAAiC;AACxC,SAAK,YAAY,IAAI,QAAQ;AAE7B,WAAO,MAAM;AACX,WAAK,YAAY,OAAO,QAAQ;AAAA,IAClC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,kBAAkB,SAA+B;AACvD,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;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../fetch-DWXwEnoe.js");exports.createAPIClient=(e,s=[])=>{let a=t.createEnhancedFetch(s);return{baseURL:e,pushChainFunction:e=>{s.push(e),a=t.createEnhancedFetch(s)},uploadFiles:async(s,r)=>{const n=`${e}/files`,d=new FormData;void 0!==s["bucket-id"]&&d.append("bucket-id",s["bucket-id"]),void 0!==s["metadata[]"]&&s["metadata[]"].forEach((t=>{d.append("metadata[]",new Blob([JSON.stringify(t)],{type:"application/json"}),"")})),void 0!==s["file[]"]&&s["file[]"].forEach((t=>{d.append("file[]",t)}));const o=await a(n,{...r,method:"POST",body:d});if(o.status>=300){const e=[412].includes(o.status)?null:await o.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,o.status,o.headers)}const u=[204,205,304].includes(o.status)?null:await o.text();return{body:u?JSON.parse(u):{},status:o.status,headers:o.headers}},deleteFile:async(s,r)=>{const n=`${e}/files/${s}`,d=await a(n,{...r,method:"DELETE",headers:{...r?.headers}});if(d.status>=300){const e=[412].includes(d.status)?null:await d.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,d.status,d.headers)}return{body:void 0,status:d.status,headers:d.headers}},getFile:async(s,r,n)=>{const d=r&&Object.entries(r).map((([t,e])=>{const s=Array.isArray(e)?e.join(","):"object"==typeof e?JSON.stringify(e):e;return`${t}=${encodeURIComponent(s)}`})).join("&"),o=d?`${e}/files/${s}?${d}`:`${e}/files/${s}`,u=await a(o,{...n,method:"GET",headers:{...n?.headers}});if(u.status>=300){const e=[412].includes(u.status)?null:await u.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,u.status,u.headers)}return{body:await u.blob(),status:u.status,headers:u.headers}},getFileMetadataHeaders:async(s,r,n)=>{const d=r&&Object.entries(r).map((([t,e])=>{const s=Array.isArray(e)?e.join(","):"object"==typeof e?JSON.stringify(e):e;return`${t}=${encodeURIComponent(s)}`})).join("&"),o=d?`${e}/files/${s}?${d}`:`${e}/files/${s}`,u=await a(o,{...n,method:"HEAD",headers:{...n?.headers}});if(u.status>=300){const e=[412].includes(u.status)?null:await u.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,u.status,u.headers)}return{body:void 0,status:u.status,headers:u.headers}},replaceFile:async(s,r,n)=>{const d=`${e}/files/${s}`,o=new FormData;void 0!==r.metadata&&o.append("metadata",new Blob([JSON.stringify(r.metadata)],{type:"application/json"}),""),void 0!==r.file&&o.append("file",r.file);const u=await a(d,{...n,method:"PUT",body:o});if(u.status>=300){const e=[412].includes(u.status)?null:await u.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,u.status,u.headers)}const i=[204,205,304].includes(u.status)?null:await u.text();return{body:i?JSON.parse(i):{},status:u.status,headers:u.headers}},getFilePresignedURL:async(s,r)=>{const n=`${e}/files/${s}/presignedurl`,d=await a(n,{...r,method:"GET",headers:{...r?.headers}});if(d.status>=300){const e=[412].includes(d.status)?null:await d.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,d.status,d.headers)}const o=[204,205,304].includes(d.status)?null:await d.text();return{body:o?JSON.parse(o):{},status:d.status,headers:d.headers}},deleteBrokenMetadata:async s=>{const r=`${e}/ops/delete-broken-metadata`,n=await a(r,{...s,method:"POST",headers:{...s?.headers}});if(n.status>=300){const e=[412].includes(n.status)?null:await n.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,n.status,n.headers)}const d=[204,205,304].includes(n.status)?null:await n.text();return{body:d?JSON.parse(d):{},status:n.status,headers:n.headers}},deleteOrphanedFiles:async s=>{const r=`${e}/ops/delete-orphans`,n=await a(r,{...s,method:"POST",headers:{...s?.headers}});if(n.status>=300){const e=[412].includes(n.status)?null:await n.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,n.status,n.headers)}const d=[204,205,304].includes(n.status)?null:await n.text();return{body:d?JSON.parse(d):{},status:n.status,headers:n.headers}},listBrokenMetadata:async s=>{const r=`${e}/ops/list-broken-metadata`,n=await a(r,{...s,method:"POST",headers:{...s?.headers}});if(n.status>=300){const e=[412].includes(n.status)?null:await n.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,n.status,n.headers)}const d=[204,205,304].includes(n.status)?null:await n.text();return{body:d?JSON.parse(d):{},status:n.status,headers:n.headers}},listFilesNotUploaded:async s=>{const r=`${e}/ops/list-not-uploaded`,n=await a(r,{...s,method:"POST",headers:{...s?.headers}});if(n.status>=300){const e=[412].includes(n.status)?null:await n.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,n.status,n.headers)}const d=[204,205,304].includes(n.status)?null:await n.text();return{body:d?JSON.parse(d):{},status:n.status,headers:n.headers}},listOrphanedFiles:async s=>{const r=`${e}/ops/list-orphans`,n=await a(r,{...s,method:"POST",headers:{...s?.headers}});if(n.status>=300){const e=[412].includes(n.status)?null:await n.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,n.status,n.headers)}const d=[204,205,304].includes(n.status)?null:await n.text();return{body:d?JSON.parse(d):{},status:n.status,headers:n.headers}},getVersion:async s=>{const r=`${e}/version`,n=await a(r,{...s,method:"GET",headers:{...s?.headers}});if(n.status>=300){const e=[412].includes(n.status)?null:await n.text(),s=e?JSON.parse(e):{};throw new t.FetchError(s,n.status,n.headers)}const d=[204,205,304].includes(n.status)?null:await n.text();return{body:d?JSON.parse(d):{},status:n.status,headers:n.headers}}}};
2
+ //# sourceMappingURL=storage.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.cjs.js","sources":["../../src/storage/client.ts"],"sourcesContent":["/**\n * This file is auto-generated. Do not edit manually.\n */\n\nimport type { ChainFunction, FetchResponse } from \"../fetch\";\nimport { createEnhancedFetch, FetchError } from \"../fetch\";\n\n/**\n * Date in RFC 2822 format\n */\nexport type RFC2822Date = string;\n\n/**\n * Error details.\n @property message (`string`) - Human-readable error message.\n * Example - `\"File not found\"`\n @property data? (`Record<string, unknown>`) - Additional data related to the error, if any.*/\nexport interface ErrorResponseError {\n /**\n * Human-readable error message.\n * Example - `\"File not found\"`\n */\n message: string;\n /**\n * Additional data related to the error, if any.\n */\n data?: Record<string, unknown>;\n}\n\n/**\n * Error information returned by the API.\n @property error? (`ErrorResponseError`) - Error details.*/\nexport interface ErrorResponse {\n /**\n * Error details.\n */\n error?: ErrorResponseError;\n}\n\n/**\n * Error details.\n @property message (`string`) - Human-readable error message.\n * Example - `\"File not found\"`\n @property data? (`Record<string, unknown>`) - Additional data related to the error, if any.*/\nexport interface ErrorResponseWithProcessedFilesError {\n /**\n * Human-readable error message.\n * Example - `\"File not found\"`\n */\n message: string;\n /**\n * Additional data related to the error, if any.\n */\n data?: Record<string, unknown>;\n}\n\n/**\n * Error information returned by the API.\n @property processedFiles? (`FileMetadata[]`) - List of files that were successfully processed before the error occurred.\n @property error? (`ErrorResponseWithProcessedFilesError`) - Error details.*/\nexport interface ErrorResponseWithProcessedFiles {\n /**\n * List of files that were successfully processed before the error occurred.\n */\n processedFiles?: FileMetadata[];\n /**\n * Error details.\n */\n error?: ErrorResponseWithProcessedFilesError;\n}\n\n/**\n * Comprehensive metadata information about a file in storage.\n @property id (`string`) - Unique identifier for the file.\n * Example - `\"d5e76ceb-77a2-4153-b7da-1f7c115b2ff2\"`\n @property name (`string`) - Name of the file including extension.\n * Example - `\"profile-picture.jpg\"`\n @property size (`number`) - Size of the file in bytes.\n * Example - `245678`\n * Format - int64\n @property bucketId (`string`) - ID of the bucket containing the file.\n * Example - `\"users-bucket\"`\n @property etag (`string`) - Entity tag for cache validation.\n * Example - `\"\\\"a1b2c3d4e5f6\\\"\"`\n @property createdAt (`string`) - Timestamp when the file was created.\n * Example - `\"2023-01-15T12:34:56Z\"`\n * Format - date-time\n @property updatedAt (`string`) - Timestamp when the file was last updated.\n * Example - `\"2023-01-16T09:45:32Z\"`\n * Format - date-time\n @property isUploaded (`boolean`) - Whether the file has been successfully uploaded.\n * Example - `true`\n @property mimeType (`string`) - MIME type of the file.\n * Example - `\"image/jpeg\"`\n @property uploadedByUserId? (`string`) - ID of the user who uploaded the file.\n * Example - `\"abc123def456\"`\n @property metadata? (`Record<string, unknown>`) - Custom metadata associated with the file.\n * Example - `{\"alt\":\"Profile picture\",\"category\":\"avatar\"}`*/\nexport interface FileMetadata {\n /**\n * Unique identifier for the file.\n * Example - `\"d5e76ceb-77a2-4153-b7da-1f7c115b2ff2\"`\n */\n id: string;\n /**\n * Name of the file including extension.\n * Example - `\"profile-picture.jpg\"`\n */\n name: string;\n /**\n * Size of the file in bytes.\n * Example - `245678`\n * Format - int64\n */\n size: number;\n /**\n * ID of the bucket containing the file.\n * Example - `\"users-bucket\"`\n */\n bucketId: string;\n /**\n * Entity tag for cache validation.\n * Example - `\"\\\"a1b2c3d4e5f6\\\"\"`\n */\n etag: string;\n /**\n * Timestamp when the file was created.\n * Example - `\"2023-01-15T12:34:56Z\"`\n * Format - date-time\n */\n createdAt: string;\n /**\n * Timestamp when the file was last updated.\n * Example - `\"2023-01-16T09:45:32Z\"`\n * Format - date-time\n */\n updatedAt: string;\n /**\n * Whether the file has been successfully uploaded.\n * Example - `true`\n */\n isUploaded: boolean;\n /**\n * MIME type of the file.\n * Example - `\"image/jpeg\"`\n */\n mimeType: string;\n /**\n * ID of the user who uploaded the file.\n * Example - `\"abc123def456\"`\n */\n uploadedByUserId?: string;\n /**\n * Custom metadata associated with the file.\n * Example - `{\"alt\":\"Profile picture\",\"category\":\"avatar\"}`\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Basic information about a file in storage.\n @property id (`string`) - Unique identifier for the file.\n * Example - `\"d5e76ceb-77a2-4153-b7da-1f7c115b2ff2\"`\n @property name (`string`) - Name of the file including extension.\n * Example - `\"profile-picture.jpg\"`\n @property bucketId (`string`) - ID of the bucket containing the file.\n * Example - `\"users-bucket\"`\n @property isUploaded (`boolean`) - Whether the file has been successfully uploaded.\n * Example - `true`*/\nexport interface FileSummary {\n /**\n * Unique identifier for the file.\n * Example - `\"d5e76ceb-77a2-4153-b7da-1f7c115b2ff2\"`\n */\n id: string;\n /**\n * Name of the file including extension.\n * Example - `\"profile-picture.jpg\"`\n */\n name: string;\n /**\n * ID of the bucket containing the file.\n * Example - `\"users-bucket\"`\n */\n bucketId: string;\n /**\n * Whether the file has been successfully uploaded.\n * Example - `true`\n */\n isUploaded: boolean;\n}\n\n/**\n * Contains a presigned URL for direct file operations.\n @property url (`string`) - The presigned URL for file operations.\n * Example - `\"https://storage.example.com/files/abc123?signature=xyz\"`\n @property expiration (`number`) - The time in seconds until the URL expires.\n * Example - `3600`*/\nexport interface PresignedURLResponse {\n /**\n * The presigned URL for file operations.\n * Example - `\"https://storage.example.com/files/abc123?signature=xyz\"`\n */\n url: string;\n /**\n * The time in seconds until the URL expires.\n * Example - `3600`\n */\n expiration: number;\n}\n\n/**\n * Metadata that can be updated for an existing file.\n @property name? (`string`) - New name to assign to the file.\n * Example - `\"renamed-file.jpg\"`\n @property metadata? (`Record<string, unknown>`) - Updated custom metadata to associate with the file.\n * Example - `{\"alt\":\"Updated image description\",\"category\":\"profile\"}`*/\nexport interface UpdateFileMetadata {\n /**\n * New name to assign to the file.\n * Example - `\"renamed-file.jpg\"`\n */\n name?: string;\n /**\n * Updated custom metadata to associate with the file.\n * Example - `{\"alt\":\"Updated image description\",\"category\":\"profile\"}`\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Metadata provided when uploading a new file.\n @property id? (`string`) - Optional custom ID for the file. If not provided, a UUID will be generated.\n * Example - `\"custom-id-123\"`\n @property name? (`string`) - Name to assign to the file. If not provided, the original filename will be used.\n * Example - `\"custom-filename.png\"`\n @property metadata? (`Record<string, unknown>`) - Custom metadata to associate with the file.\n * Example - `{\"alt\":\"Custom image\",\"category\":\"document\"}`*/\nexport interface UploadFileMetadata {\n /**\n * Optional custom ID for the file. If not provided, a UUID will be generated.\n * Example - `\"custom-id-123\"`\n */\n id?: string;\n /**\n * Name to assign to the file. If not provided, the original filename will be used.\n * Example - `\"custom-filename.png\"`\n */\n name?: string;\n /**\n * Custom metadata to associate with the file.\n * Example - `{\"alt\":\"Custom image\",\"category\":\"document\"}`\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Contains version information about the storage service.\n @property buildVersion (`string`) - The version number of the storage service build.\n * Example - `\"1.2.3\"`*/\nexport interface VersionInformation {\n /**\n * The version number of the storage service build.\n * Example - `\"1.2.3\"`\n */\n buildVersion: string;\n}\n\n/**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\nexport type OutputImageFormat =\n | \"auto\"\n | \"same\"\n | \"jpeg\"\n | \"webp\"\n | \"png\"\n | \"avif\";\n\n/**\n * \n @property bucket-id? (`string`) - Target bucket identifier where files will be stored.\n * Example - `\"user-uploads\"`\n @property metadata[]? (`UploadFileMetadata[]`) - Optional custom metadata for each uploaded file. Must match the order of the file[] array.\n @property file[] (`Blob[]`) - Array of files to upload.*/\nexport interface UploadFilesBody {\n /**\n * Target bucket identifier where files will be stored.\n * Example - `\"user-uploads\"`\n */\n \"bucket-id\"?: string;\n /**\n * Optional custom metadata for each uploaded file. Must match the order of the file[] array.\n */\n \"metadata[]\"?: UploadFileMetadata[];\n /**\n * Array of files to upload.\n */\n \"file[]\": Blob[];\n}\n\n/**\n * \n @property processedFiles (`FileMetadata[]`) - List of successfully processed files with their metadata.*/\nexport interface UploadFilesResponse201 {\n /**\n * List of successfully processed files with their metadata.\n */\n processedFiles: FileMetadata[];\n}\n\n/**\n * \n @property metadata? (`UpdateFileMetadata`) - Metadata that can be updated for an existing file.\n @property file? (`Blob`) - New file content to replace the existing file\n * Format - binary*/\nexport interface ReplaceFileBody {\n /**\n * Metadata that can be updated for an existing file.\n */\n metadata?: UpdateFileMetadata;\n /**\n * New file content to replace the existing file\n * Format - binary\n */\n file?: Blob;\n}\n\n/**\n * \n @property metadata? (`FileSummary[]`) - */\nexport interface DeleteBrokenMetadataResponse200 {\n /**\n *\n */\n metadata?: FileSummary[];\n}\n\n/**\n * \n @property files? (`string[]`) - */\nexport interface DeleteOrphanedFilesResponse200 {\n /**\n *\n */\n files?: string[];\n}\n\n/**\n * \n @property metadata? (`FileSummary[]`) - */\nexport interface ListBrokenMetadataResponse200 {\n /**\n *\n */\n metadata?: FileSummary[];\n}\n\n/**\n * \n @property metadata? (`FileSummary[]`) - */\nexport interface ListFilesNotUploadedResponse200 {\n /**\n *\n */\n metadata?: FileSummary[];\n}\n\n/**\n * \n @property files? (`string[]`) - */\nexport interface ListOrphanedFilesResponse200 {\n /**\n *\n */\n files?: string[];\n}\n\n/**\n * Parameters for the getFile method.\n @property q? (number) - Image quality (1-100). Only applies to JPEG, WebP and PNG files\n \n @property h? (number) - Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n \n @property w? (number) - Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n \n @property b? (number) - Blur the image using this sigma value. Only applies to image files\n \n @property f? (OutputImageFormat) - Output format for image files. Use 'auto' for content negotiation based on Accept header\n \n * Output format for image files. Use 'auto' for content negotiation based on Accept header*/\nexport interface GetFileParams {\n /**\n * Image quality (1-100). Only applies to JPEG, WebP and PNG files\n \n */\n q?: number;\n /**\n * Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n \n */\n h?: number;\n /**\n * Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n \n */\n w?: number;\n /**\n * Blur the image using this sigma value. Only applies to image files\n \n */\n b?: number;\n /**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n \n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\n f?: OutputImageFormat;\n}\n/**\n * Parameters for the getFileMetadataHeaders method.\n @property q? (number) - Image quality (1-100). Only applies to JPEG, WebP and PNG files\n \n @property h? (number) - Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n \n @property w? (number) - Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n \n @property b? (number) - Blur the image using this sigma value. Only applies to image files\n \n @property f? (OutputImageFormat) - Output format for image files. Use 'auto' for content negotiation based on Accept header\n \n * Output format for image files. Use 'auto' for content negotiation based on Accept header*/\nexport interface GetFileMetadataHeadersParams {\n /**\n * Image quality (1-100). Only applies to JPEG, WebP and PNG files\n \n */\n q?: number;\n /**\n * Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n \n */\n h?: number;\n /**\n * Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n \n */\n w?: number;\n /**\n * Blur the image using this sigma value. Only applies to image files\n \n */\n b?: number;\n /**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n \n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\n f?: OutputImageFormat;\n}\n\nexport interface Client {\n baseURL: string;\n pushChainFunction(chainFunction: ChainFunction): void;\n /**\n Summary: Upload files\n Upload one or more files to a specified bucket. Supports batch uploading with optional custom metadata for each file. If uploading multiple files, either provide metadata for all files or none.\n\n This method may return different T based on the response code:\n - 201: UploadFilesResponse201\n */\n uploadFiles(\n body: UploadFilesBody,\n options?: RequestInit,\n ): Promise<FetchResponse<UploadFilesResponse201>>;\n\n /**\n Summary: Delete file\n Permanently delete a file from storage. This removes both the file content and its associated metadata.\n\n This method may return different T based on the response code:\n - 204: void\n */\n deleteFile(id: string, options?: RequestInit): Promise<FetchResponse<void>>;\n\n /**\n Summary: Download file\n Retrieve and download the complete file content. Supports conditional requests, image transformations, and range requests for partial downloads.\n\n This method may return different T based on the response code:\n - 200: void\n - 206: void\n - 304: void\n - 412: void\n */\n getFile(\n id: string,\n params?: GetFileParams,\n options?: RequestInit,\n ): Promise<FetchResponse<Blob>>;\n\n /**\n Summary: Check file information\n Retrieve file metadata headers without downloading the file content. Supports conditional requests and provides caching information.\n\n This method may return different T based on the response code:\n - 200: void\n - 304: void\n - 412: void\n */\n getFileMetadataHeaders(\n id: string,\n params?: GetFileMetadataHeadersParams,\n options?: RequestInit,\n ): Promise<FetchResponse<void>>;\n\n /**\n Summary: Replace file\n Replace an existing file with new content while preserving the file ID. The operation follows these steps:\n1. The isUploaded flag is set to false to mark the file as being updated\n2. The file content is replaced in the storage backend\n3. File metadata is updated (size, mime-type, isUploaded, etc.)\n\nEach step is atomic, but if a step fails, previous steps will not be automatically rolled back.\n\n\n This method may return different T based on the response code:\n - 200: FileMetadata\n */\n replaceFile(\n id: string,\n body: ReplaceFileBody,\n options?: RequestInit,\n ): Promise<FetchResponse<FileMetadata>>;\n\n /**\n Summary: Retrieve presigned URL to retrieve the file\n Retrieve presigned URL to retrieve the file. Expiration of the URL is\ndetermined by bucket configuration\n\n\n This method may return different T based on the response code:\n - 200: PresignedURLResponse\n */\n getFilePresignedURL(\n id: string,\n options?: RequestInit,\n ): Promise<FetchResponse<PresignedURLResponse>>;\n\n /**\n Summary: Delete broken metadata\n Broken metadata is defined as metadata that has isUploaded = true but there is no file in the storage matching it. This is an admin operation that requires the Hasura admin secret.\n\n This method may return different T based on the response code:\n - 200: DeleteBrokenMetadataResponse200\n */\n deleteBrokenMetadata(\n options?: RequestInit,\n ): Promise<FetchResponse<DeleteBrokenMetadataResponse200>>;\n\n /**\n Summary: Deletes orphaned files\n Orphaned files are files that are present in the storage but have no associated metadata. This is an admin operation that requires the Hasura admin secret.\n\n This method may return different T based on the response code:\n - 200: DeleteOrphanedFilesResponse200\n */\n deleteOrphanedFiles(\n options?: RequestInit,\n ): Promise<FetchResponse<DeleteOrphanedFilesResponse200>>;\n\n /**\n Summary: Lists broken metadata\n Broken metadata is defined as metadata that has isUploaded = true but there is no file in the storage matching it. This is an admin operation that requires the Hasura admin secret.\n\n This method may return different T based on the response code:\n - 200: ListBrokenMetadataResponse200\n */\n listBrokenMetadata(\n options?: RequestInit,\n ): Promise<FetchResponse<ListBrokenMetadataResponse200>>;\n\n /**\n Summary: Lists files that haven't been uploaded\n That is, metadata that has isUploaded = false. This is an admin operation that requires the Hasura admin secret.\n\n This method may return different T based on the response code:\n - 200: ListFilesNotUploadedResponse200\n */\n listFilesNotUploaded(\n options?: RequestInit,\n ): Promise<FetchResponse<ListFilesNotUploadedResponse200>>;\n\n /**\n Summary: Lists orphaned files\n Orphaned files are files that are present in the storage but have no associated metadata. This is an admin operation that requires the Hasura admin secret.\n\n This method may return different T based on the response code:\n - 200: ListOrphanedFilesResponse200\n */\n listOrphanedFiles(\n options?: RequestInit,\n ): Promise<FetchResponse<ListOrphanedFilesResponse200>>;\n\n /**\n Summary: Get service version information\n Retrieves build and version information about the storage service. Useful for monitoring and debugging.\n\n This method may return different T based on the response code:\n - 200: VersionInformation\n */\n getVersion(options?: RequestInit): Promise<FetchResponse<VersionInformation>>;\n}\n\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let fetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n fetch = createEnhancedFetch(chainFunctions);\n };\n const uploadFiles = async (\n body: UploadFilesBody,\n options?: RequestInit,\n ): Promise<FetchResponse<UploadFilesResponse201>> => {\n const url = `${baseURL}/files`;\n const formData = new FormData();\n if (body[\"bucket-id\"] !== undefined) {\n formData.append(\"bucket-id\", body[\"bucket-id\"]);\n }\n if (body[\"metadata[]\"] !== undefined) {\n body[\"metadata[]\"].forEach((value) => {\n formData.append(\n \"metadata[]\",\n new Blob([JSON.stringify(value)], { type: \"application/json\" }),\n \"\",\n );\n });\n }\n if (body[\"file[]\"] !== undefined) {\n body[\"file[]\"].forEach((value) => {\n formData.append(\"file[]\", value);\n });\n }\n\n const res = await fetch(url, {\n ...options,\n method: \"POST\",\n body: formData,\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: UploadFilesResponse201 = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<UploadFilesResponse201>;\n };\n\n const deleteFile = async (\n id: string,\n options?: RequestInit,\n ): Promise<FetchResponse<void>> => {\n const url = `${baseURL}/files/${id}`;\n const res = await fetch(url, {\n ...options,\n method: \"DELETE\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const payload: undefined = undefined;\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<void>;\n };\n\n const getFile = async (\n id: string,\n params?: GetFileParams,\n options?: RequestInit,\n ): Promise<FetchResponse<Blob>> => {\n const encodedParameters =\n params &&\n Object.entries(params)\n .map(([key, value]) => {\n const stringValue = Array.isArray(value)\n ? value.join(\",\")\n : typeof value === \"object\"\n ? JSON.stringify(value)\n : (value as string);\n return `${key}=${encodeURIComponent(stringValue)}`;\n })\n .join(\"&\");\n\n const url = encodedParameters\n ? `${baseURL}/files/${id}?${encodedParameters}`\n : `${baseURL}/files/${id}`;\n const res = await fetch(url, {\n ...options,\n method: \"GET\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const payload: Blob = await res.blob();\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<Blob>;\n };\n\n const getFileMetadataHeaders = async (\n id: string,\n params?: GetFileMetadataHeadersParams,\n options?: RequestInit,\n ): Promise<FetchResponse<void>> => {\n const encodedParameters =\n params &&\n Object.entries(params)\n .map(([key, value]) => {\n const stringValue = Array.isArray(value)\n ? value.join(\",\")\n : typeof value === \"object\"\n ? JSON.stringify(value)\n : (value as string);\n return `${key}=${encodeURIComponent(stringValue)}`;\n })\n .join(\"&\");\n\n const url = encodedParameters\n ? `${baseURL}/files/${id}?${encodedParameters}`\n : `${baseURL}/files/${id}`;\n const res = await fetch(url, {\n ...options,\n method: \"HEAD\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const payload: undefined = undefined;\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<void>;\n };\n\n const replaceFile = async (\n id: string,\n body: ReplaceFileBody,\n options?: RequestInit,\n ): Promise<FetchResponse<FileMetadata>> => {\n const url = `${baseURL}/files/${id}`;\n const formData = new FormData();\n if (body[\"metadata\"] !== undefined) {\n formData.append(\n \"metadata\",\n new Blob([JSON.stringify(body[\"metadata\"])], {\n type: \"application/json\",\n }),\n \"\",\n );\n }\n if (body[\"file\"] !== undefined) {\n formData.append(\"file\", body[\"file\"]);\n }\n\n const res = await fetch(url, {\n ...options,\n method: \"PUT\",\n body: formData,\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: FileMetadata = responseBody ? JSON.parse(responseBody) : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<FileMetadata>;\n };\n\n const getFilePresignedURL = async (\n id: string,\n options?: RequestInit,\n ): Promise<FetchResponse<PresignedURLResponse>> => {\n const url = `${baseURL}/files/${id}/presignedurl`;\n const res = await fetch(url, {\n ...options,\n method: \"GET\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: PresignedURLResponse = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<PresignedURLResponse>;\n };\n\n const deleteBrokenMetadata = async (\n options?: RequestInit,\n ): Promise<FetchResponse<DeleteBrokenMetadataResponse200>> => {\n const url = `${baseURL}/ops/delete-broken-metadata`;\n const res = await fetch(url, {\n ...options,\n method: \"POST\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: DeleteBrokenMetadataResponse200 = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<DeleteBrokenMetadataResponse200>;\n };\n\n const deleteOrphanedFiles = async (\n options?: RequestInit,\n ): Promise<FetchResponse<DeleteOrphanedFilesResponse200>> => {\n const url = `${baseURL}/ops/delete-orphans`;\n const res = await fetch(url, {\n ...options,\n method: \"POST\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: DeleteOrphanedFilesResponse200 = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<DeleteOrphanedFilesResponse200>;\n };\n\n const listBrokenMetadata = async (\n options?: RequestInit,\n ): Promise<FetchResponse<ListBrokenMetadataResponse200>> => {\n const url = `${baseURL}/ops/list-broken-metadata`;\n const res = await fetch(url, {\n ...options,\n method: \"POST\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: ListBrokenMetadataResponse200 = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<ListBrokenMetadataResponse200>;\n };\n\n const listFilesNotUploaded = async (\n options?: RequestInit,\n ): Promise<FetchResponse<ListFilesNotUploadedResponse200>> => {\n const url = `${baseURL}/ops/list-not-uploaded`;\n const res = await fetch(url, {\n ...options,\n method: \"POST\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: ListFilesNotUploadedResponse200 = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<ListFilesNotUploadedResponse200>;\n };\n\n const listOrphanedFiles = async (\n options?: RequestInit,\n ): Promise<FetchResponse<ListOrphanedFilesResponse200>> => {\n const url = `${baseURL}/ops/list-orphans`;\n const res = await fetch(url, {\n ...options,\n method: \"POST\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: ListOrphanedFilesResponse200 = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<ListOrphanedFilesResponse200>;\n };\n\n const getVersion = async (\n options?: RequestInit,\n ): Promise<FetchResponse<VersionInformation>> => {\n const url = `${baseURL}/version`;\n const res = await fetch(url, {\n ...options,\n method: \"GET\",\n headers: {\n ...options?.headers,\n },\n });\n\n if (res.status >= 300) {\n const responseBody = [412].includes(res.status) ? null : await res.text();\n const payload: unknown = responseBody ? JSON.parse(responseBody) : {};\n throw new FetchError(payload, res.status, res.headers);\n }\n\n const responseBody = [204, 205, 304].includes(res.status)\n ? null\n : await res.text();\n const payload: VersionInformation = responseBody\n ? JSON.parse(responseBody)\n : {};\n\n return {\n body: payload,\n status: res.status,\n headers: res.headers,\n } as FetchResponse<VersionInformation>;\n };\n\n return {\n baseURL,\n pushChainFunction,\n uploadFiles,\n deleteFile,\n getFile,\n getFileMetadataHeaders,\n replaceFile,\n getFilePresignedURL,\n deleteBrokenMetadata,\n deleteOrphanedFiles,\n listBrokenMetadata,\n listFilesNotUploaded,\n listOrphanedFiles,\n getVersion,\n };\n};\n"],"names":["baseURL","chainFunctions","fetch","createEnhancedFetch","pushChainFunction","chainFunction","push","uploadFiles","async","body","options","url","formData","FormData","append","forEach","value","Blob","JSON","stringify","type","res","method","status","responseBody","includes","text","payload","parse","FetchError","headers","deleteFile","id","getFile","params","encodedParameters","Object","entries","map","key","stringValue","Array","isArray","join","encodeURIComponent","blob","getFileMetadataHeaders","replaceFile","getFilePresignedURL","deleteBrokenMetadata","deleteOrphanedFiles","listBrokenMetadata","listFilesNotUploaded","listOrphanedFiles","getVersion"],"mappings":"gJAsmB+B,CAC7BA,EACAC,EAAkC,MAElC,IAAIC,EAAQC,EAAAA,oBAAoBF,GAybhC,MAAO,CACLD,UACAI,kBAzbyBC,IACzBJ,EAAeK,KAAKD,GACpBH,EAAQC,EAAAA,oBAAoBF,EAAc,EAwb1CM,YAtbkBC,MAClBC,EACAC,KAEA,MAAMC,EAAM,GAAGX,UACTY,EAAW,IAAIC,cACK,IAAtBJ,EAAK,cACPG,EAASE,OAAO,YAAaL,EAAK,mBAET,IAAvBA,EAAK,eACPA,EAAK,cAAcM,SAASC,IAC1BJ,EAASE,OACP,aACA,IAAIG,KAAK,CAACC,KAAKC,UAAUH,IAAS,CAAEI,KAAM,qBAC1C,GAAA,SAIiB,IAAnBX,EAAK,WACPA,EAAK,UAAUM,SAASC,IACtBJ,EAASE,OAAO,SAAUE,EAAK,IAInC,MAAMK,QAAYnB,EAAMS,EAAK,IACxBD,EACHY,OAAQ,OACRb,KAAMG,IAGR,GAAIS,EAAIE,QAAU,IAAK,CACrB,MAAMC,EAAe,CAAC,KAAKC,SAASJ,EAAIE,QAAU,WAAaF,EAAIK,OAC7DC,EAAmBH,EAAeN,KAAKU,MAAMJ,GAAgB,CAAA,EACnE,MAAM,IAAIK,EAAAA,WAAWF,EAASN,EAAIE,OAAQF,EAAIS,QAChD,CAEA,MAAMN,EAAe,CAAC,IAAK,IAAK,KAAKC,SAASJ,EAAIE,QAC9C,WACMF,EAAIK,OAKd,MAAO,CACLjB,KALsCe,EACpCN,KAAKU,MAAMJ,GACX,CAAA,EAIFD,OAAQF,EAAIE,OACZO,QAAST,E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